Exemple #1
0
    def render_settings(self, ctx, data):
        settings = self.obj.settings[:]
        if self.bse != 'Room':
            settings.append('room')
        if self.bse == 'Exit':
            settings.append('destination')

        lines = []
        for setting in settings:
            error = self.args.get('_%s__error' % setting, False)
            if error:
                cls = 'textlabel_error'
            else:
                cls = 'textlabel'
            label = T.td(_class=cls)[setting]
            val = self.obj.setting(setting)
            if val is None:
                val = getattr(self.obj, setting, None)
            inpt = T.td[self.get_setting_widget(setting, val)]
            lines.append(T.tr[label, inpt])

        if self.bse != 'Room' and self.obj.container != self.obj.room:
            label = T.td(_class="textlabel")['container']
            inpt = T.td[self.container_widget(self.obj)]
            lines.append(T.tr[label, inpt])

        empty = T.td(_class='empty')['']
        lines.append(T.tr[empty, empty])
        submit = T.input(_type="submit", value=" Change ")
        lines.append(T.tr[empty, T.td[submit]])

        tbl = T.table(_class="center")[lines]

        return T.form(action=".", method="POST")[tbl]
Exemple #2
0
    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]
Exemple #3
0
 def render(self, data):
     r = []
     i = 0
     vlanlist = []
     notpresent = T.td(_class="notpresent")[
         T.acronym(title="Not present or no information from remote")["N/A"]]
     for row in data:
         if row[1] is not None:
             vlanlist.append(str(row[0]))
         vid = T.td[T.span(data=row[0], render=T.directive("vlan"))]
         if row[1] is None:
             r.append(T.tr(_class=(i%2) and "odd" or "even")[
                     vid, notpresent,
                     T.td[row[2]]])
         elif row[2] is None:
             r.append(T.tr(_class=(i%2) and "odd" or "even")
                      [vid, T.td[row[1]], notpresent])
         elif row[1] == row[2]:
             r.append(T.tr(_class=(i%2) and "odd" or "even")
                      [vid, T.td(colspan=2)[row[1]]])
         else:
             r.append(T.tr(_class=(i%2) and "odd" or "even")
                      [vid, T.td[row[1]], T.td[row[2]]])
         i += 1
     vlantable = T.table(_class="vlan")[
         T.thead[T.td["VID"], T.td["Local"], T.td["Remote"]], r]
     return [('VLAN',
              [[ [T.span(data=v, render=T.directive("vlan")), " "]
                 for v in vlanlist ],
               T.span(render=T.directive("tooltip"),
                      data=vlantable)],
              ", ".join(vlanlist))]
Exemple #4
0
    def test_athenaIdRewriting(self):
        """
        Test that IDs are correctly rewritten in id, for, and headers
        attributes.
        """
        tag = [tags.label(_for='foo'),
               tags.input(id='foo'),
               tags.th(headers=''),
               tags.th(headers='foo'),
               tags.td(headers='foo bar'),
               tags.td(headers='foo bar baz')]
        element = athena.LiveElement(docFactory=loaders.stan(tag))
        page = athena.LivePage(docFactory=loaders.stan(element))
        element.setFragmentParent(page)

        def _verifyRendering(result):
            self.assertIn('<input id="athenaid:%s-foo"' % (element._athenaID,), result)
            self.assertIn('<label for="athenaid:%s-foo"' % (element._athenaID,), result)
            self.assertIn('<th headers=""', result)
            self.assertIn('<th headers="athenaid:%s-foo"' % (
                element._athenaID,), result)
            self.assertIn('<td headers="athenaid:%s-foo athenaid:%s-bar"' % (
                element._athenaID, element._athenaID), result)
            self.assertIn('<td headers="athenaid:%s-foo athenaid:%s-bar athenaid:%s-baz"' % (
                element._athenaID, element._athenaID, element._athenaID), result)

        return renderLivePage(page).addCallback(_verifyRendering)
Exemple #5
0
    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 format_desc_list(singular, descs, plural=None):
    if plural is None:
        plural = singular + 's'
    if not descs:
        return ''
    if len(descs) > 1:
        label = plural
    else:
        label = singular
    r = []
    first = True
    for d in descs:
        if first:
            row = tags.tr(class_="fieldStart")
            row[tags.td(class_="fieldName")[label]]
            first = False
        else:
            row = tags.tr()
            row[tags.td()]
        if d.name is None:
            row[tags.td(colspan=2)[d.format()]]
        else:
            row[tags.td(class_="fieldArg")[d.name], tags.td[d.format()]]
        r.append(row)
    return r
Exemple #7
0
 def render(self, data):
     r = []
     i = 0
     vlanlist = []
     notpresent = T.td(_class="notpresent")[T.acronym(
         title="Not present or no information from remote")["N/A"]]
     for row in data:
         if row[1] is not None:
             vlanlist.append(str(row[0]))
         vid = T.td[T.span(data=row[0], render=T.directive("vlan"))]
         if row[1] is None:
             r.append(
                 T.tr(_class=(i % 2) and "odd" or "even")[vid, notpresent,
                                                          T.td[row[2]]])
         elif row[2] is None:
             r.append(
                 T.tr(_class=(i % 2) and "odd" or "even")[vid, T.td[row[1]],
                                                          notpresent])
         elif row[1] == row[2]:
             r.append(
                 T.tr(_class=(i % 2) and "odd" or "even")[
                     vid, T.td(colspan=2)[row[1]]])
         else:
             r.append(
                 T.tr(_class=(i % 2) and "odd" or "even")[vid, T.td[row[1]],
                                                          T.td[row[2]]])
         i += 1
     vlantable = T.table(_class="vlan")[T.thead[T.td["VID"], T.td["Local"],
                                                T.td["Remote"]], r]
     return [('VLAN', [[[T.span(data=v, render=T.directive("vlan")), " "]
                        for v in vlanlist],
                       T.span(render=T.directive("tooltip"),
                              data=vlantable)], ", ".join(vlanlist))]
Exemple #8
0
def format_desc_list(singular, descs, plural=None):
    if plural is None:
        plural = singular + 's'
    if not descs:
        return ''
    if len(descs) > 1:
        label = plural
    else:
        label = singular
    r = []
    first = True
    for d in descs:
        if first:
            row = tags.tr(class_="fieldStart")
            row[tags.td(class_="fieldName")[label]]
            first = False
        else:
            row = tags.tr()
            row[tags.td()]
        if d.name is None:
            row[tags.td(colspan=2)[d.format()]]
        else:
            row[tags.td(class_="fieldArg")[d.name], tags.td[d.format()]]
        r.append(row)
    return r
