<commit_before># -*- coding: utf-8 -*-

from os import chdir, environ
from os.path import dirname, abspath
from collections import Counter
from datetime import datetime, timedelta
from random import choice, randint
from re import findall
from json import loads
from pytz import utc
from flask import Flask, render_template, make_response, send_from_directory, request, redirect, jsonify, abort
from flask_cache import Cache # Caching
from flask_sslify import SSLify # Ensure HTTPS
from flask_wtf.csrf import CSRFProtect # CSRF
from whitenoise import WhiteNoise # Easy static serve
from requests import Session
from requests.adapters import HTTPAdapter
from requests.exceptions import ConnectionError
from cachecontrol import CacheControl

debug = False

app = Flask(__name__, template_folder='templates')
app.config['SECRET_KEY'] = environ.get("SECRET_KEY", "".join(choice("<KEY>!@#$%^&*(-_=+)") for _ in range(50)))
app.wsgi_app = WhiteNoise(app.wsgi_app, root="static/")

if not debug:
    app.config['REMEMBER_COOKIE_SECURE'] = True
    app.config['SESSION_COOKIE_SECURE'] = True

    cache = Cache(app, config={'CACHE_TYPE': 'redis', 'CACHE_REDIS_URL': environ.get("REDIS_URL")})
    csrf = CSRFProtect(app)
    sslify = SSLify(app)


'''
Required functionality
'''


def timeDate(typeDate, offset):
    time = None

    if (datetime.now(tz=utc) + timedelta(hours=offset)).weekday() == 6:
        time = datetime.now(tz=utc) + timedelta(hours=offset, days=1)

    elif (datetime.now(tz=utc) + timedelta(hours=offset)).weekday() + 1 == 6:
        if (datetime.now(tz=utc) + timedelta(hours=offset)).hour < 15:
            time = datetime.now(tz=utc) + timedelta(hours=offset)

        else:
            time = datetime.now(tz=utc) + timedelta(hours=offset, days=2)

    else:
        if (datetime.now(tz=utc) + timedelta(hours=offset)).hour < 15:
            time = datetime.now(tz=utc) + timedelta(hours=offset)

        else:
            time = datetime.now(tz=utc) + timedelta(hours=offset, days=1)

    if typeDate == 'day':
        return str(time.day)

    elif typeDate == 'month':
        return str(time.month)

    elif typeDate == 'year':
        return str(time.year)


def coloring(mood=None):
    if mood == "Good":
        return "teal"

    elif (mood == "Average") or (mood == "О"):
        return "#FF5722"

    elif (mood == "Bad") or (mood == "Н"):
        return "red"

    elif (mood == "Б") or (mood == "П"):
        return "#01579B"

    else:
        return "#212121"


def kaomoji(mood=None):
    if mood == "Good":
        return "( ˙꒳​˙ )"

    elif mood == "Average":
        return "(--_--)"

    elif mood == "Bad":
        return "(・・ )"

    else:
        return "ヽ(ー_ー )ノ"

'''
Template handling
'''


@app.route("/", methods=['GET'])
def index():
    response = make_response(render_template('index.html'))

    response.headers['X-Content-Type-Options'] = 'nosniff'
    response.headers['X-Frame-Options'] = 'DENY'
    response.headers['X-XSS-Protection'] = '1; mode=block'
    response.headers['Strict-Transport-Security'] = 'max-age=31536000'
    response.set_cookie('Offset', value='', max_age=0, expires=0)
    return response


@app.route("/main", methods=['GET'])
def main():
    if 'AccessToken' in request.cookies:
        s = CacheControl(Session())
        s.mount('http://', HTTPAdapter(max_retries=5))
        s.mount('https://', HTTPAdapter(max_retries=5))

        offline = False

        try:
            access_token = request.cookies.get('AccessToken')
            response = s.get(f"https://api.dnevnik.ru/v1/users/me/context?access_token={access_token}")
            user_data = loads(response.text)

        except ConnectionError:
            offline = True

        if offline:
            user = "<NAME>"

        else:
            user = user_data['firstName']

        if request.cookies.get("AccountType") == 'Student':
            response = make_response(render_template('index_logged_in.html', user=user))

        elif request.cookies.get("AccountType") == 'Parent':
            if offline:
                opts = [{"Профилактические работы": str(randint(0, 2000))}]

            else:
                options = user_data['children']
                opts = []

                for option in options:
                    opts.append({f"{option['firstName']} {option['lastName']}": option['personId']})

            response = make_response(render_template('index_logged_in.html', opts=opts, user=user))

        else:
            response = make_response(render_template('index_logged_in.html'))

    else:
        response = make_response(redirect("/"))

    response.headers['X-Content-Type-Options'] = 'nosniff'
    response.headers['X-Frame-Options'] = 'DENY'
    response.headers['X-XSS-Protection'] = '1; mode=block'
    response.headers['Strict-Transport-Security'] = 'max-age=31536000'
    response.set_cookie('Offset', value='', max_age=0, expires=0)
    return response


