Example #1
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")
Example #2
0
def _common_meta(document):
    with document:
        H.attr(lang=u'en')
    with document.head:
        H.meta(charset=u'utf-8')
        H.meta(name=u'generator', content=u'HTTPolice %s' % version)
        H.style(type=u'text/css').add_raw_string(css_code)
Example #3
0
def dominate_final_page():
    """
    第四頁:感謝頁,
    目標:利用dominate寫出 enter_page 的 html並在 templates 資料夾中存成 index4.html

    分為三個區塊
    doc = dominate.document()
    with doc.head   (包含css的style;meta確保中文可以運行在utf-8下)
    with doc.body   (h1)

    最後寫入文件中(在templates資料夾中存成index4.html)
    """

    doc = dominate.document(title="thank_you_page")
    with doc.head:
        tags.meta(name='charset', content="utf-8")
        tags.style("""\
            body {
                background-color: #F9F8F1;
                color: #2C232A;
                font-family: sans-serif;
                font-size: 14;
                text-align: center;
            }
        """)

    with doc.body:
        tags.h1('Thank You!')

    fn = 'templates/index4.html'
    with open(file=fn, mode='w', encoding='utf-8') as f:
        f.write(doc.render())
    print(f)
Example #4
0
    def __init__(self, web_dir, title, refresh=0):
        """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
        """
        self.title = title
        self.web_dir = web_dir
        self.img_dir = os.path.join(self.web_dir, 'images')
        self.file_dir = os.path.join(self.web_dir, 'files')
        self.diff_dir = os.path.join(self.web_dir, 'difference')
        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.file_dir):
            os.makedirs(self.file_dir)
        if not os.path.exists(self.diff_dir):
            os.makedirs(self.diff_dir)

        self.doc = dominate.document(title=title)
        if refresh > 0:
            with self.doc.head:
                meta(http_equiv="refresh", content=str(refresh))
Example #5
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
Example #6
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)
Example #7
0
def _common_meta(document):
    with document:
        H.attr(lang=u'en')
    with document.head:
        H.meta(charset=u'utf-8')
        H.meta(name=u'generator', content=u'HTTPolice %s' % version)
        H.style(type=u'text/css').add_raw_string(css_code)
Example #8
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
Example #9
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
Example #10
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)
Example #11
0
def make_html(pixdir, route_name, results):

    title = "Pictures from %s" % route_name

    document = dominate.document(title=title)

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

    with document.body:

        with table():

            caption(route_name)

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

            for time, filename, gc, tp in results:

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

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

                with tr():

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

    print >> open("make_html.html", "w"), document
Example #12
0
    def __init__(self, web_dir, title, reflesh=0):
        self.title = title
        self.web_dir = web_dir
        if not os.path.exists(self.web_dir):
            os.makedirs(self.web_dir)

        # print(self.img_dir)

        self.doc = dominate.document(title=title)
        if reflesh > 0:
            with self.doc.head:
                meta(http_equiv="reflesh", content=str(reflesh))
Example #13
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())
Example #14
0
def dominate_enter_page():
    """
    第三頁:確認資訊頁面,對應到  @app.route('/jump')  及其函數   registerpage_run [if request.method == 'POST']
    目標:利用dominate寫出 enter_page 的 html並在 templates 資料夾中存成 index3.html

    分為三個區塊
    doc = dominate.document()
    with doc.head   (包含css的style;meta確保中文可以運行在utf-8下)
    with doc.body   (包含 6 information: name/ password/ student_id/
                    telephone_number/ school_bike_license/ bike_lock_number and a button confirm)

    最後寫入文件中(在templates資料夾中存成index3.html)
    """
    doc = dominate.document(title="entered")

    with doc.head:
        tags.meta(name='charset', content="utf-8")
        tags.style("""\
            body {
                background-color: #F9F8F1;
                color: #2C232A;
                font-family: sans-serif;
                font-size: 14;
                text-align: center;
            }
        """)

    with doc.body:
        tags.h1('welcome' + str(name_list_temp[0]))
        tags.h2('please confirm your information')
        with tags.section(cls='information check'):
            with tags.div(cls='name', style="text-align: center"):
                tags.label('your name is  ' + str(name_list_temp[0]))
            with tags.div(cls='password', style="text-align: center"):
                tags.label('your password is  ' + str(password_temp[0]))
            with tags.div(cls='student_id', style="text-align: center"):
                tags.label('your student id is  ' + str(student_id_temp[0]))
            with tags.div(cls='telephone', style="text-align: center"):
                tags.label('your telephone number is  ' + str(telephone_number_temp[0]))
            with tags.div(cls='license', style="text-align: center"):
                tags.label('the status of your bike_lice  ' + str(school_bike_license_temp[0]))
            with tags.div(cls='lock_number', style="text-align: center"):
                tags.label('your bike lock number is  ' + str(bike_lock_number_temp[0]))
            with tags.div(cls='button', style="margin:0 auto; width:250px;"):
                tags.input(type='button', value='confirm', style="width:120px; background-color:pink;",
                           onclick="location.href='http://127.0.0.1:5000/entered'")

    fn = 'templates/index3.html'
    with open(file=fn, mode='w', encoding='utf-8') as f:
        f.write(doc.render())
    print(f)
