Exemplo n.º 1
0
    def log_results(self, output_format, results):

        if output_format == 'json':
            self.logger.info(pprint.pformat(results))
        elif output_format == 'html':
            h = HTML()
            t = h.table(border='1')
            for key, value in results.items():
                if isinstance(value, dict):
                    r = t.tr
                    r.td(str(key))
                    for k, v in value.items():
                        r = t.tr
                        r.td()
                        r.td(str(k))
                        r.td(str(v))
                else:
                    r = t.tr
                    r.td(key)
                    r.td(str(value))
            with open('results.html','w') as f:
                f.write(str(t))
        else:
            for row, data in results.items():
                if isinstance(data, dict):
                    self.logger.info(str(row).ljust(50))
                    for k, v in data.items():
                        self.logger.info(str(k).ljust(50) + str(v))
                else:
                    self.logger.info(str(row).ljust(50) + str(data))
Exemplo n.º 2
0
 def _WriteErrorReport(self, errorTable):
     h = HTML()
     
     t = h.table()
     tr = t.tr()
     tr.th("Line ID")
     tr.th("Error Message")
     tr.th("Error Details")
     
     for lineId, errorMsg, errorDetail in errorTable:
         tr = t.tr()
         tr.td(lineId)
         tr.td(errorMsg)
         tr.td(str(errorDetail))
     
     pb = _m.PageBuilder(title= "Error Report")
     
     headerText = "<b>Source Emmebank:</b> %s" %self.SourceEmmebankPath +\
                 "<br><b>Source Scenario:</b> %s" %self.SourceScenarioId +\
                 "<br><b>Target Scenario:</b> %s" %self.TargetScenario
     
     pb.add_text_element(headerText)
     
     pb.wrap_html(body= str(t))
     
     _m.logbook_write("Error report", value= pb.render())
     
     pass
         
Exemplo n.º 3
0
    def create_binary_correlation_stat_html(self, output_dir, roidb=None):
        from html import HTML
        # Create the directory if necessary
        if not osp.exists(output_dir):
            os.makedirs(output_dir)

        present_cache_file = osp.join(self.cache_path, self.name + '_present_stats.pkl')
        assert os.path.exists(present_cache_file)

        with open(present_cache_file, 'rb') as fid:
            present_stats = cPickle.load(fid)
        print '{} present stats loaded from {}'.format(self.name, present_cache_file)

        config_html = HTML()
        config_table = config_html.table(border='1')

        for i in xrange(self.num_classes):
            r = config_table.tr
            if i == 0:
                r.th('---')
            else:
                r.th('%s'%self.classes[i])
            for j in xrange(1, self.num_classes):
                c = r.td
                if i == 0:
                    c.a('%s'%self.classes[j])
                else:
                    c.a('%d'%int(present_stats[i, j]), href='images/%02d_%02d.jpg'%(i,j))

        html_file = open(osp.join(output_dir, 'coco_offsets_table.html'), 'w')
        print >> html_file, config_table
        html_file.close()
def create_html_report(topwords, top_index, Pi):
    ht = HTML()
    div = ht.div(align="center")
    heading = div.h2(style="text-align:center")
    subhead = div.h3(style="text-align:center")
    # Creating the header
    No_of_topics = len(topwords) - 1
    No_of_clusters = top_index.shape[0]
    head = "Topics : %d \n, Cluster : %d" % (No_of_topics, No_of_clusters)
    heading(head)

    # Creating the table
    for i in range(top_index.shape[0]):
        head_sub = div.h4(style="text-align:center")
        head_sub("Top Topics in Cluster %d (%.5f)" % (i + 1, Pi[i]))
        t = div.table(align="center",
                      border="2",
                      cellpadding="12",
                      cellspacing="0",
                      width="80%")
        tb = t.tbody()
        tr = tb.tr(style="text-align:center")
        tr.th("Alpha")
        tr.th("Top Words")
        ind_alpha_index = top_index[i]
        for index in ind_alpha_index:
            tr = tb.tr(style="text-align:center")
            alpha_val = '%.5f' % index[1]
            tr.td(alpha_val)
            tr.td(topwords[int(index[0])])

    return (ht)
Exemplo n.º 5
0
def send_email(user, event, message, **kw):
  if not user in config['email']['user_emails']:
    return

  args = {
    'f': config['email']['from_address'],
    't': config['email']['user_emails'][user],
    'u': kw['subject'] if 'subject' in kw else 'Notification',
  }

  if not 'app' in kw:
    kw['app'] = config['default_app']

  body = HTML('html')
  tr = body.table().tr()
  tr.td(valign='top').img(src=config['icons'][kw['app']], style='float:left; margin: 15px')
  try:
    if 'email_body' in kw:
      tr.td().text(kw['email_body'], escape=False)
    else:
      getattr(notifications, event + '_email')(tr.td(), message, **kw)
  except:
    with tr.td().p(style='margin-top: 15px') as p:
      p.b("Message:")
      p.br()
      p.text(message)

  ip = curl('ifconfig.me').strip()
  if ip != config['ip']:
    ybdst = ssh.bake(config['ip'])
    print "Sent %s email to %s" % (event, user)
    return ybdst.sendemail(_in=str(body), **args)
  else:
    print "Sent %s email to %s" % (event, user)
    return sendemail(_in=str(body), **args)
Exemplo n.º 6
0
 def preload_auto_modes(self):
     options = []
     h = HTML()
     for id, type, description in _util.getScenarioModes(self.Scenario,  ['AUTO', 'AUX_AUTO']):
         text = "%s - %s" %(id, description)
         options.append(str(h.option(text, value= id)))
     return "\n".join(options)
 def preload_auto_modes(self):
     options = []
     h = HTML()
     for id, type, description in _util.getScenarioModes(self.Scenario,  ['AUTO', 'AUX_AUTO']):
         text = "%s - %s" %(id, description)
         options.append(str(h.option(text, value= id)))
     return "\n".join(options)
Exemplo n.º 8
0
    def create_binary_correlation_stat_html(self, output_dir, roidb=None):
        from html import HTML
        # Create the directory if necessary
        if not osp.exists(output_dir):
            os.makedirs(output_dir)

        present_cache_file = osp.join(self.cache_path,
                                      self.name + '_present_stats.pkl')
        assert os.path.exists(present_cache_file)

        with open(present_cache_file, 'rb') as fid:
            present_stats = cPickle.load(fid)
        print '{} present stats loaded from {}'.format(self.name,
                                                       present_cache_file)

        config_html = HTML()
        config_table = config_html.table(border='1')

        for i in xrange(self.num_classes):
            r = config_table.tr
            if i == 0:
                r.th('---')
            else:
                r.th('%s' % self.classes[i])
            for j in xrange(1, self.num_classes):
                c = r.td
                if i == 0:
                    c.a('%s' % self.classes[j])
                else:
                    c.a('%d' % int(present_stats[i, j]),
                        href='images/%02d_%02d.jpg' % (i, j))

        html_file = open(osp.join(output_dir, 'coco_offsets_table.html'), 'w')
        print >> html_file, config_table
        html_file.close()
