def test(): import sys import regsub args = sys.argv[1:] if not args: args = [ '/etc/passwd', 'file:/etc/passwd', 'file://localhost/etc/passwd', 'ftp://ftp.cwi.nl/etc/passwd', 'gopher://gopher.cwi.nl/11/', 'http://www.cwi.nl/index.html', ] try: for url in args: print '-' * 10, url, '-' * 10 fn, h = urlretrieve(url) print fn, h if h: print '======' for k in h.keys(): print k + ':', h[k] print '======' fp = open(fn, 'r') data = fp.read() del fp print regsub.gsub('\r', '', data) fn, h = None, None print '-' * 40 finally: urlcleanup()
def test(): import sys import regsub args = sys.argv[1:] if not args: args = [ '/etc/passwd', 'file:/etc/passwd', 'file://localhost/etc/passwd', 'ftp://ftp.cwi.nl/etc/passwd', 'gopher://gopher.cwi.nl/11/', 'http://www.cwi.nl/index.html', ] try: for url in args: print '-'*10, url, '-'*10 fn, h = urlretrieve(url) print fn, h if h: print '======' for k in h.keys(): print k + ':', h[k] print '======' fp = open(fn, 'r') data = fp.read() del fp print regsub.gsub('\r', '', data) fn, h = None, None print '-'*40 finally: urlcleanup()
def escape(s): """Replace special characters '&', '<' and '>' by SGML entities.""" import regsub s = regsub.gsub("&", "&", s) # Must be done first! s = regsub.gsub("<", "<", s) s = regsub.gsub(">", ">", s) return s
def processrawspec(self, raw): if self.whole.search(raw) < 0: self.report("Bad raw spec: %s", `raw`) return type, name, args = self.whole.group('type', 'name', 'args') type = regsub.gsub("\*", " ptr", type) type = regsub.gsub("[ \t]+", "_", type) if name in self.alreadydone: self.report("Name has already been defined: %s", `name`) return self.report("==> %s %s <==", type, name) if self.blacklisted(type, name): self.error("*** %s %s blacklisted", type, name) return returnlist = [(type, name, 'ReturnMode')] returnlist = self.repairarglist(name, returnlist) [(type, name, returnmode)] = returnlist arglist = self.extractarglist(args) arglist = self.repairarglist(name, arglist) if self.unmanageable(type, name, arglist): ##for arg in arglist: ## self.report(" %s", `arg`) self.error("*** %s %s unmanageable", type, name) return self.alreadydone.append(name) self.generate(type, name, arglist)
def _ctag(str, hrefs=()): """Quote, tag, and escape the text. This is a modified version of the 'ctag' function appearing in StructuredText.py. The differences include, * it uses _split, so that it avoids escaping text in quotes or in math-mode. * it processes hrefs. * it escapes LaTeX special characters. * it doesn't try to find duplicate list items - that got moved into LaTeX. """ if str is None: str = '' str = ' %s' % str # prepend a space str = _split(str) for i in xrange(len(str)): if not i % 2: str[i] = regsub.gsub(quotable_re, '\\verb@\\0@', str[i]) str[i] = regsub.gsub(slashable_re, '\\\\\\0', str[i]) str[i] = regsub.gsub(ST.strong, ' {\\bfseries \\1}\\2', str[i]) str[i] = regsub.gsub(ST.em, ' {\\itshape \\1}\\2', str[i]) for ref, link in hrefs: tag = '{\slshape %s}\\footnote{%s}' % (ref[1:-1], link) str[i] = string.joinfields(string.split(str[i], ref), tag) return string.joinfields(str)
def Main(): form = cgi.FormContent() if not form.has_key("stations"): style.SendError("No station specified!") if not form.has_key("dataCols"): style.SendError("No data specified!") stations = form["stations"] dataCols = form["dataCols"] stationTables = map(addYear, stations) year = form["year"][0] startMonth = str( form["startMonth"][0] ) startDay = str( form["startDay"][0] ) endMonth = str( form["endMonth"][0] ) endDay = str( form["endDay"][0] ) timeType = form["timeType"][0] startTime = startMonth+"-"+startDay+"-"+year endTime = endMonth+"-"+endDay+"-"+year dataCols = tuple(dataCols) strDataCols = str(dataCols)[1:-2] strDataCols = regsub.gsub("'", " ", strDataCols) if timeType == "hourly": mydb = pg.connect('campbellHourly', 'localhost', 5432) strDataCols = "date_part('year', day) AS year, date_part('month', day) AS month, date_part('day', day) AS day, date_part('hour', day) AS hour, "+strDataCols else: mydb = pg.connect('campbellDaily', 'localhost', 5432) strDataCols = "date_part('year', day) AS year, date_part('month', day) AS month, date_part('day', day) AS day, "+strDataCols print 'Content-type: text/plain \n\n' print """ # Output for Iowa Campbell Station Data # Notes on the format of this data and units can be found at # http://www.pals.iastate.edu/campbell/info.txt # If you have trouble getting the data you want, please send email to [email protected] """ for stationTable in stationTables: queryStr = "SELECT day as sortday, '"+stationTable[:-5]+"' as statid, "+strDataCols+" from "+stationTable+" WHERE day >= '"+startTime+"' and day <= '"+endTime+"' ORDER by sortday ASC" # print queryStr results = mydb.query(queryStr) headings = results.listfields()[1:] strHeadings = str(tuple(headings))[1:-2] strHeadings = regsub.gsub("'", " ", strHeadings) print regsub.gsub(",", " ", strHeadings) results = results.getresult() printer(results, timeType) print "\n\n\n" print "#EOF"
def Main(): form = FormContent() area = form["area"][0] spec = form["spec"][0] link = form["link"][0] url = form["url"][0] area = regsub.gsub(" ","_", area) spec = regsub.gsub(" ","_", spec) link = regsub.gsub(" ","_", link) url = regsub.gsub(" ","_", url) print 'Content-type: text/html \n\n' check = mydb.query("select * from mt101 where link = '"+url+"'").getresult() if len(check) > 0: delete = mydb.query("delete from mt101 where link = '"+url+"'") print "Deleted Old Entry" update = mydb.query("insert into mt101 values('"+area+"','"+spec+"','"+url+"','"+link+"')") print '<HTML><HEAD>' print '<meta http-equiv="Refresh" content="1; URL='+url+'">' print '</HEAD><BODY BGCOLOR="white">' print 'Successfully entered'
def viewer(): if form.has_key("url"): url = form["url"][0] urlloader(url) elif form.has_key("titleA"): titleA = form["titleA"][0] titleA = regsub.gsub('_',' ', titleA) sloader(titleA) elif form.has_key("titleB"): titleB = form["titleB"][0] titleB = regsub.gsub('_',' ', titleB) floader(titleB) elif form.has_key("titleC"): titleC = form["titleC"][0] cloader(titleC) elif form.has_key("titleD"): titleD = form["titleD"][0] loadertwo(titleD) elif form.has_key("titleE"): titleE = form["titleE"][0] titler(titleE) elif form.has_key("title"): title = form["title"][0] titlertwo(title) elif form.has_key("search"): blah = form["search"][0] sloader(blah) elif form.has_key("searchloc"): save_search() elif form.has_key("saved"): saved() else: url = "/index.html" startmain()
def discover_panel_modules(self): """Identify candidate panels. Return list of tuples describing found panel modules: (name, modname, moddir). Candidate modules must end in 'prefs.py' or 'prefs.pyc'. The name is formed by extracting the prefix and substituting spaces for underscores (with leading and trailing spaces stripped). For multiple panels with the same name, the last one found is used.""" got = {} for dir in panels_dirs: entries = [] try: entries = os.listdir(dir) except os.error: # Optional dir not there. pass for entry in entries: if modname_matcher.match(entry) != -1: name = regsub.gsub("_", " ", modname_matcher.group(1)) class_name = regsub.gsub("_", "", modname_matcher.group(1)) got[name] = ((string.strip(name), class_name, entry, dir)) return got.values()
def _ctag(str, hrefs=()): """Quote, tag, and escape the text. This is a modified version of the 'ctag' function appearing in StructuredText.py. The differences include, * it uses _split, so that it avoids escaping text in quotes or in math-mode. * it processes hrefs. * it escapes LaTeX special characters. * it doesn't try to find duplicate list items - that got moved into LaTeX. """ if str is None: str = '' str = ' %s' % str # prepend a space str = _split(str) for i in xrange(len(str)): if not i%2: str[i]=regsub.gsub(quotable_re, '\\verb@\\0@', str[i]) str[i]=regsub.gsub(slashable_re, '\\\\\\0', str[i]) str[i]=regsub.gsub(ST.strong,' {\\bfseries \\1}\\2', str[i]) str[i]=regsub.gsub(ST.em,' {\\itshape \\1}\\2',str[i]) for ref, link in hrefs: tag = '{\slshape %s}\\footnote{%s}' % (ref[1:-1], link) str[i] = string.joinfields(string.split(str[i], ref), tag) return string.joinfields(str)
def spew(clearol=0, clearul=0): global content, body, ollev, ullev if content: if entityprog.search(content) > -1: content = regsub.gsub('&', '&', content) content = regsub.gsub('<', '<', content) content = regsub.gsub('>', '>', content) n = questionprog.match(content) if n > 0: content = '<em>' + content[n:] + '</em>' if ollev: # question reference in index fragid = regsub.gsub('^ +|\.? +$', '', secnum) content = '<a href="#%s">%s</a>' % (fragid, content) if element[0] == 'h': # heading in the main text fragid = regsub.gsub('^ +|\.? +$', '', secnum) content = secnum + '<a name="%s">%s</a>' % (fragid, content) n = answerprog.match(content) if n > 0: # answer paragraph content = regsub.sub(sentprog, '<strong>\\1</strong>', content[n:]) body.append('<' + element + '>' + content) body.append('</' + element + '>') content = '' while clearol and ollev: upol() if clearul and ullev: body.append('</ul>') ullev = 0
def process(fi, fo): inverbatim = 0 line = '\n' nextline = fi.readline() while nextline: prevline = line line = nextline nextline = fi.readline() fmt = None if dashes.match(nextline) >= 0: fmt = '\\subsection{%s}\n' elif equals.match(nextline) >= 0: fmt = '\\section{%s}\n' elif stars.match(nextline) >= 0: fmt = '\\chapter{%s}\n' if fmt: nextline = '\n' line = fmt % string.strip(line) if '(' in line: line = regsub.gsub('[a-zA-Z0-9_]+()', '{\\\\tt \\0}', line) elif inverbatim: if blank.match(line) >= 0 and \ indented.match(nextline) < 0: inverbatim = 0 fo.write('\\end{verbatim}\n') else: if indented.match(line) >= 0 and \ blank.match(prevline) >= 0: inverbatim = 1 fo.write('\\begin{verbatim}\n') if inverbatim: line = string.expandtabs(line, 4) elif not fmt and '(' in line: line = regsub.gsub('[a-zA-Z0-9_]+()', '\\\\code{\\0}', line) fo.write(line)
def spew(clearol=0, clearul=0): global content, body, ollev, ullev if content: if entityprog.search(content) > -1: content = regsub.gsub('&', '&', content) content = regsub.gsub('<', '<', content) content = regsub.gsub('>', '>', content) n = questionprog.match(content) if n > 0: content = '<em>' + content[n:] + '</em>' if ollev: # question reference in index fragid = regsub.gsub('^ +|\.? +$', '', secnum) content = '<a href="#%s">%s</a>' % (fragid, content) if element[0] == 'h': # heading in the main text fragid = regsub.gsub('^ +|\.? +$', '', secnum) content = secnum + '<a name="%s">%s</a>' % (fragid, content) n = answerprog.match(content) if n > 0: # answer paragraph content = regsub.sub(sentprog, '<strong>\\1</strong>', content[n:]) body.append('<' + element + '>' + content) body.append('</' + element + '>') content = '' while clearol and ollev: upol() if clearul and ullev: body.append('</ul>'); ullev = 0
def processrawspec(self, raw): if self.whole.search(raw) < 0: self.report("Bad raw spec: %s", ` raw `) return type, name, args = self.whole.group('type', 'name', 'args') type = regsub.gsub("\*", " ptr", type) type = regsub.gsub("[ \t]+", "_", type) if name in self.alreadydone: self.report("Name has already been defined: %s", ` name `) return self.report("==> %s %s <==", type, name) if self.blacklisted(type, name): self.error("*** %s %s blacklisted", type, name) return returnlist = [(type, name, 'ReturnMode')] returnlist = self.repairarglist(name, returnlist) [(type, name, returnmode)] = returnlist arglist = self.extractarglist(args) arglist = self.repairarglist(name, arglist) if self.unmanageable(type, name, arglist): ##for arg in arglist: ## self.report(" %s", `arg`) self.error("*** %s %s unmanageable", type, name) return self.alreadydone.append(name) self.generate(type, name, arglist)
def main(): metaHtmlFilename = "Quaero/web/quaero_meta.html" standardHtmlFilename = "Quaero/web/quaero.html" latex2htmlLogFilename = "Quaero/doc/manual/html.log" metaHtml = open(metaHtmlFilename,'r') standardHtml = open(standardHtmlFilename,'w') classified=0 for line1 in metaHtml.readlines(): keys = re.search("helpwindow_MANUAL\((.*)\)\.html",line1) if(not keys==None): key = keys.group(1) key = regsub.gsub("\+","\\+",key) latex2htmlLog = open(latex2htmlLogFilename,'r') foundNodeNumber = 0 for line2 in latex2htmlLog.readlines(): nodeNumber = re.search('"'+key+'" for node([0-9]*)\.html',line2) if(not nodeNumber==None): line1 = regsub.gsub("helpwindow_MANUAL("+key+").html","manual/manual/node"+nodeNumber.group(1)+".html",line1) foundNodeNumber = 1 if(foundNodeNumber==0): print 'Key "'+key+'" not found.' latex2htmlLog.close() if regex.search("BeginClassified",line1) >= 0: classified=1 if regex.search("EndClassified",line1) >= 0: classified=0 if(classified==0): standardHtml.write(line1) if regex.search("</html>",line1) >= 0: break metaHtml.close() standardHtml.close()
def add_entry(ticks, comments, analysis, caseNum): comments = regsub.gsub("'","´", comments) analysis = regsub.gsub("'","´", analysis) thisDate = DateTime.gmtime(ticks) findDate = DateTime.ISO.strGMT(thisDate) delete = mydb.query("delete from annotations WHERE validtime = '"+findDate+"' and casenum = '"+caseNum+"' ") insert = mydb.query("insert into annotations (validtime, comments, analysis, casenum) values('"+findDate+"','"+comments+"','"+analysis+"','"+caseNum+"')") print 'DONE'
def mungeFile(file): # Read the file and modify it so that it can be bundled with the # other Pmw files. file = 'Pmw' + file + '.py' text = open(os.path.join(srcdir, file)).read() text = regsub.gsub('import Pmw\>', '', text) text = regsub.gsub('INITOPT = Pmw.INITOPT', '', text) text = regsub.gsub('\<Pmw\.', '', text) text = '\n' + ('#' * 70) + '\n' + '### File: ' + file + '\n' + text return text
def extractarg(self, part): mode = "InMode" if self.asplit.match(part) < 0: self.error("Indecipherable argument: %s", `part`) return ("unknown", part, mode) type, name = self.asplit.group('type', 'name') type = regsub.gsub("\*", " ptr ", type) type = string.strip(type) type = regsub.gsub("[ \t]+", "_", type) return self.modifyarg(type, name, mode)
def extractarg(self, part): mode = "InMode" if self.asplit.match(part) < 0: self.error("Indecipherable argument: %s", ` part `) return ("unknown", part, mode) type, name = self.asplit.group('type', 'name') type = regsub.gsub("\*", " ptr ", type) type = string.strip(type) type = regsub.gsub("[ \t]+", "_", type) return self.modifyarg(type, name, mode)
def psbars(self): psbits=regsub.gsub("1","I ",self.bits) psbits=regsub.gsub("0","O ",psbits) psbits=regsub.gsub("L","L ",psbits) linewidth=50 p=0; j=linewidth; m=len(psbits); psbarlines=[]; blanks="^ | $" while p <= m: j = min(linewidth,m-p) psbarlines = psbarlines + [ regsub.gsub(blanks,"",psbits[p:p+j]) ] p=p+linewidth return [ "0 0 moveto" ] + psbarlines + [ "stroke" ]
def Main(): print 'Content-type: text/html \n\n' print '<HTML><HEAD></HEAD><BODY BGCOLOR="white">' form = FormContent() area = form["area"][0] spec = form["spec"][0] area = regsub.gsub(" ","_", area) spec = regsub.gsub(" ","_", spec) html_content(area, spec)
def Main(): print 'Content-type: text/html\n\n' print '<HEADER>\n<TITLE>Entering message</TITLE>\n</HEADER>\n' print '<BODY bgcolor="white">\n' form = FormContent() subject = form["subject"][0] name = form["name"][0] address = form["address"][0] description = form["description"][0] subject = regsub.gsub("'","´",subject) name = regsub.gsub("'","´",name) description = regsub.gsub("'","´",description) if not form.has_key("subject"): SendError("You need to enter a subject") if not form.has_key("name"): SendError("You should enter your name") if not form.has_key("address"): SendError("What is your email address") if not form.has_key("description"): SendError("What is it's description") time = os.popen('date', 'r').read() enter = mydbase.query("INSERT INTO board VALUES('"+time+"','"+subject+"','"+name+"','"+address+"','"+description+"')") print '<img src="../../images/pals_logo.gif" align=left>\n' print '<spacer type=vertical size="30">\n' print '<H1>PALS bulletin board</H1>\n' print '<a href="http://www.pals.iastate.edu/home/bboard.html">Add comment</a>' print '<BR CLEAR="all"><HR>' search = mydbase.query("select * from board") search = search.getresult() for i in range(len(search)): subject = search[i][1] name = search[i][2] address = search[i][3] description = search[i][4] date = search[i][0] date = date[4:10]+date[22:27] print "<P>\n<b>Subject:" print subject+'</b>' print "<BR>\n<dd>" print description print "<BR>\n" print '<P align="right">' print "( Posted by:" print '<A HREF="mailto:'+address+'" STYLE="color:blue">'+name+'</A>' print 'Posted on:' print date+')' print '</p><HR>'
def compact(dsn, path_src, path_dest=None, hwnd=0): if not os.path.isfile(path_src): raise ValueError, "database file (%s) does not exist!" % path_src else: if path_dest is None: path_dest = path_src path_src = regsub.gsub('/', '\\', path_src) path_dest = regsub.gsub('/', '\\', path_dest) result = odbc_installer.config_data_source( odbc_installer.ODBC_ADD_DSN, JET_DRIVER_NAME, 'COMPACT_DB=%s %s General\000\000' % (path_src, path_dest), hwnd) return result
def process(fp, outfp, env = {}): lineno = 0 while 1: line = fp.readline() if not line: break lineno = lineno + 1 n = p_define.match(line) if n >= 0: # gobble up continuation lines while line[-2:] == '\\\n': nextline = fp.readline() if not nextline: break lineno = lineno + 1 line = line + nextline name = p_define.group(1) body = line[n:] # replace ignored patterns by spaces for p in ignores: body = regsub.gsub(p, ' ', body) # replace char literals by ord(...) body = regsub.gsub(p_char, 'ord(\\0)', body) stmt = '%s = %s\n' % (name, string.strip(body)) ok = 0 try: exec stmt in env except: sys.stderr.write('Skipping: %s' % stmt) else: outfp.write(stmt) n =p_macro.match(line) if n >= 0: macro, arg = p_macro.group(1, 2) body = line[n:] for p in ignores: body = regsub.gsub(p, ' ', body) body = regsub.gsub(p_char, 'ord(\\0)', body) stmt = 'def %s(%s): return %s\n' % (macro, arg, body) try: exec stmt in env except: sys.stderr.write('Skipping: %s' % stmt) else: outfp.write(stmt) if p_include.match(line) >= 0: regs = p_include.regs a, b = regs[1] filename = line[a:b] if not filedict.has_key(filename): filedict[filename] = None outfp.write( '\n# Included from %s\n' % filename) inclfp = open('/usr/include/' + filename, 'r') process(inclfp, outfp, env)
def process(fp, outfp, env={}): lineno = 0 while 1: line = fp.readline() if not line: break lineno = lineno + 1 n = p_define.match(line) if n >= 0: # gobble up continuation lines while line[-2:] == '\\\n': nextline = fp.readline() if not nextline: break lineno = lineno + 1 line = line + nextline name = p_define.group(1) body = line[n:] # replace ignored patterns by spaces for p in ignores: body = regsub.gsub(p, ' ', body) # replace char literals by ord(...) body = regsub.gsub(p_char, 'ord(\\0)', body) stmt = '%s = %s\n' % (name, string.strip(body)) ok = 0 try: exec stmt in env except: sys.stderr.write('Skipping: %s' % stmt) else: outfp.write(stmt) n = p_macro.match(line) if n >= 0: macro, arg = p_macro.group(1, 2) body = line[n:] for p in ignores: body = regsub.gsub(p, ' ', body) body = regsub.gsub(p_char, 'ord(\\0)', body) stmt = 'def %s(%s): return %s\n' % (macro, arg, body) try: exec stmt in env except: sys.stderr.write('Skipping: %s' % stmt) else: outfp.write(stmt) if p_include.match(line) >= 0: regs = p_include.regs a, b = regs[1] filename = line[a:b] if not filedict.has_key(filename): filedict[filename] = None outfp.write('\n# Included from %s\n' % filename) inclfp = open('/usr/include/' + filename, 'r') process(inclfp, outfp, env)
def Main(): print 'Content-type: text/html \n\n' form = cgi.FormContent() bNumber = form["bNumber"][0] bTime = regsub.gsub( " ", "+", form["bTime"][0]) bTime = regsub.gsub( "_", " ", bTime) tableName = "t"+bTime[:4]+"_"+bTime[5:7] results = mydb.query("SELECT everything from "+tableName+" WHERE bTime = '"+bTime+"' and bNumber = '"+bNumber+"' ").dictresult() print '<PRE>' print regsub.gsub("\015\012", "", results[0]["everything"] ) print '</PRE>'
def Main(): form = FormContent() if not form.has_key("link"): style.SendError("Enter a Link") mylink = form["link"][0] mylink = regsub.gsub("'","´",mylink) if not form.has_key("URL"): style.SendError("Enter an URL") myURL = form["URL"][0] if not form.has_key("description"): style.SendError("What is it's description") mydescription = form["description"][0] mydescription = regsub.gsub("'","´",mydescription) style.header('Links Submitter','/images/ISU_bkgrnd.gif') mykindA = "null" mykindB = "null" mykindC = "null" mykindD = "null" if form.has_key("kindA"): mykindA = form["kindA"][0] if form.has_key("kindB"): mykindB = form["kindB"][0] if form.has_key("kindC"): mykindC = form["kindC"][0] if form.has_key("kindD"): mykindD = form["kindD"][0] mytime = os.popen('date', 'r').read() search = mydbase.query("select * from linkex where url = '"+myURL+"'") search = search.getresult() if len(search) > 0: style.std_top("URL already taken") sys.exit(0) search2 = mydbase.query("select * from linkex where link = '"+mylink+"'") search2 = search2.getresult() if len(search2) > 0: style.std_top("Link title aready taken") sys.exit(0) enter = mydbase.query("INSERT INTO linkex VALUES( ' " + mylink+"','"+myURL+"','"+mykindA+"','"+mykindB+"','"+mykindC+"','"+mykindD+"','"+mydescription+"', '"+mytime+"')") style.std_top('Your link to "'+mylink+'" was saved!') print '<br><P>You can now:<ul>' print '<li><a href="http://www.pals.iastate.edu/cgi-bin/daryl_dev/printout.py">View all the links</a>' print '<li><a href="http://www.pals.iastate.edu/index.html">Go back to PALS Homepage</a>' print '<spacer type="vertical" size="300">' style.std_bot()
def load(self, name, reloading=0): """Import the panel module and init the instance. Returns 1 if successful, None otherwise.""" entry = self.panels[name] try: sys.path.insert(0, entry[2]) try: modnm = entry[0][:string.index(entry[0], '.')] mod = __import__(modnm) if reload: reload(mod) class_name = (regsub.gsub(" ", "", name) + PANEL_CLASS_NAME_SUFFIX) # Instantiate it: entry[3] = getattr(mod, class_name)(name, self.app) return 1 except: # Whatever may go wrong in import or panel post e, v, tb = sys.exc_type, sys.exc_value, sys.exc_traceback self.app.root.report_callback_exception(e, v, tb) return None finally: try: sys.path.remove(entry[1]) except ValueError: pass
def _split(s): """Split a string into normal and quoted pieces. Splits a string into normal and quoted (or math mode) sections. Returns a list where the even elements are normal text, and the odd elements are quoted. The appropiate quote tags ($ and \\verb) are applied to the quoted text. """ r = [] while 1: epos = eqn_re.search(s) qpos = ST.code.search(s) if epos == qpos: ## == -1 break elif (qpos == -1) or (epos != -1 and epos < qpos): r.append(s[:epos]) end = epos + eqn_re.match(s[epos:]) arg = [eqn_re.group(1), eqn_re.group(3)] if not arg[1]: arg[1] = '' r.append(' $%s$%s ' % tuple(arg)) else: ## (epos==-1) or (qpos != -1 and epos > qpos): r.append(s[:qpos]) end = qpos + ST.code.match(s[qpos:]) arg = [ regsub.gsub(carrot_re, '^\\verb@\\0@\\verb^', ST.code.group(1)), ST.code.group(3) ] if not arg[1]: arg[1] = '' r.append(' \\verb^%s^%s ' % tuple(arg)) s = s[end:] r.append(s) return r
def write(self, str): if self.edit: self.edit.SetSel(-2) # translate \n to \n\r self.edit.ReplaceSel(regsub.gsub('\n','\r\n',str)) else: win32ui.OutputDebug("dlgapp - no edit control! >>\n%s\n<<\n" % str )
def saved(): print "<H1>Titles of Previous Searches</H1>\n" print '<HR>' print '<TABLE BORDER="1">\n<TR>\n' print '<TH ALIGN="LEFT" VALIGN="TOP" WIDTH="125">Username:</TH>' print '<th ALIGN="LEFT" VALIGN="TOP" WIDTH="125">You Searched For:</TH>' print '<th ALIGN="LEFT" VALIGN="TOP" WIDTH="125">In directories:</TH>' print '<th ALIGN="LEFT" VALIGN="TOP" WIDTH="50">Entries Returned:</TH>' print '<TH align="left" VALIGN="top" WIDTH="225">Click title to view search:</th></TR>' form = FormContent() user = form["user"][0] lresults = mydbase.query("select * from users where user = '******'") lresults = lresults.getresult() if len(lresults) > 0: for i in range(len(lresults)): string = lresults[i][2] field = lresults[i][3] title = lresults[i][1] filename = lresults[i][4] total = lresults[i][5] print '<tr>' print '<TD ALIGN="LEFT" VALIGN="CENTER">'+user+'</TD>' print '<TD ALIGN="LEFT" VALIGN="CENTER">'+string+'</TD>' if filename == "%": filename = "All Directories" print '<TD ALIGN="LEFT" VALIGN="CENTER">'+filename+'</TD>' print '<TD ALIGN="CENTER" VALIGN="CENTER">',total,'</TD>' title = regsub.gsub(' ','_', title) print '<TD ALIGN="LEFT" VALIGN="CENTER"><a href="'+home+'&titleA='+title+'">'+title+'</a></TD>' print '</TR>' else: print "Your username not found" print '</table>\n'
def opensocket(group, port): # Create the socket s = socket(AF_INET, SOCK_DGRAM) # Allow multiple copies of this program on one machine s.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1) # (Not strictly needed) # Bind the port to it s.bind('', port) # Look up the group once group = gethostbyname(group) # Construct binary group address group_bytes = eval(regsub.gsub('\.', ',', group)) grpaddr = 0 for byte in group_bytes: grpaddr = (grpaddr << 8) | byte # Construct struct mreq from grpaddr and ifaddr ifaddr = INADDR_ANY mreq = struct.pack('ll', grpaddr, ifaddr) # Add group membership s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq) return s
def checkin(self, name_rev, message=None, otherflags=""): """Check in NAME_REV from its work file. The optional MESSAGE argument becomes the checkin message (default "<none>" if None); or the file description if this is a new file. The optional OTHERFLAGS argument is passed to ci without interpretation. Any output from ci goes to directly to stdout. """ name, rev = self._unmangle(name_rev) new = not self.isvalid(name) if not message: message = "<none>" if message and message[-1] != '\n': message = message + '\n' lockflag = "-u" textfile = None try: if new: textfile = tempfile.mktemp() f = open(textfile, 'w') f.write(message) f.close() cmd = 'ci %s%s -t%s %s %s' % \ (lockflag, rev, textfile, otherflags, name) else: message = regsub.gsub('\([\\"$`]\)', '\\\\\\1', message) cmd = 'ci %s%s -m"%s" %s %s' % \ (lockflag, rev, message, otherflags, name) return self._system(cmd) finally: if textfile: self._remove(textfile)
def parse_qs(qs, keep_blank_values=None): """Parse a query given as a string argumen Arguments: qs : URL-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in URL encoded queries should be treated as blank strings. A true value inicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. """ import urllib, regsub name_value_pairs = string.splitfields(qs, '&') dict = {} for name_value in name_value_pairs: nv = string.splitfields(name_value, '=') if len(nv) != 2: continue name = nv[0] value = urllib.unquote(regsub.gsub('+', ' ', nv[1])) if len(value) or keep_blank_values: if dict.has_key (name): dict[name].append(value) else: dict[name] = [value] return dict
def _split(s): """Split a string into normal and quoted pieces. Splits a string into normal and quoted (or math mode) sections. Returns a list where the even elements are normal text, and the odd elements are quoted. The appropiate quote tags ($ and \\verb) are applied to the quoted text. """ r = [] while 1: epos = eqn_re.search(s) qpos = ST.code.search(s) if epos == qpos: ## == -1 break elif (qpos == -1) or (epos != -1 and epos < qpos): r.append(s[:epos]) end = epos + eqn_re.match(s[epos:]) arg = [eqn_re.group(1), eqn_re.group(3)] if not arg[1]: arg[1] = '' r.append( ' $%s$%s ' % tuple(arg)) else: ## (epos==-1) or (qpos != -1 and epos > qpos): r.append(s[:qpos]) end = qpos + ST.code.match(s[qpos:]) arg = [regsub.gsub(carrot_re, '^\\verb@\\0@\\verb^', ST.code.group(1)), ST.code.group(3)] if not arg[1]: arg[1] = '' r.append(' \\verb^%s^%s ' % tuple(arg)) s = s[end:] r.append(s) return r
def openmcastsock(group, port): # Import modules used only here import regsub import socket import struct from SOCKET import * from IN import * # # Create a socket s = socket.socket(AF_INET, SOCK_DGRAM) # # Allow multiple copies of this program on one machine # (not strictly needed) s.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1) # # Bind it to the port s.bind(('', port)) # # Look up multicast group address in name server # (doesn't hurt if it is already in ddd.ddd.ddd.ddd format) group = socket.gethostbyname(group) # # Construct binary group address bytes = eval(regsub.gsub('\.', ',', group)) grpaddr = 0 for byte in bytes: grpaddr = (grpaddr << 8) | byte # # Construct struct mreq from grpaddr and ifaddr ifaddr = INADDR_ANY mreq = struct.pack('ll', grpaddr, ifaddr) # # Add group membership s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq) # return s
def __init__(self, *args): c = len(args) if c == 1: name, val = None, args[0] elif c == 2: name, val = args[0], args[1] else: raise ValueError, "Invalid arguments" h = {"Content-Type": {"_v": ""}, "Content-Transfer-Encoding": {"_v": ""}, "Content-Disposition": {"_v": ""}} dt = type(val) b = t = None if dt == DictType: t = 1 b = self.boundary() d = [] h["Content-Type"]["_v"] = "multipart/form-data; boundary=%s" % b for n, v in val.items(): d.append(MultiPart(n, v)) elif (dt == ListType) or (dt == TupleType): raise ValueError, "Sorry, nested multipart is not done yet!" elif dt == FileType or hasattr(val, "read"): if hasattr(val, "name"): fn = gsub("\\\\", "/", val.name) fn = fn[(rfind(fn, "/") + 1) :] ex = fn[(rfind(fn, ".") + 1) :] if self._extmap.has_key(ex): ct = self._extmap[ex] else: ct = self._extmap[""] else: fn = "" ct = self._extmap[None] if self._encmap.has_key(ct): ce = self._encmap[ct] else: ce = "" h["Content-Disposition"]["_v"] = "form-data" h["Content-Disposition"]["name"] = '"%s"' % name h["Content-Disposition"]["filename"] = '"%s"' % fn h["Content-Transfer-Encoding"]["_v"] = ce h["Content-Type"]["_v"] = ct d = [] l = val.read(8192) while l: d.append(l) l = val.read(8192) else: h["Content-Disposition"]["_v"] = "form-data" h["Content-Disposition"]["name"] = '"%s"' % name d = [str(val)] self._headers = h self._data = d self._boundary = b self._top = t
def header(self,title,comments): for i in range(len(comments)): comments[i] = regsub.gsub("^","% ",comments[i]) # There's a more elegant way to do the bounding box line: return [ "%!PS-Adobe-2.0 EPSF-1.2", "%%Creator: " + MYNAME + " " + MYVERSION + " " + DATE, "%%Title: " + title, "%%BoundingBox: TBD" ] +\ comments + \ [ "%%EndComments", "\n% These font names might be different on your system:", "/ean13font { /" + EAN13FONT + " findfont 10 scalefont setfont } def", "/isbnfont { /" + ISBNFONT + " findfont 8 scalefont setfont } def", "/upc5font { /" + UPC5FONT +" findfont 14 scalefont setfont } def\n", "/nextModule { moduleWidth 0 rmoveto } def", "/barHeight { 72 } def", "/nextModule { moduleWidth 0 rmoveto } def", "/topcentershow {dup stringwidth pop neg 2 div -9 rmoveto show} def", "/toprightshow {dup stringwidth pop neg -9 rmoveto show} def", "/bottomcentershow {dup stringwidth pop neg 2 div 0 rmoveto show} def", "/bottomrightshow {dup stringwidth pop neg 0 rmoveto show} def", self.x0,self.y0,"translate", "0 0 moveto", "/I { 0 barHeight rlineto 0 barHeight neg rmoveto nextModule } def", "/L { 0 -5 rmoveto 0 5 rlineto I } def", "/O { nextModule } def" ]
def Main(): form = FormContent() # title = form["title"][0] description = form["description"][0] # runtime = form["runtime"][0] # keywords = form["keywords"][0] file = form["file"][0] title = 'null' runtime = 'null' keywords = 'null' #check and replace all 's description = regsub.gsub("'","´",description) title = regsub.gsub("'","´",title) keywords = regsub.gsub("'","´",keywords) update = mydbase.query("UPDATE movies SET description ='"+description+"',title = '"+title+"', runtime='"+runtime+"',keywords='"+keywords+"' WHERE filename = '"+file+"'") print "Content-type: text/html\n\n" print "<HEADER>\n<TITLE>C2W Update</TITLE>\n</HEADER>\n" print "<BODY bgcolor=#FFFFFF>\n" print "<h1>Update completed </h1><br>" print '<a href="http://www.pals.iastate.edu/c2w/adm">Back to main menu' print '<br><br><a href="http://www.pals.iastate.edu/c2w/adm/edit.html">' print 'Edit another entry</a> in:<br>' print '<a href="http://www.pals.iastate.edu/cgi-bin/c2w/list.py?dir=fire">' print 'fire</a><br>' print '<a href="http://www.pals.iastate.edu/cgi-bin/c2w/list.py?dir=csm">' print 'csm</a><br>' print '<a href="http://www.pals.iastate.edu/cgi-bin/c2w/list.py?dir=hydro">' print 'hydro</a><br>' print '<a href="http://www.pals.iastate.edu/cgi-bin/c2w/list.py?dir=acsse">' print 'acsse</a><br>' print '<a href="http://www.pals.iastate.edu/cgi-bin/c2w/list.py?dir=forecast">' print 'forecast</a><br>' print '<a href="http://www.pals.iastate.edu/cgi-bin/c2w/list.py?dir=marine1">' print 'marine1</a><br>' print '<a href="http://www.pals.iastate.edu/cgi-bin/c2w/list.py?dir=marine2">' print 'marine2</a><br>' print '<a href="http://www.pals.iastate.edu/cgi-bin/c2w/list.py?dir=satellite1">' print 'satellite1</a><br>' print '<a href="http://www.pals.iastate.edu/cgi-bin/c2w/list.py?dir=satellite2">' print 'satellite2</a><br>' print '</body></html>'
def font_from_name(psfontname): # PostScript fonts use dash delimiters, while Python module names # use underscores. modulename = 'PSFont_' + regsub.gsub('-', '_', psfontname) # no need to do any caching since the import mechanism does that # for us! module = __import__(modulename, globals(), locals()) return module.font
def psbarsold(self): psbits = regsub.gsub("1", "I ", self.bits) psbits = regsub.gsub("0", "O ", psbits) psbits = regsub.gsub("L", "L ", psbits) linewidth = 50 p = 0 j = linewidth m = len(psbits) psbarlines = [] blanks = "^ | $" while p <= m: j = min(linewidth, m - p) psbarlines = psbarlines + [ regsub.gsub(blanks, "", psbits[p:p + j]) ] p = p + linewidth return ["0 0 moveto"] + psbarlines + ["stroke"]
def normalize(self, path): # watch for the ever-sneaky '/+' path element path = regsub.gsub('/+', '/', path) p = self.path_module.normpath(path) # remove 'dangling' cdup's. if len(p) > 2 and p[:3] == '/..': p = '/' return p
def protocol_joiner(scheme): scheme = string.lower(scheme) sanitized = regsub.gsub("[^a-zA-Z0-9]", "_", scheme) modname = sanitized + "API" app = grailutil.get_grailapp() m = app.find_extension('protocols', modname) if m: return m.join return None
def grok_synop(line, otime): # # Fix up and split the line of this observation. # line = regsub.gsub('/', '0', line) if line[-1] == '=': line = line[:-1] sline = string.split(line) data = {} # # Second group with station and cloud base info. "table needed". # data['cloud_base'] = string.atof(sline[1][2]) # # Third group is cloud cover, and wind information. # data['cloud_cover'] = string.atof(sline[2][0]) data['wdir'] = string.atof(sline[2][1:3]) * 10.0 data['wspd'] = string.atof(sline[2][3:5]) * (1852.0 / 3600.0) # # From here on we have the number-tagged groups. # for group in sline[3:]: # # Group 1 is temperature info; 2 is dewpoint. # if group[0] == '1': data['tdry'] = getTemp(group) elif group[0] == '2': data['dp'] = getTemp(group) # # 3 and 4 pressure # elif group[0] == '3': data['spres'] = getPres(group) elif group[0] == '4': data['pres'] = getPres(group) # # 5 pressure tendency # elif group[0] == '5': data['ptend'] = string.atof(group[2:]) / 10.0 # # 6 Precip. "table needed" # elif group[0] == '6': data['rain'] = string.atof(group[1:4]) / 10.0 # this is wrong else: break # # OK, now build up our list and it's done. # return [otime, sline[0], data]
def handle_read(self): data = self.recv(512) if not data: print('\nclosed.') self.sock_channel.close() try: self.close() except: pass data = regsub.gsub('\n', '\r\n', data) self.sock_channel.push(data)
def add_flowing_data(self, data): if not data: return data = regsub.gsub(whitespace, ' ', data) if self.nospace and data[0] == ' ': data = data[1:] if not data: return elif self.softspace and data[0] != ' ': data = ' ' + data self.nospace = self.softspace = 0 if data[-1] == ' ': data = data[:-1] self.softspace = 1 self.writer.send_flowing_data(data)
def Apropos(self, event=None): str = self.apropos_str.get() if not str: self.top.bell() print "No string ?" return pipe = os.popen('apropos ' + str, 'r') self.stext.text.delete('1.0', Tix.END) tabs = regex.compile('\011+') num = 1 while 1: line = pipe.readline() if not line: break line = regsub.gsub(tabs, '\011', line) fields = string.splitfields(line, '\011') if len(fields) == 1: line = line[string.find(line, ' ') + 1:] line = regsub.gsub('^ *', '', line) fields = ['???', line] if len(fields) == 2: tmp = string.splitfields(fields[1], '-') fields = fields[0:1] + tmp num = num + 1 self.stext.text.insert('insert', fields[0] + '\t', '!') self.stext.text.insert('insert', fields[1], ` num `) self.stext.text.tag_bind( ` num `, '<Any-Enter>', lambda e=None, t=` num `, w=self: w._highlight(t, 1)) self.stext.text.tag_bind( ` num `, '<Any-Leave>', lambda e=None, t=` num `, w=self: w._highlight(t, 0)) self.stext.text.tag_bind( ` num `, '<1>', lambda e=None, w=self, t=fields[1]: w._hyper_link(t)) self.stext.text.insert('insert', fields[2])
def open(self, url): type, url = splittype(unwrap(url)) if not type: type = 'file' name = 'open_' + type if '-' in name: import regsub name = regsub.gsub('-', '_', name) if not hasattr(self, name): raise IOError, ('url error', 'unknown url type', type) try: return getattr(self, name)(url) except socket.error, msg: raise IOError, ('socket error', msg)
def open(self, fullurl): fullurl = unwrap(fullurl) type, url = splittype(fullurl) if not type: type = 'file' name = 'open_' + type if '-' in name: import regsub name = regsub.gsub('-', '_', name) if not hasattr(self, name): return self.open_unknown(fullurl) try: return getattr(self, name)(url) except socket.error, msg: raise IOError, ('socket error', msg)
def get_local_api(self, url, method, params): """get a local handler instance""" scheme, resturl = urllib.splittype(url) if not scheme: raise IOError("protocol error", "no scheme identifier in URL", url) scheme = str.lower(scheme) sanitized = regsub.gsub("[^a-zA-Z0-9]", "_", scheme) modname = sanitized + "API" try: klass = self.local_api_handlers[modname] except KeyError: return None handler = klass(resturl, method, params) handler._url_ = url # To keep BaseReader happy return handler
def write_text( self, string ): string = gsub( '&', '&', string ) # FIRST! string = gsub( '<', '<', string ) string = gsub( '>', '>', string ) # others would be a good idea # but thats enough to be unambiguous if self.boln: self.boln = 0 for i in range(self.indent): self.fd.write( self.indent_str ) # LURK count LPOS self.lpos = self.indent * len( self.indent_str ) if self.is_wrap & self.do_wrap: sp1 = "" if string[0]==' ': # first char if 0!=self.boln: self.write1( ' ') # happens between paragraphs! words = split( string ) for word in words: w = len( word ) x = self.lpos + w + 1 if x > self.wrap : self.own_line() sp1 = "" x = self.lpos + w x = w # self.fd.write( "(%d)" % self.lpos ) self.write1( sp1 ) self.write1( word ) sp1 = " " self.lpos = x if string[-1:]==' ': # last char in s self.write1( ' ') else: self.fd.write( string )