Exemple #1
0
def ParseMarkup(content, page, noteURL):
	res = Markup(content)
	# try to find tags
	p = re.compile('( (@[0-9a-zA-Z]+))')
	for tag in p.findall(res):
		tmpTag = Tag.select().where(Tag.name == tag[1])
		if tmpTag.count() > 0:
			res = res.replace(tag[0], ' ' + Tag.get(Tag.name == tag[1]).html())
	# try to find URL
	p = re.compile('[a-z]+://(?:[^[ \(\)]]*(?:\([^ ]*?\))*)+')
	for link in p.findall(res):
		res = res.replace(link, Markup('<a href="') + link + Markup('", target="_blank">') + link + Markup('</a>'))
	# try to find zim-style links (enclosed in [[ ]])
	p = re.compile('(\[\[ *([^\]]*) *\]\])')
	for link in p.findall(content):
		url =  link[1].replace(':', '/') + '.html'
		if not url.startswith('/'):
			localPath = ''
			for fold in page.path.split(':')[0:-1]:
				localPath += fold + '/'
			url = '/' + localPath + url
		url = noteURL + url
		res = res.replace(link[0], Markup('<a href="') + url + Markup('", target="_blank">') + link[1] + Markup('</a>'))
	# try to find images (enclosed in {{ }})
	p = re.compile('({{(.+?\.png).*?}})')
	for img in p.findall(content):
		url = noteURL + '/' + page.path.replace(':', '/') + '/' + img[1].strip('./')
		res = res.replace(img[0], Markup('<img src="') + url + Markup('">'))
	# try to find text that needs coloring
	p = re.compile('^comment: \[[0-9]+[-/][0-9]+[-/][0-9]+\]>')
	for comHeader in p.findall(res):
		res = res.replace(comHeader, Markup('<span class="comheader">') + comHeader + Markup('</span>'))
	return unicode(res)
def read_data(story_id=None):
    """Read the data.csv file and convert it to list.

    If 'story_id' is None, give back the whole list.
    Else read only the row with the given ID.

    Convert all escaped newlines to display it properly in the table or in a textarea.
    """
    with open("app/data.csv") as f:
        data = []
        for line in f.read().split("\n"):
            if line != "":
                data_line = []
                # Data for listing the whole table
                if not story_id:
                    for field in line.split(';'):
                        if "\\n" in field:
                            field = Markup(field.replace("\\n", "<br>"))
                        data_line.append(field)
                    data.append(data_line)
                # Data for editing the given row in the table
                else:
                    if line[0] == str(story_id):
                        for field in line.split(';'):
                            if "\\n" in field:
                                field = Markup(field.replace("\\n", "\r\n"))
                            data_line.append(field)
                        data = data_line
    return data
Exemple #3
0
def get_home_data():
    data_nl = render_template('home_content_nl.html')
    data_nl = Markup(data_nl.replace('\n', ''))
    data_en = render_template('home_content_en.html')
    data_en = Markup(data_en.replace('\n', ''))

    home_directory = os.path.join(current_app.config['file-storage'], 'home')
    return jsonify({
        "nl": data_nl,
        "en": data_en,
        "documents": os.listdir(home_directory)
    })
Exemple #4
0
def match_rcon(matchid):
    match = Match.query.get_or_404(matchid)

    command = request.values.get('command')
    server = GameServer.query.get_or_404(match.server_id)
    owns_server = util.is_server_owner(g.user, server)
    is_sadmin = g.user.super_admin
    # Check to see if user owns server.
    if not owns_server:
        if not is_sadmin:
            raise BadRequestError('You are not the server owner.')

    if command:
        try:
            rcon_response = server.send_rcon_command(command,
                                                     raise_errors=True)
            if rcon_response:
                rcon_response = Markup(rcon_response.replace('\n', '<br>'))
            else:
                rcon_response = 'No output'
            flash(rcon_response)
            # Store the command.
            match_audit.create(g.user.id, matchid, datetime.now(), command)
            db.session.commit()
        except util.RconError as e:
            print(e)
            flash('Failed to send command: ' + str(e))

    return redirect('/match/{}'.format(matchid))
