Example #1
0
def add_expense(db, cursor, users):
    userlist = []
    userid = {}
    for i in users:
        userlist.append(users[i].name)
        userid[users[i].name] = users[i].id

    user = input_group(
        "Choose user who made the expense",
        [
            radio(
                "Who made the expense?",
                name="name",
                options=userlist,
            ),
        ],
    )
    data = input_group(
        "Expense details",
        [
            input("What store?", name="store", type=TEXT),
            input("What is the amount?", name="amount", type=FLOAT),
        ],
    )
    add_to_db(db, cursor, "register",
              (userid[user['name']], data['store'], data['amount'] * 100))
def predict():
    year = input("Enter Year", type=NUMBER)
    import_ = input("Import in millions", type=NUMBER)
    export_ = input("Export in millions", type=NUMBER)
    industrial_production = input("Industrial Production", type=FLOAT)
    inflation_rate = input("Inflation rate (%)", type=FLOAT)
    exchange_rate = input("Exchange rate (USD)", type=FLOAT)
    population = input("Population Growth Rate in %", type=FLOAT)
    stock_market = input("Stock market sales", type=FLOAT)
    unemployment = input("Unemployment rate (%)", type=FLOAT)
    sensex_index = input("Sensex Index(Gain/Loss)", type=FLOAT)
    prediction = model.predict([[
        year, import_, export_, industrial_production, inflation_rate,
        exchange_rate, population, stock_market, unemployment, sensex_index
    ]])
    output_1 = round(prediction[0], 2)

    put_text('GDP increased from last year will be: ', output_1)
    years = [
        1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
        2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014,
        2015, 2016, 2017, 2018, 2019, year
    ]
    gdp_Values = [
        1.06, 5.48, 4.75, 6.66, 7.57, 7.55, 4.05, 6.18, 8.85, 3.84, 4.82, 3.8,
        7.86, 7.92, 7.92, 8.06, 7.66, 3.09, 7.86, 8.5, 5.24, 5.46, 6.39, 7.41,
        8, 8.26, 7.04, 6.12, 4.18, output_1
    ]
    plt.barh(years, gdp_Values, align='center')
    plt.savefig('fig_.png')
    img = open('fig_.png', 'rb').read()
    put_image(img)
Example #3
0
 def start(self):
     coll_info = input_group('第一步:采集人脸数据', [
         input('face_name',
               type=TEXT,
               name='face_name',
               required=True,
               placeholder="请输入人脸名称,请使用英文标识"),
         input('face_num',
               type=NUMBER,
               name='face_num',
               required=True,
               placeholder="请输入采集人脸数量",
               value=5),
         actions('action', [{
             'label': '开始采集',
             'value': 'start'
         }],
                 name='action',
                 help_text='actions'),
     ])
     if coll_info['action'] == 'start':
         self.collect(coll_info['face_num'], coll_info['face_name'])
     confirm = actions('第二步:人脸数据训练', ['开始训练'], help_text='训练人脸数据')
     if confirm == '开始训练':
         self.training()
     confirm = actions('第三步:人脸检测功能', ['开始检测'], help_text='检测人脸功能')
     if confirm == '开始检测':
         self.recognition()
Example #4
0
def main():
    # 设置网站标题
    set_env(title='自动打卡', output_animation=False)
    # 说明
    put_markdown(r""" # 杭电自动健康打卡系统
    本系统尚不完善,存在许多bug,一切以实际效果为准.
    使用说明见[自动打卡使用说明](https://jinjis.cn/index.php/archives/hduzi-dong-jian-kang-da-ka-xi-tong.html)
    """,
                 lstrip=True)
    # 输入框等交互 返回字典
    data = input_group("信息", [
        input("请输入token",
              help_text='token获取方式见底部',
              type=TEXT,
              validate=check_token,
              name='token'),
        input("请输入省份",
              help_text='城市获取方式见底部 默认为浙江省杭州市江干区',
              type=NUMBER,
              value='7',
              name='p'),
        input("请输入城市", type=NUMBER, value='9', name='c'),
        input("请输入地区", type=NUMBER, value='4', name='a'),
        input("Qmsg酱推送KEY", type=TEXT, help_text='推送说明见底部 不推送请填0', name='qq'),
    ])

    list = []
    for value in data.values():
        list.append(value)
    wb = load_workbook('data.xlsx')
    ws = wb.active
    ws.append(list)
    wb.save('data.xlsx')
    popup('提示', '信息保存成功!请不要重复提交信息 有问题请联系管理员')
