jiahuimbzuai/CoQuIR huggingface dataset:
// render_page_edit [python]
@app.route('/<page_name>/edit')
def render_page_edit(page_name):
    query = db.query("select page_content.content from page, page_content where page.id = page_content.page_id and page.page_name = $1 order by page_content.id desc limit 1", page_name)
    wiki_page = query.namedresult()
    if len(wiki_page) > 0:
        content = wiki_page[0].content
    else:
        content = ""
    return render_template(
        'edit_page.html',
        page_name = page_name,
        content = content
    )
// render_page_edit [python]
@app.route('/<page_name>/edit')
def render_page_edit(page_name):
    query = db.query("select page_content.content from page, page_content where page.id = page_content.page_id and page.page_name = '%s' order by page_content.id desc limit 1" % page_name)
    wiki_page = query.namedresult()
    if len(wiki_page) > 0:
        content = wiki_page[0].content
    else:
        content = ""
    return render_template(
        'edit_page.html',
        page_name = page_name,
        content = content
    )
// get_monthly_ranks_for_scene [python]
def get_monthly_ranks_for_scene(db, scene, tag):

    sql = "SELECT date, rank FROM ranks WHERE scene='{scene}' AND player='{tag}'"
    args = {'scene': scene, 'tag': tag}
    res = db.exec(sql, args)

    res = [r for r in res if played_during_month(db, scene, tag, get_previous_month(r[0]))]

    # Build up a dict of {date: rank}
    ranks = {}
    for r in res:
        ranks[r[0]] = r[1]

    return ranks
// get_monthly_ranks_for_scene [python]
def get_monthly_ranks_for_scene(db, scene, tag):

    sql = "SELECT date, rank FROM ranks WHERE scene='{}' AND player='{}'".format(scene, tag)
    res = db.exec(sql)

    res = [r for r in res if played_during_month(db, scene, tag, get_previous_month(r[0]))]

    # Build up a dict of {date: rank}
    ranks = {}
    for r in res:
        ranks[r[0]] = r[1]

    return ranks
// auto_unlock_tasks [python]
    @staticmethod
    def auto_unlock_tasks(project_id: int):
        """Unlock all tasks locked for longer than the auto-unlock delta"""
        expiry_delta = Task.auto_unlock_delta()
        lock_duration = (datetime.datetime.min + expiry_delta).time().isoformat()
        expiry_date = datetime.datetime.utcnow() - expiry_delta
        old_locks_query = '''SELECT t.id
            FROM tasks t, task_history th
            WHERE t.id = th.task_id
            AND t.project_id = th.project_id
            AND t.task_status IN (1,3)
            AND th.action IN ( 'LOCKED_FOR_VALIDATION','LOCKED_FOR_MAPPING' )
            AND th.action_text IS NULL
            AND t.project_id = :project_id
            AND th.action_date <= :expiry_date
            '''

        old_tasks = db.engine.execute(text(old_locks_query), project_id=project_id, expiry_date=str(expiry_date))

        if old_tasks.rowcount == 0:
            # no tasks older than the delta found, return without further processing
            return

        for old_task in old_tasks:
            task = Task.get(old_task[0], project_id)
            task.auto_unlock_expired_tasks(expiry_date, lock_duration)
// auto_unlock_tasks [python]
    @staticmethod
    def auto_unlock_tasks(project_id: int):
        """Unlock all tasks locked for longer than the auto-unlock delta"""
        expiry_delta = Task.auto_unlock_delta()
        lock_duration = (datetime.datetime.min + expiry_delta).time().isoformat()
        expiry_date = datetime.datetime.utcnow() - expiry_delta
        old_locks_query = '''SELECT t.id
            FROM tasks t, task_history th
            WHERE t.id = th.task_id
            AND t.project_id = th.project_id
            AND t.task_status IN (1,3)
            AND th.action IN ( 'LOCKED_FOR_VALIDATION','LOCKED_FOR_MAPPING' )
            AND th.action_text IS NULL
            AND t.project_id = {0}
            AND th.action_date <= '{1}'
            '''.format(project_id, str(expiry_date))

        old_tasks = db.engine.execute(old_locks_query)

        if old_tasks.rowcount == 0:
            # no tasks older than the delta found, return without further processing
            return

        for old_task in old_tasks:
            task = Task.get(old_task[0], project_id)
            task.auto_unlock_expired_tasks(expiry_date, lock_duration)
// add_input [python]
    def add_input(self, data):
        connection = self.connect()
        try:
            # The following introduces a deliberate security flaw. 
            # See section on SQL injection below
            query = "INSERT INTO crimes (description) VALUES(%s);"
            with connection.cursor() as cursor:
                cursor.execute(query, data)
                connection.commit()
        finally:
            connection.close()
// add_input [python]
    def add_input(self, data):
        connection = self.connect()
        try:
            # The following introduces a deliberate security flaw. 
            # See section on SQL injection below
            query = "INSERT INTO crimes (description) VALUES('{}');".format(data)
            with connection.cursor() as cursor:
                cursor.execute(query)
                connection.commit()
        finally:
            connection.close()
// getAllComments [python]
    def getAllComments(self):
        sqlText="select comment from comments where userid=%s order by date;"
        params = [self.userid]
        allposts=sql.queryDB(self.conn,sqlText,params)
        return allposts;
// getAllComments [python]
    def getAllComments(self):
        sqlText="select comment from comments where userid=%d order by date;"
        allposts=sql.queryDB(self.conn,sqlText)
        return allposts;