Exemple #5
0
def order_details(id, todo):
    try:
        order = system.getNextOrder(None, id)
    except (SearchError, ValueError) as er:
        return render_template('errors.html', msg=str(er))
    
    # order.updateOrder('Pending')
    msg = str(order)
    msg = Markup(msg.replace('\n', '<br/>'))
    status=order.orderStatus
    
    if request.method == 'POST':
        # if user would like to refresh order status
        if 'refresh' in request.form:
            return redirect(url_for('order_details',id=id,todo=todo))
        
        # if user would like to send receipt to eamil
        elif 'sendEmail' in request.form and 'email' in request.form and request.form['email'] != "":
            return render_template('order_details.html', msg=msg, status=status, email=request.form['email'], send=True)
        
        # if the order is not submitted, and user want to continue ordering
        elif 'continueOrder' in request.form:
            return redirect(url_for('menu', id=id))
        
        # simulate pick up action
        elif 'pickup' in request.form:
            order.updateOrder("Picked Up")
            return redirect(url_for('order_details',id=id,todo=todo))

    return render_template('order_details.html', msg=msg, status=status, todo=todo)
Exemple #6
0
def slugify(value, substitutions=()):
    '''
    Normalizes string, converts to lowercase, removes non-alpha characters,
    and converts spaces to hyphens.

    Took from Django sources.
    '''
    # TODO Maybe steal again from current Django 1.5dev
    value = Markup(value).striptags()
    # value must be unicode per se
    import unicodedata
    from unidecode import unidecode
    # unidecode returns str in Py2 and 3, so in Py2 we have to make
    # it unicode again
    value = unidecode(value)
    if isinstance(value, six.binary_type):
        value = value.decode('ascii')
    # still unicode
    value = unicodedata.normalize('NFKD', value).lower()
    for src, dst in substitutions:
        value = value.replace(src.lower(), dst.lower())
    value = re.sub('[^\w\s-]', '', value).strip()
    value = re.sub('[-\s]+', '-', value)
    # we want only ASCII chars
    value = value.encode('ascii', 'ignore')
    # but Pelican should generally use only unicode
    return value.decode('ascii')
Exemple #7
0
def home():
    results = '';
    if request.method == 'POST':
        if request.form['action'] == 'start':
            # run the start command
            results = "Starting the server...<br /><br />"
            results += check_output([app.script, "start"])
            log_action(session['uid'], 4)
            results = Markup(results.replace('\n', '<br />'))
        elif request.form['action'] == 'stop':
            # run the stop action
            results = "Stoping the server...<br /><br />"
            results += check_output([app.script, "stop"])
            log_action(session['uid'], 6)
            results = Markup(results.replace('\n', '<br />'))
        elif request.form['action'] == 'restart':
            # run the restart action
            results = "Restarting the server...<br /><br />"
            results += check_output([app.script, "restart"])
            log_action(session['uid'], 5)
            results = Markup(results.replace('\n', '<br />'))
        elif request.form['action'] == 'update':
            # run the update action
            results = "Updating the server...<br /><br />"
            results += check_output([app.script, "update"])
            log_action(session['uid'], 7)
            results = Markup(results.replace('\n', '<br />'))
        else:
            # invalid action!
            results = "INVALID ACTION!"

    g.db = connect_db()
    cur = g.db.execute('SELECT time, (SELECT users.login FROM users WHERE users.id = loggedactions.user), actions.action FROM loggedactions LEFT JOIN actions ON loggedactions.action = actions.id ORDER BY time DESC LIMIT 10;')
    actions = [dict(time=row[0], user=row[1], action=row[2]) for row in cur.fetchall()]
    g.db.close()
    return render_template('index.html', actions=actions, results=results, acp=session['priv'], username=session['username'])
Exemple #8
0
def upload():
    target = os.path.join(app.config['UPLOAD_FOLDER'], 'uploads')
    pid = request.form['pid']

    if not os.path.isdir(target):
        os.mkdir(target)

    # check if the post request has the file part
    if 'file' not in request.files:
        return redirect(request.url)

    file = request.files['file']

    # if user does not select file, browser also
    # submit a empty part without filename
    if file.filename == '':
        return redirect(request.url)

    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        destination = "/".join([target, filename])
        file.save(destination)

        # Get the result
        ans, testC = testFile(pid, destination)

        if ans == 'Accepted':
            return render_template("answer.html", answer=ans)

        for i in testC:
            testC = i

        if ans == 'Memory error':
            testC = testC.replace('\n', '<br/>')
            testC = Markup('<p>' + testC + '</p>')
            return render_template("answer.html", answer=ans, testCases=testC)

        if testC:
            testC = testC.replace('\n', '')
            testC = Markup(testC)

        return render_template("answer.html", answer = ans, testCases = testC)

    return redirect(url_for('index'))