Exemplo n.º 9
0
 def getHTMLTeamTable(self, div_age, div_gen, team_id):
     # https://pypi.python.org/pypi/html/
     return_dict = self.get_schedule('team_id', team_id,
         div_age=div_age, div_gen=div_gen)
     game_list = return_dict['game_list']
     html = HTML()
     table = html.table(width='100%', border='1px solid black')
     table.caption(self.userid_name+" "+self.schedcol_name+" "+div_age+div_gen+str(team_id))
     header_row = table.tr
     header_row.th('Game Date', padding='5px')
     header_row.th('Start Time', padding='5px')
     header_row.th('Field', padding='5px')
     header_row.th('Home', padding='5px')
     header_row.th('Away', padding='5px')
     for game in game_list:
         game_row = table.tr
         game_row.td(game['game_date'])
         game_row.td(game['start_time'])
         findex = self.fieldinfo_indexerGet(game['venue'])
         if findex is not None:
             field_name = self.fieldinfo_list[findex]['field_name']
             game_row.td(field_name)
         game_row.td(str(game['home']))
         game_row.td(str(game['away']))
     return str(html)
Exemplo n.º 10
0
def html_line(text, plus=0):
    h = HTML()
    p = ""
    if (plus):
        p = plus
    h.p(str(text) + p)
    f.write(str(h))
Exemplo n.º 11
0
def genHtmlHeader(project='', location='', csspath="css/data.css", js='js/data.js'):
    # created index object from HTML() class which should create open & close tags
    html = HTML('html')
    head = html.head()
    title = head.title('Data Status')
    meta = head.meta(charset="utf-8")  
    css = head.link(rel="stylesheet", type="text/css", href=csspath)
    if js:
        js = head.script(type="text/javascript", src=js)
        js.text("")
    # end of if js:

    # created body tag
    body = html.body()
    b = body.div(name='body', klass='bodyCls')
    #load = body.p(id="loading", style = 'display:inline')
    #load.text("Loading . . .")
    b.br
    heading = b.div(name='heading', klass='headingCls')
    ifen = ' - ' if location else ''
    if project:
        heading.h1(project + ' Project Data Report Sheet' + ifen + location)
    else:
        heading.h1(' Project Index Data Report Sheet' + ifen + location)

    form = b.form()
    tdiv = form.div(id="contentdiv")
    return (html, b, tdiv, form)
Exemplo n.º 12
0
    def buildTrivialStatsTable(self,
                               deltaSeriesCollection,
                               klass=TRIVIAL_STATS_TABLE,
                               style=''):
        """
    Builds a html table with statistics for a collection of transactions

    :param deltaSeriesCollection: A series of elapsed time or pmc values for a pair of probes
    :param klass: Css selector for this table (Default value = TRIVIAL_STATS_TABLE)
    :param style: Css inline style attributes for this table (Default value = '')

    """
        tableWrapper = HTML().div()
        klass = '{} {}'.format(TABLE_SUMMARY, klass)
        table = tableWrapper.table(border='1', klass=klass, style=style)
        self.buildStatsTableHeader(table)
        tbody = table.tbody

        for i, deltaSeries in enumerate(deltaSeriesCollection, 1):
            row = tbody.tr
            row.td('{0:,}'.format(i), klass=TD_KEY)
            row.td(deltaSeries.beginProbeName, klass=TD_KEY)
            row.td(deltaSeries.endProbeName, klass=TD_KEY)
            row.td(DURATION_FORMAT.format(deltaSeries.getMin()))
            row.td(DURATION_FORMAT.format(deltaSeries.getMax()))
            row.td(DURATION_FORMAT.format(deltaSeries.getMedian()))
            row.td(DURATION_FORMAT.format(deltaSeries.getMean()))
            row.td(
                DURATION_FORMAT.format(
                    deltaSeries.getPercentile(self.percentile1)))
            row.td(
                DURATION_FORMAT.format(
                    deltaSeries.getPercentile(self.percentile2)))
            row.td(DURATION_FORMAT.format(deltaSeries.getStandardDeviation()))
        return tableWrapper
Exemplo n.º 13
0
 def getHTMLTeamTable(self, div_age, div_gen, team_id):
     # https://pypi.python.org/pypi/html/
     return_dict = self.get_schedule('team_id',
                                     team_id,
                                     div_age=div_age,
                                     div_gen=div_gen)
     game_list = return_dict['game_list']
     html = HTML()
     table = html.table(width='100%', border='1px solid black')
     table.caption(self.userid_name + " " + self.schedcol_name + " " +
                   div_age + div_gen + str(team_id))
     header_row = table.tr
     header_row.th('Game Date', padding='5px')
     header_row.th('Start Time', padding='5px')
     header_row.th('Field', padding='5px')
     header_row.th('Home', padding='5px')
     header_row.th('Away', padding='5px')
     for game in game_list:
         game_row = table.tr
         game_row.td(game['game_date'])
         game_row.td(game['start_time'])
         findex = self.fieldinfo_indexerGet(game['venue'])
         if findex is not None:
             field_name = self.fieldinfo_list[findex]['field_name']
             game_row.td(field_name)
         game_row.td(str(game['home']))
         game_row.td(str(game['away']))
     return str(html)
def create_html_report(topwords,top_index,Pi):
    ht = HTML()
    div = ht.div(align="center")
    heading = div.h2(style="text-align:center")
    subhead = div.h3(style="text-align:center")
    # Creating the header 
    No_of_topics = len(topwords) - 1
    No_of_clusters = top_index.shape[0]
    head = "Topics : %d \n, Cluster : %d" %(No_of_topics,No_of_clusters)
    heading(head)
    
    # Creating the table
    for i in range(top_index.shape[0]):
        head_sub = div.h4(style="text-align:center")
        head_sub("Top Topics in Cluster %d (%.5f)" %(i+1,Pi[i]))
        t = div.table(align="center",border="2",cellpadding="12",cellspacing="0",width="80%")
        tb = t.tbody()
        tr = tb.tr(style="text-align:center")
        tr.th("Alpha")
        tr.th("Top Words")
        ind_alpha_index = top_index[i]
        for index in ind_alpha_index:
            tr = tb.tr(style="text-align:center")
            alpha_val = '%.5f' %index[1]
            tr.td(alpha_val)
            tr.td(topwords[int(index[0])])

    return(ht)
Exemplo n.º 15
0
    def buildFlotTitle(category, title, timelineStats, uid):
        """
    Builds markup to render title for txn visualizations

    :param category: Category of transactions visualized by this flot
    :param title: Text title for this visualization
    :param timelineStats: Timeline stats with delta series to be plotted
    :param uid: Unique identifier to generate css selector id

    """
        constituentNames = [
            '{} -> {}'.format(deltaSeries.beginProbeName,
                              deltaSeries.endProbeName)
            for deltaSeries in timelineStats.getTscDeltaSeriesCollection()
        ]

        title = '{} {} charts {}'.format(
            category, title, ' for constituent - ' if constituentNames else '')
        element = HTML().div(klass=TIME_POINT_STATS_TITLE)
        element.h3(title, style='display: inline')

        if constituentNames:
            elementId = '{}ConstituentSelector'.format(uid)
            constituentSelector = element.select(id=elementId, klass=SELECTOR)
            for i, constituentName in enumerate(constituentNames):
                if i == len(constituentNames) - 1:
                    constituentSelector.option(constituentName,
                                               selected='selected')
                else:
                    constituentSelector.option(constituentName)
        return element
