jiahuimbzuai/CoQuIR huggingface dataset:
// update_inverter [python]
    def update_inverter(self, inverter_serial, ts, status, etoday, etotal):
        query = '''
            UPDATE Inverters
            SET     
                TimeStamp='%s', 
                Status='%s', 
                eToday='%s',
                eTotal='%s'
            WHERE Serial='%s';
        ''' % (ts, status, etoday, etotal, inverter_serial)
        self.c.execute(query)
// insert [python]
def insert(key, value):
    connection = psycopg2.connect(host=config['HOST'], port=config['PORT'], database=config['NAME'], user=config['USER'], password=config['PASSWORD'])
    cur = connection.cursor()
    try:
        cur.execute("insert into reply_map values(?, ?)", (key, value))
        connection.commit()
    except:
        pass
// insert [python]
def insert(key, value):
    connection = psycopg2.connect(host=config['HOST'], port=config['PORT'], database=config['NAME'], user=config['USER'], password=config['PASSWORD'])
    cur = connection.cursor()
    try:
        cur.execute("insert into reply_map values('{}', '{}')".format(key, value))
        connection.commit()
    except:
        pass
// save_failure_transaction [python]
    def save_failure_transaction(self, user_id, project_id, money):
        self.cursor.execute("insert into transactions (project_id,user_id, money, timestamp, state) values (%s, %s, "
                            "%s, now(), 'failed' )", (project_id, user_id, money))
        self.db.commit()
// save_failure_transaction [python]
    def save_failure_transaction(self, user_id, project_id, money):
        self.cursor.execute("insert into transactions (project_id,user_id, money, timestamp, state) values (%s, %s, %s, now(), 'failed' )" % (project_id, user_id, money))
        self.db.commit()
// test_process_as_form [python]
    @unpack
    def test_process_as_form(self, job_number, dcn_key, was_prev_matched,
            was_prev_closed, was_prev_tracked):
        email_obj = {
            'sender' : "Alex Roy <Alex.Roy@dilfo.com>",
            'subject' : "DO NOT MODIFY MESSAGE BELOW - JUST HIT `SEND`",
            'date' : "Tue, 7 May 2019 17:34:17 +0000",
            'content' : (
                f"job_number={job_number}&title=TEST_ENTRY&city=Ottawa&"
                f"address=2562+Del+Zotto+Ave.%2C+Ottawa%2C+Ontario&"
                f"contractor=GCN&engineer=Goodkey&owner=Douglas+Stalker&"
                f"quality=2&cc_email=&link_to_cert={dcn_key}\r\n"
            )
        }
        # set-up new entries in db, if necessary
        fake_dilfo_insert = """
            INSERT INTO df_dilfo (job_number, receiver_email, closed)
            VALUES (?, 'alex.roy616@gmail.com', ?)
        """
        fake_match_insert = """
            INSERT INTO df_matched (job_number, verifier, ground_truth)
            VALUES (?, 'alex.roy616@gmail.com', ?)
        """
        with create_connection() as conn:
            if was_prev_closed or was_prev_tracked:
                conn.cursor().execute(fake_dilfo_insert, [job_number, was_prev_closed])
            if was_prev_matched:
                if was_prev_closed:
                    conn.cursor().execute(fake_match_insert, [job_number, 1])
                else:
                    conn.cursor().execute(fake_match_insert, [job_number, 0])
        with create_connection() as conn:
            df_dilfo_pre = pd.read_sql("SELECT * FROM df_dilfo WHERE job_number=?", conn, params=[job_number])
            df_matched_pre = pd.read_sql("SELECT * FROM df_matched WHERE job_number=?", conn, params=[job_number])
        process_as_form(email_obj)
        # make assertions about db now that reply has been processed
        with create_connection() as conn:
            df_dilfo_post = pd.read_sql("SELECT * FROM df_dilfo WHERE job_number=?", conn, params=[job_number])
            df_matched_post = pd.read_sql("SELECT * FROM df_matched WHERE job_number=?", conn, params=[job_number])
        self.assertEqual(len(df_dilfo_post), 1)
        self.assertEqual(bool(df_dilfo_post.iloc[0].closed), bool(was_prev_closed or dcn_key))
        self.assertEqual(any(df_matched_post.ground_truth), bool(was_prev_closed or dcn_key))
        self.assertEqual(len(df_matched_pre) + bool(dcn_key and not(was_prev_closed)), len(df_matched_post))
        self.assertEqual(list(df_matched_pre.columns), list(df_matched_post.columns))
        self.assertEqual(list(df_dilfo_pre.columns), list(df_dilfo_post.columns))
