示例#1
0
def dominate_final_page():
    """
    第四頁:感謝頁,
    目標:利用dominate寫出 enter_page 的 html並在 templates 資料夾中存成 index4.html

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

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

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

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

    fn = 'templates/index4.html'
    with open(file=fn, mode='w', encoding='utf-8') as f:
        f.write(doc.render())
    print(f)
示例#2
0
def create_html_file(cmd_args, all_news):
    """
    Creates and fills in the HTML file with the required data
    """
    path_to_html = create_path_to_file(cmd_args.to_html, 'RSS_NEWS.html')

    rss_html_doc = dominate.document(title='RSS NEWS')

    with rss_html_doc:
        tag.h1("RSS News")

    for num, new in enumerate(all_news, 1):
        LOGGER.info(f'Add new № {num} in HTML file.')
        rss_html_doc = convert_new_in_html(cmd_args, new, rss_html_doc)

    try:
        LOGGER.info('Create HTML file in the specified directory.')

        with open(path_to_html, 'w') as file:
            file.write(str(rss_html_doc))

        LOGGER.info("HTML file was created and filled in successfully")

    except FileNotFoundError:
        raise PATHError('Setted PATH is invalid')
示例#3
0
 def accordian_collapse(color, title, content, pre, raw_html, **kwargs):
     """
     Creates a collapsible accordian
     """
     title_random = HelperFunctions.id_with_random(5, title)
     with tag.div(_class="jumbotron container reportng-section-collapsible-class") as h:
         # with tag.div(id="accordian"):
         with tag.div(_class="card"):
             with tag.div(_class="card-header %s reportng-collapse-card-header-class" % color,
                          id="headingOne%s" % title_random):
                 tag.h1(title, _class=color, data_toggle="collapse", data_target="#collapse%s" % title_random,
                        aria_expanded="true", aria_controls="collapse%s" % title_random, id=title_random)
             with tag.div(id="collapse%s" % title_random, _class="collapse",
                          aria_labelledby="headingOne%s" % title_random, data_parent="#accordion"):
                 with tag.div(_class="card-body context reportng-collapse-card-body-class"):
                     if raw_html != '':
                         raw(raw_html)
                     elif pre:
                         tag.pre(content)
                     else:
                         tag.p(content)
             if 'alert' in kwargs:
                 HelperFunctions.make_alert(kwargs.get('alert'))
             if 'badge' in kwargs:
                 HelperFunctions.create_badges(kwargs.get('badge'))
     return HelperFunctions.convert_to_string(h)
def index():
    removed = list((REPORTS_PATH / "removed").iterdir())
    added = list((REPORTS_PATH / "added").iterdir())
    diff = list((REPORTS_PATH / "diff").iterdir())

    title = "UI changes from master"
    doc = dominate.document(title=title)

    with doc:
        h1("UI changes from master")
        hr()

        h2("Removed:", style="color: red;")
        i("UI fixtures that have been removed:")
        html.report_links(removed, REPORTS_PATH)
        br()
        hr()

        h2("Added:", style="color: green;")
        i("UI fixtures that have been added:")
        html.report_links(added, REPORTS_PATH)
        br()
        hr()

        h2("Differs:", style="color: grey;")
        i("UI fixtures that have been modified:")
        html.report_links(diff, REPORTS_PATH)

    return html.write(REPORTS_PATH, doc, "index.html")
def report_headline(version):
    with div(cls='jumbotron'):
        h1('Audit Engine: {version} - Discrepancy Report for Automated Independent Audit'
           .format(version=version))
        build_time = datetime.datetime.now(datetime.timezone.utc)
        p(f'Summary built at: {build_time.strftime("%Y-%m-%d %H:%M:%S")}',
          cls='lead')
示例#6
0
    def get_html_string(style: Style) -> document:
        """Creates a HTML string for generating the summary file."""
        utc_time = datetime.datetime.utcfromtimestamp(style.timestamp)
        style_attributes = [
            ('code', style.code),
            ('number', style.number),
            ('precinct', style.precinct),
            ('built at', f'{utc_time.strftime("%Y-%m-%d %H:%M:%S")}'),
            ('built from number of ballots', style.build_from_count),
        ]

        script_abs_path = os.path.abspath('assets/copy_to_clipboard.js')
        version = utils.show_version()
        doc = document(title='Audit Engine version: ' + version)
        with doc.head:
            link(
                rel='stylesheet',
                href=
                'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css',
                integrity=
                "sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T",
                crossorigin="anonymous",
            )
            script(type='text/javascript', src=script_abs_path)

        with doc:
            with div(cls='container'):
                with div(cls='jumbotron'):
                    h1('Audit Engine: {version} - style summary'.format(
                        version=version))
                    build_time = datetime.datetime.now(datetime.timezone.utc)
                    p(f'Summary built at: {build_time.strftime("%Y-%m-%d %H:%M:%S")}',
                      cls='lead')
                with div(cls='col pl-3 mt-1') as style_details_column:
                    for style_key, style_value in style_attributes:
                        style_details_column.add(
                            StyleSummary.get_details_row(
                                style_key, str(style_value)))
                h3('Contests', cls='mb-0 mt-1')
                with div(cls='col pl-3') as contest_details_column:
                    for style_contest in style.contests:
                        contest_details_column.add(
                            StyleSummary.get_contest_details(style_contest))
                h3('Built from ballots', cls='mb-3 mt-1')
                with div(cls='col pl-3'):
                    with div(cls='row flex-wrap') as images_column:
                        for ballot_id in style.build_from_ballots:
                            images = StyleSummary.get_ballot_images_path(
                                ballot_id, style.code)
                            images_column.add(
                                StyleSummary.get_ballot_images_div(
                                    ballot_id, images))
                h3('Style weighted images', cls='mb-3 mt-1')
                with div():
                    for image in StyleSummary.get_style_images(style.code):
                        a(img(src=os.path.basename(image),
                              cls='img-thumbnail',
                              alt='File not found'),
                          href=image)
        return doc
def diff(master_screens_path, current_screens_path, test_name, master_hash,
         current_hash):
    doc = dominate.document(title=test_name)
    master_screens = sorted(master_screens_path.iterdir())
    current_screens = sorted(current_screens_path.iterdir())

    with doc:
        h1(test_name)
        p("This UI test differs from master.",
          style="color: grey; font-weight: bold;")
        with table():
            with tr():
                td("Master:")
                td(master_hash, style="color: red;")
            with tr():
                td("Current:")
                td(current_hash, style="color: green;")
        hr()

        with table(border=1, width=600):
            with tr():
                th("Master")
                th("Current branch")

            html.diff_table(master_screens, current_screens)

    return html.write(REPORTS_PATH / "diff", doc, test_name + ".html")
def main(args=None):
    if args == None:
        args = arguments.Args()
        if len(args) < 4:
            print(
                'Returns Github Issues from the Github API based on the arguments and generates an HTML table.'
            )
            print(
                'Usage: python report.py <GITHUB_TOKEN> <GITHUB_REPO> <GITHUB_ORG> <GITHUB_ISSUE_LABEL> >report.html'
            )
            exit(1)
    token = args.get(0)
    repository = args.get(1)
    organization = args.get(2)
    label = args.get(3)
    if token is not None and repository is not None and organization is not None and label is not None:
        g = Github(token)
        repos = g.get_organization(organization).get_repos(repository)
    title = 'Github Issue Status'
    d = dominate.document(title=title)
    with d.body:
        h1(title)
        with table(border='1', width='1024', cellpadding='10').add(tbody()):
            make_table(repos, label)
    print(d)
示例#9
0
    def report_asciinema(self, asciinema_link, title='', **kwargs):
        """
        Section creates a jumbotron to house an asciinema

        :param str asciinema_link: Link to asciinema. Could be http/s or local files
        :param str title: Set the title of the asciinema. If set, it will create its own section. If not, it will append to previous section
        :param tuple alert: Kwarg Create a dismissable alert box. First value of tuple is the color, and the second is the message
        :param bool section: Kwarg Set to True to append the cards section to the preceding section. Default is false
        :raises ObjectNotInitiated: Raises exception when the correct flags are not set in ReportWriter

        Example:
            >>> r += report.report_asciinema('https://asciinema.org/a/XvEb7StzQ3C1BAAlvn9CDvqLR', title='asciinema')
        """
        logging.warning(
            'This method only works with asciinema links because of the way\n \
            browsers enforce CORS')
        # checks to see if asciinema has been intialized
        if not self.asciinema:
            raise rng.ObjectNotInitiated(
                'To integrate asciinema, set asciinema=True in ReportWriter')

        # TODO: write a check here that validates the asciinema url

        # hacky way to bypass the CORS problem
        try:
            url = get('%s.json' % asciinema_link).url
        except:
            logging.warning('Need internet to get the proper url for %s' %
                            asciinema_link)

        # controls if sticky or not
        if 'section' in kwargs:
            style = rng.CSSControl.sticky_section_css
        else:
            style = rng.CSSControl.not_sticky_section

        with tag.div(
                _class=
                "jumbotron jumbomargin container reportng-acsiinema-class",
                style=style) as a:
            if title != '':
                tag.h1(title,
                       id="%s" % rng.HelperFunctions.id_with_random(5, title))
            # create dismissable alert box
            if 'alert' in kwargs:
                rng.HelperFunctions.make_alert(kwargs.get('alert'))
            with tag.div(_class="container",
                         style="text-align: center;" + style):
                raw('<asciinema-player src="%s"></asciinema-player>' % url)
                tag.script(src=rng.JSCSS.asciinema_js)
                tag.a('Asciinema link',
                      _class=
                      "btn btn-secondary row justify-content-center btn-sm",
                      role="button",
                      href=asciinema_link,
                      target="_blank")
        return str(a)
示例#10
0
    def add_pagetitle(self, text):
        """ Insert a title in the first line

        Parametres:
        text (str): -- the page title text

        """
        with self.doc:
            h1(text)
示例#11
0
def rsvp_preselecthtml():
    invitekey = request.args.get(INVITE_KEY_URLARG)
    invite = Invite.query.filter_by(invitekey=invitekey).one()
    meeting = invite.meeting
    user = invite.user
    html = div()
    with html:
        h1('{} {}: {}\'s RSVP'.format(meeting.date, meeting.purpose, user.name))
    return html.render()
示例#12
0
    def format_pretablehtml(self):
        meeting = self.get_meeting()

        html = div()
        with html:
            self.custom_wording()
            self.instructions()
            h1('{} - {} - {}'.format(meeting.date, meeting.purpose, current_user.name), _class='TextCenter')

        return html.render()
示例#13
0
 def html(self):
     # If the user just calls ``html()``, we fill out a basic page.
     with self._edit_html():
         H.h1('Hello world!')
         H.p(lorem_ipsum())
         H.p(lorem_ipsum())
     # But then we also return the context manager that can be used
     # to rebuild the page as the user wishes. It does nothing unless
     # it is entered (``with``).
     return self._edit_html()
示例#14
0
    def report_cards(self, *args, **kwargs):
        """
        Functions that allow adding multiple cards to a jumbotron

        :param tuple \**args: Tuples that creates cards. The first value of the
            tuple is used to color the card, second value is the header for the
            card and the third is passed to a p tag for content
        * tuple values : Are in order fo ('color', 'title', 'content')
        :param bool section: Kwarg Set to True to append the cards section to the preceding section. Default is false
        :param str title: Kwarg Sets an optional title for cards
        :param bool border_only: Kwarg Changes the look of the cards
        :param tuple alert: Kwarg Creates a dismissable alert box. Requires a tuple. First value is color and second value is message.
        :raises TypeError: Raises TypeError if args is not a tuple
        :raises TooManyValues: Raises exception when the number of values in tuple is not 3

        Example:
            >>> r += report.report_cards(('primary', 'header1', 'some text'),
            >>>                       ('success', 'header2', 'some other text'),
            >>>                        title='My cards')
        """

        # Check to see if args is a tuple
        if not isinstance(args, tuple):
            raise TypeError('Use tuples only')

        # if the kwarg border exists, this set bool value
        if 'border_only' in kwargs:
            border = True
        else:
            border = False

        # control if stick to previous section or not
        if 'section' in kwargs:
            style = rng.CSSControl.sticky_section_css
        else:
            style = rng.CSSControl.not_sticky_section

        with tag.div(_class="jumbotron container context",
                     style=style) as c:  # padding mods
            if 'title' in kwargs:
                tag.h1(kwargs.get('title'))
            # create dismissable alert box
            if 'alert' in kwargs:
                rng.HelperFunctions.make_alert(kwargs.get('alert'))
            with tag.div(_class="row justify-content-center"):
                for i in range(len(args)):
                    # Checks to make sure corrent number of values in tuple
                    if len(args[i]) != 3:
                        raise rng.TooManyValues(
                            'Only pass three values to each tuple')
                    k = args[i][0]
                    h = args[i][1]
                    v = args[i][2]
                    rng.HelperFunctions.make_cards(border, k, h, v)
        return str(c)
示例#15
0
def report(job, report):
    """Generate a report.html with analysis and timelines from given jobs."""
    jobs = job

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

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

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

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

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

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

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

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

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

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

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

    articles = []

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

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

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

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

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

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

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

    generateFeed(articles)
示例#17
0
文件: html.py 项目: dfirst/httpolice
def list_notices(buf):
    title = u'HTTPolice notices'
    document = dominate.document(title=title)
    _common_meta(document)
    with document:
        H.h1(title)
        with H.div(_class=u'notices-list'):
            placeholder = Placeholder()
            for id_ in sorted(notice.notices.keys()):
                _notice_to_html(notice.notices[id_], placeholder,
                                with_anchor=True)
    buf.write(document.render().encode('utf-8'))
示例#18
0
def dominate_enter_page():
    """
    第三頁:確認資訊頁面,對應到  @app.route('/jump')  及其函數   registerpage_run [if request.method == 'POST']
    目標:利用dominate寫出 enter_page 的 html並在 templates 資料夾中存成 index3.html

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

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

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

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

    fn = 'templates/index3.html'
    with open(file=fn, mode='w', encoding='utf-8') as f:
        f.write(doc.render())
    print(f)