Example #15
0
def cv():
    base = Path('cv')
    with (base / 'content' / 'data.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)
                style(raw(css.read()))
            with body():
                with table(id='content') as content:
                    with tr():
                        with td(id='image', colspan=4):
                            img(src='img/header.png', alt='...')
                            div('Curriculum Vitae')
                for row in chain(
                        Basic(data['basic']).as_rows(),
                        Skills(data['skills']).as_rows(),
                        Experience(data['experience']).as_rows(),
                        Education(data['education']).as_rows()):
                    content.add(row)

    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)}'
Example #16
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))
Example #17
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('&laquo;&raquo;'))
                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)}'
Example #18
0
def dominate_homepage():
    """
    第一頁:歡迎頁面,對應到  @app.route('/')  及其函數  homepage_run()
    目標:利用dominate寫出homepage的html並在templates資料夾中存成index1.html

    分為三個區塊
    doc = dominate.document()
    with doc.head   (包含css的style;meta確保中文可以運行在utf-8下)
    with doc.body   (包含welcome words and a button)

    最後寫入文件中(在templates資料夾中存成index1.html)
    """
    doc = dominate.document(title='homepage')

    with doc.head:
        tags.meta(name='charset', content="utf-8")
        tags.style("""\
            body {
                background-color: #F9F8F1;
                color: #2C232A;
                font-family: sans-serif;
                font-size: 30;
                text-align: center;
            }
             section{
                  width: 300px;
                  height: 300px;
                  position: absolute;
                  top: 50%;
                  left: 50%;
                  overflow: auto;
                  text-align: center;
                  margin-left:-150px;
                  margin-top:-150px;
            } 
         """)

    with doc.body:

        with tags.section():
            with tags.div(cls='headline', style='font-size: 30;'):
                tags.h1('Find Your Bike')
            tags.input(type='button', value='click me', onclick="location.href='http://127.0.0.1:5000/jump'",
                       style="width:120px; background-color:pink; font-size: 14;")

    fn = 'templates/index1.html'
    with open(file=fn, mode='w', encoding='utf-8') as f:
        f.write(doc.render())
    print(f)
Example #19
0
def dominate_wrong_information_page():
    """
        第五頁:資料庫連接錯誤頁面,對應到  @app.route('/entered')  及其函數  eneter_success()
        目標:利用dominate寫出homepage的html並在templates資料夾中存成index5.html

        分為三個區塊
        doc = dominate.document()
        with doc.head   (包含css的style;meta確保中文可以運行在utf-8下)
        with doc.body   (包含 words and a button)

        最後寫入文件中(在templates資料夾中存成index5.html)
        """
    doc = dominate.document(title='error_page')

    with doc.head:
        tags.meta(name='charset', content="utf-8")
        tags.style("""\
                    body {
                        background-color: #F9F8F1;
                        color: #2C232A;
                        font-family: sans-serif;
                        font-size: 30;
                        text-align: center;
                    }
                     section{
                          width: 300px;
                          height: 300px;
                          position: absolute;
                          top: 50%;
                          left: 50%;
                          overflow: auto;
                          text-align: center;
                          margin-left:-150px;
                          margin-top:-150px;
                    } 
             """)

    with doc.body:
        with tags.section():
            with tags.div(cls='headline', style='font-size: 30;'):
                tags.h2("wrong information! please try again")
            tags.input(type='button', value='return back', onclick="location.href='http://127.0.0.1:5000/'",
                       style="width:120px; background-color:pink; font-size: 14;")

    fn = 'templates/index6.html'
    with open(file=fn, mode='w', encoding='utf-8') as f:
        f.write(doc.render())
    print(f)