def main():
    height = input("请输入你的身高(cm):", type=FLOAT)
    weight = input("请输入你的体重(kg):", type=FLOAT)

    bmi_value, status = bmi(height, weight)

    put_text(f'你的 BMI 值:{bmi_value:.1f},身体状态:{status}')
Example #6
0
def btn_click():
    # toast('New messages', position='right', color='#2188ff', duration=0)
    # put_markdown("> You click `%s` button" % btn_val)
    # with popup('Choose Your Best'):
    #     input('Input your Name', type=TEXT)
    #     input('Input your age', type=NUMBER)
    input('Input your age', type=NUMBER)
    print("input  Clicked")
Example #7
0
def add_product(db, cursor):
    data = input_group(
        "product details",
        [
            input("Name?", name="name", type=TEXT),
            input("Price", name="cost", type=NUMBER),
        ],
    )
    add_to_db(db, cursor, 'add_product', (data['name'], data['cost']))
Example #8
0
def main():
    info = input_group("HCL Online Exam for Machine Learning Engineer", [
        input('Name  ', name='name'),
        input('ID NO. ', name='id'),
        input('Age ', name='age', type=NUMBER),
        actions('Start Exam', ['YES'], name='confirm')
    ])

    q1 = radio(
        "Which of the following is a widely used and effective machine learning algorithm based on the idea of bagging?",
        ["Decision Tree", "Regression", "Classification", "Random Forest"])
    q2 = radio(
        "To find the minimum or the maximum of a function, we set the gradient to zero because:",
        [
            "The value of the gradient at extrema of a function is always zero",
            "Depends on the type of problem", "None of the above"
        ])
    q3 = radio("Which of the following is a disadvantage of decision trees?", [
        "Factor analysis", "Decision trees are robust to outliers",
        "Decision trees are prone to be overfit", "None of the above"
    ])
    q4 = radio(
        "When performing regression or classification, which of the following is the correct way to preprocess the data?",
        [
            "Normalize the data -> PCA -> training",
            "PCA -> normalize PCA output -> training",
            "Normalize the data -> PCA -> normalize PCA output -> training"
        ])
    q5 = radio(
        "Which of the following techniques can not be used for normalization in text mining?",
        [
            "Stemming", "Lemmatization", "Stop Word Removal",
            "None of the above"
        ])
    c = 0
    if q1 == "Random Forest":
        c += 1

    if q2 == "The value of the gradient at extrema of a function is always zero":
        c += 1

    if q3 == "Decision trees are prone to be overfit":
        c += 1

    if q4 == "Normalize the data -> PCA -> training":
        c += 1

    if q5 == "Stop Word Removal":
        c += 1

    if c > 3:
        put_markdown("""# you are passed""")

    if c <= 3:
        put_markdown("""# you are failed""")
Example #9
0
def search_food(mode):
    food = {
        'normal':
        lambda mode: input(
            'What do you want?', type=TEXT, placeholder='百頁豆腐', required=True),
        'child':
        lambda mode: input(
            'What do you want?', type=TEXT, placeholder='蔬菜沙拉', required=True),
        'dead':
        lambda mode: input(
            'What do you want?', type=TEXT, placeholder='香雞排', required=True)
    }[mode](mode)
    return food
