Ejemplo n.º 1
0
    def write_table(self):
        """
        |write_table| with HTML table format.

        :Example:
            :ref:`example-html-table-writer`

        .. note::
            - |None| is not written
        """

        tags = _get_tags_module()

        with self._logger:
            self._verify_property()
            self._preprocess()

            if typepy.is_not_null_string(self.table_name):
                self._table_tag = tags.table(id=sanitize_python_var_name(self.table_name))
                self._table_tag += tags.caption(MultiByteStrDecoder(self.table_name).unicode_str)
            else:
                self._table_tag = tags.table()

            try:
                self._write_header()
            except EmptyHeaderError:
                pass

            self._write_body()
Ejemplo n.º 2
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])
Ejemplo n.º 3
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)
Ejemplo n.º 4
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)
Ejemplo n.º 5
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)
Ejemplo n.º 6
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)
Ejemplo n.º 7
0
    def write_table(self):
        """
        |write_table| with HTML table format.
        """

        self._verify_property()
        self._preprocess()

        if dataproperty.is_not_empty_string(self.table_name):
            self._table_tag = tags.table(
                id=pathvalidate.sanitize_python_var_name(self.table_name))
            self._table_tag += tags.caption(self.table_name)
        else:
            self._table_tag = tags.table()

        self._write_header()
        self._write_body()
Ejemplo n.º 8
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()
Ejemplo n.º 9
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)
Ejemplo n.º 10
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)
 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)