@app.route("/stats", methods=['POST'])
def stats():
    if 'AccessToken' in request.cookies:
        s = CacheControl(Session())
        s.mount('http://', HTTPAdapter(max_retries=5))
        s.mount('https://', HTTPAdapter(max_retries=5))

        termPeriod = request.form.get('term', '1')

        try:
            access_token = request.cookies.get('AccessToken')
            response = s.get(f"https://api.dnevnik.ru/v1/users/me/context?access_token={access_token}")
            user_data = loads(response.text)

        except ConnectionError:
            html_out = ""
            html_out += '<h4 class="mdl-cell mdl-cell--12-col">Статистика</h4>'

            html_out += '<div class="section__circle-container mdl-cell mdl-cell--2-col mdl-cell--1-col-phone">'
            html_out += '<i class="material-icons mdl-list__item-avatar mdl-color--primary" style="font-size:32px; padding-top:2.5px; text-align:center;"></i>'
            html_out += '</div>'
            html_out += '<div class="section__text mdl-cell mdl-cell--10-col-desktop mdl-cell--6-col-tablet mdl-cell--3-col-phone">'
            html_out += '<h5>Данные не получены ¯\_(ツ)_/¯</h5>'
            html_out += 'Кажется, Дневник.Ру ушел в оффлайн :> <br>'
            html_out += 'Если вы сумели успешно запросить данные ранее, то сделайте длинное нажатие по кнопке запроса.'
            html_out += '</div>'

            response = make_response(jsonify(html_out))
            response.set_cookie('Offset', value='', max_age=0, expires=0)
            return response

        try:
            if request.cookies.get('AccountType') == 'Student':
                response = s.get(f"https://api.dnevnik.ru/mobile/v2/allMarks?personId={user_data['personId']}&groupId={user_data['groupIds'][0]}&access_token={access_token}")

            elif request.cookies.get('AccountType') == 'Parent':
                childId = request.form.get('child', '')
                for child in user_data['children']:
                    if childId == child['personId']:
                        response = s.get(f"https://api.dnevnik.ru/mobile/v2/allMarks?personId={childId}&groupId={child['groupIds'][0]}&access_token={access_token}")

            marks_data = loads(response.text)["AllMarks"]

            html_out = ""
            html_out += '<h4 class="mdl-cell mdl-cell--12-col">Статистика</h4>'

            for markData in marks_data:
                if termPeriod in markData["Period"]["Text"]:
                    for subjectData in markData["SubjectMarks"]:
                        subjectId = subjectData["SubjectId"]
                        markCollection = []

                        html_out += '<div class="section__circle-container mdl-cell mdl-cell--2-col mdl-cell--1-col-phone">'
                        html_out += '<div style="display:block; height:2px; clear:both;"></div><i class="material-icons mdl-list__item-avatar mdl-color--primary" style="font-size:32px; padding-top:2.5px; text-align:center;">format_list_bulleted</i>'
                        html_out += '</div>'
                        html_out += '<div class="section__text mdl-cell mdl-cell--10-col-desktop mdl-cell--6-col-tablet mdl-cell--3-col-phone">'
                        html_out += '<div style="display:block; height:2px; clear:both;"></div>'
                        html_out += f'<h5 style="font-weight:600">{subjectData["Name"]}</h5>'

                        for mark in subjectData["Marks"]:
                            markCollection.append((mark["Values"][0]["Value"], mark["Values"][0]["Mood"]))

                        markCollectionCounted = (*Counter(sorted(markCollection)).items(),)
                        markSum = 0
                        markTotal = len(markCollection)

                        for markTuple in markCollectionCounted:
                            try:
                                html_out += f'<h8 style="color:{coloring(markTuple[0][1])};">{markTuple[0][0]}: {markTuple[1]}</h8><br>'
                                markSum += int(markTuple[0][0]) * int(markTuple[1])

                            except (KeyError, IndexError):
                                pass

                        html_out += f'<h8 style="color:{coloring()};">Среднее значение: {markSum / markTotal}</h8><br>'

                        try:
                            html_out += f'<h8 style="color:{coloring(subjectData["FinalMark"]["Values"][0]["Mood"])};">Итоговое значение: {subjectData["FinalMark"]["Values"][0]["Value"]}</h8><br>'

                        except (KeyError, IndexError, TypeError):
                            pass

                        html_out += '<div style="display:block; height:5px; clear:both;"></div>'
                        html_out += '</div>'

            response = make_response(jsonify(html_out))
            response.set_cookie('Offset', value='', max_age=0, expires=0)
            return response

        except ConnectionError:
            html_out = ""
            html_out += '<h4 class="mdl-cell mdl-cell--12-col">Статистика</h4>'

            html_out += '<div class="section__circle-container mdl-cell mdl-cell--2-col mdl-cell--1-col-phone">'
            html_out += '<i class="material-icons mdl-list__item-avatar mdl-color--primary" style="font-size:32px; padding-top:2.5px; text-align:center;"></i>'
            html_out += '</div>'
            html_out += '<div class="section__text mdl-cell mdl-cell--10-col-desktop mdl-cell--6-col-tablet mdl-cell--3-col-phone">'
            html_out += '<h5>Данные не получены ¯\_(ツ)_/¯</h5>'
            html_out += 'Кажется, Дневник.Ру ушел в оффлайн :> <br>'
            html_out += 'Если вы сумели успешно запросить данные ранее, то сделайте длинное нажатие по кнопке запроса.'
            html_out += '</div>'
