Example #1
0
def generate_page(control_status):
    doc, tag, text = Doc().tagtext()
    with tag('html'):
        with tag('head'):
            #doc.asis('<script src="static/control.js"></script>')
            doc.asis(
                '<link rel="stylesheet" type="text/css" href="static/style.css">'
            )
            with tag('title'):
                text('EcoStatus Control')
        with tag('body'):
            with tag('div', id='body'):
                with tag('p'):
                    with tag('h2'):
                        text("Registered devices")
                    for d in control_status["registered_devices"]:
                        vis_status = "(visible)" if d in control_status[
                            "visible_devices"] else "(invisible)"
                        text(d + " " + vis_status)
                        with tag('br'):
                            pass
                    with tag('form',
                             action="/api/control/register_device",
                             method="post"):
                        #with tag('input', name="action", value="register_device"): pass
                        with tag('input', type="text", name="source"):
                            pass
                        with tag('input', type="checkbox", checked="visible"):
                            pass
                        with tag('button', type="submit"):
                            text("Register")
                with tag('p'):
                    with tag('h2'):
                        text('Database')
                        db_status = control_status["is_db_writing_enabled"]
                        db_text = "DB is writing" if db_status else "DB is NOT writing"
                        db_button = "Disable DB" if db_status else "Enable DB"
                    with tag('h4'):
                        text(db_text)
                    with tag('form',
                             method="get",
                             action="/api/control/" +
                             ("disable" if db_status else "enable") +
                             "_db_writing"):
                        with tag('button', type="submit"):
                            text(db_button)
                    with tag('h4'):
                        text('Current database: ')
                        text(control_status["current_database"])
                    with tag('form',
                             action="/api/control/new_database",
                             method="post"):
                        with tag('input', type="text", name="database_name"):
                            pass
                        with tag('button', type="submit"):
                            text("Create database")
                    with tag('form',
                             action="/api/control/new_database_with_timestamp",
                             method="get"):
                        with tag('button', type="submit"):
                            text("Create database with timestamp")
    return doc.getvalue()
Example #2
0
def render_contributers_page(translation, doc_style):
    print(f"Processing contributers page")
    page_width = 8.27
    page_height = page_width
    MARGIN = 0.5
    BUFFER = 0.1
    half_page_width = (page_width - 2 * MARGIN) / 2
    column_1_offset = 0
    column_2_offset = half_page_width

    doc, tag, text = Doc().tagtext()

    doc.asis('<!DOCTYPE html>')
    with tag('html'):
        with tag('head'):
            with tag('style'):
                doc.asis(doc_style)
        with tag('body'):
            with tag('div',
                     style=
                     "display: -webkit-box; display: flex; flex-direction: row"
                     ):
                with tag(
                        'div',
                        style=
                        f"width: 49%; height: {(page_height-2*MARGIN)}in; background-color: #a30234;"
                ):
                    with tag('h1', style=f"padding: 0.2in;", klass="heading"):
                        text(translation('end-title'))
                    with tag(
                            'p',
                            style=
                            f"padding: 0.2in; position:absolute; bottom: 0px; width: 40%;",
                            klass="footnote-yellow"):
                        text(f"v{datetime.datetime.now().strftime('%Y%m%d')}")

                with tag(
                        'div',
                        style=f"width: 49%; height: {(page_height-2*MARGIN)}in;"
                ):
                    with tag('h2',
                             style="margin: 0 0.2in;",
                             klass="subheading"):
                        text(translation('contributors-title'))
                    doc.stag('br')
                    with tag('ul',
                             style="margin: 0 0.2in; direction: ltr;",
                             klass="text"):
                        for contributer, contributions in sorted(
                                CONTRIBUTERS, key=lambda x: x[0]):
                            with tag('li'):
                                text(
                                    translation(
                                        f"{contributer} ({','.join(contributions)})"
                                    ))
                    doc.stag('br')
                    with tag('h2',
                             style="margin: 0 0.2in;",
                             klass="subheading"):
                        text(translation('created-title'))
                    doc.stag('br')
                    with tag('p',
                             style="margin: 0 0.2in; direction: ltr;",
                             klass="text"):
                        text("Fahim Dalvi")
                    doc.stag('br')
                    with tag('p',
                             style="margin: 0 0.2in;",
                             klass="footnote-red"):
                        doc.asis(
                            translation("contribution-note").replace(
                                "<CONTACT_EMAIL>",
                                '<a href="mailto:[email protected]" color="blue">[email protected]</a>'
                            ))

    options = {
        'page-width': f'{page_width}in',
        'page-height': f'{page_height+BUFFER}in',
        'margin-top': f'{MARGIN}in',
        'margin-right': f'{MARGIN}in',
        'margin-bottom': f'{MARGIN}in',
        'margin-left': f'{MARGIN}in',
        'encoding': "UTF-8",
        'disable-smart-shrinking': None,
        'user-style-sheet': 'main.css',
        'enable-local-file-access': None,
        'quiet': None
    }

    return pdfkit.from_string(doc.getvalue(), False, options=options)
Example #3
0
from yattag import Doc, indent
from mytool import compare
import text_txt_position as tp
from shutil import copyfile

doc, tag, text = Doc().tagtext()

# patientID = 80001
# start_date = 5
# num_of_day = 1
def annotate(patientID, start_date, num_of_day,):
    """做標注,標柱完後會將結果輸出至 Clinical_Note/80001/output_annotated

    Args:
        patientID (int): 輸入欲標注的病人ID
        start_date (int): 起始天數
        num_of_day (int): 回搠幾天
    """

    # 要使用的標注檔案 複製一份到 tmp 資料夾內
    input_for_anno_path = 'Clinical_Note/'+str(patientID)+'/output/'+str(start_date)+'_o.txt'
    tmp_for_anno_path = 'Clinical_Note/'+str(patientID)+'/tmp/tmp_'+str(patientID)+'_'+str(start_date)+'_'+str(num_of_day)+'.txt'
    copyfile(input_for_anno_path, tmp_for_anno_path)

    #  --- 檢查檔案長度 ---
    file = open(input_for_anno_path, "r")
    data = file.read()
    end_node = len(data)
    file.close()
    #  --------------------
Example #4
0
def generate_monster_block(m):
    output = f"./img/{m.index}.jpg"
    if path.exists(f'./img/{m.index}.jpg'):
        return output
    else:
        doc, tag, text = Doc().tagtext()
        doc.asis(
            '<!DOCTYPE html><link rel="stylesheet" href="..\css\stylednd.css"> <link href="http://fonts.googleapis.com/css?family=Libre+Baskerville:7monstermonster" rel="stylesheet" type="text/css">',
            '<link href="http://fonts.googleapis.com/css?family=Noto+Sans:4monstermonster,7monstermonster,4monstermonsteritalic,7monstermonsteritalic" rel="stylesheet" type="text/css">',
            '<div class="stat-block wide">	<hr class="orange-border" /> <div class="section-left"> <div class="creature-heading">'
        )

        with tag('h1'):
            text(m.name)
        with tag('h2'):
            text(m.size + " " + m.type + " " + m.alignment)
        doc.asis("""</div> <!-- creature heading -->
                <svg height="5" width="100%" class="taperedrule">
                <polyline points="0,0 400,2.5 0,5"></polyline>
            </svg>
                <div class="top-stats">
                    <div class="property-line first">
                        <h4>Armor Class</h4>: """)
        with tag('p'):
            text(m.ac)
        doc.asis("""</div> <!-- property line -->
                    <div class="property-line">
                        <h4>Hit Points</h4>: """)
        with tag('p'):
            text(m.hp)
        doc.asis("""</div> <!-- property line -->
                    <div class="property-line last">
                        <h4>Speed</h4>: """)
        with tag('p'):
            for i in m.speed:

                text(i + ":" + m.speed[i])
        doc.asis("""</div> <!-- property line -->
                    <svg height="5" width="100%" class="taperedrule">
                <polyline points="0,0 400,2.5 0,5"></polyline>
            </svg>
                    <div class="abilities">
                        <div class="ability-strength">
                            <h4>STR</h4>""")
        with tag('p'):
            ab = m.str
            ab_mod = (m.str - 10) / 2
            if ab_mod >= 0:
                text(f"{ab} (+{math.floor(ab_mod)})")
            else:
                text(f"{ab} (  {math.floor(ab_mod)})")
        doc.asis("""</div> <!-- ability strength -->
                        <div class="ability-dexterity">
                            <h4>DEX</h4>""")
        with tag('p'):
            ab = m.dex
            ab_mod = (ab - 10) / 2
            if ab_mod >= 0:
                text(f"{ab} (+{math.floor(ab_mod)})")
            else:
                text(f"{ab} (  {math.floor(ab_mod)})")
        doc.asis("""</div> <!-- ability dexteriry -->
                        <div class="ability-constitution">
                            <h4>CON</h4>""")
        with tag('p'):
            ab = m.con
            ab_mod = (ab - 10) / 2
            if ab_mod >= 0:
                text(f"{ab} (+{math.floor(ab_mod)})")
            else:
                text(f"{ab} (  {math.floor(ab_mod)})")
        doc.asis("""</div> <!-- ability constitution -->
                        <div class="ability-intelligence">
                            <h4>INT</h4>""")
        with tag('p'):
            ab = m.int
            ab_mod = (ab - 10) / 2
            if ab_mod >= 0:
                text(f"{ab} (+{math.floor(ab_mod)})")
            else:
                text(f"{ab} (  {math.floor(ab_mod)})")
        doc.asis("""</div> <!-- ability intelligence -->
                        <div class="ability-wisdom">
                            <h4>WIS</h4>""")
        with tag('p'):
            ab = m.wis
            ab_mod = (ab - 10) / 2
            if ab_mod >= 0:
                text(f"{ab} (+{math.floor(ab_mod)})")
            else:
                text(f"{ab} (  {math.floor(ab_mod)})")
        doc.asis("""</div> <!-- ability wisdom -->
                        <div class="ability-charisma">
                            <h4>CHA</h4>""")
        with tag('p'):
            ab = m.cha
            ab_mod = (ab - 10) / 2
            if ab_mod >= 0:
                text(f"{ab} (+{math.floor(ab_mod)})")
            else:
                text(f"{ab} (  {math.floor(ab_mod)})")
        doc.asis("""</div> <!-- ability charisma --> </div> <!-- abilities -->
                    <svg height="5" width="100%" class="taperedrule">
                <polyline points="0,0 400,2.5 0,5"></polyline>
            </svg>
                    <div class="property-line first">
                        <h4>Damage Immunities</h4>: """)
        with tag('p'):
            try:
                for i in m.di:
                    text(f"{i}, ")
            except AttributeError:
                text("None")

        doc.asis("""</div> <!-- property line -->
                    <div class="property-line">
                        <h4>Condition Immunities</h4>: """)
        with tag('p'):
            try:
                for i in m.ci:
                    text(f'{i}, ')
            except AttributeError:
                text("None")
        doc.asis("""</div> <!-- property line -->
                    <div class="property-line">
                        <h4>Senses</h4>: """)
        with tag('p'):
            for a in m.senses:
                text(m.senses[a])
        doc.asis("""</div> <!-- property line -->
                    <div class="property-line">
                        <h4>Languages</h4>: """)
        with tag('p'):
            text(m.lang)
        doc.asis("""</div> <!-- property line -->
                    <div class="property-line last">
                        <h4>Challenge</h4>: """)
        with tag('p'):
            text(m.cr)
        doc.asis("""</div> <!-- property line -->
                </div> <!-- top stats -->
                <svg height="5" width="100%" class="taperedrule">
                <polyline points="0,0, 400,2.5 0,5"></polyline>
            </svg>
                <div class="property-block">  """)
        try:
            with tag('p'):
                special_ability = [(i['name'], i['desc']) for i in m.sa]
                for i, a in enumerate(special_ability):
                    doc.asis(
                        f"<span class=\"br\"><b> {a[0]}</b> : {a[1]}</span></br>"
                    )
            doc.asis("""</div> <!-- property block-->
                </div> <!-- section left -->
                <div class="sectionright">
                    <div class="actions">
                        <h3>Actions</h3>
                        <div class="property-block"> """)
        except AttributeError:
            pass
        with tag('p'):
            actions = [(i['name'], i['desc']) for i in m.action]
            for i, a in enumerate(actions):
                doc.asis(
                    f"<span class=\"br\"><b> {a[0]}</b> : {a[1]}</span></br>")
        doc.asis("""</div> <!-- property block -->
                    
                </div> <!-- actions -->
        """)

        if hasattr(m, 'legact'):
            doc.asis("""<div class="actions">
                    <h3>Legendary Actions</h3>
                    <div class="property-block">
                        """)
            with tag('p'):
                legactions = [(i['name'], i['desc']) for i in m.legact]
                for i, a in enumerate(legactions):
                    doc.asis(
                        f"<span class=\"br\"><b> {a[0]}</b> : {a[1]}</span></br>"
                    )
            doc.asis("""</div> <!-- property block -->
                    
                    
                </div> <!-- actions -->
            </div> <!-- section right -->
            <hr class="orange-border bottom" />
        </div> <!-- stat block -->
        """)

        content = doc.getvalue()

        with open(f'./html/{m.index}.html', 'w+',
                  encoding='UTF8') as test_file:
            test_file.write(content)

        options = {
            'enable-local-file-access': '',
            'width': '1280',
            'quality': 50
        }

        imgkit.from_file(f'./html/{m.index}.html',
                         output,
                         config=imgkitconfig,
                         options=options)

        return output