Ejemplo n.º 12
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)
Ejemplo n.º 13
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)
Ejemplo n.º 14
0
    def get_html(self, site_number):
        """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 panel panel-default"):
                with div(cls="panel-heading"):
                    with h4(cls="panel-title"):
                        a(self.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')
                                    td(self.site_name)
                                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')
                                    td(self.variable_name)
                                with tr():
                                    get_th('Variable Code')
                                    td(self.variable_code)
                                with tr():
                                    get_th('Method Description')
                                    td(self.method_description)
                                with tr():
                                    get_th('Method Link')
                                    with td():
                                        a(self.method_link, href=self.method_link, target="_blank")
                                with tr():
                                    get_th('Sample Medium')
                                    td(self.sample_medium)
                                with tr():
                                    get_th('Value Count')
                                    td(self.value_count)
                                with tr():
                                    get_th('Begin Date')
                                    td(self.start_date)
                                with tr():
                                    get_th('End Date')
                                    td(self.end_date)

        return root_div
Ejemplo n.º 15
0
    def report_table(self, *args, **kwargs):
        """
        Helps create tables

        :param tuple \*args: Rows of data as tuples. Ex ('data1', 'data2', ...)
        :param str \**kwargs: Kwargs to control title, header, etc.
        :param tuple header: Kwarg The header for the table. Accepts a tuple
        :param str title: Kwarg The title of the section
        :param bool section: Kwarg Set to false to append table to previous section
        :param str header_color: Kwarg Sets the color of the header. Defaults to dark
        :param bool tindex: Kwarg Sets an index column
        :param tuple alert: Kwarg Creats a dismissable alert box. Requires a tuple. First value is color and second value is message.
        :param dict modal: Create a modal. Is a dictionary. Valid keys are button, title and content

        :return: A table object

        :raises TypeError: Raises exception if not a tuple or all lenghts are not the same
        :raises NotValidTag: If not a valid bootstrap color
        :raises TableError: When there are issues creating a table

        Example showing how to change the default theme:
            >>> r = report.report_table(('data1', 'demo1'), ('data2', 'demo2'),
            >>>                         header=('header1', 'header2'), title='demo')
        """
        if 'section' in kwargs:
            style = rng.CSSControl.sticky_section_css
        else:
            style = "padding-bottom:3; padding-top:40;"
        if 'header_color' in kwargs:
            header_color = kwargs.get('header_color')
            if header_color not in rng.HelperFunctions.valid_tags:
                raise rng.NotValidTag('Not a valid header color')
        else:
            header_color = 'dark'
        # creates optional header
        if 'header' in kwargs:
            table_header = kwargs.get('header')
        # Check to make sure it is args
        if not isinstance(args, tuple):
            raise TypeError('Not a tuple')
        # Saves length of first arg
        check_length = len(args[0])
        # Run checks agains header
        if not isinstance(table_header, tuple):
            raise TypeError('Headers are not a tuple')
        elif len(table_header) != check_length:
            raise rng.TableError('Header not the same length as data')
        # starts building the table
        with tag.div(_class="jumbotron container context reportng-table-class",
                     style=style) as c:  # padding mods
            if 'title' in kwargs:
                tag.h1(
                    kwargs.get('title'),
                    id="%s" %
                    rng.HelperFunctions.id_with_random(5, kwargs.get('title')))
            # create dismissable alert box
            if 'alert' in kwargs:
                rng.HelperFunctions.make_alert(kwargs.get('alert'))
            with tag.div(
                    _class="container",
                    style="overflow-x:auto; max-height: 70%; overflow: auto;"):
                with tag.table(
                        _class="table table-striped display nowrap table-hover",
                        style="width: 90%") as tables:
                    # Make table header
                    if table_header:
                        with tag.thead(
                                _class="table-%s" %
                                rng.HelperFunctions.color_to_tag(header_color)
                        ).add(tag.tr()):
                            if kwargs.get('tindex') == True:
                                tag.th('Index')
                            for h in range(len(table_header)):
                                tag.th(table_header[h], scope='col')
                    for r in range(len(args)):
                        with tag.tr():
                            if kwargs.get('tindex') == True:
                                tag.td(str(r + 1))
                            # Checks length of subsequent args with first arg
                            if len(args[r]) != check_length:
                                raise rng.TableError(
                                    'Length of all tuples has to be the same')
                            for t in range(len(args[r])):
                                tag.td(args[r][t])
                if 'modal' in kwargs:
                    if isinstance(kwargs.get('modal'), dict):
                        rng.HelperFunctions.make_modals(
                            kwargs.get('title').replace(' ', ''),
                            kwargs.get('modal'))
        return rng.HelperFunctions.convert_to_string(c)
Ejemplo n.º 16
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
Ejemplo n.º 17
0
def futurize_code(args=None):
    """Main program.

    Args:
        fixer_pkg: the name of a package where the fixers are located.
        args: optional; a list of command line arguments. If omitted,
              sys.argv[1:] is used.

    Returns a suggested exit status (0, 1, 2).
    """

    # Set up option parser
    parser = optparse.OptionParser(usage="futurize [options] file|dir ...")
    parser.add_option("-V", "--version", action="store_true",
                      help="Report the version number of futurize")
    parser.add_option("-a", "--all-imports", action="store_true",
                      help="Add all __future__ and future imports to each module")
    parser.add_option("-1", "--stage1", action="store_true",
                      help="Modernize Python 2 code only; no compatibility with Python 3 (or dependency on ``future``)")
    parser.add_option("-2", "--stage2", action="store_true",
                      help="Take modernized (stage1) code and add a dependency on ``future`` to provide Py3 compatibility.")
    parser.add_option("-0", "--both-stages", action="store_true",
                      help="Apply both stages 1 and 2")
    parser.add_option("-u", "--unicode-literals", action="store_true",
                      help="Add ``from __future__ import unicode_literals`` to implicitly convert all unadorned string literals '' into unicode strings")
    parser.add_option("-f", "--fix", action="append", default=[],
                      help="Each FIX specifies a transformation; default: all.\nEither use '-f division -f metaclass' etc. or use the fully-qualified module name: '-f lib2to3.fixes.fix_types -f libfuturize.fixes.fix_unicode_keep_u'")
    parser.add_option("-j", "--processes", action="store", default=1,
                      type="int", help="Run 2to3 concurrently")
    parser.add_option("-x", "--nofix", action="append", default=[],
                      help="Prevent a fixer from being run.")
    parser.add_option("-l", "--list-fixes", action="store_true",
                      help="List available transformations")
    parser.add_option("-p", "--print-function", action="store_true",
                      help="Modify the grammar so that print() is a function")
    parser.add_option("-v", "--verbose", action="store_true",
                      help="More verbose logging")
    parser.add_option("--no-diffs", action="store_true",
                      help="Don't show diffs of the refactoring")
    parser.add_option("-w", "--write", action="store_true",
                      help="Write back modified files")
    parser.add_option("-n", "--nobackups", action="store_true", default=False,
                      help="Don't write backups for modified files.")
    parser.add_option("-o", "--output-dir", action="store", type="str",
                      default="", help="Put output files in this directory "
                                       "instead of overwriting the input files.  Requires -n. "
                                       "For Python >= 2.7 only.")
    parser.add_option("-W", "--write-unchanged-files", action="store_true",
                      help="Also write files even if no changes were required"
                           " (useful with --output-dir); implies -w.")
    parser.add_option("--add-suffix", action="store", type="str", default="",
                      help="Append this string to all output filenames."
                           " Requires -n if non-empty. For Python >= 2.7 only."
                           "ex: --add-suffix='3' will generate .py3 files.")

    # Parse command line arguments
    flags = {}
    refactor_stdin = False
    options, args = parser.parse_args(args)

    if options.write_unchanged_files:
        flags["write_unchanged_files"] = True
        if not options.write:
            warn("--write-unchanged-files/-W implies -w.")
        options.write = True
    # If we allowed these, the original files would be renamed to backup names
    # but not replaced.
    if options.output_dir and not options.nobackups:
        parser.error("Can't use --output-dir/-o without -n.")
    if options.add_suffix and not options.nobackups:
        parser.error("Can't use --add-suffix without -n.")

    if not options.write and options.no_diffs:
        warn("not writing files and not printing diffs; that's not very useful")
    if not options.write and options.nobackups:
        parser.error("Can't use -n without -w")
    if "-" in args:
        refactor_stdin = True
        if options.write:
            print("Can't write to stdin.", file=sys.stderr)
            return 2
    # Is this ever necessary?
    if options.print_function:
        flags["print_function"] = True

    # Set up logging handler
    level = logging.DEBUG if options.verbose else logging.INFO
    logging.basicConfig(format='%(name)s: %(message)s', level=level)
    logger = logging.getLogger('libfuturize.main')

    if options.stage1 or options.stage2:
        assert options.both_stages is None
        options.both_stages = False
    else:
        options.both_stages = True

    avail_fixes = set()

    if options.stage1 or options.both_stages:
        avail_fixes.update(lib2to3_fix_names_stage1)
        avail_fixes.update(libfuturize_fix_names_stage1)
    if options.stage2 or options.both_stages:
        avail_fixes.update(lib2to3_fix_names_stage2)
        avail_fixes.update(libfuturize_fix_names_stage2)

    if options.unicode_literals:
        avail_fixes.add('libfuturize.fixes.fix_unicode_literals_import')

    if options.version:
        print(__version__)
        return 0
    if options.list_fixes:
        print("Available transformations for the -f/--fix option:")
        # for fixname in sorted(refactor.get_all_fix_names(fixer_pkg)):
        for fixname in sorted(avail_fixes):
            print(fixname)
        if not args:
            return 0
    if not args:
        print("At least one file or directory argument required.",
              file=sys.stderr)
        print("Use --help to show usage.", file=sys.stderr)
        return 2

    unwanted_fixes = set()
    for fix in options.nofix:
        if ".fix_" in fix:
            unwanted_fixes.add(fix)
        else:
            # Infer the full module name for the fixer.
            # First ensure that no names clash (e.g.
            # lib2to3.fixes.fix_blah and libfuturize.fixes.fix_blah):
            found = [f for f in avail_fixes
                     if f.endswith('fix_{0}'.format(fix))]
            if len(found) > 1:
                print("Ambiguous fixer name. Choose a fully qualified "
                      "module name instead from these:\n" +
                      "\n".join("  " + myf for myf in found),
                      file=sys.stderr)
                return 2
            elif len(found) == 0:
                print("Unknown fixer. Use --list-fixes or -l for a list.",
                      file=sys.stderr)
                return 2
            unwanted_fixes.add(found[0])

    extra_fixes = set()
    if options.all_imports:
        if options.stage1:
            prefix = 'libfuturize.fixes.'
            extra_fixes.add(prefix +
                            'fix_add__future__imports_except_unicode_literals')
        else:
            # In case the user hasn't run stage1 for some reason:
            prefix = 'libpasteurize.fixes.'
            extra_fixes.add(prefix + 'fix_add_all__future__imports')
            extra_fixes.add(prefix + 'fix_add_future_standard_library_import')
            extra_fixes.add(prefix + 'fix_add_all_future_builtins')
    explicit = set()
    if options.fix:
        all_present = False
        for fix in options.fix:
            if fix == 'all':
                all_present = True
            else:
                if ".fix_" in fix:
                    explicit.add(fix)
                else:
                    # Infer the full module name for the fixer.
                    # First ensure that no names clash (e.g.
                    # lib2to3.fixes.fix_blah and libfuturize.fixes.fix_blah):
                    found = [f for f in avail_fixes
                             if f.endswith('fix_{0}'.format(fix))]
                    if len(found) > 1:
                        print("Ambiguous fixer name. Choose a fully qualified "
                              "module name instead from these:\n" +
                              "\n".join("  " + myf for myf in found),
                              file=sys.stderr)
                        return 2
                    elif len(found) == 0:
                        print("Unknown fixer. Use --list-fixes or -l for a list.",
                              file=sys.stderr)
                        return 2
                    explicit.add(found[0])
        if len(explicit & unwanted_fixes) > 0:
            print("Conflicting usage: the following fixers have been "
                  "simultaneously requested and disallowed:\n" +
                  "\n".join("  " + myf for myf in (explicit & unwanted_fixes)),
                  file=sys.stderr)
            return 2
        requested = avail_fixes.union(explicit) if all_present else explicit
    else:
        requested = avail_fixes.union(explicit)
    fixer_names = (requested | extra_fixes) - unwanted_fixes

    input_base_dir = os.path.commonprefix(args)
    if (input_base_dir and not input_base_dir.endswith(os.sep)
            and not os.path.isdir(input_base_dir)):
        # One or more similar names were passed, their directory is the base.
        # os.path.commonprefix() is ignorant of path elements, this corrects
        # for that weird API.
        input_base_dir = os.path.dirname(input_base_dir)
    # if options.output_dir:
    #     input_base_dir = input_base_dir.rstrip(os.sep)
    #     logger.info('Output in %r will mirror the input directory %r layout.',
    #                 options.output_dir, input_base_dir)

    # Initialize the refactoring tool
    if future.utils.PY26:
        extra_kwargs = {}
    else:
        extra_kwargs = {
            'append_suffix': options.add_suffix,
            'output_dir': options.output_dir,
            'input_base_dir': input_base_dir,
            }

    # Remove results directory.
    if os.path.isdir(RESULTS_DIR):
        shutil.rmtree(RESULTS_DIR)
    os.mkdir(RESULTS_DIR)

    if os.path.isdir(DIFF_DIR):
        shutil.rmtree(DIFF_DIR)
    os.mkdir(DIFF_DIR)

    # We override their RefactoringTool with `FileRefactoringTool`
    rt = FileRefactoringTool(
        sorted(fixer_names), flags, sorted(explicit),
        options.nobackups, not options.no_diffs,
        **extra_kwargs)

    # Refactor all files and directories passed as arguments
    if not rt.errors:
        if refactor_stdin:
            rt.refactor_stdin()
        else:
            try:
                rt.refactor(args, options.write, None,
                            options.processes)
            except refactor.MultiprocessingUnsupported:
                assert options.processes > 1
                print("Sorry, -j isn't supported on this platform.", file=sys.stderr)
                return 1
        rt.summarize()

    # This is our own custom html reporting.
    table_body = tbody()
    remove_line_count_total = 0
    with table_body:
        for file_name, file_summary in DiffSummary.list_all():
            with tr():
                td(a(file_name, href=file_summary.href))
                td(file_summary.add_line_count, style="text-align:right")
                td(file_summary.remove_line_count, style="text-align:right")
                td(file_summary.percent_coverage, style="text-align:right")
                remove_line_count_total += file_summary.remove_line_count

    with document(title='2/3 Summary') as doc:
        h1('2/3 Summary', style='padding: 0 40px;')
        p('Total lines that need to be removed:', style='padding: 0 40px;').add(b(remove_line_count_total))
        summary_table = table(width='100%', style="padding: 20px 40px; margin: 0 auto;")
        with summary_table.add(thead()):
            with tr():
                th('File Name', style="text-align:left")
                th('Add Lines', style="text-align:right")
                th('Remove Lines', style="text-align:right")
                th('Coverage %', style="text-align:right")
            summary_table.add(table_body)

    with open('{results_dir}/summary.html'.format(results_dir=RESULTS_DIR), 'w+') as summary_file:
        summary_file.write(doc.render())

    # Write a machine readable report that can be parsed later.
    json_report = {
        'summary': {
            'remove_line_count_total': remove_line_count_total
            },
        'files': [
            {
                'file_name': file_name,
                'add_line_count': file_summary.add_line_count,
                'remove_line_count': file_summary.remove_line_count,
                'percent_coverage': file_summary.percent_coverage,
                } for file_name, file_summary in DiffSummary.list_all()
            ]
        }
    json.dump(json_report, open('{results_dir}/report.json'.format(results_dir=RESULTS_DIR), 'w+'))

    # Return error status (0 if rt.errors is zero)
    return int(bool(rt.errors))
Ejemplo n.º 18
0
def generate_html_document(trackers: List[Tracker], sequences: List[Sequence], results, storage: Storage):

    import io
    import dominate
    from dominate.tags import h1, h2, table, thead, tbody, tr, th, td, div, p, li, ol, span, style, link, script
    from dominate.util import raw

    order_classes = {1: "first", 2: "second", 3: "third"}

    def insert_figure():
        buffer = io.StringIO()
        plt.savefig(buffer, format="SVG", bbox_inches='tight', transparent=True)
        raw(buffer.getvalue())
        plt.close()

    def insert_cell(value, order):
        attrs = dict(data_sort_value=order, data_value=value)
        if order in order_classes:
            attrs["cls"] = order_classes[order]
        td(_format_value(value), **attrs)

    def add_style(name, linked=False):
        if linked:
            link(rel='stylesheet', href='file://' + os.path.join(os.path.dirname(__file__), name))
        else:
            style(_read_resource(name))

    def add_script(name, linked=False):
        if linked:
            script(type='text/javascript', src='file://' + os.path.join(os.path.dirname(__file__), name))
        else:
            with script(type='text/javascript'):
                raw("//<![CDATA[\n" + _read_resource(name) + "\n//]]>")

    logger = logging.getLogger("vot")

    legend = Legend()
    table_header, table_data, table_order = _extract_measures_table(trackers, results)
    graphs = _extract_graphs(trackers ,results, legend)

    doc = dominate.document(title='VOT report')

    linked = check_debug()

    with doc.head:
        add_style("pure.css", linked)
        add_style("report.css", linked)
        add_script("jquery.js", linked)
        add_script("table.js", linked)
        add_script("report.js", linked)

    with doc:

        h1("VOT report")

        with ol(cls="metadata"):
            li('Toolkit version: ' + version)
            li('Created: ' + datetime.datetime.now().isoformat())

        if len(table_header[2]) == 0:
            logger.debug("No measures found, skipping table")
        else:
            with table(cls="measures pure-table pure-table-horizontal pure-table-striped"):
                with thead():
                    with tr():
                        th()
                        [th(c[0].identifier, colspan=c[1]) for c in _merge_repeats(table_header[0])]
                    with tr():
                        th()
                        [th(c[0].name, colspan=c[1]) for c in _merge_repeats(table_header[1])]
                    with tr():
                        th("Trackers")
                        [th(c.abbreviation, data_sort="int" if order else "") for c, order in zip(table_header[2], table_order)]
                with tbody():
                    for tracker, data in table_data.items():
                        with tr():
                            number = legend.number(tracker.identifier)
                            with td(id="legend_%d" % number):
                                legend.figure(tracker.identifier)
                                insert_figure()
                                span(tracker.label)
                            for value, order in zip(data, table_order):
                                insert_cell(value, order[tracker] if not order is None else None)

        for experiment, experiment_graphs in graphs.items():
            if len(experiment_graphs) == 0:
                continue

            h2("Experiment {}".format(experiment.identifier), cls="experiment")

            with div(cls="graphs"):

                for title, graph in experiment_graphs:
                    with graph, div(cls="graph"):
                        p(title)
                        insert_figure()
                        

    with storage.write("report.html") as filehandle:
        filehandle.write(doc.render())
Ejemplo n.º 19
0
 def add_table(self, border=1):
     self.t = table(border=1, style='table-layout: fixed;')
     self.doc.add(self.t)
Ejemplo n.º 20
0
 def add_table(self, border=1):
     """Add table."""
     table = htags.table(border=border, style="table-layout: fixed;")
     self.doc.add(table)
     return table
    def add_images(self, ims, txts, width=400, realFlag=False):
        """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:
            for im, txt in zip(ims, txts):
                with tr():
                    with td(style="word-wrap: break-word;",
                            halign="center",
                            valign="top"):
                        with p():
                            # with a(href=os.path.join('images', link)):
                            # with a(href=os.path.join(link)):
                            #     # img(style="width:%dpx" % width, src=os.path.join('images', im))
                            img(style="width:%dpx" % width, src=im[0])
                            br()
                            p(txt[0])
                    with td(style="word-wrap: break-word;",
                            halign="center",
                            valign="top"):
                        with p():
                            # with a(href=os.path.join('images', link)):
                            # with a(href=os.path.join(link)):
                            #     # img(style="width:%dpx" % width, src=os.path.join('images', im))
                            img(style="width:%dpx" % width, src=im[1])
                            br()
                            p(txt[1])
                    if not (realFlag):
                        with td(style="word-wrap: break-word;",
                                halign="center",
                                valign="top"):
                            with p():
                                # with a(href=os.path.join('images', link)):
                                # with a(href=os.path.join(link)):
                                #     # img(style="width:%dpx" % width, src=os.path.join('images', im))
                                img(style="width:%dpx" % width, src=im[2])
                                br()
                                p(txt[2])
                    with td(style="word-wrap: break-word;",
                            halign="center",
                            valign="top"):
                        with p():
                            # with a(href=os.path.join('images', link)):
                            # with a(href=os.path.join(link)):
                            #     # img(style="width:%dpx" % width, src=os.path.join('images', im))
                            img(style="width:%dpx" % width, src=im[3])
                            br()
                            p(txt[3])

                    if len(im) > 4:
                        with td(style="word-wrap: break-word;",
                                halign="center",
                                valign="top"):
                            with p():
                                # with a(href=os.path.join('images', link)):
                                # with a(href=os.path.join(link)):
                                #     # img(style="width:%dpx" % width, src=os.path.join('images', im))
                                img(style="width:%dpx" % width, src=im[4])
                                br()
                                p(txt[4])
                    if len(im) > 5:
                        with td(style="word-wrap: break-word;",
                                halign="center",
                                valign="top"):
                            with p():
                                # with a(href=os.path.join('images', link)):
                                # with a(href=os.path.join(link)):
                                #     # img(style="width:%dpx" % width, src=os.path.join('images', im))
                                img(style="width:%dpx" % width, src=im[5])
                                br()
                                p(txt[5])
                    if len(im) > 6:
                        with td(style="word-wrap: break-word;",
                                halign="center",
                                valign="top"):
                            with p():
                                # with a(href=os.path.join('images', link)):
                                # with a(href=os.path.join(link)):
                                #     # img(style="width:%dpx" % width, src=os.path.join('images', im))
                                img(style="width:%dpx" % width, src=im[6])
                                br()
                                p(txt[6])
                    if len(im) > 7:
                        with td(style="word-wrap: break-word;",
                                halign="center",
                                valign="top"):
                            with p():
                                # with a(href=os.path.join('images', link)):
                                # with a(href=os.path.join(link)):
                                #     # img(style="width:%dpx" % width, src=os.path.join('images', im))
                                img(style="width:%dpx" % width, src=im[7])
                                br()
                                p(txt[7])