<commit_msg>ZeroDivision<commit_after># -*- coding: utf-8 -*-

from os import chdir, environ
from os.path import dirname, abspath
from collections import Counter
from datetime import datetime, timedelta
from random import choice, randint
from re import findall
from json import loads
from pytz import utc
from flask import Flask, render_template, make_response, send_from_directory, request, redirect, jsonify, abort
from flask_cache import Cache # Caching
from flask_sslify import SSLify # Ensure HTTPS
from flask_wtf.csrf import CSRFProtect # CSRF
from whitenoise import WhiteNoise # Easy static serve
from requests import Session
from requests.adapters import HTTPAdapter
from requests.exceptions import ConnectionError
from cachecontrol import CacheControl

debug = False

app = Flask(__name__, template_folder='templates')
app.config['SECRET_KEY'] = environ.get("SECRET_KEY", "".join(choice("<KEY>_=+)") for _ in range(50)))
app.wsgi_app = WhiteNoise(app.wsgi_app, root="static/")

if not debug:
    app.config['REMEMBER_COOKIE_SECURE'] = True
    app.config['SESSION_COOKIE_SECURE'] = True

    cache = Cache(app, config={'CACHE_TYPE': 'redis', 'CACHE_REDIS_URL': environ.get("REDIS_URL")})
    csrf = CSRFProtect(app)
    sslify = SSLify(app)


'''
Required functionality
'''


def timeDate(typeDate, offset):
    time = None

    if (datetime.now(tz=utc) + timedelta(hours=offset)).weekday() == 6:
        time = datetime.now(tz=utc) + timedelta(hours=offset, days=1)

    elif (datetime.now(tz=utc) + timedelta(hours=offset)).weekday() + 1 == 6:
        if (datetime.now(tz=utc) + timedelta(hours=offset)).hour < 15:
            time = datetime.now(tz=utc) + timedelta(hours=offset)

        else:
            time = datetime.now(tz=utc) + timedelta(hours=offset, days=2)

    else:
        if (datetime.now(tz=utc) + timedelta(hours=offset)).hour < 15:
            time = datetime.now(tz=utc) + timedelta(hours=offset)

        else:
            time = datetime.now(tz=utc) + timedelta(hours=offset, days=1)

    if typeDate == 'day':
        return str(time.day)

    elif typeDate == 'month':
        return str(time.month)

    elif typeDate == 'year':
        return str(time.year)