Exemple #9
0
    def render_sessions(self, ctx, data):
        if len(self.pytrans.sessions) <= 0:
            return "No active sessions."

        ret = tags.table(border=0, width="100%", cellspacing=5, cellpadding=2)
        row = tags.tr[
            tags.th["User"],
            tags.th["Incoming Messages"],
            tags.th["Outgoing Messages"],
            tags.th["Connections"]
        ]
        ret[row]
        for key in self.pytrans.sessions:
            jid = self.pytrans.sessions[key].jabberID
            row = tags.tr[
                tags.td[jid],
                tags.td(align="center")[self.pytrans.serviceplugins[
                    'Statistics'].sessionstats[jid]['IncomingMessages']],
                tags.td(align="center")[self.pytrans.serviceplugins[
                    'Statistics'].sessionstats[jid]['OutgoingMessages']],
                tags.td(align="center")[
                    self.pytrans.serviceplugins['Statistics'].sessionstats[jid]['Connections']]
            ]
            ret[row]
        return ret
Exemple #10
0
def varTable(usedVars):
    return t.table(_class="variables")[[
        t.tr(_class="varRow")[
            t.td(_class="varName")[ key ],
            t.td(_class="varValue")[ htmlrepr(value) ]
        ]
        for (key, value) in usedVars
    ]]
Exemple #11
0
def varTable(usedVars):
    return t.table(_class="variables")[[
        t.tr(_class="varRow")[
            t.td(_class="varName")[ key ],
            t.td(_class="varValue")[ htmlrepr(value) ]
        ]
        for (key, value) in usedVars
    ]]
 def exLister(context, data):
     for input, output, note in data:
         context.tag [ T.tr [
             T.td (class_ = "input") [input.encode('utf-8')],
             T.td (class_ = "output") [output.encode('utf-8')],
             T.td (class_ = "note") [note.encode('utf-8')]
             ]
         ]
     return context.tag
Exemple #13
0
 def render_idtable(self, ctx, data):
     lines = []
     for obj in data:
         editlink = T.a(href="/edit/%s" % obj.tzid)[obj.name]
         tzid = T.td(_class="objtzid")[obj.tzid, ':']
         #name = T.td(_class="objname")[obj.name]
         name = T.td(_class="objname")[editlink]
         lines.append(T.tr[tzid, name])
     return T.table[lines]
 def exLister(context, data):
     for input, output, note in data:
         context.tag [ T.tr [
             T.td (class_ = "input") [input.encode('utf-8')],
             T.td (class_ = "output") [output.encode('utf-8')],
             T.td (class_ = "note") [note.encode('utf-8')]
             ]
         ]
     return context.tag
Exemple #15
0
def htmlDict(d):
    return t.div(_class="dict")[
        t.span(_class="heading")["Dictionary instance @ 0x%x" % id(d)],
        t.table(_class="dict")[[
            t.tr[t.td(
                _class="dictKey")[k == '__builtins__' and 'builtin dictionary'
                                  or htmlrepr(k)],
                 t.td(_class="dictValue")[htmlrepr(v)]] for k, v in d.items()
        ]]]
Exemple #16
0
    def render_roster(self, ctx, data):
        request = inevow.IRequest(ctx)
        username = request.getUser()

        ret = tags.table(border=0, cellspacing=5, cellpadding=2)
        row = tags.tr(height=25)[
            tags.th["UIN/Screen Name"],
            tags.th["Nickname"],
            tags.th["Network"],
            tags.th["Avatar"],
            tags.th["Status"]
        ]
        ret[row]
        roster = self.pytrans.xdb.getList("roster", username)
        if not roster:
            return ret
        for item in roster:
            if item[0][0].isdigit():
                network = "ICQ"
            else:
                network = "AIM"
            avatar = "-"
            if not config.disableAvatars and item[1].has_key("shahash"):
                avatar = tags.a(href=("/avatars/%s" % item[1]["shahash"]))[
                    tags.img(
                        border=0, height=25, src=("/avatars/%s" % item[1]["shahash"]))
                ]
            nickname = "-"
            if "nickname" in item[1]:
                nickname = item[1]["nickname"]
            else:
                if username in self.pytrans.sessions and \
                        self.pytrans.sessions[username].ready:
                    c = self.pytrans.sessions[username].contactList.getContact(
                        "%s@%s" % (item[0], config.jid))
                    if c.nickname and c.nickname != "":
                        nickname = c.nickname
            status = "-"
            if username in self.pytrans.sessions and \
                    self.pytrans.sessions[username].ready:
                c = self.pytrans.sessions[username].contactList.getContact(
                    "%s@%s" % (item[0], config.jid))
                status = c.ptype
                if not status:
                    status = c.show
                    if not status:
                        status = "available"
            row = tags.tr(height=25)[
                tags.td(height=25, align="middle")[item[0]],
                tags.td(height=25, align="middle")[nickname],
                tags.td(height=25, align="middle")[network],
                tags.td(height=25, align="middle")[avatar],
                tags.td(height=25, align="middle")[status]
            ]
            ret[row]
        return ret
Exemple #17
0
def htmlDict(d):
    return t.div(_class="dict")[
        t.span(_class="heading")[
            "Dictionary instance @ 0x%x" % id(d)
        ],
        t.table(_class="dict")[[
            t.tr[
                t.td(_class="dictKey")[ k == '__builtins__' and 'builtin dictionary' or htmlrepr(k) ],
                t.td(_class="dictValue")[ htmlrepr(v) ]
            ]
            for k, v in d.items()
        ]]
    ]
Exemple #18
0
    def content(self, name, **kwargs):
        game = games[name]
        yield t.h1["Game: ", name]
        yield t.h2["Min. Date: ", str(game.mindate)]
        yield t.h2["Players"]
        header = t.tr[t.th["Name"], t.th["Date"], t.th["Cem'y"], t.th,
                      [] if game.locked else t.th]
        rows = [
            t.form(method='GET', action='/part')[
                t.tr[t.td[t.a(href="/player" +
                              self.query_string(game=name, name=n))[n]],
                     t.td[str(game.players[n].date)],
                     t.td(Class='num')[str(game.players[n].kia)],
                     t.td['Leader' if game.players[n].leader else []],
                     [] if game.locked else t.td[
                         t.input(type='hidden', name='game', value=name),
                         t.input(type='hidden', name='name', value=n),
                         t.input(type='submit', value='Remove')], ]]
            for n in sorted(game.players)
        ]
        rows.append(
            t.form(method='GET', action='/join')
            [t.input(type='hidden', name='game', value=name),
             t.tr[t.td[t.input(type='text', name='name')],
                  t.td(colspan=2), [] if game.locked else t.
                  td[t.input(type='submit', value='New')]]])
        if not game.locked:
            yield t.form(method='GET', action='/lock')[
                t.input(type='hidden', name='game', value=name),
                t.input(type='submit', value='Lock')]
        yield t.table[header, rows]

        def shortresult(contract):
            front = [
                p for p in contract.date
                if contract.date[p] == contract.firstdate
            ]
            text = [
                '%s, %s, %s' % (p.name, contract.date[p], contract.first(p))
                for p in front
            ]
            return '(%s)' % ('; '.join(text))

        yield t.h2["Contracts"]
        yield t.ul[[
            t.li[t.a(href="/result" +
                     self.query_string(game=name, contract=n))[n], ': ',
                 shortresult(game.contracts[n])]
            for n in sorted(game.contracts,
                            key=lambda n: game.contracts[n].firstdate)
        ]]