Ejemplo n.º 22
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="row", id="filetype-extra-metadata")
            with root_div_extra:
                with div(cls="col-lg-12 content-block"):
                    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
Ejemplo n.º 23
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(HTML("<div class='row'>"),
                               geom_information_layout,
                               ori_coverage_layout,
                               HTML("</div>"),
                               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
Ejemplo n.º 24
0
 def add_table(self, border=1):
     self.t = table(border=border, style="table-layout: fixed;")
     self.doc.add(self.t)
Ejemplo n.º 25
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
Ejemplo n.º 26
0
 def _add_table(self, border=1):
     self.row_image_count = 0
     self.t = tags.table(border=border, style="table-layout: fixed;")
     self.doc.add(self.t)
Ejemplo n.º 27
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
def create_html_string(COUNTERS, BALLOTLISTS, DISAGREED_INFO_DICT):
    """Creates a HTML string for generating the summary file.
    
    Accesses the following:
        COUNTERS['ballots_processed']
        COUNTERS['styles_detected']
        COUNTERS['matched_ballots']
        COUNTERS['non_matched_ballots']
        COUNTERS['blank_ballots']
        list of ballot OVERVOTED_BALLOTS
        list of ballot DISAGREED_BALLOTS
            accesses ballot pdf files per precinct and ballot_id
        DISAGREE_INFO_DICT is keyed by ballot_id which provides dict of contests providing error information
                f"{config_dict['RESOURCES_PATH']}{config_dict['DISAGREEMENTS_PATHFRAG']}{ballot.ballotdict['precinct']}/{ballot.ballotdict['ballot_id']}.pdf")

        list STYLES
            style.style_num
            style.number
            style.build_from_count
        files style_summary = glob.glob(f"{config_dict['RESOURCES_PATH']}{config_dict['STYLES_PATHFRAG']}{style.code}.html")[0]
        list VOTES_RESULTS   (results for each contest)
            result_contest['contest_name']
            result_contest['selections']
            result_contest['vote_for']
            result_contest['question']
            result_contest['total_ballots']
            result_contest['total_votes']
            result_contest['undervote']
            result_contest['overvote']
    """
    script_abs_path = os.path.abspath('assets/copy_to_clipboard.js')
    version = utils.show_version()
    doc = dominate.document(title='Audit Engine version: ' + version)
    with doc.head:
        link(
            rel='stylesheet',
            href=
            'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css',
            integrity=
            "sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T",
            crossorigin="anonymous",
        )
        script(type='text/javascript', src=script_abs_path)

    with doc:
        with div(cls='container'):
            with div(cls='jumbotron'):
                h1('Audit Engine: {version} - vote records summary'.format(
                    version=version))
                build_time = datetime.datetime.now(datetime.timezone.utc)
                p(f'Summary built at: {build_time.strftime("%Y-%m-%d %H:%M:%S")}',
                  cls='lead')
            with table(cls='table table-striped'):
                with tbody():
                    with tr():
                        th('Number of ballots processed')
                        td(COUNTERS['ballots_processed'])
                    with tr():
                        th('Number of different ballot types')
                        td(COUNTERS['styles_detected'])
                    with tr():
                        th('Number of ballots matching the CVR results')
                        td(COUNTERS['matched_ballots'])
                    with tr():
                        th('Number of ballots not matching the CVR results')
                        td(COUNTERS['non_matched_ballots'])
                    with tr():
                        th('Number of completely blank ballots')
                        td(COUNTERS['blank_ballots'])
                    with tr():
                        th('Number of overvotes')
                        td(COUNTERS['overvoted_ballots'])
                    with tr():
                        th('Number of disagreements')
                        td(COUNTERS['disagreed_ballots'])
            with div(cls='my-4'):
                h2('Styles')
            with table(cls='table table-striped'):
                with thead():
                    with tr():
                        th('Style code', scope="col")
                        th('Style number', scope="col")
                        th('Based on number of ballots', scope="col")
                        th('Built at', scope="col")
                with tbody():
                    for style in STYLES:
                        with tr():
                            utc_time = datetime.datetime.utcfromtimestamp(
                                style.timestamp)
                            style_summary = glob.glob(
                                f"{config_dict['RESOURCES_PATH']}{config_dict['STYLES_PATHFRAG']}{style.code}.html"
                            )[0]
                            td(
                                a(style.style_num,
                                  href=os.path.realpath(style_summary),
                                  target="_blank"))
                            td(style.number)
                            td(style.build_from_count)
                            td(f'{utc_time.strftime("%Y-%m-%d %H:%M:%S")}')
            # Tables with contests results:
            with div(cls='my-4'):
                h2('Contests results')
            for result_contest in VOTES_RESULTS:
                contest_name = result_contest['contest_name']
                selections = result_contest['selections']
                vote_for = result_contest['vote_for']
                question = result_contest['question']
                with div(cls='my-4'):
                    h5(f'Contest results "{contest_name}" (vote for {vote_for}):'
                       )
                    if question:
                        h6(f'Question "{question}"')
                with table(cls='table table-striped'):
                    with thead():
                        with tr():
                            th('#', scope="col")
                            th('Candidate', scope="col")
                            th('Votes', scope="col")
                            th('%', scope="col")
                    with tbody():
                        for index, candidate_name in enumerate(
                                sort_option_names(selections.keys())):
                            try:
                                total_votes = result_contest['total_votes']
                                percent = round(
                                    (selections[candidate_name] / total_votes)
                                    * 100, 2)
                            except ZeroDivisionError:
                                percent = 0.0
                            with tr():
                                th(index + 1, scope="row")
                                td(candidate_name)
                                td(candidate_name)
                                td(f'{percent}%')
                with table(cls='table table-striped'):
                    with tbody():
                        with tr():
                            th('Total number of ballots')
                            td(result_contest['total_ballots'])
                        with tr():
                            th('Number of votes')
                            td(result_contest['total_votes'])
                        with tr():
                            th('Number of undervotes')
                            td(result_contest['undervote'])
                        with tr():
                            th('Number of overvotes')
                            td(result_contest['overvote'])
            # Table with overvotes:
            with div(cls='my-4'):
                h2('Ballots with overvotes:')
            with table(cls='table table-striped'):
                with thead():
                    with tr():
                        th('#', scope="col")
                        th('Precinct / Contest name', scope="col")
                        th('Ballot file / Ballot and CVR status', scope="col")
                        th('Overvotes / Contest validation status',
                           scope="col")
                with tbody():
                    dirpath = DB.dirpath_from_dirname('overvotes')
                    for index, ballot_id in enumerate(
                            BALLOTLISTS['overvoted_ballots']):
                        filepathlist = glob.glob(
                            f"{dirpath}**/{ballot_id}i.pdf", recursive=True)
                        if not filepathlist: continue
                        filepath = filepathlist[0]
                        with tr():
                            th(index + 1, scope="row")
                            td('')
                            with td():
                                ballot_image_filepath = os.path.abspath(
                                    filepath)
                                a(ballot_id,
                                  href=ballot_image_filepath,
                                  target="_blank")
                            td('')


#                        overvotes_contests = list(
#                            filter(
#                                lambda x: (x.contest_ballot_status == STATUS_DICT['overvote']) or
#                                (x.contest_cvr_status == STATUS_DICT['overvote']), ballot.ballotdict['contests']))
#                        for contest in overvotes_contests:
#                            with tr():
#                                td()
#                                td(contest.contest_name)
#                                td(f"{contest.contest_ballot_status} / {contest.contest_cvr_status}")
#                                td(contest.contest_validation if contest.contest_validation is not None else '')
# Table with blank ballots:
            with div(cls='my-4'):
                h2('Blank Ballots:')
            with table(cls='table table-striped'):
                with thead():
                    with tr():
                        th('#', scope="col")
                        th('Precinct / Contest name', scope="col")
                        th('Ballot file / Ballot and CVR status', scope="col")
                        th('Overvotes / Contest validation status',
                           scope="col")
                with tbody():
                    dirpath = DB.dirpath_from_dirname('blank_ballots')
                    for index, ballot_id in enumerate(
                            BALLOTLISTS['blank_ballots']):
                        filepathlist = glob.glob(f"f{dirpath}{ballot_id}i.pdf",
                                                 recursive=True)
                        if not filepathlist:
                            continue
                        filepath = filepathlist[0]
                        with tr():
                            th(index + 1, scope="row")
                            td('')
                            with td():
                                ballot_image_filepath = os.path.abspath(
                                    filepath)
                                a(ballot_id,
                                  href=ballot_image_filepath,
                                  target="_blank")
                            td('')
            # Table with disagreements:
            with div(cls='my-4'):
                h2('Ballots with disagreements:')
            with table(cls='table table-striped'):
                with thead():
                    with tr():
                        th('#', scope="col")
                        th('Ballot file', scope="col")
                        th('Disagreement Details', scope="col")
                with tbody():
                    dirpath = DB.dirpath_from_dirname('disagreements')
                    for index, ballot_id in enumerate(
                            BALLOTLISTS['disagreed_ballots']):
                        filepathlist = glob.glob(
                            f"{dirpath}**/{ballot_id}i.pdf", recursive=True)
                        if not filepathlist: continue
                        filepath = filepathlist[0]
                        with tr():
                            th(index + 1, scope="row")
                            with td():
                                ballot_image_filepath = os.path.abspath(
                                    filepath)
                                a(ballot_id,
                                  href=ballot_image_filepath,
                                  target="_blank")
                            td(
                                raw(f"<pre>{DISAGREED_INFO_DICT[ballot_id]}</PRE>"
                                    ))
    return doc