def coloring(mood=None):
    if mood == "Good":
        return "teal"

    elif (mood == "Average") or (mood == "О"):
        return "#FF5722"

    elif (mood == "Bad") or (mood == "Н"):
        return "red"

    elif (mood == "Б") or (mood == "П"):
        return "#01579B"

    else:
        return "#212121"


def kaomoji(mood=None):
    if mood == "Good":
        return "( ˙꒳​˙ )"

    elif mood == "Average":
        return "(--_--)"

    elif mood == "Bad":
        return "(・・ )"

    else:
        return "ヽ(ー_ー )ノ"

'''
Template handling
'''


@app.route("/", methods=['GET'])
def index():
    response = make_response(render_template('index.html'))

    response.headers['X-Content-Type-Options'] = 'nosniff'
    response.headers['X-Frame-Options'] = 'DENY'
    response.headers['X-XSS-Protection'] = '1; mode=block'
    response.headers['Strict-Transport-Security'] = 'max-age=31536000'
    response.set_cookie('Offset', value='', max_age=0, expires=0)
    return response


@app.route("/main", methods=['GET'])
def main():
    if 'AccessToken' in request.cookies:
        s = CacheControl(Session())
        s.mount('http://', HTTPAdapter(max_retries=5))
        s.mount('https://', HTTPAdapter(max_retries=5))

        offline = False

        try:
            access_token = request.cookies.get('AccessToken')
            response = s.get(f"https://api.dnevnik.ru/v1/users/me/context?access_token={access_token}")
            user_data = loads(response.text)

        except ConnectionError:
            offline = True

        if offline:
            user = "<NAME>"

        else:
            user = user_data['firstName']

        if request.cookies.get("AccountType") == 'Student':
            response = make_response(render_template('index_logged_in.html', user=user))

        elif request.cookies.get("AccountType") == 'Parent':
            if offline:
                opts = [{"Профилактические работы": str(randint(0, 2000))}]

            else:
                options = user_data['children']
                opts = []

                for option in options:
                    opts.append({f"{option['firstName']} {option['lastName']}": option['personId']})

            response = make_response(render_template('index_logged_in.html', opts=opts, user=user))

        else:
            response = make_response(render_template('index_logged_in.html'))

    else:
        response = make_response(redirect("/"))

    response.headers['X-Content-Type-Options'] = 'nosniff'
    response.headers['X-Frame-Options'] = 'DENY'
    response.headers['X-XSS-Protection'] = '1; mode=block'
    response.headers['Strict-Transport-Security'] = 'max-age=31536000'
    response.set_cookie('Offset', value='', max_age=0, expires=0)
    return response


