Input:
@api.route('/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
    sql = '''SELECT id, name_enus FROM tblDBCItem WHERE id = {} AND auctionable = true;'''.format(item_id)
    cursor = mysql.connection.cursor()
    cursor.execute(sql)
    data = cursor.fetchone()

    if data:
        item = {}
        for tup in zip([column[0] for column in cursor.description], data):
            item[tup[0]] = tup[1]
    else:
        return jsonify({"error": "item not found"}), 404

    return jsonify(item)

@api.route('/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
    sql = '''SELECT id, name_enus FROM tblDBCItem WHERE id = %s AND auctionable = true;'''
    cursor = mysql.connection.cursor()
    cursor.execute(sql, [item_id])
    data = cursor.fetchone()

    if data:
        item = {}
        for tup in zip([column[0] for column in cursor.description], data):
            item[tup[0]] = tup[1]
    else:
        return jsonify({"error": "item not found"}), 404

    return jsonify(item)


Input:
    def set_language(self, lang):
        """
        Update language of user in the User object and in the database
        :param lang: string with language tag like "en-US"
        :return: None
        """
        log.debug('Updating info about user %s language '
                  'in memory & database...', self)

        self.language = lang

        query = ("UPDATE users "
                 f"SET language='{self.language}' "
                 f"WHERE chat_id='{self.chat_id}'")

        try:
            db.add(query)
        except DatabaseError:
            log.error("Can't add new language of %s to the database", self)
        else:
            log.debug('Language updated.')

    def set_language(self, lang):
        """
        Update language of user in the User object and in the database
        :param lang: string with language tag like "en-US"
        :return: None
        """
        log.debug('Updating info about user %s language '
                  'in memory & database...', self)

        self.language = lang

        query = ("UPDATE users "
                 f"SET language=%s "
                 f"WHERE chat_id=%s")

        parameters = self.language, self.chat_id
        try:
            db.add(query, parameters)
        except DatabaseError:
            log.error("Can't add new language of %s to the database", self)
        else:
            log.debug('Language updated.')


Input:
    @staticmethod
    def upsert_mapped_projects(user_id: int, project_id: int):
        """ Adds projects to mapped_projects if it doesn't exist """
        sql = "select * from users where id = {0} and projects_mapped @> '{{{1}}}'".format(user_id, project_id)
        result = db.engine.execute(sql)

        if result.rowcount > 0:
            return  # User has previously mapped this project so return

        sql = '''update users
                    set projects_mapped = array_append(projects_mapped, {0})
                  where id = {1}'''.format(project_id, user_id)

        db.engine.execute(sql)

    @staticmethod
    def upsert_mapped_projects(user_id: int, project_id: int):
        """ Adds projects to mapped_projects if it doesn't exist """
        sql = "select * from users where id = :user_id and projects_mapped @> '{{:project_id}}'"
        result = db.engine.execute(text(sql), user_id=user_id, project_id=project_id)

        if result.rowcount > 0:
            return  # User has previously mapped this project so return

        sql = '''update users
                    set projects_mapped = array_append(projects_mapped, :project_id)
                  where id = :user_id'''

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


Input:
@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
    )

@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
    )


Input:
@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)

@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)


Input:
@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.")

@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.")


Input:
@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))

@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))


Input:
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

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


Input:
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()

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()


Input:
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

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


Input:
    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

    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


Input:
@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)

@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)


Input:
    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()

    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()


Input:
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

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


Input:
@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)

@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)


Input:
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()

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()


Input:
    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.'

    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.'


Input:
@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)

@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)


Input:
  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('_', ' ')

  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('_', ' ')


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

        old_tasks = db.engine.execute(old_locks_query)

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

        for old_task in old_tasks:
            task = Task.get(old_task[0], project_id)
            task.auto_unlock_expired_tasks(expiry_date, lock_duration)

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

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

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

        for old_task in old_tasks:
            task = Task.get(old_task[0], project_id)
            task.auto_unlock_expired_tasks(expiry_date, lock_duration)


Input:
def shame_ask(name):
    db = db_connect()
    cursor = db.cursor()
    try:
        cursor.execute('''
            SELECT shame FROM people WHERE name='{}'
            '''.format(name))
        shame = cursor.fetchone()
        db.close()
        if shame is None:
            logger.debug('No shame found for name {}'.format(name))
            return shame
        else:
            shame = shame[0]
            logger.debug('shame of {} found for name {}'.format(shame, name))
            return shame
    except Exception as e:
        logger.error('Execution failed with error: {}'.format(e))
        raise

def shame_ask(name):
    db = db_connect()
    cursor = db.cursor()
    try:
        cursor.execute('''
            SELECT shame FROM people WHERE name=%(name)s
            ''', (name, ))
        shame = cursor.fetchone()
        db.close()
        if shame is None:
            logger.debug('No shame found for name {}'.format(name))
            return shame
        else:
            shame = shame[0]
            logger.debug('shame of {} found for name {}'.format(shame, name))
            return shame
    except Exception as e:
        logger.error('Execution failed with error: {}'.format(e))
        raise


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

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

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

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

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

	return redirect(url_for('index'))

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

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

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

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

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

	return redirect(url_for('index'))


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

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

    return render_template('comment/edit.html', m=m, cmt_id=cmt_id)

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

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

    return render_template('comment/edit.html', m=m, cmt_id=cmt_id)


Input:
@app.route('/quiz')
def quiz():

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

    try:
        rows =[]

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

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

            return render_template('quiz.html', rows=rows, paryaya=paryaya, varga=varga)
    finally:
        con.close()

@app.route('/quiz')
def quiz():

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

    try:
        rows =[]

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

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

            return render_template('quiz.html', rows=rows, paryaya=paryaya, varga=varga)
    finally:
        con.close()


Input:
    def add_month_data_row(self, inverter_serial, ts, etoday, etotal):

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

        query = '''
            INSERT INTO MonthData (
                TimeStamp,
                Serial,
                DayYield,
                TotalYield
            ) VALUES (
                %s,
                %s,
                %s,
                %s
            );
        ''' % (y_ts, inverter_serial, etoday, etotal)
        self.c.execute(query)

    def add_month_data_row(self, inverter_serial, ts, etoday, etotal):

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

        query = '''
            INSERT INTO MonthData (
                TimeStamp,
                Serial,
                DayYield,
                TotalYield
            ) VALUES (
                ?,
                ?,
                ?,
                ?
            );
        '''
        self.c.execute(query, (y_ts, inverter_serial, etoday, etotal))


Input:
def karma_ask(name):
    db = db_connect()
    cursor = db.cursor()
    try:
        cursor.execute(
            ''' SELECT karma FROM people WHERE name='{}' '''.format(name))
        karma = cursor.fetchone()
        if karma is None:
            logger.debug('No karma found for name {}'.format(name))
            db.close()
            return karma
        else:
            karma = karma[0]
            logger.debug('karma of {} found for name {}'.format(karma, name))
            db.close()
            return karma
    except Exception as e:
        logger.error('Execution failed with error: {}'.format(e))
        raise

def karma_ask(name):
    db = db_connect()
    cursor = db.cursor()
    try:
        cursor.execute(''' SELECT karma FROM people WHERE name=%(name)s ''',
                       (name, ))
        karma = cursor.fetchone()
        if karma is None:
            logger.debug('No karma found for name {}'.format(name))
            db.close()
            return karma
        else:
            karma = karma[0]
            logger.debug('karma of {} found for name {}'.format(karma, name))
            db.close()
            return karma
    except Exception as e:
        logger.error('Execution failed with error: {}'.format(e))
        raise


