jiahuimbzuai/CoQuIR huggingface dataset:
// fetch_data [python]
    def fetch_data(self, session, id):
        self._openContainer(session)
        sid = str(id)
        if (self.idNormalizer is not None):
            sid = self.idNormalizer.process_string(session, sid)
        query = ("SELECT data FROM %s WHERE identifier = $1;" %
                 (self.table)
                 )
        res = self._query(query, sid)
        try:
            data = res.dictresult()[0]['data']
        except IndexError:
            raise ObjectDoesNotExistException(id)
        try:
            ndata = pg.unescape_bytea(data)
        except:
            # insufficient PyGreSQL version
            ndata = data.replace("\\'", "'")

        ndata = ndata.replace('\\000\\001', nonTextToken)
        ndata = ndata.replace('\\012', '\n')
        return ndata
// fetch_data [python]
    def fetch_data(self, session, id):
        self._openContainer(session)
        sid = str(id)
        if (self.idNormalizer is not None):
            sid = self.idNormalizer.process_string(session, sid)
        query = ("SELECT data FROM %s WHERE identifier = '%s';" %
                 (self.table, sid)
                 )
        res = self._query(query)
        try:
            data = res.dictresult()[0]['data']
        except IndexError:
            raise ObjectDoesNotExistException(id)
        try:
            ndata = pg.unescape_bytea(data)
        except:
            # insufficient PyGreSQL version
            ndata = data.replace("\\'", "'")

        ndata = ndata.replace('\\000\\001', nonTextToken)
        ndata = ndata.replace('\\012', '\n')
        return ndata
// registerPlayer [python]
def registerPlayer(name):
    """Adds a player to the tournament database.

    The database assigns a unique serial id number for the player.  (This
    should be handled by your SQL database schema, not in your Python code.)

    Args:
      name: the player's full name (need not be unique).
    """
    conn = connect()
    cursor = conn.cursor()
    query = "INSERT INTO players (name) VALUES (%s);"
    cursor.execute(query, (name,))
    conn.commit()
    conn.close()
// registerPlayer [python]
def registerPlayer(name):
    """Adds a player to the tournament database.

    The database assigns a unique serial id number for the player.  (This
    should be handled by your SQL database schema, not in your Python code.)

    Args:
      name: the player's full name (need not be unique).
    """
    conn = connect()
    cursor = conn.cursor()
    cursor.execute("INSERT INTO players (name) VALUES ('%s')" % (name,));
    conn.commit()
    conn.close()
// register [python]
@mod.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        error = None
        email = request.form['email'].strip()
        nickname = request.form['nickname'].strip()
        password = request.form['password'].strip()
        password2 = request.form['password2'].strip()

        email = email.lower()

        if email == "" or nickname == "" or password == "" or password2 == "":
            error = 'Please input all the information'
        elif password2 != password:
            error = 'The password is not repeated correctly'
        elif len(password) < 6:
            error = 'The password has at least 6 characters'
        elif not re.match(r'^[0-9a-zA-Z_]{0,19}@' +
                          '[0-9a-zA-Z]{1,15}\.[com,cn,net]', email):
            error = 'Please input the right email'

        cursor.execute("SELECT * FROM users where email = %s;", (email,))
        u = cursor.fetchone()

        if u is not None:
            error = 'The email has already exsit'

        if error is not None:
            return render_template('register.html', error=error)
        else:
            password = bcrypt.generate_password_hash(password)
            cursor.execute("INSERT INTO users(email,nickname,password) VALUES(%s,%s,%s);", (email, nickname, password))
            conn.commit()
            flash('Register Success!')
            return redirect(url_for('users.login'))

    return render_template('register.html')
// register [python]
@mod.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        error = None
        email = request.form['email'].strip()
        nickname = request.form['nickname'].strip()
        password = request.form['password'].strip()
        password2 = request.form['password2'].strip()

        email = email.lower()

        if email == "" or nickname == "" or password == "" or password2 == "":
            error = 'Please input all the information'
        elif password2 != password:
            error = 'The password is not repeated correctly'
        elif len(password) < 6:
            error = 'The password has at least 6 characters'
        elif not re.match(r'^[0-9a-zA-Z_]{0,19}@' +
                          '[0-9a-zA-Z]{1,15}\.[com,cn,net]', email):
            error = 'Please input the right email'

        sql = "SELECT * FROM users where email = '%s';" % (email)
        cursor.execute(sql)
        u = cursor.fetchone()

        if u is not None:
            error = 'The email has already exsit'

        if error is not None:
            return render_template('register.html', error=error)
        else:
            password = bcrypt.generate_password_hash(password)
            cursor.execute("INSERT INTO users(email,nickname,password) VALUES(%s,%s,%s);", (email, nickname, password))
            conn.commit()
            flash('Register Success!')
            return redirect(url_for('users.login'))

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


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


    if "user" not in form or "game" not in form:
        raise FormError("Invalid parameters.")
    if "pos" not in form and "resign" not in form:
        raise FormError("Invalid parameters.")

    game = int(form["game"].value)


    (players,size,state) = get_game_info(conn, game)

    user = form["user"].value
    if user not in players:
        raise FormError("Invalid player ID - player is not part of this game")


    if "resign" in form:
        resign = True
    else:
        resign = False
        pos = form["pos"].value.split(",")
        assert len(pos) == 2
        x = int(pos[0])
        y = int(pos[1])


    (board,nextPlayer,letter) = build_board(conn, game,size)

    if user != players[nextPlayer]:
        raise FormError("Internal error, incorrect player is attempting to move.")


    if resign:
        # this user is choosing to resign.  Update the game state to reflect that.
        other_player_name = players[1-nextPlayer]

        cursor = conn.cursor()
        cursor.execute("""UPDATE games SET state="%s:resignation" WHERE id=%d;""", (other_player_name,game))
        cursor.close()

    else:
        assert x >= 0 and x < size
        assert y >= 0 and y < size

        assert board[x][y] == ""
        board[x][y] = "XO"[nextPlayer]

        # we've done all of our sanity checks.  We now know enough to say that
        # it's safe to add a new move.
        cursor = conn.cursor()
        cursor.execute("""INSERT INTO moves(gameID,x,y,letter,time) VALUES(%d,%d,%d,"%s",NOW());""", (game,x,y,letter))

        if cursor.rowcount != 1:
            raise FormError("Could not make move, reason unknown.")

        cursor.close()

        result = analyze_board(board)
        if result != "":
            if result == "win":
                result = players[nextPlayer]+":win"

            cursor = conn.cursor()
            cursor.execute("""UPDATE games SET state="%s" WHERE id=%d;""", (result,game))
            cursor.close()

    # we've made changes, make sure to commit them!
    conn.commit()
    conn.close()


    # return the parms to the caller, so that they can build a good redirect
    return (user,game)
