def render_content(self, ctx, data): if self.db[0] == "FIRSTRUN": return ctx.tag[tags.table( height="100%", width="100%" )[tags.tr(height="100%")[tags.td[tags.div( id="centerBox", valign="middle" )[tags.div(id="blockTop") [""], tags .div(id="centerBlock")[tags.h1( style="color:#fff;font-family:arial;" )["TUMS Installation Wizard"]], tags .div(id="menuBlock")[tags.div( style= "margin-top:-5em; text-align:left; font-family:arial; color:#786D38;" )[tags.h3["Welcome to the TUMS installation wizard."], """This wizard will guide you through an initial configuration of the host system. This should be carried out by a Thusa employee. If your server has arrived unconfigured it is recommended that you contact Thusa support for this to be carried out. """, tags.br, """Click the NEXT button bellow to continue with the installation""", tags.br, tags.br, tags.a(href="Wizard/1/")[tags.img( src='/images/next.png')]]]]]]]] return ctx.tag[tags.a(href="/auth/")["Login"]]
def render_content(self, ctx, data): """ Function is deffered to make less blocking on system calls""" if not self.avatarId.isAdmin: return ctx.tag[""] # Fetch running profile thisProfile = Utils.currentProfile() runningProfile = Utils.runningProfile()[0] if thisProfile[0] != runningProfile: thisProfile = [ thisProfile[0], " [", tags.a(href=url.root.child("Profiles").child("switch").child( thisProfile[1]))["Activate"] ], "]" else: thisProfile = thisProfile[0] return ctx.tag[tags.table( width="100%", cellspacing="10")[tags.tr[tags.td(colspan=2)[tags.div( id="ProfileBlock")[tags.div(_class="roundedBlock")[ tags.h1["Profile"], tags.div(id="123")["Current profile: ", thisProfile, tags.br, "Running profile: ", runningProfile, tags.br, tags.directive('form selectProfile'), tags.a(href=url.root.child("Profiles") )["Manage Profiles"]]], ], ]], tags.tr[tags.invisible( render=tags.directive('thisFragment'))]]]
def render_links(self, context, data): ds = self.root.edits(self.ob) therange = range(len(ds)) rev = therange[self.rev] ul = tags.ul() for i in therange: li = tags.li() if i: li[tags.a(href=url.URL.fromContext( context).sibling('diff').add('ob', self.ob.fullName()).add( 'revA', i - 1).add('revB', i))["(diff)"]] else: li["(diff)"] li[" - "] if i == len(ds) - 1: label = "Latest" else: label = str(i) if i == rev: li[label] else: li[tags.a(href=url.gethere.replace('rev', str(i)))[label]] li[' - ' + ds[i].user + '/' + ds[i].time] ul[li] return context.tag[ul]
def render_random(self, ctx, data): for randRow in randomSet(self.graph, 3): print 'randRow', randRow current = randRow['uri'] bindings = {"pic": current} tags = [[ T.a(href=['/set?tag=', row['tag']])[row['tag']], ' ' ] for row in self.graph.queryd("""SELECT DISTINCT ?tag WHERE { ?pic scot:hasTag [ rdfs:label ?tag ] }""", initBindings=bindings)] depicts = [[T.a(href=localSite(row['uri']))[row['label']], ' '] for row in self.graph.queryd(""" SELECT DISTINCT ?uri ?label WHERE { ?pic foaf:depicts ?uri . ?uri rdfs:label ?label . }""", initBindings=bindings)] # todo: description and tags would be good too, and some # other service should be rendering this whole section yield T.div(class_="randPick")[T.a(href=[ '/set?', urllib.urlencode(dict(date=randRow['date'], current=current)) ])[T.img(src=[localSite(current), '?size=medium']), ], T.div[tags], T.div[depicts], T.div[randRow['filename']. replace('/my/pic/', '')], ]
def page_body(kwargs): merits = parse_merits(kwargs) checks = [gen_checks(b, merits) for b in ribbonator.bodies] job = '?' + '&'.join('='.join(gen_job(b, merits[b])) for b in merits if 'soi' in merits[b]) print('serving index', job) return [ t.script(type='text/javascript')[PAGE_SCRIPT], t.h1['RSS Ribbonator - Clumsy Web Interface'], t. p["Generator and RSS Ribbons by Edward Cree. Based on the KSP Ribbons by Unistrut. 'Inspired' by ", t.a(href='http://www.kerbaltek.com/ribbons' )["Ezriilc's Ribbon Generator"], "."], t.p[t.a(href="https://github.com/ec429/ribbonator")["Source Code"]], t. p["Select your achievements with the checkboxes and radiobuttons, and click Submit to generate the ribbon image URL. This will also generate a Ribbonator 'job card' URL; bookmark this if you want to be able to update your ribbons later."], t. p["Moons will only appear when their parent planet's 'Reached SOI' is selected."], t. p["The Ribbonator does not store any user data. Instead, the ribbon contents are encoded in the URL of the image, using the same 'job card' format."], t. p["I recommend against linking directly to the generated image. Download it, then upload to some other hosting; that way your image won't break if the Ribbonator moves, dies, or has bandwidth troubles."], t.img(src='gen.png' + job, alt="Generated ribbons"), t.p[t.a( href=job)["Job Card URL - bookmark this"] if len(job) > 1 else ''], t.form(method='GET')[t.ul[checks], t.input(type='submit', value='Submit')], ]
def gotMail(mail): print mail attachments, hdrs, data = mail uFrom, uDate, uSubject = hdrs toolbar = [("/mail/Mail/##%s" % self.params[0], 'Inbox', "/images/inbox.png"), ("/mail/New/##%s.%s" % self.params, 'Reply', "/images/inbox.png")] return ctx.tag[tags.div( id="mailViewHolder")[ tags.ul( id="mailTools")[[ tags.li[tags.a(href=link)[tags.div[tags.img( src=image)], name]] for link, name, image in toolbar ]], tags.table( id="mailViewHeaders" )[tags.tr[tags.td["From:"], tags.td[uFrom]], tags.tr[tags.td["Date:"], tags.td[uDate]], tags.tr[tags.td["Subject:"], tags.td[uSubject]], tags.tr[tags.td["Attachments:"], tags.td[[[ tags.a(href="/mail/mdata/%s/%s" % (self.avatarId.username, v[0]))[tags.img( src="/images/attachment.png"), " ", k], " (%0.2f KB)" % (v[1] / 1024.0), tags.br ] for k, v in attachments.items()]]], ], tags.div(id="mailViewContentBox")[tags.xml(data)], ]]
class Progressbar(livepage.LivePage): addSlash = True progress = { 'bar1': 0, 'bar2': 20, 'bar3': 30, 'bar4': 50, } def data_bar1(self, ctx, data): return {'name': 'bar1'} def data_bar2(self, ctx, data): return {'name': 'bar2', 'percent': self.progress['bar2']} def data_bar3(self, ctx, data): return {'name': 'bar3', 'percent': self.progress['bar3']} def data_bar4(self, ctx, data): return {'name': 'bar4', 'percent': self.progress['bar4']} def goingLive(self, ctx, client): self.progress = self.progress.copy() def handle_click(self, ctx, value): def send(): if self.progress[value] >= 100: t.stop() else: self.progress[value] += 1 livepage.IClientHandle(ctx).send(component[value].setPercent( str(self.progress[value]))) t = task.LoopingCall(send) t.start(1) docFactory = loaders.stan(t.html[t.head[ t.title["ProgressBar Example"], livepage.glue, componentGlue.inlineGlue, progressBarGlue.inlineGlue, ], t.body[ t.invisible(data=t.directive('bar1'), render=progressBar), t.p[t.a(href="", onclick= [livepage.server.handle('click', 'bar1'), livepage. stop])['Start meter']], t.invisible(data=t.directive('bar2'), render=progressBar), t.p[t.a(href="", onclick= [livepage.server.handle('click', 'bar2'), livepage. stop])['Start meter']], t.invisible(data=t.directive('bar3'), render=progressBar), t.p[t.a(href="", onclick= [livepage.server.handle('click', 'bar3'), livepage. stop])['Start meter']], t.invisible(data=t.directive('bar4'), render=progressBar), t.p[t.a(href="", onclick= [livepage.server.handle('click', 'bar4'), livepage. stop])['Start meter']], ]])
def render_userbox(self, ctx, data): """Render the box containing the user's login status.""" avatar = maybe_user(ctx) srv = IService(ctx) warn = '' if avatar.anonymous: email = None else: email = avatar.user.email if not email: email = srv.pretendedEmail(avatar.user) warn = T.span( id="activate")[u"Vous devez encore ", T.a(href="/")[u"activer votre compte"]] if email: greetings = T.div( _class="userinfo")[warn, T.span(style="padding-right:3em")[email], T.a(href="/")[u"Réservations"], u' :: ', T.a(href="/logout")[u"Quitter"], ] else: info = login.LoginInfo(warnings=False, force_reconnect=True) greetings = T.div(_class="userinfo")[login.LoginFragment( original=info)] return ctx.tag[T.a(href="/")[T.img(src="/images/mes-souhaits.png", align="left", alt="Mes souhaits", width=203, height=36)], greetings]
def render_listsheets(self,ctx): return [T.div[ T.span(style="font-weight:bold;")[ T.a(href=i[0])[i[1]]],' located at ', T.a(href=i[0])[i[0]] ] for i in self.emailInfo]
def render_content(self, ctx, data): dir = os.listdir('/usr/local/tcs/tums/profiles/') dir.sort() tab = [] for l in dir: if l[-3:] == ".py": name = l[:-3].replace('_', ' ').capitalize() tab.append( (name,[ tags.a(href="copy/%s" % l)["Copy"], " ", tags.a(href="#", onclick="showElement('ren'); getElement('rename-source').value = '%s'; return false;" % name)["Rename"], " ", tags.a( href="delete/%s"%(l), onclick="return confirm('Are you sure you want to delete this profile?');", title="Delete this profile" )[tags.img(src="/images/ex.png")] ]) ) return ctx.tag[ tags.h3[tags.img(src="/images/cluster.png"), " Configuration Profiles"], PageHelpers.dataTable(['Profile Name',""], tab), tags.br, tags.div(id="ren", style="display:none;")[ tags.directive('form rename') ] ]
def render_links(self, context, data): ds = self.root.edits(self.ob) therange = range(len(ds)) rev = therange[self.rev] ul = tags.ul() for i in therange: li = tags.li() if i: li[tags.a(href=url.URL.fromContext(context).sibling( 'diff').add( 'ob', self.ob.fullName()).add( 'revA', i-1).add( 'revB', i))["(diff)"]] else: li["(diff)"] li[" - "] if i == len(ds) - 1: label = "Latest" else: label = str(i) if i == rev: li[label] else: li[tags.a(href=url.gethere.replace('rev', str(i)))[label]] li[' - ' + ds[i].user + '/' + ds[i].time] ul[li] return context.tag[ul]
def render_content(self, ctx, data): notice = "" if self.returns=='Completed': notice = tags.img(src='/images/modsuccess.png') keyName = "You do not have any support files associated with your username" for i in os.listdir('/etc/openvpn/keys/'): if "%s.%s" % (self.avatarId.username, self.avatarId.dom) in i and "key" in i: keyName = [ tags.a(href='/packs/%s.%s-vpn.zip' % ( self.avatarId.username, self.avatarId.dom ))["Download Client Settings"], tags.br, tags.a(href='/packs/openvpn-install.exe')["Download OpenVPN Client"] ] return ctx.tag[ tags.div(id="rightBlock")[ tags.h3["Account Settings"], notice, tags.directive('form userSettings'), tags.h3["User Support Files"], keyName ] ]
def data_header(self, ctx, data): u = url.URL.fromContext(ctx) u = u.parentdir().parentdir().clear() l = [] l.append(tags.a(href=u.sibling("search"))[_("Search")]) l.append(tags.a(href=u.sibling("add"))[_("add new entry")]) return l
def render_menu(self, ctx, data): host = str(url.URL.fromContext(ctx)).split('//')[-1].split(':')[0] if self.avatarId.isUser: self.menu= [] if self.avatarId.reports: try: del self.menu[3] except: pass if self.menu: newBlock = tags.img(src="/images/blockMB.png") else: newBlock = "" return ctx.tag[ tags.img(src="/images/blockMB.png"), [ tags.a(href=elm[0].replace('$ME$',host), title=elm[3])[tags.img(src=elm[1])] for elm in self.menu], newBlock, [ tags.a(href=elm[0].replace('$ME$',host), title=elm[3])[tags.img(src=elm[1])] for elm in self.userMenu], self.addedMenu(), ]
def render_index_players(self, ctx, data): data.sort(key=attrgetter('name')) lines = [] for player in data: line = [] name = player.name tzid = player.tzid tzidcell = T.td(_class="objtzid")[tzid, ':'] line.append(tzidcell) if admin.verify(player): line.append(T.td['!']) elif wizard.verify(player): line.append(T.td['@']) else: line.append(T.td) editlink = T.a(href="/edit/%s" % tzid)[name] line.append(T.td(_class="objname")[editlink]) if player.logged_in: room = player.room editlink = "/edit/%s" % room.tzid link = T.a(href=editlink)[T.span(_class="editlink")[room.name]] line.append(T.td[link]) else: line.append(T.td) lines.append(T.tr[line]) return T.table[lines]
def returnMonthView(dayData): """ Returns the details for a particular month""" flatBlocks = [] date = datetime.date(self.year, self.month, 1).strftime("%h %Y") tsite = "" for rows in dayData: tsite = rows[6] flatBlocks.append(( tags.a(href=url.root.child("ProxyUse").child("ShowHost").child(rows[2]).child(self.year).child(self.month).child('0'))[rows[1]], rows[4], "%0.2fMB" % (rows[0]/(1024*1024)), )) return ctx.tag[ tags.h3[ tags.img(src="/images/stock-download.png"), "Web Usage - Hosts who visited %s during %s" % (tsite, date) ], tags.a(href=url.root.child("ProxyUse"))["Back to overview"], " ", tags.a(href=url.root.child("ProxyUse").child("ShowDays").child(self.year).child(self.month))["Back to month overview"], " ", tags.a(href=url.root.child("ProxyUse").child("ShowDays").child(self.year).child(self.month).child(self.day))["Back to day overview"], " ", tags.a(href=url.root.child("ProxyUse").child("ShowSites").child(self.year).child(self.month).child('0'))["Back to sites overview"], tags.br, tags.br, PageHelpers.dataTable([('str', 'Host'), ('str', 'Username'), ('int', 'Total Traffic')], flatBlocks, sortable=True) ]
def render_menu(self, ctx, data): request = inevow.IRequest(ctx) username = request.getUser() ret = tags.table(border=0, cellspacing=3, cellpadding=3) row = tags.tr(valign="middle") row[tags.td(_class="menuentry", width="150", align="center", onclick="self.location='/account/'", onmouseover="this.className='menuentrypressed';", onmouseout="this.className='menuentry';") [tags.a(_class="menuentry", href="/account/")["Account"]]] if config.admins.count(username) > 0: row[tags.td(_class="menuentry", width="150", align="center", onclick="self.location='/status/'", onmouseover="this.className='menuentrypressed';", onmouseout="this.className='menuentry';") [tags.a(_class="menuentry", href="/status/")["Status"]]] row[tags.td(_class="menuentry", width="150", align="center", onclick="self.location='/config/'", onmouseover="this.className='menuentrypressed';", onmouseout="this.className='menuentry';") [tags.a(_class="menuentry", href="/config/")["Configuration"]]] row[tags.td(_class="menuentry", width="150", align="center", onclick="self.location='/controls/'", onmouseover="this.className='menuentrypressed';", onmouseout="this.className='menuentry';") [tags.a(_class="menuentry", href="/controls/")["Controls"]]] return ret
def data_header(self, ctx, data): u = url.URL.fromContext(ctx).up().clear() l = [] l.append(tags.a(href=u.sibling("search"))[_("Search")]) l.append(tags.a(href=u.sibling("add"))[_("add new entry")]) l.append(tags.a(href=u.sibling("edit").child(str(self.dn)))[_("edit")]) return l
def data_header(self, ctx, data): u=url.URL.fromContext(ctx) u=u.parentdir().parentdir().clear() l=[] l.append(tags.a(href=u.sibling("search"))[_("Search")]) l.append(tags.a(href=u.sibling("add"))[_("add new entry")]) return l
def render_status(self, context, data): try: obj = context.locate(inevow.IHand) except KeyError: return context.tag.clear() if not isinstance(obj, EditStatus): return context.tag.clear()[obj] u=url.URL.fromContext(context) u=u.parentdir().parentdir().clear() return context.tag.clear()[ _("Edited "), tags.a(href=u.parentdir() .child(obj.entry.dn) .child("search"))[obj.entry.dn], _(" successfully. "), # TODO share implementation with entryLinks '[', tags.a(href=u.sibling('move').child(uriQuote(obj.entry.dn)))[_('move')], '|', tags.a(href=u.sibling('delete').child(uriQuote(obj.entry.dn)))[_('delete')], '|', tags.a(href=u.sibling('change_password').child(uriQuote(obj.entry.dn)))[_('change password')], ']', tags.p[obj.changes], ]
def renderTable(result): resCopy = [i for i in result] return ctx.tag[ tags.h2["Shorewall Rules"], tags.table(cellspacing=0)[tags.thead[tags.tr[ tags.th["Priority"], tags.th["Action"], tags.th["Source"], tags.th["Destination"], tags.th["Protocol"], tags.th["Port"], tags.th["Comment"], tags.th[""]]], tags.tbody[[ tags.tr[tags.td[tags.a( href=url.root.child("swapShorerule"). child(self.machineID).child(i[0]). child(resCopy[1 + loc - len(resCopy)][0]))["Down"], "|", tags. a(href=url.root.child("swapShorerule"). child(self.machineID).child(i[0]). child(resCopy[loc - 1][0]))["Up"]], tags.td[i[2]], tags.td[i[3]], tags.td[i[4]], tags.td[i[5]], tags.td[i[6]], tags.td[i[10]], tags.td[tags.a( href=url.root.child("deleteShorerule"). child(self.machineID).child(i[0]) )[tags.img(src="/images/delete.png")]]] for loc, i in enumerate(resCopy) ]]], tags.a(href=url.root.child("updateShorewall"). child(self.machineID))["Send to client"]]
class MyRootResource(rend.Page): """Some resource.""" addSlash = True def render_randomNumber(self, ctx, data): session = ISession(ctx) number = random.randrange(0, 100) session.setComponent(ISessionValue, number) history = session.getComponent(IValueHistory) if history is None: history = [] history.append(number) session.setComponent(IValueHistory, history) return str(number) def render_valueHistory(self, ctx, data): session = ISession(ctx) history = session.getComponent(IValueHistory, default=[]) return repr(history[:-1]) docFactory = loaders.stan( T.html[T.body[T.p['Your random number is: ', render_randomNumber], T.p['Previous random numbers were: ', render_valueHistory], T.div[T.a( href=url.here)['Click here to get a new number']], T.div[T.a(href=url.here.child(guard.LOGOUT_AVATAR) )['Click here to log out']], ]])
def render_downloadtable(self, ctx, data): rows = [] for packageName, version, release, md5, download, release_notes in \ data: download_link = T.a(href = download)["Download %s" % version] release_notes_link = T.a(href = release_notes)["%s release notes" % version] tr = T.tr[ T.td[packageName], T.td[version], T.td[release], T.td[md5], T.td[download_link], ] if release_notes: tr[T.td[release_notes_link]] rows.append(tr) return ctx.tag[ T.thead[T.tr[ T.td["Package"], T.td["Version number"], T.td["Release date"], T.td["MD5 sum"], T.td["Download link"], T.td["Release Notes"] ]], T.body[rows] ]
def returnMailLog(mail): if self.offset > 0: previousTag = tags.a( href=url.root.child("Mail").child(self.offset - 20))["Previous 20"] else: previousTag = "Previous 20" return ctx.tag[ #tags.div(id="rightBlockIFrame")[ tags.h3[tags.img(src="/images/maillog.png"), " Mail Logs"], previousTag, tags.a(href=url.root.child("Mail").child(self.offset + 20))["Next 20"], tags.br, tags.table(cellspacing=0, _class='listing')[tags.thead( background="/images/gradMB.png")[tags.tr[ tags.th["Date"], tags.th["From"], tags.th["To"], tags.th["Size"], tags.th["Message ID"]]], tags.tbody[[ tags.tr[tags.td[time.ctime(m[2])], tags.td[m[5]], tags.td[m[18]], tags.td["%0.3f KB" % (float(m[11]) / 1024.0)], tags.td[m[1]]] for m in mail ]]], tags.br, previousTag, tags.a(href=url.root.child("Mail").child(self.offset + 20))["Next 20"], tags.br, tags.h3["Search Logs"], tags.invisible(render=tags.directive('form searchForm'))]
def render_random(self, ctx, data): for randRow in randomSet(self.graph, 3): print 'randRow', randRow current = randRow['uri'] bindings = {"pic" : current} tags = [[T.a(href=['/set?tag=', row['tag']])[row['tag']], ' '] for row in self.graph.queryd( """SELECT DISTINCT ?tag WHERE { ?pic scot:hasTag [ rdfs:label ?tag ] }""", initBindings=bindings)] depicts = [[T.a(href=localSite(row['uri']))[row['label']], ' '] for row in self.graph.queryd(""" SELECT DISTINCT ?uri ?label WHERE { ?pic foaf:depicts ?uri . ?uri rdfs:label ?label . }""", initBindings=bindings)] # todo: description and tags would be good too, and some # other service should be rendering this whole section yield T.div(class_="randPick")[ T.a(href=['/set?', urllib.urlencode(dict(date=randRow['date'], current=current))])[ T.img(src=[localSite(current), '?size=medium']), ], T.div[tags], T.div[depicts], T.div[randRow['filename'].replace('/my/pic/','')], ]
def data_header(self, ctx, data): u=url.URL.fromContext(ctx).up().clear() l=[] l.append(tags.a(href=u.sibling("search"))[_("Search")]) l.append(tags.a(href=u.sibling("add"))[_("add new entry")]) l.append(tags.a(href=u.sibling("edit").child(str(self.dn)))[_("edit")]) return l
def gotItems(items,categories): categoryCMSItems = {} for item in items: i = item.getProtectedObject() categoryCMSItems[i.name] = i for n, category in enumerate(categories.children): name = category.textid categoryCMSItem = categoryCMSItems.get(name,None) column = divmod(n,3)[1]+1 try: title = categoryCMSItem.title shortDescription = categoryCMSItem.shortDescription except AttributeError: title = category.label shortDescription = '' html = [ T.h4[ T.a(href=url.here.up().child(name))[ title ] ], T.p[ T.a(href=url.here.up().child(name))[ shortDescription ] ] ] yield html
def gotProducts(products): htmlblock = [] for n,product in enumerate(products): column = divmod(n,3)[1]+1 name = product.code title = product.title shortDescription = product.summary imgsrc='/system/ecommerce/%s/mainImage?size=190x300&sharpen=1.0x0.5%%2b0.8%%2b0.1'%product.id html = T.div(class_='category c%s'%column)[ T.a(href=url.here.child(name))[ T.img(src=imgsrc,width=190),T.span(class_='mbf-item')['#gallery %s'%product.code] ], T.h4[ T.a(href=url.here.child(name))[ title ] ], T.p[ T.a(href=url.here.child(name))[ shortDescription ] ] ] htmlblock.append(html) # Group the output into threes if column == 3: out = htmlblock htmlblock = [] yield T.div(class_="threecolumnleft clearfix")[ out ] # and then yield anything left over if the last item wasn't at the end of a row if column != 3: yield T.div(class_="threecolumnleft clearfix")[ htmlblock ]
def render_langs(self, ctx, data): """Render a list of links to select from the available translations. """ out = [T.a(href=url.here.remove("lang"))["default"], " | "] for lang in langs: out.append(T.a(href=url.here.replace("lang", lang))[lang]) out.append(" | ") return out[:-1]
def render_langs(self, ctx, data): """Render a list of links to select from the available translations. """ out = [T.a(href=url.here.remove('lang'))['default'], ' | '] for lang in langs: out.append(T.a(href=url.here.replace('lang', lang))[lang]) out.append(' | ') return out[:-1]
def render_userBar(self, ctx, data): return ctx.tag[ "Logged in as: ", self.avatarId.username, " | ", tags.a(href=url.root.child('Settings'), title="Personal account settings")["Account Settings"], " | ", tags.a(href=url.root.child(guard.LOGOUT_AVATAR), title="Logout of TUMS")["Logout"] ]
def render_footer(self, ctx, data): ctx.fillSlots('blog_path', T.a(href="http://blog.%s/" % self.app.servers.httpserver._cfg_site_domain)[ "blog" ] ) ctx.fillSlots('blog_path', T.a(href="http://blog.%s/" % self.app.servers.httpserver._cfg_site_domain)[ "blog" ] ) return ctx
def gotAll(items,categories,products): categoryCMSItems = {} for item in items: i = item.getProtectedObject() categoryCMSItems[i.name] = i categoryCMSItemMainImage = {} categoryCMSItemCode = {} for categoryCMSItem in categoryCMSItems.values(): category = categoryCMSItem.name for product in products: if u'gallery.%s'%category in product.categories: match = product categoryCMSItemMainImage[categoryCMSItem.name] = match.id categoryCMSItemCode[categoryCMSItem.name] = match.code break htmlblock = [] for n, category in enumerate(categories.children): name = category.textid categoryCMSItem = categoryCMSItems.get(name,None) column = divmod(n,3)[1]+1 try: title = categoryCMSItem.title shortDescription = categoryCMSItem.shortDescription except AttributeError: title = category.label shortDescription = '' try: imgsrc='/system/ecommerce/%s/mainImage?size=190x300&sharpen=1.0x0.5%%2b0.7%%2b0.1'%categoryCMSItemMainImage[name] except KeyError: imgsrc='/skin/images/spacer.gif' html = T.div(class_='category c%s'%column)[ T.a(href=url.here.child(name))[ T.img(src=imgsrc,width=190),T.span(class_='mbf-item')['#gallery %s'%categoryCMSItemCode[name]] ], T.h4[ T.a(href=url.here.child(name))[ title ] ], T.p[ T.a(href=url.here.child(name))[ shortDescription ] ] ] htmlblock.append(html) # Group the output into threes if column == 3: out = htmlblock htmlblock = [] yield T.div(class_="threecolumnleft clearfix")[ out ] # and then yield anything left over if the last item wasn't at the end of a row if column != 3: yield T.div(class_="threecolumnleft clearfix")[ htmlblock ]
def recentLinks(self): raise NotImplementedError choices = [] for opt in [10, 50, 100]: href = self.desc.altUrl(recent=str(opt)) choices.append(T.a(href=href)[opt]) choices.append(T.a(href=self.desc.altUrl(recent=''))['all']) return ['show only the ', [[c, ' '] for c in choices], ' most recent of these']
def _explain_api(cls, service): return T.invisible[ "an interface for operation with curl and" " similar low-level-tools. The endpoint is at ", T.a(href=service.getURL("api"))[service.getURL("api")], "; as usual for DALI-conforming services, parameters" " an response structure is available by ", T.a(href=service.getURL("api") + "MAXREC=0")["querying with" " MAXREC=0"], "."]
class RootPage(rend.Page): addSlash = True child_twist = Twister('twist') child_feeds = FeedsPage('feeds') docFactory = loaders.stan( T.html[T.body[T.p[T.a(href='twist')["Twist me, baby"], "!", ], T.p[T.a(href='feeds')["Play with feeds"], ".", ]]])
def getData(self): #allow_domains allow_dst allow_hosts doms = self.sysconf.ProxyAllowedDomains dsts = self.sysconf.ProxyAllowedDestinations ips = self.sysconf.ProxyAllowedHosts bdoms = self.sysconf.ProxyBlockedDomains # Read timed access data l = self.sysconf.ProxyConfig times = [] cnt = 0 for action, days, time, domain, exacl in l.get('timedaccess', []): times.append(( action and "Allow" or "Deny", ", ".join([self.daymap[i] for i in days.split()]), time, domain or "", exacl or "", tags.a(href="DeleteTime/%s/" % (cnt,), onclick="return confirm('Are you sure you want to delete this entry?');")[ tags.img(src="/images/ex.png") ] )) cnt += 1 domains = [] cnt = 0 for ln in doms: l = ln.strip('\n') if l: domains.append([l, tags.a(href="Delete/Domain/%s/" % cnt, onclick="return confirm('Are you sure you want to delete this entry?');")[tags.img(src="/images/ex.png")] ] ) cnt += 1 bdomains = [] cnt = 0 for ln in bdoms: l = ln.strip('\n') if l: bdomains.append([l, tags.a(href="Delete/BDomain/%s/" % cnt, onclick="return confirm('Are you sure you want to delete this entry?');")[tags.img(src="/images/ex.png")] ] ) cnt += 1 destinations = [] cnt = 0 for ln in dsts: l = ln.strip('\n') if l: destinations.append([l, tags.a(href="Delete/Destination/%s/" % cnt, onclick="return confirm('Are you sure you want to delete this entry?');")[tags.img(src="/images/ex.png")] ] ) cnt += 1 hosts = [] cnt = 0 for ln in ips: l = ln.strip('\n') if l: hosts.append([l, tags.a(href="Delete/Host/%s/" % cnt, onclick="return confirm('Are you sure you want to delete this entry?');")[tags.img(src="/images/ex.png")] ] ) cnt += 1 return domains, destinations, hosts, bdomains, times
def render_footer(self, ctx, data): ctx.fillSlots( 'blog_path', T.a(href="http://blog.%s/" % self.app.servers.httpserver._cfg_site_domain)["blog"]) ctx.fillSlots( 'blog_path', T.a(href="http://blog.%s/" % self.app.servers.httpserver._cfg_site_domain)["blog"]) return ctx
def render_sortOrder(self, ctx, data): request = inevow.IRequest(ctx) if "alphaOrder" in request.args: return ctx.tag["Sorted alphabetically. ", T.a(href=url.URL.fromRequest(request).remove( "alphaOrder"))["[Sort by DB column index]"]] else: return ctx.tag["Sorted by DB column index. ", T.a(href=url.URL.fromRequest(request).add( "alphaOrder", "True"))["[Sort alphabetically]"]]
class ControllerPageAthena(athena.LivePage): """This is broken""" chat = None addSlash = True docFactory = loaders.stan( tags.html[tags.head( render=tags.directive('liveglue') )[tags.link(rel="stylesheet", type="text/css", href="main.css"), tags.link(rel="stylesheet", type="text/css", href="controller.css")], tags.body[tags.h1["IPython Controller"], tags.br, tags.h2[tags.div( render=tags.directive('idwidget')), tags.br, tags.a(href="results")["results"], tags.br, tags.a(href="status")["status"], tags.br, tags.a(href="command")["command"], tags.br, tags.a(href="monitor")["monitor"]], tags.br, tags.div(render=tags.directive('chat'))]]) def __init__(self, controller): athena.LivePage.__init__(self) self.controller = controller if not self.children: self.children = {} self.children["main.css"] = static.File( util.sibpath(__file__, 'main.css')) self.children["controller.css"] = static.File( util.sibpath(__file__, 'controller.css')) def render_idwidget(self, ctx, data): w = aw.IDWidget(self.controller) w.setFragmentParent(self) return ctx.tag[w] def render_chat(self, ctx, data): self.chat = "NO CHAT" if self.chat is None: self.chat = aw.ChatWidget() self.chat.setFragmentParent(self) return ctx.tag[self.chat] def child_results(self, ctx): return ResultsPage(self.controller) def child_status(self, ctx): return StatusPage(self.controller) def child_command(self, ctx): return CommandPage(self.controller) def child_monitor(self, ctx): return MonitorPage(self.controller) def goingLive(self, ctx, client): return self.chat.goingLive(ctx, client)
def render_adminswapper(self,ctx,data): if isAdminOn(ctx) == True: if ctx.arg('q'): return T.a(href="?admin=False&q=%s"%ctx.arg('q'),class_="adminswapper")[ T.img(src="/skin/images/swapadmin.gif") ] else: return T.a(href="?admin=False",class_="adminswapper")[ T.img(src="/skin/images/swapadmin.gif") ] else: if ctx.arg('q'): return T.a(href="?admin=True&q=%s"%ctx.arg('q'),class_="adminswapper")[ T.img(src="/skin/images/swapadmin.gif") ] else: return T.a(href="?admin=True",class_="adminswapper")[ T.img(src="/skin/images/swapadmin.gif") ]
def render_tooltip(self, ctx, data): return T.invisible[ T.a(_class="tt")[" [?] "], T.span(_class="tooltip")[ T.div(_class="tooltipactions")[ T.ul[ T.li(_class="closetooltip")[ " [ ", T.a(href="#")["close"], " ]"]]], data]]
def render_todo(self, ctx, data): deluri = "freeform_post!!delete?id="+str(data[0]) updateuri = "freeform_post!!update?id="+str(data[0])+"&oldstate="+str(data[2]) state = [" Done", " To Do"][int(data[2])==0] tag = ctx.tag if data[2]: tag = ctx.tag(_class="done") return tag[data[1]+" - ", t.a(href=deluri)["Delete"], " / ", t.a(href=updateuri)[("Mark Done", "Mark Undone")[data[2]]], state]
def render_viewSelector(self, context, data): args = inevow.IRequest(context).args view = args.get('view', ['view'])[0] if view == 'view': selector = "View | ", tags.a(href=here.add('view','edit'))[ "Edit" ] editor = '' else: selector = tags.a(href=here.add('view','view'))["View"], " | Edit" editor = context.onePattern('edit')() # get one copy of the edit pattern viewer = context.onePattern('view')() # get one copy of the view pattern return selector, viewer, editor
def render_listmenu(self, ctx, data): l = [] l.append( tags.div(id="t", class_="coherence_menu_item")[tags.a( href='/' + 'devices', class_="coherence_menu_link")['Devices']]) l.append( tags.div(id="t", class_="coherence_menu_item")[tags.a( href='/' + 'logging', class_="coherence_menu_link")['Logging']]) return ctx.tag[l]
def render_backgroundswapper(self,ctx,data): if isInverted(ctx) == True: if ctx.arg('q'): return T.a(href="?invert=False&q=%s"%ctx.arg('q'),class_="backgroundswapper")[ T.img(src="/skin/images/swapbackground-invert.gif") ] else: return T.a(href="?invert=False",class_="backgroundswapper")[ T.img(src="/skin/images/swapbackground-invert.gif") ] else: if ctx.arg('q'): return T.a(href="?invert=True&q=%s"%ctx.arg('q'),class_="backgroundswapper")[ T.img(src="/skin/images/swapbackground.gif") ] else: return T.a(href="?invert=True",class_="backgroundswapper")[ T.img(src="/skin/images/swapbackground.gif") ]
def render_hostname(self, ctx, name): d = self.dbpool.runQueryInPast( ctx, "SELECT name FROM equipment_full " "WHERE lower(name)=lower(%(name)s) " "AND deleted='infinity'", {'name': name}) d.addCallback(lambda x: x and T.a( href="equipment/%s/" % name, render=self.render_apiurl)[ self.render_zwsp(name)] or T.a(href="search/%s/" % name, render=self.render_apiurl)[ self.render_zwsp(name)]) return d
def render_viewSelector(self, context, data): args = inevow.IRequest(context).args view = args.get("view", ["view"])[0] if view == "view": selector = "View | ", tags.a(href=here.add("view", "edit"))["Edit"] editor = "" else: selector = tags.a(href=here.add("view", "view"))["View"], " | Edit" editor = context.onePattern("edit")() # get one copy of the edit pattern viewer = context.onePattern("view")() # get one copy of the view pattern return selector, viewer, editor
def makeDocFactory(self): core.setup(self.repository) return loaders.stan( T.html[self.render_Head, T.body[T.h1["This is the QSOS Repository [" + self.repository + "] Main Page"], T.p["For now, you can ", T.a(href='repository')["browse"], " the repository or ", T.a(href='submit')["submit"], " an evaluation. "]], ])
def render_ip(self, ctx, ip): d = self.dbpool.runQueryInPast(ctx, "SELECT ip FROM equipment_full WHERE ip=%(ip)s " "AND deleted='infinity'", {'ip': ip}) d.addCallback(lambda x: T.invisible[ x and T.a(href="equipment/%s/" % ip, render=self.render_apiurl) [ ip ] or T.a(href="search/%s/" % ip, render=self.render_apiurl) [ ip ], T.invisible(data=self.data_solvedip, # Dunno why we can't use T.directive here render=T.directive("solvedip"))]) return d
def render_hostname(self, ctx, name): d = self.dbpool.runQueryInPast(ctx, "SELECT name FROM equipment_full " "WHERE lower(name)=lower(%(name)s) " "AND deleted='infinity'", {'name': name}) d.addCallback(lambda x: x and T.a(href="equipment/%s/" % name, render=self.render_apiurl) [ self.render_zwsp(name) ] or T.a(href="search/%s/" % name, render=self.render_apiurl) [ self.render_zwsp(name) ]) return d
def makeDocFactory(self) : core.setup(self.repository) return loaders.stan ( T.html [ self.render_Head, T.body [ T.h1 [ "This is the QSOS Repository [" + self.repository + "] Main Page" ], T.p ["For now, you can ", T.a ( href = 'repository' ) [ "browse" ], " the repository or ", T.a ( href = 'submit' ) [ "submit" ], " an evaluation. " ] ], ] )
def gotModel(model): ecategories = inevow.IRequest(ctx).args.get('ecategories',[None])[0] if ecategories is not None: CATEGORIES = ecategories.split('+') else: CATEGORIES = [] #['toy_type.art_and_craft','toy_type.books'] for c in CATEGORIES: id = 'category-%s'%('1234567890'.join(c.split('.'))) model.attributes[id] = tabular.Attribute(sortable=False) model.attributes['id'] = tabular.Attribute(sortable=False) model.attributes['code'] = tabular.Attribute(sortable=True) model.attributes['title'] = tabular.Attribute(sortable=True) view = ProductTabularView('products', model, perPage) view.columns.append(tabular.Column('id', '', cellrenderers.CheckboxRenderer('id'))) view.columns.append(tabular.Column('image', 'Image', ImageRenderer('id'))) view.columns.append(tabular.Column('code', 'Code', cellrenderers.LinkRenderer(url.URL.fromContext(ctx), 'id' ))) view.columns.append(tabular.Column('title', 'Title')) for c in CATEGORIES: id = 'category-%s'%('1234567890'.join(c.split('.'))) view.columns.append(tabular.Column('id', T.a(href='#',title=c)['#'] , StoredStateCheckboxRenderer(id))) return view
def render_topic(self, ctx, data): link = url.root.child('topic').child(data['tid']) ctx.tag.fillSlots('title', t.a(href=link)[data['ttitle']]) ctx.tag.fillSlots('posts_num', int(data['posts_num'])-1) ctx.tag.fillSlots('author', data['towner']) ctx.tag.fillSlots('modification', pptime(data['tmodification'])) return ctx.tag
def render_show_readonly(self, ctx, data): if self.node.is_unknown() or self.node.is_readonly(): return "" rocap = self.node.get_readonly_uri() root = get_root(ctx) uri_link = "%s/uri/%s/" % (root, urllib.quote(rocap)) return ctx.tag[T.a(href=uri_link)["Read-Only Version"]]
def render_footer(self, context, data): return tags.p() [ tags.div()['Lumen is running on port %s' % lumen.config['port']], tags.div()[ tags.a(href='http://github.com/unsouled/lumen')['Github'] ] ]
def render_simpleBreadcrumb(self, ctx, data): # Get a url and a path list u = url.URL.fromContext(ctx) pathList = u.pathList(copy=True) if not pathList[0]: pathList = pathList[1:] pathList = ['home'] + pathList # Work from right to left pathList.reverse() rv = [] first = True while pathList: tag = T.a(href=u)[pathList[0]] if first: # Right most element is not a link first = False tag = pathList[0] rv.append(tag) # set up for next iteration u = u.up() pathList = pathList[1:] if pathList: rv.append(' > ') # Switch so it reads left to right rv.reverse() return ctx.tag[rv]
def render_examples(self, ctx, data): for name in examples: cls = reflect.namedAny(name) yield T.div(class_='example')[ T.h1[T.a(href=url.here.child(name))[cls.title]], T.p[cls.description], ]