Exemplo n.º 1
0
    def show(self) -> None:
        self._show()
        self.init_aside(name="Home")
        self.set_aside()
        self.collapse_menu()
        self.alas_name = ""
        if hasattr(self, "alas"):
            del self.alas
        self.set_status(0)

        def set_language(l):
            lang.set_language(l)
            self.show()

        def set_theme(t):
            self.set_theme(t)
            run_js("location.reload()")

        with use_scope("content"):
            put_text("Select your language / 选择语言").style("text-align: center")
            put_buttons(
                [
                    {"label": "简体中文", "value": "zh-CN"},
                    {"label": "繁體中文", "value": "zh-TW"},
                    {"label": "English", "value": "en-US"},
                    {"label": "日本語", "value": "ja-JP"},
                ],
                onclick=lambda l: set_language(l),
            ).style("text-align: center")
            put_text("Change theme / 更改主题").style("text-align: center")
            put_buttons(
                [
                    {"label": "Light", "value": "default", "color": "light"},
                    {"label": "Dark", "value": "dark", "color": "dark"},
                ],
                onclick=lambda t: set_theme(t),
            ).style("text-align: center")

            # show something
            put_markdown(
                """
            Alas is a free open source software, if you paid for Alas from any channel, please refund.
            Alas 是一款免费开源软件,如果你在任何渠道付费购买了Alas,请退款。
            Project repository 项目地址:`https://github.com/LmeSzinc/AzurLaneAutoScript`
            """
            ).style("text-align: center")

        if lang.TRANSLATE_MODE:
            lang.reload()

            def _disable():
                lang.TRANSLATE_MODE = False
                self.show()

            toast(
                _t("Gui.Toast.DisableTranslateMode"),
                duration=0,
                position="right",
                onclick=_disable,
            )
Exemplo n.º 2
0
async def main():
    """PyWebIO聊天室
    和当前所有在线的人聊天
    """
    global chat_msgs
    # run_js("alert('233')")
    put_markdown(
        "## PyWebIO聊天室\n欢迎来到聊天室,你可以和当前所有在线的人聊天。你可以在浏览器的多个标签页中打开本页面来测试聊天效果。"
        "本应用使用不到80行代码实现,源代码[链接](https://github.com/wang0618/PyWebIO/blob/dev/demos/chat_room.py)",
        lstrip=True)

    msg_box = output()
    put_scrollable(msg_box, height=300, keep_bottom=True)
    nickname = await input("请输入你的昵称",
                           required=True,
                           validate=lambda n: '昵称已被使用'
                           if n in online_users or n == '📢' else None)

    online_users.add(nickname)
    chat_msgs.append(
        ('📢', '`%s`加入聊天室. 当前在线人数 %s' % (nickname, len(online_users))))
    msg_box.append(
        put_markdown('`📢`: `%s`加入聊天室. 当前在线人数 %s' %
                     (nickname, len(online_users))))

    @defer_call
    def on_close():
        online_users.remove(nickname)
        chat_msgs.append(
            ('📢', '`%s`退出聊天室. 当前在线人数 %s' % (nickname, len(online_users))))

    refresh_task = run_async(refresh_msg(nickname, msg_box))

    while True:
        data = await input_group(
            '发送消息', [
                input(name='msg', help_text='消息内容支持行内Markdown语法'),
                actions(
                    name='cmd',
                    buttons=['发送', '多行输入', {
                        'label': '退出',
                        'type': 'cancel'
                    }])
            ],
            validate=lambda d: ('msg', '消息不为空')
            if d['cmd'] == '发送' and not d['msg'] else None)
        if data is None:
            break
        if data['cmd'] == '多行输入':
            data['msg'] = '\n' + await textarea(
                '消息内容', help_text='消息内容支持Markdown语法', required=True)
        msg_box.append(
            put_markdown('`%s`: %s' % (nickname, data['msg']), sanitize=True))
        msg_box.append(put_markdown(str(chat_msgs), sanitize=True))
        chat_msgs.append((nickname, data['msg']))

    refresh_task.close()
    toast("你已经退出聊天室")
Exemplo n.º 3
0
def hike():
    current_salary = input("Enter your current salary ($):", type=FLOAT)
    new_salary = input("Enter your new salary ($):", type=FLOAT)
    total_hike = (new_salary - current_salary)
    hike_per = (((new_salary - current_salary) / current_salary) * 100)
    put_markdown('# **Results**')
    put_html('<br><br>')
    put_markdown('Your Hike: %.1f. Hike percentage: %s' %
                 (total_hike, hike_per))
    put_html('<hr>')
    put_table([
        ['Hike($)', 'Hike (%)'],
        [total_hike, hike_per],
    ])