// process_form [python]
def process_form():
    # see https://docs.python.org/3.4/library/cgi.html for the basic usage
    # here.
    form = cgi.FieldStorage()


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


    if "user" not in form or "game" not in form:
        raise FormError("Invalid parameters.")
    if "pos" not in form and "resign" not in form:
        raise FormError("Invalid parameters.")

    game = int(form["game"].value)


    (players,size,state) = get_game_info(conn, game)

    user = form["user"].value
    if user not in players:
        raise FormError("Invalid player ID - player is not part of this game")


    if "resign" in form:
        resign = True
    else:
        resign = False
        pos = form["pos"].value.split(",")
        assert len(pos) == 2
        x = int(pos[0])
        y = int(pos[1])


    (board,nextPlayer,letter) = build_board(conn, game,size)

    if user != players[nextPlayer]:
        raise FormError("Internal error, incorrect player is attempting to move.")


    if resign:
        # this user is choosing to resign.  Update the game state to reflect that.
        other_player_name = players[1-nextPlayer]

        cursor = conn.cursor()
        cursor.execute("""UPDATE games SET state="%s:resignation" WHERE id=%d;""" % (other_player_name,game))
        cursor.close()

    else:
        assert x >= 0 and x < size
        assert y >= 0 and y < size

        assert board[x][y] == ""
        board[x][y] = "XO"[nextPlayer]

        # we've done all of our sanity checks.  We now know enough to say that
        # it's safe to add a new move.
        cursor = conn.cursor()
        cursor.execute("""INSERT INTO moves(gameID,x,y,letter,time) VALUES(%d,%d,%d,"%s",NOW());""" % (game,x,y,letter))

        if cursor.rowcount != 1:
            raise FormError("Could not make move, reason unknown.")

        cursor.close()

        result = analyze_board(board)
        if result != "":
            if result == "win":
                result = players[nextPlayer]+":win"

            cursor = conn.cursor()
            cursor.execute("""UPDATE games SET state="%s" WHERE id=%d;""" % (result,game))
            cursor.close()

    # we've made changes, make sure to commit them!
    conn.commit()
    conn.close()


    # return the parms to the caller, so that they can build a good redirect
    return (user,game)
// load_user [python]
@login_manager.user_loader
def load_user(s_id):
    email = str(s_id)
    query = 'select * from usr where email like %s'
    cursor = g.conn.execute(query, (email, ))
    user = User()
    for row in cursor:
        user.name = str(row.name)
        user.email = str(row.email)
        break
    return user
// load_user [python]
@login_manager.user_loader
def load_user(s_id):
    email = str(s_id)
    query = '''select * from usr where email like\'''' + email + '\''
    cursor = g.conn.execute(query)
    user = User()
    for row in cursor:
        user.name = str(row.name)
        user.email = str(row.email)
        break
    return user
// delete [python]
@mod.route('/delete/<int:cmt_id>', methods=['GET', 'POST'])
def delete(cmt_id):
    if request.method == 'GET':
        cursor.execute("SELECT msg_id FROM comment where cmt_id = %s;", (cmt_id,))
        m = cursor.fetchone()
        cursor.execute("DELETE FROM comment where cmt_id = %s;", (cmt_id,))
        conn.commit()
        flash('Delete Success!')
    return redirect(url_for('comment.show', msg_id=m[0]))
// delete [python]
@mod.route('/delete/<int:cmt_id>', methods=['GET', 'POST'])
def delete(cmt_id):
    if request.method == 'GET':
        sql = "SELECT msg_id FROM comment where cmt_id = %d;" % (cmt_id)
        cursor.execute(sql)
        m = cursor.fetchone()
        sql = "DELETE FROM comment where cmt_id = '%d';" % (cmt_id)
        cursor.execute(sql)
        conn.commit()
        flash('Delete Success!')
    return redirect(url_for('comment.show', msg_id=m[0]))