// save_accepted_transaction [python]
    def save_accepted_transaction(self, user_id, project_id, money):
        self.cursor.execute("update users set money = money - %s where id = %s", (money, user_id))
        self.cursor.execute("update projects set money = money + %s where id = %s", (money, project_id))
        self.cursor.execute("insert into transactions (project_id, user_id, money, timestamp, state) values (%s, %s, "
                            "%s, now(), 'accepted' )", (project_id, user_id, money))
        self.db.commit()
// save_accepted_transaction [python]
    def save_accepted_transaction(self, user_id, project_id, money):
        self.cursor.execute("update users set money = money - %s where id = %s"%(money, user_id))
        self.cursor.execute("update projects set money = money + %s where id = %s" % (money, project_id))
        self.cursor.execute("insert into transactions (project_id, user_id, money, timestamp, state) values (%s, %s, %s, now(), 'accepted' )" % (project_id, user_id, money))
        self.db.commit()
// shame_ask [python]
def shame_ask(name):
    db = db_connect()
    cursor = db.cursor()
    try:
        cursor.execute('''
            SELECT shame FROM people WHERE name=%(name)s
            ''', (name, ))
        shame = cursor.fetchone()
        db.close()
        if shame is None:
            logger.debug('No shame found for name {}'.format(name))
            return shame
        else:
            shame = shame[0]
            logger.debug('shame of {} found for name {}'.format(shame, name))
            return shame
    except Exception as e:
        logger.error('Execution failed with error: {}'.format(e))
        raise
// shame_ask [python]
def shame_ask(name):
    db = db_connect()
    cursor = db.cursor()
    try:
        cursor.execute('''
            SELECT shame FROM people WHERE name='{}'
            '''.format(name))
        shame = cursor.fetchone()
        db.close()
        if shame is None:
            logger.debug('No shame found for name {}'.format(name))
            return shame
        else:
            shame = shame[0]
            logger.debug('shame of {} found for name {}'.format(shame, name))
            return shame
    except Exception as e:
        logger.error('Execution failed with error: {}'.format(e))
        raise
// incrementOption [python]
def incrementOption(cursor, poll_name, option):
    key = poll_name+"-"+option
    req = "UPDATE {} SET count=count+1 WHERE name_option=?".format(CFG("options_table_name"))
    cursor.execute(req, (key,))
// incrementOption [python]
def incrementOption(cursor, poll_name, option):
    key = poll_name+"-"+option
    req = "UPDATE {} SET count=count+1 WHERE name_option = '{}';".format(CFG("options_table_name"), key)
    cursor.execute(req)
// overview [python]
@app.route('/overview/<classNum>')
def overview(classNum):
	if 'username' in session:
		classNoSpace = classNum.split(' ')[0]+classNum.split(' ')[1]

		#Save the current course as a session variable.
		session['currentCourse'] = classNoSpace

		conn = mysql.connect()
		cursor = conn.cursor()

		cursor.execute("SELECT courseName,courseOverview from courses where courseAbbreviation=%s", (classNoSpace))
		data = cursor.fetchone()

		return render_template('overview.html', className = classNum, courseTitle = data[0], courseOverview = data[1])

	return redirect(url_for('index'))
// overview [python]
@app.route('/overview/<classNum>')
def overview(classNum):
	if 'username' in session:
		classNoSpace = classNum.split(' ')[0]+classNum.split(' ')[1]

		#Save the current course as a session variable.
		session['currentCourse'] = classNoSpace

		conn = mysql.connect()
		cursor = conn.cursor()

		cursor.execute("SELECT courseName,courseOverview from courses where courseAbbreviation='" + classNoSpace + "'")
		data = cursor.fetchone()

		return render_template('overview.html', className = classNum, courseTitle = data[0], courseOverview = data[1])

	return redirect(url_for('index'))
// addTags [python]
def addTags(tag_list, listing_id):
    """
    Adds a list of tags tag_list for a given listing with listing_id to the database
    """
    cur = conn.cursor()
    for x in tag_list:
        sql = "INSERT INTO %s VALUES (%s %s)"
        cur.execute(sql, (listing_tags_table_name, listing_id, x))
// addTags [python]
def addTags(tag_list, listing_id):
    """
    Adds a list of tags tag_list for a given listing with listing_id to the database
    """
    cur = conn.cursor()
    for x in tag_list:
        sql = "INSERT INTO {} VALUES {}".format(listing_tags_table_name, str((listing_id, x)))
        cur.execute(sql)
// edit [python]
@mod.route('/edit/<int:cmt_id>', methods=['GET', 'POST'])
def edit(cmt_id):
    m = None
    if request.method == 'GET':
        cursor.execute("SELECT * FROM comment where cmt_id = %s;", (cmt_id,))
        m = cursor.fetchone()
        return render_template('comment/edit.html', m=m, cmt_id=cmt_id)

    if request.method == 'POST':
        content = request.form['content']
        cursor.execute("UPDATE comment SET content = %s where cmt_id = %s;", (content, cmt_id))
        conn.commit()
        cursor.execute("SELECT msg_id FROM comment where cmt_id = %s;", (cmt_id,))
        m = cursor.fetchone()
        flash('Edit Success!')
        return redirect(url_for('comment.show', msg_id=m[0]))

    return render_template('comment/edit.html', m=m, cmt_id=cmt_id)
