Example #1
0
    def render(self):
        """Print unique values for a column."""
        rows: List[Row] = self.query(
            query_text=self.legend_query,
            column=self.iri,
        )

        table_rows = [
            tr(
                td(
                    raw(
                        render(
                            node=row['prov_value'],
                            octiron=self.octiron,
                            environments=[
                                TABLE.td,
                                IOLANTA.html,
                            ],
                        ) if row['prov_value'] is not None else '', ), ),
                td(*self.render_comment(row)),
                td(row['count']),
            ) for row in rows
        ]

        return table(
            thead(
                tr(
                    # These are hard coded, and I cannot change that. See the
                    # docstring for details.
                    th('Value'),
                    th('Description'),
                    th('Count'),
                ), ),
            tbody(*table_rows),
        )
Example #2
0
    def get_html(self):
        """generates html code for viewing web service related data"""

        root_div = div(cls="col-xs-12 pull-left", style="margin-top:10px;")

        def get_th(heading_name):
            return th(heading_name, cls="text-muted")

        with root_div:
            with div(cls="custom-well"):
                # strong(self.name)
                with table(cls='custom-table'):
                    with tbody():
                        with tr():
                            get_th('URL')
                            td(self.url)
                        with tr():
                            get_th('Service Type')
                            td(self.service_type)
                        with tr():
                            get_th('Return Type')
                            td(self.return_type)
                        with tr():
                            get_th('Reference Type')
                            td(self.reference_type)

        return root_div.render(pretty=True)
def build_discrepancy_parent_report(discrepancy_reports):
    version = utils.show_version()
    doc = dominate.document(title='Audit Engine version: ' + version)
    report_head(doc)
    discrepancy_reports.sort(key=itemgetter('discrepancy', 'ballots'),
                             reverse=True)
    with doc:
        with div(cls='container'):
            report_headline(version)
            with table(cls='table table-striped'):
                with thead():
                    with tr():
                        th('#', scope="col")
                        th('Precinct', scope="col")
                        th('Ballots total', scope="col")
                        th('Discrepancy', scope="col")
                        th('Report', scope="col")
                with tbody():
                    for index, report in enumerate(discrepancy_reports):
                        with tr():
                            report_abs_path = os.path.abspath(
                                report.get('path'))
                            th(index + 1)
                            td(report.get('precinct'))
                            td(report.get('ballots'))
                            td(f"{report.get('discrepancy')}%")
                            td(
                                a(i(cls='far fa-file-alt'),
                                  href=report_abs_path,
                                  targer='_blank'))
    return doc
Example #4
0
def table(
        data: List[List[str]],
        header: Optional[List[str]] = None,
        green_value: Optional[str] = None,
        red_value: Optional[str] = None,
        red_predicate: Optional[Callable] = None
) -> None:
    """
    Print table to HTML output
    :param data: List of lines, each containing list of cell data
    :param header: optional list of header cells, no header if None or empty
    :param green_value: cell value content to highlight in green
    :param red_value: cell value content to highlight in red
    :param red_predicate: predicate on line to highlight in red
    """

    with tags.table():

        if header:
            with tags.tr():
                for cell in header:
                    tags.th(cell)

        for line in data:
            with tags.tr():
                for cell in line:
                    color = "var(--main-color)"
                    if green_value and green_value in cell:
                        color = "var(--green-color)"
                    if red_value and red_value in cell:
                        color = "var(--red-color)"
                    if red_predicate and red_predicate(line):
                        color = "var(--red-color)"
                    tags.td(cell, style="color:" + color)
Example #5
0
    def get_html(self):
        """generates html code for viewing web service related data"""

        root_div = div(cls="col-xs-12 pull-left", style="margin-top:10px;")

        def get_th(heading_name):
            return th(heading_name, cls="text-muted")

        with root_div:
            with div(cls="custom-well"):
                # strong(self.name)
                with table(cls='custom-table'):
                    with tbody():
                        with tr():
                            get_th('URL')
                            td(self.url)
                        with tr():
                            get_th('Service Type')
                            td(self.service_type)
                        with tr():
                            get_th('Return Type')
                            td(self.return_type)
                        with tr():
                            get_th('Reference Type')
                            td(self.reference_type)

        return root_div.render(pretty=True)
def diff(master_screens_path, current_screens_path, test_name, master_hash,
         current_hash):
    doc = dominate.document(title=test_name)
    master_screens = sorted(master_screens_path.iterdir())
    current_screens = sorted(current_screens_path.iterdir())

    with doc:
        h1(test_name)
        p("This UI test differs from master.",
          style="color: grey; font-weight: bold;")
        with table():
            with tr():
                td("Master:")
                td(master_hash, style="color: red;")
            with tr():
                td("Current:")
                td(current_hash, style="color: green;")
        hr()

        with table(border=1, width=600):
            with tr():
                th("Master")
                th("Current branch")

            html.diff_table(master_screens, current_screens)

    return html.write(REPORTS_PATH / "diff", doc, test_name + ".html")
Example #7
0
    def populate(self, pages):
        self.data = [[
            'Title', 'Rating', {
                'role': 'tooltip',
                'p': {
                    'html': 'true'
                }
            }, {
                'role': 'style'
            }
        ]]

        for p in pages:
            if 'scp' in p.tags:
                color = 'color: #db4437'
            elif 'tale' in p.tags:
                color = 'color: #4285f4'
            else:
                color = 'color: #f4b400'

            date = p.metadata[self.user].date[:10] or '-'

            tooltip = dt.table(dt.tr(dt.td(p.title, colspan=2)),
                               dt.tr(dt.td('Rating:'), dt.td(p.rating)),
                               dt.tr(dt.td('Created:'), dt.td(date)),
                               cls='articles_chart_tooltip')

            self.data.append(
                [p.title, p.rating,
                 tooltip.render(pretty=False), color])