Exemple #9
0
 def t1():
     value = text
     multiline = "\n" in value
     if multiline:
         value = value.replace("|"," ||").replace("\n"," |n")
     if "&" in value or "<" in value:
         value = Markup(Markup(value).unescape()).striptags()
     # soporte multilinea
     if multiline:
         values = value.split(" |n")
         # strip de la lista
         start = 0
         end = len(values)-1
         while values and start<end and not values[start].strip(): start+=1
         while values and end>start and not values[end].strip(): end-=1
         if values and start<end:
             value = "\n".join(value.replace(" ||", "|") for value in values[start:end+1])
         else:
             value = ""
     return value
Exemple #10
0
def match_rcon(matchid):
    match = Match.query.get_or_404(matchid)
    admintools_check(g.user, match)

    command = request.values.get('command')
    server = GameServer.query.get_or_404(match.server_id)

    if command:
        try:
            rcon_response = server.send_rcon_command(
                command, raise_errors=True)
            if rcon_response:
                rcon_response = Markup(rcon_response.replace('\n', '<br>'))
            else:
                rcon_response = 'No output'
            flash(rcon_response)
        except util.RconError as e:
            print(e)
            flash('Failed to send command: ' + str(e))

    return redirect('/match/{}'.format(matchid))
Exemple #11
0
def match_rcon(matchid):
    match = Match.query.get_or_404(matchid)
    admintools_check(g.user, match)

    command = request.values.get('command')
    server = GameServer.query.get_or_404(match.server_id)

    if command:
        try:
            rcon_response = server.send_rcon_command(
                command, raise_errors=True)
            if rcon_response:
                rcon_response = Markup(rcon_response.replace('\n', '<br>'))
            else:
                rcon_response = 'No output'
            flash(rcon_response)
        except util.RconError as e:
            print(e)
            flash('Failed to send command: ' + str(e))

    return redirect('/match/{}'.format(matchid))
Exemple #12
0
def choose_filename(f,text=False):
    '''
    Elige el archivo correcto
    '''
    text=slugify(text) if text else text
    srcs = f['file']['src']
    fns = f['file']['fn']
    chosen = None
    max_count = -1
    has_text = 0
    try:
        for hexuri,src in srcs.items():
            if 'bl' in src and src['bl']!=0:
                continue

            this_has_text=0
            for crc,srcfn in src['fn'].items():
                #si no tiene nombre no se tiene en cuenta
                m = srcfn['m'] if len(fns[crc]['n'])>0 else 0
                if 'c' in fns[crc]:
                    fns[crc]['c']+=m
                else:
                    fns[crc]['c']=m

                if text:
                    slugified_fn = slugify(fns[crc]['n']).strip()
                    if len(slugified_fn)>0:
                        #TODO hace lo mismo que para poner el nombre en negrita y sacar el mejor texto aunque no tenga tildes o no venga unido por espacios
                        if slugified_fn.upper().find(text.upper())!=-1:
                            this_has_text = 2000
                        else:
                            matches = 0
                            for word in [re.escape(w) for w in text.split(" ")]:
                                matches += len(re.findall(r"/((?:\b|_)%s(?:\b|_))/i"%word, slugified_fn))

                            if matches>0:
                                this_has_text = 1000 + matches

                f['file']['fn'][crc]['tht'] = this_has_text
                better = fns[crc]['c']>max_count
                if this_has_text > has_text or (better and this_has_text==has_text):
                    has_text = this_has_text
                    chosen = crc
                    max_count = fns[crc]['c']

    except KeyError as e: #para los sources que tienen nombre pero no estan en el archivo
        logging.exception(e)

    f['view']['url'] = mid2url(hex2mid(f['file']['_id']))
    if chosen:
        filename = fns[chosen]['n']
        ext = fns[chosen]['x']
    else: #uses filename from src
        srcurl = ""
        for hexuri,src in srcs.items():
            if src['url'].find("/")!=-1:
                srcurl = src['url']

        if srcurl=="":
            return

        srcurl = srcurl[srcurl.rfind("/")+1:]
        ext = srcurl[srcurl.rfind(".")+1:]
        filename = srcurl[0:srcurl.rfind(".")]

    filename = Markup(filename).striptags()[:512]
    if not ext in EXTENSIONS:
        filename += ext
        ext=""
        nfilename = filename
    else:
        #clean filename
        end = filename.upper().rfind("."+ext.upper())
        if end == -1:
            nfilename = filename
        else:
            nfilename = filename.strip()[0:end]

    f['view']['fn'] = filename #TODO para los tipo archive buscar el tipo real en el nombre (mp3,avi...)
    f['view']['fnx'] = ext
    f['view']['efn'] = filename.replace(" ", "%20")

    #poner bonito nombre del archivo
    if nfilename.find(" ")==-1:
        nfilename = nfilename.replace(".", " ")

    f['view']['nfn'] = nfilename.replace("_", " ")

    #nombre del archivo escapado para generar las url de descarga
    f['view']['qfn'] = u(filename).encode("UTF-8")

    #nombre del archivo con las palabras que coinciden con la busqueda resaltadas
    if not text:# or not has_text:
        f['view']['fnh'] = f['view']['fnhs'] = filename
    else:
        f['view']['fnh'], f['view']['fnhs'] = highlight(text,filename,True)

    return has_text>0