// get_markets [python]
@app.route('/get_markets')
def get_markets():
    asset_id = request.args.get('asset_id')

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


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

    query = "SELECT * FROM markets WHERE aid=%s"
    cur.execute(query, (asset_id,))
    results = cur.fetchall()
    con.close()
    return jsonify(results)
// get_markets [python]
@app.route('/get_markets')
def get_markets():
    asset_id = request.args.get('asset_id')

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


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

    query = "SELECT * FROM markets WHERE aid='"+asset_id+"'"
    cur.execute(query)
    results = cur.fetchall()
    con.close()
    return jsonify(results)
// get_secrets [python]
	def get_secrets(self, from_date_added=0):
		secrets = []
		for row in self.cursor.execute('SELECT encrypted, json_id, date_added FROM secret WHERE date_added > ? ORDER BY date_added DESC', (from_date_added,)):
			aes_key, json_id, date_added = cryptlib.eciesDecrypt(row[0], self.privkey), row[1], row[2]
			if aes_key != None:
				secrets.append([aes_key, json_id])
			from_date_added = max(from_date_added, date_added)
		return (secrets, from_date_added)
// get_secrets [python]
	def get_secrets(self, from_date_added=0):
		secrets = []
		for row in self.cursor.execute('SELECT encrypted, json_id, date_added FROM secret WHERE date_added > %s ORDER BY date_added DESC' % from_date_added):
			aes_key, json_id, date_added = cryptlib.eciesDecrypt(row[0], self.privkey), row[1], row[2]
			if aes_key != None:
				secrets.append([aes_key, json_id])
			from_date_added = max(from_date_added, date_added)
		return (secrets, from_date_added)
// add_consumption_data_row [python]
    def add_consumption_data_row(self, ts, energy_used, power_used):

        if power_used > 0:

            query = '''
                INSERT OR IGNORE INTO Consumption (
                    TimeStamp,
                    EnergyUsed,
                    PowerUsed                                
                ) VALUES (
                    ?,
                    ?,
                    ?
                );
            '''
            self.c.execute(query, (ts, 0, 0))

            query = '''
                UPDATE Consumption SET 
                EnergyUsed = EnergyUsed + ?,
                PowerUsed = PowerUsed + ?
                WHERE TimeStamp=?;
            '''

            self.c.execute(query, (energy_used, power_used, ts))

            self.db.commit()
// add_consumption_data_row [python]
    def add_consumption_data_row(self, ts, energy_used, power_used):

        if power_used > 0:

            query = '''
                INSERT OR IGNORE INTO Consumption (
                    TimeStamp,
                    EnergyUsed,
                    PowerUsed                                
                ) VALUES (
                    %s,
                    %s,
                    %s
                );
            ''' % (ts, 0, 0)
            self.c.execute(query)

            query = '''
                UPDATE Consumption SET 
                EnergyUsed = EnergyUsed + %s,
                PowerUsed = PowerUsed + %s
                WHERE TimeStamp = %s;
            ''' % (energy_used, power_used, ts)

            self.c.execute(query)

            self.db.commit()
// lookup_assets [python]
@app.route('/lookup_assets')
def lookup_assets():
    start = request.args.get('start')

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

    query = "SELECT aname FROM assets WHERE aname LIKE %s"
    cur.execute(query, (start+'%',))
    results = cur.fetchall()
    con.close()
    return jsonify(results)
// lookup_assets [python]
@app.route('/lookup_assets')
def lookup_assets():
    start = request.args.get('start')

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

    query = "SELECT aname FROM assets WHERE aname LIKE '"+start+"%'"
    cur.execute(query)
    results = cur.fetchall()
    con.close()
    return jsonify(results)
// set_state [python]
def set_state(chat_id, value):
    settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\settings.db")
    conn = settings.cursor()
    conn.execute("update users set state = ? where chat_id = ?", (str(value), str(chat_id)))
    settings.commit()
    settings.close()
// set_state [python]
def set_state(chat_id, value):
    settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\settings.db")
    conn = settings.cursor()
    conn.execute("update users set state ='" + str(value) + "' where chat_id = '" + str(chat_id) + "'")
    settings.commit()
    settings.close()
// _get_degree_2 [python]
def _get_degree_2(user_id, cnx):
    """Get all users of degree 2 follow that are not currently followed.
    Example:
        this user (follows) user B (follows) user B
        AND user (does NOT follow) user B
        means that user B will be in the list
    Args:
        user_id (int): id of user
        cnx: DB connection
    Returns:
        list: list of user_ids
    """
    sql = 'WITH tmp_suggest (followed_id) AS ' \
    '(' \
        'SELECT b.followed_id AS followed_id ' \
        'FROM ' \
            'tbl_follow a INNER JOIN tbl_follow b ' \
            'ON a.followed_id = b.follower_id ' \
        'WHERE a.follower_id = %s ' \
        'AND b.followed_id NOT IN ' \
            '(SELECT followed_id FROM tbl_follow WHERE follower_id = %s) ' \
        'AND b.followed_id != %s ' \
    ') ' \
    'SELECT followed_id, COUNT(*) AS num_mutual FROM tmp_suggest ' \
    'GROUP BY followed_id ' \
    'ORDER BY num_mutual DESC'
    with cnx.cursor() as cursor:
        cursor.execute(sql, (user_id, user_id, user_id))
        res = cursor.fetchall()
    return list(map(lambda x: x[0], res))