// edit [python]
@mod.route('/edit/<int:cmt_id>', methods=['GET', 'POST'])
def edit(cmt_id):
    m = None
    if request.method == 'GET':
        sql = "SELECT * FROM comment where cmt_id = %d;" % (cmt_id)
        cursor.execute(sql)
        m = cursor.fetchone()
        return render_template('comment/edit.html', m=m, cmt_id=cmt_id)

    if request.method == 'POST':
        content = request.form['content']
        sql = "UPDATE comment SET content = '%s' where cmt_id = '%d';" \
            % (content, cmt_id)
        cursor.execute(sql)
        conn.commit()
        sql = "SELECT msg_id FROM comment where cmt_id = %d;" % (cmt_id)
        cursor.execute(sql)
        m = cursor.fetchone()
        flash('Edit Success!')
        return redirect(url_for('comment.show', msg_id=m[0]))

    return render_template('comment/edit.html', m=m, cmt_id=cmt_id)
// process_form [python]
def process_form():
    # see https://docs.python.org/3.4/library/cgi.html for the basic usage
    # here.
    form = cgi.FieldStorage()


    if "player1" not in form or "player2" not in form or "size" not in form:
        raise FormError("Invalid parameters.")

    player1 = form["player1"].value
    player2 = form["player2"].value
    for c in player1+player2:
        if c not in "_-" and not c.isdigit() and not c.isalpha():
            raise FormError("Invalid parameters: The player names can only contains upper and lowercase characters, digits, underscores, and hypens")
            return

    try:
        size = int(form["size"].value)
    except:
        raise FormError("Invalid parameters: 'size' is not an integer.")
        return

    if size < 2 or size > 9:
        raise FormError("The 'size' must be in the range 2-9, inclusive.")


    # connect to the database
    conn = MySQLdb.connect(host   = pnsdp.SQL_HOST,
                           user   = pnsdp.SQL_USER,
                           passwd = pnsdp.SQL_PASSWD,
                           db     = pnsdp.SQL_DB)
    cursor = conn.cursor()

    # insert the new row
    cursor.execute("""INSERT INTO games(player1,player2,size) VALUES("%s","%s",%d);""", (player1,player2,size))

    gameID = cursor.lastrowid


    # MySQLdb has been building a transaction as we run.  Commit them now, and
    # also clean up the other resources we've allocated.
    conn.commit()
    cursor.close()
    conn.close()

    return gameID
// process_form [python]
def process_form():
    # see https://docs.python.org/3.4/library/cgi.html for the basic usage
    # here.
    form = cgi.FieldStorage()


    if "player1" not in form or "player2" not in form or "size" not in form:
        raise FormError("Invalid parameters.")

    player1 = form["player1"].value
    player2 = form["player2"].value
    for c in player1+player2:
        if c not in "_-" and not c.isdigit() and not c.isalpha():
            raise FormError("Invalid parameters: The player names can only contains upper and lowercase characters, digits, underscores, and hypens")
            return

    try:
        size = int(form["size"].value)
    except:
        raise FormError("Invalid parameters: 'size' is not an integer.")
        return

    if size < 2 or size > 9:
        raise FormError("The 'size' must be in the range 2-9, inclusive.")


    # connect to the database
    conn = MySQLdb.connect(host   = pnsdp.SQL_HOST,
                           user   = pnsdp.SQL_USER,
                           passwd = pnsdp.SQL_PASSWD,
                           db     = pnsdp.SQL_DB)
    cursor = conn.cursor()

    # insert the new row
    cursor.execute("""INSERT INTO games(player1,player2,size) VALUES("%s","%s",%d);""" % (player1,player2,size))

    gameID = cursor.lastrowid


    # MySQLdb has been building a transaction as we run.  Commit them now, and
    # also clean up the other resources we've allocated.
    conn.commit()
    cursor.close()
    conn.close()

    return gameID
// clean_cache [python]
    def clean_cache(self, limit):
        """
        Method that remove several User objects from cache - the least 
        active users
        :param limit: number of the users that the method should remove
        from cache
        :return: None
        """

        log.info('Figuring out the least active users...')
        # Select users that the least active recently
        user_ids = tuple(self.users.keys())
        query = ('SELECT chat_id '
                 'FROM photo_queries_table2 '
                 f'WHERE chat_id in {user_ids} '
                 'GROUP BY chat_id '
                 'ORDER BY MAX(time) '
                 f'LIMIT %s')

        parameters = limit,

        try:
            cursor = db.execute_query(query, parameters)
        except DatabaseConnectionError:
            log.error("Can't figure out the least active users...")
            return

        if not cursor.rowcount:
            log.warning("There are no users in the db")
            return

        # Make list out of tuple of tuples that is returned by MySQL
        least_active_users = [chat_id[0] for chat_id in cursor.fetchall()]
        log.info('Removing %d least active users from cache...', limit)
        num_deleted_entries = 0
        for entry in least_active_users:
            log.debug('Deleting %s...', entry)
            deleted_entry = self.users.pop(entry, None)
            if deleted_entry:
                num_deleted_entries += 1
        log.debug("%d users were removed from cache.", num_deleted_entries)