Exemple #13
0
def results(page, url):
    results = {}
    url = url
    print "URL in MODEL"
    print url
    extract = page.extract()
    links_list = page.get_links()
    outline = page.get_outline()
    stats = page.get_stats()
    headings = stats['Number of Headings']
    headings = num2words(headings)
    links = stats['Number of Links']
    links = num2words(links)

    # Format body for web. Replace new lines with spaces, add markup for styling
    body = Markup(page.get_body())
    body = body.replace('\n', (' '))
    body = body.replace('{{', Markup('<span class="highlight">'))
    body = body.replace('}}', Markup('</span>'))
    body = body.replace('^', Markup('<br><span class="highlight"><br />'))
    body = body.replace('*', Markup('</span><br>'))
    
    # Encode outline and lists as json objects
    store_outline = json.dumps(outline)
    store_links = json.dumps(links_list)
    store_stats = json.dumps(stats)
    
    # Create and store report
    r = Report(url=url, text_output=body, links=store_links, outline=store_outline, stats=store_stats)
    db.session.add(r)
    db.session.commit()
    # Run checks
    checks = page.checks()
    page_report = {}

    # If error found, add to report_message database
    if checks['Header'] == 'header':
        message = add_message(report=r, key='Header', value='header', error='header', code_snippet=None)
        page_report['Header Element Present'] = message
    
    if checks['Title'] == 'titleoveruse':
        message = add_message(report=r, key='Title', value='titleoveruse', error='titleoveruse', code_snippet=None)
        page_report['Title'] = message

    if checks['Title'] == 'titlenone':
        message = add_message(report=r, key='Title', value='titlenone', error='titlenone', code_snippet=None)
        page_report['Title'] = message

    if checks['Redundant Links']:
        redundant_links = json.dumps(page.redundant_link())
        message = add_message(report=r, key='Redundant Links', value=redundant_links, error='redundantlinks', code_snippet=redundant_links)
        page_report['Redundant Links'] = [message, json.loads(redundant_links)]

    if checks['Empty Links']['Total'] > 0:
        empty_links = json.dumps(page.empty_links())
        message = add_message(report=r, key='Empty Links', value=empty_links, error='emptylink', code_snippet=empty_links)
        page_report['Empty Links'] = message

    if checks['Alt Tags'] == 'alttags':
        message = add_message(report=r, key='Alt Tags', value='alttags', error='alttags', code_snippet=None)
        page_report['Missing Alternative Text'] = message

    if checks['Headings'] == 'missingh1':
        message = add_message(report=r, key='Headings', value='missingh1', error='missingh1', code_snippet=None)
        page_report['Headings'] = message

    if checks['Headings'] == 'noheadings':
        message = add_message(report=r, key='Headings', value='noheadings', error='noheadings', code_snippet=None)
        page_report['Headings'] = message

    if checks['Headings'] == 'headingsskip':
        message = add_message(report=r, key='Headings', value='headingsskip', error='headingsskip', code_snippet=None)
        page_report['Headings Steps'] = message

    if checks['Tables'] == 'layouttables':
        message = add_message(report=r, key='Tables', value='layouttables', error='layouttables', code_snippet=None)
        page_report['Layout Tables'] = message

    if checks['Language'] == 'language':
        message = add_message(report=r, key='Language', value='language', error='language', code_snippet=None)
        page_report['Language'] = message

    if checks['No Script'] == 'noscript':
        message = add_message(report=r, key='No Script', value='noscript', error='noscript', code_snippet=None)
        page_report['noscript Element Present'] = message

    if checks['Form - Input Label'] == 'inputlabel':
        message = add_message(report=r, key='Form - Input Label', value='inputlabel', error='inputlabel', code_snippet=None)
        page_report['Missing Input Label'] = message

    if checks['Form - Text Area Label'] == 'textarealabel':
        message = add_message(report=r, key='Form - Text Area Label', value='textarealabel', error='textarealabel', code_snippet=None)
        page_report['Missing Text Area Label'] = message 

    if checks['Form - Select Label'] == 'selectlabel':
        message = add_message(report=r, key='Form - Select Label', value='selectlabel', error='selectlabel', code_snippet=None)
        page_report['Missing Select Label'] = message

    report_id = r.id
    # Add report details to dict
    results['headings'] = headings
    results['links'] = links
    results['body'] = body
    results['outline'] = outline
    results['links_list'] = links_list
    results['page_report'] = page_report
    results['report_id'] = report_id

    return results