Input:
    def post(self):
        """ Returns JWT upon login verification """
        json_data = request.get_json()
        if not json_data['email']:
            return jsonify({"msg": "Missing email"}), 400

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

            resp = jsonify({"login": True})
            set_access_cookies(resp, access_token)
            set_refresh_cookies(resp, refresh_token)
            return resp
        else:
            return jsonify({"msg": "User is not an admin"})

    def post(self):
        """ Returns JWT upon login verification """
        json_data = request.get_json()
        if not json_data['email']:
            return jsonify({"msg": "Missing email"}), 400

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

            resp = jsonify({"login": True})
            set_access_cookies(resp, access_token)
            set_refresh_cookies(resp, refresh_token)
            return resp
        else:
            return jsonify({"msg": "User is not an admin"})


Input:
    def store_metadata(self, session, key, mType, value):
        if (self.idNormalizer is not None):
            id = self.idNormalizer.process_string(session, id)
        elif type(id) == unicode:
            id = id.encode('utf-8')
        else:
            id = str(id)
        self._openContainer(session)
        query = ("UPDATE %s SET %s = %r WHERE identifier = '%s';" %
                 (self.table, mType, value, id)
                 )
        try:
            self._query(query)
        except:
            return None
        return value

    def store_metadata(self, session, key, mType, value):
        if (self.idNormalizer is not None):
            id = self.idNormalizer.process_string(session, id)
        elif type(id) == unicode:
            id = id.encode('utf-8')
        else:
            id = str(id)
        self._openContainer(session)
        query = ("UPDATE %s SET %s = $1 WHERE identifier = $2;" %
                 (self.table, mType)
                 )
        args = (value, id)
        try:
            self._query(query, *args)
        except:
            return None
        return value


Input:
def get_top_author(top_num):
    """ query the top(top_num) popular author
        top_num => list of [author, count]
    """
    cmd = """SELECT authors.name,author_result.num
                    FROM authors JOIN
                    (SELECT SUM(article_result.num) as num,
                    article_result.author
                    from (SELECT articles.title, articles.author,
                    SUM(log.views) AS num
                    FROM articles
                    INNER JOIN (
                    SELECT path, count(path) AS views
                    FROM log GROUP BY log.path
                    ) AS log ON log.path = '/article/'
                    || articles.slug
                    GROUP BY articles.title, articles.author)
                    AS article_result
                    GROUP BY article_result.author) as author_result
                    ON authors.id = author_result.author
                    ORDER BY num DESC LIMIT {}""".format(top_num)
    return execute_query(cmd)

def get_top_author(top_num):
    """ query the top(top_num) popular author
        top_num => list of [author, count]
    """
    cmd = """SELECT authors.name,author_result.num
                    FROM authors JOIN
                    (SELECT SUM(article_result.num) as num,
                    article_result.author
                    from (SELECT articles.title, articles.author,
                    SUM(log.views) AS num
                    FROM articles
                    INNER JOIN (
                    SELECT path, count(path) AS views
                    FROM log GROUP BY log.path
                    ) AS log ON log.path = '/article/'
                    || articles.slug
                    GROUP BY articles.title, articles.author)
                    AS article_result
                    GROUP BY article_result.author) as author_result
                    ON authors.id = author_result.author
                    ORDER BY num DESC LIMIT %s"""
    data = [top_num, ]
    return execute_query(cmd, data)


Input:
@app.route('/get_all_referrers')
def get_all_referrers():
    account_id = request.args.get('account_id')

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

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

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

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

    return jsonify(results)

@app.route('/get_all_referrers')
def get_all_referrers():
    account_id = request.args.get('account_id')

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

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

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

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

    return jsonify(results)


Input:
def findNPC(race, classe, sex,level):
	c, conn = getConnection()
	date = now()
	#select image, SUM(legit) as l FROM npc WHERE race='Elf' AND class='Bard' AND sex='Male' GROUP BY image HAVING l>5 ORDER BY SUM(legit) DESC;
	c.execute("select image, avg(legit) as l FROM npc WHERE race='"+race+"' AND class='"+classe+"' AND sex='"+sex+"' GROUP BY image HAVING l > 5 ORDER BY SUM(legit) DESC;")
	conn.commit()
	out = c.fetchmany(5)
	conn.close()
	return out

def findNPC(race, classe, sex,level):
	c, conn = getConnection()
	date = now()
	#select image, SUM(legit) as l FROM npc WHERE race='Elf' AND class='Bard' AND sex='Male' GROUP BY image HAVING l>5 ORDER BY SUM(legit) DESC;
	c.execute("select image, avg(legit) as l FROM npc WHERE race=(?) AND class=(?) AND sex=(?) GROUP BY image HAVING l > 5 ORDER BY SUM(legit) DESC",(race,classe,sex))
	conn.commit()
	out = c.fetchmany(5)
	conn.close()
	return out


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

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

    return render_template('message/edit.html', m=m, msg_id=msg_id)

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

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

    return render_template('message/edit.html', m=m, msg_id=msg_id)


Input:
@bot.message_handler(func = lambda message: get_current_state(message.chat.id) == config.States.S_LOGIN.value)
def get_login2(message):
    settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\settings.db")
    conn = settings.cursor()
    if bases.createuserbase.check_username(message.text):
        bot.send_message(message.chat.id, "Invalid handle.")
        set_state(message.chat.id, config.States.S_START.value)
        return 0

    conn.execute("select * from users where chat_id = '" + str(message.chat.id) + "'")
    name = conn.fetchone()
    settings.close()
    bases.update.cf_update()
    bases.createuserbase.clean_base(name[1])
    bases.createuserbase.clean_base(message.text)
    bot.send_message(message.chat.id, "Creating base...")
    bases.createuserbase.init_user(message.text, message.chat.id)
    bot.send_message(message.chat.id, "Done!")
    set_state(message.chat.id, config.States.S_START.value)

@bot.message_handler(func = lambda message: get_current_state(message.chat.id) == config.States.S_LOGIN.value)
def get_login2(message):
    settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\settings.db")
    conn = settings.cursor()
    if bases.createuserbase.check_username(message.text):
        bot.send_message(message.chat.id, "Invalid handle.")
        set_state(message.chat.id, config.States.S_START.value)
        return 0
    conn.execute("select * from users where chat_id = ?", (str(message.chat.id),))
    name = conn.fetchone()
    settings.close()
    bases.update.cf_update()
    bases.createuserbase.clean_base(name[1])
    bases.createuserbase.clean_base(message.text)
    bot.send_message(message.chat.id, "Creating base...")
    bases.createuserbase.init_user(message.text, message.chat.id)
    bot.send_message(message.chat.id, "Done!")
    set_state(message.chat.id, config.States.S_START.value)


Input:
@app.route('/referrer_count')
def referrer_count():
    account_id = request.args.get('account_id')

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

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

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

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

    return jsonify(results)

@app.route('/referrer_count')
def referrer_count():
    account_id = request.args.get('account_id')

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

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

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

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

    return jsonify(results)


Input:
@mod.route('/edit', methods=['GET', 'POST'])
def edit():
    sql = "SELECT * FROM users where email = '%s';" % (session['logged_email'])
    cursor.execute(sql)
    u = cursor.fetchone()
    if request.method == 'POST':
        sql = "UPDATE users SET nickname = '%s' where email = '%s'" \
        % (request.form['nickname'], session['logged_email'])
        cursor.execute(sql)
        sql = "SELECT * FROM users where email = '%s';" \
            % (session['logged_email'])
        cursor.execute(sql)
        u = cursor.fetchone()
        conn.commit()
        flash('Edit Nickname Success!')
    return render_template('users/edit.html', u=u)

