rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if line == '.': line = '..'
if line[:1] == '.': line = '.' + line
def post(self, f): resp = self.shortcmd('POST') # Raises error_??? if posting is not allowed if resp[0] <> '3': raise error_reply, resp while 1: line = f.readline() if not line: break if line[-1] == '\n': line = line[:-1] if line == '.': line = '..' self.putline(line) self.putline('.') return self.getresp()
if line == '.': line = '..'
if line[:1] == '.': line = '.' + line
def ihave(self, id, f): resp = self.shortcmd('IHAVE ' + id) # Raises error_??? if the server already has it if resp[0] <> '3': raise error_reply, resp while 1: line = f.readline() if not line: break if line[-1] == '\n': line = line[:-1] if line == '.': line = '..' self.putline(line) self.putline('.') return self.getres...
self.show(name, headers['title'], text, 1)
self.show(name, headers['title'], text)
def do_show(self):
self.show(name, title, text, 1)
self.show(name, title, text)
def do_all(self):
self.show(name, headers['title'], text, 1) print '<P><A HREF="faq.py?req=roulette">Show another one</A>'
self.show(name, headers['title'], text) print "<P>Use `Reload' to show another one."
def do_roulette(self):
self.show(name, headers['title'], text, 1)
self.show(name, headers['title'], text)
def do_recent(self):
self.show(name, title, text, 1)
self.show(name, title, text)
def do_query(self):
self.show(name, title, text)
self.show(name, title, text, edit=0)
def do_edit(self):
self.show(name, title, text)
self.show(name, title, text, edit=0)
def do_review(self):
self.show(name, title, text, 1)
self.show(name, title, text)
def checkin(self):
Title: <INPUT TYPE=text SIZE=70 NAME=title VALUE="%s"<BR>
Title: <INPUT TYPE=text SIZE=70 NAME=title VALUE="%s"><BR>
def showedit(self, name, title, text):
<CODE>Name : </CODE><INPUT TYPE=text SIZE=70 NAME=author VALUE="%s"<BR> <CODE>Email: </CODE><INPUT TYPE=text SIZE=70 NAME=email VALUE="%s"<BR>
<CODE>Name : </CODE><INPUT TYPE=text SIZE=40 NAME=author VALUE="%s"> <BR> <CODE>Email: </CODE><INPUT TYPE=text SIZE=40 NAME=email VALUE="%s"> <BR>
def showedit(self, name, title, text):
return headers, text f = open(name) headers = rfc822.Message(f) text = f.read() f.close()
else: f = open(name) headers = rfc822.Message(f) text = f.read() f.close() self.headers = headers
def read(self, name):
def show(self, name, title, text, edit=0):
def show(self, name, title, text, edit=1):
def show(self, name, title, text, edit=0):
{'message' : 'foo', 'args' : ('foo',)}),
{'message' : 'foo', 'args' : ('foo',), 'filename' : None, 'errno' : None, 'strerror' : None}),
def testAttributes(self): # test that exception attributes are happy
{'message' : '', 'args' : ('foo', 'bar')}),
{'message' : '', 'args' : ('foo', 'bar'), 'filename' : None, 'errno' : 'foo', 'strerror' : 'bar'}),
def testAttributes(self): # test that exception attributes are happy
{'message' : '', 'args' : ('foo', 'bar')}),
{'message' : '', 'args' : ('foo', 'bar'), 'filename' : 'baz', 'errno' : 'foo', 'strerror' : 'bar'}), (IOError, ('foo', 'bar', 'baz', 'quux'), {'message' : '', 'args' : ('foo', 'bar', 'baz', 'quux')}),
def testAttributes(self): # test that exception attributes are happy
if type(klass) != types.ClassType: raise TypeError, "setLoggerClass is expecting a class"
def setLoggerClass(klass): """ Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__() """ if klass != Logger: if type(klass) != types.ClassType: raise TypeError, "setLoggerClass is expecting a ...
if hasattr(os, 'chmod'):
if hasattr(os, 'chmod') and sys.platform[:6] != 'cygwin':
def test_rmtree_errors(self): # filename is guaranteed not to exist filename = tempfile.mktemp() self.assertRaises(OSError, shutil.rmtree, filename)
global template if template == None:
global template, _pid if os.name == 'posix' and _pid and _pid != os.getpid(): template = None if template is None:
def gettempprefix(): global template if template == None: if os.name == 'posix': template = '@' + `os.getpid()` + '.' elif os.name == 'nt': template = '~' + `os.getpid()` + '-' elif os.name == 'mac': template = 'Python-Tmp-' else: template = 'tmp' # XXX might choose a better one return template
template = '@' + `os.getpid()` + '.'
_pid = os.getpid() template = '@' + `_pid` + '.'
def gettempprefix(): global template if template == None: if os.name == 'posix': template = '@' + `os.getpid()` + '.' elif os.name == 'nt': template = '~' + `os.getpid()` + '-' elif os.name == 'mac': template = 'Python-Tmp-' else: template = 'tmp' # XXX might choose a better one return template
if cl.super:
if hasattr(cl, 'super') and cl.super:
def listclasses(self): dir, file = os.path.split(self.file) name, ext = os.path.splitext(file) if os.path.normcase(ext) != ".py": return [] try: dict = pyclbr.readmodule_ex(name, [dir] + sys.path) except ImportError, msg: return [] items = [] self.classes = {} for key, cl in dict.items(): if cl.module == name: s = key ...
self.__current_realm = None
def __init__(self, password_mgr=None): if password_mgr is None: password_mgr = HTTPPasswordMgr() self.passwd = password_mgr self.add_password = self.passwd.add_password self.__current_realm = None # if __current_realm is not None, then the server must have # refused our name/password and is asking for authorization # a...
if self.__current_realm is None: self.__current_realm = realm else: self.__current_realm = realm return None
def retry_http_basic_auth(self, host, req, realm): if self.__current_realm is None: self.__current_realm = realm else: self.__current_realm = realm return None user,pw = self.passwd.find_user_password(realm, host) if pw: raw = "%s:%s" % (user, pw) auth = base64.encodestring(raw).strip() req.add_header(self.header, 'Bas...
auth = base64.encodestring(raw).strip() req.add_header(self.header, 'Basic %s' % auth) resp = self.parent.open(req) self.__current_realm = None return resp else: self.__current_realm = None
auth = 'Basic %s' % base64.encodestring(raw).strip() if req.headers.get(self.auth_header, None) == auth: return None req.add_header(self.auth_header, auth) return self.parent.open(req) else:
def retry_http_basic_auth(self, host, req, realm): if self.__current_realm is None: self.__current_realm = realm else: self.__current_realm = realm return None user,pw = self.passwd.find_user_password(realm, host) if pw: raw = "%s:%s" % (user, pw) auth = base64.encodestring(raw).strip() req.add_header(self.header, 'Bas...
header = 'Authorization'
auth_header = 'Authorization'
def retry_http_basic_auth(self, host, req, realm): if self.__current_realm is None: self.__current_realm = realm else: self.__current_realm = realm return None user,pw = self.passwd.find_user_password(realm, host) if pw: raw = "%s:%s" % (user, pw) auth = base64.encodestring(raw).strip() req.add_header(self.header, 'Bas...
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)
self.__current_realm = None
def __init__(self, passwd=None): if passwd is None: passwd = HTTPPasswordMgr() self.passwd = passwd self.add_password = self.passwd.add_password self.__current_realm = None
authreq = headers.get(self.header, None)
authreq = headers.get(self.auth_header, None)
def http_error_auth_reqed(self, authreq, host, req, headers): authreq = headers.get(self.header, None) if authreq: kind = authreq.split()[0] if kind == 'Digest': return self.retry_http_digest_auth(req, authreq)
req.add_header(self.header, 'Digest %s' % auth)
auth_val = 'Digest %s' % auth if req.headers.get(self.auth_header, None) == auth_val: return None req.add_header(self.auth_header, auth_val)
def retry_http_digest_auth(self, req, auth): token, challenge = auth.split(' ', 1) chal = parse_keqv_list(parse_http_list(challenge)) auth = self.get_authorization(req, chal) if auth: req.add_header(self.header, 'Digest %s' % auth) resp = self.parent.open(req) self.__current_realm = None return resp
self.__current_realm = None
def retry_http_digest_auth(self, req, auth): token, challenge = auth.split(' ', 1) chal = parse_keqv_list(parse_http_list(challenge)) auth = self.get_authorization(req, chal) if auth: req.add_header(self.header, 'Digest %s' % auth) resp = self.parent.open(req) self.__current_realm = None return resp
return None if self.__current_realm is None: self.__current_realm = realm else: self.__current_realm = realm
def get_authorization(self, req, chal): try: realm = chal['realm'] nonce = chal['nonce'] algorithm = chal.get('algorithm', 'MD5') # mod_digest doesn't send an opaque, even though it isn't # supposed to be optional opaque = chal.get('opaque', None) except KeyError: return None
BLOCKSIZE = 8192 while 1: data = source.read(BLOCKSIZE) if not data: break outputfile.write(data)
shutil.copyfileobj(source, outputfile)
def copyfile(self, source, outputfile): """Copy all data between two file objects.
c = cmp(dict1, dict2)
if random.random() < 0.5: c = cmp(dict1, dict2) else: c = dict1 == dict2
def test_one(n): global mutate, dict1, dict2, dict1keys, dict2keys # Fill the dicts without mutating them. mutate = 0 dict1keys = fill_dict(dict1, range(n), n) dict2keys = fill_dict(dict2, range(n), n) # Enable mutation, then compare the dicts so long as they have the # same size. mutate = 1 if verbose: print "trying...
menu.configure(postcommand=self.postwindowsmenu)
WindowList.register_callback(self.postwindowsmenu)
def __init__(self, flist=None, filename=None, key=None, root=None): self.flist = flist root = root or flist.root self.root = root if flist: self.vars = flist.vars self.menubar = Menu(root) self.top = top = self.Toplevel(root, menu=self.menubar) self.vbar = vbar = Scrollbar(top, name='vbar') self.text = text = Text(top,...
import WindowList
def postwindowsmenu(self): # Only called when Windows menu exists # XXX Actually, this Just-In-Time updating interferes # XXX badly with the tear-off feature. It would be better # XXX to update all Windows menus whenever the list of windows # XXX changes. menu = self.menudict['windows'] end = menu.index("end") if end ...
if m[0] != '_' and m != 'config':
if m[0] != '_' and m != 'config' and m != 'configure':
def __init__(self, master=None, cnf={}, **kw): if kw: cnf = _cnfmerge((cnf, kw)) fcnf = {} for k in cnf.keys(): if type(k) == ClassType or k == 'name': fcnf[k] = cnf[k] del cnf[k] self.frame = apply(Frame, (master,), fcnf) self.vbar = Scrollbar(self.frame, name='vbar') self.vbar.pack(side=RIGHT, fill=Y) cnf['name'] = '...
- server response code (e.g. '250', or such, if all goes well) Note: returns -1 if it can't read response code. - server response string corresponding to response code (note : multiline responses converted to a single, multiline string)
- server response code (e.g. '250', or such, if all goes well) Note: returns -1 if it can't read response code. - server response string corresponding to response code (multiline responses are converted to a single, multiline string).
def getreply(self): """Get a reply from the server. Returns a tuple consisting of: - server response code (e.g. '250', or such, if all goes well) Note: returns -1 if it can't read response code. - server response string corresponding to response code (note : multiline responses converted to a single, multiline string)...
"""SMTP 'DATA' command. Sends message data to server.
"""SMTP 'DATA' command -- sends message data to server.
def data(self,msg): """SMTP 'DATA' command. Sends message data to server. Automatically quotes lines beginning with a period per rfc821. """ self.putcmd("data") (code,repl)=self.getreply() if self.debuglevel >0 : print "data:", (code,repl) if code <> 354: return -1 else: self.send(quotedata(msg)) self.send("%s.%s" % (C...
makefile_in = os.path.join(exec_prefix, 'Modules', 'Makefile')
makefile_in = os.path.join(exec_prefix, 'Makefile')
def main(): # overridable context prefix = None # settable with -p option exec_prefix = None # settable with -P option extensions = [] exclude = [] # settable with -x option addn_link = [] # settable with -l, but only honored under Windows. path = sys.p...
ef = codecs.EncodedFile(f, 'utf-16', 'utf-8')
ef = codecs.EncodedFile(f, 'utf-16-le', 'utf-8')
def test_basic(self): f = StringIO.StringIO('\xed\x95\x9c\n\xea\xb8\x80') ef = codecs.EncodedFile(f, 'utf-16', 'utf-8') self.assertEquals(ef.read(), '\xff\xfe\\\xd5\n\x00\x00\xae')
self.compiler = new_compiler ( compiler="msvc",
self.compiler = new_compiler (compiler=self.compiler,
def run (self):
extra_args = ext.extra_compile_args
extra_args = ext.extra_compile_args or []
def build_extensions (self):
extra_args = ext.extra_link_args
extra_args = ext.extra_link_args or []
def build_extensions (self):
xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)),
xmlrpclib.Fault(1, "%s:%s" % (exc_type, exc_value)),
def _marshaled_dispatch(self, data, dispatch_method = None): """Dispatches an XML-RPC method from marshalled (XML) data.
'faultString' : "%s:%s" % (sys.exc_type, sys.exc_value)}
'faultString' : "%s:%s" % (exc_type, exc_value)}
def system_multicall(self, call_list): """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \
if i < 0: return None data[0] = data[0][i+1:]
if i >= 0: data[0] = data[0][i+1:]
def parsedate_tz(data): """Convert a date string to a time tuple. Accounts for military timezones. """ data = data.split() # The FWS after the comma after the day-of-week is optional, so search and # adjust for this. if data[0].endswith(',') or data[0].lower() in _daynames: # There's a dayname here. Skip it del data[0...
tester('ntpath.splitdrive("\\\\conky\\mountpoint\\foo\\bar")', ('\\\\conky\\mountpoint', '\\foo\\bar'))
tester('ntpath.splitunc("\\\\conky\\mountpoint\\foo\\bar")', ('\\\\conky\\mountpoint', '\\foo\\bar'))
def tester(fn, wantResult): fn = string.replace(fn, "\\", "\\\\") gotResult = eval(fn) if wantResult != gotResult: print "error!" print "evaluated: " + str(fn) print "should be: " + str(wantResult) print " returned: " + str(gotResult) print "" global errors errors = errors + 1
tester('ntpath.splitdrive("//conky/mountpoint/foo/bar")', ('//conky/mountpoint', '/foo/bar'))
tester('ntpath.splitunc("//conky/mountpoint/foo/bar")', ('//conky/mountpoint', '/foo/bar'))
def tester(fn, wantResult): fn = string.replace(fn, "\\", "\\\\") gotResult = eval(fn) if wantResult != gotResult: print "error!" print "evaluated: " + str(fn) print "should be: " + str(wantResult) print " returned: " + str(gotResult) print "" global errors errors = errors + 1
tester('ntpath.split("\\\\conky\\mountpoint\\")', ('\\\\conky\\mountpoint\\', ''))
tester('ntpath.split("\\\\conky\\mountpoint\\")', ('\\\\conky\\mountpoint', ''))
def tester(fn, wantResult): fn = string.replace(fn, "\\", "\\\\") gotResult = eval(fn) if wantResult != gotResult: print "error!" print "evaluated: " + str(fn) print "should be: " + str(wantResult) print " returned: " + str(gotResult) print "" global errors errors = errors + 1
tester('ntpath.split("//conky/mountpoint/")', ('//conky/mountpoint/', ''))
tester('ntpath.split("//conky/mountpoint/")', ('//conky/mountpoint', ''))
def tester(fn, wantResult): fn = string.replace(fn, "\\", "\\\\") gotResult = eval(fn) if wantResult != gotResult: print "error!" print "evaluated: " + str(fn) print "should be: " + str(wantResult) print " returned: " + str(gotResult) print "" global errors errors = errors + 1
if name in ('os2', ):
if name in ('os2', 'nt', 'dos'):
def _execvpe(file, args, env = None): if env: func = execve argrest = (args, env) else: func = execv argrest = (args,) env = environ global _notfound head, tail = path.split(file) if head: apply(func, (file,) + argrest) return if env.has_key('PATH'): envpath = env['PATH'] else: envpath = defpath import string PATH = st...
key = string.upper(key)
def __setitem__(self, key, item): key = string.upper(key) putenv(key, item) self.data[key] = item
def __getitem__(self, key): return self.data[string.upper(key)] else: class _Environ(UserDict.UserDict): def __init__(self, environ): UserDict.UserDict.__init__(self) self.data = environ def __getinitargs__(self): import copy return (copy.copy(self.data),) def __setitem__(self, key, item): putenv(key, item) self.data[...
def __getitem__(self, key): return self.data[string.upper(key)]
from distutils.core import DEBUG
def parse_config_files (self, filenames=None):
from distutils.core import DEBUG
def get_command_obj (self, command, create=1): """Return the command object for 'command'. Normally this object is cached on a previous call to 'get_command_obj()'; if no command object for 'command' is in the cache, then we either create and return it (if 'create' is true) or return None. """ from distutils.core impo...
from distutils.core import DEBUG
def _set_command_options (self, command_obj, option_dict=None): """Set the options for 'command_obj' from 'option_dict'. Basically this means copying elements of a dictionary ('option_dict') to attributes of an instance ('command').
for key, val in dict.items():
for key in dict.keys():
def __fixdict(self, dict): for key, val in dict.items(): if key[:6] == 'start_': key = key[6:] start, end = self.elements.get(key, (None, None)) if start is None: self.elements[key] = val, end elif key[:4] == 'end_': key = key[4:] start, end = self.elements.get(key, (None, None)) if end is None: self.elements[key] = st...
key = key[6:] start, end = self.elements.get(key, (None, None))
tag = key[6:] start, end = self.elements.get(tag, (None, None))
def __fixdict(self, dict): for key, val in dict.items(): if key[:6] == 'start_': key = key[6:] start, end = self.elements.get(key, (None, None)) if start is None: self.elements[key] = val, end elif key[:4] == 'end_': key = key[4:] start, end = self.elements.get(key, (None, None)) if end is None: self.elements[key] = st...
self.elements[key] = val, end
self.elements[tag] = getattr(self, key), end
def __fixdict(self, dict): for key, val in dict.items(): if key[:6] == 'start_': key = key[6:] start, end = self.elements.get(key, (None, None)) if start is None: self.elements[key] = val, end elif key[:4] == 'end_': key = key[4:] start, end = self.elements.get(key, (None, None)) if end is None: self.elements[key] = st...
key = key[4:] start, end = self.elements.get(key, (None, None))
tag = key[4:] start, end = self.elements.get(tag, (None, None))
def __fixdict(self, dict): for key, val in dict.items(): if key[:6] == 'start_': key = key[6:] start, end = self.elements.get(key, (None, None)) if start is None: self.elements[key] = val, end elif key[:4] == 'end_': key = key[4:] start, end = self.elements.get(key, (None, None)) if end is None: self.elements[key] = st...
self.elements[key] = start, val
self.elements[tag] = start, getattr(self, key)
def __fixdict(self, dict): for key, val in dict.items(): if key[:6] == 'start_': key = key[6:] start, end = self.elements.get(key, (None, None)) if start is None: self.elements[key] = val, end elif key[:4] == 'end_': key = key[4:] start, end = self.elements.get(key, (None, None)) if end is None: self.elements[key] = st...
i = 0 while i < len(line) and line[i].isspace(): i = i+1 list.append(' %s\n' % line.strip()) if offset is not None: s = ' ' for c in line[i:offset-1]: if c.isspace(): s = s + c else: s = s + ' ' list.append('%s^\n' % s) value = msg
if line is not None: i = 0 while i < len(line) and line[i].isspace(): i = i+1 list.append(' %s\n' % line.strip()) if offset is not None: s = ' ' for c in line[i:offset-1]: if c.isspace(): s = s + c else: s = s + ' ' list.append('%s^\n' % s) value = msg
def format_exception_only(etype, value): """Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError...
compileargs = r"-Wi [TARGETDIR]Lib\compileall.py -f -x badsyntax [TARGETDIR]Lib"
compileargs = r"-Wi [TARGETDIR]Lib\compileall.py -f -x bad_coding|badsyntax|site-packages [TARGETDIR]Lib"
def add_ui(db): x = y = 50 w = 370 h = 300 title = "[ProductName] Setup" # see "Dialog Style Bits" modal = 3 # visible | modal modeless = 1 # visible track_disk_space = 32 add_data(db, 'ActionText', uisample.ActionText) add_data(db, 'UIText', uisample.UIText) # Bitmaps if not os.path.exists(srcdir+r"\PC\pytho...
except SyntaxWarning, msg: print "got SyntaxWarning as expected"
except SyntaxError, msg: print "got SyntaxError as expected"
def compile_and_catch_warning(text): try: compile(text, "<test code>", "exec") except SyntaxWarning, msg: print "got SyntaxWarning as expected" else: print "expected SyntaxWarning"
print "expected SyntaxWarning"
print "expected SyntaxError"
def compile_and_catch_warning(text): try: compile(text, "<test code>", "exec") except SyntaxWarning, msg: print "got SyntaxWarning as expected" else: print "expected SyntaxWarning"
'/usr/lib',
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')
'/lib',
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')
), 'incs': ('db.h',)},
)},
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')
'/usr/lib', '/lib',
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')
find_lib_file = self.compiler.find_library_file
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')
for dbinc in dbd['incs']: db_incs = find_file(dbinc, [], dbd['incdirs']) dblib_dir = find_lib_file(dbd['libdirs'], dblib) if db_incs and dblib_dir: dblib_dir = os.path.dirname(dblib_dir) dblibs = [dblib] raise found
db_incs = find_file('db.h', [], dbd['incdirs']) dblib_dir = find_library_file(self.compiler, dblib, lib_dirs, list(dbd['libdirs'])) if (db_incs or dbkey == std_dbinc) and \ dblib_dir is not None: dblibs = [dblib] raise found
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
library_dirs=[dblib_dir], runtime_library_dirs=[dblib_dir],
library_dirs=dblib_dir, runtime_library_dirs=dblib_dir,
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
try: os.rename(self.baseFilename, dfn) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record)
os.rename(self.baseFilename, dfn)
def doRollover(self): """ Do a rollover, as described in __init__(). """
try: os.rename(self.baseFilename, dfn) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record)
os.rename(self.baseFilename, dfn)
def doRollover(self): """ do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a list of matching filenames, sort them and remove...
print f(2)(5)
class TestFuture(unittest.TestCase): def test_floor_div_operator(self): self.assertEqual(7 // 2, 3) def test_true_div_as_default(self): self.assertAlmostEqual(7 / 2, 3.5) def test_nested_scopes(self): self.assertEqual(nester(), 3) def test_main(): test_support.run_unittest(TestFuture) if __name__ == "__main__": te...
def g(y): return y // x
if self.__at_start:
data = rawdata[i:j] if self.__at_start and space.match(data) is None:
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 ...
data = rawdata[i:j]
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 ...
res = qname.match(tagname)
if self.__use_namespaces: res = qname.match(tagname) else: res = None
def parse_starttag(self, i): rawdata = self.rawdata # i points to start of tag end = endbracketfind.match(rawdata, i+1) if end is None: return -1 tag = starttagmatch.match(rawdata, i) if tag is None or tag.end(0) != end.end(0): self.syntax_error('garbage in starttag') return end.end(0) nstag = tagname = tag.group('tagn...
nattrdict = {} for key, val in attrdict.items(): res = qname.match(key) if res is not None: aprefix, key = res.group('prefix', 'local') if aprefix is None: aprefix = '' ans = None for t, d, nst in self.stack: if d.has_key(aprefix): ans = d[aprefix] if ans is None and aprefix != '': ans = self.__namespaces.get(aprefix) ...
if self.__use_namespaces: nattrdict = {} for key, val in attrdict.items(): res = qname.match(key) if res is not None: aprefix, key = res.group('prefix', 'local') if aprefix is None: aprefix = '' ans = None for t, d, nst in self.stack: if d.has_key(aprefix): ans = d[aprefix] if ans is None and aprefix != '': ans = self....
def parse_starttag(self, i): rawdata = self.rawdata # i points to start of tag end = endbracketfind.match(rawdata, i+1) if end is None: return -1 tag = starttagmatch.match(rawdata, i) if tag is None or tag.end(0) != end.end(0): self.syntax_error('garbage in starttag') return end.end(0) nstag = tagname = tag.group('tagn...
self.assertRaises(ValueError, lambda: bytes([C(-1)])) self.assertRaises(ValueError, lambda: bytes([C(256)]))
self.assertRaises(ValueError, bytes, [C(-1)]) self.assertRaises(ValueError, bytes, [C(256)])
def __index__(self): return self.i
self.assertRaises(TypeError, lambda: bytes(["0"])) self.assertRaises(TypeError, lambda: bytes([0.0])) self.assertRaises(TypeError, lambda: bytes([None])) self.assertRaises(TypeError, lambda: bytes([C()]))
self.assertRaises(TypeError, bytes, ["0"]) self.assertRaises(TypeError, bytes, [0.0]) self.assertRaises(TypeError, bytes, [None]) self.assertRaises(TypeError, bytes, [C()])
def test_constructor_type_errors(self): class C: pass self.assertRaises(TypeError, lambda: bytes(["0"])) self.assertRaises(TypeError, lambda: bytes([0.0])) self.assertRaises(TypeError, lambda: bytes([None])) self.assertRaises(TypeError, lambda: bytes([C()]))
self.assertRaises(ValueError, lambda: bytes([-1])) self.assertRaises(ValueError, lambda: bytes([-sys.maxint])) self.assertRaises(ValueError, lambda: bytes([-sys.maxint-1])) self.assertRaises(ValueError, lambda: bytes([-sys.maxint-2])) self.assertRaises(ValueError, lambda: bytes([-10**100])) self.assertRaises(ValueError...
self.assertRaises(ValueError, bytes, [-1]) self.assertRaises(ValueError, bytes, [-sys.maxint]) self.assertRaises(ValueError, bytes, [-sys.maxint-1]) self.assertRaises(ValueError, bytes, [-sys.maxint-2]) self.assertRaises(ValueError, bytes, [-10**100]) self.assertRaises(ValueError, bytes, [256]) self.assertRaises(ValueE...
def test_constructor_value_errors(self): self.assertRaises(ValueError, lambda: bytes([-1])) self.assertRaises(ValueError, lambda: bytes([-sys.maxint])) self.assertRaises(ValueError, lambda: bytes([-sys.maxint-1])) self.assertRaises(ValueError, lambda: bytes([-sys.maxint-2])) self.assertRaises(ValueError, lambda: bytes(...
def __init__(self, widget): self.widget = widget self.tipwindow = None self.id = None self.x = self.y = 0
keydefs = { '<<paren-open>>': ['<Key-parenleft>'], '<<paren-close>>': ['<Key-parenright>'], '<<check-calltip-cancel>>': ['<KeyRelease>', '<ButtonRelease>'] } windows_keydefs = { }
def __init__(self, widget): self.widget = widget self.tipwindow = None self.id = None self.x = self.y = 0
def showtip(self, text): self.text = text if self.tipwindow or not self.text: return self.widget.see("insert") x, y, cx, cy = self.widget.bbox("insert") x = x + self.widget.winfo_rootx() + 2 y = y + cy + self.widget.winfo_rooty() self.tipwindow = tw = Toplevel(self.widget) tw.wm_overrideredirect(1) tw.wm_geometry("+%d+...
unix_keydefs = { } def __init__(self, editwin): self.editwin = editwin self.text = editwin.text self.calltip = None if hasattr(self.text, "make_calltip_window"): self._make_calltip_window = self.text.make_calltip_window else: self._make_calltip_window = self._make_tk_calltip_window def _make_tk_calltip_window(self): ...
def showtip(self, text): self.text = text if self.tipwindow or not self.text: return self.widget.see("insert") x, y, cx, cy = self.widget.bbox("insert") x = x + self.widget.winfo_rootx() + 2 y = y + cy + self.widget.winfo_rooty() self.tipwindow = tw = Toplevel(self.widget) tw.wm_overrideredirect(1) tw.wm_geometry("+%d+...
class container: def __init__(self): root = Tk() text = self.text = Text(root) text.pack(side=LEFT, fill=BOTH, expand=1) text.insert("insert", "string.split") root.update() self.calltip = CallTip(text)
def test( tests ): failed=[] for t in tests: if get_arg_text(t) != t.__doc__: failed.append(t) print "%s - expected %s, but got %s" % (t, `t.__doc__`, `get_arg_text(t)`) print "%d of %d tests failed" % (len(failed), len(tests))
def hidetip(self): tw = self.tipwindow self.tipwindow = None if tw: tw.destroy()
text.event_add("<<calltip-show>>", "(") text.event_add("<<calltip-hide>>", ")") text.bind("<<calltip-show>>", self.calltip_show) text.bind("<<calltip-hide>>", self.calltip_hide) text.focus_set()
tc = TC() tests = t1, t2, t3, t4, t5, t6, \ tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6
def __init__(self): root = Tk() text = self.text = Text(root) text.pack(side=LEFT, fill=BOTH, expand=1) text.insert("insert", "string.split") root.update() self.calltip = CallTip(text)
def calltip_show(self, event): self.calltip.showtip("Hello world") def calltip_hide(self, event): self.calltip.hidetip() def main(): c=container() if __name__=='__main__': main()
test(tests)
def calltip_show(self, event): self.calltip.showtip("Hello world")
print "open", askopenfilename(filetypes=[("all files", "*")]).encode(enc) print "saveas", asksaveasfilename().encode(enc)
def askdirectory (**options): "Ask for a directory, and return the file name" return Directory(**options).show()
extern int _QdRGB_Convert(PyObject *, RGBColorPtr *);
extern int _QdRGB_Convert(PyObject *, RGBColorPtr);
#ifdef USE_TOOLBOX_OBJECT_GLUE
PyMac_INIT_TOOLBOX_OBJECT_CONVERT(RGBColorPtr, QdRGB_Convert);
PyMac_INIT_TOOLBOX_OBJECT_CONVERT(RGBColor, QdRGB_Convert);
#ifdef USE_TOOLBOX_OBJECT_GLUE
if hex(-16) != '0xfffffff0': raise TestFailed, 'hex(-16)'
if len(hex(-1)) != len(hex(sys.maxint)): raise TestFailed, 'len(hex(-1))' if hex(-16) not in ('0xfffffff0', '0xfffffffffffffff0'): raise TestFailed, 'hex(-16)'
def f(): pass
longopts.sort()
def getopt(args, shortopts, longopts = []): """getopt(args, options[, long_options]) -> opts, args Parses command line options and parameter list. args is the argument list to be parsed, without the leading reference to the running program. Typically, this means "sys.argv[1:]". shortopts is the string of option let...
for i in range(len(longopts)): if longopts[i].startswith(opt): break else:
possibilities = [o for o in longopts if o.startswith(opt)] if not possibilities:
def long_has_args(opt, longopts): for i in range(len(longopts)): if longopts[i].startswith(opt): break else: raise GetoptError('option --%s not recognized' % opt, opt) # opt is a prefix of longopts[i]; find j s.t. opt is a prefix of # each possibility in longopts[i:j] j = i+1 while j < len(longopts) and longopts[j].sta...
j = i+1 while j < len(longopts) and longopts[j].startswith(opt): j += 1 possibilities = longopts[i:j]
def long_has_args(opt, longopts): for i in range(len(longopts)): if longopts[i].startswith(opt): break else: raise GetoptError('option --%s not recognized' % opt, opt) # opt is a prefix of longopts[i]; find j s.t. opt is a prefix of # each possibility in longopts[i:j] j = i+1 while j < len(longopts) and longopts[j].sta...
exceptions, this sets `sender' to the string that the SMTP refused
exceptions, this sets `sender' to the string that the SMTP refused.
def __init__(self, code, msg): self.smtp_code = code self.smtp_error = msg self.args = (code, msg)
Double leading '.', and change Unix newline '\n', or Mac '\r' into
Double leading '.', and change Unix newline '\\n', or Mac '\\r' into
def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\n', or Mac '\r' into Internet CRLF end-of-line. """ return re.sub(r'(?m)^\.', '..', re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data))
This is the message given by the server in responce to the
This is the message given by the server in response to the
def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\n', or Mac '\r' into Internet CRLF end-of-line. """ return re.sub(r'(?m)^\.', '..', re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data))
will _after you do an EHLO command_, contain the names of the SMTP service extentions this server supports, and their
will _after you do an EHLO command_, contain the names of the SMTP service extensions this server supports, and their
def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\n', or Mac '\r' into Internet CRLF end-of-line. """ return re.sub(r'(?m)^\.', '..', re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data))
Note, all extention names are mapped to lower case in the
Note, all extension names are mapped to lower case in the
def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\n', or Mac '\r' into Internet CRLF end-of-line. """ return re.sub(r'(?m)^\.', '..', re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data))