Example #1
0
def get_document(filename):
    filename = filename.lower()
    # filename = filename.encode("utf-8")
    username = get_username()
    try:
        with io.open(
                "userdata/{}/writer/documents/{}.html".format(
                    username, filename),
                "r",
                encoding="utf-8",
        ) as file:
            document = file.read()
    # except FileNotFoundError:
    #    io.open("/var/www/jforseth.tech/text/writerdocs/{}.html".format(name))
    #    document=""
    except IOError:  # Python2
        io.open(
            "userdata/{}/writer/documents/{}.html".format(
                get_username().encode("utf-8"), filename),
            "w",
        )
        refresh_thumbs(username)
        document = ""
    # files = [i for i in files if i.replace("\n", "") != filename+".html"]
    # files.insert(0, filename+".html\n")
    # files=[i.decode("utf-8") for i in files]
    # with io.open('/var/www/jforseth.tech/text/writer_file_order.txt', 'w') as file:
    #    file.writelines(files)
    return Markup(document)
Example #2
0
def account(account):
    if is_logged_in() and account == get_username():  # .encode("utf-8"):
        if platform.node() == "backup-server-vm":
            flash(
                "The main jforseth.tech server is experiencing issues. Account changes have been suspended."
            )
        account = get_account(get_username())  # .encode("utf-8"))
        groups = account["prayer_groups"].split("|")
        return render_template("accounts/account.html", groups=groups)
    return render_template("errors/403.html"), 403
Example #3
0
def writer_thumb(name):
    # name = name.encode("utf-8")
    try:
        return send_file(
            "userdata/{}/writer/thumbnails/{}.html_thumb.png".format(
                get_username(), name.lower()))
    except:
        refresh_thumbs(get_username())  # .encode("utf-8"))
        return send_file(
            "userdata/{}/writer/thumbnails/{}.html_thumb.png".format(
                get_username(), name.lower()))
Example #4
0
def add_group():
    group = escape(request.form.get("group"))
    username = get_username()
    group = PARISH_DICTIONARY.get(group)
    if group is None:
        return redirect("/account/" + username)
    conn = sqlite3.connect("/var/www/jforseth.tech/database.db")
    cur = conn.cursor()
    with conn:
        cur.execute(
            """SELECT prayer_groups FROM accounts WHERE username = ? """,
            ([username]),
        )
    prayer_groups = cur.fetchone()[0]
    if prayer_groups == "None":
        prayer_groups = group + "|Public"
        flash("Subscribed", category="success")
    elif group in prayer_groups:
        flash("Already part of this group")
    else:
        prayer_groups = prayer_groups + "|" + group
        flash("Subscribed", category="success")

    with conn:
        cur.execute(
            """UPDATE accounts SET prayer_groups = ? WHERE username= ?""",
            ([prayer_groups, username]),
        )
    return redirect("/account/" + username)
Example #5
0
def _create_cypher_yrs_none(month, day, attestation_uri, title, date_string, date_category):
    """
    creates cypher query for none type of yrs
    :param month:
    :param day:
    :param attestation_uri:
    :param title:
    :param date_string:
    :return: cypher query string
    """
    godot_uri = "https://godot.date/id/" + shortuuid.uuid()
    if day == "":
        # only month specified
        cypher_query = """
        MATCH (root:Timeline)--(yrs:YearReferenceSystem {type: 'None'})-[:hasCalendarType]->(ct:CalendarType 
          {type:'Egyptian Calendar'})-[:hasCalendarPartial]->(cp_month:CalendarPartial {type:'month', value:'%s'}),
          (cp_month)-->(g_month:GODOT)
        MERGE (g_month)-[:hasAttestation]->(att:Attestation {uri: '%s', title: '%s', date_string: '%s', date_category: '%s', username: '******', last_update: date()})
        RETURN g_month.uri as g
        """ % (month, attestation_uri, title, date_string, date_category, get_username())
    else:
        # both month and day specified
        cypher_query = """
        MATCH (root:Timeline)--(yrs:YearReferenceSystem {type: 'None'})-[:hasCalendarType]->(ct:CalendarType 
          {type:'Egyptian Calendar'})-[:hasCalendarPartial]->(cp_month:CalendarPartial {type:'month', value:'%s'})
        MERGE (cp_month)-[:hasCalendarPartial]->(cp_day:CalendarPartial {type:'day', value:'%s'})
        MERGE (cp_day)-[:hasGodotUri]->(g_day:GODOT {type:'standard'})
          ON CREATE SET g_day.uri='%s'
        MERGE (g_day)-[:hasAttestation]->(att:Attestation {uri: '%s', title: '%s', date_string: '%s', date_category: '%s', username: '******', last_update: date()})
        RETURN g_day.uri as g
        """ % (month, day, godot_uri, attestation_uri, title, date_string, date_category, get_username())
    return cypher_query
