rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
return
return True
def scriptswalk(self, top, menu, done=None): if done is None: done = {} if done.has_key(top): return done[top] = 1 import os, string try: names = os.listdir(top) except os.error: FrameWork.MenuItem(menu, '(Scripts Folder not found)', None, None) return savedir = os.getcwd() os.chdir(top) for name in names: if name == "CVS": continue try: fsr, isdir, isalias = File.FSResolveAliasFile(name, 1) except: # maybe a broken alias continue path = fsr.as_pathname() if done.has_key(path): continue name = string.strip(name) if os.name == "posix": name = unicode(name, "utf-8") if name[-3:] == '---': menu.addseparator() elif isdir: submenu = FrameWork.SubMenu(menu, name) self.scriptswalk(path, submenu, done) else: creator, type = MacOS.GetCreatorAndType(path) if type == 'TEXT': if name[-3:] == '.py': name = name[:-3] item = FrameWork.MenuItem(menu, name, None, self.domenu_script) self._scripts[(menu.id, item.item)] = path done[path] = 1 os.chdir(savedir)
self.scriptswalk(path, submenu, done)
if not self.scriptswalk(path, submenu, done): return False
def scriptswalk(self, top, menu, done=None): if done is None: done = {} if done.has_key(top): return done[top] = 1 import os, string try: names = os.listdir(top) except os.error: FrameWork.MenuItem(menu, '(Scripts Folder not found)', None, None) return savedir = os.getcwd() os.chdir(top) for name in names: if name == "CVS": continue try: fsr, isdir, isalias = File.FSResolveAliasFile(name, 1) except: # maybe a broken alias continue path = fsr.as_pathname() if done.has_key(path): continue name = string.strip(name) if os.name == "posix": name = unicode(name, "utf-8") if name[-3:] == '---': menu.addseparator() elif isdir: submenu = FrameWork.SubMenu(menu, name) self.scriptswalk(path, submenu, done) else: creator, type = MacOS.GetCreatorAndType(path) if type == 'TEXT': if name[-3:] == '.py': name = name[:-3] item = FrameWork.MenuItem(menu, name, None, self.domenu_script) self._scripts[(menu.id, item.item)] = path done[path] = 1 os.chdir(savedir)
return if address.lower().startswith('stimpy'): self.push('503 You suck %s' % address)
def smtp_RCPT(self, arg): print >> DEBUGSTREAM, '===> RCPT', arg if not self.__mailfrom: self.push('503 Error: need MAIL command') return address = self.__getaddr('TO:', arg) if not address: self.push('501 Syntax: RCPT TO: <address>') return if address.lower().startswith('stimpy'): self.push('503 You suck %s' % address) return self.__rcpttos.append(address) print >> DEBUGSTREAM, 'recips:', self.__rcpttos self.push('250 Ok')
return getattr(self, self.err)
return getattr(self.err, attr)
def __getattr__(self, attr): return getattr(self, self.err)
'UNICODE': ('ref/strings', 'encodings unicode TYPES STRING'),
'UNICODE': ('ref/strings', 'encodings unicode SEQUENCES STRINGMETHODS FORMATTING TYPES'),
def writedocs(dir, pkgpath='', done=None): """Write out HTML documentation for all modules in a directory tree.""" if done is None: done = {} for file in os.listdir(dir): path = os.path.join(dir, file) if ispackage(path): writedocs(path, pkgpath + file + '.', done) elif os.path.isfile(path): modname = inspect.getmodulename(path) if modname: if modname == '__init__': modname = pkgpath[:-1] # remove trailing period else: modname = pkgpath + modname if modname not in done: done[modname] = 1 writedoc(modname)
'EXECUTION': ('ref/naming', ''), 'NAMESPACES': ('ref/naming', 'global ASSIGNMENT DELETION'),
'EXECUTION': ('ref/execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'), 'NAMESPACES': ('ref/naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'), 'DYNAMICFEATURES': ('ref/dynamic-features', ''),
'METHODS': ('lib/typesmethods', 'class def CLASSES TYPES'),
'COERCIONS': 'CONVERSIONS', 'CONVERSIONS': ('ref/conversions', ''),
'COERCIONS': ('ref/coercion-rules','CONVERSIONS'), 'CONVERSIONS': ('ref/conversions', 'COERCIONS'),
'METHODS': ('lib/typesmethods', 'class def CLASSES TYPES'),
print "Can't copy %s to %s: %s" % (`srcname`, `dstname`, str(why))
errors.append((srcname, dstname, why)) if errors: raise Error, errors
def copytree(src, dst, symlinks=0): """Recursively copy a directory tree using copy2(). The destination directory must not already exist. Error are reported to standard output. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. XXX Consider this example code rather than the ultimate tool. """ names = os.listdir(src) os.mkdir(dst) for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): copytree(srcname, dstname, symlinks) else: copy2(srcname, dstname) # XXX What about devices, sockets etc.? except (IOError, os.error), why: print "Can't copy %s to %s: %s" % (`srcname`, `dstname`, str(why))
macros=macros,
def build_extensions (self):
opts, args = getopt.getopt(sys.argv[1:], 'm:qv')
opts, args = getopt.getopt(sys.argv[1:], 't:m:qva')
def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'm:qv') except getopt.error, msg: sys.stdout = sys.stderr print msg print __doc__%vars(webchecker) sys.exit(2) for o, a in opts: if o == '-m': webchecker.maxpage = string.atoi(a) if o == '-q': webchecker.verbose = 0 if o == '-v': webchecker.verbose = webchecker.verbose + 1 root = Tk(className='Webchecker') root.protocol("WM_DELETE_WINDOW", root.quit) c = CheckerWindow(root) if args: for arg in args[:-1]: c.addroot(arg) c.suggestroot(args[-1]) root.mainloop()
self.__todo = ListPanel(mp, "To check", self.showinfo) self.__done = ListPanel(mp, "Checked", self.showinfo) self.__bad = ListPanel(mp, "Bad links", self.showinfo) self.__errors = ListPanel(mp, "Pages w/ bad links", self.showinfo)
self.__todo = ListPanel(mp, "To check", self, self.showinfo) self.__done = ListPanel(mp, "Checked", self, self.showinfo) self.__bad = ListPanel(mp, "Bad links", self, self.showinfo) self.__errors = ListPanel(mp, "Pages w/ bad links", self, self.showinfo)
def __init__(self, parent, root=webchecker.DEFROOT): self.__parent = parent
self.__checking.config(text="Checking "+url)
self.__checking.config(text="Checking "+self.format_url(url))
def dosomething(self): if self.__busy: return self.__busy = 1 if self.todo: l = self.__todo.selectedindices() if l: i = l[0] else: i = 0 self.__todo.list.select_set(i) self.__todo.list.yview(i) url = self.__todo.items[i] self.__checking.config(text="Checking "+url) self.__parent.update() self.dopage(url) else: self.stop() self.__busy = 0 self.go()
d.put("URL: %s\n" % url)
d.put("URL: %s\n" % self.format_url(url))
def showinfo(self, url): d = self.__details d.clear() d.put("URL: %s\n" % url) if self.bad.has_key(url): d.put("Error: %s\n" % str(self.bad[url])) if url in self.roots: d.put("Note: This is a root URL\n") if self.done.has_key(url): d.put("Status: checked\n") o = self.done[url] elif self.todo.has_key(url): d.put("Status: to check\n") o = self.todo[url] else: d.put("Status: unknown (!)\n") o = [] if self.errors.has_key(url): d.put("Bad links from this page:\n") for triple in self.errors[url]: link, rawlink, msg = triple d.put(" HREF %s" % link) if link != rawlink: d.put(" (%s)" %rawlink) d.put("\n") d.put(" error %s\n" % str(msg)) self.__mp.showpanel("Details") for source, rawlink in o: d.put("Origin: %s" % source) if rawlink != url: d.put(" (%s)" % rawlink) d.put("\n") d.text.yview("1.0")
if self.errors.has_key(url):
if (not url[1]) and self.errors.has_key(url[0]):
def showinfo(self, url): d = self.__details d.clear() d.put("URL: %s\n" % url) if self.bad.has_key(url): d.put("Error: %s\n" % str(self.bad[url])) if url in self.roots: d.put("Note: This is a root URL\n") if self.done.has_key(url): d.put("Status: checked\n") o = self.done[url] elif self.todo.has_key(url): d.put("Status: to check\n") o = self.todo[url] else: d.put("Status: unknown (!)\n") o = [] if self.errors.has_key(url): d.put("Bad links from this page:\n") for triple in self.errors[url]: link, rawlink, msg = triple d.put(" HREF %s" % link) if link != rawlink: d.put(" (%s)" %rawlink) d.put("\n") d.put(" error %s\n" % str(msg)) self.__mp.showpanel("Details") for source, rawlink in o: d.put("Origin: %s" % source) if rawlink != url: d.put(" (%s)" % rawlink) d.put("\n") d.text.yview("1.0")
for triple in self.errors[url]:
for triple in self.errors[url[0]]:
def showinfo(self, url): d = self.__details d.clear() d.put("URL: %s\n" % url) if self.bad.has_key(url): d.put("Error: %s\n" % str(self.bad[url])) if url in self.roots: d.put("Note: This is a root URL\n") if self.done.has_key(url): d.put("Status: checked\n") o = self.done[url] elif self.todo.has_key(url): d.put("Status: to check\n") o = self.todo[url] else: d.put("Status: unknown (!)\n") o = [] if self.errors.has_key(url): d.put("Bad links from this page:\n") for triple in self.errors[url]: link, rawlink, msg = triple d.put(" HREF %s" % link) if link != rawlink: d.put(" (%s)" %rawlink) d.put("\n") d.put(" error %s\n" % str(msg)) self.__mp.showpanel("Details") for source, rawlink in o: d.put("Origin: %s" % source) if rawlink != url: d.put(" (%s)" % rawlink) d.put("\n") d.text.yview("1.0")
d.put(" HREF %s" % link) if link != rawlink: d.put(" (%s)" %rawlink)
d.put(" HREF %s" % self.format_url(link)) if self.format_url(link) != rawlink: d.put(" (%s)" %rawlink)
def showinfo(self, url): d = self.__details d.clear() d.put("URL: %s\n" % url) if self.bad.has_key(url): d.put("Error: %s\n" % str(self.bad[url])) if url in self.roots: d.put("Note: This is a root URL\n") if self.done.has_key(url): d.put("Status: checked\n") o = self.done[url] elif self.todo.has_key(url): d.put("Status: to check\n") o = self.todo[url] else: d.put("Status: unknown (!)\n") o = [] if self.errors.has_key(url): d.put("Bad links from this page:\n") for triple in self.errors[url]: link, rawlink, msg = triple d.put(" HREF %s" % link) if link != rawlink: d.put(" (%s)" %rawlink) d.put("\n") d.put(" error %s\n" % str(msg)) self.__mp.showpanel("Details") for source, rawlink in o: d.put("Origin: %s" % source) if rawlink != url: d.put(" (%s)" % rawlink) d.put("\n") d.text.yview("1.0")
if rawlink != url:
if rawlink != self.format_url(url):
def showinfo(self, url): d = self.__details d.clear() d.put("URL: %s\n" % url) if self.bad.has_key(url): d.put("Error: %s\n" % str(self.bad[url])) if url in self.roots: d.put("Note: This is a root URL\n") if self.done.has_key(url): d.put("Status: checked\n") o = self.done[url] elif self.todo.has_key(url): d.put("Status: to check\n") o = self.todo[url] else: d.put("Status: unknown (!)\n") o = [] if self.errors.has_key(url): d.put("Bad links from this page:\n") for triple in self.errors[url]: link, rawlink, msg = triple d.put(" HREF %s" % link) if link != rawlink: d.put(" (%s)" %rawlink) d.put("\n") d.put(" error %s\n" % str(msg)) self.__mp.showpanel("Details") for source, rawlink in o: d.put("Origin: %s" % source) if rawlink != url: d.put(" (%s)" % rawlink) d.put("\n") d.text.yview("1.0")
self.__errors.insert(url)
self.__errors.insert((url, ''))
def seterror(self, url, triple): webchecker.Checker.seterror(self, url, triple) self.__errors.insert(url) self.newstatus()
def __init__(self, mp, name, showinfo=None):
def __init__(self, mp, name, checker, showinfo=None):
def __init__(self, mp, name, showinfo=None): self.mp = mp self.name = name self.showinfo = showinfo self.panel = mp.addpanel(name) self.list, self.frame = tktools.make_list_box( self.panel, width=60, height=5) self.list.config(exportselection=0) if showinfo: self.list.bind('<Double-Button-1>', self.doubleclick) self.items = []
self.showinfo(self.list.get(l[0]))
self.showinfo(self.items[l[0]])
def doubleclick(self, event): l = self.selectedindices() if l: self.showinfo(self.list.get(l[0]))
self.list.insert(i, url)
self.list.insert(i, self.checker.format_url(url))
def insert(self, url): if url not in self.items: if not self.items: self.mp.showpanel(self.name) # (I tried sorting alphabetically, but the display is too jumpy) i = len(self.items) self.list.insert(i, url) self.list.yview(i) self.items.insert(i, url)
Checks wether this line is typed in the normal prompt or in a breakpoint command list definition
Checks whether this line is typed at the normal prompt or in a breakpoint command list definition.
def onecmd(self, line): """Interpret the argument as though it had been typed in response to the prompt.
if platform == 'cygwin': lib_prefix = 'cyg' else: lib_prefix = ''
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module.
tklib = self.compiler.find_library_file(lib_dirs, lib_prefix + 'tk' + version) tcllib = self.compiler.find_library_file(lib_dirs, lib_prefix + 'tcl' + version)
tklib = self.compiler.find_library_file(lib_dirs, 'tk' + version) tcllib = self.compiler.find_library_file(lib_dirs, 'tcl' + version)
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module.
libs.append(lib_prefix + 'tk'+ version) libs.append(lib_prefix + 'tcl'+ version)
libs.append('tk'+ version) libs.append('tcl'+ version)
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module.
if os.environ.has_key("MSSdk") and self.find_exe("cl.exe"):
if os.environ.has_key("DISTUTILS_USE_SDK") and os.environ.has_key("MSSdk") and self.find_exe("cl.exe"):
def initialize(self): self.__paths = [] if os.environ.has_key("MSSdk") and self.find_exe("cl.exe"): # Assume that the SDK set up everything alright; don't try to be # smarter self.cc = "cl.exe" self.linker = "link.exe" self.lib = "lib.exe" self.rc = "rc.exe" self.mc = "mc.exe" else: self.__paths = self.get_msvc_paths("path")
library_dirs=None):
library_dirs=None, build_info=None):
def link_shared_lib (self, objects, output_libname, libraries=None, library_dirs=None): # XXX should we sanity check the library name? (eg. no # slashes) self.link_shared_object (objects, "lib%s%s" % (output_libname, SO))
self.link_shared_object (objects, "lib%s%s" % (output_libname, SO))
self.link_shared_object (objects, "lib%s%s" % \ (output_libname, self._shared_lib_ext), build_info=build_info)
def link_shared_lib (self, objects, output_libname, libraries=None, library_dirs=None): # XXX should we sanity check the library name? (eg. no # slashes) self.link_shared_object (objects, "lib%s%s" % (output_libname, SO))
library_dirs=None):
library_dirs=None, build_info=None):
def link_shared_object (self, objects, output_filename, libraries=None, library_dirs=None):
if build_info is None: build_info = {}
def link_shared_object (self, objects, output_filename, libraries=None, library_dirs=None):
outnames.append (re.sub (r'\.(c|C|cc|cxx)$', '.o', inname))
outnames.append ( re.sub (r'\.(c|C|cc|cxx|cpp)$', self._obj_ext, inname))
def object_filenames (self, source_filenames): outnames = [] for inname in source_filenames: outnames.append (re.sub (r'\.(c|C|cc|cxx)$', '.o', inname)) return outnames
return re.sub (r'\.(c|C|cc|cxx)$', SO)
return re.sub (r'\.(c|C|cc|cxx|cpp)$', self._shared_lib_ext)
def shared_object_filename (self, source_filename): return re.sub (r'\.(c|C|cc|cxx)$', SO)
return "lib%s.a" % libname
return "lib%s%s" % (libname, self._static_lib_ext )
def library_filename (self, libname): return "lib%s.a" % libname
return "lib%s.so" % libname
return "lib%s%s" % (libname, self._shared_lib_ext )
def shared_library_filename (self, libname): return "lib%s.so" % libname
self._tofill = []
def reset(self): """ Clear the screen, re-center the pen, and set variables to the default values.
if self._tofill: for item in self._tofill: self._canvas.itemconfigure(item, fill=self._color) self._items.append(item)
def fill(self, flag): """ Call fill(1) before drawing the shape you want to fill, and fill(0) when done.
self._tofill = []
def fill(self, flag): """ Call fill(1) before drawing the shape you want to fill, and fill(0) when done.
self.forward(0)
def fill(self, flag): """ Call fill(1) before drawing the shape you want to fill, and fill(0) when done.
self.fill(1)
self._path = [self._position] self._filling = 1
def begin_fill(self): """ Called just before drawing a shape to be filled.
color("green") left(130)
left(120)
def demo2(): # exercises some new and improved features speed('fast') width(3) # draw a segmented half-circle setheading(towards(0,0)) x,y = position() r = (x**2+y**2)**.5/2.0 right(90) pendown = True for i in range(18): if pendown: up() pendown = False else: down() pendown = True circle(r,10) sleep(2) reset() left(90) # draw a series of triangles l = 10 color("green") width(3) left(180) sp = 5 for i in range(-2,16): if i > 0: color(1.0-0.05*i,0,0.05*i) fill(1) color("green") for j in range(3): forward(l) left(120) l += 10 left(15) if sp > 0: sp = sp-1 speed(speeds[sp]) color(0.25,0,0.75) fill(0) color("green") left(130) up() forward(90) color("red") speed('fastest') down(); # create a second turtle and make the original pursue and catch it turtle=Turtle() turtle.reset() turtle.left(90) turtle.speed('normal') turtle.up() turtle.goto(280,40) turtle.left(24) turtle.down() turtle.speed('fast') turtle.color("blue") turtle.width(2) speed('fastest') # turn default turtle towards new turtle object setheading(towards(turtle)) while ( abs(position()[0]-turtle.position()[0])>4 or abs(position()[1]-turtle.position()[1])>4): turtle.forward(3.5) turtle.left(0.6) # turn default turtle towards new turtle object setheading(towards(turtle)) forward(4) write("CAUGHT! ", move=True)
forward(90)
forward(70) right(30) down()
def demo2(): # exercises some new and improved features speed('fast') width(3) # draw a segmented half-circle setheading(towards(0,0)) x,y = position() r = (x**2+y**2)**.5/2.0 right(90) pendown = True for i in range(18): if pendown: up() pendown = False else: down() pendown = True circle(r,10) sleep(2) reset() left(90) # draw a series of triangles l = 10 color("green") width(3) left(180) sp = 5 for i in range(-2,16): if i > 0: color(1.0-0.05*i,0,0.05*i) fill(1) color("green") for j in range(3): forward(l) left(120) l += 10 left(15) if sp > 0: sp = sp-1 speed(speeds[sp]) color(0.25,0,0.75) fill(0) color("green") left(130) up() forward(90) color("red") speed('fastest') down(); # create a second turtle and make the original pursue and catch it turtle=Turtle() turtle.reset() turtle.left(90) turtle.speed('normal') turtle.up() turtle.goto(280,40) turtle.left(24) turtle.down() turtle.speed('fast') turtle.color("blue") turtle.width(2) speed('fastest') # turn default turtle towards new turtle object setheading(towards(turtle)) while ( abs(position()[0]-turtle.position()[0])>4 or abs(position()[1]-turtle.position()[1])>4): turtle.forward(3.5) turtle.left(0.6) # turn default turtle towards new turtle object setheading(towards(turtle)) forward(4) write("CAUGHT! ", move=True)
speed('fastest')
speed("fastest") fill(1) for i in range(4): circle(50,90) right(90) forward(30) right(90) color("yellow") fill(0) left(90) up() forward(30)
def demo2(): # exercises some new and improved features speed('fast') width(3) # draw a segmented half-circle setheading(towards(0,0)) x,y = position() r = (x**2+y**2)**.5/2.0 right(90) pendown = True for i in range(18): if pendown: up() pendown = False else: down() pendown = True circle(r,10) sleep(2) reset() left(90) # draw a series of triangles l = 10 color("green") width(3) left(180) sp = 5 for i in range(-2,16): if i > 0: color(1.0-0.05*i,0,0.05*i) fill(1) color("green") for j in range(3): forward(l) left(120) l += 10 left(15) if sp > 0: sp = sp-1 speed(speeds[sp]) color(0.25,0,0.75) fill(0) color("green") left(130) up() forward(90) color("red") speed('fastest') down(); # create a second turtle and make the original pursue and catch it turtle=Turtle() turtle.reset() turtle.left(90) turtle.speed('normal') turtle.up() turtle.goto(280,40) turtle.left(24) turtle.down() turtle.speed('fast') turtle.color("blue") turtle.width(2) speed('fastest') # turn default turtle towards new turtle object setheading(towards(turtle)) while ( abs(position()[0]-turtle.position()[0])>4 or abs(position()[1]-turtle.position()[1])>4): turtle.forward(3.5) turtle.left(0.6) # turn default turtle towards new turtle object setheading(towards(turtle)) forward(4) write("CAUGHT! ", move=True)
import traceback
def formatException(self, ei): """ Format and return the specified exception information as a string.
import traceback
def handleError(self, record): """ Handle errors which occur during an emit() call.
def __init__(self, filename, mode="a"):
def __init__(self, filename, mode='a', encoding=None):
def __init__(self, filename, mode="a"): """ Open the specified file and use it as the stream for logging. """ StreamHandler.__init__(self, open(filename, mode)) #keep the absolute path, otherwise derived classes which use this #may come a cropper when the current directory changes self.baseFilename = os.path.abspath(filename) self.mode = mode
StreamHandler.__init__(self, open(filename, mode))
if codecs is None: encoding = None if encoding is None: stream = open(filename, mode) else: stream = codecs.open(filename, mode, encoding) StreamHandler.__init__(self, stream)
def __init__(self, filename, mode="a"): """ Open the specified file and use it as the stream for logging. """ StreamHandler.__init__(self, open(filename, mode)) #keep the absolute path, otherwise derived classes which use this #may come a cropper when the current directory changes self.baseFilename = os.path.abspath(filename) self.mode = mode
(if filemode is unspecified, it defaults to "a").
(if filemode is unspecified, it defaults to 'a').
def basicConfig(**kwargs): """ Do basic configuration for the logging system. This function does nothing if the root logger already has handlers configured. It is a convenience method intended for use by simple scripts to do one-shot configuration of the logging package. The default behaviour is to create a StreamHandler which writes to sys.stderr, set a formatter using the BASIC_FORMAT format string, and add the handler to the root logger. A number of optional keyword arguments may be specified, which can alter the default behaviour. filename Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler. filemode Specifies the mode to open the file, if filename is specified (if filemode is unspecified, it defaults to "a"). format Use the specified format string for the handler. datefmt Use the specified date/time format. level Set the root logger level to the specified level. stream Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with 'filename' - if both are present, 'stream' is ignored. Note that you could specify a stream created using open(filename, mode) rather than passing the filename and mode in. However, it should be remembered that StreamHandler does not close its stream (since it may be using sys.stdout or sys.stderr), whereas FileHandler closes its stream when the handler is closed. """ if len(root.handlers) == 0: filename = kwargs.get("filename") if filename: mode = kwargs.get("filemode", "a") hdlr = FileHandler(filename, mode) else: stream = kwargs.get("stream") hdlr = StreamHandler(stream) fs = kwargs.get("format", BASIC_FORMAT) dfs = kwargs.get("datefmt", None) fmt = Formatter(fs, dfs) hdlr.setFormatter(fmt) root.addHandler(hdlr) level = kwargs.get("level") if level: root.setLevel(level)
mode = kwargs.get("filemode", "a")
mode = kwargs.get("filemode", 'a')
def basicConfig(**kwargs): """ Do basic configuration for the logging system. This function does nothing if the root logger already has handlers configured. It is a convenience method intended for use by simple scripts to do one-shot configuration of the logging package. The default behaviour is to create a StreamHandler which writes to sys.stderr, set a formatter using the BASIC_FORMAT format string, and add the handler to the root logger. A number of optional keyword arguments may be specified, which can alter the default behaviour. filename Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler. filemode Specifies the mode to open the file, if filename is specified (if filemode is unspecified, it defaults to "a"). format Use the specified format string for the handler. datefmt Use the specified date/time format. level Set the root logger level to the specified level. stream Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with 'filename' - if both are present, 'stream' is ignored. Note that you could specify a stream created using open(filename, mode) rather than passing the filename and mode in. However, it should be remembered that StreamHandler does not close its stream (since it may be using sys.stdout or sys.stderr), whereas FileHandler closes its stream when the handler is closed. """ if len(root.handlers) == 0: filename = kwargs.get("filename") if filename: mode = kwargs.get("filemode", "a") hdlr = FileHandler(filename, mode) else: stream = kwargs.get("stream") hdlr = StreamHandler(stream) fs = kwargs.get("format", BASIC_FORMAT) dfs = kwargs.get("datefmt", None) fmt = Formatter(fs, dfs) hdlr.setFormatter(fmt) root.addHandler(hdlr) level = kwargs.get("level") if level: root.setLevel(level)
outputs.extend(cmd.get_outputs())
for filename in cmd.get_outputs(): if filename not in outputs: outputs.append(filename)
def get_outputs (self): # This command doesn't have any outputs of its own, so just # get the outputs of all its sub-commands. outputs = [] for cmd_name in self.get_sub_commands(): cmd = self.get_finalized_command(cmd_name) outputs.extend(cmd.get_outputs())
def __init__(self, filenames=()):
def __init__(self, filenames=(), strict=True):
def __init__(self, filenames=()): if not inited: init() self.encodings_map = encodings_map.copy() self.suffix_map = suffix_map.copy() self.types_map = types_map.copy() self.common_types = common_types.copy() for name in filenames: self.read(name)
self.types_map = types_map.copy() self.common_types = common_types.copy()
self.types_map = ({}, {}) self.types_map_inv = ({}, {}) for (ext, type) in types_map.items(): self.add_type(type, ext, True) for (ext, type) in common_types.items(): self.add_type(type, ext, False)
def __init__(self, filenames=()): if not inited: init() self.encodings_map = encodings_map.copy() self.suffix_map = suffix_map.copy() self.types_map = types_map.copy() self.common_types = common_types.copy() for name in filenames: self.read(name)
self.read(name) def guess_type(self, url, strict=1):
self.read(name, strict) def add_type(self, type, ext, strict=True): """Add a mapping between a type and and extension. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ self.types_map[strict][ext] = type exts = self.types_map_inv[strict].setdefault(type, []) if ext not in exts: exts.append(ext) def guess_type(self, url, strict=True):
def __init__(self, filenames=()): if not inited: init() self.encodings_map = encodings_map.copy() self.suffix_map = suffix_map.copy() self.types_map = types_map.copy() self.common_types = common_types.copy() for name in filenames: self.read(name)
Optional `strict' argument when false adds a bunch of commonly found,
Optional `strict' argument when False adds a bunch of commonly found,
def guess_type(self, url, strict=1): """Guess the type of a file based on its URL.
types_map = self.types_map common_types = self.common_types
types_map = self.types_map[True]
def guess_type(self, url, strict=1): """Guess the type of a file based on its URL.
elif ext in common_types: return common_types[ext], encoding elif ext.lower() in common_types: return common_types[ext.lower()], encoding
types_map = self.types_map[False] if ext in types_map: return types_map[ext], encoding elif ext.lower() in types_map: return types_map[ext.lower()], encoding
def guess_type(self, url, strict=1): """Guess the type of a file based on its URL.
def guess_extension(self, type, strict=1):
def guess_all_extensions(self, type, strict=True): """Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ type = type.lower() extensions = self.types_map_inv[True].get(type, []) if not strict: for ext in self.types_map_inv[False].get(type, []): if ext not in extensions: extensions.append(ext) if len(extensions): return extensions def guess_extension(self, type, strict=True):
def guess_extension(self, type, strict=1): """Guess the extension for a file based on its MIME type.
type = type.lower() for ext, stype in self.types_map.items(): if type == stype: return ext if not strict: for ext, stype in common_types.items(): if type == stype: return ext return None def read(self, filename): """Read a single mime.types-format file, specified by pathname."""
extensions = self.guess_all_extensions(type, strict) if extensions is not None: extensions = extensions[0] return extensions def read(self, filename, strict=True): """ Read a single mime.types-format file, specified by pathname. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """
def guess_extension(self, type, strict=1): """Guess the extension for a file based on its MIME type.
def readfp(self, fp): """Read a single mime.types-format file.""" map = self.types_map
def readfp(self, fp, strict=True): """ Read a single mime.types-format file. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """
def readfp(self, fp): """Read a single mime.types-format file.""" map = self.types_map while 1: line = fp.readline() if not line: break words = line.split() for i in range(len(words)): if words[i][0] == '#': del words[i:] break if not words: continue type, suffixes = words[0], words[1:] for suff in suffixes: map['.' + suff] = type
map['.' + suff] = type def guess_type(url, strict=1):
self.add_type(type, suff, strict) def guess_type(url, strict=True):
def readfp(self, fp): """Read a single mime.types-format file.""" map = self.types_map while 1: line = fp.readline() if not line: break words = line.split() for i in range(len(words)): if words[i][0] == '#': del words[i:] break if not words: continue type, suffixes = words[0], words[1:] for suff in suffixes: map['.' + suff] = type
def guess_extension(type, strict=1):
def guess_all_extensions(type, strict=True): """Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ init() return guess_all_extensions(type, strict) def guess_extension(type, strict=True):
def guess_extension(type, strict=1): """Guess the extension for a file based on its MIME type. Return value is a string giving a filename extension, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ init() return guess_extension(type, strict)
global guess_extension, guess_type
global guess_all_extensions, guess_extension, guess_type
def init(files=None): global guess_extension, guess_type global suffix_map, types_map, encodings_map, common_types global inited inited = 1 db = MimeTypes() if files is None: files = knownfiles for file in files: if os.path.isfile(file): db.readfp(open(file)) encodings_map = db.encodings_map suffix_map = db.suffix_map types_map = db.types_map guess_extension = db.guess_extension guess_type = db.guess_type common_types = db.common_types
global inited inited = 1
global add_type, inited inited = True
def init(files=None): global guess_extension, guess_type global suffix_map, types_map, encodings_map, common_types global inited inited = 1 db = MimeTypes() if files is None: files = knownfiles for file in files: if os.path.isfile(file): db.readfp(open(file)) encodings_map = db.encodings_map suffix_map = db.suffix_map types_map = db.types_map guess_extension = db.guess_extension guess_type = db.guess_type common_types = db.common_types
types_map = db.types_map
types_map = db.types_map[True] guess_all_extensions = db.guess_all_extensions
def init(files=None): global guess_extension, guess_type global suffix_map, types_map, encodings_map, common_types global inited inited = 1 db = MimeTypes() if files is None: files = knownfiles for file in files: if os.path.isfile(file): db.readfp(open(file)) encodings_map = db.encodings_map suffix_map = db.suffix_map types_map = db.types_map guess_extension = db.guess_extension guess_type = db.guess_type common_types = db.common_types
common_types = db.common_types
add_type = db.add_type common_types = db.types_map[False]
def init(files=None): global guess_extension, guess_type global suffix_map, types_map, encodings_map, common_types global inited inited = 1 db = MimeTypes() if files is None: files = knownfiles for file in files: if os.path.isfile(file): db.readfp(open(file)) encodings_map = db.encodings_map suffix_map = db.suffix_map types_map = db.types_map guess_extension = db.guess_extension guess_type = db.guess_type common_types = db.common_types
doc = getattr(value, "__doc__", None)
if callable(value): doc = getattr(value, "__doc__", None) else: doc = None
def spilldata(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: base = self.docother(getattr(object, name), name, mod) doc = getattr(value, "__doc__", None) if doc is None: push('<dl><dt>%s</dl>\n' % base) else: doc = self.markup(getdoc(value), self.preformat, funcs, classes, mdict) doc = '<dd><tt>%s</tt>' % doc push('<dl><dt>%s%s</dl>\n' % (base, doc)) push('\n') return attrs
doc = getattr(value, "__doc__", None)
if callable(value): doc = getattr(value, "__doc__", None) else: doc = None
def spilldata(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: doc = getattr(value, "__doc__", None) push(self.docother(getattr(object, name), name, mod, 70, doc) + '\n') return attrs
(0, 50001), RuntimeError)
(0, 50001))
def bump_num(matchobj): int_value = int(matchobj.group(0)) return str(int_value + 1)
class Boolean: """Boolean-value wrapper. Use True or False to generate a "boolean" XML-RPC value. """ def __init__(self, value = 0): self.value = operator.truth(value) def encode(self, out): out.write("<value><boolean>%d</boolean></value>\n" % self.value) def __cmp__(self, other): if isinstance(other, Boolean): other = other.value return cmp(self.value, other) def __repr__(self): if self.value: return "<Boolean True at %x>" % id(self) else: return "<Boolean False at %x>" % id(self) def __int__(self): return self.value def __nonzero__(self): return self.value True, False = Boolean(1), Boolean(0) def boolean(value, _truefalse=(False, True)): """Convert any Python value to XML-RPC 'boolean'.""" return _truefalse[operator.truth(value)]
if _bool_is_builtin: boolean = Boolean = bool True, False = True, False else: class Boolean: """Boolean-value wrapper. Use True or False to generate a "boolean" XML-RPC value. """ def __init__(self, value = 0): self.value = operator.truth(value) def encode(self, out): out.write("<value><boolean>%d</boolean></value>\n" % self.value) def __cmp__(self, other): if isinstance(other, Boolean): other = other.value return cmp(self.value, other) def __repr__(self): if self.value: return "<Boolean True at %x>" % id(self) else: return "<Boolean False at %x>" % id(self) def __int__(self): return self.value def __nonzero__(self): return self.value True, False = Boolean(1), Boolean(0) def boolean(value, _truefalse=(False, True)): """Convert any Python value to XML-RPC 'boolean'.""" return _truefalse[operator.truth(value)]
def __repr__(self): return ( "<Fault %s: %s>" % (self.faultCode, repr(self.faultString)) )
WRAPPERS = DateTime, Binary, Boolean
WRAPPERS = (DateTime, Binary) if not _bool_is_builtin: WRAPPERS = WRAPPERS + (Boolean,)
def _binary(data): # decode xml element contents into a Binary structure value = Binary() value.decode(data) return value
if not self.distribution.has_ext_modules(): spec_file.append('BuildArchitectures: noarch')
if not self.force_arch: if not self.distribution.has_ext_modules(): spec_file.append('BuildArch: noarch') else: spec_file.append( 'BuildArch: %s' % self.force_arch )
def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version().replace('-','_'), '%define release ' + self.release.replace('-','_'), '', 'Summary: ' + self.distribution.get_description(), ]
for stack in self.rows + self.suits:
for stack in self.openstacks:
def closeststack(self, card):
for stack in [self.opendeck] + self.suits + self.rows:
for stack in self.openstacks:
def reset(self):
import __main__ class_ = getattr(__main__, options.classname)
classname = options.classname if "." in classname: lastdot = classname.rfind(".") mod = __import__(classname[:lastdot], globals(), locals(), [""]) classname = classname[lastdot+1:] else: import __main__ as mod print mod.__name__, dir(mod) class_ = getattr(mod, classname)
def parseargs(): global DEBUGSTREAM try: opts, args = getopt.getopt( sys.argv[1:], 'nVhc:d', ['class=', 'nosetuid', 'version', 'help', 'debug']) except getopt.error, e: usage(1, e) options = Options() for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-V', '--version'): print >> sys.stderr, __version__ sys.exit(0) elif opt in ('-n', '--nosetuid'): options.setuid = 0 elif opt in ('-c', '--class'): options.classname = arg elif opt in ('-d', '--debug'): DEBUGSTREAM = sys.stderr # parse the rest of the arguments if len(args) < 1: localspec = 'localhost:8025' remotespec = 'localhost:25' elif len(args) < 2: localspec = args[0] remotespec = 'localhost:25' elif len(args) < 3: localspec = args[0] remotespec = args[1] else: usage(1, 'Invalid arguments: %s' % COMMASPACE.join(args)) # split into host/port pairs i = localspec.find(':') if i < 0: usage(1, 'Bad local spec: %s' % localspec) options.localhost = localspec[:i] try: options.localport = int(localspec[i+1:]) except ValueError: usage(1, 'Bad local port: %s' % localspec) i = remotespec.find(':') if i < 0: usage(1, 'Bad remote spec: %s' % remotespec) options.remotehost = remotespec[:i] try: options.remoteport = int(remotespec[i+1:]) except ValueError: usage(1, 'Bad remote port: %s' % remotespec) return options
if w[0] != '-' and w[-2:] in ('.o', '.a'):
if w[0] not in ('-', '$') and w[-2:] in ('.o', '.a'):
def select(e, mods, vars, mod, skipofiles): files = [] for w in mods[mod]: w = treatword(w) if not w: continue w = expandvars(w, vars) for w in string.split(w): if skipofiles and w[-2:] == '.o': continue if w[0] != '-' and w[-2:] in ('.o', '.a'): w = os.path.join(e, w) if w[:2] in ('-L', '-R'): w = w[:2] + os.path.join(e, w[2:]) files.append(w) return files
if w[:2] in ('-L', '-R'):
if w[:2] in ('-L', '-R') and w[2:3] != '$':
def select(e, mods, vars, mod, skipofiles): files = [] for w in mods[mod]: w = treatword(w) if not w: continue w = expandvars(w, vars) for w in string.split(w): if skipofiles and w[-2:] == '.o': continue if w[0] != '-' and w[-2:] in ('.o', '.a'): w = os.path.join(e, w) if w[:2] in ('-L', '-R'): w = w[:2] + os.path.join(e, w[2:]) files.append(w) return files
del self._data[element]
self.remove(element)
def discard(self, element): """Remove an element from a set if it is a member.
vr = 0, 0, r[2]-r[0]-15, r[3]-r[1]-15 dr = (0, 0, vr[2], 0)
x0, y0, x1, y1 = self.wid.GetWindowPort().portRect x0 = x0 + 4 y0 = y0 + 4 x1 = x1 - 20 y1 = y1 - 20 vr = dr = x0, y0, x1, y1
def open(self, path, name, data): self.path = path self.name = name r = windowbounds(400, 400) w = Win.NewWindow(r, name, 1, 0, -1, 1, 0x55555555) self.wid = w vr = 0, 0, r[2]-r[0]-15, r[3]-r[1]-15 dr = (0, 0, vr[2], 0) Qd.SetPort(w) Qd.TextFont(4) Qd.TextSize(9) self.ted = TE.TENew(dr, vr) self.ted.TEAutoView(1) self.ted.TESetText(data) w.DrawGrowIcon() self.scrollbars() self.changed = 0 self.do_postopen() self.do_activate(1, None)
match = mime_head.group(0, 1) newline = newline + line[:i] + mime_decode(match[1]) line = line[i + len(match[0]):]
match0, match1 = mime_head.group(0, 1) match1 = string.join(string.split(match1, '_'), ' ') newline = newline + line[:i] + mime_decode(match1) line = line[i + len(match0):]
def mime_decode_header(line): '''Decode a header line to 8bit.''' newline = '' while 1: i = mime_head.search(line) if i < 0: break match = mime_head.group(0, 1) newline = newline + line[:i] + mime_decode(match[1]) line = line[i + len(match[0]):] return newline + line
id = 257
def AskString(prompt, default = "", id=257, ok=None, cancel=None): """Display a PROMPT string and a text entry field with a DEFAULT string. 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. """ id = 257 d = GetNewDialog(id, -1) if not d: print "Can't get DLOG resource with id =", id return tp, h, rect = d.GetDialogItem(3) SetDialogItemText(h, lf2cr(prompt)) tp, h, rect = d.GetDialogItem(4) SetDialogItemText(h, lf2cr(default)) d.SelectDialogItemText(4, 0, 999)
return strftime(self.format, (item,)*9).capitalize()
return strftime(self.format, (item,)*8+(0,)).capitalize()
def __getitem__(self, item): if isinstance(item, int): if item < 0: item += self.len if not 0 <= item < self.len: raise IndexError, "out of range" return strftime(self.format, (item,)*9).capitalize() elif isinstance(item, type(slice(0))): return [self[e] for e in range(self.len)].__getslice__(item.start, item.stop)
framework = sysconfig.get_config_var('PYTHONFRAMEWORK') if framework: exts.append( Extension('gestalt', ['gestaltmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('MacOS', ['macosmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('icglue', ['icgluemodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('macfs', ['macfsmodule.c', '../Python/getapplbycreator.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Res', ['res/_Resmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Snd', ['snd/_Sndmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('Nav', ['Nav.c'],
exts.append( Extension('gestalt', ['gestaltmodule.c'],
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')
exts.append( Extension('_AE', ['ae/_AEmodule.c'],
exts.append( Extension('MacOS', ['macosmodule.c'],
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')
exts.append( Extension('_AH', ['ah/_AHmodule.c'],
exts.append( Extension('icglue', ['icgluemodule.c'],
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')
exts.append( Extension('_Alias', ['alias/_Aliasmodule.c'],
exts.append( Extension('macfs', ['macfsmodule.c', '../Python/getapplbycreator.c'],
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')
exts.append( Extension('_App', ['app/_Appmodule.c'],
exts.append( Extension('_Res', ['res/_Resmodule.c'],
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')
exts.append( Extension('_CarbonEvt', ['carbonevt/_CarbonEvtmodule.c'],
exts.append( Extension('_Snd', ['snd/_Sndmodule.c'],
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')
exts.append( Extension('_CG', ['cg/_CGmodule.c'], extra_link_args=['-framework', 'ApplicationServices', '-framework', 'Carbon']) ) exts.append( Extension('_Cm', ['cm/_Cmmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Ctl', ['ctl/_Ctlmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Dlg', ['dlg/_Dlgmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Drag', ['drag/_Dragmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Evt', ['evt/_Evtmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_File', ['file/_Filemodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Folder', ['folder/_Foldermodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Fm', ['fm/_Fmmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Help', ['help/_Helpmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Icn', ['icn/_Icnmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_IBCarbon', ['ibcarbon/_IBCarbon.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_List', ['list/_Listmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Menu', ['menu/_Menumodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Mlte', ['mlte/_Mltemodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Qd', ['qd/_Qdmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Qdoffs', ['qdoffs/_Qdoffsmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Qt', ['qt/_Qtmodule.c'], extra_link_args=['-framework', 'QuickTime', '-framework', 'Carbon']) ) exts.append( Extension('_Scrap', ['scrap/_Scrapmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_TE', ['te/_TEmodule.c'], extra_link_args=['-framework', 'Carbon']) ) waste_incs = find_file("WASTE.h", [], ['../'*n + 'waste/C_C++ Headers' for n in (0,1,2,3,4)]) waste_libs = find_library_file(self.compiler, "WASTE", [], [ "../"*n + "waste/Static Libraries" for n in (0,1,2,3,4)]) if waste_incs != None and waste_libs != None: (srcdir,) = sysconfig.get_config_vars('srcdir') exts.append( Extension('waste', ['waste/wastemodule.c'] + [ os.path.join(srcdir, d) for d in 'Mac/Wastemods/WEObjectHandlers.c', 'Mac/Wastemods/WETabHooks.c', 'Mac/Wastemods/WETabs.c' ], include_dirs = waste_incs + [os.path.join(srcdir, 'Mac/Wastemods')], library_dirs = waste_libs, libraries = ['WASTE'], extra_link_args = ['-framework', 'Carbon'], ) ) exts.append( Extension('_Win', ['win/_Winmodule.c'], extra_link_args=['-framework', 'Carbon']) )
exts.append( Extension('Nav', ['Nav.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_AE', ['ae/_AEmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_AH', ['ah/_AHmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Alias', ['alias/_Aliasmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_App', ['app/_Appmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_CarbonEvt', ['carbonevt/_CarbonEvtmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_CG', ['cg/_CGmodule.c'], extra_link_args=['-framework', 'ApplicationServices', '-framework', 'Carbon']) ) exts.append( Extension('_Cm', ['cm/_Cmmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Ctl', ['ctl/_Ctlmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Dlg', ['dlg/_Dlgmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Drag', ['drag/_Dragmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Evt', ['evt/_Evtmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_File', ['file/_Filemodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Folder', ['folder/_Foldermodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Fm', ['fm/_Fmmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Help', ['help/_Helpmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Icn', ['icn/_Icnmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_IBCarbon', ['ibcarbon/_IBCarbon.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_List', ['list/_Listmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Menu', ['menu/_Menumodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Mlte', ['mlte/_Mltemodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Qd', ['qd/_Qdmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Qdoffs', ['qdoffs/_Qdoffsmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Qt', ['qt/_Qtmodule.c'], extra_link_args=['-framework', 'QuickTime', '-framework', 'Carbon']) ) exts.append( Extension('_Scrap', ['scrap/_Scrapmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_TE', ['te/_TEmodule.c'], extra_link_args=['-framework', 'Carbon']) ) waste_incs = find_file("WASTE.h", [], ['../'*n + 'waste/C_C++ Headers' for n in (0,1,2,3,4)]) waste_libs = find_library_file(self.compiler, "WASTE", [], ["../"*n + "waste/Static Libraries" for n in (0,1,2,3,4)]) if waste_incs != None and waste_libs != None: (srcdir,) = sysconfig.get_config_vars('srcdir') exts.append( Extension('waste', ['waste/wastemodule.c'] + [ os.path.join(srcdir, d) for d in 'Mac/Wastemods/WEObjectHandlers.c', 'Mac/Wastemods/WETabHooks.c', 'Mac/Wastemods/WETabs.c' ], include_dirs = waste_incs + [os.path.join(srcdir, 'Mac/Wastemods')], library_dirs = waste_libs, libraries = ['WASTE'], extra_link_args = ['-framework', 'Carbon'], ) ) exts.append( Extension('_Win', ['win/_Winmodule.c'], extra_link_args=['-framework', 'Carbon']) )
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')
def __init__(self, format):
def __init__(self, format, len):
def __init__(self, format): self.format = format
day_name = _localized_name('%A') day_abbr = _localized_name('%a')
day_name = _localized_name('%A', 7) day_abbr = _localized_name('%a', 7)
def __getitem__(self, item): return strftime(self.format, (item,)*9).capitalize()
month_name = _localized_name('%B') month_abbr = _localized_name('%b')
month_name = _localized_name('%B', 12) month_abbr = _localized_name('%b', 12)
def __getitem__(self, item): return strftime(self.format, (item,)*9).capitalize()
list.append('%s: %s\n' % (str(stype), _some_str(value)))
s = _some_str(value) if s: list.append('%s: %s\n' % (str(stype), s)) else: list.append('%s\n' % str(stype))
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] in string.whitespace: i = i+1 list.append(' %s\n' % string.strip(line)) s = ' ' for c in line[i:offset-1]: if c in string.whitespace: s = s + c else: s = s + ' ' list.append('%s^\n' % s) value = msg list.append('%s: %s\n' % (str(stype), _some_str(value))) return list
_write_data(writer, "<![CDATA[%s]]>" % self.data)
writer.write("<![CDATA[%s]]>" % self.data)
def writexml(self, writer, indent="", addindent="", newl=""): _write_data(writer, "<![CDATA[%s]]>" % self.data)
res = platform.libc_ver()
from sys import executable import os if os.path.isdir(executable) and os.path.exists(executable+'.exe'): executable = executable + '.exe' res = platform.libc_ver(executable)
def test_libc_ver(self): res = platform.libc_ver()
print e.__dict__
def update(self): self.prepare() for file in self.rcsfiles: e = self.preparedetails(file) if e.lsum == e.sum == e.rsum: print '=', file continue if e.sum == e.rsum: if e.rev != e.rrev: print '%s: %s -> %s w/o change' % \ (file, e.rev, e.rrev) e.rev = e.rrev if e.lsum != e.sum: if e.lsum is None: print '%s: file was lost' % \ (file,) self.get(e) elif e.new: print 'A', file else: print 'M', file continue if e.lsum == e.sum: if e.rev == e.rrev: print '%s: no new revision' % file print 'U', file, sys.stdout.flush() self.get(e) print continue if e.lsum == e.rsum: print 'c', file print e.__dict__ e.rev = e.rrev e.sum = e.rsum e.new = e.sum is None and e.lsum is not None if e.sum: e.mtime, e.ctime = os.stat(e.file)[-2:] print e.__dict__ self.entries[file] = e continue print 'C', file, '(not resolved)' self.writeentries() self.writesums()
end = self.newBlock() self.set_lineno(node) self.emit('LOAD_GLOBAL', '__debug__') self.emit('JUMP_IF_FALSE', end) self.nextBlock() self.emit('POP_TOP') self.visit(node.test) self.emit('JUMP_IF_TRUE', end) self.nextBlock() self.emit('POP_TOP') self.emit('LOAD_GLOBAL', 'AssertionError') if node.fail: self.visit(node.fail) self.emit('RAISE_VARARGS', 2) else: self.emit('RAISE_VARARGS', 1) self.nextBlock(end) self.emit('POP_TOP')
if __debug__: end = self.newBlock() self.set_lineno(node) self.nextBlock() self.visit(node.test) self.emit('JUMP_IF_TRUE', end) self.nextBlock() self.emit('POP_TOP') self.emit('LOAD_GLOBAL', 'AssertionError') if node.fail: self.visit(node.fail) self.emit('RAISE_VARARGS', 2) else: self.emit('RAISE_VARARGS', 1) self.nextBlock(end) self.emit('POP_TOP')
def visitAssert(self, node): # XXX would be interesting to implement this via a # transformation of the AST before this stage end = self.newBlock() self.set_lineno(node) # XXX __debug__ and AssertionError appear to be special cases # -- they are always loaded as globals even if there are local # names. I guess this is a sort of renaming op. self.emit('LOAD_GLOBAL', '__debug__') self.emit('JUMP_IF_FALSE', end) self.nextBlock() self.emit('POP_TOP') self.visit(node.test) self.emit('JUMP_IF_TRUE', end) self.nextBlock() self.emit('POP_TOP') self.emit('LOAD_GLOBAL', 'AssertionError') if node.fail: self.visit(node.fail) self.emit('RAISE_VARARGS', 2) else: self.emit('RAISE_VARARGS', 1) self.nextBlock(end) self.emit('POP_TOP')
try: if os.isatty(sys.stdin.fileno()): NO_ARG_FUNCTIONS.append("getlogin") except: pass
def testNoArgFunctions(self): # test posix functions which take no arguments and have # no side-effects which we need to cleanup (e.g., fork, wait, abort) NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdu", "uname", "times", "getloadavg", "tmpnam", "getegid", "geteuid", "getgid", "getgroups", "getpid", "getpgrp", "getppid", "getuid", ] # getlogin() only works when run from a tty (terminal) try: if os.isatty(sys.stdin.fileno()): NO_ARG_FUNCTIONS.append("getlogin") except: pass
if (arg[0],arg[-1]) in (('(',')'),('"','"')):
if len(arg) >= 2 and (arg[0],arg[-1]) in (('(',')'),('"','"')):
def _checkquote(self, arg):
if self.mustquote.search(arg) is None:
if arg and self.mustquote.search(arg) is None:
def _checkquote(self, arg):
post_interp = match.group(1)
post_interp = match.group(1) or ''
def copy_scripts (self): """Copy each script listed in 'self.scripts'; if it's marked as a Python script in the Unix way (first line matches 'first_line_re', ie. starts with "\#!" and contains "python"), then adjust the first line to refer to the current Python interpreter as we copy. """ self.mkpath(self.build_dir) for script in self.scripts: adjust = 0 script = convert_path(script) outfile = os.path.join(self.build_dir, os.path.basename(script))
f.fileno = None
def open_data(self, url, data=None): """Use "data" URL.""" # ignore POSTed data # # syntax of data URLs: # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data # mediatype := [ type "/" subtype ] *( ";" parameter ) # data := *urlchar # parameter := attribute "=" value import mimetools try: from cStringIO import StringIO except ImportError: from StringIO import StringIO try: [type, data] = url.split(',', 1) except ValueError: raise IOError, ('data error', 'bad data URL') if not type: type = 'text/plain;charset=US-ASCII' semi = type.rfind(';') if semi >= 0 and '=' not in type[semi:]: encoding = type[semi+1:] type = type[:semi] else: encoding = '' msg = [] msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT', time.gmtime(time.time()))) msg.append('Content-type: %s' % type) if encoding == 'base64': import base64 data = base64.decodestring(data) else: data = unquote(data) msg.append('Content-length: %d' % len(data)) msg.append('') msg.append(data) msg = '\n'.join(msg) f = StringIO(msg) headers = mimetools.Message(f, 0) f.fileno = None # needed for addinfourl return addinfourl(f, headers, url)