// test_process_as_form [python]
    @unpack
    def test_process_as_form(self, job_number, dcn_key, was_prev_matched,
            was_prev_closed, was_prev_tracked):
        email_obj = {
            'sender' : "Alex Roy <Alex.Roy@dilfo.com>",
            'subject' : "DO NOT MODIFY MESSAGE BELOW - JUST HIT `SEND`",
            'date' : "Tue, 7 May 2019 17:34:17 +0000",
            'content' : (
                f"job_number={job_number}&title=TEST_ENTRY&city=Ottawa&"
                f"address=2562+Del+Zotto+Ave.%2C+Ottawa%2C+Ontario&"
                f"contractor=GCN&engineer=Goodkey&owner=Douglas+Stalker&"
                f"quality=2&cc_email=&link_to_cert={dcn_key}\r\n"
            )
        }
        # set-up new entries in db, if necessary
        fake_dilfo_insert = """
            INSERT INTO df_dilfo (job_number, receiver_email, closed)
            VALUES ({}, 'alex.roy616@gmail.com', {})
        """
        fake_match_insert = """
            INSERT INTO df_matched (job_number, verifier, ground_truth)
            VALUES ({}, 'alex.roy616@gmail.com', {})
        """
        with create_connection() as conn:
            if was_prev_closed or was_prev_tracked:
                conn.cursor().execute(fake_dilfo_insert.format(job_number, was_prev_closed))
            if was_prev_matched:
                if was_prev_closed:
                    conn.cursor().execute(fake_match_insert.format(job_number, 1))
                else:
                    conn.cursor().execute(fake_match_insert.format(job_number, 0))
        with create_connection() as conn:
            df_dilfo_pre = pd.read_sql(f"SELECT * FROM df_dilfo WHERE job_number={job_number}", conn)
            df_matched_pre = pd.read_sql(f"SELECT * FROM df_matched WHERE job_number={job_number}", conn)
        process_as_form(email_obj)
        # make assertions about db now that reply has been processed
        with create_connection() as conn:
            df_dilfo_post = pd.read_sql(f"SELECT * FROM df_dilfo WHERE job_number={job_number}", conn)
            df_matched_post = pd.read_sql(f"SELECT * FROM df_matched WHERE job_number={job_number}", conn)
        self.assertEqual(len(df_dilfo_post), 1)
        self.assertEqual(bool(df_dilfo_post.iloc[0].closed), bool(was_prev_closed or dcn_key))
        self.assertEqual(any(df_matched_post.ground_truth), bool(was_prev_closed or dcn_key))
        self.assertEqual(len(df_matched_pre) + bool(dcn_key and not(was_prev_closed)), len(df_matched_post))
        self.assertEqual(list(df_matched_pre.columns), list(df_matched_post.columns))
        self.assertEqual(list(df_dilfo_pre.columns), list(df_dilfo_post.columns))
// render_page_name [python]
@app.route('/<page_name>')
def render_page_name(page_name):
    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)
    wiki_page = query.namedresult()
    has_content = False
    page_is_taken = False
    if len(wiki_page) < 1:
        content = ""
    else:
        page_is_taken = True
        content = wiki_page[0].content
    if len(content) > 0:
        has_content = True
    else:
        pass
    content = markdown.markdown(wiki_linkify(content))
    return render_template(
        'pageholder.html',
        page_is_taken = page_is_taken,
        page_name = page_name,
        markdown = markdown,
        wiki_linkify = wiki_linkify,
        has_content = has_content,
        content = content
    )
// render_page_name [python]
@app.route('/<page_name>')
def render_page_name(page_name):
    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)
    wiki_page = query.namedresult()
    has_content = False
    page_is_taken = False
    if len(wiki_page) < 1:
        content = ""
    else:
        page_is_taken = True
        content = wiki_page[0].content
    if len(content) > 0:
        has_content = True
    else:
        pass
    content = markdown.markdown(wiki_linkify(content))
    return render_template(
        'pageholder.html',
        page_is_taken = page_is_taken,
        page_name = page_name,
        markdown = markdown,
        wiki_linkify = wiki_linkify,
        has_content = has_content,
        content = content
    )
// tid_to_tid_num [python]
    def tid_to_tid_num(self, tid):
        ''' Returns tid_num, given tid. '''

        q = "SELECT rowid FROM tids WHERE tid = ?"
        self.query(q, tid)
        return self.c.fetchone()[0]
// tid_to_tid_num [python]
    def tid_to_tid_num(self, tid):
        ''' Returns tid_num, given tid. '''

        q = "SELECT rowid FROM tids WHERE tid = '" + tid + "'"
        self.query(q)
        return self.c.fetchone()[0]
// get_old_sourcebyinstitution_number [python]
def get_old_sourcebyinstitution_number(conn, sqlite, sourcebyinstitution):
    """
    Get all the old sourcebyinstitution number from the SQLite database.
    """
    query = """
        SELECT
            titles
        FROM
            history
        WHERE
            sourcebyinstitution = ?
        ORDER BY
            titles DESC
        LIMIT 1
    """

    sqlite.execute(query, (sourcebyinstitution,))
    for record in sqlite:
        old_sourcebyinstitution_number = record[0]
        return old_sourcebyinstitution_number
// get_old_sourcebyinstitution_number [python]
def get_old_sourcebyinstitution_number(conn, sqlite, sourcebyinstitution):
    """
    Get all the old sourcebyinstitution number from the SQLite database.
    """
    query = """
        SELECT
            titles
        FROM
            history
        WHERE
            sourcebyinstitution = "%s"
        ORDER BY
            titles DESC
        LIMIT 1
    """ % sourcebyinstitution

    sqlite.execute(query)
    for record in sqlite:
        old_sourcebyinstitution_number = record[0]
        return old_sourcebyinstitution_number
// top_karma [python]
def top_karma(bot, trigger):
    """
    Show karma status for the top n number of IRC users.
    """
    try:
        top_limit = int(trigger.group(2).strip())
    except ValueError:
        top_limit = 5

    query = "SELECT slug, value FROM nick_values NATURAL JOIN nicknames \
        WHERE key = 'karma' ORDER BY value DESC LIMIT ?"
    karmalist = bot.db.execute(query, str(top_limit)).fetchall()
    for user in karmalist:
        bot.say("%s == %s" % (user[0], user[1]))