Exemple #19
0
 def render_bayeux_environments(self):
     return [
         tags.h3()['Bayeux Environmerts'],
         tags.table()[
             tags.tr()[
                 tags.th()['Port'],
                 tags.td()[lumen.config['port']],
             ],
             tags.tr()[
                 tags.th()['Engine'],
                 tags.td()[lumen.config['engine']],
             ]
         ],
     ]
Exemple #20
0
    def render_roster(self, ctx, data):
        request = inevow.IRequest(ctx)
        username = request.getUser()

        ret = T.table(border=0, cellspacing=5, cellpadding=2)
        row = T.tr(height=25)[T.th["UIN/Screen Name"], T.th["Nickname"],
                              T.th["Network"], T.th["Avatar"], T.th["Status"]]
        ret[row]
        roster = self.pytrans.xdb.getList("roster", username)
        if not roster:
            return ret
        for item in roster:
            if item[0][0].isdigit():
                network = "ICQ"
            else:
                network = "AIM"
            avatar = "-"
            if not config.disableAvatars and item[1].has_key("shahash"):
                avatar = T.a(href=("/avatars/%s" % item[1]["shahash"]))[T.img(
                    border=0,
                    height=25,
                    src=("/avatars/%s" % item[1]["shahash"]))]
            nickname = "-"
            if item[1].has_key("nickname"):
                nickname = item[1]["nickname"]
            else:
                if self.pytrans.sessions.has_key(
                        username) and self.pytrans.sessions[username].ready:
                    c = self.pytrans.sessions[username].contactList.getContact(
                        "%s@%s" % (item[0], config.jid))
                    if c.nickname and c.nickname != "":
                        nickname = c.nickname
            status = "-"
            if self.pytrans.sessions.has_key(
                    username) and self.pytrans.sessions[username].ready:
                c = self.pytrans.sessions[username].contactList.getContact(
                    "%s@%s" % (item[0], config.jid))
                status = c.ptype
                if not status:
                    status = c.show
                    if not status:
                        status = "available"
            row = T.tr(height=25)[T.td(height=25, align="middle")[item[0]],
                                  T.td(height=25, align="middle")[nickname],
                                  T.td(height=25, align="middle")[network],
                                  T.td(height=25, align="middle")[avatar],
                                  T.td(height=25, align="middle")[status]]
            ret[row]
        return ret
Exemple #21
0
    def format(self):
        r = []

        ivs = []
        for iv in self.ivar_descs:
            attr = zopeinterface.Attribute(self.obj.system, iv.name, iv.body,
                                           self.obj)
            if iv.name is None or attr.isVisible:
                ivs.append(iv)
        self.ivar_descs = ivs

        cvs = []
        for cv in self.cvar_descs:
            attr = zopeinterface.Attribute(self.obj.system, cv.name, cv.body,
                                           self.obj)
            if attr.isVisible:
                cvs.append(cv)
        self.cvar_descs = cvs

        for d, l in (('Parameters', self.parameter_descs),
                     ('Instance Variables', self.ivar_descs),
                     ('Class Variables', self.cvar_descs), ('Variables',
                                                            self.var_descs)):
            r.append(format_desc_list(d, l, d))
        if self.return_desc:
            r.append(
                tags.tr(class_="fieldStart")[
                    tags.td(class_="fieldName")['Returns'],
                    tags.td(colspan="2")[self.return_desc.format()]])
        r.append(format_desc_list("Raises", self.raise_descs, "Raises"))
        for s, p, l in (('Author', 'Authors', self.authors),
                        ('See Also', 'See Also', self.seealsos),
                        ('Present Since', 'Present Since',
                         self.sinces), ('Note', 'Notes', self.notes)):
            r.append(format_field_list(self.obj, s, l, p))
        unknowns = {}
        unknownsinorder = []
        for fieldinfo in self.unknowns:
            tag = fieldinfo.kind
            if tag in unknowns:
                unknowns[tag].append(fieldinfo)
            else:
                unknowns[tag] = [fieldinfo]
                unknownsinorder.append(unknowns[tag])
        for fieldlist in unknownsinorder:
            label = "Unknown Field: " + fieldlist[0].kind
            r.append(format_desc_list(label, fieldlist, label))

        return tags.table(class_='fieldTable')[r]
Exemple #22
0
    def render_index_rooms(self, ctx, data):
        lines = []
        data.sort(key=attrgetter('name'))
        for room in data:
            editlink = T.a(href="/edit/%s" % room.tzid)[room.name]
            tzid = T.td(_class="roomtzid")[room.tzid, ':']
            #name = T.td(_class="roomname")[room.name]
            name = T.td(_class="roomname")[editlink]
            if not room.exits():
                row = T.tr(_class='warn')
            else:
                row = T.tr
            lines.append(row[tzid, name])

        return T.table[lines]
Exemple #23
0
        def ret(ethtool):
            state = False
            rate = "Unknown"
            for n in ethtool.split('\n'):
                l = n.strip()
                if not ':' in l:
                    continue
                l = n.strip().split(':')

                k = l[0].strip()
                v = l[1].strip()

                if k == 'Link detected':
                    state = v == 'yes'
                if k == 'Speed':
                    rate = v

            if not state:
                rate = "Not Connected"

            if doState:
                green = "#29b25c"
                red = "#bf0000"
                img = state and '/images/state-running.png' or '/images/state-stopped-whitebg.png'
                color = state and green or red
                return [
                    tags.td[tags.img(src=img)],
                    tags.td(
                        width="100%")[entities.nbsp,
                                      tags.span(
                                          style="color: %s" %
                                          color)["Ethernet connection (%s)" %
                                                 (iface)]],
                ]
            return ctx.tag["%s" % rate]
Exemple #24
0
    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'))]]]
Exemple #25
0
def dataTable(headings, content, sortable = False, tabid=None):
    """ Produces a tabular listing which is either sortable or not. Sortable expects headings to be a 
        list of tuples, but if it is not a list of tuples the 'string' type will be assumed for every cell """
    if sortable:
        if isinstance(headings[0], tuple):
            header = [ tags.th(colformat=j)[i] for j,i in headings ]
        else:
            header = [ tags.th(colformat='istr')[i] for i in headings ]
        tclass = 'sortable'
    else:
        header = [ tags.th[i] for i in headings ]
        tclass = 'listing'

    if not content: 
        rows = tags.tr[ tags.td(colspan=len(headings))[tags.em["No entries."]]]
    else:
        rows = [tags.tr[ [tags.td[col] for col in row] ]
        for row in content]

    return tags.table(id = tabid, cellspacing=0,  _class=tclass)[
        tags.thead(background="/images/gradMB.png")[
            tags.tr[
                header
            ]
        ],
        tags.tbody[
            rows
        ]
    ]
