def populate_problems():
    for i in range(len(op1_A)): #72 probs total
        if i <= 25:
            week = 1
        elif i <= 51:
            week = 2
        elif i <= 61: #wrong
            week = 3
        else: #wrong
            week = 4
        db.insert({"n1":op1_A[i],
        "n2":op2_A[i],
        "solution":sum_A[i],
        "problem_set":problem_set[0],
        "week":week},"problems")

    for i in range(len(op1_B)):
        if i <= 25:
            week = 1
        elif i <= 51:
            week = 2
        elif i <= 61: #wrong
            week = 3
        else: #wrong
            week = 4
        db.insert({"n1":op1_B[i],
        "n2":op2_B[i],
        "solution":sum_B[i],
        "problem_set":problem_set[1],
        "week":week},"problems")
    def POST(self):
        row = cherrypy.request.json

        if row.has_key('task') and row.has_key('training_mode'):
            db.insert(row, "tasks")
        else:
            raise cherrypy.HTTPError(400, "Missing task and/or training_mode field")
    def POST(self):
        row = cherrypy.request.json

        if row.has_key('task') and row.has_key('username'):
            result = db.insert(row, "trials")
        else:
            raise cherrypy.HTTPError(400, "Missing task and/or username field.")
def populate_tasks():
    for task in tasks:
        if '_timed' in task:
            db.insert({"task":task,
            "training_mode":training_mode[0],
            "timing_mode":timing_mode[0],
            "time_limit":time_limit[0]},"tasks")
        elif '_untimed' in task:
            db.insert({"task":task,
            "training_mode":training_mode[0],
            "timing_mode":timing_mode[1]},"tasks")
        else:
            db.insert({"task":task,
            "training_mode":training_mode[1],
            "timing_mode":timing_mode[1]},"tasks")
def createUser(d):
	#encrypt the password
	d['password'] = bcrypt.hashpw(d['password'].encode('utf-8'), bcrypt.gensalt())

	#check if user exists
	conn = psycopg2.connect("dbname=%s" % (db_name))
	cur = conn.cursor()
	cur.execute("SELECT COUNT(*) FROM users WHERE username = %s", [d['username']])
	result = cur.fetchall()[0][0]
	conn.close()

	if result == 0:
		response = databeast.insert(d, 'users')
		print response
		if response[0] == True:
			return [True, "User %s created" % d['username']]
		else:
			#pass SQL error up the chain
			return [False, response[1]]
	else:
		return [False, "User with name %s already exists" % d['username']]
def openSession(username):
    """
    open a training session for a given user within the database
    IMPORTANT - this function is only run during a login event
    returns db status message
    """
    conn, cur = databeast.connect()

    #first determine whether any open sessions exist
    sql = "SELECT count(*) FROM sessions WHERE username = %s AND end_time IS NULL"
    cur.execute(sql, [username])
    result = cur.fetchall()
    #TODO - check to see whether we are on the same training day - would want
    #to resume previous session in this case, and not close this one
    if result[0][0] >= 1:
        closeSession(username) #closes any active session for that user
    #now, determine the previous session number
    sql = "SELECT MAX(session) FROM sessions WHERE username = %s"
    cur.execute(sql, [username])
    result = cur.fetchall()
    if result[0][0]:
        session = result[0][0] + 1
    else:
        session = 1

    conn.close()

    #now, open the new session
    d = {}
    d['username'] = username
    d['tasks_to_play'] = tasks #TODO - counterbalancing
    d['training_day'] = 1 #TODO - increment based on previous training day
    d['week'] = 1
    d['session'] = session

    result = databeast.insert(d, "sessions")
    return result