Exemplo n.º 1
0
 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 report_head(doc):
    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",
        )
        link(
            rel='stylesheet',
            href='https://use.fontawesome.com/releases/v5.7.0/css/all.css',
            integrity=
            'sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ',
            crossorigin="anonymous",
        )
        script(
            src="https://code.jquery.com/jquery-3.4.1.slim.min.js",
            integrity=
            "sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n",
            crossorigin="anonymous")
        script(
            src=
            "https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js",
            integrity=
            "sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6",
            crossorigin="anonymous")
Exemplo n.º 3
0
def add_head(doc):
    doc_head = doc.add(tags.head())
    with doc_head:
        tags.meta(charset='utf-8')
        tags.title('Man')
        tags.link(rel='stylesheet', href='styles.css')
    return doc
Exemplo n.º 4
0
def site():
    base = Path('website')
    with (base/'content'/'index.toml').open() as toml, \
         (base/'style'/'index.css').open() as css:
        data = loads(toml.read())

        with html(lang='en') as document:

            with head():
                meta(charset='utf-8')
                meta(name='description',
                     content=f'{SHARED.info.person_name} (engineer|designer)')
                meta(name='keywords', content=','.join(SHARED.meta.keywords))
                meta(name='author', content=f'{SHARED.info.person_name}')
                title(SHARED.info.person_name)
                link(rel='shortcut icon',
                     type='image/x-icon',
                     href='favicon.ico')
                link(rel='icon', type='image/x-icon', href='favicon.ico')
                style(raw(css.read()))
                script(src='website/js/anim.js')
                script(src='website/js/index.js')

            with body():
                _block('engineer', data['engineer'])
                _block('designer', data['designer'])
                with div(id='handler'):
                    div(raw('«»'))
                script('main();', type='text/javascript')

    copyright = comment(f'Copyright (C) 2015 - {datetime.now().year} '
                        f'{SHARED.info.person_name}. '
                        'All rights reserved.')
    return f'<!DOCTYPE html>{copyright}{document.render(pretty=False)}'
Exemplo n.º 5
0
    def get_html_string(style: Style) -> document:
        """Creates a HTML string for generating the summary file."""
        utc_time = datetime.datetime.utcfromtimestamp(style.timestamp)
        style_attributes = [
            ('code', style.code),
            ('number', style.number),
            ('precinct', style.precinct),
            ('built at', f'{utc_time.strftime("%Y-%m-%d %H:%M:%S")}'),
            ('built from number of ballots', style.build_from_count),
        ]

        script_abs_path = os.path.abspath('assets/copy_to_clipboard.js')
        version = utils.show_version()
        doc = 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} - style 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 div(cls='col pl-3 mt-1') as style_details_column:
                    for style_key, style_value in style_attributes:
                        style_details_column.add(
                            StyleSummary.get_details_row(
                                style_key, str(style_value)))
                h3('Contests', cls='mb-0 mt-1')
                with div(cls='col pl-3') as contest_details_column:
                    for style_contest in style.contests:
                        contest_details_column.add(
                            StyleSummary.get_contest_details(style_contest))
                h3('Built from ballots', cls='mb-3 mt-1')
                with div(cls='col pl-3'):
                    with div(cls='row flex-wrap') as images_column:
                        for ballot_id in style.build_from_ballots:
                            images = StyleSummary.get_ballot_images_path(
                                ballot_id, style.code)
                            images_column.add(
                                StyleSummary.get_ballot_images_div(
                                    ballot_id, images))
                h3('Style weighted images', cls='mb-3 mt-1')
                with div():
                    for image in StyleSummary.get_style_images(style.code):
                        a(img(src=os.path.basename(image),
                              cls='img-thumbnail',
                              alt='File not found'),
                          href=image)
        return doc
Exemplo n.º 6
0
    def __init__(self, title, css='splendor'):
        self.doc = dominate.document(title=title)
        self.has_widgets = False
        self.has_tables = False

        with self.doc.head:
            link(rel='stylesheet', href=Journal.css[css], type='text/css')

            # bokeh css/js
            link_href, js_src = bu.get_bokeh_src()
            link(rel='stylesheet', href=link_href, type="text/css")
            script(type='text/javascript', src=js_src)

            # css to center the bokeh plots
            style("""
            div.bk-grid {
                margin: auto;
                width: 50%;
            }

            div.bk-plot-layout {
                margin: auto;
                width: 50%;
            }

            div.bk-root {
                margin: auto;
                width: 50%;
            }

            div.bk-canvas-wrapper {
                margin: auto;
                width: 50%;
            }
            """)
Exemplo n.º 7
0
 def _link_css(self, css):
     if os.path.exists(f"static/{css}"):
         tags.link(rel="stylesheet",
                   type="text/css",
                   href=url_for('static', filename=css))
     elif css.startswith('http'):
         tags.link(rel="stylesheet", type="text/css", href=css)
Exemplo n.º 8
0
def write_head(doc: dominate.document):
    """
    Write head for HTML document
    :param doc: Dominate document
    """
    with doc.head:
        tags.link(rel='stylesheet', href='style.css')