// _get_degree_2 [python]
def _get_degree_2(user_id, cnx):
    """Get all users of degree 2 follow that are not currently followed.
    Example:
        this user (follows) user B (follows) user B
        AND user (does NOT follow) user B
        means that user B will be in the list
    Args:
        user_id (int): id of user
        cnx: DB connection
    Returns:
        list: list of user_ids
    """
    sql = 'WITH tmp_suggest (followed_id) AS ' \
    '(' \
        'SELECT b.followed_id AS followed_id ' \
        'FROM ' \
            'tbl_follow a INNER JOIN tbl_follow b ' \
            'ON a.followed_id = b.follower_id ' \
        'WHERE a.follower_id = %s ' \
        'AND b.followed_id NOT IN ' \
            '(SELECT followed_id FROM tbl_follow WHERE follower_id = %s) ' \
        'AND b.followed_id != %s ' \
    ') ' \
    'SELECT followed_id, COUNT(*) AS num_mutual FROM tmp_suggest ' \
    'GROUP BY followed_id ' \
    'ORDER BY num_mutual DESC' % (user_id, user_id, user_id)
    with cnx.cursor() as cursor:
        cursor.execute(sql)
        res = cursor.fetchall()
    return list(map(lambda x: x[0], res))
// get_tournaments_during_month [python]
def get_tournaments_during_month(db, scene, date):
    y, m, d = date.split('-')
    ym_date = '{}-{}'.format(y, m)
    sql = "select url, date from matches where scene='{scene}' and date like '%{date}%' group by url, date order by date"
    args = {'scene': scene, 'date': ym_date}
    res = db.exec(sql, args)
    urls = [r[0] for r in res]
    return urls
// get_tournaments_during_month [python]
def get_tournaments_during_month(db, scene, date):
    y, m, d = date.split('-')
    ym_date = '{}-{}'.format(y, m)
    sql = "select url, date from matches where scene='{}' and date like '%{}%' group by url, date order by date".format(scene, ym_date)
    res = db.exec(sql)
    urls = [r[0] for r in res]
    return urls
// add_input [python]
    def add_input(self,data):
        connection = self.connect()
        try:
            # The following is a flaw
            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 is a flaw
            query = "INSERT INTO crimes(description) VALUES ('{}');".format(data)
            with connection.cursor() as cursor:
                cursor.execute(query)
                connection.commit()
        finally:
            connection.close()
// get_error_days [python]
def get_error_days(cur, error_percent):
    """Fetches the days in which requests led to errors.

    Fetches the days in which the specified percentage
    of requests led to errors.

    Args:
        cur(obj): The cursor to execute the query.
        error_percent(int): The percentage of requests that led to errors.

    Return:
        True if success, False otherwise.
    """
    data = (error_percent, )
    query = '''SELECT to_char(log_errors.date, 'Mon DD YYYY'),
            round((log_errors.errors * 100
            / log_requests.total::numeric), 2) as percent
            FROM log_errors, log_requests
            WHERE log_errors.date = log_requests.date AND
            log_errors.errors * 100
            / log_requests.total::numeric > %s
            ORDER BY log_errors.date'''
    rows = get_data(cur, query, data)

    # Write data to txt file.
    if rows is not None:
        file = open("error_report.txt", "w")
        for row in rows:
            file.write("{} - {}% errors \n".format(row[0], row[1]))
        file.close()

        return True
    else:
        return False
// get_error_days [python]
def get_error_days(cur, error_percent):
    """Fetches the days in which requests led to errors.

    Fetches the days in which the specified percentage
    of requests led to errors.

    Args:
        cur(obj): The cursor to execute the query.
        error_percent(int): The percentage of requests that led to errors.

    Return:
        True if success, False otherwise.
    """
    query = '''SELECT to_char(log_errors.date, 'Mon DD YYYY'),
            round((log_errors.errors * 100
            / log_requests.total::numeric), 2) as percent
            FROM log_errors, log_requests
            WHERE log_errors.date = log_requests.date AND
            log_errors.errors * 100
            / log_requests.total::numeric > {}
            ORDER BY log_errors.date'''.format(error_percent)
    rows = get_data(cur, query)

    # Write data to txt file.
    if rows is not None:
        file = open("error_report.txt", "w")
        for row in rows:
            file.write("{} - {}% errors \n".format(row[0], row[1]))
        file.close()

        return True
    else:
        return False
// all_deposits [python]
    def all_deposits(self,coin):
        sql = "SELECT * FROM deposits WHERE coin='%s'"
        self.cursor.execute(sql, (coin,))
        return self.cursor.fetchall()
// all_deposits [python]
    def all_deposits(self,coin):
        sql = "SELECT * FROM deposits WHERE coin='%s'" % coin
        self.cursor.execute(sql)
        return self.cursor.fetchall()
// get_user [python]
    def get_user(self):
        if not hasattr(self, '_user'):
            qs = "select * from account_access where access_token = %s"
            result = self.db.get(qs, self.access_token)
            if result:
                self._user = result
            else:
                self._user = None
        
        return self._user