@mod.route('/edit', methods=['GET', 'POST'])
def edit():
    cursor.execute("SELECT * FROM users where email = %s;", (session['logged_email'],))
    u = cursor.fetchone()
    if request.method == 'POST':
        cursor.execute("UPDATE users SET nickname = %s where email = %s", (request.form['nickname'], session['logged_email']))
        cursor.execute("SELECT * FROM users where email = %s;", (session['logged_email'],))
        u = cursor.fetchone()
        conn.commit()
        flash('Edit Nickname Success!')
    return render_template('users/edit.html', u=u)


Input:
def shame_add(name):
    shame = shame_ask(name)
    db = db_connect()
    cursor = db.cursor()
    if shame is None:
        try:
            cursor.execute('''
                INSERT INTO people(name,karma,shame) VALUES('{}',0,1)
                '''.format(name))
            db.commit()
            logger.debug('Inserted into karmadb 1 shame for {}'.format(name))
            db.close()
            return 1
        except Exception as e:
            logger.error('Execution failed with error: {}'.format(e))
            raise

    else:
        shame = shame + 1
        try:
            cursor.execute('''
                UPDATE people SET shame = {0} WHERE name = '{1}'
                '''.format(shame, name))
            db.commit()
            logger.debug('Inserted into karmadb {} shame for {}'.format(
                shame, name))
            db.close()
            return shame
        except Exception as e:
            logger.error('Execution failed with error: {}'.format(e))
            raise

def shame_add(name):
    shame = shame_ask(name)
    db = db_connect()
    cursor = db.cursor()
    if shame is None:
        try:
            cursor.execute('''
                INSERT INTO people(name,karma,shame) VALUES(%(name)s,0,1)
                ''', (name, ))
            db.commit()
            logger.debug('Inserted into karmadb 1 shame for {}'.format(name))
            db.close()
            return 1
        except Exception as e:
            logger.error('Execution failed with error: {}'.format(e))
            raise

    else:
        shame = shame + 1
        try:
            cursor.execute('''
                UPDATE people SET shame = %(karma)s WHERE name = %(name)s
                ''' (
                shame,
                name,
            ))
            db.commit()
            logger.debug('Inserted into karmadb {} shame for {}'.format(
                shame, name))
            db.close()
            return shame
        except Exception as e:
            logger.error('Execution failed with error: {}'.format(e))
            raise


Input:
@hook.command(autohelp=False)
def showPoll(pollID, db=None):
    """Shows the answers for a given poll."""
    if not db_ready: db_init(db)
    if pollID == None:
        poll = db.execute("SELECT pollID, question FROM polls WHERE active = 1")
        if len(poll) == 0:
            reply("There's no poll open.")
            return
    else:
        poll = db.execute("SELECT pollID, question FROM polls WHERE pollID = '{}'".format(pollID))
        if len(poll) == 0:
            reply("No such poll found.")
            return
    pollID = poll[0][0]
    question = poll[0][1]
    reply(question)
    for (index, answer, votes) in db.execute("SELECT 'index', answer, count(voteID) FROM answers LEFT JOIN votes ON votes.answerID = answers.answerID WHERE pollID = {} GROUP BY answers.answerID, 'index', answer ORDER BY 'index' ASC".format(pollID, )):
        reply("%s. %s (%s)" % (index, answer, votes))

@hook.command(autohelp=False)
def showPoll(pollID, db=None):
    """Shows the answers for a given poll."""
    if not db_ready: db_init(db)
    if pollID == None:
        poll = db.execute("SELECT pollID, question FROM polls WHERE active = 1")
        if len(poll) == 0:
            reply("There's no poll open.")
            return
    else:
        poll = db.execute("SELECT pollID, question FROM polls WHERE pollID = ?", (pollID,))
        if len(poll) == 0:
            reply("No such poll found.")
            return
    pollID = poll[0][0]
    question = poll[0][1]
    reply(question)
    for (index, answer, votes) in db.execute("SELECT 'index', answer, count(voteID) FROM answers LEFT JOIN votes ON votes.answerID = answers.answerID WHERE pollID = ? GROUP BY answers.answerID, 'index', answer ORDER BY 'index' ASC", (pollID, )):
        reply("%s. %s (%s)" % (index, answer, votes))


Input:
    def analyze_smashgg(self, urls, name):
        LOG.info('we are about to analyze scene {} with {} brackets'.format(name, len(urls)))
        for url in urls:
            # Before we process this URL, check to see if we already have
            sql = "SELECT * FROM analyzed where base_url='{}'".format(url)
            res = self.db.exec(sql)
            if len(res) == 0:

                display_name = bracket_utils.get_display_base(url)

                # We don't care about doubles tournaments
                if 'doubles' in display_name.lower() or 'dubs' in display_name.lower():
                    LOG.info('We are skipping the tournament {} because it is a doubles tournament'.format(display_name))
                    continue

                LOG.info('About to process pro bracket {}'.format(url))
                self.data_processor.process(url, name, display_name)
            else:
                LOG.info("Skpping pro bracket because it has already been analyzed: {}".format(url))

    def analyze_smashgg(self, urls, name):
        LOG.info('we are about to analyze scene {} with {} brackets'.format(name, len(urls)))
        for url in urls:
            # Before we process this URL, check to see if we already have
            sql = "SELECT * FROM analyzed where base_url='{url}'"
            args = {'url':url}
            res = self.db.exec(sql, args)
            if len(res) == 0:

                display_name = bracket_utils.get_display_base(url)

                # We don't care about doubles tournaments
                if 'doubles' in display_name.lower() or 'dubs' in display_name.lower():
                    LOG.info('We are skipping the tournament {} because it is a doubles tournament'.format(display_name))
                    continue

                LOG.info('About to process pro bracket {}'.format(url))
                self.data_processor.process(url, name, display_name)
            else:
                LOG.info("Skpping pro bracket because it has already been analyzed: {}".format(url))


Input:
    @staticmethod
    def _add_to_db(user):
        """
        Adds User object to the database
        :param user: User object with info about user
        :return: None
        """
        query = ("INSERT INTO users (chat_id, first_name, nickname, "
                 "last_name, language) "
                 f"VALUES ({user.chat_id}, '{user.first_name}', "
                 f"'{user.nickname}', '{user.last_name}', '{user.language}')")
        try:
            db.add(query)
        except DatabaseError:
            log.error("Cannot add user to the database")
        else:
            log.info(f"User {user} was successfully added to the users db")

    @staticmethod
    def _add_to_db(user):
        """
        Adds User object to the database
        :param user: User object with info about user
        :return: None
        """
        query = ("INSERT INTO users (chat_id, first_name, nickname, "
                 "last_name, language) "
                 f"VALUES (%s, %s, %s, %s, %s)")

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

        try:
            db.add(query, parameters)
        except DatabaseError:
            log.error("Cannot add user to the database")
        else:
            log.info(f"User {user} was successfully added to the users db")


Input:
static void set_fdc(int drive)
{
	if (drive >= 0 && drive < N_DRIVE) {
		fdc = FDC(drive);
		current_drive = drive;
	}
	if (fdc != 1 && fdc != 0) {
		pr_info("bad fdc value\n");
		return;
	}
	set_dor(fdc, ~0, 8);
#if N_FDC > 1
	set_dor(1 - fdc, ~8, 0);
#endif
	if (FDCS->rawcmd == 2)
		reset_fdc_info(1);
	if (fd_inb(FD_STATUS) != STATUS_READY)
		FDCS->reset = 1;
}