Exemple #26
0
 def render_channels_list(self):
     result = tags.table()
     result.children.append(
         tags.tr()[
             tags.th()['id'],
             tags.th()['subscribers'],
         ]
     )
     for clientId, c in channel.channels.items():
         result.children.append(
             tags.tr()[
                 tags.td()[c.id],
                 tags.td()[len(c.subscribers)],
             ]
         )
     return result
Exemple #27
0
 def render(self, data):
     r = []
     i = 0
     notpresent = T.td(_class="notpresent")[
         T.acronym(title="Unable to get IP from ARP tables")["N/A"]]
     for row in data:
         mac = T.td[T.span(data=row[0], render=T.directive("mac"))]
         if row[1] is not None:
             r.append(T.tr(_class=(i%2) and "odd" or "even")
                      [mac, T.td[T.invisible(data=row[1],
                                             render=T.directive("ip"))]])
         else:
             r.append(T.tr(_class=(i%2) and "odd" or "even")
                      [mac, notpresent])
         i += 1
     if len(r) == 1:
         return [('FDB',
                  [T.span(data=data[0][0], render=T.directive("mac")),
                   data[0][1] and [", ", T.span(data=data[0][1],
                                                render=T.directive("ip"))] or ""],
                  1)]
     return [('FDB',
              [len(r) == 20 and "20+" or len(r),
               T.span(render=T.directive("tooltip"),
                      data=T.table(_class="mac")[
                     T.thead[T.td["MAC"], T.td["IP"]], r])],
              len(r) == 20 and 21 or len(r))]
Exemple #28
0
def autoTable(headers, rows):
    table = tags.table[tags.thead[tags.tr[[tags.th[i] for i in headers]]],
                       tags.tbody[[
                           tags.tr[[tags.td(valign='top')[i] for i in cols]]
                           for cols in rows
                       ]]]
    return table
Exemple #29
0
 def test_nestedpatterns(self):
     def data_table(context, data):  return [[1,2,3],[4,5,6]]
     def data_header(context, data):  return ['col1', 'col2', 'col3']
     tag = tags.html[
         tags.body[
             tags.table(data=data_table, render=rend.sequence)[
                 tags.tr(pattern='header', data=data_header, render=rend.sequence)[
                     tags.td(pattern='item')[str]
                 ],
                 tags.tr(pattern='item', render=rend.sequence)[
                     tags.td(pattern='item')[str]
                 ]
             ]
         ]
     ]
     self.assertEqual(self.render(tag), "<html><body><table><tr><td>col1</td><td>col2</td><td>col3</td></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table></body></html>")
Exemple #30
0
 def render(self, data):
     r = []
     i = 0
     notpresent = T.td(_class="notpresent")[T.acronym(
         title="Unable to get IP from ARP tables")["N/A"]]
     for row in data:
         mac = T.td[T.span(data=row[0], render=T.directive("mac"))]
         if row[1] is not None:
             r.append(
                 T.tr(_class=(i % 2) and "odd" or "even")
                 [mac,
                  T.td[T.invisible(data=row[1], render=T.directive("ip"))]])
         else:
             r.append(
                 T.tr(_class=(i % 2) and "odd" or "even")[mac, notpresent])
         i += 1
     if len(r) == 1:
         return [('FDB', [
             T.span(data=data[0][0],
                    render=T.directive("mac")), data[0][1] and
             [", ", T.span(data=data[0][1], render=T.directive("ip"))] or ""
         ], 1)]
     return [('FDB', [
         len(r) == 20 and "20+" or len(r),
         T.span(render=T.directive("tooltip"),
                data=T.table(_class="mac")[T.thead[T.td["MAC"], T.td["IP"]],
                                           r])
     ], len(r) == 20 and 21 or len(r))]
Exemple #31
0
 def test_nestedpatterns(self):
     def data_table(context, data):  return [[1,2,3],[4,5,6]]
     def data_header(context, data):  return ['col1', 'col2', 'col3']
     tag = tags.html[
         tags.body[
             tags.table(data=data_table, render=rend.sequence)[
                 tags.tr(pattern='header', data=data_header, render=rend.sequence)[
                     tags.td(pattern='item')[str]
                 ],
                 tags.tr(pattern='item', render=rend.sequence)[
                     tags.td(pattern='item')[str]
                 ]
             ]
         ]
     ]
     self.assertEquals(self.render(tag), "<html><body><table><tr><td>col1</td><td>col2</td><td>col3</td></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table></body></html>")
    def format(self):
        r = []

        ivs = []
        for iv in self.ivar_descs:
            attr = zopeinterface.Attribute(
                self.obj.system, iv.name, iv.body, self.obj)
            if iv.name is None or attr.isVisible:
                ivs.append(iv)
        self.ivar_descs = ivs

        cvs = []
        for cv in self.cvar_descs:
            attr = zopeinterface.Attribute(
                self.obj.system, cv.name, cv.body, self.obj)
            if attr.isVisible:
                cvs.append(cv)
        self.cvar_descs = cvs

        for d, l in (('Parameters', self.parameter_descs),
                     ('Instance Variables', self.ivar_descs),
                     ('Class Variables', self.cvar_descs),
                     ('Variables', self.var_descs)):
            r.append(format_desc_list(d, l, d))
        if self.return_desc:
            r.append(tags.tr(class_="fieldStart")[tags.td(class_="fieldName")['Returns'],
                               tags.td(colspan="2")[self.return_desc.format()]])
        r.append(format_desc_list("Raises", self.raise_descs, "Raises"))
        for s, p, l in (('Author', 'Authors', self.authors),
                        ('See Also', 'See Also', self.seealsos),
                        ('Present Since', 'Present Since', self.sinces),
                        ('Note', 'Notes', self.notes)):
            r.append(format_field_list(self.obj, s, l, p))
        unknowns = {}
        unknownsinorder = []
        for fieldinfo in self.unknowns:
            tag = fieldinfo.kind
            if tag in unknowns:
                unknowns[tag].append(fieldinfo)
            else:
                unknowns[tag] = [fieldinfo]
                unknownsinorder.append(unknowns[tag])
        for fieldlist in unknownsinorder:
            label = "Unknown Field: " + fieldlist[0].kind
            r.append(format_desc_list(label, fieldlist, label))

        return tags.table(class_='fieldTable')[r]
Exemple #33
0
    def render_transactions(self, ctx):
        coll = mongo['heist']['transactions']
        rows = reversed(list(coll.find(sort=[("readAt", -1)], limit=6)))
        now = datetime.datetime.now(tzlocal())

        def recentClass(d):
            if (now - d).total_seconds() < 86400 * 2:
                return {"class": "recent"}
            return {}

        return T.table(class_="transactions")[[
            T.tr(**recentClass(row['date']))[T.td(
                class_="date")[row['date'].date().isoformat()],
                                             T.td(class_="to")[row['payee']],
                                             T.td(class_="amt")[row['amount']]]
            for row in rows
        ]]