Example #6
0
def check_if_admin():
    """Check if a given user has admin access.

    Returns:
        bool -- Whether or not the user has admin access.
    """
    return bool(is_logged_in()
                and 'admin' in get_current_access(get_username()))
Example #7
0
 def get(self):
     """Get the list of all trade sessions for the currently logged in user"""
     username = get_username()
     trading_sessions = (db.session.query(trading_session).filter(
         trading_session.username == username).all())
     return [
         trading_session_.to_dict() for trading_session_ in trading_sessions
     ]
Example #8
0
def new_todo():
    todoFilePath = "userdata/{}/todo/list.csv".format(get_username())
    name = request.form.get("taskname")  # Not esaping this because reasons.
    name = name.replace(",", "COMMA")
    currentlist = escape(request.form.get("list"))
    add_todo(todoFilePath, name, currentlist)
    # send_email('*****@*****.**', name, 'Submitted from jforseth.tech',PERSONAL_EMAIL, PERSONAL_PASSWORD)

    return redirect("/todo")
Example #9
0
def todo_deleted():
    todoFilePath = "userdata/{}/todo/list.csv".format(get_username())
    try:
        task_id = int(escape(request.form.get("taskid")))
    except ValueError:
        flash("Please enter a number", category="warning")
        return redirect("/todo")
    delete_todo(todoFilePath, task_id)
    return redirect("/todo")
Example #10
0
 def get(self):
     """Get the list of all stock trades for the currently logged in user"""
     username = get_username()
     trading_sessions_ids = (db.session.query(
         trading_session.session_id).filter(
             trading_session.username == username).all())
     trades = (db.session.query(trade).filter(
         trade.session_id.in_(trading_sessions_ids)).all())
     return [trade_.to_dict() for trade_ in trades]
Example #11
0
def landing_page():
    username = get_username()
    home = request.args['home']
    away = request.args['away']
    pick_type = request.args['type']
    result = request.args['result'].upper()
    print("home: " + home)
    print("pick_type: " + pick_type)
    return render_template('index.html')
Example #12
0
def todo_reordered():
    todoFilePath = "userdata/{}/todo/list.csv".format(get_username())
    try:
        item_to_reorder = int(escape(request.form.get("taskid")))
        position_to_move = int(escape(request.form.get("taskloc")))
    except ValueError:
        flash("Please enter a number", category="warning")
    reorder_todo(todoFilePath, item_to_reorder, position_to_move)
    return redirect("/todo")
Example #13
0
 def get(self, session_id):
     """Get a trade session for the currently logged in user""" ""
     username = get_username()
     trading_session_ = (db.session.query(trading_session).filter(
         trading_session.session_id == session_id,
         trading_session.username == username,
     ).first())
     if not trading_session_:
         abort(404, "trading session not found")
     return trading_session_.to_dict()
Example #14
0
def account_del():
    password = escape(request.form.get("confirm_password"))
    user = get_username()  # .encode("utf-8")
    current_account = get_account(user)
    if check_password_hash(current_account.get("hashed_password"), password):
        delete_account(user)
        flash("Your account has been deleted!", category="success")
        return redirect("/logout")
    else:
        flash("Incorrect password")
Example #15
0
def update_attestation(node_id, attestation_uri, title, date_string, date_category):
    title = _clean_string(title)
    date_string = _clean_string(date_string)
    query = """
    match (a:Attestation) 
    where id(a) = %s 
    set a.date_string='%s', a.title = '%s', a.uri = '%s', a.date_category = '%s', a.username = '******', a.last_update = date()
    """ % (node_id, date_string, title, attestation_uri, date_category, get_username())
    results = query_neo4j_db(query)
    if results:
        return results