// clean_cache [python]
    def clean_cache(self, limit):
        """
        Method that remove several User objects from cache - the least 
        active users
        :param limit: number of the users that the method should remove
        from cache
        :return: None
        """

        log.info('Figuring out the least active users...')
        # Select users that the least active recently
        user_ids = tuple(self.users.keys())
        query = ('SELECT chat_id '
                 'FROM photo_queries_table2 '
                 f'WHERE chat_id in {user_ids} '
                 'GROUP BY chat_id '
                 'ORDER BY MAX(time) '
                 f'LIMIT {limit}')

        try:
            cursor = db.execute_query(query)
        except DatabaseConnectionError:
            log.error("Can't figure out the least active users...")
            return

        if not cursor.rowcount:
            log.warning("There are no users in the db")
            return

        # Make list out of tuple of tuples that is returned by MySQL
        least_active_users = [chat_id[0] for chat_id in cursor.fetchall()]
        log.info('Removing %d least active users from cache...', limit)
        num_deleted_entries = 0
        for entry in least_active_users:
            log.debug('Deleting %s...', entry)
            deleted_entry = self.users.pop(entry, None)
            if deleted_entry:
                num_deleted_entries += 1
        log.debug("%d users were removed from cache.", num_deleted_entries)
// quiz [python]
@app.route('/quiz')
def quiz():

    varga = request.args.get('varga')

    try:
        rows =[]

        with sql.connect('amara.db') as con:
            con.row_factory = sql.Row
            cur = con.cursor()
            cur.execute("select * from pada inner join mula on pada.sloka_line = mula.sloka_line where pada.varga = ? order by random() limit 1;", [varga])
            rows = cur.fetchall();

            artha = rows[0]["artha"];
            cur.execute("select pada from pada where varga = ? and artha = ? order by id", [varga, artha]);
            paryaya = cur.fetchall();

            return render_template('quiz.html', rows=rows, paryaya=paryaya, varga=varga)
    finally:
        con.close()
// quiz [python]
@app.route('/quiz')
def quiz():

    varga = request.args.get('varga')

    try:
        rows =[]

        with sql.connect('amara.db') as con:
            con.row_factory = sql.Row
            cur = con.cursor()
            cur.execute("select * from pada inner join mula on pada.sloka_line = mula.sloka_line where pada.varga = '%s' order by random() limit 1;" % varga)
            rows = cur.fetchall();

            artha = rows[0]["artha"];
            cur.execute("select pada from pada where varga = '%s' and artha = '%s' order by id" % (varga, artha));
            paryaya = cur.fetchall();

            return render_template('quiz.html', rows=rows, paryaya=paryaya, varga=varga)
    finally:
        con.close()
// reportMatch._checkPairing [python]
    def _checkPairing():
        if winner == loser:
            raise ValueError('Attempt to match player against self')

        q = '''
        SELECT COUNT(*) FROM matches
        WHERE (matches.winner_id = %s AND matches.loser_id = %s)
              OR (matches.winner_id = %s AND matches.loser_id = %s);
        '''
        cur.execute(q, (winner, loser, loser, winner))
        if cur.fetchone()[0] > 0:
            raise ValueError('Pairing %s, %s already played' % (winner, loser))
// reportMatch._checkPairing [python]
    def _checkPairing():
        if winner == loser:
            raise ValueError('Attempt to match player against self')

        q = '''
        SELECT COUNT(*) FROM matches
        WHERE (matches.winner_id = %s AND matches.loser_id = %s)
              OR (matches.winner_id = %s AND matches.loser_id = %s);
        ''' % (winner, loser, loser, winner)
        cur.execute(q)
        if cur.fetchone()[0] > 0:
            raise ValueError('Pairing %s, %s already played' % (winner, loser))
// add_month_data_row [python]
    def add_month_data_row(self, inverter_serial, ts, etoday, etotal):

        y = datetime.fromtimestamp(ts) - timedelta(days=1)
        y_ts = int(datetime(y.year, y.month, y.day, 23, tzinfo=pytz.utc).timestamp())

        query = '''
            INSERT INTO MonthData (
                TimeStamp,
                Serial,
                DayYield,
                TotalYield                                 
            ) VALUES (
                ?,
                ?,
                ?,
                ?
            );
        '''
        self.c.execute(query, (y_ts, inverter_serial, etoday, etotal))
// add_month_data_row [python]
    def add_month_data_row(self, inverter_serial, ts, etoday, etotal):

        y = datetime.fromtimestamp(ts) - timedelta(days=1)
        y_ts = int(datetime(y.year, y.month, y.day, 23, tzinfo=pytz.utc).timestamp())

        query = '''
            INSERT INTO MonthData (
                TimeStamp,
                Serial,
                DayYield,
                TotalYield                                 
            ) VALUES (
                %s,
                %s,
                %s,
                %s
            );
        ''' % (y_ts, inverter_serial, etoday, etotal)
        self.c.execute(query)
// create_playlist [python]
def create_playlist(name, db):
    db.execute(
        "INSERT INTO playlist (name, video_position) VALUES(%s, 0);", (name,))
// create_playlist [python]
def create_playlist(name, db):
    db.execute(
        "INSERT INTO playlist (name, video_position) VALUES('{name}', 0);".format(name=name))
// karma_ask [python]
def karma_ask(name):
    db = db_connect()
    cursor = db.cursor()
    try:
        cursor.execute(''' SELECT karma FROM people WHERE name=%(name)s ''',
                       (name, ))
        karma = cursor.fetchone()
        if karma is None:
            logger.debug('No karma found for name {}'.format(name))
            db.close()
            return karma
        else:
            karma = karma[0]
            logger.debug('karma of {} found for name {}'.format(karma, name))
            db.close()
            return karma
    except Exception as e:
        logger.error('Execution failed with error: {}'.format(e))
        raise