Example #10
0
def bmicalculator():
    height = input("Please enter the height in cm", type=FLOAT)
    weight = input("Please enter the weight in kg", type=FLOAT)

    bmi = weight / (height / 100)**2
    bmi_output = [(16, 'Severely underweight'), (18.5, 'underweight'),
                  (25, 'Normal'), (30, 'Overweight'), (35, 'Moderately obese'),
                  (float('inf'), 'severely obese')]

    for tuple1, tuple2 in bmi_output:
        if bmi <= tuple1:
            put_text('your BMI is: %.1f and the person is:%s' % (bmi, tuple2))
            break
Example #11
0
def vaccine():
    name = input("Enter your Name: ", type='text')
    age = input("Enter your age:", type=NUMBER)

    if age >= 18:
        put_text('Check if your details')
        put_table([['NAME', 'AGE'], [name, age]])
        check = checkbox(options=['All Details are correct'])
        if check:
            selection = radio("Select your vaccine",
                              ['Moderna', 'Pfizer', 'JnJ'])
            put_text('Your Vaccine Information is Recorded')
            put_table([['NAME', 'AGE', 'Vaccine'], [name, age, selection]])
Example #12
0
def bmi_calc():
    height = input("Please enter your Height in cm :", type=FLOAT)
    weight = input("Please enter your weight in kg :", type=FLOAT)

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

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

    for tuple1, tuple2 in bmi_output:
        if bmi <= tuple1:
            put_text("Your bmi is", bmi, ",You are", tuple2)
            break
Example #13
0
def BMI_CALC():
    height = input("Enter the height in cms", type=FLOAT)
    weight = input("Enter the weight in kg", type=FLOAT)

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

    bmi_output = [(16, 'severely underweight'), (18.5, 'underweight'),
                  (25, 'normal'), (30, 'overweight'), (35, 'moderately obese'),
                  (float('inf'), 'severely obese')]

    for t1, t2 in bmi_output:
        if bmi <= t1:
            put_text("your bmi is :%.1f and the person is :%s " % (bmi, t2))

            break
Example #14
0
def bmi():
    height = input("Input your height(cm):", type=FLOAT)
    weight = input("Input your weight(kg):", type=FLOAT)

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

    print(f"YOUR BMI = {BMI}")

    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_text('Your BMI: %.1f. Category: %s' % (BMI, status))
            break
Example #15
0
def change_username(db, cursor, users):
    userlist = []
    userid = {}
    for i in users:
        userlist.append(users[i].name)
        userid[users[i].name] = users[i].id

    user = input_group(
        "Choose user who made the expense",
        [
            radio(
                "Who made the expense?",
                name="name",
                options=userlist,
            ),
        ],
    )
    data = input_group(
        "Expense details",
        [
            input("What's the new name?", name="newname", type=TEXT),
        ],
    )

    querie = f"UPDATE `users` SET `user_name` = '{data['newname']}' " \
             f"WHERE `users`.`user_id` = '{userid[user['name']]}'"

    cursor.execute(querie)
Example #16
0
        def addNetworkAction():
            def checkPSK(psk):
                if len(psk) < 8 and len(psk) > 0:
                    return "psk password is at less 8 charactor long"

            with use_scope("result", clear=True):
                data = input_group("Add New SSID/Password", [
                    input("Interface", name="intf", value="wan"),
                    input("SSID", name="ssid"),
                    input("psk", name="psk", validate=checkPSK),
                ])
                print(type(data['intf']), type(data['ssid']),
                      type(data['psk']))
                print(data['intf'], data['ssid'], data['psk'])
                wi.addNetwork(str(data['intf']), str(data['ssid']),
                              str(data['psk']))
                knownNetworkAction()
Example #17
0
def predict():
    sepallength = input("Enter the sepal length: ", type=FLOAT)
    sepalwidth = input("Enter the sepal width: ", type=FLOAT)
    petallength = input("Enter the petal length: ", type=FLOAT)
    petalwidth = input("Enter the petal width: ", type=FLOAT)

    prediction = model.predict(
        [[sepallength, sepalwidth, petallength, petalwidth]])

    if prediction == 0:
        put_text("The prediction is setosa")

    elif prediction == 1:
        put_text("The prediction is versicolor")

    else:
        put_text("The prediction is virginica")