Example #20
0
    def render(self, posts_per_page=25):
        pages_count = (len(self.rendered_items) + posts_per_page - 1) // posts_per_page
        page_names = ["%d.html" % i for i in range(pages_count)]

        nav_section = T.nav(
            *[T.a(str(i), href=page_names[i], target=_PAGE_FRAME) for i in range(pages_count)]
        )

        index = T.html(
            T.head(
                T.meta(charset='utf-8'),
                stylesheet(_STYLE_CSS),
                stylesheet(_NAVBAR_CSS),
                T.script(src=_JQUERY_URL),
                inline_script_from(get_resource(Path(_SELECTED_JS)))
            ),
            T.body(
                nav_section,
                T.iframe(name=_PAGE_FRAME, src=page_names[0] if pages_count > 0 else 'none', width='100%', height='100%', style='border:none')
            )
        )
        self.pages['index.html'] = index

        for page_index in range(pages_count):
            page_items = self.rendered_items[page_index * posts_per_page: (page_index + 1) * posts_per_page]
            chunk_html = T.html(
                T.head(stylesheet('page.css')),
                T.body(
                    T.div(*page_items, id=ID_CONTAINER)
                )
            )
            self.pages[page_names[page_index]] = chunk_html
Example #21
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")
Example #22
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())
Example #23
0
 def __init__(self, web_dir, title, reflesh=0):
     """Create a html file with concise elements."""
     # the title of the page
     self.title = title
     # dir to save the web page
     self.web_dir = web_dir
     # dir to save the images
     self.img_dir = os.path.join(self.web_dir, 'images')
     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)
     # create a document with given title
     self.doc = dominate.document(title=title)
     # a time interval for the document to refresh itself
     if reflesh > 0:
         with self.doc.head:
             htags.meta(http_equiv="reflesh", content=str(reflesh))
    def __init__(self, web_dir, title, refresh=0):
        """

        :param web_dir: a directory that stores the webpage
        :param title: the webpage name
        :param refresh: how often the website refresh itself
        """
        self.title = title
        self.web_dir = web_dir
        self.img_dir = os.path.join(self.web_dir, 'images')
        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)

        self.doc = dominate.document(title=title)
        if refresh > 0:
            with self.doc.head:
                meta(http_equiv="refresh", content=str(refresh))
Example #25
0
    def __init__(self, web_dir, web_subdir, title, refresh=0):
        self.title = title
        if web_subdir is not None:
            self.web_dir = os.path.join(web_dir, web_subdir)
        else:
            self.web_dir = web_dir

        if os.path.exists(self.web_dir):
            logging.warning(
                "Web directory already exists, removing: {}".format(
                    self.web_dir))
            shutil.rmtree(self.web_dir)

        file_utils.mkdir(self.web_dir)

        self.doc = dominate.document(title=title)
        if refresh > 0:
            with self.doc.head:
                meta(http_equiv="refresh", content=str(refresh))
Example #26
0
 def generate_html(self, filmlist):
     doc = dominate.document(title='Dominate your HTML')
     with doc.head:
         meta({
             "http-equiv": "Content-Type",
             "content": "text/html; charset=UTF-8"
         })
     with doc:
         with div():
             with table():
                 for url, text in filmlist:
                     with tr():
                         with td():
                             a(text, href=url, target="_blank")
     with open(self.baidufile, "w") as f:
         f.write(doc.render())
     print("========3. All finished, have a look please.========")
     webbrowser.open("file://{}".format(self.baidufile),
                     new=0,
                     autoraise=True)
Example #27
0
    def head_(self, jsData=""):
        """ The HTML <head> contents. Inserts the jsData. """
        framework = "https://unpkg.com/spectre.css/dist/spectre.min.css"
        visCSS = "https://cdnjs.cloudflare.com/ajax/libs/vis/4.16.1/vis.css"

        def css(href):
            return link(rel="stylesheet", href=href, type="text/css")

        stylesheets = [framework, visCSS, "/style.css"]

        return (
            meta(charset='UTF-8'),
            meta(name='viewport',
                 content='width=device-width',
                 initialScale=1.0), base(href="/"),
            *[css(url) for url in stylesheets],
            script(
                type="text/javascript",
                src=
                "https://cdnjs.cloudflare.com/ajax/libs/vis/4.16.1/vis-network.min.js"
            ))