// karma_ask [python]
def karma_ask(name):
    db = db_connect()
    cursor = db.cursor()
    try:
        cursor.execute(
            ''' SELECT karma FROM people WHERE name='{}' '''.format(name))
        karma = cursor.fetchone()
        if karma is None:
            logger.debug('No karma found for name {}'.format(name))
            db.close()
            return karma
        else:
            karma = karma[0]
            logger.debug('karma of {} found for name {}'.format(karma, name))
            db.close()
            return karma
    except Exception as e:
        logger.error('Execution failed with error: {}'.format(e))
        raise
// post [python]
    def post(self):
        """ Returns JWT upon login verification """
        json_data = request.get_json()
        if not json_data['email']:
            return jsonify({"msg": "Missing email"}), 400

        data = database_utilities.execute_query(
            f"""select * from admins where email = %s""", (json_data['email'], ))
        if data:
            email = data[0]['email']
            access_token = create_access_token(identity=email)
            refresh_token = create_refresh_token(identity=email)

            resp = jsonify({"login": True})
            set_access_cookies(resp, access_token)
            set_refresh_cookies(resp, refresh_token)
            return resp
        else:
            return jsonify({"msg": "User is not an admin"})
// post [python]
    def post(self):
        """ Returns JWT upon login verification """
        json_data = request.get_json()
        if not json_data['email']:
            return jsonify({"msg": "Missing email"}), 400

        data = database_utilities.execute_query(
            f"""select * from admins where email = '{json_data['email']}'""")
        if data:
            email = data[0]['email']
            access_token = create_access_token(identity=email)
            refresh_token = create_refresh_token(identity=email)

            resp = jsonify({"login": True})
            set_access_cookies(resp, access_token)
            set_refresh_cookies(resp, refresh_token)
            return resp
        else:
            return jsonify({"msg": "User is not an admin"})
// add_day_data_row [python]
    def add_day_data_row(self, ts, data, prev_etotal):

        if data['power'] > 0:

            inv_serial = data['source']['serial_id']
            query = '''
               INSERT INTO DayData (
                   TimeStamp,
                   Serial,
                   Power,
                   TotalYield
               ) VALUES (
                   ?,
                   ?,
                   ?,
                   ?
               );
            '''
            self.c.execute(query, (ts, inv_serial, data['power'],  prev_etotal + data['energy']))
// add_day_data_row [python]
    def add_day_data_row(self, ts, data, prev_etotal):

        if data['power'] > 0:

            inv_serial = data['source']['serial_id']
            query = '''
               INSERT INTO DayData (
                   TimeStamp,
                   Serial,
                   Power,
                   TotalYield
               ) VALUES (
                   %s,
                   %s,
                   %s,
                   %s
               );
            ''' % (ts, inv_serial, data['power'],  prev_etotal + data['energy'])
            self.c.execute(query)
// store_metadata [python]
    def store_metadata(self, session, key, mType, value):
        if (self.idNormalizer is not None):
            id = self.idNormalizer.process_string(session, id)
        elif type(id) == unicode:
            id = id.encode('utf-8')
        else:
            id = str(id)
        self._openContainer(session)
        query = ("UPDATE %s SET %s = $1 WHERE identifier = $2;" %
                 (self.table, mType)
                 )
        args = (value, id)
        try:
            self._query(query, *args)
        except:
            return None
        return value
// store_metadata [python]
    def store_metadata(self, session, key, mType, value):
        if (self.idNormalizer is not None):
            id = self.idNormalizer.process_string(session, id)
        elif type(id) == unicode:
            id = id.encode('utf-8')
        else:
            id = str(id)
        self._openContainer(session)
        query = ("UPDATE %s SET %s = %r WHERE identifier = '%s';" %
                 (self.table, mType, value, id)
                 )
        try:
            self._query(query)
        except:
            return None
        return value
// get [python]
    def get(self, space_id):
        """ Fetch data for space with the corresponding space_id """
        return database_utilities.execute_query(
            f"""select * from spaces where space_id = %s""", (space_id, ))
// get [python]
    def get(self, space_id):
        """ Fetch data for space with the corresponding space_id """
        return database_utilities.execute_query(
            f"""select * from spaces where space_id = '{space_id}'""")
// check [python]
def check(current_num):
    try:
        cursor.execute('SELECT * FROM comics WHERE num=?', (current_num,))
    except sqlite3.OperationalError:
        cursor.execute('CREATE TABLE comics (num text)')
        return False
    else:
        return False if cursor.fetchone() is None else True
// check [python]
def check(current_num):
    try:
        cursor.execute('SELECT * FROM comics WHERE num="%s"' % current_num)
    except sqlite3.OperationalError:
        cursor.execute('CREATE TABLE comics (num text)')
        return False
    else:
        return False if cursor.fetchone() is None else True
// delete_crawl [python]
@app.route('/delete_crawl', methods=['POST'])
@is_logged_in
def delete_crawl():

        # Get Form Fields
        cid = request.form['cid']

        # Create cursor
        cur = mysql.connection.cursor()

        # Get user by username
        result = cur.execute("""DELETE FROM Crawls WHERE cid = %s""" (cid,))

        # Commit to DB
        mysql.connection.commit()

        # Close connection
        cur.close()

        # FIXME check if successfull first, return message
        flash('Crawl successfully removed', 'success')

        return redirect(url_for('dashboard'))
// delete_crawl [python]
@app.route('/delete_crawl', methods=['POST'])
@is_logged_in
def delete_crawl():

        # Get Form Fields
        cid = request.form['cid']

        # Create cursor
        cur = mysql.connection.cursor()

        # Get user by username
        result = cur.execute("DELETE FROM Crawls WHERE cid = %s" % cid)

        # Commit to DB
        mysql.connection.commit()

        # Close connection
        cur.close()

        # FIXME check if successfull first, return message
        flash('Crawl successfully removed', 'success')

        return redirect(url_for('dashboard'))