static void set_fdc(int drive)
{
	unsigned int new_fdc = fdc;

	if (drive >= 0 && drive < N_DRIVE) {
		new_fdc = FDC(drive);
		current_drive = drive;
	}
	if (new_fdc >= N_FDC) {
		pr_info("bad fdc value\n");
		return;
	}
	fdc = new_fdc;
	set_dor(fdc, ~0, 8);
#if N_FDC > 1
	set_dor(1 - fdc, ~8, 0);
#endif
	if (FDCS->rawcmd == 2)
		reset_fdc_info(1);
	if (fd_inb(FD_STATUS) != STATUS_READY)
		FDCS->reset = 1;
}


Input:
BOOL glyph_cache_put(rdpGlyphCache* glyphCache, UINT32 id, UINT32 index, rdpGlyph* glyph)
{
	rdpGlyph* prevGlyph;

	if (id > 9)
	{
		WLog_ERR(TAG, "invalid glyph cache id: %" PRIu32 "", id);
		return FALSE;
	}

	if (index > glyphCache->glyphCache[id].number)
	{
		WLog_ERR(TAG, "invalid glyph cache index: %" PRIu32 " in cache id: %" PRIu32 "", index, id);
		return FALSE;
	}

	WLog_Print(glyphCache->log, WLOG_DEBUG, "GlyphCachePut: id: %" PRIu32 " index: %" PRIu32 "", id,
	           index);
	prevGlyph = glyphCache->glyphCache[id].entries[index];

	if (prevGlyph)
		prevGlyph->Free(glyphCache->context, prevGlyph);

	glyphCache->glyphCache[id].entries[index] = glyph;
	return TRUE;
}

BOOL glyph_cache_put(rdpGlyphCache* glyphCache, UINT32 id, UINT32 index, rdpGlyph* glyph)
{
	rdpGlyph* prevGlyph;

	if (id > 9)
	{
		WLog_ERR(TAG, "invalid glyph cache id: %" PRIu32 "", id);
		return FALSE;
	}

	if (index >= glyphCache->glyphCache[id].number)
	{
		WLog_ERR(TAG, "invalid glyph cache index: %" PRIu32 " in cache id: %" PRIu32 "", index, id);
		return FALSE;
	}

	WLog_Print(glyphCache->log, WLOG_DEBUG, "GlyphCachePut: id: %" PRIu32 " index: %" PRIu32 "", id,
	           index);
	prevGlyph = glyphCache->glyphCache[id].entries[index];

	if (prevGlyph)
		prevGlyph->Free(glyphCache->context, prevGlyph);

	glyphCache->glyphCache[id].entries[index] = glyph;
	return TRUE;
}


Input:
Status GraphConstructor::MakeEdge(Node* src, int output_index, Node* dst,
                                  int input_index) {
  DataType src_out = src->output_type(output_index);
  DataType dst_in = dst->input_type(input_index);
  if (!TypesCompatible(dst_in, src_out)) {
    return errors::InvalidArgument(
        "Input ", input_index, " of node ", dst->name(), " was passed ",
        DataTypeString(src_out), " from ", src->name(), ":", output_index,
        " incompatible with expected ", DataTypeString(dst_in), ".");
  }
  g_->AddEdge(src, output_index, dst, input_index);
  return Status::OK();
}

Status GraphConstructor::MakeEdge(Node* src, int output_index, Node* dst,
                                  int input_index) {
  if (output_index >= src->num_outputs()) {
    return errors::InvalidArgument(
        "Output ", output_index, " of node ", src->name(),
        " does not exist. Node only has ", src->num_outputs(), " outputs.");
  }
  if (input_index >= dst->num_inputs()) {
    return errors::InvalidArgument(
        "Input ", input_index, " of node ", dst->name(),
        " does not exist. Node only has ", dst->num_inputs(), " inputs.");
  }

  DataType src_out = src->output_type(output_index);
  DataType dst_in = dst->input_type(input_index);
  if (!TypesCompatible(dst_in, src_out)) {
    return errors::InvalidArgument(
        "Input ", input_index, " of node ", dst->name(), " was passed ",
        DataTypeString(src_out), " from ", src->name(), ":", output_index,
        " incompatible with expected ", DataTypeString(dst_in), ".");
  }
  g_->AddEdge(src, output_index, dst, input_index);
  return Status::OK();
}


Input:
  static bool TryParse(const char* inp, int length,
                       TypedValue* buf, Variant& out,
                       JSONContainerType container_type, bool is_tsimplejson) {
    SimpleParser parser(inp, length, buf, container_type, is_tsimplejson);
    bool ok = parser.parseValue();
    parser.skipSpace();
    if (!ok || parser.p != inp + length) {
      // Unsupported, malformed, or trailing garbage. Release entire stack.
      tvDecRefRange(buf, parser.top);
      return false;
    }
    out = Variant::attach(*--parser.top);
    return true;
  }

  static bool TryParse(const char* inp, int length,
                       TypedValue* buf, Variant& out,
                       JSONContainerType container_type, bool is_tsimplejson) {
    SimpleParser parser(inp, length, buf, container_type, is_tsimplejson);
    bool ok = parser.parseValue();
    if (!ok ||
        (parser.skipSpace(), parser.p != inp + length)) {
      // Unsupported, malformed, or trailing garbage. Release entire stack.
      tvDecRefRange(buf, parser.top);
      return false;
    }
    out = Variant::attach(*--parser.top);
    return true;
  }


Input:
static void exif_process_APP12(image_info_type *ImageInfo,
                               char *buffer, size_t length) {
  size_t l1, l2=0;
  if ((l1 = php_strnlen(buffer+2, length-2)) > 0) {
    exif_iif_add_tag(ImageInfo, SECTION_APP12, "Company",
                     TAG_NONE, TAG_FMT_STRING, l1, buffer+2);
    if (length > 2+l1+1) {
      l2 = php_strnlen(buffer+2+l1+1, length-2-l1+1);
      exif_iif_add_tag(ImageInfo, SECTION_APP12, "Info",
                       TAG_NONE, TAG_FMT_STRING, l2, buffer+2+l1+1);
    }
  }
}

static void exif_process_APP12(image_info_type *ImageInfo,
                               char *buffer, size_t length) {
  size_t l1, l2=0;
  if ((l1 = php_strnlen(buffer+2, length-2)) > 0) {
    exif_iif_add_tag(ImageInfo, SECTION_APP12, "Company",
                     TAG_NONE, TAG_FMT_STRING, l1, buffer+2);
    if (length > 2+l1+1) {
      l2 = php_strnlen(buffer+2+l1+1, length-2-l1-1);
      exif_iif_add_tag(ImageInfo, SECTION_APP12, "Info",
                       TAG_NONE, TAG_FMT_STRING, l2, buffer+2+l1+1);
    }
  }
}


Input:
str_lower_case_match(OnigEncoding enc, int case_fold_flag,
                     const UChar* t, const UChar* tend,
                     const UChar* p, const UChar* end)
{
  int lowlen;
  UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];

  while (t < tend) {
    lowlen = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &p, end, lowbuf);
    q = lowbuf;
    while (lowlen > 0) {
      if (*t++ != *q++) return 0;
      lowlen--;
    }
  }

  return 1;
}

str_lower_case_match(OnigEncoding enc, int case_fold_flag,
                     const UChar* t, const UChar* tend,
                     const UChar* p, const UChar* end)
{
  int lowlen;
  UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];

  while (t < tend) {
    lowlen = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &p, end, lowbuf);
    q = lowbuf;
    while (lowlen > 0) {
      if (t >= tend)    return 0;
      if (*t++ != *q++) return 0;
      lowlen--;
    }
  }

  return 1;
}


