Ejemplo n.º 1
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)
Ejemplo n.º 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)
Ejemplo n.º 3
0
def close_html_doc(html_doc):
    with html_doc.body.children[-1]:
        assert html_doc.body.children[-1]['class'] == 'container-fluid'
        with tags.div(id="search_modal"):
            tags.attr(cls="modal fade")


    with html_doc:
        # add footnotes content of this section:
        with tags.ol(id="footnotes"):
            for (id) in html_doc.footnote_ids_of_this_html_doc:
                footnote = word_doc_footnotes.footnotes_part.notes[id + 1]
                assert footnote.id == id
                htmler.add_footnote_to_output(footnote.paragraphs)

        # add placeholder for searching
        tags.comment("search_placeholder")

    place_holder = "<!--search_placeholder-->"
    with open("input_web/stub_search.html", 'r') as file:
        search_html = file.read()

    html_doc_name = html_doc.index
    name = "debug_%s.html" % html_doc_name
    with open("output/" + name, 'w') as f:
        f.write(html_doc.render(pretty=True).encode('utf8'))
    replace_in_file("output/" + name, place_holder, search_html)

    name = "%s.html" % html_doc_name
    with open("output/" + name, 'w') as f:
        f.write(html_doc.render(pretty=False).encode('utf8'))
        print "Created ", name
    replace_in_file("output/" + name, place_holder, search_html)
Ejemplo n.º 4
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")
Ejemplo n.º 5
0
def close_html_doc(html_doc):
    with html_doc.body.children[-1]:
        assert html_doc.body.children[-1]['class'] == 'container-fluid'
        with tags.div(id="search_modal"):
            tags.attr(cls="modal fade")

    with html_doc:
        # add footnotes content of this section:
        with tags.ol(id="footnotes"):
            for (id) in html_doc.footnote_ids_of_this_html_doc:
                footnote = word_doc_footnotes.footnotes_part.notes[id + 1]
                assert footnote.id == id
                htmler.add_footnote_to_output(footnote.paragraphs)

        # add placeholder for searching
        tags.comment("search_placeholder")

    place_holder = "<!--search_placeholder-->"
    with open("input_web/stub_search.html", 'r') as file:
        search_html = file.read()

    html_doc_name = html_doc.index
    name = "debug_%s.html" % html_doc_name
    with open("output/" + name, 'w') as f:
        f.write(html_doc.render(inline=False).encode('utf8'))
    replace_in_file("output/" + name, place_holder, search_html)

    name = "%s.html" % html_doc_name
    with open("output/" + name, 'w') as f:
        f.write(html_doc.render(inline=True).encode('utf8'))
        print "Created ", name
    replace_in_file("output/" + name, place_holder, search_html)
Ejemplo n.º 6
0
def create_doc(my_date=""):
    doc = document(title="My favorite page")
    with doc:
        with div():
            attr(cls="body")
            p("lorem ipsum")
            p(f"{my_date}")
    return doc
Ejemplo n.º 7
0
def subject(html_doc, type, text):
    clean_text = clean_name(text.strip())
    new_subject_l = subjects_db.get(clean_text, [])
    subject_id = calc_subject_id(text.strip(), len(new_subject_l))
    new_subject_l.append((text.strip(), html_doc.section, "%s.html#%s" % (html_doc.index, subject_id)))
    subjects_db[clean_text] = new_subject_l

    with tags.span(text, id=subject_id):
        tags.attr(cls=type)
Ejemplo n.º 8
0
def subject(html_doc, type, text):
    clean_text = clean_name(text.strip())
    new_subject_l = subjects_db.get(clean_text, [])
    subject_id = calc_subject_id(text.strip(), len(new_subject_l))
    new_subject_l.append((text.strip(), html_doc.section,
                          "%s.html#%s" % (html_doc.index, subject_id)))
    subjects_db[clean_text] = new_subject_l

    with tags.span(text, id=subject_id):
        tags.attr(cls=type)