// add_movie [python]
@app.route('/movies/add', methods=['GET', 'POST'])
def add_movie():
    form = MovieForm()
    if not form.validate_on_submit():
        return render_template('new_movie.html', title='Add New Movie', form=form)
    lang_id = add_language(form.data['language'])
    movie = {
            'title': '',
            'description': '',
            'release_year': 0,
            'rental_duration': 0,
            'rental_rate': 0.00,
            'length': 0,
            'replacement_cost': 0.00
        }
    for k, v in movie.items():
        movie[k] = form.data[k]
    movie['language_id'] = movie.get('language_id', lang_id)
    cur.execute(
        """
        INSERT INTO film (title, description, release_year, language_id, rental_duration, rental_rate, length, replacement_cost)
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
        """, [(v, ) for k, v in movie.items()]
    )
    try:
        cur.execute("SELECT * FROM film where fulltext @@ to_tsquery(%s)", (movie['title'], ))
        res = cur.fetchall()
        conn.commit()
        return redirect(url_for('movies'))
    except Exception as e:
        return redirect(url_for('index'))
// add_movie [python]
@app.route('/movies/add', methods=['GET', 'POST'])
def add_movie():
    form = MovieForm()
    if not form.validate_on_submit():
        return render_template('new_movie.html', title='Add New Movie', form=form)
    lang_id = add_language(form.data['language'])
    movie = {
            'title': '',
            'description': '',
            'release_year': 0,
            'rental_duration': 0,
            'rental_rate': 0.00,
            'length': 0,
            'replacement_cost': 0.00
        }
    for k, v in movie.items():
        movie[k] = form.data[k]
    movie['language_id'] = movie.get('language_id', lang_id)
    cur.execute(
        """
        INSERT INTO film (title, description, release_year, language_id, rental_duration, rental_rate, length, replacement_cost)
        VALUES ('{}', '{}', {}, {}, {}, {}, {}, {})
        """.format(*[v for k, v in movie.items()])
    )
    try:
        cur.execute(f"SELECT * FROM film where fulltext @@ to_tsquery('Dark Knight')")
        res = cur.fetchall()
        conn.commit()
        return redirect(url_for('movies'))
    except Exception as e:
        return redirect(url_for('index'))
// new_category [python]
def new_category(category_name):
    try:
        conn = check_heroku_db()
        cur = conn.cursor()

        query = "INSERT INTO categories (cat_name) VALUES (%s);"
        data = (category_name,)
        cur.execute(query, data)

        conn.commit()
        conn.close()

    except psycopg2.DatabaseError as e:
        print('Error %s' % e)
        sys.exit(1)
// new_category [python]
def new_category(category_name):
    try:
        conn = check_heroku_db()
        cur = conn.cursor()
        cur.execute('''INSERT INTO categories (cat_name) VALUES (%s)''', (category_name,))
        conn.commit()
        conn.close()

    except psycopg2.DatabaseError as e:
        print('Error %s' % e)
        sys.exit(1)
// get_first_month [python]
def get_first_month(db, scene):
    sql = "select date from matches where scene='{scene}' order by date limit 1;"
    args = {'scene': scene}
    res = db.exec(sql, args)
    date = res[0][0]
    return date
// get_first_month [python]
def get_first_month(db, scene):
    sql = "select date from matches where scene='{}' order by date limit 1;".format(scene)
    res = db.exec(sql)
    date = res[0][0]
    return date
// getOptions [python]
def getOptions(poll_name):
    conn, c = connectDB()
    req = "SELECT options FROM {} WHERE name=?".format(CFG("poll_table_name"))
    options_str = queryOne(c, req, (poll_name,))
    if options_str == None:
        return None
    options = options_str.split(",")
    closeDB(conn)
    return options
// getOptions [python]
def getOptions(poll_name):
    conn, c = connectDB()
    options_str = queryOne(c, "SELECT options FROM {} WHERE name='{}'".format(CFG("poll_table_name"), poll_name))
    if options_str == None:
        return None
    options = options_str.split(",")
    closeDB(conn)
    return options
// retrieve_last_video_position [python]
def retrieve_last_video_position(playlist_id, db):
    db.execute(
        "SELECT max(position) as position from video WHERE playlist_id=%s;", (playlist_id,))
    row = db.fetchone()
    return row['position']
// retrieve_last_video_position [python]
def retrieve_last_video_position(playlist_id, db):
    db.execute("SELECT max(position) as position from video WHERE playlist_id={playlist_id};".format(
        playlist_id=playlist_id))
    row = db.fetchone()
    return row['position']
// view_page_history [python]
@app.route('/<page_name>/history')
def view_page_history(page_name):
    query = db.query("select page_content.timestamp, page_content.id from page, page_content where page.id = page_content.page_id and page.page_name = $1", page_name)
    page_histories = query.namedresult()

    return render_template(
        'page_history.html',
        page_name = page_name,
        page_histories = page_histories
    )
// view_page_history [python]
@app.route('/<page_name>/history')
def view_page_history(page_name):
    query = db.query("select page_content.timestamp, page_content.id from page, page_content where page.id = page_content.page_id and page.page_name = '%s'" % page_name)
    page_histories = query.namedresult()

    return render_template(
        'page_history.html',
        page_name = page_name,
        page_histories = page_histories
    )