Input:
static int sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
	ut8 op_MSB,op_LSB;
	int ret;
	if (!data)
		return 0;
	memset (op, '\0', sizeof (RAnalOp));
	op->addr = addr;
	op->type = R_ANAL_OP_TYPE_UNK;
	op->jump = op->fail = -1;
	op->ptr = op->val = -1;

	op->size = 2;

	op_MSB = anal->big_endian? data[0]: data[1];
	op_LSB = anal->big_endian? data[1]: data[0];
	ret =  first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB));
	return ret;
}

static int sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
	ut8 op_MSB,op_LSB;
	int ret;
	if (!data || len < 2) {
		return 0;
	}
	memset (op, '\0', sizeof (RAnalOp));
	op->addr = addr;
	op->type = R_ANAL_OP_TYPE_UNK;
	op->jump = op->fail = -1;
	op->ptr = op->val = -1;

	op->size = 2;

	op_MSB = anal->big_endian? data[0]: data[1];
	op_LSB = anal->big_endian? data[1]: data[0];
	ret =  first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB));
	return ret;
}


Input:
int string_rfind(const char *input, int len, const char *s, int s_len,
                 int pos, bool case_sensitive) {
  assertx(input);
  assertx(s);
  if (!s_len || pos < -len || pos > len) {
    return -1;
  }
  void *ptr;
  if (case_sensitive) {
    if (pos >= 0) {
      ptr = bstrrstr(input + pos, len - pos, s, s_len);
    } else {
      ptr = bstrrstr(input, len + pos + s_len, s, s_len);
    }
  } else {
    if (pos >= 0) {
      ptr = bstrrcasestr(input + pos, len - pos, s, s_len);
    } else {
      ptr = bstrrcasestr(input, len + pos + s_len, s, s_len);
    }
  }
  if (ptr != nullptr) {
    return (int)((const char *)ptr - input);
  }
  return -1;
}

int string_rfind(const char *input, int len, const char *s, int s_len,
                 int pos, bool case_sensitive) {
  assertx(input);
  assertx(s);
  if (!s_len || pos < -len || pos > len) {
    return -1;
  }
  void *ptr;
  if (case_sensitive) {
    if (pos >= 0) {
      ptr = bstrrstr(input + pos, len - pos, s, s_len);
    } else {
      ptr = bstrrstr(input, len + std::min(pos + s_len, 0), s, s_len);
    }
  } else {
    if (pos >= 0) {
      ptr = bstrrcasestr(input + pos, len - pos, s, s_len);
    } else {
      ptr = bstrrcasestr(input, len + std::min(pos + s_len, 0), s, s_len);
    }
  }
  if (ptr != nullptr) {
    return (int)((const char *)ptr - input);
  }
  return -1;
}


Input:
@app.route('/delete_video/<filename>')
def delete_video(filename):
	if 'username' in session:
		#os.remove("static/videos/{}".format(filename))
		print(session['username'], file=sys.stdout)
		data=users.query.filter_by(Username=session['username']).first()
		video=Video.query.filter_by(UserID=data.UserID,Name=filename).first()
		if video != None:
			os.remove("static/videos/{}".format(filename))
			db.session.delete(video)
			db.session.commit()
		else:
			return "Don't delete other people's videos!"
		return redirect(url_for('upload'))
	return "test"

@app.route('/delete_video/<filename>')
def delete_video(filename):
	if 'username' in session:
		#os.remove("static/videos/{}".format(filename))
		print(session['username'], file=sys.stdout)
		data=users.query.filter_by(Username=session['username']).first()
		video=Video.query.filter_by(UserID=data.UserID,Name=filename).first()
		if video != None:
			#os.remove("static/videos/{}".format(filename))
			os.system("rm static/videos/{}".format(filename))
			db.session.delete(video)
			db.session.commit()
		else:
			return "Don't delete other people's videos!"
		return redirect(url_for('upload'))
	return "test"


Input:
    def extend_volume(self, volume, new_size):
        LOG.debug(_('enter: extend_volume: volume %s') % volume['id'])
        ret = self._ensure_vdisk_no_fc_mappings(volume['name'],
                                                allow_snaps=False)
        if not ret:
            exception_message = (_('extend_volume: Extending a volume with '
                                   'snapshots is not supported.'))
            raise exception.VolumeBackendAPIException(data=exception_message)

        extend_amt = int(new_size) - volume['size']
        ssh_cmd = ('svctask expandvdisksize -size %(amt)d -unit gb %(name)s'
                   % {'amt': extend_amt, 'name': volume['name']})
        out, err = self._run_ssh(ssh_cmd)
        # No output should be returned from expandvdisksize
        self._assert_ssh_return(len(out.strip()) == 0, 'extend_volume',
                                ssh_cmd, out, err)
        LOG.debug(_('leave: extend_volume: volume %s') % volume['id'])

    def extend_volume(self, volume, new_size):
        LOG.debug(_('enter: extend_volume: volume %s') % volume['id'])
        ret = self._ensure_vdisk_no_fc_mappings(volume['name'],
                                                allow_snaps=False)
        if not ret:
            exception_message = (_('extend_volume: Extending a volume with '
                                   'snapshots is not supported.'))
            raise exception.VolumeBackendAPIException(data=exception_message)

        extend_amt = int(new_size) - volume['size']
        ssh_cmd = (['svctask', 'expandvdisksize', '-size', str(extend_amt),
                    '-unit', 'gb', volume['name']])
        out, err = self._run_ssh(ssh_cmd)
        # No output should be returned from expandvdisksize
        self._assert_ssh_return(len(out.strip()) == 0, 'extend_volume',
                                ssh_cmd, out, err)
        LOG.debug(_('leave: extend_volume: volume %s') % volume['id'])


Input:
    def _get_hostvdisk_mappings(self, host_name):
        """Return the defined storage mappings for a host."""

        return_data = {}
        ssh_cmd = 'svcinfo lshostvdiskmap -delim ! %s' % host_name
        out, err = self._run_ssh(ssh_cmd)

        mappings = out.strip().split('\n')
        if len(mappings):
            header = mappings.pop(0)
            for mapping_line in mappings:
                mapping_data = self._get_hdr_dic(header, mapping_line, '!')
                return_data[mapping_data['vdisk_name']] = mapping_data

        return return_data

    def _get_hostvdisk_mappings(self, host_name):
        """Return the defined storage mappings for a host."""

        return_data = {}
        ssh_cmd = ['svcinfo', 'lshostvdiskmap', '-delim', '!', host_name]
        out, err = self._run_ssh(ssh_cmd)

        mappings = out.strip().split('\n')
        if len(mappings):
            header = mappings.pop(0)
            for mapping_line in mappings:
                mapping_data = self._get_hdr_dic(header, mapping_line, '!')
                return_data[mapping_data['vdisk_name']] = mapping_data

        return return_data