Ejemplo n.º 9
0
def _render_known(obj):
    """Render an instance of one of the :data:`httpolice.known.classes`."""
    text = printable(str(obj))
    cite = known.citation(obj)
    if cite:
        with H.a(text, href=cite.url):
            title = known.title(obj, with_citation=True)
            if title:
                H.attr(title=title)
    else:
        text_node(text)
Ejemplo n.º 10
0
def _render_known(obj):
    """Render an instance of one of the :data:`httpolice.known.classes`."""
    text = printable(str(obj))
    cite = known.citation(obj)
    if cite:
        with H.a(text, href=cite.url):
            title = known.title(obj, with_citation=True)
            if title:
                H.attr(title=title)
    else:
        text_node(text)
Ejemplo n.º 11
0
def _render_known(obj):
    cls = type(obj).__name__
    text = printable(six.text_type(obj))
    cite = known.citation(obj)
    if cite:
        elem = H.a(text, _class=cls, href=cite.url, target=u'_blank')
    else:
        elem = H.span(text, _class=cls)
    title = known.title(obj, with_citation=True)
    if title:
        with elem:
            H.attr(title=title)
Ejemplo n.º 12
0
def add_footnote_to_output(paragraphs):
    with tags.li():
        for (para) in paragraphs:
            for (run) in para.runs:
                style = footer.get_style(run)
                if style == "bolded":
                    with tags.span(run.text):
                        tags.attr(cls="sub-subject_small")
                else:
                    with tags.span(run.text):
                        tags.attr(cls="definition_small")
            tags.br()
Ejemplo n.º 13
0
def _render_known(obj):
    """Render an instance of one of the :data:`httpolice.known.classes`."""
    cls = type(obj).__name__
    text = printable(six.text_type(obj))
    cite = known.citation(obj)
    if cite:
        elem = H.a(text, _class=cls, href=cite.url, target=u'_blank')
    else:
        elem = H.span(text, _class=cls)
    title = known.title(obj, with_citation=True)
    if title:
        with elem:
            H.attr(title=title)
Ejemplo n.º 14
0
def list_notices(buf):
    """Render the list of all notices to the file-like `buf`."""
    title = u'HTTPolice notices'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.body:
        H.attr(_class=u'notices-list')
    with document:
        H.h1(title)
        placeholder = Placeholder()
        for id_ in sorted(notice.all_notices.keys()):
            _notice_to_html(notice.all_notices[id_],
                            placeholder,
                            with_anchor=True)
    buf.write(document.render().encode('utf-8'))
Ejemplo n.º 15
0
 def _make_table_row(self, vid):
     with tags.tr():
         try:
             tags.attr()
             tags.td(str(vid.create_date))
             tags.td(vid.series.name)
             tags.td(
                 tags.a(vid.name,
                        href=url_for(self.play_endpoint,
                                     series=vid.series.name,
                                     video=vid.name),
                        onclick="shift_edit(event, this)"))
             tags.td(f"{int(vid.duration/60)} mins")
         except Exception as e:
             print(f"Removing corrupt video {vid.name}!")
             vid.delete()
Ejemplo n.º 16
0
def list_notices(buf):
    """Render the list of all notices to the file-like `buf`."""
    title = u'HTTPolice notices'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.body:
        H.attr(_class=u'notices-list')
    with document:
        H.h1(title)
        H.p(u'This is the list of all notices produced by ',
            H.a(u'HTTPolice', href=homepage, target='_self'),
            u' version ', version, u'.')
        H.p(u'See also the ',
            H.a(u'HTTPolice manual', href=u'index.html', target='_self'), u'.')
        placeholder = Placeholder()
        for id_ in sorted(notice.all_notices.keys()):
            _notice_to_html(notice.all_notices[id_], placeholder,
                            with_anchor=True)
    buf.write(document.render().encode('utf-8'))
