rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
labels = doc.getElementsByTagName("label") for label in labels: id = label.getAttribute("id") if not id: continue parent = label.parentNode if parent.tagName == "title": parent.parentNode.setAttribute("id", id) else: parent.setAttribute("id", id) parent.removeChild(label)
for node in doc.childNodes: if node.nodeType == xml.dom.core.ELEMENT: labels = node.getElementsByTagName("label") for label in labels: id = label.getAttribute("id") if not id: continue parent = label.parentNode if parent.tagName == "title": parent.parentNode.setAttribute("id", id) else: parent.setAttribute("id", id) p...
def handle_labels(doc): labels = doc.getElementsByTagName("label") for label in labels: id = label.getAttribute("id") if not id: continue parent = label.parentNode if parent.tagName == "title": parent.parentNode.setAttribute("id", id) else: parent.setAttribute("id", id) # now, remove <label id="..."/> from parent: pare...
if a.index(-2,-10) != 0: raise TestFailed, 'list index, negative start argument'
if a.index(0,-4) != 2: raise TestFailed, 'list index, -start argument' if a.index(-2,-10) != 0: raise TestFailed, 'list index, very -start argument'
def __getitem__(self, key): return str(key) + '!!!'
raise TestFailed, 'list index, negative stop argument'
raise TestFailed, 'list index, very -stop argument'
def __getitem__(self, key): return str(key) + '!!!'
self._file.write(struct.pack('<lsslhhllhhs',
self._file.write(struct.pack('<l4s4slhhllhh4s',
def _write_header(self, initlength): self._file.write('RIFF') if not self._nframes: self._nframes = initlength / (self._nchannels * self._sampwidth) self._datalength = self._nframes * self._nchannels * self._sampwidth self._form_length_pos = self._file.tell() self._file.write(struct.pack('<lsslhhllhhs', 36 + self._data...
return swi.swi('OS_File', '5s;i', p)!=0
try: return swi.swi('OS_File', '5s;i', p)!=0 except swi.error: return 0
def exists(p): """
return swi.swi('OS_File', '5s;i', p) in [2, 3]
try: return swi.swi('OS_File', '5s;i', p) in [2, 3] except swi.error: return 0
def isdir(p): """
return swi.swi('OS_File', '5s;i', p) in [1, 3]
try: return swi.swi('OS_File', '5s;i', p) in [1, 3] except swi.error: return 0
def isfile(p): """
print mod.__name__, dir(mod)
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, __ver...
print "File name %s contains a suspicious null byte!" % filename
def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)): self.orig_filename = filename # Original file name in archive
elif platform == 'cygwin': x11_inc = find_file('X11/Xlib.h', [], inc_dirs) if x11_inc is None: return
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module.
if __name__ == "__main__": import __main__ sys.modules['warnings'] = __main__ _test() else: _processoptions(sys.warnoptions) simplefilter("ignore", category=OverflowWarning, append=1) simplefilter("ignore", category=PendingDeprecationWarning, append=1)
_processoptions(sys.warnoptions) simplefilter("ignore", category=OverflowWarning, append=1) simplefilter("ignore", category=PendingDeprecationWarning, append=1)
def _getcategory(category): import re if not category: return Warning if re.match("^[a-zA-Z0-9_]+$", category): try: cat = eval(category) except NameError: raise _OptionError("unknown warning category: %r" % (category,)) else: i = category.rfind(".") module = category[:i] klass = category[i+1:] try: m = __import__(modu...
if 0: def test_timeout(): test_support.requires('network')
def test_timeout(): test_support.requires('network')
def test_basic(): test_support.requires('network') import urllib socket.RAND_status() try: socket.RAND_egd(1) except TypeError: pass else: print "didn't raise TypeError" socket.RAND_add("this is a random string", 75.0) f = urllib.urlopen('https://sf.net') buf = f.read() f.close()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(30.0) s.connect(("gmail.org", 995)) ss = socket.ssl(s) ss.read(1) ss.read(1) s.close() else: def test_timeout(): pass
if test_support.verbose: print "test_timeout ..." ADDR = "gmail.org", 995 s = socket.socket() s.settimeout(30.0) try: s.connect(ADDR) except socket.timeout: print >> sys.stderr, """\ WARNING: an attempt to connect to %r timed out, in test_timeout. That may be legitimate, but is not the outcome we hoped for. I...
def test_timeout(): test_support.requires('network')
containing the table) showing a side by side, line by line comparision
containing the table) showing a side by side, line by line comparison
def _line_pair_iterator(): """Yields from/to lines of text with a change indication.
cantset(f, "func_name", "f") cantset(f, "__name__", "f")
f.__name__ = "g" verify(f.__name__ == "g") verify(f.func_name == "g") f.func_name = "h" verify(f.__name__ == "h") verify(f.func_name == "h") cantset(f, "func_globals", 1) cantset(f, "__name__", 1)
def f(): pass
self._parsing = 0
def reset(self): if self._namespaces: self._parser = expat.ParserCreate(None, " ") self._parser.StartElementHandler = self.start_element_ns self._parser.EndElementHandler = self.end_element_ns else: self._parser = expat.ParserCreate() self._parser.StartElementHandler = self.start_element self._parser.EndElementHandler ...
verify(log == [('getattr', '__init__'), ('getattr', '__setattr__'),
verify(log == [('getattr', '__setattr__'),
def __delattr__(self, name): log.append(("delattr", name)) MT.__delattr__(self, name)
e.delta = getint(D)
try: e.delta = getint(D) except ValueError: e.delta = 0
def _substitute(self, *args): """Internal function.""" if len(args) != len(self._subst_format): return args getboolean = self.tk.getboolean getint = int nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args # Missing: (a, c, d, m, o, v, B, R) e = Event() e.serial = getint(nsign) e.num = getint(b) try: e.fo...
print socket.getservbyname('telnet', 'tcp') try: socket.getservbyname('telnet', 'udp') except socket.error: pass
if hasattr(socket, 'getservbyname'): print socket.getservbyname('telnet', 'tcp') try: socket.getservbyname('telnet', 'udp') except socket.error: pass
def missing_ok(str): try: getattr(socket, str) except AttributeError: pass
libraries=[dblib]))
libraries=dblibs))
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')
if platform not in ['cygwin', 'mac']: if (self.compiler.find_library_file(lib_dirs, 'ndbm')):
if platform not in ['cygwin']: if (self.compiler.find_library_file(lib_dirs, 'ndbm') and find_file("ndbm.h", inc_dirs, []) is not None):
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')
elif self.compiler.find_library_file(lib_dirs, 'gdbm'):
elif (platform in ['darwin'] and find_file("ndbm.h", inc_dirs, []) is not None):
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,
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')
else: exts.append( Extension('dbm', ['dbmmodule.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')
frameworkdir = sysconfig.get_config_var('PYTHONFRAMEWORKDIR') 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_...
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('_Res', ['res/_Resmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Snd', ['snd/_Sndmodule.c'], extra_link_args=['-framework', 'Carbon']) ) if frameworkdir:
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'], ext...
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')
_keep_alive(args, memo)
def _deepcopy_inst(x, memo): if hasattr(x, '__deepcopy__'): return x.__deepcopy__(memo) if hasattr(x, '__getinitargs__'): args = x.__getinitargs__() _keep_alive(args, memo) args = deepcopy(args, memo) y = apply(x.__class__, args) else: y = _EmptyClass() y.__class__ = x.__class__ memo[id(x)] = y if hasattr(x, '__getstat...
_keep_alive(state, memo)
def _deepcopy_inst(x, memo): if hasattr(x, '__deepcopy__'): return x.__deepcopy__(memo) if hasattr(x, '__getinitargs__'): args = x.__getinitargs__() _keep_alive(args, memo) args = deepcopy(args, memo) y = apply(x.__class__, args) else: y = _EmptyClass() y.__class__ = x.__class__ memo[id(x)] = y if hasattr(x, '__getstat...
access *: private
if 0: access *: private
def close(self): self._ensure_header_written() if self._nframeswritten != self._nframes or \ self._datalength != self._datawritten: self._patchheader() self._file.flush() self._file = None
def copytree(src, dst, symlinks=0):
def copytree(src, dst, symlinks=False):
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, th...
Error are reported to standard output.
If exception(s) occur, an Error is raised with a list of reasons.
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, th...
if issubclass(t, TypeType):
try: issc = issubclass(t, TypeType) except TypeError: issc = 0 if issc:
def save(self, object, pers_save = 0): memo = self.memo
self.pack_uint(int(x>>32 & 0xffffffff)) self.pack_uint(int(x & 0xffffffff))
self.pack_uint(x>>32 & 0xffffffffL) self.pack_uint(x & 0xffffffffL)
def pack_uhyper(self, x):
elif path == '' or path[-1:] in '/\\':
elif path == '' or path[-1:] in '/\\:':
def join(a, *p): """Join two or more pathname components, inserting "\\" as needed""" path = a for b in p: if isabs(b): path = b elif path == '' or path[-1:] in '/\\': path = path + b else: path = path + os.sep + b return path
verify(self.cbcalled == 1, "callback did not properly set 'cbcalled'") verify(ref() is None, "ref2 should be dead after deleting object reference")
self.assert_(self.cbcalled == 1, "callback did not properly set 'cbcalled'") self.assert_(ref() is None, "ref2 should be dead after deleting object reference")
def check_basic_callback(self, factory): self.cbcalled = 0 o = factory() ref = weakref.ref(o, self.callback) del o verify(self.cbcalled == 1, "callback did not properly set 'cbcalled'") verify(ref() is None, "ref2 should be dead after deleting object reference")
self.assertEqual(grp.getgrgid(e.gr_gid), e)
entriesbygid.setdefault(e.gr_gid, []).append(e) for e in entries: self.assert_(grp.getgrgid(e.gr_gid) in entriesbygid[e.gr_gid])
def test_values(self): entries = grp.getgrall()
if type(url) in types.StringTypes:
if type(url) is types.StringType:
def open_https(self, url, data=None): """Use HTTPS protocol.""" import httplib user_passwd = None if type(url) in types.StringTypes: host, selector = splithost(url) if host: user_passwd, host = splituser(host) host = unquote(host) realhost = host else: host, selector = url urltype, rest = splittype(selector) url = rest...
while cursel > 0 and selstart[:i] <= self.completions[cursel-1]:
previous_completion = self.completions[cursel - 1] while cursel > 0 and selstart[:i] <= previous_completion:
def _selection_changed(self): """Should be called when the selection of the Listbox has changed. Updates the Listbox display and calls _change_start.""" cursel = int(self.listbox.curselection()[0])
print repr(str(err))
# def __getstate__(self):
return pydoc.getdoc(method)
import pydoc return pydoc.getdoc(method)
def system_methodHelp(self, method_name): """system.methodHelp('add') => "Adds two integers together"
sys.stdout.write(reponse)
sys.stdout.write(response)
def handle_get(self): """Handle a single HTTP GET request.
socket.SOL_SOCKET, socket.SO_REUSEADDR,
socket.SOL_SOCKET, reuse_constant,
def set_reuse_addr(self): # try to re-use a server port if possible try: self.socket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1 ) except socket.error: pass
socket.SO_REUSEADDR) | 1
reuse_constant) | 1
def set_reuse_addr(self): # try to re-use a server port if possible try: self.socket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1 ) except socket.error: pass
if os.path.exists (self.build_lib): remove_tree (self.build_lib, self.verbose, self.dry_run) else: self.warn ("'%s' does not exist -- can't clean it" % self.build_lib) if os.path.exists (self.bdist_base): remove_tree (self.bdist_base, self.verbose, self.dry_run) else: self.warn ("'%s' does not exist -- can't clea...
for directory in (self.build_lib, self.bdist_base, self.build_scripts): if os.path.exists (directory): remove_tree (directory, self.verbose, self.dry_run) else: self.warn ("'%s' does not exist -- can't clean it" % directory)
def run(self): # remove the build/temp.<plat> directory (unless it's already # gone) if os.path.exists (self.build_temp): remove_tree (self.build_temp, self.verbose, self.dry_run) else: self.warn ("'%s' does not exist -- can't clean it" % self.build_temp)
if netloc:
if netloc or (scheme in uses_netloc and url[:2] == '//'):
def urlunparse((scheme, netloc, url, params, query, fragment)): if netloc: if url[:1] != '/': url = '/' + url url = '//' + netloc + url if scheme: url = scheme + ':' + url if params: url = url + ';' + params if query: url = url + '?' + query if fragment: url = url + '#' + fragment return url
url = '//' + netloc + url
url = '//' + (netloc or '') + url
def urlunparse((scheme, netloc, url, params, query, fragment)): if netloc: if url[:1] != '/': url = '/' + url url = '//' + netloc + url if scheme: url = scheme + ':' + url if params: url = url + ';' + params if query: url = url + '?' + query if fragment: url = url + '#' + fragment return url
sys.settrace(gself.lobaltrace)
sys.settrace(self.globaltrace)
def runctx(self, cmd, globals=None, locals=None): if globals is None: globals = {} if locals is None: locals = {} if not self.donothing: sys.settrace(gself.lobaltrace) try: exec cmd in dict, dict finally: if not self.donothing: sys.settrace(None)
exec cmd in dict, dict
exec cmd in globals, locals
def runctx(self, cmd, globals=None, locals=None): if globals is None: globals = {} if locals is None: locals = {} if not self.donothing: sys.settrace(gself.lobaltrace) try: exec cmd in dict, dict finally: if not self.donothing: sys.settrace(None)
ignore_it = self.ignore.names(filename, modulename) if not ignore_it: if self.trace: print " --- modulename: %s, funcname: %s" % (modulename, funcname,) return self.localtrace
if modulename is not None: ignore_it = self.ignore.names(filename, modulename) if not ignore_it: if self.trace: print " --- modulename: %s, funcname: %s" % (modulename, funcname,) return self.localtrace
def globaltrace_lt(self, frame, why, arg): """ Handles `call' events (why == 'call') and if the code block being entered is to be ignored then it returns `None', else it returns `self.localtrace'. """ if why == 'call': (filename, lineno, funcname, context, lineindex,) = inspect.getframeinfo(frame, 0) # if DEBUG_MODE an...
try: print "%s(%d): %s" % (bname, lineno, context[lineindex],), except IndexError: pass
if context is not None: try: print "%s(%d): %s" % (bname, lineno, context[lineindex],), except IndexError: pass else: print "%s(???): ???" % bname
def localtrace_trace(self, frame, why, arg): if why == 'line': # XXX shouldn't do the count increment when arg is exception? But be careful to return self.localtrace when arg is exception! ? --Zooko 2001-10-14 # record the file name and line number of every trace # XXX I wish inspect offered me an optimized `getfilen...
if host[0] == '[' and host[-1] == ']':
if host and host[0] == '[' and host[-1] == ']':
def _set_hostport(self, host, port): if port is None: i = host.rfind(':') j = host.rfind(']') # ipv6 addresses have [...] if i > j: try: port = int(host[i+1:]) except ValueError: raise InvalidURL("nonnumeric port: '%s'" % host[i+1:]) host = host[:i] else: port = self.default_port if host[0] == '[' and host[-1] ...
"<function <lambda> at 0x"))
"<function <lambda"))
def test_lambda(self): self.failUnless(repr(lambda x: x).startswith( "<function <lambda> at 0x")) # XXX anonymous functions? see func_repr
except string.atoi_error: pass
except string.atoi_error: raise socket.error, "nonnumeric port"
def connect(self, host, port = 0): if not port: i = string.find(host, ':') if i >= 0: host, port = host[:i], host[i+1:] try: port = string.atoi(port) except string.atoi_error: pass if not port: port = HTTP_PORT self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if self.debuglevel > 0: print 'connect:', (host...
gotone, evt = Evt.WaitNextEvent(-1, 0)
gotone, evt = Evt.WaitNextEvent(0xffff, 0)
def main(): print 'hello world' # XXXX # skip the toolbox initializations, already done # XXXX Should use gestalt here to check for quicktime version Qt.EnterMovies() # Get the movie file fss, ok = macfs.StandardGetFile(QuickTime.MovieFileType) if not ok: sys.exit(0) # Open the window bounds = (175, 75, 175+160, 75+1...
except (DistutilsExecError, DistutilsFileError, DistutilsOptionError,
except (DistutilsError,
def setup (**attrs): """The gateway to the Distutils: do everything your setup script needs to do, in a highly flexible and user-driven way. Briefly: create a Distribution instance; find and parse config files; parse the command line; run each Distutils command found there, customized by the options supplied to 'setup...
except AttrinuteError:
except AttributeError:
def do_mouseDown(self, event): (what, message, when, where, modifiers) = event partcode, window = FindWindow(where) if partname.has_key(partcode): name = "do_" + partname[partcode] else: name = "do_%d" % partcode try: handler = getattr(self, name) except AttrinuteError: handler = self.do_unknownpartcode handler(partcod...
print "Should close window:", window
if DEBUG: print "Should close window:", window
def do_close(self, window): print "Should close window:", window
print "SystemClick", event, window
MacOS.HandleEvent(event)
def do_inSysWindow(self, partcode, window, event): print "SystemClick", event, window # SystemClick(event, window) # XXX useless, window is None
print "inDesk"
def do_inDesk(self, partcode, window, event): print "inDesk" # XXX what to do with it?
print "FindControl(%s, %s) -> (%s, %s)" % \
if DEBUG: print "FindControl(%s, %s) -> (%s, %s)" % \
def do_inContent(self, partcode, window, event): (what, message, when, where, modifiers) = event local = GlobalToLocal(where) ctltype, control = FindControl(local, window) if ctltype and control: pcode = control.TrackControl(local) if pcode: self.do_controlhit(window, control, pcode, event) else: print "FindControl(%s,...
print "control hit in", window, "on", control, "; pcode =", pcode
if DEBUG: print "control hit in", window, "on", control, "; pcode =", pcode
def do_controlhit(self, window, control, pcode, event): print "control hit in", window, "on", control, "; pcode =", pcode
print "Mouse down at global:", where print "\tUnknown part code:", partcode
if DEBUG: print "Mouse down at global:", where if DEBUG: print "\tUnknown part code:", partcode MacOS.HandleEvent(event)
def do_unknownpartcode(self, partcode, window, event): (what, message, when, where, modifiers) = event print "Mouse down at global:", where print "\tUnknown part code:", partcode
print 'Command-W without front window'
if DEBUG: print 'Command-W without front window'
def do_key(self, event): (what, message, when, where, modifiers) = event c = chr(message & charCodeMask) if modifiers & cmdKey: if c == '.': raise self else: result = MenuKey(ord(c)) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id: self.do_rawmenu(id, item, None, event) elif c == 'w': w = F...
print "Command-" +`c`
if DEBUG: print "Command-" +`c`
def do_key(self, event): (what, message, when, where, modifiers) = event c = chr(message & charCodeMask) if modifiers & cmdKey: if c == '.': raise self else: result = MenuKey(ord(c)) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id: self.do_rawmenu(id, item, None, event) elif c == 'w': w = F...
print "Character", `c`
if DEBUG: print "Character", `c`
def do_char(self, c, event): print "Character", `c`
print "do_update", self.printevent(event)
if DEBUG: print "do_update", self.printevent(event)
def do_updateEvt(self, event): print "do_update", self.printevent(event) window = FrontWindow() # XXX This is wrong! if window: self.do_rawupdate(window, event) else: print "no window for do_updateEvt"
print "no window for do_updateEvt"
MacOS.HandleEvent(event)
def do_updateEvt(self, event): print "do_update", self.printevent(event) window = FrontWindow() # XXX This is wrong! if window: self.do_rawupdate(window, event) else: print "no window for do_updateEvt"
print "raw update for", window
if DEBUG: print "raw update for", window
def do_rawupdate(self, window, event): print "raw update for", window window.BeginUpdate() self.do_update(window, event) DrawControls(window) window.DrawGrowIcon() window.EndUpdate()
print "High Level Event:", self.printevent(event)
if DEBUG: print "High Level Event:", self.printevent(event)
def do_kHighLevelEvent(self, event): (what, message, when, where, modifiers) = event print "High Level Event:", self.printevent(event) try: AEProcessAppleEvent(event) except: print "AEProcessAppleEvent error:" traceback.print_exc()
print "MenuBar.dispatch(%d, %d, %s, %s)" % \
if DEBUG: print "MenuBar.dispatch(%d, %d, %s, %s)" % \
def dispatch(self, id, item, window, event): if self.menus.has_key(id): self.menus[id].dispatch(id, item, window, event) else: print "MenuBar.dispatch(%d, %d, %s, %s)" % \ (id, item, window, event)
src_extensions = _c_extensions + _cpp_extensions
src_extensions = (_c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions) res_extension = '.res'
def set_path_env_var (name, version_number): """Set environment variable 'name' to an MSVC path type value obtained from 'get_msvc_paths()'. This is equivalent to a SET command prior to execution of spawned commands.""" p = get_msvc_paths (name, version_number) if p: os.environ[name] = string.join (p,';')
self.mkpath (os.path.dirname (obj))
def compile (self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None):
status.append ('%s:%d' % self.addr) return '<%s %s at %x>' % ( self.__class__.__name__, ' '.join (status), id(self) )
if self.addr == types.TupleType: status.append ('%s:%d' % self.addr) else: status.append (self.addr) return '<%s %s at %x>' % (self.__class__.__name__, ' '.join (status), id (self))
def __repr__ (self): try: status = [] if self.accepting and self.addr: status.append ('listening') elif self.connected: status.append ('connected') if self.addr: status.append ('%s:%d' % self.addr) return '<%s %s at %x>' % ( self.__class__.__name__, ' '.join (status), id(self) ) except: try: ar = repr(self.addr) except...
try: ar = repr(self.addr) except: ar = 'no self.addr!' return '<__repr__ (self) failed for object at %x (addr=%s)>' % (id(self),ar)
pass try: ar = repr (self.addr) except AttributeError: ar = 'no self.addr!' return '<__repr__() failed for %s instance at %x (addr=%s)>' % \ (self.__class__.__name__, id (self), ar)
def __repr__ (self): try: status = [] if self.accepting and self.addr: status.append ('listening') elif self.connected: status.append ('connected') if self.addr: status.append ('%s:%d' % self.addr) return '<%s %s at %x>' % ( self.__class__.__name__, ' '.join (status), id(self) ) except: try: ar = repr(self.addr) except...
return os.path.join(sys.exec_prefix, "lib", "python" + sys.version[:3], "config", "config.h")
return os.path.join(sys.exec_prefix, "include", "python" + sys.version[:3], "config.h")
def get_config_h_filename(): """Return full pathname of installed config.h file.""" return os.path.join(sys.exec_prefix, "lib", "python" + sys.version[:3], "config", "config.h")
applemenu.AppendMenu("All about cgitest...;(-")
applemenu.AppendMenu("About %s...;(-" % self.__class__.__name__)
def __init__(self): self.quitting = 0 # Initialize menu self.appleid = 1 self.quitid = 2 Menu.ClearMenuBar() self.applemenu = applemenu = Menu.NewMenu(self.appleid, "\024") applemenu.AppendMenu("All about cgitest...;(-") applemenu.AppendResMenu('DRVR') applemenu.InsertMenu(0) self.quitmenu = Menu.NewMenu(self.quitid, "...
if c == '.' and modifiers & cmdKey: raise KeyboardInterrupt, "Command-period"
if modifiers & cmdKey: if c == '.': raise KeyboardInterrupt, "Command-period" if c == 'q': self.quitting = 1
def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: print 'AE error: ', err print 'in', msg traceback.print_exc() retur...
EasyDialogs.Message("cgitest - First cgi test") return
EasyDialogs.Message(self.getabouttext())
def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: print 'AE error: ', err print 'in', msg traceback.print_exc() retur...
name = self.applemenu.GetItem(item) Qd.OpenDeskAcc(name) return if id == self.quitid and item == 1: print "Menu-requested QUIT"
name = self.applemenu.GetMenuItemText(item) Menu.OpenDeskAcc(name) elif id == self.quitid and item == 1:
def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: print 'AE error: ', err print 'in', msg traceback.print_exc() retur...
MacOS.HandleEvent(event)
Menu.HiliteMenu(0) else: MacOS.HandleEvent(event) def getabouttext(self): return self.__class__.__name__
def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: print 'AE error: ', err print 'in', msg traceback.print_exc() retur...
self._version = _read_long(chunk)
self._version = _read_ulong(chunk)
def initfp(self, file): self._version = 0 self._decomp = None self._convert = None self._markers = [] self._soundpos = 0 self._file = Chunk(file) if self._file.getname() != 'FORM': raise Error, 'file does not start with FORM id' formdata = self._file.read(4) if formdata == 'AIFF': self._aifc = 0 elif formdata == 'AIFC'...
self.message(" possible to distinguish between from \"package import submodule\" ", 1)
self.message(" possible to distinguish between \"from package " "import submodule\" ", 1)
def reportMissing(self): missing = [name for name in self.missingModules if name not in MAYMISS_MODULES] if self.maybeMissingModules: maybe = self.maybeMissingModules else: maybe = [name for name in missing if "." in name] missing = [name for name in missing if "." not in name] missing.sort() maybe.sort() if maybe: sel...
@bigmemtest(minsize=_2G // 2 + 2, memuse=8)
@bigmemtest(minsize=_2G // 2 + 2, memuse=24)
def basic_test_inplace_concat(self, size): l = [sys.stdout] * size l += l self.assertEquals(len(l), size * 2) self.failUnless(l[0] is l[-1]) self.failUnless(l[size - 1] is l[size + 1])
@bigmemtest(minsize=_2G + 2, memuse=8)
@bigmemtest(minsize=_2G + 2, memuse=24)
def test_inplace_concat_small(self, size): return self.basic_test_inplace_concat(size)
self.__frame = Frame(parent) self.__frame.pack(expand=YES, fill=BOTH)
self.__frame = Frame(parent, relief=GROOVE, borderwidth=2) self.__frame.pack()
def __init__(self, switchboard, parent=None): self.__sb = switchboard self.__frame = Frame(parent) self.__frame.pack(expand=YES, fill=BOTH) # create the chip that will display the currently selected color # exactly self.__sframe = Frame(self.__frame) self.__sframe.grid(row=0, column=0) self.__selected = ChipWidget(self...
attempdirs = ['/var/tmp', '/usr/tmp', '/tmp', pwd]
attempdirs = ['/tmp', '/var/tmp', '/usr/tmp', pwd]
def gettempdir(): """Function to calculate the directory to use.""" global tempdir if tempdir is not None: return tempdir try: pwd = os.getcwd() except (AttributeError, os.error): pwd = os.curdir attempdirs = ['/var/tmp', '/usr/tmp', '/tmp', pwd] if os.name == 'nt': attempdirs.insert(0, 'C:\\TEMP') attempdirs.insert(0,...
if not iscode(co): raise TypeError, 'arg is not a code object'
if not iscode(co): raise TypeError('arg is not a code object')
def getargs(co): """Get information about the arguments accepted by a code object. Three things are returned: (args, varargs, varkw), where 'args' is a list of argument names (possibly containing nested lists), and 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" if not iscode(co): raise TypeE...
'defaults' is an n-tuple of the default values of the last n arguments.""" if not isfunction(func): raise TypeError, 'arg is not a Python function'
'defaults' is an n-tuple of the default values of the last n arguments. """ if ismethod(func): func = func.im_func if not isfunction(func): raise TypeError('arg is not a Python function')
def getargspec(func): """Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tupl...
'raw_unicode_escape', 'unicode_escape', 'unicode_internal'):
'unicode_escape', 'unicode_internal'):
def __str__(self): return self.x
self.headers.update(headers)
for key, value in headers.iteritems(): self.add_header(key, value)
def __init__(self, url, data=None, headers={}): # unwrap('<URL:type://host/path>') --> 'type://host/path' self.__original = unwrap(url) self.type = None # self.__r_type is what's left after doing the splittype self.host = None self.port = None self.data = data self.headers = {} self.headers.update(headers)
self.headers[key] = val
self.headers[key.capitalize()] = val
def add_header(self, key, val): # useful for something like authentication self.headers[key] = val
for type, url in proxies.items():
for type, url in proxies.iteritems():
def __init__(self, proxies=None): if proxies is None: proxies = getproxies() assert hasattr(proxies, 'has_key'), "proxies must be a mapping" self.proxies = proxies for type, url in proxies.items(): setattr(self, '%s_open' % type, lambda r, proxy=url, type=type, meth=self.proxy_open: \ meth(r, proxy, type))
for uris, authinfo in domains.items():
for uris, authinfo in domains.iteritems():
def find_user_password(self, realm, authuri): domains = self.passwd.get(realm, {}) authuri = self.reduce_uri(authuri) for uris, authinfo in domains.items(): for uri in uris: if self.is_suburi(uri, authuri): return authinfo return None, None
for k, v in req.headers.items():
for k, v in req.headers.iteritems():
def do_open(self, http_class, req): host = req.get_host() if not host: raise URLError('no host given')
for k, v in self.timeout.items():
for k, v in self.timeout.iteritems():
def check_cache(self): # first check for old ones t = time.time() if self.soonest <= t: for k, v in self.timeout.items(): if v < t: self.cache[k].close() del self.cache[k] del self.timeout[k] self.soonest = min(self.timeout.values())
Note: this functions only works if Mark Hammond's win32
Note: this function only works if Mark Hammond's win32
def win32_ver(release='',version='',csd='',ptype=''): """ Get additional version information from the Windows Registry and return a tuple (version,csd,ptype) referring to version number, CSD level and OS type (multi/single processor). As a hint: ptype returns 'Uniprocessor Free' on single processor NT machines and 'M...
self.__frame.grid(row=3, column=1, sticky='NS')
self.__frame.grid(row=3, column=1, sticky='NSEW')
def __init__(self, switchboard, master=None): # non-gui ivars self.__sb = switchboard optiondb = switchboard.optiondb() self.__hexp = BooleanVar() self.__hexp.set(optiondb.get('HEXTYPE', 0)) self.__uwtyping = BooleanVar() self.__uwtyping.set(optiondb.get('UPWHILETYPE', 0)) # create the gui self.__frame = Frame(master, ...
s = madstring("\x00" * 5) verify(str(s) == "\x00" * 5)
base = "\x00" * 5 s = madstring(base) verify(str(s) == base)
def rev(self): if self._rev is not None: return self._rev L = list(self) L.reverse() self._rev = self.__class__("".join(L)) return self._rev
contents = contents[:i-1] + contents[i:]
if event.char: contents = contents[:i-1] + contents[i:] icursor = icursor-1
def __normalize(self, event=None): ew = event.widget contents = ew.get() icursor = ew.index(INSERT) if contents == '': contents = '0' # figure out what the contents value is in the current base try: if self.__hexp.get(): v = string.atoi(contents, 16) else: v = string.atoi(contents) except ValueError: v = None # if valu...
icursor = icursor-1
def __normalize(self, event=None): ew = event.widget contents = ew.get() icursor = ew.index(INSERT) if contents == '': contents = '0' # figure out what the contents value is in the current base try: if self.__hexp.get(): v = string.atoi(contents, 16) else: v = string.atoi(contents) except ValueError: v = None # if valu...