Input:
    def _get_vvset_from_3par(self, volume_name):
        """Get Virtual Volume Set from 3PAR.

        The only way to do this currently is to try and delete the volume
        to get the error message.

        NOTE(walter-boring): don't call this unless you know the volume is
        already in a vvset!
        """
        cmd = "removevv -f %s" % volume_name
        LOG.debug("Issuing remove command to find vvset name %s" % cmd)
        out = self._cli_run(cmd, None)
        vvset_name = None
        if out and len(out) > 1:
            if out[1].startswith("Attempt to delete "):
                words = out[1].split(" ")
                vvset_name = words[len(words) - 1]

        return vvset_name

    def _get_vvset_from_3par(self, volume_name):
        """Get Virtual Volume Set from 3PAR.

        The only way to do this currently is to try and delete the volume
        to get the error message.

        NOTE(walter-boring): don't call this unless you know the volume is
        already in a vvset!
        """
        cmd = ['removevv', '-f', volume_name]
        LOG.debug("Issuing remove command to find vvset name %s" % cmd)
        out = self._cli_run(cmd)
        vvset_name = None
        if out and len(out) > 1:
            if out[1].startswith("Attempt to delete "):
                words = out[1].split(" ")
                vvset_name = words[len(words) - 1]

        return vvset_name


Input:
    def _add_volume_to_volume_set(self, volume, volume_name,
                                  cpg, vvs_name, qos):
        if vvs_name is not None:
            # Admin has set a volume set name to add the volume to
            self._cli_run('createvvset -add %s %s' % (vvs_name,
                                                      volume_name), None)
        else:
            vvs_name = self._get_3par_vvs_name(volume['id'])
            domain = self.get_domain(cpg)
            self._cli_run('createvvset -domain %s %s' % (domain,
                                                         vvs_name), None)
            self._set_qos_rule(qos, vvs_name)
            self._cli_run('createvvset -add %s %s' % (vvs_name,
                                                      volume_name), None)

    def _add_volume_to_volume_set(self, volume, volume_name,
                                  cpg, vvs_name, qos):
        if vvs_name is not None:
            # Admin has set a volume set name to add the volume to
            self._cli_run(['createvvset', '-add', vvs_name, volume_name])
        else:
            vvs_name = self._get_3par_vvs_name(volume['id'])
            domain = self.get_domain(cpg)
            self._cli_run(['createvvset', '-domain', domain, vvs_name])
            self._set_qos_rule(qos, vvs_name)
            self._cli_run(['createvvset', '-add', vvs_name, volume_name])


Input:
    def test_initialize_connection(self):
        self.driver._eql_execute = self.mox.\
            CreateMock(self.driver._eql_execute)
        volume = {'name': self.volume_name}
        self.stubs.Set(self.driver, "_get_iscsi_properties",
                       self._fake_get_iscsi_properties)
        self.driver._eql_execute('volume', 'select', volume['name'], 'access',
                                 'create', 'initiator',
                                 self.connector['initiator'],
                                 'authmethod chap',
                                 'username',
                                 self.configuration.eqlx_chap_login)
        self.mox.ReplayAll()
        iscsi_properties = self.driver.initialize_connection(volume,
                                                             self.connector)
        self.assertEqual(iscsi_properties['data'],
                         self._fake_get_iscsi_properties(volume))

    def test_initialize_connection(self):
        self.driver._eql_execute = self.mox.\
            CreateMock(self.driver._eql_execute)
        volume = {'name': self.volume_name}
        self.stubs.Set(self.driver, "_get_iscsi_properties",
                       self._fake_get_iscsi_properties)
        self.driver._eql_execute('volume', 'select', volume['name'], 'access',
                                 'create', 'initiator',
                                 self.connector['initiator'],
                                 'authmethod', 'chap',
                                 'username',
                                 self.configuration.eqlx_chap_login)
        self.mox.ReplayAll()
        iscsi_properties = self.driver.initialize_connection(volume,
                                                             self.connector)
        self.assertEqual(iscsi_properties['data'],
                         self._fake_get_iscsi_properties(volume))


Input:
    def _get_fc_wwpns(self):
        for key in self._storage_nodes:
            node = self._storage_nodes[key]
            ssh_cmd = 'svcinfo lsnode -delim ! %s' % node['id']
            raw = self._run_ssh(ssh_cmd)
            resp = CLIResponse(raw, delim='!', with_header=False)
            wwpns = set(node['WWPN'])
            for i, s in resp.select('port_id', 'port_status'):
                if 'unconfigured' != s:
                    wwpns.add(i)
            node['WWPN'] = list(wwpns)
            LOG.info(_('WWPN on node %(node)s: %(wwpn)s')
                     % {'node': node['id'], 'wwpn': node['WWPN']})

    def _get_fc_wwpns(self):
        for key in self._storage_nodes:
            node = self._storage_nodes[key]
            ssh_cmd = ['svcinfo', 'lsnode', '-delim', '!', node['id']]
            raw = self._run_ssh(ssh_cmd)
            resp = CLIResponse(raw, delim='!', with_header=False)
            wwpns = set(node['WWPN'])
            for i, s in resp.select('port_id', 'port_status'):
                if 'unconfigured' != s:
                    wwpns.add(i)
            node['WWPN'] = list(wwpns)
            LOG.info(_('WWPN on node %(node)s: %(wwpn)s')
                     % {'node': node['id'], 'wwpn': node['WWPN']})


Input:
    def add_extra_args(self, args=None):
        """Add more args depending on how known args are set."""
        parsed = vars(self.parse_known_args(nohelp=True)[0])

        # find which image mode specified if any, and add additional arguments
        image_mode = parsed.get('image_mode', None)
        if image_mode is not None and image_mode != 'none':
            self.add_image_args(image_mode)

        # find which task specified if any, and add its specific arguments
        task = parsed.get('task', None)
        if task is not None:
            self.add_task_args(task)
        evaltask = parsed.get('evaltask', None)
        if evaltask is not None:
            self.add_task_args(evaltask)

        # find which model specified if any, and add its specific arguments
        model = parsed.get('model', None)
        if model is not None:
            self.add_model_subargs(model)

        # reset parser-level defaults over any model-level defaults
        try:
            self.set_defaults(**self._defaults)
        except AttributeError:
            raise RuntimeError('Please file an issue on github that argparse '
                               'got an attribute error when parsing.')

    def add_extra_args(self, args=None):
        """Add more args depending on how known args are set."""
        parsed = vars(self.parse_known_args(args, nohelp=True)[0])

        # find which image mode specified if any, and add additional arguments
        image_mode = parsed.get('image_mode', None)
        if image_mode is not None and image_mode != 'none':
            self.add_image_args(image_mode)

        # find which task specified if any, and add its specific arguments
        task = parsed.get('task', None)
        if task is not None:
            self.add_task_args(task)
        evaltask = parsed.get('evaltask', None)
        if evaltask is not None:
            self.add_task_args(evaltask)

        # find which model specified if any, and add its specific arguments
        model = parsed.get('model', None)
        if model is not None:
            self.add_model_subargs(model)

        # reset parser-level defaults over any model-level defaults
        try:
            self.set_defaults(**self._defaults)
        except AttributeError:
            raise RuntimeError('Please file an issue on github that argparse '
                               'got an attribute error when parsing.')


Input:
    def _copy_volume(self, src_name, dest_name, cpg=None, snap_cpg=None,
                     tpvv=True):
        # Virtual volume sets are not supported with the -online option
        cmd = 'createvvcopy -p %s -online ' % src_name
        if snap_cpg:
            cmd += '-snp_cpg %s ' % snap_cpg
        if tpvv:
            cmd += '-tpvv '
        if cpg:
            cmd += cpg + ' '
        cmd += dest_name
        LOG.debug('Creating clone of a volume with %s' % cmd)
        self._cli_run(cmd, None)

    def _copy_volume(self, src_name, dest_name, cpg=None, snap_cpg=None,
                     tpvv=True):
        # Virtual volume sets are not supported with the -online option
        cmd = ['createvvcopy', '-p', src_name, '-online']
        if snap_cpg:
            cmd.extend(['-snp_cpg', snap_cpg])
        if tpvv:
            cmd.append('-tpvv')
        if cpg:
            cmd.append(cpg)
        cmd.append(dest_name)
        LOG.debug('Creating clone of a volume with %s' % cmd)
        self._cli_run(cmd)