// get_user [python]
    def get_user(self):
        if not hasattr(self, '_user'):
            qs = "select * from account_access where access_token = '%s'" % self.access_token
            result = self.db.get(qs)
            if result:
                self._user = result
            else:
                self._user = None
        
        return self._user
// compare_and_update [python]
    @staticmethod
    def compare_and_update(user, message):
        """
        This method compare a user object from the bot and his info from
        the Telegram message to check whether a user has changed his bio
        or not. If yes, the user object that represents him in the bot will
        be updated accordingly. Now this function is called only when a user
        asks the bot for showing the most popular cams

        :param user: user object that represents a Telegram user in this bot
        :param message: object from Telegram that contains info about user's
        message and about himself
        :return: None
        """

        log.info('Checking whether user have changed his info or not...')
        msg = message.from_user
        usr_from_message = User(message.chat.id, msg.first_name, msg.username,
                                msg.last_name)

        if user.chat_id != usr_from_message.chat_id:
            log.error("Wrong user to compare!")
            return

        if user.first_name != usr_from_message.first_name:
            user.first_name = usr_from_message.first_name

        elif user.nickname != usr_from_message.nickname:
            user.nickname = usr_from_message.nickname

        elif user.last_name != usr_from_message.last_name:
            user.last_name = usr_from_message.last_name

        else:
            log.debug("User's info hasn't changed")
            return

        log.info("User has changed his info")
        log.debug("Updating user's info in the database...")
        query = (f"UPDATE users "
                 f"SET first_name=%s, "
                 f"nickname=%s, "
                 f"last_name=%s "
                 f"WHERE chat_id=%s")

        parameters = (user.first_name, user.nickname, user.last_name,
                      user.chat_id)

        try:
            db.add(query, parameters)
        except DatabaseError:
            log.error("Could not update info about %s in the database",
                      user)
        else:
            log.debug("User's info has been updated")
// compare_and_update [python]
    @staticmethod
    def compare_and_update(user, message):
        """
        This method compare a user object from the bot and his info from
        the Telegram message to check whether a user has changed his bio
        or not. If yes, the user object that represents him in the bot will
        be updated accordingly. Now this function is called only when a user
        asks the bot for showing the most popular cams

        :param user: user object that represents a Telegram user in this bot
        :param message: object from Telegram that contains info about user's
        message and about himself
        :return: None
        """

        log.info('Checking whether user have changed his info or not...')
        msg = message.from_user
        usr_from_message = User(message.chat.id, msg.first_name, msg.username,
                                msg.last_name)

        if user.chat_id != usr_from_message.chat_id:
            log.error("Wrong user to compare!")
            return

        if user.first_name != usr_from_message.first_name:
            user.first_name = usr_from_message.first_name

        elif user.nickname != usr_from_message.nickname:
            user.nickname = usr_from_message.nickname

        elif user.last_name != usr_from_message.last_name:
            user.last_name = usr_from_message.last_name

        else:
            log.debug("User's info hasn't changed")
            return

        log.info("User has changed his info")
        log.debug("Updating user's info in the database...")
        query = (f"UPDATE users "
                 f"SET first_name='{user.first_name}', "
                 f"nickname='{user.nickname}', "
                 f"last_name='{user.last_name}' "
                 f"WHERE chat_id={user.chat_id}")

        try:
            db.add(query)
        except DatabaseError:
            log.error("Could not update info about %s in the database",
                      user)
        else:
            log.debug("User's info has been updated")
// GameNewPlayed [python]
def GameNewPlayed(Played, ID):
	db.execute("UPDATE games set GamesPlayed = ? WHERE ID = ?", Played, ID)
	database.commit()
// GameNewPlayed [python]
def GameNewPlayed(Played, ID):
	db.execute("UPDATE games set GamesPlayed = %i WHERE ID = %i" % (Played, ID))
	database.commit()
// insertNPC [python]
def insertNPC(name, race,classe,sex,level,image,legit):
	c, conn = getConnection()
	date = now()
	c.execute("INSERT INTO npc VALUES (?,?,?,?,?,?,?,?)",(date,str(name),race,classe,sex,str(level),image,str(legit)))
	conn.commit()
	conn.close()
// insertNPC [python]
def insertNPC(name, race,classe,sex,level,image,legit):
	c, conn = getConnection()
	date = now()
	c.execute("INSERT INTO npc VALUES ('"+date+"','"+str(name)+"','"+race+"','"+classe+"','"+sex+"','"+str(level)+"','"+image+"','"+str(legit)+"')")
	conn.commit()
	conn.close()
// get [python]
    def get(self, user_id):
        """ Fetch data for user with corresponding user_id """
        return database_utilities.execute_query(f"""select * from users where user_id = %s""", (user_id, ))
// get [python]
    def get(self, user_id):
        """ Fetch data for user with corresponding user_id """
        return database_utilities.execute_query(f"""select * from users where user_id = '{user_id}'""")
// h2h [python]
@endpoints.route("/h2h")
def h2h():
    if db == None:
        init()

    player1 = request.args.get('tag1', default="christmasmike")
    player2 = request.args.get('tag2', default="christmasmike")
    sql = "SELECT * FROM matches WHERE (player1 = '{player1}' OR "\
            +"player2 = '{player1}') AND (player1 = '{player2}' OR "\
            +"player2 = '{player2}') ORDER BY date DESC;"
    args = {'player1': player1, 'player2': player2}
    result = db.exec(sql, args)
    return json.dumps(result)