def predict():
    Year = input("Enter the Model Year:", type=NUMBER)
    Year = 2021 - Year
    Present_Price = input("Enter the Present Price(in LAKHS)", type=FLOAT)
    Kms_Driven = input("Enter the distance it has travelled(in KMS):",
                       type=FLOAT)
    Kms_Driven2 = np.log(Kms_Driven)
    Owner = input(
        "Enter the number of owners who have previously owned it(0 or 1 or 2 or 3)",
        type=NUMBER)
    Fuel_Type = select('What is the Fuel Type', ['Petrol', 'Diesel', 'CNG'])
    if (Fuel_Type == 'Petrol'):
        Fuel_Type = 239

    elif (Fuel_Type == 'Diesel'):
        Fuel_Type = 60

    else:
        Fuel_Type = 2
    Seller_Type = select('Are you a dealer or an individual',
                         ['Dealer', 'Individual'])
    if (Seller_Type == 'Individual'):
        Seller_Type = 106

    else:
        Seller_Type = 195
    Transmission = select('Transmission Type', ['Manual Car', 'Automatic Car'])
    if (Transmission == 'Manual Car'):
        Transmission = 261
    else:
        Transmission = 40

    prediction = model.predict([[
        Present_Price, Kms_Driven2, Fuel_Type, Seller_Type, Transmission,
        Owner, Year
    ]])
    output = round(prediction[0], 2)

    if output < 0:
        put_text("Sorry You can't sell this Car")

    else:
        put_text('You can sell this Car at price:', output)
        put_markdown(
            '**We can put some taken information here from the user in the form of table. Thanks..!!**'
        )
Example #19
0
def customize_text():
    return input_group('Text Fonts and Size', [
        select(label='Select your font',
               options=FONTS,
               value='Arial',
               name='font'),
        input("Select your text size", value='16', type=NUMBER, name='size')
    ])
Example #20
0
def edit():
    info = input_group('编辑音乐标签', [
        input('标题', name='title', value=edited_info['title']),
        input('专辑', name='album', value=edited_info['album']),
        input('艺术家', name='artist', value=edited_info['artist']),
        file_upload('封面图像', accept='image/*', name='img'),
    ],
                       cancelable=True)
    if info is None:
        return
    if info.get('img'):
        info['img'] = info['img']['content']
    for k, v in info.items():
        if v:
            edited_info[k] = v

    show_music_info(current_tag)
Example #21
0
async def setup_raft(raft_addr, cluster):
    """初始化/连接 Raft 集群

    :param raft_addr: 本节点用于Raft集群通信的地址;为None时表示加入现有集群,本节点地址由本节点第一位用户输入
    :param cluster: 集群节点地址列表;为None时表示加入现有集群,集群节点地址由本节点第一位用户输入
    :return: 本节点Raft集群通信地址
    """
    global raft_server

    mode = 'init'
    if not raft_addr:  # raft_addr 为None时,表示加入Raft集群
        mode = 'join'
        currhost = session.get_info().origin.rsplit(":", 1)[0].split("//",
                                                                     1)[-1]
        data = await input_group("加入Raft集群", [
            input("当前节点的Raft通信端口", name="port"),
            input("当前节点的Host地址",
                  name="host",
                  value=currhost,
                  help_text="其他节点需要可以通过此Host与当前节点通信"),
            input("集群节点地址",
                  name="remote",
                  placeholder='host:ip',
                  help_text="填入集群中任一节点的地址即可")
        ])
        raft_addr = '%s:%s' % (data['host'], data['port'])
        cluster = join_cluster(raft_addr, data['remote'])
        if not cluster:
            put_markdown("### 加入集群失败")
            return

    raft_port = raft_addr.split(":", 1)[-1]
    cfg = SyncObjConf(dynamicMembershipChange=True,
                      fullDumpFile=raft_addr + '.data',
                      onStateChanged=partial(onStateChanged, node=raft_addr),
                      bindAddress="0.0.0.0:%s" % raft_port)
    raft_server = SyncObj(
        raft_addr,
        cluster,
        consumers=[chat_msgs, node_user_cnt, node_webui_addr],
        conf=cfg)
    if mode == 'join':
        send_msg(ADMIN_USER, '节点`%s`加入集群' % raft_addr, instant_output=False)

    return raft_addr
