rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
blocknum = blocknum + 1 | read += len(block) blocknum += 1 | def retrieve(self, url, filename=None, reporthook=None, data=None): """retrieve(url) returns (filename, headers) for a local object or (tempfilename, headers) for a remote object.""" url = unwrap(toBytes(url)) if self.tempcache and url in self.tempcache: return self.tempcache[url] type, url1 = splittype(url) if filename is None and (not type or type == 'file'): try: fp = self.open_local_file(url1) hdrs = fp.info() del fp return url2pathname(splithost(url1)[1]), hdrs except IOError, msg: pass fp = self.open(url, data) headers = fp.info() if filename: tfp = open(filename, 'wb') else: import tempfile garbage, path = splittype(url) garbage, path = splithost(path or "") path, garbage = splitquery(path or "") path, garbage = splitattr(path or "") suffix = os.path.splitext(path)[1] (fd, filename) = tempfile.mkstemp(suffix) self.__tempfiles.append(filename) tfp = os.fdopen(fd, 'wb') result = filename, headers if self.tempcache is not None: self.tempcache[url] = result bs = 1024*8 size = -1 blocknum = 1 if reporthook: if "content-length" in headers: size = int(headers["Content-Length"]) reporthook(0, bs, size) block = fp.read(bs) if reporthook: reporthook(1, bs, size) while block: tfp.write(block) block = fp.read(bs) blocknum = blocknum + 1 if reporthook: reporthook(blocknum, bs, size) fp.close() tfp.close() del fp del tfp return result |
def putrequest(self, method, url): | def putrequest(self, method, url, skip_host=0): | def putrequest(self, method, url): """Send a request to the server. |
if url.startswith('http:'): nil, netloc, nil, nil, nil = urlsplit(url) self.putheader('Host', netloc) elif self.port == HTTP_PORT: self.putheader('Host', netloc) else: self.putheader('Host', "%s:%s" % (self.host, self.port)) | if not skip_host: netloc = '' if url.startswith('http'): nil, netloc, nil, nil, nil = urlsplit(url) if netloc: self.putheader('Host', netloc) elif self.port == HTTP_PORT: self.putheader('Host', self.host) else: self.putheader('Host', "%s:%s" % (self.host, self.port)) | def putrequest(self, method, url): """Send a request to the server. |
self.putrequest(method, url) | if (headers.has_key('Host') or [k for k in headers.iterkeys() if k.lower() == "host"]): self.putrequest(method, url, skip_host=1) else: self.putrequest(method, url) | def _send_request(self, method, url, body, headers): self.putrequest(method, url) |
self.format_all(map(lambda (mtime, file): file, list)) | self.format_all(map(lambda (mtime, file): file, list), headers=0) | def do_recent(self): |
while 1: | depth = 0 while depth < 10: depth = depth + 1 | def get(self, section, option, raw=0, vars=None): """Get an option value for a given section. |
release = '98' | release = 'postMe' | 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 'Multiprocessor Free' on multi processor machines. The 'Free' refers to the OS version being free of debugging code. It could also state 'Checked' which means the OS version uses debugging code, i.e. code that checks arguments, ranges, etc. (Thomas Heller). Note: this function only works if Mark Hammond's win32 package is installed and obviously only runs on Win32 compatible platforms. """ # XXX Is there any way to find out the processor type on WinXX ? # XXX Is win32 available on Windows CE ? # Adapted from code posted by Karl Putland to comp.lang.python. # Import the needed APIs try: import win32api except ImportError: return release,version,csd,ptype from win32api import RegQueryValueEx,RegOpenKeyEx,RegCloseKey,GetVersionEx from win32con import HKEY_LOCAL_MACHINE,VER_PLATFORM_WIN32_NT,\ VER_PLATFORM_WIN32_WINDOWS # Find out the registry key and some general version infos maj,min,buildno,plat,csd = GetVersionEx() version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF) if csd[:13] == 'Service Pack ': csd = 'SP' + csd[13:] if plat == VER_PLATFORM_WIN32_WINDOWS: regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion' # Try to guess the release name if maj == 4: if min == 0: release = '95' else: release = '98' elif maj == 5: release = '2000' elif plat == VER_PLATFORM_WIN32_NT: regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion' if maj <= 4: release = 'NT' elif maj == 5: release = '2000' else: if not release: # E.g. Win3.1 with win32s release = '%i.%i' % (maj,min) return release,version,csd,ptype # Open the registry key try: keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE,regkey) # Get a value to make sure the key exists... RegQueryValueEx(keyCurVer,'SystemRoot') except: return release,version,csd,ptype # Parse values #subversion = _win32_getvalue(keyCurVer, # 'SubVersionNumber', # ('',1))[0] #if subversion: # release = release + subversion # 95a, 95b, etc. build = _win32_getvalue(keyCurVer, 'CurrentBuildNumber', ('',1))[0] ptype = _win32_getvalue(keyCurVer, 'CurrentType', (ptype,1))[0] # Normalize version version = _norm_version(version,build) # Close key RegCloseKey(keyCurVer) return release,version,csd,ptype |
release = '2000' | if min == 0: release = '2000' elif min == 1: release = 'XP' elif min == 2: release = '2003Server' else: release = 'post2003' | 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 'Multiprocessor Free' on multi processor machines. The 'Free' refers to the OS version being free of debugging code. It could also state 'Checked' which means the OS version uses debugging code, i.e. code that checks arguments, ranges, etc. (Thomas Heller). Note: this function only works if Mark Hammond's win32 package is installed and obviously only runs on Win32 compatible platforms. """ # XXX Is there any way to find out the processor type on WinXX ? # XXX Is win32 available on Windows CE ? # Adapted from code posted by Karl Putland to comp.lang.python. # Import the needed APIs try: import win32api except ImportError: return release,version,csd,ptype from win32api import RegQueryValueEx,RegOpenKeyEx,RegCloseKey,GetVersionEx from win32con import HKEY_LOCAL_MACHINE,VER_PLATFORM_WIN32_NT,\ VER_PLATFORM_WIN32_WINDOWS # Find out the registry key and some general version infos maj,min,buildno,plat,csd = GetVersionEx() version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF) if csd[:13] == 'Service Pack ': csd = 'SP' + csd[13:] if plat == VER_PLATFORM_WIN32_WINDOWS: regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion' # Try to guess the release name if maj == 4: if min == 0: release = '95' else: release = '98' elif maj == 5: release = '2000' elif plat == VER_PLATFORM_WIN32_NT: regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion' if maj <= 4: release = 'NT' elif maj == 5: release = '2000' else: if not release: # E.g. Win3.1 with win32s release = '%i.%i' % (maj,min) return release,version,csd,ptype # Open the registry key try: keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE,regkey) # Get a value to make sure the key exists... RegQueryValueEx(keyCurVer,'SystemRoot') except: return release,version,csd,ptype # Parse values #subversion = _win32_getvalue(keyCurVer, # 'SubVersionNumber', # ('',1))[0] #if subversion: # release = release + subversion # 95a, 95b, etc. build = _win32_getvalue(keyCurVer, 'CurrentBuildNumber', ('',1))[0] ptype = _win32_getvalue(keyCurVer, 'CurrentType', (ptype,1))[0] # Normalize version version = _norm_version(version,build) # Close key RegCloseKey(keyCurVer) return release,version,csd,ptype |
_platform_cache_terse = None _platform_cache_not_terse = None _platform_aliased_cache_terse = None _platform_aliased_cache_not_terse = None | _platform_cache = {} | def python_compiler(): """ Returns a string identifying the compiler used for compiling Python. """ return _sys_version()[3] |
global _platform_cache_terse, _platform_cache_not_terse global _platform_aliased_cache_terse, _platform_aliased_cache_not_terse if not aliased and terse and (_platform_cache_terse is not None): return _platform_cache_terse elif not aliased and not terse and (_platform_cache_not_terse is not None): return _platform_cache_not_terse elif terse and _platform_aliased_cache_terse is not None: return _platform_aliased_cache_terse elif not terse and _platform_aliased_cache_not_terse is not None: return _platform_aliased_cache_not_terse | result = _platform_cache.get((aliased, terse), None) if result is not None: return result | def platform(aliased=0, terse=0): """ Returns a single string identifying the underlying platform with as much useful information as possible (but no more :). The output is intended to be human readable rather than machine parseable. It may look different on different platforms and this is intended. If "aliased" is true, the function will use aliases for various platforms that report system names which differ from their common names, e.g. SunOS will be reported as Solaris. The system_alias() function is used to implement this. Setting terse to true causes the function to return only the absolute minimum information needed to identify the platform. """ global _platform_cache_terse, _platform_cache_not_terse global _platform_aliased_cache_terse, _platform_aliased_cache_not_terse if not aliased and terse and (_platform_cache_terse is not None): return _platform_cache_terse elif not aliased and not terse and (_platform_cache_not_terse is not None): return _platform_cache_not_terse elif terse and _platform_aliased_cache_terse is not None: return _platform_aliased_cache_terse elif not terse and _platform_aliased_cache_not_terse is not None: return _platform_aliased_cache_not_terse # Get uname information and then apply platform specific cosmetics # to it... system,node,release,version,machine,processor = uname() if machine == processor: processor = '' if aliased: system,release,version = system_alias(system,release,version) if system == 'Windows': # MS platforms rel,vers,csd,ptype = win32_ver(version) if terse: platform = _platform(system,release) else: platform = _platform(system,release,version,csd) elif system in ('Linux',): # Linux based systems distname,distversion,distid = dist('') if distname and not terse: platform = _platform(system,release,machine,processor, 'with', distname,distversion,distid) else: # If the distribution name is unknown check for libc vs. glibc libcname,libcversion = libc_ver(sys.executable) platform = _platform(system,release,machine,processor, 'with', libcname+libcversion) elif system == 'Java': # Java platforms r,v,vminfo,(os_name,os_version,os_arch) = java_ver() if terse: platform = _platform(system,release,version) else: platform = _platform(system,release,version, 'on', os_name,os_version,os_arch) elif system == 'MacOS': # MacOS platforms if terse: platform = _platform(system,release) else: platform = _platform(system,release,machine) else: # Generic handler if terse: platform = _platform(system,release) else: bits,linkage = architecture(sys.executable) platform = _platform(system,release,machine,processor,bits,linkage) if aliased and terse: _platform_aliased_cache_terse = platform elif aliased and not terse: _platform_aliased_cache_not_terse = platform elif terse: pass else: if terse: _platform_cache_terse = platform else: _platform_cache_not_terse = platform return platform |
if aliased and terse: _platform_aliased_cache_terse = platform elif aliased and not terse: _platform_aliased_cache_not_terse = platform elif terse: pass else: if terse: _platform_cache_terse = platform else: _platform_cache_not_terse = platform | _platform_cache[(aliased, terse)] = platform | def platform(aliased=0, terse=0): """ Returns a single string identifying the underlying platform with as much useful information as possible (but no more :). The output is intended to be human readable rather than machine parseable. It may look different on different platforms and this is intended. If "aliased" is true, the function will use aliases for various platforms that report system names which differ from their common names, e.g. SunOS will be reported as Solaris. The system_alias() function is used to implement this. Setting terse to true causes the function to return only the absolute minimum information needed to identify the platform. """ global _platform_cache_terse, _platform_cache_not_terse global _platform_aliased_cache_terse, _platform_aliased_cache_not_terse if not aliased and terse and (_platform_cache_terse is not None): return _platform_cache_terse elif not aliased and not terse and (_platform_cache_not_terse is not None): return _platform_cache_not_terse elif terse and _platform_aliased_cache_terse is not None: return _platform_aliased_cache_terse elif not terse and _platform_aliased_cache_not_terse is not None: return _platform_aliased_cache_not_terse # Get uname information and then apply platform specific cosmetics # to it... system,node,release,version,machine,processor = uname() if machine == processor: processor = '' if aliased: system,release,version = system_alias(system,release,version) if system == 'Windows': # MS platforms rel,vers,csd,ptype = win32_ver(version) if terse: platform = _platform(system,release) else: platform = _platform(system,release,version,csd) elif system in ('Linux',): # Linux based systems distname,distversion,distid = dist('') if distname and not terse: platform = _platform(system,release,machine,processor, 'with', distname,distversion,distid) else: # If the distribution name is unknown check for libc vs. glibc libcname,libcversion = libc_ver(sys.executable) platform = _platform(system,release,machine,processor, 'with', libcname+libcversion) elif system == 'Java': # Java platforms r,v,vminfo,(os_name,os_version,os_arch) = java_ver() if terse: platform = _platform(system,release,version) else: platform = _platform(system,release,version, 'on', os_name,os_version,os_arch) elif system == 'MacOS': # MacOS platforms if terse: platform = _platform(system,release) else: platform = _platform(system,release,machine) else: # Generic handler if terse: platform = _platform(system,release) else: bits,linkage = architecture(sys.executable) platform = _platform(system,release,machine,processor,bits,linkage) if aliased and terse: _platform_aliased_cache_terse = platform elif aliased and not terse: _platform_aliased_cache_not_terse = platform elif terse: pass else: if terse: _platform_cache_terse = platform else: _platform_cache_not_terse = platform return platform |
body = "HTTP/1.1 200 Ok\r\n\r\nText" sock = FakeSocket(body) resp = httplib.HTTPResponse(sock, 1) resp.begin() print resp.read() resp.close() | import sys | def makefile(self, mode, bufsize=None): if mode != 'r' and mode != 'rb': raise httplib.UnimplementedFileMode() return StringIO.StringIO(self.text) |
body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText" sock = FakeSocket(body) resp = httplib.HTTPResponse(sock, 1) try: | def test(): buf = StringIO.StringIO() _stdout = sys.stdout try: sys.stdout = buf _test() finally: sys.stdout = _stdout s = buf.getvalue() for line in s.split("\n"): print line.strip() def _test(): body = "HTTP/1.1 200 Ok\r\n\r\nText" sock = FakeSocket(body) resp = httplib.HTTPResponse(sock, 1) | def makefile(self, mode, bufsize=None): if mode != 'r' and mode != 'rb': raise httplib.UnimplementedFileMode() return StringIO.StringIO(self.text) |
except httplib.BadStatusLine: print "BadStatusLine raised as expected" else: print "Expect BadStatusLine" | print resp.read() resp.close() | def makefile(self, mode, bufsize=None): if mode != 'r' and mode != 'rb': raise httplib.UnimplementedFileMode() return StringIO.StringIO(self.text) |
body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText" sock = FakeSocket(body) resp = httplib.HTTPResponse(sock, 1) try: resp.begin() except httplib.BadStatusLine: print "BadStatusLine raised as expected" else: print "Expect BadStatusLine" | def makefile(self, mode, bufsize=None): if mode != 'r' and mode != 'rb': raise httplib.UnimplementedFileMode() return StringIO.StringIO(self.text) |
|
for hp in ("www.python.org:abc", "www.python.org:"): try: h = httplib.HTTP(hp) except httplib.InvalidURL: print "InvalidURL raised as expected" else: print "Expect InvalidURL" | def makefile(self, mode, bufsize=None): if mode != 'r' and mode != 'rb': raise httplib.UnimplementedFileMode() return StringIO.StringIO(self.text) |
|
text = ('HTTP/1.1 200 OK\r\n' 'Set-Cookie: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"\r\n' 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";' ' Path="/acme"\r\n' '\r\n' 'No body\r\n') hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"' ', ' 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"') s = FakeSocket(text) r = httplib.HTTPResponse(s, 1) r.begin() cookies = r.getheader("Set-Cookie") if cookies != hdr: raise AssertionError, "multiple headers not combined properly" | for hp in ("www.python.org:abc", "www.python.org:"): try: h = httplib.HTTP(hp) except httplib.InvalidURL: print "InvalidURL raised as expected" else: print "Expect InvalidURL" text = ('HTTP/1.1 200 OK\r\n' 'Set-Cookie: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"\r\n' 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";' ' Path="/acme"\r\n' '\r\n' 'No body\r\n') hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"' ', ' 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"') s = FakeSocket(text) r = httplib.HTTPResponse(s, 1) r.begin() cookies = r.getheader("Set-Cookie") if cookies != hdr: raise AssertionError, "multiple headers not combined properly" test() | def makefile(self, mode, bufsize=None): if mode != 'r' and mode != 'rb': raise httplib.UnimplementedFileMode() return StringIO.StringIO(self.text) |
def register(name, klass, instance=None): | def register(name, klass, instance=None, update_tryorder=1): | def register(name, klass, instance=None): """Register a browser connector and, optionally, connection.""" _browsers[name.lower()] = [klass, instance] |
if command[1] is None: | if command[1] is not None: return command[1] elif command[0] is not None: | def get(using=None): """Return a browser launcher instance appropriate for the environment.""" if using is not None: alternatives = [using] else: alternatives = _tryorder for browser in alternatives: if '%s' in browser: # User gave us a command line, don't mess with it. return GenericBrowser(browser) else: # User gave us a browser name. try: command = _browsers[browser.lower()] except KeyError: command = _synthesize(browser) if command[1] is None: return command[0]() else: return command[1] raise Error("could not locate runnable browser") |
else: return command[1] | def get(using=None): """Return a browser launcher instance appropriate for the environment.""" if using is not None: alternatives = [using] else: alternatives = _tryorder for browser in alternatives: if '%s' in browser: # User gave us a command line, don't mess with it. return GenericBrowser(browser) else: # User gave us a browser name. try: command = _browsers[browser.lower()] except KeyError: command = _synthesize(browser) if command[1] is None: return command[0]() else: return command[1] raise Error("could not locate runnable browser") |
|
get().open(url, new, autoraise) | for name in _tryorder: browser = get(name) if browser.open(url, new, autoraise): return True return False | def open(url, new=0, autoraise=1): get().open(url, new, autoraise) |
get().open(url, 1) def _synthesize(browser): | return open(url, 1) def open_new_tab(url): return open(url, 2) def _synthesize(browser, update_tryorder=1): | def open_new(url): get().open(url, 1) |
if not os.path.exists(browser): | cmd = browser.split()[0] if not _iscommand(cmd): | def _synthesize(browser): """Attempt to synthesize a controller base on existing controllers. This is useful to create a controller when a user specifies a path to an entry in the BROWSER environment variable -- we can copy a general controller to operate using a specific installation of the desired browser in this way. If we can't create a controller in this way, or if there is no executable for the requested browser, return [None, None]. """ if not os.path.exists(browser): return [None, None] name = os.path.basename(browser) try: command = _browsers[name.lower()] except KeyError: return [None, None] # now attempt to clone to fit the new name: controller = command[1] if controller and name.lower() == controller.basename: import copy controller = copy.copy(controller) controller.name = browser controller.basename = os.path.basename(browser) register(browser, None, controller) return [None, controller] return [None, None] |
name = os.path.basename(browser) | name = os.path.basename(cmd) | def _synthesize(browser): """Attempt to synthesize a controller base on existing controllers. This is useful to create a controller when a user specifies a path to an entry in the BROWSER environment variable -- we can copy a general controller to operate using a specific installation of the desired browser in this way. If we can't create a controller in this way, or if there is no executable for the requested browser, return [None, None]. """ if not os.path.exists(browser): return [None, None] name = os.path.basename(browser) try: command = _browsers[name.lower()] except KeyError: return [None, None] # now attempt to clone to fit the new name: controller = command[1] if controller and name.lower() == controller.basename: import copy controller = copy.copy(controller) controller.name = browser controller.basename = os.path.basename(browser) register(browser, None, controller) return [None, controller] return [None, None] |
register(browser, None, controller) | register(browser, None, controller, update_tryorder) | def _synthesize(browser): """Attempt to synthesize a controller base on existing controllers. This is useful to create a controller when a user specifies a path to an entry in the BROWSER environment variable -- we can copy a general controller to operate using a specific installation of the desired browser in this way. If we can't create a controller in this way, or if there is no executable for the requested browser, return [None, None]. """ if not os.path.exists(browser): return [None, None] name = os.path.basename(browser) try: command = _browsers[name.lower()] except KeyError: return [None, None] # now attempt to clone to fit the new name: controller = command[1] if controller and name.lower() == controller.basename: import copy controller = copy.copy(controller) controller.name = browser controller.basename = os.path.basename(browser) register(browser, None, controller) return [None, controller] return [None, None] |
if _isexecutable(cmd): return True | def _iscommand(cmd): """Return True if cmd can be found on the executable search path.""" path = os.environ.get("PATH") if not path: return False for d in path.split(os.pathsep): exe = os.path.join(d, cmd) if os.path.isfile(exe): return True return False |
|
if os.path.isfile(exe): | if _isexecutable(exe): | def _iscommand(cmd): """Return True if cmd can be found on the executable search path.""" path = os.environ.get("PATH") if not path: return False for d in path.split(os.pathsep): exe = os.path.join(d, cmd) if os.path.isfile(exe): return True return False |
PROCESS_CREATION_DELAY = 4 class GenericBrowser: | class BaseBrowser(object): """Parent class for all browsers.""" def __init__(self, name=""): self.name = name def open_new(self, url): return self.open(url, 1) def open_new_tab(self, url): return self.open(url, 2) class GenericBrowser(BaseBrowser): """Class for all browsers started with a command and without remote functionality.""" | def _iscommand(cmd): """Return True if cmd can be found on the executable search path.""" path = os.environ.get("PATH") if not path: return False for d in path.split(os.pathsep): exe = os.path.join(d, cmd) if os.path.isfile(exe): return True return False |
self.basename = os.path.basename(self.name) | def __init__(self, cmd): self.name, self.args = cmd.split(None, 1) self.basename = os.path.basename(self.name) |
|
os.system(command % url) def open_new(self, url): self.open(url) class Netscape: "Launcher class for Netscape browsers." def __init__(self, name): self.name = name self.basename = os.path.basename(name) def _remote(self, action, autoraise): raise_opt = ("-noraise", "-raise")[autoraise] cmd = "%s %s -remote '%s' >/dev/null 2>&1" % (self.name, raise_opt, action) | rc = os.system(command % url) return not rc class UnixBrowser(BaseBrowser): """Parent class for all Unix browsers with remote functionality.""" raise_opts = None remote_cmd = '' remote_action = None remote_action_newwin = None remote_action_newtab = None remote_background = False def _remote(self, url, action, autoraise): autoraise = int(bool(autoraise)) raise_opt = self.raise_opts and self.raise_opts[autoraise] or '' cmd = "%s %s %s '%s' >/dev/null 2>&1" % (self.name, raise_opt, self.remote_cmd, action) if remote_background: cmd += ' &' | def open(self, url, new=0, autoraise=1): assert "'" not in url command = "%s %s" % (self.name, self.args) os.system(command % url) |
import time os.system("%s &" % self.name) time.sleep(PROCESS_CREATION_DELAY) rc = os.system(cmd) | rc = os.system("%s %s" % (self.name, url)) | def _remote(self, action, autoraise): raise_opt = ("-noraise", "-raise")[autoraise] cmd = "%s %s -remote '%s' >/dev/null 2>&1" % (self.name, raise_opt, action) rc = os.system(cmd) if rc: import time os.system("%s &" % self.name) time.sleep(PROCESS_CREATION_DELAY) rc = os.system(cmd) return not rc |
if new: self._remote("openURL(%s, new-window)"%url, autoraise) | assert "'" not in url if new == 0: action = self.remote_action elif new == 1: action = self.remote_action_newwin elif new == 2: if self.remote_action_newtab is None: action = self.remote_action_newwin else: action = self.remote_action_newtab | def open(self, url, new=0, autoraise=1): if new: self._remote("openURL(%s, new-window)"%url, autoraise) else: self._remote("openURL(%s)" % url, autoraise) |
self._remote("openURL(%s)" % url, autoraise) def open_new(self, url): self.open(url, 1) class Galeon: """Launcher class for Galeon browsers.""" def __init__(self, name): self.name = name self.basename = os.path.basename(name) def _remote(self, action, autoraise): raise_opt = ("--noraise", "")[autoraise] cmd = "%s %s %s >/dev/null 2>&1" % (self.name, raise_opt, action) rc = os.system(cmd) if rc: import time os.system("%s >/dev/null 2>&1 &" % self.name) time.sleep(PROCESS_CREATION_DELAY) rc = os.system(cmd) return not rc def open(self, url, new=0, autoraise=1): if new: self._remote("-w '%s'" % url, autoraise) else: self._remote("-n '%s'" % url, autoraise) def open_new(self, url): self.open(url, 1) class Konqueror: | raise Error("Bad 'new' parameter to open(); expected 0, 1, or 2, got %s" % new) return self._remote(url, action % url, autoraise) class Mozilla(UnixBrowser): """Launcher class for Mozilla/Netscape browsers.""" raise_opts = ("-noraise", "-raise") remote_cmd = '-remote' remote_action = "openURL(%s)" remote_action_newwin = "openURL(%s,new-window)" remote_action_newtab = "openURL(%s,new-tab)" Netscape = Mozilla class Galeon(UnixBrowser): """Launcher class for Galeon/Epiphany browsers.""" raise_opts = ("-noraise", "") remote_action = "-n '%s'" remote_action_newwin = "-w '%s'" remote_background = True class Konqueror(BaseBrowser): | def open(self, url, new=0, autoraise=1): if new: self._remote("openURL(%s, new-window)"%url, autoraise) else: self._remote("openURL(%s)" % url, autoraise) |
def __init__(self): if _iscommand("konqueror"): self.name = self.basename = "konqueror" else: self.name = self.basename = "kfm" def _remote(self, action): | def _remote(self, url, action): | def __init__(self): if _iscommand("konqueror"): self.name = self.basename = "konqueror" else: self.name = self.basename = "kfm" |
import time if self.basename == "konqueror": os.system(self.name + " --silent &") else: os.system(self.name + " -d &") time.sleep(PROCESS_CREATION_DELAY) rc = os.system(cmd) | if _iscommand("konqueror"): rc = os.system(self.name + " --silent '%s' &" % url) elif _iscommand("kfm"): rc = os.system(self.name + " -d '%s'" % url) | def _remote(self, action): cmd = "kfmclient %s >/dev/null 2>&1" % action rc = os.system(cmd) if rc: import time if self.basename == "konqueror": os.system(self.name + " --silent &") else: os.system(self.name + " -d &") time.sleep(PROCESS_CREATION_DELAY) rc = os.system(cmd) return not rc |
def open(self, url, new=1, autoraise=1): | def open(self, url, new=0, autoraise=1): | def open(self, url, new=1, autoraise=1): # XXX Currently I know no way to prevent KFM from # opening a new win. assert "'" not in url self._remote("openURL '%s'" % url) |
self._remote("openURL '%s'" % url) open_new = open class Grail: | if new == 2: action = "newTab '%s'" % url else: action = "openURL '%s'" % url ok = self._remote(url, action) return ok class Opera(UnixBrowser): "Launcher class for Opera browser." raise_opts = ("", "-raise") remote_cmd = '-remote' remote_action = "openURL(%s)" remote_action_newwin = "openURL(%s,new-window)" remote_action_newtab = "openURL(%s,new-page)" class Elinks(UnixBrowser): "Launcher class for Elinks browsers." remote_cmd = '-remote' remote_action = "openURL(%s)" remote_action_newwin = "openURL(%s,new-window)" remote_action_newtab = "openURL(%s,new-tab)" def _remote(self, url, action, autoraise): cmd = "%s %s '%s' 2>/dev/null" % (self.name, self.remote_cmd, action) rc = os.system(cmd) if rc: rc = os.system("%s %s" % (self.name, url)) return not rc class Grail(BaseBrowser): | def open(self, url, new=1, autoraise=1): # XXX Currently I know no way to prevent KFM from # opening a new win. assert "'" not in url self._remote("openURL '%s'" % url) |
self._remote("LOADNEW " + url) | ok = self._remote("LOADNEW " + url) | def open(self, url, new=0, autoraise=1): if new: self._remote("LOADNEW " + url) else: self._remote("LOAD " + url) |
self._remote("LOAD " + url) def open_new(self, url): self.open(url, 1) class WindowsDefault: def open(self, url, new=0, autoraise=1): os.startfile(url) def open_new(self, url): self.open(url) | ok = self._remote("LOAD " + url) return ok | def open(self, url, new=0, autoraise=1): if new: self._remote("LOADNEW " + url) else: self._remote("LOAD " + url) |
if os.environ.get("TERM") or os.environ.get("DISPLAY"): _tryorder = ["links", "lynx", "w3m"] if os.environ.get("TERM"): if _iscommand("links"): register("links", None, GenericBrowser("links '%s'")) if _iscommand("lynx"): register("lynx", None, GenericBrowser("lynx '%s'")) if _iscommand("w3m"): register("w3m", None, GenericBrowser("w3m '%s'")) if os.environ.get("DISPLAY"): _tryorder = ["galeon", "skipstone", "mozilla-firefox", "mozilla-firebird", "mozilla", "netscape", "kfm", "grail"] + _tryorder for browser in ("mozilla-firefox", "mozilla-firebird", "mozilla", "netscape"): if _iscommand(browser): register(browser, None, Netscape(browser)) if _iscommand("mosaic"): register("mosaic", None, GenericBrowser( "mosaic '%s' >/dev/null &")) if _iscommand("galeon"): register("galeon", None, Galeon("galeon")) if _iscommand("skipstone"): register("skipstone", None, GenericBrowser( "skipstone '%s' >/dev/null &")) if _iscommand("kfm") or _iscommand("konqueror"): register("kfm", Konqueror, Konqueror()) if _iscommand("grail"): register("grail", Grail, None) class InternetConfig: def open(self, url, new=0, autoraise=1): ic.launchurl(url) def open_new(self, url): self.open(url) | if os.environ.get("DISPLAY"): for browser in ("mozilla-firefox", "firefox", "mozilla-firebird", "firebird", "mozilla", "netscape"): if _iscommand(browser): register(browser, None, Mozilla(browser)) if _iscommand("gconftool-2"): gc = 'gconftool-2 -g /desktop/gnome/url-handlers/http/command' out = os.popen(gc) commd = out.read().strip() retncode = out.close() if retncode == None and len(commd) != 0: register("gnome", None, GenericBrowser( commd + " '%s' >/dev/null &")) if _iscommand("kfm") or _iscommand("konqueror"): register("kfm", Konqueror, Konqueror()) for browser in ("galeon", "epiphany"): if _iscommand(browser): register(browser, None, Galeon(browser)) if _iscommand("skipstone"): register("skipstone", None, GenericBrowser("skipstone '%s' &")) if _iscommand("opera"): register("opera", None, Opera("opera")) if _iscommand("mosaic"): register("mosaic", None, GenericBrowser("mosaic '%s' &")) if _iscommand("grail"): register("grail", Grail, None) if os.environ.get("TERM"): if _iscommand("links"): register("links", None, GenericBrowser("links '%s'")) if _iscommand("elinks"): register("elinks", None, Elinks("elinks")) if _iscommand("lynx"): register("lynx", None, GenericBrowser("lynx '%s'")) if _iscommand("w3m"): register("w3m", None, GenericBrowser("w3m '%s'")) | def open_new(self, url): self.open(url) |
_tryorder = ["netscape", "windows-default"] | class WindowsDefault(BaseBrowser): def open(self, url, new=0, autoraise=1): os.startfile(url) return True _tryorder = [] _browsers = {} for browser in ("firefox", "firebird", "mozilla", "netscape", "opera"): if _iscommand(browser): register(browser, None, GenericBrowser(browser + ' %s')) | def open_new(self, url): self.open(url) |
_tryorder = ["internet-config"] register("internet-config", InternetConfig) | class InternetConfig(BaseBrowser): def open(self, url, new=0, autoraise=1): ic.launchurl(url) return True register("internet-config", InternetConfig, update_tryorder=-1) if sys.platform == 'darwin': class MacOSX(BaseBrowser): """Launcher class for Aqua browsers on Mac OS X Optionally specify a browser name on instantiation. Note that this will not work for Aqua browsers if the user has moved the application package after installation. If no browser is specified, the default browser, as specified in the Internet System Preferences panel, will be used. """ def __init__(self, name): self.name = name def open(self, url, new=0, autoraise=1): assert "'" not in url new = int(bool(new)) if self.name == "default": script = _safequote('open location "%s"', url) else: if self.name == "OmniWeb": toWindow = "" else: toWindow = "toWindow %d" % (new - 1) cmd = _safequote('OpenURL "%s"', url) script = '''tell application "%s" activate %s %s end tell''' % (self.name, cmd, toWindow) osapipe = os.popen("osascript", "w") if osapipe is None: return False osapipe.write(script) rc = osapipe.close() return not rc register("MacOSX", None, MacOSX('default'), -1) | def open_new(self, url): self.open(url) |
if sys.platform[:3] == "os2" and _iscommand("netscape.exe"): _tryorder = ["os2netscape"] | if sys.platform[:3] == "os2" and _iscommand("netscape"): _tryorder = [] _browsers = {} | def open_new(self, url): self.open(url) |
GenericBrowser("start netscape.exe %s")) | GenericBrowser("start netscape %s"), -1) | def open_new(self, url): self.open(url) |
_tryorder = os.environ["BROWSER"].split(os.pathsep) for cmd in _tryorder: if not cmd.lower() in _browsers: if _iscommand(cmd.lower()): register(cmd.lower(), None, GenericBrowser( "%s '%%s'" % cmd.lower())) cmd = None del cmd _tryorder = filter(lambda x: x.lower() in _browsers or x.find("%s") > -1, _tryorder) | _userchoices = os.environ["BROWSER"].split(os.pathsep) _userchoices.reverse() for cmdline in _userchoices: if cmdline != '': _synthesize(cmdline, -1) cmdline = None del cmdline del _userchoices | def open_new(self, url): self.open(url) |
s.bind('', self.port) | s.bind(('', self.port)) | def __init__(self, port=None, connection_hook=None): self.connections = [] self.port = port or self.default_port self.connection_hook = connection_hook |
except BClass, v: raise TestFailed except AClass, v: | except BClass, v: | def __init__(self, ignore): |
else: raise TestFailed | def __init__(self, ignore): |
|
last = last + 1 | last = min(self.maxx, last+1) | def _end_of_line(self, y): "Go to the location of the first blank on the given line." last = self.maxx while 1: if ascii.ascii(self.win.inch(y, last)) != ascii.SP: last = last + 1 break elif last == 0: break last = last - 1 return last |
parts = ctype.split('/') if len(parts) > 0: return ctype.split('/')[0] return failobj | if ctype.count('/') <> 1: return failobj return ctype.split('/')[0] | def get_main_type(self, failobj=None): """Return the message's main content type if present.""" missing = [] ctype = self.get_type(missing) if ctype is missing: return failobj parts = ctype.split('/') if len(parts) > 0: return ctype.split('/')[0] return failobj |
parts = ctype.split('/') if len(parts) > 1: return ctype.split('/')[1] return failobj | if ctype.count('/') <> 1: return failobj return ctype.split('/')[1] def get_content_type(self): """Returns the message's content type. The returned string is coerced to lowercase and returned as a ingle string of the form `maintype/subtype'. If there was no Content-Type: header in the message, the default type as give by get_default_type() will be returned. Since messages always have a default type this will always return a value. The current state of RFC standards define a message's default type to be text/plain unless it appears inside a multipart/digest container, in which case it would be message/rfc822. """ missing = [] value = self.get('content-type', missing) if value is missing: return self.get_default_type() return paramre.split(value)[0].lower().strip() def get_content_maintype(self): """Returns the message's main content type. This is the `maintype' part of the string returned by get_content_type(). If no slash is found in the full content type, a ValueError is raised. """ ctype = self.get_content_type() if ctype.count('/') <> 1: raise ValueError, 'No maintype found in: %s' % ctype return ctype.split('/')[0] def get_content_subtype(self): """Returns the message's sub content type. This is the `subtype' part of the string returned by get_content_type(). If no slash is found in the full content type, a ValueError is raised. """ ctype = self.get_content_type() if ctype.count('/') <> 1: raise ValueError, 'No subtype found in: %s' % ctype return ctype.split('/')[1] | def get_subtype(self, failobj=None): """Return the message's content subtype if present.""" missing = [] ctype = self.get_type(missing) if ctype is missing: return failobj parts = ctype.split('/') if len(parts) > 1: return ctype.split('/')[1] return failobj |
ctype must be either "text/plain" or "message/rfc822". The default content type is not stored in the Content-Type: header. """ if ctype not in ('text/plain', 'message/rfc822'): raise ValueError( 'first arg must be either "text/plain" or "message/rfc822"') | ctype should be either "text/plain" or "message/rfc822", although this is not enforced. The default content type is not stored in the Content-Type: header. """ | def set_default_type(self, ctype): """Set the `default' content type. |
import regex prefix_cache = {} def prefix_regex (needle): if prefix_cache.has_key (needle): return prefix_cache[needle] else: reg = needle[-1] for i in range(1,len(needle)): reg = '%c\(%s\)?' % (needle[-(i+1)], reg) reg = regex.compile (reg+'$') prefix_cache[needle] = reg, len(needle) return reg, len(needle) | def pop (self): if self.list: result = self.list[0] del self.list[0] return (1, result) else: return (0, None) |
|
setattr (self, 'install_' + key, scheme[key]) | attrname = 'install_' + key if getattr(self, attrname) is None: setattr(self, attrname, scheme[key]) | def select_scheme (self, name): # it's the caller's problem if they supply a bad name! scheme = INSTALL_SCHEMES[name] for key in ('purelib', 'platlib', 'scripts', 'data'): setattr (self, 'install_' + key, scheme[key]) |
assert isinstance(req, Request) | def open(self, fullurl, data=None): # accept a URL or a Request object if isinstance(fullurl, basestring): req = Request(fullurl, data) else: req = fullurl if data is not None: req.add_data(data) assert isinstance(req, Request) # really only care about interface |
|
def findall(pattern, string, maxsplit=0): | def findall(pattern, string): | def findall(pattern, string, maxsplit=0): """Return a list of all non-overlapping matches in the string. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.""" return _compile(pattern, 0).findall(string, maxsplit) |
return _compile(pattern, 0).findall(string, maxsplit) | return _compile(pattern, 0).findall(string) | def findall(pattern, string, maxsplit=0): """Return a list of all non-overlapping matches in the string. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.""" return _compile(pattern, 0).findall(string, maxsplit) |
"n" * newtabwith) | "n" * newtabwidth) | def set_tabwidth(self, newtabwidth): text = self.text if self.get_tabwidth() != newtabwidth: pixels = text.tk.call("font", "measure", text["font"], "-displayof", text.master, "n" * newtabwith) text.configure(tabs=pixels) |
if not callback: callback = print_line | if not callable(callback): callback = print_line | def retrlines(self, cmd, callback = None): '''Retrieve data in line mode. The argument is a RETR or LIST command. The callback function (2nd argument) is called for each line, with trailing CRLF stripped. This creates a new port for you. print_line() is the default callback.''' if not callback: callback = print_line resp = self.sendcmd('TYPE A') conn = self.transfercmd(cmd) fp = conn.makefile('rb') while 1: line = fp.readline() if self.debugging > 2: print '*retr*', `line` if not line: break if line[-2:] == CRLF: line = line[:-2] elif line[-1:] == '\n': line = line[:-1] callback(line) fp.close() conn.close() return self.voidresp() |
exc_type, exc_val, exc_tb = sys.exc_info() | exc_type, exc_val = sys.exc_info()[:2] | def _run_examples_inner(out, fakeout, examples, globs, verbose, name): import sys, traceback OK, BOOM, FAIL = range(3) NADA = "nothing" stderr = _SpoofOut() failures = 0 for source, want, lineno in examples: if verbose: _tag_out(out, ("Trying", source), ("Expecting", want or NADA)) fakeout.clear() try: exec compile(source, "<string>", "single") in globs got = fakeout.get() state = OK except: # See whether the exception was expected. if want.find("Traceback (innermost last):\n") == 0 or \ want.find("Traceback (most recent call last):\n") == 0: # Only compare exception type and value - the rest of # the traceback isn't necessary. want = want.split('\n')[-2] + '\n' exc_type, exc_val, exc_tb = sys.exc_info() got = traceback.format_exception_only(exc_type, exc_val)[-1] state = OK else: # unexpected exception stderr.clear() traceback.print_exc(file=stderr) state = BOOM if state == OK: if got == want: if verbose: out("ok\n") continue state = FAIL assert state in (FAIL, BOOM) failures = failures + 1 out("*" * 65 + "\n") _tag_out(out, ("Failure in example", source)) out("from line #" + `lineno` + " of " + name + "\n") if state == FAIL: _tag_out(out, ("Expected", want or NADA), ("Got", got)) else: assert state == BOOM _tag_out(out, ("Exception raised", stderr.get())) return failures, len(examples) |
if isinstance(s, StringType): unicode(s, charset.get_output_charset()) elif isinstance(s, UnicodeType): for charset in USASCII, charset, UTF8: try: s = s.encode(charset.get_output_charset()) break except UnicodeError: pass else: assert False, 'Could not encode to utf-8' | if charset <> '8bit': if isinstance(s, StringType): incodec = charset.input_codec or 'us-ascii' ustr = unicode(s, incodec) outcodec = charset.output_codec or 'us-ascii' ustr.encode(outcodec) elif isinstance(s, UnicodeType): for charset in USASCII, charset, UTF8: try: outcodec = charset.output_codec or 'us-ascii' s = s.encode(outcodec) break except UnicodeError: pass else: assert False, 'utf-8 conversion failed' | def append(self, s, charset=None): """Append a string to the MIME header. |
typ, dat = self._simple_command('GETQUOTA', mailbox) | typ, dat = self._simple_command('GETQUOTAROOT', mailbox) | def getquotaroot(self, mailbox): """Get the list of quota roots for the named mailbox. |
""" | Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so other responses should be obtained via <instance>.response('FLAGS') etc. """ | def select(self, mailbox='INBOX', readonly=None): """Select a mailbox. |
try: ignore = posix.fdopen except: raise AttributeError, 'dup() method unavailable' | if not hasattr(posix, 'fdopen'): raise AttributeError, 'dup() method unavailable' | def dup(self): import posix |
try: ignore = posix.fdopen except: raise AttributeError, 'dup() method unavailable' | if not hasattr(posix, 'fdopen'): raise AttributeError, 'dup() method unavailable' | def dup2(self, fd): import posix |
fn = os.path.join(fn, os.pardir, os.pardir, "Doc", "index.html") | fn = os.path.join(fn, os.pardir, os.pardir, "pythlp.chm") | def help_dialog(self, event=None): fn=os.path.join(os.path.abspath(os.path.dirname(__file__)),'help.txt') textView.TextViewer(self.top,'Help',fn) |
def python_docs(self, event=None): self.display_docs(self.help_url) | def python_docs(self, event=None): os.startfile(self.help_url) else: def python_docs(self, event=None): self.display_docs(self.help_url) | def help_dialog(self, event=None): fn=os.path.join(os.path.abspath(os.path.dirname(__file__)),'help.txt') textView.TextViewer(self.top,'Help',fn) |
self.baseFilename = filename | self.baseFilename = os.path.abspath(filename) | def __init__(self, filename, mode="a"): """ Open the specified file and use it as the stream for logging. """ StreamHandler.__init__(self, open(filename, mode)) self.baseFilename = filename self.mode = mode |
return Utils.collapse_rfc2231_value(boundary).strip() | return Utils.collapse_rfc2231_value(boundary).rstrip() | def get_boundary(self, failobj=None): """Return the boundary associated with the payload if present. |
'recv', 'recvfrom', 'send', 'sendall', 'sendto', 'setblocking', | 'sendall', 'setblocking', | def getfqdn(name=''): """Get fully qualified domain name from name. An empty argument is interpreted as meaning the local host. First the hostname returned by gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available, hostname is returned. """ name = name.strip() if not name or name == '0.0.0.0': name = gethostname() try: hostname, aliases, ipaddrs = gethostbyaddr(name) except error: pass else: aliases.insert(0, hostname) for name in aliases: if '.' in name: break else: name = hostname return name |
def __getattr__(self, name): | def _dummy(*args): | def __getattr__(self, name): raise error(9, 'Bad file descriptor') |
__slots__ = ["_sock"] | __slots__ = ["_sock", "send", "recv", "sendto", "recvfrom"] | def __getattr__(self, name): raise error(9, 'Bad file descriptor') |
return self.dict.len() | return len(self.dict) | def __len__(self): return self.dict.len() |
if sys.platform == "darwin": supports_unicode_filenames = True else: supports_unicode_filenames = False | supports_unicode_filenames = False | def realpath(filename): """Return the canonical path of the specified filename, eliminating any |
def_op('RAISE_VARARGS', 130) def_op('CALL_FUNCTION', 131) def_op('MAKE_FUNCTION', 132) def_op('BUILD_SLICE', 133) | def_op('RAISE_VARARGS', 130) def_op('CALL_FUNCTION', 131) def_op('MAKE_FUNCTION', 132) def_op('BUILD_SLICE', 133) def_op('CALL_FUNCTION_VAR', 140) def_op('CALL_FUNCTION_KW', 141) def_op('CALL_FUNCTION_VAR_KW', 142) | def jabs_op(name, op): opname[op] = name hasjabs.append(op) |
self.fp.write("\n%s = %s\n"%(pname, othername)) | self.fp.write("\n_Prop_%s = _Prop_%s\n"%(pname, othername)) | def compileproperty(self, prop): [name, code, what] = prop if code == 'c@#!': # Something silly with plurals. Skip it. return pname = identify(name) if self.namemappers[0].hascode('property', code): # plural forms and such othername, dummy, dummy = self.namemappers[0].findcodename('property', code) if pname == othername: return if self.fp: self.fp.write("\n%s = %s\n"%(pname, othername)) else: if self.fp: self.fp.write("class %s(aetools.NProperty):\n" % pname) self.fp.write('\t"""%s - %s """\n' % (ascii(name), ascii(what[1]))) self.fp.write("\twhich = %s\n" % `code`) self.fp.write("\twant = %s\n" % `what[0]`) self.namemappers[0].addnamecode('property', pname, code) |
self.fp.write("class %s(aetools.NProperty):\n" % pname) | self.fp.write("class _Prop_%s(aetools.NProperty):\n" % pname) | def compileproperty(self, prop): [name, code, what] = prop if code == 'c@#!': # Something silly with plurals. Skip it. return pname = identify(name) if self.namemappers[0].hascode('property', code): # plural forms and such othername, dummy, dummy = self.namemappers[0].findcodename('property', code) if pname == othername: return if self.fp: self.fp.write("\n%s = %s\n"%(pname, othername)) else: if self.fp: self.fp.write("class %s(aetools.NProperty):\n" % pname) self.fp.write('\t"""%s - %s """\n' % (ascii(name), ascii(what[1]))) self.fp.write("\twhich = %s\n" % `code`) self.fp.write("\twant = %s\n" % `what[0]`) self.namemappers[0].addnamecode('property', pname, code) |
self.fp.write("\t'%s' : %s,\n"%(n, n)) | self.fp.write("\t'%s' : _Prop_%s,\n"%(n, n)) | def fillclasspropsandelems(self, cls): [name, code, desc, properties, elements] = cls cname = identify(name) if self.namemappers[0].hascode('class', code) and \ self.namemappers[0].findcodename('class', code)[0] != cname: # This is an other name (plural or so) for something else. Skip. if self.fp and (elements or len(properties) > 1 or (len(properties) == 1 and properties[0][1] != 'c@#!')): if self.verbose: print >>self.verbose, '** Skip multiple %s of %s (code %s)' % (cname, self.namemappers[0].findcodename('class', code)[0], `code`) raise RuntimeError, "About to skip non-empty class" return plist = [] elist = [] superclasses = [] for prop in properties: [pname, pcode, what] = prop if pcode == "c@#^": superclasses.append(what) if pcode == 'c@#!': continue pname = identify(pname) plist.append(pname) |
self.fp.write("\n_propdeclarations = {\n") proplist = self.namemappers[0].getall('property') proplist.sort() for k, v in proplist: self.fp.write("\t%s : %s,\n" % (`k`, v)) self.fp.write("}\n") self.fp.write("\n_compdeclarations = {\n") complist = self.namemappers[0].getall('comparison') complist.sort() for k, v in complist: self.fp.write("\t%s : %s,\n" % (`k`, v)) self.fp.write("}\n") self.fp.write("\n_enumdeclarations = {\n") enumlist = self.namemappers[0].getall('enum') enumlist.sort() for k, v in enumlist: self.fp.write("\t%s : %s,\n" % (`k`, v)) self.fp.write("}\n") | def dumpindex(self): if not self.fp: return self.fp.write("\n#\n# Indices of types declared in this module\n#\n") self.fp.write("_classdeclarations = {\n") classlist = self.namemappers[0].getall('class') classlist.sort() for k, v in classlist: self.fp.write("\t%s : %s,\n" % (`k`, v)) self.fp.write("}\n") self.fp.write("\n_propdeclarations = {\n") proplist = self.namemappers[0].getall('property') proplist.sort() for k, v in proplist: self.fp.write("\t%s : %s,\n" % (`k`, v)) self.fp.write("}\n") self.fp.write("\n_compdeclarations = {\n") complist = self.namemappers[0].getall('comparison') complist.sort() for k, v in complist: self.fp.write("\t%s : %s,\n" % (`k`, v)) self.fp.write("}\n") self.fp.write("\n_enumdeclarations = {\n") enumlist = self.namemappers[0].getall('enum') enumlist.sort() for k, v in enumlist: self.fp.write("\t%s : %s,\n" % (`k`, v)) self.fp.write("}\n") |
|
Pack the values v2, v2, ... according to fmt, write | Pack the values v1, v2, ... according to fmt, write | def pack_into(fmt, buf, offset, *args): """ Pack the values v2, v2, ... according to fmt, write the packed bytes into the writable buffer buf starting at offset. See struct.__doc__ for more on format strings. """ try: o = _cache[fmt] except KeyError: o = _compile(fmt) return o.pack_into(buf, offset, *args) |
langdict = {} | nelangs = [] | def find(domain, localedir=None, languages=None): # Get some reasonable defaults for arguments that were not supplied if localedir is None: localedir = _default_localedir if languages is None: languages = [] for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'): val = os.environ.get(envar) if val: languages = val.split(':') break if 'C' not in languages: languages.append('C') # now normalize and expand the languages langdict = {} for lang in languages: for nelang in _expand_lang(lang): langdict[nelang] = nelang languages = langdict.keys() # select a language for lang in languages: if lang == 'C': break mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain) if os.path.exists(mofile): return mofile return None |
langdict[nelang] = nelang languages = langdict.keys() | if nelang not in nelangs: nelangs.append(nelang) | def find(domain, localedir=None, languages=None): # Get some reasonable defaults for arguments that were not supplied if localedir is None: localedir = _default_localedir if languages is None: languages = [] for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'): val = os.environ.get(envar) if val: languages = val.split(':') break if 'C' not in languages: languages.append('C') # now normalize and expand the languages langdict = {} for lang in languages: for nelang in _expand_lang(lang): langdict[nelang] = nelang languages = langdict.keys() # select a language for lang in languages: if lang == 'C': break mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain) if os.path.exists(mofile): return mofile return None |
for lang in languages: | for lang in nelangs: | def find(domain, localedir=None, languages=None): # Get some reasonable defaults for arguments that were not supplied if localedir is None: localedir = _default_localedir if languages is None: languages = [] for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'): val = os.environ.get(envar) if val: languages = val.split(':') break if 'C' not in languages: languages.append('C') # now normalize and expand the languages langdict = {} for lang in languages: for nelang in _expand_lang(lang): langdict[nelang] = nelang languages = langdict.keys() # select a language for lang in languages: if lang == 'C': break mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain) if os.path.exists(mofile): return mofile return None |
This (mostly) supports the API for Cryptographic Hash Functions (PEP 247). | This supports the API for Cryptographic Hash Functions (PEP 247). | def _strxor(s1, s2): """Utility method. XOR the two strings s1 and s2 (must have same length). """ return "".join(map(lambda x, y: chr(ord(x) ^ ord(y)), s1, s2)) |
self.digest_size = digestmod.digest_size | def __init__(self, key, msg = None, digestmod = None): """Create a new HMAC object. |
|
return HMAC(self) | other = HMAC("") other.digestmod = self.digestmod other.inner = self.inner.copy() other.outer = self.outer.copy() return other | def copy(self): """Return a separate copy of this hashing object. |
def test(): def md5test(key, data, digest): h = HMAC(key, data) assert(h.hexdigest().upper() == digest.upper()) md5test(chr(0x0b) * 16, "Hi There", "9294727A3638BB1C13F48EF8158BFC9D") md5test("Jefe", "what do ya want for nothing?", "750c783e6ab0b503eaa86e310a5db738") md5test(chr(0xAA)*16, chr(0xDD)*50, "56be34521d144c88dbb8c733f0e8b3f6") if __name__ == "__main__": test() | def test(): def md5test(key, data, digest): h = HMAC(key, data) assert(h.hexdigest().upper() == digest.upper()) # Test vectors from the RFC md5test(chr(0x0b) * 16, "Hi There", "9294727A3638BB1C13F48EF8158BFC9D") md5test("Jefe", "what do ya want for nothing?", "750c783e6ab0b503eaa86e310a5db738") md5test(chr(0xAA)*16, chr(0xDD)*50, "56be34521d144c88dbb8c733f0e8b3f6") |
|
if not self._dict['MD5Sum']: | if not self._dict.get('MD5Sum'): | def _archiveOK(self): """Test an archive. It should exist and the MD5 checksum should be correct.""" if not os.path.exists(self.archiveFilename): return 0 if not self._dict['MD5Sum']: sys.stderr.write("Warning: no MD5Sum for %s\n" % self.fullname()) return 1 data = open(self.archiveFilename, 'rb').read() checksum = md5.new(data).hexdigest() return checksum == self._dict['MD5Sum'] |
def configure(self, cnf=None, **kw): """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method keys. """ | def _configure(self, cmd, cnf, kw): """Internal function.""" | def _report_exception(self): """Internal function.""" import sys exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback root = self._root() root.report_callback_exception(exc, val, tb) |
self.tk.call(self._w, 'configure')): | self.tk.call(_flatten((self._w, cmd)))): | def configure(self, cnf=None, **kw): """Configure resources of a widget. |
x = self.tk.split(self.tk.call( self._w, 'configure', '-'+cnf)) | x = self.tk.split( self.tk.call(_flatten((self._w, cmd, '-'+cnf)))) | def configure(self, cnf=None, **kw): """Configure resources of a widget. |
self.tk.call((self._w, 'configure') + self._options(cnf)) | self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) def configure(self, cnf=None, **kw): """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method keys. """ return self._configure('configure', cnf, kw) | def configure(self, cnf=None, **kw): """Configure resources of a widget. |
if cnf is None and not kw: cnf = {} for x in self.tk.split( self.tk.call(self._w, 'itemconfigure', tagOrId)): cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf if type(cnf) == StringType and not kw: x = self.tk.split(self.tk.call( self._w, 'itemconfigure', tagOrId, '-'+cnf)) return (x[0][1:],) + x[1:] self.tk.call((self._w, 'itemconfigure', tagOrId) + self._options(cnf, kw)) | return self._configure(('itemconfigure', tagOrId), cnf, kw) | def itemconfigure(self, tagOrId, cnf=None, **kw): """Configure resources of an item TAGORID. |
if cnf is None and not kw: cnf = {} for x in self.tk.split( self.tk.call(self._w, 'itemconfigure', index)): cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf if type(cnf) == StringType and not kw: x = self.tk.split(self.tk.call( self._w, 'itemconfigure', index, '-'+cnf)) return (x[0][1:],) + x[1:] self.tk.call((self._w, 'itemconfigure', index) + self._options(cnf, kw)) | return self._configure(('itemconfigure', index), cnf, kw) | def itemconfigure(self, index, cnf=None, **kw): """Configure resources of an ITEM. |
if cnf is None and not kw: cnf = {} for x in self.tk.split(self.tk.call( (self._w, 'entryconfigure', index))): cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf if type(cnf) == StringType and not kw: x = self.tk.split(self.tk.call( (self._w, 'entryconfigure', index, '-'+cnf))) return (x[0][1:],) + x[1:] self.tk.call((self._w, 'entryconfigure', index) + self._options(cnf, kw)) | return self._configure(('entryconfigure', index), cnf, kw) | def entryconfigure(self, index, cnf=None, **kw): """Configure a menu item at INDEX.""" if cnf is None and not kw: cnf = {} for x in self.tk.split(self.tk.call( (self._w, 'entryconfigure', index))): cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf if type(cnf) == StringType and not kw: x = self.tk.split(self.tk.call( (self._w, 'entryconfigure', index, '-'+cnf))) return (x[0][1:],) + x[1:] self.tk.call((self._w, 'entryconfigure', index) + self._options(cnf, kw)) |
def image_configure(self, index, cnf={}, **kw): | def image_configure(self, index, cnf=None, **kw): | def image_configure(self, index, cnf={}, **kw): """Configure an embedded image at INDEX.""" if not cnf and not kw: cnf = {} for x in self.tk.split( self.tk.call( self._w, "image", "configure", index)): cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf apply(self.tk.call, (self._w, "image", "configure", index) + self._options(cnf, kw)) |
if not cnf and not kw: cnf = {} for x in self.tk.split( self.tk.call( self._w, "image", "configure", index)): cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf apply(self.tk.call, (self._w, "image", "configure", index) + self._options(cnf, kw)) | return self._configure(('image', 'configure', index), cnf, kw) | def image_configure(self, index, cnf={}, **kw): """Configure an embedded image at INDEX.""" if not cnf and not kw: cnf = {} for x in self.tk.split( self.tk.call( self._w, "image", "configure", index)): cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf apply(self.tk.call, (self._w, "image", "configure", index) + self._options(cnf, kw)) |
def tag_configure(self, tagName, cnf={}, **kw): | def tag_configure(self, tagName, cnf=None, **kw): | def tag_configure(self, tagName, cnf={}, **kw): """Configure a tag TAGNAME.""" if type(cnf) == StringType: x = self.tk.split(self.tk.call( self._w, 'tag', 'configure', tagName, '-'+cnf)) return (x[0][1:],) + x[1:] self.tk.call( (self._w, 'tag', 'configure', tagName) + self._options(cnf, kw)) |
if type(cnf) == StringType: x = self.tk.split(self.tk.call( self._w, 'tag', 'configure', tagName, '-'+cnf)) return (x[0][1:],) + x[1:] self.tk.call( (self._w, 'tag', 'configure', tagName) + self._options(cnf, kw)) | return self._configure(('tag', 'configure', tagName), cnf, kw) | def tag_configure(self, tagName, cnf={}, **kw): """Configure a tag TAGNAME.""" if type(cnf) == StringType: x = self.tk.split(self.tk.call( self._w, 'tag', 'configure', tagName, '-'+cnf)) return (x[0][1:],) + x[1:] self.tk.call( (self._w, 'tag', 'configure', tagName) + self._options(cnf, kw)) |
def window_configure(self, index, cnf={}, **kw): | def window_configure(self, index, cnf=None, **kw): | def window_configure(self, index, cnf={}, **kw): """Configure an embedded window at INDEX.""" if type(cnf) == StringType: x = self.tk.split(self.tk.call( self._w, 'window', 'configure', index, '-'+cnf)) return (x[0][1:],) + x[1:] self.tk.call( (self._w, 'window', 'configure', index) + self._options(cnf, kw)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.