Ejemplo n.º 17
0
def list_notices(buf):
    """Render the list of all notices to the file-like `buf`."""
    title = u'HTTPolice notices'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.body:
        H.attr(_class=u'notices-list')
    with document:
        H.h1(title)
        H.p(u'This is the list of all notices produced by ',
            H.a(u'HTTPolice', href=homepage, target='_self'), u' version ',
            version, u'.')
        H.p(u'See also the ',
            H.a(u'HTTPolice manual', href=u'index.html', target='_self'), u'.')
        placeholder = Placeholder()
        for id_ in sorted(notice.all_notices.keys()):
            _notice_to_html(notice.all_notices[id_],
                            placeholder,
                            with_anchor=True)
    buf.write(document.render().encode('utf-8'))
Ejemplo n.º 18
0
 def __init__(self, catalog, **kwargs):
     super().__init__("Import a series to the Catalog")
     # Form list from the unlisted series of the catalog
     # That is a list of vimeo folders that are not
     # present as a VideoSeries object in mongodb
     us = list(catalog.unlisted_series())
     # get the names associated with the vimeo folders
     usn = [x['name'] for x in us]
     # Stringify the unlisted series dictionary data because both name and
     # data elements of the SelectField choice list
     us = [str(x) for x in us]
     with self.content:
         tags.attr(style=g30c70)
         tags.label("Choose from existing vimeo folders: ")
         with tags.select(name="serselect", type='text'):
             for opt, name in zip(usn, us):
                 tags.option(opt, value=name)
         tags.label("First recorded:")
         tags.input(_class="post_date",
                    type="date",
                    name="postdate",
                    value=f"{datetime.date.today().isoformat()}")
Ejemplo n.º 19
0
    def add_videos(self, vids, txts, links, width=400, hidden_tag="hidden"):
        """add images to the HTML file

        Parameters:
            vids (str list)   -- a list of image paths
            txts (str list)  -- a list of image names shown on the website
            links (str list) --  a list of hyperref links; when you click an image,
            it will redirect you to a new page
        """
        self.t = table(border=1, style="table-layout: fixed;")  # Insert a table
        self.doc.add(self.t)
        colors = ["red", "blue", "gold", "salman"]
        with self.t:
            with tr():
                for vid, txt, link in zip(vids, txts, links):
                    td_style = "word-wrap: break-word; width:{}px".format(width)
                    with td(style=td_style, halign="center", valign="top"):
                        with p():
                            vid_path = str(vid)
                            if vid_path == hidden_tag:
                                p_style = "font-weight: bold; width:{}px;"
                                p_style = p_style.format(width * 3)
                                p("hidden video", style=p_style)
                            else:
                                with a(href=str(link)):
                                    with video():
                                        attr(controls="controls")
                                        source(src=vid_path, type="video/mp4")
                            br()
                            rows = txt.split("<br>")
                            for idx, row in enumerate(rows):
                                color = colors[idx % len(colors)]
                                bold_tag = "<b>"
                                if not row.startswith(bold_tag):
                                    s_style = "color:{};".format(color)
                                else:
                                    s_style = "color:black; font-weight: bold;"
                                    row = row[len(bold_tag):]
                                span(row, style=s_style)
Ejemplo n.º 20
0
def html_report(exchanges, buf):
    """Generate an HTML report with check results.

    :param exchanges:
        An iterable of :class:`~httpolice.Exchange` objects.
        They must be already processed by :func:`~httpolice.check_exchange`.

    :param buf:
        The file (or file-like object) to which the report will be written.
        It must be opened in binary mode (not text).

    """
    # We don't want to hold the entire report in memory before printing it,
    # because that would mean unbounded memory growth with more input.
    # But Dominate obviously doesn't have a streaming mode, so we do this
    # manually. We create our document, but instead of the actual exchanges,
    # we insert a separator string that allows us to split it into a prologue
    # and an epilogue.
    separator = u'---- CUT HERE ----'

    title = u'HTTPolice report'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.head:
        H.script(type=u'text/javascript').add_raw_string(js_code)
    with document.body:
        H.attr(_class=u'report')
    with document:
        H.h1(title)
        H.hr()
        text_node(separator)

    (prologue, epilogue) = document.render().split(separator)

    buf.write(prologue.encode('utf-8'))
    for div in _generate_exchange_divs(exchanges):
        buf.write(div.render().encode('utf-8'))
    buf.write(epilogue.encode('utf-8'))