Exemple #14
0
def staff():
    # list to store order detail in str
    msgList = []
    error = ''
    orderList = system.order
    filterList = [None]

    if request.method == "POST":
        
        # if staff wants to delte a particular order
        if 'delete' in request.form:
            id = request.form['delete'].split()[2]
            try:
                id = int(id)
            except:
                error = 'No such order'
            else:
                try:
                    system.deleteOrder(id)
                except SearchError as er:
                    error = str(er)

        # change orderStatus to 'Prepare'
        elif 'prepare' in request.form:
            id = request.form['prepare'].split()[2]
            try:
                id = int(id)
            except:
                error = 'No such order'
            else:
                try:
                    order = system.getNextOrder(None,id)
                except SearchError as er:
                    error = str(er)
                else:
                    order.updateOrder('Preparing')
        
        # chagne orderStatus to 'Ready'
        elif 'ready' in request.form:
            id = request.form['ready'].split()[1]
            try:
                id = int(id)
            except:
                error = 'No such order'
            else:
                try:
                    order = system.getNextOrder(None,id)
                except SearchError as er:
                    error = str(er)
                else:
                    order.updateOrder('Ready')

        # if staff wnats to filter order
        if 'filter' in request.form:
            if request.form['filter'] == 'All':
                pass
            else:
                filterList = [request.form['filter']]
                orderList = system.filterOrder(filterList)

    # read python str in Markup
    for elem in orderList:
        msg = str(elem)
        msg = Markup(msg.replace('\n', ' <br/>'))
        msgList.append(msg)

    return render_template('staff.html', msgList = msgList, filter=filterList[0], statusList=system.statusList, error = error)
