rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if hasattr(self.fp, "fileno"): self.fileno = self.fp.fileno
if hasattr(self.fp, "fileno"): self.fileno = self.fp.fileno else: self.fileno = lambda: None
def __init__(self, fp): self.fp = fp self.read = self.fp.read self.readline = self.fp.readline if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines if hasattr(self.fp, "fileno"): self.fileno = self.fp.fileno if hasattr(self.fp, "__iter__"): self.__iter__ = self.fp.__iter__ if hasattr(self.fp, "next"): s...
outputs[-1:] = \
outputs.extend (
def copy_tree (src, dst, preserve_mode=1, preserve_times=1, preserve_symlinks=0, update=0, verbose=0, dry_run=0): """Copy an entire directory tree 'src' to a new location 'dst'. Both 'src' and 'dst' must be directory names. If 'src' is not a directory, raise DistutilsFileError. If 'dst' does not exist, it is creat...
update, verbose, dry_run)
update, verbose, dry_run))
def copy_tree (src, dst, preserve_mode=1, preserve_times=1, preserve_symlinks=0, update=0, verbose=0, dry_run=0): """Copy an entire directory tree 'src' to a new location 'dst'. Both 'src' and 'dst' must be directory names. If 'src' is not a directory, raise DistutilsFileError. If 'dst' does not exist, it is creat...
s.save_views()
def run(app, s): try: app.start() except KeyboardInterrupt: pass # save the option database s.save_views()
run()
app, sb = build(initialcolor=initialcolor, initfile=initfile, ignore=ignore) run(app, sb) sb.save_views()
def main(): try: opts, args = getopt.getopt( sys.argv[1:], 'hd:i:X', ['database=', 'initfile=', 'ignore', 'help']) except getopt.error, msg: usage(1, msg) if len(args) == 0: initialcolor = None elif len(args) == 1: initialcolor = args[0] else: usage(1) ignore = 0 initfile = os.path.expanduser('~/.pynche') for opt, ar...
linker_so=('%s -mcygwin -mdll -static' %
linker_so=('%s -mcygwin -mdll' %
def __init__ (self, verbose=0, dry_run=0, force=0):
linker_so='%s -mno-cygwin -mdll -static %s'
linker_so='%s -mno-cygwin -mdll %s'
def __init__ (self, verbose=0, dry_run=0, force=0):
Return a list of all keywords, built-in functions and names currently defines in __main__ that match.
Return a list of all keywords, built-in functions and names currently defined in self.namespace that match.
def global_matches(self, text): """Compute matches when text is a simple name.
__main__.__dict__.keys()]:
self.namespace.keys()]:
def global_matches(self, text): """Compute matches when text is a simple name.
evaluatable in the globals of __main__, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are are also considered.)
evaluatable in self.namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are are also considered.)
def attr_matches(self, text): """Compute matches when text contains a dot.
object = eval(expr, __main__.__dict__)
object = eval(expr, self.namespace)
def attr_matches(self, text): """Compute matches when text contains a dot.
s = ''
s = []
def _safe_read(self, amt): """Read the number of bytes requested, compensating for partial reads.
chunk = self.fp.read(amt)
chunk = self.fp.read(min(amt, MAXAMOUNT))
def _safe_read(self, amt): """Read the number of bytes requested, compensating for partial reads.
s += chunk
s.append(chunk)
def _safe_read(self, amt): """Read the number of bytes requested, compensating for partial reads.
return s
return ''.join(s)
def _safe_read(self, amt): """Read the number of bytes requested, compensating for partial reads.
assert sre.split("(b)|(:+)", ":a:b::c") == \ ['', None, ':', 'a', None, ':', '', 'b', None, '', None, '::', 'c']
def bump_num(matchobj): int_value = int(matchobj.group(0)) return str(int_value + 1)
>>> max(tupleids) - min(tupleids)
>>> int(max(tupleids) - min(tupleids))
>>> def f(n):
test(r"""sre.match(r"\%03o" % i, chr(i)) != None""", 1) test(r"""sre.match(r"\%03o0" % i, chr(i)+"0") != None""", 1) test(r"""sre.match(r"\%03o8" % i, chr(i)+"8") != None""", 1) test(r"""sre.match(r"\x%02x" % i, chr(i)) != None""", 1) test(r"""sre.match(r"\x%02x0" % i, chr(i)+"0") != None""", 1) test(r"""sre.match(r"\x...
test(r"""sre.match(r"\%03o" % i, chr(i)) is not None""", 1) test(r"""sre.match(r"\%03o0" % i, chr(i)+"0") is not None""", 1) test(r"""sre.match(r"\%03o8" % i, chr(i)+"8") is not None""", 1) test(r"""sre.match(r"\x%02x" % i, chr(i)) is not None""", 1) test(r"""sre.match(r"\x%02x0" % i, chr(i)+"0") is not None""", 1) tes...
def test(expression, result, exception=None): try: r = eval(expression) except: if exception: if not isinstance(sys.exc_value, exception): print expression, "FAILED" # display name, not actual value if exception is sre.error: print "expected", "sre.error" else: print "expected", exception.__name__ print "got", sys.exc_...
test(r"""sre.match(sre.escape(chr(i)), chr(i)) != None""", 1)
test(r"""sre.match(sre.escape(chr(i)), chr(i)) is not None""", 1)
def bump_num(matchobj): int_value = int(matchobj.group(0)) return str(int_value + 1)
test(r"""pat.match(p) != None""", 1)
test(r"""pat.match(p) is not None""", 1)
def bump_num(matchobj): int_value = int(matchobj.group(0)) return str(int_value + 1)
class _Verbose:
class _Verbose(object):
def _note(self, format, *args): if self.__verbose: format = format % args format = "%s: %s\n" % ( currentThread().getName(), format) _sys.stderr.write(format)
text = text[:75] + ' ...'
textlines = text.splitlines() for i, line in enumerate(textlines): if len(line) > 79: textlines[i] = line[:75] + ' ...' text = '\n'.join(textlines)
def showtip(self, text, parenleft, parenright): """Show the calltip, bind events which will close it and reposition it. """ # truncate overly long calltip if len(text) >= 79: text = text[:75] + ' ...' self.text = text if self.tipwindow or not self.text: return
def test_compresscopy(self): data0 = HAMLET_SCENE data1 = HAMLET_SCENE.swapcase() c0 = zlib.compressobj(zlib.Z_BEST_COMPRESSION) bufs0 = [] bufs0.append(c0.compress(data0)) c1 = c0.copy() bufs1 = bufs0[:] bufs0.append(c0.compress(data0)) bufs0.append(c0.flush()) s0 = ''.join(bufs0) bufs1.append(c1.compress(data1)) ...
if hasattr(zlib.compressobj(), "copy"): def test_compresscopy(self): data0 = HAMLET_SCENE data1 = HAMLET_SCENE.swapcase() c0 = zlib.compressobj(zlib.Z_BEST_COMPRESSION) bufs0 = [] bufs0.append(c0.compress(data0)) c1 = c0.copy() bufs1 = bufs0[:] bufs0.append(c0.compress(data0)) bufs0.append(c0.flush()) s0 = ''.join(b...
def test_compresscopy(self): # Test copying a compression object data0 = HAMLET_SCENE data1 = HAMLET_SCENE.swapcase() c0 = zlib.compressobj(zlib.Z_BEST_COMPRESSION) bufs0 = [] bufs0.append(c0.compress(data0))
alltests.addTest(module.suite())
alltests.addTest(module.test_suite())
def suite(): test_modules = [ 'test_associate', 'test_basics', 'test_compat', 'test_dbobj', 'test_dbshelve', 'test_dbtables', 'test_env_close', 'test_get_none', 'test_join', 'test_lock', 'test_misc', 'test_queue', 'test_recno', 'test_thread', ] alltests = unittest.TestSuite() for name in test_modules: module = __impor...
def _fix_link_args (self, objects, output_dir, takes_libs=0, libraries=None, library_dirs=None): """Typecheck and fix up some of the arguments supplied to the 'link_*' methods and return the fixed values. Specifically: ensure that 'objects' is a list; if output_dir is None, use self.output_dir; ensure that 'libraries'...
def _fix_object_args (self, objects, output_dir): """Typecheck and fix up some arguments supplied to various methods. Specifically: ensure that 'objects' is a list; if output_dir is None, replace with self.output_dir. Return fixed versions of 'objects' and 'output_dir'."""
def _fix_link_args (self, objects, output_dir, takes_libs=0, libraries=None, library_dirs=None): """Typecheck and fix up some of the arguments supplied to the 'link_*' methods and return the fixed values. Specifically: ensure that 'objects' is a list; if output_dir is None, use self.output_dir; ensure that 'libraries'...
if takes_libs: if libraries is None: libraries = self.libraries elif type (libraries) in (ListType, TupleType): libraries = list (libraries) + (self.libraries or []) else: raise TypeError, \ "'libraries' (if supplied) must be a list of strings" if library_dirs is None: library_dirs = self.library_dirs elif type (libra...
return (objects, output_dir) def _fix_lib_args (self, libraries, library_dirs, runtime_library_dirs): """Typecheck and fix up some of the arguments supplied to the 'link_*' methods. Specifically: ensure that all arguments are lists, and augment them with their permanent versions (eg. 'self.libraries' augments 'libra...
def _fix_link_args (self, objects, output_dir, takes_libs=0, libraries=None, library_dirs=None): """Typecheck and fix up some of the arguments supplied to the 'link_*' methods and return the fixed values. Specifically: ensure that 'objects' is a list; if output_dir is None, use self.output_dir; ensure that 'libraries'...
return (objects, output_dir)
raise TypeError, \ "'libraries' (if supplied) must be a list of strings" if library_dirs is None: library_dirs = self.library_dirs elif type (library_dirs) in (ListType, TupleType): library_dirs = list (library_dirs) + (self.library_dirs or []) else: raise TypeError, \ "'library_dirs' (if supplied) must be a list of s...
def _fix_link_args (self, objects, output_dir, takes_libs=0, libraries=None, library_dirs=None): """Typecheck and fix up some of the arguments supplied to the 'link_*' methods and return the fixed values. Specifically: ensure that 'objects' is a list; if output_dir is None, use self.output_dir; ensure that 'libraries'...
once and write the results to sys.stdout after the the
once and write the results to sys.stdout after the
def usage(outfile): outfile.write("""Usage: %s [OPTIONS] <file> [ARGS]
try: value = SyntaxError(msg, (filename, lineno, offset, line)) except: value = msg, (filename, lineno, offset, line)
value = SyntaxError(msg, (filename, lineno, offset, line))
def showsyntaxerror(self, filename=None): """Display the syntax error that just occurred.
except:
except ImportError:
def interact(banner=None, readfunc=None, local=None): """Closely emulate the interactive Python interpreter. This is a backwards compatible interface to the InteractiveConsole class. When readfunc is not specified, it attempts to import the readline module to enable GNU readline if it is available. Arguments (all op...
import thread
import threading
def __init__(self, maxsize=0): """Initialize a queue object with a given maximum size.
import dummy_thread as thread
import dummy_threading as threading
def __init__(self, maxsize=0): """Initialize a queue object with a given maximum size.
self.mutex = thread.allocate_lock() self.esema = thread.allocate_lock() self.esema.acquire() self.fsema = thread.allocate_lock()
self.mutex = threading.Lock() self.not_empty = threading.Condition(self.mutex) self.not_full = threading.Condition(self.mutex)
def __init__(self, maxsize=0): """Initialize a queue object with a given maximum size.
if block:
if not block: return self.put_nowait(item) self.not_full.acquire() try:
def put(self, item, block=True, timeout=None): """Put an item into the queue.
self.fsema.acquire() elif timeout >= 0: delay = 0.0005
while self._full(): self.not_full.wait() else: if timeout < 0: raise ValueError("'timeout' must be a positive number")
def put(self, item, block=True, timeout=None): """Put an item into the queue.
while True: if self.fsema.acquire(0): break
while self._full():
def put(self, item, block=True, timeout=None): """Put an item into the queue.
if remaining <= 0:
if remaining < 0.0:
def put(self, item, block=True, timeout=None): """Put an item into the queue.
delay = min(delay * 2, remaining, .05) _sleep(delay) else: raise ValueError("'timeout' must be a positive number") elif not self.fsema.acquire(0): raise Full self.mutex.acquire() release_fsema = True try: was_empty = self._empty()
self.not_full.wait(remaining)
def put(self, item, block=True, timeout=None): """Put an item into the queue.
if was_empty: self.esema.release() release_fsema = not self._full()
self.not_empty.notify()
def put(self, item, block=True, timeout=None): """Put an item into the queue.
if release_fsema: self.fsema.release() self.mutex.release()
self.not_full.release()
def put(self, item, block=True, timeout=None): """Put an item into the queue.
return self.put(item, False)
self.not_full.acquire() try: if self._full(): raise Full else: self._put(item) self.not_empty.notify() finally: self.not_full.release()
def put_nowait(self, item): """Put an item into the queue without blocking.
if block:
if not block: return self.get_nowait() self.not_empty.acquire() try:
def get(self, block=True, timeout=None): """Remove and return an item from the queue.
self.esema.acquire() elif timeout >= 0: delay = 0.0005
while self._empty(): self.not_empty.wait() else: if timeout < 0: raise ValueError("'timeout' must be a positive number")
def get(self, block=True, timeout=None): """Remove and return an item from the queue.
while 1: if self.esema.acquire(0): break
while self._empty():
def get(self, block=True, timeout=None): """Remove and return an item from the queue.
if remaining <= 0:
if remaining < 0.0:
def get(self, block=True, timeout=None): """Remove and return an item from the queue.
delay = min(delay * 2, remaining, .05) _sleep(delay) else: raise ValueError("'timeout' must be a positive number") elif not self.esema.acquire(0): raise Empty self.mutex.acquire() release_esema = True try: was_full = self._full()
self.not_empty.wait(remaining)
def get(self, block=True, timeout=None): """Remove and return an item from the queue.
if was_full: self.fsema.release() release_esema = not self._empty()
self.not_full.notify() return item
def get(self, block=True, timeout=None): """Remove and return an item from the queue.
if release_esema: self.esema.release() self.mutex.release() return item
self.not_empty.release()
def get(self, block=True, timeout=None): """Remove and return an item from the queue.
return self.get(False)
self.not_empty.acquire() try: if self._empty(): raise Empty else: item = self._get() self.not_full.notify() return item finally: self.not_empty.release()
def get_nowait(self): """Remove and return an item from the queue without blocking.
def remap_element_names(root, name_map): queue = [] for child in root.childNodes: if child.nodeType == ELEMENT: queue.append(child) while queue: node = queue.pop() tagName = node.tagName if name_map.has_key(tagName): name, attrs = name_map[tagName] node._node.name = name for attr, value in attrs.items(): node.setAttrib...
def remap_element_names(root, name_map): queue = [] for child in root.childNodes: if child.nodeType == ELEMENT: queue.append(child) while queue: node = queue.pop() tagName = node.tagName if name_map.has_key(tagName): name, attrs = name_map[tagName] node._node.name = name for attr, value in attrs.items(): node.setAttrib...
"sectionauthor", "seealso",
"sectionauthor", "seealso", "itemize",
def move_elements_by_name(doc, source, dest, name, sep=None): nodes = [] for child in source.childNodes: if child.nodeType == ELEMENT and child.tagName == name: nodes.append(child) for node in nodes: source.removeChild(node) dest.appendChild(node) if sep: dest.appendChild(doc.createTextNode(sep))
"index", "indexii", "indexiii", "indexiv", "setindexsubitem",
"setindexsubitem",
def move_elements_by_name(doc, source, dest, name, sep=None): nodes = [] for child in source.childNodes: if child.nodeType == ELEMENT and child.tagName == name: nodes.append(child) for node in nodes: source.removeChild(node) dest.appendChild(node) if sep: dest.appendChild(doc.createTextNode(sep))
"moduleauthor", "indexterm",
"moduleauthor", "indexterm", "leader",
def move_elements_by_name(doc, source, dest, name, sep=None): nodes = [] for child in source.childNodes: if child.nodeType == ELEMENT and child.tagName == name: nodes.append(child) for node in nodes: source.removeChild(node) dest.appendChild(node) if sep: dest.appendChild(doc.createTextNode(sep))
module_name = entry.getAttribute("name")
module_name = entry.getAttribute("module")
def fixup_refmodindexes_chunk(container): # node is probably a <para>; let's see how often it isn't: if container.tagName != PARA_ELEMENT: bwrite("--- fixup_refmodindexes_chunk(%s)\n" % container) module_entries = find_all_elements(container, "module") if not module_entries: return index_entries = find_all_elements_fro...
remap_element_names(fragment, { "tableii": ("table", {"cols": "2"}), "tableiii": ("table", {"cols": "3"}), "tableiv": ("table", {"cols": "4"}), "lineii": ("row", {}), "lineiii": ("row", {}), "lineiv": ("row", {}), "refmodule": ("module", {"link": "link"}), })
def convert(ifp, ofp): p = esistools.ExtendedEsisBuilder() p.feed(ifp.read()) doc = p.document fragment = p.fragment normalize(fragment) simplify(doc, fragment) handle_labels(doc, fragment) handle_appendix(doc, fragment) fixup_trailing_whitespace(doc, { "abstract": "\n", "title": "", "chapter": "\n\n", "section": "\n\n...
makevars = parsesetup.getmakevars(makefile_in)
def main(): # overridable context prefix = None # settable with -p option exec_prefix = None # settable with -P option extensions = [] path = sys.path odir = '' win = sys.platform[:3] == 'win' # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' ...
def _utc2time(utc): return utc[1]
def _utc2time(utc): t = utc[1] if t < 0: t = t + 0x100000000L return t
def _utc2time(utc): return utc[1]
del os
fp = None try: fp = open(TESTFN, 'w+') except IOError: TMP_TESTFN = os.path.join('/tmp', TESTFN) try: fp = open(TMP_TESTFN, 'w+') TESTFN = TMP_TESTFN del TMP_TESTFN except IOError: print ('WARNING: tests will fail, unable to write to: %s or %s' % (TESTFN, TMP_TESTFN)) if fp is not None: fp.close() try: os.unlink(TESTFN...
def fcmp(x, y): # fuzzy comparison function if type(x) == type(0.0) or type(y) == type(0.0): try: x, y = coerce(x, y) fuzz = (abs(x) + abs(y)) * FUZZ if abs(x-y) <= fuzz: return 0 except: pass elif type(x) == type(y) and type(x) in (type(()), type([])): for i in range(min(len(x), len(y))): outcome = fcmp(x[i], y[i]) if...
return st[stat.ST_MTIME]
return st[stat.ST_ATIME]
def getatime(filename): """Return the last access time of a file, reported by os.stat()""" st = os.stat(filename) return st[stat.ST_MTIME]
self.lines = []
def __init__(self, fp=None, headers=None, outerboundary="", environ=os.environ, keep_blank_values=0, strict_parsing=0): """Constructor. Read multipart/* until last part.
self.lines.append(line)
def read_lines_to_eof(self): """Internal: read lines until EOF.""" while 1: line = self.fp.readline() if not line: self.done = -1 break self.lines.append(line) self.file.write(line)
self.lines.append(line)
def read_lines_to_outerboundary(self): """Internal: read lines until outerboundary.""" next = "--" + self.outerboundary last = next + "--" delim = "" while 1: line = self.fp.readline() if not line: self.done = -1 break self.lines.append(line) if line[:2] == "--": strippedline = string.strip(line) if strippedline == nex...
self.lines.append(line)
def skip_lines(self): """Internal: skip lines until outer boundary if defined.""" if not self.outerboundary or self.done: return next = "--" + self.outerboundary last = next + "--" while 1: line = self.fp.readline() if not line: self.done = -1 break self.lines.append(line) if line[:2] == "--": strippedline = string.str...
home = os.environ['HOME']
home = os.environ.get('HOME')
def addpackage(sitedir, name): global _dirs_in_sys_path if _dirs_in_sys_path is None: _init_pathinfo() reset = 1 else: reset = 0 fullname = os.path.join(sitedir, name) try: f = open(fullname) except IOError: return while 1: dir = f.readline() if not dir: break if dir[0] == '#': continue if dir.startswith("import"): exe...
new_sources.append(base + ".c")
new_sources.append(base + target_ext)
def swig_sources (self, sources):
swig_cmd = [swig, "-python", "-dnone", "-ISWIG"]
swig_cmd = [swig, "-python", "-dnone", "-ISWIG"] if self.swig_cpp: swig_cmd.append ("-c++")
def swig_sources (self, sources):
self.announce ("swigging %s to %s" % (src, obj)) self.spawn(swig_cmd + ["-o", swig_targets[source], source])
target = swig_targets[source] self.announce ("swigging %s to %s" % (source, target)) self.spawn(swig_cmd + ["-o", target, source])
def swig_sources (self, sources):
startofline = tell()
try: startofline = tell() except IOError: startofline = tell = None self.seekable = 0
def readheaders(self): """Read header lines. Read header lines up to the entirely blank line that terminates them. The (normally blank) line that ends the headers is skipped, but not included in the returned list. If a non-header line ends the headers, (which is an error), an attempt is made to backspace over it; it ...
if auth: h.putheader('Authorization', 'Basic %s' % auth)
if proxy_auth: h.putheader('Proxy-Authorization: Basic %s' % proxy_auth) if auth: h.putheader('Authorization: Basic %s' % auth)
def open_https(self, url, data=None): """Use HTTPS protocol.""" import httplib user_passwd = None if isinstance(url, str): 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 user_pass...
See this URL for a description of the basic authentication scheme: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt"""
This function supports Basic authentication only."""
def http_error_401(self, url, fp, errcode, errmsg, headers, data=None): """Error 401 -- authentication required. See this URL for a description of the basic authentication scheme: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt""" if not 'www-authenticate' in headers: URLopener.http_error_default(s...
def http_error_407(self, url, fp, errcode, errmsg, headers, data=None): """Error 407 -- proxy authentication required. This function supports Basic authentication only.""" if not 'proxy-authenticate' in headers: URLopener.http_error_default(self, url, fp, errcode, errmsg, headers) stuff = headers['proxy-authenticate'] ...
def http_error_401(self, url, fp, errcode, errmsg, headers, data=None): """Error 401 -- authentication required. See this URL for a description of the basic authentication scheme: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt""" if not 'www-authenticate' in headers: URLopener.http_error_default(s...
newurl = '//' + host + selector return self.open_https(newurl, data)
newurl = 'https://' + host + selector if data is None: return self.open(newurl) else: return self.open(newurl, data)
def retry_https_basic_auth(self, url, realm, data=None): host, selector = splithost(url) i = host.find('@') + 1 host = host[i:] user, passwd = self.get_user_passwd(host, realm, i) if not (user or passwd): return None host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host newurl = '//' + host + selector...
self.announce ("making hard links in %s..." % base_dir)
try: link = os.link msg = "making hard links in %s..." % base_dir except AttributeError: link = 0 msg = "copying files to %s..." % base_dir self.announce (msg)
def make_release_tree (self, base_dir, files):
if not os.path.exists (dest): self.execute (os.link, (file, dest), "linking %s -> %s" % (file, dest))
if link: if not os.path.exists (dest): self.execute (os.link, (file, dest), "linking %s -> %s" % (file, dest)) else: self.copy_file (file, dest)
def make_release_tree (self, base_dir, files):
class Konquerer: """Controller for the KDE File Manager (kfm, or Konquerer).
class Konqueror: """Controller for the KDE File Manager (kfm, or Konqueror).
def open_new(self, url): self._remote("openURL(%s, new-window)" % url)
for more information on the Konquerer remote-control interface.
for more information on the Konqueror remote-control interface.
def open_new(self, url): self._remote("openURL(%s, new-window)" % url)
register("kfm", Konquerer)
register("kfm", Konqueror)
def open_new(self, url): self._remote("openURL %s" % url)
self.unixsocket = 1
def __init__(self, address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER): """ Initialize a handler.
self.unixsocket = 0
def __init__(self, address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER): """ Initialize a handler.
if not os.isatty(slave_fd): raise TestFailed, "slave_fd is not a tty"
def debug(msg): pass
args['compiler_so'] = compiler
(ccshared,) = sysconfig.get_config_vars('CCSHARED') args['compiler_so'] = compiler + ' ' + ccshared
def build_extensions(self):
self.temp_files.append(prog)
def _link (self, body, headers, include_dirs, libraries, library_dirs, lang): (src, obj) = self._compile(body, headers, include_dirs, lang) prog = os.path.splitext(os.path.basename(src))[0] self.temp_files.append(prog) # XXX should be prog + exe_ext self.compiler.link_executable([obj], prog, libraries=libraries, lib...
self.openedurl = '%s:%s' % (type, url)
def open(self, fullurl, data=None): fullurl = unwrap(fullurl) if self.tempcache and self.tempcache.has_key(fullurl): filename, headers = self.tempcache[fullurl] fp = open(filename, 'rb') return addinfourl(fp, headers, fullurl) type, url = splittype(fullurl) if not type: type = 'file' self.openedurl = '%s:%s' % (type, u...
self.openedurl = url
def retrieve(self, url, filename=None): url = unwrap(url) self.openedurl = url if self.tempcache and self.tempcache.has_key(url): return self.tempcache[url] type, url1 = splittype(url) if not filename and (not type or type == 'file'): try: fp = self.open_local_file(url1) del fp return url2pathname(splithost(url1)[1]), ...
return addinfourl(fp, headers, self.openedurl)
return addinfourl(fp, headers, "http:" + url)
def open_http(self, url, data=None): import httplib if type(url) is type(""): host, selector = splithost(url) user_passwd, host = splituser(host) realhost = host else: host, selector = url urltype, rest = splittype(selector) user_passwd = None if string.lower(urltype) != 'http': realhost = None else: realhost, rest = s...
return addinfourl(fp, noheaders(), self.openedurl)
return addinfourl(fp, noheaders(), "gopher:" + url)
def open_gopher(self, url): import gopherlib host, selector = splithost(url) if not host: raise IOError, ('gopher error', 'no host given') type, selector = splitgophertype(selector) selector, query = splitquery(selector) selector = unquote(selector) if query: query = unquote(query) fp = gopherlib.send_query(selector, q...
noheaders(), self.openedurl)
noheaders(), "ftp:" + url)
def open_ftp(self, url): host, path = splithost(url) if not host: raise IOError, ('ftp error', 'no host given') host, port = splitport(host) user, host = splituser(host) if user: user, passwd = splitpasswd(user) else: passwd = None host = socket.gethostbyname(host) if not port: import ftplib port = ftplib.FTP_PORT else...
return addinfourl(fp, headers, self.openedurl)
return addinfourl(fp, headers, "http:" + url)
def http_error_default(self, url, fp, errcode, errmsg, headers): return addinfourl(fp, headers, self.openedurl)
log.warn(("warngin: no files found matching '%s' " +
log.warn(("warning: no files found matching '%s' " +
def process_template_line (self, line):
self.lineno = self.lineno + string.count(rawdata[i:i], '\n')
self.lineno = self.lineno + string.count(rawdata[i:k], '\n')
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: if i > 0: self.__at_start = 0 if self.nomoretags: data = rawdata[i:n] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = n break res = interesting.search(rawdata, i) if res: j = res.start(0) else: j = n if i ...
method = self.elements.get(tag, (None, None))[1] if method is not None: self.handle_endtag(tag, method) else: self.unknown_endtag(tag)
def finish_endtag(self, tag): if not tag: self.syntax_error('name-less end tag') found = len(self.stack) - 1 if found < 0: self.unknown_endtag(tag) return else: found = -1 for i in range(len(self.stack)): if tag == self.stack[i][0]: found = i if found == -1: self.syntax_error('unopened end tag') method = self.elements....
def maketables():
def maketables(trace=0):
def maketables(): unicode = UnicodeData(UNICODE_DATA) # extract unicode properties dummy = (0, 0, 0, 0) table = [dummy] cache = {0: dummy} index = [0] * len(unicode.chars) # 1) database properties for char in unicode.chars: record = unicode.table[char] if record: # extract database properties category = CATEGORY_NAM...
index1, index2, shift = splitbins(index)
index1, index2, shift = splitbins(index, trace)
def maketables(): unicode = UnicodeData(UNICODE_DATA) # extract unicode properties dummy = (0, 0, 0, 0) table = [dummy] cache = {0: dummy} index = [0] * len(unicode.chars) # 1) database properties for char in unicode.chars: record = unicode.table[char] if record: # extract database properties category = CATEGORY_NAM...
index1, index2, shift = splitbins(decomp_index)
index1, index2, shift = splitbins(decomp_index, trace)
def maketables(): unicode = UnicodeData(UNICODE_DATA) # extract unicode properties dummy = (0, 0, 0, 0) table = [dummy] cache = {0: dummy} index = [0] * len(unicode.chars) # 1) database properties for char in unicode.chars: record = unicode.table[char] if record: # extract database properties category = CATEGORY_NAM...
print len(table), "ctype entries"
def maketables(): unicode = UnicodeData(UNICODE_DATA) # extract unicode properties dummy = (0, 0, 0, 0) table = [dummy] cache = {0: dummy} index = [0] * len(unicode.chars) # 1) database properties for char in unicode.chars: record = unicode.table[char] if record: # extract database properties category = CATEGORY_NAM...
def __init__(self, filename):
def __init__(self, filename, expand=1):
def __init__(self, filename): file = open(filename) table = [None] * 65536 while 1: s = file.readline() if not s: break s = string.split(string.strip(s), ";") char = string.atoi(s[0], 16) table[char] = s
If optional arg trace is true (default false), progress info is printed to sys.stderr.
If optional arg trace is non-zero (default zero), progress info is printed to sys.stderr. The higher the value, the more info you'll get.
def splitbins(t, trace=0): """t, trace=0 -> (t1, t2, shift). Split a table to save space. t is a sequence of ints. This function can be useful to save space if many of the ints are the same. t1 and t2 are lists of ints, and shift is an int, chosen to minimize the combined size of t1 and t2 (in C code), and where fo...
if trace:
if trace > 1:
def dump(t1, t2, shift, bytes): print >>sys.stderr, "%d+%d bins at shift %d; %d bytes" % ( len(t1), len(t2), shift, bytes)
maketables()
maketables(1)
def dump(t1, t2, shift, bytes): print >>sys.stderr, "%d+%d bins at shift %d; %d bytes" % ( len(t1), len(t2), shift, bytes)
gen.startElementNS((ns_uri, "doc"), "ns:doc", {}) gen.endElementNS((ns_uri, "doc"), "ns:doc")
gen.startElementNS((ns_uri, "doc"), "ns1:doc", {}) gen.endElementNS((ns_uri, "doc"), "ns1:doc")
def test_xmlgen_ns(): result = StringIO() gen = XMLGenerator(result) gen.startDocument() gen.startPrefixMapping("ns1", ns_uri) gen.startElementNS((ns_uri, "doc"), "ns:doc", {}) gen.endElementNS((ns_uri, "doc"), "ns:doc") gen.endPrefixMapping("ns1") gen.endDocument() return result.getvalue() == start + ('<ns1:doc xmln...