rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
This is equivalent to the Dict lookup, except that we cascade through lower level Dict's (not dict's though!). | This is equivalent to the dict lookup, except that we cascade through lower level dict's. | def __getitem__(self, key): """Allows items to be addressed as self[key]. |
return dict.__getitem__(self, key) | return cascade(self, key) | def __getitem__(self, key): """Allows items to be addressed as self[key]. |
try: for v in self.itervalues(): if isinstance(v,Dict): try: return v[key] except CascadingKeyError: pass raise CascadingKeyError except CascadingKeyError: pass return self.default | return self.default | def __getitem__(self, key): """Allows items to be addressed as self[key]. |
C = Dict({'a':1,'x':Dict({'b':'2','x':Dict({'c':3,'x':Dict({'d':4,'a':0})})})}) print C print C.a,C.b,C.c,C.d,C.e,C.x.a | def printval(s): """Prints the name and value of a (sequence of) variables.""" try: print "%s = %s" % (s,eval(s)) except: print "Error in %s" % s | ## def getprop(self,key): |
C = CascadingDict(C) print C.a,C.b,C.c,C.d,C.e,C.x.a C = CascadingDict({'a':1,'x':CascadingDict({'b':'2','x':CascadingDict({'c':3,'x':CascadingDict({'d':4,'a':0})})})}) print C.a,C.b,C.c,C.d,C.e,C.x.a C = CascadingDict({'a':1,'x':CascadingDict({'b':'2','x':CascadingDict({'c':3,'x':Dict({'d':4,'a':0})})})}) print C.a,... | C = CascadingDict({'x':CascadingDict({'a':1,'y':CascadingDict({'b':5,'c':6})}),'y':CascadingDict({'c':3,'d':4}),'d':0}) printval("C") printval("C['a'],C['b'],C['c'],C['d'],C['x']['c']") printval("C['e']") printval("C.a,C.b,C.c,C.d,C.x.c") printval("C.e") | ## def getprop(self,key): |
data = self.tagByName(tag) | data = self.hdr[tag] | def listTagByName(self, tag): """take a tag that should be a list and make sure it is one""" lst = [] data = self.tagByName(tag) if data is None: pass if type(data) is types.ListType: lst.extend(data) else: lst.append(data) return lst |
pass | return lst | def listTagByName(self, tag): """take a tag that should be a list and make sure it is one""" lst = [] data = self.tagByName(tag) if data is None: pass if type(data) is types.ListType: lst.extend(data) else: lst.append(data) return lst |
def color(self): pass | def color(self): # do something here - but what I don't know pass | |
if file == '' or file is None: continue if mode is None: | if mode is None or mode == '': self.filenames.append(file) | def genFileLists(self): """produces lists of dirs and files for this header in two lists""" files = self.listTagByName('filenames') fileflags = self.listTagByName('fileflags') filemodes = self.listTagByName('filemodes') filetuple = zip(files, filemodes, fileflags) for (file, mode, flag) in filetuple: #garbage checks i... |
else: self.filenames.append(file) | continue self.filenames.append(file) | def genFileLists(self): """produces lists of dirs and files for this header in two lists""" files = self.listTagByName('filenames') fileflags = self.listTagByName('fileflags') filemodes = self.listTagByName('filemodes') filetuple = zip(files, filemodes, fileflags) for (file, mode, flag) in filetuple: #garbage checks i... |
if os.path.exists(a): | if os.path.exists(directory + '/' + a): | def parseArgs(args): """ Parse the command line args return a commands dict and directory. Sanity check all the things being passed in. """ if len(args) == 0: usage() cmds = {} cmds['quiet'] = 0 cmds['verbose'] = 0 cmds['excludes'] = [] cmds['baseurl'] = None cmds['groupfile'] = None cmds['sumtype'] = 'md5' cmds['pret... |
if len(argsleft) != 1: errorprint(_('Error: Only one directory allowed per run.')) usage() else: directory = argsleft[0] | def parseArgs(args): """ Parse the command line args return a commands dict and directory. Sanity check all the things being passed in. """ if len(args) == 0: usage() cmds = {} cmds['quiet'] = 0 cmds['verbose'] = 0 cmds['excludes'] = [] cmds['baseurl'] = None cmds['groupfile'] = None cmds['sumtype'] = 'md5' cmds['pret... | |
gopts, argsleft = getopt.getopt(args, 'phqVvg:s:x:u:', ['help', 'exclude', | gopts, argsleft = getopt.getopt(args, 'phqVvg:s:x:u:', ['help', 'exclude=', | def parseArgs(args): """ Parse the command line args return a commands dict and directory. Sanity check all the things being passed in. """ cmds = {} cmds['quiet'] = 0 cmds['verbose'] = 0 cmds['excludes'] = [] cmds['baseurl'] = None cmds['groupfile'] = None cmds['sumtype'] = 'sha' cmds['pretty'] = 0 try: gopts, argsle... |
%s [options] directory-of-packages | createrepo [options] directory-of-packages | def usage(): print _(""" %s [options] directory-of-packages Options: -u, --baseurl = optional base url location for all files -x, --exclude = files globs to exclude, can be specified multiple times -q, --quiet = run quietly -g, --groupfile <filename> to point to for group information (precreated) -v, --verbose = run v... |
""") % os.path.basename(sys.argv[0]) | """) | def usage(): print _(""" %s [options] directory-of-packages Options: -u, --baseurl = optional base url location for all files -x, --exclude = files globs to exclude, can be specified multiple times -q, --quiet = run quietly -g, --groupfile <filename> to point to for group information (precreated) -v, --verbose = run v... |
if (flag & 64): self.ghostnames.append(file) | if flag is None: self.filenames.append(file) | def genFileLists(self): """produces lists of dirs and files for this header in two lists""" files = self.listTagByName('filenames') fileflags = self.listTagByName('fileflags') filemodes = self.listTagByName('filemodes') filetuple = zip(files, filemodes, fileflags) for (file, mode, flag) in filetuple: if stat.S_ISDIR(m... |
self.filenames.append(file) | if (flag & 64): self.ghostnames.append(file) else: self.filenames.append(file) | def genFileLists(self): """produces lists of dirs and files for this header in two lists""" files = self.listTagByName('filenames') fileflags = self.listTagByName('fileflags') filemodes = self.listTagByName('filemodes') filetuple = zip(files, filemodes, fileflags) for (file, mode, flag) in filetuple: if stat.S_ISDIR(m... |
entry = format.newChild(None, tag, None) | entry = format.newChild(formatns, tag, None) | def generateXML(doc, node, rpmObj, sumtype): """takes an xml doc object and a package metadata entry node, populates a package node with the md information""" ns = node.ns() pkgNode = node.newChild(None, "package", None) pkgNode.newProp('type', 'rpm') pkgNode.newChild(None, 'name', rpmObj.tagByName('name')) pkgNode.new... |
if os.path.exists(a): cmds['groupfile'] = a else: errorprint(_('Error: groupfile %s cannot be found.' % a)) usage() | cmds['groupfile'] = a | def parseArgs(args): """ Parse the command line args return a commands dict and directory. Sanity check all the things being passed in. """ cmds = {} cmds['quiet'] = 0 cmds['verbose'] = 0 cmds['excludes'] = [] cmds['baseurl'] = None cmds['groupfile'] = None cmds['sumtype'] = 'sha' cmds['pretty'] = 0 |
if not os.path.isabs(a): a = os.path.join(os.getcwd(), a) | def parseArgs(args): """ Parse the command line args return a commands dict and directory. Sanity check all the things being passed in. """ cmds = {} cmds['quiet'] = 0 cmds['verbose'] = 0 cmds['excludes'] = [] cmds['baseurl'] = None cmds['groupfile'] = None cmds['sumtype'] = 'sha' cmds['pretty'] = 0 | |
if not checkAndMakeDir(a): errorprint(_('Error: cannot open/write to cache dir %s' % a)) usage() | def parseArgs(args): """ Parse the command line args return a commands dict and directory. Sanity check all the things being passed in. """ cmds = {} cmds['quiet'] = 0 cmds['verbose'] = 0 cmds['excludes'] = [] cmds['baseurl'] = None cmds['groupfile'] = None cmds['sumtype'] = 'sha' cmds['pretty'] = 0 | |
def extension_visitor(arg, dirname, names): | def extension_visitor(filelist, dirname, names): | def extension_visitor(arg, dirname, names): for fn in names: if os.path.isdir(fn): continue elif string.lower(fn[-extlen:]) == '%s' % (ext): arg.append(os.path.join(directory,fn)) |
elif string.lower(fn[-extlen:]) == '%s' % (ext): arg.append(os.path.join(directory,fn)) rpmlist = [] startdir = os.path.join(basepath, directory) os.path.walk(startdir, extension_visitor, rpmlist) return rpmlist | elif fn[-extlen:].lower() == '%s' % (ext): relativepath = dirname.replace(startdir, "", 1) relativepath = relativepath.lstrip("/") filelist.append(os.path.join(relativepath,fn)) filelist = [] startdir = os.path.join(basepath, directory) + '/' os.path.walk(startdir, extension_visitor, filelist) return filelist | def extension_visitor(arg, dirname, names): for fn in names: if os.path.isdir(fn): continue elif string.lower(fn[-extlen:]) == '%s' % (ext): arg.append(os.path.join(directory,fn)) |
self.writeMetadataDocs(files) | self.writeMetadataDocs(files, directory) | def doPkgMetadata(self, directory): """all the heavy lifting for the package metadata""" |
def writeMetadataDocs(self, files, current=0): | def writeMetadataDocs(self, files, directory, current=0): | def writeMetadataDocs(self, files, current=0): for file in files: current+=1 try: mdobj = dumpMetadata.RpmMetaData(self.ts, self.cmds['basedir'], file, self.cmds) if not self.cmds['quiet']: if self.cmds['verbose']: print '%d/%d - %s' % (current, len(files), file) else: sys.stdout.write('\r' + ' ' * 80) sys.stdout.write... |
mdobj = dumpMetadata.RpmMetaData(self.ts, self.cmds['basedir'], file, self.cmds) | rpmdir= os.path.join(self.cmds['basedir'], directory) mdobj = dumpMetadata.RpmMetaData(self.ts, rpmdir, file, self.cmds) | def writeMetadataDocs(self, files, current=0): for file in files: current+=1 try: mdobj = dumpMetadata.RpmMetaData(self.ts, self.cmds['basedir'], file, self.cmds) if not self.cmds['quiet']: if self.cmds['verbose']: print '%d/%d - %s' % (current, len(files), file) else: sys.stdout.write('\r' + ' ' * 80) sys.stdout.write... |
self.cmds['basedir'] = os.path.join(original_basedir, mydir) | def doPkgMetadata(self, directories): """all the heavy lifting for the package metadata""" import types if type(directories) == types.StringType: MetaDataGenerator.doPkgMetadata(self, directories) return filematrix = {} for mydir in directories: filematrix[mydir] = self.getFileList(self.cmds['basedir'], mydir, '.rpm') ... | |
current = self.writeMetadataDocs(filematrix[mydir], current) | current = self.writeMetadataDocs(filematrix[mydir], mydir, current) | def doPkgMetadata(self, directories): """all the heavy lifting for the package metadata""" import types if type(directories) == types.StringType: MetaDataGenerator.doPkgMetadata(self, directories) return filematrix = {} for mydir in directories: filematrix[mydir] = self.getFileList(self.cmds['basedir'], mydir, '.rpm') ... |
-U, --update-info-location <url> = acquire package update metadata | def usage(retval=1): print _(""" createrepo [options] directory-of-packages Options: -u, --baseurl <url> = optional base url location for all files -o, --outputdir <dir> = optional directory to output to -x, --exclude = files globs to exclude, can be specified multiple times -q, --quiet = run quietly -n, --noepoch = d... | |
try: if self.cmds['update-info-location']: metadata = urlgrabber.urlopen( self.cmds['update-info-location'] + '?pkg=%s' % file) filename = file.replace('.rpm', '.xml') metadata.filename = os.path.join( self.cmds['basedir'], self.cmds['tempdir'], self.cmds['update-info-dir'], filename) metadata._do_grab() metadata.clos... | def writeMetadataDocs(self, files, current=0): for file in files: current+=1 try: mdobj = dumpMetadata.RpmMetaData(self.ts, self.cmds['basedir'], file, self.cmds) if not self.cmds['quiet']: if self.cmds['verbose']: print '%d/%d - %s' % (current, len(files), file) else: sys.stdout.write('\r' + ' ' * 80) sys.stdout.write... | |
gopts, argsleft = getopt.getopt(args, 'phqVvng:s:x:u:c:U:o:', ['help', 'exclude=', | gopts, argsleft = getopt.getopt(args, 'phqVvng:s:x:u:c:o:', ['help', 'exclude=', | def parseArgs(args): """ Parse the command line args return a commands dict and directory. Sanity check all the things being passed in. """ cmds = {} cmds['quiet'] = 0 cmds['verbose'] = 0 cmds['excludes'] = [] cmds['baseurl'] = None cmds['groupfile'] = None cmds['sumtype'] = 'sha' cmds['noepoch'] = False cmds['pretty']... |
'update-info-location=', 'noepoch']) | 'noepoch']) | def parseArgs(args): """ Parse the command line args return a commands dict and directory. Sanity check all the things being passed in. """ cmds = {} cmds['quiet'] = 0 cmds['verbose'] = 0 cmds['excludes'] = [] cmds['baseurl'] = None cmds['groupfile'] = None cmds['sumtype'] = 'sha' cmds['noepoch'] = False cmds['pretty']... |
elif arg in ['-U', '--update-info-location']: cmds['update-info-location'] = a | def parseArgs(args): """ Parse the command line args return a commands dict and directory. Sanity check all the things being passed in. """ cmds = {} cmds['quiet'] = 0 cmds['verbose'] = 0 cmds['excludes'] = [] cmds['baseurl'] = None cmds['groupfile'] = None cmds['sumtype'] = 'sha' cmds['noepoch'] = False cmds['pretty']... | |
cmds['update-info-dir'] = 'update-info' | def parseArgs(args): """ Parse the command line args return a commands dict and directory. Sanity check all the things being passed in. """ cmds = {} cmds['quiet'] = 0 cmds['verbose'] = 0 cmds['excludes'] = [] cmds['baseurl'] = None cmds['groupfile'] = None cmds['sumtype'] = 'sha' cmds['noepoch'] = False cmds['pretty']... | |
if cmds.has_key('update-info-location'): if not checkAndMakeDir(os.path.join(cmds['basedir'], cmds['tempdir'], cmds['update-info-dir'])): errorprint(_('Error: cannot open/write to update info dir %s' % a)) usage() | def main(args): cmds, directories = parseArgs(args) directory = directories[0] # start the sanity/stupidity checks if not os.path.exists(os.path.join(cmds['basedir'], directory)): errorprint(_('Directory must exist')) sys.exit(1) if not os.path.isdir(os.path.join(cmds['basedir'], directory)): errorprint(_('Directory o... | |
mdpath = os.path.join(cmds['basedir'], cmds['olddir'], cmds['update-info-dir']) if os.path.isdir(mdpath): for file in os.listdir(mdpath): os.remove(os.path.join(mdpath, file)) os.rmdir(mdpath) | def main(args): cmds, directories = parseArgs(args) directory = directories[0] # start the sanity/stupidity checks if not os.path.exists(os.path.join(cmds['basedir'], directory)): errorprint(_('Directory must exist')) sys.exit(1) if not os.path.isdir(os.path.join(cmds['basedir'], directory)): errorprint(_('Directory o... | |
gopts, argsleft = getopt.getopt(args, 'phqVvng:s:x:u:c:o:', ['help', 'exclude=', | gopts, argsleft = getopt.getopt(args, 'phqVvng:s:x:u:c:o:C', ['help', 'exclude=', | def parseArgs(args): """ Parse the command line args return a commands dict and directory. Sanity check all the things being passed in. """ cmds = {} cmds['quiet'] = 0 cmds['verbose'] = 0 cmds['excludes'] = [] cmds['baseurl'] = None cmds['groupfile'] = None cmds['sumtype'] = 'sha' cmds['noepoch'] = False cmds['pretty']... |
'noepoch']) | 'noepoch', 'checkts']) | def parseArgs(args): """ Parse the command line args return a commands dict and directory. Sanity check all the things being passed in. """ cmds = {} cmds['quiet'] = 0 cmds['verbose'] = 0 cmds['excludes'] = [] cmds['baseurl'] = None cmds['groupfile'] = None cmds['sumtype'] = 'sha' cmds['noepoch'] = False cmds['pretty']... |
if cmds['checkts']: ts = os.path.getctime(filepath) if ts > cmds['mdtimestamp']: cmds['mdtimestamp'] = ts | def main(args): cmds, directories = parseArgs(args) directory = directories[0] testdir = os.path.realpath(os.path.join(cmds['basedir'], directory)) # start the sanity/stupidity checks if not os.path.exists(testdir): errorprint(_('Directory %s must exist') % (directory,)) sys.exit(1) if not os.path.isdir(testdir): erro... | |
a = os.path.join(cmds['basedir'] ,a) | a = os.path.join(cmds['outputdir'] ,a) | def parseArgs(args): """ Parse the command line args return a commands dict and directory. Sanity check all the things being passed in. """ cmds = {} cmds['quiet'] = 0 cmds['verbose'] = 0 cmds['excludes'] = [] cmds['baseurl'] = None cmds['groupfile'] = None cmds['sumtype'] = 'sha' cmds['noepoch'] = False cmds['pretty']... |
if self.tagByName('sourcepackage') == 1: | if self.tagByName('sourcepackage') == 1 or not self.tagByName('sourcerpm'): | def arch(self): if self.tagByName('sourcepackage') == 1: return 'src' else: return self.tagByName('arch') |
csumtag = '%s-%s' % (self.hdr['name'] , self.hdr[rpm.RPMTAG_SHA1HEADER]) | key = "".join([hex(ord(x))[2:].zfill(2) for x in tuple(self.hdr[rpm.RPMTAG_SIGMD5])]) csumtag = '%s-%s' % (self.hdr['name'] , key) | def doChecksumCache(self, fo): """return a checksum for a package: - check if the checksum cache is enabled if not - return the checksum if so - check to see if it has a cache file if so, open it and return the first line's contents if not, grab the checksum and write it to a file for this pkg """ if not self.options['... |
print '%s - %s - %s' % (file, mode, flag) | def genFileLists(self): """produces lists of dirs and files for this header in two lists""" files = self.listTagByName('filenames') fileflags = self.listTagByName('fileflags') filemodes = self.listTagByName('filemodes') filetuple = zip(files, filemodes, fileflags) for (file, mode, flag) in filetuple: #garbage checks i... | |
def is_repository_clean(path): """Does the repository at path contain any uncommitted modifications""" | def is_repository_clean(): """Does the repository contain any uncommitted modifications""" | def is_repository_clean(path): """Does the repository at path contain any uncommitted modifications""" clean_msg='nothing to commit' try: curdir=os.path.abspath(os.path.curdir) os.chdir(path) except OSError: return False popen = subprocess.Popen(['git','status'], stdout=subprocess.PIPE) popen.wait() out=popen.stdout.re... |
try: curdir=os.path.abspath(os.path.curdir) os.chdir(path) except OSError: return False | def is_repository_clean(path): """Does the repository at path contain any uncommitted modifications""" clean_msg='nothing to commit' try: curdir=os.path.abspath(os.path.curdir) os.chdir(path) except OSError: return False popen = subprocess.Popen(['git','status'], stdout=subprocess.PIPE) popen.wait() out=popen.stdout.re... | |
os.chdir(curdir) | def is_repository_clean(path): """Does the repository at path contain any uncommitted modifications""" clean_msg='nothing to commit' try: curdir=os.path.abspath(os.path.curdir) os.chdir(path) except OSError: return False popen = subprocess.Popen(['git','status'], stdout=subprocess.PIPE) popen.wait() out=popen.stdout.re... | |
def get_repository_branch(path): """on what branch is the repository at path?""" try: curdir=os.path.abspath(os.path.curdir) os.chdir(path) except OSError: return None | def get_repository_branch(): """on what branch is the repository""" | def get_repository_branch(path): """on what branch is the repository at path?""" try: curdir=os.path.abspath(os.path.curdir) os.chdir(path) except OSError: return None popen = subprocess.Popen(['git','branch'], stdout=subprocess.PIPE) popen.wait() for line in popen.stdout: if line.startswith('*'): return line.split(' '... |
title = page | title = page_name | def process_request(self, req): req.hdf['trac.href.blog'] = req.href.blog() |
'escaped': Markup.escape(str(description)), | 'escaped': Markup.escape(unicode(description)), | def process_request(self, req): req.hdf['trac.href.blog'] = req.href.blog() |
factory = database.factory.name_to_serial(factory) | try: factory = database.factory.name_to_serial(factory) except KeyError: return "Unknown factory name '%s'." % factory | def challenge(factory): """ challenge(string) => string Generate a random authentication challenge. Parameter: - The name of the factory (string, length max 20). Return value: - Authentication challenge (hex string, length 36). The first 4 characters contain the password salt. The remaining 32 characters contain a rand... |
data_bytes, tag = struct.unpack('!I4s', self.file.read(8)) | try: data_bytes, tag = struct.unpack('!I4s', self.file.read(8)) except struct.error: raise ValueError('Chunk too short for header') | def read_chunk(self): """ Read a PNG chunk from the input file, return tag name and data. """ # http://www.w3.org/TR/PNG/#5Chunk-layout data_bytes, tag = struct.unpack('!I4s', self.file.read(8)) data = self.file.read(data_bytes) checksum = struct.unpack('!i', self.file.read(4))[0] verify = zlib.crc32(tag) verify = zlib... |
checksum = struct.unpack('!i', self.file.read(4))[0] | if len(data) != data_bytes: raise ValueError('Chunk %s too short for required %i data octets' % (tag, data_bytes)) checksum = self.file.read(4) if len(checksum) != 4: raise ValueError('Chunk %s too short for checksum', tag) | def read_chunk(self): """ Read a PNG chunk from the input file, return tag name and data. """ # http://www.w3.org/TR/PNG/#5Chunk-layout data_bytes, tag = struct.unpack('!I4s', self.file.read(8)) data = self.file.read(data_bytes) checksum = struct.unpack('!i', self.file.read(4))[0] verify = zlib.crc32(tag) verify = zlib... |
raise ValueError("checksum error in %s chunk: %x != %x" % (tag, checksum, verify)) | (a,) = struct.unpack('!I', checksum) (b,) = struct.unpack('!I', verify) raise ValueError("Checksum error in %s chunk: 0x%X != 0x%X" % (tag, a, b)) | def read_chunk(self): """ Read a PNG chunk from the input file, return tag name and data. """ # http://www.w3.org/TR/PNG/#5Chunk-layout data_bytes, tag = struct.unpack('!I4s', self.file.read(8)) data = self.file.read(data_bytes) checksum = struct.unpack('!i', self.file.read(4))[0] verify = zlib.crc32(tag) verify = zlib... |
re_url = re.compile(r"http://(www\.|)([\w\.\-]+)") | def limit_expire(expire): """ Upper limit on expiry interval. >>> limit_expire('invalid') '0:30' >>> limit_expire('2:00') '2:00' >>> limit_expire('2:61') '3:01' >>> limit_expire('4000:99') '4:00' >>> limit_expire('4:01') '4:00' """ match = expire_match(expire) if not match: return '0:30' hours = int(match.group(1)) mi... | |
>>> extract_domain('http://test.example.com:8000/') | >>> extract_domain('https://test.example.com:8000/') | def extract_domain(url): """ Extract the domain name from a http:// URL, without www prefix. >>> extract_domain('http://browsershots.org/submit/') 'browsershots.org' >>> extract_domain('http://www.google.com') 'google.com' >>> extract_domain('http://test.example.com:8000/') 'test.example.com' """ match = re_url.match(... |
match = re_url.match(url) | match = url_match(url) | def extract_domain(url): """ Extract the domain name from a http:// URL, without www prefix. >>> extract_domain('http://browsershots.org/submit/') 'browsershots.org' >>> extract_domain('http://www.google.com') 'google.com' >>> extract_domain('http://test.example.com:8000/') 'test.example.com' """ match = re_url.match(... |
(_guess is None and len(kw) != 1): | (_guess is None and len(kw) != 1)): | def __init__(self, _guess=None, **kw): """ Create a PNG decoder object. |
self.write(outfile, self.array_scanlines_interlace(pixels)) | self.write(outfile, self.array_scanlines_interlace(pixels), interlaced=True) | def convert_ppm_and_pgm(self, ppmfile, pgmfile, outfile, interlace=False): """ Convert a PPM and PGM file containing raw pixel data into a PNG outfile with the parameters set in the writer object. """ pixels = array('B') pixels.fromfile(ppmfile, self.bytes_per_sample * self.color_depth * self.width * self.height) apixe... |
if line.startswith('import ') and line.count(','): return line.index(','), "E130 multiple imports on one line" | if line.startswith('import '): found = line.find(',') if found > -1: return found, "E130 multiple imports on one line" | def imports_on_separate_lines(logical_line_muted): """ Imports should usually be on separate lines. """ line = logical_line_muted if line.startswith('import ') and line.count(','): return line.index(','), "E130 multiple imports on one line" |
>>> triple_quoted_incomplete("'''") | >>> triple_quoted_incomplete("a('''") | def triple_quoted_incomplete(line): """ Test if line contains an incomplete triple-quoted string. >>> triple_quoted_incomplete("'''") True >>> triple_quoted_incomplete("''''''") False >>> triple_quoted_incomplete("'''''''''") True """ if line.count('"""'): return bool(line.count('"""') % 2) if line.count("'''"): retur... |
>>> triple_quoted_incomplete("''''''") | >>> triple_quoted_incomplete("a(''''''") | def triple_quoted_incomplete(line): """ Test if line contains an incomplete triple-quoted string. >>> triple_quoted_incomplete("'''") True >>> triple_quoted_incomplete("''''''") False >>> triple_quoted_incomplete("'''''''''") True """ if line.count('"""'): return bool(line.count('"""') % 2) if line.count("'''"): retur... |
>>> triple_quoted_incomplete("'''''''''") | >>> triple_quoted_incomplete("a('''''''''") | def triple_quoted_incomplete(line): """ Test if line contains an incomplete triple-quoted string. >>> triple_quoted_incomplete("'''") True >>> triple_quoted_incomplete("''''''") False >>> triple_quoted_incomplete("'''''''''") True """ if line.count('"""'): return bool(line.count('"""') % 2) if line.count("'''"): retur... |
if line.count('"""'): return bool(line.count('"""') % 2) if line.count("'''"): return bool(line.count("'''") % 2) | if line.count('"""') % 2: return True if line.count("'''") % 2: return True | def triple_quoted_incomplete(line): """ Test if line contains an incomplete triple-quoted string. >>> triple_quoted_incomplete("'''") True >>> triple_quoted_incomplete("''''''") False >>> triple_quoted_incomplete("'''''''''") True """ if line.count('"""'): return bool(line.count('"""') % 2) if line.count("'''"): retur... |
line = line[-1] | line = line[:-1] | def physical_to_logical(physical): """ Convert multi-line statements to single lines. """ logical = [] line_number = 0 while line_number < len(physical): indent = get_indent(physical[line_number][1]) line = physical[line_number][1].strip() mapping = [(0, line_number + 1, indent)] while (line.endswith('\\') or triple_qu... |
message(' ' + line) | message(line.rstrip()) message(' ' * (offset) + '^') | def check_lines(argument_name, lines, filename): """ Find all checks with matching first argument name and run all of them on each line. """ global state state = {} # {'previous_line': None} error_count = 0 checks = find_checks(argument_name) for location, line in lines: line_muted = mute_comment(mute_strings(line)) fo... |
flushed = compressor.flush() if len(compressed) or len(flushed): self.write_chunk(outfile, 'IDAT', compressed + flushed) | else: compressed = '' flushed = compressor.flush() if len(compressed) or len(flushed): self.write_chunk(outfile, 'IDAT', compressed + flushed) | def write(self, outfile, scanlines): """ Write a PNG image to the output file. """ # http://www.w3.org/TR/PNG/#5PNG-file-signature outfile.write(struct.pack("8B", 137, 80, 78, 71, 13, 10, 26, 10)) |
if xml: | if DEBUG_XML_IN_TITLE and not xml: xhtml.write_tag_line('title', 'This browser does not understand XML') else: | def write_html_head(title): """ Send HTTP header and XHTML head. """ req.content_type = 'text/html; charset=UTF-8' xml = negotiate_xml() if xml: req.content_type = 'application/xhtml+xml; charset=UTF-8' req.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"') req.write(' "http://www.w3.org/TR/xhtml11/DTD/xhtml11.... |
else: xhtml.write_tag_line('title', 'This browser does not understand XML') | def write_html_head(title): """ Send HTTP header and XHTML head. """ req.content_type = 'text/html; charset=UTF-8' xml = negotiate_xml() if xml: req.content_type = 'application/xhtml+xml; charset=UTF-8' req.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"') req.write(' "http://www.w3.org/TR/xhtml11/DTD/xhtml11.... | |
cur.execute("""CREATE TABLE %s ( | cur.execute("""CREATE TABLE `%s` ( | def read_credentials(filename = '/root/.my.cnf'): """ Parse db admin and password from config file. """ user = password = None for line in file(filename): m = re_key_value.match(line) if m is None: continue key, value = m.groups() if key == 'user': user = value if key == 'password': password = value if user is None: ra... |
KEY (browser, browserver), KEY (engine, enginever), | KEY (browser, browser_version), KEY (engine, engine_version), | def read_credentials(filename = '/root/.my.cnf'): """ Parse db admin and password from config file. """ user = password = None for line in file(filename): m = re_key_value.match(line) if m is None: continue key, value = m.groups() if key == 'user': user = value if key == 'password': password = value if user is None: ra... |
browser INT UNSIGNED NOT NULL, browserver CHAR(10), engine INT UNSIGNED NOT NULL, enginever CHAR(10), | browser INT UNSIGNED NOT NULL, browser_version CHAR(10), engine INT UNSIGNED NOT NULL, engine_version CHAR(10), | def read_credentials(filename = '/root/.my.cnf'): """ Parse db admin and password from config file. """ user = password = None for line in file(filename): m = re_key_value.match(line) if m is None: continue key, value = m.groups() if key == 'user': user = value if key == 'password': password = value if user is None: ra... |
>>> triple_quoted_incomplete("a('''") | >>> triple_quoted_incomplete("'''") | def triple_quoted_incomplete(line): """ Test if line contains an incomplete triple-quoted string. >>> triple_quoted_incomplete("a('''") True >>> triple_quoted_incomplete("a(''''''") False >>> triple_quoted_incomplete("a('''''''''") True """ if line.count('"""') % 2: return True if line.count("'''") % 2: return True re... |
>>> triple_quoted_incomplete("a(''''''") | >>> triple_quoted_incomplete("''''''") | def triple_quoted_incomplete(line): """ Test if line contains an incomplete triple-quoted string. >>> triple_quoted_incomplete("a('''") True >>> triple_quoted_incomplete("a(''''''") False >>> triple_quoted_incomplete("a('''''''''") True """ if line.count('"""') % 2: return True if line.count("'''") % 2: return True re... |
>>> triple_quoted_incomplete("a('''''''''") | >>> triple_quoted_incomplete("'''''''''") | def triple_quoted_incomplete(line): """ Test if line contains an incomplete triple-quoted string. >>> triple_quoted_incomplete("a('''") True >>> triple_quoted_incomplete("a(''''''") False >>> triple_quoted_incomplete("a('''''''''") True """ if line.count('"""') % 2: return True if line.count("'''") % 2: return True re... |
if line.count('"""') % 2: return True if line.count("'''") % 2: return True | line = mute_strings(line) single = line.find("'''") double = line.find('"""') if single > -1 and double > -1: if single < double: return bool(line.count("'''") % 2) else: return bool(line.count('"""') % 2) elif single > -1: return bool(line.count("'''") % 2) elif double > -1: return bool(line.count('"""') % 2) | def triple_quoted_incomplete(line): """ Test if line contains an incomplete triple-quoted string. >>> triple_quoted_incomplete("a('''") True >>> triple_quoted_incomplete("a(''''''") False >>> triple_quoted_incomplete("a('''''''''") True """ if line.count('"""') % 2: return True if line.count("'''") % 2: return True re... |
Find all checks with matching first argument name and run all of them on each line. | Find all checks with matching first argument name. Then iterate over the input lines and run all checks on each line. | def check_lines(argument_name, lines, filename): """ Find all checks with matching first argument name and run all of them on each line. """ global state state = {} # {'previous_line': None} error_count = 0 checks = find_checks(argument_name) for location, line in lines: line_muted = mute_comment(mute_strings(line)) fo... |
except socket.error, (dummy, errorstring): error = ' '.join(("Could not open web address.", errorstring + '.', "Please check for typos.")) | except socket.error, error: try: (dummy, errorstring) = error.args except: errorstring = str(error) if errorstring: errorstring = errorstring[0].upper() + errorstring[1:] error = ' '.join(( "Could not open web address.", errorstring + '.', "Please check for typos.")) | def test_get(url): """ Test the URL with a GET request. If unsuccessful, redirect back to front page with error message. """ socket.setdefaulttimeout(10) protocol, server, path, query, fragment = urlparse.urlsplit(url, '') try: if protocol == 'http': connection = httplib.HTTPConnection(server) elif protocol == 'https':... |
msie, 'Internet Explorer_Server') | self.msie_window, 'Internet Explorer_Server') | def start_browser(self, browser, url): """Start browser and load website.""" self.close() command = 'c:\programme\internet explorer\iexplore.exe' os.spawnl(os.P_DETACH, command, 'iexplore', url) self.msie_window = 0 self.scroll_window = 0 timeout = 20 while timeout > 0: try: self.msie_window = window_by_classname('IEFr... |
comment = {} for key in 'author email ip posted title website'.split(): pos = content.find(key + '="') if pos >= 0: start = pos + len(key) + 2 stop = content.index('"', start) comment[key] = content[start:stop] return Markup("""</p> <h2 style="float: left; margin: 0 1ex 0 -18px;">%(title)s</h2> <p style="font-size: sma... | return self._simple_blog_comment(req, content) def _simple_blog_comment(self, req, content): comment = {} for key in 'author email ip posted title website'.split(): pos = content.find(key + '="') if pos >= 0: start = pos + len(key) + 2 stop = content.index('"', start) comment[key] = content[start:stop] if not comment.... | def render_macro(self, req, name, content): if name == 'SimpleBlogComment': comment = {} for key in 'author email ip posted title website'.split(): pos = content.find(key + '="') if pos >= 0: start = pos + len(key) + 2 stop = content.index('"', start) comment[key] = content[start:stop] return Markup("""</p> |
if len(sys.argv) != 2: | if len(sys.argv) != 3: | def read_options(): """ Read options from command line. """ full = False # Parse options. while len(sys.argv) > 1 and sys.argv[1].startswith("-"): option = sys.argv.pop(1) if option == "--full": full = True else: usage("unknown option %s" % option) if len(sys.argv) != 2: usage() # Normalize path name arguments. repos, ... |
repos, backup = sys.argv | dummy, repos, backup = sys.argv | def read_options(): """ Read options from command line. """ full = False # Parse options. while len(sys.argv) > 1 and sys.argv[1].startswith("-"): option = sys.argv.pop(1) if option == "--full": full = True else: usage("unknown option %s" % option) if len(sys.argv) != 2: usage() # Normalize path name arguments. repos, ... |
'date': format_datetime(original.time), 'rfcdate': http_date(original.time), 'author': original.author, 'comment': original.comment, | 'date': format_datetime(original['time']), 'rfcdate': http_date(original['time']), 'author': original['author'], 'comment': original['comment'], | def process_request(self, req): req.hdf['trac.href.blog'] = req.href.blog() |
entries.append((original.time, event)) | entries.append((original['time'], event)) | def process_request(self, req): req.hdf['trac.href.blog'] = req.href.blog() |
connection.request('HEAD', path) | headers = {"User-Agent": "Browsershots URL Check"} connection.request('HEAD', path, headers=headers) | def test_head(url): """ Test the URL with a HEAD request. If unsuccessful, redirect back to front page with error message. """ protocol, server, path, query, fragment = urlparse.urlsplit(url, '') try: if protocol == 'http': connection = httplib.HTTPConnection(server) elif protocol == 'https': connection = httplib.HTTPS... |
except FormatError: | except FormatError, instance: print instance.message | def check_files(files): """ Check a list of files. Exit with error code 1 if any files don't comply. """ error = False files.sort() for filename in files: try: check_file(filename) except FormatError: error = True if error: sys.exit(1) |
def print_statistics(): """ Print overall statistics (number of errors and warnings of each type) """ keys = options.counters.keys() | def get_error_statistics(): """Get error statistics.""" return get_statistics("E") def get_warning_statistics(): """Get warning statistics.""" return get_statistics("W") def get_statistics(prefix=''): """ Get statistics for message codes that start with the prefix. prefix='' matches all errors and warnings prefix=... | def print_statistics(): """ Print overall statistics (number of errors and warnings of each type) """ keys = options.counters.keys() keys.sort() for key in keys: if key[0] in 'EW': print '%-7s %s %s' % (options.counters[key], key, options.messages[key]) |
if key[0] in 'EW': print '%-7s %s %s' % (options.counters[key], key, options.messages[key]) def get_error_statistics(): """ Get error statistics. """ return get_statistics("E") def get_warning_statistics(): """ Get warning statistics. """ return get_statistics("W") def get_statistics(type): """ Get statistics for m... | if key.startswith(prefix): stats.append('%-7s %s %s' % (options.counters[key], key, options.messages[key])) | def print_statistics(): """ Print overall statistics (number of errors and warnings of each type) """ keys = options.counters.keys() keys.sort() for key in keys: if key[0] in 'EW': print '%-7s %s %s' % (options.counters[key], key, options.messages[key]) |
def print_benchmark(): | def print_statistics(prefix=''): """Print overall statistics (number of errors and warnings).""" for line in get_statistics(prefix): print line def print_benchmark(elapsed): | def print_benchmark(): """ Print benchmark numbers. """ print '%-7.2f %s' % (elapsed, 'seconds elapsed') keys = ['directories', 'files', 'logical lines', 'physical lines'] for key in keys: if key in options.counters: print '%-7d %s per second (%d total)' % ( options.counters[key] / elapsed, key, options.counters[key]) |
print_benchmark() | print_benchmark(elapsed) | def _main(): """ Parse options and run checks on Python source. """ options, args = process_options() if options.doctest: import doctest return doctest.testmod() start_time = time.time() for path in args: if os.path.isdir(path): input_dir(path) else: input_file(path) elapsed = time.time() - start_time if options.statis... |
self.js("window.resizeTo(screen.width,screen.height)") | time.sleep(1) self.js("window.resizeTo(screen.availWidth,screen.availHeight)") | def start_browser(self, browser, url): """Start browser and load website.""" self.safari = appscript.app('Safari') self.js("window.moveTo(0,0)") self.js("window.resizeTo(screen.width,screen.height)") time.sleep(1) self.js("document.location='%s'" % url) for dummy in range(10): time.sleep(3) if self.ready_state(): break |
def ready_state(): | def ready_state(self): | def ready_state(): """Get progress indicator.""" answer = self.js("document.readyState") return answer == u'complete' |
def _main(): """ Parse command line options and run checks on Python source. """ global options | def print_statistics(): """ Print overall statistics (number of errors and warnings of each type) """ keys = options.counters.keys() keys.sort() for key in keys: if key[0] in 'EW': print '%-7s %s %s' % (options.counters[key], key, options.messages[key]) def get_error_statistics(): """ Get error statistics. """ return... | def _main(): """ Parse command line options and run checks on Python source. """ global options usage = "%prog [options] input ..." parser = OptionParser(usage) parser.add_option('-v', '--verbose', default=0, action='count', help="print status messages, or debug with -vv") parser.add_option('-q', '--quiet', default=0, ... |
options, args = parser.parse_args() if options.doctest: import doctest return doctest.testmod() | options, args = parser.parse_args(arglist) | def _main(): """ Parse command line options and run checks on Python source. """ global options usage = "%prog [options] input ..." parser = OptionParser(usage) parser.add_option('-v', '--verbose', default=0, action='count', help="print status messages, or debug with -vv") parser.add_option('-q', '--quiet', default=0, ... |
start_time = time.time() | def _main(): """ Parse command line options and run checks on Python source. """ global options usage = "%prog [options] input ..." parser = OptionParser(usage) parser.add_option('-v', '--verbose', default=0, action='count', help="print status messages, or debug with -vv") parser.add_option('-q', '--quiet', default=0, ... | |
keys = options.counters.keys() keys.sort() for key in keys: if key[0] in 'EW': print '%-7s %s %s' % (options.counters[key], key, options.messages[key]) | print_statistics() | def _main(): """ Parse command line options and run checks on Python source. """ global options usage = "%prog [options] input ..." parser = OptionParser(usage) parser.add_option('-v', '--verbose', default=0, action='count', help="print status messages, or debug with -vv") parser.add_option('-q', '--quiet', default=0, ... |
print '%-7.2f %s' % (elapsed, 'seconds elapsed') keys = ['directories', 'files', 'logical lines', 'physical lines'] for key in keys: if key in options.counters: print '%-7d %s per second (%d total)' % ( options.counters[key] / elapsed, key, options.counters[key]) | print_benchmark() | def _main(): """ Parse command line options and run checks on Python source. """ global options usage = "%prog [options] input ..." parser = OptionParser(usage) parser.add_option('-v', '--verbose', default=0, action='count', help="print status messages, or debug with -vv") parser.add_option('-q', '--quiet', default=0, ... |
except appscript.specifier.CommandError: | except: | def js(self, command): """Run JavaScript in Safari.""" try: return self.safari.do_JavaScript(command, in_=self.safari.documents[0]) except appscript.specifier.CommandError: return None |
def __init__(width, height, bpp, dpi): | def __init__(self, width, height, bpp, dpi): | def __init__(width, height, bpp, dpi): self.width = width self.height = height self.bpp = bpp self.dpi = dpi |
flushed = compressor.flush() if len(compressed) or len(flushed): self.write_chunk(outfile, 'IDAT', compressed + flushed) | else: compressed = '' flushed = compressor.flush() if len(compressed) or len(flushed): self.write_chunk(outfile, 'IDAT', compressed + flushed) | def write(self, outfile, scanlines, interlaced=False): """ Write a PNG image to the output file. """ # http://www.w3.org/TR/PNG/#5PNG-file-signature outfile.write(struct.pack("8B", 137, 80, 78, 71, 13, 10, 26, 10)) |
if options.alpha: | if options.alpha is not None: | def _main(): """ Run the PNG encoder with options from the command line. """ # Parse command line arguments from optparse import OptionParser version = '%prog ' + __revision__.strip('$').replace('Rev: ', 'r') parser = OptionParser(version=version) parser.set_usage("%prog [options] [pnmfile]") parser.add_option("-i", "-... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.