// h2h [python]
@endpoints.route("/h2h")
def h2h():
    if db == None:
        init()

    player1 = request.args.get('tag1', default="christmasmike")
    player2 = request.args.get('tag2', default="christmasmike")
    sql = "SELECT * FROM matches WHERE (player1 = '"+str(player1)+"' OR "\
            +"player2 = '"+str(player1)+"') AND (player1 = '"+str(player2)+"' OR "\
            +"player2 = '"+str(player2)+"') ORDER BY date DESC;"
    result = db.exec(sql)
    return json.dumps(result)
// insertData [python]
    def insertData(self,userid,post):
        sqlText="insert into post(userid,date,comment) \
                values(%s,current_timestamp(0),%s);"
        params=[userid,post];
        result=sql.insertDB(self.conn,sqlText,params)
        return result;
// insertData [python]
    def insertData(self,userid,post):
        sqlText="insert into post(userid,date,comment) \
                values(%d,current_timestamp(0),'%s');"%(userid,post);
        result=sql.insertDB(self.conn,sqlText)
        return result;
// get_requested_month_for_inverter [python]
    def get_requested_month_for_inverter(self, inverter_serial, date):
        data = dict()

        month_start, month_end = self.get_epoch_month(date)
        data['interval'] = {'from': self.convert_local_ts_to_utc(month_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(month_end, self.local_timezone)}
        month_total = 0

        query = '''
            SELECT TimeStamp, DayYield AS Power 
            FROM MonthData 
            WHERE TimeStamp BETWEEN ? AND ? AND Serial=?;
            '''

        data['data'] = list()
        for row in self.c.execute(query, (month_start, month_end, inverter_serial)):
            data['data'].append({'time': self.convert_local_ts_to_utc(row[0], self.local_timezone), 'power': row[1]})
            month_total += row[1]

        data['total'] = month_total

        query = '''
            SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max 
            FROM MonthData 
            WHERE Serial=?;
            '''

        self.c.execute(query, (inverter_serial,))
        first_data, last_data = self.c.fetchone()

        if first_data: data['hasPrevious'] = (first_data < month_start)
        else: data['hasPrevious'] = False
        if last_data: data['hasNext'] = (last_data > month_end)
        else: data['hasNext'] = False

        return data
// get_requested_month_for_inverter [python]
    def get_requested_month_for_inverter(self, inverter_serial, date):
        data = dict()

        month_start, month_end = self.get_epoch_month(date)
        data['interval'] = {'from': self.convert_local_ts_to_utc(month_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(month_end, self.local_timezone)}
        month_total = 0

        query = '''
            SELECT TimeStamp, DayYield AS Power 
            FROM MonthData 
            WHERE TimeStamp BETWEEN %s AND %s AND Serial = %s
            '''

        data['data'] = list()
        for row in self.c.execute(query % (month_start, month_end, inverter_serial)):
            data['data'].append({'time': self.convert_local_ts_to_utc(row[0], self.local_timezone), 'power': row[1]})
            month_total += row[1]

        data['total'] = month_total

        query = '''
            SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max 
            FROM MonthData 
            WHERE Serial = %s;
            ''' % inverter_serial

        self.c.execute(query)
        first_data, last_data = self.c.fetchone()

        if first_data: data['hasPrevious'] = (first_data < month_start)
        else: data['hasPrevious'] = False
        if last_data: data['hasNext'] = (last_data > month_end)
        else: data['hasNext'] = False

        return data
// delete_resultSet [python]
    def delete_resultSet(self, session, id):
        self._openContainer(session)
        sid = str(id)
        if (self.idNormalizer is not None):
            sid = self.idNormalizer.process_string(session, sid)
        query = "DELETE FROM %s WHERE identifier = $1;" % (self.table)
        self._query(query, sid)
// delete_resultSet [python]
    def delete_resultSet(self, session, id):
        self._openContainer(session)
        sid = str(id)
        if (self.idNormalizer is not None):
            sid = self.idNormalizer.process_string(session, sid)
        query = "DELETE FROM %s WHERE identifier = '%s';" % (self.table, sid)
        self._query(query)
// getSeriesDateFromDatabase [python]
def getSeriesDateFromDatabase(submission):
    database = sqlite3.connect('database.db')
    cursor = database.cursor()
    return cursor.execute("SELECT StartDate FROM SeriesTracking WHERE SeriesTitle = ?", [getTitle(submission)]).fetchone()[0]
    database.close()
// getSeriesDateFromDatabase [python]
def getSeriesDateFromDatabase(submission):
    database = sqlite3.connect('database.db')
    cursor = database.cursor()
    return cursor.execute("SELECT StartDate FROM SeriesTracking WHERE SeriesTitle = '" + str(getTitle(submission)) + "'").fetchone()[0]
    database.close()
// karma_add [python]
def karma_add(name):
    karma = karma_ask(name)
    db = db_connect()
    cursor = db.cursor()
    if karma is None:
        try:
            cursor.execute('''
                INSERT INTO people(name,karma,shame) VALUES(%(name)s,1,0)
                ''', name)
            db.commit()
            logger.debug('Inserted into karmadb 1 karma for {}'.format(name))
            return 1
        except Exception as e:
            logger.error('Execution failed with error: {}'.format(e))
            raise
    else:
        karma = karma + 1
        try:
            cursor.execute('''
                UPDATE people SET karma = %(karma)s WHERE name = %(name)s
                ''', (karma, name))
            db.commit()
            logger.debug('Inserted into karmadb {} karma for {}'.format(
                karma,
                name,
            ))
            return karma

        except Exception as e:
            logger.error('Execution failed with error: {}'.format(e))
            raise
    db.close()
// karma_add [python]
def karma_add(name):
    karma = karma_ask(name)
    db = db_connect()
    cursor = db.cursor()
    if karma is None:
        try:
            cursor.execute('''
                INSERT INTO people(name,karma,shame) VALUES('{}',1,0)
                '''.format(name))
            db.commit()
            logger.debug('Inserted into karmadb 1 karma for {}'.format(name))
            return 1
        except Exception as e:
            logger.error('Execution failed with error: {}'.format(e))
            raise
    else:
        karma = karma + 1
        try:
            cursor.execute('''
                UPDATE people SET karma = {0} WHERE name = '{1}'
                '''.format(karma, name))
            db.commit()
            logger.debug('Inserted into karmadb {} karma for {}'.format(
                karma, name))
            return karma

        except Exception as e:
            logger.error('Execution failed with error: {}'.format(e))
            raise
    db.close()
// update_date_modified [python]
  def update_date_modified(self):
    quote_tuple = CURRENT_DATESTAMP, self.entry_id

    sql = "UPDATE jdk_entries " + \
      "SET date_last_modified = ? " + \
      "WHERE jdk_entries.id = ?;"
    
    db_execute(sql, quote_tuple)

    return None
// update_date_modified [python]
  def update_date_modified(self):
    sql = "UPDATE jdk_entries " + \
      "SET date_last_modified = " + CURRENT_DATESTAMP + " " + \
      "WHERE jdk_entries.id = '" + self.entry_id + "';"
    
    db_execute(sql)

    return None
// system_search [python]
    def system_search(self, search):
        search = search.lower()
        conn = sqlite3.connect('data/ed.db').cursor()
        table = conn.execute('select * from populated where lower(name) = ?', (search,))
        results = table.fetchone()
        if not results:
            table = conn.execute('select * from systems where lower(name) = ?', (search,))
            results = table.fetchone()
        if results:
            keys = tuple(i[0] for i in table.description) 
            return '\n'.join(f'{key.replace("_", " ").title()}: {field}'
                             for key, field in zip(keys[1:], results[1:]) if field)
        else:
            return 'No systems found.'
// system_search [python]
    def system_search(self, search):
        search = search.lower()
        conn = sqlite3.connect('data/ed.db').cursor()
        table = conn.execute(f"select * from populated where lower(name) = '{search}'")
        results = table.fetchone()
        if not results:
            table = conn.execute(f"select * from systems where lower(name) = '{search}'")
            results = table.fetchone()
        if results:
            keys = tuple(i[0] for i in table.description) 
            return '\n'.join(f'{key.replace("_", " ").title()}: {field}'
                             for key, field in zip(keys[1:], results[1:]) if field)
        else:
            return 'No systems found.'
// add_input [python]
    def add_input(self, data):
        connection = self.connect()
        try:
            # The following introduces a deliberate security flaw - SQL Injection
            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 - SQL Injection
            query = "INSERT INTO crimes (description) VALUES ('{}');".format(data)
            with connection.cursor() as cursor:
                cursor.execute(query)
                connection.commit()
        finally:
            connection.close()
// get_login [python]
@bot.message_handler(commands =['login'])
def get_login(message):
    settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\settings.db")
    conn = settings.cursor()
    conn.execute("select * from users where chat_id = ?", (str(message.chat.id),))
    name = conn.fetchone()
    if name != None:
        bot.send_message(message.chat.id, "Previous handle: " + str(name[1]))
    else:
        bot.send_message(message.chat.id, "Previous handle: None")
    settings.close()
    bot.send_message(message.chat.id, "Type new handle: ")
    set_state(message.chat.id, config.States.S_LOGIN.value)
// get_login [python]
@bot.message_handler(commands =['login'])
def get_login(message):
    settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\settings.db")
    conn = settings.cursor()
    conn.execute("select * from users where chat_id = '" + str(message.chat.id) + "'")
    name = conn.fetchone()
    if name != None:
        bot.send_message(message.chat.id, "Previous handle: " + str(name[1]))
    else:
        bot.send_message(message.chat.id, "Previous handle: None")
    settings.close()
    bot.send_message(message.chat.id, "Type new handle: ")
    set_state(message.chat.id, config.States.S_LOGIN.value)
// login [python]
    def login(self, username, password):
        select_query = """
            SELECT client_id, username, balance, message
            FROM Clients
            WHERE username = ? AND password = ?
            LIMIT 1
        """

        cursor = self.__conn.cursor()

        cursor.execute(select_query, (username, password))
        user = cursor.fetchone()

        if(user):
            return Client(user[0], user[1], user[2], user[3])
        else:
            return False
// login [python]
    def login(self, username, password):
        select_query = """
            SELECT client_id, username, balance, message
            FROM Clients
            WHERE username = '{}' AND password = '{}'
            LIMIT 1
        """.format(username, password)

        cursor = self.__conn.cursor()

        cursor.execute(select_query)
        user = cursor.fetchone()

        if(user):
            return Client(user[0], user[1], user[2], user[3])
        else:
            return False
// get_current_state [python]
def get_current_state(chat_id):
    settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__))+"\\bases\\settings.db")
    conn = settings.cursor()
    conn.execute("select * from users where chat_id = ?", (str(chat_id),))
    name = conn.fetchone()
    if name != None:
        return name[4]
    else:
        return False
    settings.close()