// add_input [python]
    def add_input(self, data):
        connection = self.connects()
        try:
            # The following introduces a deliberate security flaw. See section on SQL injecton below
            query = "INSERT INTO crimes (description) VALUES (%s);"
            with connection.cursor() as cursor:
                cursor.execute(query, data)
                connection.commit()
        finally:
            connection.close()
// add_input [python]
    def add_input(self, data):
        connection = self.connects()
        try:
            # The following introduces a deliberate security flaw. See section on SQL injecton below
            query = "INSERT INTO crimes (description) VALUES ('{}');".format(
                data)
            with connection.cursor() as cursor:
                cursor.execute(query)
                connection.commit()
        finally:
            connection.close()
// get_top_author [python]
def get_top_author(top_num):
    """ query the top(top_num) popular author
        top_num => list of [author, count]
    """
    cmd = """SELECT authors.name,author_result.num
                    FROM authors JOIN
                    (SELECT SUM(article_result.num) as num,
                    article_result.author
                    from (SELECT articles.title, articles.author,
                    SUM(log.views) AS num
                    FROM articles
                    INNER JOIN (
                    SELECT path, count(path) AS views
                    FROM log GROUP BY log.path
                    ) AS log ON log.path = '/article/'
                    || articles.slug
                    GROUP BY articles.title, articles.author)
                    AS article_result
                    GROUP BY article_result.author) as author_result
                    ON authors.id = author_result.author
                    ORDER BY num DESC LIMIT %s"""
    data = [top_num, ]
    return execute_query(cmd, data)
// get_top_author [python]
def get_top_author(top_num):
    """ query the top(top_num) popular author
        top_num => list of [author, count]
    """
    cmd = """SELECT authors.name,author_result.num
                    FROM authors JOIN
                    (SELECT SUM(article_result.num) as num,
                    article_result.author
                    from (SELECT articles.title, articles.author,
                    SUM(log.views) AS num
                    FROM articles
                    INNER JOIN (
                    SELECT path, count(path) AS views
                    FROM log GROUP BY log.path
                    ) AS log ON log.path = '/article/'
                    || articles.slug
                    GROUP BY articles.title, articles.author)
                    AS article_result
                    GROUP BY article_result.author) as author_result
                    ON authors.id = author_result.author
                    ORDER BY num DESC LIMIT {}""".format(top_num)
    return execute_query(cmd)
// get_all_referrers [python]
@app.route('/get_all_referrers')
def get_all_referrers():
    account_id = request.args.get('account_id')

    if not isObject(account_id):
        ws.send('{"id":1, "method":"call", "params":[0,"lookup_account_names",[["' + account_id + '"], 0]]}')
        result_l = ws.recv()
        j_l = json.loads(result_l)

        account_id = j_l["result"][0]["id"]

    con = psycopg2.connect(**config.POSTGRES)
    cur = con.cursor()

    query = "select * from referrers where referrer=%s"
    cur.execute(query, (account_id,))
    results = cur.fetchall()

    return jsonify(results)
// get_all_referrers [python]
@app.route('/get_all_referrers')
def get_all_referrers():
    account_id = request.args.get('account_id')

    if not isObject(account_id):
        ws.send('{"id":1, "method":"call", "params":[0,"lookup_account_names",[["' + account_id + '"], 0]]}')
        result_l = ws.recv()
        j_l = json.loads(result_l)

        account_id = j_l["result"][0]["id"]

    con = psycopg2.connect(**config.POSTGRES)
    cur = con.cursor()

    query = "select * from referrers where referrer='"+account_id+"'"
    cur.execute(query)
    results = cur.fetchall()

    return jsonify(results)
// add_translationname [python]
    def add_translationname(self, trname):
        """Add new translation by item name for an item."""
        if self.connection:
            for item in self.find_item_name([trname[0], '0']):
                t = (item[0], trname[1], trname[2], )
                self.cursor.execute('insert into itemtranslation (itemid, itemlanguageid, translation) values (?, ?, ?)', t)
            self.connection.commit()
// add_translationname [python]
    def add_translationname(self, trname):
        """Add new translation by item name for an item."""
        if self.connection:
            for item in self.find_item_name([trname[0], '0']):
                self.cursor.execute('insert into itemtranslation (itemid, itemlanguageid, translation) values ("%s", "%s", "%s")' % (item[0], trname[1], trname[2]))
            self.connection.commit()
// get_max_task_id_for_project [python]
    @staticmethod
    def get_max_task_id_for_project(project_id: int):
        """Gets the nights task id currently in use on a project"""
        sql = """select max(id) from tasks where project_id = :project_id GROUP BY project_id"""
        result = db.engine.execute(text(sql), project_id=project_id)
        if result.rowcount == 0:
            raise NotFound()
        for row in result:
            return row[0]
// get_max_task_id_for_project [python]
    @staticmethod
    def get_max_task_id_for_project(project_id: int):
        """Gets the nights task id currently in use on a project"""
        sql = """select max(id) from tasks where project_id = {0} GROUP BY project_id""".format(project_id)
        result = db.engine.execute(sql)
        if result.rowcount == 0:
            raise NotFound()
        for row in result:
            return row[0]
// findNPC [python]
def findNPC(race, classe, sex,level):
	c, conn = getConnection()
	date = now()
	#select image, SUM(legit) as l FROM npc WHERE race='Elf' AND class='Bard' AND sex='Male' GROUP BY image HAVING l>5 ORDER BY SUM(legit) DESC;
	c.execute("select image, avg(legit) as l FROM npc WHERE race=(?) AND class=(?) AND sex=(?) GROUP BY image HAVING l > 5 ORDER BY SUM(legit) DESC",(race,classe,sex))
	conn.commit()
	out = c.fetchmany(5)
	conn.close()
	return out