Example #22
0
def display_recommendations(document_scores):
    clear()
    global main_document_scores
    try:
        main_document_scores = document_scores.tolist()
        put_text('' + str(len(main_document_scores)))
    except Exception as ex:
        put_text(ex)

    try:
        clear('BTV')
    except:
        pass
    img = open('Images/DesiSafar Logo.jpg', 'rb').read()
    put_image(img, width='900px')
    put_markdown('# **IR Project - Group Number 4**')
    recommendations = int(input('Enter number of recommendations you want : '))
    #     put_buttons(['Home'], onclick=[choices])
    #     put_buttons(['Check another algorithm'], onclick=[select_recommendation_system])
    ds = document_scores
    recommendations_index = ds.argsort()[-recommendations:][::-1]
    print(recommendations_index)
    cities = dataset2['City']
    desc = dataset2['description']

    displayed_recommendations = []
    displayed_recommendations_index = {}

    put_text('Scores calculated in time : ' + str(total_time))
    for i in range(recommendations_index.shape[0]):
        put_html('<hr>')
        put_html('<hr>')
        pic = 'Images/' + str(cities[recommendations_index[i]]) + '.jpg'
        img = open(pic, 'rb').read()
        put_image(img, width='1500px')
        put_markdown("# *`%s`*" % cities[recommendations_index[i]])
        t = desc[recommendations_index[i]]
        t = t.strip()
        t = t.replace('-', '')
        put_text(t)
        displayed_recommendations.append(cities[recommendations_index[i]])
        displayed_recommendations_index[cities[
            recommendations_index[i]]] = recommendations_index[i]
        print('-------------------------------------------------------')
    try:
        displayed_recommendations.append('Home')
        displayed_recommendations.append('Check another algorithm')
        selected_recommendation = select('Explore :',
                                         displayed_recommendations)
        if (selected_recommendation == 'Home'):
            choices()
        if (selected_recommendation == 'Check another algorithm'):
            select_recommendation_system()
        display_details(
            displayed_recommendations_index[selected_recommendation])
    except Exception as ex:
        put_text(ex)
Example #23
0
def app():

    pages = get_pages()

    text_info = customize_text()

    save_location = input("What is the name of your PDF file?", required=True)
    create_pdf(pages, font='Arial', size=16, save_location=save_location)
    put_text("Congratulations! A PDF file is generated for you.")
Example #24
0
def voting():
    name = input('Enter your name', type="text")
    age = input('Enter your age', type=NUMBER)

    if age >= 18:
        put_text('Check your details..')

        put_table([['NAME', 'AGE'], [name, age]])

        check = checkbox(options=['All details are correct.'])

        if check:
            selction = radio("Select your party", ['Congress', 'BJP', 'AAP'])

            records = {'name': name, 'age': age, 'vote_for': selction}
            coll.insert_one(records)

            put_text('Thanks, Your response has been recorded.')

            keep_voting = radio('Keep Voting', ['Yes', 'No'])

            if keep_voting == 'Yes':
                voting()

            else:
                return style(
                    put_text(
                        'Voting has been ended, We will announce the result soon..'
                    ), 'color:green')

    else:
        style(put_text('You are not eligible for voting..'), 'color:red')

        keep_voting = radio('Keep Voting', ['Yes', 'No'])

        if keep_voting == 'Yes':
            voting()

        else:
            return style(
                put_text(
                    'Voting has been ended, We will announce the result soon..'
                ), 'color:green')