Example #16
0
def todo_page():
    # if not os.path.isdir("userdata/{}/todo/".format(get_username().encode('utf-8'))):
    #    os.makedirs('userdata/{}/todo/'.format(get_username().encode('utf-8')))
    #    with open("userdata/{}/todo/list.csv".format(get_username().encode('utf-8')), 'w'):
    #        pass
    todoFilePath = "userdata/{}/todo/list.csv".format(get_username())
    todos = get_todos(todoFilePath)
    todos.reverse()
    lists = get_lists(todoFilePath)
    todos = [(todo[0], todo[1]) for todo in todos]
    lists = [list for list in lists]
    return render_template("todo/todo.html", result=todos, lists=lists)
Example #17
0
 def post(self, session_id):
     """Restart/unpause a trading session"""
     username = get_username()
     trading_session_ = (db.session.query(trading_session).filter(
         trading_session.session_id == session_id,
         trading_session.username == username,
     ).first())
     if not trading_session_:
         abort(404, "trading session not found")
     trading_session_.is_paused = False
     db.session.commit()
     return trading_session_.to_dict()
Example #18
0
def lock_form_route():
    form = lock_form.LockForm()
    if form.validate_on_submit():
        username = get_username()
        print("Form for week " + str(form.week.data) + " validated")
        p = lock_form.convert_form_to_pick_obj(form)
        print("Pick obj: " + str(p.__dict__))
        dynamo.insert_pick(username, p)
        return redirect('/en')
    else:
        print("Not validated")
    return render_template('add-lock.html', form=form)
Example #19
0
def on_click(n_clicks, stock_id):
    __log__.debug(f"finishing trading session for stock {stock_id}")
    username = get_username()
    trading_session_ = (db.session.query(trading_session).filter(
        trading_session.is_finished != True,
        trading_session.ticker == stock_id,
        trading_session.username == username,
    ).first())
    if not trading_session_:
        abort(404, "trading session not found")
    trading_session_.is_finished = True
    db.session.commit()
Example #20
0
def save(filename, data):
    filename = filename.lower()
    username = get_username()  # .encode("utf-8")
    path = "userdata/{}/writer/documents/".format(username)
    # if not os.path.isdir(path):
    #    os.makedirs(path)

    print(data)
    print(path + "{}.html".format(filename))
    with io.open(path + "{}.html".format(filename), "w",
                 encoding="utf-8") as file:
        file.write(data)
    return redirect("/writer/{}".format(filename))
Example #21
0
 def get(self, trade_id):
     """Get a stock trade for the currently logged in user"""
     username = get_username()
     trading_sessions_ids = (db.session.query(
         trading_session.session_id).filter(
             trading_session.username == username).all())
     if not trading_sessions_ids:
         abort(404, "no trading sessions for user")
     trade_ = (db.session.query(trade).filter(
         trade.trade_id == trade_id,
         trade.session_id.in_(trading_sessions_ids)).first())
     if not trade_:
         abort(404, "trade not found")
     return trade_.to_dict()