Exemple #34
0
 def render_widgets(self, ctx, data):
     f = aw.CommandWidget(self.controller)
     f.setFragmentParent(self)
     g = aw.StatusWidget(self.controller)
     g.setFragmentParent(self)
     h = aw.ResultWidget()
     h.setFragmentParent(self)
     n1 = results.notifierFromFunction(h.handleResult)
     self.controller.addNotifier(n1)
     n2 = results.notifierFromFunction(g.refreshStatus)
     f.addNotifier(n2)
     reactor.callLater(1, g.refreshStatus)
     build = tags.table(id="monitor")[tags.tr[tags.td(valign="top")[g],
                                              tags.td(valign="top")[h,
                                                                    tags.br,
                                                                    f]]]
     return ctx.tag[build]
Exemple #35
0
class Tester(livepage.LivePage):
    addSlash = True
    child_css = static.File(os.path.join(resourceDirectory, 'livetest.css'))
    child_scripts = static.File(os.path.join(resourceDirectory, 'livetest.js'))
    child_postscripts = static.File(
        os.path.join(resourceDirectory, 'livetest-postscripts.js'))
    docFactory = loaders.stan(tags.html[
        tags.head[tags.script(src="scripts"),
                  tags.link(rel="stylesheet", type="text/css", href="css")],
        tags.body[tags.table(id="testprogress")[
            tags.tr[tags.th["Tests"], tags.th["Pass"], tags.th["Fail"]], tags.
            tr[tags.td(id="test-status")["Running"],
               tags.td(id="test-passes", _class="test-passes")[entities.nbsp],
               tags.td(id="test-failures", _class="test-failures")[entities.
                                                                   nbsp]]],
                  tags.
                  table(id="testresults", render=tags.directive('table')
                        )[tags.
                          tr(pattern="item", render=tags.directive('test'))[
                              tags.td[tags.slot('action')],
                              tags.td[tags.slot('target')],
                              tags.td[tags.slot('parameter')]]],
                  tags.iframe(id="testframe", src="asdf"),
                  tags.script(src="postscripts"), livepage.glue]])

    def render_table(self, ctx, suite):
        self.testId = 0
        driver = Driver(suite)
        handle = livepage.IClientHandle(ctx)
        driver.notifyWhenTestsComplete().addCallback(self.testsComplete,
                                                     handle)
        driver.setHandle(handle)
        driver.nextTest()
        return rend.sequence(ctx, suite)

    def render_test(self, ctx, test):
        ctx.tag(id=("test-", self.testId))
        action, target, parameter = test
        ctx.fillSlots('action', action)
        ctx.fillSlots('target', str(target))
        ctx.fillSlots('parameter', parameter)
        self.testId += 1
        return ctx.tag

    def testsComplete(self, results, handle):
        handle.set('test-status', 'Complete')
Exemple #36
0
 def document(self):
     return stan(T.html[T.head[T.invisible(
         render=T.directive('head'))], T.body[T.form(
             action=url.root.child(guard.LOGIN_AVATAR),
             method="post",
             id="loginForm"
         )[T.table(
             style="text-align: center"
         )[T.tr[T.td[T.label(_for="username")["Username:"******"text", id="username", name="username")]],
           T.tr[
               T.td[T.label(_for="password")["Password:"******"password", id="password", name="password"
                            )]],
           T.tr[T.td(colspan="2", style="text-align:left")[
               T.label(_for="rememberMe")["Remember Me"],
               T.input(type="checkbox", id="rememberMe", name="rememberMe"
                       )]],
           T.tr[T.td(colspan="2", style="text-align: center"
                     )[T.input(type="submit", value="Login")]]]]]])
Exemple #37
0
	def _computeDefaultTds(self):
		"""leaves a sequence of children for each row in the
		defaultTds attribute.

		This calls _computeSerializationRules.  The function was
		(and can still be) used for stan-based serialization of HTML tables,
		but beware that that is dead slow.  The normal rendering doesn't
		use defaultTds any more.
		"""
		self._computeSerializationRules()
		self.defaultTds = []
		for (name, formatter, wantsRow) in self.formatterSeq:
			if wantsRow:
				self.defaultTds.append(
					T.td(formatter=formatter, render=T.directive("useformatter")))
			else:
				self.defaultTds.append(T.td(
					data=T.slot(unicode(name)),
					formatter=formatter,
					render=T.directive("useformatter")))
Exemple #38
0
    def render_transactions(self, ctx):
        coll = mongo["heist"]["transactions"]
        rows = reversed(list(coll.find(sort=[("readAt", -1)], limit=6)))
        now = datetime.datetime.now(tzlocal())

        def recentClass(d):
            if (now - d).total_seconds() < 86400 * 2:
                return {"class": "recent"}
            return {}

        return T.table(class_="transactions")[
            [
                T.tr(**recentClass(row["date"]))[
                    T.td(class_="date")[row["date"].date().isoformat()],
                    T.td(class_="to")[row["payee"]],
                    T.td(class_="amt")[row["amount"]],
                ]
                for row in rows
            ]
        ]
Exemple #39
0
    def render_sessions(self, ctx, data):
        if len(self.pytrans.sessions) <= 0:
            return "No active sessions."

        ret = T.table(border=0, width="100%", cellspacing=5, cellpadding=2)
        row = T.tr[T.th["User"], T.th["Incoming Messages"],
                   T.th["Outgoing Messages"], T.th["Connections"]]
        ret[row]
        for key in self.pytrans.sessions:
            jid = self.pytrans.sessions[key].jabberID
            row = T.tr[
                T.td[jid],
                T.td(align="center")[self.pytrans.serviceplugins['Statistics'].
                                     sessionstats[jid]['IncomingMessages']],
                T.td(align="center")[self.pytrans.serviceplugins['Statistics'].
                                     sessionstats[jid]['OutgoingMessages']],
                T.td(align="center")[self.pytrans.serviceplugins['Statistics'].
                                     sessionstats[jid]['Connections']]]
            ret[row]
        return ret
Exemple #40
0
    def render_clients_list(self):
        result = tags.table()
        result.children.append(
            tags.tr()[
                tags.th()['id'],
                tags.th()['type'],
                tags.th()['created at'],


            ]
        )
        for clientId, c in client.clients.items():
            result.children.append(
                tags.tr()[
                    tags.td()[clientId],
                    tags.td()[c.typename],
                    tags.td()[c.createdAt.strftime("%A, %d. %B %Y %I:%M%p")],
                ]
            )
        return result
Exemple #41
0
    def render_webconsole_environments(self):
        return [
            tags.h3()['Web console Environments'],
            tags.table()[
                tags.tr()[
                    tags.th()['Port'],
                    tags.td()[lumen.config['webport']],
                ],

            ],
        ]