Exemplo n.º 16
0
    def _sprite_proof(self, sprite_width, sprite_height, sprite_layout):
        """ Create a sprite proof showing how the image was cut. Should look like
        original. """
        h = HTML('html')
        head = h.head()
        title = h.title('Sprite Proof')
        stylesheet = head.link(href="%s.css" % self.scale, rel="stylesheet",
                type="text/css")
        style = head.style(type="text/css")
        style.raw_text("""
        .pc {
            position: absolute;
            text-indent: -999em;
        }
        .pc:hover {
            text-indent: 0;
        }
        """)
        body = h.body()
        for (k, v) in self.pieces.items():
            x = v[0]
            y = v[1]
            el = body.div(klass='pc pc-%s-%s' % (self.scale, k),
                    style="left:%spx;top:%spx;" % (x, y))
            el.text(str(k))

        f = open(os.path.join(self._mydir, 'sprite_proof.html'), 'w')
        f.write(str(h))
        f.close()
Exemplo n.º 17
0
    def page(self):
        pb = _tmgTPB.TmgToolPageBuilder(
            self,
            title="TMG Toolbox Index",
            description="Lists all tools and libraries within the TMG Toolbox, \
                         alphabetically by tool name, with links to each tool.",
            branding_text="- TMG Toolbox",
            runnable=False)

        tmg = [tb for tb in _MODELLER.toolboxes if tb.namespace() == 'tmg'][0]
        toolNames = self.get_tool_names(tmg)
        topCategories = self.get_top_categories(tmg)

        alphabetizedToolNames = {}
        for name, namespacce in toolNames:
            firstChar = name[0].upper()
            if firstChar in alphabetizedToolNames:
                alphabetizedToolNames[firstChar].append((name, namespacce))
            else:
                alphabetizedToolNames[firstChar] = [(name, namespacce)]
        orderedKeys = [key for key in alphabetizedToolNames.iterkeys()]
        orderedKeys.sort()

        for firstChar in orderedKeys:
            #pb.add_header(firstChar)

            toolNames = alphabetizedToolNames[firstChar]
            h = HTML()
            t = h.table(style='border-style:none;', width='100%')
            tr = t.tr()
            tr.th(firstChar, colspan='3', align='left')

            for name, namespace in toolNames:

                #Get description from the code
                tool = _MODELLER.tool(namespace)
                if hasattr(tool, 'short_description'):
                    description = tool.short_description()
                else:
                    description = "<em>--No description--</em>"

                #Determine the top-level category
                topNamespace = namespace.split('.')[1]
                if topNamespace in topCategories:
                    category = topCategories[topNamespace]
                else:
                    continue  #Skip top-level tool

                #Add data to table
                tr = t.tr()
                tr.td("<em>%s</em>" % category, escape=False, width='20%')
                link = '<a data-ref="%s" class="-inro-modeller-namespace-link" style="text-decoration: none;">' % namespace
                link += name + "</a>"
                tr.td(link, escape=False, width='40%')
                tr.td(description, escape=False, align='left')

            pb.wrap_html(body=str(t))

        return pb.render()
Exemplo n.º 18
0
    def buy_used(self, buy_info, used_info):
        alarm_num = 0
        used_info = Counter(all_type_list)
        buy_info = Counter(all_type_pur)
        # print used_info, buy_info, type(used_info)
        all_info = Counter(used_info + buy_info)
        # print all_info
        # print list(all_info)
        from html import HTML
        inline_css = {
            'class1':
            'color:#00FF00;width:500;valign:middle;vertical-line:top;',  #green
            'class2':
            'color:#FF0000;width:500;valign:middle;vertical-line:top;',  #red
            'class3':
            'color:#FFFF00;width:500;valign:middle;vertical-line:top;',  #yellow
            'class4':
            'color:#000000;width:500;valign:middle;vertical-line:top;',  #black
        }

        b = HTML()
        t = b.table(border='1px solid black')
        r = t.tr()
        t2 = t.tr()
        t3 = t.tr()
        r.td('Type', style=inline_css['class4'])
        t2.td('Purd', style=inline_css['class4'])
        t3.td('Used', style=inline_css['class4'])
        for m_title in list(all_info):
            r.td(str(m_title), style=inline_css['class4'])
            if m_title in dict(buy_info).keys():
                # print dict(buy_info)[m_title]
                t2.td(str(dict(buy_info)[m_title]), style=inline_css['class1'])
            else:
                # print 'no key'
                t2.td('Null', style=inline_css['class2'])
            if m_title in dict(used_info).keys():
                # print dict(used_info)[m_title]
                t3.td(str(dict(used_info)[m_title]),
                      style=inline_css['class1'])
            else:
                # print 'nn key'
                t3.td('Null', style=inline_css['class2'])
            if m_title in dict(buy_info).keys() and m_title in dict(
                    used_info).keys():
                if dict(buy_info)[m_title] < dict(used_info)[m_title]:
                    # print 'haha %s' % m_title
                    alarm_num = alarm_num + 1
            elif m_title not in dict(buy_info).keys() and m_title in dict(
                    used_info).keys():
                # print 'used but not buy: %s' % m_title
                alarm_num = alarm_num + 1
            # elif m_title in dict(buy_info).keys() and m_title not in dict(used_info).keys():
            #     print 'buy but not used: %s' % m_title

        alarm_info_ec2 = {'status': str(alarm_num), 'report': str(b)}
        # print alarm_info_ec2
        return alarm_info_ec2
Exemplo n.º 19
0
 def buildDiffTitle(lhs, rhs):
     """
 Builds a title for the transaction diff table
 """
     from xpedite.report.markup import TIME_POINT_STATS_TITLE
     title = 'Transaction diff\ntxn #{} vs txn #{}'.format(lhs, rhs)
     element = HTML().div(klass=TIME_POINT_STATS_TITLE)
     element.h3(title)
     return element
 def html_representation(self):
     return [
         str(self.rating()),
         str(self.price),
         str('%.2f' % round(self.km_distance_from_work(), 2)),
         HTML.link('Source', self.html_link()),
         HTML.link('Google Maps', self.maps_link()), self.address,
         str(self.time_ago())
     ]
