def _getProfileType(self, container_id: str, db_cursor: db.Cursor) -> Optional[str]: db_cursor.execute( "select id, container_type from containers where id = ?", (container_id, )) row = db_cursor.fetchone() if row: return row[1] return None
def _read_part(self, cursor: sqlite3.Cursor, version: int): cursor.execute( 'select size, content from part_versions where version = ?', (version, )) size, content = cursor.fetchone() data = np.array(np.frombuffer(content, dtype='int8').reshape( (size, size, size)), dtype='int8') return size, data
def load(self, cursor: sqlite3.Cursor) -> None: """Load the properties from the provided database cursor.""" cursor.execute('select mu, sigma, games_count, wins_count from players ' 'where name=? and ladder=?', [self.name, self.ranking.ladder]) loaded = cursor.fetchone() logging.info('Fetched player %s skill %s', self.name, loaded['mu']) self.rating = self.ranking.tsh.create_rating(loaded['mu'], loaded['sigma']) self.games_count = loaded['games_count'] self.wins_count = loaded['wins_count']
def get_genes_for_intron(c: sqlite3.Cursor, intron_feature: str) -> str: query = "select genes from intron_feature where intron = ?" c.execute(query, (intron_feature, )) genes = c.fetchone() if genes is not None: genes = genes[0] return genes
def analyse_exam(cursor: Cursor, exam_id: int) -> dict: ''' Gives all stats about the exam Args: cursor (Cursor): sqlite3 Cursor object exam_id (int): the unique id of the exam Returns: dict: all the stats ''' logger.info('Analyzing exam with id ') cursor.execute(___(f'SELECT AVG(marks) FROM marks WHERE exam={exam_id}')) average = cursor.fetchone()[0] cursor.execute(___(f'SELECT MAX(marks) FROM marks WHERE exam={exam_id}')) highest = cursor.fetchone()[0] return {'average': average, 'highest': highest}
def _getProfileModificationTime(self, container_id: str, db_cursor: db.Cursor) -> Optional[float]: db_cursor.execute( "select id, last_modified from containers where id = ?", (container_id, )) row = db_cursor.fetchone() if row: return row[1] return None
def check_if_link_exists(cursor: sqlite3.Cursor, link: str): sql_query = """ SELECT COUNT(link) FROM Links WHERE link = ? """ cursor.execute(sql_query, (link, )) if cursor.fetchone()[0] == 0: return False return True
def _get_showcase_info(cursor: sqlite3.Cursor, channel_id: int, user_id: int) -> (core.SimShowcase, int, int): cursor.execute( "SELECT showcase, rate, total_summons FROM pity WHERE channel = ? AND user = ?", (channel_id, user_id)) result = cursor.fetchone() if result is None: return core.SimShowcaseCache.default_showcase, 0, 0 else: return core.SimShowcaseCache.get(result[0]), result[1], result[2]
def genre_exists(cursor: Cursor, name: str) -> bool: cursor.execute( f""" SELECT EXISTS(SELECT 1 from {GENRE_TABLE_NAME} WHERE name = ?); """, (name, ), ) result = cursor.fetchone()[0] return result == 1
def _check_rank_and_update(guild_id: int, member_id: int, cu: sqlite3.Cursor): cu.execute( 'SELECT xp, rank FROM server_{} WHERE member_id=(?);'.format(guild_id), (member_id, )) fetch_ = cu.fetchone() if fetch_ != None: xp, rank = fetch_ else: return False if xp >= int( LevelUtil.calculateXPRequiredForLevel(desire_level=(rank + 1))): cu.execute( 'UPDATE server_{} SET rank={} WHERE member_id=(?)'.format( guild_id, rank + 1), (member_id, )) cu.execute( 'SELECT rank FROM server_{} WHERE member_id=(?);'.format(guild_id), (member_id, )) return cu.fetchone() return False
def album_exists(cursor: Cursor, title: str) -> bool: cursor.execute( f""" SELECT EXISTS(SELECT 1 from {ALBUM_TABLE_NAME} WHERE title = ?); """, (title, ), ) result = cursor.fetchone()[0] return result == 1
def exec_withdrawal(cursor: sqlite3.Cursor) -> None: cursor.execute( 'select address from withdrawal_req where completed == 0') addresses = {r[0] for r in cursor.fetchall()} if len(addresses) == 0: return params = {} for address in addresses: cursor.execute( 'select amount from withdrawal_req where address == ? and completed == 0', (address, )) req_amounts = [Decimal(str(r[0])) for r in cursor.fetchall()] amount = Decimal('0.0') for req_amount in req_amounts: amount = amount + req_amount params[address] = float(amount) try: txid = coinrpc.call('sendmany', '', params, MINCONF, '', list(addresses)) except: txid = None if txid is None: cursor.execute( 'select account, value from withdrawal_req where completed == 0' ) for req in cursor.fetchall(): account = req[0] value = Decimal(str(req[1])) cursor.execute( 'select balance from account_wallet where account == ?', (account, )) balance = Decimal(str(cursor.fetchone()[0])) balance = balance + value cursor.execute( 'update account_wallet set balance = ? where account == ?', (float(balance), account)) cursor.execute( 'update withdrawal_req set completed = -1 where completed == 0' ) return cursor.execute( 'update withdrawal_req set completed = 1 where completed == 0')
def check_for_change(row: Series, conn: Connection, cursor: Cursor) -> None: """ Check if row differs from information saved in database. :param row: table row from HTML :param conn: db Connection :param cursor: db Cursor :return: """ if row.isnull().all(): return result_html = parse_row(row) if result_html[0].strip() == '': return cursor.execute('SELECT * FROM CareerCenter WHERE Thema=? AND table_num=?', (result_html[0], int(result_html[-1]))) result_db = cursor.fetchone() if result_db is None: cursor.execute('INSERT INTO CareerCenter VALUES (?,?,?,?,?,?,?,?)', result_html) conn.commit() generate_message(result_html) else: result = () change_detected = False for entry_db, entry_html in zip(result_db, result_html): diff = calc_str_diff(str(entry_db), str(entry_html)) thema, ue, bv, termine, uhrzeit, raum, anmeldung, table_num = result_html num_changed_elements = sum([elem[0] != 0 for elem in diff]) if num_changed_elements > 0: change_detected = True result += (generate_pretty_diff(diff), ) else: result += (entry_db, ) if change_detected: cursor.execute( '''UPDATE CareerCenter SET Zeitlicher_Umfang=?, Anerkennung=?, Termin=?, Uhrzeit=?, Raum=?, Anmeldung=? WHERE Thema = ? AND table_num = ?''', (ue, bv, termine, uhrzeit, raum, anmeldung, thema, table_num)) conn.commit() generate_message(result)
def get_character_stats(cursor: sqlite3.Cursor): cursor.execute( "SELECT level, gold, xp, xp_for_next_level FROM character WHERE id = 1" ) character = cursor.fetchone() return { "level": character[0], "gold": character[1], "xp": character[2], "xp_for_next_level": character[3] }
def _getProfileType(self, container_id: str, db_cursor: db.Cursor) -> Optional[str]: try: db_cursor.execute("select id, container_type from containers where id = ?", (container_id, )) except db.DatabaseError as e: Logger.error(f"Could not access database: {e}. Is it corrupt? Recreating it.") self._recreateCorruptDataBase(db_cursor) return None row = db_cursor.fetchone() if row: return row[1] return None
def InsertUserDB(temp_c: sqlite3.Cursor, DiscordUserName: str): # Check if user in database temp_c.execute("SELECT Discord_User FROM users WHERE Discord_User = (?)", (str(DiscordUserName), )) user = temp_c.fetchone() if not user: # Not found, introduce temp_c.execute( "INSERT INTO users (Discord_User, Last_Daily_Call) VALUES((?), (SELECT strftime('%s','now')))", (str(DiscordUserName), )) else: # Found user return
def artist_exists(cursor: Cursor, name: str): cursor.execute( f""" SELECT EXISTS(SELECT 1 from {ARTIST_TABLE_NAME} WHERE name = ?) """, (name, ), ) result = cursor.fetchone()[0] return result == 1
def str2int(s: str, cursor: sqlite3.Cursor) -> int: """ On interroge une base données, on vérifie si la chaine de caractère est soit dans la case phonologie, soit dans la case graphie et on renvoie tous les entiers correspondants. :param s: chaine de caractères :param cursor: pointeur de base de données :return: l'entier associé à la chaine de caractères d'entrée, False sinon """ recherche = "SELECT integer FROM Lexique WHERE ortho = ? OR phon = ?" cursor.execute(recherche, (s,)*2) return cursor.fetchone()
def get_album_id(cursor: Cursor, title: str) -> Optional[int]: cursor.execute( f""" SELECT id FROM {ALBUM_TABLE_NAME} WHERE title = ?; """, (title, ), ) result = cursor.fetchone() if result is not None: return result[0] return None
def get_genre_id(cursor: Cursor, name: str) -> Optional[int]: cursor.execute( f""" SELECT id FROM {GENRE_TABLE_NAME} WHERE name = ? """, (name, ), ) result = cursor.fetchone() if result is not None: return result[0] return None
def getLatestTemp(c: sqlite3.Cursor) -> Optional[float]: c.execute(f'''SELECT * FROM temperature ORDER BY time DESC LIMIT 1; ''') res = c.fetchone() if res == []: return None else: return float(res[1])
def action(cursor: sqlite3.Cursor) -> Parameters: row = cursor.fetchone() if row is not None: return Parameters( uid=row['id'], timestamp=row['timestamp'], parameters=pickle.loads(row['data']), database=self, ) else: raise BearDatabaseError( f'could not find parameters with id: {uid}')
def get_existing_token(cursor: Cursor, user_id: int) -> Union[str, None]: cursor.execute(select_token, (user_id, )) select_result = cursor.fetchone() if select_result is None: return None try: (token, ) = select_result jwt.decode(token, jwt_secret) return token.decode("utf-8") except ExpiredSignatureError: cursor.execute(delete_token_for_user, (user_id, )) return None
def get_additional_info(self, cursor: sqlite3.Cursor) -> int: """ gets some info from an SQLite database with ``mace4`` outputs :param cursor: an SQLite database cursor :returns: a total number of rows in a table, a magma dimension """ cursor.execute( f"SELECT COUNT(*) FROM mace_output {self._where_clause}" ) row_count = cursor.fetchone()[0] return row_count
def v8_process_live_vykon(cur: sqlite3.Cursor, data: bytes, od: bytes): data = data[6:-1] r = data[3:] s_adr = conv_hex_to_str(od) cur.execute( """select (select konst from zapojeni_vstupy zv inner join zapojeni z on zv.zapojeni_id = z.id where adr_zarizeni = ? and zv.cislo=1) k1, (select konst from zapojeni_vstupy zv inner join zapojeni z on zv.zapojeni_id = z.id where adr_zarizeni = ? and zv.cislo=2) k2, (select konst from zapojeni_vstupy zv inner join zapojeni z on zv.zapojeni_id = z.id where adr_zarizeni = ? and zv.cislo=3) k3, (select konst from zapojeni_vstupy zv inner join zapojeni z on zv.zapojeni_id = z.id where adr_zarizeni = ? and zv.cislo=4) k4, (select konst from zapojeni_vstupy zv inner join zapojeni z on zv.zapojeni_id = z.id where adr_zarizeni = ? and zv.cislo=5) k5, (select konst from zapojeni_vstupy zv inner join zapojeni z on zv.zapojeni_id = z.id where adr_zarizeni = ? and zv.cislo=6) k6, (select konst from zapojeni_vstupy zv inner join zapojeni z on zv.zapojeni_id = z.id where adr_zarizeni = ? and zv.cislo=7) k7, (select konst from zapojeni_vstupy zv inner join zapojeni z on zv.zapojeni_id = z.id where adr_zarizeni = ? and zv.cislo=8) k8""", (s_adr, s_adr, s_adr, s_adr, s_adr, s_adr, s_adr, s_adr)) k = cur.fetchone() for i in range(0, 8): try: x = i * 2 cas = bytes_to_int_reverse(r[x:x + 2]) if cas > 0 and cas <= 32767: cas = int(round(cas / 1000, 0)) elif cas > 32767 and cas <= 65280: cas = int(round((cas - 32768) + 32.767, 0)) else: cas = 0 vykon = 0 if cas > 0 and k[i] != 0: vykon = 3600 / (cas * k[i]) vykon = round(vykon, 2) f = cur.execute( "select 1 from livedata_v8 where adr_zarizeni=? and vstup=? ", (s_adr, i + 1)).fetchone() if f != None: cur.execute( "update livedata_v8 set cas_imp=?, vykon=?, cas_odecet=? where adr_zarizeni=? and vstup=?", (cas, vykon, datetime.now(), s_adr, i + 1)) else: cur.execute( "insert into livedata_v8(adr_zarizeni, vstup, cas_imp, vykon, prace, cas_odecet) values(?,?,?,?,0,?)", (s_adr, i + 1, cas, vykon, datetime.now())) except Exception as e: print("v8_process_live_vykon(): i: {} Ex: {}".format( str(i), str(e)), flush=True) pass
def getUser(cur: sqlite3.Cursor, name: str) -> typing.Optional[User]: """ Gets the user named 'name' from the database as a (username, email) pair, or None if no such user was found. """ cur.execute('''SELECT username, email FROM user WHERE username=?''', (name, )) u = cur.fetchone() if u is None: return None ret: User = (u[0], u[1]) return ret
def check_if_number_of_rows_less_than_5000(cursor: sqlite3.Cursor): try: sql_query = """ SELECT count(*) FROM Links """ cursor.execute(sql_query) number_of_rows = cursor.fetchone()[0] if number_of_rows < 5000: return True return False except Exception as error_message: print("Error Message: " + str(error_message))
def is_crawled(cursor: sqlite3.Cursor, link: str): try: sql_query = """ SELECT is_crawled FROM Links WHERE link = ? """ cursor.execute(sql_query, (link, )) if cursor.fetchone()[0] == "1": return True return False except Exception as error_message: print("Error Message: " + str(error_message))
def inner_get_node_by_id( query: sqlite3.Cursor, node_id: Text, ) -> Union['Node', None]: query.execute( ''' SELECT id, name, trashed, created, modified FROM nodes WHERE id=? ;''', (node_id, )) rv = query.fetchone() if not rv: return None node = dict(rv) query.execute( ''' SELECT id, md5, size FROM files WHERE id=? ;''', (node_id, )) rv = query.fetchone() is_folder = rv is None node['is_folder'] = is_folder node['md5'] = None if is_folder else rv['md5'] node['size'] = None if is_folder else rv['size'] query.execute( ''' SELECT parent, child FROM parentage WHERE child=? ;''', (node_id, )) rv = query.fetchall() node['parents'] = None if not rv else [_['parent'] for _ in rv] node = Node.from_database(node) return node
def move(cursor: sqlite3.Cursor, from_account: str, to_account: str, str_amount: str) -> Union[str, Decimal]: cursor.execute('insert or ignore into account_wallet(account) values(?)', (from_account, )) cursor.execute('insert or ignore into account_wallet(account) values(?)', (to_account, )) if from_account == to_account: return 'self' if not is_amount(str_amount): return 'wrong' cursor.execute('select balance from account_wallet where account == ?', (from_account, )) from_balance = Decimal(str(cursor.fetchone()[0])) cursor.execute('select balance from account_wallet where account == ?', (to_account, )) to_balance = Decimal(str(cursor.fetchone()[0])) amount = get_amount(str_amount, from_balance) if amount <= 0: return 'few' if from_balance < amount: return 'insufficient' from_balance = from_balance - amount to_balance = to_balance + amount cursor.execute('update account_wallet set balance = ? where account == ?', (float(from_balance), from_account)) cursor.execute('update account_wallet set balance = ? where account == ?', (float(to_balance), to_account)) return amount
def delete_food(connection: sqlite3.Connection, cursor: sqlite3.Cursor, food: str): foodExists = False cursor.execute("SELECT * FROM FOODS WHERE FOODS.FOOD = ?", (food, )) if cursor.fetchone() is not None: foodExists = True if not foodExists: print("Food information not found in database.") return cursor.execute("DELETE FROM FOODS WHERE FOODS.FOOD = ?", (food, )) print("Food information successfully deleted from database.") connection.commit()