// findNPC [python]
def findNPC(race, classe, sex,level):
	c, conn = getConnection()
	date = now()
	#select image, SUM(legit) as l FROM npc WHERE race='Elf' AND class='Bard' AND sex='Male' GROUP BY image HAVING l>5 ORDER BY SUM(legit) DESC;
	c.execute("select image, avg(legit) as l FROM npc WHERE race='"+race+"' AND class='"+classe+"' AND sex='"+sex+"' GROUP BY image HAVING l > 5 ORDER BY SUM(legit) DESC;")
	conn.commit()
	out = c.fetchmany(5)
	conn.close()
	return out
// edit [python]
@mod.route('/edit/<int:msg_id>', methods=['GET', 'POST'])
def edit(msg_id):
    m = None
    if request.method == 'GET':
        cursor.execute("SELECT * FROM message where msg_id = %s;", (msg_id,))
        m = cursor.fetchone()
        return render_template('message/edit.html', m=m, msg_id=msg_id)

    if request.method == 'POST':
        content = request.form['content']
        cursor.execute("UPDATE message SET content = %s where msg_id = %s;", (content, msg_id))
        conn.commit()
        flash('Edit Success!')
        return redirect(url_for('show_entries'))

    return render_template('message/edit.html', m=m, msg_id=msg_id)
// edit [python]
@mod.route('/edit/<int:msg_id>', methods=['GET', 'POST'])
def edit(msg_id):
    m = None
    if request.method == 'GET':
        sql = "SELECT * FROM message where msg_id = %d;" % (msg_id)
        cursor.execute(sql)
        m = cursor.fetchone()
        return render_template('message/edit.html', m=m, msg_id=msg_id)

    if request.method == 'POST':
        content = request.form['content']
        sql = "UPDATE message SET content = '%s' where msg_id = '%d';" \
            % (content, msg_id)
        cursor.execute(sql)
        conn.commit()
        flash('Edit Success!')
        return redirect(url_for('show_entries'))

    return render_template('message/edit.html', m=m, msg_id=msg_id)
// add_input [python]
    def add_input(self,data):
        connection = self.connect()

        try:
            query = "INSERT INTO crimes (description) VALUES (%s);"
            with connection.cursor() as cursor:
                cursor.execute(query,data)
                connection.commit()
        finally:
            connection.close()
// add_input [python]
    def add_input(self,data):
        connection = self.connect()

        try:
            query = "INSERT INTO crimes (description) VALUES ('{}');".format(data)
            with connection.cursor() as cursor:
                cursor.execute(query)
                connection.commit()
        finally:
            connection.close()
// fetch_resultSet [python]
    def fetch_resultSet(self, session, id):
        self._openContainer(session)

        sid = str(id)
        if (self.idNormalizer is not None):
            sid = self.idNormalizer.process_string(session, sid)
        query = ("SELECT class, data FROM %s WHERE identifier = $1;" %
                 (self.table)
                 )
        res = self._query(query, sid)
        try:
            rdict = res.dictresult()[0]
        except IndexError:
            raise ObjectDoesNotExistException('%s/%s' % (self.id, sid))

        data = rdict['data']
        try:
            ndata = pg.unescape_bytea(data)
        except:
            # Insufficient PyGreSQL version
            ndata = data.replace("\\'", "'")

        ndata = ndata.replace('\\000', '\x00')
        ndata = ndata.replace('\\012', '\n')
        # data is res.dictresult()
        cl = rdict['class']
        rset = dynamic.buildObject(session, cl, [[]])
        rset.deserialize(session, ndata)
        rset.id = id

        # Update expires
        now = time.time()
        nowStr = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(now))
        expires = now + self.get_default(session, 'expires', 600)
        rset.timeExpires = expires
        expiresStr = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(expires))

        query = ("UPDATE %s SET timeAccessed = $1, expires = $2 "
                 "WHERE identifier = $3;" % (self.table)
                 )
        self._query(query, nowStr, expiresStr, sid)
        return rset
// fetch_resultSet [python]
    def fetch_resultSet(self, session, id):
        self._openContainer(session)

        sid = str(id)
        if (self.idNormalizer is not None):
            sid = self.idNormalizer.process_string(session, sid)
        query = ("SELECT class, data FROM %s WHERE identifier = '%s';" %
                 (self.table, sid)
                 )
        res = self._query(query)
        try:
            rdict = res.dictresult()[0]
        except IndexError:
            raise ObjectDoesNotExistException('%s/%s' % (self.id, sid))

        data = rdict['data']
        try:
            ndata = pg.unescape_bytea(data)
        except:
            # Insufficient PyGreSQL version
            ndata = data.replace("\\'", "'")

        ndata = ndata.replace('\\000', '\x00')
        ndata = ndata.replace('\\012', '\n')
        # data is res.dictresult()
        cl = rdict['class']
        rset = dynamic.buildObject(session, cl, [[]])
        rset.deserialize(session, ndata)
        rset.id = id

        # Update expires
        now = time.time()
        nowStr = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(now))
        expires = now + self.get_default(session, 'expires', 600)
        rset.timeExpires = expires
        expiresStr = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(expires))

        query = ("UPDATE %s SET timeAccessed = '%s', expires = '%s' "
                 "WHERE identifier = '%s';" %
                 (self.table, nowStr, expiresStr, sid)
                 )
        self._query(query)
        return rset