Exemplo n.º 9
0
def makeHtml(path, fileName, sitename, authorname, usecss, usejs):
    doc = dominate.document(title=sitename)

    with doc.head:
        if (usecss.lower() == "y"):
            link(rel='stylesheet', href='style.css')
        if (usejs.lower() == "y"):
            script(type='text/javascript', src='script.js')
        with meta():
            attr(author=authorname)

    with doc:
        with div(id='header').add(ol()):
            for i in ['home', 'about', 'contact']:
                li(a(i.title(), href='/%s.html' % i))

        with div():
            attr(cls='body')
            p('Lorem ipsum..')

    if not os.path.exists("./" + path):
        os.makedirs("./" + path)

    f = open("./" + path + "/" + fileName, 'w+')
    f.write(str(doc))
    f.close()

    if (usejs.lower() == "y"):
        if not os.path.exists("./" + sitename + "/js"):
            os.makedirs("./" + sitename + "/js")
    if (usecss.lower() == "y"):
        if not os.path.exists("./" + sitename + "/css"):
            os.makedirs("./" + sitename + "/css")
Exemplo n.º 10
0
def createDoc(calendar):
    doc = document(title=calendar.title)  # use calendar.title
    with doc.head:
        meta(charset="utf-8")
        link(rel='stylesheet',
             href="{}.css".format(os.path.basename(
                 calendar.outputBase)))  # add CSS file
    return doc