// get_current_state [python]
def get_current_state(chat_id):
    settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__))+"\\bases\\settings.db")
    conn = settings.cursor()
    conn.execute("select * from users where chat_id = '" + str(chat_id) + "'")
    name = conn.fetchone()
    if name != None:
        return name[4]
    else:
        return False
    settings.close()
// fetch_page_name [python]
  def fetch_page_name(self, page_id):
    '''
    Returns the page name corresponding to the provided page ID.

    Args:
      page_id: The page ID whose ID to fetch.

    Returns:
      str: The page name corresponding to the provided page ID.

    Raises:
      ValueError: If the provided page ID is invalid or does not exist.
    '''
    helpers.validate_page_id(page_id)

    query = 'SELECT name FROM pages WHERE id = ?;'
    query_bindings = (page_id,)
    self.cursor.execute(query, query_bindings)

    page_name = self.cursor.fetchone()

    if not page_name:
      raise ValueError('Invalid page ID "{0}" provided. Page ID does not exist.'.format(page_id))

    return page_name[0].encode('utf-8').replace('_', ' ')
// fetch_page_name [python]
  def fetch_page_name(self, page_id):
    '''
    Returns the page name corresponding to the provided page ID.

    Args:
      page_id: The page ID whose ID to fetch.

    Returns:
      str: The page name corresponding to the provided page ID.

    Raises:
      ValueError: If the provided page ID is invalid or does not exist.
    '''
    helpers.validate_page_id(page_id)

    query = 'SELECT name FROM pages WHERE id="{0}"'.format(page_id)
    self.cursor.execute(query)

    page_name = self.cursor.fetchone()

    if not page_name:
      raise ValueError('Invalid page ID "{0}" provided. Page ID does not exist.'.format(page_id))

    return page_name[0].encode('utf-8').replace('_', ' ')