Exemplo n.º 4
0
def markdown():
    put_markdown(r"""
    # Ad caret Claninque nati virum

    ## Verba consurgere urbis

    Lorem markdownum Hippomenes opes unus. Naides Troiaeque vagans aeris, firmat
    classis attollere vocat, et utinam dextris inritat. Membraque o heres Eumenides
    vultu erat quaeque ait vocato. *Vota alebat licet* praedelassat potitur in
    interea restare oculis hoc vestigia quotiens flammae suarum Cyanen et oscula
    liquida. Ante summam strigis.

    1. Amantes mira
    2. Illic et annis corpore
    3. Tuae paternos Actaeo adsensere si fecisse nostris
    4. Speciosoque est opus o reverentia nati

    Dei resupino aquarum translucet genitam pavor, sub regia: iamque. Satum
    glomerataque vulnere? Et gravitate, ab busta, circumspexit cornua premitur
    accinctus mutare, ille. Properare [regnum a adest](http://www.vidit.net/),
    Hecates, si eram quo caesoque fuit locum pugnax ille. Socia deficiunt nixus
    rigidos, quae illam Amathunta insequar pugnat.

    Absentes dixit deprendere dixit nec dum et credi illam. Nec saepe et mihi ubi
    longus dextera nec laniata [umeris sperneret](http://www.flammis-fretum.com/sic)
    veneni, simillima et mota venerande, ite sic. *Trahi radiare* nodum. Parentis
    contraria patent **lumina securus** meque altum, Atrides sive. **Quid
    laboratum** denegat circumspexit nostra.

    ## Sibi cum conviciaque iubar

    Simul via una, liquidis hac, in validi classem credit: omnia unde meorum.
    Bracchia non sit mater recondidit repulsam pennis ab bracchia pepercit eadem
    quod eurus partes. Dis [non vocavit](http://telaque.net/pellibus), opes quid
    quamvis te vincis cinctam.

    1. Memini nutrimen rictus
    2. Adeo genetrix fallitis instruxit gesserat una sceptri
    3. Vidit utque et nam pete restitit
    4. Similis fixus quoque cruribus pictis
    5. Mutantur generis non muros per levati quid

    Te teneros brevis unica licet pinu *sed quem Sisyphon*; Ityn quae: manu. Tacitus
    scopulum et praemia, in quemquam luctus: dextra sepulcro porrexit est tibi.

    Huic de iuvenes eundo, ceu sub adductaque Dianae. Cernes vulnus fuit praeda, et
    nulla dryades potest [ipso](http://quicquid.net/). Castique Ceyce mihi *per fui
    intendit* crudelia me igne inplerit Erymanthidas?
    """, lstrip=True)
Exemplo n.º 5
0
def create_profile(df: pd.DataFrame = None, title: Optional[str] = 'Title'):
    profile = None
    with put_loading(shape='grow'):
        report = sv.analyze(df)
        # NOTE: Line below will take some time to complete...
        profile = report.show_html(layout='vertical')
    if profile:
        print(session_info.user_language)
        put_html(profile)
    else:
        put_markdown(t(
            r"""
                ## <p align="middle">_Errors occured analyzing the \"csv\" file._</p>
                """, r"""
                ## <p align="middle">_При анализе загруженного \"csv\" файла возникли ошибки._</p>
                """),
                     strip_indent=4)
Exemplo n.º 6
0
async def index():
    """PyWebIO Chart Gallery

    PyWebIO supports for data visualization with the third-party libraries. This page shows the demos of data visualization using plotly, bokeh, pyecharts and cutcharts in PyWebIO.
    PyWebIO 支持使用第三方库进行数据可视化,本页面展示了在 PyWebIO 中使用plotly、bokeh、pyecharts和cutecharts进行数据可视化的示例
    """
    global readme, readme_zh

    md = readme_zh if 'zh' in session_info.user_language else readme
    md = re.sub(r"\[\*\*demos\*\*\]\(.*?\?app=(.+?)\)",
                r"[**demos**](./?app=\g<1>)", md)
    cdn = r"https://fastly.jsdelivr.net/gh/wang0618/pywebio-chart-gallery"
    github_url = r"https://raw.githubusercontent.com/wang0618/pywebio-chart-gallery/master"
    md = md.replace(github_url, cdn)
    md = re.sub(r"<div></div>[\s\S]*$", "", md)

    put_markdown(md)