Ejemplo n.º 21
0
def html_report(exchanges, buf):
    """Generate an HTML report with check results.

    :param exchanges:
        An iterable of :class:`~httpolice.Exchange` objects.
        They must be already processed by :func:`~httpolice.check_exchange`.

    :param buf:
        The file (or file-like object) to which the report will be written.
        It must be opened in binary mode (not text).

    """
    # We don't want to hold the entire report in memory before printing it,
    # because that would mean unbounded memory growth with more input.
    # But Dominate obviously doesn't have a streaming mode, so we do this
    # manually. We create our document, but instead of the actual exchanges,
    # we insert a separator string that allows us to split it into a prologue
    # and an epilogue.
    separator = u'---- CUT HERE ----'

    title = u'HTTPolice report'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.head:
        H.script(type=u'text/javascript').add_raw_string(js_code)
    with document.body:
        H.attr(_class=u'report')
    with document:
        H.h1(title)
        H.hr()
        text_node(separator)

    (prologue, epilogue) = document.render().split(separator)

    buf.write(prologue.encode('utf-8'))
    for div in _generate_exchange_divs(exchanges):
        buf.write(div.render().encode('utf-8'))
    buf.write(epilogue.encode('utf-8'))
Ejemplo n.º 22
0
def html_report(exchanges, buf):
    """Generate an HTML report with check results.

    :param exchanges:
        An iterable of :class:`~httpolice.Exchange` objects.
        They must be already processed by :func:`~httpolice.check_exchange`.

    :param buf:
        The file (or file-like object) to which the report will be written.
        It must be opened in binary mode (not text).

    """
    title = u'HTTPolice report'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.head:
        H.script(type=u'text/javascript').add_raw_string(js_code)
    with document.body:
        H.attr(_class=u'report')
    with document:
        H.h1(title)
        _render_exchanges(exchanges)
    buf.write(document.render().encode('utf-8'))
Ejemplo n.º 23
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))
Ejemplo n.º 24
0
def regular(type, text):
    if type in ['footnote', 'footnote_recurrence']:
        with tags.a("(%s)" % text.strip()):
            tags.attr(cls="ptr")
    else:
        if "\n" in text:
            print "New:", text
        if u"°" in text:
            href = re.sub(u"°", "", text)
            href = re.sub(u"־", " ", href)
            with tags.span(tags.a(text, href="#"+href)):
                tags.attr(cls=type)
        else:
            with tags.span(text):
                tags.attr(cls=type)
Ejemplo n.º 25
0
def regular(type, text):
    if type in ['footnote', 'footnote_recurrence']:
        with tags.a("(%s)" % text.strip()):
            tags.attr(cls="ptr")
    else:
        if "\n" in text:
            print "New:", text
        if u"°" in text:
            href = re.sub(u"°", "", text)
            href = re.sub(u"־", " ", href)
            with tags.span(tags.a(text, href="#" + href)):
                tags.attr(cls=type)
        else:
            with tags.span(text):
                tags.attr(cls=type)
Ejemplo n.º 26
0
def flash_messages(messages=None,
                   container=False,
                   dismiss='alert-dismissible'):
    if container:
        wrap = tags.div(cls='container flashed-messages')
        row = wrap.add(tags.div(cls='row'))
        col = row.add(tags.div(cls='col-md-12'))
    else:
        wrap = col = tags.div()

    for cat, msg in messages:
        if cat == 'message':
            cat = 'dark'

        with col:
            with tags.div(Markup(msg)):
                tags.attr(cls=f'alert alert-{cat} {dismiss}')
                if dismiss:
                    with tags.button():
                        tags.attr(cls='close')
                        tags.attr(data_dismiss='alert')
                        tags.span(Markup('&times;'))

    return wrap