Example #8
0
def failed(fixture_test_path, test_name, actual_hash, expected_hash):
    doc = dominate.document(title=test_name)
    recorded_path = fixture_test_path / "recorded"
    actual_path = fixture_test_path / "actual"

    if not recorded_path.exists():
        recorded_path.mkdir()
    download.fetch_recorded(expected_hash, recorded_path)

    recorded_screens = sorted(recorded_path.iterdir())
    actual_screens = sorted(actual_path.iterdir())

    if not recorded_screens:
        return

    with doc:
        _header(test_name, expected_hash, actual_hash)

        with table(border=1, width=600):
            with tr():
                th("Expected")
                th("Actual")

            for recorded, actual in zip_longest(recorded_screens, actual_screens):
                if recorded and actual and filecmp.cmp(actual, recorded):
                    background = "white"
                else:
                    background = "red"
                with tr(bgcolor=background):
                    _image(recorded)
                    _image(actual)

    return _write(REPORTS_PATH / "failed", doc, test_name + ".html")
Example #9
0
    def format(trait, objs, *args, **kwargs) -> Htmlish:
        # TODO would be nice to have spinboard imported here for type checking..
        res = T.div(cls='pinboard')

        title = trait.title(objs)
        link = trait.link(objs)
        res.add(T.div(T.a(title, href=link)))

        with adhoc_html('pinboard', cb=lambda children: res.add(*children)):
            with T.table():
                for _, obj in objs:
                    if not isempty(obj.description):
                        with T.tr():
                            with T.td(colspan=3):
                                T.span(obj.description, cls='description')
                    with T.tr():
                        # TODO wtf is min??
                        with T.td(cls='min'):
                            T.a(f'{fdate(obj.when)}',
                                href=obj.blink,
                                cls='permalink timestamp')
                        with T.td(cls='min'):
                            text('by ')
                            trait.user_link(user=obj.user)
                        with T.td():
                            for t in obj.ntags:
                                trait.tag_link(tag=t, user=obj.user)
        # TODO userstats
        return res
Example #10
0
    def _contact(self):
        contact = self._toml['contact']
        assert isinstance(contact, dict)

        with tr() as row:
            label = contact['label']
            assert isinstance(label, str)
            td(label, rowspan=2, colspan=1, class_name='label')

            contact_points = contact['value']
            assert isinstance(contact_points, dict)

            email = contact_points['email']
            assert isinstance(email, str)
            with td(colspan=3, class_name='value'):
                a(email, href=f'mailto:{email}', target='_blank')

        yield row

        with tr() as row:
            url = contact_points['url']
            assert isinstance(url, str)
            with td(colspan=3, class_name='value'):
                a(url, href=url, target='_blank')

        yield row
Example #11
0
    def get_html(self):
        """generates html code for viewing site related data"""

        root_div = div(cls="col-xs-12 pull-left", style="margin-top:10px;")

        def get_th(heading_name):
            return th(heading_name, cls="text-muted")

        with root_div:
            with div(cls="custom-well"):
                # strong(self.name)
                with table(cls='custom-table'):
                    with tbody():
                        with tr():
                            get_th('Name')
                            td(self.name)
                        with tr():
                            get_th('Code')
                            td(self.code)
                        with tr():
                            get_th('Latitude')
                            td(self.latitude)
                        with tr():
                            get_th('Longitude')
                            td(self.longitude)

        return root_div.render(pretty=True)
Example #12
0
    def populate(self, pages):
        self.data = [[
            'Title',
            'Rating',
            {'role': 'tooltip', 'p': {'html': 'true'}},
            {'role': 'style'}]]

        for p in pages:
            if 'scp' in p.tags:
                color = 'color: #db4437'
            elif 'tale' in p.tags:
                color = 'color: #4285f4'
            else:
                color = 'color: #f4b400'

            date = p.metadata[self.user].date[:10] or '-'

            tooltip = dt.table(
                dt.tr(dt.td(p.title, colspan=2)),
                dt.tr(dt.td('Rating:'), dt.td(p.rating)),
                dt.tr(dt.td('Created:'), dt.td(date)),
                cls='articles_chart_tooltip')

            self.data.append([
                p.title,
                p.rating,
                tooltip.render(pretty=False),
                color])
def getDescriptionPills(statistics):
    statistics = np.round(statistics, 1)

    statisticstable = table(cls='table')
    table_header_row = tr()
    table_header_row.appendChild(th('Measurements count'))
    table_header_row.appendChild(th('Mean error'))
    table_header_row.appendChild(th('Standard Error dev'))
    table_header_row.appendChild(th('Min error measured'))
    table_header_row.appendChild(th('First quartile (25%)'))
    table_header_row.appendChild(th('Median (50%)'))
    table_header_row.appendChild(th('Third quartile (75%)'))
    table_header_row.appendChild(th('Max error measured'))

    table_row = tr()
    table_row.appendChild(td(str(statistics[0])))
    table_row.appendChild(td(str(statistics[1])))
    table_row.appendChild(td(str(statistics[2])))
    table_row.appendChild(td(str(statistics[3])))
    table_row.appendChild(td(str(statistics[4])))
    table_row.appendChild(td(str(statistics[5])))
    table_row.appendChild(td(str(statistics[6])))
    table_row.appendChild(td(str(statistics[7])))

    statisticstable.appendChild(thead(table_header_row))
    statisticstable.appendChild(tbody(table_row))
    return statisticstable