def main(argv):
  # Authenticate and construct service.
  service, flags = sample_tools.init(
      argv,
      'androidpublisher',
      'v2',
      __doc__,
      __file__,
      parents=[argparser],
      scope='https://www.googleapis.com/auth/androidpublisher')

  # Process flags and read their values.
  package_name = flags.package_name

  try:

    edit_request = service.edits().insert(body={}, packageName=package_name)
    result = edit_request.execute()
    edit_id = result['id']

    apks_result = service.edits().apks().list(
        editId=edit_id, packageName=package_name).execute()

    version_codes = [apk['versionCode'] for apk in apks_result['apks']]

    doc = dominate.document(title="Build Up The Base! Changelog")
    with doc.head:
        tags.script(type='text/javascript', src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js')
        tags.link(rel='stylesheet', href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css')
        tags.script(type='text/javascript', src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js')
        tags.script("""
        $(function(){
            $('#change_log').accordion();
        });
        """,type='text/javascript')

    with doc:
        with tags.div(id="change_log"):
            for version in version_codes[::-1]:
                listings_result = service.edits().apklistings().list(
                        editId=edit_id, packageName=package_name, apkVersionCode=version
                    ).execute()

                tags.h3("VERSION %s" % version, id="version_%s"%version)
                with tags.div():
                    if 'listings' in listings_result:
                        for line in  listings_result['listings'][0]['recentChanges'].splitlines():
                            tags.div(line)
                    else:
                        tags.div("No listing found")

    print doc

  except client.AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
Exemplo n.º 12
0
def report(job, report):
    """Generate a report.html with analysis and timelines from given jobs."""
    jobs = job

    today = datetime.datetime.now().strftime("%Y-%m-%d")
    doc = dominate.document(title='Build Stats - {}'.format(today))
    with doc.head:
        dt.link(
            rel='stylesheet',
            href=
            'https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/3.0.1/github-markdown.min.css'
        )
        dt.meta(name='viewport', content='width=device-width, initial-scale=1')

    # Create <article>...</article> according to sindresorhus/github-markdown-css
    article = dt.article(cls='markdown-body')
    doc += article

    with article:
        dt.h1('Marathon Loop Build Stats ({})'.format(today))

    # Generate report for each job.
    for job in jobs:
        j = JenkinsJob.load(job)

        loop = asyncio.get_event_loop()
        tests = loop.run_until_complete(j.unique_fails()).to_html()
        errors = loop.run_until_complete(j.unique_errors()).to_html()

        f = io.BytesIO()
        fail_statuses = ['FAILED', 'REGRESSION']
        loop = asyncio.get_event_loop()
        df = loop.run_until_complete(j.test_dataframe())

        ts = df.groupby(level=0).agg({
            'status':
            lambda x: x.isin(fail_statuses).any(),
            'timestamp':
            'max'
        })

        plt.figure(figsize=(20, 3))
        c = ts.status.map({True: 'xkcd:light red', False: 'xkcd:light blue'})
        plt.bar(x=ts.timestamp, height=1, width=0.01, color=c, align='edge')
        plt.xlim([ts.timestamp.min(), ts.timestamp.max()])
        plt.savefig(f, format='svg')

        with article:
            dt.h2('Marathon {}'.format(job))
            dt.div(dominate.util.raw(errors))
            dt.div(dominate.util.raw(tests))
            dt.div(dominate.util.raw(f.getvalue().decode('utf-8')))

    with open(report, "w") as report_file:
        print(doc, file=report_file)
Exemplo n.º 13
0
def generateHtml():
    with open(path.join(current_dir, '../changelog/', 'storage.json'),
              'r') as f:
        data = json.load(f)[::-1]

    doc = document(title='Changelog - lkellar.org')

    articles = []

    with doc.head:
        tags.link(rel='stylesheet', href='style.css')
        tags.meta(charset="UTF-8")
        tags.meta(name="description",
                  content="A log of all changes made on lkellar.org")
        tags.meta(name="viewport",
                  content="width=device-width, initial-scale=1")
        tags.link(rel="alternate",
                  title="Changelog Feed",
                  type="application/json",
                  href="https://lkellar.org/changelog/feed.json")

    with doc:
        with tags.nav().add(tags.ol()):
            with tags.li():
                tags.a("Home", href="../")
            tags.li("Changelog")

        with tags.main():
            tags.h1('Changelog')
            for entry in data:
                tags.hr()
                article_content = tags.article()

                with article_content:
                    tags.h2(
                        f'{entry["title"]} - {entry["date"].split("T")[0]}',
                        id=f'{entry["title"]} - {entry["date"]}'.replace(
                            ' ', ''.lower()))

                    list_content = tags.ul()
                    with list_content:
                        for line in entry['items']:
                            line = urls.sub(r'<a href="\2">\1</a>', line)
                            tags.li(raw(line))

                articles.append((f'{entry["title"]} - {entry["date"]}'.replace(
                    ' ', ''.lower()), list_content.render(), entry["date"],
                                 entry['title']))

    with open(path.join(current_dir, '../changelog/', 'index.html'), 'w') as f:
        f.write(doc.render())

    generateFeed(articles)
Exemplo n.º 14
0
    def __init__(self, web_dir, title=None, refresh=0, overwrite=True, base_url='~/www', inverted=False):
        """Initialize the HTML classes
        Parameters:
            web_dir (str) -- a directory that stores the webpage. HTML file will be created at <web_dir>/index.html; images will be saved at <web_dir/images/
            title (str)   -- the webpage name
            refresh (int) -- how often the website refresh itself; if 0; no refreshing
        """
        if title is None:
            title = web_dir.split('/')[-1]

        self.title = title

        self._url = web_dir
        self.web_dir = web_dir

        if base_url is not None:
            self.web_dir = os.path.expanduser(base_url) + self.web_dir

        self.img_dir = os.path.join(self.web_dir, 'images')
        self.image_dir = self.img_dir
        self.video_dir = os.path.join(self.web_dir, 'videos')
        self.overwrite = overwrite
        if not os.path.exists(self.web_dir):
            os.makedirs(self.web_dir)
        if not os.path.exists(self.img_dir):
            os.makedirs(self.img_dir)
        if not os.path.exists(self.video_dir):
            os.makedirs(self.video_dir)

        self.doc = dominate.document(title=title)
        with self.doc.head:
            link(rel='stylesheet', href='/css/main.css')
            css = """
                table { border-collapse: collapse; border: 1px solid #ccc; margin: auto !important; table-layout: fixed; margin-bottom: 10px; }
                th, span { font-family: monospace; }
                td { word-wrap: break-word; padding: 5px; }
                caption { text-align: center; font-weight: 600; }
                h1, h2, h3 { text-align: center; font-weight: normal; }
                html, body { font-size: 18px; }
                """
            if inverted:
                css += """
                html, body { background-color: #111; color: #eee; }
                """
            style(css)
            meta(charset='utf-8')

        if refresh > 0:
            with self.doc.head:
                meta(http_equiv="refresh", content=str(refresh))
Exemplo n.º 15
0
def open_html_doc(name, letter=None):
    html_doc = dominate.document(title=u"מילון הראיה")
    html_doc['dir'] = 'rtl'
    with html_doc.head:
        with tags.meta():
            tags.attr(charset="utf-8")
        with tags.meta():
            tags.attr(name="viewport", content="width=device-width, initial-scale=1")

        tags.script(src="jquery/dist/jquery.min.js")
        tags.link(rel='stylesheet', href='bootstrap-3.3.6-dist/css/bootstrap.min.css')
        tags.link(rel='stylesheet', href='style.css')
        tags.script(src="bootstrap-3.3.6-dist/js/bootstrap.min.js")
        tags.link(rel='stylesheet', href="bootstrap-rtl-3.3.4/dist/css/bootstrap-rtl.css")
        tags.link(rel='stylesheet', href='html_demos-gh-pages/footnotes.css')
        tags.script(src="milon.js")
        tags.script(src="html_demos-gh-pages/footnotes.js")
        tags.script(src="subjects_db.json")




    html_doc.footnote_ids_of_this_html_doc = []
    html_doc.name = name
    if letter:
        html_doc.letter = letter
        html_doc.section = html_docs_l[-1].section
    else:
        html_doc.section = name

    html_doc.index = len(html_docs_l) + 1
    with html_doc.body:
        with tags.div():
            tags.attr(cls="container-fluid")
            # TODO: call page_loaded to update saved URL also in other links
            tags.script("page_loaded('%s.html')" % html_doc.index)

            with tags.div():
                tags.attr(cls="fixed_top_left", id="menu_bar")
                with tags.div():
                    with tags.button(type="button"):
                        tags.attr(id="search_icon_button", type="button", cls="btn btn-default")
                        with tags.span():
                            tags.attr(cls="glyphicon glyphicon-search")
                    with tags.span():
                        tags.attr(cls="dropdown")
                        with tags.button(type="button", cls="btn btn-primary") as b:
                            tags.attr(href="#") #, cls="dropdown-toggle")
                            with tags.span():
                                tags.attr(cls="glyphicon glyphicon-menu-hamburger")
                                # b['data-toggle'] = "dropdown"
                        with tags.ul():
                            tags.attr(cls="dropdown-menu dropdown-menu-left scrollable-menu")





    return html_doc
Exemplo n.º 16
0
def dump_html_standalone(snippets, fname, webpage_style, include_banner,
                         include_vernums, html_assets, html_classes):
    from dominate import tags, document
    from dominate.util import raw
    from . import GENERATOR
    from .core import SerAPI
    from .html import gen_banner, wrap_classes, ASSETS
    from .pygments import HTML_FORMATTER

    doc = document(title=fname)
    doc.head.add(tags.meta(charset="utf-8"))
    doc.head.add(tags.meta(name="generator", content=GENERATOR))
    doc.set_attribute("class", "alectryon-standalone")

    for css in ASSETS.ALECTRYON_CSS:
        doc.head.add(tags.link(rel="stylesheet", href=css))
    for link in (ASSETS.IBM_PLEX_CDN, ASSETS.FIRA_CODE_CDN):
        doc.head.add(raw(link))
    for js in ASSETS.ALECTRYON_JS:
        doc.head.add(tags.script(src=js))

    html_assets.extend(ASSETS.ALECTRYON_CSS)
    html_assets.extend(ASSETS.ALECTRYON_JS)

    pygments_css = HTML_FORMATTER.get_style_defs('.highlight')
    doc.head.add(tags.style(pygments_css, type="text/css"))

    cls = wrap_classes(webpage_style, *html_classes)
    root = doc.body.add(tags.article(cls=cls))
    if include_banner:
        root.add(raw(gen_banner(SerAPI.version_info(), include_vernums)))
    for snippet in snippets:
        root.add(snippet)

    return doc.render(pretty=False)
Exemplo n.º 17
0
def create_page_index():
    doc = dominate.document(title="Phone alignments")
    lexicon = load_lexicon()

    with doc.head:
        T.meta(**{'content': 'text/html;charset=utf-8', 'http-equiv': 'Content-Type'})
        T.meta(**{'content': 'utf-8', 'http-equiv': 'encoding'})
        T.link(rel='stylesheet', href='../style.css')
        T.script(
            src="https://code.jquery.com/jquery-3.4.1.min.js",
            integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=",
            crossorigin="anonymous",
        )
        T.script(type='text/javascript', src='../script.js')

    with doc:
        T.p("""
            The web-pages linked below show alignments of phones with lip movement.
            The data is a subset of 2000 utterances from the Grid corpus.
            We picked a selection of phones and for each of them we randomly selected at most 128 pairs.
        """)

        with T.ul():
            for k, g in itertools.groupby(SELECTED_PHONES, key=lambda w: w[0]):
                with T.li():
                    for i in g:
                        T.a(i, href=i + "/index.html")

        T.p("""Mean duration (s) of each phone:""")
        T.pre("""
AA 0.154
AE 0.066
AH 0.060
AO 0.143
AW 0.277
AY 0.142
EH 0.091
EY 0.124
IH 0.068
IY 0.113
OW 0.123
UW 0.152
            """, style="font-family: Courier")

    path = "www/index.html"
    with open(path, "w") as f:
        f.write(doc.render())
Exemplo n.º 18
0
    def create_page(self):
        # Open plots directory
        if not os.path.isdir(self.get_output('plots')):
            os.mkdir(self.get_output('plots'))

        # Create HTML page
        self.doc = dom.document(title='BBPipe plots page')
        with self.doc.head:
            dtg.link(rel='stylesheet', href='style.css')
            dtg.script(type='text/javascript', src='script.js')
        with self.doc:
            dtg.h1("Pipeline outputs")
            dtg.h2("Contents:", id='contents')
            lst = dtg.ul()
            lst += dtg.li(dtg.a('Bandpasses', href='#bandpasses'))
            lst += dtg.li(dtg.a('Coadded power spectra', href='#coadded'))
            lst += dtg.li(dtg.a('Null tests', href='#nulls'))
            lst += dtg.li(dtg.a('Likelihood', href='#like'))
Exemplo n.º 19
0
def create_mainpage_html(local, url_list, path, web_title):
    _html = dmtags.html(style="background-color:#fcfbeb;")
    _head, _body = _html.add(dmtags.head(dmtags.title(web_title)),
                             dmtags.body(cls="main_page"))
    with _head:
        dmtags.comment("The page is genarated on {} by Ein".format(
            time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
        dmtags.meta(charset="utf-8",
                    name="viewport",
                    content="width=device-width, initial-scale=1")
        dmtags.link(
            href="https://fonts.googleapis.com/css?family=Noto+Sans+JP:500",
            rel="stylesheet")
        dmtags.link(
            href=
            "https://cdnjs.cloudflare.com/ajax/libs/milligram/1.3.0/milligram.min.css",
            rel="stylesheet")
        dmtags.link(href="https://rawcdn.githack.com/c892836a/python_for_fun/"
                    "b2fa53022b0ae5a26d6f140c38b860a210c21040/css/custom.css",
                    rel="stylesheet")
        dmtags.link(
            href="https://lh3.googleusercontent.com/S__tM5EYqZDFLuv1uPG" +
            "mlZTTLLyNAbUvljzDH8-S0Pxq2nA9fnFF3SwU0w0wF8PlMu_hv3WhLMdlFodKbQ=s0",
            rel="shortcut icon",
            type="image/vnd.microsoft.icon")
    main_div = _body.add(
        dmtags.div(
            style=
            "text-align:center; font-family: 'Noto Sans JP', sans-serif; font-size:36px;"
        ))

    with main_div:
        _p1 = dmtags.p(style="color:#470000;")
        for url in url_list:
            _p2 = dmtags.p(style="font-size:20px;")
            with _p2:
                dmtags.a(url[0], href="{}".format(url[1]))
        with _p1:
            text("{}".format(web_title))

    # create html file
    if local:
        os.chdir(path)
        os.chdir(os.pardir)
        with open("{}.html".format(web_title), "w", encoding='utf8') as f:
            f.write("<!DOCTYPE html>\n")
            f.write(_html.render())

    else:
        with open("{}\\{}.html".format(path, web_title), "w",
                  encoding='utf8') as f:
            f.write("<!DOCTYPE html>\n")
            f.write(_html.render())
def get_cmpcvr_doc(cmpcvr_df: pd.DataFrame) -> dominate.document:
    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(
            src="https://code.jquery.com/jquery-3.4.1.slim.min.js",
            integrity=
            "sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n",
            crossorigin="anonymous")
        script(
            src=
            "https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js",
            integrity=
            "sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6",
            crossorigin="anonymous")
    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')
            get_summary_table(cmpcvr_df)
            with table(cls='table table-hover'):
                with thead():
                    with tr():
                        th('#', scope="col")
                        th('Ballot ID', scope="col")
                        th('Style', scope="col")
                table_body = tbody()
                table_body += mount_ballots_to_table(cmpcvr_df)

    return doc
Exemplo n.º 21
0
def add_head_style(this_urlpath=""):
    """Adds <link> tags for style files, assuming <head> context."""

    tags.meta(charset="utf-8")
    tags.meta(name="viewport", content="width=device-width, initial-scale=1.0")

    emoji = urls.link(this_urlpath, "NotoColorEmoji.ttf")
    tags.style(f"""
        @font-face {{
            font-family: 'Noto Color Emoji';
            src: local('Noto Color Emoji'), url({emoji}) format("truetype");'
        }}
    """)

    tags.link(
        rel="icon",
        type="image/png",
        sizes="32x32",
        href=urls.link(this_urlpath, "favicon-32x32.png"),
    )
    tags.link(
        rel="icon",
        type="image/png",
        sizes="16x16",
        href=urls.link(this_urlpath, "favicon-16x16.png"),
    )
    tags.link(
        rel="stylesheet",
        type="text/css",
        href=urls.link(this_urlpath, "style.css"),
    )
    tags.script(src=urls.link(this_urlpath, "video.js"))
    tags.script(src="https://kit.fontawesome.com/7e1cde4d00.js",
                crossorigin="anonymous")
Exemplo n.º 22
0
 def generateHtmlView(self):
     log.info("Generating HTML view")
     #lets remove the HTML file if present
     if os.path.exists(HTML_PATH) == False:
         os.mkdir(HTML_PATH)
         os.mkdir(HTML_PATH + "css/")
     rawfilepath = HTML_PATH + "index.html"
     if os.path.exists(HTML_PATH + "css/") == False:
         os.mkdir(HTML_PATH + "css/")
     copyfile('processor/lib/ui/html/css/styles.css',
              'processor/data/html/css/styles.css')
     indexdoc = dominate.document(title="Torbay Slack Chats")
     list_subfolders = [
         f.name for f in os.scandir(CHANNELS_PATH) if f.is_dir()
     ]
     with indexdoc.head:
         link(rel='stylesheet', href='css/styles.css')
     with indexdoc:
         # Iterate through a loop and create the list of channels
         h3('Channels list')
         log.info("Creating Channels list page")
         for ch in list_subfolders:
             log.debug(f"Creating Channel entry for {ch}")
             chdisplay = '#' + ch
             chlink = ch + ".html"
             with a(href=chlink):
                 with div(chdisplay):
                     attr(cls='channels')
     log.debug(indexdoc)
     self.updateRawFile(path=rawfilepath, msg=str(indexdoc))
     log.info("Generation of index.html completed")
     # Next step is create the html file for each channel
     for cpage in list_subfolders:
         fpath = HTML_PATH + cpage + ".html"
         chdoc = self.renderChannelPage(cpage)
         self.updateRawFile(path=fpath, msg=str(chdoc))
Exemplo n.º 23
0
 def __init__(self, _title, file=None, data=None):
     self.file = file
     self.data = data
     self.html = tags.html(lang='en')
     self.head = self.html.add(tags.head())
     self.head.add(tags.meta(charset='utf-8'))
     self.head.add(tags.title(_title))
     self.head.add(tags.link(rel='stylesheet', href='styles.css'))
     self.body = self.html.add(tags.body())
     self.paragraph = None
     self.div_header = None
     self.div_subheader = None
     self.date = None
     self.program = None
     self.name_page = None
     self.iterator = None
     self.indent = 0
     self.rs = None
Exemplo n.º 24
0
    def __init__(self, *args, \
            bootstrap_url='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6', \
            jquery_url='https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js',
            static_folder=None,
            **kwargs):

        super().__init__(**kwargs)
        self.navbar = None

        self.meta = self.head.add(
            meta(
                name='viewport',
                content='width=device-width, initial-scale=1.0'
            )
        )
        self.head.add(comment('Latest compiled and minified CSS'))
        if static_folder is not None:
            bootstrap_url = static_folder

        self.head.add(
            link(
                rel='stylesheet',
                href=bootstrap_url + '/css/bootstrap.min.css'
            ),
        )
        self.content = self.body.add(Div(id='content'))
        self.scripts = self.body.add(Div(id='scripts'))
        self.scripts.add(comment('jQuery library'))

        if static_folder is not None:
            jquery_url = static_folder + '/js/jquery.min.js'

        self.scripts.add(
            script(src=jquery_url)
        )
        self.scripts.add(comment('Latest compiled JavaScript'))
        self.scripts.add(
            script(src=bootstrap_url + '/js/bootstrap.min.js')
        )

        self.add(*args)
Exemplo n.º 25
0
    def html(self):
        """ Method to get the `dominate` HTML of the page. This HTML needs to be
        rendered.

        Returns:
            dominate.document: HTML document corresponding to the page.
        """
        doc = dominate.document(title=self.title)

        # Add favicon
        if self.favicon is not None:
            with doc.head:
                link(rel='icon', href=self.favicon)

        # Add external files (Skin)
        if self.skin is not None:
            with doc.head:
                for ref in self.skin.libs:  # Libs
                    link(rel='stylesheet', crossorigin='anonymous', href=ref)

                for ref in self.skin.fonts:  # Fonts
                    link(rel='stylesheet', type='text/css', href=ref)

                if self.skin.rules != "":
                    style(raw(self.skin.rules))

        # Add Widgets HTML to the page
        main_div = div(cls="container")
        for w in self.widgets:
            main_div.add(w.html())
            main_div.add(br())
        doc.add(main_div)

        # Add Javascript code to the page
        js_str = "\n\n".join([a.js() for a in self.ajax()])
        if js_str != '':
            doc.add(script(src=JQUERY_CDN))
            doc.add(script(raw(js_str + "\n\n" + COMMON_JS)))

        return doc
Exemplo n.º 26
0
def link_(lk):
    return dom.link(rel="stylesheet", type="text/css", href=lk)
Exemplo n.º 27
0
def getHTML(title,
            info=None,
            body=None,
            style=None,
            state=None,
            theme=None,
            icon=None):
    """Provide HTML object

    :param str title: short name of the notification, e.g.: server error
    :param str info: some short description if needed, e.g.: It looks like the server is not responding
    :param body: it can be string or dominate tag object, e.g.:
                 from dominate import tags as dom
                 return getHTML('server error', body=dom.pre(dom.code(result['Message']))
    :param str style: additional css style if needed, e.g.: '.card{color:red;}'
    :param int state: response state code, if needed, e.g.: 404
    :param str theme: message color theme, the same that in bootstrap 5, e.g.: 'warning'
    :param str icon: awesome icon name, e.g.: 'users'

    :return: str -- HTML document
    """
    html = document("DIRAC - %s" % title)

    # select the color to the state code
    if state in [400, 401, 403, 404]:
        theme = theme or "warning"
    elif state in [500]:
        theme = theme or "danger"
    elif state in [200]:
        theme = theme or "success"

    # select the icon to the theme
    if theme in ["warning", "warn"]:
        theme = "warning"
        icon = icon or "exclamation-triangle"
    elif theme == "info":
        icon = icon or "info"
    elif theme == "success":
        icon = icon or "check"
    elif theme in ["error", "danger"]:
        theme = "danger"
        icon = icon or "times"
    else:
        theme = theme or "secondary"
        icon = icon or "flask"

    # If body is text wrap it with tags
    if body and isinstance(body, six.string_types):
        body = dom.pre(
            dom.code(traceback.format_exc() if body == "traceback" else body),
            cls="mt-5")

    try:
        diracLogo = collectMetadata(ignoreErrors=True).get("logoURL", "")
    except Exception:
        diracLogo = ""

    # Create head
    with html.head:
        # Meta tags
        dom.meta(charset="utf-8")
        dom.meta(name="viewport",
                 content="width=device-width, initial-scale=1")
        # Favicon
        dom.link(rel="shortcut icon",
                 href="/static/core/img/icons/system/favicon.ico",
                 type="image/x-icon")
        # Provide awesome icons
        # https://fontawesome.com/v4.7/license/
        dom.script(
            src=
            "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/js/all.min.js"
        )
        # Enable bootstrap 5
        # https://getbootstrap.com/docs/5.0/getting-started/introduction/
        # https://getbootstrap.com/docs/5.0/about/license/
        dom.link(
            rel="stylesheet",
            integrity=
            "sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC",
            href=
            "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css",
            crossorigin="anonymous",
        )
        dom.script(
            src=
            "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js",
            integrity=
            "sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM",
            crossorigin="anonymous",
        )
        # Provide additional css
        style = ".card{transition:.3s;}.card:hover{transform:scale(1.03);}" + (
            style or "")
        dom.style(style)

    # Create body
    with html:
        # Background image
        dom.i(
            cls="position-absolute bottom-0 start-0 translate-middle-x m-5 fa "
            "fa-%s text-%s" % (icon, theme),
            style="font-size:40vw;z-index:-1;",
        )

        # A4 page with align center
        with dom.div(
                cls=
                "row vh-100 vw-100 justify-content-md-center align-items-center m-0"
        ):
            with dom.div(cls="container", style="max-width:600px;") as page:
                # Main panel
                with dom.div(cls="row align-items-center"):
                    # Logo
                    dom.div(dom.img(src=diracLogo, cls="card-img px-2"),
                            cls="col-md-6 my-3")
                    # Information card
                    with dom.div(cls="col-md-6 my-3"):

                        # Show response state number
                        if state and state != 200:
                            dom.div(dom.h1(
                                state,
                                cls="text-center badge bg-%s text-wrap" %
                                theme),
                                    cls="row py-2")

                        # Message title
                        with dom.div(cls="row"):
                            dom.div(dom.i(cls="fa fa-%s text-%s" %
                                          (icon, theme)),
                                    cls="col-auto")
                            dom.div(title, cls="col-auto ps-0 pb-2 fw-bold")

                        # Description
                        if info:
                            dom.small(dom.i(cls="fa fa-info text-info"))
                            dom.small(info, cls="ps-1")

            # Add content
            if body:
                page.add(body)

    return html.render()
Exemplo n.º 28
0
                        action="store_true")
    args = parser.parse_args()

    with open("data/script.js", "r", encoding="utf-8") as js, \
            open("data/style.css", "r", encoding="utf-8") as css:
        script = "\n" + js.read() + "\n"
        style = "\n" + css.read() + "\n"

    with open(args.verification_profile, "r") as f:
        contrast = jsonpickle.decode(f.read())

    doc = document(title='Comparison of smart cards')

    with doc.head:
        if args.exclude_style_and_scripts:
            tags.link(rel="stylesheet", href="style.css")
            tags.script(type="text/javascript", src="script.js")
        else:
            tags.style(raw(style))
            tags.script(raw(script), type="text/javascript")

    with doc:

        tags.button("Back to Top",
                    onclick="backToTop()",
                    id="topButton",
                    cls="floatingbutton")
        intro_div = tags.div(id="intro")
        with intro_div:
            tags.h1("Verification of " + contrast.prof_name + " against " +
                    contrast.ref_name)
Exemplo n.º 29
0
                        help="Path to html file",
                        default="tmp.html")
    parser.add_argument("--print",
                        action="store_true",
                        help="Prints html doc as string")
    parser.add_argument("--shuffle",
                        action="store_true",
                        help="Shuffle images")
    parser.add_argument("--max_img_size", help="Limit image size")
    args = parser.parse_args()

    doc = dominate.document("my doc")
    with doc.head:
        dtags.link(
            rel="stylesheet",
            href=
            "https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/2.10.0/github-markdown.css",
        )
        dtags.link(
            rel="stylesheet",
            href=
            "https://www.rocq.inria.fr/cluster-willow/yhasson/markdown-reports/css/perso-git-markdown.css",
        )

    all_images = []

    if args.split == "val":
        split_suffix = "validation"
    else:
        split_suffix = args.split
Exemplo n.º 30
0
def stylesheet(path: str) -> T.link:
    return T.link(rel='stylesheet', href=path)
Exemplo n.º 31
0
import dominate
from dominate import tags as dtags

doc = dominate.document(title="TKP")

with doc.head:
    dtags.link(rel="stylesheet", href="style.css", type="text/css")
    with open("gtag.html", "r") as gtag:
        content = gtag.read()
    # print(content)
    dominate.util.raw(content)

with doc:
    with dtags.div(id='header').add(dtags.ol()):
        for i in ['home', 'about', 'contact']:
            dtags.li(dtags.a(i.title(), href='/%s.html' % i))

    with dtags.div():
        dtags.attr(cls='body')
        dtags.p('Lorem ipsum..')

print(doc)
Exemplo n.º 32
0
    def __init__(self, config):
        self.config = config

        env = jinja2.Environment(
                  loader=jinja2.FileSystemLoader(self.config['templates_dir']),
                  trim_blocks=True)
        self.script = env.get_template(self.config['js_file']).render(**self.config)

        self.document = dominate.document(title=self.config['project_name'])
        self.document['lang'] = 'en'

        self.images = []
        for image_file in os.listdir(self.config['images_dir']):
            dir_image_file = os.path.join(self.config['images_dir'], image_file)
            if os.path.isfile(dir_image_file):
                src = '{}/{}'.format(self.config['images_route'], image_file)
                alt = os.path.splitext(
                          image_file.capitalize()
                              .replace('-', ' ')
                              .replace('_', ' '))[0]
                self.images.append((src, alt))
        self.images.sort(key=lambda x: x[1])

        with self.document.head:
            tags.meta(charset='utf-8')
            tags.meta(
                name='viewport',
                content='width=device-width, initial-scale=1, shrink-to-fit=no')
            # Bootstrap CSS.
            tags.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')
            # Fonts.
            tags.link(
                rel='stylesheet',
                href='https://fonts.googleapis.com/css?family=Dancing+Script&display=swap')

        with self.document:
            self.noscript()

            with tags.script():
                util.text(self.script, escape=False)

            with tags.div(id='root'):
                with tags.div(cls='container'):
                    with tags.div(cls='row mb-3 mt-3'):
                        with tags.div(cls='col'):

                            with tags.div(cls='card'):
                                with tags.div(cls='card-body'):
                                    with tags.h1(cls='display-5', style="font-family: 'Dancing Script', cursive;"):
                                        with tags.span(cls='text-capitalize'):
                                            util.text(self.config['project_name'])

                                    with tags.p(cls='lead'):
                                        util.text('Use machine learning to classify flowers! The ')
                                        tags.a('fast.ai library', href='https://docs.fast.ai')
                                        util.text(' was used to ')
                                        tags.a('train', href='https://github.com/nkaretnikov/resnet-flowers')
                                        util.text(' a ')
                                        tags.a('residual', href='https://arxiv.org/pdf/1512.03385.pdf')
                                        util.text(' ')
                                        tags.a('neural network', href='http://cs231n.github.io/convolutional-networks')
                                        util.text(' on the ')
                                        tags.a('Flower Color Images', href='https://www.kaggle.com/olgabelitskaya/flower-color-images')
                                        util.text(' dataset to recognize the classes below.')

                                    tags.hr(cls='my-4')

                                    with tags.div(cls='container'):
                                        with tags.div(cls='row mb-1'):
                                            for src, alt in self.images:
                                                with tags.div(cls='col-6 col-sm-4 col-md-3 col-lg-2'):
                                                    self.image(src=src, alt=alt)

                    with tags.div(cls='row mb-1'):
                        with tags.div(cls='col-md-9 col-lg-7 col-xl-6'):
                            self.upload_form()

                    with tags.div(cls='row mb-3'):
                        with tags.div(cls='col-md-9 col-lg-7 col-xl-6'):
                            self.url_form()

            # Optional JavaScript for Bootstrap.
            tags.script(
                src='https://code.jquery.com/jquery-3.3.1.slim.min.js',
                integrity='sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo',
                crossorigin='anonymous')
            tags.script(
                src='https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js',
                integrity='sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1',
                crossorigin='anonymous')
            tags.script(
                src='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js',
                integrity='sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM',
                crossorigin='anonymous')

            # Show the filename when using 'custom-file'.
            tags.script(
                src='https://cdn.jsdelivr.net/npm/bs-custom-file-input/dist/bs-custom-file-input.min.js',
                integrity='sha384-wbycNUwFmhRaoqw8zOxtEdIA5kWW1MUAV4bXEfNNOk0e5HmG3AaNRvOHFjWNAAQb',
                crossorigin='anonymous')
            with tags.script():
                util.text('$(document).ready(function () { bsCustomFileInput.init() })')
Exemplo n.º 33
0
 def css(href):
     return link(rel="stylesheet", href=href, type="text/css")
Exemplo n.º 34
0
 def head(self) -> html_tag:
     h = head()
     h.add(script(src="/giotto-statics/main.js", defer=True))
     h.add(script(src="https://unpkg.com/[email protected]"))
     h.add(link(href="/giotto-statics/styles.css", rel="stylesheet"))
     return h
Exemplo n.º 35
0
def _doc(title, css=None, scripts=None):
    d = document(title=title)
    with d.head:
        t.meta(name='viewport', content='width=device-width, initial-scale=1')
        t.link(href=settings.k_static_url + 'css/main.css', rel='stylesheet')
    return d