Exemple #15
0
def configure_data(email):

    # get user name
    username = get_username(email)
    print(username)

    time = datetime.now(timezone(ZONE))
    time = str(time)

    age = request.form.get('age', "")
    gender = request.form.get('gender', "")
    weight = request.form.get('weight', "")
    height = request.form.get('height', "")
    waist = request.form.get('waist', "")
    hip = request.form.get('hip', "")
    heart = request.form.get('heart', "")
    # optional choices
    blood = request.form.get('blood', "")
    step = request.form.get('steps', "")
    sleep = request.form.get('sleep', "")
    water = request.form.get('water', "")
    vegetable = request.form.get('vegetable', "")

    if age == '' and gender == '' and weight == '' and height == '' and waist == '' and hip == '' and heart == '':
        return "Error: You must fill all required fields !"

    # calculate BMI
    bmi = float(weight) / ((float(height) / 100)**2)  # height is in cm
    # calculate WHR
    whr = float(waist) / float(hip)
    # calculate calories
    if step != '':
        calorie = float(6.54e-4) * float(step) * float(weight)
    else:
        calorie = 0
    if blood == '':
        blood = 0
    if sleep == '':
        sleep = 0
    if water == '':
        water = 0
    if vegetable == '':
        vegetable = 0

    user_data = [
        age, gender, weight, height, waist, hip, heart, "optional input:",
        blood, step, sleep, water, vegetable
    ]

    # insert the provided user data into our database
    userdata_putItem(time, email, username, Decimal(age), gender,
                     Decimal(weight), Decimal(height), Decimal(waist),
                     Decimal(hip), Decimal(heart), Decimal(blood),
                     Decimal(step), Decimal(sleep), Decimal(water),
                     Decimal(vegetable), round(Decimal(bmi), 1),
                     round(Decimal(whr), 2), round(Decimal(calorie), 0))

    output = ''

    if bmi < 18.5:
        output = "BMI result: Underweight \n \u2022 Risk: increase the risk for osteoporosis, anemia, hair loss and fertility problems.\n \u2022 To eat more often to consume enough calories to gain weight(six small meals spread throughout the day instead of trying to pack more into three meals)\n \u2022 Consume nutrient-dense foods, such as lean protein, whole grains, legumes, low-fat dairy products, nuts and seeds and fruits and vegetables.\n \u2022 More strength training, approximately two to three days per week. \n\n\n"
    elif bmi < 25.0:
        output = "BMI result: Normal \n \u2022 Keep current habits, try to avoid foods that are high in saturated fat, cholesterol, sugars and sodium, as these can increase your risks for certain health conditions. \n\n\n"
    elif bmi < 29.9:
        output = "BMI result: Overweight \n \u2022 Risk: Increase the risk of many health problems, including diabetes, heart disease, and certain cancers.\n \u2022 To eating fewer and meals should be low carb, which limits carbs to 20–50 carbs per day. Each meal should have protein, healthy fats, veggies, and a small portion of complex carbohydrates, such as whole grains.\n \u2022 losing 1–2 pounds per week, try going to the gym three to four times a week to workout, including lifting weights, and some cardio workouts such as walking, jogging, running, cycling, or swimming.\n \u2022 Set weight goals and find someone could support you and encourage you. \n\n\n"
    else:
        output = "BMI result: Obesity \n \u2022 Risk:To causes a large number of health conditions, including heart disease, stroke, diabetes, high blood pressure, unhealthy cholesterol, asthma, sleep apnea, gallstones, kidney stones, infertility, and as many as 11 types of cancers, including leukemia, breast, and colon cancer. \n \u2022 Consume less fat, Eating more vegetables and fruits help keep calories reasonable and reduce the risk of overeating. \n \u2022 Regular weight training, find a professional trainer to design training plans, including strength training, and some cardio workouts such as walking, jogging, running, cycling, or swimming. \n \u2022 Try to reduce daily stress, stress may trigger a brain response that changes eating patterns and leads to cravings for high-calorie foods. \n \u2022 Set weight goals and find someone could support you and encourage you. \n \u2022 Weight-loss medications, a doctor will sometimes prescribe medication, such as orlistat (Xenical) to help a person lose weight. \n\n\n"

    if int(blood) != 0:
        if int(blood) >= 140:
            output = output + "High Blood Pressure: \n \u2022 Reduce sodium in your diet, put less salt during cooking. \n \u2022 Quit smoking. \n \u2022 Limit the amount of alcohol you drink. \n \u2022 Monitor your blood pressure at home and see your doctor regularly.\n\n"

    if int(sleep) != 0:
        sleepless = "Lack of Sleeping: \n \u2022 Short-term effects on lacking of sleep: brain will fog, making it difficult to concentrate and make decisions.\n \u2022 Long-term effects on lacking of sleep: closely associated with hypertension, heart attacks and strokes, obesity, diabetes, depression and anxiety, decreased brain function, memory loss, weakened immune system, lower fertility rates and psychiatric disorders.\n \u2022 Daily sunlight or artificial bright light can improve sleep quality and duration\n \u2022 Don’t consume caffeine late in the day. \n \u2022 Reduce irregular or long daytime naps. \n \u2022 Try to sleep and wake at consistent times.\n \u2022 Relax and clear your mind in the evening.\n \u2022 Get a comfortable bed, mattress, and pillow.\n \u2022 Putting any smart mobile devices away.\n\n"
        oversleep = "Oversleeping: \n \u2022 Effects on oversleeping: increase the risk for diabetes; more likely to become obese; cause head pain; suffer from back pain; increase the risk of heart disease.\n \u2022 Change your alarm habits and resist hitting the snooze button.\n \u2022 Avoid sleeping in on weekends, even when you really want to.\n \u2022 Dodge the urge to take a nap  Improve your morning routine & day-to-day habits.\n \u2022 Avoid blue light before bed.\n \u2022 Create an ideal sleeping environment.\n\n"
        if int(age) <= 17 and int(sleep) < 8:
            output = output + sleepless
        elif int(age) <= 17 and int(sleep) > 12:
            output = output + oversleep
        elif int(age) <= 64 and int(sleep) < 7:
            output = output + sleepless
        elif int(age) <= 64 and int(sleep) > 11:
            output = output + oversleep
        elif int(age) >= 65 and int(sleep) < 7:
            output = output + sleepless
        elif int(age) >= 65 and int(sleep) > 10:
            output = output + oversleep
        else:
            output = output + "Your sleeping is current in a good condition. \n\n"

    if int(water) != 0:
        if gender == 'Male' and int(water) > 9:
            output = output + '--Drinking too much water: \n \u2022 As you intake more water you can begin to flush water soluble vitamins and minerals.\n\n'
        elif gender == 'Male' and int(water) < 4:
            output = output + '--Should drink more water:\n \u2022 Don’t drinking enough water would lead to some health issues like high blood pressure and kidney stones.\n\n'
        elif gender == 'Female' and int(water) > 7:
            output = output + '--Drinking too much water: \n \u2022 As you intake more water you can begin to flush water soluble vitamins and minerals.\n\n'
        elif gender == 'Female' and int(water) < 3:
            output = output + '--Should drink more water:\n \u2022 Don’t drinking enough water would lead to some health issues like high blood pressure and kidney stones.\n\n'
        else:
            output = output + "--The amount of water you drink is at a good level. Please keep your habits \n\n"

    if int(vegetable) != 0:
        if int(vegetable) < 30:
            output = output + '--Should eat more vegetable: \n \u2022 half of your plate at any given meal—about 30 percent vegetables and 20 percent fruit. \n\n'
        else:
            output = output + '--Your dietary habit is good, and please remember to keep half of your plate at any given meal—about 30 percent vegetables and 20 percent fruit.\n\n'

    mealplan1 = '<h6> Meal Plan for you:</h6> <p>Breakfast — Egg and avocado toast\n   \u2022 2 eggs\n   \u2022 1 slice of Ezekiel toast\n   \u2022 1/2 avocado\n Lunch — Salad with grilled chicken\n   \u2022 2 cups (40 grams) of spinach\n   \u2022 4 ounces (112 grams) of grilled chicken\n   \u2022 1/2 cup (120 grams) of chickpeas\n   \u2022 1/2 cup (25 grams) of shredded carrots\n   \u2022 1 ounce (28 grams) of goat cheese\n   \u2022 Balsamic vinaigrette\n Dinner — Cod with quinoa and broccoli\n   \u2022 5 ounces (140 grams) of baked cod\n   \u2022 1 tablespoon (15 ml) of olive oil\n   \u2022 3/4 cup (138 grams) of quinoa\n   \u2022 2 cups (176 grams) of roasted broccoli </p>'
    mealplan2 = '<h6> Meal Plan for you:</h6> <p>Breakfast — Healthy yogurt bowl\n   \u2022 1 cup (245 grams) of full-fat plain yogurt\n   \u2022 1 cup (123 grams) of raspberries\n   \u2022 2 tablespoons (28 grams) of sliced almonds\n   \u2022 2 tablespoons (28 grams) of chia seeds\n   \u2022 1 tablespoon (14 grams) of unsweetened coconut\n Lunch — Mozzarella wrap\n   \u2022 2 ounces (46 grams) of fresh mozzarella\n   \u2022 1 cup (140 grams) of sweet red peppers\n   \u2022 2 slices of tomato\n   \u2022 1 tablespoon (15 grams) of pesto\n   \u2022 1 small, whole-grain wrap\n Dinner — Cod with quinoa and broccoli\n   \u2022 1 small sweet potato (60 grams)\n   \u2022 1 teaspoon (5 grams) of butter\n   \u2022 4 ounces (112 grams) of wild-caught salmon\n   \u2022 1 cup (88 grams) of roasted Brussels sprouts</p>'
    mealplan3 = '<h6> Meal Plan for you:</h6> <p>Breakfast — Oatmeal\n   \u2022 1 cup (81 grams) of oatmeal cooked in 1 cup (240 ml) of unsweetened almond milk\n   \u2022 1 cup (62 grams) of sliced apple\n   \u2022 1/2 teaspoon of cinnamon\n   \u2022 2 tablespoons (32 grams) of natural peanut butter\n Lunch — Veggie and hummus wrap\n   \u2022 1 small whole-grain wrap\n   \u2022 2 tablespoons (32 grams) of hummus\n   \u2022 1/2 avocado\n   \u2022 2 slices of tomato\n   \u2022 1 cup (20 grams) of fresh arugula\n   \u2022 1 ounce (28 grams) of muenster cheese\n Dinner — Chili\n   \u2022 3 ounces (84 grams) of ground turkey\n   \u2022 1/2 cup (120 grams) of black beans\n   \u2022 1/2 cup (120 grams) of kidney beans\n   \u2022 1 cup (224 grams) of crushed tomatoes</p>'
    mealplan4 = '<h6> Meal Plan for you:</h6> <p>Breakfast — Peanut butter and banana toast with eggs\n   \u2022 2 fried eggs\n   \u2022 1 slice of Ezekiel toast\n   \u2022 2 tablespoons (32 grams) of natural peanut butter\n   \u2022 1/2 sliced banana\n Lunch — On-the-go sushi\n   \u2022 1 cucumber and avocado sushi roll made with brown rice\n   \u2022 1 vegetable roll with brown rice\n   \u2022 2 pieces of salmon sashimi and a green salad\n Dinner — Black bean burger\n   \u2022 1 cup (240 grams) of black beans\n   \u2022 1 egg\n   \u2022 Chopped onion\n   \u2022 Chopped garlic \n   \u2022 1 tablespoon (14 grams) of breadcrumbs\n   \u2022 2 cups (20 grams) of mixed greens\n   \u2022 1 ounce (28 grams) of feta cheese</p>'
    mealplan5 = '<h6> Meal Plan for you:</h6> <p>Breakfast — Breakfast smoothie\n   \u2022 1 scoop of pea protein powder\n   \u2022 1 cup (151 grams) of frozen blackberries\n   \u2022 1 cup (240 ml) of coconut milk\n   \u2022 1 tablespoon (16 grams) of cashew butter\n   \u2022 1 tablespoon (14 grams) of hemp seeds\n Lunch — Kale salad with grilled chicken\n   \u2022 2 cups (40 grams) of kale\n   \u2022 4 ounces (112 grams) of grilled chicken\n   \u2022 1/2 cup (120 grams) of lentils\n   \u2022 1/2 cup (25 grams) of shredded carrots\n   \u2022 1 cup (139 grams) of cherry tomatoes\n   \u2022 1 ounce (28 grams) of goat cheese\n   \u2022 Balsamic vinaigrette\n Dinner — Shrimp fajitas\n   \u2022 4 ounces (112 grams) of grilled shrimp\n   \u2022 2 cups (278 grams) of onions and peppers sauteed in 1 tablespoon (15 ml) of olive oil\n   \u2022 2 small corn tortillas\n   \u2022 1 tablespoon of full-fat sour cream \n   \u2022 1 ounce (28 grams) of shredded cheese </p>'
    mealplan6 = '<h6> Meal Plan for you:</h6> <p>Breakfast — Oatmeal\n   \u2022 1 cup (81 grams) of oatmeal cooked in 1 cup (240 ml) unsweetened almond milk\n   \u2022 1 cup (123 grams) of blueberries\n   \u2022 1/2 teaspoon of cinnamon\n   \u2022 2 tablespoons (32 grams) of natural almond butter\n Lunch — Tuna salad\n   \u2022 5 ounces (140 grams) of canned tuna\n   \u2022 1 tablespoon (16 grams) of mayo\n   \u2022 Chopped celery\n   \u2022 2 cups (40 grams) of mixed greens\n   \u2022 1/4 sliced avocado\n   \u2022 1/2 cup (31 grams) of sliced green apple\n Dinner — Chicken with veggies\n   \u2022 5 ounces (120 grams) of baked chicken\n   \u2022 1 cup (205 grams) of roasted butternut squash cooked in 1 tablespoon (15 ml) of olive oil\n   \u2022 2 cups (176 grams) roasted broccoli</p>'
    mealplan7 = '<h6> Meal Plan for you:</h6> <p>Breakfast — Omelet\n   \u2022 2 eggs\n   \u2022 1 ounce (28 grams) of cheddar cheese\n   \u2022 1 cup (20 grams) of spinach cooked in 1 tablespoon (15 ml) of coconut oil\n   \u2022 1 cup (205 grams) of sautéed sweet potatoes\n Lunch — On-the-go Chipotle\n   \u2022 1 Chipotle burrito bowl made with romaine lettuce, Barbacoa chicken, brown rice, 1/2 serving of guacamole and fresh salsa\n Dinner — Pasta with pesto and beans\n   \u2022 1 cup (140 grams) of brown-rice pasta or whole-wheat pasta\n   \u2022 1 tablespoon (14 grams) of pesto\n   \u2022 1/4 cup (60 grams) of cannellini beans\n   \u2022 1 cup (20 grams) of spinach\n   \u2022 1 cup (139 grams) of cherry tomatoes\n   \u2022 1 tablespoon (5 grams) of grated parmesan cheese</p>'

    mealPlan = [
        mealplan1, mealplan2, mealplan3, mealplan4, mealplan5, mealplan6,
        mealplan7
    ]
    rand_x = random.randint(0, 6)
    output = output + mealPlan[rand_x]
    output = Markup(output.replace('\n', '<br>'))

    return render_template('message.html', email=email, message=output)
Exemple #16
0
def instruct():
    with open("INSTRUCTIONS.md") as fin:
        content = markdown.markdown(fin.read())
        content = Markup(content.replace("<code>", "<code class='square'>"))
        # Markup to escape html characters
        return render_template("instructions.html", content=content)