Example #28
0
    def save_feed_to_html(self):
        """Creating an html file, using curent datetime as a filename"""
        logging.info('Started saving feed to html file')
        time_now = str(datetime.datetime.now())
        time_for_path = time_now[:-16] + '_' + time_now[
            -15:-13] + '-' + time_now[-12:-10] + '-' + time_now[-9:-7]
        html = dominate.document(title="HTML RSS feed")
        with html.head:
            dtags.meta(charset='utf-8')
        html += dtags.h1(self.feed_name)
        for article_number, article in enumerate(self.articles):
            html += dtags.br()

            date = article.published
            str_date = f'{date.tm_year}/{date.tm_mon}/{date.tm_mday} {date.tm_hour}:{date.tm_min}'

            html += dtags.h2(f'{article_number + 1}.  {article.title}')
            html += dtags.h3(f'   {str_date}')

            html += dtags.a(f'Link: {article.link}')
            html += dtags.br()

            with html:
                if check.internet_connection_check():
                    # if have internet access, downloading images and pasting in a html file
                    for link in article.media:
                        dtags.img(src=link['url'])
                else:
                    # if no, paste links of these images
                    dtags.a('Image links:')
                    for link_number, link in enumerate(article.media):
                        img_url = link['url']
                        dtags.a(f'{link_number + 1}. {img_url}', href=link)
            html += dtags.p(article.summary)
            html += dtags.br()
        with open('html_feeds/' + time_for_path + ' RSS_feeds.html',
                  'w') as html_file:
            html_file.write(str(html))
        logging.info('Finished saving feed to html file')
 def __init__(self, web_dir, title='Visualization', width=256, refresh=0):
     """
     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
         width (int) -- images width
         refresh (int) -- how often the website refresh itself; if 0, no refreshing
     """
     # Tile & dirs
     self._title = title
     self._web_dir = web_dir
     self._img_dir = os.path.join(self._web_dir, 'images')
     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)
     self._width = width
     # Document
     self._doc = dominate.document(title=title)
     # Refresh
     if refresh > 0:
         with self._doc.head:
             meta(http_equiv="refresh", content=str(refresh))
Example #30
0
def dominate_error_page():
    """
        第五頁:資料庫連接錯誤頁面,對應到  @app.route('/entered')  及其函數  eneter_success()
        目標:利用dominate寫出homepage的html並在templates資料夾中存成index5.html

        分為三個區塊
        doc = dominate.document()
        with doc.head   (包含css的style;meta確保中文可以運行在utf-8下)
        with doc.body   (包含 words and a button)

        最後寫入文件中(在templates資料夾中存成index5.html)
        """
    doc = dominate.document(title='error_page')

    with doc.head:
        tags.meta(name='charset', content="utf-8")
        tags.style("""\
                    body {
                        background-color: #F9F8F1;
                        color: #2C232A;
                        font-family: sans-serif;
                        font-size: 30;
                        text-align: center;
                    }
             """)

    with doc.body:
        with tags.section():
            with tags.div(cls='headline', style='font-size: 30;'):
                tags.h1('Register failed! You have registered before!')
            tags.input(type='button', value='return back', onclick="location.href='http://127.0.0.1:5000/'",
                       style="width:120px; background-color:pink; font-size: 14;")

    fn = 'templates/index5.html'
    with open(file=fn, mode='w', encoding='utf-8') as f:
        f.write(doc.render())
    print(f)
def create_html(command_line_args, news_collection, logger):
    """Creates html file"""
    news_collection = limit_news_collections(command_line_args, news_collection, logger)

    logger.info("Creating html file...")
    doc_html = dominate.document(title='RSS News')
    with doc_html.head:
        tag.meta(charset='utf-8')
    with doc_html:
        tag.h1("RSS News")
    # Internet connection checking
    internet = set_internet_flag(logger)

    for num, news in enumerate(news_collection):
        logger.info("Add html entry {}".format(num + 1))
        doc_html = create_html_news_entry(news, doc_html, internet)

    path_to_html = os.path.join(command_line_args.to_html, 'RSS News.html')
    try:
        with open(path_to_html, 'w') as html_obj:
            html_obj.write(str(doc_html))
        logger.info("HTML file is created")
    except FileNotFoundError:
        raise DirectoryError(f"There are no directory {command_line_args.to_html}")