Example #22
0
def _create_cypher_yrs_unknown(year, month, day, attestation_uri, title, date_string, date_category):
    """
    creates cypher query for unknown yrs
    :param year:
    :param month:
    :param day:
    :param attestation_uri:
    :param title:
    :param date_string:
    :return: cypher query string
    """
    godot_uri = "https://godot.date/id/" + shortuuid.uuid()
    if month == "None" and day == "":
        # only year given
        cypher_query = """
        MATCH (root:Timeline)--(yrs:YearReferenceSystem {type: 'Unknown'})
        MERGE (yrs)-[:hasCalendarPartial]->(cp:CalendarPartial {type: 'year', value: '%s'})
        MERGE (cp)-[:hasGodotUri]->(g:GODOT {type:'standard'})
          ON CREATE SET g.uri='%s'
        MERGE (g)-[:hasAttestation]->(att:Attestation {uri: '%s', title: '%s', date_string: '%s', date_category:'%s', username: '******', last_update: date()})
        RETURN g.uri as g 
        """ % (year, godot_uri, attestation_uri, title, date_string, date_category, get_username())
    else:
        if day == "":
            # only month specified
            cypher_query = """
            MATCH (root:Timeline)--(yrs:YearReferenceSystem {type: 'Unknown'})
            MERGE (yrs)-[:hasCalendarPartial]->(cp:CalendarPartial {type: 'year', value: '%s'})
            MERGE (cp)-[:hasCalendarType]->(ct:CalendarType {type: 'Egyptian Calendar'})
            MERGE (ct)-[:hasCalendarPartial]->(cp_month:CalendarPartial {type: 'month', value: '%s'})
            MERGE (cp_month)-[:hasGodotUri]->(g:GODOT {type:'standard'})
              ON CREATE SET g.uri='%s'
            MERGE (g)-[:hasAttestation]->(att:Attestation {uri: '%s', title: '%s', date_string: '%s', date_category:'%s', username: '******', last_update: date()})
            RETURN g.uri as g 
            """ % (year, month, godot_uri, attestation_uri, title, date_string, date_category, get_username())
        else:
            # month & day specified
            cypher_query = """
            MATCH (root:Timeline)--(yrs:YearReferenceSystem {type: 'Unknown'})
            MERGE (yrs)-[:hasCalendarPartial]->(cp:CalendarPartial {type: 'year', value: '%s'})
            MERGE (cp)-[:hasCalendarType]->(ct:CalendarType {type: 'Egyptian Calendar'})
            MERGE (ct)-[:hasCalendarPartial]->(cp_month:CalendarPartial {type: 'month', value: '%s'})
            MERGE (cp_month)-[:hasCalendarPartial]->(cp_day:CalendarPartial {type: 'day', value: '%s'})
            MERGE (cp_day)-[:hasGodotUri]->(g:GODOT {type:'standard'})
              ON CREATE SET g.uri='%s'
            MERGE (g)-[:hasAttestation]->(att:Attestation {uri: '%s', title: '%s', date_string: '%s', date_category:'%s', username: '******', last_update: date()})
            RETURN g.uri as g 
            """ % (year, month, day, godot_uri, attestation_uri, title, date_string, date_category, get_username())
    return cypher_query
Example #23
0
    def post(self, session_id):
        """Finish a trading session

        .. warning::
            This action is irreversible
        """
        username = get_username()
        trading_session_ = (db.session.query(trading_session).filter(
            trading_session.session_id == session_id,
            trading_session.username == username,
        ).first())
        if not trading_session_:
            abort(404, "trading session not found")
        trading_session_.is_finished = True
        db.session.commit()
        return trading_session_.to_dict()
Example #24
0
    def post(self):
        """Add a trade session to the currently logged in user"""
        new_trading_session = api.payload

        # TODO: ensure ticker is valid
        username = get_username()
        new_trading_session_db = trading_session(
            username=username,
            start_time=new_trading_session["start_time"],
            end_time=new_trading_session.get("end_time"),
            ticker=new_trading_session["ticker"],
            is_paused=new_trading_session.get("is_paused", False),
            is_finished=new_trading_session.get("is_finished", False),
        )
        db.session.add(new_trading_session_db)
        db.session.commit()
        return new_trading_session_db.to_dict(), 201
def secret():
    user_data = get_username()
    f = open("static/CSV/"+user_data+".csv","r")
    k = f.readlines()
    Subject = ["SB","BA","BB","ACJ","SM","MC"]
    objects = ["SB","BA","BB","ACJ","SM","MC"]
    Total = [0]*6
    Present = [0]*6
    Att = list()

    for i in k:
        a = i.split(",")
        b = a[1].split(" ")
        c = a[2].split(" ")
        
        for j in range(0,6):
            for l in b:
                if(Subject[j] == l):
                    Total[j] = Total[j]+1

            for m in c:
                if(Subject[j] == m):
                    Total[j] = Total[j]+1
                    Present[j] = Present[j]+1


    for i in range(0,6):
        a = Present[i]/Total[i]
        a = a*100
        a = int(a)
        objects[i] = objects[i]+" "+str(a)
        Att.append(a)

    y_pos = np.arange(len(objects))
    plt.bar(y_pos, Att, align='center', alpha=0.5)
    plt.xticks(y_pos, objects)
    plt.ylabel('Attendance')
    plt.title('Subject')

    plt.savefig("static/people_photo/"+user_data+"1.jpg")
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'], user_data+'1.jpg')

    return render_template('secret.html', user_image = full_filename)