Ejemplo n.º 27
0
            for i, dist in enumerate(dists):
                if i != 0:
                    text(' | ')
                a(dist, href='#%s' % dist, _class='mono')

            text(' — ')
            text('direct access: ')
            a('dists', href='dists/', _class='mono')
            text(' | ')
            a('pool', href='pool/', _class='mono')

            text(' — ')
            text('freshness scale: ')
            for i in range(5):
                span('    ', _class='hot%d' % (i + 1))

    for dist in dists:
        with doc.add(table()):
            with tr():
                attr(id=dist)
                th('Distribution: %s' % dist, colspan=4, _class='distribution')
            with tr():
                th(raw('Package<br>name'), _class='col1')
                th(raw('Newest<br>versions'), _class='col2')
                th(raw('Newest<br>debs'), _class='col3')
                th(raw('Older<br>versions'), _class='col4')
            render_dist_html(dist)
            br()

    print(doc)
Ejemplo n.º 28
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)
Ejemplo n.º 29
0
def fix_links(html_docs_l):
    # fix outbound links
    print "Fixing links"
    for (doc) in html_docs_l:
        for (child) in doc.body.children[0].children:
            if 'definition' in child.attributes.get('class', ()):
                href = ""
                try:
                    href = child.children[0].attributes.get("href")
                except AttributeError as e:
                    pass

                # it's a link - try to update it
                if href:
                    # first, strip it of weird chars
                    try:
                        href = clean_name(href)

                        updated = False
                        if update_values_for_href(child, href):
                            updated = True
                        else:
                            if href[0] in (u"ה", u"ו", u"ש", u"ב", u"כ", u"ל",
                                           u"מ"):
                                updated = update_values_for_href(
                                    child, href[1:])
                        if not updated:
                            # failed to update - it's not a real link...
                            update_href_no_link(child)

                    except Exception as e:
                        pass
                        print e, "Exception of HREF update", href
                        #TODO - investigate why it happens? (it's a single corner case, I think)

    def sorter(html_doc):
        if html_doc.name in [
                u"ערכים כלליים",
        ]:
            return "FIRST"
        if html_doc.name in [
                u"נספחות",
        ]:
            return u"תתתתתתתתתת"  #last
        else:
            return html_doc.name

    # update sections menu
    for (doc) in html_docs_l:
        letters_l = []

        # content_menu = doc.body.children[0].children[1].children[0].children[0].children[-1].children[0].children[1]
        content_menu = doc.body.children[0].children[1].children[0].children[
            1].children[-1]
        assert content_menu[
            'class'] == 'dropdown-menu dropdown-menu-left scrollable-menu'

        with content_menu:
            with tags.li():
                tags.a(u"אודות", href="index.html")
            with tags.li():
                tags.a(u"הקדמות", href="opening_intros.html")
            with tags.li():
                tags.a(u"הסכמות", href="opening_haskamot.html")
            with tags.li():
                tags.a(u"קיצורים", href="opening_abbrev.html")
            with tags.li():
                tags.a(u"סימנים", href="opening_signs.html")
            # if you add more entries here, please update add_menu_to_apriory_htmls(..)
            with tags.li():
                tags.attr(cls="divider")

            sorted_html_docs_l = sorted(html_docs_l, key=sorter)

            for (html_doc) in sorted_html_docs_l:
                # Only if this a 'high' heading, and not just a letter - include it in the TOC
                if html_doc.name != "NEW_LETTER":
                    with tags.li():
                        tags.a(html_doc.name,
                               href=str(html_doc.index) + ".html")
                        if doc.section == html_doc.section:
                            tags.attr(cls="active")
                else:
                    # it's a letter - if it's related to me, save it
                    if doc.section == html_doc.section:
                        letters_l.append(html_doc)

        with doc.body.children[-1]:
            assert doc.body.children[-1]['class'] == 'container-fluid'
            with tags.ul():
                tags.attr(cls="pagination")
                for (html_doc) in letters_l:
                    tags.li(
                        tags.a(html_doc.letter,
                               href=str(html_doc.index) + ".html"))

    return html_docs_l