def mount_discrepancy_table(contest: str, contest_disagreed_df: pd.DataFrame,
                            precinct_marks_df: pd.DataFrame) -> table:
    contest_marks_df = precinct_marks_df.loc[precinct_marks_df['contest'] ==
                                             contest]
    overvotes = contest_marks_df['overvotes'].sum()
    undervotes = contest_marks_df['undervotes'].sum()
    options = [
        o for o in contest_marks_df['option'].unique().tolist()
        if not o.startswith('#contest vote_for')
    ]
    with table(cls='table table-striped'):
        with thead():
            with tr():
                th('Candidate or Issue', scope="col")
                th('Audit System Adjudicated Votes', scope="col")
                th('Audit Indeterminate Votes', scope="col")
                th('Canvassing Board Adjustments', scope="col")
                th('Audit Total Votes', scope="col")
                th('Certified Results Total', scope="col")
                th('Difference', scope="col")
        with tbody():
            for option in options:
                mount_option_row(option, contest_disagreed_df,
                                 contest_marks_df)
            with tr():
                td('Number of overvotes')
                td(overvotes, colspan=6)
            with tr():
                td('Number of undervotes')
                td(undervotes, colspan=6)
Example #15
0
    def get_html(self, pretty=True):
        """Generates html code for displaying data for this metadata element"""

        root_div = div(cls="content-block")

        def get_th(heading_name):
            return th(heading_name, cls="text-muted")

        with root_div:
            legend('Cell Information')
            with table(cls='custom-table'):
                with tbody():
                    with tr():
                        get_th('Rows')
                        td(self.rows)
                    with tr():
                        get_th('Columns')
                        td(self.columns)
                    with tr():
                        get_th('Cell Size X Value')
                        td(self.cellSizeXValue)
                    with tr():
                        get_th('Cell Size Y Value')
                        td(self.cellSizeYValue)
                    with tr():
                        get_th('Cell Data Type')
                        td(self.cellDataType)

        return root_div.render(pretty=pretty)
Example #16
0
    def writeContent(self):
        self.writeln('<h1>Using Webware with Dominate</h1>')
        self.writeln(
            '<p>Dominate is a Python library that can be used in Webware'
            ' applications to generate HTML programmatically.</p>')
        if not dominate:
            self.writeln(
                f'<p>Please install <a href="{self.homepage}">Dominate</a>'
                ' in order to view this demo.</p>')
            return

        content = div(id='content')
        with content:
            h2('Hello World!')
            with table(cls="NiceTable").add(tbody()):
                tr(th('Demo table', colspan=3))
                r = tr()
                r += td('One')
                r.add(td('Two'))
                with r:
                    td('Three')
            para = p(__pretty=False)
            with para:
                text('This content has been produced with ')
                a('Dominate', href=self.homepage)
                text(' programmatically.')
        self.write(content)
Example #17
0
    def get_html(self):
        """generates html code for viewing site related data"""

        root_div = div(cls="col-xs-12 pull-left", style="margin-top:10px;")

        def get_th(heading_name):
            return th(heading_name, cls="text-muted")

        with root_div:
            with div(cls="custom-well"):
                # strong(self.name)
                with table(cls='custom-table'):
                    with tbody():
                        with tr():
                            get_th('Name')
                            td(self.name)
                        with tr():
                            get_th('Code')
                            td(self.code)
                        with tr():
                            get_th('Latitude')
                            td(self.latitude)
                        with tr():
                            get_th('Longitude')
                            td(self.longitude)

        return root_div.render(pretty=True)
Example #18
0
    def get_html(self, pretty=True):
        """Generates html code for displaying data for this metadata element"""

        root_div = div(cls="content-block")

        def get_th(heading_name):
            return th(heading_name, cls="text-muted")

        with root_div:
            legend('Cell Information')
            with table(cls='custom-table'):
                with tbody():
                    with tr():
                        get_th('Rows')
                        td(self.rows)
                    with tr():
                        get_th('Columns')
                        td(self.columns)
                    with tr():
                        get_th('Cell Size X Value')
                        td(self.cellSizeXValue)
                    with tr():
                        get_th('Cell Size Y Value')
                        td(self.cellSizeYValue)
                    with tr():
                        get_th('Cell Data Type')
                        td(self.cellDataType)

        return root_div.render(pretty=pretty)
Example #19
0
    def _create_table(self, rows):
        columns = []
        for row in rows:
            for column in row.keys():
                if column in columns:
                    continue
                columns.append(column)

        # Create table
        table = tags.table()

        thead = tags.thead()
        tr = tags.tr()
        for column in columns:
            tr += tags.th(raw(column))
        thead += tr

        tbody = tags.tbody()
        for row in rows:
            tr = tags.tr()
            for column in columns:
                tr += tags.td(row.get(column, ''))
            tbody += tr

        table += thead
        table += tbody

        return table
Example #20
0
    def get_html(self, pretty=True):
        """Generates html code for displaying data for this metadata element"""

        root_div = div(cls="content-block")

        def get_th(heading_name):
            return th(heading_name, cls="text-muted")

        with root_div:
            legend('Spatial Reference')
            div('Coordinate Reference System', cls='text-muted space-top')
            div(self.value.get('projection', ''))
            div('Coordinate Reference System Unit', cls='text-muted space-top')
            div(self.value['units'])
            div('Datum', cls='text-muted space-top')
            div(self.value.get('datum', ''))
            div('Coordinate String', cls='text-muted space-top')
            div(self.value.get('projection_string', ''), style="word-break: break-all;")
            h4('Extent', cls='space-top')
            with table(cls='custom-table'):
                with tbody():
                    with tr():
                        get_th('North')
                        td(self.value['northlimit'])
                    with tr():
                        get_th('West')
                        td(self.value['westlimit'])
                    with tr():
                        get_th('South')
                        td(self.value['southlimit'])
                    with tr():
                        get_th('East')
                        td(self.value['eastlimit'])

        return root_div.render(pretty=pretty)