Exemple #42
0
    def render_menu(self, ctx, data):
        request = inevow.IRequest(ctx)
        username = request.getUser()

        ret = T.table(border=0, cellspacing=3, cellpadding=3)
        row = T.tr(valign="middle")
        row[T.td(_class="menuentry",
                 width="150",
                 align="center",
                 onclick="self.location='/account/'",
                 onmouseover="this.className='menuentrypressed';",
                 onmouseout="this.className='menuentry';")[T.a(
                     _class="menuentry", href="/account/")["Account"]]]

        if config.admins.count(username) > 0:
            row[T.td(_class="menuentry",
                     width="150",
                     align="center",
                     onclick="self.location='/status/'",
                     onmouseover="this.className='menuentrypressed';",
                     onmouseout="this.className='menuentry';")[T.a(
                         _class="menuentry", href="/status/")["Status"]]]
            row[T.td(_class="menuentry",
                     width="150",
                     align="center",
                     onclick="self.location='/config/'",
                     onmouseover="this.className='menuentrypressed';",
                     onmouseout="this.className='menuentry';")[T.a(
                         _class="menuentry",
                         href="/config/")["Configuration"]]]
            row[T.td(_class="menuentry",
                     width="150",
                     align="center",
                     onclick="self.location='/controls/'",
                     onmouseover="this.className='menuentrypressed';",
                     onmouseout="this.className='menuentry';")[T.a(
                         _class="menuentry", href="/controls/")["Controls"]]]

        ret[row]

        return ret
Exemple #43
0
def table(updatingMeasurements):
    meas = []
    for m in updatingMeasurements.measurements:
        # (but consider beyond my strip, to see approaching traffic)
        if m['freeway_id'] == '101' and 408 < float(m['abs_pm']) < 412.5:
            meas.append((float(m['abs_pm']), m))

    meas.sort()

    rows = [T.tr[T.th(colspan=4, class_="dir-N")['North'],
                 T.th(colspan=4, class_="dir-S")['South']],
            T.tr[T.th['fwy'], T.th['postmile'], T.th['name'], T.th['speed'],
                 T.th['fwy'], T.th['postmile'], T.th['name'], T.th['speed']]]
    for _, m in meas:
        attr = dict(class_="dir-%s" % m['freeway_dir'])
        chunk = [T.td(**attr)[m['freeway_id'] + m['freeway_dir']],
                 T.td(**attr)[m['abs_pm']],
                 T.td(**attr)[m['name']],
                 T.td(**attr)[m['speed']],
                 ]
        if m['freeway_dir'] == 'N':
            tds = chunk + [T.td(colspan=4)]
        else:
            tds = [T.td(colspan=4)] + chunk
        rows.append(T.tr[tds])

    return T.table[rows]
Exemple #44
0
def table(updatingMeasurements):
    meas = []
    for m in updatingMeasurements.measurements:
        # (but consider beyond my strip, to see approaching traffic)
        if m['freeway_id'] == '101' and 408 < float(m['abs_pm']) < 412.5:
            meas.append((float(m['abs_pm']), m))

    meas.sort()

    rows = [
        T.tr[T.th(colspan=4, class_="dir-N")['North'],
             T.th(colspan=4, class_="dir-S")['South']],
        T.tr[T.th['fwy'], T.th['postmile'], T.th['name'], T.th['speed'],
             T.th['fwy'], T.th['postmile'], T.th['name'], T.th['speed']]
    ]
    for _, m in meas:
        attr = dict(class_="dir-%s" % m['freeway_dir'])
        chunk = [
            T.td(**attr)[m['freeway_id'] + m['freeway_dir']],
            T.td(**attr)[m['abs_pm']],
            T.td(**attr)[m['name']],
            T.td(**attr)[m['speed']],
        ]
        if m['freeway_dir'] == 'N':
            tds = chunk + [T.td(colspan=4)]
        else:
            tds = [T.td(colspan=4)] + chunk
        rows.append(T.tr[tds])

    return T.table[rows]
Exemple #45
0
def format_field_list(obj, singular, fields, plural=None):
    if plural is None:
        plural = singular + 's'
    if not fields:
        return ''
    if len(fields) > 1:
        label = plural
    else:
        label = singular
    rows = []
    first = True
    for field in fields:
        if first:
            row = tags.tr(class_="fieldStart")
            row[tags.td(class_="fieldName")[label]]
            first = False
        else:
            row = tags.tr()
            row[tags.td()]
        row[tags.td(colspan=2)[field.body]]
        rows.append(row)
    return rows
Exemple #46
0
def recentReviews():
    result = fetch("""
PREFIX rev: <http://purl.org/stuff/rev#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?thing ?name ?review ?createdOn ?rating
WHERE
{
  ?thing rdfs:label ?name ;
         rev:hasReview ?review .
  ?review rev:reviewer <people/drewp> ;
          rev:createdOn ?createdOn ;
          rev:rating ?rating .
} 
ORDER BY DESC(?createdOn)
LIMIT 10
""")

    et = fromstring(result)
    headers = [e.get('name') for e in et.find(SPARQL_RESULTS + 'head')]
    rows = []
    for result in et.find(SPARQL_RESULTS + 'results').getchildren():
        bindings = dict([(b.get('name').replace('?',''),
                          nodeElement(b.getchildren()))
                         for b in result.findall(SPARQL_RESULTS + 'binding')])
        rows.append(bindings)
        
    rows.sort(key=lambda row: row['createdOn'], reverse=True)
    return flat.ten.flatten(T.table(class_="recentReviews")[
        T.tr[T.th(class_="recentReviews title", colspan=3)[
             "Recent reviews on ", T.a(class_="recentReviews",
                                       href="http://revyu.com")["revyu.com"],
             #" (-tmp)"
               ]],
        T.tr[T.th["Date"], T.th["Review"], T.th["Rating"]],
        [T.tr[T.td(class_="date")[row['createdOn'].split('T')[0]],
              T.td(class_="subj")[T.a(href=row['review'])[row['name']]],
              T.td(class_="rate")[row['rating']]]
         for row in rows]
        ])
def format_field_list(obj, singular, fields, plural=None):
    if plural is None:
        plural = singular + 's'
    if not fields:
        return ''
    if len(fields) > 1:
        label = plural
    else:
        label = singular
    rows = []
    first = True
    for field in fields:
        if first:
            row = tags.tr(class_="fieldStart")
            row[tags.td(class_="fieldName")[label]]
            first=False
        else:
            row = tags.tr()
            row[tags.td()]
        row[tags.td(colspan=2)[field.body]]
        rows.append(row)
    return rows