Exemplo n.º 21
0
    def __init__(self,
                 name,
                 local_jquery=None,
                 local_requirejs=None,
                 local_d3_js=None,
                 local_c3_js=None,
                 local_c3_css=None):

        super(Chart, self).__init__()

        self.chart_html = HTML()

        self.name = name
        self.c3_css_path = local_c3_css or 'https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css'
        self.jquery_path = local_jquery or 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js'
        self.requirejs_path = local_requirejs or \
            'https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.17/require.min.js'
        self.d3_js_path = local_d3_js or 'http://d3js.org/d3.v3.min'
        self.c3_js_path = local_c3_js or 'https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min'

        self.chart_html.div('', id=self.name)
        self.chart_html.link('',
                             href=self.c3_css_path,
                             rel='stylesheet',
                             type='text/css')
        self.chart_html.script('', src=self.jquery_path)
        self.chart_html.script('', src=self.requirejs_path)

        self.requirejs_config = {
            'paths': {
                'c3': self.c3_js_path,
                'd3': self.d3_js_path,
            }
        }

        self.axes = Axes()
        self.data = Data(self.axes)
        self.grid = Grid(self.axes)
        self.legend = Legend()
        self.tooltip = Tooltip()
        self.regions = Regions(self.axes)
        self.point = Point()
        self.size = Size()
        self.padding = Padding()

        self.chart_dict = {
            'bindto': "'#" + self.name + "'",
            'data': self.data.config,
            'axis': self.axes.config,
            'grid': self.grid.config,
            'legend': self.legend.config,
            'tooltip': self.tooltip.config,
            'regions': self.regions.config,
            'point': self.point.config,
            'size': self.size.config,
            'padding': self.padding.config,
        }
    def _AddReportSection(self, pb, type, modes, fountains, sinks, orphans):
        modes = [str(mode) for mode in modes]

        h = HTML()

        plural = ''
        if len(modes) > 1: plural = "s"
        sectionTitle = "{0} results for mode{1} {2!s}".format(
            type, plural, modes)

        #h.h3(sectionTitle)

        nFountains = len(fountains)
        nSinks = len(sinks)
        nOrphans = len(orphans)

        if nFountains > 0:

            plural = ''
            if nFountains > 1: plural = 's'
            title = "Found %s fountain node%s:" % (nFountains, plural)

            t = h.table()
            tr = t.tr()
            tr.th(title)

            for node in fountains:
                t.tr().td(str(node))

        if nSinks > 0:

            plural = ''
            if nSinks > 1: plural = 's'
            title = "Found %s sink node%s:" % (nSinks, plural)

            t = h.table()
            tr = t.tr()
            tr.th(title)

            for node in sinks:
                t.tr().td(str(node))

        if nOrphans > 0:

            plural = ''
            if nOrphans > 1: plural = 's'
            title = "Found %s orphan node%s:" % (nOrphans, plural)

            t = h.table()
            tr = t.tr()
            tr.th(title)

            for node in orphans:
                t.tr().td(str(node))

        pb.wrap_html(sectionTitle, body=str(h))
Exemplo n.º 23
0
def build_html():
    matrices = []
    check_make_dir('matrices_html')

    for root, dirs, files in os.walk('matrices'):
      h = HTML()
      matrix = os.path.basename(root)
      if not dirs:
        print root, dirs, files
        h.p('Matrix: ' + matrix)
        sparsity_plot = None
        for f in files:
          if not f.endswith('.png'):
            with open(os.path.join(root, f)) as fin:
              h.p(fin.read(), style='white-space: pre-wrap;')
          else:
            p = h.p()
            p.img(src=matrix + '.png')
            sparsity_plot = os.path.join(root, f)

        path = 'matrices_html/' + matrix + '.html'
        with open(path, 'w') as fout:
          matrices.append(matrix + '.html')
          fout.write(str(h))
          shutil.copyfile(sparsity_plot, 'matrices_html/' + matrix + '.png')

    with open('matrices_html/index.html', 'w') as fout:
      h = HTML()
      h.p('matrices: ')
      l = h.ol

      for m in matrices:
        l.li.a(m, href=m)

      fout.write(str(h))
Exemplo n.º 24
0
    def page(self):
        pb = _tmgTPB.TmgToolPageBuilder(self, title="TMG Toolbox Index" ,
                     description="Lists all tools and libraries within the TMG Toolbox, \
                         alphabetically by tool name, with links to each tool.",
                     branding_text="- TMG Toolbox", runnable= False)
        
        tmg = [tb for tb in _MODELLER.toolboxes if tb.namespace() == 'tmg'][0]
        toolNames = self.get_tool_names(tmg)
        topCategories = self.get_top_categories(tmg)
        
        alphabetizedToolNames = {}
        for name, namespacce in toolNames:
            firstChar = name[0].upper()
            if firstChar in alphabetizedToolNames:
                alphabetizedToolNames[firstChar].append((name, namespacce))
            else:
                alphabetizedToolNames[firstChar] = [(name, namespacce)]
        orderedKeys = [key for key in alphabetizedToolNames.iterkeys()]
        orderedKeys.sort()
        
        for firstChar in orderedKeys:
            #pb.add_header(firstChar)
            
            toolNames = alphabetizedToolNames[firstChar]
            h = HTML()
            t = h.table(style= 'border-style:none;', width= '100%')
            tr = t.tr()
            tr.th(firstChar, colspan= '3', align= 'left')
            
            for name, namespace in toolNames:
                
                #Get description from the code
                tool = _MODELLER.tool(namespace)
                if hasattr(tool, 'short_description'):
                    description = tool.short_description()
                else:
                    description = "<em>--No description--</em>"
                
                #Determine the top-level category
                topNamespace = namespace.split('.')[1]
                if topNamespace in topCategories:
                    category = topCategories[topNamespace]
                else: continue #Skip top-level tool
                
                #Add data to table
                tr = t.tr()
                tr.td("<em>%s</em>" %category, escape= False, width= '20%')
                link = '<a data-ref="%s" class="-inro-modeller-namespace-link" style="text-decoration: none;">' %namespace
                link += name + "</a>"
                tr.td(link, escape= False, width= '40%')
                tr.td(description, escape= False, align= 'left')

            pb.wrap_html(body= str(t))
        
        return pb.render()
Exemplo n.º 25
0
def savePredictedTags(scores, groundTruth, dataloader, topN=20):
    # local aliases
    gtLabels, imgIds = groundTruth['gtLabels'], groundTruth['imageId']

    # Create a page with 3 columns
    page = HTML(3)
    page.setTitle(['Image', 'Ground Truth', 'Predicted Tags'])
    imgPath = 'val2014/COCO_val2014_%012d.jpg'
    numImgs = 100

    for ii in xrange(numImgs):
        rowContent = [page.linkImage(imgPath % imgIds[ii])]
        #data = dataloader.getIndexInstance(ii, 'test');
        # set
        #setData = data[:dataloader.evalSize];
        #setWords = [dataloader.ind2word[str(setData[jj])] \
        #                for jj in xrange(setData.size(0))];
        #rowContent.append('\n'.join(setWords));

        # gt words, scores, ranks
        #gtData = data[dataloader.evalSize:];
        gtWords = [dataloader.ind2word[jj] for jj in gtLabels[ii]]
        rowContent.append('\n'.join(gtWords))

        # Get the predicted tags
        imgScore = scores[ii, :]
        predTags = imgScore.argsort()[-topN:][::-1]
        tags = [dataloader.ind2word[jj] for jj in predTags]
        rowContent.append('\n'.join(tags))

        page.addRow(rowContent)

    # render page and save
    page.savePage('img_tags_espgame.html')
 def _AddReportSection(self, pb, type, modes, fountains, sinks, orphans):
     modes = [str(mode) for mode in modes]
     
     h = HTML()
     
     plural = ''
     if len(modes) > 1: plural = "s"
     sectionTitle = "{0} results for mode{1} {2!s}".format(type, plural, modes)
     
     #h.h3(sectionTitle)
     
     nFountains = len(fountains)
     nSinks = len(sinks)
     nOrphans = len(orphans)
     
     if nFountains > 0:
         
         plural = ''
         if nFountains > 1: plural = 's'
         title= "Found %s fountain node%s:" %(nFountains, plural)
         
         t = h.table()
         tr = t.tr()
         tr.th(title)
         
         for node in fountains:
             t.tr().td(str(node))
         
     if nSinks > 0:
         
         plural = ''
         if nSinks > 1: plural = 's'
         title= "Found %s sink node%s:" %(nSinks, plural)
         
         t = h.table()
         tr = t.tr()
         tr.th(title)
         
         for node in sinks:
             t.tr().td(str(node))
             
     if nOrphans > 0:
         
         plural = ''
         if nOrphans > 1: plural = 's'
         title= "Found %s orphan node%s:" %(nOrphans, plural)
         
         t = h.table()
         tr = t.tr()
         tr.th(title)
         
         for node in orphans:
             t.tr().td(str(node))
     
     pb.wrap_html(sectionTitle, body= str(h))
