rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
if line == '.': line = '..' | if line[:1] == '.': line = '.' + line | def post(self, f): resp = self.shortcmd('POST') # Raises error_??? if posting is not allowed if resp[0] <> '3': raise error_reply, resp while 1: line = f.readline() if not line: break if line[-1] == '\n': line = line[:-1] if line == '.': line = '..' self.putline(line) self.putline('.') return self.getresp() |
if line == '.': line = '..' | if line[:1] == '.': line = '.' + line | def ihave(self, id, f): resp = self.shortcmd('IHAVE ' + id) # Raises error_??? if the server already has it if resp[0] <> '3': raise error_reply, resp while 1: line = f.readline() if not line: break if line[-1] == '\n': line = line[:-1] if line == '.': line = '..' self.putline(line) self.putline('.') return self.getresp() |
self.show(name, headers['title'], text, 1) | self.show(name, headers['title'], text) | def do_show(self): |
self.show(name, title, text, 1) | self.show(name, title, text) | def do_all(self): |
self.show(name, headers['title'], text, 1) print '<P><A HREF="faq.py?req=roulette">Show another one</A>' | self.show(name, headers['title'], text) print "<P>Use `Reload' to show another one." | def do_roulette(self): |
self.show(name, headers['title'], text, 1) | self.show(name, headers['title'], text) | def do_recent(self): |
self.show(name, title, text, 1) | self.show(name, title, text) | def do_query(self): |
self.show(name, title, text) | self.show(name, title, text, edit=0) | def do_edit(self): |
self.show(name, title, text) | self.show(name, title, text, edit=0) | def do_review(self): |
self.show(name, title, text, 1) | self.show(name, title, text) | def checkin(self): |
Title: <INPUT TYPE=text SIZE=70 NAME=title VALUE="%s"<BR> | Title: <INPUT TYPE=text SIZE=70 NAME=title VALUE="%s"><BR> | def showedit(self, name, title, text): |
<CODE>Name : </CODE><INPUT TYPE=text SIZE=70 NAME=author VALUE="%s"<BR> <CODE>Email: </CODE><INPUT TYPE=text SIZE=70 NAME=email VALUE="%s"<BR> | <CODE>Name : </CODE><INPUT TYPE=text SIZE=40 NAME=author VALUE="%s"> <BR> <CODE>Email: </CODE><INPUT TYPE=text SIZE=40 NAME=email VALUE="%s"> <BR> | def showedit(self, name, title, text): |
return headers, text f = open(name) headers = rfc822.Message(f) text = f.read() f.close() | else: f = open(name) headers = rfc822.Message(f) text = f.read() f.close() self.headers = headers | def read(self, name): |
def show(self, name, title, text, edit=0): | def show(self, name, title, text, edit=1): | def show(self, name, title, text, edit=0): |
{'message' : 'foo', 'args' : ('foo',)}), | {'message' : 'foo', 'args' : ('foo',), 'filename' : None, 'errno' : None, 'strerror' : None}), | def testAttributes(self): # test that exception attributes are happy |
{'message' : '', 'args' : ('foo', 'bar')}), | {'message' : '', 'args' : ('foo', 'bar'), 'filename' : None, 'errno' : 'foo', 'strerror' : 'bar'}), | def testAttributes(self): # test that exception attributes are happy |
{'message' : '', 'args' : ('foo', 'bar')}), | {'message' : '', 'args' : ('foo', 'bar'), 'filename' : 'baz', 'errno' : 'foo', 'strerror' : 'bar'}), (IOError, ('foo', 'bar', 'baz', 'quux'), {'message' : '', 'args' : ('foo', 'bar', 'baz', 'quux')}), | def testAttributes(self): # test that exception attributes are happy |
if type(klass) != types.ClassType: raise TypeError, "setLoggerClass is expecting a class" | def setLoggerClass(klass): """ Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__() """ if klass != Logger: if type(klass) != types.ClassType: raise TypeError, "setLoggerClass is expecting a class" if not issubclass(klass, Logger): raise TypeError, "logger not derived from logging.Logger: " + \ klass.__name__ global _loggerClass _loggerClass = klass |
|
if hasattr(os, 'chmod'): | if hasattr(os, 'chmod') and sys.platform[:6] != 'cygwin': | def test_rmtree_errors(self): # filename is guaranteed not to exist filename = tempfile.mktemp() self.assertRaises(OSError, shutil.rmtree, filename) |
global template if template == None: | global template, _pid if os.name == 'posix' and _pid and _pid != os.getpid(): template = None if template is None: | def gettempprefix(): global template if template == None: if os.name == 'posix': template = '@' + `os.getpid()` + '.' elif os.name == 'nt': template = '~' + `os.getpid()` + '-' elif os.name == 'mac': template = 'Python-Tmp-' else: template = 'tmp' # XXX might choose a better one return template |
template = '@' + `os.getpid()` + '.' | _pid = os.getpid() template = '@' + `_pid` + '.' | def gettempprefix(): global template if template == None: if os.name == 'posix': template = '@' + `os.getpid()` + '.' elif os.name == 'nt': template = '~' + `os.getpid()` + '-' elif os.name == 'mac': template = 'Python-Tmp-' else: template = 'tmp' # XXX might choose a better one return template |
if cl.super: | if hasattr(cl, 'super') and cl.super: | def listclasses(self): dir, file = os.path.split(self.file) name, ext = os.path.splitext(file) if os.path.normcase(ext) != ".py": return [] try: dict = pyclbr.readmodule_ex(name, [dir] + sys.path) except ImportError, msg: return [] items = [] self.classes = {} for key, cl in dict.items(): if cl.module == name: s = key if cl.super: supers = [] for sup in cl.super: if type(sup) is type(''): sname = sup else: sname = sup.name if sup.module != cl.module: sname = "%s.%s" % (sup.module, sname) supers.append(sname) s = s + "(%s)" % ", ".join(supers) items.append((cl.lineno, s)) self.classes[s] = cl items.sort() list = [] for item, s in items: list.append(s) return list |
self.__current_realm = None | def __init__(self, password_mgr=None): if password_mgr is None: password_mgr = HTTPPasswordMgr() self.passwd = password_mgr self.add_password = self.passwd.add_password self.__current_realm = None # if __current_realm is not None, then the server must have # refused our name/password and is asking for authorization # again. must be careful to set it to None on successful # return. |
|
if self.__current_realm is None: self.__current_realm = realm else: self.__current_realm = realm return None | def retry_http_basic_auth(self, host, req, realm): if self.__current_realm is None: self.__current_realm = realm else: self.__current_realm = realm return None user,pw = self.passwd.find_user_password(realm, host) if pw: raw = "%s:%s" % (user, pw) auth = base64.encodestring(raw).strip() req.add_header(self.header, 'Basic %s' % auth) resp = self.parent.open(req) self.__current_realm = None return resp else: self.__current_realm = None return None |
|
auth = base64.encodestring(raw).strip() req.add_header(self.header, 'Basic %s' % auth) resp = self.parent.open(req) self.__current_realm = None return resp else: self.__current_realm = None | auth = 'Basic %s' % base64.encodestring(raw).strip() if req.headers.get(self.auth_header, None) == auth: return None req.add_header(self.auth_header, auth) return self.parent.open(req) else: | def retry_http_basic_auth(self, host, req, realm): if self.__current_realm is None: self.__current_realm = realm else: self.__current_realm = realm return None user,pw = self.passwd.find_user_password(realm, host) if pw: raw = "%s:%s" % (user, pw) auth = base64.encodestring(raw).strip() req.add_header(self.header, 'Basic %s' % auth) resp = self.parent.open(req) self.__current_realm = None return resp else: self.__current_realm = None return None |
header = 'Authorization' | auth_header = 'Authorization' | def retry_http_basic_auth(self, host, req, realm): if self.__current_realm is None: self.__current_realm = realm else: self.__current_realm = realm return None user,pw = self.passwd.find_user_password(realm, host) if pw: raw = "%s:%s" % (user, pw) auth = base64.encodestring(raw).strip() req.add_header(self.header, 'Basic %s' % auth) resp = self.parent.open(req) self.__current_realm = None return resp else: self.__current_realm = None return None |
header = 'Proxy-Authorization' | auth_header = 'Proxy-Authorization' | def http_error_401(self, req, fp, code, msg, headers): host = urlparse.urlparse(req.get_full_url())[1] return self.http_error_auth_reqed('www-authenticate', host, req, headers) |
self.__current_realm = None | def __init__(self, passwd=None): if passwd is None: passwd = HTTPPasswordMgr() self.passwd = passwd self.add_password = self.passwd.add_password self.__current_realm = None |
|
authreq = headers.get(self.header, None) | authreq = headers.get(self.auth_header, None) | def http_error_auth_reqed(self, authreq, host, req, headers): authreq = headers.get(self.header, None) if authreq: kind = authreq.split()[0] if kind == 'Digest': return self.retry_http_digest_auth(req, authreq) |
req.add_header(self.header, 'Digest %s' % auth) | auth_val = 'Digest %s' % auth if req.headers.get(self.auth_header, None) == auth_val: return None req.add_header(self.auth_header, auth_val) | def retry_http_digest_auth(self, req, auth): token, challenge = auth.split(' ', 1) chal = parse_keqv_list(parse_http_list(challenge)) auth = self.get_authorization(req, chal) if auth: req.add_header(self.header, 'Digest %s' % auth) resp = self.parent.open(req) self.__current_realm = None return resp |
self.__current_realm = None | def retry_http_digest_auth(self, req, auth): token, challenge = auth.split(' ', 1) chal = parse_keqv_list(parse_http_list(challenge)) auth = self.get_authorization(req, chal) if auth: req.add_header(self.header, 'Digest %s' % auth) resp = self.parent.open(req) self.__current_realm = None return resp |
|
return None if self.__current_realm is None: self.__current_realm = realm else: self.__current_realm = realm | def get_authorization(self, req, chal): try: realm = chal['realm'] nonce = chal['nonce'] algorithm = chal.get('algorithm', 'MD5') # mod_digest doesn't send an opaque, even though it isn't # supposed to be optional opaque = chal.get('opaque', None) except KeyError: return None |
|
BLOCKSIZE = 8192 while 1: data = source.read(BLOCKSIZE) if not data: break outputfile.write(data) | shutil.copyfileobj(source, outputfile) | def copyfile(self, source, outputfile): """Copy all data between two file objects. |
c = cmp(dict1, dict2) | if random.random() < 0.5: c = cmp(dict1, dict2) else: c = dict1 == dict2 | def test_one(n): global mutate, dict1, dict2, dict1keys, dict2keys # Fill the dicts without mutating them. mutate = 0 dict1keys = fill_dict(dict1, range(n), n) dict2keys = fill_dict(dict2, range(n), n) # Enable mutation, then compare the dicts so long as they have the # same size. mutate = 1 if verbose: print "trying w/ lengths", len(dict1), len(dict2), while dict1 and len(dict1) == len(dict2): if verbose: print ".", c = cmp(dict1, dict2) if verbose: print |
menu.configure(postcommand=self.postwindowsmenu) | WindowList.register_callback(self.postwindowsmenu) | def __init__(self, flist=None, filename=None, key=None, root=None): self.flist = flist root = root or flist.root self.root = root if flist: self.vars = flist.vars self.menubar = Menu(root) self.top = top = self.Toplevel(root, menu=self.menubar) self.vbar = vbar = Scrollbar(top, name='vbar') self.text = text = Text(top, name='text', padx=5, background="white", wrap="none") |
import WindowList | def postwindowsmenu(self): # Only called when Windows menu exists # XXX Actually, this Just-In-Time updating interferes # XXX badly with the tear-off feature. It would be better # XXX to update all Windows menus whenever the list of windows # XXX changes. menu = self.menudict['windows'] end = menu.index("end") if end is None: end = -1 if end > self.wmenu_end: menu.delete(self.wmenu_end+1, end) import WindowList WindowList.add_windows_to_menu(menu) |
|
if m[0] != '_' and m != 'config': | if m[0] != '_' and m != 'config' and m != 'configure': | def __init__(self, master=None, cnf={}, **kw): if kw: cnf = _cnfmerge((cnf, kw)) fcnf = {} for k in cnf.keys(): if type(k) == ClassType or k == 'name': fcnf[k] = cnf[k] del cnf[k] self.frame = apply(Frame, (master,), fcnf) self.vbar = Scrollbar(self.frame, name='vbar') self.vbar.pack(side=RIGHT, fill=Y) cnf['name'] = 'text' apply(Text.__init__, (self, self.frame), cnf) self.pack(side=LEFT, fill=BOTH, expand=1) self['yscrollcommand'] = self.vbar.set self.vbar['command'] = self.yview |
- server response code (e.g. '250', or such, if all goes well) Note: returns -1 if it can't read response code. - server response string corresponding to response code (note : multiline responses converted to a single, multiline string) | - server response code (e.g. '250', or such, if all goes well) Note: returns -1 if it can't read response code. - server response string corresponding to response code (multiline responses are converted to a single, multiline string). | def getreply(self): """Get a reply from the server. Returns a tuple consisting of: - server response code (e.g. '250', or such, if all goes well) Note: returns -1 if it can't read response code. - server response string corresponding to response code (note : multiline responses converted to a single, multiline string) """ resp=[] self.file = self.sock.makefile('rb') while 1: line = self.file.readline() if self.debuglevel > 0: print 'reply:', `line` resp.append(string.strip(line[4:])) code=line[:3] #check if multiline resp if line[3:4]!="-": break try: errcode = string.atoi(code) except(ValueError): errcode = -1 |
"""SMTP 'DATA' command. Sends message data to server. | """SMTP 'DATA' command -- sends message data to server. | def data(self,msg): """SMTP 'DATA' command. Sends message data to server. Automatically quotes lines beginning with a period per rfc821. """ self.putcmd("data") (code,repl)=self.getreply() if self.debuglevel >0 : print "data:", (code,repl) if code <> 354: return -1 else: self.send(quotedata(msg)) self.send("%s.%s" % (CRLF, CRLF)) (code,msg)=self.getreply() if self.debuglevel >0 : print "data:", (code,msg) return code |
makefile_in = os.path.join(exec_prefix, 'Modules', 'Makefile') | makefile_in = os.path.join(exec_prefix, 'Makefile') | def main(): # overridable context prefix = None # settable with -p option exec_prefix = None # settable with -P option extensions = [] exclude = [] # settable with -x option addn_link = [] # settable with -l, but only honored under Windows. path = sys.path[:] modargs = 0 debug = 1 odir = '' win = sys.platform[:3] == 'win' replace_paths = [] # settable with -r option error_if_any_missing = 0 # default the exclude list for each platform if win: exclude = exclude + [ 'dos', 'dospath', 'mac', 'macpath', 'macfs', 'MACFS', 'posix', 'os2', 'ce', 'riscos', 'riscosenviron', 'riscospath', ] fail_import = exclude[:] # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' subsystem = 'console' # parse command line by first replacing any "-i" options with the # file contents. pos = 1 while pos < len(sys.argv)-1: # last option can not be "-i", so this ensures "pos+1" is in range! if sys.argv[pos] == '-i': try: options = open(sys.argv[pos+1]).read().split() except IOError, why: usage("File name '%s' specified with the -i option " "can not be read - %s" % (sys.argv[pos+1], why) ) # Replace the '-i' and the filename with the read params. sys.argv[pos:pos+2] = options pos = pos + len(options) - 1 # Skip the name and the included args. pos = pos + 1 # Now parse the command line with the extras inserted. try: opts, args = getopt.getopt(sys.argv[1:], 'r:a:dEe:hmo:p:P:qs:wX:x:l:') except getopt.error, msg: usage('getopt error: ' + str(msg)) # proces option arguments for o, a in opts: if o == '-h': print __doc__ return if o == '-d': debug = debug + 1 if o == '-e': extensions.append(a) if o == '-m': modargs = 1 if o == '-o': odir = a if o == '-p': prefix = a if o == '-P': exec_prefix = a if o == '-q': debug = 0 if o == '-w': win = not win if o == '-s': if not win: usage("-s subsystem option only on Windows") subsystem = a if o == '-x': exclude.append(a) if o == '-X': exclude.append(a) fail_import.append(a) if o == '-E': error_if_any_missing = 1 if o == '-l': addn_link.append(a) if o == '-a': apply(modulefinder.AddPackagePath, tuple(a.split("=", 2))) if o == '-r': f,r = a.split("=", 2) replace_paths.append( (f,r) ) # modules that are imported by the Python runtime implicits = [] for module in ('site', 'warnings',): if module not in exclude: implicits.append(module) # default prefix and exec_prefix if not exec_prefix: if prefix: exec_prefix = prefix else: exec_prefix = sys.exec_prefix if not prefix: prefix = sys.prefix # determine whether -p points to the Python source tree ishome = os.path.exists(os.path.join(prefix, 'Python', 'ceval.c')) # locations derived from options version = sys.version[:3] if win: extensions_c = 'frozen_extensions.c' if ishome: print "(Using Python source directory)" binlib = exec_prefix incldir = os.path.join(prefix, 'Include') config_h_dir = exec_prefix config_c_in = os.path.join(prefix, 'Modules', 'config.c.in') frozenmain_c = os.path.join(prefix, 'Python', 'frozenmain.c') makefile_in = os.path.join(exec_prefix, 'Modules', 'Makefile') if win: frozendllmain_c = os.path.join(exec_prefix, 'Pc\\frozen_dllmain.c') else: binlib = os.path.join(exec_prefix, 'lib', 'python%s' % version, 'config') incldir = os.path.join(prefix, 'include', 'python%s' % version) config_h_dir = os.path.join(exec_prefix, 'include', 'python%s' % version) config_c_in = os.path.join(binlib, 'config.c.in') frozenmain_c = os.path.join(binlib, 'frozenmain.c') makefile_in = os.path.join(binlib, 'Makefile') frozendllmain_c = os.path.join(binlib, 'frozen_dllmain.c') supp_sources = [] defines = [] includes = ['-I' + incldir, '-I' + config_h_dir] # sanity check of directories and files check_dirs = [prefix, exec_prefix, binlib, incldir] if not win: # These are not directories on Windows. check_dirs = check_dirs + extensions for dir in check_dirs: if not os.path.exists(dir): usage('needed directory %s not found' % dir) if not os.path.isdir(dir): usage('%s: not a directory' % dir) if win: files = supp_sources + extensions # extensions are files on Windows. else: files = [config_c_in, makefile_in] + supp_sources for file in supp_sources: if not os.path.exists(file): usage('needed file %s not found' % file) if not os.path.isfile(file): usage('%s: not a plain file' % file) if not win: for dir in extensions: setup = os.path.join(dir, 'Setup') if not os.path.exists(setup): usage('needed file %s not found' % setup) if not os.path.isfile(setup): usage('%s: not a plain file' % setup) # check that enough arguments are passed if not args: usage('at least one filename argument required') # check that file arguments exist for arg in args: if arg == '-m': break # if user specified -m on the command line before _any_ # file names, then nothing should be checked (as the # very first file should be a module name) if modargs: break if not os.path.exists(arg): usage('argument %s not found' % arg) if not os.path.isfile(arg): usage('%s: not a plain file' % arg) # process non-option arguments scriptfile = args[0] modules = args[1:] # derive target name from script name base = os.path.basename(scriptfile) base, ext = os.path.splitext(base) if base: if base != scriptfile: target = base else: target = base + '.bin' # handle -o option base_frozen_c = frozen_c base_config_c = config_c base_target = target if odir and not os.path.isdir(odir): try: os.mkdir(odir) print "Created output directory", odir except os.error, msg: usage('%s: mkdir failed (%s)' % (odir, str(msg))) base = '' if odir: base = os.path.join(odir, '') frozen_c = os.path.join(odir, frozen_c) config_c = os.path.join(odir, config_c) target = os.path.join(odir, target) makefile = os.path.join(odir, makefile) if win: extensions_c = os.path.join(odir, extensions_c) # Handle special entry point requirements # (on Windows, some frozen programs do not use __main__, but # import the module directly. Eg, DLLs, Services, etc custom_entry_point = None # Currently only used on Windows python_entry_is_main = 1 # Is the entry point called __main__? # handle -s option on Windows if win: import winmakemakefile try: custom_entry_point, python_entry_is_main = \ winmakemakefile.get_custom_entry_point(subsystem) except ValueError, why: usage(why) # Actual work starts here... # collect all modules of the program dir = os.path.dirname(scriptfile) path[0] = dir mf = modulefinder.ModuleFinder(path, debug, exclude, replace_paths) if win and subsystem=='service': # If a Windows service, then add the "built-in" module. mod = mf.add_module("servicemanager") mod.__file__="dummy.pyd" # really built-in to the resulting EXE for mod in implicits: mf.import_hook(mod) for mod in modules: if mod == '-m': modargs = 1 continue if modargs: if mod[-2:] == '.*': mf.import_hook(mod[:-2], None, ["*"]) else: mf.import_hook(mod) else: mf.load_file(mod) # Add the main script as either __main__, or the actual module name. if python_entry_is_main: mf.run_script(scriptfile) else: mf.load_file(scriptfile) if debug > 0: mf.report() print dict = mf.modules if error_if_any_missing: missing = mf.any_missing() if missing: sys.exit("There are some missing modules: %r" % missing) # generate output for frozen modules files = makefreeze.makefreeze(base, dict, debug, custom_entry_point, fail_import) # look for unfrozen modules (builtin and of unknown origin) builtins = [] unknown = [] mods = dict.keys() mods.sort() for mod in mods: if dict[mod].__code__: continue if not dict[mod].__file__: builtins.append(mod) else: unknown.append(mod) # search for unknown modules in extensions directories (not on Windows) addfiles = [] frozen_extensions = [] # Windows list of modules. if unknown or (not win and builtins): if not win: addfiles, addmods = \ checkextensions.checkextensions(unknown+builtins, extensions) for mod in addmods: if mod in unknown: unknown.remove(mod) builtins.append(mod) else: # Do the windows thang... import checkextensions_win32 # Get a list of CExtension instances, each describing a module # (including its source files) frozen_extensions = checkextensions_win32.checkextensions( unknown, extensions, prefix) for mod in frozen_extensions: unknown.remove(mod.name) # report unknown modules if unknown: sys.stderr.write('Warning: unknown modules remain: %s\n' % ' '.join(unknown)) # windows gets different treatment if win: # Taking a shortcut here... import winmakemakefile, checkextensions_win32 checkextensions_win32.write_extension_table(extensions_c, frozen_extensions) # Create a module definition for the bootstrap C code. xtras = [frozenmain_c, os.path.basename(frozen_c), frozendllmain_c, os.path.basename(extensions_c)] + files maindefn = checkextensions_win32.CExtension( '__main__', xtras ) frozen_extensions.append( maindefn ) outfp = open(makefile, 'w') try: winmakemakefile.makemakefile(outfp, locals(), frozen_extensions, os.path.basename(target)) finally: outfp.close() return # generate config.c and Makefile builtins.sort() infp = open(config_c_in) outfp = bkfile.open(config_c, 'w') try: makeconfig.makeconfig(infp, outfp, builtins) finally: outfp.close() infp.close() cflags = ['$(OPT)'] cppflags = defines + includes libs = [os.path.join(binlib, 'libpython$(VERSION).a')] somevars = {} if os.path.exists(makefile_in): makevars = parsesetup.getmakevars(makefile_in) for key in makevars.keys(): somevars[key] = makevars[key] somevars['CFLAGS'] = ' '.join(cflags) # override somevars['CPPFLAGS'] = ' '.join(cppflags) # override files = [base_config_c, base_frozen_c] + \ files + supp_sources + addfiles + libs + \ ['$(MODLIBS)', '$(LIBS)', '$(SYSLIBS)'] outfp = bkfile.open(makefile, 'w') try: makemakefile.makemakefile(outfp, somevars, files, base_target) finally: outfp.close() # Done! if odir: print 'Now run "make" in', odir, print 'to build the target:', base_target else: print 'Now run "make" to build the target:', base_target |
ef = codecs.EncodedFile(f, 'utf-16', 'utf-8') | ef = codecs.EncodedFile(f, 'utf-16-le', 'utf-8') | def test_basic(self): f = StringIO.StringIO('\xed\x95\x9c\n\xea\xb8\x80') ef = codecs.EncodedFile(f, 'utf-16', 'utf-8') self.assertEquals(ef.read(), '\xff\xfe\\\xd5\n\x00\x00\xae') |
self.compiler = new_compiler ( compiler="msvc", | self.compiler = new_compiler (compiler=self.compiler, | def run (self): |
extra_args = ext.extra_compile_args | extra_args = ext.extra_compile_args or [] | def build_extensions (self): |
extra_args = ext.extra_link_args | extra_args = ext.extra_link_args or [] | def build_extensions (self): |
xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)), | xmlrpclib.Fault(1, "%s:%s" % (exc_type, exc_value)), | def _marshaled_dispatch(self, data, dispatch_method = None): """Dispatches an XML-RPC method from marshalled (XML) data. |
'faultString' : "%s:%s" % (sys.exc_type, sys.exc_value)} | 'faultString' : "%s:%s" % (exc_type, exc_value)} | def system_multicall(self, call_list): """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \ |
if i < 0: return None data[0] = data[0][i+1:] | if i >= 0: data[0] = data[0][i+1:] | def parsedate_tz(data): """Convert a date string to a time tuple. Accounts for military timezones. """ data = data.split() # The FWS after the comma after the day-of-week is optional, so search and # adjust for this. if data[0].endswith(',') or data[0].lower() in _daynames: # There's a dayname here. Skip it del data[0] else: i = data[0].rfind(',') if i < 0: return None data[0] = data[0][i+1:] if len(data) == 3: # RFC 850 date, deprecated stuff = data[0].split('-') if len(stuff) == 3: data = stuff + data[1:] if len(data) == 4: s = data[3] i = s.find('+') if i > 0: data[3:] = [s[:i], s[i+1:]] else: data.append('') # Dummy tz if len(data) < 5: return None data = data[:5] [dd, mm, yy, tm, tz] = data mm = mm.lower() if mm not in _monthnames: dd, mm = mm, dd.lower() if mm not in _monthnames: return None mm = _monthnames.index(mm) + 1 if mm > 12: mm -= 12 if dd[-1] == ',': dd = dd[:-1] i = yy.find(':') if i > 0: yy, tm = tm, yy if yy[-1] == ',': yy = yy[:-1] if not yy[0].isdigit(): yy, tz = tz, yy if tm[-1] == ',': tm = tm[:-1] tm = tm.split(':') if len(tm) == 2: [thh, tmm] = tm tss = '0' elif len(tm) == 3: [thh, tmm, tss] = tm else: return None try: yy = int(yy) dd = int(dd) thh = int(thh) tmm = int(tmm) tss = int(tss) except ValueError: return None tzoffset = None tz = tz.upper() if _timezones.has_key(tz): tzoffset = _timezones[tz] else: try: tzoffset = int(tz) except ValueError: pass # Convert a timezone offset into seconds ; -0500 -> -18000 if tzoffset: if tzoffset < 0: tzsign = -1 tzoffset = -tzoffset else: tzsign = 1 tzoffset = tzsign * ( (tzoffset/100)*3600 + (tzoffset % 100)*60) tuple = (yy, mm, dd, thh, tmm, tss, 0, 0, 0, tzoffset) return tuple |
tester('ntpath.splitdrive("\\\\conky\\mountpoint\\foo\\bar")', ('\\\\conky\\mountpoint', '\\foo\\bar')) | tester('ntpath.splitunc("\\\\conky\\mountpoint\\foo\\bar")', ('\\\\conky\\mountpoint', '\\foo\\bar')) | def tester(fn, wantResult): fn = string.replace(fn, "\\", "\\\\") gotResult = eval(fn) if wantResult != gotResult: print "error!" print "evaluated: " + str(fn) print "should be: " + str(wantResult) print " returned: " + str(gotResult) print "" global errors errors = errors + 1 |
tester('ntpath.splitdrive("//conky/mountpoint/foo/bar")', ('//conky/mountpoint', '/foo/bar')) | tester('ntpath.splitunc("//conky/mountpoint/foo/bar")', ('//conky/mountpoint', '/foo/bar')) | def tester(fn, wantResult): fn = string.replace(fn, "\\", "\\\\") gotResult = eval(fn) if wantResult != gotResult: print "error!" print "evaluated: " + str(fn) print "should be: " + str(wantResult) print " returned: " + str(gotResult) print "" global errors errors = errors + 1 |
tester('ntpath.split("\\\\conky\\mountpoint\\")', ('\\\\conky\\mountpoint\\', '')) | tester('ntpath.split("\\\\conky\\mountpoint\\")', ('\\\\conky\\mountpoint', '')) | def tester(fn, wantResult): fn = string.replace(fn, "\\", "\\\\") gotResult = eval(fn) if wantResult != gotResult: print "error!" print "evaluated: " + str(fn) print "should be: " + str(wantResult) print " returned: " + str(gotResult) print "" global errors errors = errors + 1 |
tester('ntpath.split("//conky/mountpoint/")', ('//conky/mountpoint/', '')) | tester('ntpath.split("//conky/mountpoint/")', ('//conky/mountpoint', '')) | def tester(fn, wantResult): fn = string.replace(fn, "\\", "\\\\") gotResult = eval(fn) if wantResult != gotResult: print "error!" print "evaluated: " + str(fn) print "should be: " + str(wantResult) print " returned: " + str(gotResult) print "" global errors errors = errors + 1 |
if name in ('os2', ): | if name in ('os2', 'nt', 'dos'): | def _execvpe(file, args, env = None): if env: func = execve argrest = (args, env) else: func = execv argrest = (args,) env = environ global _notfound head, tail = path.split(file) if head: apply(func, (file,) + argrest) return if env.has_key('PATH'): envpath = env['PATH'] else: envpath = defpath import string PATH = string.splitfields(envpath, pathsep) if not _notfound: import tempfile # Exec a file that is guaranteed not to exist try: execv(tempfile.mktemp(), ()) except error, _notfound: pass exc, arg = error, _notfound for dir in PATH: fullname = path.join(dir, file) try: apply(func, (fullname,) + argrest) except error, (errno, msg): if errno != arg[0]: exc, arg = error, (errno, msg) raise exc, arg |
key = string.upper(key) | def __setitem__(self, key, item): key = string.upper(key) putenv(key, item) self.data[key] = item |
|
def __getitem__(self, key): return self.data[string.upper(key)] else: class _Environ(UserDict.UserDict): def __init__(self, environ): UserDict.UserDict.__init__(self) self.data = environ def __getinitargs__(self): import copy return (copy.copy(self.data),) def __setitem__(self, key, item): putenv(key, item) self.data[key] = item def __copy__(self): return _Environ(self.data.copy()) | def __getitem__(self, key): return self.data[string.upper(key)] |
|
from distutils.core import DEBUG | def parse_config_files (self, filenames=None): |
|
from distutils.core import DEBUG | def get_command_obj (self, command, create=1): """Return the command object for 'command'. Normally this object is cached on a previous call to 'get_command_obj()'; if no command object for 'command' is in the cache, then we either create and return it (if 'create' is true) or return None. """ from distutils.core import DEBUG cmd_obj = self.command_obj.get(command) if not cmd_obj and create: if DEBUG: print "Distribution.get_command_obj(): " \ "creating '%s' command object" % command |
|
from distutils.core import DEBUG | def _set_command_options (self, command_obj, option_dict=None): """Set the options for 'command_obj' from 'option_dict'. Basically this means copying elements of a dictionary ('option_dict') to attributes of an instance ('command'). |
|
for key, val in dict.items(): | for key in dict.keys(): | def __fixdict(self, dict): for key, val in dict.items(): if key[:6] == 'start_': key = key[6:] start, end = self.elements.get(key, (None, None)) if start is None: self.elements[key] = val, end elif key[:4] == 'end_': key = key[4:] start, end = self.elements.get(key, (None, None)) if end is None: self.elements[key] = start, val |
key = key[6:] start, end = self.elements.get(key, (None, None)) | tag = key[6:] start, end = self.elements.get(tag, (None, None)) | def __fixdict(self, dict): for key, val in dict.items(): if key[:6] == 'start_': key = key[6:] start, end = self.elements.get(key, (None, None)) if start is None: self.elements[key] = val, end elif key[:4] == 'end_': key = key[4:] start, end = self.elements.get(key, (None, None)) if end is None: self.elements[key] = start, val |
self.elements[key] = val, end | self.elements[tag] = getattr(self, key), end | def __fixdict(self, dict): for key, val in dict.items(): if key[:6] == 'start_': key = key[6:] start, end = self.elements.get(key, (None, None)) if start is None: self.elements[key] = val, end elif key[:4] == 'end_': key = key[4:] start, end = self.elements.get(key, (None, None)) if end is None: self.elements[key] = start, val |
key = key[4:] start, end = self.elements.get(key, (None, None)) | tag = key[4:] start, end = self.elements.get(tag, (None, None)) | def __fixdict(self, dict): for key, val in dict.items(): if key[:6] == 'start_': key = key[6:] start, end = self.elements.get(key, (None, None)) if start is None: self.elements[key] = val, end elif key[:4] == 'end_': key = key[4:] start, end = self.elements.get(key, (None, None)) if end is None: self.elements[key] = start, val |
self.elements[key] = start, val | self.elements[tag] = start, getattr(self, key) | def __fixdict(self, dict): for key, val in dict.items(): if key[:6] == 'start_': key = key[6:] start, end = self.elements.get(key, (None, None)) if start is None: self.elements[key] = val, end elif key[:4] == 'end_': key = key[4:] start, end = self.elements.get(key, (None, None)) if end is None: self.elements[key] = start, val |
i = 0 while i < len(line) and line[i].isspace(): i = i+1 list.append(' %s\n' % line.strip()) if offset is not None: s = ' ' for c in line[i:offset-1]: if c.isspace(): s = s + c else: s = s + ' ' list.append('%s^\n' % s) value = msg | if line is not None: i = 0 while i < len(line) and line[i].isspace(): i = i+1 list.append(' %s\n' % line.strip()) if offset is not None: s = ' ' for c in line[i:offset-1]: if c.isspace(): s = s + c else: s = s + ' ' list.append('%s^\n' % s) value = msg | def format_exception_only(etype, value): """Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is the always last string in the list. """ list = [] if type(etype) == types.ClassType: stype = etype.__name__ else: stype = etype if value is None: list.append(str(stype) + '\n') else: if etype is SyntaxError: try: msg, (filename, lineno, offset, line) = value except: pass else: if not filename: filename = "<string>" list.append(' File "%s", line %d\n' % (filename, lineno)) i = 0 while i < len(line) and line[i].isspace(): i = i+1 list.append(' %s\n' % line.strip()) if offset is not None: s = ' ' for c in line[i:offset-1]: if c.isspace(): s = s + c else: s = s + ' ' list.append('%s^\n' % s) value = msg s = _some_str(value) if s: list.append('%s: %s\n' % (str(stype), s)) else: list.append('%s\n' % str(stype)) return list |
compileargs = r"-Wi [TARGETDIR]Lib\compileall.py -f -x badsyntax [TARGETDIR]Lib" | compileargs = r"-Wi [TARGETDIR]Lib\compileall.py -f -x bad_coding|badsyntax|site-packages [TARGETDIR]Lib" | def add_ui(db): x = y = 50 w = 370 h = 300 title = "[ProductName] Setup" # see "Dialog Style Bits" modal = 3 # visible | modal modeless = 1 # visible track_disk_space = 32 add_data(db, 'ActionText', uisample.ActionText) add_data(db, 'UIText', uisample.UIText) # Bitmaps if not os.path.exists(srcdir+r"\PC\python_icon.exe"): raise "Run icons.mak in PC directory" add_data(db, "Binary", [("PythonWin", msilib.Binary(srcdir+r"\PCbuild\installer.bmp")), # 152x328 pixels ("py.ico",msilib.Binary(srcdir+r"\PC\py.ico")), ]) add_data(db, "Icon", [("python_icon.exe", msilib.Binary(srcdir+r"\PC\python_icon.exe"))]) # Scripts # CheckDir sets TargetExists if TARGETDIR exists. # UpdateEditIDLE sets the REGISTRY.tcl component into # the installed/uninstalled state according to both the # Extensions and TclTk features. if os.system("nmake /nologo /c /f msisupport.mak") != 0: raise "'nmake /f msisupport.mak' failed" add_data(db, "Binary", [("Script", msilib.Binary("msisupport.dll"))]) # See "Custom Action Type 1" if msilib.Win64: CheckDir = "CheckDir" UpdateEditIDLE = "UpdateEditIDLE" else: CheckDir = "_CheckDir@4" UpdateEditIDLE = "_UpdateEditIDLE@4" add_data(db, "CustomAction", [("CheckDir", 1, "Script", CheckDir)]) if have_tcl: add_data(db, "CustomAction", [("UpdateEditIDLE", 1, "Script", UpdateEditIDLE)]) # UI customization properties add_data(db, "Property", # See "DefaultUIFont Property" [("DefaultUIFont", "DlgFont8"), # See "ErrorDialog Style Bit" ("ErrorDialog", "ErrorDlg"), ("Progress1", "Install"), # modified in maintenance type dlg ("Progress2", "installs"), ("MaintenanceForm_Action", "Repair")]) # Fonts, see "TextStyle Table" add_data(db, "TextStyle", [("DlgFont8", "Tahoma", 9, None, 0), ("DlgFontBold8", "Tahoma", 8, None, 1), #bold ("VerdanaBold10", "Verdana", 10, None, 1), ("VerdanaRed9", "Verdana", 9, 255, 0), ]) compileargs = r"-Wi [TARGETDIR]Lib\compileall.py -f -x badsyntax [TARGETDIR]Lib" # See "CustomAction Table" add_data(db, "CustomAction", [ # msidbCustomActionTypeFirstSequence + msidbCustomActionTypeTextData + msidbCustomActionTypeProperty # See "Custom Action Type 51", # "Custom Action Execution Scheduling Options" ("InitialTargetDir", 307, "TARGETDIR", "[WindowsVolume]Python%s%s" % (major, minor)), ("SetDLLDirToTarget", 307, "DLLDIR", "[TARGETDIR]"), ("SetDLLDirToSystem32", 307, "DLLDIR", SystemFolderName), # msidbCustomActionTypeExe + msidbCustomActionTypeSourceFile # See "Custom Action Type 18" ("CompilePyc", 18, "python.exe", compileargs), ("CompilePyo", 18, "python.exe", "-O "+compileargs), ]) # UI Sequences, see "InstallUISequence Table", "Using a Sequence Table" # Numbers indicate sequence; see sequence.py for how these action integrate add_data(db, "InstallUISequence", [("PrepareDlg", "Not Privileged or Windows9x or Installed", 140), ("WhichUsersDlg", "Privileged and not Windows9x and not Installed", 141), ("InitialTargetDir", 'TARGETDIR=""', 750), # In the user interface, assume all-users installation if privileged. ("SetDLLDirToSystem32", 'DLLDIR="" and ' + sys32cond, 751), ("SetDLLDirToTarget", 'DLLDIR="" and not ' + sys32cond, 752), ("SelectDirectoryDlg", "Not Installed", 1230), # XXX no support for resume installations yet #("ResumeDlg", "Installed AND (RESUME OR Preselected)", 1240), ("MaintenanceTypeDlg", "Installed AND NOT RESUME AND NOT Preselected", 1250), ("ProgressDlg", None, 1280)]) add_data(db, "AdminUISequence", [("InitialTargetDir", 'TARGETDIR=""', 750), ("SetDLLDirToTarget", 'DLLDIR=""', 751), ]) # Execute Sequences add_data(db, "InstallExecuteSequence", [("InitialTargetDir", 'TARGETDIR=""', 750), ("SetDLLDirToSystem32", 'DLLDIR="" and ' + sys32cond, 751), ("SetDLLDirToTarget", 'DLLDIR="" and not ' + sys32cond, 752), ("UpdateEditIDLE", None, 1050), ("CompilePyc", "COMPILEALL", 6800), ("CompilePyo", "COMPILEALL", 6801), ]) add_data(db, "AdminExecuteSequence", [("InitialTargetDir", 'TARGETDIR=""', 750), ("SetDLLDirToTarget", 'DLLDIR=""', 751), ("CompilePyc", "COMPILEALL", 6800), ("CompilePyo", "COMPILEALL", 6801), ]) ##################################################################### # Standard dialogs: FatalError, UserExit, ExitDialog fatal=PyDialog(db, "FatalError", x, y, w, h, modal, title, "Finish", "Finish", "Finish") fatal.title("[ProductName] Installer ended prematurely") fatal.back("< Back", "Finish", active = 0) fatal.cancel("Cancel", "Back", active = 0) fatal.text("Description1", 135, 70, 220, 80, 0x30003, "[ProductName] setup ended prematurely because of an error. Your system has not been modified. To install this program at a later time, please run the installation again.") fatal.text("Description2", 135, 155, 220, 20, 0x30003, "Click the Finish button to exit the Installer.") c=fatal.next("Finish", "Cancel", name="Finish") # See "ControlEvent Table". Parameters are the event, the parameter # to the action, and optionally the condition for the event, and the order # of events. c.event("EndDialog", "Exit") user_exit=PyDialog(db, "UserExit", x, y, w, h, modal, title, "Finish", "Finish", "Finish") user_exit.title("[ProductName] Installer was interrupted") user_exit.back("< Back", "Finish", active = 0) user_exit.cancel("Cancel", "Back", active = 0) user_exit.text("Description1", 135, 70, 220, 80, 0x30003, "[ProductName] setup was interrupted. Your system has not been modified. " "To install this program at a later time, please run the installation again.") user_exit.text("Description2", 135, 155, 220, 20, 0x30003, "Click the Finish button to exit the Installer.") c = user_exit.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Exit") exit_dialog = PyDialog(db, "ExitDialog", x, y, w, h, modal, title, "Finish", "Finish", "Finish") exit_dialog.title("Completing the [ProductName] Installer") exit_dialog.back("< Back", "Finish", active = 0) exit_dialog.cancel("Cancel", "Back", active = 0) exit_dialog.text("Acknowledgements", 135, 95, 220, 120, 0x30003, "Special Windows thanks to:\n" " LettError, Erik van Blokland, for the \n" " Python for Windows graphic.\n" " http://www.letterror.com/\n" "\n" " Mark Hammond, without whose years of freely \n" " shared Windows expertise, Python for Windows \n" " would still be Python for DOS.") c = exit_dialog.text("warning", 135, 200, 220, 40, 0x30003, "{\\VerdanaRed9}Warning: Python 2.5.x is the last " "Python release for Windows 9x.") c.condition("Hide", "NOT Version9X") exit_dialog.text("Description", 135, 235, 220, 20, 0x30003, "Click the Finish button to exit the Installer.") c = exit_dialog.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Return") ##################################################################### # Required dialog: FilesInUse, ErrorDlg inuse = PyDialog(db, "FilesInUse", x, y, w, h, 19, # KeepModeless|Modal|Visible title, "Retry", "Retry", "Retry", bitmap=False) inuse.text("Title", 15, 6, 200, 15, 0x30003, r"{\DlgFontBold8}Files in Use") inuse.text("Description", 20, 23, 280, 20, 0x30003, "Some files that need to be updated are currently in use.") inuse.text("Text", 20, 55, 330, 50, 3, "The following applications are using files that need to be updated by this setup. Close these applications and then click Retry to continue the installation or Cancel to exit it.") inuse.control("List", "ListBox", 20, 107, 330, 130, 7, "FileInUseProcess", None, None, None) c=inuse.back("Exit", "Ignore", name="Exit") c.event("EndDialog", "Exit") c=inuse.next("Ignore", "Retry", name="Ignore") c.event("EndDialog", "Ignore") c=inuse.cancel("Retry", "Exit", name="Retry") c.event("EndDialog","Retry") # See "Error Dialog". See "ICE20" for the required names of the controls. error = Dialog(db, "ErrorDlg", 50, 10, 330, 101, 65543, # Error|Minimize|Modal|Visible title, "ErrorText", None, None) error.text("ErrorText", 50,9,280,48,3, "") error.control("ErrorIcon", "Icon", 15, 9, 24, 24, 5242881, None, "py.ico", None, None) error.pushbutton("N",120,72,81,21,3,"No",None).event("EndDialog","ErrorNo") error.pushbutton("Y",240,72,81,21,3,"Yes",None).event("EndDialog","ErrorYes") error.pushbutton("A",0,72,81,21,3,"Abort",None).event("EndDialog","ErrorAbort") error.pushbutton("C",42,72,81,21,3,"Cancel",None).event("EndDialog","ErrorCancel") error.pushbutton("I",81,72,81,21,3,"Ignore",None).event("EndDialog","ErrorIgnore") error.pushbutton("O",159,72,81,21,3,"Ok",None).event("EndDialog","ErrorOk") error.pushbutton("R",198,72,81,21,3,"Retry",None).event("EndDialog","ErrorRetry") ##################################################################### # Global "Query Cancel" dialog cancel = Dialog(db, "CancelDlg", 50, 10, 260, 85, 3, title, "No", "No", "No") cancel.text("Text", 48, 15, 194, 30, 3, "Are you sure you want to cancel [ProductName] installation?") cancel.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None, "py.ico", None, None) c=cancel.pushbutton("Yes", 72, 57, 56, 17, 3, "Yes", "No") c.event("EndDialog", "Exit") c=cancel.pushbutton("No", 132, 57, 56, 17, 3, "No", "Yes") c.event("EndDialog", "Return") ##################################################################### # Global "Wait for costing" dialog costing = Dialog(db, "WaitForCostingDlg", 50, 10, 260, 85, modal, title, "Return", "Return", "Return") costing.text("Text", 48, 15, 194, 30, 3, "Please wait while the installer finishes determining your disk space requirements.") costing.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None, "py.ico", None, None) c = costing.pushbutton("Return", 102, 57, 56, 17, 3, "Return", None) c.event("EndDialog", "Exit") ##################################################################### # Preparation dialog: no user input except cancellation prep = PyDialog(db, "PrepareDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel") prep.text("Description", 135, 70, 220, 40, 0x30003, "Please wait while the Installer prepares to guide you through the installation.") prep.title("Welcome to the [ProductName] Installer") c=prep.text("ActionText", 135, 110, 220, 20, 0x30003, "Pondering...") c.mapping("ActionText", "Text") c=prep.text("ActionData", 135, 135, 220, 30, 0x30003, None) c.mapping("ActionData", "Text") prep.back("Back", None, active=0) prep.next("Next", None, active=0) c=prep.cancel("Cancel", None) c.event("SpawnDialog", "CancelDlg") ##################################################################### # Target directory selection seldlg = PyDialog(db, "SelectDirectoryDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") seldlg.title("Select Destination Directory") c = seldlg.text("Existing", 135, 25, 235, 30, 0x30003, "{\VerdanaRed9}This update will replace your existing [ProductLine] installation.") c.condition("Hide", 'REMOVEOLDVERSION="" and REMOVEOLDSNAPSHOT=""') seldlg.text("Description", 135, 50, 220, 40, 0x30003, "Please select a directory for the [ProductName] files.") seldlg.back("< Back", None, active=0) c = seldlg.next("Next >", "Cancel") c.event("DoAction", "CheckDir", "TargetExistsOk<>1", order=1) # If the target exists, but we found that we are going to remove old versions, don't bother # confirming that the target directory exists. Strictly speaking, we should determine that # the target directory is indeed the target of the product that we are going to remove, but # I don't know how to do that. c.event("SpawnDialog", "ExistingDirectoryDlg", 'TargetExists=1 and REMOVEOLDVERSION="" and REMOVEOLDSNAPSHOT=""', 2) c.event("SetTargetPath", "TARGETDIR", 'TargetExists=0 or REMOVEOLDVERSION<>"" or REMOVEOLDSNAPSHOT<>""', 3) c.event("SpawnWaitDialog", "WaitForCostingDlg", "CostingComplete=1", 4) c.event("NewDialog", "SelectFeaturesDlg", 'TargetExists=0 or REMOVEOLDVERSION<>"" or REMOVEOLDSNAPSHOT<>""', 5) c = seldlg.cancel("Cancel", "DirectoryCombo") c.event("SpawnDialog", "CancelDlg") seldlg.control("DirectoryCombo", "DirectoryCombo", 135, 70, 172, 80, 393219, "TARGETDIR", None, "DirectoryList", None) seldlg.control("DirectoryList", "DirectoryList", 135, 90, 208, 136, 3, "TARGETDIR", None, "PathEdit", None) seldlg.control("PathEdit", "PathEdit", 135, 230, 206, 16, 3, "TARGETDIR", None, "Next", None) c = seldlg.pushbutton("Up", 306, 70, 18, 18, 3, "Up", None) c.event("DirectoryListUp", "0") c = seldlg.pushbutton("NewDir", 324, 70, 30, 18, 3, "New", None) c.event("DirectoryListNew", "0") ##################################################################### # SelectFeaturesDlg features = PyDialog(db, "SelectFeaturesDlg", x, y, w, h, modal|track_disk_space, title, "Tree", "Next", "Cancel") features.title("Customize [ProductName]") features.text("Description", 135, 35, 220, 15, 0x30003, "Select the way you want features to be installed.") features.text("Text", 135,45,220,30, 3, "Click on the icons in the tree below to change the way features will be installed.") c=features.back("< Back", "Next") c.event("NewDialog", "SelectDirectoryDlg") c=features.next("Next >", "Cancel") c.mapping("SelectionNoItems", "Enabled") c.event("SpawnDialog", "DiskCostDlg", "OutOfDiskSpace=1", order=1) c.event("EndDialog", "Return", "OutOfDiskSpace<>1", order=2) c=features.cancel("Cancel", "Tree") c.event("SpawnDialog", "CancelDlg") # The browse property is not used, since we have only a single target path (selected already) features.control("Tree", "SelectionTree", 135, 75, 220, 95, 7, "_BrowseProperty", "Tree of selections", "Back", None) #c=features.pushbutton("Reset", 42, 243, 56, 17, 3, "Reset", "DiskCost") #c.mapping("SelectionNoItems", "Enabled") #c.event("Reset", "0") features.control("Box", "GroupBox", 135, 170, 225, 90, 1, None, None, None, None) c=features.xbutton("DiskCost", "Disk &Usage", None, 0.10) c.mapping("SelectionNoItems","Enabled") c.event("SpawnDialog", "DiskCostDlg") c=features.xbutton("Advanced", "Advanced", None, 0.30) c.event("SpawnDialog", "AdvancedDlg") c=features.text("ItemDescription", 140, 180, 210, 30, 3, "Multiline description of the currently selected item.") c.mapping("SelectionDescription","Text") c=features.text("ItemSize", 140, 210, 210, 45, 3, "The size of the currently selected item.") c.mapping("SelectionSize", "Text") ##################################################################### # Disk cost cost = PyDialog(db, "DiskCostDlg", x, y, w, h, modal, title, "OK", "OK", "OK", bitmap=False) cost.text("Title", 15, 6, 200, 15, 0x30003, "{\DlgFontBold8}Disk Space Requirements") cost.text("Description", 20, 20, 280, 20, 0x30003, "The disk space required for the installation of the selected features.") cost.text("Text", 20, 53, 330, 60, 3, "The highlighted volumes (if any) do not have enough disk space " "available for the currently selected features. You can either " "remove some files from the highlighted volumes, or choose to " "install less features onto local drive(s), or select different " "destination drive(s).") cost.control("VolumeList", "VolumeCostList", 20, 100, 330, 150, 393223, None, "{120}{70}{70}{70}{70}", None, None) cost.xbutton("OK", "Ok", None, 0.5).event("EndDialog", "Return") ##################################################################### # WhichUsers Dialog. Only available on NT, and for privileged users. # This must be run before FindRelatedProducts, because that will # take into account whether the previous installation was per-user # or per-machine. We currently don't support going back to this # dialog after "Next" was selected; to support this, we would need to # find how to reset the ALLUSERS property, and how to re-run # FindRelatedProducts. # On Windows9x, the ALLUSERS property is ignored on the command line # and in the Property table, but installer fails according to the documentation # if a dialog attempts to set ALLUSERS. whichusers = PyDialog(db, "WhichUsersDlg", x, y, w, h, modal, title, "AdminInstall", "Next", "Cancel") whichusers.title("Select whether to install [ProductName] for all users of this computer.") # A radio group with two options: allusers, justme g = whichusers.radiogroup("AdminInstall", 135, 60, 160, 50, 3, "WhichUsers", "", "Next") g.add("ALL", 0, 5, 150, 20, "Install for all users") g.add("JUSTME", 0, 25, 150, 20, "Install just for me") whichusers.back("Back", None, active=0) c = whichusers.next("Next >", "Cancel") c.event("[ALLUSERS]", "1", 'WhichUsers="ALL"', 1) c.event("EndDialog", "Return", order = 2) c = whichusers.cancel("Cancel", "AdminInstall") c.event("SpawnDialog", "CancelDlg") ##################################################################### # Advanced Dialog. advanced = PyDialog(db, "AdvancedDlg", x, y, w, h, modal, title, "CompilePyc", "Next", "Cancel") advanced.title("Advanced Options for [ProductName]") # A radio group with two options: allusers, justme advanced.checkbox("CompilePyc", 135, 60, 230, 50, 3, "COMPILEALL", "Compile .py files to byte code after installation", "Next") c = advanced.next("Finish", "Cancel") c.event("EndDialog", "Return") c = advanced.cancel("Cancel", "CompilePyc") c.event("SpawnDialog", "CancelDlg") ##################################################################### # Existing Directory dialog dlg = Dialog(db, "ExistingDirectoryDlg", 50, 30, 200, 80, modal, title, "No", "No", "No") dlg.text("Title", 10, 20, 180, 40, 3, "[TARGETDIR] exists. Are you sure you want to overwrite existing files?") c=dlg.pushbutton("Yes", 30, 60, 55, 17, 3, "Yes", "No") c.event("[TargetExists]", "0", order=1) c.event("[TargetExistsOk]", "1", order=2) c.event("EndDialog", "Return", order=3) c=dlg.pushbutton("No", 115, 60, 55, 17, 3, "No", "Yes") c.event("EndDialog", "Return") ##################################################################### # Installation Progress dialog (modeless) progress = PyDialog(db, "ProgressDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel", bitmap=False) progress.text("Title", 20, 15, 200, 15, 0x30003, "{\DlgFontBold8}[Progress1] [ProductName]") progress.text("Text", 35, 65, 300, 30, 3, "Please wait while the Installer [Progress2] [ProductName]. " "This may take several minutes.") progress.text("StatusLabel", 35, 100, 35, 20, 3, "Status:") c=progress.text("ActionText", 70, 100, w-70, 20, 3, "Pondering...") c.mapping("ActionText", "Text") #c=progress.text("ActionData", 35, 140, 300, 20, 3, None) #c.mapping("ActionData", "Text") c=progress.control("ProgressBar", "ProgressBar", 35, 120, 300, 10, 65537, None, "Progress done", None, None) c.mapping("SetProgress", "Progress") progress.back("< Back", "Next", active=False) progress.next("Next >", "Cancel", active=False) progress.cancel("Cancel", "Back").event("SpawnDialog", "CancelDlg") # Maintenance type: repair/uninstall maint = PyDialog(db, "MaintenanceTypeDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") maint.title("Welcome to the [ProductName] Setup Wizard") maint.text("BodyText", 135, 63, 230, 42, 3, "Select whether you want to repair or remove [ProductName].") g=maint.radiogroup("RepairRadioGroup", 135, 108, 230, 60, 3, "MaintenanceForm_Action", "", "Next") g.add("Change", 0, 0, 200, 17, "&Change [ProductName]") g.add("Repair", 0, 18, 200, 17, "&Repair [ProductName]") g.add("Remove", 0, 36, 200, 17, "Re&move [ProductName]") maint.back("< Back", None, active=False) c=maint.next("Finish", "Cancel") # Change installation: Change progress dialog to "Change", then ask # for feature selection c.event("[Progress1]", "Change", 'MaintenanceForm_Action="Change"', 1) c.event("[Progress2]", "changes", 'MaintenanceForm_Action="Change"', 2) # Reinstall: Change progress dialog to "Repair", then invoke reinstall # Also set list of reinstalled features to "ALL" c.event("[REINSTALL]", "ALL", 'MaintenanceForm_Action="Repair"', 5) c.event("[Progress1]", "Repairing", 'MaintenanceForm_Action="Repair"', 6) c.event("[Progress2]", "repairs", 'MaintenanceForm_Action="Repair"', 7) c.event("Reinstall", "ALL", 'MaintenanceForm_Action="Repair"', 8) # Uninstall: Change progress to "Remove", then invoke uninstall # Also set list of removed features to "ALL" c.event("[REMOVE]", "ALL", 'MaintenanceForm_Action="Remove"', 11) c.event("[Progress1]", "Removing", 'MaintenanceForm_Action="Remove"', 12) c.event("[Progress2]", "removes", 'MaintenanceForm_Action="Remove"', 13) c.event("Remove", "ALL", 'MaintenanceForm_Action="Remove"', 14) # Close dialog when maintenance action scheduled c.event("EndDialog", "Return", 'MaintenanceForm_Action<>"Change"', 20) c.event("NewDialog", "SelectFeaturesDlg", 'MaintenanceForm_Action="Change"', 21) maint.cancel("Cancel", "RepairRadioGroup").event("SpawnDialog", "CancelDlg") |
except SyntaxWarning, msg: print "got SyntaxWarning as expected" | except SyntaxError, msg: print "got SyntaxError as expected" | def compile_and_catch_warning(text): try: compile(text, "<test code>", "exec") except SyntaxWarning, msg: print "got SyntaxWarning as expected" else: print "expected SyntaxWarning" |
print "expected SyntaxWarning" | print "expected SyntaxError" | def compile_and_catch_warning(text): try: compile(text, "<test code>", "exec") except SyntaxWarning, msg: print "got SyntaxWarning as expected" else: print "expected SyntaxWarning" |
'/usr/lib', | def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') |
|
'/lib', | def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') |
|
), 'incs': ('db.h',)}, | )}, | def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') |
'/usr/lib', '/lib', | def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') |
|
find_lib_file = self.compiler.find_library_file | def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') |
|
for dbinc in dbd['incs']: db_incs = find_file(dbinc, [], dbd['incdirs']) dblib_dir = find_lib_file(dbd['libdirs'], dblib) if db_incs and dblib_dir: dblib_dir = os.path.dirname(dblib_dir) dblibs = [dblib] raise found | db_incs = find_file('db.h', [], dbd['incdirs']) dblib_dir = find_library_file(self.compiler, dblib, lib_dirs, list(dbd['libdirs'])) if (db_incs or dbkey == std_dbinc) and \ dblib_dir is not None: dblibs = [dblib] raise found | def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') |
library_dirs=[dblib_dir], runtime_library_dirs=[dblib_dir], | library_dirs=dblib_dir, runtime_library_dirs=dblib_dir, | def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') |
try: os.rename(self.baseFilename, dfn) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) | os.rename(self.baseFilename, dfn) | def doRollover(self): """ Do a rollover, as described in __init__(). """ |
try: os.rename(self.baseFilename, dfn) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) | os.rename(self.baseFilename, dfn) | def doRollover(self): """ do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a list of matching filenames, sort them and remove the one with the oldest suffix. """ self.stream.close() # get the time that this sequence started at and make it a TimeTuple t = self.rolloverAt - self.interval timeTuple = time.localtime(t) dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple) if os.path.exists(dfn): os.remove(dfn) try: os.rename(self.baseFilename, dfn) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) if self.backupCount > 0: # find the oldest log file and delete it s = glob.glob(self.baseFilename + ".20*") if len(s) > self.backupCount: s.sort() os.remove(s[0]) #print "%s -> %s" % (self.baseFilename, dfn) if self.encoding: self.stream = codecs.open(self.baseFilename, 'w', self.encoding) else: self.stream = open(self.baseFilename, 'w') self.rolloverAt = self.rolloverAt + self.interval |
print f(2)(5) | class TestFuture(unittest.TestCase): def test_floor_div_operator(self): self.assertEqual(7 // 2, 3) def test_true_div_as_default(self): self.assertAlmostEqual(7 / 2, 3.5) def test_nested_scopes(self): self.assertEqual(nester(), 3) def test_main(): test_support.run_unittest(TestFuture) if __name__ == "__main__": test_main() | def g(y): return y // x |
if self.__at_start: | data = rawdata[i:j] if self.__at_start and space.match(data) is None: | def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: if i > 0: self.__at_start = 0 if self.nomoretags: data = rawdata[i:n] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = n break res = interesting.search(rawdata, i) if res: j = res.start(0) else: j = n if i < j: if self.__at_start: self.syntax_error('illegal data at start of file') self.__at_start = 0 data = rawdata[i:j] if not self.stack and space.match(data) is None: self.syntax_error('data not in content') if illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = j if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue k = self.parse_starttag(i) if k < 0: break self.__seen_starttag = 1 self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if endtagopen.match(rawdata, i): k = self.parse_endtag(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if commentopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue k = self.parse_comment(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if cdataopen.match(rawdata, i): k = self.parse_cdata(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:i], '\n') i = k continue res = xmldecl.match(rawdata, i) if res: if not self.__at_start: self.syntax_error("<?xml?> declaration not at start of document") version, encoding, standalone = res.group('version', 'encoding', 'standalone') if version[1:-1] != '1.0': raise RuntimeError, 'only XML version 1.0 supported' if encoding: encoding = encoding[1:-1] if standalone: standalone = standalone[1:-1] self.handle_xml(encoding, standalone) i = res.end(0) continue res = procopen.match(rawdata, i) if res: k = self.parse_proc(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue res = doctype.match(rawdata, i) if res: if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue if self.__seen_doctype: self.syntax_error('multiple DOCTYPE elements') if self.__seen_starttag: self.syntax_error('DOCTYPE not at beginning of document') k = self.parse_doctype(res) if k < 0: break self.__seen_doctype = res.group('name') self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue elif rawdata[i] == '&': if self.literal: data = rawdata[i] self.handle_data(data) i = i+1 continue res = charref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in charref") i = i-1 if not self.stack: self.syntax_error('data not in content') self.handle_charref(res.group('char')[:-1]) self.lineno = self.lineno + string.count(res.group(0), '\n') continue res = entityref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in entityref") i = i-1 name = res.group('name') if self.entitydefs.has_key(name): self.rawdata = rawdata = rawdata[:res.start(0)] + self.entitydefs[name] + rawdata[i:] n = len(rawdata) i = res.start(0) else: self.syntax_error('reference to unknown entity') self.unknown_entityref(name) self.lineno = self.lineno + string.count(res.group(0), '\n') continue elif rawdata[i] == ']': if self.literal: data = rawdata[i] self.handle_data(data) i = i+1 continue if n-i < 3: break if cdataclose.match(rawdata, i): self.syntax_error("bogus `]]>'") self.handle_data(rawdata[i]) i = i+1 continue else: raise RuntimeError, 'neither < nor & ??' # We get here only if incomplete matches but # nothing else break # end while if i > 0: self.__at_start = 0 if end and i < n: data = rawdata[i] self.syntax_error("bogus `%s'" % data) if illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') self.rawdata = rawdata[i+1:] return self.goahead(end) self.rawdata = rawdata[i:] if end: if not self.__seen_starttag: self.syntax_error('no elements in file') if self.stack: self.syntax_error('missing end tags') while self.stack: self.finish_endtag(self.stack[-1][0]) |
data = rawdata[i:j] | def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: if i > 0: self.__at_start = 0 if self.nomoretags: data = rawdata[i:n] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = n break res = interesting.search(rawdata, i) if res: j = res.start(0) else: j = n if i < j: if self.__at_start: self.syntax_error('illegal data at start of file') self.__at_start = 0 data = rawdata[i:j] if not self.stack and space.match(data) is None: self.syntax_error('data not in content') if illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = j if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue k = self.parse_starttag(i) if k < 0: break self.__seen_starttag = 1 self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if endtagopen.match(rawdata, i): k = self.parse_endtag(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if commentopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue k = self.parse_comment(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if cdataopen.match(rawdata, i): k = self.parse_cdata(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:i], '\n') i = k continue res = xmldecl.match(rawdata, i) if res: if not self.__at_start: self.syntax_error("<?xml?> declaration not at start of document") version, encoding, standalone = res.group('version', 'encoding', 'standalone') if version[1:-1] != '1.0': raise RuntimeError, 'only XML version 1.0 supported' if encoding: encoding = encoding[1:-1] if standalone: standalone = standalone[1:-1] self.handle_xml(encoding, standalone) i = res.end(0) continue res = procopen.match(rawdata, i) if res: k = self.parse_proc(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue res = doctype.match(rawdata, i) if res: if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue if self.__seen_doctype: self.syntax_error('multiple DOCTYPE elements') if self.__seen_starttag: self.syntax_error('DOCTYPE not at beginning of document') k = self.parse_doctype(res) if k < 0: break self.__seen_doctype = res.group('name') self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue elif rawdata[i] == '&': if self.literal: data = rawdata[i] self.handle_data(data) i = i+1 continue res = charref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in charref") i = i-1 if not self.stack: self.syntax_error('data not in content') self.handle_charref(res.group('char')[:-1]) self.lineno = self.lineno + string.count(res.group(0), '\n') continue res = entityref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in entityref") i = i-1 name = res.group('name') if self.entitydefs.has_key(name): self.rawdata = rawdata = rawdata[:res.start(0)] + self.entitydefs[name] + rawdata[i:] n = len(rawdata) i = res.start(0) else: self.syntax_error('reference to unknown entity') self.unknown_entityref(name) self.lineno = self.lineno + string.count(res.group(0), '\n') continue elif rawdata[i] == ']': if self.literal: data = rawdata[i] self.handle_data(data) i = i+1 continue if n-i < 3: break if cdataclose.match(rawdata, i): self.syntax_error("bogus `]]>'") self.handle_data(rawdata[i]) i = i+1 continue else: raise RuntimeError, 'neither < nor & ??' # We get here only if incomplete matches but # nothing else break # end while if i > 0: self.__at_start = 0 if end and i < n: data = rawdata[i] self.syntax_error("bogus `%s'" % data) if illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') self.rawdata = rawdata[i+1:] return self.goahead(end) self.rawdata = rawdata[i:] if end: if not self.__seen_starttag: self.syntax_error('no elements in file') if self.stack: self.syntax_error('missing end tags') while self.stack: self.finish_endtag(self.stack[-1][0]) |
|
res = qname.match(tagname) | if self.__use_namespaces: res = qname.match(tagname) else: res = None | def parse_starttag(self, i): rawdata = self.rawdata # i points to start of tag end = endbracketfind.match(rawdata, i+1) if end is None: return -1 tag = starttagmatch.match(rawdata, i) if tag is None or tag.end(0) != end.end(0): self.syntax_error('garbage in starttag') return end.end(0) nstag = tagname = tag.group('tagname') if not self.__seen_starttag and self.__seen_doctype and \ tagname != self.__seen_doctype: self.syntax_error('starttag does not match DOCTYPE') if self.__seen_starttag and not self.stack: self.syntax_error('multiple elements on top level') k, j = tag.span('attrs') attrdict, nsdict, k = self.parse_attributes(tagname, k, j) self.stack.append((tagname, nsdict, nstag)) res = qname.match(tagname) if res is not None: prefix, nstag = res.group('prefix', 'local') if prefix is None: prefix = '' ns = None for t, d, nst in self.stack: if d.has_key(prefix): ns = d[prefix] if ns is None and prefix != '': ns = self.__namespaces.get(prefix) if ns is not None: nstag = ns + ' ' + nstag elif prefix != '': nstag = prefix + ':' + nstag # undo split self.stack[-1] = tagname, nsdict, nstag # translate namespace of attributes nattrdict = {} for key, val in attrdict.items(): res = qname.match(key) if res is not None: aprefix, key = res.group('prefix', 'local') if aprefix is None: aprefix = '' ans = None for t, d, nst in self.stack: if d.has_key(aprefix): ans = d[aprefix] if ans is None and aprefix != '': ans = self.__namespaces.get(aprefix) if ans is not None: key = ans + ' ' + key elif aprefix != '': key = aprefix + ':' + key elif ns is not None: key = ns + ' ' + key nattrdict[key] = val attrdict = nattrdict attributes = self.attributes.get(nstag) if attributes is not None: for key in attrdict.keys(): if not attributes.has_key(key): self.syntax_error("unknown attribute `%s' in tag `%s'" % (key, tagname)) for key, val in attributes.items(): if val is not None and not attrdict.has_key(key): attrdict[key] = val method = self.elements.get(nstag, (None, None))[0] self.finish_starttag(nstag, attrdict, method) if tag.group('slash') == '/': self.finish_endtag(tagname) return tag.end(0) |
nattrdict = {} for key, val in attrdict.items(): res = qname.match(key) if res is not None: aprefix, key = res.group('prefix', 'local') if aprefix is None: aprefix = '' ans = None for t, d, nst in self.stack: if d.has_key(aprefix): ans = d[aprefix] if ans is None and aprefix != '': ans = self.__namespaces.get(aprefix) if ans is not None: key = ans + ' ' + key elif aprefix != '': key = aprefix + ':' + key elif ns is not None: key = ns + ' ' + key nattrdict[key] = val attrdict = nattrdict | if self.__use_namespaces: nattrdict = {} for key, val in attrdict.items(): res = qname.match(key) if res is not None: aprefix, key = res.group('prefix', 'local') if aprefix is None: aprefix = '' ans = None for t, d, nst in self.stack: if d.has_key(aprefix): ans = d[aprefix] if ans is None and aprefix != '': ans = self.__namespaces.get(aprefix) if ans is not None: key = ans + ' ' + key elif aprefix != '': key = aprefix + ':' + key elif ns is not None: key = ns + ' ' + key nattrdict[key] = val attrdict = nattrdict | def parse_starttag(self, i): rawdata = self.rawdata # i points to start of tag end = endbracketfind.match(rawdata, i+1) if end is None: return -1 tag = starttagmatch.match(rawdata, i) if tag is None or tag.end(0) != end.end(0): self.syntax_error('garbage in starttag') return end.end(0) nstag = tagname = tag.group('tagname') if not self.__seen_starttag and self.__seen_doctype and \ tagname != self.__seen_doctype: self.syntax_error('starttag does not match DOCTYPE') if self.__seen_starttag and not self.stack: self.syntax_error('multiple elements on top level') k, j = tag.span('attrs') attrdict, nsdict, k = self.parse_attributes(tagname, k, j) self.stack.append((tagname, nsdict, nstag)) res = qname.match(tagname) if res is not None: prefix, nstag = res.group('prefix', 'local') if prefix is None: prefix = '' ns = None for t, d, nst in self.stack: if d.has_key(prefix): ns = d[prefix] if ns is None and prefix != '': ns = self.__namespaces.get(prefix) if ns is not None: nstag = ns + ' ' + nstag elif prefix != '': nstag = prefix + ':' + nstag # undo split self.stack[-1] = tagname, nsdict, nstag # translate namespace of attributes nattrdict = {} for key, val in attrdict.items(): res = qname.match(key) if res is not None: aprefix, key = res.group('prefix', 'local') if aprefix is None: aprefix = '' ans = None for t, d, nst in self.stack: if d.has_key(aprefix): ans = d[aprefix] if ans is None and aprefix != '': ans = self.__namespaces.get(aprefix) if ans is not None: key = ans + ' ' + key elif aprefix != '': key = aprefix + ':' + key elif ns is not None: key = ns + ' ' + key nattrdict[key] = val attrdict = nattrdict attributes = self.attributes.get(nstag) if attributes is not None: for key in attrdict.keys(): if not attributes.has_key(key): self.syntax_error("unknown attribute `%s' in tag `%s'" % (key, tagname)) for key, val in attributes.items(): if val is not None and not attrdict.has_key(key): attrdict[key] = val method = self.elements.get(nstag, (None, None))[0] self.finish_starttag(nstag, attrdict, method) if tag.group('slash') == '/': self.finish_endtag(tagname) return tag.end(0) |
self.assertRaises(ValueError, lambda: bytes([C(-1)])) self.assertRaises(ValueError, lambda: bytes([C(256)])) | self.assertRaises(ValueError, bytes, [C(-1)]) self.assertRaises(ValueError, bytes, [C(256)]) | def __index__(self): return self.i |
self.assertRaises(TypeError, lambda: bytes(["0"])) self.assertRaises(TypeError, lambda: bytes([0.0])) self.assertRaises(TypeError, lambda: bytes([None])) self.assertRaises(TypeError, lambda: bytes([C()])) | self.assertRaises(TypeError, bytes, ["0"]) self.assertRaises(TypeError, bytes, [0.0]) self.assertRaises(TypeError, bytes, [None]) self.assertRaises(TypeError, bytes, [C()]) | def test_constructor_type_errors(self): class C: pass self.assertRaises(TypeError, lambda: bytes(["0"])) self.assertRaises(TypeError, lambda: bytes([0.0])) self.assertRaises(TypeError, lambda: bytes([None])) self.assertRaises(TypeError, lambda: bytes([C()])) |
self.assertRaises(ValueError, lambda: bytes([-1])) self.assertRaises(ValueError, lambda: bytes([-sys.maxint])) self.assertRaises(ValueError, lambda: bytes([-sys.maxint-1])) self.assertRaises(ValueError, lambda: bytes([-sys.maxint-2])) self.assertRaises(ValueError, lambda: bytes([-10**100])) self.assertRaises(ValueError, lambda: bytes([256])) self.assertRaises(ValueError, lambda: bytes([257])) self.assertRaises(ValueError, lambda: bytes([sys.maxint])) self.assertRaises(ValueError, lambda: bytes([sys.maxint+1])) self.assertRaises(ValueError, lambda: bytes([10**100])) | self.assertRaises(ValueError, bytes, [-1]) self.assertRaises(ValueError, bytes, [-sys.maxint]) self.assertRaises(ValueError, bytes, [-sys.maxint-1]) self.assertRaises(ValueError, bytes, [-sys.maxint-2]) self.assertRaises(ValueError, bytes, [-10**100]) self.assertRaises(ValueError, bytes, [256]) self.assertRaises(ValueError, bytes, [257]) self.assertRaises(ValueError, bytes, [sys.maxint]) self.assertRaises(ValueError, bytes, [sys.maxint+1]) self.assertRaises(ValueError, bytes, [10**100]) | def test_constructor_value_errors(self): self.assertRaises(ValueError, lambda: bytes([-1])) self.assertRaises(ValueError, lambda: bytes([-sys.maxint])) self.assertRaises(ValueError, lambda: bytes([-sys.maxint-1])) self.assertRaises(ValueError, lambda: bytes([-sys.maxint-2])) self.assertRaises(ValueError, lambda: bytes([-10**100])) self.assertRaises(ValueError, lambda: bytes([256])) self.assertRaises(ValueError, lambda: bytes([257])) self.assertRaises(ValueError, lambda: bytes([sys.maxint])) self.assertRaises(ValueError, lambda: bytes([sys.maxint+1])) self.assertRaises(ValueError, lambda: bytes([10**100])) |
def __init__(self, widget): self.widget = widget self.tipwindow = None self.id = None self.x = self.y = 0 | keydefs = { '<<paren-open>>': ['<Key-parenleft>'], '<<paren-close>>': ['<Key-parenright>'], '<<check-calltip-cancel>>': ['<KeyRelease>', '<ButtonRelease>'] } windows_keydefs = { } | def __init__(self, widget): self.widget = widget self.tipwindow = None self.id = None self.x = self.y = 0 |
def showtip(self, text): self.text = text if self.tipwindow or not self.text: return self.widget.see("insert") x, y, cx, cy = self.widget.bbox("insert") x = x + self.widget.winfo_rootx() + 2 y = y + cy + self.widget.winfo_rooty() self.tipwindow = tw = Toplevel(self.widget) tw.wm_overrideredirect(1) tw.wm_geometry("+%d+%d" % (x, y)) label = Label(tw, text=self.text, justify=LEFT, background=" label.pack() def hidetip(self): tw = self.tipwindow self.tipwindow = None if tw: tw.destroy() | unix_keydefs = { } def __init__(self, editwin): self.editwin = editwin self.text = editwin.text self.calltip = None if hasattr(self.text, "make_calltip_window"): self._make_calltip_window = self.text.make_calltip_window else: self._make_calltip_window = self._make_tk_calltip_window def _make_tk_calltip_window(self): import CallTipWindow return CallTipWindow.CallTip(self.text) def _remove_calltip_window(self): if self.calltip: self.calltip.hidetip() self.calltip = None def paren_open_event(self, event): self._remove_calltip_window() arg_text = get_arg_text(self.get_object_at_cursor()) if arg_text: self.calltip_start = self.text.index("insert") self.calltip = self._make_calltip_window() self.calltip.showtip(arg_text) def paren_close_event(self, event): self._remove_calltip_window() def check_calltip_cancel_event(self, event): if self.calltip: if self.text.compare("insert", "<=", self.calltip_start) or \ self.text.compare("insert", ">", self.calltip_start + " lineend"): self._remove_calltip_window() def get_object_at_cursor(self, wordchars="._" + string.uppercase + string.lowercase + string.digits): text = self.text index = 0 while 1: index = index + 1 indexspec = "insert-%dc" % index ch = text.get(indexspec) if ch not in wordchars: break if text.compare(indexspec, "<=", "1.0"): break word = text.get("insert-%dc" % (index-1,), "insert") if word: import sys, __main__ namespace = sys.modules.copy() namespace.update(__main__.__dict__) try: return eval(word, namespace) except: pass return None def get_arg_text(ob): argText = "" if ob is not None: argOffset = 0 if type(ob)==types.MethodType: ob = ob.im_func argOffset = 1 if type(ob) in [types.FunctionType, types.LambdaType]: try: realArgs = ob.func_code.co_varnames[argOffset:ob.func_code.co_argcount] defaults = ob.func_defaults or [] defaults = list(map(lambda name: "=%s" % name, defaults)) defaults = [""] * (len(realArgs)-len(defaults)) + defaults argText = string.join( map(lambda arg, dflt: arg+dflt, realArgs, defaults), ", ") if len(realArgs)+argOffset < (len(ob.func_code.co_varnames) - len(ob.func_code.co_names) ): if argText: argText = argText + ", " argText = argText + "..." argText = "(%s)" % argText except: pass if not argText and hasattr(ob, "__doc__") and ob.__doc__: pos = string.find(ob.__doc__, "\n") if pos<0 or pos>70: pos=70 argText = ob.__doc__[:pos] return argText if __name__=='__main__': def t1(): "()" def t2(a, b=None): "(a, b=None)" def t3(a, *args): "(a, ...)" def t4(*args): "(...)" def t5(a, *args): "(a, ...)" def t6(a, b=None, *args, **kw): "(a, b=None, ...)" class TC: def t1(self): "()" def t2(self, a, b=None): "(a, b=None)" def t3(self, a, *args): "(a, ...)" def t4(self, *args): "(...)" def t5(self, a, *args): "(a, ...)" def t6(self, a, b=None, *args, **kw): "(a, b=None, ...)" | def showtip(self, text): self.text = text if self.tipwindow or not self.text: return self.widget.see("insert") x, y, cx, cy = self.widget.bbox("insert") x = x + self.widget.winfo_rootx() + 2 y = y + cy + self.widget.winfo_rooty() self.tipwindow = tw = Toplevel(self.widget) tw.wm_overrideredirect(1) tw.wm_geometry("+%d+%d" % (x, y)) label = Label(tw, text=self.text, justify=LEFT, background="#ffffe0", relief=SOLID, borderwidth=1) label.pack() |
class container: def __init__(self): root = Tk() text = self.text = Text(root) text.pack(side=LEFT, fill=BOTH, expand=1) text.insert("insert", "string.split") root.update() self.calltip = CallTip(text) | def test( tests ): failed=[] for t in tests: if get_arg_text(t) != t.__doc__: failed.append(t) print "%s - expected %s, but got %s" % (t, `t.__doc__`, `get_arg_text(t)`) print "%d of %d tests failed" % (len(failed), len(tests)) | def hidetip(self): tw = self.tipwindow self.tipwindow = None if tw: tw.destroy() |
text.event_add("<<calltip-show>>", "(") text.event_add("<<calltip-hide>>", ")") text.bind("<<calltip-show>>", self.calltip_show) text.bind("<<calltip-hide>>", self.calltip_hide) text.focus_set() | tc = TC() tests = t1, t2, t3, t4, t5, t6, \ tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6 | def __init__(self): root = Tk() text = self.text = Text(root) text.pack(side=LEFT, fill=BOTH, expand=1) text.insert("insert", "string.split") root.update() self.calltip = CallTip(text) |
def calltip_show(self, event): self.calltip.showtip("Hello world") def calltip_hide(self, event): self.calltip.hidetip() def main(): c=container() if __name__=='__main__': main() | test(tests) | def calltip_show(self, event): self.calltip.showtip("Hello world") |
print "open", askopenfilename(filetypes=[("all files", "*")]).encode(enc) print "saveas", asksaveasfilename().encode(enc) | def askdirectory (**options): "Ask for a directory, and return the file name" return Directory(**options).show() |
|
extern int _QdRGB_Convert(PyObject *, RGBColorPtr *); | extern int _QdRGB_Convert(PyObject *, RGBColorPtr); | #ifdef USE_TOOLBOX_OBJECT_GLUE |
PyMac_INIT_TOOLBOX_OBJECT_CONVERT(RGBColorPtr, QdRGB_Convert); | PyMac_INIT_TOOLBOX_OBJECT_CONVERT(RGBColor, QdRGB_Convert); | #ifdef USE_TOOLBOX_OBJECT_GLUE |
if hex(-16) != '0xfffffff0': raise TestFailed, 'hex(-16)' | if len(hex(-1)) != len(hex(sys.maxint)): raise TestFailed, 'len(hex(-1))' if hex(-16) not in ('0xfffffff0', '0xfffffffffffffff0'): raise TestFailed, 'hex(-16)' | def f(): pass |
longopts.sort() | def getopt(args, shortopts, longopts = []): """getopt(args, options[, long_options]) -> opts, args Parses command line options and parameter list. args is the argument list to be parsed, without the leading reference to the running program. Typically, this means "sys.argv[1:]". shortopts is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (i.e., the same format that Unix getopt() uses). If specified, longopts is a list of strings with the names of the long options which should be supported. The leading '--' characters should not be included in the option name. Options which require an argument should be followed by an equal sign ('='). The return value consists of two elements: the first is a list of (option, value) pairs; the second is the list of program arguments left after the option list was stripped (this is a trailing slice of the first argument). Each option-and-value pair returned has the option as its first element, prefixed with a hyphen (e.g., '-x'), and the option argument as its second element, or an empty string if the option has no argument. The options occur in the list in the same order in which they were found, thus allowing multiple occurrences. Long and short options may be mixed. """ opts = [] if type(longopts) == type(""): longopts = [longopts] else: longopts = list(longopts) longopts.sort() while args and args[0].startswith('-') and args[0] != '-': if args[0] == '--': args = args[1:] break if args[0][:2] == '--': opts, args = do_longs(opts, args[0][2:], longopts, args[1:]) else: opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:]) return opts, args |
|
for i in range(len(longopts)): if longopts[i].startswith(opt): break else: | possibilities = [o for o in longopts if o.startswith(opt)] if not possibilities: | def long_has_args(opt, longopts): for i in range(len(longopts)): if longopts[i].startswith(opt): break else: raise GetoptError('option --%s not recognized' % opt, opt) # opt is a prefix of longopts[i]; find j s.t. opt is a prefix of # each possibility in longopts[i:j] j = i+1 while j < len(longopts) and longopts[j].startswith(opt): j += 1 possibilities = longopts[i:j] # Is there an exact match? if opt in possibilities: return 0, opt elif opt + '=' in possibilities: return 1, opt # No exact match, so better be unique. if len(possibilities) > 1: # XXX since possibilities contains all valid continuations, might be # nice to work them into the error msg raise GetoptError('option --%s not a unique prefix' % opt, opt) assert len(possibilities) == 1 unique_match = possibilities[0] has_arg = unique_match.endswith('=') if has_arg: unique_match = unique_match[:-1] return has_arg, unique_match |
j = i+1 while j < len(longopts) and longopts[j].startswith(opt): j += 1 possibilities = longopts[i:j] | def long_has_args(opt, longopts): for i in range(len(longopts)): if longopts[i].startswith(opt): break else: raise GetoptError('option --%s not recognized' % opt, opt) # opt is a prefix of longopts[i]; find j s.t. opt is a prefix of # each possibility in longopts[i:j] j = i+1 while j < len(longopts) and longopts[j].startswith(opt): j += 1 possibilities = longopts[i:j] # Is there an exact match? if opt in possibilities: return 0, opt elif opt + '=' in possibilities: return 1, opt # No exact match, so better be unique. if len(possibilities) > 1: # XXX since possibilities contains all valid continuations, might be # nice to work them into the error msg raise GetoptError('option --%s not a unique prefix' % opt, opt) assert len(possibilities) == 1 unique_match = possibilities[0] has_arg = unique_match.endswith('=') if has_arg: unique_match = unique_match[:-1] return has_arg, unique_match |
|
exceptions, this sets `sender' to the string that the SMTP refused | exceptions, this sets `sender' to the string that the SMTP refused. | def __init__(self, code, msg): self.smtp_code = code self.smtp_error = msg self.args = (code, msg) |
Double leading '.', and change Unix newline '\n', or Mac '\r' into | Double leading '.', and change Unix newline '\\n', or Mac '\\r' into | def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\n', or Mac '\r' into Internet CRLF end-of-line. """ return re.sub(r'(?m)^\.', '..', re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data)) |
This is the message given by the server in responce to the | This is the message given by the server in response to the | def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\n', or Mac '\r' into Internet CRLF end-of-line. """ return re.sub(r'(?m)^\.', '..', re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data)) |
will _after you do an EHLO command_, contain the names of the SMTP service extentions this server supports, and their | will _after you do an EHLO command_, contain the names of the SMTP service extensions this server supports, and their | def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\n', or Mac '\r' into Internet CRLF end-of-line. """ return re.sub(r'(?m)^\.', '..', re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data)) |
Note, all extention names are mapped to lower case in the | Note, all extension names are mapped to lower case in the | def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\n', or Mac '\r' into Internet CRLF end-of-line. """ return re.sub(r'(?m)^\.', '..', re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.