rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
for key, value in headers.iteritems():
for key, value in headers.items():
def __init__(self, url, data=None, headers={}): # unwrap('<URL:type://host/path>') --> 'type://host/path' self.__original = unwrap(url) self.type = None # self.__r_type is what's left after doing the splittype self.host = None self.port = None self.data = data self.headers = {} for key, value in headers.iteritems(): self.add_header(key, value)
for k, v in self.timeout.iteritems():
for k, v in self.timeout.items():
def check_cache(self): # first check for old ones t = time.time() if self.soonest <= t: for k, v in self.timeout.iteritems(): if v < t: self.cache[k].close() del self.cache[k] del self.timeout[k] self.soonest = min(self.timeout.values())
return self.readlines().join('')
return ''.join(self.readlines())
def read(self): # Note: no size argument -- read until EOF only! return self.readlines().join('')
if not host: return addinfourl(open(url2pathname(file), 'r'), noheaders(), self.openedurl)
if not host: return addinfourl(open(url2pathname(file), 'r'), noheaders(), 'file:'+file)
def open_local_file(self, url): host, file = splithost(url) if not host: return addinfourl(open(url2pathname(file), 'r'), noheaders(), self.openedurl) host, port = splitport(host) if not port and socket.gethostbyname(host) in ( localhost(), thishost()): file = unquote(file) return addinfourl(open(url2pathname(file), 'r'), noheaders(), self.openedurl) raise IOError, ('local file error', 'not on local host')
return addinfourl(open(url2pathname(file), 'r'), noheaders(), self.openedurl)
return addinfourl(open(url2pathname(file), 'r'), noheaders(), 'file:'+file)
def open_local_file(self, url): host, file = splithost(url) if not host: return addinfourl(open(url2pathname(file), 'r'), noheaders(), self.openedurl) host, port = splitport(host) if not port and socket.gethostbyname(host) in ( localhost(), thishost()): file = unquote(file) return addinfourl(open(url2pathname(file), 'r'), noheaders(), self.openedurl) raise IOError, ('local file error', 'not on local host')
buf = ''
buf = ['', '']
def process_rawq(self): """Transfer from raw queue to cooked queue.
if c == theNULL: continue if c == "\021": continue if c != IAC: buf = buf + c continue c = self.rawq_getchar() if c == IAC: buf = buf + c elif c in (DO, DONT): opt = self.rawq_getchar() self.msg('IAC %s %d', c == DO and 'DO' or 'DONT', ord(opt)) if self.option_callback: self.option_callback(self.sock, c, opt)
if not self.iacseq: if c == theNULL: continue if c == "\021": continue if c != IAC: buf[self.sb] = buf[self.sb] + c continue
def process_rawq(self): """Transfer from raw queue to cooked queue.
self.sock.sendall(IAC + WONT + opt) elif c in (WILL, WONT): opt = self.rawq_getchar() self.msg('IAC %s %d', c == WILL and 'WILL' or 'WONT', ord(opt)) if self.option_callback: self.option_callback(self.sock, c, opt)
self.iacseq += c elif len(self.iacseq) == 1: 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]' if c in (DO, DONT, WILL, WONT): self.iacseq += c continue self.iacseq = '' if c == IAC: buf[self.sb] = buf[self.sb] + c
def process_rawq(self): """Transfer from raw queue to cooked queue.
self.sock.sendall(IAC + DONT + opt) else: self.msg('IAC %d not recognized' % ord(c))
if c == SB: self.sb = 1 self.sbdataq = '' elif c == SE: self.sb = 0 self.sbdataq = self.sbdataq + buf[1] buf[1] = '' if self.option_callback: self.option_callback(self.sock, c, NOOPT) else: self.msg('IAC %d not recognized' % ord(c)) elif len(self.iacseq) == 2: cmd = self.iacseq[1] self.iacseq = '' opt = c if cmd in (DO, DONT): self.msg('IAC %s %d', cmd == DO and 'DO' or 'DONT', ord(opt)) if self.option_callback: self.option_callback(self.sock, cmd, opt) else: self.sock.sendall(IAC + WONT + opt) elif cmd in (WILL, WONT): self.msg('IAC %s %d', cmd == WILL and 'WILL' or 'WONT', ord(opt)) if self.option_callback: self.option_callback(self.sock, cmd, opt) else: self.sock.sendall(IAC + DONT + opt)
def process_rawq(self): """Transfer from raw queue to cooked queue.
self.cookedq = self.cookedq + buf
self.cookedq = self.cookedq + buf[0] self.sbdataq = self.sbdataq + buf[1]
def process_rawq(self): """Transfer from raw queue to cooked queue.
self.ted.WEInsert(stuff, None, None)
try: self.ted.WEInsert(stuff, None, None) finally: self._buf = ""
def flush(self): stuff = string.split(self._buf, '\n') stuff = string.join(stuff, '\r') self.setselection_at_end() self.ted.WEInsert(stuff, None, None) selstart, selend = self.getselection() self._inputstart = selstart self._buf = "" self.ted.WEClearUndo() self.updatescrollbars() if self._parentwindow.wid.GetWindowPort().QDIsPortBuffered(): self._parentwindow.wid.GetWindowPort().QDFlushPortBuffer(None)
self._buf = ""
def flush(self): stuff = string.split(self._buf, '\n') stuff = string.join(stuff, '\r') self.setselection_at_end() self.ted.WEInsert(stuff, None, None) selstart, selend = self.getselection() self._inputstart = selstart self._buf = "" self.ted.WEClearUndo() self.updatescrollbars() if self._parentwindow.wid.GetWindowPort().QDIsPortBuffered(): self._parentwindow.wid.GetWindowPort().QDFlushPortBuffer(None)
self.w.outputtext.ted.WEInsert(stuff, None, None) self._buf = ""
try: self.w.outputtext.ted.WEInsert(stuff, None, None) finally: self._buf = ""
def flush(self): self.show() stuff = string.split(self._buf, '\n') stuff = string.join(stuff, '\r') end = self.w.outputtext.ted.WEGetTextLength() self.w.outputtext.setselection(end, end) self.w.outputtext.ted.WEFeatureFlag(WASTEconst.weFReadOnly, 0) self.w.outputtext.ted.WEInsert(stuff, None, None) self._buf = "" self.w.outputtext.updatescrollbars() self.w.outputtext.ted.WEFeatureFlag(WASTEconst.weFReadOnly, 1) if self.w.wid.GetWindowPort().QDIsPortBuffered(): self.w.wid.GetWindowPort().QDFlushPortBuffer(None)
class BadException:
class BadException(Exception):
def ckmsg(src, msg): try: compile(src, '<fragment>', 'exec') except SyntaxError, e: print e.msg if e.msg == msg: print "ok" else: print "expected:", msg else: print "failed to get expected SyntaxError"
if (self.compiler.find_library_file(lib_dirs, 'z')): exts.append( Extension('zlib', ['zlibmodule.c'], libraries = ['z']) )
zlib_inc = find_file('zlib.h', [], inc_dirs) if zlib_inc is not None: zlib_h = zlib_inc[0] + '/zlib.h' version = '"0.0.0"' version_req = '"1.1.3"' fp = open(zlib_h) while 1: line = fp.readline() if not line: break if line.find(' version = line.split()[2] break if version >= version_req: if (self.compiler.find_library_file(lib_dirs, 'z')): exts.append( Extension('zlib', ['zlibmodule.c'], libraries = ['z']) )
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.insert(0, '/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.insert(0, '/usr/local/include' )
command = interpolate(SH_LOCK, file=file) p = os.popen(command) output = p.read()
def commit(self, entry): file = entry.file # Normalize line endings in body if '\r' in self.ui.body: self.ui.body = re.sub('\r\n?', '\n', self.ui.body) # Normalize whitespace in title self.ui.title = string.join(string.split(self.ui.title)) # Check that there were any changes if self.ui.body == entry.body and self.ui.title == entry.title: self.error("You didn't make any changes!") return # XXX Should lock here try: os.unlink(file) except os.error: pass try: f = open(file, 'w') except IOError, why: self.error(CANTWRITE, file=file, why=why) return date = time.ctime(now) emit(FILEHEADER, self.ui, os.environ, date=date, _file=f, _quote=0) f.write('\n') f.write(self.ui.body) f.write('\n') f.close()
command = interpolate( SH_LOCK + '\n' + SH_CHECKIN, file=file, tfn=tfn)
command = interpolate(SH_CHECKIN, file=file, tfn=tfn) log("\n\n" + command)
def commit(self, entry): file = entry.file # Normalize line endings in body if '\r' in self.ui.body: self.ui.body = re.sub('\r\n?', '\n', self.ui.body) # Normalize whitespace in title self.ui.title = string.join(string.split(self.ui.title)) # Check that there were any changes if self.ui.body == entry.body and self.ui.title == entry.title: self.error("You didn't make any changes!") return # XXX Should lock here try: os.unlink(file) except os.error: pass try: f = open(file, 'w') except IOError, why: self.error(CANTWRITE, file=file, why=why) return date = time.ctime(now) emit(FILEHEADER, self.ui, os.environ, date=date, _file=f, _quote=0) f.write('\n') f.write(self.ui.body) f.write('\n') f.close()
log("output: " + output) log("done: " + str(sts)) log("TempFile:\n" + open(tfn).read() + "end")
def commit(self, entry): file = entry.file # Normalize line endings in body if '\r' in self.ui.body: self.ui.body = re.sub('\r\n?', '\n', self.ui.body) # Normalize whitespace in title self.ui.title = string.join(string.split(self.ui.title)) # Check that there were any changes if self.ui.body == entry.body and self.ui.title == entry.title: self.error("You didn't make any changes!") return # XXX Should lock here try: os.unlink(file) except os.error: pass try: f = open(file, 'w') except IOError, why: self.error(CANTWRITE, file=file, why=why) return date = time.ctime(now) emit(FILEHEADER, self.ui, os.environ, date=date, _file=f, _quote=0) f.write('\n') f.write(self.ui.body) f.write('\n') f.close()
self.assertRaises(ValueError, time.strftime, '', (1900, 0, 1, 0, 0, 0, 0, 1, -1))
self.assertRaises(ValueError, time.strftime, '', (1900, -1, 1, 0, 0, 0, 0, 1, -1))
def test_strftime_bounds_checking(self): # Make sure that strftime() checks the bounds of the various parts #of the time tuple.
self.assertRaises(ValueError, time.strftime, '', (1900, 1, 0, 0, 0, 0, 0, 1, -1))
self.assertRaises(ValueError, time.strftime, '', (1900, 1, -1, 0, 0, 0, 0, 1, -1))
def test_strftime_bounds_checking(self): # Make sure that strftime() checks the bounds of the various parts #of the time tuple.
self.assertRaises(ValueError, time.strftime, '', (1900, 1, 1, 0, 0, 0, 0, 0, -1))
self.assertRaises(ValueError, time.strftime, '', (1900, 1, 1, 0, 0, 0, 0, -1, -1))
def test_strftime_bounds_checking(self): # Make sure that strftime() checks the bounds of the various parts #of the time tuple.
out_fn = string.replace (f, '.py', '.pyc')
out_fn = f + (__debug__ and "c" or "o") compile_msg = "byte-compiling %s to %s" % \ (f, os.path.basename (out_fn)) skip_msg = "byte-compilation of %s skipped" % f
def run (self):
"byte-compiling %s" % f, "byte-compilation of %s skipped" % f)
compile_msg, skip_msg)
def run (self):
if len_nodelist != 2 and isinstance(result, GenExpr):
if len_nodelist != 2 and isinstance(result, GenExpr) \ and len(node) == 3 and node[2][0] == symbol.gen_for:
def com_call_function(self, primaryNode, nodelist): if nodelist[0] == token.RPAR: return CallFunc(primaryNode, [], lineno=extractLineNo(nodelist)) args = [] kw = 0 len_nodelist = len(nodelist) for i in range(1, len_nodelist, 2): node = nodelist[i] if node[0] == token.STAR or node[0] == token.DOUBLESTAR: break kw, result = self.com_argument(node, kw) if len_nodelist != 2 and isinstance(result, GenExpr): raise SyntaxError, 'generator expression needs parenthesis' args.append(result) else: # No broken by star arg, so skip the last one we processed. i = i + 1 if i < len_nodelist and nodelist[i][0] == token.COMMA: # need to accept an application that looks like "f(a, b,)" i = i + 1 star_node = dstar_node = None while i < len_nodelist: tok = nodelist[i] ch = nodelist[i+1] i = i + 3 if tok[0]==token.STAR: if star_node is not None: raise SyntaxError, 'already have the varargs indentifier' star_node = self.com_node(ch) elif tok[0]==token.DOUBLESTAR: if dstar_node is not None: raise SyntaxError, 'already have the kwargs indentifier' dstar_node = self.com_node(ch) else: raise SyntaxError, 'unknown node type: %s' % tok return CallFunc(primaryNode, args, star_node, dstar_node, lineno=extractLineNo(nodelist))
if (isinstance (filename, str)): new_base = base.decode(TESTFN_ENCODING) file_list = [f.decode(TESTFN_ENCODING) for f in os.listdir(path)] else: new_base = base file_list = os.listdir(path)
if isinstance(base, str): base = base.decode(TESTFN_ENCODING) file_list = os.listdir(path) if file_list and isinstance(file_list[0], str): file_list = [f.decode(TESTFN_ENCODING) for f in file_list]
def _do_single(self, filename): self.failUnless(os.path.exists(filename)) self.failUnless(os.path.isfile(filename)) self.failUnless(os.path.exists(os.path.abspath(filename))) self.failUnless(os.path.isfile(os.path.abspath(filename))) os.chmod(filename, 0777) os.utime(filename, None) os.utime(filename, (time.time(), time.time())) # Copy/rename etc tests using the same filename self._do_copyish(filename, filename) # Filename should appear in glob output self.failUnless( os.path.abspath(filename)==os.path.abspath(glob.glob(filename)[0])) # basename should appear in listdir. path, base = os.path.split(os.path.abspath(filename)) if (isinstance (filename, str)): new_base = base.decode(TESTFN_ENCODING) file_list = [f.decode(TESTFN_ENCODING) for f in os.listdir(path)] else: new_base = base file_list = os.listdir(path)
new_base = unicodedata.normalize("NFD", new_base)
base = unicodedata.normalize("NFD", base)
def _do_single(self, filename): self.failUnless(os.path.exists(filename)) self.failUnless(os.path.isfile(filename)) self.failUnless(os.path.exists(os.path.abspath(filename))) self.failUnless(os.path.isfile(os.path.abspath(filename))) os.chmod(filename, 0777) os.utime(filename, None) os.utime(filename, (time.time(), time.time())) # Copy/rename etc tests using the same filename self._do_copyish(filename, filename) # Filename should appear in glob output self.failUnless( os.path.abspath(filename)==os.path.abspath(glob.glob(filename)[0])) # basename should appear in listdir. path, base = os.path.split(os.path.abspath(filename)) if (isinstance (filename, str)): new_base = base.decode(TESTFN_ENCODING) file_list = [f.decode(TESTFN_ENCODING) for f in os.listdir(path)] else: new_base = base file_list = os.listdir(path)
self.failUnless(new_base in file_list)
self.failUnless(base in file_list)
def _do_single(self, filename): self.failUnless(os.path.exists(filename)) self.failUnless(os.path.isfile(filename)) self.failUnless(os.path.exists(os.path.abspath(filename))) self.failUnless(os.path.isfile(os.path.abspath(filename))) os.chmod(filename, 0777) os.utime(filename, None) os.utime(filename, (time.time(), time.time())) # Copy/rename etc tests using the same filename self._do_copyish(filename, filename) # Filename should appear in glob output self.failUnless( os.path.abspath(filename)==os.path.abspath(glob.glob(filename)[0])) # basename should appear in listdir. path, base = os.path.split(os.path.abspath(filename)) if (isinstance (filename, str)): new_base = base.decode(TESTFN_ENCODING) file_list = [f.decode(TESTFN_ENCODING) for f in os.listdir(path)] else: new_base = base file_list = os.listdir(path)
Instantiate with: IMAP4_SSL([, host[, port[, keyfile[, certfile]]]])
Instantiate with: IMAP4_SSL([host[, port[, keyfile[, certfile]]]])
def print_log(self): self._mesg('last %d IMAP4 interactions:' % len(self._cmd_log)) i, n = self._cmd_log_idx, self._cmd_log_len while n: try: apply(self._mesg, self._cmd_log[i]) except: pass i += 1 if i >= self._cmd_log_len: i = 0 n -= 1
':action':'file_upload', 'protcol_version':'1', 'name':self.distribution.get_name(), 'version':self.distribution.get_version(), 'content':(os.path.basename(filename),content), 'filetype':command, 'pyversion':pyversion, 'md5_digest':md5(content).hexdigest(),
':action': 'file_upload', 'protcol_version': '1', 'name': meta.get_name(), 'version': meta.get_version(), 'content': (os.path.basename(filename),content), 'filetype': command, 'pyversion': pyversion, 'md5_digest': md5(content).hexdigest(), 'metadata_version' : '1.0', 'summary': meta.get_description(), 'home_page': meta.get_url(), 'author': meta.get_contact(), 'author_email': meta.get_contact_email(), 'license': meta.get_licence(), 'description': meta.get_long_description(), 'keywords': meta.get_keywords(), 'platform': meta.get_platforms(), 'classifiers': meta.get_classifiers(), 'download_url': meta.get_download_url(), 'provides': meta.get_provides(), 'requires': meta.get_requires(), 'obsoletes': meta.get_obsoletes(),
def upload_file(self, command, pyversion, filename): # Sign if requested if self.sign: spawn(("gpg", "--detach-sign", "-a", filename), dry_run=self.dry_run)
class PackBufferTestCase(unittest.TestCase): """ Test the packing methods that work on buffers. """ def test_unpack_from( self ): test_string = 'abcd01234' fmt = '4s' s = struct.Struct(fmt) for cls in (str, buffer): data = cls(test_string) self.assertEquals(s.unpack_from(data), ('abcd',)) self.assertEquals(s.unpack_from(data, 2), ('cd01',)) self.assertEquals(s.unpack_from(data, 4), ('0123',)) for i in xrange(6): self.assertEquals(s.unpack_from(data, i), (data[i:i+4],)) for i in xrange(6, len(test_string) + 1): simple_err(s.unpack_from, data, i) for cls in (str, buffer): data = cls(test_string) self.assertEquals(struct.unpack_from(fmt, data), ('abcd',)) self.assertEquals(struct.unpack_from(fmt, data, 2), ('cd01',)) self.assertEquals(struct.unpack_from(fmt, data, 4), ('0123',)) for i in xrange(6): self.assertEquals(struct.unpack_from(fmt, data, i), (data[i:i+4],)) for i in xrange(6, len(test_string) + 1): simple_err(struct.unpack_from, fmt, data, i) def test_pack_to( self ): test_string = 'Reykjavik rocks, eow!' writable_buf = array.array('c', ' '*100) fmt = '21s' s = struct.Struct(fmt) s.pack_to(writable_buf, 0, test_string) from_buf = writable_buf.tostring()[:len(test_string)] self.assertEquals(from_buf, test_string) s.pack_to(writable_buf, 10, test_string) from_buf = writable_buf.tostring()[:len(test_string)+10] self.assertEquals(from_buf, (test_string[:10] + test_string)) small_buf = array.array('c', ' '*10) self.assertRaises(struct.error, s.pack_to, small_buf, 0, test_string) self.assertRaises(struct.error, s.pack_to, small_buf, 2, test_string) def test_pack_to_fn( self ): test_string = 'Reykjavik rocks, eow!' writable_buf = array.array('c', ' '*100) fmt = '21s' pack_to = lambda *args: struct.pack_to(fmt, *args) pack_to(writable_buf, 0, test_string) from_buf = writable_buf.tostring()[:len(test_string)] self.assertEquals(from_buf, test_string) pack_to(writable_buf, 10, test_string) from_buf = writable_buf.tostring()[:len(test_string)+10] self.assertEquals(from_buf, (test_string[:10] + test_string)) small_buf = array.array('c', ' '*10) self.assertRaises(struct.error, pack_to, small_buf, 0, test_string) self.assertRaises(struct.error, pack_to, small_buf, 2, test_string) def test_main(): test.test_support.run_unittest(PackBufferTestCase) if __name__ == "__main__": test_main()
def assertRaises(excClass, callableObj, *args, **kwargs): try: callableObj(*args, **kwargs) except excClass: return else: raise RuntimeError("%s not raised." % excClass) def test_unpack_from(): test_string = 'abcd01234' fmt = '4s' s = struct.Struct(fmt) for cls in (str, buffer): data = cls(test_string) assert s.unpack_from(data) == ('abcd',) assert s.unpack_from(data, 2) == ('cd01',) assert s.unpack_from(data, 4) == ('0123',) for i in xrange(6): assert s.unpack_from(data, i) == (data[i:i+4],) for i in xrange(6, len(test_string) + 1): simple_err(s.unpack_from, data, i) for cls in (str, buffer): data = cls(test_string) assert struct.unpack_from(fmt, data) == ('abcd',) assert struct.unpack_from(fmt, data, 2) == ('cd01',) assert struct.unpack_from(fmt, data, 4) == ('0123',) for i in xrange(6): assert (struct.unpack_from(fmt, data, i) == (data[i:i+4],)) for i in xrange(6, len(test_string) + 1): simple_err(struct.unpack_from, fmt, data, i) def test_pack_to(): test_string = 'Reykjavik rocks, eow!' writable_buf = array.array('c', ' '*100) fmt = '21s' s = struct.Struct(fmt) s.pack_to(writable_buf, 0, test_string) from_buf = writable_buf.tostring()[:len(test_string)] assert from_buf == test_string s.pack_to(writable_buf, 10, test_string) from_buf = writable_buf.tostring()[:len(test_string)+10] assert from_buf == (test_string[:10] + test_string) small_buf = array.array('c', ' '*10) assertRaises(struct.error, s.pack_to, small_buf, 0, test_string) assertRaises(struct.error, s.pack_to, small_buf, 2, test_string) def test_pack_to_fn(): test_string = 'Reykjavik rocks, eow!' writable_buf = array.array('c', ' '*100) fmt = '21s' pack_to = lambda *args: struct.pack_to(fmt, *args) pack_to(writable_buf, 0, test_string) from_buf = writable_buf.tostring()[:len(test_string)] assert from_buf == test_string pack_to(writable_buf, 10, test_string) from_buf = writable_buf.tostring()[:len(test_string)+10] assert from_buf == (test_string[:10] + test_string) small_buf = array.array('c', ' '*10) assertRaises(struct.error, pack_to, small_buf, 0, test_string) assertRaises(struct.error, pack_to, small_buf, 2, test_string) test_unpack_from() test_pack_to() test_pack_to_fn()
def test_1229380(): import sys for endian in ('', '>', '<'): for cls in (int, long): for fmt in ('B', 'H', 'I', 'L'): deprecated_err(struct.pack, endian + fmt, cls(-1)) deprecated_err(struct.pack, endian + 'B', cls(300)) deprecated_err(struct.pack, endian + 'H', cls(70000)) deprecated_err(struct.pack, endian + 'I', sys.maxint * 4L) deprecated_err(struct.pack, endian + 'L', sys.maxint * 4L)
if __debug__: stderr = re.sub(r"\[\d+ refs\]\r?\n?$", "", stderr) return stderr
return re.sub(r"\[\d+ refs\]\r?\n?$", "", stderr)
def remove_stderr_debug_decorations(stderr): if __debug__: stderr = re.sub(r"\[\d+ refs\]\r?\n?$", "", stderr) return stderr
return Decimal((sign, self._int, self._exp))._fix(context=context)
return Decimal((sign, self._int, self._exp))._fix(context)
def __neg__(self, context=None): """Returns a copy with the sign switched.
ans = self._fix(context=context)
ans = self._fix(context)
def __pos__(self, context=None): """Returns a copy, unless it is a sNaN.
ans = ans._fix(context=context)
ans = ans._fix(context)
def __add__(self, other, context=None): """Returns self + other.
ans = ans._fix(context=context)
ans = ans._fix(context)
def _increment(self, round=1, context=None): """Special case of add, adding 1eExponent
ans = ans._fix(context=context)
ans = ans._fix(context)
def __mul__(self, other, context=None): """Return self * other.
ans2 = ans2._fix(context=context)
ans2 = ans2._fix(context)
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
otherside = otherside._fix(context=context)
otherside = otherside._fix(context)
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
ans = ans._fix(context=context)
ans = ans._fix(context)
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
return r._fix(context=context)
return r._fix(context)
def remainder_near(self, other, context=None): """ Remainder nearest to 0- abs(remainder-near) <= other/2 """ other = _convert_other(other)
def _fix(self, prec=None, rounding=None, folddown=None, context=None):
def _fix(self, context):
def _fix(self, prec=None, rounding=None, folddown=None, context=None): """Round if it is necessary to keep self within prec precision.
prec - precision to which to round. By default, the context decides. rounding - Rounding method. By default, the context decides. folddown - Fold down high elements, by default context._clamp
def _fix(self, prec=None, rounding=None, folddown=None, context=None): """Round if it is necessary to keep self within prec precision.
if prec is None: prec = context.prec ans = Decimal(self) ans = ans._fixexponents(prec, rounding, folddown=folddown, context=context)
prec = context.prec ans = self._fixexponents(prec, context)
def _fix(self, prec=None, rounding=None, folddown=None, context=None): """Round if it is necessary to keep self within prec precision.
ans = ans._round(prec, rounding, context=context) ans = ans._fixexponents(prec, rounding, folddown=folddown, context=context)
ans = ans._round(prec, context=context) ans = ans._fixexponents(prec, context)
def _fix(self, prec=None, rounding=None, folddown=None, context=None): """Round if it is necessary to keep self within prec precision.
def _fixexponents(self, prec=None, rounding=None, folddown=None, context=None): """Fix the exponents and return a copy with the exponent in bounds.""" if self._is_special: return self if context is None: context = getcontext() if prec is None: prec = context.prec if folddown is None: folddown = context._clamp
def _fixexponents(self, prec, context): """Fix the exponents and return a copy with the exponent in bounds. Only call if known to not be a special value. """ folddown = context._clamp
def _fixexponents(self, prec=None, rounding=None, folddown=None, context=None): """Fix the exponents and return a copy with the exponent in bounds.""" if self._is_special: return self if context is None: context = getcontext() if prec is None: prec = context.prec if folddown is None: folddown = context._clamp Emin = context.Emin ans = Decimal(self) ans_adjusted = ans.adjusted() if ans_adjusted < Emin: Etiny = context.Etiny() if ans._exp < Etiny: if not ans: ans._exp = Etiny context._raise_error(Clamped) return ans ans = ans._rescale(Etiny, context=context) #It isn't zero, and exp < Emin => subnormal context._raise_error(Subnormal) if context.flags[Inexact]: context._raise_error(Underflow) else: if ans: #Only raise subnormal if non-zero. context._raise_error(Subnormal) else: Etop = context.Etop() if folddown and ans._exp > Etop: context._raise_error(Clamped) ans = ans._rescale(Etop, context=context) else: Emax = context.Emax if ans_adjusted > Emax: if not ans: ans._exp = Emax context._raise_error(Clamped) return ans context._raise_error(Inexact) context._raise_error(Rounded) return context._raise_error(Overflow, 'above Emax', ans._sign) return ans
return val._fix(context=context)
return val._fix(context)
def __pow__(self, n, modulo = None, context=None): """Return self ** n (mod modulo)
dup = self._fix(context=context)
dup = self._fix(context)
def normalize(self, context=None): """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
ans = ans._fix(context=context)
ans = ans._fix(context)
def sqrt(self, context=None): """Return the square root of self.
return ans._fix(context=context)
return ans._fix(context)
def sqrt(self, context=None): """Return the square root of self.
return ans._fix(context=context)
return ans._fix(context)
def max(self, other, context=None): """Returns the larger value.
return ans._fix(context=context)
return ans._fix(context)
def min(self, other, context=None): """Returns the smaller value.
return d._fix(context=self)
return d._fix(self)
def create_decimal(self, num='0'): """Creates a new Decimal instance but using self as context.""" d = Decimal(num, context=self) return d._fix(context=self)
return str(a._fix(context=self))
return str(a._fix(self))
def _apply(self, a): return str(a._fix(context=self))
self.__buf = ''
self.__buf = _StringIO()
def reset(self): self.__buf = ''
return self.__buf
return self.__buf.getvalue()
def get_buffer(self): return self.__buf
self.__buf = self.__buf + struct.pack('>L', x)
self.__buf.write(struct.pack('>L', x))
def pack_uint(self, x): self.__buf = self.__buf + struct.pack('>L', x)
if x: self.__buf = self.__buf + '\0\0\0\1' else: self.__buf = self.__buf + '\0\0\0\0'
if x: self.__buf.write('\0\0\0\1') else: self.__buf.write('\0\0\0\0')
def pack_bool(self, x): if x: self.__buf = self.__buf + '\0\0\0\1' else: self.__buf = self.__buf + '\0\0\0\0'
try: self.__buf = self.__buf + struct.pack('>f', x)
try: self.__buf.write(struct.pack('>f', x))
def pack_float(self, x): try: self.__buf = self.__buf + struct.pack('>f', x) except struct.error, msg: raise ConversionError, msg
try: self.__buf = self.__buf + struct.pack('>d', x)
try: self.__buf.write(struct.pack('>d', x))
def pack_double(self, x): try: self.__buf = self.__buf + struct.pack('>d', x) except struct.error, msg: raise ConversionError, msg
self.__buf = self.__buf + data
self.__buf.write(data)
def pack_fstring(self, n, s): if n < 0: raise ValueError, 'fstring size must be nonnegative' n = ((n+3)/4)*4 data = s[:n] data = data + (n - len(data)) * '\0' self.__buf = self.__buf + data
verify(str(s).__class__ is str)
def rev(self): if self._rev is not None: return self._rev L = list(self) L.reverse() self._rev = self.__class__("".join(L)) return self._rev
chmfile = os.path.join(sys.prefix, "Python%d%d.chm" % sys.version_info[:2])
chmfile = os.path.join(sys.prefix, 'Doc', 'Python%d%d.chm' % sys.version_info[:2])
def __init__(self, flist=None, filename=None, key=None, root=None): if EditorWindow.help_url is None: dochome = os.path.join(sys.prefix, 'Doc', 'index.html') if sys.platform.count('linux'): # look for html docs in a couple of standard places pyver = 'python-docs-' + '%s.%s.%s' % sys.version_info[:3] if os.path.isdir('/var/www/html/python/'): # "python2" rpm dochome = '/var/www/html/python/index.html' else: basepath = '/usr/share/doc/' # standard location dochome = os.path.join(basepath, pyver, 'Doc', 'index.html') elif sys.platform[:3] == 'win': chmfile = os.path.join(sys.prefix, "Python%d%d.chm" % sys.version_info[:2]) if os.path.isfile(chmfile): dochome = chmfile dochome = os.path.normpath(dochome) if os.path.isfile(dochome): EditorWindow.help_url = dochome else: EditorWindow.help_url = "http://www.python.org/doc/current" currentTheme=idleConf.CurrentTheme() self.flist = flist root = root or flist.root self.root = root self.menubar = Menu(root) self.top = top = self.Toplevel(root, menu=self.menubar) if flist: self.tkinter_vars = flist.vars #self.top.instance_dict makes flist.inversedict avalable to #configDialog.py so it can access all EditorWindow instaces self.top.instance_dict=flist.inversedict else: self.tkinter_vars = {} # keys: Tkinter event names # values: Tkinter variable instances self.recent_files_path=os.path.join(idleConf.GetUserCfgDir(), 'recent-files.lst') self.vbar = vbar = Scrollbar(top, name='vbar') self.text_frame = text_frame = Frame(top) self.width = idleConf.GetOption('main','EditorWindow','width') self.text = text = Text(text_frame, name='text', padx=5, wrap='none', foreground=idleConf.GetHighlight(currentTheme, 'normal',fgBg='fg'), background=idleConf.GetHighlight(currentTheme, 'normal',fgBg='bg'), highlightcolor=idleConf.GetHighlight(currentTheme, 'hilite',fgBg='fg'), highlightbackground=idleConf.GetHighlight(currentTheme, 'hilite',fgBg='bg'), insertbackground=idleConf.GetHighlight(currentTheme, 'cursor',fgBg='fg'), width=self.width, height=idleConf.GetOption('main','EditorWindow','height') )
self.copy_file(name, outfile, preserve_mode = 0)
self.copy_file(os.path.join(package_dir, name), outfile, preserve_mode = 0)
def run(self): # Copies all .py files, then also copies the txt and gif files build_py.run(self) assert self.packages == [idlelib] for name in txt_files: outfile = self.get_plain_outfile(self.build_lib, [idlelib], name) dir = os.path.dirname(outfile) self.mkpath(dir) self.copy_file(name, outfile, preserve_mode = 0) for name in Icons: outfile = self.get_plain_outfile(self.build_lib, [idlelib,"Icons"], name) dir = os.path.dirname(outfile) self.mkpath(dir) self.copy_file(os.path.join("Icons",name), outfile, preserve_mode = 0)
icons = [os.path.join("Icons",name) for name in Icons]
icons = [os.path.join(package_dir, "Icons",name) for name in Icons] txts = [os.path.join(package_dir, name) for name in txt_files]
def get_source_files(self): # returns the .py files, the .txt files, and the icons icons = [os.path.join("Icons",name) for name in Icons] return build_py.get_source_files(self)+txt_files+icons
package_dir = {idlelib:'.'},
package_dir = {idlelib: package_dir},
def _bytecode_filenames(self, files): files = [n for n in files if n.endswith('.py')] return install_lib._bytecode_filenames(self,files)
scripts = ['idle']
scripts = [os.path.join(package_dir, 'idle')]
def _bytecode_filenames(self, files): files = [n for n in files if n.endswith('.py')] return install_lib._bytecode_filenames(self,files)
expectedchecksum = 'b45b79f3203ee1a896d9b5655484adaff5d4964b'
expectedchecksum = '4e389f97e9f88b8b7ab743121fd643089116f9f2'
def tearDown(self): del self.db
test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 0)
test('replace', 'one!two!three!', 'one!two!three!', '!', '@', 0)
def __getitem__(self, i): return self.seq[i]
if cfg_target != cur_target:
elif map(int, cfg_target.split('.')) > map(int, cur_target.split('.')):
def _init_posix(): """Initialize the module as appropriate for POSIX systems.""" g = {} # load the installed Makefile: try: filename = get_makefile_filename() parse_makefile(filename, g) except IOError, msg: my_msg = "invalid Python installation: unable to open %s" % filename if hasattr(msg, "strerror"): my_msg = my_msg + " (%s)" % msg.strerror raise DistutilsPlatformError(my_msg) # load the installed pyconfig.h: try: filename = get_config_h_filename() parse_config_h(file(filename), g) except IOError, msg: my_msg = "invalid Python installation: unable to open %s" % filename if hasattr(msg, "strerror"): my_msg = my_msg + " (%s)" % msg.strerror raise DistutilsPlatformError(my_msg) # On MacOSX we need to check the setting of the environment variable # MACOSX_DEPLOYMENT_TARGET: configure bases some choices on it so # it needs to be compatible. # If it isn't set we set it to the configure-time value if sys.platform == 'darwin' and g.has_key('CONFIGURE_MACOSX_DEPLOYMENT_TARGET'): cfg_target = g['CONFIGURE_MACOSX_DEPLOYMENT_TARGET'] cur_target = os.getenv('MACOSX_DEPLOYMENT_TARGET', '') if cur_target == '': cur_target = cfg_target os.putenv('MACOSX_DEPLOYMENT_TARGET', cfg_target) if cfg_target != cur_target: my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: now "%s" but "%s" during configure' % (cur_target, cfg_target)) raise DistutilsPlatformError(my_msg) # On AIX, there are wrong paths to the linker scripts in the Makefile # -- these paths are relative to the Python source, but when installed # the scripts are in another directory. if python_build: g['LDSHARED'] = g['BLDSHARED'] elif get_python_version() < '2.1': # The following two branches are for 1.5.2 compatibility. if sys.platform == 'aix4': # what about AIX 3.x ? # Linker script is in the config directory, not in Modules as the # Makefile says. python_lib = get_python_lib(standard_lib=1) ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix') python_exp = os.path.join(python_lib, 'config', 'python.exp') g['LDSHARED'] = "%s %s -bI:%s" % (ld_so_aix, g['CC'], python_exp) elif sys.platform == 'beos': # Linker script is in the config directory. In the Makefile it is # relative to the srcdir, which after installation no longer makes # sense. python_lib = get_python_lib(standard_lib=1) linkerscript_path = string.split(g['LDSHARED'])[0] linkerscript_name = os.path.basename(linkerscript_path) linkerscript = os.path.join(python_lib, 'config', linkerscript_name) # XXX this isn't the right place to do this: adding the Python # library to the link, if needed, should be in the "build_ext" # command. (It's also needed for non-MS compilers on Windows, and # it's taken care of for them by the 'build_ext.get_libraries()' # method.) g['LDSHARED'] = ("%s -L%s/lib -lpython%s" % (linkerscript, PREFIX, get_python_version())) global _config_vars _config_vars = g
if os.name in ('nt', 'os2'):
if os.name in ('nt', 'os2') or sys.platform == 'cygwin':
def setUp(self): TestMailbox.setUp(self) if os.name in ('nt', 'os2'): self._box.colon = '!'
self.assertRaises(mailbox.ExternalClashError, self._box.lock) exited_pid, status = os.waitpid(pid, 0)
try: self.assertRaises(mailbox.ExternalClashError, self._box.lock) finally: exited_pid, status = os.waitpid(pid, 0)
def test_lock_conflict(self): # Fork off a subprocess that will lock the file for 2 seconds, # unlock it, and then exit. if not hasattr(os, 'fork'): return pid = os.fork() if pid == 0: # In the child, lock the mailbox. self._box.lock() time.sleep(2) self._box.unlock() os._exit(0)
expected = longx // longy got = x // y
expected = longx / longy got = x / y
def checkit(*args): # Heavy use of nested scopes here! verify(got == expected, "for %r expected %r got %r" % (args, expected, got))
if importer in (None, True, False):
if importer is None:
def get_importer(path_item): """Retrieve a PEP 302 importer for the given path item The returned importer is cached in sys.path_importer_cache if it was newly created by a path hook. If there is no importer, a wrapper around the basic import machinery is returned. This wrapper is never inserted into the importer cache (None is inserted instead). The cache (or part of it) can be cleared manually if a rescan of sys.path_hooks is necessary. """ try: importer = sys.path_importer_cache[path_item] except KeyError: for path_hook in sys.path_hooks: try: importer = path_hook(path_item) break except ImportError: pass else: importer = None sys.path_importer_cache.setdefault(path_item, importer) # The boolean values are used for caching valid and invalid # file paths for the built-in import machinery if importer in (None, True, False): try: importer = ImpImporter(path_item) except ImportError: importer = None return importer
tcl_version = self.tk.getvar('tcl_version')
tcl_version = str(self.tk.getvar('tcl_version'))
def __init__(self, screenName=None, baseName=None, className='Tk'): """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will be created. BASENAME will be used for the identification of the profile file (see readprofile). It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME is the name of the widget class.""" global _default_root self.master = None self.children = {} if baseName is None: import sys, os baseName = os.path.basename(sys.argv[0]) baseName, ext = os.path.splitext(baseName) if ext not in ('.py', '.pyc', '.pyo'): baseName = baseName + ext self.tk = _tkinter.create(screenName, baseName, className) self.tk.wantobjects(wantobjects) if _MacOS and hasattr(_MacOS, 'SchedParams'): # Disable event scanning except for Command-Period _MacOS.SchedParams(1, 0) # Work around nasty MacTk bug # XXX Is this one still needed? self.update() # Version sanity checks tk_version = self.tk.getvar('tk_version') if tk_version != _tkinter.TK_VERSION: raise RuntimeError, \ "tk.h version (%s) doesn't match libtk.a version (%s)" \ % (_tkinter.TK_VERSION, tk_version) tcl_version = self.tk.getvar('tcl_version') if tcl_version != _tkinter.TCL_VERSION: raise RuntimeError, \ "tcl.h version (%s) doesn't match libtcl.a version (%s)" \ % (_tkinter.TCL_VERSION, tcl_version) if TkVersion < 4.0: raise RuntimeError, \ "Tk 4.0 or higher is required; found Tk %s" \ % str(TkVersion) self.tk.createcommand('tkerror', _tkerror) self.tk.createcommand('exit', _exit) self.readprofile(baseName, className) if _support_default_root and not _default_root: _default_root = self self.protocol("WM_DELETE_WINDOW", self.destroy)
except:
except ValueError:
def do_clear(self, arg): """Three possibilities, tried in this order: clear -> clear all breaks, ask for confirmation clear file:lineno -> clear all breaks at file:lineno clear bpno bpno ... -> clear breakpoints by number""" if not arg: try: reply = raw_input('Clear all breaks? ') except EOFError: reply = 'no' reply = reply.strip().lower() if reply in ('y', 'yes'): self.clear_all_breaks() return if ':' in arg: # Make sure it works for "clear C:\foo\bar.py:12" i = arg.rfind(':') filename = arg[:i] arg = arg[i+1:] try: lineno = int(arg) except: err = "Invalid line number (%s)" % arg else: err = self.clear_break(filename, lineno) if err: print '***', err return numberlist = arg.split() for i in numberlist: if not (0 <= i < len(bdb.Breakpoint.bpbynumber)): print 'No breakpoint numbered', i continue err = self.clear_bpbynumber(i) if err: print '***', err else: print 'Deleted breakpoint', i
def test_monotonic(self): data = hamlet_scene * 8 * 16 last = length = len(zlib.compress(data, 0)) self.failUnless(last > len(data), "compress level 0 always expands") for level in range(10): length = len(zlib.compress(data, level)) self.failUnless(length <= last, 'compress level %d more effective than %d!' % ( level-1, level)) last = length
def test_monotonic(self): # higher compression levels should not expand compressed size data = hamlet_scene * 8 * 16 last = length = len(zlib.compress(data, 0)) self.failUnless(last > len(data), "compress level 0 always expands") for level in range(10): length = len(zlib.compress(data, level)) self.failUnless(length <= last, 'compress level %d more effective than %d!' % ( level-1, level)) last = length
def urlencode(dict): """Encode a dictionary of form entries into a URL query string."""
def urlencode(dict,doseq=0): """Encode a dictionary of form entries into a URL query string. If any values in the dict are sequences and doseq is true, each sequence element is converted to a separate parameter. """
def urlencode(dict): """Encode a dictionary of form entries into a URL query string.""" l = [] for k, v in dict.items(): k = quote_plus(str(k)) v = quote_plus(str(v)) l.append(k + '=' + v) return '&'.join(l)
for k, v in dict.items(): k = quote_plus(str(k)) v = quote_plus(str(v)) l.append(k + '=' + v)
if not doseq: for k, v in dict.items(): k = quote_plus(str(k)) v = quote_plus(str(v)) l.append(k + '=' + v) else: for k, v in dict.items(): k = quote_plus(str(k)) if type(v) == types.StringType: v = quote_plus(v) l.append(k + '=' + v) elif type(v) == types.UnicodeType: v = quote_plus(v.encode("ASCII","replace")) l.append(k + '=' + v) else: try: x = len(v) except TypeError: v = quote_plus(str(v)) l.append(k + '=' + v) else: for elt in v: l.append(k + '=' + quote_plus(str(elt)))
def urlencode(dict): """Encode a dictionary of form entries into a URL query string.""" l = [] for k, v in dict.items(): k = quote_plus(str(k)) v = quote_plus(str(v)) l.append(k + '=' + v) return '&'.join(l)
_mesg('abort exception ignored: %s' % val)
def _get_tagged_response(self, tag):
code = compile(line + '\n', '<stdin>', 'single')
def default(self, line): if line[:1] == '!': line = line[1:] locals = self.curframe.f_locals globals = self.curframe.f_globals globals['__privileged__'] = 1 code = compile(line + '\n', '<stdin>', 'single') try: exec code in globals, locals except: if type(sys.exc_type) == type(''): exc_type_name = sys.exc_type else: exc_type_name = sys.exc_type.__name__ print '***', exc_type_name + ':', sys.exc_value
import imp
def _visit_pyfiles(list, dirname, names): """ Helper for getFilesForName(). """ # get extension for python source files if not globals().has_key('_py_ext'): import imp global _py_ext _py_ext = [triple[0] for triple in imp.get_suffixes() if triple[2] == imp.PY_SOURCE][0] # don't recurse into CVS directories if 'CVS' in names: names.remove('CVS') # add all *.py files to list list.extend( [os.path.join(dirname, file) for file in names if os.path.splitext(file)[1] == _py_ext])
import imp
def _get_modpkg_path(dotted_name, pathlist=None): """ Get the filesystem path for a module or a package. Return the file system path to a file for a module, and to a directory for a package. Return None if the name is not found, or is a builtin or extension module. """ import imp # split off top-most name parts = dotted_name.split('.', 1) if len(parts) > 1: # we have a dotted path, import top-level package try: file, pathname, description = imp.find_module(parts[0], pathlist) if file: file.close() except ImportError: return None # check if it's indeed a package if description[2] == imp.PKG_DIRECTORY: # recursively handle the remaining name parts pathname = _get_modpkg_path(parts[1], [pathname]) else: pathname = None else: # plain name try: file, pathname, description = imp.find_module(dotted_name, pathlist) if file: file.close() if description[2] not in [imp.PY_SOURCE, imp.PKG_DIRECTORY]: pathname = None except ImportError: pathname = None return pathname
import imp
def getFilesForName(name): """ Get a list of module files for a filename, a module or package name, or a directory. """ import imp if not os.path.exists(name): # check for glob chars if containsAny(name, "*?[]"): import glob files = glob.glob(name) list = [] for file in files: list.extend(getFilesForName(file)) return list # try to find module or package name = _get_modpkg_path(name) if not name: return [] if os.path.isdir(name): # find all python files in directory list = [] os.path.walk(name, _visit_pyfiles, list) return list elif os.path.exists(name): # a single file return [name] return []
import glob
def getFilesForName(name): """ Get a list of module files for a filename, a module or package name, or a directory. """ import imp if not os.path.exists(name): # check for glob chars if containsAny(name, "*?[]"): import glob files = glob.glob(name) list = [] for file in files: list.extend(getFilesForName(file)) return list # try to find module or package name = _get_modpkg_path(name) if not name: return [] if os.path.isdir(name): # find all python files in directory list = [] os.path.walk(name, _visit_pyfiles, list) return list elif os.path.exists(name): # a single file return [name] return []
_('*** Seen unexpected token "%(token)s"' % {'token': 'test'})
_('*** Seen unexpected token "%(token)s"') % {'token': 'test'}
def main(): global default_keywords try: opts, args = getopt.getopt( sys.argv[1:], 'ad:DEhk:Kno:p:S:Vvw:x:X:', ['extract-all', 'default-domain=', 'escape', 'help', 'keyword=', 'no-default-keywords', 'add-location', 'no-location', 'output=', 'output-dir=', 'style=', 'verbose', 'version', 'width=', 'exclude-file=', 'docstrings', 'no-docstrings', ]) except getopt.error, msg: usage(1, msg) # for holding option values class Options: # constants GNU = 1 SOLARIS = 2 # defaults extractall = 0 # FIXME: currently this option has no effect at all. escape = 0 keywords = [] outpath = '' outfile = 'messages.pot' writelocations = 1 locationstyle = GNU verbose = 0 width = 78 excludefilename = '' docstrings = 0 nodocstrings = {} options = Options() locations = {'gnu' : options.GNU, 'solaris' : options.SOLARIS, } # parse options for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-a', '--extract-all'): options.extractall = 1 elif opt in ('-d', '--default-domain'): options.outfile = arg + '.pot' elif opt in ('-E', '--escape'): options.escape = 1 elif opt in ('-D', '--docstrings'): options.docstrings = 1 elif opt in ('-k', '--keyword'): options.keywords.append(arg) elif opt in ('-K', '--no-default-keywords'): default_keywords = [] elif opt in ('-n', '--add-location'): options.writelocations = 1 elif opt in ('--no-location',): options.writelocations = 0 elif opt in ('-S', '--style'): options.locationstyle = locations.get(arg.lower()) if options.locationstyle is None: usage(1, _('Invalid value for --style: %s') % arg) elif opt in ('-o', '--output'): options.outfile = arg elif opt in ('-p', '--output-dir'): options.outpath = arg elif opt in ('-v', '--verbose'): options.verbose = 1 elif opt in ('-V', '--version'): print _('pygettext.py (xgettext for Python) %s') % __version__ sys.exit(0) elif opt in ('-w', '--width'): try: options.width = int(arg) except ValueError: usage(1, _('--width argument must be an integer: %s') % arg) elif opt in ('-x', '--exclude-file'): options.excludefilename = arg elif opt in ('-X', '--no-docstrings'): fp = open(arg) try: while 1: line = fp.readline() if not line: break options.nodocstrings[line[:-1]] = 1 finally: fp.close() # calculate escapes make_escapes(options.escape) # calculate all keywords options.keywords.extend(default_keywords) # initialize list of strings to exclude if options.excludefilename: try: fp = open(options.excludefilename) options.toexclude = fp.readlines() fp.close() except IOError: print >> sys.stderr, _( "Can't read --exclude-file: %s") % options.excludefilename sys.exit(1) else: options.toexclude = [] # resolve args to module lists expanded = [] for arg in args: if arg == '-': expanded.append(arg) else: expanded.extend(getFilesForName(arg)) args = expanded # slurp through all the files eater = TokenEater(options) for filename in args: if filename == '-': if options.verbose: print _('Reading standard input') fp = sys.stdin closep = 0 else: if options.verbose: print _('Working on %s') % filename fp = open(filename) closep = 1 try: eater.set_filename(filename) try: tokenize.tokenize(fp.readline, eater) except tokenize.TokenError, e: print >> sys.stderr, '%s: %s, line %d, column %d' % ( e[0], filename, e[1][0], e[1][1]) finally: if closep: fp.close() # write the output if options.outfile == '-': fp = sys.stdout closep = 0 else: if options.outpath: options.outfile = os.path.join(options.outpath, options.outfile) fp = open(options.outfile, 'w') closep = 1 try: eater.write(fp) finally: if closep: fp.close()
self.assertEqual(stderr, "pineapple")
self.assert_(stderr.startswith("pineapple"))
def test_communicate_stderr(self): p = subprocess.Popen([sys.executable, "-c", 'import sys; sys.stderr.write("pineapple")'], stderr=subprocess.PIPE) (stdout, stderr) = p.communicate() self.assertEqual(stdout, None) self.assertEqual(stderr, "pineapple")
import string if len(id) == 0:
global _idprog if not _idprog: _idprog = compile(r"[a-zA-Z_]\w*$") if _idprog.match(id): return 1 else:
def valid_identifier(id): import string if len(id) == 0: return 0 if id[0] not in string.letters+'_': return 0 for char in id[1:]: if not syntax_table[char] & word: return 0 return 1
if id[0] not in string.letters+'_': return 0 for char in id[1:]: if not syntax_table[char] & word: return 0 return 1
def valid_identifier(id): import string if len(id) == 0: return 0 if id[0] not in string.letters+'_': return 0 for char in id[1:]: if not syntax_table[char] & word: return 0 return 1
without effecting this threads data:
without affecting this thread's data:
... def squared(self):
if err[0] = errno.EINTR:
if err[0] == errno.EINTR:
def makefile(self, mode, bufsize=None): """Return a readable file-like object with data from socket.
'Header', 'Iterators', 'MIMEAudio', 'MIMEBase', 'MIMEImage', 'MIMEMessage', 'MIMEText', 'Message', 'Parser', 'Utils', 'base64MIME',
'Header', 'Iterators', 'MIMEAudio', 'MIMEBase', 'MIMEImage', 'MIMEMessage', 'MIMEMultipart', 'MIMENonMultipart', 'MIMEText', 'Message', 'Parser', 'Utils', 'base64MIME',
def test__all__(self): module = __import__('email') all = module.__all__ all.sort() self.assertEqual(all, ['Charset', 'Encoders', 'Errors', 'Generator', 'Header', 'Iterators', 'MIMEAudio', 'MIMEBase', 'MIMEImage', 'MIMEMessage', 'MIMEText', 'Message', 'Parser', 'Utils', 'base64MIME', 'message_from_file', 'message_from_string', 'quopriMIME'])
test_support.run_unittest(TestSFbugs) test_support.run_doctest(difflib)
Doctests = doctest.DocTestSuite(difflib) test_support.run_unittest(TestSFbugs, Doctests)
def test_ratio_for_null_seqn(self): # Check clearing of SF bug 763023 s = difflib.SequenceMatcher(None, [], []) self.assertEqual(s.ratio(), 1) self.assertEqual(s.quick_ratio(), 1) self.assertEqual(s.real_quick_ratio(), 1)
self.badmodules[name] = {m.__name__:None}
if not self.badmodules.has_key(name): self.badmodules[name] = {} self.badmodules[name][m.__name__] = None
def scan_code(self, co, m): code = co.co_code n = len(code) i = 0 lastname = None while i < n: c = code[i] i = i+1 op = ord(c) if op >= dis.HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 if op == IMPORT_NAME: name = lastname = co.co_names[oparg] if not self.badmodules.has_key(lastname): try: self.import_hook(name, m) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) self.badmodules[name] = {m.__name__:None} elif op == IMPORT_FROM: name = co.co_names[oparg] assert lastname is not None if not self.badmodules.has_key(lastname): try: self.import_hook(lastname, m, [name]) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) fullname = lastname + "." + name self.badmodules[fullname] = {m.__name__:None} else: lastname = None for c in co.co_consts: if isinstance(c, type(co)): self.scan_code(c, m)
self.badmodules[fullname] = {m.__name__:None}
if not self.badmodules.has_key(fullname): self.badmodules[fullname] = {} self.badmodules[fullname][m.__name__] = None
def scan_code(self, co, m): code = co.co_code n = len(code) i = 0 lastname = None while i < n: c = code[i] i = i+1 op = ord(c) if op >= dis.HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 if op == IMPORT_NAME: name = lastname = co.co_names[oparg] if not self.badmodules.has_key(lastname): try: self.import_hook(name, m) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) self.badmodules[name] = {m.__name__:None} elif op == IMPORT_FROM: name = co.co_names[oparg] assert lastname is not None if not self.badmodules.has_key(lastname): try: self.import_hook(lastname, m, [name]) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) fullname = lastname + "." + name self.badmodules[fullname] = {m.__name__:None} else: lastname = None for c in co.co_consts: if isinstance(c, type(co)): self.scan_code(c, m)
def AskPassword(prompt, default='', id=264):
def AskPassword(prompt, default='', id=264, ok=None, cancel=None):
def AskPassword(prompt, default='', id=264): """Display a PROMPT string and a text entry field with a DEFAULT string. The string is displayed as bullets only. Return the contents of the text entry field when the user clicks the OK button or presses Return. Return None when the user clicks the Cancel button. If omitted, DEFAULT is empty. The PROMPT and DEFAULT strings, as well as the return value, can be at most 255 characters long. """ d = GetNewDialog(id, -1) if not d: print "Can't get DLOG resource with id =", id return h = d.GetDialogItemAsControl(3) # STATIC TEXT ITEM <= prompt SetDialogItemText(h, lf2cr(prompt)) h = d.GetDialogItemAsControl(4) # EDIT TEXT ITEM bullets = '\245'*len(default) SetDialogItemText(h, bullets ) d.SelectDialogItemText(4, 999, 999) d.SetDialogDefaultItem(Dialogs.ok) d.SetDialogCancelItem(Dialogs.cancel) string = default oldschedparams = MacOS.SchedParams(0,0) while 1: ready,ev = Evt.WaitNextEvent(Events.everyEvent, 6) if not ready: continue what,msg,when,where,mod = ev if what == 0 : Dlg.DialogSelect(ev) # for blinking caret elif Dlg.IsDialogEvent(ev): if what in (Events.keyDown, Events.autoKey): charcode = msg & Events.charCodeMask if ( mod & Events.cmdKey ): MacOS.SysBeep() continue # don't do cut & paste commands else: if charcode == Events.kReturnCharCode: break elif charcode == Events.kEscapeCharCode: string = None break elif charcode in (Events.kLeftArrowCharCode, Events.kBackspaceCharCode): string = string[:-1] else: string = string + chr(charcode) msg = 0245 # Octal code for bullet ev = (what,msg,when,where,mod) rs, win, item = Dlg.DialogSelect(ev) if item == Dialogs.ok : break elif item == Dialogs.cancel : string = None break elif what == Events.mouseDown: part, win = Win.FindWindow(where) if part == Windows.inDrag and win: win.DragWindow(where, screenbounds) elif part == Windows.inMenuBar: MacOS.HandleEvent(ev) else: MacOS.SysBeep() # Cannot handle selections, unfortunately elif what == Events.updateEvt: MacOS.HandleEvent(ev) apply(MacOS.SchedParams, oldschedparams) return string
h = d.GetDialogItemAsControl(4)
pwd = d.GetDialogItemAsControl(4)
def AskPassword(prompt, default='', id=264): """Display a PROMPT string and a text entry field with a DEFAULT string. The string is displayed as bullets only. Return the contents of the text entry field when the user clicks the OK button or presses Return. Return None when the user clicks the Cancel button. If omitted, DEFAULT is empty. The PROMPT and DEFAULT strings, as well as the return value, can be at most 255 characters long. """ d = GetNewDialog(id, -1) if not d: print "Can't get DLOG resource with id =", id return h = d.GetDialogItemAsControl(3) # STATIC TEXT ITEM <= prompt SetDialogItemText(h, lf2cr(prompt)) h = d.GetDialogItemAsControl(4) # EDIT TEXT ITEM bullets = '\245'*len(default) SetDialogItemText(h, bullets ) d.SelectDialogItemText(4, 999, 999) d.SetDialogDefaultItem(Dialogs.ok) d.SetDialogCancelItem(Dialogs.cancel) string = default oldschedparams = MacOS.SchedParams(0,0) while 1: ready,ev = Evt.WaitNextEvent(Events.everyEvent, 6) if not ready: continue what,msg,when,where,mod = ev if what == 0 : Dlg.DialogSelect(ev) # for blinking caret elif Dlg.IsDialogEvent(ev): if what in (Events.keyDown, Events.autoKey): charcode = msg & Events.charCodeMask if ( mod & Events.cmdKey ): MacOS.SysBeep() continue # don't do cut & paste commands else: if charcode == Events.kReturnCharCode: break elif charcode == Events.kEscapeCharCode: string = None break elif charcode in (Events.kLeftArrowCharCode, Events.kBackspaceCharCode): string = string[:-1] else: string = string + chr(charcode) msg = 0245 # Octal code for bullet ev = (what,msg,when,where,mod) rs, win, item = Dlg.DialogSelect(ev) if item == Dialogs.ok : break elif item == Dialogs.cancel : string = None break elif what == Events.mouseDown: part, win = Win.FindWindow(where) if part == Windows.inDrag and win: win.DragWindow(where, screenbounds) elif part == Windows.inMenuBar: MacOS.HandleEvent(ev) else: MacOS.SysBeep() # Cannot handle selections, unfortunately elif what == Events.updateEvt: MacOS.HandleEvent(ev) apply(MacOS.SchedParams, oldschedparams) return string
SetDialogItemText(h, bullets ) d.SelectDialogItemText(4, 999, 999)
SetControlData(pwd, kControlEditTextPart, kControlEditTextPasswordTag, default) d.SelectDialogItemText(4, 0, 999) Ctl.SetKeyboardFocus(d, pwd, kControlEditTextPart) if ok != None: h = d.GetDialogItemAsControl(1) h.SetControlTitle(ok) if cancel != None: h = d.GetDialogItemAsControl(2) h.SetControlTitle(cancel)
def AskPassword(prompt, default='', id=264): """Display a PROMPT string and a text entry field with a DEFAULT string. The string is displayed as bullets only. Return the contents of the text entry field when the user clicks the OK button or presses Return. Return None when the user clicks the Cancel button. If omitted, DEFAULT is empty. The PROMPT and DEFAULT strings, as well as the return value, can be at most 255 characters long. """ d = GetNewDialog(id, -1) if not d: print "Can't get DLOG resource with id =", id return h = d.GetDialogItemAsControl(3) # STATIC TEXT ITEM <= prompt SetDialogItemText(h, lf2cr(prompt)) h = d.GetDialogItemAsControl(4) # EDIT TEXT ITEM bullets = '\245'*len(default) SetDialogItemText(h, bullets ) d.SelectDialogItemText(4, 999, 999) d.SetDialogDefaultItem(Dialogs.ok) d.SetDialogCancelItem(Dialogs.cancel) string = default oldschedparams = MacOS.SchedParams(0,0) while 1: ready,ev = Evt.WaitNextEvent(Events.everyEvent, 6) if not ready: continue what,msg,when,where,mod = ev if what == 0 : Dlg.DialogSelect(ev) # for blinking caret elif Dlg.IsDialogEvent(ev): if what in (Events.keyDown, Events.autoKey): charcode = msg & Events.charCodeMask if ( mod & Events.cmdKey ): MacOS.SysBeep() continue # don't do cut & paste commands else: if charcode == Events.kReturnCharCode: break elif charcode == Events.kEscapeCharCode: string = None break elif charcode in (Events.kLeftArrowCharCode, Events.kBackspaceCharCode): string = string[:-1] else: string = string + chr(charcode) msg = 0245 # Octal code for bullet ev = (what,msg,when,where,mod) rs, win, item = Dlg.DialogSelect(ev) if item == Dialogs.ok : break elif item == Dialogs.cancel : string = None break elif what == Events.mouseDown: part, win = Win.FindWindow(where) if part == Windows.inDrag and win: win.DragWindow(where, screenbounds) elif part == Windows.inMenuBar: MacOS.HandleEvent(ev) else: MacOS.SysBeep() # Cannot handle selections, unfortunately elif what == Events.updateEvt: MacOS.HandleEvent(ev) apply(MacOS.SchedParams, oldschedparams) return string
string = default oldschedparams = MacOS.SchedParams(0,0)
def AskPassword(prompt, default='', id=264): """Display a PROMPT string and a text entry field with a DEFAULT string. The string is displayed as bullets only. Return the contents of the text entry field when the user clicks the OK button or presses Return. Return None when the user clicks the Cancel button. If omitted, DEFAULT is empty. The PROMPT and DEFAULT strings, as well as the return value, can be at most 255 characters long. """ d = GetNewDialog(id, -1) if not d: print "Can't get DLOG resource with id =", id return h = d.GetDialogItemAsControl(3) # STATIC TEXT ITEM <= prompt SetDialogItemText(h, lf2cr(prompt)) h = d.GetDialogItemAsControl(4) # EDIT TEXT ITEM bullets = '\245'*len(default) SetDialogItemText(h, bullets ) d.SelectDialogItemText(4, 999, 999) d.SetDialogDefaultItem(Dialogs.ok) d.SetDialogCancelItem(Dialogs.cancel) string = default oldschedparams = MacOS.SchedParams(0,0) while 1: ready,ev = Evt.WaitNextEvent(Events.everyEvent, 6) if not ready: continue what,msg,when,where,mod = ev if what == 0 : Dlg.DialogSelect(ev) # for blinking caret elif Dlg.IsDialogEvent(ev): if what in (Events.keyDown, Events.autoKey): charcode = msg & Events.charCodeMask if ( mod & Events.cmdKey ): MacOS.SysBeep() continue # don't do cut & paste commands else: if charcode == Events.kReturnCharCode: break elif charcode == Events.kEscapeCharCode: string = None break elif charcode in (Events.kLeftArrowCharCode, Events.kBackspaceCharCode): string = string[:-1] else: string = string + chr(charcode) msg = 0245 # Octal code for bullet ev = (what,msg,when,where,mod) rs, win, item = Dlg.DialogSelect(ev) if item == Dialogs.ok : break elif item == Dialogs.cancel : string = None break elif what == Events.mouseDown: part, win = Win.FindWindow(where) if part == Windows.inDrag and win: win.DragWindow(where, screenbounds) elif part == Windows.inMenuBar: MacOS.HandleEvent(ev) else: MacOS.SysBeep() # Cannot handle selections, unfortunately elif what == Events.updateEvt: MacOS.HandleEvent(ev) apply(MacOS.SchedParams, oldschedparams) return string
ready,ev = Evt.WaitNextEvent(Events.everyEvent, 6) if not ready: continue what,msg,when,where,mod = ev if what == 0 : Dlg.DialogSelect(ev) elif Dlg.IsDialogEvent(ev): if what in (Events.keyDown, Events.autoKey): charcode = msg & Events.charCodeMask if ( mod & Events.cmdKey ): MacOS.SysBeep() continue else: if charcode == Events.kReturnCharCode: break elif charcode == Events.kEscapeCharCode: string = None break elif charcode in (Events.kLeftArrowCharCode, Events.kBackspaceCharCode): string = string[:-1] else: string = string + chr(charcode) msg = 0245 ev = (what,msg,when,where,mod) rs, win, item = Dlg.DialogSelect(ev) if item == Dialogs.ok : break elif item == Dialogs.cancel : string = None break elif what == Events.mouseDown: part, win = Win.FindWindow(where) if part == Windows.inDrag and win: win.DragWindow(where, screenbounds) elif part == Windows.inMenuBar: MacOS.HandleEvent(ev) else: MacOS.SysBeep() elif what == Events.updateEvt: MacOS.HandleEvent(ev) apply(MacOS.SchedParams, oldschedparams) return string
n = ModalDialog(None) if n == 1: h = d.GetDialogItemAsControl(4) return cr2lf(GetControlData(pwd, kControlEditTextPart, kControlEditTextPasswordTag)) if n == 2: return None
def AskPassword(prompt, default='', id=264): """Display a PROMPT string and a text entry field with a DEFAULT string. The string is displayed as bullets only. Return the contents of the text entry field when the user clicks the OK button or presses Return. Return None when the user clicks the Cancel button. If omitted, DEFAULT is empty. The PROMPT and DEFAULT strings, as well as the return value, can be at most 255 characters long. """ d = GetNewDialog(id, -1) if not d: print "Can't get DLOG resource with id =", id return h = d.GetDialogItemAsControl(3) # STATIC TEXT ITEM <= prompt SetDialogItemText(h, lf2cr(prompt)) h = d.GetDialogItemAsControl(4) # EDIT TEXT ITEM bullets = '\245'*len(default) SetDialogItemText(h, bullets ) d.SelectDialogItemText(4, 999, 999) d.SetDialogDefaultItem(Dialogs.ok) d.SetDialogCancelItem(Dialogs.cancel) string = default oldschedparams = MacOS.SchedParams(0,0) while 1: ready,ev = Evt.WaitNextEvent(Events.everyEvent, 6) if not ready: continue what,msg,when,where,mod = ev if what == 0 : Dlg.DialogSelect(ev) # for blinking caret elif Dlg.IsDialogEvent(ev): if what in (Events.keyDown, Events.autoKey): charcode = msg & Events.charCodeMask if ( mod & Events.cmdKey ): MacOS.SysBeep() continue # don't do cut & paste commands else: if charcode == Events.kReturnCharCode: break elif charcode == Events.kEscapeCharCode: string = None break elif charcode in (Events.kLeftArrowCharCode, Events.kBackspaceCharCode): string = string[:-1] else: string = string + chr(charcode) msg = 0245 # Octal code for bullet ev = (what,msg,when,where,mod) rs, win, item = Dlg.DialogSelect(ev) if item == Dialogs.ok : break elif item == Dialogs.cancel : string = None break elif what == Events.mouseDown: part, win = Win.FindWindow(where) if part == Windows.inDrag and win: win.DragWindow(where, screenbounds) elif part == Windows.inMenuBar: MacOS.HandleEvent(ev) else: MacOS.SysBeep() # Cannot handle selections, unfortunately elif what == Events.updateEvt: MacOS.HandleEvent(ev) apply(MacOS.SchedParams, oldschedparams) return string
ok = AskYesNoCancel("Do you want to identify?", yes="Indentify", no="Don't identify")
ok = AskYesNoCancel("Do you want to identify?", yes="Identify", no="No")
def test(): import time Message("Testing EasyDialogs.") ok = AskYesNoCancel("Do you want to proceed?") ok = AskYesNoCancel("Do you want to identify?", yes="Indentify", no="Don't identify") if ok > 0: s = AskString("Enter your first name", "Joe") Message("Thank you,\n%s" % `s`) text = ( "Working Hard...", "Hardly Working..." , "So far, so good!", "Keep on truckin'" ) bar = ProgressBar("Progress, progress...", 100) try: appsw = MacOS.SchedParams(1, 0) for i in range(100): bar.set(i) time.sleep(0.1) if i % 10 == 0: bar.label(text[(i/10) % 4]) bar.label("Done.") time.sleep(0.3) # give'em a chance to see the done. finally: del bar apply(MacOS.SchedParams, appsw)