Exemplo n.º 27
0
def dashboard():
    page = HTML()
    t = page.table()
    r = t.tr
    r.th("Count")
    r.th("Page name")
    for name in pageviews:
        r = t.tr
        r.td(str(pageviews[name]))
        r.td(name)
    return str(page)
Exemplo n.º 28
0
def dashboard():
    page = HTML()
    t = page.table()
    r = t.tr
    r.th("Count")
    r.th("Page name")
    for name in pageviews:
        r = t.tr
        r.td(str(pageviews[name]))
        r.td(name)
    return str(page)
Exemplo n.º 29
0
    def get(self):
        q = HTML()

        if self.request.GET:
            search = self.request.GET['search']

            wolframModel = WolframModel()
            answer = wolframModel.search(search)
            q.answer = answer
            q.search = search

        self.response.write(q.print_out())
Exemplo n.º 30
0
def alert_html(checklist,checkup):	
	h = HTML()	
	try:
		for key in checklist.keys():
			# If the key exceeds a threshhold, look for drivers.
		# 	print '''checkup[key]['Abs_Avg_Day_Diff']''',checkup[key]['Abs_Avg_Day_Diff']
		# 	print '''checklist[key]['l'])''', checklist[key]['l']
			if float(checkup[key]['Abs_Avg_Day_Diff'])>float(checklist[key]['l']): 
		# 		
		# 		#generate alert text
				txt=key+'value of '+str(checkup[key]['Abs_Avg_Day_Diff'])+' is over alert threshold of '+str(checklist[key]['l'])
				print txt
				h.p(txt)
		# 		
		# 		#run driver analytics
				lev=0
		# 		# for this dependent variable, get the list of driver variables.
				driverlist=checklist[key]['d']
		# 		
		# 		print 'driverlist', driverlist		
		# 		print '''driverlist[key]['l']''', checklist[key]['l']
			
				for driver in driverlist.keys():
					lev=driverlist[driver]['l']
		# 			# if no driver-level threshold was provided...
					if lev==0:
						lev=checklist[key]['l']
					subdrivlist=checkup[driver]
					for subdriv in subdrivlist.keys():
		# 				print 'subdrivlist', subdrivlist[subdriv]
		# 	# 				# default to the same threshold for the primary variable
		# 				print '''checkup[key]['Day_Avg_Diff']''', checkup[key]['Day_Avg_Diff']
		# 				print '''sign(subdrivlist[subdriv]['Day_Avg_Diff'])''', subdrivlist[subdriv]['Day_Avg_Diff']
				
				
						if sign(checkup[key]['Day_Avg_Diff'])==sign(subdrivlist[subdriv]['Day_Avg_Diff']):
							# and it's over the threshold...
							driverlev=subdrivlist[subdriv]['Day_Avg_Diff']
		# 					print 'triverlev', driverlev, 'lev', lev
		# 					print '''abs(driverlev)''',abs(driverlev), '''abs(lev)''',abs(lev)
							if abs(driverlev)>abs(lev):
								# generate driver text note
								txt=' Driver variable '+driver+':'+subdriv+' is at '+ str(subdrivlist[subdriv]['Day_Avg_Diff'])
								print txt
						h.p(txt)
		return h
	except:
		e = sys.exc_info()[0]
		el=sys.exc_traceback.tb_lineno
		print 'Error: %s' % e 
		print 'lineno: %s' % el	
    def buy_used(self, buy_info, used_info):
        alarm_num = 0
        used_info = Counter(all_type_list)
        buy_info = Counter(all_type_pur)
        # print used_info, buy_info, type(used_info)
        all_info = Counter(used_info + buy_info)
        # print all_info
        # print list(all_info)
        from html import HTML
        inline_css = {
            'class1': 'color:#00FF00;width:500;valign:middle;vertical-line:top;', #green
            'class2': 'color:#FF0000;width:500;valign:middle;vertical-line:top;', #red
            'class3': 'color:#FFFF00;width:500;valign:middle;vertical-line:top;', #yellow
            'class4': 'color:#000000;width:500;valign:middle;vertical-line:top;', #black
        }

        b = HTML()
        t = b.table(border='1px solid black')
        r = t.tr()
        t2 = t.tr()
        t3 = t.tr()
        r.td('Type', style=inline_css['class4'])
        t2.td('Purd', style=inline_css['class4'])
        t3.td('Used', style=inline_css['class4'])
        for m_title in list(all_info):
            r.td(str(m_title), style=inline_css['class4'])
            if m_title in dict(buy_info).keys():
                # print dict(buy_info)[m_title]
                t2.td(str(dict(buy_info)[m_title]), style=inline_css['class1'])
            else:
                # print 'no key'
                t2.td('Null', style=inline_css['class2'])
            if m_title in dict(used_info).keys():
                # print dict(used_info)[m_title]
                t3.td(str(dict(used_info)[m_title]), style=inline_css['class1'])
            else:
                # print 'nn key'
                t3.td('Null', style=inline_css['class2'])
            if m_title in dict(buy_info).keys() and m_title in dict(used_info).keys():
                if dict(buy_info)[m_title] < dict(used_info)[m_title]:
                    # print 'haha %s' % m_title
                    alarm_num = alarm_num + 1
            elif m_title not in dict(buy_info).keys() and m_title in dict(used_info).keys():
                # print 'used but not buy: %s' % m_title
                alarm_num = alarm_num + 1
            # elif m_title in dict(buy_info).keys() and m_title not in dict(used_info).keys():
            #     print 'buy but not used: %s' % m_title

        alarm_info_ec2 = {'status':str(alarm_num), 'report':str(b)}
        # print alarm_info_ec2
        return alarm_info_ec2
Exemplo n.º 32
0
def make_html(data, table_header):
    h = HTML('html')
    h.h4(u"视频云相关业务过去5天的报警统计:")
    t = h.table(border='1')
    r = t.tr
    r.th('Item')
    for i in table_header:
        r.th(i)

    for items in data:
        r = t.tr
        for item in items:
            r.td(str(item))
    return str(h)