Exemple #48
0
def recentReviews():
    result = fetch("""
PREFIX rev: <http://purl.org/stuff/rev#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?thing ?name ?review ?createdOn ?rating
WHERE
{
  ?thing rdfs:label ?name ;
         rev:hasReview ?review .
  ?review rev:reviewer <people/drewp> ;
          rev:createdOn ?createdOn ;
          rev:rating ?rating .
} 
ORDER BY DESC(?createdOn)
LIMIT 10
""")

    et = fromstring(result)
    headers = [e.get('name') for e in et.find(SPARQL_RESULTS + 'head')]
    rows = []
    for result in et.find(SPARQL_RESULTS + 'results').getchildren():
        bindings = dict([(b.get('name').replace('?', ''),
                          nodeElement(b.getchildren()))
                         for b in result.findall(SPARQL_RESULTS + 'binding')])
        rows.append(bindings)

    rows.sort(key=lambda row: row['createdOn'], reverse=True)
    return flat.ten.flatten(
        T.table(class_="recentReviews")
        [T.tr[T.th(class_="recentReviews title", colspan=3)[
            "Recent reviews on ",
            T.a(class_="recentReviews", href="http://revyu.com")["revyu.com"],
            #" (-tmp)"
        ]], T.tr[T.th["Date"], T.th["Review"], T.th["Rating"]], [
            T.tr[T.td(class_="date")[row['createdOn'].split('T')[0]],
                 T.td(class_="subj")[T.a(href=row['review'])[row['name']]],
                 T.td(class_="rate")[row['rating']]] for row in rows
        ]])
Exemple #49
0
	def makeDocFactory(self):
		return loaders.stan([
			T.div(render=T.directive("meta"), class_="warning")["_warning"],
			T.table(class_="keyvalue", render=rend.mapping,
					data=T.directive("firstrow")) [
				[[T.tr[
						T.th(data=colDef, render=T.directive("headCell"),
							class_="thHorizontal"),
						td],
					T.tr(class_="keyvaluedesc")[T.td(colspan=2)[
						colDef.description]]]
					for colDef, td in zip(self.serManager.table.tableDef.columns, 
						self.defaultTds)]],
			T.invisible(render=T.directive("footnotes")),
			])
Exemple #50
0
 def content(self, **kwargs):
     yield t.h1["KSP Race Into Space server"]
     yield t.h2["Games in progress"]
     header = t.tr[t.th["Name"], t.th["Players"], t.th["Min. Date"]]
     rows = [t.form(method='GET', action='/rmgame')[t.tr[
                 t.td[t.a(href="/game" + self.query_string(name=n))[n]],
                 t.td[", ".join(games[n].players.keys())],
                 t.td[str(games[n].mindate)],
                 t.td if games[n].locked or not kwargs.get('_local') else
                 t.td[t.input(type='hidden', name='game', value=n),
                      t.input(type='submit', value='End')]
                 ]]
             for n in sorted(games)]
     rows.append(t.form(method='GET', action='/newgame')[t.tr[
                     t.td[t.input(type='text', name='name')],
                     t.td(colspan=2),
                     t.td[t.input(type='submit', value='New')]]])
     yield t.table[header, rows]
Exemple #51
0
    def _makeAdditionalSelector(self):
        """returns an ul element containing form material for additional output
		columns.
		"""
        checkLiterals = {True: "checked", False: None}
        fields = []
        for column, checked in sorted(self.availableFields,
                                      key=lambda p: p[0].name):
            fields.append(
                T.tr[T.td[T.input(type="checkbox",
                                  name="_ADDITEM",
                                  value=column.key,
                                  style="width:auto",
                                  checked=checkLiterals[checked])],
                     T.td(
                         style="vertical-align:middle")[" %s -- %s" %
                                                        (column.name,
                                                         column.description)]])
        return T.table(id="addSelection")[fields]
Exemple #52
0
    def render_fullList(self, ctx, data):
        """Render details of a single item."""
        tag = ListBase.render_fullList(self, ctx, data)

        srv = IService(ctx)

        # pylint: disable-msg=E1101
        if srv.isReserved(self.item):
            msg = u"""Ce souhait est déjà réservé par
            quelqu'un. Êtes-vous sûr de vouloir le supprimer\xa0?"""
        else:
            msg = u"""Vous êtes sur le point d'effacer un
            souhait. Cette opération est irréversible."""

        return T.div[T.table[T.tr[T.td[T.img(src="/images/logo-danger.png",
                                             width="35",
                                             height="41",
                                             style="margin-right: 1em",
                                             alt="Attention"), ],
                                  T.td(valign="center")[msg]]], tag]
 def render_listRow(self, ctx: WovenContext, data=None):
     listCell = inevow.IQ(ctx).patternGenerator("listCell")
     self.expanded = False
     ctx.fillSlots('index', self._employee.employee_id)
     if self.length == 3:
         r = [
             listCell(data=dict(listItem='►'))(id='expand-button')[
                 T.Tag("athena:handler")(event='onclick', handler='expand')],
             listCell(data=dict(listItem='▼'))(style='display:none', id='unexpand-button')[
                 T.Tag("athena:handler")(event='onclick', handler='expand')],
         ]
     else:
         r = []
     for k in self.keys:
         if k == 'expanded':
             if not self.parent.selectable:
                 r.append(T.td(style='display:none', id='expanded')[self.tableDocFactory.load(ctx, self.preprocessors)])
             continue
         r.append(listCell(data=dict(listItem=getattr(self._employee, k)))[Tag('athena:handler')(event='ondblclick', handler='expand')])
     return r
Exemple #54
0
 def render_vlans(self, ctx, data):
     if not data:
         return ctx.tag["No VLAN information available for this host."]
     vlans = {}
     for row in data:
         if (row[0], row[1]) not in vlans:
             vlans[row[0], row[1]] = []
         vlans[row[0], row[1]].append(row[2])
     r = []
     i = 0
     vlans = list(vlans.iteritems())
     vlans.sort()
     for (vid, name), ports in vlans:
         r.append(T.tr(_class=(i%2) and "odd" or "even")[
                 T.td[T.span(data=vid, render=T.directive("vlan"))],
                 T.td[name],
                 T.td(render=T.directive("ports"),
                      data=ports)])
         i += 1
     return T.table(_class="vlan")[
         T.thead[T.td["VID"], T.td["Name"], T.td["Ports"]], r]
Exemple #55
0
 def render_vlans(self, ctx, data):
     if not data:
         return ctx.tag["No VLAN information available for this host."]
     vlans = {}
     for row in data:
         if (row[0], row[1]) not in vlans:
             vlans[row[0], row[1]] = []
         vlans[row[0], row[1]].append(row[2])
     r = []
     i = 0
     vlans = list(vlans.iteritems())
     vlans.sort()
     for (vid, name), ports in vlans:
         r.append(
             T.tr(_class=(i % 2) and "odd" or "even")
             [T.td[T.span(data=vid, render=T.directive("vlan"))],
              T.td[name],
              T.td(render=T.directive("ports"), data=ports)])
         i += 1
     return T.table(_class="vlan")[T.thead[T.td["VID"], T.td["Name"],
                                           T.td["Ports"]], r]