// top_karma [python]
def top_karma(bot, trigger):
    """
    Show karma status for the top n number of IRC users.
    """
    try:
        top_limit = int(trigger.group(2).strip())
    except ValueError:
        top_limit = 5

    query = "SELECT slug, value FROM nick_values NATURAL JOIN nicknames \
        WHERE key = 'karma' ORDER BY value DESC LIMIT %d"
    karmalist = bot.db.execute(query % top_limit).fetchall()
    for user in karmalist:
        bot.say("%s == %s" % (user[0], user[1]))
// retrieve_playlist_by_id [python]
def retrieve_playlist_by_id(id, db):
    db.execute(
        "SELECT id, name, video_position from playlist WHERE id=%s;", (id,))
    row = db.fetchone()
    return row
// retrieve_playlist_by_id [python]
def retrieve_playlist_by_id(id, db):
    db.execute(
        "SELECT id, name, video_position from playlist WHERE id={id};".format(id=id))
    row = db.fetchone()
    return row
// get_task [python]
@bot.message_handler(func = lambda message: get_current_state(message.chat.id) == config.States.S_GET_TASK.value)
def get_task(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()
    settings.close()
    if name == None:
        bot.send_message(message.chat.id, "You should login before get tasks.")
    else:
        bases.update.update_user(name[1], name[0], name[2])
        bot.send_message(message.chat.id, bases.problem.get_unsolved_problem(message.text, name[1]))
    set_state(message.chat.id, config.States.S_START.value)
// get_task [python]
@bot.message_handler(func = lambda message: get_current_state(message.chat.id) == config.States.S_GET_TASK.value)
def get_task(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()
    settings.close()
    if name == None:
        bot.send_message(message.chat.id, "You should login before get tasks.")
    else:
        bases.update.update_user(name[1], name[0], name[2])
        bot.send_message(message.chat.id, bases.problem.get_unsolved_problem(message.text, name[1]))
    set_state(message.chat.id, config.States.S_START.value)
// stats [python]
@bot.message_handler(commands=['stats'])
def stats(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()
    settings.close()
    if name != None:
        bases.update.update_user(name[1], name[0], name[2])
        bases.problem.create_text_stats(name[1])
        img = open(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\users\\" + name[1] + ".png", "rb")
        bot.send_photo(message.chat.id, img)
        img.close()
        if bases.problem.create_stats_picture(name[1]):
            bot.send_message(message.chat.id, "Sorry, you haven't solved tasks.")
            return 0
        img = open(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\users\\" + name[1] + ".png", "rb")
        bot.send_photo(message.chat.id, img)
        img.close()
    else:
        bot.send_message(message.chat.id, "You should login before getting statistic.")
// stats [python]
@bot.message_handler(commands=['stats'])
def stats(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()
    settings.close()
    if name != None:
        bases.update.update_user(name[1], name[0], name[2])
        bases.problem.create_text_stats(name[1])
        img = open(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\users\\" + name[1] + ".png", "rb")
        bot.send_photo(message.chat.id, img)
        img.close()
        if bases.problem.create_stats_picture(name[1]):
            bot.send_message(message.chat.id, "Sorry, you haven't solved tasks.")
            return 0
        img = open(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\users\\" + name[1] + ".png", "rb")
        bot.send_photo(message.chat.id, img)
        img.close()
    else:
        bot.send_message(message.chat.id, "You should login before getting statistic.")
// delete [python]
    @jwt_required
    def delete(self, user_id):
        """ Deletes user with the corresponding user_id """
        return database_utilities.execute_query(f"""delete from users where user_id = %s""", (user_id, ))
// delete [python]
    @jwt_required
    def delete(self, user_id):
        """ Deletes user with the corresponding user_id """
        return database_utilities.execute_query(f"""delete from users where user_id = '{user_id}'""")
// verify_rno [python]
    def verify_rno(self, rno):
        self.cursor.execute("SELECT COUNT(rno) FROM rides WHERE rno = :rno", {'rno': rno})
        result = self.cursor.fetchone()
        if (int(result[0]) > 0):
            return True 
        else:
            return False
// verify_rno [python]
    def verify_rno(self, rno):
        query = "SELECT COUNT(rno) FROM rides WHERE rno = {rno}".format(rno = rno)
        self.cursor.execute(query)
        result = self.cursor.fetchone()
        if (int(result[0]) > 0):
            return True 
        else:
            return False
// get_requested_day [python]
    def get_requested_day(self, date):

        data = dict()

        day_start, day_end = self.get_epoch_day(date)
        data['interval'] = {'from': self.convert_local_ts_to_utc(day_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(day_end, self.local_timezone)}

        query = '''
            SELECT TimeStamp, SUM(Power) AS Power 
            FROM DayData 
            WHERE TimeStamp BETWEEN ? AND ?
            GROUP BY TimeStamp;
        '''

        data['data'] = list()
        for row in self.c.execute(query, (day_start, day_end)):
            data['data'].append({ 'time': row[0], 'power': row[1] })


        if self.get_datetime(date).date() == datetime.today().date():
            query = '''
                SELECT SUM(EToday) as EToday
                FROM Inverters;
                '''
            self.c.execute(query)
        else:
            query = '''
                SELECT SUM(DayYield) AS Power 
                FROM MonthData 
                WHERE TimeStamp BETWEEN ? AND ?
                GROUP BY TimeStamp;
                '''
            self.c.execute(query, (day_start, day_end))

        row = self.c.fetchone()
        if row and row[0]: data['total'] = row[0]
        else: data['total'] = 0


        query = '''
            SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max 
            FROM ( SELECT TimeStamp FROM DayData GROUP BY TimeStamp );
            '''

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

        if (first_data):  data['hasPrevious'] = (first_data < day_start)
        else: data['hasPrevious'] = False

        if (last_data): data['hasNext'] = (last_data > day_end)
        else: data['hasNext'] = False

        #print(json.dumps(data, indent=4))
        return data
// get_requested_day [python]
    def get_requested_day(self, date):

        data = dict()

        day_start, day_end = self.get_epoch_day(date)
        data['interval'] = {'from': self.convert_local_ts_to_utc(day_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(day_end, self.local_timezone)}

        query = '''
            SELECT TimeStamp, SUM(Power) AS Power 
            FROM DayData 
            WHERE TimeStamp BETWEEN %s AND %s 
            GROUP BY TimeStamp;
        '''

        data['data'] = list()
        for row in self.c.execute(query % (day_start, day_end)):
            data['data'].append({ 'time': row[0], 'power': row[1] })


        if self.get_datetime(date).date() == datetime.today().date():
            query = '''
                SELECT SUM(EToday) as EToday
                FROM Inverters;
                '''
        else:
            query = '''
                SELECT SUM(DayYield) AS Power 
                FROM MonthData 
                WHERE TimeStamp BETWEEN %s AND %s
                GROUP BY TimeStamp
                ''' % (day_start, day_end)
        self.c.execute(query)
        row = self.c.fetchone()
        if row and row[0]: data['total'] = row[0]
        else: data['total'] = 0


        query = '''
            SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max 
            FROM ( SELECT TimeStamp FROM DayData GROUP BY TimeStamp );
            '''

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

        if (first_data):  data['hasPrevious'] = (first_data < day_start)
        else: data['hasPrevious'] = False

        if (last_data): data['hasNext'] = (last_data > day_end)
        else: data['hasNext'] = False

        #print(json.dumps(data, indent=4))
        return data
// add_language [python]
def add_language(lang):
    try:
        cur.execute("INSERT INTO language (name) VALUES (%s)", (lang, ))
    except Exception as e:
        pass
    cur.execute("SELECT language_id FROM language where name=%s", (lang, ))
    lang_id = cur.fetchone()[0]
    if conn.commit():
        return lang_id
    return lang_id
// add_language [python]
def add_language(lang):
    try:
        cur.execute(f"INSERT INTO language (name) VALUES ('{lang}')")
    except Exception as e:
        pass
    cur.execute(f"SELECT language_id FROM language where name='{lang}'")
    lang_id = cur.fetchone()[0]
    if conn.commit():
        return lang_id
    return lang_id
// makeJudge [python]
def makeJudge(judge):
	db.execute("UPDATE players SET Judge = 1 WHERE Name = ? COLLATE NOCASE", judge) 
	database.commit()
// makeJudge [python]
def makeJudge(judge):
	db.execute("UPDATE players SET Judge = 1 WHERE Name = '%s' COLLATE NOCASE" % (judge)) 
	database.commit()
// isValidAdmToken [python]
def isValidAdmToken(adm_token):
    conn, c = connectDB()
    req = "SELECT *  from {} where adm_token=?".format(CFG("admintoken_table_name"))
    answer = bool(queryOne(c, req, (adm_token,)))
    closeDB(conn)
    return answer
// isValidAdmToken [python]
def isValidAdmToken(adm_token):
    conn, c = connectDB()
    req = "SELECT *  from {} where adm_token='{}'".format(CFG("admintoken_table_name"), adm_token)
    answer = bool(queryOne(c, req))
    closeDB(conn)
    return answer
// get_mapped_projects [python]
    @staticmethod
    def get_mapped_projects(user_id: int, preferred_locale: str) -> UserMappedProjectsDTO:
        """ Get all projects a user has mapped on """

        # This query looks scary, but we're really just creating an outer join between the query that gets the
        # counts of all mapped tasks and the query that gets counts of all validated tasks.  This is necessary to
        # handle cases where users have only validated tasks on a project, or only mapped on a project.
        sql = '''SELECT p.id,
                        p.status,
                        p.default_locale,
                        c.mapped,
                        c.validated,
                        st_asgeojson(p.centroid)
                   FROM projects p,
                        (SELECT coalesce(v.project_id, m.project_id) project_id,
                                coalesce(v.validated, 0) validated,
                                coalesce(m.mapped, 0) mapped
                          FROM (SELECT t.project_id,
                                       count (t.validated_by) validated
                                  FROM tasks t
                                 WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = :user_id)
                                   AND t.validated_by = :user_id
                                 GROUP BY t.project_id, t.validated_by) v
                         FULL OUTER JOIN
                        (SELECT t.project_id,
                                count(t.mapped_by) mapped
                           FROM tasks t
                          WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = :user_id)
                            AND t.mapped_by = :user_id
                          GROUP BY t.project_id, t.mapped_by) m
                         ON v.project_id = m.project_id) c
                   WHERE p.id = c.project_id ORDER BY p.id DESC'''

        results = db.engine.execute(text(sql), user_id=user_id)

        if results.rowcount == 0:
            raise NotFound()

        mapped_projects_dto = UserMappedProjectsDTO()
        for row in results:
            mapped_project = MappedProject()
            mapped_project.project_id = row[0]
            mapped_project.status = ProjectStatus(row[1]).name
            mapped_project.tasks_mapped = row[3]
            mapped_project.tasks_validated = row[4]
            mapped_project.centroid = geojson.loads(row[5])

            project_info = ProjectInfo.get_dto_for_locale(row[0], preferred_locale, row[2])
            mapped_project.name = project_info.name

            mapped_projects_dto.mapped_projects.append(mapped_project)

        return mapped_projects_dto
// get_mapped_projects [python]
    @staticmethod
    def get_mapped_projects(user_id: int, preferred_locale: str) -> UserMappedProjectsDTO:
        """ Get all projects a user has mapped on """

        # This query looks scary, but we're really just creating an outer join between the query that gets the
        # counts of all mapped tasks and the query that gets counts of all validated tasks.  This is necessary to
        # handle cases where users have only validated tasks on a project, or only mapped on a project.
        sql = '''SELECT p.id,
                        p.status,
                        p.default_locale,
                        c.mapped,
                        c.validated,
                        st_asgeojson(p.centroid)
                   FROM projects p,
                        (SELECT coalesce(v.project_id, m.project_id) project_id,
                                coalesce(v.validated, 0) validated,
                                coalesce(m.mapped, 0) mapped
                          FROM (SELECT t.project_id,
                                       count (t.validated_by) validated
                                  FROM tasks t
                                 WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = {0})
                                   AND t.validated_by = {0}
                                 GROUP BY t.project_id, t.validated_by) v
                         FULL OUTER JOIN
                        (SELECT t.project_id,
                                count(t.mapped_by) mapped
                           FROM tasks t
                          WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = {0})
                            AND t.mapped_by = {0}
                          GROUP BY t.project_id, t.mapped_by) m
                         ON v.project_id = m.project_id) c
                   WHERE p.id = c.project_id ORDER BY p.id DESC'''.format(user_id)

        results = db.engine.execute(sql)

        if results.rowcount == 0:
            raise NotFound()

        mapped_projects_dto = UserMappedProjectsDTO()
        for row in results:
            mapped_project = MappedProject()
            mapped_project.project_id = row[0]
            mapped_project.status = ProjectStatus(row[1]).name
            mapped_project.tasks_mapped = row[3]
            mapped_project.tasks_validated = row[4]
            mapped_project.centroid = geojson.loads(row[5])

            project_info = ProjectInfo.get_dto_for_locale(row[0], preferred_locale, row[2])
            mapped_project.name = project_info.name

            mapped_projects_dto.mapped_projects.append(mapped_project)

        return mapped_projects_dto
// delete_data [python]
    def delete_data(self, session, id):
        self._openContainer(session)
        sid = str(id)
        if (self.idNormalizer is not None):
            sid = self.idNormalizer.process_string(session, str(id))
        query = "DELETE FROM %s WHERE identifier = $1;" % (self.table)
        self._query(query, sid)
        return None
// delete_data [python]
    def delete_data(self, session, id):
        self._openContainer(session)
        sid = str(id)
        if (self.idNormalizer is not None):
            sid = self.idNormalizer.process_string(session, str(id))
        query = "DELETE FROM %s WHERE identifier = '%s';" % (self.table, sid)
        self._query(query)
        return None
// user_verify [python]
    def user_verify(self):
        eid = self.email
        code = self.password
        if eid.strip() == '':
            return
        if code.strip() == '':
            return
        query = 'select * from usr where email like %s'
        cursor = g.conn.execute(query, (eid, ))
        for row in cursor:
            key = str(row.password)
            if key.strip() == code.strip():
                self.name = str(row.name)
                self.email = eid
                self.id = eid
                self.valid = True
            break
// user_verify [python]
    def user_verify(self):
        eid = self.email
        code = self.password
        if eid.strip() == '':
            return
        if code.strip() == '':
            return
        query = '''select * from usr where email like\''''+eid+'\''
        cursor = g.conn.execute(query)
        for row in cursor:
            key = str(row.password)
            if key.strip() == code.strip():
                self.name = str(row.name)
                self.email = eid
                self.id = eid
                self.valid = True
            break
// search_films [python]
@app.route('/movies/search', methods=['GET', 'POST'])
def search_films():
    form = SearchForm()
    if not form.validate_on_submit():
        return render_template('search.html', title='Search for films', form=form)
    search_terms = form.data['term'].split(' ')
    search_string = ' & '.join(search_terms)
    cur.execute("SELECT * FROM film where fulltext @@ to_tsquery(%s)", (search_string, ))
    res = cur.fetchall()
    return render_template('search_results.html', title='Home', res=len(res))
// search_films [python]
@app.route('/movies/search', methods=['GET', 'POST'])
def search_films():
    form = SearchForm()
    if not form.validate_on_submit():
        return render_template('search.html', title='Search for films', form=form)
    search_terms = form.data['term'].split(' ')
    search_string = ' & '.join(search_terms)
    cur.execute(f"SELECT * FROM film where fulltext @@ to_tsquery('{search_string}')")
    res = cur.fetchall()
    return render_template('search_results.html', title='Home', res=len(res))
// getGameCountInSeriesSoFar [python]
def getGameCountInSeriesSoFar(submission):
    database = sqlite3.connect('database.db')
    cursor = database.cursor()
    return cursor.execute("SELECT COUNT(*) FROM ChallengeRankings WHERE SeriesTitle = ? AND Date <= ?", [getTitle(submission), getSubmissionDateFromDatabase(submission)]).fetchone()[0]
    database.close()
// getGameCountInSeriesSoFar [python]
def getGameCountInSeriesSoFar(submission):
    database = sqlite3.connect('database.db')
    cursor = database.cursor()
    return cursor.execute("SELECT COUNT(*) FROM ChallengeRankings WHERE SeriesTitle = '" + getTitle(submission) + "' AND Date <= '" + getSubmissionDateFromDatabase(submission) + "'").fetchone()[0]
    database.close()
// add [python]
@mod.route('/add', methods=['GET', 'POST'])
def add():
    if request.method == 'POST':
        msg_id = int(request.form['msg_id'])
        user_id = session['logged_id']
        content = request.form['content']
        c_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        cursor.execute("INSERT INTO comment(msg_id,user_id,content,c_time) VALUES(%s,%s,%s,%s);", (msg_id, user_id, content, c_time))
        conn.commit()
    return redirect(url_for('comment.show', msg_id=msg_id))
// add [python]
@mod.route('/add', methods=['GET', 'POST'])
def add():
    if request.method == 'POST':
        msg_id = int(request.form['msg_id'])
        user_id = session['logged_id']
        content = request.form['content']
        c_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        sql = "INSERT INTO comment(msg_id,user_id,content,c_time) " + \
                "VALUES(%d,%d,'%s','%s');" % (msg_id, user_id, content, c_time)
        cursor.execute(sql)
        conn.commit()
    return redirect(url_for('comment.show', msg_id=msg_id))
// get_mod_taken_together_with [python]
def get_mod_taken_together_with(code):
    '''
        Retrieves the list of modules taken together with the specified
        module code in the same semester.

        Returns a table of lists (up to 10 top results). Each list contains
        (specified code, module code of mod taken together, aySem, number of students)

        e.g. [(CS1010, CS1231, AY 16/17 Sem 1, 5)] means there are 5 students
        taking CS1010 and CS1231 together in AY 16/17 Sem 1.
    '''
    NUM_TOP_RESULTS_TO_RETURN = 10

    sql_command = "SELECT sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem, COUNT(*) " + \
                "FROM studentPlans sp1, studentPlans sp2 " + \
                "WHERE sp1.moduleCode = %s AND " + \
                "sp2.moduleCode <> sp1.moduleCode AND " + \
                "sp1.studentId = sp2.studentId AND " + \
                "sp1.acadYearAndSem = sp2.acadYearAndSem " + \
                "GROUP BY sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem " + \
                "ORDER BY COUNT(*) DESC"

    DB_CURSOR.execute(sql_command, (code,))

    return DB_CURSOR.fetchmany(NUM_TOP_RESULTS_TO_RETURN)
// get_mod_taken_together_with [python]
def get_mod_taken_together_with(code):
    '''
        Retrieves the list of modules taken together with the specified
        module code in the same semester.

        Returns a table of lists (up to 10 top results). Each list contains
        (specified code, module code of mod taken together, aySem, number of students)

        e.g. [(CS1010, CS1231, AY 16/17 Sem 1, 5)] means there are 5 students
        taking CS1010 and CS1231 together in AY 16/17 Sem 1.
    '''
    NUM_TOP_RESULTS_TO_RETURN = 10

    sql_command = "SELECT sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem, COUNT(*) " + \
                "FROM studentPlans sp1, studentPlans sp2 " + \
                "WHERE sp1.moduleCode = '" + code + "' AND " + \
                "sp2.moduleCode <> sp1.moduleCode AND " + \
                "sp1.studentId = sp2.studentId AND " + \
                "sp1.acadYearAndSem = sp2.acadYearAndSem " + \
                "GROUP BY sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem " + \
                "ORDER BY COUNT(*) DESC"

    DB_CURSOR.execute(sql_command)

    return DB_CURSOR.fetchmany(NUM_TOP_RESULTS_TO_RETURN)
// wins [python]
@endpoints.route("/wins")
def wins():
    if db == None:
        init()

    player = request.args.get('tag', default="christmasmike")
    sql = "SELECT * FROM matches WHERE winner = '{player}' ORDER BY date DESC;"
    args = {'player': player}
    result = db.exec(sql, args)

    result = [str(x) for x in result]
    result = '\n'.join(result)
    return json.dumps(result)
// wins [python]
@endpoints.route("/wins")
def wins():
    if db == None:
        init()

    player = request.args.get('tag', default="christmasmike")
    sql = "SELECT * FROM matches WHERE winner = '"+str(player)+"' ORDER BY date DESC;"
    result = db.exec(sql)

    result = [str(x) for x in result]
    result = '\n'.join(result)
    return json.dumps(result)
// delete_event [python]
    def delete_event(self, event_id):
        sql = """
              DELETE FROM events
              WHERE event_id = %s
              """
        affected_count = self.cur.execute(sql, (event_id,))
        self.conn.commit()
        return affected_count
// delete_event [python]
    def delete_event(self, event_id):
        sql = """DELETE FROM events
                 WHERE event_id = {0}
                 """.format(event_id)
        affected_count = self.cur.execute(sql)
        self.conn.commit()
        return affected_count
// add_item [python]
    def add_item(self, item):
        """"Add new item."""
        if self.connection:
            t = (item[0], item[1], )
            self.cursor.execute('insert into item (name, shoppinglistid) values (?, ?)', t)
            self.connection.commit()
// add_item [python]
    def add_item(self, item):
        """"Add new item."""
        if self.connection:
            self.cursor.execute('insert into item (name, shoppinglistid) values ("%s", "%s")' % (item[0], item[1]))
            self.connection.commit()
// fetch_issue [python]
def fetch_issue(cursor, id):
    """
    Fetch an issue by id along with its tags. Returns None if no issue
    with the specified id exists in the database.
    """
    cursor.execute("""
        SELECT
            issue.id,
            issue.title,
            issue.description,
            tag.namespace,
            tag.predicate,
            tag.value
        FROM
            issue LEFT JOIN tag
            ON issue.id = tag.issue_id
        WHERE
            issue.id = ?
    """, (id,))

    issue = None
    for row in cursor:
        if issue is None:
            issue = {
                "id": row["id"],
                "title": row["title"],
                "description": row["description"],
                "tags": [],
            }
        # If tag exists in row, add to issue.
        if row["value"]:
            issue["tags"].append({
                "namespace": row["namespace"],
                "predicate": row["predicate"],
                "value": row["value"],
            })

    return issue
// fetch_issue [python]
def fetch_issue(cursor, id):
    """
    Fetch an issue by id along with its tags. Returns None if no issue
    with the specified id exists in the database.
    """
    cursor.execute(f"""
        SELECT
            issue.id,
            issue.title,
            issue.description,
            tag.namespace,
            tag.predicate,
            tag.value
        FROM
            issue LEFT JOIN tag
            ON issue.id = tag.issue_id
        WHERE
            issue.id = {id}
    """)

    issue = None
    for row in cursor:
        if issue is None:
            issue = {
                "id": row["id"],
                "title": row["title"],
                "description": row["description"],
                "tags": [],
            }
        # If tag exists in row, add to issue.
        if row["value"]:
            issue["tags"].append({
                "namespace": row["namespace"],
                "predicate": row["predicate"],
                "value": row["value"],
            })

    return issue
// also_add [python]
def also_add(name, also):
    db = db_connect()
    cursor = db.cursor()
    try:
        cursor.execute('''
            INSERT INTO isalso(name,also) VALUES(%(name)s,%(also)s)
            ''', (
            name,
            also,
        ))
        db.commit()
        logger.debug('added to isalso name {} with value {}'.format(
            name, also))
        db.close()
    except Exception as e:
        logger.error('Execution failed with error: {}'.format(e))
        raise
// also_add [python]
def also_add(name, also):
    db = db_connect()
    cursor = db.cursor()
    try:
        cursor.execute('''
            INSERT INTO isalso(name,also) VALUES('{}','{}')
            '''.format(name, also))
        db.commit()
        logger.debug('added to isalso name {} with value {}'.format(
            name, also))
        db.close()
    except Exception as e:
        logger.error('Execution failed with error: {}'.format(e))
        raise
// getCommentsLike [python]
    def getCommentsLike(self,commentid):
        sqlText="select userid from comment_like where commentid=%s"
        params=[commentid]
        result=sql.queryDB(self.conn,sqlText,params)
        return result;
// getCommentsLike [python]
    def getCommentsLike(self,commentid):
        sqlText="select userid from comment_like where commentid=%d"%(commentid)
        result=sql.queryDB(self.conn,sqlText)
        return result;
// update_theory_base [python]
def update_theory_base(tag, link):
    theory = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\theory.db")
    conn = theory.cursor()
    conn.execute("insert into ? values (?)", (tag, str(link)))
    theory.commit()
    theory.close()
// update_theory_base [python]
def update_theory_base(tag, link):
    theory = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\theory.db")
    conn = theory.cursor()
    conn.execute("insert into " + str(tag) + " values (?)", (str(link), ))
    theory.commit()
    theory.close()
// get_asset_and_volume [python]
@app.route('/get_asset_and_volume')
def get_asset_and_volume():
    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"]

    #print asset_id
    ws.send('{"id":1, "method":"call", "params":[0,"get_assets",[["' + asset_id + '"], 0]]}')
    result = ws.recv()
    j = json.loads(result)

    dynamic_asset_data_id =  j["result"][0]["dynamic_asset_data_id"]

    ws.send('{"id": 1, "method": "call", "params": [0, "get_objects", [["'+dynamic_asset_data_id+'"]]]}')
    result2 = ws.recv()
    j2 = json.loads(result2)
    #print j2["result"][0]["current_supply"]

    j["result"][0]["current_supply"] = j2["result"][0]["current_supply"]
    j["result"][0]["confidential_supply"] = j2["result"][0]["confidential_supply"]
    #print j["result"]

    j["result"][0]["accumulated_fees"] = j2["result"][0]["accumulated_fees"]
    j["result"][0]["fee_pool"] = j2["result"][0]["fee_pool"]

    issuer = j["result"][0]["issuer"]
    ws.send('{"id": 1, "method": "call", "params": [0, "get_objects", [["'+issuer+'"]]]}')
    result3 = ws.recv()
    j3 = json.loads(result3)
    j["result"][0]["issuer_name"] = j3["result"][0]["name"]


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

    query = "SELECT volume, mcap FROM assets WHERE aid=%s"
    cur.execute(query, (asset_id,))
    results = cur.fetchall()
    con.close()
    try:
        j["result"][0]["volume"] = results[0][0]
        j["result"][0]["mcap"] = results[0][1]
    except:
        j["result"][0]["volume"] = 0
        j["result"][0]["mcap"] = 0

    return jsonify(j["result"])
// get_asset_and_volume [python]
@app.route('/get_asset_and_volume')
def get_asset_and_volume():
    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"]

    #print asset_id
    ws.send('{"id":1, "method":"call", "params":[0,"get_assets",[["' + asset_id + '"], 0]]}')
    result = ws.recv()
    j = json.loads(result)

    dynamic_asset_data_id =  j["result"][0]["dynamic_asset_data_id"]

    ws.send('{"id": 1, "method": "call", "params": [0, "get_objects", [["'+dynamic_asset_data_id+'"]]]}')
    result2 = ws.recv()
    j2 = json.loads(result2)
    #print j2["result"][0]["current_supply"]

    j["result"][0]["current_supply"] = j2["result"][0]["current_supply"]
    j["result"][0]["confidential_supply"] = j2["result"][0]["confidential_supply"]
    #print j["result"]

    j["result"][0]["accumulated_fees"] = j2["result"][0]["accumulated_fees"]
    j["result"][0]["fee_pool"] = j2["result"][0]["fee_pool"]

    issuer = j["result"][0]["issuer"]
    ws.send('{"id": 1, "method": "call", "params": [0, "get_objects", [["'+issuer+'"]]]}')
    result3 = ws.recv()
    j3 = json.loads(result3)
    j["result"][0]["issuer_name"] = j3["result"][0]["name"]


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

    query = "SELECT volume, mcap FROM assets WHERE aid='"+asset_id+"'"
    cur.execute(query)
    results = cur.fetchall()
    con.close()
    try:
        j["result"][0]["volume"] = results[0][0]
        j["result"][0]["mcap"] = results[0][1]
    except:
        j["result"][0]["volume"] = 0
        j["result"][0]["mcap"] = 0

    return jsonify(j["result"])
// reportMatch [python]
def reportMatch(winner, loser):
    """Records the outcome of a single match between two players.

    Args:
      winner:  the id number of the player who won
      loser:  the id number of the player who lost
    """
    try:
        int(winner)
        int(loser)
    except ValueError:
        raise ValueError(
            "\"winner\" and/or \"loser\" input are not integers.\n"
            "Please use the id number of each player to report match results."
        )
    w = str(winner)
    l = str(loser)
    db = connect()
    c = db.cursor()
    c.execute("INSERT INTO matches values (%s, %s)", (w,l))
    db.commit()
    db.close()
// reportMatch [python]
def reportMatch(winner, loser):
    """Records the outcome of a single match between two players.

    Args:
      winner:  the id number of the player who won
      loser:  the id number of the player who lost
    """
    try:
        int(winner)
        int(loser)
    except ValueError:
        raise ValueError(
            "\"winner\" and/or \"loser\" input are not integers.\n"
            "Please use the id number of each player to report match results."
        )
    w = str(winner)
    l = str(loser)
    db = connect()
    c = db.cursor()
    statement = "INSERT INTO matches values ({w}, {l})".format(w=w, l=l)
    c.execute(statement)
    db.commit()
    db.close()
// getPlayer [python]
def getPlayer(player):
	db.execute("SELECT * FROM players WHERE Name = ? COLLATE NOCASE", player)
	playerstats = dict(db.fetchone())
	return playerstats
// getPlayer [python]
def getPlayer(player):
	db.execute("SELECT * FROM players WHERE Name = '%s' COLLATE NOCASE" % player)
	playerstats = dict(db.fetchone())
	return playerstats
// karma_sub [python]
def karma_sub(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))
            db.close()
            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 -1 karma for {}'.format(name))
            db.close()
            return karma
        except Exception as e:
            logger.error('Execution failed with error: {}'.format(e))
            raise
// karma_sub [python]
def karma_sub(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))
            db.close()
            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 -1 karma for {}'.format(name))
            db.close()
            return karma
        except Exception as e:
            logger.error('Execution failed with error: {}'.format(e))
            raise
// login [python]
@app.route('/', methods=['POST'])
def login():
    print('login')
    user = str(request.form['username'])
    password = str(request.form['password'])
    cur.execute("SELECT * FROM users WHERE name = ? AND password = ?;", [user, password])
    response = cur.fetchone()
    if response != None:
        print(response, 'OK')
        return redirect(url_for('enter_test_point'))
    else:
        print(response, 'not OK')
        flash('Invalid login or password')
        return render_template('login.html')
// login [python]
@app.route('/', methods=['POST'])
def login():
    print('login')
    user = str(request.form['username'])
    password = str(request.form['password'])
    cur.execute('SELECT * FROM users WHERE name = \'{}\' AND password = \'{}\';'.format(user, password))
    response = cur.fetchone()
    if response != None:
        print(response, 'OK')
        return redirect(url_for('enter_test_point'))
    else:
        print(response, 'not OK')
        flash('Invalid login or password')
        return render_template('login.html')