Exemplo n.º 33
0
def saveResultPagePool(loadPath):
    # image, task, converation, GT, pred
    page = HTML(4);
    page.setTitle(['Pool', 'GT', 'Conversation', 'Pred']);

    savePath = loadPath.replace('json', 'html').replace('chatlog', 'chatpage');

    with open(loadPath, 'r') as fileId: talk = json.load(fileId);

    maps = {};
    cleaner = lambda x: maps[x] if x in maps else x;

    for datum in talk:
        datum['pool'] = [[cleaner(jj) for jj in ii] \
                                        for ii in datum['pool']];
        datum['gt'] = [cleaner(ii) for ii in datum['gt']];
        datum['pred'] = [cleaner(ii) for ii in datum['pred']];
        datum['chat'] = [cleaner(ii) for ii in datum['chat']];

        row = ['\n'.join([', '.join(ii) for ii in datum['pool']])];
        row.append(', '.join(datum['gt']));

        # add chat
        chat = 'Q1 : %3s \tA1: %s ' % (datum['chat'][0], datum['chat'][1]);
        if len(datum['chat']) > 3:
            chat += '\tQ2 : %3s \t A2: %s' % (datum['chat'][2], datum['chat'][3]);
        row.append(chat)

        # add GT and pred
        row.append(', '.join(datum['pred']));
        page.addRow(row);

    # render and save page
    page.savePage(savePath);
Exemplo n.º 34
0
def main(args):

    win_width = 300
    win_height = 300
    webpage = HTML('web/', args.title)
    webpage.add_header(args.title)

    for i, dir in tqdm(enumerate(os.listdir('web/'+ args.img_dir))):
        imgs = []
        txts = []
        for image_path in os.listdir('web/{}/{}'.format(args.img_dir, dir)):

            img = os.path.join('{}/{}'.format(args.img_dir,dir),image_path)
            
            imgs.append(img)

        imgs.sort()

        for img_path in imgs:
            if img_path.split('/')[-1] == '0.jpg':
                txts.append('Original Image')
            elif img_path.split('/')[-1] == '1.jpg':
                txts.append('Background')
            else:
                txts.append('Completed Object')

        webpage.add_images(imgs, txts, imgs, i+1, width=win_width, height=win_height)
        webpage.save()
Exemplo n.º 35
0
def saveResultPage(loadPath):
    # image, task, converation, GT, pred
    page = HTML(5);
    page.setTitle(['Image', 'Task', 'Conversation', 'GT', 'Pred']);

    savePath = loadPath.replace('json', 'html').replace('chatlog', 'chatpage');

    with open(loadPath, 'r') as fileId: talk = json.load(fileId);

    maps = {'rectangle':'triangle', 'rhombus':'star', 'cyan':'purple'};
            #'A':'  I', 'B':' II', 'C':'III'};
    cleaner = lambda x: maps[x] if x in maps else x;

    for datum in talk:
        datum['image'] = [cleaner(ii) for ii in datum['image']];
        datum['gt'] = [cleaner(ii) for ii in datum['gt']];
        datum['pred'] = [cleaner(ii) for ii in datum['pred']];
        datum['chat'] = [cleaner(ii) for ii in datum['chat']];

        row = [', '.join(datum['image']), ', '.join(datum['task'])];

        # add chat
        chat = 'Q1 : %3s \tA1: %s ' % (datum['chat'][0], datum['chat'][1]);
        if len(datum['chat']) > 3:
            chat += '\tQ2 : %3s \t A2: %s' % (datum['chat'][2], datum['chat'][3]);
        row.append(chat)

        # add GT and pred
        row.extend([', '.join(datum['gt']), ', '.join(datum['pred'])]);

        page.addRow(row);

    # render and save page
    page.savePage(savePath);
Exemplo n.º 36
0
 def _WriteErrorReport(self, linesMissingInNetwork):
     h = HTML()
     t = h.table()
     tr = t.tr()
     tr.th("Line ID")
     for id in linesMissingInNetwork:
         tr = t.tr()
         tr.td(str(id))
     
     pb = _m.PageBuilder(title="Lines not in network report")
     
     pb.wrap_html("Lines references in file but not in network", body= str(t))
     
     _m.logbook_write("Error report", value= pb.render())
Exemplo n.º 37
0
    def _WriteErrorReport(self, linesMissingInNetwork):
        h = HTML()
        t = h.table()
        tr = t.tr()
        tr.th("Line ID")
        for id in linesMissingInNetwork:
            tr = t.tr()
            tr.td(str(id))

        pb = _m.PageBuilder(title="Lines not in network report")

        pb.wrap_html("Lines references in file but not in network",
                     body=str(t))

        _m.logbook_write("Error report", value=pb.render())
 def _WriteMainReport(self, reversedLines):
     h = HTML()
     t = h.table()
     tr = t.tr()
     tr.th('Original ID')
     tr.th('Reversed ID')
     
     for originalId, newId in  reversedLines:
         tr = t.tr()
         tr.td(originalId)
         tr.td(newId)
     
     pb = _m.PageBuilder(title= "Reversed Lines Report")
     pb.wrap_html(body= str(t))
     _m.logbook_write("Reversed lines report", value= pb.render())
Exemplo n.º 39
0
class TestHTML(unittest.TestCase):
    def setUp(self):
        self.html = HTML('dont care')

    def test_get_comment_definitions(self):
        self.assertItemsEqual(self.html.get_comment_definitions(),
                [ { 'type':'comment',
                    'startwith':r'<!--',
                    'endwith':r'-->',
                    'block':True } ])
        self.assertListEqual(self.html.get_comment_definitions(),
                [ { 'type':'comment',
                    'startwith':r'<!--',
                    'endwith':r'-->',
                    'block':True } ])
Exemplo n.º 40
0
 def _WriteMainReport(self, reversedLines):
     h = HTML()
     t = h.table()
     tr = t.tr()
     tr.th('Original ID')
     tr.th('Reversed ID')
     
     for originalId, newId in  reversedLines:
         tr = t.tr()
         tr.td(originalId)
         tr.td(newId)
     
     pb = _m.PageBuilder(title= "Reversed Lines Report")
     pb.wrap_html(body= str(t))
     _m.logbook_write("Reversed lines report", value= pb.render())
    def format_exception(self):
        etype, evalue, etb = self.exception_info
        python_version = 'Python ' + sys.version.split(
        )[0] + ': ' + sys.executable
        date = time.ctime(time.time())
        html_page = HTML()
        frames = []
        records = inspect.getinnerframes(etb, self.no_of_tb_steps)
        for frame, file, lnum, func_name, lines, index in records:
            file_name = ''
            if file:
                file_name = os.path.abspath(file)
            args, varargs, varkw, locals = inspect.getargvalues(frame)
            function_args = inspect.formatargvalues(args, varargs, varkw,
                                                    locals)

            def reader(line_num=lnum):
                try:
                    return linecache.getline(file, line_num)
                finally:
                    line_num += 1

            vars = scanvars(reader, frame, locals)
            if index:
                i = lnum - index
                for line in lines:
                    if i == lnum: continue
                    i += 1
            frames.append({
                'file_name': file_name,
                'function_args': function_args,
                'locals': vars
            })