// save_page_edit [python]
@app.route('/<page_name>/save', methods=['POST'])
def save_page_edit(page_name):
    # grab the new content from the user
    content = request.form.get('content')
    # check if 'page_name' exists in the database
    query = db.query("select page_content.content, page.id as page_id, page_content.id as content_id 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)
    result = query.namedresult()
    # if it doesn't exist, create a new page in the database
    if len(result) < 1:
        db.insert(
            'page', {
                'page_name': page_name
            }
        )
    else:
        pass
    # now that we're certain that the page exists in the database, we again grab the query
    # and insert new content in the database
    query = db.query("select id from page where page_name = '%s'" % page_name)
    page_id = query.namedresult()[0].id
    db.insert(
        'page_content', {
            'page_id': page_id,
            'content': content,
            'timestamp': time.strftime("%Y-%m-%d %H:%M:%S", localtime())
        }
    )
    return redirect("/%s" % page_name)
// save_page_edit [python]
@app.route('/<page_name>/save', methods=['POST'])
def save_page_edit(page_name):
    # grab the new content from the user
    content = request.form.get('content')
    # check if 'page_name' exists in the database
    query = db.query("select page_content.content, page.id as page_id, page_content.id as content_id 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)
    result = query.namedresult()
    # if it doesn't exist, create a new page in the database
    if len(result) < 1:
        db.insert(
            'page', {
                'page_name': page_name
            }
        )
    else:
        pass
    # now that we're certain that the page exists in the database, we again grab the query
    # and insert new content in the database
    query = db.query("select id from page where page_name = '%s'" % page_name)
    page_id = query.namedresult()[0].id
    db.insert(
        'page_content', {
            'page_id': page_id,
            'content': content,
            'timestamp': time.strftime("%Y-%m-%d %H:%M:%S", localtime())
        }
    )
    return redirect("/%s" % page_name)
// get_top_popular [python]
def get_top_popular(top_num):
    """ query the top(top_num) popular articles
        top_num => list of [title, count]
    """
    cmd = """SELECT title, views FROM articles
             INNER JOIN (
             SELECT path, count(path) AS views
             FROM log GROUP BY log.path
             ) AS log
             ON log.path = '/article/' || articles.slug
             ORDER BY views DESC
             LIMIT %s"""
    data = [top_num, ]
    return execute_query(cmd, data)
// get_top_popular [python]
def get_top_popular(top_num):
    """ query the top(top_num) popular articles
        top_num => list of [title, count]
    """
    cmd = """SELECT title, views FROM articles
             INNER JOIN (
             SELECT path, count(path) AS views
             FROM log GROUP BY log.path
             ) AS log
             ON log.path = '/article/' || articles.slug
             ORDER BY views DESC
             LIMIT {}""".format(top_num)
    return execute_query(cmd)