示例#19
0
def dominate_homepage():
    """
    第一頁:歡迎頁面,對應到  @app.route('/')  及其函數  homepage_run()
    目標:利用dominate寫出homepage的html並在templates資料夾中存成index1.html

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

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

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

    with doc.body:

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

    fn = 'templates/index1.html'
    with open(file=fn, mode='w', encoding='utf-8') as f:
        f.write(doc.render())
    print(f)
示例#20
0
def list_notices(buf):
    """Render the list of all notices to the file-like `buf`."""
    title = u'HTTPolice notices'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.body:
        H.attr(_class=u'notices-list')
    with document:
        H.h1(title)
        placeholder = Placeholder()
        for id_ in sorted(notice.all_notices.keys()):
            _notice_to_html(notice.all_notices[id_],
                            placeholder,
                            with_anchor=True)
    buf.write(document.render().encode('utf-8'))
示例#21
0
def motionvote_preselecthtml():
    motionvotekey = request.args.get(MOTIONVOTE_KEY_URLARG)
    motionvote = MotionVote.query.filter_by(motionvotekey=motionvotekey).one()
    meeting = motionvote.meeting
    motion = motionvote.motion
    user = motionvote.user
    html = div()
    with html:
        h1('{} {}: {}\'s Vote'.format(meeting.date, meeting.purpose, user.name))
        p(b('Motion'))
        with div(style='margin-left: 1em;'):
            raw(motion.motion)
            if motion.comments:
                raw(motion.comments)
    return html.render()
示例#22
0
def create_indexhtml(outdir):

    from dominate import document
    from dominate import tags

    mds = glob.glob('{}mds/*.md'.format(outdir))
    mds.sort()
    with document(title='TIGRESS Models') as doc:
        tags.h1('TIGRESS Models Quick View')
        for path in mds:
            title = os.path.basename(path).replace('.md', '')
            tags.li(tags.a(title, href='./mds/{}.md'.format(title)))

    with open('{}index.html'.format(outdir), 'w') as f:
        f.write(doc.render())
示例#23
0
def _header(test_name, expected_hash, actual_hash):
    h1(test_name)
    with div():
        if actual_hash == expected_hash:
            p(
                "This test succeeded on UI comparison.",
                style="color: green; font-weight: bold;",
            )
        else:
            p(
                "This test failed on UI comparison.",
                style="color: red; font-weight: bold;",
            )
        p("Expected: ", expected_hash)
        p("Actual: ", actual_hash)
    hr()
示例#24
0
def home():
    return t.html(
        [
            t.head(
                [
                    cccp.REQUIRED,
                    cccp.BOOTSTRAP,
                    cccp.CreateReplaceHtmlFunc(),
                    cccp.CreateAppendHtmlFunc(),
                    cccp.CreatePrependHtmlFunc(),
                ]
            ),
            t.body(
                [
                    t.h1("Hello, CCCP!"),
                    t.div(id="pageContent"),
                    t.button(
                        "go to blog",
                        onClick=cccp.replaceHtml(
                            "http://127.0.0.1:9999/page/1", "pageContent"
                        ),
                    ),
                ]
            ),
        ]
    ).render()
def visualize(data, text, clusterer, cluster_by, whitespace_only=False):
    ''' Visualize appearances of each cluster in the sample text.
    'data' should be output like that from get_comp_data'''

    # Get data for text to use for clustering:
    tokens = [unidecode.unidecode(char) for char in text]
    tokens = [ct.tweak_whitespace(w) for w in tokens[0:-1]]

    print("Starting labelling")
    labels, _ = hdbscan.approximate_predict(clusterer, data[cluster_by])
    clusters = sorted(list(set(labels)))
    print("Done labelling")

    content = dt.div(dt.h1("Cluster Visualization"))
    for i, c in enumerate(clusters):
        print("DEBUG: - Visualizing cluster %d" % i)
        details = dt.details(dt.summary("Cluster: %d" % c))
        colors = [1.0 if c == labels[j] else 0.0 for j in range(len(tokens))]
        if whitespace_only:
            for j in range(len(tokens)):
                colors[j] = colors[j] if text[j] in [" ", "\n"] else 0.0
        token_data = zip(tokens, colors)
        details.add(ct.colored_text(token_data))
        content.add(details)
    return content
示例#26
0
def generateStatsHTML(graph,statsFilePath = "stats.html",postStatsFilePath = "postStats.html"): #Generates the Stats HTML section

	firstLevel = checkFirstLevel(graph)
	softwareLabelNum = queryVersionNum(graph)
	softwareLabelNumList = addQueryToList(softwareLabelNum)
	
	stats = document(title="FSL Viewer") #Creates initial html page (stats)
	stats += h1("Sample FSL Viewer")
	stats += ul(li(a("Stats", href="stats.html")), li("-"),li(a("Post Stats", href = "postStats.html")))
	stats += h2("Stats")
	stats += hr()
	stats += h3("Analysis Methods")
	
	if askSpm(graph) == True: #Checks if SPM was used
		
		stats += p("FMRI data processing was carried out using SPM Version %s (SPM, http://www.fil.ion.ucl.ac.uk/spm/)." % softwareLabelNumList[1])
		
	elif askFsl(graph) == True: #Checks if FSL was used
		
		fslFeatVersion = queryFslFeatVersion(graph)
		stats += p("FMRI data processing was carried out using FEAT (FMRI Expert Analysis Tool) Version %s, part of FSL %s (FMRIB's Software Library, www.fmrib.ox.ac.uk/fsl)." % (fslFeatVersion[0], softwareLabelNumList[1]))
		
	stats += hr()
	stats += h3("Design Matrix")
	
	designMatrixLocation = queryDesignMatrixLocation(graph)
	stats += a(img(src = designMatrixLocation[1], style = "border:5px solid black", border = 0), href = designMatrixLocation[0]) #Adds design matrix image (as a link) to html page
	
	statsFile = open(statsFilePath, "x")
	print(stats, file = statsFile) #Prints html page to a file
	statsFile.close()
示例#27
0
def generateMainHTML(graph,mainFilePath = "Main.html", statsFilePath = "stats.html", postStatsFilePath = "postStats.html"): #Generates the main HTML page

	main = document(title="FSL Viewer")
	main += h1("Sample FSL Viewer")
	main += ul(li(a("Stats", href="stats.html")), li("-"),li(a("Post Stats", href = "postStats.html")))
	mainFile = open(mainFilePath, "x")
	print(main, file = mainFile)
	mainFile.close()
示例#28
0
    def create_page(self):
        # Open plots directory
        if not os.path.isdir(self.get_output('plots')):
            os.mkdir(self.get_output('plots'))

        # Create HTML page
        self.doc = dom.document(title='BBPipe plots page')
        with self.doc.head:
            dtg.link(rel='stylesheet', href='style.css')
            dtg.script(type='text/javascript', src='script.js')
        with self.doc:
            dtg.h1("Pipeline outputs")
            dtg.h2("Contents:", id='contents')
            lst = dtg.ul()
            lst += dtg.li(dtg.a('Bandpasses', href='#bandpasses'))
            lst += dtg.li(dtg.a('Coadded power spectra', href='#coadded'))
            lst += dtg.li(dtg.a('Null tests', href='#nulls'))
            lst += dtg.li(dtg.a('Likelihood', href='#like'))
示例#29
0
    def index(self):
        with html.div() as content:

            html.h1("Herzlich wilkommen beim Gründungsroboter!")
            html.br()

            html.div(
                "Sie werden in den nächsten fünf Minuten eine Firma gründen.")
            html.br()
            with html.div():
                html.span('Bitte lesen Sie vorher sorgfältig unsere ')
                html.a('Allgemeinen Geschäftsbedingungen')
                html.span(' und den ')
                html.a('Disclaimer')
            html.br()

            html.div(html.a('Loslegen', cls='btn btn-success', href='/step1'))
        return self.template.render(content=content)
示例#30
0
    def report_list_group(self, items, **kwargs):
        """
        Creates a list group. Each arg is a line

        :param str title: Title of the section
        :param list items: Each arg passed will be treated as a new list item
        :param bool section: Kwarg Set to True to append the cards section to the preceding section. Default is false
        :param tuple alert: Kwarg Create a dismissable alert box. First value of tuple is the color, and the second is the message
        :param tuple reference: Kwarg Adds a small button which hrefs to a user supplied link. Is a tuple. First value is color, second is link
        :param dict badge: Kwarg Adds badges. Key is the color, and value is the message.
        :param str custom_html: Insert raw html to be added to the end of the section
        :param dict modal: Create a modal. Is a dictionary. Valid keys are button, title and content
        :raises NoValidTag: Raises not valid tag

        Example:
            >>> r += report.report_list_group('First entry', 'Second entry', ...)
        """
        if not kwargs.get('title'):
            raise rng.NotValidTag('Need a title')
        title = kwargs.get('title')
        if not isinstance(items, list):
            raise rng.NotValidTag('Items have to be in the form of a list')

        if 'section' in kwargs:
            style = rng.CSSControl.sticky_section_css
        else:
            style = rng.CSSControl.css_overflow
        with tag.div(
                _class="jumbotron container context reportng-list-group-class",
                style=style) as r:
            t = tag.h1(title,
                       id="%s" % rng.HelperFunctions.id_with_random(5, title))
            # creates a reference button with link
            if 'reference' in kwargs:
                t.add(rng.HelperFunctions.ref_button(kwargs.get('reference')))
            # creates dismissable alert box
            if 'alert' in kwargs:
                rng.HelperFunctions.make_alert(kwargs.get('alert'))

            with tag.ul(_class="list-group"):
                for i in range(len(items)):
                    tag.li(
                        items[i],
                        _class=
                        "list-group-item d-flex justify-content-between align-items-center text-primary"
                    )

            if 'badge' in kwargs:
                rng.HelperFunctions.create_badges(kwargs.get('badge'))
            if 'custom_html' in kwargs:
                raw(kwargs.get('custom_html'))
            if 'modal' in kwargs:
                if isinstance(kwargs.get('modal'), dict):
                    rng.HelperFunctions.make_modals(title.replace(' ', ''),
                                                    kwargs.get('modal'))
        return rng.HelperFunctions.convert_to_string(r)
示例#31
0
def list_notices(buf):
    """Render the list of all notices to the file-like `buf`."""
    title = u'HTTPolice notices'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.body:
        H.attr(_class=u'notices-list')
    with document:
        H.h1(title)
        H.p(u'This is the list of all notices produced by ',
            H.a(u'HTTPolice', href=homepage, target='_self'),
            u' version ', version, u'.')
        H.p(u'See also the ',
            H.a(u'HTTPolice manual', href=u'index.html', target='_self'), u'.')
        placeholder = Placeholder()
        for id_ in sorted(notice.all_notices.keys()):
            _notice_to_html(notice.all_notices[id_], placeholder,
                            with_anchor=True)
    buf.write(document.render().encode('utf-8'))
示例#32
0
def html_report(figs,
                text=None,
                name='report',
                directory=None,
                dpi=75,
                fig_dir='figs'):
    """Produce an HTML report containing figs and text."""
    #
    # if dominate not installed, dive out here
    if not dominate:
        return

    if directory is None:
        directory = name
    try:
        os.mkdir(directory)
    except FileExistsError as e:
        print(e)

    try:
        os.mkdir(os.path.join(directory, fig_dir))
    except FileExistsError as e:
        print(e)

    h = html()
    with h.add(body()).add(div(id='content')):
        h1(f'Performance Plots: {name}')
        if text:
            pre(text)
        with table().add(tbody()):
            for j, row in enumerate(figs):
                r = tr()
                for i, item in enumerate(row):
                    url = os.path.join(fig_dir, f"{name}-fig-{j}_{i}.png")
                    item.savefig(os.path.join(directory, url),
                                 dpi=dpi,
                                 bbox_inches='tight')
                    r += td(img(src=url))

    with open(os.path.join(directory, name + '.html'), 'w') as f:
        print(h, file=f)
    return h
def get_cmpcvr_doc(cmpcvr_df: pd.DataFrame) -> dominate.document:
    version = utils.show_version()
    doc = dominate.document(title='Audit Engine version: ' + version)
    with doc.head:
        link(
            rel='stylesheet',
            href=
            'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css',
            integrity=
            "sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T",
            crossorigin="anonymous",
        )
        script(
            src="https://code.jquery.com/jquery-3.4.1.slim.min.js",
            integrity=
            "sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n",
            crossorigin="anonymous")
        script(
            src=
            "https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js",
            integrity=
            "sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6",
            crossorigin="anonymous")
    with doc:
        with div(cls='container'):
            with div(cls='jumbotron'):
                h1('Audit Engine: {version} - vote records summary'.format(
                    version=version))
                build_time = datetime.datetime.now(datetime.timezone.utc)
                p(f'Summary built at: {build_time.strftime("%Y-%m-%d %H:%M:%S")}',
                  cls='lead')
            get_summary_table(cmpcvr_df)
            with table(cls='table table-hover'):
                with thead():
                    with tr():
                        th('#', scope="col")
                        th('Ballot ID', scope="col")
                        th('Style', scope="col")
                table_body = tbody()
                table_body += mount_ballots_to_table(cmpcvr_df)

    return doc
示例#34
0
def list_notices(buf):
    """Render the list of all notices to the file-like `buf`."""
    title = u'HTTPolice notices'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.body:
        H.attr(_class=u'notices-list')
    with document:
        H.h1(title)
        H.p(u'This is the list of all notices produced by ',
            H.a(u'HTTPolice', href=homepage, target='_self'), u' version ',
            version, u'.')
        H.p(u'See also the ',
            H.a(u'HTTPolice manual', href=u'index.html', target='_self'), u'.')
        placeholder = Placeholder()
        for id_ in sorted(notice.all_notices.keys()):
            _notice_to_html(notice.all_notices[id_],
                            placeholder,
                            with_anchor=True)
    buf.write(document.render().encode('utf-8'))
示例#35
0
文件: html.py 项目: dfirst/httpolice
def html_report(exchanges, buf):
    """Generate an HTML report with check results.

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

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

    """
    title = u'HTTPolice report'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.head:
        H.script(type=u'text/javascript').add_raw_string(js_code)
    with document:
        H.h1(title)
        _render_exchanges(exchanges)
    buf.write(document.render().encode('utf-8'))
示例#36
0
def html_report(exchanges, buf):
    """Generate an HTML report with check results.

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

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

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

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

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

    buf.write(prologue.encode('utf-8'))
    for div in _generate_exchange_divs(exchanges):
        buf.write(div.render().encode('utf-8'))
    buf.write(epilogue.encode('utf-8'))