Exemplo n.º 42
0
    def buildDifferentialStatsTable(self, deltaSeriesCollection, refDsc, klass,
                                    style):
        """
    Builds a table with statistics for current profile session side by side with benchmarks

    :param deltaSeriesCollection: A series of elapsed time or pmc values for a pair of probes
    :param refDsc: Reference delta series collection for the current profile session
    :param klass: Css selector for this table (Default value = TRIVIAL_STATS_TABLE)
    :param style: Css inline style attributes for this table (Default value = '')

    """
        from xpedite.report import getDeltaMarkup, getDeltaType
        klass = '{} {}'.format(TABLE_SUMMARY, klass)
        table = HTML().table(border='1', klass=klass, style=style)
        self.buildStatsTableHeader(table)
        tbody = table.tbody
        fmt = DURATION_FORMAT + ' ({1}' + DURATION_FORMAT_2 + ')'

        for i, deltaSeries in enumerate(deltaSeriesCollection, 1):
            row = tbody.tr
            row.td('{0:,}'.format(i), klass=TD_KEY)
            row.td(deltaSeries.beginProbeName, klass=TD_KEY)
            row.td(deltaSeries.endProbeName, klass=TD_KEY)

            delta = deltaSeries.getMin() - refDsc[i - 1].getMin()
            row.td(fmt.format(deltaSeries.getMin(), getDeltaMarkup(delta),
                              delta),
                   klass=getDeltaType(delta))

            delta = deltaSeries.getMax() - refDsc[i - 1].getMax()
            row.td(fmt.format(deltaSeries.getMax(), getDeltaMarkup(delta),
                              delta),
                   klass=getDeltaType(delta))

            delta = deltaSeries.getMedian() - refDsc[i - 1].getMedian()
            row.td(fmt.format(deltaSeries.getMedian(), getDeltaMarkup(delta),
                              delta),
                   klass=getDeltaType(delta))

            delta = deltaSeries.getMean() - refDsc[i - 1].getMean()
            row.td(fmt.format(deltaSeries.getMean(), getDeltaMarkup(delta),
                              delta),
                   klass=getDeltaType(delta))

            percentile1 = deltaSeries.getPercentile(self.percentile1)
            delta = percentile1 - refDsc[i - 1].getPercentile(self.percentile1)
            row.td(fmt.format(percentile1, getDeltaMarkup(delta), delta),
                   klass=getDeltaType(delta))

            percentile2 = deltaSeries.getPercentile(self.percentile2)
            delta = percentile2 - refDsc[i - 1].getPercentile(self.percentile2)
            row.td(fmt.format(percentile2, getDeltaMarkup(delta), delta),
                   klass=getDeltaType(delta))

            delta = deltaSeries.getStandardDeviation() - refDsc[
                i - 1].getStandardDeviation()
            row.td(fmt.format(deltaSeries.getStandardDeviation(),
                              getDeltaMarkup(delta), delta),
                   klass=getDeltaType(delta))
        return table
    def create_table(self, tg):
        '''
        Given a tableGroup element returns html marked up table wrapped in a div
        '''
        

        h = HTML.table()
Exemplo n.º 44
0
    def buildEnvironmentTable(app):
        """
    Builds a table with environment details

    :param app: an instance of xpedite app, to interact with target application

    """
        table = HTML().table(border='1', klass=TABLE_ENV)
        heading = table.thead.tr
        heading.th('No')
        heading.th('Parameter')
        heading.th('Value')

        details = [('application', app.name),
                   ('report time', strftime('%Y-%m-%d %H:%M:%S', gmtime())),
                   ('host', app.ip), ('pid', app.pid),
                   ('user', getpass.getuser()), ('os', app.getOsUname()),
                   ('os boot param', app.getBootParam())]

        tbody = table.tbody
        for i, (k, val) in enumerate(details):
            row = tbody.tr
            row.td('{:,}'.format(i + 1), klass=TD_KEY)
            row.td('{} '.format(k), klass=TD_KEY)
            row.td('{} '.format(val))
        return table
Exemplo n.º 45
0
def make_html(text):
    h = HTML()
    p = h.p
    for line in text.splitlines():
        p += line
        p.br
    return p
Exemplo n.º 46
0
 def __init__(self):
     #constructor function
     Animal.__init__(self)
     HTML.__init__(self)
     self.title = "The Rabbit"
     self.animal = "Belgian Hare Rabbit"
     self._phylum = "Chordata"
     self._class_ = "Mammalia"
     self._order = "Lagomorpha"
     self._family = "Leporidae"
     self._genus = "Sylvilagus"
     self._url = "images/Rabbit.jpg"
     self._avg_lifespan = "Ten years"
     self._habitat = "Woodlands, Prairies, Deserts."
     self._geo_location = "North, South America, Asia, Europe, Africa, Australia"
     self.sound = "Weening"
     self._body_id = "rabbit"
Exemplo n.º 47
0
 def __init__(self):
     #constructor function
     Animal.__init__(self)
     HTML.__init__(self)
     self.title = "The Grey Wolf"
     self.animal = "GREY WOLF"
     self._phylum = "Chordata"
     self._class_ = "Mammalia"
     self._order = "Carnivora"
     self._family = "Canidae"
     self._genus = "	Canis"
     self._url = "images/GreyWolf.jpg"
     self._avg_lifespan = "Five years "
     self._habitat = "Deserts, Woodlands and Arctic."
     self._geo_location = "North America and Europe, Australia"
     self.sound = "Howling"
     self._body_id = "wolf"
 def _WriteErrorReport(self, errorLines):
     h = HTML()
     t = h.table()
     tr = t.tr()
     tr.th('Line ID')
     tr.th('Error Type')
     tr.th('Error Message')
     
     for lineId, errorType, errorMsg in errorLines:
         tr = t.tr()
         tr.td(lineId)
         tr.td(errorType)
         tr.td(errorMsg)
     
     pb = _m.PageBuilder(title= "Error Report")
     pb.wrap_html(body= str(t))
     _m.logbook_write("Error report", value= pb.render())
Exemplo n.º 49
0
def makeTable(results_list):
    #generate html
    h = HTML()
    t = h.table(border='1')
    heading = t.tr
    heading.td('IP Address')
    heading.td('MAC Address')
    heading.td('Hostname')
    heading.td('Operating System Detected')
    for rows in results_list:
        r = t.tr
        for data in rows:
            if data is None:
                data = 'Not Available'
            r.td(data)
    logger.debug(h)
    return h
    def html_representation_compared_to_average(self, average_price,
                                                average_distance):
        price_distortion = (self.price - average_price) / average_price
        price_distortion_sign = tendency_sign(price_distortion)
        distance_distortion = (self.km_distance_from_work() -
                               average_distance) / average_distance
        distance_distortion_sign = tendency_sign(distance_distortion)

        return [
            str(self.rating()),
            str(self.price) + " (" + percent_me(price_distortion) + "%)",
            round_me(self.km_distance_from_work()) + " (" +
            percent_me(distance_distortion) + "%)",
            HTML.link('Source', self.html_link()),
            HTML.link('Google Maps', self.maps_link()), self.address,
            str(self.time_ago())
        ]