@app.route("/stats", methods=['POST'])
def stats():
    if 'AccessToken' in request.cookies:
        s = CacheControl(Session())
        s.mount('http://', HTTPAdapter(max_retries=5))
        s.mount('https://', HTTPAdapter(max_retries=5))

        termPeriod = request.form.get('term', '1')

        try:
            access_token = request.cookies.get('AccessToken')
            response = s.get(f"https://api.dnevnik.ru/v1/users/me/context?access_token={access_token}")
            user_data = loads(response.text)

        except ConnectionError:
            html_out = ""
            html_out += '<h4 class="mdl-cell mdl-cell--12-col">Статистика</h4>'

            html_out += '<div class="section__circle-container mdl-cell mdl-cell--2-col mdl-cell--1-col-phone">'
            html_out += '<i class="material-icons mdl-list__item-avatar mdl-color--primary" style="font-size:32px; padding-top:2.5px; text-align:center;"></i>'
            html_out += '</div>'
            html_out += '<div class="section__text mdl-cell mdl-cell--10-col-desktop mdl-cell--6-col-tablet mdl-cell--3-col-phone">'
            html_out += '<h5>Данные не получены ¯\_(ツ)_/¯</h5>'
            html_out += 'Кажется, Дневник.Ру ушел в оффлайн :> <br>'
            html_out += 'Если вы сумели успешно запросить данные ранее, то сделайте длинное нажатие по кнопке запроса.'
            html_out += '</div>'

            response = make_response(jsonify(html_out))
            response.set_cookie('Offset', value='', max_age=0, expires=0)
            return response

        try:
            if request.cookies.get('AccountType') == 'Student':
                response = s.get(f"https://api.dnevnik.ru/mobile/v2/allMarks?personId={user_data['personId']}&groupId={user_data['groupIds'][0]}&access_token={access_token}")

            elif request.cookies.get('AccountType') == 'Parent':
                childId = request.form.get('child', '')
                for child in user_data['children']:
                    if childId == child['personId']:
                        response = s.get(f"https://api.dnevnik.ru/mobile/v2/allMarks?personId={childId}&groupId={child['groupIds'][0]}&access_token={access_token}")

            marks_data = loads(response.text)["AllMarks"]

            html_out = ""
            html_out += '<h4 class="mdl-cell mdl-cell--12-col">Статистика</h4>'

            for markData in marks_data:
                if termPeriod in markData["Period"]["Text"]:
                    for subjectData in markData["SubjectMarks"]:
                        subjectId = subjectData["SubjectId"]
                        markCollection = []

                        html_out += '<div class="section__circle-container mdl-cell mdl-cell--2-col mdl-cell--1-col-phone">'
                        html_out += '<div style="display:block; height:2px; clear:both;"></div><i class="material-icons mdl-list__item-avatar mdl-color--primary" style="font-size:32px; padding-top:2.5px; text-align:center;">format_list_bulleted</i>'
                        html_out += '</div>'
                        html_out += '<div class="section__text mdl-cell mdl-cell--10-col-desktop mdl-cell--6-col-tablet mdl-cell--3-col-phone">'
                        html_out += '<div style="display:block; height:2px; clear:both;"></div>'
                        html_out += f'<h5 style="font-weight:600">{subjectData["Name"]}</h5>'

                        for mark in subjectData["Marks"]:
                            markCollection.append((mark["Values"][0]["Value"], mark["Values"][0]["Mood"]))

                        markCollectionCounted = (*Counter(sorted(markCollection)).items(),)
                        markSum = 0
                        markTotal = len(markCollection)

                        for markTuple in markCollectionCounted:
                            try:
                                html_out += f'<h8 style="color:{coloring(markTuple[0][1])};">{markTuple[0][0]}: {markTuple[1]}</h8><br>'
                                markSum += int(markTuple[0][0]) * int(markTuple[1])

                            except (KeyError, IndexError):
                                pass

                        try:
                            html_out += f'<h8 style="color:{coloring()};">Среднее значение: {markSum / markTotal}</h8><br>'

                        except ZeroDivisionError:
                            html_out += f'<h8 style="color:{coloring()};">Среднее значение: n/a</h8><br>'

                        try:
                            html_out += f'<h8 style="color:{coloring(subjectData["FinalMark"]["Values"][0]["Mood"])};">Итоговое значение: {subjectData["FinalMark"]["Values"][0]["Value"]}</h8><br>'

                        except (KeyError, IndexError, TypeError):
                            pass

                        html_out += '<div style="display:block; height:5px; clear:both;"></div>'
                        html_out += '</div>'

            response = make_response(jsonify(html_out))
            response.set_cookie('Offset', value='', max_age=0, expires=0)
            return response

        except ConnectionError:
            html_out = ""
            html_out += '<h4 class="mdl-cell mdl-cell--12-col">Статистика</h4>'

            html_out += '<div class="section__circle-container mdl-cell mdl-cell--2-col mdl-cell--1-col-phone">'
            html_out += '<i class="material-icons mdl-list__item-avatar mdl-color--primary" style="font-size:32px; padding-top:2.5px; text-align:center;"></i>'
            html_out += '</div>'
            html_out += '<div class="section__text mdl-cell mdl-cell--10-col-desktop mdl-cell--6-col-tablet mdl-cell--3-col-phone">'
            html_out += '<h5>Данные не получены ¯\_(ツ)_/¯</h5>'
            html_out += 'Кажется, Дневник.Ру ушел в оффлайн :> <br>'
            html_out += 'Если вы сумели успешно запросить данные ранее, то сделайте длинное нажатие по кнопке запроса.'
            html_out += '</div>'

{'fraction_non_alphanumeric': 0.15320604687716702, 'fraction_numerical': 0.013314224954925801, 'mean_word_length': 2.46112, 'pattern_counts': {'":': 12, '<': 108, '<?xml version=': 0, '>': 108, 'https://': 12, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2693947', 'n_tokens_mistral': 7031, 'n_tokens_neox': 6763, 'n_words': 1266}