Example #21
0
    def get_extra_metadata_html_form(self):
        def get_add_keyvalue_button():
            add_key_value_btn = a(cls="btn btn-success",
                                  type="button",
                                  data_toggle="modal",
                                  data_target="#add-keyvalue-filetype-modal",
                                  style="margin-bottom:20px;")
            with add_key_value_btn:
                with span(cls="glyphicon glyphicon-plus"):
                    span("Add Key/Value", cls="button-label")
            return add_key_value_btn

        if self.extra_metadata:
            root_div_extra = div(cls="col-xs-12", id="filetype-extra-metadata")
            with root_div_extra:
                legend('Extended Metadata')
                get_add_keyvalue_button()
                with table(cls="table table-striped funding-agencies-table",
                           style="width: 100%"):
                    with tbody():
                        with tr(cls="header-row"):
                            th("Key")
                            th("Value")
                            th("Edit/Remove")
                        counter = 0
                        for k, v in self.extra_metadata.iteritems():
                            counter += 1
                            with tr(data_key=k):
                                td(k)
                                td(v)
                                with td():
                                    a(data_toggle="modal",
                                      data_placement="auto",
                                      title="Edit",
                                      cls=
                                      "glyphicon glyphicon-pencil icon-button icon-blue",
                                      data_target="#edit-keyvalue-filetype-modal"
                                      "-{}".format(counter))
                                    a(data_toggle="modal",
                                      data_placement="auto",
                                      title="Remove",
                                      cls=
                                      "glyphicon glyphicon-trash icon-button btn-remove",
                                      data_target=
                                      "#delete-keyvalue-filetype-modal"
                                      "-{}".format(counter))

                self._get_add_key_value_modal_form()
                self._get_edit_key_value_modal_forms()
                self._get_delete_key_value_modal_forms()
            return root_div_extra
        else:
            root_div_extra = div(cls="row", id="filetype-extra-metadata")
            with root_div_extra:
                with div(cls="col-lg-12 content-block"):
                    legend('Extended Metadata')
                    get_add_keyvalue_button()
                    self._get_add_key_value_modal_form()
            return root_div_extra
def list_test1(hits, url):
    table = t.table()
    with table:
        for hit in hits:
            with t.tr():
                t.td(t.a(hit['name'], href='%s/%d' % (url, hit['id'])))
        if len(hits) >= 9:
            t.tr(t.td('... (type in search bar to narrow list)'))
    return table.render()
Example #23
0
def filter_user_list(results, url):  # TODO: GENERALIZE for other lists!
    table = t.table()
    with table:
        for result in results:
            with t.tr():
                t.td(
                    t.a(result['username'],
                        href='%s/%d' % (url, result['id'])))
        if len(results) >= 9:
            t.tr(t.td('... (type in search bar to narrow list)'))
    return table.render()
Example #24
0
def _report_links(tests):
    if not tests:
        i("None!")
        return
    with table(border=1):
        with tr():
            th("Link to report")
        for test in sorted(tests):
            with tr():
                path = test.relative_to(REPORTS_PATH)
                td(a(test.name, href=path))
Example #25
0
    def render(self) -> table:
        """Render the table."""
        columns = list_columns(
            iri=self.uriref,
            octiron=self.octiron,
        )

        ordering = get_ordering(
            iri=self.uriref,
            octiron=self.octiron,
        )

        headers = construct_headers(
            octiron=self.octiron,
            table_iri=self.uriref,
            columns=columns,
        )

        instances = select_instances(
            iri=self.uriref,
            octiron=self.octiron,
        )

        rows = [
            construct_row(
                instance=instance,
                columns=columns,
                octiron=self.octiron,
            )
            for instance in instances
        ]

        rows = order_rows(
            rows=rows,
            ordering=ordering,
        )

        rows = [
            tr(
                *render_row(
                    row=row,
                    columns=columns,
                    octiron=self.octiron,
                ),
            )
            for row in rows
        ]

        return table(
            thead(
                tr(*headers),
            ),
            tbody(*rows),
        )
def mount_ballots_to_table(cmpcvr_df: pd.DataFrame) -> tuple:
    cmpcvr_df.dropna(subset=['disagreed_info'], inplace=True)
    index = 1
    for _, row in cmpcvr_df.iterrows():
        head_row = tr(cls='',
                      data_toggle='collapse',
                      data_target=f'#collapse{index}')
        head_row += th(index), td(row['ballot_id']), td(row['style'])
        collapse_row = tr(id=f'collapse{index}', cls='collapse')
        collapse_row += td(), get_ballot_details_td(row)
        index += 1
        yield head_row, collapse_row
Example #27
0
def make_html(pixdir, route_name, results):

    title = "Pictures from %s" % route_name

    document = dominate.document(title=title)

    with document.head:
        meta(charset="UTF-8")
        style("""
        table { page-break-inside:auto; border-spacing:3px; padding:3px; }
        table { margin-left:auto; margin-right:auto; }
        table, td, th, tr { border:1px solid green; }
        th { background-color: green; color: white; }
        th.tiny { width:3%; }
        th.narrow { width:47%; }
        th.wide { width:50%; }
        tr { page-break-inside:avoid; page-break-after:auto; }
        tr.center { margin-left:auto; margin-right:auto; }
        tr.alt { background-color: #f0f0f0; }
        caption { background-color: #c0c040; font-size: 16px; \
font-family: "Courier New"; }
        body { font-size: 16px; }
        @media print {
            body { font-size: 8px; font-family: "Courier New" }
            caption { font-size: 10px }
            a {
            text-decoration: none; font-style: italic; font-weight: bold}
            th { background-color: white; color: black; }
        }
        """)

    with document.body:

        with table():

            caption(route_name)

            tr(th("Name"), th("Description"), th("Imagefile"))

            for time, filename, gc, tp in results:

                pathname = os.path.join(pixdir, filename)

                gcname, gcdesc = map(str, gc[1:])
                gclink = "http://coord.info/%s" % quote(gcname)

                with tr():

                    td(a(gcname, href=gclink))
                    td(gcdesc)
                    td(a(filename, href=quote(pathname)))

    print >> open("make_html.html", "w"), document
