rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
try: errcode = string.atoi(code) except(ValueError): errcode = -1
def getreply(self): """Get a reply from the server. Returns a tuple consisting of:
On Unix, there are three possible config files: pydistutils.cfg in the Distutils installation directory (ie. where the top-level Distutils __inst__.py file lives), .pydistutils.cfg in the user's home directory, and setup.cfg in the current directory. On Windows and Mac OS, there are two possible config files: pydistut...
There are three possible config files: distutils.cfg in the Distutils installation directory (ie. where the top-level Distutils __inst__.py file lives), a file in the user's home directory named .pydistutils.cfg on Unix and pydistutils.cfg on Windows/Mac, and setup.cfg in the current directory.
def find_config_files (self): """Find as many configuration files as should be processed for this platform, and return a list of filenames in the order in which they should be parsed. The filenames returned are guaranteed to exist (modulo nasty race conditions).
eq(msg.epilogue, '\n\n')
eq(msg.epilogue, '\n')
def test_mondo_message(self): eq = self.assertEqual neq = self.ndiffAssertEqual msg = self._msgobj('crispin-torture.txt') payload = msg.get_payload() eq(type(payload), ListType) eq(len(payload), 12) eq(msg.preamble, None) eq(msg.epilogue, '\n\n') # Probably the best way to verify the message is parsed correctly is to #...
existed = sectdict.has_key(key)
existed = sectdict.has_key(option)
def remove_option(self, section, option): """Remove an option.""" if not section or section == "DEFAULT": sectdict = self.__defaults else: try: sectdict = self.__sections[section] except KeyError: raise NoSectionError(section) existed = sectdict.has_key(key) if existed: del sectdict[key] return existed
del sectdict[key]
del sectdict[option]
def remove_option(self, section, option): """Remove an option.""" if not section or section == "DEFAULT": sectdict = self.__defaults else: try: sectdict = self.__sections[section] except KeyError: raise NoSectionError(section) existed = sectdict.has_key(key) if existed: del sectdict[key] return existed
subconvert(ifp.read(), ofp, table, discards, autoclosing)
subconvert(data, ofp, table, discards, autoclosing)
def convert(ifp, ofp, table={}, discards=(), autoclosing=()): try: subconvert(ifp.read(), ofp, table, discards, autoclosing) except IOError, (err, msg): if err != errno.EPIPE: raise
"calling %s returned %s, not a test" % obj,test
"calling %s returned %s, not a test" % (obj,test)
def loadTestsFromName(self, name, module=None): """Return a suite of all tests cases given a string specifier.
<type 'None'>
<type 'NoneType'>
... def g():
<type 'None'>
<type 'NoneType'>
... def f(self):
file.warn ("exclude (!) doesn't apply to " + "whole directory trees")
manifest.warn ("exclude (!) doesn't apply to " + "whole directory trees")
def read_manifest (self):
file.warn ("can't have multiple words unless first word " + "('%s') is a directory name" % words[0])
manifest.warn ("can't have multiple words unless first word " + "('%s') is a directory name" % words[0])
def read_manifest (self):
file.warn ("no files excluded by '%s'" % pattern)
manifest.warn ("no files excluded by '%s'" % pattern)
def read_manifest (self):
self.sock.send(str)
if self.sock: self.sock.send(str) else: raise SMTPServerDisconnected
def send(self, str): """Send `str' to the server.""" if self.debuglevel > 0: print 'send:', `str` self.sock.send(str)
This method will return normally if the mail is accepted for at least one recipiant .Otherwise it will throw an exception (either SMTPSenderRefused,SMTPRecipientsRefused, or SMTPDataError) That is, if this method does not throw an excception, then someone
This method will return normally if the mail is accepted for at least one recipiant. Otherwise it will throw an exception (either SMTPSenderRefused, SMTPRecipientsRefused, or SMTPDataError) That is, if this method does not throw an exception, then someone
def sendmail(self,from_addr,to_addrs,msg): """ This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : a list of addresses to send this mail to - msg : the message to send.
>>> tolist= [ "one@one.org", ... "two@two.org", ... "three@three.org", ... "four@four.org"]
>>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
def sendmail(self,from_addr,to_addrs,msg): """ This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : a list of addresses to send this mail to - msg : the message to send.
senderr[each]=(code,resp)
senderrs[each]=(code,resp)
def sendmail(self,from_addr,to_addrs,msg): """ This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : a list of addresses to send this mail to - msg : the message to send.
if self.elements is XMLParser.elements: self.__fixelements()
def __init__(self): self.reset() if self.elements is XMLParser.elements: self.__fixelements()
self.syntax_error('reference to unknown entity')
self.syntax_error("reference to unknown entity `&%s;'" % str)
def translate_references(self, data, all = 1): i = 0 while 1: res = amp.search(data, i) if res is None: return data res = ref.match(data, res.start(0)) if res is None: self.syntax_error("bogus `&'") i =i+1 continue i = res.end(0) if data[i - 1] != ';': self.syntax_error("`;' missing after entity/char reference") i = i-...
self.syntax_error('reference to unknown entity')
self.syntax_error("reference to unknown entity `&%s;'" % name)
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 ...
childNodeTypes = (Node.TEXT_NODE, Node.ENTITY_REFERENCE_NODE)
def _getElementsByTagNameNSHelper(parent, nsURI, localName, rc): for node in parent.childNodes: if node.nodeType == Node.ELEMENT_NODE: if ((localName == "*" or node.tagName == localName) and (nsURI == "*" or node.namespaceURI == nsURI)): rc.append(node) _getElementsByTagNameNSHelper(node, nsURI, localName, rc) return r...
childNodeTypes = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.TEXT_NODE, Node.CDATA_SECTION_NODE, Node.ENTITY_REFERENCE_NODE)
def __delitem__(self, attname_or_tuple): node = self[attname_or_tuple] node.unlink() del self._attrs[node.name] del self._attrsNS[(node.namespaceURI, node.localName)] self.length = len(self._attrs)
childNodeTypes = ()
def _get_attributes(self): return AttributeList(self._attrs, self._attrsNS)
childNodeTypes = ()
def writexml(self, writer): writer.write("<!--%s-->" % self.data)
childNodeTypes = ()
def writexml(self, writer): writer.write("<?%s %s?>" % (self.target, self.data))
magic = unpack('<i', buf[:4])[0]
magic = unpack('<i', buf[:4])[0] & MASK
def _parse(self, fp): """Override this method to support alternative .mo formats.""" unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() # Are we big endian or little endian? magic = unpack(...
msgcount &= MASK masteridx &= MASK transidx &= MASK
def _parse(self, fp): """Override this method to support alternative .mo formats.""" unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() # Are we big endian or little endian? magic = unpack(...
mend = moff + mlen
moff &= MASK mend = moff + (mlen & MASK)
def _parse(self, fp): """Override this method to support alternative .mo formats.""" unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() # Are we big endian or little endian? magic = unpack(...
tend = toff + tlen if mend < len(buf) and tend < len(buf):
toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen:
def _parse(self, fp): """Override this method to support alternative .mo formats.""" unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() # Are we big endian or little endian? magic = unpack(...
if ((localName == "*" or node.tagName == localName) and
if ((localName == "*" or node.localName == localName) and
def _getElementsByTagNameNSHelper(parent, nsURI, localName, rc): for node in parent.childNodes: if node.nodeType == Node.ELEMENT_NODE: if ((localName == "*" or node.tagName == localName) and (nsURI == "*" or node.namespaceURI == nsURI)): rc.append(node) _getElementsByTagNameNSHelper(node, nsURI, localName, rc) return r...
_getElementsByTagNameNSHelper(self, namespaceURI, localName, [])
rc = [] _getElementsByTagNameNSHelper(self, namespaceURI, localName, rc) return rc
def getElementsByTagNameNS(self, namespaceURI, localName): _getElementsByTagNameNSHelper(self, namespaceURI, localName, [])
_getElementsByTagNameNSHelper(self, namespaceURI, localName)
rc = [] _getElementsByTagNameNSHelper(self, namespaceURI, localName, rc) return rc
def getElementsByTagNameNS(self, namespaceURI, localName): _getElementsByTagNameNSHelper(self, namespaceURI, localName)
opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vx')
opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vxa')
def main(): checkext = CHECKEXT verbose = VERBOSE maxpage = MAXPAGE roundsize = ROUNDSIZE dumpfile = DUMPFILE restart = 0 norun = 0 try: # Begin SLB 2/24/99: Added -t option here. opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vx') # End SLB 2/24/99 except getopt.error, msg: sys.stdout = sys.stderr print msg p...
if o == '-t': extra_roots.append(a)
if o == '-t': extra_roots.append(a) if o == '-a': nonames = not nonames
def main(): checkext = CHECKEXT verbose = VERBOSE maxpage = MAXPAGE roundsize = ROUNDSIZE dumpfile = DUMPFILE restart = 0 norun = 0 try: # Begin SLB 2/24/99: Added -t option here. opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vx') # End SLB 2/24/99 except getopt.error, msg: sys.stdout = sys.stderr print msg p...
maxpage=maxpage, roundsize=roundsize)
maxpage=maxpage, roundsize=roundsize, nonames=nonames )
def main(): checkext = CHECKEXT verbose = VERBOSE maxpage = MAXPAGE roundsize = ROUNDSIZE dumpfile = DUMPFILE restart = 0 norun = 0 try: # Begin SLB 2/24/99: Added -t option here. opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vx') # End SLB 2/24/99 except getopt.error, msg: sys.stdout = sys.stderr print msg p...
for root in extra_roots: if root[-1] != "/": root = root + "/" c.addroot(root)
for root in extra_roots: if root[-1] != "/": root = root + "/" c.addroot(root, add_to_do = 0)
def main(): checkext = CHECKEXT verbose = VERBOSE maxpage = MAXPAGE roundsize = ROUNDSIZE dumpfile = DUMPFILE restart = 0 norun = 0 try: # Begin SLB 2/24/99: Added -t option here. opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vx') # End SLB 2/24/99 except getopt.error, msg: sys.stdout = sys.stderr print msg p...
def addroot(self, root):
def addroot(self, root, add_to_do = 1):
def addroot(self, root): if root not in self.roots: troot = root scheme, netloc, path, params, query, fragment = \ urlparse.urlparse(root) i = string.rfind(path, "/") + 1 if 0 < i < len(path): path = path[:i] troot = urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) self.roots.append(troot) self.addr...
self.newlink((root, ""), ("<root>", root))
if add_to_do: self.newlink((root, ""), ("<root>", root))
def addroot(self, root): if root not in self.roots: troot = root scheme, netloc, path, params, query, fragment = \ urlparse.urlparse(root) i = string.rfind(path, "/") + 1 if 0 < i < len(path): path = path[:i] troot = urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) self.roots.append(troot) self.addr...
url, local_fragment = url_pair self.name_table[url] = page if local_fragment and local_fragment not in page.getnames(): self.setbad(url_pair, ("Missing name anchor `%s'" % local_fragment)) for info in page.getlinkinfos():
self.name_table[url] = page if local_fragment and local_fragment not in page.getnames(): self.setbad(url_pair, ("Missing name anchor `%s'" % local_fragment)) for info in page.getlinkinfos():
def dopage(self, url_pair):
self.done[url].append(origin)
if origin not in self.done[url]: self.done[url].append(origin)
def newdonelink(self, url, origin): self.done[url].append(origin)
if self.bad.has_key(url): source, rawlink = origin triple = url, rawlink, self.bad[url] self.seterror(source, triple)
def newdonelink(self, url, origin): self.done[url].append(origin)
self.todo[url].append(origin)
if origin not in self.todo[url]: self.todo[url].append(origin)
def newtodolink(self, url, origin):
if path[-1] != os.sep: url = url + '/'
def open_file(self, url): path = urllib.url2pathname(urllib.unquote(url)) if path[-1] != os.sep: url = url + '/' if os.path.isdir(path): indexpath = os.path.join(path, "index.html") if os.path.exists(indexpath): return self.open_file(url + "index.html") try: names = os.listdir(path) except os.error, msg: raise IOError,...
return urllib.FancyURLopener.open_file(self, path)
return urllib.FancyURLopener.open_file(self, url)
def open_file(self, url): path = urllib.url2pathname(urllib.unquote(url)) if path[-1] != os.sep: url = url + '/' if os.path.isdir(path): indexpath = os.path.join(path, "index.html") if os.path.exists(indexpath): return self.open_file(url + "index.html") try: names = os.listdir(path) except os.error, msg: raise IOError,...
sys.stderr.write ("warning: template: %s\n" % msg)
sys.stderr.write ("warning: %s\n" % msg)
def __warn (self, msg): sys.stderr.write ("warning: template: %s\n" % msg)
def process_line(self, line): words = string.split (line) action = words[0] if action in ('include','exclude', 'global-include','global-exclude'): if len (words) < 2:
def process_line (self, line): words = string.split (line) action = words[0] if action in ('include','exclude', 'global-include','global-exclude'): if len (words) < 2: self.warn \ ("invalid template line: " + "'%s' expects <pattern1> <pattern2> ..." % action) return pattern_list = map(convert_path, words[1:]) eli...
def process_line(self, line):
("invalid template line: " + "'%s' expects <pattern1> <pattern2> ..." % action) return pattern_list = map(convert_path, words[1:]) elif action in ('recursive-include','recursive-exclude'): if len (words) < 3:
(("no previously-included files matching '%s' " + "found anywhere in distribution") % pattern) elif action == 'recursive-include': self.debug_print("recursive-include %s %s" % (dir, string.join(pattern_list))) for pattern in pattern_list: if not self.select_pattern (pattern, prefix=dir): self.warn (("no files found ma...
def process_line(self, line):
("invalid template line: " + "'%s' expects <dir> <pattern1> <pattern2> ..." % action) return dir = convert_path(words[1]) pattern_list = map (convert_path, words[2:]) elif action in ('graft','prune'): if len (words) != 2: self.warn \ ("invalid template line: " + "'%s' expects a single <dir_pattern>" % action) return ...
(("no previously-included files matching '%s' " + "found under directory '%s'") % (pattern, dir)) elif action == 'graft': self.debug_print("graft " + dir_pattern) if not self.select_pattern(None, prefix=dir_pattern): self.warn ("no directories found matching '%s'" % dir_pattern) elif action == 'prune': self.debug_pri...
def process_line(self, line):
if iconv_incs: if iconv_libs:
if platform not in ['darwin'] and iconv_incs is not None: if iconv_libs is not None:
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
raise TypeError, 'string payload expected'
raise TypeError, 'string payload expected: %s' % type(payload)
def _handle_text(self, msg): payload = msg.get_payload() if not isinstance(payload, StringType): raise TypeError, 'string payload expected' if self._mangle_from_: payload = fcre.sub('>From ', payload) self._fp.write(payload)
g = self.__class__(s)
g = self.__class__(s, self._mangle_from_, self.__maxheaderlen)
def _handle_multipart(self, msg, isdigest=0): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] for part in msg.get_payload(): s = StringIO() g = self.__class__(s) g(part, unixfrom=0) msgtexts...
def _handle_message_rfc822(self, msg):
def _handle_message_delivery_status(self, msg): blocks = [] for part in msg.get_payload(): s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) g(part, unixfrom=0) text = s.getvalue() lines = text.split('\n') if lines and lines[-1] == '': blocks.append(NL.join(lines[:-1])) else: blocks.appe...
def _handle_message_rfc822(self, msg): s = StringIO() g = self.__class__(s) # A message/rfc822 should contain a scalar payload which is another # Message object. Extract that object, stringify it, and write that # out. g(msg.get_payload(), unixfrom=0) self._fp.write(s.getvalue())
g = self.__class__(s)
g = self.__class__(s, self._mangle_from_, self.__maxheaderlen)
def _handle_message_rfc822(self, msg): s = StringIO() g = self.__class__(s) # A message/rfc822 should contain a scalar payload which is another # Message object. Extract that object, stringify it, and write that # out. g(msg.get_payload(), unixfrom=0) self._fp.write(s.getvalue())
if part.get_main_type('text') == 'text':
maintype = part.get_main_type('text') if maintype == 'text':
def _dispatch(self, msg): for part in msg.walk(): if part.get_main_type('text') == 'text': print >> self, part.get_payload(decode=1) else: print >> self, self._fmt % { 'type' : part.get_type('[no MIME type]'), 'maintype' : part.get_main_type('[no main MIME type]'), 'subtype' : part.get_subtype('[no sub-MIME ...
except IOError, msg:
except (OSError, IOError), msg:
def addrobot(self, root): root = urlparse.urljoin(root, "/") if self.robots.has_key(root): return url = urlparse.urljoin(root, "/robots.txt") self.robots[root] = rp = robotparser.RobotFileParser() self.note(2, "Parsing %s", url) rp.debug = self.verbose > 3 rp.set_url(url) try: rp.read() except IOError, msg: self.note(1...
except IOError, msg:
except (OSError, IOError), msg:
def openpage(self, url_pair): url, fragment = url_pair try: return self.urlopener.open(url) except IOError, msg: msg = self.sanitize(msg) self.note(0, "Error %s", msg) if self.verbose > 0: self.show(" HREF ", url, " from", self.todo[url_pair]) self.setbad(url_pair, msg) return None
self.addheaders = [('User-Agent', server_version)]
self.addheaders = [('User-agent', server_version)]
def __init__(self): server_version = "Python-urllib/%s" % __version__ self.addheaders = [('User-Agent', server_version)] # manage the individual handlers self.handlers = [] self.handle_open = {} self.handle_error = {}
req.add_header('Proxy-Authorization', 'Basic ' + user_pass)
req.add_header('Proxy-authorization', 'Basic ' + user_pass)
def proxy_open(self, req, proxy, type): orig_type = req.get_type() type, r_type = splittype(proxy) host, XXX = splithost(r_type) if '@' in host: user_pass, host = host.split('@', 1) if ':' in user_pass: user, password = user_pass.split(':', 1) user_pass = base64.encodestring('%s:%s' % (unquote(user), unquote(password))...
auth_header = 'Proxy-Authorization'
auth_header = 'Proxy-authorization'
def http_error_401(self, req, fp, code, msg, headers): host = urlparse.urlparse(req.get_full_url())[1] return self.http_error_auth_reqed('www-authenticate', host, req, headers)
for args in self.parent.addheaders: name, value = args
for name, value in self.parent.addheaders: name = name.capitalize()
def do_open(self, http_class, req): host = req.get_host() if not host: raise URLError('no host given')
h.putheader(*args)
h.putheader(name, value)
def do_open(self, http_class, req): host = req.get_host() if not host: raise URLError('no host given')
'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
def open_local_file(self, req): host = req.get_host() file = req.get_selector() localfile = url2pathname(file) stats = os.stat(localfile) size = stats.st_size modified = rfc822.formatdate(stats.st_mtime) mtype = mimetypes.guess_type(file)[0] headers = mimetools.Message(StringIO( 'Content-Type: %s\nContent-Length: %d\nL...
headers += "Content-Type: %s\n" % mtype
headers += "Content-type: %s\n" % mtype
def ftp_open(self, req): host = req.get_host() if not host: raise IOError, ('ftp error', 'no host given') # XXX handle custom username & password try: host = socket.gethostbyname(host) except socket.error, msg: raise URLError(msg) host, port = splitport(host) if port is None: port = ftplib.FTP_PORT path, attrs = splita...
headers += "Content-Length: %d\n" % retrlen
headers += "Content-length: %d\n" % retrlen
def ftp_open(self, req): host = req.get_host() if not host: raise IOError, ('ftp error', 'no host given') # XXX handle custom username & password try: host = socket.gethostbyname(host) except socket.error, msg: raise URLError(msg) host, port = splitport(host) if port is None: port = ftplib.FTP_PORT path, attrs = splita...
y = _reconstruct(x, reductor(), 1)
y = _reconstruct(x, reductor(), 1, memo)
def deepcopy(x, memo = None): """Deep copy operation on arbitrary Python objects. See the module's __doc__ string for more info. """ if memo is None: memo = {} d = id(x) if memo.has_key(d): return memo[d] try: copierfunction = _deepcopy_dispatch[type(x)] except KeyError: try: copier = x.__deepcopy__ except AttributeE...
def _reconstruct(x, info, deep):
def _reconstruct(x, info, deep, memo=None):
def _reconstruct(x, info, deep): if isinstance(info, str): return x assert isinstance(info, tuple) n = len(info) assert n in (2, 3) callable, args = info[:2] if n > 2: state = info[2] else: state = {} if deep: args = deepcopy(args) y = callable(*args) if state: if deep: state = deepcopy(state) y.__dict__.update(state) ...
args = deepcopy(args)
args = deepcopy(args, memo)
def _reconstruct(x, info, deep): if isinstance(info, str): return x assert isinstance(info, tuple) n = len(info) assert n in (2, 3) callable, args = info[:2] if n > 2: state = info[2] else: state = {} if deep: args = deepcopy(args) y = callable(*args) if state: if deep: state = deepcopy(state) y.__dict__.update(state) ...
state = deepcopy(state)
state = deepcopy(state, memo)
def _reconstruct(x, info, deep): if isinstance(info, str): return x assert isinstance(info, tuple) n = len(info) assert n in (2, 3) callable, args = info[:2] if n > 2: state = info[2] else: state = {} if deep: args = deepcopy(args) y = callable(*args) if state: if deep: state = deepcopy(state) y.__dict__.update(state) ...
raise error, "illegal range"
raise error, "bad character range"
def _parse(source, state): # parse a simple pattern subpattern = SubPattern(state) while 1: if source.next in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if state.flags & SRE_FLAG_VERBOSE: # skip whitespace and comments if this in WHITESPACE: continue if this ==...
if max < min: raise error, "bad repeat interval"
def _parse(source, state): # parse a simple pattern subpattern = SubPattern(state) while 1: if source.next in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if state.flags & SRE_FLAG_VERBOSE: # skip whitespace and comments if this in WHITESPACE: continue if this ==...
raise error, "illegal character in group name"
raise error, "bad character in group name"
def _parse(source, state): # parse a simple pattern subpattern = SubPattern(state) while 1: if source.next in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if state.flags & SRE_FLAG_VERBOSE: # skip whitespace and comments if this in WHITESPACE: continue if this ==...
if char is None or char == ")":
if char is None: raise error, "unexpected end of pattern" if char == ")":
def _parse(source, state): # parse a simple pattern subpattern = SubPattern(state) while 1: if source.next in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if state.flags & SRE_FLAG_VERBOSE: # skip whitespace and comments if this in WHITESPACE: continue if this ==...
raise error, "illegal character in group name"
raise error, "bad character in group name"
def parse_template(source, pattern): # parse 're' replacement string into list of literals and # group references s = Tokenizer(source) p = [] a = p.append while 1: this = s.get() if this is None: break # end of replacement string if this and this[0] == "\\": # group if this == "\\g": name = "" if s.match("<"): while 1...
def __init__(self, master=None): """Construct a variable with an optional MASTER as master widget. The variable is named PY_VAR_number in Tcl.
def __init__(self, master=None, value=None, name=None): """Construct a variable MASTER can be given as master widget. VALUE is an optional value (defaults to "") NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained.
def __init__(self, master=None): """Construct a variable with an optional MASTER as master widget. The variable is named PY_VAR_number in Tcl. """ global _varnum if not master: master = _default_root self._master = master self._tk = master.tk self._name = 'PY_VAR' + repr(_varnum) _varnum = _varnum + 1 self.set(self._de...
self._name = 'PY_VAR' + repr(_varnum) _varnum = _varnum + 1 self.set(self._default)
if name: self._name = name else: self._name = 'PY_VAR' + `_varnum` _varnum += 1 if value != None: self.set(value) elif not self._tk.call("info", "exists", self._name): self.set(self._default)
def __init__(self, master=None): """Construct a variable with an optional MASTER as master widget. The variable is named PY_VAR_number in Tcl. """ global _varnum if not master: master = _default_root self._master = master self._tk = master.tk self._name = 'PY_VAR' + repr(_varnum) _varnum = _varnum + 1 self.set(self._de...
def __init__(self, master=None):
def __init__(self, master=None, value=None, name=None):
def __init__(self, master=None): """Construct a string variable.
MASTER can be given as master widget.""" Variable.__init__(self, master)
MASTER can be given as master widget. VALUE is an optional value (defaults to "") NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name)
def __init__(self, master=None): """Construct a string variable.
def __init__(self, master=None):
def __init__(self, master=None, value=None, name=None):
def __init__(self, master=None): """Construct an integer variable.
MASTER can be given as master widget.""" Variable.__init__(self, master)
MASTER can be given as master widget. VALUE is an optional value (defaults to 0) NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name)
def __init__(self, master=None): """Construct an integer variable.
def __init__(self, master=None):
def __init__(self, master=None, value=None, name=None):
def __init__(self, master=None): """Construct a float variable.
MASTER can be given as a master widget.""" Variable.__init__(self, master)
MASTER can be given as master widget. VALUE is an optional value (defaults to 0.0) NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name)
def __init__(self, master=None): """Construct a float variable.
_default = "false" def __init__(self, master=None):
_default = False def __init__(self, master=None, value=None, name=None):
def get(self): """Return the value of the variable as a float.""" return getdouble(self._tk.globalgetvar(self._name))
MASTER can be given as a master widget.""" Variable.__init__(self, master)
MASTER can be given as master widget. VALUE is an optional value (defaults to False) NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name)
def __init__(self, master=None): """Construct a boolean variable.
if hasattr(self.db, 'close'): self.db.close() self.db = None
if hasattr(self.dict, 'close'): self.dict.close() self.dict = None
def close(self): if hasattr(self.db, 'close'): self.db.close() self.db = None
dict['prefixname'] = 'mwerks_plugin_config.h'
if hasattr(MacOS, 'runtimemodel') and MacOS.runtimemodel == "carbon": dict['prefixname'] = 'mwerks_carbonplugin_config.h' else: dict['prefixname'] = 'mwerks_plugin_config.h'
def __init__(self, dict, templatelist=TEMPLATELIST, templatename=None): if templatename == None: if hasattr(MacOS, 'runtimemodel'): templatename = 'template-%s'%MacOS.runtimemodel else: templatename = 'template' if os.sep in templatename: templatedir = templatename else: try: packagedir = os.path.split(__file__)[0] exc...
testformat("One million is %i", 1000000, grouping=1, output='One million is 1,000,000',
testformat("One million is %i", 1000000, grouping=1, output='One million is 1%s000%s000' % (sep, sep),
def testformat(formatstr, value, grouping = 0, output=None, func=locale.format): if verbose: if output: print "%s %% %s =? %s ..." %\ (repr(formatstr), repr(value), repr(output)), else: print "%s %% %s works? ..." % (repr(formatstr), repr(value)), result = func(formatstr, value, grouping = grouping) if output and resul...
testformat("--> %10.2f", 1000.0, grouping=1, output='--> 1,000.00',
testformat("--> %10.2f", 1000.0, grouping=1, output='--> 1%s000.00' % sep,
def testformat(formatstr, value, grouping = 0, output=None, func=locale.format): if verbose: if output: print "%s %% %s =? %s ..." %\ (repr(formatstr), repr(value), repr(output)), else: print "%s %% %s works? ..." % (repr(formatstr), repr(value)), result = func(formatstr, value, grouping = grouping) if output and resul...
testformat("%*.*f", (10, 2, 1000.0), grouping=1, output=' 1,000.00',
testformat("%*.*f", (10, 2, 1000.0), grouping=1, output=' 1%s000.00' % sep,
def testformat(formatstr, value, grouping = 0, output=None, func=locale.format): if verbose: if output: print "%s %% %s =? %s ..." %\ (repr(formatstr), repr(value), repr(output)), else: print "%s %% %s works? ..." % (repr(formatstr), repr(value)), result = func(formatstr, value, grouping = grouping) if output and resul...
output='int 1,000 float 1,000.00 str str', func=locale.format_string)
output='int 1%s000 float 1%s000.00 str str' % (sep, sep), func=locale.format_string)
def testformat(formatstr, value, grouping = 0, output=None, func=locale.format): if verbose: if output: print "%s %% %s =? %s ..." %\ (repr(formatstr), repr(value), repr(output)), else: print "%s %% %s works? ..." % (repr(formatstr), repr(value)), result = func(formatstr, value, grouping = grouping) if output and resul...
def __init__(self, sock=None): dispatcher.__init__(self, sock)
def __init__(self, sock=None, map=None): dispatcher.__init__(self, sock, map)
def __init__(self, sock=None): dispatcher.__init__(self, sock) self.out_buffer = ''
def __init__(self, fd): dispatcher.__init__(self)
def __init__(self, fd, map=None): dispatcher.__init__(self, None, map)
def __init__(self, fd): dispatcher.__init__(self) self.connected = True # set it to non-blocking mode flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0) flags = flags | os.O_NONBLOCK fcntl.fcntl(fd, fcntl.F_SETFL, flags) self.set_file(fd)
self.assertRaises(TypeError, islice, xrange(10))
self.assertEqual(list(islice(xrange(10))), range(10)) self.assertEqual(list(islice(xrange(10), None)), range(10)) self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10)) self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2))
def test_islice(self): for args in [ # islice(args) should agree with range(args) (10, 20, 3), (10, 3, 20), (10, 20), (10, 3), (20,) ]: self.assertEqual(list(islice(xrange(100), *args)), range(*args))
import test_itertools
def test_main(verbose=None): import test_itertools suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestBasicOps)) test_support.run_suite(suite) test_support.run_doctest(test_itertools, verbose) # verify reference counting import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [] for i in xr...
test_support.run_doctest(test_itertools, verbose)
def test_main(verbose=None): import test_itertools suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestBasicOps)) test_support.run_suite(suite) test_support.run_doctest(test_itertools, verbose) # verify reference counting import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [] for i in xr...
exts.append( Extension('nis', ['nismodule.c'], libraries = ['nsl']) )
libs = ['nsl'] else: libs = [] exts.append( Extension('nis', ['nismodule.c'], libraries = libs) )
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.append('/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.append( '/usr/local/include' )
if _arguments.has_key('errn'):
if _arguments.get('errn', 0):
def run(self, _no_object=None, _attributes={}, **_arguments): """run: Run the Terminal application Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'core' _subcode = 'oapp'
if _arguments.has_key('errn'):
if _arguments.get('errn', 0):
def quit(self, _no_object=None, _attributes={}, **_arguments): """quit: Quit the Terminal application Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'core' _subcode = 'quit'
if _arguments.has_key('errn'):
if _arguments.get('errn', 0):
def count(self, _object=None, _attributes={}, **_arguments): """count: Return the number of elements of a particular class within an object Required argument: a reference to the objects to be counted Keyword argument _attributes: AppleEvent attribute dictionary Returns: the number of objects counted """ _code = 'core' ...
if _arguments.has_key('errn'):
if _arguments.get('errn', 0):
def do_script(self, _no_object=None, _attributes={}, **_arguments): """do script: Run a UNIX shell script or command Keyword argument with_command: data to be passed to the Terminal application as the command line Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'core' _subcode = 'dosc'
test(r"""sre.match("\%03o" % i, chr(i)) != None""", 1) test(r"""sre.match("\%03o0" % i, chr(i)+"0") != None""", 1) test(r"""sre.match("\%03o8" % i, chr(i)+"8") != None""", 1)
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)
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.search('x*', 'axx').span(0)""", (0, 0)) test(r"""sre.search('x*', 'axx').span()""", (0, 0)) test(r"""sre.search('x+', 'axx').span(0)""", (1, 3)) test(r"""sre.search('x+', 'axx').span()""", (1, 3)) test(r"""sre.search('x', 'aaa')""", None) test(r"""sre.match('a*', 'xxx').span(0)""", (0, 0)) test(r"""sre.ma...
test(r"""sre.search(r'x*', 'axx').span(0)""", (0, 0)) test(r"""sre.search(r'x*', 'axx').span()""", (0, 0)) test(r"""sre.search(r'x+', 'axx').span(0)""", (1, 3)) test(r"""sre.search(r'x+', 'axx').span()""", (1, 3)) test(r"""sre.search(r'x', 'aaa')""", None) test(r"""sre.match(r'a*', 'xxx').span(0)""", (0, 0)) test(r"""...
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_...