Example #5
0
def render_guide_pages(translation, doc_style):
    # Define page data
    page_images = [
        f"assets/lowres-nas-page{page_number}.jpg"
        for page_number in range(1, 8)
    ] + [
        f"assets/lowres-portal-page{page_number}.jpg"
        for page_number in range(1, 7)
    ]

    # Format: [(type, text)]
    page_texts = [
        [
            ("title", translation("nas-title")),
            (
                "bullet",
                translation("nas-page1-text1").replace(
                    "<NAS_URL>",
                    '<a href="https://www.nas.gov.qa/self-service/" color="blue"> https://www.nas.gov.qa </a>',
                ),
            ),
            ("bullet", translation("nas-page1-text2")),
            ("footnote", translation("nas-page1-footnote")),
        ],
        [
            ("title", translation("nas-title")),
            ("bullet", translation("nas-page2-text1")),
            ("bullet", translation("nas-page2-text2")),
        ],
        [
            ("title", translation("nas-title")),
            ("bullet", translation("nas-page3-text1")),
            ("bullet", translation("nas-page3-text2")),
            ("bullet", translation("nas-page3-text3")),
            ("bullet", translation("nas-page3-text4")),
        ],
        [
            ("title", translation("nas-title")),
            ("bullet", translation("nas-page4-text1")),
            ("bullet", translation("nas-page4-text2")),
        ],
        [
            ("title", translation("nas-title")),
            ("bullet", translation("nas-page5-text1")),
            ("bullet", translation("nas-page5-text2")),
            ("bullet", translation("nas-page5-text3")),
            ("bullet", translation("nas-page5-text4")),
            ("bullet", translation("nas-page5-text5")),
            ("bullet", translation("nas-page5-text6")),
            ("bullet", translation("nas-page5-text7")),
            ("bullet", translation("nas-page5-text8")),
            ("bullet", translation("nas-page5-text9")),
            ("bullet", translation("nas-page5-text10")),
            ("bullet", translation("nas-page5-text11")),
            ("bullet", translation("nas-page5-text12")),
        ],
        [
            ("title", translation("nas-title")),
            ("bullet", translation("nas-page6-text1")),
            ("bullet", translation("nas-page6-text2")),
            ("bullet", translation("nas-page6-text3")),
        ],
        [
            ("title", translation("nas-title")),
            ("bullet", translation("nas-page7-text1")),
            ("footnote", translation("nas-page7-footnote")),
        ],
        [
            ("title", translation("vaccineportal-title")),
            (
                "bullet",
                translation("vaccineportal-page1-text1").replace(
                    "<PORTAL_URL>",
                    '<a href="http://app-covid19.moph.gov.qa" color="blue">http://app-covid19.moph.gov.qa</a>',
                ),
            ),
            ("bullet", translation("vaccineportal-page1-text2")),
            ("footnote", translation("vaccineportal-page1-footnote")),
        ],
        [
            ("title", translation("vaccineportal-title")),
            ("bullet", translation("vaccineportal-page2-text1")),
            ("bullet", translation("vaccineportal-page2-text2")),
            ("bullet", translation("vaccineportal-page2-text3")),
        ],
        [
            ("title", translation("vaccineportal-title")),
            ("bullet", translation("vaccineportal-page3-text1")),
            ("bullet", translation("vaccineportal-page3-text2")),
            ("bullet", translation("vaccineportal-page3-text3")),
            ("bullet", translation("vaccineportal-page3-text4")),
        ],
        [
            ("title", translation("vaccineportal-title")),
            ("bullet", translation("vaccineportal-page4-text1")),
            ("bullet", translation("vaccineportal-page4-text2")),
            ("bullet", translation("vaccineportal-page4-text3")),
            ("bullet", translation("vaccineportal-page4-text4")),
            ("bullet", translation("vaccineportal-page4-text5")),
        ],
        [
            ("title", translation("vaccineportal-title")),
            ("bullet", translation("vaccineportal-page5-text1")),
            ("bullet", translation("vaccineportal-page5-text2")),
            ("bullet", translation("vaccineportal-page5-text3")),
            ("bullet", translation("vaccineportal-page5-text4")),
            ("bullet", translation("vaccineportal-page5-text5")),
            ("bullet", translation("vaccineportal-page5-text6")),
            ("bullet", translation("vaccineportal-page5-text7")),
            ("bullet", translation("vaccineportal-page5-text8")),
            ("bullet", translation("vaccineportal-page5-text9")),
            ("footnote", translation("vaccineportal-page5-footnote")),
        ],
        [
            ("title", translation("vaccineportal-title")),
            ("bullet", translation("vaccineportal-page6-text1")),
        ],
    ]

    page_width = 8.27
    MARGIN = 0.5
    BUFFER = 0.1
    half_page_width = (page_width - 2 * MARGIN) * 0.485

    page_pdfs = []
    for page_idx, page_image in enumerate(page_images):
        print(f"Processing page {page_idx+2}")
        page_screenshot = Image.open(page_image)
        screenshot_width, screenshot_height = page_screenshot.size
        resize_ratio = half_page_width / screenshot_width

        page_height = screenshot_height * resize_ratio + MARGIN * 2 + 1

        doc, tag, text = Doc().tagtext()

        doc.asis('<!DOCTYPE html>')
        with tag('html'):
            with tag('head'):
                with tag('style'):
                    doc.asis(doc_style)
            with tag('body'):
                with tag(
                        'div',
                        style=
                        "display: -webkit-box; display: flex; flex-direction: row"
                ):
                    with tag('div',
                             style=
                             f"width: 49%; height: {(page_height-2*MARGIN)}in;"
                             ):
                        doc.stag('img', src=os.path.abspath(page_image))
                    with tag('div',
                             style=
                             f"width: 49%; height: {(page_height-2*MARGIN)}in;"
                             ):
                        titles = [
                            x for x in page_texts[page_idx] if x[0] == 'title'
                        ]

                        for _, text_snippet in titles:
                            with tag('h2',
                                     style="margin: 0 0.2in;",
                                     klass="subheading"):
                                doc.asis(text_snippet)

                        bullets = [
                            x for x in page_texts[page_idx] if x[0] == 'bullet'
                        ]
                        with tag('ul', klass="text"):
                            for _, text_snippet in bullets:
                                with tag('li',
                                         style="margin: 0 0.2in;",
                                         klass="text"):
                                    doc.asis(text_snippet)

                        footnotes = [
                            x for x in page_texts[page_idx]
                            if x[0] == 'footnote'
                        ]
                        for _, text_snippet in footnotes:
                            with tag(
                                    'p',
                                    style=
                                    "margin: 0 0.2in; position:absolute; bottom: 6px; width: 40%;",
                                    klass="footnote-red"):
                                doc.asis(text_snippet)

        options = {
            'page-width': f'{page_width}in',
            'page-height': f'{page_height+BUFFER}in',
            'margin-top': f'{MARGIN}in',
            'margin-right': f'{MARGIN}in',
            'margin-bottom': f'{MARGIN}in',
            'margin-left': f'{MARGIN}in',
            'encoding': "UTF-8",
            'disable-smart-shrinking': None,
            'user-style-sheet': 'main.css',
            'enable-local-file-access': None,
            'quiet': None
        }

        page_pdfs.append(
            pdfkit.from_string(doc.getvalue(), False, options=options))
    return page_pdfs