Example #25
0
def predict():
    Year = input("Enter model Year: ", type=NUMBER)
    Year = 2021 - Year
    Present_Price = input("Enter Present Price(in LAKHS): ", type=FLOAT)
    Kms_Driven = input("Enter distance it has travelled(in KMS): ", type=FLOAT)
    Kms_Driven2 = np.log(Kms_Driven)
    Owner = input(
        "Enter number of owners who have previously owned it(0 or 1 or 2 or 3): ",
        type=NUMBER)

    Fuel_type = select('What is the fuel type', ['Petrol', 'Diesel', 'CNG'])
    if (Fuel_type == 'Petrol'):
        Fuel_type = 239

    elif (Fuel_type == 'Diesel'):
        Fuel_type = 60

    else:
        Fuel_type = 2

    Seller_Type = select('Dealer or Individual?', ['Dealer', 'Individual'])
    if Seller_Type == 'Individual':
        Seller_Type = 106
    else:
        Seller_Type = 195

    Transmission = select('Transmission Type', ['Manual Car', 'Automatic Car'])
    if Transmission == 'Manual Car':
        Transmission = 261
    else:
        Transmission = 40

    prediction = model.predict([[
        Present_Price, Kms_Driven2, Fuel_type, Seller_Type, Transmission,
        Owner, Year
    ]])
    output = round(prediction[0], 2)

    if output < 0:
        put_text('Sorry you can not sell this car')

    else:
        put_text('Sell this car at ', output, 'price')
Example #26
0
def main():
    put_markdown('''
        # Salary Prediction Web App (`Using PyWebIO`)
        ''',
                 lstrip=True)

    model_inputs = input_group("Enter the following information", [
        input("Rating of the Job", name='rating', type=FLOAT),
        select("Job Sector",
               name='job_sec',
               options=[(i, i) for i in [
                   'Information Technology', 'Business Services', 'Education',
                   'Finance', 'Government', 'Travel & Tourism', 'Health Care'
               ]]),
        select("Job Role",
               name='job_role',
               options=[('Data Scientist', 'data scientist'),
                        ('Data Engineer', 'data engineer'),
                        ('Analyst', 'analyst'),
                        ('Machine Learning Engineer', 'mle'),
                        ('Director', 'director'), ('Manager', 'manager')]),
        radio("Are you familiar with Python?",
              name='py_choice',
              options=[('Yes', 1), ('No', 0)]),
        radio("Are you familiar with R?",
              name='r_choice',
              options=[('Yes', 1), ('No', 0)]),
        radio("Are you familiar with Tableau?",
              name='t_choice',
              options=[('Yes', 1), ('No', 0)]),
        radio("Are you familiar with Power Bi?",
              name='pi_choice',
              options=[('Yes', 1), ('No', 0)]),
        radio("Are you familiar with Machine Learning?",
              name='ml_choice',
              options=[('Yes', 1), ('No', 0)]),
        radio("Are you familiar with Deep Learning?",
              name='dl_choice',
              options=[('Yes', 1), ('No', 0)]),
    ])

    prediction_df = pd.DataFrame(data=[[
        model_inputs[i] for i in [
            'job_sec', 'job_role', 'py_choice', 'r_choice', 't_choice',
            'pi_choice', 'ml_choice', 'dl_choice', 'rating'
        ]
    ]],
                                 columns=[
                                     'Sector', 'job_sim', 'python_yn', 'R_yn',
                                     'tableau', 'power bi', 'ml', 'dl',
                                     'Rating'
                                 ])

    expectedSalary = prediction(prediction_df)
    put_markdown("### Predicted Salary: {}k Dollars".format(expectedSalary))
Example #27
0
def mathemticaloperation():
    a = input("Enter the firt number:", type=FLOAT)
    b = input("Enter the second number:", type=FLOAT)
    c=0
    operation = radio("Choose one operation", options=['+', '*', '/', '%'])
    operation_name=""
    if operation=="+":
        operation_name="Addition"
        c=a+b
    elif operation=="*":
        operation_name="Multiplication"
        c=a*b
    elif operation=="/":
        operation_name="Division"
        c=a/b
    else:
        operation_name="Modulus"
        c=a%b
        
    put_text('The operation selected is: %s. and the output is: %.1f' % (operation_name, c))