Example #28
0
    def get_html(self):
        """Generates html for displaying all metadata elements associated with this logical file.
        Subclass must override to include additional html for additional metadata it supports.
        """

        root_div = div()
        dataset_name_div = div()
        if self.logical_file.dataset_name:
            with dataset_name_div:
                with table(cls='custom-table'):
                    with tbody():
                        with tr():
                            th("Title", cls="text-muted")
                            td(self.logical_file.dataset_name)
        keywords_div = div()
        if self.keywords:
            keywords_div = div(cls="col-sm-12 content-block")
            with keywords_div:
                legend('Keywords')
                with div(cls="tags"):
                    with ul(id="list-keywords-file-type",
                            cls="tag-list custom-well"):
                        for kw in self.keywords:
                            with li():
                                a(kw, cls="tag")

        extra_metadata_div = div()
        if self.extra_metadata:
            extra_metadata_div = div(cls="col-sm-12 content-block")
            with extra_metadata_div:
                legend('Extended Metadata')
                with table(cls="table table-striped funding-agencies-table",
                           style="width: 100%"):
                    with tbody():
                        with tr(cls="header-row"):
                            th("Key")
                            th("Value")
                        for k, v in self.extra_metadata.iteritems():
                            with tr(data_key=k):
                                td(k)
                                td(v)

        if self.logical_file.dataset_name:
            root_div.add(dataset_name_div)
        if self.keywords:
            root_div.add(keywords_div)
        if self.extra_metadata:
            root_div.add(extra_metadata_div)

        return root_div.render()
Example #29
0
def report_links(tests, reports_path, actual_hashes=None):
    if actual_hashes is None:
        actual_hashes = {}

    if not tests:
        i("None!")
        return
    with table(border=1):
        with tr():
            th("Link to report")
        for test in sorted(tests):
            with tr(data_actual_hash=actual_hashes.get(test.stem, "")):
                path = test.relative_to(reports_path)
                td(a(test.name, href=path))
Example #30
0
def mtable(columns, data, tclass):
    t = table(cls=tclass, style="width: 100%; table-layout:fixed;")
    _tr = tr()
    for c, style in columns:
        _tr.add(th(c, style=style))
    t.add(thead(_tr))
    tb = tbody()
    for r in data:
        _tr = tr()
        for i, c in enumerate(r):
            _tr.add(td(c, style=columns[i][1]))
        tb.add(_tr)

    t.add(tb)
    return t
Example #31
0
def failed(fixture_test_path, test_name, actual_hash, expected_hash):
    doc = dominate.document(title=test_name)
    recorded_path = fixture_test_path / "recorded"
    actual_path = fixture_test_path / "actual"

    download_failed = False

    if not recorded_path.exists():
        recorded_path.mkdir()
    try:
        download.fetch_recorded(expected_hash, recorded_path)
    except Exception:
        download_failed = True

    recorded_screens = sorted(recorded_path.iterdir())
    actual_screens = sorted(actual_path.iterdir())

    with doc:
        _header(test_name, expected_hash, actual_hash)

        if download_failed:
            with p():
                strong("WARNING:")
                text(" failed to download recorded fixtures. Is this a new test case?")

        with table(border=1, width=600):
            with tr():
                th("Expected")
                th("Actual")

            html.diff_table(recorded_screens, actual_screens)

    return html.write(REPORTS_PATH / "failed", doc, test_name + ".html")
Example #32
0
def status_class(octiron: Octiron, iri: URIRef):
    """Visualize all available status values as a table."""
    choices = octiron.query('''
        SELECT
            ?status ?label ?symbol
            ?defined_by_iri ?defined_by_url ?defined_by_label
        WHERE {
            ?status a adr:Status .

            GRAPH ?defined_by_iri {
                ?status rdfs:label ?label .

                OPTIONAL {
                   ?status octa:symbol ?symbol .
                }
            }

            OPTIONAL {
                ?defined_by_iri octa:url ?defined_by_url .
            }

            OPTIONAL {
                ?defined_by_iri rdfs:label ?defined_by_label .
            }
        } ORDER BY ?label
        ''')

    rows = map(build_table_row, choices)

    return table(thead(tr(
        th('Code'),
        th('Label'),
        th('Defined By'),
    )), tbody(*rows))
Example #33
0
    def add_videos(self, vids, txts, links, width=400):
        """add images to the HTML file

        Parameters:
            ims (str list)   -- a list of image paths
            txts (str list)  -- a list of image names shown on the website
            links (str list) --  a list of hyperref links; when you click an image, it will redirect you to a new page
        """
        self.t = table(border=1,
                       style="table-layout: fixed;")  # Insert a table
        self.doc.add(self.t)
        with self.t:
            with tr():
                for vid, txt, link in zip(vids, txts, links):
                    with td(style="word-wrap: break-word;",
                            halign="center",
                            valign="top"):
                        with p():
                            with a(href=os.path.join('videos', link)):
                                with video(style="width:%dpx" % width,
                                           controls=True):
                                    source(src=os.path.join('videos', vid),
                                           type="video/mp4")
                            br()
                            p(txt)
