<commit_before>#!/usr/bin/python
import time
import flask
import database
import utils
from config import Config
from alarm import Alarm
import smbio
app = flask.Flask(__name__)


# =================================================
# Request Context
# =================================================
@app.before_request
def before_request():
    flask.g.db = database.get_db()
    flask.g.title = Config["title"]


@app.teardown_request
def teardown_request(exception):
    db = getattr(flask.g, 'db', None)
    if db is not None:
        db.close()


# =================================================
# Root & Static
# =================================================
@app.route("/")
def root():
    if utils.needs_user():
        return flask.redirect(flask.url_for('setup'))
    if 'logged_in' in flask.session and flask.session['logged_in']:
        return flask.redirect(flask.url_for('dashboard'))
    return flask.redirect(flask.url_for('login'))


@app.route('/js/<path:path>')
def send_j2(path):
    return flask.send_from_directory('js', path)


@app.route('/css/<path:path>')
def send_css(path):
    return flask.send_from_directory('css', path)


@app.route('/img/<path:path>')
def send_img(path):
    return flask.send_from_directory('img', path)


@app.route('/fonts/<path:path>')
def send_font(path):
    return flask.send_from_directory('fonts', path)


# =================================================
# Users
# =================================================
@app.route('/login', methods=['GET', 'POST'])
def login():
    if utils.needs_user():
        return flask.redirect(flask.url_for('setup'))
    if 'logged_in' in flask.session and flask.session['logged_in']:
        return flask.redirect(flask.url_for('dashboard'))
    error = None
    if flask.request.method == 'POST':
        username = flask.request.form['username']
        user = utils.get_user(username)
        if user:
            if utils.check_user_pass(user, flask.request.form['password']):
                flask.session['logged_in'] = True
                flask.session['username'] = user
                flask.flash('You were logged in')
                return flask.redirect(flask.url_for('dashboard'))
        error = "Invaid username or password"
    return flask.render_template('login.j2', error=error)


@app.route('/logout')
def logout():
    flask.session.pop('logged_in', None)
    flask.flash('You were logged out')
    return flask.redirect(flask.url_for('login'))


@app.route('/users', methods=['GET', 'POST'])
def users():
    if utils.needs_user():
        return flask.redirect(flask.url_for('setup'))
    if ('logged_in' not in flask.session) or (not flask.session['logged_in']):
        return flask.redirect(flask.url_for('login'))

    error = None
    if flask.request.method == 'POST':
        if "delete" in flask.request.form:
            if len(utils.get_users()) > 1:
                user_id = int(flask.request.form['id'])
                utils.delete_user(user_id)
                flask.flash('User Deleted')
            else:
                flask.flash("can not delete last user")
        else:
            username = flask.request.form['username']
            user = utils.get_user()
            if not user:
                password = flask.request.form['password']
                password_confirm = flask.request.form['password_confirm']
                if password == password_confirm:
                    utils.create_user(username, password)
                    flask.flash('User Created')
                    return flask.redirect(flask.url_for('login'))
                error = "passwords do not match"
            else:
                error = "user already exists"

    users = utils.get_users()
    return flask.render_template(
        'users.j2',
        users=users,
        error=error)


# =================================================
# Setup
# =================================================
@app.route('/setup', methods=['GET', 'POST'])
def setup():
    if not utils.needs_user():
        return flask.redirect(flask.url_for('login'))
    error = None
    if flask.request.method == 'POST':
        username = flask.request.form['username']
        password = flask.request.form['password']
        password_confirm = flask.request.form['password_confirm']
        if password == password_confirm:
            utils.create_user(username, password)
            flask.flash('User Created')
            return flask.redirect(flask.url_for('login'))
        error = "passwords do not match"
    return flask.render_template('setup.j2', error=error)