Example #28
0
def main():
    """BMI Calculation

    计算BMI指数的简单应用
    """

    put_markdown("""# BMI指数

    [`BMI指数`](https://baike.baidu.com/item/%E4%BD%93%E8%B4%A8%E6%8C%87%E6%95%B0/1455733)(Body Mass Index,BMI),是用体重千克数除以身高米数的平方得出的数字,是国际上常用的衡量人体胖瘦程度以及是否健康的一个标准。
    
    成年人的BMI值处于以下阶段
    
    | 体形分类 | BMI值范围 |
    | -------- | --------- |
    | 极瘦   | BMI<14.9    |
    | 偏瘦    | 14.9≤BMI<18.4     |
    | 正常    | 18.4≤BMI<22.9     |
    | 过重    |  22.9≤BMI<27.5  |
    | 肥胖    |  27.5≤BMI<40  |
    | 非常肥胖 |     BMI≥40      |
    
    ## BMI指数计算器
    本程序的源代码[链接](https://github.com/wang0618/PyWebIO/blob/dev/demos/bmi.py)
    
    """,
                 strip_indent=4)

    info = input_group('计算BMI:', [
        input("请输入你的身高(cm)", name="height", type=FLOAT),
        input("请输入你的体重(kg)", name="weight", type=FLOAT),
    ])

    BMI = info['weight'] / (info['height'] / 100)**2

    top_status = [(14.9, '极瘦'), (18.4, '偏瘦'), (22.9, '正常'), (27.5, '过重'),
                  (40.0, '肥胖'), (float('inf'), '非常肥胖')]

    for top, status in top_status:
        if BMI <= top:
            put_markdown('你的 BMI 值: `%.1f`,身体状态:`%s`' % (BMI, status))
            break
Example #29
0
def sign_up_page():
    clear()
    img = open('Images/DesiSafar Logo.jpg', 'rb').read()
    put_image(img, width='900px')
    put_markdown('# **Sign UP**')
    #     data = input_group("Basic info", [
    #         input('Input your name', name='name'),
    #         input('Input your age', name='age', type=NUMBER)
    #     ], validate=check_form)
    #     put_markdown("`data = %r`" % data)

    info = input_group("User info", [
        input('Name', name='name', required=True),
        input(
            'Input your age',
            name='age',
            type=NUMBER,
            required=True,
        ),
        input('password', type=PASSWORD, name='password', required=True),
        select('Select your state', [
            'Andaman And Nicobar Islands', 'Andhra Pradesh',
            'Arunanchal Pradesh', 'Assam', 'Bihar', 'Chandigarh',
            'Chattisgarh', 'Dadra And Nagar Haveli', 'Delhi', 'Goa', 'Haryana',
            'Himachal Pradesh', 'Jammu & Kashmir', 'Jharkhand', 'Karnataka',
            'Kerala', 'Lakshadweep Island', 'Madhya Pradesh', 'Maharashtra',
            'Manipur', 'Meghalaya', 'Mizoram', 'Nagaland', 'Odisha',
            'Pondicherry', 'Punjab', 'Rajasthan', 'Sikkim'
            'Tamil Nadu', 'Tripura', 'Uttar Pradesh', 'Uttarakhand',
            'West Bengal', 'Gujarat', 'Telangana', 'Daman & Diu', 'Ladakh'
        ],
               name='state',
               required=True)
    ],
                       validate=check_form)

    #     put_markdown("`info = %r`" % info)

    #     put_text(info['name'],info['age'],info['password'],info['state'])
    insert_details(info)
    pywebio.session.hold()
Example #30
0
def whoAreYou():
    with use_scope('whoAreYou', if_exist='remove'):
        global name
        img = open('eatago_logo.jpg', 'rb').read()
        style(put_image(img, width='300px'), 'display: flex'
              'justify-content: center')
        if name == '':
            name = input("What is your name?",
                         type=TEXT,
                         placeholder='Annie',
                         required=True)
        choose_eat_type(name)