Ejemplo n.º 30
0
def fix_links(html_docs_l):
    # fix outbound links
    print "Fixing links"
    for (doc) in html_docs_l:
        for (child) in doc.body.children[0].children:
            if 'definition' in child.attributes.get('class', ()):
                href = ""
                try:
                    href = child.children[0].attributes.get("href")
                except AttributeError as e:
                    pass

                # it's a link - try to update it
                if href:
                    # first, strip it of weird chars
                    try:
                        href = clean_name(href)

                        updated = False
                        if update_values_for_href(child, href):
                            updated = True
                        else:
                            if href[0] in (u"ה", u"ו", u"ש", u"ב", u"כ", u"ל", u"מ"):
                                updated = update_values_for_href(child, href[1:])
                        if not updated:
                            # failed to update - it's not a real link...
                            update_href_no_link(child)

                    except Exception as e:
                        pass
                        print e, "Exception of HREF update", href
                        #TODO - investigate why it happens? (it's a single corner case, I think)


    def sorter(html_doc):
        if html_doc.name in [u"ערכים כלליים",]:
            return "FIRST"
        if html_doc.name in [u"נספחות",]:
            return u"תתתתתתתתתת"    #last
        else:
            return html_doc.name

    # update sections menu
    for (doc) in html_docs_l:
        letters_l = []

        # content_menu = doc.body.children[0].children[1].children[0].children[0].children[-1].children[0].children[1]
        content_menu = doc.body.children[0].children[1].children[0].children[1].children[-1]
        assert content_menu['class'] == 'dropdown-menu dropdown-menu-left scrollable-menu'

        with content_menu:
            with tags.li():
                tags.a(u"אודות", href="index.html")
            with tags.li():
                tags.a(u"הקדמות", href="opening_intros.html")
            with tags.li():
                tags.a(u"הסכמות", href="opening_haskamot.html")
            with tags.li():
                tags.a(u"קיצורים", href="opening_abbrev.html")
            with tags.li():
                tags.a(u"סימנים", href="opening_signs.html")
            # if you add more entries here, please update add_menu_to_apriory_htmls(..)
            with tags.li():
                tags.attr(cls="divider")

            sorted_html_docs_l = sorted(html_docs_l, key=sorter)

            for (html_doc) in sorted_html_docs_l:
                # Only if this a 'high' heading, and not just a letter - include it in the TOC
                if html_doc.name != "NEW_LETTER":
                    with tags.li():
                        tags.a(html_doc.name, href=str(html_doc.index)+".html")
                        if doc.section == html_doc.section:
                            tags.attr(cls="active")
                else:
                    # it's a letter - if it's related to me, save it
                    if doc.section == html_doc.section:
                        letters_l.append(html_doc)

        with doc.body.children[-1]:
            assert doc.body.children[-1]['class'] == 'container-fluid'
            with tags.ul():
                tags.attr(cls="pagination")
                for (html_doc) in letters_l:
                    tags.li(tags.a(html_doc.letter, href=str(html_doc.index)+".html"))



    return html_docs_l