Input:
    def initialize_connection(self, volume, connector):
        """Restrict access to a volume."""
        try:
            cmd = ['volume', 'select', volume['name'], 'access', 'create',
                   'initiator', connector['initiator']]
            if self.configuration.eqlx_use_chap:
                cmd.extend(['authmethod chap', 'username',
                            self.configuration.eqlx_chap_login])
            self._eql_execute(*cmd)
            iscsi_properties = self._get_iscsi_properties(volume)
            return {
                'driver_volume_type': 'iscsi',
                'data': iscsi_properties
            }
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.error(_('Failed to initialize connection to volume %s'),
                          volume['name'])

    def initialize_connection(self, volume, connector):
        """Restrict access to a volume."""
        try:
            cmd = ['volume', 'select', volume['name'], 'access', 'create',
                   'initiator', connector['initiator']]
            if self.configuration.eqlx_use_chap:
                cmd.extend(['authmethod', 'chap', 'username',
                            self.configuration.eqlx_chap_login])
            self._eql_execute(*cmd)
            iscsi_properties = self._get_iscsi_properties(volume)
            return {
                'driver_volume_type': 'iscsi',
                'data': iscsi_properties
            }
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.error(_('Failed to initialize connection to volume %s'),
                          volume['name'])


Input:
bool IsBlacklistedArg(const base::CommandLine::CharType* arg) {
#if defined(OS_WIN)
  const auto converted = base::WideToUTF8(arg);
  const char* a = converted.c_str();
#else
  const char* a = arg;
#endif

  static const char* prefixes[] = {"--", "-", "/"};

  int prefix_length = 0;
  for (auto& prefix : prefixes) {
    if (base::StartsWith(a, prefix, base::CompareCase::SENSITIVE)) {
      prefix_length = strlen(prefix);
      break;
    }
  }

  if (prefix_length > 0) {
    a += prefix_length;
    std::string switch_name(a, strcspn(a, "="));
    auto* iter = std::lower_bound(std::begin(kBlacklist), std::end(kBlacklist),
                                  switch_name);
    if (iter != std::end(kBlacklist) && switch_name == *iter) {
      return true;
    }
  }

  return false;
}

bool IsBlacklistedArg(const base::CommandLine::CharType* arg) {
#if defined(OS_WIN)
  const auto converted = base::WideToUTF8(arg);
  const char* a = converted.c_str();
#else
  const char* a = arg;
#endif

  static const char* prefixes[] = {"--", "-", "/"};

  int prefix_length = 0;
  for (auto& prefix : prefixes) {
    if (base::StartsWith(a, prefix, base::CompareCase::SENSITIVE)) {
      prefix_length = strlen(prefix);
      break;
    }
  }

  if (prefix_length > 0) {
    a += prefix_length;
    std::string switch_name =
        base::ToLowerASCII(base::StringPiece(a, strcspn(a, "=")));
    auto* iter = std::lower_bound(std::begin(kBlacklist), std::end(kBlacklist),
                                  switch_name);
    if (iter != std::end(kBlacklist) && switch_name == *iter) {
      return true;
    }
  }

  return false;
}


Input:
    def _call_prepare_fc_map(self, fc_map_id, source, target):
        try:
            out, err = self._run_ssh('svctask prestartfcmap %s' % fc_map_id)
        except exception.ProcessExecutionError as e:
            with excutils.save_and_reraise_exception():
                LOG.error(_('_prepare_fc_map: Failed to prepare FlashCopy '
                            'from %(source)s to %(target)s.\n'
                            'stdout: %(out)s\n stderr: %(err)s')
                          % {'source': source,
                             'target': target,
                             'out': e.stdout,
                             'err': e.stderr})

    def _call_prepare_fc_map(self, fc_map_id, source, target):
        try:
            out, err = self._run_ssh(['svctask', 'prestartfcmap', fc_map_id])
        except exception.ProcessExecutionError as e:
            with excutils.save_and_reraise_exception():
                LOG.error(_('_prepare_fc_map: Failed to prepare FlashCopy '
                            'from %(source)s to %(target)s.\n'
                            'stdout: %(out)s\n stderr: %(err)s')
                          % {'source': source,
                             'target': target,
                             'out': e.stdout,
                             'err': e.stderr})


Input:
    def _find_host_exhaustive(self, connector, hosts):
        for host in hosts:
            ssh_cmd = 'svcinfo lshost -delim ! %s' % host
            out, err = self._run_ssh(ssh_cmd)
            self._assert_ssh_return(len(out.strip()),
                                    '_find_host_exhaustive',
                                    ssh_cmd, out, err)
            for attr_line in out.split('\n'):
                # If '!' not found, return the string and two empty strings
                attr_name, foo, attr_val = attr_line.partition('!')
                if (attr_name == 'iscsi_name' and
                        'initiator' in connector and
                        attr_val == connector['initiator']):
                    return host
                elif (attr_name == 'WWPN' and
                      'wwpns' in connector and
                      attr_val.lower() in
                      map(str.lower, map(str, connector['wwpns']))):
                        return host
        return None

    def _find_host_exhaustive(self, connector, hosts):
        for host in hosts:
            ssh_cmd = ['svcinfo', 'lshost', '-delim', '!', host]
            out, err = self._run_ssh(ssh_cmd)
            self._assert_ssh_return(len(out.strip()),
                                    '_find_host_exhaustive',
                                    ssh_cmd, out, err)
            for attr_line in out.split('\n'):
                # If '!' not found, return the string and two empty strings
                attr_name, foo, attr_val = attr_line.partition('!')
                if (attr_name == 'iscsi_name' and
                        'initiator' in connector and
                        attr_val == connector['initiator']):
                    return host
                elif (attr_name == 'WWPN' and
                      'wwpns' in connector and
                      attr_val.lower() in
                      map(str.lower, map(str, connector['wwpns']))):
                        return host
        return None


Input:
    def write_section(self, section_name, section_data):
        self.write_line("")
        self.write_line("define %s {" % section_name)
        sorted_keys = section_data.keys()
        sorted_keys.sort()
        for key in sorted_keys:
            value = section_data[key]
            self.icinga_lines.append(("%s%-45s%s" % (self.indent, key, self.value_to_icinga(value))))
        self.write_line("}")

    def write_section(self, section_name, section_data):
        self.write_line("")
        self.write_line("define %s {" % section_name)
        sorted_keys = section_data.keys()
        sorted_keys.sort()
        for key in sorted_keys:
            value = self.value_to_icinga(section_data[key])
            icinga_line = "%s%-45s%s" % (self.indent, key, value)

            if "\n" in icinga_line or "}" in icinga_line:
                msg = "Found forbidden newline or '}' character in section %r."
                raise Exception(msg % section_name)

            self.icinga_lines.append(icinga_line)
        self.write_line("}")


Input:
def install(filename, target):
  '''Run a package's installer script against the given target directory.'''
  print(' Unpacking %s...' % filename)
  os.system('tar xf ' + filename)
  basename = filename.split('.tar')[0]
  print(' Installing %s...' % basename)
  install_opts = '--prefix=${PWD}/%s --disable-ldconfig' % target
  os.system('%s/install.sh %s' % (basename, install_opts))
  print(' Cleaning %s...' % basename)
  os.system('rm -rf %s' % basename)