Example #6
0
def gen_xml(workbook):
    # Load our Excel File
    wb = load_workbook(workbook)
    # Getting an object of active sheet 1
    ws = wb.worksheets[0]
    # Returning returns a triplet
    doc, tag, text = Doc().tagtext()
    # headers = get_row_headers(workbook)
    # get_xml_elements(ele)
    # get_rte_keys(k)
    # keymap = gen_keymap(k, ele)

    xml_header = '<?xml version="1.0" encoding="UTF-8"?>'
    # xml_schema = '<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"></xs:schema>'

    doc.asis(xml_header)
    # doc.asis(xml_schema)

    with tag('report',
             ('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance"),
             ('xsi:noNamespaceSchemaLocation', "goAMLSchema.xsd")):
        for idx, row in enumerate(
                ws.iter_rows(min_row=8, max_row=8, min_col=1, max_col=127)):
            row = [cell.value for cell in row if row is not None]
            with tag('rentity_id'):
                text(int('1059'))  # int
            with tag('rentity_branch'):
                text("1")  # str
            with tag('submission_code'):
                if row[36] == "EFECTIVO" or row[36] == "CHEQUE":
                    text("M")
                else:
                    text("M")
            with tag('report_code'):
                text("CTR")
            with tag('entity_reference'):
                text("Bagricola")
            with tag('fiu_ref_number'):
                text("UAF Santo Domingo")
            with tag('submission_date'):
                tmp = datetime.strptime(str(row[4]), "%Y-%m-%d %H:%M:%S")
                text(tmp.strftime("%Y-%m-%dT%H:%M:%S"))
            with tag("currency_code_local"):
                text("DOP")
            with tag("reporting_person"):
                with tag("gender"):
                    text("F")
                with tag("title"):
                    text("Oficial de Cumplimiento")
                with tag("first_name"):
                    text("Naty")
                with tag("last_name"):
                    text("Abreu")
                with tag("birthdate"):
                    tmp = datetime.strptime("1972-10-03 00:00:00",
                                            "%Y-%m-%d %H:%M:%S")
                    text(tmp.strftime("%Y-%m-%dT%H:%M:%S"))
                with tag("id_number"):
                    text("001-0955138-2")
                with tag("nationality1"):
                    text("DO")
                with tag("phones"):
                    with tag("phone"):
                        with tag("tph_contact_type"):
                            text(1)
                        with tag("tph_communication_type"):
                            text("L")
                        with tag("tph_country_prefix"):
                            text("809")
                        with tag("tph_number"):
                            text("535-8088")
                        with tag("tph_extension"):
                            text("3212")
                with tag("addresses"):
                    with tag("address"):
                        with tag("address_type"):
                            text(int("2"))
                        with tag("address"):
                            text("Ave. George Washington NO. 601")
                        with tag("town"):
                            text("Santo Domingo")
                        with tag("city"):
                            text("Santo Domingo")
                        with tag("zip"):
                            text("10103")
                        with tag("country_code"):
                            text("DO")
                with tag("email"):
                    text("*****@*****.**")
                with tag("occupation"):
                    text("Ing. de Sistemas")

            with tag("location"):
                with tag("address_type"):
                    text(int("1"))
                with tag("address"):
                    text("Calle Ave. George Washington No. 601")
                with tag("city"):
                    text("Santo Domingo")
                with tag("country_code"):
                    text("DO")

            with tag("reason"):
                if row[105] is None:
                    row[105] = "Transaccion sospechosa"
                else:
                    text(row[105])
            with tag("action"):
                if row[80] is None:
                    row[80] = "Acciones a tomar"
                else:
                    text(row[80])

        # ? Append all transactions per report
        for idx, row in enumerate(
                ws.iter_rows(min_row=8, max_row=186, min_col=1, max_col=127)):
            row = [cell.value for cell in row if row is not None]

            with tag("transaction"):
                with tag("transactionnumber"):
                    if row[97] is None:
                        row[97] = ""
                    else:
                        text(row[97])
                with tag("internal_ref_number"):
                    if row[19] is None:
                        row[19] = ""
                    else:
                        text(row[19])
                with tag("transaction_location"):
                    if row[3] is None:
                        row[3] = ""
                    else:
                        text(row[3])
                with tag("transaction_description"):
                    if row[31] is None:
                        row[31] = ""
                    else:
                        text(row[31])
                with tag("date_transaction"):
                    if row[37] is None:
                        row[37] = datetime.strptime("1900-01-01 00:00:00",
                                                    "%Y-%m-%d %H:%M:%S")
                        text(str(row[37]))
                    else:
                        tmp = datetime.strptime(str(row[37]),
                                                "%Y-%m-%d %H:%M:%S")
                        text(tmp.strftime("%Y-%m-%dT%H:%M:%S"))

                with tag("transmode_code"):
                    text("A")

                with tag("transmode_comment"):
                    if row[105] is None:
                        row[105] = ""
                    else:
                        text(row[105])
                with tag("amount_local"):
                    if row[34] is None:
                        row[34] = 0.0
                    else:
                        text(row[34])
                with tag("involved_parties"):
                    with tag("party"):
                        with tag("role"):
                            text("B")
                        with tag("person_my_client"):
                            with tag("first_name"):
                                text(row[10])
                            with tag("middle_name"):
                                text(row[10])
                            with tag("last_name"):
                                if row[11] is None or row[11] == "":
                                    row[11] = "n/a"
                                else:
                                    text(row[11])
                            with tag("birthdate"):
                                tmp = datetime.strptime(
                                    "1900-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
                                text(tmp.strftime("%Y-%m-%dT%H:%M:%S"))
                            with tag("ssn"):
                                if row[15] is None:
                                    row[15] = "n/a"
                                else:
                                    text(row[15])
                            with tag("id_number"):
                                if row[15] is None:
                                    row[15] = "n/a"
                                else:
                                    text(row[15])

                            with tag("phones"):
                                with tag("phone"):
                                    with tag("tph_contact_type"):
                                        text(2)
                                    with tag("tph_communication_type"):
                                        text("L")
                                    with tag("tph_number"):
                                        text("809-222-2222")
                                        # if row[28] is None or row[28] == "":
                                        #     row[28] = "8098881722"
                                        # else:
                                        #     text(row[28])

                            with tag("addresses"):
                                with tag("address"):
                                    with tag("address_type"):
                                        text(int("1"))
                                    with tag("address"):
                                        if row[25] is None or row[25] == "":
                                            row[25] = "prueba"
                                        else:
                                            text(row[25])
                                    with tag("city"):
                                        if row[22] is None:
                                            row[22] = "prueba"
                                        else:
                                            text(row[22])
                                    with tag("country_code"):
                                        text("DO")

                            with tag("email"):
                                text("*****@*****.**")

                            with tag("employer_address_id"):
                                with tag("address_type"):
                                    text(int("2"))
                                with tag("address"):
                                    text("Calle prueba no. 2")
                                with tag("city"):
                                    text(row[22])
                                with tag("country_code"):
                                    text("DO")

                            with tag("employer_phone_id"):
                                with tag("tph_contact_type"):
                                    text(1)
                                with tag("tph_communication_type"):
                                    text("M")
                                with tag("tph_number"):
                                    text("829-000-0000")

                            with tag("identification"):
                                with tag("type"):
                                    text(int("1"))
                                with tag("number"):
                                    if row[55] is None:
                                        row[55] = "n/a"
                                    else:
                                        text(row[55])
                                with tag("issue_date"):
                                    tmp = datetime.strptime(
                                        "2020-03-03 00:00:00",
                                        "%Y-%m-%d %H:%M:%S")
                                    text(tmp.strftime("%Y-%m-%dT%H:%M:%S"))
                                with tag("expiry_date"):
                                    tmp = datetime.strptime(
                                        "2020-03-03 00:00:00",
                                        "%Y-%m-%d %H:%M:%S")
                                    text(tmp.strftime("%Y-%m-%dT%H:%M:%S"))
                                with tag("issue_country"):
                                    text("DO")
                        with tag("funds_code"):
                            text("K")
                        with tag("funds_comment"):
                            text(row[31])
                        with tag("country"):
                            text("DO")
                        with tag("significance"):
                            text(int("6"))

                with tag("comments"):
                    text("Prueba")

    result = indent(doc.getvalue(), indentation='   ', indent_text=False)

    date = ''.join(str(datetime.now()).replace('-', '_')[:10])
    filename = "_UAF_Web_Report_" + date + ".xml"

    with open(filename, "w") as f:
        f.write(result)
Example #7
0
    def _writexml(self, traffic: types.Traffic, route_path: str):
        """Writes a traffic spec into a route file. Typically this would be the source
        data to Sumo's DUAROUTER.
        """
        doc = Doc()
        doc.asis('<?xml version="1.0" encoding="UTF-8"?>')
        with doc.tag(
                "routes",
            ("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"),
            ("xsi:noNamespaceSchemaLocation",
             "http://sumo.sf.net/xsd/routes_file.xsd"),
        ):
            # Actors and routes may be declared once then reused. To prevent creating
            # duplicates we unique them here.
            for actor in {
                    actor
                    for flow in traffic.flows for actor in flow.actors.keys()
            }:
                sigma = min(1, max(0,
                                   actor.imperfection.sample()))  # range [0,1]
                min_gap = max(0, actor.min_gap.sample())  # range >= 0
                doc.stag(
                    "vType",
                    id=actor.id,
                    accel=actor.accel,
                    decel=actor.decel,
                    vClass=actor.vehicle_type,
                    speedFactor=actor.speed.mean,
                    speedDev=actor.speed.sigma,
                    sigma=sigma,
                    minGap=min_gap,
                    **actor.lane_changing_model,
                    **actor.junction_model,
                )

            # Make sure all routes are "resolved" (e.g. `RandomRoute` are converted to
            # `Route`) so that we can write them all to file.
            resolved_routes = {}
            for route in {flow.route for flow in traffic.flows}:
                resolved_routes[route] = self.resolve_route(route)

            for route in set(resolved_routes.values()):
                doc.stag("route", id=route.id, edges=" ".join(route.edges))

            # We don't de-dup flows since defining the same flow multiple times should
            # create multiple traffic flows. Since IDs can't be reused, we also unique
            # them here.
            for flow_idx, flow in enumerate(traffic.flows):
                total_weight = sum(flow.actors.values())
                route = resolved_routes[flow.route]
                for actor_idx, (actor,
                                weight) in enumerate(flow.actors.items()):
                    doc.stag(
                        "flow",
                        id="{}-{}-{}-{}".format(actor.name, flow.id, flow_idx,
                                                actor_idx),
                        type=actor.id,
                        route=route.id,
                        vehsPerHour=flow.rate * (weight / total_weight),
                        departLane=route.begin[1],
                        departPos=route.begin[2],
                        departSpeed=actor.depart_speed,
                        arrivalLane=route.end[1],
                        arrivalPos=route.end[2],
                        begin=flow.begin,
                        end=flow.end,
                    )

        with open(route_path, "w") as f:
            f.write(
                indent(doc.getvalue(),
                       indentation="    ",
                       newline="\r\n",
                       indent_text=True))
Example #8
0
    def make_epub(self):
        self.make_ToC(
        )  # first we make the table of contents based on the current contents of this Ebook instance
        with tempfile.TemporaryDirectory(
        ) as td:  # we make the epub as a standard directory using tempfiles to begin with

            # First, we include the stuff that's the same in every epub file. These never change.
            # TODO This part should probably be a seperate class function
            with codecs.open(td + '/mimetype', 'w', 'utf-8') as f:
                f.write(constants.MIMETYPE)

            os.mkdir(td + '/META-INF')
            with codecs.open(td + '/META-INF/container.xml', 'w',
                             'utf-8') as f:
                f.write(constants.CONTAINER)

            os.mkdir(td + '/OEPBS')
            os.mkdir(td + '/OEPBS/Styles')
            with codecs.open(td + '/OEPBS/Styles/style.css', 'w',
                             'utf-8') as f:
                f.write(constants.CSS)

            # Now we get to the dynamic stuff
            # TODO Should probably split this up in to seperate functions

            # The OEPBS contains all the main content of the epub
            os.mkdir(td + '/OEPBS/Text')
            for chapter in self.chapters:  # here we add all of the chapters
                with codecs.open(td + '/OEPBS/' + chapter.path, 'w',
                                 'utf-8') as f:
                    f.write(chapter.content)

            for page in self.pages:  # then we add the rest of the pages
                with codecs.open(td + '/OEPBS/Text/' + page.ID + '.xhtml', 'w',
                                 'utf-8') as f:
                    f.write(page.content)

            # contents.opf contains the metadata, the manifest, and the spine
            with codecs.open(td + '/OEPBS/content.opf', 'w', 'utf-8') as f:
                doc, tag, text, line = Doc().ttl()
                doc.asis('<?xml version="1.0" encoding="UTF-8"?>')
                with tag('package', ('unique-identifier', self.bookID),
                         xmns="http://www.idpf.org/2007/opf",
                         version="2.0"):

                    # the metadata section should speak for itself
                    with tag('metadata',
                             ('xmlns:dc', "http://purl.org/dc/elements/1.1/"),
                             ('xmlns:opf', "http://www.idpf.org/2007/opf")):
                        line('dc:title', self.bookTitle)
                        line('dc:creator', self.bookAuthor)
                        line('dc:language', 'en-US')
                        line('dc:rights', 'Public Domain')
                        line('dc:publisher', self.bookPublisher)
                        line('dc:identifier',
                             self.bookID, ('opf:scheme', "UUID"),
                             id="bookID")

                    # the manifest lists ALL files contained in the epub. Notably, this includes things like embedded images.
                    with tag('manifest'):
                        doc.stag('item',
                                 ('media-type', "application/x-dtbncx+xml"),
                                 id="ncx",
                                 href="toc.ncx")
                        doc.stag('item', ('media-type', "text/css"),
                                 id="style",
                                 href="Styles/style.css")
                        for page in self.pages:
                            doc.stag('item',
                                     ('media-type', "application/xhtml+xml"),
                                     id=page.ID,
                                     href=page.path)

                        for chapter in self.chapters:
                            doc.stag('item',
                                     ('media-type', "application/xhtml+xml"),
                                     id=chapter.ID,
                                     href=chapter.path)

                    # the spine section determines what order the pages and chapters are ordered in the final epub
                    with tag('spine', toc="ncx"):
                        for page in self.pages:
                            doc.stag('itemref', idref=page.ID)
                        for chapter in self.chapters:
                            doc.stag('itemref', idref=chapter.ID)

                f.write(indent(doc.getvalue()))

            # tox.ncx is a special file basically implementing the table of contents
            # TODO this should also probably be a seperate function
            with codecs.open(td + '/OEPBS/tox.ncx', 'w', 'utf-8') as f:
                doc, tag, text = Doc().tagtext()
                doc.asis('<?xml version="1.0" encoding="UTF-8"?>')
                with tag('ncx',
                         xmlns="http://www.daisy.org/z3986/2005/ncx/",
                         version="2005-1"):
                    with tag('head'):
                        doc.stag('meta', name="dtb:uid", content=self.bookID)
                        doc.stag('meta', name="dtb:depth", content="1")
                        doc.stag('meta',
                                 name="dtb:totalPageCount",
                                 content="0")
                        doc.stag('meta', name="dtb:maxPageNumber", content="0")

                    with tag('docTitle'):
                        line('text', self.bookTitle)

                    with tag('navMap'):
                        for chapter in self.chapters:
                            with tag('navPoint',
                                     id="navPoint-" + chapter.fillID):
                                with tag('navLabel'):
                                    line(
                                        'text', "Chapter " + chapter.baseID +
                                        ":" + chapter.title)

                                doc.stag('content', src=chapter.path)

            # Last, we call a seperate function that creates the actual epub from the temp directory populated in this function
            self.make_epub_from_file(td)
Example #9
0
def generate_html_file_with_deviants(average_matchups, deviant_spreads,
                                     deviant_mlines, file_name):
    from yattag import Doc
    from yattag import indent

    doc, tag, text, line = Doc().ttl()

    doc.asis('<!DOCTYPE html>')
    with tag('html'):
        with tag('body'):
            line('p', time_string('day'))
            line('p', time_string('time'))
            line('h1', 'Lines and largest deviants')
            with tag('head'):
                doc.stag('link', rel='stylesheet', href='style.css')
            for i, matchup in enumerate(average_matchups):
                deviant_spread = deviant_spreads[i]
                deviant_mline = deviant_mlines[i]
                with tag('table'):
                    with tag('tr'):
                        with tag('td', klass='outer'):
                            with tag('table'):
                                with tag('tr'):
                                    line('td',
                                         matchup.website,
                                         rowspan=3,
                                         klass='site')
                                    line('th', 'Team')
                                    line('th', 'Spread')
                                    line('th', 'Money Line')
                                    line('th', 'O/U')
                                with tag('tr'):
                                    line('td', matchup.team_one)
                                    line('td', matchup.spread_one.get_string())
                                    line('td', matchup.mline_one.get_string())
                                    line('td',
                                         matchup.over.get_string(),
                                         rowspan=2)
                                with tag('tr'):
                                    line('td', matchup.team_two)
                                    line('td', matchup.spread_two.get_string())
                                    line('td', matchup.mline_two.get_string())
                        with tag('td', klass='outer'):
                            with tag('table'):
                                with tag('tr'):
                                    line('td',
                                         deviant_spread.website,
                                         rowspan=3,
                                         klass='site')
                                    line('th', 'Spread', klass='deviant')
                                with tag('tr'):
                                    line(
                                        'td',
                                        deviant_spread.spread_one.get_string())
                                with tag('tr'):
                                    line(
                                        'td',
                                        deviant_spread.spread_two.get_string())
                        with tag('td', klass='outer'):
                            with tag('table'):
                                with tag('tr'):
                                    line('td',
                                         deviant_mline.website,
                                         rowspan=3,
                                         klass='site')
                                    line('th', 'Money Line', klass='deviant')
                                with tag('tr'):
                                    line('td',
                                         deviant_mline.mline_one.get_string())
                                with tag('tr'):
                                    line('td',
                                         deviant_mline.mline_two.get_string())

    file = open(file_name, 'w')
    file.write(indent(doc.getvalue()))
def create_page(sources, list_order):
    """Creates the table from YAML"""
    global download_names
    doc, tag, text = Doc().tagtext()
    doc.asis("<!DOCTYPE html>")
    with tag("html", ("lang", "en")):
        with tag("head"):
            with tag("title"):
                text(constants.SHORT_NAME)
            doc.asis("<!-- Required meta tags -->")
            doc.asis('<meta charset="utf-8">')
            doc.asis(
                '<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">'
            )
            doc.asis("<!-- bootstrap CSS -->")
            doc.asis(
                """<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">"""
            )
            doc.asis("""<link rel="stylesheet" href="./css/list.css">""")
            doc.asis("<!-- Fonts -->")
            doc.asis(
                '<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">'
            )
        with tag("body"):
            doc.asis("<!-- navbar -->")
            doc.asis(
                generate_navbar.navbar(active=constants.LIST_TAB, sorttab=list_order)
            )
            doc.asis("<!-- note -->")
            with tag("div", ("class", "container py-3 mb-0"), ("id", "note")):
                with tag("p", ("class", "text-center mb-0")):
                    text("This is not an exhaustive list, just my recommendations.")
            doc.asis("<!-- list -->")
            with tag("main", klass="container", id="main-container"):
                sources = sort_list(sources, list_order)
                for s in sources:
                    with tag("div", ("class", "anime-row-container")):
                        with tag(
                            "div", klass="row anime-row align-items-center border"
                        ):  # row for each anime
                            # name/tags/info button
                            with tag("div", klass="col-sm"):
                                # name
                                with tag("h6"):
                                    text(str(s["name"]))
                                    # tags
                                    for t in sorted(s["tags"]):
                                        if t.lower() in [
                                            "anthology",
                                            "arthouse",
                                            "commercial",
                                            "film",
                                            "music video",
                                            "series",
                                        ]:
                                            tag_slug = (
                                                t.lower().strip().replace(" ", "-")
                                            )
                                            with tag(
                                                "span",
                                                klass="badge tag {}".format(tag_slug),
                                            ):
                                                with tag(
                                                    "a",
                                                    ("href", "javascript:void(0)"),
                                                    ("class", "badge-link"),
                                                    ("data-toggle", "tooltip"),
                                                    (
                                                        "data-original-title",
                                                        "filter page to shorts tagged '{}'".format(
                                                            t.strip().lower()
                                                        ),
                                                    ),
                                                    (
                                                        "onclick",
                                                        "filterBadge('{}', this)".format(
                                                            tag_slug
                                                        ),
                                                    ),
                                                ):
                                                    text(t.capitalize())
                                        else:
                                            print("Warning, Unknown tag:", t)
                                    if list_order == constants.order.DATE:
                                        with tag("span", klass="badge badge-info"):
                                            text(str(s["date"]))
                                    # if this has extra info
                                    if s["extra_info"] is not None:
                                        with tag(
                                            "a",
                                            ("role", "button"),
                                            ("class", "more-info-expand ml-2"),
                                            (
                                                "href",
                                                create_id(
                                                    name="{}-extra-info".format(
                                                        s["name"]
                                                    ),
                                                    octothorpe=True,
                                                ),
                                            ),
                                            ("aria-expanded", "false"),
                                            ("data-toggle", "collapse"),
                                        ):
                                            text("ⓘ")

                            # time (durations/episodes)
                            if s["duration"] is not None and s["episodes"] is not None:
                                dur, eps = s["duration"], s["episodes"]
                                with tag("div", ("class", "time col-md-1")):
                                    if eps == 1:
                                        with tag("span", klass="badge"):
                                            text("{}".format(format_duration(dur)))
                                    elif eps == 0:  # unknown ep count
                                        with tag("span", klass="badge"):
                                            text(
                                                "{} x ? eps".format(
                                                    format_duration(dur)
                                                )
                                            )
                                    else:
                                        with tag("span", klass="badge"):
                                            text(
                                                "{} x {} eps".format(
                                                    format_duration(dur), eps
                                                )
                                            )  # display as multiple episodes
                            else:
                                print("Undefined duration/episodes:", s)

                            # buttons
                            with tag(
                                "div",
                                klass="circular-buttons-container col-md-4 col-lg-3 col-xl-3",
                            ):
                                # databases
                                if s["database"] is not None:
                                    for db in s["database"]:
                                        # MAL
                                        if "mal" in db:
                                            # if multiple entries
                                            if isinstance(db["mal"], list):
                                                # place button
                                                list_hash_id = create_id(
                                                    name="{}{}".format(
                                                        str(s["name"]),
                                                        "".join(
                                                            list(map(str, db["mal"]))
                                                        ),
                                                    ),
                                                    octothorpe=True,
                                                )
                                                with tag(
                                                    "a",
                                                    ("role", "button"),
                                                    ("href", list_hash_id),
                                                    ("aria-expanded", "false"),
                                                    ("data-toggle", "collapse"),
                                                ):
                                                    doc.stag(
                                                        "img",
                                                        (
                                                            "src",
                                                            "./images/mal_icon.png",
                                                        ),
                                                        (
                                                            "alt",
                                                            "{} (MyAnimeList)".format(
                                                                s["name"]
                                                            ),
                                                        ),
                                                        ("class", "rounded-circle"),
                                                    )

                                            else:
                                                # if single entry
                                                mal_url = join_urls(
                                                    "https://myanimelist.net",
                                                    "anime",
                                                    db["mal"],
                                                )
                                                with tag("a", href=mal_url):
                                                    doc.stag(
                                                        "img",
                                                        (
                                                            "src",
                                                            """./images/mal_icon.png""",
                                                        ),
                                                        (
                                                            "alt",
                                                            "{} (MyAnimeList)".format(
                                                                s["name"]
                                                            ),
                                                        ),
                                                        ("class", "rounded-circle"),
                                                    )
                                        # add elifs for other databases here
                                        # (if expading later)
                                        else:
                                            print(
                                                "Warning, found unknown database:", db
                                            )

                                # streaming
                                if s["streaming"] is not None:
                                    for vid in s["streaming"]:
                                        if "youtube" in vid:
                                            # if list of videos
                                            if isinstance(vid["youtube"], list):
                                                # print("Creating list for", s['name'])
                                                list_hash_id = create_id(
                                                    name="{}{}".format(
                                                        str(s["name"]),
                                                        "".join(
                                                            list(
                                                                map(str, vid["youtube"])
                                                            )
                                                        ),
                                                    ),
                                                    octothorpe=True,
                                                )
                                                with tag(
                                                    "a",
                                                    ("role", "button"),
                                                    ("href", list_hash_id),
                                                    ("aria-expanded", "false"),
                                                    ("data-toggle", "collapse"),
                                                ):
                                                    doc.stag(
                                                        "img",
                                                        (
                                                            "src",
                                                            "./images/yt_icon.png",
                                                        ),
                                                        (
                                                            "alt",
                                                            "{} (Youtube)".format(
                                                                s["name"]
                                                            ),
                                                        ),
                                                        ("class", "rounded-circle"),
                                                    )
                                                    if s["cc"]:
                                                        with tag(
                                                            "span",
                                                            ("class", "badge cc"),
                                                            ("data-toggle", "tooltip"),
                                                            (
                                                                "data-original-title",
                                                                "Videos have Subtitles",
                                                            ),
                                                        ):
                                                            text("CC")
                                            else:
                                                # single video
                                                with tag(
                                                    "a",
                                                    href=join_urls(
                                                        "https://youtu.be"
                                                        if "playlist"
                                                        not in vid["youtube"]
                                                        else "https://youtube.com",
                                                        vid["youtube"],
                                                    ),
                                                ):
                                                    doc.stag(
                                                        "img",
                                                        (
                                                            "src",
                                                            "./images/yt_icon.png",
                                                        ),
                                                        (
                                                            "alt",
                                                            "{} (Youtube)".format(
                                                                s["name"]
                                                            ),
                                                        ),
                                                        ("class", "rounded-circle"),
                                                    )
                                                    if s["cc"]:
                                                        with tag(
                                                            "span",
                                                            ("class", "badge cc"),
                                                            ("data-toggle", "tooltip"),
                                                            (
                                                                "data-original-title",
                                                                "Video has Subtitles",
                                                            ),
                                                        ):
                                                            text("CC")

                                        elif "vimeo" in vid:
                                            # if list of videos
                                            if isinstance(vid["vimeo"], list):
                                                list_hash_id = create_id(
                                                    name="{}{}".format(
                                                        str(s["name"]),
                                                        "".join(
                                                            list(map(str, vid["vimeo"]))
                                                        ),
                                                    ),
                                                    octothorpe=True,
                                                )
                                                with tag(
                                                    "a",
                                                    ("role", "button"),
                                                    ("href", list_hash_id),
                                                    ("aria-expanded", "false"),
                                                    ("data-toggle", "collapse"),
                                                ):
                                                    doc.stag(
                                                        "img",
                                                        (
                                                            "src",
                                                            "./images/vimeo_icon.png",
                                                        ),
                                                        (
                                                            "alt",
                                                            "{} (Vimeo)".format(
                                                                s["name"]
                                                            ),
                                                        ),
                                                        ("class", "rounded-circle"),
                                                    )
                                            else:
                                                # single video
                                                with tag(
                                                    "a",
                                                    href=join_urls(
                                                        "https://vimeo.com",
                                                        vid["vimeo"],
                                                    ),
                                                ):
                                                    doc.stag(
                                                        "img",
                                                        (
                                                            "src",
                                                            "./images/vimeo_icon.png",
                                                        ),
                                                        (
                                                            "alt",
                                                            "{} (Vimeo)".format(
                                                                s["name"]
                                                            ),
                                                        ),
                                                        ("class", "rounded-circle"),
                                                    )
                                        elif "crunchyroll" in vid:
                                            with tag(
                                                "a",
                                                href=join_urls(
                                                    "http://www.crunchyroll.com",
                                                    vid["crunchyroll"],
                                                ),
                                            ):
                                                doc.stag(
                                                    "img",
                                                    (
                                                        "src",
                                                        "./images/cr_icon.png",
                                                    ),
                                                    (
                                                        "alt",
                                                        "{} (Crunchyroll)".format(
                                                            s["name"]
                                                        ),
                                                    ),
                                                    ("class", "rounded-circle"),
                                                )
                                        elif "netflix" in vid:
                                            with tag(
                                                "a",
                                                href=join_urls(
                                                    "https://www.netflix.com",
                                                    "title",
                                                    vid["netflix"],
                                                ),
                                            ):
                                                doc.stag(
                                                    "img",
                                                    (
                                                        "src",
                                                        "./images/netflix_icon.png",
                                                    ),
                                                    (
                                                        "alt",
                                                        "{} (Netflix)".format(
                                                            s["name"]
                                                        ),
                                                    ),
                                                    ("class", "rounded-circle"),
                                                )
                                        elif "funimation" in vid:
                                            with tag(
                                                "a",
                                                href=join_urls(
                                                    "https://www.funimation.com",
                                                    "shows",
                                                    vid["funimation"],
                                                ),
                                            ):
                                                doc.stag(
                                                    "img",
                                                    (
                                                        "src",
                                                        "./images/fn_icon.png",
                                                    ),
                                                    (
                                                        "alt",
                                                        "{} (Funimation)".format(
                                                            s["name"]
                                                        ),
                                                    ),
                                                    ("class", "rounded-circle"),
                                                )
                                        elif "hidive" in vid:
                                            with tag(
                                                "a",
                                                href=join_urls(
                                                    "https://www.hidive.com",
                                                    "tv",
                                                    str(vid["hidive"]),
                                                ),
                                            ):
                                                doc.stag(
                                                    "img",
                                                    (
                                                        "src",
                                                        "./images/hidive_icon.png",
                                                    ),
                                                    (
                                                        "alt",
                                                        "{} (Hidive)".format(s["name"]),
                                                    ),
                                                    ("class", "rounded-circle"),
                                                )

                                        elif "twitter" in vid:
                                            with tag(
                                                "a",
                                                href=join_urls(vid["twitter"]),
                                            ):
                                                doc.stag(
                                                    "img",
                                                    (
                                                        "src",
                                                        "./images/twitter.svg",
                                                    ),
                                                    (
                                                        "alt",
                                                        "{} (Twitter)".format(
                                                            s["name"]
                                                        ),
                                                    ),
                                                    ("class", "rounded-circle"),
                                                )
                                        elif "website" in vid:
                                            if "attraction-lemanga" in vid["website"]:
                                                with tag("a", href=vid["website"]):
                                                    doc.stag(
                                                        "img",
                                                        (
                                                            "src",
                                                            "./images/attraction_icon.png",
                                                        ),
                                                        (
                                                            "alt",
                                                            "attraction-lemanga website",
                                                        ),
                                                        ("class", "rounded-circle"),
                                                    )
                                            else:
                                                print(
                                                    "Warning, unfound 'source' in streaming:",
                                                    vid,
                                                )
                                        else:
                                            print(
                                                "Warning, unfound 'source' in streaming:",
                                                vid,
                                            )

                        # HIDDEN ROWS
                        # insert hidden row for extra info if ⓘ exists
                        if s["extra_info"] is not None:
                            with tag(
                                "div",
                                klass="collapse border rounded-bottom border-top-0 mb-1",
                                id=create_id(
                                    name="{}-extra-info".format(s["name"]),
                                    octothorpe=False,
                                ),
                            ):
                                with tag("p", klass="pl-2 mb-0"):
                                    text(str(s["extra_info"]))

                        # insert hidden row for databases
                        if s["database"] is not None:
                            for db in s["database"]:
                                if "mal" in db and isinstance(db["mal"], list):
                                    list_hash_id = create_id(
                                        name="{}{}".format(
                                            str(s["name"]),
                                            "".join(list(map(str, db["mal"]))),
                                        ),
                                        octothorpe=False,
                                    )
                                    with tag(
                                        "div",
                                        klass="collapse rounded mb-2",
                                        id=list_hash_id,
                                    ):
                                        with tag("div", klass="list-group"):
                                            for entry in db["mal"]:
                                                with tag(
                                                    "a",
                                                    klass="list-group-item list-group-item-action",
                                                    href=join_urls(
                                                        "https://myanimelist.net",
                                                        "anime",
                                                        entry,
                                                    ),
                                                ):
                                                    if download_names:
                                                        text(mal_cache.get(entry))
                                                    else:
                                                        text(entry)
                            # insert hidden rows for youtube/vimeo
                        if s["streaming"] is not None:
                            for vid in s["streaming"]:
                                # multiple youtube videos
                                if "youtube" in vid and isinstance(
                                    vid["youtube"], list
                                ):
                                    list_hash_id = create_id(
                                        name="{}{}".format(
                                            str(s["name"]),
                                            "".join(list(map(str, vid["youtube"]))),
                                        ),
                                        octothorpe=False,
                                    )
                                    with tag(
                                        "div",
                                        klass="collapse rounded mb-2",
                                        id=list_hash_id,
                                    ):
                                        with tag("div", klass="list-group"):
                                            # check if episodes have names [
                                            # correlates to MAL entries 1-1 ]
                                            for db in s["database"]:
                                                if "mal" in db and isinstance(
                                                    db["mal"], list
                                                ):
                                                    for mal_id, v in zip(
                                                        db["mal"], vid["youtube"]
                                                    ):
                                                        with tag(
                                                            "a",
                                                            klass="list-group-item list-group-item-action",
                                                            href=join_urls(
                                                                "https://youtu.be", v
                                                            ),
                                                        ):
                                                            text(mal_cache.get(mal_id))
                                                else:  # else use 'episode 1,2,3' as link text
                                                    for i, v in enumerate(
                                                        vid["youtube"], 1
                                                    ):
                                                        with tag(
                                                            "a",
                                                            klass="list-group-item list-group-item-action",
                                                            href=join_urls(
                                                                "https://youtu.be", v
                                                            ),
                                                        ):
                                                            text("Episode {}".format(i))
                                # multiple vimeo videos
                                elif "vimeo" in vid and isinstance(vid["vimeo"], list):
                                    list_hash_id = create_id(
                                        name="{}{}".format(
                                            str(s["name"]),
                                            "".join(list(map(str, vid["vimeo"]))),
                                        ),
                                        octothorpe=False,
                                    )
                                    with tag(
                                        "div",
                                        klass="collapse rounded mb-2",
                                        id=list_hash_id,
                                    ):
                                        with tag("div", klass="list-group"):
                                            for i, v in enumerate(vid["vimeo"], 1):
                                                with tag(
                                                    "a",
                                                    klass="list-group-item list-group-item-action",
                                                    href=join_urls(
                                                        "https://vimeo.com", v
                                                    ),
                                                ):
                                                    text("Episode {}".format(i))
            # footer
            doc.asis("<!-- footer -->")
            with tag("footer", ("class", "bg-dark footer")):
                with tag("div", klass="container center"):
                    with tag("div", klass="row justify-content-center py-2"):
                        with tag("p", klass="mb-0"):
                            text("© PurplePinapples")
                with tag("a", klass="d-none", href=constants.user_link):
                    pass
            doc.asis("<!-- javascript/popper.js -->")
            doc.asis(
                """<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>"""
            )
            with tag("script"):
                doc.asis(
                    """
// function to filter the list page to include only particular badges
function filterBadge(badgeSlug, clickedTooltip) {
    document.querySelectorAll(".anime-row-container").forEach((anime) => {
        // set display property accordingly if the tag the user clicked on is included in this entry
        anime.style.display = (anime.querySelector(`span.badge.${badgeSlug}`) === null) ? 'none': '';
    });
    // disable/re-enable tooltip to fix visual display bug
    if (typeof clickedTooltip !== null) {
        $(clickedTooltip).tooltip("dispose")
        $(clickedTooltip).tooltip({
            placement: "top"
        });
    }
    window.location.hash = badgeSlug
}

// runs when document is loaded:
document.addEventListener('DOMContentLoaded', function() {
  // activate CC tooltips
  $('span.cc').tooltip({
    placement: "top"
  });

  //activate ? tooltip
  $('span.ordernote').tooltip({
    placement: "bottom"
  });

  // activate tooltip for badge link filters
  $('.badge-link').tooltip({
    placement: "top"
  })

  // sort by rec order/date added
  $('#orderchoice button').click(function() {
    $('#sort').val($(this).text().trim());
    $('#choiceform').submit();
  });

  // footer onclick
  let footer = document.querySelector("footer.footer");
  footer.onmouseup = function(a) { // when mouse is released
    if (a.ctrlKey || a.metaKey || a.which == 2) {
      a.preventDefault(); // prevent middle click from opening tab, so it doesnt open twice.
      window.open($(footer).find('a').attr("href"));
    } else {
      window.location = $(footer).find('a').attr("href");
    }
  }

  // check url to filter by tag onload
  if (window.location.hash.slice(1)) {
    filterBadge(window.location.hash.slice(1), null)
  }
}, false);

"""
                )
    return indent(doc.getvalue(), indent_text=True)
Example #11
0
    def generate_new_chapter(self,
                             manga_title,
                             chapter_title,
                             page_list,
                             destination,
                             prefix='',
                             previous='#',
                             next='#'):
        """
        manga_title (str): title of the manga the chapter belongs to
        chapter_title (str): title of chapter the page belongs to
        page_list (list): list of pages in numerical order
        destination (str): save path for the chapter html file

        prefix (str): relative path to pages
        previous (str): relative path to previous chapter html
        next (str): relative path to next chapter html

        Creates a new html file containing all pages and named (chapter_title).html
        """

        m = manga.databases[manga_title].get_info()

        doc, tag, text = Doc().tagtext()

        manga_link = os.path.join('..', manga_title + '.html')

        # html
        doc.asis('<!DOCTYPE html>')
        doc.asis('<html lang="en" dir="ltr">')
        with tag('head'):
            doc.asis('<meta charset="utf-8">')
            doc.asis('<link rel="stylesheet" href="../style.css">')
            with tag('title'):
                text(manga_title + ' - ' + chapter_title)
        with tag('body'):
            doc.asis(self.header(manga_title, manga_link))

            with tag('div', klass='divider'):
                pass

            doc.asis(self.chapter_header(chapter_title, next, previous))

            # loop through the page list
            for page in page_list:
                # add_manga img tag
                doc.stag(
                    'img',
                    src=self.verify_source(os.path.join(prefix, page)),
                    klass='page',
                    style=
                    f"margin:{0 if m.is_manhwa else self.chapter_seperation}px auto;"
                )

            doc.asis(self.chapter_header(chapter_title, next, previous))
            doc.asis(self.footer())

            doc.asis(
                '<script type="text/javascript" src="../script.js"></script>')

        doc.asis('</html>')

        # save html doc in (destination)
        with open(destination, 'w') as f:
            f.write(doc.getvalue())
def main():
    """Main entry point"""
    parser = argparse.ArgumentParser(prog="report2html.py")
    parser.add_argument("--title", default="Report")
    parser.add_argument("--sub-title")
    args, _ = parser.parse_known_args()

    # -------------------------------------------------------------------------

    title = args.title
    if args.sub_title:
        title = f"{title} ({args.sub_title})"

    results = json.load(sys.stdin)
    stats = results

    expected = results["expected"]
    actual = results["actual"]

    # -------------------------------------------------------------------------

    doc, tag, text = Doc().tagtext()
    doc.asis("<!DOCTYPE html>")

    with tag("html"):
        with tag("head"):
            with tag("title"):
                text(title)

            with tag("style", type="text/css"):
                doc.asis(css())

        with tag("body"):
            with tag("h1"):
                text(title)

            with tag("p"):
                text(f"Date: {datetime.now()}%")

            with tag("p"):
                text(
                    f"Intent/Entity Accuracy: {stats['intent_entity_accuracy']*100:.2f}%"
                )

            with tag("p"):
                text(f"Intent Accuracy: {stats['intent_accuracy']*100:.2f}%")

            with tag("p"):
                text(f"Entity Accuracy: {stats['entity_accuracy']*100:.2f}%")

            with tag("p"):
                text(
                    f"Transcription Accuracy: {stats['transcription_accuracy']*100:.2f}%"
                )

            with tag("p"):
                text(
                    f"Average Transcription Speed-Up: {stats['average_transcription_speedup']:.2f}x"
                )

            with tag("table", klass="pure-table pure-table-bordered"):
                with tag("thead"):
                    with tag("th"):
                        text("Key")

                    with tag("th"):
                        text("Intent")

                    with tag("th"):
                        text("Text")

                    with tag("th"):
                        text("Errors")

                with tag("tbody"):
                    for key, actual_intent in sorted(
                            actual.items(),
                            key=lambda kv: sort_score(kv[1]),
                            reverse=True):
                        expected_intent = expected[key]
                        expected_intent_name = expected_intent["intent"][
                            "name"]
                        expected_entities = expected_intent.get("entities", [])

                        wer = actual_intent["word_error"]
                        num_errors = wer["errors"]
                        expected_text = " ".join(wer["reference"])

                        actual_intent_name = actual_intent["intent"]["name"]
                        actual_text = " ".join(wer["hypothesis"])
                        actual_entities = actual_intent.get("entities", [])

                        row_class = "match"
                        if actual_intent_name != expected_intent_name:
                            row_class = "error"

                        wrong_entities = actual_intent.get(
                            "wrong_entities", [])
                        missing_entities = actual_intent.get(
                            "missing_entities", [])
                        if len(wrong_entities) > 0 or len(
                                missing_entities) > 0:
                            if actual_intent_name == expected_intent_name:
                                row_class = "warn"
                            else:
                                row_class = "error"

                        # Expected
                        with tag("tr"):
                            # Key
                            with tag("td"):
                                text(key)

                            # Intent
                            with tag("td"):
                                text(expected_intent_name)

                            # Text
                            with tag("td"):
                                with tag("tt"):
                                    text(expected_text)

                            # Errors
                            with tag("td"):
                                text("")

                        with tag("tr"):
                            # Key
                            with tag("td"):
                                doc.asis("&#9733;" if actual_text ==
                                         expected_text else "")

                            # Intent
                            with tag("td"):
                                text("")

                            # Text
                            with tag("td"):
                                with tag("tt"):
                                    text(entity_str(expected_entities))

                            # Errors
                            with tag("td"):
                                text("")

                        # Actual
                        with tag("tr", klass=row_class):
                            # Key
                            with tag("td"):
                                text(key)

                            # Intent
                            with tag("td"):
                                text(actual_intent_name)

                            # Text
                            with tag("td"):
                                with tag("tt"):
                                    text(actual_text)

                            # Errors
                            with tag("td"):
                                text(num_errors)

                        with tag("tr", klass=row_class):
                            # Key
                            with tag("td"):
                                text("")

                            # Intent
                            with tag("td"):
                                text("")

                            # Text
                            with tag("td"):
                                with tag("tt"):
                                    text(entity_str(actual_entities))

                            # Errors
                            with tag("td"):
                                text("")

                        # Empty row
                        with tag("tr", klazz="black"):
                            for i in range(4):
                                with tag("td"):
                                    text("")

        # Timestamp
        with tag("hr"):
            pass

        with tag("p"):
            text(str(datetime.now()))

    print(indent(doc.getvalue()))
Example #13
0
def generate_plot_browser(plot_browser_dir, load_data, base_url_dir,
                          github_url, full_report_filename, list_of_figures,
                          list_of_figures_full_report):
    if not path.exists(plot_browser_dir):
        os.mkdir(plot_browser_dir)

    alphabetical_states = sorted(load_data.map_state_to_population.keys())
    alphabetical_states.remove('total')
    alphabetical_states = ['total'] + alphabetical_states

    map_state_to_html = dict()
    for state in alphabetical_states:

        state_lc = state.lower().replace(' ', '_')
        doc, tag, text = Doc(defaults={
            'title': f'Plots for {state}'
        }).tagtext()

        doc.asis('<!DOCTYPE html>')
        with tag('html'):
            with tag('head'):
                pass
            with tag('body'):
                with tag('div', id='photo-container'):
                    with tag('ul'):
                        with tag('li'):
                            with tag('a', href='../index.html'):
                                text('<-- Back')
                        for figure_name in list_of_figures:
                            tmp_url = base_url_dir + state_lc + '/' + figure_name
                            with tag("a", href=tmp_url):
                                doc.stag('img',
                                         src=tmp_url,
                                         klass="photo",
                                         height="300",
                                         width="400")
                            with tag('li'):
                                with doc.tag("a", href=tmp_url):
                                    doc.text(figure_name)
                            with tag('hr'):
                                pass

        result = doc.getvalue()
        map_state_to_html[state] = result

    for state in map_state_to_html:
        state_lc = state.lower().replace(' ', '_')
        if not path.exists(path.join(plot_browser_dir, state_lc)):
            os.mkdir(path.join(plot_browser_dir, state_lc))
        with open(
                path.join(plot_browser_dir, path.join(state_lc, 'index.html')),
                'w') as f:
            f.write(map_state_to_html[state])

    #####
    # Generate state-report page
    #####

    with open(path.join(plot_browser_dir, full_report_filename), 'w') as f:
        doc, tag, text = Doc(defaults={
            'title': f'Plots for Full U.S. Report'
        }).tagtext()
        doc.asis('<!DOCTYPE html>')
        with tag('html'):
            with tag('head'):
                pass
            with tag('body'):
                with tag('div', id='photo-container'):
                    with tag('ul'):
                        with tag('li'):
                            with tag('a', href='index.html'):
                                text('<-- Back')
                        for figure_name in list_of_figures_full_report:
                            tmp_url = base_url_dir + figure_name
                            with tag("a", href=tmp_url):
                                doc.stag('img',
                                         src=tmp_url,
                                         klass="photo",
                                         height="400",
                                         width="300")
                            with tag('li'):
                                with doc.tag("a", href=tmp_url):
                                    doc.text(figure_name)
                            with tag('hr'):
                                pass
        f.write(doc.getvalue())

    #####
    # Generate landing page
    #####

    with open(path.join(plot_browser_dir, 'index.html'), 'w') as f:
        doc, tag, text = Doc(defaults={
            'title': f'Plots for {state}'
        }).tagtext()

        doc.asis('<!DOCTYPE html>')
        with tag('html'):
            with tag('head'):
                pass
            with tag('body'):
                with tag('ul'):
                    with tag('li'):
                        with tag("a", href=github_url):
                            text('<-- Back to Repository')
                    with tag('li'):
                        with tag("a", href=full_report_filename):
                            text('Full U.S. Report')
                    for state in alphabetical_states:
                        state_lc = state.lower().replace(' ', '_')
                        tmp_url = state_lc + '/index.html'
                        with tag('li'):
                            with tag("a", href=tmp_url):
                                text(state)
        f.write(doc.getvalue())
Example #14
0
    def get_html_from_daily_schedule(self, currentTime, bgImageURL, datalist, nowPlayingTitle):

        now = datetime.now()
        time = now.strftime("%B %d, %Y")
        doc, tag, text, line = Doc(

        ).ttl()
        doc.asis('<!DOCTYPE html>')
        with tag('html'):
            with tag('head'):
                with tag('title'):
                    text(time + " - Daily Pseudo Schedule")
                doc.asis('<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet">')
                doc.asis('<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>')
                doc.asis("""
        <script>
        $(function(){

            var refreshFlag = '';
            """
            +"""var controllerServerPath ='"""+self.CONTROLLER_SERVER_PATH+":"+self.CONTROLLER_SERVER_PORT+"""';

            if(controllerServerPath != ''){

                console.log("here");

                window.setInterval(function(){

                $.ajax({
                        url: controllerServerPath+"/pseudo_refresh.txt",
                        async: true,   // asynchronous request? (synchronous requests are discouraged...)
                        cache: false,   // with this, you can force the browser to not make cache of the retrieved data
                        dataType: "text",  // jQuery will infer this, but you can set explicitly
                        success: function( data, textStatus, jqXHR ) {
                            newFlag = data; 

                            if(refreshFlag != ''){
                            
                                if (refreshFlag != newFlag){

                                    location.reload();

                                } else {

                                    //do nothing
                                    console.log("skip");

                                }

                            } else {

                                refreshFlag = newFlag;

                            }

                        }
                    });
                }, 1000);

            } else {

                setTimeout(function() {location.reload();}, 30000);

            }

        });
        </script>
                            """)
                if bgImageURL != None:
                    doc.asis('<style>body{ background:transparent!important; } html { background: url('+bgImageURL+') no-repeat center center fixed; -webkit-background-size: cover;-moz-background-size: cover;-o-background-size: cover;background-size: cover;}.make-white { padding: 24px; background:rgba(255,255,255, 0.9); }</style>')
            with tag('body'):
                with tag('div', klass='container mt-3'):
                    with tag('div', klass='row make-white'):
                        with tag('div'):
                            with tag('div'):
                                line('h1', self.HTML_PSEUDO_TITLE, klass='col-12 pl-0')
                            with tag('div'):
                                line('h3', time, klass='col-12 pl-1')
                                line('h3', 
                                     "Now Playing: "+nowPlayingTitle, 
                                     klass='col-12 pl-1',
                                     style="color:red;")
                        with tag('table', klass='col-12 table table-bordered table-hover'):
                            with tag('thead', klass='table-info'):
                                with tag('tr'):
                                    with tag('th'):
                                        text('#')
                                    with tag('th'):
                                        text('Type')
                                    with tag('th'):
                                        text('Series')
                                    with tag('th'):
                                        text('Title')
                                    with tag('th'):
                                        text('Start Time')
                            numberIncrease = 0
                            for row in datalist:
                                if str(row[11]) == "Commercials" and self.DEBUG == False:
                                    continue
                                numberIncrease += 1
                                with tag('tbody'):
                                    if currentTime != None:
                                        currentTime = currentTime.replace(year=1900, month=1, day=1)
                                    timeBStart = datetime.strptime(row[8], '%I:%M:%S %p')
                                    timeBStart = timeBStart.replace(year=1900, month=1, day=1)
                                    try:
                                        timeBEnd = datetime.strptime(row[9], '%Y-%m-%d %H:%M:%S.%f')
                                    except:
                                        timeBEnd = datetime.strptime(row[9], '%Y-%m-%d %H:%M:%S')
                                    #print timeBStart
                                    if currentTime == None:
                                        with tag('tr'):
                                            with tag('th', scope='row'):
                                                text(numberIncrease)
                                            with tag('td'):
                                                text(row[11])
                                            with tag('td'):
                                                text(row[6])
                                            with tag('td'):
                                                text(row[3])
                                            with tag('td'):
                                                text(row[8])
                                    elif (currentTime - timeBStart).total_seconds() >= 0 and \
                                         (timeBEnd - currentTime).total_seconds() >= 0:

                                            #if self.DEBUG:
                                            print "+++++ Currently Playing:", row[3]

                                            with tag('tr', klass='bg-info'):
                                                with tag('th', scope='row'):
                                                    text(numberIncrease)
                                                with tag('td'):
                                                    text(row[11])
                                                with tag('td'):
                                                    text(row[6])
                                                with tag('td'):
                                                    text(row[3])
                                                with tag('td'):
                                                    text(row[8])
                                    else:
                                        with tag('tr'):
                                            with tag('th', scope='row'):
                                                text(numberIncrease)
                                            with tag('td'):
                                                text(row[11])
                                            with tag('td'):
                                                text(row[6])
                                            with tag('td'):
                                                text(row[3])
                                            with tag('td'):
                                                text(row[8])
        return indent(doc.getvalue())
Example #15
0
from yattag import Doc
from yattag import indent

data = {}
data["form_defaults"] = ""
data["form_errors"] = ""
data["article"] = {}
data["article"]["title"] = ""
data["article"]["description"] = ""
data['user'] = {}
# data['user']['username'] = ""

doc, tag, text, line = Doc(defaults=data['form_defaults'],
                           errors=data['form_errors']).ttl()


def connection_box(data):

    with tag('div', id='connection-box'):
        if data['user']:
            text('Hello ', data['user']['username'], '!')
        else:
            with tag('form', action='/connect'):
                line('label', 'Username:'******'username', type='text')

                line('label', 'Password:'******'password', type='password')

                doc.stag('input', type='submit', value='Connexion')
Example #16
0
def gen_personal_html(data):

    PERSONAL_TEMPLATE = '''
	<!DOCTYPE html>
	<html>
	<meta charset="UTF-8">
	<head>
		<title>KNC -- {knc_id}</title>
		<link rel="stylesheet" href="../style.css">
		{header_stuff}
	</head>
	<body style="padding-left: 20%;padding-right: 20%">
	<a href="../index.html">KNC Home</a>
	
	{everything_else}
	</body>
	</html>
	'''

    doc, tag, text = Doc().tagtext()

    # if they want a webpage redirect
    if ('redirect_page_to_website' in data and 'website' in data
            and data['redirect_page_to_website']):

        # do the redirect
        redirect_header = (
            '<meta http-equiv="refresh" content="0; URL=%s" />' %
            data['website'])

        # print a link also
        with tag('p'):
            text('redirecting to:')
            doc._append("<br/>")
            with tag('a', href=data['website']):
                text(data['website'])

        return PERSONAL_TEMPLATE.format(
            knc_id=data['knc_id'],
            everything_else=doc.getvalue(),
            header_stuff=redirect_header,
        )

    with tag('center'):
        with tag('h1'):
            text(data['name'])
        with tag('h2'):
            with tag('a', href='mailto:' + data['email']):
                text(data['email'])
        with tag('h2'):
            text(data['role'])

    if 'bio' in data:
        with tag('p'):
            text(data['bio'])

    links_list = ['github', 'website', 'CV']

    if any((x in data) for x in links_list):
        with tag('h2'):
            text('Links:')
        with tag('ul'):
            for x in links_list:
                if x in data:
                    with tag('li'):
                        with tag('a', href=data[x]):
                            text(x)

    if 'interests' in data:
        with tag('h2'):
            text('Interests:')
        with tag('p'):
            text(data['interests'])

    if 'proj_blurb' in data:
        with tag('h2'):
            text('Projects:')
        with tag('p'):
            text(data['proj_blurb'])

    return PERSONAL_TEMPLATE.format(
        knc_id=data['knc_id'],
        everything_else=doc.getvalue(),
        header_stuff='',
    )
Example #17
0
def lambda_handler(_, __):

    configuration = yaml.load(open("config.yaml").read())
    questions = configuration['Questions'];
    title = configuration['Title'];
    author = configuration['Author'];
    image = configuration['Image'];
    theme = configuration['Theme'];
    
    questionsNames = list()
    for questionIterator in questions:
        questionsNames.append(questionIterator)
    questionsNames.sort()
    
    doc, tag, text = Doc().tagtext()

    with tag('html'):
        with tag('body'):
                            
            doc.stag('br')
            doc.stag('br')
            doc.stag('br')
            
            with tag('div', align='center'):
                with doc.tag('div', style="font-size: medium;font-weight: bold; font-family: verdana; color:#" + str(theme) + ";"): 
                    text(title)
                    doc.stag('br')
                with doc.tag('div', style="font-size: small; font-weight: bold; font-family: verdana;"):
                    text("by " + author)
                    doc.stag('br')
                    doc.stag('img', src=image, width="500")
                    doc.stag('br')
                    doc.stag('br')
            
            with tag('form', action = "submitsurvey", style="margin-left: auto; margin-right: auto; width: 70%;"):
                for questionName in questionsNames:
                    with tag('div'):
                        questionLabel = questions[questionName]['Label']
                        questionType = questions[questionName]['Type']

                        #doc.stag('font', size="4", style="font-weight: bold; font-family: verdana; color:#" + str(theme) + ";")    
                        with doc.tag('div',style="font-size: medium;font-weight: bold; font-family: verdana; color:#" + str(theme) + ";"): 
                            doc.asis(questionLabel)
                            doc.stag('br')
                        
                        if (questionType == "Text"):
                            with doc.textarea(name = questionName, style="width: 100%; border-color: #" + str(theme) + "; " , rows="5"):
                                pass
                            
                        if (questionType == "ShortText"):  
                            with doc.textarea(name = questionName, style="width: 100%; border-color: #" + str(theme) + "; " , rows="1"):
                                pass
                            
                        if (questionType == "Radio"):
                            values = questions[questionName]['Values']
                            for valueIterator in values:
                                value = questions[questionName]['Values'][valueIterator]
                                with doc.tag('div', style="font-size: small; font-weight: normal; font-family: verdana; color:black;"):
                                    doc.input(name = questionName, type = 'radio', value = value, style="border-color: #" + str(theme) + "; ")
                                    text(" "+str(value))
                                    doc.stag('br')
                                
                        if (questionType == "CheckBox"):
                            with tag('fieldset',style="border: 0px; padding: 0px; font-size: small; font-weight: normal; font-family: verdana; color:black;"):
                                values = list(questions[questionName]['Values'])
                                for valueIterator in values:
                                    value = questions[questionName]['Values'][valueIterator]
                                    field_name = questionName + "_" + "".join([ c if c.isalnum() else "_" for c in value.lower() ])
                                    doc.input(name = field_name, type = 'hidden', value = "0",style="border-color: #" + str(theme) + "; ")
                                    doc.input(name = field_name, id = field_name ,  type = 'checkbox', value = "1", style="border-color: #" + str(theme) + "; ")
                                    text(" "+str(value))
                                    doc.stag('br')
                            
                        doc.stag('br')
                        doc.stag('br')
    
                doc.stag('input', type = "submit", value = "Send!", style="background-color: #" + str(theme) + "; border: none; color: white; float: right; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer;")




    htmlResult = doc.getvalue()

    return {
            'statusCode': "200",
            'body': htmlResult,
            'headers': {
                'Content-Type': 'text/html',
            }
        }
Example #18
0
def gen_proj_page(data):
    user_info = load_user_info()

    PERSONAL_TEMPLATE = '''
	<!DOCTYPE html>
	<html>
	<meta charset="UTF-8">
	<head>
		<title>KNC -- {projname}</title>
	<link rel="stylesheet" href="../../style.css">
	</head>
	<body style="padding-left: 20%;padding-right: 20%">
	<a href="../../index.html">KNC Home</a>
	
	{everything_else}
	</body>
	</html>
	'''

    doc, tag, text = Doc().tagtext()

    with tag('center'):
        with tag('h1'):
            text(data['projname'])
        doc._append("<br/>")

    with tag('center'):
        with tag('ul',
                 id="nav",
                 style="list-style-type: none; margin: 0; padding: 0"):
            for link in data['links']:
                with tag('a', href=data['links'][link]):
                    with tag('li'):
                        text(link)
        doc._append("<br/>")

    with tag('center'):
        with tag('h2'):
            with tag('b'):
                text('Contributors:  ')

            u_idx = 0
            for user in data['contributors']:
                if user[0] == '@':
                    with tag('a', href='../../' + user):
                        text(user_info[user]['name'])
                else:
                    text(user)
                u_idx += 1
                if u_idx < len(data['contributors']):
                    text(', ')
        doc._append("<br/>")

    text(data['long_desc'])

    doc._append("<br/>\n\n")

    if 'images' in data:
        for img in data['images']:
            doc._append('<img src="%s" style="width: 25vw;">\n' % img)

    doc._append("<br/>\n\n")

    return PERSONAL_TEMPLATE.format(
        projname=data['projname'],
        everything_else=doc.getvalue(),
    )
Example #19
0
def record_listens(request, data):
    """ Submit the listen in the lastfm format to be inserted in db.
        Accepts listens for both track.updateNowPlaying and track.scrobble methods.
    """
    output_format = data.get('format', 'xml')
    try:
        sk, api_key = data['sk'], data['api_key']
    except KeyError:
        raise InvalidAPIUsage(
            CompatError.INVALID_PARAMETERS,
            output_format=output_format)  # Invalid parameters

    session = Session.load(sk)
    if not session:
        if not Token.is_valid_api_key(api_key):
            raise InvalidAPIUsage(
                CompatError.INVALID_API_KEY,
                output_format=output_format)  # Invalid API_KEY
        raise InvalidAPIUsage(
            CompatError.INVALID_SESSION_KEY,
            output_format=output_format)  # Invalid Session KEY

    lookup = defaultdict(dict)
    for key, value in data.items():
        if key in ["sk", "token", "api_key", "method", "api_sig"]:
            continue
        matches = re.match('(.*)\[(\d+)\]', key)
        if matches:
            key = matches.group(1)
            number = matches.group(2)
        else:
            number = 0
        lookup[number][key] = value

    if request.form['method'].lower() == 'track.updatenowplaying':
        for i, listen in lookup.items():
            if 'timestamp' not in listen:
                listen['timestamp'] = calendar.timegm(
                    datetime.now().utctimetuple())

    # Convert to native payload then submit 'em after validation.
    listen_type, native_payload = _to_native_api(lookup, data['method'],
                                                 output_format)
    for listen in native_payload:
        validate_listen(listen, listen_type)

    user = db_user.get(session.user_id)
    augmented_listens = insert_payload(native_payload,
                                       user,
                                       listen_type=listen_type)

    # With corrections than the original submitted listen.
    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        if listen_type == 'playing_now':
            doc.asis(
                create_response_for_single_listen(
                    list(lookup.values())[0], augmented_listens[0],
                    listen_type))
        else:
            accepted_listens = len(lookup.values())
            # Currently LB accepts all the listens and ignores none
            with tag('scrobbles', accepted=accepted_listens, ignored='0'):
                for original_listen, augmented_listen in zip(
                        list(lookup.values()), augmented_listens):
                    doc.asis(
                        create_response_for_single_listen(
                            original_listen, augmented_listen, listen_type))

    return format_response(
        '<?xml version="1.0" encoding="utf-8"?>\n' +
        yattag.indent(doc.getvalue()), output_format)
Example #20
0
    def toc_to_html(self, match, current=None, depth=1):
        """Convert TOC to a plain string.

    Parameters
    ----------
    match: re.match()
    current: [current_chapter, current_section, current_subsection, current_slide]
      eventual current chpater-section-subsection-slide number
    depth: int
      depth of TOC: 4 => up-to slides, 3 => up-to subsections, 2 => up-to sections, 1 => only chapters

    Returns
    -------
    str:
      plain string of TOC
    """
        def get_style(match):
            """Get TOC style if one.

      Parameters
      ----------
      match: re.match()

      Returns
      -------
      str:
        style
      """
            style = None
            if match.group('style'):
                style = str(match.group('style'))
            return style

        def get_actual_depth(style, depth):
            """Get the actual depth of TOC using the eventual provided depth or the one defined into the style.

      Parameters
      ----------
      style: str
      depth: int
        depth of TOC: 4 => up-to slides, 3 => up-to subsections, 2 => up-to sections, 1 => only chapters

      Returns
      -------
      int:
        actual depth
      """
            actual_depth = int(depth)
            if style is not None:
                if 'depth' in style.lower():
                    match_depth = re.search(r'depth\:(?P<depth>[1-4])\;*',
                                            style)
                    if match_depth.group('depth'):
                        actual_depth = int(match_depth.group('depth'))
            return actual_depth

        style = get_style(match=match)
        actual_depth = get_actual_depth(style=style, depth=depth)
        doc = Doc()
        # numbering: [local_chap, local_sec, local_subsec, local_slide, global_slide]
        actual_current = [0, 0, 0, 0, 1]
        with doc.tag('div', klass='toc'):
            if style is not None:
                doc.attr(style=style)
            self.toc_put_chapters(doc=doc,
                                  depth=actual_depth,
                                  actual_current=actual_current,
                                  current=current)
        return '\n' + doc.getvalue()
Example #21
0
    def render(self):
        '''
        This renders an in-line preview of a question set
        '''
        doc, tag, text = Doc().tagtext()

        with tag('div', ('class', 'preview')):
            for question in self.question_list:

                #initialize string indexer
                si = 0
                raise_next = 0
                #render a question in its own div
                with tag('div', ('class', 'question')):
                    while question[si:] != '':

                        #if we are dealing with a token marker, start token processing
                        if question[si] in self.tokens:

                            if question[si] == self.ts_reading:
                                renderd_question = self.reading(
                                    question[si + 1:], 'preview')
                            elif question[si] == self.ts_writing:
                                renderd_question = self.writing(
                                    question[si + 1:], 'preview')
                            elif question[si] == self.ts_furi:
                                renderd_question = self.furigana(
                                    question[si + 1:], 'preview')
                            elif question[si] == self.ts_combo:
                                renderd_question = self.combo(
                                    question[si + 1:], 'preview')

                            doc.asis(renderd_question[0])
                            raise_next = renderd_question[1]
                            #eat the token untill we find its closure
                            while question[si] not in self.close_tokens:
                                si += 1

                            si += 1  # eat the closing marker of this token
                        else:  #this is just "normal" output

                            # if we got a raise parameter from the render_question call
                            # this is where we'll use it
                            div_style = ''
                            if raise_next != 0:
                                div_style = f'margin-top: {raise_next}px'
                            with tag('div', ('class', 'hiragana-90'),
                                     style=div_style):
                                with tag('div', ('class', 'hiragana-content')):
                                    with tag('div'):
                                        text(' ')
                                    with tag('div'):
                                        h = ""
                                        while (question[si - 1:] !=
                                               '') and (question[si:si + 1]
                                                        not in self.tokens):
                                            h = h + question[si]
                                            si += 1
                                        text(h)
                                    with tag('div'):
                                        text(' ')
                                with tag('div'):
                                    text(' ')
        return doc.getvalue()
def navbar(active, **kwargs):
    """'active' determines which tab is highlighted"""
    if not kwargs:
        sorttab = None
    else:
        sorttab = kwargs["sorttab"]
    doc, tag, text = Doc().tagtext()
    with tag(
        "nav",
        klass="navbar navbar-expand-lg navbar-dark bg-dark navbar-static-top container",
    ):
        # hamburger menu
        with tag(
            "button",
            ("class", "navbar-toggler"),
            ("data-toggle", "collapse"),
            ("data-target", "#collapse_navbar_target"),
        ):
            with tag("span", klass="navbar-toggler-icon"):
                text()
        # navbar title
        with tag("a", klass="navbar-brand text-nowrap mr-3 my-2", href="./"):
            text(constants.FULL_NAME)
        # collapsable page links
        with tag("div", klass="collapse navbar-collapse", id="collapse_navbar_target"):
            with tag("ul", klass="navbar-nav nav-pills dark-blue"):
                with tag(
                    "li",
                    klass="nav-item{}".format(
                        " active" if active == constants.LIST_TAB else ""
                    ),
                ):
                    with tag(
                        "a",
                        ("class", "nav-link px-2"),
                        (
                            "style",
                            "{}".format(
                                "background-color: #385289;"
                                if active == constants.LIST_TAB
                                else ""
                            ),
                        ),
                        ("href", "./"),
                    ):
                        text(constants.LIST_TAB)
                with tag(
                    "li",
                    klass="nav-item{}".format(
                        " active" if active == constants.PEOPLE_TAB else ""
                    ),
                ):
                    with tag(
                        "a",
                        ("class", "nav-link px-2"),
                        (
                            "style",
                            "{}".format(
                                "background-color: #385289;"
                                if active == constants.PEOPLE_TAB
                                else ""
                            ),
                        ),
                        ("href", "./people"),
                    ):
                        text(constants.PEOPLE_TAB)
            if active == constants.LIST_TAB:
                with tag("ul", klass="navbar-nav pr-2"):
                    with tag("li", klass="nav-item"):
                        with tag(
                            "a",
                            klass="mx-2",
                            style="color: white; position: relative; top: 0.1rem;",
                        ):
                            text("Order By:")
                        with tag(
                            "div",
                            ("class", "btn-group ml-1"),
                            ("role", "group"),
                        ):
                            with tag("form", ("action", "./"), ("class", "btn-group")):
                                with tag(
                                    "button",
                                    (
                                        "class",
                                        "btn btn-secondary{}".format(
                                            " active"
                                            if sorttab == constants.order.REC
                                            else ""
                                        ),
                                    ),
                                ):
                                    text("Recommendation")
                            with tag(
                                "form", ("action", "./newest"), ("class", "btn-group")
                            ):
                                with tag(
                                    "button",
                                    (
                                        "class",
                                        "btn btn-secondary{}".format(
                                            " active"
                                            if sorttab == constants.order.DATE
                                            else ""
                                        ),
                                    ),
                                ):
                                    text("Date Added")
                            with tag(
                                "span",
                                (
                                    "style",
                                    "color: white; position: relative; top: 0.3rem;",
                                ),
                                ("class", "ml-2 badge ordernote"),
                                ("data-toggle", "tooltip"),
                                (
                                    "data-original-title",
                                    "Recommendation lists better entries near the top. Date Added lists entries I added to the list recently at the top.",
                                ),
                            ):
                                text("?")
            with tag("ul", klass="navbar-nav p-2"):
                with tag("li", klass="nav-item"):
                    with tag(
                        "a",
                        (
                            "href",
                            "https://github.com/seanbreckenridge/animeshorts",
                        ),
                    ):
                        doc.stag(
                            "img",
                            ("src", """./images/github.png"""),
                            ("alt", "Source on Github"),
                            ("style", "max-height: 40px; width: auto; invert(80);"),
                        )

    return indent(doc.getvalue(), indent_text=True)
Example #23
0
def page(S=None):
    doc, tag, text = Doc().tagtext()
    if S:
        with tag('div', klass='wrapper'):
            doc, tag, text = prof_menu.sidebar(doc, tag, text)
            with tag('div', id='content'):
                with tag('div', klass='container-fluid ajouter'):

                    with tag(
                            'table',
                            id='table_prof_sujet',
                            klass=
                            "table table-striped table-bordered table-sm top-buffer",
                            cellspacing="0",
                            width="100%"):
                        with tag('thead'):
                            with tag('tr', klass='text-center'):
                                with tag('th', cope="col"):
                                    text('Actif')
                                with tag('th', cope="col"):
                                    text('Titre')
                                with tag('th', scope="col"):
                                    text('Programme')
                                with tag('th', scope="col"):
                                    text('Filière')
                                with tag('th',
                                         scope="col",
                                         klass='text-center'):
                                    text('Modifier')
                                with tag('th',
                                         scope="col",
                                         klass='text-center'):
                                    text('Supprimer')

                        with tag('tbody'):
                            """A FAIRE UNE BOUCLE POUR LES sujets"""
                            with tag('tr'):
                                with tag('td',
                                         scope="col",
                                         klass='text-center'):
                                    with tag('input',
                                             type='checkbox',
                                             value='0'):
                                        pass
                                with tag('td', scope="col"):
                                    with tag(
                                            'textarea',
                                            klass='disable_text text',
                                            placeholder='Sujet sur les tomates'
                                    ):
                                        pass
                                with tag('td', scope="col"):
                                    with tag('textarea',
                                             klass='disable_text text',
                                             placeholder='Agriculture'):
                                        pass
                                with tag('td', scope="col"):
                                    with tag('textarea',
                                             klass='disable_text text',
                                             placeholder='Eco'):
                                        pass
                                with tag('td',
                                         scope="col",
                                         klass='mouse_hand text-center'):
                                    with tag('img',
                                             src='./dist/images/pencil.png',
                                             id="myBtn"):
                                        pass
                                with tag('td',
                                         scope="col",
                                         klass='mouse_hand text-center'):
                                    with tag('img',
                                             src='./dist/images/bin.png',
                                             onclick='change()'):
                                        pass
                                """ MODAL """
                                with tag('div', id='myModal', klass='modal'):
                                    with tag('div', klass='modal-content'):
                                        with tag('span', klass='close'):
                                            text("Fermer")

                                        with tag(
                                                'row',
                                                klass=
                                                'row justify-content-center top-buffer'
                                        ):

                                            with tag('form'):
                                                """ajouter sujet"""
                                                with tag('row',
                                                         id="ajouter_sujet",
                                                         klass='cacher'):

                                                    # """Demander si le sujet sera actif pendant des années"""
                                                    # with tag('div', klass='row justify-content-center top-buffer'):
                                                    # with tag('div', klass='col-sm-4 text-center'):
                                                    # with tag('label', klass='switch'):
                                                    # doc.input( type = 'checkbox', name = 'valable_des_annees', value = '0')
                                                    # with tag('span',klass='slider round'):
                                                    # text('Sujet valable plusieures années ?')

                                                    with tag(
                                                            'row',
                                                            klass=
                                                            'row justify-content-center top-buffer'
                                                    ):

                                                        with tag(
                                                                'row',
                                                                klass=
                                                                'col-sm-10 text-center mod_width_textarea'
                                                        ):
                                                            with tag(
                                                                    'textarea',
                                                                    placeholder
                                                                    ='Titre'):
                                                                pass
                                                        with tag(
                                                                'row',
                                                                klass=
                                                                'col-sm-10 text-center mod_width_textarea'
                                                        ):
                                                            with tag(
                                                                    'textarea',
                                                                    placeholder=
                                                                    'Descriptif'
                                                            ):
                                                                pass

                                                    with tag(
                                                            'row',
                                                            klass=' top-buffer'
                                                    ):

                                                        with tag('div',
                                                                 klass='row'):
                                                            """Afficher dynamiquement les programmes"""
                                                            with tag(
                                                                    'div',
                                                                    klass=
                                                                    'col-6 text-center'
                                                            ):
                                                                with tag(
                                                                        'div',
                                                                        id=
                                                                        "programmes"
                                                                ):
                                                                    text(
                                                                        'Programmes : '
                                                                    )
                                                                    with tag(
                                                                            'div'
                                                                    ):
                                                                        for p in programme:
                                                                            with tag(
                                                                                    'div'
                                                                            ):
                                                                                # , klass='switch'):
                                                                                with tag(
                                                                                        'label'
                                                                                ):
                                                                                    doc.input(
                                                                                        type
                                                                                        ='checkbox',
                                                                                        name
                                                                                        =p,
                                                                                        value
                                                                                        ='0',
                                                                                        onclick
                                                                                        ='afficherFilFin()'
                                                                                    )
                                                                                    with tag(
                                                                                            'span',
                                                                                            id
                                                                                            =p
                                                                                            +
                                                                                            '1'
                                                                                    ):
                                                                                        text(
                                                                                            p
                                                                                        )
                                                            """Afficher dynamiquement les filières"""
                                                            with tag(
                                                                    'div',
                                                                    klass=
                                                                    'filiere col-6 text-center',
                                                                    id=
                                                                    'FiliereFin'
                                                            ):
                                                                with tag(
                                                                        'div'):
                                                                    text(
                                                                        'Filiére : '
                                                                    )
                                                                    with tag(
                                                                            'div'
                                                                    ):
                                                                        for f in programme[
                                                                                'Finances']:
                                                                            with tag(
                                                                                    'div'
                                                                            ):
                                                                                with tag(
                                                                                        'label'
                                                                                ):
                                                                                    doc.input(
                                                                                        type
                                                                                        ='checkbox',
                                                                                        name
                                                                                        =f,
                                                                                        value
                                                                                        ='0'
                                                                                    )
                                                                                    with tag(
                                                                                            'span'
                                                                                    ):
                                                                                        text(
                                                                                            f
                                                                                        )

                                                    with tag('div',
                                                             klass='row'):

                                                        with tag(
                                                                'div',
                                                                klass=
                                                                'col-4 text-center'
                                                        ):
                                                            """Ajouter fichier annexe"""
                                                            with tag(
                                                                    'div',
                                                                    klass=
                                                                    'top-buffer row justify-content-center'
                                                            ):
                                                                text(
                                                                    'Ajouter un fichier annexe'
                                                                )
                                                            with tag(
                                                                    'br',
                                                                    klass=
                                                                    'top-buffer row justify-content-center'
                                                            ):
                                                                with tag(
                                                                        'input',
                                                                        type=
                                                                        'file'
                                                                ):
                                                                    pass
                                                        """Etablir min et max etudiants"""
                                                        # with tag('row', klass='row justify-content-center top-buffer'):
                                                        # with tag('div', id='nbr_min_etus'):
                                                        # with tag('input', type='number', placeholder='Nbr. min d\'étudiants'):pass
                                                        with tag(
                                                                'div',
                                                                klass=
                                                                'col-4 text-center'
                                                        ):
                                                            with tag(
                                                                    'div',
                                                                    klass=
                                                                    'top-buffer row justify-content-center'
                                                            ):
                                                                text(
                                                                    'Décider le nombre d\'étudiant qui pourront avoic ce sujet'
                                                                )
                                                            with tag(
                                                                    'br',
                                                                    klass=
                                                                    'row justify-content-center top-buffer'
                                                            ):
                                                                with tag(
                                                                        'div',
                                                                        id=
                                                                        'nbr_max_etus'
                                                                ):
                                                                    with tag(
                                                                            'input',
                                                                            type
                                                                            ='number',
                                                                            placeholder
                                                                            ='Nbr. max d\'étudiants',
                                                                            min=
                                                                            '1'
                                                                    ):
                                                                        pass

                                                        with tag(
                                                                'div',
                                                                klass=
                                                                'col-4 text-center'
                                                        ):
                                                            with tag(
                                                                    'div',
                                                                    klass=
                                                                    'top-buffer row justify-content-center'
                                                            ):
                                                                text(
                                                                    'Année académique pour laquelle le sujet sera disponible'
                                                                )
                                                            with tag('div'):
                                                                doc.input(
                                                                    type=
                                                                    'checkbox',
                                                                    name=p,
                                                                    value='0')
                                                                with tag(
                                                                        'span',
                                                                        id=
                                                                        '2020-2021'
                                                                ):
                                                                    text(
                                                                        '2020-2021'
                                                                    )
                                                            with tag('div'):
                                                                doc.input(
                                                                    type=
                                                                    'checkbox',
                                                                    name=p,
                                                                    value='0')
                                                                with tag(
                                                                        'span',
                                                                        id=
                                                                        '2021-2022'
                                                                ):
                                                                    text(
                                                                        '2021-2022'
                                                                    )
                                                            with tag('div'):
                                                                doc.input(
                                                                    type=
                                                                    'checkbox',
                                                                    name=p,
                                                                    value='0')
                                                                with tag(
                                                                        'span',
                                                                        id=
                                                                        '2022-2023'
                                                                ):
                                                                    text(
                                                                        '2022-2023'
                                                                    )
                                                    """ligne pour bouton 'enregistrer"""
                                                    with tag(
                                                            'div',
                                                            klass=
                                                            'row justify-content-center top-buffer'
                                                    ):
                                                        with tag('div'):
                                                            with tag('a',
                                                                     href=''):
                                                                with tag(
                                                                        'img',
                                                                        src=
                                                                        "./dist/images/check.png"
                                                                ):
                                                                    pass
                                """MODAL FIN"""

                            # """ICI IL FAUT UNE BOUCLE QUI VA GENERER LES SUJETS"""
                            # with tag('tr'):
                            # with tag('td', klass='col-lg-8 top buffer-top'):
                            # with tag('input', type='checkbox', value='0', onchange='sujet_actif()'):pass
                            # with tag('td', klass='col-lg-8 top buffer-top'):
                            # with tag('textarea', name = 'titre', klass='disable_text '):
                            # text('Titre : ' + 'Ceci est un titre')
                            # with tag('td', klass='col-lg-1'):
                            # with tag('img', src='./dist/images/down_arrow_small.png', onclick='afficher_details_sujet()'):pass
                            # with tag('td', klass='col-lg-1'):
                            # with tag('img', src="./dist/images/pencil.png"):pass
                            # with tag('td', klass='col-lg-1 content-center', id='nbr_etus'):

                            # """IL FAUT ALLER CHERCHER LA SOMMES DES ETUS PAR SUJET"""

                            # with tag('div', klass="nbr_etus"):
                            # with tag('input', name = 'nbr_etus', type='number', klass='disable_text hover', value="5"):pass

                            # with tag('td', klass='col-lg-1'):
                            # with tag('img', src="./dist/images/bin.png"):pass

                            # with tag('tr', id = 'details_sujet'):

                            # with tag('row'):
                            # with tag('div'):

                            # with tag('td', klass='col-sm-9'):
                            # with tag('textarea', name = 'descriptif', placeholder = 'Descriptif : ' + 'qsdqsdqsdqsdqsdqsdqsd', klass='disable_text '):
                            # text('Descriptif : ' + 'Ceci est un descriptif')

                            # with tag('td', klass='col-sm-1'):
                            # """Afficher dynamiquement les programmes"""
                            # with tag('div', klass='top-buffer col-sm-1'):
                            # text('Programmes : ')
                            # with tag('div'):
                            # for p in programme:
                            # with tag('div'):
                            # with tag('label', klass='switch'):
                            # doc.input( type = 'checkbox', name = p, value = '0', onclick='afficherFil()')
                            # with tag('span', klass='slider round', id=p+'1'):
                            # text(p)

                            # with tag('td', klass='col-sm-1'):
                            # """Afficher dynamiquement les filières"""
                            # with tag('div', klass='top-buffer filiere col-sm-1', id='FiliereInfo'):
                            # text('Filiére : ')
                            # with tag('div'):
                            # for f in programme['Finances']:
                            # with tag('div'):
                            # with tag('label', klass='switch'):
                            # doc.input( type = 'checkbox', name = f, value = '0')
                            # with tag('span',klass='slider round'):
                            # text(f)

                            # with tag('td', klass='col-sm-1'):pass

                            # with tag('td', klass='col-sm-1'):pass

        with tag('script', src="./dist/js/prof_sujets.js"):
            pass
        with tag('script', src="./dist/js/prof_modal.js"):
            pass
        with tag('script', src="./dist/js/datatables.min.js"):
            pass
        with tag('script', src="./dist/js/datatables.js"):
            pass
        with tag('script', src='./dist/js/responsive.min.js'):
            pass
        with tag('stylesheet', src='./dist/css/modal.css'):
            pass

        webPage(Page=doc, Session=S, CSS='dist/css/mycss.css', JS='myjs.js')
    else:
        webPage(doc)
def page(S=None):
    doc, tag, text = Doc().tagtext()
    if S:
        with tag('div', klass='wrapper'):
            doc, tag, text = prof_menu.sidebar(doc, tag, text)
            with tag('div', id='content'):
                with tag('div', klass='container-fluid ajouter'):

                    with tag('form'):
                        """ajouter sujet"""
                        with tag('row', id="ajouter_sujet", klass='cacher'):

                            # """Demander si le sujet sera actif pendant des années"""
                            # with tag('div', klass='row justify-content-center top-buffer'):
                            # with tag('div', klass='col-sm-4 text-center'):
                            # with tag('label', klass='switch'):
                            # doc.input( type = 'checkbox', name = 'valable_des_annees', value = '0')
                            # with tag('span',klass='slider round'):
                            # text('Sujet valable plusieures années ?')

                            with tag('row',
                                     klass=
                                     'row justify-content-center top-buffer'):

                                with tag(
                                        'row',
                                        klass=
                                        'col-sm-10 text-center mod_width_textarea'
                                ):
                                    with tag('textarea', placeholder='Titre'):
                                        pass
                                with tag(
                                        'row',
                                        klass=
                                        'col-sm-10 text-center mod_width_textarea'
                                ):
                                    with tag('textarea',
                                             placeholder='Descriptif'):
                                        pass

                            with tag('row', klass=' top-buffer'):

                                with tag('div', klass='row'):
                                    """Afficher dynamiquement les programmes"""
                                    with tag('div', klass='col-6 text-center'):
                                        with tag('div', id="programmes"):
                                            text('Programmes : ')
                                            with tag('div'):
                                                for p in programme:
                                                    with tag('div'):
                                                        # , klass='switch'):
                                                        with tag('label'):
                                                            doc.input(
                                                                type='checkbox',
                                                                name=p,
                                                                value='0',
                                                                onclick=
                                                                'afficherFilFin()'
                                                            )
                                                            with tag('span',
                                                                     id=p +
                                                                     '1'):
                                                                text(p)
                                    """Afficher dynamiquement les filières"""
                                    with tag('div',
                                             klass='filiere col-6 text-center',
                                             id='FiliereFin'):
                                        with tag('div'):
                                            text('Filiére : ')
                                            with tag('div'):
                                                for f in programme['Finances']:
                                                    with tag('div'):
                                                        with tag('label'):
                                                            doc.input(
                                                                type='checkbox',
                                                                name=f,
                                                                value='0')
                                                            with tag('span'):
                                                                text(f)

                            with tag('div', klass='row'):

                                with tag('div', klass='col-4 text-center'):
                                    """Ajouter fichier annexe"""
                                    with tag(
                                            'div',
                                            klass=
                                            'top-buffer row justify-content-center'
                                    ):
                                        text('Ajouter un fichier annexe')
                                    with tag(
                                            'br',
                                            klass=
                                            'top-buffer row justify-content-center'
                                    ):
                                        with tag('input', type='file'):
                                            pass
                                """Etablir min et max etudiants"""
                                # with tag('row', klass='row justify-content-center top-buffer'):
                                # with tag('div', id='nbr_min_etus'):
                                # with tag('input', type='number', placeholder='Nbr. min d\'étudiants'):pass
                                with tag('div', klass='col-4 text-center'):
                                    with tag(
                                            'div',
                                            klass=
                                            'top-buffer row justify-content-center'
                                    ):
                                        text(
                                            'Décider le nombre d\'étudiant qui pourront avoic ce sujet'
                                        )
                                    with tag(
                                            'br',
                                            klass=
                                            'row justify-content-center top-buffer'
                                    ):
                                        with tag('div', id='nbr_max_etus'):
                                            with tag('input',
                                                     type='number',
                                                     placeholder=
                                                     'Nbr. max d\'étudiants',
                                                     min='1'):
                                                pass

                                with tag('div', klass='col-4 text-center'):
                                    with tag(
                                            'div',
                                            klass=
                                            'top-buffer row justify-content-center'
                                    ):
                                        text(
                                            'Année académique pour laquelle le sujet sera disponible'
                                        )
                                    with tag('div'):
                                        doc.input(type='checkbox',
                                                  name=p,
                                                  value='0')
                                        with tag('span', id='2020-2021'):
                                            text('2020-2021')
                                    with tag('div'):
                                        doc.input(type='checkbox',
                                                  name=p,
                                                  value='0')
                                        with tag('span', id='2021-2022'):
                                            text('2021-2022')
                                    with tag('div'):
                                        doc.input(type='checkbox',
                                                  name=p,
                                                  value='0')
                                        with tag('span', id='2022-2023'):
                                            text('2022-2023')
                            """ligne pour bouton 'enregistrer"""
                            with tag('div',
                                     klass=
                                     'row justify-content-center top-buffer'):
                                with tag('div'):
                                    with tag('a', href=''):
                                        with tag(
                                                'img',
                                                src="./dist/images/check.png"):
                                            pass

        with tag('script', src="dist/js/myjs.js"):
            pass
        with tag('stylesheet', src='./dist/css/mycss.css'):
            pass

        webPage(Page=doc, Session=S, CSS='dist/css/mycss.css', JS='myjs.js')
    else:
        webPage(doc)
Example #25
0
def render_cover_page(translation, doc_style):
    print(f"Processing page 1")
    page_width = 8.27
    page_height = page_width
    MARGIN = 0.5
    BUFFER = 0.1
    half_page_width = (page_width - 2 * MARGIN) / 2
    column_1_offset = 0
    column_2_offset = half_page_width

    doc, tag, text = Doc().tagtext()

    doc.asis('<!DOCTYPE html>')
    with tag('html'):
        with tag('head'):
            with tag('style'):
                doc.asis(doc_style)
        with tag('body'):
            with tag('div',
                     style=
                     "display: -webkit-box; display: flex; flex-direction: row"
                     ):
                with tag(
                        'div',
                        style=
                        f"width: 49%; height: {(page_height-2*MARGIN)}in; background-color: #a30234;"
                ):
                    with tag('p', style=f"padding: 0.2in;", klass="heading"):
                        text(translation('main-title'))
                    with tag(
                            'p',
                            style=
                            f"padding: 0.2in; position:absolute; bottom: 0px; width: 40%;",
                            klass="footnote-yellow"):
                        text(translation('disclaimer'))

                with tag(
                        'div',
                        style=f"width: 49%; height: {(page_height-2*MARGIN)}in;"
                ):
                    with tag('p', style="margin: 0 0.2in;",
                             klass="subheading"):
                        text(translation('preparation-title'))
                    doc.stag('br')
                    with tag('p', style="margin: 0 0.2in;", klass="text"):
                        text(translation('time-text'))
                    doc.stag('br')
                    with tag('ul', style="margin: 0 0.2in;", klass="text"):
                        for prep_text_idx in range(1, 6):
                            with tag('li'):
                                text(
                                    translation(
                                        f'preparation-text-{prep_text_idx}'))
                    doc.stag('br')
                    with tag('p', style="margin: 0 0.2in;",
                             klass="subheading"):
                        text(translation('overview-title'))
                    doc.stag('br')
                    with tag('ul', style="margin: 0 0.2in;", klass="text"):
                        for prep_text_idx in range(1, 3):
                            with tag('li'):
                                text(
                                    translation(
                                        f'overview-text-{prep_text_idx}'))

    options = {
        'page-width': f'{page_width}in',
        'page-height': f'{page_height+BUFFER}in',
        'margin-top': f'{MARGIN}in',
        'margin-right': f'{MARGIN}in',
        'margin-bottom': f'{MARGIN}in',
        'margin-left': f'{MARGIN}in',
        'encoding': "UTF-8",
        'disable-smart-shrinking': None,
        'user-style-sheet': 'main.css',
        'enable-local-file-access': None,
        'quiet': None
    }

    # with open('out.html', 'w') as fp:
    #     fp.write(doc.getvalue())

    return pdfkit.from_string(doc.getvalue(), False, options=options)
Example #26
0
def report_html():
    doc, tag, text = Doc().tagtext()
    doc.asis('<!DOCTYPE html>')
    with tag('html', lang='en'):
        with tag('head'):
            doc.stag('meta', charset='utf-8')
            doc.stag('meta', name='viewport', content='width=device-width, initial-scale=1, shrink-to-fit=no')
            doc.stag('link',
                     rel='stylesheet',
                     href='https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css',
                     integrity='sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB',
                     crossorigin='anonymous')
            with tag('title'):
                text('Cosmic Ray Report')
        with tag('body'):
            with tag('h1'):
                text('Cosmic Ray Report')

            work_items = (WorkItem(json.loads(line, cls=WorkItemJsonDecoder)) for line in sys.stdin)

            for index, work_item in enumerate(work_items, start=1):
                with tag('div', klass='container work-item'):
                    with tag('h4', klass='job_id'):
                        text('{} : job ID {}'.format(index, work_item.job_id))
                    if work_item.test_outcome == TestOutcome.SURVIVED:
                        with tag('div', klass='alert alert-danger test-outcome', role='alert'):
                            text('Survived!')
                    elif work_item.test_outcome == TestOutcome.INCOMPETENT:
                        with tag('div', klass='alert alert-info test-outcome', role='alert'):
                            text('Incompetent.')
                    elif work_item.test_outcome == TestOutcome.KILLED:
                         with tag('div', klass='alert alert-success test-outcome', role='alert'):
                            text('Killed.')

                    if work_item.command_line:
                        with tag('pre', klass='command-line'):
                            text(work_item.command_line)

                    with tag('a', href=pycharm_url(
                        work_item.filename,
                        work_item.line_number)):
                        with tag('pre', klass='location'):
                            text('{}:{}:{}'.format(
                                work_item.filename,
                                work_item.line_number,
                                work_item.col_offset
                            ))
                    if work_item.diff:
                        diff = markup_character_level_diff(diff_without_header(work_item.diff))
                        with tag('pre', klass='diff'):
                            text('\n'.join(diff))

            doc.stag('script',
                     src='https://code.jquery.com/jquery-3.3.1.slim.min.js',
                     integrity='sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo',
                     crossorigin='anonymous')
            doc.stag('script',
                     src='https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js',
                     integrity='sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49',
                     crossorigin='anonymous')
            doc.stag('script',
                     src='https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js',
                     integrity='sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T',
                     crossorigin='anonymous')

    print(doc.getvalue())
Example #27
0
import os
from yattag import Doc
from config import web_page_base, student_item_path
from bs4 import BeautifulSoup

# 需事先将照片放到student_item_path下,命名格式:degree_name.extension
soup = BeautifulSoup(open(os.path.join(web_page_base, 'student_list.html'), 'rb'), 'lxml')
item_list = soup.find("ul", id='portfolio-container')
# 获取图片与根目录的相对路径
item_relpath = os.path.relpath(student_item_path, web_page_base)
# 获取teacher_item_path和teacher_photo_path下的文件列表
photos = [f for f in os.listdir(student_item_path) if os.path.isfile(os.path.join(student_item_path, f))]
degree_dict = {'本科': 'undergraduate', '硕士': 'master', '博士': 'phd', '毕业': 'graduate', '毕业博士': 'graduate'}
doc, tag, text, line = Doc().ttl()
photo_dict = {}
for photo in photos:
    degree, name = os.path.splitext(photo)[0].split('_')
    if degree not in photo_dict:
        photo_dict[degree] = []
    photo_dict[degree].append(photo)

# print(photo_dict)
order = ['博士', '硕士', '本科', '毕业博士', '毕业']
for item in order:
    for photo in photo_dict[item]:
        degree, name = os.path.splitext(photo)[0].split('_')
        category = degree_dict[degree]
        if degree == '毕业':
            degree = '毕业硕士'
        with tag('li', ('class', 'isotope-item'), ('data-categories', category)):
            with tag('div', klass='item-wrapp'):
Example #28
0
    def __init__(self, hosts):
        self.doc, self.tag, self.text = Doc().tagtext()

        with self.tag("report"):
            for host in hosts.values():
                self.add_value(host.get_report_data())
async def main(loop):
    for dc in allshards:
        start_time = time.time()
        # Construct a page at a time
        doc, tag, text = Doc().tagtext()
        with tag('html'):
            with tag('head'):
                doc.stag('meta', ('http-equiv', "Refresh"), ('content', 60))
                doc.stag('meta', ('http-equiv', "Content-Type"),
                         ('content', "text/html; charset=UTF-8"))
                doc.stag('link', ('rel', "stylesheet"), ('type', "text/css"),
                         ('href', "style.css"))
                with tag('title'):
                    text(config['name'])
            with tag('body'):
                with tag('h2'):
                    text(config['name'], ' - ', dc.upper())
                # Links to other DCs
                with tag('p'):
                    for otherdc in allshards:
                        if (otherdc != dc):
                            with tag('a', href=otherdc + ".html"):
                                text(otherdc.upper())
                with tag('p'):
                    text(config['customtext'])
                # Event table
                with tag('table'):
                    with tag('thead'):
                        with tag('tr'):
                            for title in [
                                    'Shard', 'Zone', 'Event Name',
                                    'Elapsed Time'
                            ]:
                                with tag('th'):
                                    text(title)
                    with tag('tbody'):
                        # Get each shard's events
                        urls = []
                        for shardid in sorted(allshards[dc],
                                              key=allshards[dc].get):
                            urls.append(
                                "http{2}://web-api-{0}.riftgame.com{3}/chatservice/zoneevent/list?shardId={1}"
                                .format(dc, str(shardid), str(https[dc]),
                                        str(port[dc])))
                        results = []
                        with aiohttp.ClientSession(loop=loop) as session:
                            results = await asyncio.gather(
                                *[fetch(session, url) for url in urls], )
                        for idx, url in enumerate(urls):
                            shardid = int(url[-4:])
                            data = json.loads(results[idx])['data']
                            data.reverse()
                            # Print any events
                            displayshard = allshards[dc][shardid]
                            for zone in data:
                                # An event is running in a zone, so add a table row
                                if "name" in zone:
                                    with tag('tr'):
                                        with tag('td', klass="bold"):
                                            text(displayshard)
                                        zoneclass = "secondary"
                                        # Starfall zone IDs
                                        if zone['zoneId'] in [
                                                788055204, 2007770238,
                                                1208799201, 2066418614,
                                                511816852
                                        ]:
                                            zoneclass = "bold"
                                        for display in [
                                                zone['zone'], zone['name'],
                                                str(
                                                    int(
                                                        math.floor(
                                                            (time.time() -
                                                             zone['started']) /
                                                            60))) + " min"
                                        ]:
                                            with tag('td', klass=zoneclass):
                                                text(display)
                                    # already printed the shard name once, so clear it
                                    displayshard = ""
                with tag('p', klass='small tertiary'):
                    text("Generated at {0} in {1:.3f}s".format(
                        time.strftime("%d-%b-%Y %H:%M:%S %Z"),
                        (time.time() - start_time)))
                with tag('p', klass='small tertiary'):
                    text(
                        "Trion, Trion Worlds, RIFT, Storm Legion, Nightmare Tide, Prophecy of Ahnket, Telara, and their respective logos, are trademarks or registered trademarks of Trion Worlds, Inc. in the U.S. and other countries. This site is not affiliated with Trion Worlds or any of its affiliates."
                    )
        # Write page then move it over the old one
        with tempfile.NamedTemporaryFile(delete=False) as outfile:
            outfile.write(doc.getvalue().encode('utf8'))
            os.chmod(outfile.name, 0o0644)
        os.rename(outfile.name, config['outputdir'] + dc + ".html")
        if not os.path.exists(config['outputdir'] + "index.html"):
            os.symlink(config['outputdir'] + dc + ".html",
                       config['outputdir'] + "index.html")
        if not os.path.exists(config['outputdir'] + "style.css"):
            shutil.copy2(mydir + "/style.css",
                         config['outputdir'] + "style.css")
Example #30
0
def record_listens(request, data):
    """ Submit the listen in the lastfm format to be inserted in db.
        Accepts listens for both track.updateNowPlaying and track.scrobble methods.
    """
    output_format = data.get('format', 'xml')
    try:
        sk, api_key = data['sk'], data['api_key']
    except KeyError:
        raise InvalidAPIUsage(
            CompatError.INVALID_PARAMETERS,
            output_format=output_format)  # Invalid parameters

    session = Session.load(sk)
    if not session:
        if not Token.is_valid_api_key(api_key):
            raise InvalidAPIUsage(
                CompatError.INVALID_API_KEY,
                output_format=output_format)  # Invalid API_KEY
        raise InvalidAPIUsage(
            CompatError.INVALID_SESSION_KEY,
            output_format=output_format)  # Invalid Session KEY

    lookup = defaultdict(dict)
    for key, value in data.items():
        if key in ["sk", "token", "api_key", "method", "api_sig"]:
            continue
        matches = re.match('(.*)\[(\d+)\]', key)
        if matches:
            key = matches.group(1)
            number = matches.group(2)
        else:
            number = 0
        lookup[number][key] = value

    if request.form['method'].lower() == 'track.updatenowplaying':
        for i, listen in lookup.items():
            if 'timestamp' not in listen:
                listen['timestamp'] = calendar.timegm(
                    datetime.now().utctimetuple())

    # Convert to native payload then submit 'em after validation.
    listen_type, native_payload = _to_native_api(lookup, data['method'],
                                                 output_format)
    for listen in native_payload:
        validate_listen(listen, listen_type)
    augmented_listens = insert_payload(native_payload,
                                       session.user,
                                       listen_type=listen_type)

    # With corrections than the original submitted listen.
    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        with tag('nowplaying' if listen_type ==
                 'playing_now' else 'scrobbles'):

            for origL, augL in zip(list(lookup.values()), augmented_listens):
                corr = defaultdict(lambda: '0')

                track = augL['track_metadata']['track_name']
                if origL['track'] != augL['track_metadata']['track_name']:
                    corr['track'] = '1'

                artist = augL['track_metadata']['artist_name']
                if origL['artist'] != augL['track_metadata']['artist_name']:
                    corr['artist'] = '1'

                ts = augL['listened_at']

                albumArtist = artist
                if origL.get('albumArtist', origL['artist']) != artist:
                    corr['albumArtist'] = '1'

                album = augL['track_metadata'].get('release_name', '')
                if origL.get('album', '') != album:
                    corr['album'] = '1'

                with tag('scrobble'):
                    with tag('track', corrected=corr['track']):
                        text(track)
                    with tag('artist', corrected=corr['artist']):
                        text(artist)
                    with tag('album', corrected=corr['album']):
                        text(album)
                    with tag('albumArtist', corrected=corr['albumArtist']):
                        text(albumArtist)
                    with tag('timestamp'):
                        text(ts)
                    with tag('ignoredMessage', code="0"):
                        text('')

    return format_response(
        '<?xml version="1.0" encoding="utf-8"?>\n' +
        yattag.indent(doc.getvalue()), output_format)