Ejemplo n.º 31
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
Ejemplo n.º 32
0
    def renderChannelPage(self, cpage):
        chdoc = dominate.document(title=cpage)
        log.info(f"Rendering {cpage}")
        with chdoc.head:
            link(rel='stylesheet', href='css/styles.css')
        with chdoc:
            # Iterate through a loop and create the list of channels
            h3(cpage)
            log.info(f"Creating detailed page for Channel {cpage}")
            rawpath = CHANNELS_PATH + cpage + "/raw.json"
            with open(rawpath) as f:
                data = json.load(f)
            try:
                msgs = data['messages']
            except KeyError:
                log.info("No message found this is OK")
                h3("No message in channel")
                fpath = HTML_PATH + cpage + ".html"
                self.updateRawFile(path=fpath, msg=str(chdoc))
                return chdoc

            except TypeError:
                log.info("No message found this is OK")
                h3("Type error message in channel")
                fpath = HTML_PATH + cpage + ".html"
                self.updateRawFile(path=fpath, msg=str(chdoc))
                return chdoc

            for m in msgs:
                try:
                    if "files" in m or 'attachments' in m:
                        #print("This message is a file and the URL is")
                        log.debug(f"File name or attachment present ")
                        if 'files' in m:
                            dname = m['files'][0]['name']
                            did = m['files'][0]['id']
                            dname = did + "_" + dname
                            with div(self.translateuser(m['user'])):
                                attr(cls='usern')
                            with div(self.getDisplayTime(m['ts'])):
                                attr(cls='time')
                            with div(dname):
                                attr(cls='files')
                        elif 'attachments' in m:
                            #log.info(f"Attachment:  {m}")
                            log.info(
                                f"Attachments: Title- {m['attachments'][0]['title']} "
                            )  #text is {m['text']} user is {m['attachments'][0]['user']} ts is {m['attachments'][0]['ts']}")
                            #ADD ADDING Files to Chat logic
                    elif "user" in m and 'ts' in m and 'text' in m:
                        log.debug(
                            f"Message read is {m['text']} sent by {m['user']} on {m['ts']}"
                        )
                        with div(self.translateuser(m['user'])):
                            attr(cls='usern')
                        with div(self.getDisplayTime(m['ts'])):
                            attr(cls='time')
                        with div(m['text']):
                            attr(cls='box1 sb1')
                    elif 'subtype' in m:
                        log.info(f"Channel join or leave message {m}")
                    else:
                        log.info(f"Non client message ")
                except KeyError:
                    log.info(
                        f"One of the keys missing- this is a DEFECT- should not happen {m}"
                    )
                    log.error(KeyError)
                    break

        ###REMOVE THIS _ FOR TESTING ONLY
        #fpath = HTML_PATH+cpage+".html"
        #updateRawFile(path=fpath,msg=str(chdoc))
        ### REMOVE ABOVE FOR TESTING ONLY

        return chdoc
Ejemplo n.º 33
0
 def __init__(self, catalog, **kwargs):
     super().__init__("Add a new series")
     with self.content:
         tags.attr(style=g30c70)
         tags.label("Series Name:")
         tags.input(name='name')
Ejemplo n.º 34
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
Ejemplo n.º 35
0
    f3.close

f = open('dice_jobs.csv', 'r')
f2 = open('cb_jobs.csv', 'r')
f3 = open('monster_jobs.csv', 'r')

doc = dominate.document(title='Tech Jobs')

with doc.head:
    link(rel='stylesheet', href='jobs.css')

with doc:
    h1('New' + ' ' + position + ' ' + 'Jobs')
    with div():
        h2('Dice' + ' ' + position + ' ' + 'Jobs')
        attr(cls='body')
        for path in f:
            a(position, href=path)
    with div():
        h2('Career Builder' + ' ' + position + ' ' + 'Jobs')
        attr(cls='body')
        for path2 in f2:
            a(position, href=path2)
    with div():
        h2('Monster' + ' ' + position + ' ' + 'Jobs')
        attr(cls='body')
        for path3 in f3:
            a(position, href=path3)

with open('joblinks.html', 'w') as f4:
    f4.write(str(doc))
Ejemplo n.º 36
0
 def __init__(self, series, **kwargs):
     super().__init__(f"Rename the {series.name} series")
     with self.content:
         tags.attr(style=g50c50)
         tags.label("New series name:")
         tags.input(name="new_series_name", type='text')