def install(filename, target):
  '''Run a package's installer script against the given target directory.'''
  print(' Unpacking %s...' % filename)
  subprocess.check_call(['tar', 'xf', filename])
  basename = filename.split('.tar')[0]
  print(' Installing %s...' % basename)
  install_cmd = [os.path.join(basename, 'install.sh')]
  install_cmd += ['--prefix=' + os.path.abspath(target)]
  install_cmd += ['--disable-ldconfig']
  subprocess.check_call(install_cmd)
  print(' Cleaning %s...' % basename)
  subprocess.check_call(['rm', '-rf', basename])


Input:
    def _start_fc_map(self, fc_map_id, source, target):
        try:
            out, err = self._run_ssh('svctask startfcmap %s' % fc_map_id)
        except exception.ProcessExecutionError as e:
            with excutils.save_and_reraise_exception():
                LOG.error(_('_start_fc_map: Failed to start FlashCopy '
                            'from %(source)s to %(target)s.\n'
                            'stdout: %(out)s\n stderr: %(err)s')
                          % {'source': source,
                             'target': target,
                             'out': e.stdout,
                             'err': e.stderr})

    def _start_fc_map(self, fc_map_id, source, target):
        try:
            out, err = self._run_ssh(['svctask', 'startfcmap', fc_map_id])
        except exception.ProcessExecutionError as e:
            with excutils.save_and_reraise_exception():
                LOG.error(_('_start_fc_map: Failed to start FlashCopy '
                            'from %(source)s to %(target)s.\n'
                            'stdout: %(out)s\n stderr: %(err)s')
                          % {'source': source,
                             'target': target,
                             'out': e.stdout,
                             'err': e.stderr})


Input:
    def _create_3par_fibrechan_host(self, hostname, wwn, domain, persona_id):
        """Create a 3PAR host.

        Create a 3PAR host, if there is already a host on the 3par using
        the same wwn but with a different hostname, return the hostname
        used by 3PAR.
        """
        out = self.common._cli_run('createhost -persona %s -domain %s %s %s'
                                   % (persona_id, domain,
                                      hostname, " ".join(wwn)), None)
        if out and len(out) > 1:
            return self.common.parse_create_host_error(hostname, out)

        return hostname

    def _create_3par_fibrechan_host(self, hostname, wwns, domain, persona_id):
        """Create a 3PAR host.

        Create a 3PAR host, if there is already a host on the 3par using
        the same wwn but with a different hostname, return the hostname
        used by 3PAR.
        """
        command = ['createhost', '-persona', persona_id, '-domain', domain,
                   hostname]
        for wwn in wwns:
            command.append(wwn)

        out = self.common._cli_run(command)
        if out and len(out) > 1:
            return self.common.parse_create_host_error(hostname, out)

        return hostname


Input:
    def extend_volume(self, volume, new_size):
        volume_name = self._get_3par_vol_name(volume['id'])
        old_size = volume.size
        growth_size = int(new_size) - old_size
        LOG.debug("Extending Volume %s from %s to %s, by %s GB." %
                  (volume_name, old_size, new_size, growth_size))
        try:
            self._cli_run("growvv -f %s %sg" % (volume_name, growth_size),
                          None)
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.error(_("Error extending volume %s") % volume)

    def extend_volume(self, volume, new_size):
        volume_name = self._get_3par_vol_name(volume['id'])
        old_size = volume.size
        growth_size = int(new_size) - old_size
        LOG.debug("Extending Volume %s from %s to %s, by %s GB." %
                  (volume_name, old_size, new_size, growth_size))
        try:
            self._cli_run(['growvv', '-f', volume_name, '%dg' % growth_size])
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.error(_("Error extending volume %s") % volume)


Input:
    def _get_3par_hostname_from_wwn_iqn(self, wwns_iqn):
        out = self._cli_run('showhost -d', None)
        # wwns_iqn may be a list of strings or a single
        # string. So, if necessary, create a list to loop.
        if not isinstance(wwns_iqn, list):
            wwn_iqn_list = [wwns_iqn]
        else:
            wwn_iqn_list = wwns_iqn

        for wwn_iqn in wwn_iqn_list:
            for showhost in out:
                if (wwn_iqn.upper() in showhost.upper()):
                    return showhost.split(',')[1]

    def _get_3par_hostname_from_wwn_iqn(self, wwns_iqn):
        out = self._cli_run(['showhost', '-d'])
        # wwns_iqn may be a list of strings or a single
        # string. So, if necessary, create a list to loop.
        if not isinstance(wwns_iqn, list):
            wwn_iqn_list = [wwns_iqn]
        else:
            wwn_iqn_list = wwns_iqn

        for wwn_iqn in wwn_iqn_list:
            for showhost in out:
                if (wwn_iqn.upper() in showhost.upper()):
                    return showhost.split(',')[1]


Input:
def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False):
    # XXX see if we want to keep an external call here
    if verbose:
        zipoptions = "-r"
    else:
        zipoptions = "-rq"
    from distutils.errors import DistutilsExecError
    from distutils.spawn import spawn
    try:
        spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run)
    except DistutilsExecError:
        # XXX really should distinguish between "couldn't find
        # external 'zip' command" and "zip failed".
        raise ExecError, \
            ("unable to create zip file '%s': "
            "could neither import the 'zipfile' module nor "
            "find a standalone zip utility") % zip_filename

def _call_external_zip(base_dir, zip_filename, verbose, dry_run, logger):
    # XXX see if we want to keep an external call here
    if verbose:
        zipoptions = "-r"
    else:
        zipoptions = "-rq"
    cmd = ["zip", zipoptions, zip_filename, base_dir]
    if logger is not None:
        logger.info(' '.join(cmd))
    if dry_run:
        return
    import subprocess
    try:
        subprocess.check_call(cmd)
    except subprocess.CalledProcessError:
        # XXX really should distinguish between "couldn't find
        # external 'zip' command" and "zip failed".
        raise ExecError, \
            ("unable to create zip file '%s': "
            "could neither import the 'zipfile' module nor "
            "find a standalone zip utility") % zip_filename


Input:
    def _get_iscsi_ip_addrs(self):
        generator = self._port_conf_generator('svcinfo lsportip')
        header = next(generator, None)
        if not header:
            return

        for port_data in generator:
            try:
                port_node_id = port_data['node_id']
                port_ipv4 = port_data['IP_address']
                port_ipv6 = port_data['IP_address_6']
                state = port_data['state']
            except KeyError:
                self._handle_keyerror('lsportip', header)

            if port_node_id in self._storage_nodes and (
                    state == 'configured' or state == 'online'):
                node = self._storage_nodes[port_node_id]
                if len(port_ipv4):
                    node['ipv4'].append(port_ipv4)
                if len(port_ipv6):
                    node['ipv6'].append(port_ipv6)

    def _get_iscsi_ip_addrs(self):
        generator = self._port_conf_generator(['svcinfo', 'lsportip'])
        header = next(generator, None)
        if not header:
            return

        for port_data in generator:
            try:
                port_node_id = port_data['node_id']
                port_ipv4 = port_data['IP_address']
                port_ipv6 = port_data['IP_address_6']
                state = port_data['state']
            except KeyError:
                self._handle_keyerror('lsportip', header)

            if port_node_id in self._storage_nodes and (
                    state == 'configured' or state == 'online'):
                node = self._storage_nodes[port_node_id]
                if len(port_ipv4):
                    node['ipv4'].append(port_ipv4)
                if len(port_ipv6):
                    node['ipv6'].append(port_ipv6)