示例#37
0
    def index():
        doc = BootstrapDocument()
        # add socket-io client to the doc and our custom js.
        doc.scripts.add(script(
            src='//cdn.socket.io/socket.io-1.4.5.js',
            type='text/javascript'),
            script(src='/static/my.js',
                type='text/javascript'))

        doc.body.children.insert(0, Div(h1('Advanced Example'), 
            Div(h3('Flashes'), Div(id='flashes')))) 
        
        # add buttons below the content of the document
        doc.body.add(Button(
            'Table',
            onclick="user_socket.emit('table');"),
            Button('Form',
                onclick="user_socket.emit('form');"))

        return doc.render()
示例#38
0
def generatePostStatsHTML(graph,statsFilePath = "stats.html",postStatsFilePath = "postStats.html"): #Generates Post-Stats page
	voxelWise = checkHeightThreshold(graph)
	clusterWise = checkExtentThreshold(graph)
	softwareLabelNum = queryVersionNum(graph)
	softwareLabelNumList = addQueryToList(softwareLabelNum)
	statisticType = queryStatisticType(graph)
	statisticType = statisticImage(statisticType[0])
	statisticTypeString = statisticImageString(statisticType)
	contrastName = queryContrastName(graph)
	statisticMapImage = queryExcursionSetMap(graph)
	
	postStats = document(title="FSL Viewer") #Creates initial HTML page (Post Stats)
	postStats += h1("Sample FSL Viewer")
	postStats += ul(li(a("Stats", href="stats.html")), li("-"),li(a("Post Stats", href = "postStats.html")))
	postStats += h2("Post-stats")
	postStats += hr()
	postStats += h3("Analysis Methods")
	
	if voxelWise == True: #If main threshold is Height Threshold
		mainThreshValue = queryHeightThresholdValue(graph)
		if askSpm(graph) == True:
			
			postStats += p("FMRI data processing was carried out using SPM Version %s (SPM, http://www.fil.ion.ucl.ac.uk/spm/). %s statistic images were thresholded at P = %s (corrected)" % (softwareLabelNumList[1], statisticTypeString, mainThreshValue[0]))
	
		elif askFsl(graph) == True:
			fslFeatVersion = queryFslFeatVersion(graph)
			postStats += p("FMRI data processing was carried out using FEAT (FMRI Expert Analysis Tool) Version %s, part of FSL %s (FMRIB's Software Library, www.fmrib.ox.ac.uk/fsl)."
			"%s statistic images were thresholded at P = %s (corrected)" 
			%(fslFeatVersion[0], softwareLabelNumList[1], statisticTypeString, mainThreshValue[0]))
	
	elif clusterWise == True: #If main threshold is extent threshold
		
		mainThreshValue = queryClusterThresholdValue(graph)
		heightThreshValue = queryUHeightThresholdValue(graph)
		clusterThreshType = clusterFormingThreshType(graph, statisticType)
		
		if askSpm(graph) == True:
			
			postStats += p("FMRI data processing was carried out using SPM Version %s (SPM, http://www.fil.ion.ucl.ac.uk/spm/). %s statistic images were thresholded using clusters determined by %s > %s and a (corrected) "
			"cluster significance of P = %s " 
			% (softwareLabelNumList[1], statisticTypeString, clusterThreshType, heightThreshValue[0], mainThreshValue[0]))
	
		elif askFsl(graph) == True:
			fslFeatVersion = queryFslFeatVersion(graph)
			postStats += p("FMRI data processing was carried out using FEAT (FMRI Expert Analysis Tool) Version %s, part of FSL %s (FMRIB's Software Library, www.fmrib.ox.ac.uk/fsl). %s statistic images were thresholded "
			"using clusters determined by %s > %s and a (corrected) cluster significance of P = %s" 
			%(fslFeatVersion[0], softwareLabelNumList[1], statisticTypeString, clusterThreshType, heightThreshValue[0], mainThreshValue[0]))
		
	
	else: #If there is no corrected threshold - assume voxel wise
		mainThreshValue = queryUHeightThresholdValue(graph)
		if askSpm(graph) == True and askIfPValueUncorrected(graph) == True: #SPM used and threshold type is nidm_PValueUncorrected
			postStats += p("FMRI data processing was carried out using SPM Version %s (SPM, http://www.fil.ion.ucl.ac.uk/spm/). %s statistic images were thresholded at P = %s (uncorrected)" % (softwareLabelNumList[1], statisticTypeString, mainThreshValue[0]))
			
		
		elif askSpm(graph) == True and askIfOboStatistic(graph) == True: #SPM used and threshold type is obo_statistic
			postStats += p("FMRI data processing was carried out using SPM Version %s (SPM, http://www.fil.ion.ucl.ac.uk/spm/). %s statistic images were thresholded at %s = %s (uncorrected)" % (softwareLabelNumList[1], statisticTypeString, statisticType, mainThreshValue[0]))
			
		
		elif askFsl(graph) == True and askIfPValueUncorrected(graph) == True:
			
			fslFeatVersion = queryFslFeatVersion(graph)
			postStats += p("FMRI data processing was carried out using FEAT (FMRI Expert Analysis Tool) Version %s, part of FSL %s (FMRIB's Software Library, www.fmrib.ox.ac.uk/fsl)."
			"%s statistic images were thresholded at P = %s (uncorrected)." % (fslFeatVersion[0], softwareLabelNumList[1], statisticTypeString, mainThreshValue[0]))
			
			
		elif askFsl(graph) == True and askIfOboStatistic(graph) == True:
			
			fslFeatVersion = queryFslFeatVersion(graph)
			postStats += p("FMRI data processing was carried out using FEAT (FMRI Expert Analysis Tool) Version %s, part of FSL %s (FMRIB's Software Library, www.fmrib.ox.ac.uk/fsl)."
			"%s statistic images were thresholded at %s = %s (uncorrected)." % (fslFeatVersion[0], softwareLabelNumList[1], statisticTypeString, statisticType, mainThreshValue[0]))
			
		
	
	postStats += hr()
	postStats += h3("Thresholded Activation Images")
	postStats += hr()
	i = 0
	
	if askFsl(graph) == True:
	
		while i < len(contrastName):
		
			postStats += p("%s" % contrastName[i])
			postStats += img(src = statisticMapImage[i])
			i = i + 1
	
	postStatsFile = open(postStatsFilePath, "x")
	print(postStats, file = postStatsFile)
	postStatsFile.close()