Ejemplo n.º 37
0
def make_region_html(region, args):
    """Write region-specific HTML page."""

    latest = max(
        m.frame.index.max()
        for m in region.metrics["covid"].values()
        if m.emphasis >= 0
    )

    doc = dominate.document(title=f"{region.name} COVID-19 ({latest.date()})")
    doc_url = urls.region_page(region)

    def doc_link(url):
        return urls.link(doc_url, url)

    with doc.head:
        style.add_head_style(doc_url)

    with doc.body:
        tags.attr(id="map_key_target", tabindex="-1")
        with tags.h1():

            def write_breadcrumbs(r):
                if r is not None:
                    write_breadcrumbs(r.parent)
                    tags.a(r.short_name, href=doc_link(urls.region_page(r)))
                    util.text(" » ")

            write_breadcrumbs(region.parent)
            util.text(region.name)

        with tags.div():
            pop = region.totals["population"]
            vax = region.totals.get("vaccinated", 0)
            pos = region.totals.get("positives", 0)
            dead = region.totals.get("deaths", 0)

            nobreak = lambda t: tags.span(t, cls="nobreak")
            nobreak(f"{pop:,.0f} pop; ")
            if vax:
                nobreak(f"{vax:,.0f} ({100 * vax / pop:.2g}%) vacc, ")
            nobreak(f"{pos:,.0f} ({100 * pos / pop:.2g}%) pos, ")
            nobreak(f"{dead:,.0f} ({100 * dead / pop:.2g}%) deaths ")
            nobreak(f"as of {latest.date()}")

        if urls.has_map(region):
            with tags.div(cls="graphic"):
                with tags.video(id="map", preload="auto"):
                    href = urls.link(doc_url, urls.map_video_maybe(region))
                    tags.source(type="video/webm", src=f"{href}#t=1000")

                with tags.div(cls="map_controls"):

                    def i(n):
                        return tags.i(cls=f"fas fa-{n}")

                    tags.button(i("pause"), " ", i("play"), " P", id="map_play")
                    tags.button(i("repeat"), " L", id="map_loop")
                    tags.button(i("backward"), " R", id="map_rewind")
                    tags.button(i("step-backward"), " [", id="map_prev")
                    tags.input_(type="range", id="map_slider")
                    tags.button(i("step-forward"), " ]", id="map_next")
                    tags.button(i("forward"), " F", id="map_forward")

        tags.img(cls="graphic", src=doc_link(urls.chart_image(region)))

        notables = [p for p in region.policy_changes if p.score]
        if notables:
            tags.h2(
                tags.span("Closing", cls="policy_close"),
                " and ",
                tags.span("Reopening", cls="policy_open"),
                " policy changes",
            )

            with tags.div(cls="policies"):
                last_date = None
                for p in notables:
                    date, s = str(p.date.date()), p.score
                    if date != last_date:
                        tags.div(date, cls=f"date")
                        last_date = date

                    tags.div(p.emoji, cls=f"emoji")

                    tags.div(
                        p.text,
                        cls="text"
                        + (" policy_close" if s < 0 else "")
                        + (" policy_open" if s > 0 else "")
                        + (" policy_major" if abs(s) >= 2 else ""),
                    )

        subs = [
            r
            for r in region.subregions.values()
            if r.matches_regex(args.region_regex)
        ]
        if subs:
            sub_pop = sum(s.totals["population"] for s in subs)
            if len(subs) >= 10 and sub_pop > 0.9 * region.totals["population"]:

                def pop(r):
                    return r.totals.get("population", 0)

                def pos(r):
                    m = r.metrics["covid"].get("COVID positives / day / 100Kp")
                    return m.frame.value.iloc[-1] * pop(r) if m else 0

                tags.h2("Top 5 by population")
                for s in list(sorted(subs, key=pop, reverse=True))[:5]:
                    make_subregion_html(doc_url, s)

                tags.h2("Top 5 by new positives")
                for s in list(sorted(subs, key=pos, reverse=True))[:5]:
                    make_subregion_html(doc_url, s)

                tags.h2(f'All {"divisions" if region.parent else "countries"}')
            else:
                tags.h2("Subdivisions")
            for s in sorted(subs, key=lambda r: r.name):
                make_subregion_html(doc_url, s)

        r = region
        credits = dict(c for p in r.policy_changes for c in p.credits.items())
        for ms in r.metrics.values():
            credits.update(c for m in ms.values() for c in m.credits.items())
        with tags.p("Sources: ", cls="credits"):
            for i, (url, text) in enumerate(credits.items()):
                util.text(", ") if i > 0 else None
                tags.a(text, href=url)

    with open(urls.file(args.site_dir, doc_url), "w") as doc_file:
        doc_file.write(doc.render())