Exemplo n.º 7
0
def index():
    """PyWebIO demos

    PyWebIO的基本demo和数据可视化demo
    """
    style(
        put_row([
            put_markdown('# PyWebIO demos'),
            put_html(
                '<a class="github-button" data-size="large" href="https://github.com/wang0618/PyWebIO" data-show-count="true" aria-label="Star wang0618/PyWebIO on GitHub">Star</a>'
            )
        ],
                size='1fr auto'), 'align-items:center')
    put_html(
        '<script async defer src="https://buttons.github.io/buttons.js"></script>'
    )

    put_markdown(index_md)
Exemplo n.º 8
0
def bmi():
    height = input("Input your height(cm):", type=FLOAT)
    weight = input("Input your weight(kg):", type=FLOAT)

    BMI = weight / (height / 100) ** 2

    top_status = [(16, 'Severely underweight'), (18.5, 'Underweight'),
                  (25, 'Normal'), (30, 'Overweight'),
                  (35, 'Moderately obese'), (float('inf'), 'Severely obese')]

    for top, status in top_status:
        if BMI <= top:
            put_markdown('# **Results**')
            put_html('<br><br>')
            put_markdown('Your BMI: `%.1f`. Category: `%s`' % (BMI, status))
            put_html('<hr>')
            put_table([
                ['Your BMI', 'Category'],
                [BMI, status],
            ])

            break