Exemple #56
0
    def render_addexitform(self, ctx, data):
        if self.bse != 'Room':
            return ''

        tzid = self.tzid # to know which room to add the exit to
        action = '/exits/add/'
        lines = [T.h2['Add Exit to Room']]
        exitclasses = exits.classes()
        exitclasses.sort()
        choices = [(cls, cls) for cls in exitclasses]
        xinfo = dict(name='xclass',
                            choices=choices,
                            selected='Exit')
        bxinfo = dict(name='bxclass',
                            choices=choices,
                            selected='Exit')
        row = T.tr[T.td['Exit type...', T.br,
                            self.render_form_select(xinfo), T.br,
                            'named...', T.br,
                            T.input(name='xname')],
                    T.td['to...', T.br, '-->'],
                    T.td(align="center")[self.rooms_widget('dest', None),
                            T.br, 'or', T.br,
                            self.new_room_widget('newroom'), T.br,
                            'named...', T.br,
                            T.input(name='newroomname'), T.br,
                            T.input(type='submit', value=' Add ')],
                    T.td[T.br, '<--'],
                    T.td['return by...', T.br,
                            'Exit type...', T.br,
                            self.render_form_select(bxinfo), T.br,
                            'named...', T.br,
                            T.input(name='bxname')]]
        tbl = T.table(_class="center")[row]
        lines.append(tbl)
        lines.append(T.input(_type="hidden", name="roomid", value=tzid))
        form = T.form(action=action, method='POST')[lines]

        return T.div(_class='addexit')[form]
Exemple #57
0
    def render_table(self, ctx, data):
        if not ctx.arg('dir'):
            return []
        
        d = URIRef(ctx.arg('dir')) # "http://photo.bigasterisk.com/digicam/dl-2008-09-25")
        rows = []
        for i, (pic, filename) in enumerate(sorted(
            picsInDirectory(self.graph, d))[:]):
            img = T.img(src=[localSite(pic), '?size=thumb'],
                        onclick='javascript:photo.showLarge("%s")' %
                        (localSite(pic) + "?size=large"))

            picCols = [''] * self.brickColumns
            for fill in range(i, self.brickColumns):
                picCols[fill] = T.td
            picCols[i % self.brickColumns] = T.td(rowspan=self.brickColumns)[img]
            
            rows.append(T.tr(subj=pic)[
                T.td[T.a(href=localSite(pic))[filename]],
                picCols,
                ])

        return rows
Exemple #58
0
    def render_rooms(self, ctx, data):
        lines = []
        data.sort(key=attrgetter('tzid'))
        for room in data:
            empty = T.td(_class='empty')['']
            tzid = T.td(_class="tzid")[room.tzid, ':']
            editlink = T.td(_class="text")[T.a(href="/edit/%s" % room.tzid)[room.name]]
            name = T.td(_class="text")[room.name]
            shortline = T.td(_class="text")[room.short]
            longline = T.td(_class="text")[room.long]
            xs = room.exits()
            if not xs:
                rowcls = 'warn'
            else:
                rowcls = 'normal'
            lines.append(T.tr(_class=rowcls)[tzid, editlink])
            if room.short:
                lines.append(T.tr(_class=rowcls)[empty, shortline])
            if room.long:
                lines.append(T.tr(_class=rowcls)[empty, longline])
            if xs:
                for x in xs:
                    dest = x.destination
                    desttzid = getattr(dest, 'tzid', 'None')
                    destname = getattr(dest, 'name', None)
                    xlink = T.a(href="/edit/%s" % x.tzid)[x.name]

                    if dest is not None:
                        roomlink = T.a(href="/edit/%s" % desttzid)[destname]
                    else:
                        roomlink = 'Broken'
                    xd = T.td(_class="text2")[xlink, ' --> ', roomlink, ' (%s)' % desttzid]
                    lines.append(T.tr(_class=rowcls)[empty, xd])

            lines.append(T.tr(_class='normal')[empty, empty])

        return T.table[lines]
Exemple #59
0
 def render_my_nodeid(self, ctx, data):
     tubid_s = "TubID: "+self.client.get_long_tubid()
     return T.td(title=tubid_s)[self.client.get_long_nodeid()]
Exemple #60
0
    def calendar(self, ctx, data):
        now = datetime.datetime.now()
        self.current_date = now
        month_delta = datetime.timedelta(31)
        options = itaglibrary.ICalendarOptions(ctx, {})
        strftime = options.get('strftime', '%b %d, %Y @ %I:%M %p')
        width = options.get('width', 2)
        prev = options.get('prev', None)
        next = options.get('next', None)
        base = options.get('base_url', None)
        calendar_class = options.get('calendar_class', 'calendar')
        if data is None:
            d = now
            current = d.year, d.month
        elif isinstance(data, tuple):
            year, month = data
            d = datetime.date(year, month, 4)
            current = data
        elif isinstance(data, (datetime.date, datetime.datetime)):
            d = data
            current = d.year, d.month

        if prev is None or next is None:
            p = d - month_delta
            n = d + month_delta
            prev = p.year, p.month
            next = n.year, n.month
            if base is None:
                u = url.URL.fromContext(ctx)
                segments = u.pathList()
                if segments[-1] == '':
                    u = u.up()
                    segments = segments[:-1]
                if segments[-1].isdigit() and segments[-2].isdigit():
                    u = u.up().up()
                prev_url = u
                next_url = u
            else:
                prev_url = base
                next_url = base

            add_query_params = False
            def buildUrl(u, el):
                if add_query_params:
                    param_name, param_value = el
                    u = u.add(param_name, str(param_value))
                else:
                    u = u.child(str(el))
                return u

            for el in prev:
                if el == '?':
                    add_query_params = True
                    continue
                prev_url = buildUrl(prev_url, el)
            add_query_params = False
            for el in next:
                if el == '?':
                    add_query_params = True
                    continue
                next_url = buildUrl(next_url, el)
        else:
            if isinstance(prev, (url.URL, url.URLOverlay)) and \
               isinstance(next, (url.URL, url.URLOverlay)):
                next_url = next
                prev_url = prev

        return t.table(class_=calendar_class)[
            t.thead[
              t.tr[
                t.th(colspan="7")[
                   t.a(href=prev_url)[t.xml("&larr;")],
                   t.xml(" "),
                   t.xml('-'.join([str(el) for el in current])),
                   t.xml(" "),
                   t.a(href=next_url)[t.xml("&rarr;")]
                ]
              ],
              [
                t.tr[[t.td[dayname] for dayname in calendar.weekheader(width).split()]]
              ]
            ],
            t.tbody[
              t.invisible(data=self.days(*current), render=rend.sequence)[
                 t.tr(pattern='item', render=rend.sequence)[
                     t.td(pattern='item', render=self.render_calendarDay)
                 ]
              ]
            ],
            t.tfoot[
               t.tr[
                  t.td(colspan="7")[
                      now.strftime(strftime)
                  ]
               ]
            ]
        ]