# =================================================
# Dashboard
# =================================================
@app.route('/dashboard')
def dashboard():
    if utils.needs_user():
        return flask.redirect(flask.url_for('setup'))
    if ('logged_in' not in flask.session) or (not flask.session['logged_in']):
        return flask.redirect(flask.url_for('login'))
    running = utils.check_pid(Config["pidfile"])
    trunning, tutime = utils.get_last_manager_state()
    tutime_s = ""
    if tutime:
        tutime_s = time.strftime("%c", time.localtime(tutime))

    thread_state = {
        "running": bool(trunning),
        "utime": tutime_s
    }

    utime = time.strftime("%c", time.localtime())
    state_text = "Not Runnning"
    flags = {
        "alarm": False,
        "armed": False,
        "disarmed": False,
        "tripped": False,
        "falted": False,
    }

    state_data = None

    state = utils.get_latest_state()
    if state:
        alarm_state, state_data, state_time_i = state
        utime = time.strftime("%c", time.localtime(state_time_i))
        state_text = Alarm.ALARM_STATES[alarm_state]
        flags["alarm"] = alarm_state == Alarm.ALARMED
        flags["disarmed"] = alarm_state == Alarm.DISARMED
        flags["tripped"] = alarm_state == Alarm.TRIPPED
        flags["falted"] = alarm_state == Alarm.FALT
        flags["armed"] = alarm_state == Alarm.ARMED

    interfaces = utils.get_interfaces()
    return flask.render_template(
        'dashboard.j2',
        flags=flags,
        running=running,
        thread_state=thread_state,
        state_text=state_text,<commit_msg>check for the None case<commit_after>#!/usr/bin/python
import time
import flask
import database
import utils
from config import Config
from alarm import Alarm
import smbio
app = flask.Flask(__name__)


# =================================================
# Request Context
# =================================================
@app.before_request
def before_request():
    flask.g.db = database.get_db()
    flask.g.title = Config["title"]


@app.teardown_request
def teardown_request(exception):
    db = getattr(flask.g, 'db', None)
    if db is not None:
        db.close()


# =================================================
# Root & Static
# =================================================
@app.route("/")
def root():
    if utils.needs_user():
        return flask.redirect(flask.url_for('setup'))
    if 'logged_in' in flask.session and flask.session['logged_in']:
        return flask.redirect(flask.url_for('dashboard'))
    return flask.redirect(flask.url_for('login'))


@app.route('/js/<path:path>')
def send_j2(path):
    return flask.send_from_directory('js', path)


@app.route('/css/<path:path>')
def send_css(path):
    return flask.send_from_directory('css', path)


@app.route('/img/<path:path>')
def send_img(path):
    return flask.send_from_directory('img', path)


@app.route('/fonts/<path:path>')
def send_font(path):
    return flask.send_from_directory('fonts', path)


# =================================================
# Users
# =================================================
@app.route('/login', methods=['GET', 'POST'])
def login():
    if utils.needs_user():
        return flask.redirect(flask.url_for('setup'))
    if 'logged_in' in flask.session and flask.session['logged_in']:
        return flask.redirect(flask.url_for('dashboard'))
    error = None
    if flask.request.method == 'POST':
        username = flask.request.form['username']
        user = utils.get_user(username)
        if user:
            if utils.check_user_pass(user, flask.request.form['password']):
                flask.session['logged_in'] = True
                flask.session['username'] = user
                flask.flash('You were logged in')
                return flask.redirect(flask.url_for('dashboard'))
        error = "Invaid username or password"
    return flask.render_template('login.j2', error=error)


@app.route('/logout')
def logout():
    flask.session.pop('logged_in', None)
    flask.flash('You were logged out')
    return flask.redirect(flask.url_for('login'))


@app.route('/users', methods=['GET', 'POST'])
def users():
    if utils.needs_user():
        return flask.redirect(flask.url_for('setup'))
    if ('logged_in' not in flask.session) or (not flask.session['logged_in']):
        return flask.redirect(flask.url_for('login'))

    error = None
    if flask.request.method == 'POST':
        if "delete" in flask.request.form:
            if len(utils.get_users()) > 1:
                user_id = int(flask.request.form['id'])
                utils.delete_user(user_id)
                flask.flash('User Deleted')
            else:
                flask.flash("can not delete last user")
        else:
            username = flask.request.form['username']
            user = utils.get_user()
            if not user:
                password = <PASSWORD>.request.form['password']
                password_confirm = flask.request.form['password_confirm']
                if password == password_confirm:
                    utils.create_user(username, password)
                    flask.flash('User Created')
                    return flask.redirect(flask.url_for('login'))
                error = "passwords do not match"
            else:
                error = "user already exists"

    users = utils.get_users()
    return flask.render_template(
        'users.j2',
        users=users,
        error=error)


# =================================================
# Setup
# =================================================
@app.route('/setup', methods=['GET', 'POST'])
def setup():
    if not utils.needs_user():
        return flask.redirect(flask.url_for('login'))
    error = None
    if flask.request.method == 'POST':
        username = flask.request.form['username']
        password = flask.request.form['password']
        password_confirm = flask.request.form['password_confirm']
        if password == password_confirm:
            utils.create_user(username, password)
            flask.flash('User Created')
            return flask.redirect(flask.url_for('login'))
        error = "passwords do not match"
    return flask.render_template('setup.j2', error=error)


# =================================================
# Dashboard
# =================================================
@app.route('/dashboard')
def dashboard():
    if utils.needs_user():
        return flask.redirect(flask.url_for('setup'))
    if ('logged_in' not in flask.session) or (not flask.session['logged_in']):
        return flask.redirect(flask.url_for('login'))
    running = utils.check_pid(Config["pidfile"])
    trunning, tutime = utils.get_last_manager_state()
    tutime_s = ""
    if tutime:
        tutime_s = time.strftime("%c", time.localtime(tutime))

    thread_state = {
        "running": bool(trunning),
        "utime": tutime_s
    }

    utime = time.strftime("%c", time.localtime())
    state_text = "Not Runnning"
    flags = {
        "alarm": False,
        "armed": False,
        "disarmed": False,
        "tripped": False,
        "falted": False,
    }

    state_data = None

    state = utils.get_latest_state()
    if state:
        alarm_state, state_data, state_time_i = state
        if alarm_state is not None:
            utime = time.strftime("%c", time.localtime(state_time_i))
            state_text = Alarm.ALARM_STATES[alarm_state]
            flags["alarm"] = alarm_state == Alarm.ALARMED
            flags["disarmed"] = alarm_state == Alarm.DISARMED
            flags["tripped"] = alarm_state == Alarm.TRIPPED
            flags["falted"] = alarm_state == Alarm.FALT
            flags["armed"] = alarm_state == Alarm.ARMED

    interfaces = utils.get_interfaces()
    return flask.render_template(
        'dashboard.j2',
        flags=flags,
        running=running,
        thread_state=thread_state,
        state_text=state_text,
{'fraction_non_alphanumeric': 0.2043336254281845, 'fraction_numerical': 0.0009559467856289333, 'mean_word_length': 2.9828680203045685, 'pattern_counts': {'":': 14, '<': 12, '<?xml version=': 0, '>': 14, 'https://': 0, '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': '1602588', 'n_tokens_mistral': 3804, 'n_tokens_neox': 3634, 'n_words': 720}