Exemplo n.º 9
0
def refresh_msg(my_name, msg_box):
    """刷新聊天消息"""
    global chat_msgs
    last_idx = len(chat_msgs)
    while True:
        for m in chat_msgs[last_idx:]:
            if m[0] != my_name:  # 仅刷新其他人的新信息
                msg_box.append(put_markdown('`%s`: %s' % m))

        # 清理聊天记录
        if len(chat_msgs) > MAX_MESSAGES_CNT:
            chat_msgs = chat_msgs[len(chat_msgs) // 2:]

        last_idx = len(chat_msgs)
Exemplo n.º 10
0
async def refresh_msg(my_name, msg_box):
    """刷新聊天消息"""
    global chat_msgs
    print("---")
    last_idx = len(chat_msgs)
    while True:
        await asyncio.sleep(0.5)
        for m in chat_msgs[last_idx:]:
            print(m)
            if m[0] != my_name:  # 仅刷新其他人的新信息
                msg_box.append(put_markdown('`%s`: %s' % m))

        # 清理聊天记录
        if len(chat_msgs) > MAX_MESSAGES_CNT:
            chat_msgs = chat_msgs[len(chat_msgs) // 2:]

        last_idx = len(chat_msgs)
#!/usr/bin/env python3
# vim: set fileencoding=utf-8

import pywebio.output as out

markdown = '''
Markdown rendering
==================

Lorem ipsum
-----------

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
'''

out.put_markdown(markdown)
# pout.put_code("""pin.checkbox("What toppings for pizza?", options=["pepperoni", "sausage", "chicken"])""")
# pin.checkbox("What toppings for pizza?", options=["pepperoni", "sausage", "chicken"])
#
# pout.put_code("""pin.select("Who's GOAT in NBA?", options=["Bryant", "Jordan", "James"])""")
# pin.select("Who's GOAT in NBA?", options=["Bryant", "Jordan", "James"])
#
# pout.put_code("""pin.radio("Are you ready to try pyWebIO?", options=["Yes", "No"])""")
# pin.radio("Are you ready to try pyWebIO?", options=["Yes", "No"])

pout.put_text("This is an awesome library.")

pout.put_table([("Col 1 Title", "Col 2 Title"),
                ("Row 1, Col 1", "Row 1, Col 2"),
                ("Row 2, Col 1", "Row 2, Col2")])

pout.put_markdown("# This is the Title")
pout.put_markdown("## This is the Subtitle")
pout.put_markdown("_Bold Text_")
pout.put_markdown("__Italic Text__")
pout.put_markdown("*__Bold & Italic__*")
pout.put_markdown("[google.com](google.com)")

pout.put_image(open("airplane.jpg", "rb").read())
pout.toast("Please Pay Attention!", duration=10)


def show_text():
    pout.toast("Button is clicked!", duration=10)


pout.put_button("I'm Ready!", onclick=show_text)
Exemplo n.º 13
0
def index():
    put_markdown(index_md)
Exemplo n.º 14
0
 def index():
     from pywebio.output import put_markdown
     put_markdown(md_text)
Exemplo n.º 15
0
from pywebio import input, output
from time import *

output.put_markdown("## Hi </fooders>")
output.put_markdown("<p>I am Jayant</p>")

output.put_table([["Name", "code"], ['Food', 11], ['Water', 12],
                  ['Sunlight', 13]])

with output.popup("Subscribe to the page"):
    output.put_text("Join Other Customer!")

food = input.select("Choose Your Favorite Food", ['Maggi', 'Noodles'])
output.put_text("You Choose", food, "from given list")

output.put_processbar('bar')

for i in range(1, 11):
    output.set_processbar('bar', i / 10)
    sleep(0.1)

output.put_markdown("Your Order is ready")

if food == "Maggi":
    with open("maggi.jpg", "rb+") as f:
        image = f.read()
else:
    with open("noodles.jpg", "rb+") as f:
        image = f.read()

output.put_image(image, height="100", width="100")
Exemplo n.º 16
0
def translate():
    """
        Translate Alas
    """
    set_env(output_animation=False)
    run_js(r"""$('head').append('<style>footer {display: none}</style>')""")

    put_markdown("""
        # Translate
        You can submit(Next) by press `Enter`.
    """)

    dict_lang = {
        "zh-CN": read_file(filepath_i18n('zh-CN')),
        "zh-TW": read_file(filepath_i18n('zh-TW')),
        "en-US": read_file(filepath_i18n('en-US')),
        "ja-JP": read_file(filepath_i18n('ja-JP')),
    }
    modified = {
        "zh-CN": {},
        "zh-TW": {},
        "en-US": {},
        "ja-JP": {},
    }

    list_path = []  # Menu.Task.name
    list_group = []  # Menu
    list_arg = []  # Task
    list_key = []  # name
    for L, _ in deep_iter(dict_lang['zh-CN'], depth=3):
        list_path.append('.'.join(L))
        list_group.append(L[0])
        list_arg.append(L[1])
        list_key.append(L[2])
    total = len(list_path)

    class V:
        lang = lang.LANG
        untranslated_only = False
        clear = False

        idx = -1
        group = ''
        group_idx = 0
        groups = list(dict_lang['zh-CN'].keys())
        arg = ''
        arg_idx = 0
        args = []
        key = ''
        key_idx = 0
        keys = []

    def update_var(group=None, arg=None, key=None):
        if group:
            V.group = group
            V.idx = list_group.index(group)
            V.group_idx = V.idx
            V.arg = list_arg[V.idx]
            V.arg_idx = V.idx
            V.args = list(dict_lang["zh-CN"][V.group].keys())
            V.key = list_key[V.idx]
            V.key_idx = V.idx
            V.keys = list(dict_lang["zh-CN"][V.group][V.arg].keys())
        elif arg:
            V.arg = arg
            V.idx = list_arg.index(arg, V.group_idx)
            V.arg_idx = V.idx
            V.args = list(dict_lang["zh-CN"][V.group].keys())
            V.key = list_key[V.idx]
            V.key_idx = V.idx
            V.keys = list(dict_lang["zh-CN"][V.group][V.arg].keys())
        elif key:
            V.key = key
            V.idx = list_key.index(key, V.arg_idx)
            V.key_idx = V.idx
            V.keys = list(dict_lang["zh-CN"][V.group][V.arg].keys())

        update_form()

    def next_key():
        if V.idx + 1 > total:
            V.idx = -1

        V.idx += 1

        if V.untranslated_only:
            while True:
                # print(V.idx)
                key = deep_get(dict_lang[V.lang], list_path[V.idx])
                if list_path[V.idx] == key or list_path[V.idx].split(
                        '.')[2] == key:
                    break
                else:
                    V.idx += 1
                if V.idx + 1 > total:
                    V.idx = 0
                    break

        (V.group, V.arg, V.key) = tuple(list_path[V.idx].split('.'))
        V.group_idx = list_group.index(V.group)
        V.arg_idx = list_arg.index(V.arg, V.group_idx)
        V.args = list(dict_lang["zh-CN"][V.group].keys())
        V.key_idx = list_key.index(V.key, V.arg_idx)
        V.keys = list(dict_lang["zh-CN"][V.group][V.arg].keys())

    def update_form():
        input_update('arg', options=V.args, value=V.arg)
        input_update('key', options=V.keys, value=V.key)
        for L in LANGUAGES:
            input_update(L,
                         value=deep_get(dict_lang[L],
                                        f'{V.group}.{V.arg}.{V.key}',
                                        'Key not found!'))

        old = deep_get(dict_lang[V.lang], f'{V.group}.{V.arg}.{V.key}',
                       'Key not found!')
        input_update(
            V.lang,
            value=None if V.clear else old,
            help_text=f'{V.group}.{V.arg}.{V.key}',
            placeholder=old,
        )

    def get_inputs():
        out = []
        old = deep_get(dict_lang[V.lang], f'{V.group}.{V.arg}.{V.key}',
                       'Key not found!')
        out.append(
            input(
                name=V.lang,
                label=V.lang,
                value=None if V.clear else old,
                help_text=f'{V.group}.{V.arg}.{V.key}',
                placeholder=old,
            ))
        out.append(
            select(name='group',
                   label='Group',
                   options=V.groups,
                   value=V.group,
                   onchange=lambda g: update_var(group=g),
                   required=True))
        out.append(
            select(name='arg',
                   label='Arg',
                   options=V.args,
                   value=V.arg,
                   onchange=lambda a: update_var(arg=a),
                   required=True))
        out.append(
            select(name='key',
                   label='Key',
                   options=V.keys,
                   value=V.key,
                   onchange=lambda k: update_var(key=k),
                   required=True))
        _LANGUAGES = LANGUAGES.copy()
        _LANGUAGES.remove(V.lang)
        for L in _LANGUAGES:
            out.append(
                input(name=L,
                      label=L,
                      readonly=True,
                      value=deep_get(dict_lang[L],
                                     f'{V.group}.{V.arg}.{V.key}',
                                     'Key not found!')))
        out.append(
            actions(name='action',
                    buttons=[
                        {
                            "label": "Next",
                            "value": 'Next',
                            "type": "submit",
                            "color": "success"
                        },
                        {
                            "label": "Next without save",
                            "value": 'Skip',
                            "type": "submit",
                            "color": "secondary"
                        },
                        {
                            "label": "Submit",
                            "value": "Submit",
                            "type": "submit",
                            "color": "primary"
                        },
                        {
                            "label": "Quit and save",
                            "type": "cancel",
                            "color": "secondary"
                        },
                    ]))

        return out

    def save():
        for LANG in LANGUAGES:
            d = read_file(filepath_i18n(LANG))
            for k in modified[LANG].keys():
                deep_set(d, k, modified[LANG][k])
            write_file(filepath_i18n(LANG), d)

    defer_call(save)

    def loop():
        while True:
            data = input_group(inputs=get_inputs())
            if data is None:
                save()
                break

            if data['action'] == 'Next':

                modified[V.lang][f'{V.group}.{V.arg}.{V.key}'] = data[
                    V.lang].replace("\\n", "\n")
                deep_set(dict_lang[V.lang], f'{V.group}.{V.arg}.{V.key}',
                         data[V.lang].replace("\\n", "\n"))
                next_key()
            if data['action'] == 'Skip':
                next_key()
            elif data['action'] == 'Submit':

                modified[V.lang][f'{V.group}.{V.arg}.{V.key}'] = data[
                    V.lang].replace("\\n", "\n")
                deep_set(dict_lang[V.lang], f'{V.group}.{V.arg}.{V.key}',
                         data[V.lang].replace("\\n", "\n"))
                continue

    def setting():
        data = input_group(inputs=[
            select(name='language',
                   label='Language',
                   options=LANGUAGES,
                   value=V.lang,
                   required=True),
            checkbox(
                name='check',
                label='Other settings',
                options=[{
                    "label": 'Button [Next] only shows untranslated key',
                    'value': 'untranslated',
                    'selected': V.untranslated_only
                }, {
                    "label":
                    'Do not fill input with old value (only effect the language you selected)',
                    "value": "clear",
                    "selected": V.clear
                }])
        ])
        V.lang = data['language']
        V.untranslated_only = True if 'untranslated' in data['check'] else False
        V.clear = True if 'clear' in data['check'] else False

    put_buttons([{
        "label": "Start",
        "value": "start"
    }, {
        "label": "Setting",
        "value": "setting"
    }],
                onclick=[loop, setting])
    next_key()
    setting()
    hold()