Example #34
0
    def _write_body(self, write_attr: bool) -> None:
        tags, raw = _get_tags_module()
        tbody_tag = tags.tbody()

        for row_idx, (values, value_dp_list) in enumerate(
                zip(self._table_value_matrix, self._table_value_dp_matrix)):
            tr_tag = tags.tr()
            for value, value_dp, column_dp in zip(values, value_dp_list,
                                                  self._column_dp_list):
                td_tag = tags.td(raw(MultiByteStrDecoder(value).unicode_str))

                default_style = self._get_col_style(column_dp.column_index)
                style = self._fetch_style_from_filter(row_idx, column_dp,
                                                      value_dp, default_style)

                if write_attr:
                    if style.align == Align.AUTO:
                        td_tag["align"] = value_dp.align.align_string
                    else:
                        td_tag["align"] = style.align.align_string

                    if style.vertical_align != VerticalAlign.BASELINE:
                        td_tag["valign"] = style.vertical_align.align_str

                    style_tag = self.__make_style_tag(style=style)
                    if style_tag:
                        td_tag["style"] = style_tag

                tr_tag += td_tag
            tbody_tag += tr_tag

        self._table_tag += tbody_tag
        self._write_line(self._table_tag.render(indent=self.indent_string))
Example #35
0
    def add_images(self, epoch, ims, txts, links, width=400):
        if epoch != -1:
            img_dir_epoch = os.path.join(self.img_dir, str(epoch))
            util.mkdirs(img_dir_epoch)
        else:
            img_dir_epoch = self.img_dir

        path_parts = img_dir_epoch.split('/')

        if self.is_test:
            rel_path = path_parts[-1:]
        else:
            rel_path = path_parts[-2:]
        rel_path = '/'.join(rel_path)

        self.add_table()
        with self.t:
            with tr():
                for im, txt, link in zip(ims, txts, links):
                    with td(style="word-wrap: break-word;",
                            halign="center",
                            valign="top"):
                        with p():
                            with a(href=os.path.join(rel_path, link)):
                                img(style="width:%dpx" % width,
                                    src=os.path.join(rel_path, im))
                            br()
                            p(txt)
Example #36
0
    def get_html(self, pretty=True):
        """Generates html code for displaying data for this metadata element"""

        root_div = div(cls="content-block", style="margin-bottom:40px;")

        def get_th(heading_name):
            return th(heading_name, cls="text-muted")

        with root_div:
            legend('Geometry Information')
            with table(cls='custom-table'):
                with tbody():
                    with tr():
                        get_th('Geometry Type')
                        td(self.geometryType)
                    with tr():
                        get_th('Feature Count')
                        td(self.featureCount)
        return root_div.render(pretty=pretty)
Example #37
0
    def get_html(self, pretty=True):
        """Generates html code for displaying data for this metadata element"""

        field_infor_tr = tr(cls='row')
        with field_infor_tr:
            td(self.fieldName)
            td(self.fieldType)
            td(self.fieldWidth)
            td(self.fieldPrecision)
        if pretty:
            return field_infor_tr.render(pretty=pretty)
        return field_infor_tr
Example #38
0
    def _write_header(self):
        if not self.is_write_header:
            return

        tr_tag = tags.tr()
        for header in self.header_list:
            tr_tag += tags.th(header)

        thead_tag = tags.thead()
        thead_tag += tr_tag

        self._table_tag += thead_tag
Example #39
0
    def _write_body(self):
        tbody_tag = tags.tbody()

        for value_list, value_prop_list in zip(self._value_matrix, self._value_prop_matrix):
            tr_tag = tags.tr()
            for value, value_prop in zip(value_list, value_prop_list):
                td_tag = tags.td(value)
                td_tag["align"] = value_prop.align.align_string
                tr_tag += td_tag
            tbody_tag += tr_tag

        self._table_tag += tbody_tag
        self._write_line(self._table_tag.render(indent=self.indent_string))
 def get_student_grades_html(self):
     import dominate
     from dominate import tags
     page = dominate.document(title='Final Grades')
     with page:
         with tags.table(border="1"):
             number_of_assignments = self.get_number_of_assignments()
             with tags.tr():
                 tags.th("First Name")
                 tags.th("Last Name")
                 tags.th("Overall Average")
                 tags.th("Letter Grade")
                 tags.th("Scores", colspan=str(number_of_assignments))
             for student in self.sorted_students():
                 with tags.tr():
                     grade_average = student.grade_average(number_of_assignments)
                     tags.td(student.name.first)
                     tags.td(student.name.last)
                     tags.td(grade_average)
                     tags.td(self._grade_tiers.letter(grade_average))
                     for score in student.sorted_scores():
                         tags.td(score)
     return str(page)
Example #41
0
    def get_html(self, pretty=True):
        """Generates html code for displaying data for this metadata element"""

        root_div = div(cls="content-block")

        def get_th(heading_name):
            return th(heading_name, cls="text-muted")

        with root_div:
            legend('Spatial Reference')
            div('Coordinate Reference System', cls='text-muted')
            div(self.projection_name)
            div('Datum', cls='text-muted space-top')
            div(self.datum)
            div('Coordinate String Text', cls='text-muted space-top')
            div(self.projection_string)
            h4('Extent', cls='space-top')
            with table(cls='custom-table'):
                with tbody():
                    with tr():
                        get_th('North')
                        td(self.northlimit)
                    with tr():
                        get_th('West')
                        td(self.westlimit)
                    with tr():
                        get_th('South')
                        td(self.southlimit)
                    with tr():
                        get_th('East')
                        td(self.eastlimit)
                    with tr():
                        get_th('Unit')
                        td(self.unit)

        return root_div.render(pretty=pretty)