Exemplo n.º 51
0
 def _WriteErrorReport(self, errorLines):
     h = HTML()
     t = h.table()
     tr = t.tr()
     tr.th('Line ID')
     tr.th('Error Type')
     tr.th('Error Message')
     
     for lineId, errorType, errorMsg in errorLines:
         tr = t.tr()
         tr.td(lineId)
         tr.td(errorType)
         tr.td(errorMsg)
     
     pb = _m.PageBuilder(title= "Error Report")
     pb.wrap_html(body= str(t))
     _m.logbook_write("Error report", value= pb.render())
Exemplo n.º 52
0
 def index(self):
   h = HTML()
   h.h1("Hello world")
   h.h2("And")
   h.h3("Bye")
   indexString= str(h)
   return indexString
Exemplo n.º 53
0
    def genTR(self):
        tr = HTML('tr')

        url = "http://www.gw2spidy.com/recipe/%d" % self.itemId
        # Name
        tr.td.a(self.name, href=url, target="_blank")
        for i in (self.toS(self.matCost),
                self.toS(self.buyPrice), 
                self.toS(self.sellPrice),
                self.toS(self.instantProfit),
                self.toS(self.flipProfit),
                self.toS(self.craftProfit)):
                

            tr.td(i, align="right")
            # Profession
        tr.td(disc[self.disc])
        tr.td(str(self.skill))
        return (tr)
Exemplo n.º 54
0
    def __init__(self,list_data):
        self.h = HTML()
	        
	self.table = self.h.table(border='2',align='center')
	
	
        for i in range(len(list_data)):
            self.r = self.table.tr
            self.r.td('%s'%str(i+1))
            self.r.td(list_data[i])
        print self.table
Exemplo n.º 55
0
    def __init__(self):
        #constructor functions
        Animal.__init__(self)
        HTML.__init__(self)

        self.__css_url = ""

        self.title = "The Fox"
        self.animal = "Red Fox"
        self._phylum = "Chordata"
        self._class_ = "Mammalia"
        self._order = "Carnivora"
        self.__family = "Canidae"
        self._genus = "Vulpes"
        self._url = "images/foximg.jpg"
        self._avg_lifespan = "Five years"
        self._habitat = "Woodlands"
        self._geo_location = "North America, Asia, Europe Australia"
        self.sound = "Howling"
        self._body_id = "fox"
 def page(self):
     pb = _tmgTPB.TmgToolPageBuilder(self, title="Search Logbook Attribtues v%s" %self.version,
                  description="Searches the logbook for entries with a named attribute value \
                      (available attributes & their associated values can be discovered by \
                      double-clicking a logbook entry). One example of where this is useful is \
                      to trace the histroy of a single scenario.",
                  branding_text="- TMG Toolbox")
     
     if self.tool_run_msg != "": # to display messages in the page
         pb.tool_run_status(self.tool_run_msg_status)
         
     if self.matches:
         with pb.section('Search Results'):
             h = HTML()
             l = h.ul()
             for timestamp, element_id, title in self.matches:
                 description = "%s: %s" %(title, timestamp)
                 
                 a = self._render_entry_link(element_id, description)
                 
                 l.li(a, escape= False)
             
             pb.wrap_html(body= str(l))
     
     pb.add_text_box(tool_attribute_name= 'AttributeName',
                     title= "Attribute",
                     note= "Match attribute names containing this text.",
                     size=100)
     
     pb.add_text_box(tool_attribute_name= 'AttributeValue',
                     title = "Value",
                     note="Match attribute values containing this text",
                     size=100)
     
     pb.add_checkbox(tool_attribute_name= 'CaseSensitivity',
                    label= "Case sensitive?")
     
     return pb.render()
Exemplo n.º 57
0
class Html(object):
    def __init__(self):
        self.h = HTML()

    def table(self, title, data):
        self.t = self.h.table(border="1")
        self.t.caption(title)
        for i in data:
            r = self.t.tr
            for j in xrange(len(i)):
                r.td(str(i[j]))
        return str(self.t)

    def text(self, data):
        self.p = self.h.p()
        for line in data:
            self.p.text(str(line))
            self.p.br
        return str(self.h)

    def link(self, url):
        self.a = self.h.a(str(url))
        return str(self.a)
Exemplo n.º 58
0
    def __init__(self, name, local_jquery=None, local_requirejs=None, local_d3_js=None, local_c3_js=None,
                 local_c3_css=None):

        super(Chart, self).__init__()

        self.chart_html = HTML()

        self.name = name
        self.c3_css_path = local_c3_css or 'https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css'
        self.jquery_path = local_jquery or 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js'
        self.requirejs_path = local_requirejs or \
            'https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.17/require.min.js'
        self.d3_js_path = local_d3_js or 'http://d3js.org/d3.v3.min'
        self.c3_js_path = local_c3_js or 'https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min'

        self.chart_html.div('', id=self.name)
        self.chart_html.link('', href=self.c3_css_path, rel='stylesheet', type='text/css')
        self.chart_html.script('', src=self.jquery_path)
        self.chart_html.script('', src=self.requirejs_path)

        self.requirejs_config = {
            'paths': {
                'c3': self.c3_js_path,
                'd3': self.d3_js_path,
            }
        }

        self.axes = Axes()
        self.data = Data(self.axes)
        self.grid = Grid(self.axes)
        self.legend = Legend()
        self.tooltip = Tooltip()
        self.regions = Regions(self.axes)
        self.point = Point()
        self.size = Size()
        self.padding = Padding()

        self.chart_dict = {
            'bindto': "'#" + self.name + "'",
            'data': self.data.config,
            'axis': self.axes.config,
            'grid': self.grid.config,
            'legend': self.legend.config,
            'tooltip': self.tooltip.config,
            'regions': self.regions.config,
            'point': self.point.config,
            'size': self.size.config,
            'padding': self.padding.config,
        }
Exemplo n.º 59
0
		'''
		Handled in Video tag generation function getVideoRowHTML.

		if ele_type.strip() == "Subtitles (Video)" and ele_val != 'NONE':
			pass
		'''
	# print "\n body_DOM == ", body_DOM
	return body_DOM
try:
	for each_sheet in activities_template_workbook.sheets():
		# print " || No. of rows found: ", each_sheet.nrows
		# if "Activity" in each_sheet.name:
		print "\n Processing: ", each_sheet.name,
		html_content = header_ele = None
		body_html = HTML('body')
		for each_row in xrange(each_sheet.nrows):
			val_list = each_sheet.row_values(each_row)
			val_list = map(unicode,val_list)
			# print "\n val list = ", val_list
			if "Activity Number" in val_list:
				try:
					activity_num = val_list[1]
				except IndexError as name_not_found:
					print "\n Error !! ", name_not_found
					pass

			if "Activity Name" in val_list:
				try:
					activity_name = val_list[2]
				except IndexError as name_not_found: