rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
setupname = os.path.join(self._buildDirname, "setup.py") if not os.path.exists(setupname) and not NO_EXECUTE: return "no setup.py found after unpack of archive"
def installPackageOnly(self, output=None): """Default install method, to be overridden by subclasses""" return "Cannot automatically install package %s" % self.fullname()
def unpackSinglePackage(self, output=None): """Unpack a downloaded package archive.""" filename = os.path.split(self.archiveFilename)[1] for ext, cmd in ARCHIVE_FORMATS: if filename[-len(ext):] == ext: break else: return "unknown extension for archive file: %s" % filename basename = filename[:-len(ext)] cmd = cmd % se...
msg = self.downloadSinglePackage(output)
msg = self.downloadPackageOnly(output)
def installSinglePackage(self, output=None): """Download, unpack and install a single package. If output is given it should be a file-like object and it will receive a log of what happened.""" if not self._dict['Download-URL']: return "%s: This package needs to be installed manually" % _fmtpackagename(self) msg = sel...
msg = self.unpackSinglePackage(output)
msg = self.unpackPackageOnly(output)
def installSinglePackage(self, output=None): """Download, unpack and install a single package. If output is given it should be a file-like object and it will receive a log of what happened.""" if not self._dict['Download-URL']: return "%s: This package needs to be installed manually" % _fmtpackagename(self) msg = sel...
if self._dict.has_key('Pre-install-command'): if self._cmd(output, self._buildDirname, self._dict['Pre-install-command']): return "pre-install %s: running \"%s\" failed" % \ (self.fullname(), self._dict['Pre-install-command']) old_contents = os.listdir(self._db.preferences.installDir) installcmd = self._dict.get('Inst...
return self.installPackageOnly(output) def beforeInstall(self): """Bookkeeping before installation: remember what we have in site-packages""" self._old_contents = os.listdir(self._db.preferences.installDir) def afterInstall(self): """Bookkeeping after installation: interpret any new .pth files that have appeared"""
def installSinglePackage(self, output=None): """Download, unpack and install a single package. If output is given it should be a file-like object and it will receive a log of what happened.""" if not self._dict['Download-URL']: return "%s: This package needs to be installed manually" % _fmtpackagename(self) msg = sel...
self._interpretPthFiles(old_contents, new_contents) if self._dict.has_key('Post-install-command'): if self._cmd(output, self._buildDirname, self._dict['Post-install-command']): return "post-install %s: running \"%s\" failed" % \ (self.fullname(), self._dict['Post-install-command']) return None def _interpretPthFiles(...
def installSinglePackage(self, output=None): """Download, unpack and install a single package. If output is given it should be a file-like object and it will receive a log of what happened.""" if not self._dict['Download-URL']: return "%s: This package needs to be installed manually" % _fmtpackagename(self) msg = sel...
if fn in old_contents:
if fn in self._old_contents:
def _interpretPthFiles(self, old_contents, new_contents): """Evaluate any new .pth files that have appeared after installing""" for fn in new_contents: if fn in old_contents: continue if fn[-4:] != '.pth': continue fullname = os.path.join(self._db.preferences.installDir, fn) f = open(fullname) for line in f.readlines()...
sys.path.append(line)
sys.path.append(line) class PimpPackage_binary(PimpPackage): def unpackPackageOnly(self, output=None): """We don't unpack binary packages until installing""" pass def installPackageOnly(self, output=None): """Install a single source package. If output is given it should be a file-like object and it will receive a l...
def _interpretPthFiles(self, old_contents, new_contents): """Evaluate any new .pth files that have appeared after installing""" for fn in new_contents: if fn in old_contents: continue if fn[-4:] != '.pth': continue fullname = os.path.join(self._db.preferences.installDir, fn) f = open(fullname) for line in f.readlines()...
output = struct.pack("iiiiiii", 0x950412de,
output = struct.pack("Iiiiiii", 0x950412deL,
def generate(): "Return the generated output." global MESSAGES keys = MESSAGES.keys() # the keys are sorted in the .mo file keys.sort() offsets = [] ids = strs = '' for id in keys: # For each string, we need size and file offset. Each string is NUL # terminated; the NUL does not count into the size. offsets.append((le...
f2 = self.tar.extractfile("/S-SPARSE-WITH-NULLS")
f2 = self.tar.extractfile("S-SPARSE-WITH-NULLS")
def test_sparse(self): """Test sparse member extraction. """ if self.sep != "|": f1 = self.tar.extractfile("S-SPARSE") f2 = self.tar.extractfile("/S-SPARSE-WITH-NULLS") self.assert_(f1.read() == f2.read(), "_FileObject failed on sparse file member")
filename = "/0-REGTYPE-TEXT"
filename = "0-REGTYPE-TEXT"
def test_readlines(self): """Test readlines() method of _FileObject. """ if self.sep != "|": filename = "/0-REGTYPE-TEXT" self.tar.extract(filename, dirname()) lines1 = file(os.path.join(dirname(), filename), "rU").readlines() lines2 = self.tar.extractfile(filename).readlines() self.assert_(lines1 == lines2, "_FileObje...
filename = "/0-REGTYPE"
filename = "0-REGTYPE"
def test_seek(self): """Test seek() method of _FileObject, incl. random reading. """ if self.sep != "|": filename = "/0-REGTYPE" self.tar.extract(filename, dirname()) data = file(os.path.join(dirname(), filename), "rb").read()
ssl = socket.ssl(sock, self.key_file, self.cert_file)
realsock = sock if hasattr(sock, "_sock"): realsock = sock._sock ssl = socket.ssl(realsock, self.key_file, self.cert_file)
def connect(self): "Connect to a host on a given (SSL) port."
if sys.platform[:4] != 'java': value = u"%(x)s, %()s" % {'x':u"abc", u''.encode('utf-8'):"def"} else: value = u"%(x)s, %()s" % {'x':u"abc", u'':"def"}
value = u"%(x)s, %()s" % {'x':u"abc", u'':"def"}
def test_fixup(s): s2 = u'\ud800\udc01' test_lecmp(s, s2) s2 = u'\ud900\udc01' test_lecmp(s, s2) s2 = u'\uda00\udc01' test_lecmp(s, s2) s2 = u'\udb00\udc01' test_lecmp(s, s2) s2 = u'\ud800\udd01' test_lecmp(s, s2) s2 = u'\ud900\udd01' test_lecmp(s, s2) s2 = u'\uda00\udd01' test_lecmp(s, s2) s2 = u'\udb00\udd01' test_le...
print 'd=', d
def message(str = "Hello, world!", id = MESSAGE_ID): """Show a simple alert with a text message""" d = GetNewDialog(id, -1) d.SetDialogDefaultItem(1) print 'd=', d tp, h, rect = d.GetDialogItem(2) SetDialogItemText(h, str) while 1: n = ModalDialog(None) if n == 1: break
return [0]*7, None return map(lambda x: ord(x), opr.data), opr
return [0]*9, None options = map(lambda x: ord(x), opr.data) while len(options) < 9: options = options + [0] return options, opr
def getoptions(id): try: opr = GetResource('Popt', id) except (MacOS.Error, Res.Error): return [0]*7, None return map(lambda x: ord(x), opr.data), opr
print 'Created new GUSI option' ngusi_opr = Resource(gusi_opr.data)
ngusi_opr = Resource(newdata)
def edit_preferences(): preff_handle = openpreffile(WRITE) l, sr = getprefpath(PATH_STRINGS_ID) if l == None: message('Cannot find any sys.path resource! (Old python?)') sys.exit(0) fss, dr, fss_changed = getprefdir(DIRECTORY_ID) if fss == None: fss = macfs.FSSpec(os.getcwd()) fss_changed = 1 options, opr = getoptio...
if not opr:
if not gusi_opr:
def edit_applet(name): pref_handle = openpreffile(READ) app_handle = openapplet(name) notfound = '' l, sr = getprefpath(OVERRIDE_PATH_STRINGS_ID) if l == None: notfound = 'path' l, dummy = getprefpath(PATH_STRINGS_ID) if l == None: message('Cannot find any sys.path resource! (Old python?)') sys.exit(0) fss, dr, fss_...
creator, type, delaycons, dummy = getgusioptions(GUSI_ID)
creator, type, delaycons, gusi_opr = getgusioptions(GUSI_ID)
def edit_applet(name): pref_handle = openpreffile(READ) app_handle = openapplet(name) notfound = '' l, sr = getprefpath(OVERRIDE_PATH_STRINGS_ID) if l == None: notfound = 'path' l, dummy = getprefpath(PATH_STRINGS_ID) if l == None: message('Cannot find any sys.path resource! (Old python?)') sys.exit(0) fss, dr, fss_...
pathlist, nfss, options = result
pathlist, nfss, (options, creator, type, delaycons) = result
def edit_applet(name): pref_handle = openpreffile(READ) app_handle = openapplet(name) notfound = '' l, sr = getprefpath(OVERRIDE_PATH_STRINGS_ID) if l == None: notfound = 'path' l, dummy = getprefpath(PATH_STRINGS_ID) if l == None: message('Cannot find any sys.path resource! (Old python?)') sys.exit(0) fss, dr, fss_...
if gusi_opr.HomeResFile == app_handle:
id, type, name = gusi_opr.GetResInfo() if gusi_opr.HomeResFile() == app_handle and id == OVERRIDE_GUSI_ID:
def edit_applet(name): pref_handle = openpreffile(READ) app_handle = openapplet(name) notfound = '' l, sr = getprefpath(OVERRIDE_PATH_STRINGS_ID) if l == None: notfound = 'path' l, dummy = getprefpath(PATH_STRINGS_ID) if l == None: message('Cannot find any sys.path resource! (Old python?)') sys.exit(0) fss, dr, fss_...
gusi_opr = Resource(gusi_opr.data) gusi_opr.AddResource('GU\267I', OVERRIDE_GUSI_ID, '')
ngusi_opr = Resource(newdata) ngusi_opr.AddResource('GU\267I', OVERRIDE_GUSI_ID, '')
def edit_applet(name): pref_handle = openpreffile(READ) app_handle = openapplet(name) notfound = '' l, sr = getprefpath(OVERRIDE_PATH_STRINGS_ID) if l == None: notfound = 'path' l, dummy = getprefpath(PATH_STRINGS_ID) if l == None: message('Cannot find any sys.path resource! (Old python?)') sys.exit(0) fss, dr, fss_...
self.build_scripts = os.path.join(self.build_base, 'scripts')
self.build_scripts = os.path.join(self.build_base, 'scripts-' + sys.version[0:3])
def finalize_options (self):
if not self.have_fork: for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH', 'HTTP_USER_AGENT', 'HTTP_COOKIE'): env.setdefault(k, "")
for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH', 'HTTP_USER_AGENT', 'HTTP_COOKIE'): env.setdefault(k, "")
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.translate_path(scrip...
underline=0,indicatoron=FALSE,highlightthickness=0,
indicatoron=FALSE,highlightthickness=0,
def __init__(self,parent): Frame.__init__(self, parent,borderwidth=2,relief=RIDGE) self.button=Radiobutton(self,padx=5,pady=5,takefocus=FALSE, underline=0,indicatoron=FALSE,highlightthickness=0, borderwidth=0,selectcolor=self.cget('bg')) self.button.pack()
def __init__(self,parent,pageNames,**kw):
def __init__(self,parent,pageNames=[],**kw):
def __init__(self,parent,pageNames,**kw): """ pageNames - a list of strings, each string will be the dictionary key to a page's data, and the name displayed on the page's tab. Should be specified in desired page order. The first page will be the default and first active page. """ Frame.__init__(self, parent, kw) self.g...
def testmod(m, name=None, globs=None, verbose=None, isprivate=None,
def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
def testmod(m, name=None, globs=None, verbose=None, isprivate=None, report=1): """m, name=None, globs=None, verbose=None, isprivate=None, report=1 Test examples in docstrings in functions and classes reachable from module m, starting with m.__doc__. Private names are skipped. Also test examples reachable from dict m...
"""m, name=None, globs=None, verbose=None, isprivate=None, report=1 Test examples in docstrings in functions and classes reachable from module m, starting with m.__doc__. Private names are skipped.
"""m=None, name=None, globs=None, verbose=None, isprivate=None, report=1 Test examples in docstrings in functions and classes reachable from module m (or the current module if m is not supplied), starting with m.__doc__. Private names are skipped.
def testmod(m, name=None, globs=None, verbose=None, isprivate=None, report=1): """m, name=None, globs=None, verbose=None, isprivate=None, report=1 Test examples in docstrings in functions and classes reachable from module m, starting with m.__doc__. Private names are skipped. Also test examples reachable from dict m...
ignores.append(regex.compile(a))
ignores.append(re.compile(a))
def main(): global filedict opts, args = getopt.getopt(sys.argv[1:], 'i:') for o, a in opts: if o == '-i': ignores.append(regex.compile(a)) if not args: args = ['-'] for filename in args: if filename == '-': sys.stdout.write('# Generated by h2py from stdin\n') process(sys.stdin, sys.stdout) else: fp = open(filename, 'r...
i = string.rfind(outfile, '.')
i = outfile.rfind('.')
def main(): global filedict opts, args = getopt.getopt(sys.argv[1:], 'i:') for o, a in opts: if o == '-i': ignores.append(regex.compile(a)) if not args: args = ['-'] for filename in args: if filename == '-': sys.stdout.write('# Generated by h2py from stdin\n') process(sys.stdin, sys.stdout) else: fp = open(filename, 'r...
outfile = string.upper(outfile) outfile = outfile + '.py'
modname = outfile.upper() outfile = modname + '.py'
def main(): global filedict opts, args = getopt.getopt(sys.argv[1:], 'i:') for o, a in opts: if o == '-i': ignores.append(regex.compile(a)) if not args: args = ['-'] for filename in args: if filename == '-': sys.stdout.write('# Generated by h2py from stdin\n') process(sys.stdin, sys.stdout) else: fp = open(filename, 'r...
if p_include.match(line) >= 0: regs = p_include.regs
match = p_include.match(line) if match: regs = match.regs
stmt = 'def %s(%s): return %s\n' % (macro, arg, body)
if not filedict.has_key(filename):
if importable.has_key(filename): outfp.write('import %s\n' % importable[filename]) elif not filedict.has_key(filename):
stmt = 'def %s(%s): return %s\n' % (macro, arg, body)
inclfp = open(dir + '/' + filename, 'r')
inclfp = open(dir + '/' + filename)
stmt = 'def %s(%s): return %s\n' % (macro, arg, body)
try: execv(tempfile.mktemp(), ())
try: execv(tempfile.mktemp(), ('blah',))
def _execvpe(file, args, env=None): if env is not None: 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 PATH = envpat...
code = co.co_code n = len(code) i = 0 lastname = None while i < n: c = code[i] i = i+1 op = ord(c) if op >= dis.HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 if op == IMPORT_NAME: name = lastname = co.co_names[oparg] if not self.badmodules.has_key(lastname): try: self.import_hook(name, m) except Impo...
self.scan_code(co, m)
def load_module(self, fqname, fp, pathname, (suffix, mode, type)): self.msgin(2, "load_module", fqname, fp and "fp", pathname) if type == imp.PKG_DIRECTORY: m = self.load_package(fqname, pathname) self.msgout(2, "load_module ->", m) return m if type == imp.PY_SOURCE: co = compile(fp.read(), pathname, 'exec') elif type ...
Output("self->ob_type->tp_base->tp_dealloc((PyObject *)self);")
Output("%s.tp_dealloc((PyObject *)self);", self.basetype)
def outputDealloc(self): Output() Output("static void %s_dealloc(%s *self)", self.prefix, self.objecttype) OutLbrace() self.outputCleanupStructMembers() if self.basetype: Output("self->ob_type->tp_base->tp_dealloc((PyObject *)self);") elif hasattr(self, 'output_tp_free'): # This is a new-style object with tp_free slot ...
Output("if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;")
if self.basetype: Output("if (%s.tp_new)", self.basetype) OutLbrace() Output("if ( (*%s.tp_init)(_self, _args, _kwds) == NULL) return NULL;", self.basetype) Dedent() Output("} else {") Indent() Output("if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;") OutRbrace() else: Output("if ((_self = type->tp_alloc(ty...
def output_tp_newBody(self): Output("PyObject *_self;"); Output("%s itself;", self.itselftype); Output("char *kw[] = {\"itself\", 0};") Output() Output("if (!PyArg_ParseTupleAndKeywords(_args, _kwds, \"O&\", kw, %s_Convert, &itself)) return NULL;", self.prefix); Output("if ((_self = type->tp_alloc(type, 0)) == NULL) re...
result = pdb.Pdb.trace_dispatch(self, *args) sys.stdout = save_stdout return result
try: return pdb.Pdb.trace_dispatch(self, *args) finally: sys.stdout = save_stdout
def trace_dispatch(self, *args): # Redirect stdout to the given stream. save_stdout = sys.stdout sys.stdout = self.__out # Call Pdb's trace dispatch method. result = pdb.Pdb.trace_dispatch(self, *args) # Restore stdout. sys.stdout = save_stdout return result
print "source", nodelist[-1]
def factor(self, nodelist): elt = nodelist[0] t = elt[0] print "source", nodelist[-1] node = self.com_node(nodelist[-1]) # need to handle (unary op)constant here... if t == token.PLUS: node = UnaryAdd(node) node.lineno = elt[2] elif t == token.MINUS: print node node = UnarySub(node) node.lineno = elt[2] elif t == token...
print node
def factor(self, nodelist): elt = nodelist[0] t = elt[0] print "source", nodelist[-1] node = self.com_node(nodelist[-1]) # need to handle (unary op)constant here... if t == token.PLUS: node = UnaryAdd(node) node.lineno = elt[2] elif t == token.MINUS: print node node = UnarySub(node) node.lineno = elt[2] elif t == token...
(?P<escaped>%(delim)s{2}) | %(delim)s(?P<named>%(id)s) | %(delim)s{(?P<braced>%(id)s)} | (?P<invalid>%(delim)s)
%(delim)s(?: (?P<escaped>%(delim)s) | (?P<named>%(id)s) | {(?P<braced>%(id)s)} | (?P<invalid>) )
def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key]
if froms == '*': froms = theMod.__dict__.keys() for item in froms: (envLocals or envGlobals)[item] = theMod.__dict__[item]
while froms: item = froms[0]; del froms[0] if item == '*': froms = theMod.__dict__.keys() + froms else: try: (envLocals or envGlobals)[item] = theMod.__dict__[item] except KeyError: raise ImportError, ("name '%s' not found in module %s" % (item, theMod.__name__))
def import_module(name, envLocals=None, envGlobals=None, froms=None, inPkg=None): """Primary service routine implementing 'import' with package nesting.""" # The job is divided into a few distinct steps: # # - Look for either an already loaded module or a file to be loaded. # * if neither loaded module nor prospect ...
def read(self, size=-1, chars=-1):
def read(self, size=-1, chars=-1, firstline=False):
def read(self, size=-1, chars=-1):
newchars, decodedbytes = self.decode(data, self.errors)
try: newchars, decodedbytes = self.decode(data, self.errors) except UnicodeDecodeError, exc: if firstline: newchars, decodedbytes = self.decode(data[:exc.start], self.errors) lines = newchars.splitlines(True) if len(lines)<=1: raise else: raise
def read(self, size=-1, chars=-1):
data = self.read(readsize)
data = self.read(readsize, firstline=True)
def readline(self, size=None, keepends=True):
attrs['script_name'] = sys.argv[0]
attrs['script_name'] = os.path.basename(sys.argv[0])
def setup (**attrs): """The gateway to the Distutils: do everything your setup script needs to do, in a highly flexible and user-driven way. Briefly: create a Distribution instance; find and parse config files; parse the command line; run each Distutils command found there, customized by the options supplied to 'setup...
x = self.dict[headerseen] + "\n " + line.strip()
def readheaders(self): """Read header lines.
conn = self.msg.getheader('connection') if conn: conn = conn.lower() self.will_close = conn.find('close') != -1 or \ ( self.version != 11 and \ not self.msg.getheader('keep-alive') ) else: self.will_close = self.version != 11 and \ not self.msg.getheader('keep-alive')
self.will_close = self._check_close()
def begin(self): if self.msg is not None: # we've already started reading the response return
"setparameters%r: returned %r" % (config + result))
"setparameters%r: returned %r" % (config, result))
def test_setparameters(dsp): # Two configurations for testing: # config1 (8-bit, mono, 8 kHz) should work on even the most # ancient and crufty sound card, but maybe not on special- # purpose high-end hardware # config2 (16-bit, stereo, 44.1kHz) should work on all but the # most ancient and crufty ha...
self.sock.send(str)
sendptr = 0 while sendptr < len(str): sendptr = sendptr + self.sock.send(str[sendptr:])
def send(self, str): """Send `str' to the server.""" if self.debuglevel > 0: print 'send:', `str` if self.sock: try: self.sock.send(str) except socket.error: raise SMTPServerDisconnected('Server not connected') else: raise SMTPServerDisconnected('please run connect() first')
ref = Res.FSpOpenResFile(dst, 1)
ref = Res.FSpOpenResFile(dst, 2)
def buildone(template, wrapper, src, dst): buildtools.process(template, wrapper, dst, 1) # write source as a PYC resource into dst ref = Res.FSpOpenResFile(dst, 1) try: Res.UseResFile(ref) py_resource.frompyfile(src, "CGI_MAIN", preload=1) finally: Res.CloseResFile(ref)
d0 = base.replace(minute=3, tzinfo=OperandDependentOffset()) d1 = base.replace(minute=9, tzinfo=OperandDependentOffset()) d2 = base.replace(minute=11, tzinfo=OperandDependentOffset()) for x in d0, d1, d2: for y in d0, d1, d2: got = cmp(x, y) if (x is d0 or x is d1) and (y is d0 or y is d1): expected = 0 elif x is y is ...
if cls is not timetz: d0 = base.replace(minute=3, tzinfo=OperandDependentOffset()) d1 = base.replace(minute=9, tzinfo=OperandDependentOffset()) d2 = base.replace(minute=11, tzinfo=OperandDependentOffset()) for x in d0, d1, d2: for y in d0, d1, d2: got = cmp(x, y) if (x is d0 or x is d1) and (y is d0 or y is d1): expect...
def utcoffset(self, t): if t.minute < 10: return t.minute # d0 and d1 equal after adjustment else: return 59 # d2 off in the weeds
if dt is None or isinstance(dt, time) or dt.tzinfo is None:
if dt is None or dt.tzinfo is None:
def dst(self, dt): if dt is None or isinstance(dt, time) or dt.tzinfo is None: # An exception instead may be sensible here, in one or more of # the cases. return ZERO
user_pass = base64.encode_string(unquote(user_passw)).strip() req.addheader('Proxy-Authorization', user_pass)
user_pass = base64.encodestring(unquote(user_pass)).strip() 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) user_pass = base64.encode_string(unquote(user_passw)).strip() req.addheader('Proxy-Authorization', user_pass) host = unquote(host) req.set...
host = req.get_host()
host = urlparse.urlparse(req.get_full_url())[1]
def do_open(self, http_class, req): host = req.get_host() if not host: raise URLError('no host given')
h.putheader('Content-type', 'application/x-www-form-urlencoded') h.putheader('Content-length', '%d' % len(data))
if not req.headers.has_key('Content-type'): h.putheader('Content-type', 'application/x-www-form-urlencoded') if not req.headers.has_key('Content-length'): h.putheader('Content-length', '%d' % len(data))
def do_open(self, http_class, req): host = req.get_host() if not host: raise URLError('no host given')
if hasattr(x, 'im_func'): x = x.im_func if hasattr(x, 'func_code'): x = x.func_code if hasattr(x, 'co_code'): disassemble(x) else: raise TypeError, \ "don't know how to disassemble %s objects" % \ type(x).__name__
raise TypeError, \ "don't know how to disassemble %s objects" % \ type(x).__name__
def dis(x=None): """Disassemble classes, methods, functions, or code. With no argument, disassemble the last traceback. """ if not x: distb() return if type(x) is types.InstanceType: x = x.__class__ if hasattr(x, '__dict__'): items = x.__dict__.items() items.sort() for name, x1 in items: if type(x1) in (types.MethodT...
user,pw = self.passwd.find_user_password(realm, host)
user, pw = self.passwd.find_user_password(realm, req.get_full_url())
def retry_http_basic_auth(self, host, req, realm): user,pw = self.passwd.find_user_password(realm, host) if pw is not None: raw = "%s:%s" % (user, pw) 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.p...
base = base + ', opaque="%s"' % opaque
base += ', opaque="%s"' % opaque
def get_authorization(self, req, chal): try: realm = chal['realm'] nonce = chal['nonce'] qop = chal.get('qop') 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
base = base + ', digest="%s"' % entdig if algorithm != 'MD5': base = base + ', algorithm="%s"' % algorithm
base += ', digest="%s"' % entdig base += ', algorithm="%s"' % algorithm
def get_authorization(self, req, chal): try: realm = chal['realm'] nonce = chal['nonce'] qop = chal.get('qop') 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
base = base + ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
def get_authorization(self, req, chal): try: realm = chal['realm'] nonce = chal['nonce'] qop = chal.get('qop') 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
if type(ob)==types.ClassType:
if type(ob) in (types.ClassType, types.TypeType):
def get_arg_text(ob): """Get a string describing the arguments for the given object""" argText = "" if ob is not None: argOffset = 0 if type(ob)==types.ClassType: # Look for the highest __init__ in the class chain. fob = _find_constructor(ob) if fob is None: fob = lambda: None else: argOffset = 1 elif type(ob)==types.M...
lines = f.readlines()
lines = [] line = f.readline() while line: lines.append(line.strip()) line = f.readline()
def read(self): opener = URLopener() f = opener.open(self.url) lines = f.readlines() self.errcode = opener.errcode if self.errcode == 401 or self.errcode == 403: self.disallow_all = 1 _debug("disallow all") elif self.errcode >= 400: self.allow_all = 1 _debug("allow all") elif self.errcode == 200 and lines: _debug("pars...
line = line.strip()
def parse(self, lines): """parse the input lines from a robot.txt file. We allow that a user-agent: line is not preceded by one or more blank lines.""" state = 0 linenumber = 0 entry = Entry()
self.tries = 0 self.maxtries = 10
def __init__(self, *args): apply(urllib.FancyURLopener.__init__, (self,) + args) self.errcode = 200 self.tries = 0 self.maxtries = 10
def http_error_302(self, url, fp, errcode, errmsg, headers, data=None): self.tries += 1 if self.tries >= self.maxtries: return self.http_error_default(url, fp, 500, "Internal Server Error: Redirect Recursion", headers) result = urllib.FancyURLopener.http_error_302(self, url, fp, errcode, errmsg, headers, data) self.tri...
def http_error_default(self, url, fp, errcode, errmsg, headers): self.errcode = errcode return urllib.FancyURLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
formlength = formlength - 8 - chunk.chunksize if chunk.chunksize & 1: formlength = formlength - 1
def initfp(self, file): self._file = file self._version = 0 self._decomp = None self._markers = [] self._soundpos = 0 form = self._file.read(4) if form != 'FORM': raise Error, 'file does not start with FORM id' formlength = _read_long(self._file) if formlength <= 0: raise Error, 'invalid FORM chunk data size' formdata ...
level = 0 if "absolute_import" in self.futures else -1
level = 0 if self.graph.checkFlag(CO_FUTURE_ABSIMPORT) else -1
def visitImport(self, node): self.set_lineno(node) level = 0 if "absolute_import" in self.futures else -1 for name, alias in node.names: if VERSION > 1: self.emit('LOAD_CONST', level) self.emit('LOAD_CONST', None) self.emit('IMPORT_NAME', name) mod = name.split(".")[0] if alias: self._resolveDots(name) self.storeName(a...
if level == 0 and "absolute_import" not in self.futures:
if level == 0 and not self.graph.checkFlag(CO_FUTURE_ABSIMPORT):
def visitFrom(self, node): self.set_lineno(node) level = node.level if level == 0 and "absolute_import" not in self.futures: level = -1 fromlist = map(lambda (name, alias): name, node.names) if VERSION > 1: self.emit('LOAD_CONST', level) self.emit('LOAD_CONST', tuple(fromlist)) self.emit('IMPORT_NAME', node.modname) fo...
if self.addr == types.TupleType:
if type(self.addr) == types.TupleType:
def __repr__ (self): try: status = [] if self.accepting and self.addr: status.append ('listening') elif self.connected: status.append ('connected') if self.addr: if self.addr == types.TupleType: status.append ('%s:%d' % self.addr) else: status.append (self.addr) return '<%s %s at %x>' % (self.__class__.__name__, ' '.jo...
import httplib tries = 0 while tries<5: connection = httplib.HTTP(self.host) connection.putrequest("GET", self.path) connection.putheader("Host", self.host) connection.endheaders() status, text, mime = connection.getreply() if status in [301,302] and mime: tries = tries + 1 newurl = mime.get("Location", mime.get("Uri",...
opener = URLopener() f = opener.open(self.url) lines = f.readlines() self.errcode = opener.errcode if self.errcode == 401 or self.errcode == 403:
def read(self): import httplib tries = 0 while tries<5: connection = httplib.HTTP(self.host) connection.putrequest("GET", self.path) connection.putheader("Host", self.host) connection.endheaders() status, text, mime = connection.getreply() if status in [301,302] and mime: tries = tries + 1 newurl = mime.get("Location",...
elif status>=400:
_debug("disallow all") elif self.errcode >= 400:
def read(self): import httplib tries = 0 while tries<5: connection = httplib.HTTP(self.host) connection.putrequest("GET", self.path) connection.putheader("Host", self.host) connection.endheaders() status, text, mime = connection.getreply() if status in [301,302] and mime: tries = tries + 1 newurl = mime.get("Location",...
else: self.parse(connection.getfile().readlines())
_debug("allow all") elif self.errcode == 200 and lines: _debug("parse lines") self.parse(lines)
def read(self): import httplib tries = 0 while tries<5: connection = httplib.HTTP(self.host) connection.putrequest("GET", self.path) connection.putheader("Host", self.host) connection.endheaders() status, text, mime = connection.getreply() if status in [301,302] and mime: tries = tries + 1 newurl = mime.get("Location",...
_debug("Checking robot.txt allowance for\n%s\n%s" % (useragent, url))
_debug("Checking robot.txt allowance for:\n user agent: %s\n url: %s" % (useragent, url))
def can_fetch(self, useragent, url): """using the parsed robots.txt decide if useragent can fetch url""" _debug("Checking robot.txt allowance for\n%s\n%s" % (useragent, url)) if self.disallow_all: return 0 if self.allow_all: return 1 # search for given user agent matches # the first match counts useragent = useragent.l...
useragent = useragent.lower() url = urllib.quote(urlparse.urlparse(url)[2])
url = urllib.quote(urlparse.urlparse(url)[2]) or "/"
def can_fetch(self, useragent, url): """using the parsed robots.txt decide if useragent can fetch url""" _debug("Checking robot.txt allowance for\n%s\n%s" % (useragent, url)) if self.disallow_all: return 0 if self.allow_all: return 1 # search for given user agent matches # the first match counts useragent = useragent.l...
"check if this entry applies to the specified agent"
useragent = useragent.split("/")[0].lower()
def applies_to(self, useragent): "check if this entry applies to the specified agent" for agent in self.useragents: if agent=="*": return 1 if re.match(agent, useragent): return 1 return 0
if agent=="*":
if agent=='*':
def applies_to(self, useragent): "check if this entry applies to the specified agent" for agent in self.useragents: if agent=="*": return 1 if re.match(agent, useragent): return 1 return 0
if re.match(agent, useragent):
agent = agent.lower() if re.search(re.escape(useragent), agent):
def applies_to(self, useragent): "check if this entry applies to the specified agent" for agent in self.useragents: if agent=="*": return 1 if re.match(agent, useragent): return 1 return 0
if len(sys.argv) <= 1: rp.set_url('http://www.musi-cal.com/robots.txt') rp.read() else: rp.parse(open(sys.argv[1]).readlines()) print rp.can_fetch('*', 'http://www.musi-cal.com/') print rp.can_fetch('Musi-Cal-Robot/1.0',
rp.set_url('http://www.musi-cal.com/robots.txt') rp.read() _check(rp.can_fetch('*', 'http://www.musi-cal.com/'), 1) _check(rp.can_fetch('', 'http://www.musi-cal.com/'), 0) _check(rp.can_fetch('CherryPickerSE',
def _test(): global debug import sys rp = RobotFileParser() debug = 1 if len(sys.argv) <= 1: rp.set_url('http://www.musi-cal.com/robots.txt') rp.read() else: rp.parse(open(sys.argv[1]).readlines()) print rp.can_fetch('*', 'http://www.musi-cal.com/') print rp.can_fetch('Musi-Cal-Robot/1.0', 'http://www.musi-cal.com/cgi-...
'?city=San+Francisco')
'?city=San+Francisco'), 0) _check(rp.can_fetch('CherryPickerSE/1.0', 'http://www.musi-cal.com/cgi-bin/event-search' '?city=San+Francisco'), 0) _check(rp.can_fetch('CherryPickerSE/1.5', 'http://www.musi-cal.com/cgi-bin/event-search' '?city=San+Francisco'), 0) _check(rp.can_fetch('ExtractorPro', 'http://www.musi-cal.com...
def _test(): global debug import sys rp = RobotFileParser() debug = 1 if len(sys.argv) <= 1: rp.set_url('http://www.musi-cal.com/robots.txt') rp.read() else: rp.parse(open(sys.argv[1]).readlines()) print rp.can_fetch('*', 'http://www.musi-cal.com/') print rp.can_fetch('Musi-Cal-Robot/1.0', 'http://www.musi-cal.com/cgi-...
def grid_slaves(self, master, row=None, column=None): args = (master,)
def grid_slaves(self, row=None, column=None): args = ()
def grid_slaves(self, master, row=None, column=None): args = (master,) if row: args = args + ('-row', row) if column: args = args + ('-column', column) return map(self._nametowidget, self.tk.splitlist( apply(self.tk.call, ('grid', 'slaves', self._w) + args)))
return self.tk.call(self._w, 'entrycget', '-' + option)
return self.tk.call(self._w, 'entrycget', index, '-' + option)
def entrycget(self, index, option): return self.tk.call(self._w, 'entrycget', '-' + option)
if _active:
if _active is not None:
def __del__(self): # In case the child hasn't been waited on, check if it's done. self.poll(_deadstate=sys.maxint) if self.sts < 0: if _active: # Child is still running, keep us alive until we can wait on it. _active.append(self)
if size < 0: size = sys.maxint bufs = [] readsize = min(100, size)
if size < 0: size = sys.maxint readsize = self.min_readsize else: readsize = size bufs = ""
def readline(self, size=-1): if size < 0: size = sys.maxint bufs = [] readsize = min(100, size) # Read from the file in small chunks while True: if size == 0: return "".join(bufs) # Return resulting line
if size == 0: return "".join(bufs)
if size == 0: return bufs
def readline(self, size=-1): if size < 0: size = sys.maxint bufs = [] readsize = min(100, size) # Read from the file in small chunks while True: if size == 0: return "".join(bufs) # Return resulting line
if size is not None: if i==-1 and len(c) > size: i=size-1 elif size <= i: i = size -1
def readline(self, size=-1): if size < 0: size = sys.maxint bufs = [] readsize = min(100, size) # Read from the file in small chunks while True: if size == 0: return "".join(bufs) # Return resulting line
bufs.append(c[:i+1]) self._unread(c[i+1:]) return ''.join(bufs) bufs.append(c) size = size - len(c) readsize = min(size, readsize * 2)
if size <= i: i = size - 1 self._unread(c[i+1:]) return bufs + c[:i+1] else: if len(c) > size: i = size - 1 bufs = bufs + c size = size - len(c) readsize = min(size, int(readsize * 1.1)) if readsize > self.min_readsize: self.min_readsize = readsize
def readline(self, size=-1): if size < 0: size = sys.maxint bufs = [] readsize = min(100, size) # Read from the file in small chunks while True: if size == 0: return "".join(bufs) # Return resulting line
def check(a, b): if a != b: print '*** check failed: %s != %s' % (repr(a), repr(b)) else: print '%s == %s: OK' % (a, b)
import test.test_support, unittest
def check(a, b): if a != b: print '*** check failed: %s != %s' % (repr(a), repr(b)) else: print '%s == %s: OK' % (a, b)
check(unicode('abc', codecname), u'abc') check(unicode('xdef', codecname), u'abcdef') check(unicode('defx', codecname), u'defabc') check(unicode('dxf', codecname), u'dabcf') check(unicode('dxfx', codecname), u'dabcfabc')
class CharmapCodecTest(unittest.TestCase): def test_constructorx(self): self.assertEquals(unicode('abc', codecname), u'abc') self.assertEquals(unicode('xdef', codecname), u'abcdef') self.assertEquals(unicode('defx', codecname), u'defabc') self.assertEquals(unicode('dxf', codecname), u'dabcf') self.assertEquals(unicode(...
def check(a, b): if a != b: print '*** check failed: %s != %s' % (repr(a), repr(b)) else: print '%s == %s: OK' % (a, b)
check(u'abc'.encode(codecname), 'abc') check(u'xdef'.encode(codecname), 'abcdef') check(u'defx'.encode(codecname), 'defabc') check(u'dxf'.encode(codecname), 'dabcf') check(u'dxfx'.encode(codecname), 'dabcfabc')
def test_encodex(self): self.assertEquals(u'abc'.encode(codecname), 'abc') self.assertEquals(u'xdef'.encode(codecname), 'abcdef') self.assertEquals(u'defx'.encode(codecname), 'defabc') self.assertEquals(u'dxf'.encode(codecname), 'dabcf') self.assertEquals(u'dxfx'.encode(codecname), 'dabcfabc')
def check(a, b): if a != b: print '*** check failed: %s != %s' % (repr(a), repr(b)) else: print '%s == %s: OK' % (a, b)
check(unicode('ydef', codecname), u'def') check(unicode('defy', codecname), u'def') check(unicode('dyf', codecname), u'df') check(unicode('dyfy', codecname), u'df')
def test_constructory(self): self.assertEquals(unicode('ydef', codecname), u'def') self.assertEquals(unicode('defy', codecname), u'def') self.assertEquals(unicode('dyf', codecname), u'df') self.assertEquals(unicode('dyfy', codecname), u'df')
def check(a, b): if a != b: print '*** check failed: %s != %s' % (repr(a), repr(b)) else: print '%s == %s: OK' % (a, b)
try: unicode('abc\001', codecname) except UnicodeError: print '\\001 maps to undefined: OK' else: print '*** check failed: \\001 does not map to undefined'
def test_maptoundefined(self): self.assertRaises(UnicodeError, unicode, 'abc\001', codecname) def test_main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(CharmapCodecTest)) test.test_support.run_suite(suite) if __name__ == "__main__": test_main()
def check(a, b): if a != b: print '*** check failed: %s != %s' % (repr(a), repr(b)) else: print '%s == %s: OK' % (a, b)
def testWriteXML(): pass
def testWriteXML(): str = '<a b="c"/>' dom = parseString(str) domstr = dom.toxml() dom.unlink() confirm(str == domstr)
def testWriteXML(): pass
"Strange! filename %s has two different module names" % \ (key, modules[key], other_module[key])
"Strange! filename %s has two different module " \ "names: %s and %s" % \ (key, modules[key], other_modules[key])
def update(self, other): """Merge in the data from another CoverageResults""" counts = self.counts other_counts = other.counts modules = self.modules other_modules = other.modules
save_counts = 0):
save_counts = 0, summary = 0, coverdir = None):
def create_results_log(results, dirname = ".", show_missing = 1, save_counts = 0): import re # turn the counts data ("(filename, lineno) = count") into something # accessible on a per-file basis per_file = {} for filename, lineno in results.counts.keys(): lines_hit = per_file[filename] = per_file.get(filename, {}) line...
fndir = os.path.dirname(filename) if filename[:1] == os.sep: coverpath = os.path.join(dirname, "."+fndir) else: coverpath = os.path.join(dirname, fndir)
modulename = os.path.split(results.modules[key])[1]
def create_results_log(results, dirname = ".", show_missing = 1, save_counts = 0): import re # turn the counts data ("(filename, lineno) = count") into something # accessible on a per-file basis per_file = {} for filename, lineno in results.counts.keys(): lines_hit = per_file[filename] = per_file.get(filename, {}) line...
sys.stderr.write("%s: Could not open %s for reading " \ "because: %s - skipping\n" % \ ("trace", `filename`, err.strerror)) continue modulename = os.path.split(results.modules[key])[1] listfilename = os.path.join(coverpath, modulename + ".cover")
print >> sys.stderr, "trace: Could not open %s for reading " \ "because: %s - skipping" % (`filename`, err.strerror) continue
def create_results_log(results, dirname = ".", show_missing = 1, save_counts = 0): import re # turn the counts data ("(filename, lineno) = count") into something # accessible on a per-file basis per_file = {} for filename, lineno in results.counts.keys(): lines_hit = per_file[filename] = per_file.get(filename, {}) line...
modulename = frame.f_globals["__name__"]
try: modulename = frame.f_globals["__name__"] except KeyError: modulename = None
def trace(self, frame, why, arg): if why == 'line': # something is fishy about getting the file name filename = frame.f_globals.get("__file__", None) if filename is None: filename = frame.f_code.co_filename modulename = frame.f_globals["__name__"]
modulename = frame.f_globals["__name__"]
try: modulename = frame.f_globals["__name__"] except KeyError: modulename = None
def trace(self, frame, why, arg): if why == 'line': filename = frame.f_code.co_filename modulename = frame.f_globals["__name__"]
sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
print >> sys.stderr, "%s: %s" % (sys.argv[0], msg)
def _err_exit(msg): sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) sys.exit(1)