Example #42
0
    def _get_field_informations_html(self):
        root_div = div(cls="content-block")
        with root_div:
            legend('Field Information')
            with table(style="width: 100%;"):
                with tbody():
                    with tr(cls='row'):
                        th('Name')
                        th('Type')
                        th('Width')
                        th('Precision')

                    for field_info in self.fieldinformations.all():
                        field_info.get_html(pretty=False)

        return root_div.render()
Example #43
0
    def _write_header(self):
        tags = _get_tags_module()

        if not self.is_write_header:
            return

        if typepy.is_empty_sequence(self.headers):
            raise EmptyHeaderError("headers is empty")

        tr_tag = tags.tr()
        for header in self.headers:
            tr_tag += tags.th(MultiByteStrDecoder(header).unicode_str)

        thead_tag = tags.thead()
        thead_tag += tr_tag

        self._table_tag += thead_tag
Example #44
0
    def _write_body(self):
        tags = _get_tags_module()
        tbody_tag = tags.tbody()

        for values, value_dp_list in zip(self._table_value_matrix, self._table_value_dp_matrix):
            tr_tag = tags.tr()
            for value, value_dp, styler in zip(values, value_dp_list, self._styler_list):
                td_tag = tags.td(MultiByteStrDecoder(value).unicode_str)
                td_tag["align"] = value_dp.align.align_string

                style_tag = self.__make_style_tag(styler)
                if style_tag:
                    td_tag["style"] = style_tag

                tr_tag += td_tag
            tbody_tag += tr_tag

        self._table_tag += tbody_tag
        self._write_line(self._table_tag.render(indent=self.indent_string))
Example #45
0
    def get_html(self, pretty=True):
        """Generates html code for displaying data for this metadata element"""

        root_div = div()

        def get_th(heading_name):
            return th(heading_name, cls="text-muted")

        with root_div:
            with div(cls="custom-well"):
                strong(self.name)
                with table(cls='custom-table'):
                    with tbody():
                        with tr():
                            get_th('Variable Name')
                            td(self.variableName)
                        with tr():
                            get_th('Variable Unit')
                            td(self.variableUnit)
                        if self.noDataValue:
                            with tr():
                                get_th('No Data Value')
                                td(self.noDataValue)
                        if self.maximumValue:
                            with tr():
                                get_th('Maximum Value')
                                td(self.maximumValue)
                        if self.minimumValue:
                            with tr():
                                get_th('Minimum Value')
                                td(self.minimumValue)
                        if self.method:
                            with tr():
                                get_th('Method')
                                td(self.method)
                        if self.comment:
                            with tr():
                                get_th('Comment')
                                td(self.comment)

        return root_div.render(pretty=pretty)
Example #46
0
    def get_html(self, pretty=True):
        """Generates html code for displaying data for this metadata element"""

        root_div = div(cls="content-block")

        def get_th(heading_name):
            return th(heading_name, cls="text-muted")

        with root_div:
            with div(cls="custom-well"):
                strong(self.name)
                with table(cls='custom-table'):
                    with tbody():
                        with tr():
                            get_th('Unit')
                            td(self.unit)
                        with tr():
                            get_th('Type')
                            td(self.type)
                        with tr():
                            get_th('Shape')
                            td(self.shape)
                        if self.descriptive_name:
                            with tr():
                                get_th('Long Name')
                                td(self.descriptive_name)
                        if self.missing_value:
                            with tr():
                                get_th('Missing Value')
                                td(self.missing_value)
                        if self.method:
                            with tr():
                                get_th('Comment')
                                td(self.method)

        return root_div.render(pretty=pretty)
Example #47
0
    def get_html(self, site_number):
        """generates html code for viewing site related data"""

        root_div = div(cls="content-block")

        def get_th(heading_name):
            return th(heading_name, cls="text-muted")

        with root_div:
            with div(cls="panel panel-default"):
                with div(cls="panel-heading"):
                    with h4(cls="panel-title"):
                        site_name = "Site-{}".format(site_number)
                        if self.site_name:
                            site_name = self.site_name
                        a(site_name, data_toggle="collapse", data_parent="#accordion",
                          href="#collapse{}".format(site_number))
                with div(id="collapse{}".format(site_number), cls="panel-collapse collapse"):
                    with div(cls="panel-body"):
                        with table(cls='custom-table'):
                            with tbody():
                                with tr():
                                    get_th('Network Name')
                                    td(self.network_name)
                                with tr():
                                    get_th('Service Type')
                                    td(self.service_type)
                                with tr():
                                    get_th('Return Type')
                                    td(self.return_type)
                                with tr():
                                    get_th('Reference Type')
                                    td(self.reference_type)
                                with tr():
                                    get_th('URL')
                                    with td():
                                        a(self.url, href=self.url, target="_blank")
                                with tr():
                                    get_th('Site Name')
                                    if self.site_name:
                                        td(self.site_name)
                                    else:
                                        td("")
                                with tr():
                                    get_th('Site Code')
                                    td(self.site_code)
                                with tr():
                                    get_th('Latitude')
                                    td(self.latitude)
                                with tr():
                                    get_th('Longitude')
                                    td(self.longitude)
                                with tr():
                                    get_th('Variable Name')
                                    if self.variable_name:
                                        td(self.variable_name)
                                    else:
                                        td("")
                                with tr():
                                    get_th('Variable Code')
                                    td(self.variable_code)
                                with tr():
                                    get_th('Method Description')
                                    if self.method_description:
                                        td(self.method_description)
                                    else:
                                        td("")
                                with tr():
                                    get_th('Method Link')
                                    if self.method_link \
                                            and self.method_link.lower() != 'unknown':
                                        with td():
                                            a(self.method_link, href=self.method_link,
                                              target="_blank")
                                    elif self.method_link:
                                        td(self.method_link)
                                    else:
                                        td("")
                                with tr():
                                    get_th('Sample Medium')
                                    if self.sample_medium:
                                        td(self.sample_medium)
                                    else:
                                        td("")
                                with tr():
                                    get_th('Value Count')
                                    if self.value_count is not None:
                                        td(self.value_count)
                                    else:
                                        td("")
                                with tr():
                                    get_th('Begin Date')
                                    td(self.start_date)
                                with tr():
                                    get_th('End Date')
                                    td(self.end_date)

        return root_div