Example #32
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)
Example #33
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
Example #34
0
    def html(self):
        "Late bind scriptage and return the html of the page"
        if hasattr(self, '_redirection'):
            return self._redirection

        if 'monitor' in executor.futures._futures:
            if executor.futures.done('monitor'):
                executor.futures.pop('monitor')
            else:
                flask.flash(executor.status)
                self.doc.head.add(
                    tags.meta(http_equiv="refresh",
                              content=f"3;{flask.request.url}"))
        self.script_list.append(f"""$(document).ready( 
                    function() {{ 
                        {" ".join(self.on_ready_scriptage)} 
                    }}); """)
        self.script_list.extend(self.scriptage)
        return str(self.doc)
Example #35
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)
Example #36
0
def hocr(records, image_name=u'', image_size=(0, 0), line_bbox=True,
         split_words=True, word_bbox=True, char_cuts=True,
         confidence_vals=True):
    """
    Merges a list of predictions and their corresponding character positions
    into an hOCR document.

    Args:
        records (iterable): List of kraken.rpred.ocr_record
        image_name (unicode): Name of the source image
        image_size (tuple): Dimensions of the source image
        line_bbox (bool): Enable writing of line bounding boxes
        split_words (bool): Split recognized line into words at
                            non-alphanumeric characters
        word_bbox (bool): Enable writing of word bounding boxes (only with
                          split_words)
        char_cuts (bool): Enable writing of character cuts (only with
                          line_bbox)
        confidence_vals (bool): Enable writing of confidence values for
                                recognition results
    """

    doc = dominate.document()

    with doc.head:
        meta(name='ocr-system', content='kraken')
        meta(name='ocr-capabilities', content='ocr_page ocr_line ocrx_word')
        meta(charset='utf-8')

    with doc:
        hocr_title = micro_hocr()
        if image_size > (1, 1):
            hocr_title.add('bbox', 0, 0, *[str(s) for s in image_size])
        if image_name:
            hocr_title.add(u'image', image_name)
        with div(cls='ocr_page', title=str(hocr_title)):
            for idx, record in enumerate(records):
                logger.debug('Adding record {} - {} to hocr'.format(idx, record.prediction))
                with span(cls='ocr_line', id='line_' + str(idx)) as line_span:
                    line_title = micro_hocr()
                    if line_bbox:
                        line_title.add('bbox', *max_bbox(record.cuts))
                    if char_cuts:
                        line_title.add('cuts',
                                       *list(delta(max_bbox(record.cuts),
                                                   record.cuts)))
                    # only add if field contains text to avoid unseemly empty
                    # titles
                    if str(line_title):
                        line_span['title'] = str(line_title)
                    if split_words:
                        logger.debug('Splitting record into words')
                        splits = regex.split(u'(\w+)', record.prediction)
                        line_offset = 0
                        # operate on pairs of non-word character strings and
                        # words. The former are encoded in ocrx_cinfo classes
                        # while the latter is adorned with ocrx_word classes.
                        for w_idx, non_word, word in zip(count(), splits[0::2],
                                                         splits[1::2]):
                            # add non word blocks only if they contain actual
                            # text
                            if non_word:
                                nw_span = span(non_word, cls='ocrx_block',
                                               id='block_' + str(idx) + '_' +
                                               str(w_idx))
                                nw = micro_hocr()
                                if word_bbox:
                                    nw.add('bbox',
                                           *max_bbox(record.cuts[line_offset:line_offset
                                                                 +
                                                                 len(non_word)]))
                                if confidence_vals:
                                    nw.add('x_conf', *[str(int(100*v)) for v in
                                                       record.confidences[line_offset:line_offset
                                                                          +
                                                                          len(non_word)]])
                                if str(nw):
                                    nw_span['title'] = str(nw)
                                line_offset += len(non_word)
                            w_span = span(word, cls='ocrx_word', id='word_' +
                                          str(idx) + '_' + str(w_idx))
                            w = micro_hocr()
                            if word_bbox:
                                w.add('bbox',
                                      *max_bbox(record.cuts[line_offset:line_offset
                                                            + len(word)]))
                            if confidence_vals:
                                w.add('x_conf', *[str(int(100*v)) for v in
                                                  record.confidences[line_offset:line_offset
                                                                     +
                                                                     len(word)]])
                            if str(w):
                                w_span['title'] = str(w)
                            line_offset += len(word)
                    else:
                        line_span.add(record.prediction)
                br()
    return doc