Example #26
0
def home():
    username = get_username()
    titles = [('pick_string', 'Pick'), ('outcome', 'Outcome'),
              ('game_title', 'Game'), ('pick_type', 'Pick Type')]

    weeks_available = dynamo.get_weeks_available(username)
    picks_for_each_week = []
    for week in weeks_available:
        picks_for_each_week.append(
            (str(week), dynamo.get_picks_for_user_for_week(username, week)))

    print("Picks for each week: " + str(picks_for_each_week))
    return render_template(
        'home.html',
        username=username.capitalize(),
        picks_for_each_week=picks_for_each_week,
        titles=titles,
        header_classes='text-info',
        table_classes="table-striped table-bordered table-sm")
Example #27
0
def writer_home():
    if platform.node() == "backup-server-vm":
        flash(
            "The main jforseth.tech server is currently experiencing issues. Your changes may not be saved when the main server comes back online."
        )
    username = get_username()  # .encode("utf-8")
    path = "userdata/{}/writer/documents/".format(username)
    print(path)
    # if not os.path.isdir(path):
    #    os.makedirs(path)
    #    os.makedirs("userdata/{}/writer/thumbnails/".format(username))
    files = os.listdir(path)
    files = [i for i in files if i != "oopsie"]
    new_files = []
    for i in files:
        if i != "oopsie":
            i = i.replace(".html", "")
            i = i.title()
            new_files.append(i)
    return render_template("writer/writer.html", docs=new_files)
Example #28
0
def on_click(n_clicks, stock_id):
    username = get_username()
    trading_session_ = (db.session.query(trading_session).filter(
        trading_session.is_finished != True,
        trading_session.ticker == stock_id,
        trading_session.username == username,
    ).first())
    if trading_session_:  # only have one trading session for each stock ticker
        abort(409, f"trading session already exists for stock {stock_id}")
    else:
        __log__.debug(f"adding trading session for stock {stock_id}")
        new_trading_session_db = trading_session(
            username=username,
            start_time=datetime.utcnow(),
            end_time=None,
            ticker=stock_id,
            is_paused=False,
            is_finished=False,
        )
        db.session.add(new_trading_session_db)
        db.session.commit()
Example #29
0
def change_password():
    old_password = escape(request.form.get("old_password"))
    new_password = escape(request.form.get("new_password"))
    confirm_new_password = escape(request.form.get("confirm_new_password"))

    current_username = get_username()  # .encode("utf-8")
    current_account = get_account(current_username)

    if platform.node() == "backup-server-vm":
        pass

    elif new_password != confirm_new_password:
        flash("New passwords do not match!", category="Success")

    elif check_password_hash(current_account.get("hashed_password"), old_password):
        update_pw(current_username, new_password)
        flash("Success!", category="success")

    else:
        flash("Old password incorrect.", category="warning")

    return redirect("/account/{}".format(current_username))
Example #30
0
    def post(self):
        """Add a stock trade to the currently logged in user"""
        new_trade = api.payload

        # trade type is BUY or SELL
        if new_trade["trade_type"] not in ["BUY", "SELL"]:
            abort(400, "trade_type must be either BUY or SELL")

        # ensure volume>1
        if new_trade["volume"] < 1:
            abort(400, "volume must be a integer equal to or greater than 1")

        # ensure price>0
        if new_trade["price"] <= 0:
            abort(400, "price must be greater than 0")

        # get the session id by the currently non_paused trading session
        username = get_username()
        trading_session_id = (db.session.query(
            trading_session.session_id).filter(
                trading_session.username == username,
                trading_session.session_id == new_trade["session_id"],
                trading_session.is_finished == False,
                trading_session.is_paused == False,
            ).first())
        if trading_session_id is None:
            abort(404, "trading session not found")

        new_trade_db = trade(
            price=new_trade["price"],
            trade_type=new_trade["trade_type"],
            volume=new_trade["volume"],
            session_id=new_trade["session_id"],
            time_stamp=new_trade["time_stamp"],
        )
        db.session.add(new_trade_db)
        db.session.commit()
        return new_trade_db.to_dict(), 201
Example #31
0
def get_current_user():
    return get_username() or getpass.getuser()