Example #48
0
def landing_page(request, page):
    content_model = page.get_content_model()
    edit_resource = page_processors.check_resource_mode(request)

    if not edit_resource:  # non-edit mode
        # get the context from hs_core
        context = page_processors.get_page_context(page, request.user, resource_edit=edit_resource,
                                                   extended_metadata_layout=None, request=request)
        extended_metadata_exists = False

        if content_model.metadata.originalcoverage:
            extended_metadata_exists = True

        context['extended_metadata_exists'] = extended_metadata_exists

        # add the original coverage context
        geom_info_for_view = {}
        geom_info = content_model.metadata.geometryinformation
        if geom_info:
            geom_info_for_view['geometryType'] = geom_info.geometryType
            geom_info_for_view['featureCount'] = geom_info.featureCount
            context['geometry_information'] = geom_info_for_view

        ori_cov_dict = {}
        ori_cov_obj = content_model.metadata.originalcoverage
        if ori_cov_obj:
            ori_cov_dict['northlimit'] = ori_cov_obj.northlimit
            ori_cov_dict['eastlimit'] = ori_cov_obj.eastlimit
            ori_cov_dict['southlimit'] = ori_cov_obj.southlimit
            ori_cov_dict['westlimit'] = ori_cov_obj.westlimit
            ori_cov_dict['projection_string'] = ori_cov_obj.projection_string
            ori_cov_dict['projection_name'] = ori_cov_obj.projection_name
            ori_cov_dict['datum'] = ori_cov_obj.datum
            ori_cov_dict['unit'] = ori_cov_obj.unit
            context['original_coverage'] = ori_cov_dict

        field_info_list = content_model.metadata.fieldinformations.all()
        field_info_list_context = []
        for field_info in field_info_list:
            field_info_dict_item = {}
            field_info_dict_item["fieldName"] = field_info.fieldName
            field_info_dict_item["fieldType"] = field_info.fieldType
            field_info_dict_item["fieldTypeCode"] = field_info.fieldTypeCode
            field_info_dict_item["fieldWidth"] = field_info.fieldWidth
            field_info_dict_item["fieldPrecision"] = field_info.fieldPrecision
            field_info_list_context.append(field_info_dict_item)
        context['field_information'] = field_info_list_context

    else:  # editing mode
        # now editing is allowed for resource specific metadata
        geom_info_for_view = {}
        geom_info = content_model.metadata.geometryinformation
        if geom_info:
            geom_info_for_view['geometryType'] = geom_info.geometryType
            geom_info_for_view['featureCount'] = geom_info.featureCount

        geom_information_form = GeometryInformationForm(initial=geom_info_for_view,
                                                        res_short_id=content_model.short_id,
                                                        allow_edit=False,
                                                        element_id=geom_info.id
                                                        if geom_info else None)

        geom_information_layout = HTML('<div class="form-group col-lg-6 col-xs-12" '
                                       'id="geometryinformation">'
                                       '{% load crispy_forms_tags %}'
                                       '{% crispy geom_information_form %}'
                                       '</div>')

        # origina coverage_form
        ori_cov_obj = content_model.metadata.originalcoverage
        ori_coverage_data_dict = {}
        if ori_cov_obj:
            ori_coverage_data_dict['projection_string'] = ori_cov_obj.projection_string
            ori_coverage_data_dict['projection_name'] = ori_cov_obj.projection_name
            ori_coverage_data_dict['datum'] = ori_cov_obj.datum
            ori_coverage_data_dict['unit'] = ori_cov_obj.unit
            ori_coverage_data_dict['northlimit'] = ori_cov_obj.northlimit
            ori_coverage_data_dict['eastlimit'] = ori_cov_obj.eastlimit
            ori_coverage_data_dict['southlimit'] = ori_cov_obj.southlimit
            ori_coverage_data_dict['westlimit'] = ori_cov_obj.westlimit

        ori_coverage_form = OriginalCoverageForm(initial=ori_coverage_data_dict,
                                                 res_short_id=content_model.short_id,
                                                 allow_edit=False,
                                                 element_id=ori_cov_obj.id
                                                 if ori_cov_obj else None)
        ori_coverage_layout = HTML('<div class="form-group col-lg-6 '
                                   'col-xs-12" id="originalcoverage"> '
                                   '{% load crispy_forms_tags %} '
                                   '{% crispy ori_coverage_form %} '
                                   '</div>')
        root_div = div(cls="col-md-12 col-sm-12 pull-left", style="margin-bottom:40px;")
        with root_div:
            legend('Field Information')
            with table(style="width: 100%;"):
                with tbody():
                    with tr(cls='row'):
                        th('Name')
                        th('Type')
                        th('Width')
                        th('Precision')

                    for field_info in content_model.metadata.fieldinformations.all():
                        field_info.get_html(pretty=False)

        ext_md_layout = Layout(geom_information_layout,
                               ori_coverage_layout,
                               HTML(root_div.render()))

        context = page_processors.get_page_context(page,
                                                   request.user,
                                                   resource_edit=edit_resource,
                                                   extended_metadata_layout=ext_md_layout,
                                                   request=request)
        context['ori_coverage_form'] = ori_coverage_form
        context['geom_information_form'] = geom_information_form

    context['edit_mode'] = edit_resource
    hs_core_context = add_generic_context(request, page)
    context.update(hs_core_context)

    return context