def al1(bot, update): global idlot db = SQLite() idlot = tools.timestamp() db.magic('insert into lot(id) values (?)', (idlot, )) update.message.reply_text(RU.aname) return NAME
def search(self, searchEncode): db = SQLite() sourceImageEncode = np.array(searchEncode).astype( np.float) #bulmak istenilen yüz results = [] DBImageList = [] DBImageList = db.GETALL() #veri tabaındaki tüö resimleri getir newList = [] knownFaces = [] for item in DBImageList: faceNumber = item[0] #yüzün numarası faceEncode = item[1].split('/') #stringi parcalıyor del faceEncode[-1] #son elemanı siliyor imagePaht = item[2] data = [] data.append(faceNumber) data.append(np.array(faceEncode).astype(np.float)) data.append(imagePaht) newList.append(data) knownFaces.append(np.array(faceEncode).astype(np.float)) results = face_recognition.compare_faces( np.array(knownFaces), sourceImageEncode) #karşılastırma yapıyor sayac2 = 0 returnList = [] for item in results: if item == True: returnList.append( newList[sayac2][2] ) #bulunan her bir elemanın pathini alıyo resultliste atıyo sayac2 += 1 return returnList
def get(self, fromtimestamp, totimestamp): assert (isinstance(fromtimestamp, datetime.datetime)) assert (isinstance(totimestamp, datetime.datetime)) t = StopWatch("DataBaseDataSource SQL query") db = SQLite(self._parameters["dbfile"] or "gammascout.sqlite") points = db.execute( "SELECT tfrom, tto, counts FROM data WHERE (tfrom >= ?) AND (tfrom < ?) ORDER BY tfrom ASC;", fromtimestamp, totimestamp).fetchall() if len(points) == 0: print("Data acquisition returned no points to plotting.") sys.exit(1) # Parse "from" and "to" from strings to datetime.datetime objects xfrom = [ datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S") for (x, y, z) in points ] xto = [ datetime.datetime.strptime(y, "%Y-%m-%d %H:%M:%S") for (x, y, z) in points ] cts = [z for (x, y, z) in points] t.finish() return (xfrom, xto, cts)
class OutputBackendSqlite(OutputBackend): def __init__(self, filename): OutputBackend.__init__(self, filename) self._db = SQLite(filename) self._db.exec_mayfail_commit("""CREATE TABLE metadata ( key character varying PRIMARY KEY, value character varying NOT NULL );""") self._db.exec_mayfail_commit( "INSERT INTO metadata (key, value) VALUES ('dbversion', '1');") self._db.exec_mayfail_commit("""CREATE TABLE data ( id integer PRIMARY KEY, tfrom timestamp NOT NULL, tto timestamp NOT NULL, counts integer NOT NULL, CHECK(tto > tfrom), CHECK(counts >= 0) );""") def newinterval(self, fromtime, totime, counts): self._db.execute( "INSERT INTO data (tfrom, tto, counts) VALUES (?, ?, ?);", fromtime, totime, counts) def close(self): self._db.commit()
def name(bot, update): db = SQLite() global idlot update.message.reply_text(RU.description) name = update.message.text db.magic('update lot set head = (?) where id = {}'.format(idlot), (name, )) tools.log('Created lot {} with name {}'.format(idlot, name)) return DESCR
def setup(self): predictor_path = r"C:\Users\Sinem\Documents\GitHub\Playground\PyQt Examples\Models\shape_predictor_5_face_landmarks.dat" face_rec_model_path = r"C:\Users\Sinem\Documents\GitHub\Playground\PyQt Examples\Models\dlib_face_recognition_resnet_model_v1.dat" self.detector = dlib.get_frontal_face_detector( ) #kaç yüz olduğunu buluyo self.sp = dlib.shape_predictor(predictor_path) self.facerec = dlib.face_recognition_model_v1(face_rec_model_path) self.db = SQLite()
def descr(bot, update): db = SQLite() global idlot update.message.reply_text(RU.price) descr = update.message.text db.magic('update lot set description = (?) where id = {}'.format(idlot), (descr, )) tools.log('Lot {} description updated'.format(idlot)) return PRICE
def button(bot, update): db = SQLite() query = update.callback_query res = query.data if res == 'a': reply_markup =[] result = db.magic('select * from sales').fetchall() for item in result: reply_markup.append([InlineKeyboardButton(' {}...'.format(item[1][:15]), callback_data='a{}'.format(item[0]))]) reply_markup.append([InlineKeyboardButton("Назад", callback_data='back')]) bot.edit_message_text(text="Выберите акцию для удаления", reply_markup=InlineKeyboardMarkup(reply_markup), chat_id=query.message.chat_id, message_id=query.message.message_id) logger.info('User {}:{} go to SALES DELETE PAGE'.format(query.from_user.id, query.from_user.username)) elif res == 'f': reply_markup = [] result = db.magic('select * from facts').fetchall() for item in result: reply_markup.append([InlineKeyboardButton(' {}...'.format(item[1][:15]), callback_data='f{}'.format(item[0]))]) reply_markup.append([InlineKeyboardButton("Назад", callback_data='back')]) bot.edit_message_text(text="Выберите факт для удаления", reply_markup=InlineKeyboardMarkup(reply_markup), chat_id=query.message.chat_id, message_id=query.message.message_id) logger.info('User {}:{} go to FACTS DELETE PAGE'.format(query.from_user.id, query.from_user.username)) elif re.match(r'^a\d+', query.data): delID = query.data[1:] result = db.magic('select * from sales where id = {}'.format(delID)).fetchall() db.magic('delete from sales where id = {}'.format(delID)) bot.edit_message_text(text='{}\n\nАКЦИЯ УДАЛЕНА'.format(result[0][1]), chat_id=query.message.chat_id, message_id=query.message.message_id) logger.info('User {}:{} DELETE SALE {}'.format(query.from_user.id, query.from_user.username,result[0][1])) return ConversationHandler.END elif re.match(r'^f\d+', query.data): delID = query.data[1:] result = db.magic('select * from facts where id = {}'.format(delID)).fetchall() db.magic('delete from facts where id = {}'.format(delID)) bot.edit_message_text(text='{}\n\nФАКТ УДАЛЕН'.format(result[0][1]), chat_id=query.message.chat_id, message_id=query.message.message_id) logger.info('User {}:{} DELETE FACT {}'.format(query.from_user.id, query.from_user.username,result[0][1])) return ConversationHandler.END elif res == 'back': reply_markup = [[InlineKeyboardButton("Удалить Акцию", callback_data='a')], [InlineKeyboardButton("Удалить Факт", callback_data='f')], [InlineKeyboardButton("Прысь!", callback_data='out')]] bot.edit_message_text(text="Выберите факт для удаления", chat_id=query.message.chat_id, message_id=query.message.message_id, reply_markup=InlineKeyboardMarkup(reply_markup)) logger.info('User {}:{} go to main page'.format(query.from_user.id,query.from_user.username)) elif res == 'out': bot.edit_message_text(text="Все, ухожу! 👐", chat_id=query.message.chat_id, message_id=query.message.message_id)
def intro(bot, update): keybrd = [['END']] db = SQLite() text = RU.addolay otypes = db.magic('select id, name from otype').fetchall() for i in otypes: text += '{} {}\n'.format(i[0], i[1]) update.message.reply_text(text, reply_markup=ReplyKeyboardMarkup(keybrd, True)) return MSG
def balfunc(bot, update): user = update.message.from_user db = SQLite() account = db.magic('select bal, fname, nid from memb where tgid = {}'.format(str(user.id))).fetchall() #logger.info('User {} open bal'.format(user.first_name)) return update.message.reply_text(RU.balinfo.format( str(account[0][1]), str(account[0][2]).zfill(4), str(account[0][0])), parse_mode=ParseMode.HTML)
def dayadding(bot, update): db = SQLite() text = update.message.text date = tools.getdate() try: res = db.magic('insert into alday(date,val) values (?,?)', (date, text)) except Error as e: update.message.reply_text('ERROR ADDING' + str(e)) return MSG
def start(bot, update): user = update.message.from_user db = SQLite() try: db.magic( sql='insert or ignore into membs (tgID, uName, fName) VALUES (?,?,?)', data=(user.id, user.name, user.first_name)) except Error: return tools.log('User "%s", error "%s"' % (user.id, error)) markup = [[InlineKeyboardButton("Что нового", callback_data='refr'),]] update.message.reply_text(RU.welcome1.format(user.first_name), reply_markup=InlineKeyboardMarkup(markup))
def adding(bot, update): db = SQLite() text = update.message.text[2:] oval = re.search(r'^\d+', text).group(0) otype = update.message.text[:2] text = text.replace(oval, '') date = tools.getdate() res = db.magic( 'insert into outlay(type, value, date, text) VALUES (?,?,?,?)', (otype, oval, date, text)).fetchall() update.message.reply_text('Done') return MSG
def rate(bot, update): db = SQLite() global idlot update.message.reply_text(RU.pics) try: price = float(update.message.text) except ValueError: return update.message.reply_text(RU.pricewrong) db.magic('update lot set rate = (?) where id = {}'.format(idlot), (price, )) tools.log('Lot {} rate updated'.format(idlot)) return PICTS
def price(bot, update): db = SQLite() global idlot update.message.reply_text(RU.maxprace) try: price = float(update.message.text) except ValueError: return update.message.reply_text(RU.pricewrong) db.magic( 'update lot set sPrice = (?), price = (?) where id = {}'.format(idlot), (price, price)) tools.log('Lot {} price updated'.format(idlot)) return MAX
def pics(bot, update): db = SQLite() global idlot text = update.message.photo[4].file_id try: picsID = db.magic('select pictures from lot where id = (?)', (idlot, )).fetchall()[0][0] #TODO is null except Error: pass if picsID is None: picsID = text else: picsID = str(picsID) + ' ' + text db.magic('update lot set pictures = (?) where id = {}'.format(idlot), (picsID, ))
class TestUI(unittest.TestCase): path = "sqlite_example.db" db = SQLite(path) ui = UI(db) sql_commad_example_1 = "SELECT * FROM test_table" sql_commad_example_2 = "SELECT test_text_field, test_int_field FROM test_table" sql_commad_example_3 = "SELECT test_int_field FROM test_table" def test_get_command_type_and_command_text(self): ui_command_example = "/UI_COMMAND_EXAMPLE" self.assertEqual(("SQL_COMMAND", self.sql_commad_example_1), self.ui.get_command_type_and_command_text( self.sql_commad_example_1)) self.assertEqual( ("UI_COMMAND", "UI_COMMAND_EXAMPLE"), self.ui.get_command_type_and_command_text(ui_command_example)) self.assertEqual(ValueError, self.ui.get_command_type_and_command_text("")) def test_process_sql_command(self): self.assertEqual(["test_int_field", "test_text_field"], self.ui.process_sql_command_and_get_columns_names( self.sql_commad_example_1)) self.assertEqual(["test_text_field", "test_int_field"], self.ui.process_sql_command_and_get_columns_names( self.sql_commad_example_2)) self.assertEqual(["test_int_field"], self.ui.process_sql_command_and_get_columns_names( self.sql_commad_example_3))
class testSQL(unittest.TestCase): sql_obj = SQLite("test.db") def test_select_request(self): # Test "SELECT ALL" test_request_1 = "SELECT * FROM test_table" expected_answ_1 = "[(123, '23'), (123, '123'), (1323, '123'), (1323, '123'), (1323, '123'), (1323, '123'), (1323, '123'), ('dffgdfg', 'sdgfdfg')]" self.assertEqual(str(self.sql_obj.execute_request(test_request_1)), expected_answ_1) # Test "SELECT from" by columns test_request_2 = "SELECT test_int_field FROM test_table" expected_answ_2 = "[(123,), (123,), (1323,), (1323,), (1323,), (1323,), (1323,), ('dffgdfg',)]" self.assertEqual(str(self.sql_obj.execute_request(test_request_2)), expected_answ_2) test_request_3 = test_request_2.replace("test_int_field", "test_text_field") expected_answ_3 = "[('23',), ('123',), ('123',), ('123',), ('123',), ('123',), ('123',), ('sdgfdfg',)]" self.assertEqual(str(self.sql_obj.execute_request(test_request_3)), expected_answ_3) # Test column that doesn't exist test_request_4 = test_request_2.replace("test_int_field", "column_random") self.assertEqual(self.sql_obj.execute_request(test_request_4), RuntimeError)
def __init__(self, db, f_class=None, d_type='L1'): self.NGT_dir = 'NGT_{}_{}'.format(f_class,d_type) self.NGT_path = b'' self.fearure = f_class self.SQLdb = SQLite() if f_class == 'daisy': self.f_c = Daisy() self.NGT_path = b'NGT/NGT_daisy_'+d_type.encode() elif f_class == 'edge': self.f_c = Edge() self.NGT_path = b'NGT/NGT_edge_'+d_type.encode() elif f_class == 'hog': self.f_c = HOG() self.NGT_path = b'NGT/NGT_hog_'+d_type.encode() elif f_class == 'vgg': self.f_c = VGGNetFeat() self.NGT_path = b'NGT/NGT_vgg_'+d_type.encode() elif f_class == 'res': self.f_c = ResNetFeat() self.NGT_path = b'NGT/NGT_res_'+d_type.encode() if not os.path.exists(os.path.join(NGT_dir,self.NGT_dir)): samples = self.f_c.make_samples(db, verbose=False) dim = 0 try: dim = samples[0]['hist'].shape[0] except: pass images= [] objects = [] for i, row in enumerate(samples): vector = row['hist'] link = row['img'] lable = row['cls'] data = {'index':i,'link':link,'lable':lable} images.append(data) objects.append(vector) self.SQLdb.updateMuti(f_class,images) # cPickle.dump(images, open(os.path.join(NGT_dir, sample_cache), "wb", True)) ngtpy.create(path=self.NGT_path, dimension=dim, distance_type=d_type) self.index = ngtpy.Index(self.NGT_path) self.index.batch_insert(objects) self.index.save() self.index = ngtpy.Index(self.NGT_path)
def __init__(self, filename): OutputBackend.__init__(self, filename) self._db = SQLite(filename) self._db.exec_mayfail_commit("""CREATE TABLE metadata ( key character varying PRIMARY KEY, value character varying NOT NULL );""") self._db.exec_mayfail_commit( "INSERT INTO metadata (key, value) VALUES ('dbversion', '1');") self._db.exec_mayfail_commit("""CREATE TABLE data ( id integer PRIMARY KEY, tfrom timestamp NOT NULL, tto timestamp NOT NULL, counts integer NOT NULL, CHECK(tto > tfrom), CHECK(counts >= 0) );""")
def admcheckbal(bot, update): db = SQLite() user = update.message.from_user bal = update.message.text.split()[1] adm_list = RU.admins.split() if user.username in adm_list or user.name in adm_list: try: account = db.magic('select bal, fname, nid from memb where nid = {}'.format(str(bal))).fetchall()[0] except: return bot.send_photo(update.message.from_user.id, RU.error404) logger.info('Admin {} open bal {}'.format(user.first_name, bal)) return update.message.reply_text(RU.balinfo.format( str(account[1]), str(account[2]).zfill(4), str(account[0])), parse_mode=ParseMode.HTML) else: # account = db.magic('select bal, fname, nid from memb where tgid = {}'.format(str(user.id))).fetchall() logger.info('User {} open bal USE COMMAND /b {}'.format(user.first_name, bal)) return balfunc(bot,update)
class OutputBackendSqlite(OutputBackend): def __init__(self, filename): OutputBackend.__init__(self, filename) self._db = SQLite(filename) self._db.exec_mayfail_commit("""CREATE TABLE metadata ( key character varying PRIMARY KEY, value character varying NOT NULL );""") self._db.exec_mayfail_commit("INSERT INTO metadata (key, value) VALUES ('dbversion', '1');") self._db.exec_mayfail_commit("""CREATE TABLE data ( id integer PRIMARY KEY, tfrom timestamp NOT NULL, tto timestamp NOT NULL, counts integer NOT NULL, CHECK(tto > tfrom), CHECK(counts >= 0) );""") def newinterval(self, fromtime, totime, counts): self._db.execute("INSERT INTO data (tfrom, tto, counts) VALUES (?, ?, ?);", fromtime, totime, counts) def close(self): self._db.commit()
def main(): db = "northwind_small.sqlite3" with SQLite(db) as c: ten_most_expensive_products = "SELECT ProductName, UnitPrice " \ "FROM Product " \ "ORDER BY UnitPrice " \ "DESC " \ "LIMIT 10" c.execute(ten_most_expensive_products) print("Ten Most Expensive Products") pprint(c.fetchall()) print("\n") average_employee_age_at_hire_time = "SELECT AVG(HireDate - " \ "BirthDate) FROM Employee" c.execute(average_employee_age_at_hire_time) print("Average Employee Age at Hire Time") print(c.fetchone()[0]) print("\n") ten_most_expensive_products_with_suppliers = "SELECT p.ProductName, " \ "p.UnitPrice, " \ "s.CompanyName " \ "FROM Product p " \ "JOIN Supplier s " \ "ON " \ "p.SupplierId = s.Id " \ "ORDER BY p.UnitPrice " \ "DESC LIMIT 10" c.execute(ten_most_expensive_products_with_suppliers) print("Ten Most Expensive Products with Suppliers") pprint(c.fetchall()) print("\n") largest_category = "SELECT p.CategoryId, " \ "c.CategoryName, " \ "COUNT(*) as count " \ "FROM Product p " \ "JOIN Category c " \ "ON c.Id = p.CategoryId " \ "GROUP BY p.CategoryId " \ "ORDER BY count " \ "DESC " \ "LIMIT 10" c.execute(largest_category) print("Largest Category by Number of Unique Products") pprint(c.fetchall())
def __init__(self, filename): OutputBackend.__init__(self, filename) self._db = SQLite(filename) self._db.exec_mayfail_commit("""CREATE TABLE metadata ( key character varying PRIMARY KEY, value character varying NOT NULL );""") self._db.exec_mayfail_commit("INSERT INTO metadata (key, value) VALUES ('dbversion', '1');") self._db.exec_mayfail_commit("""CREATE TABLE data ( id integer PRIMARY KEY, tfrom timestamp NOT NULL, tto timestamp NOT NULL, counts integer NOT NULL, CHECK(tto > tfrom), CHECK(counts >= 0) );""")
class face_detection: sayac = 1 imageDataList = [] def setup(self): predictor_path = r"C:\Users\Sinem\Documents\GitHub\Playground\PyQt Examples\Models\shape_predictor_5_face_landmarks.dat" face_rec_model_path = r"C:\Users\Sinem\Documents\GitHub\Playground\PyQt Examples\Models\dlib_face_recognition_resnet_model_v1.dat" self.detector = dlib.get_frontal_face_detector( ) #kaç yüz olduğunu buluyo self.sp = dlib.shape_predictor(predictor_path) self.facerec = dlib.face_recognition_model_v1(face_rec_model_path) self.db = SQLite() def detection(self, f): #resmin pathi self.setup() print("Processing file: {}".format(f)) img = io.imread(f) #pathi okuyo img değişkenin içine atıyo dets = self.detector(img, 1) #1 rsim renkli/0 gri print("Number of faces detected: {}".format( len(dets))) #bulunan yüzlerin sayısını veriyor for k, d in enumerate(dets): #dets yüz bilgisi data = [] data.append(d.left()) #yüzün koordinatlarıı data.append(d.top()) data.append(d.right()) data.append(d.bottom()) self.imageDataList.append(data) #yüz embed bilgisi cıkarıyo 128elemanlı dizi shape = self.sp(img, d) face_descriptor = self.facerec.compute_face_descriptor(img, shape) face_chip = dlib.get_face_chip(img, shape) face_descriptor_from_prealigned_image = self.facerec.compute_face_descriptor( face_chip) self.listToStr(face_descriptor_from_prealigned_image, f) # print(face_descriptor_from_prealigned_image) def listToStr(self, liste, path): data = "" for item in liste: data += str(item) + "/" #128elemanı tek bir string haline ceviriyo result = self.db.INSERT(self.sayac, data, path) print(result) self.sayac += 1
def fact(bot, update): db = SQLite() d = datetime.now().day last = db.magic('select lastfact from memb where tgid = {}'.format( update.message.from_user.id)).fetchall()[0][0] if int(last)!=int(d): text = db.magic('select text, id from facts order by random() LIMIT 1').fetchall() db.magic('update memb set lastfact = (?) where tgid = (?)', (d,update.message.from_user.id)) answer = text[0][0] else: answer = RU.notToday update.message.reply_text(answer, parse_mode=ParseMode.HTML)
def start(bot, update): user = update.message.from_user logger.info('User {} start'.format(user.first_name)) db = SQLite() isexistch = db.magic('select tgid from memb where tgid = (?)', (user.id,)).fetchall() if not isexistch: mnid = int(db.magic('select max(nid) from memb').fetchall()[0][0]) mnid += 1 try: db.magic( sql='insert into memb (nid, tgid, fname, nname, bal) VALUES (?,?,?,?,?)', data=(mnid, user.id, user.first_name, user.username, RU.startbonuses)) except Error as e: logger.error('USER Registration ERROR: User: {}\n{}'.format(user.id, e)) text = update.message.text.split() if len(text) == 2: db.magic('insert into referals (refer, referal) VALUES (?,?)', data=(text[1], mnid)) logger.info('User {} was invited by {}'.format(user.first_name, text[1])) else: mnid = db.magic('select nid from memb where tgid = {}'.format(user.id)).fetchall()[0][0] markup = [[RU.mybal], [RU.refbut, RU.salebut], [RU.howbut, RU.factbut]] update.message.reply_text(RU.welcome.format(user.first_name, str(mnid).zfill(4)), reply_markup=ReplyKeyboardMarkup(markup), resize_keyboard=True, parse_mode=ParseMode.HTML)
def addtotab(bot, update): db = SQLite() text = update.message.text adm_list = RU.admins.split() user=update.message.from_user if user.username in adm_list or user.name in adm_list: if text[:2] == '/f': db.magic('insert into facts(text) values (?)', (text[2:],)) update.message.reply_text(RU.addfact) logger.info('User {}:{} ADD FACT!'.format(user.id,user.username)) elif text[:2] == '/a': db.magic('insert into sales(text) values (?)', (text[2:],)) update.message.reply_text(RU.addsale) logger.info('User {}:{} ADD S A L E!'.format(user.id,user.username))
def usebal(bot, update): db = SQLite() user = update.message.from_user bonus_addr = update.message.text.split() adm_list = RU.admins.split() if user.username in adm_list or user.name in adm_list: if len(bonus_addr)>1: try: account = db.magic('select bal, fname, tgid from memb where nid = {}'.format(str(bonus_addr[1]))).fetchall()[0] except: return bot.send_photo(user.id, RU.error404) bal = int(account[0]) if len(bonus_addr) == 3: b = RU.bonuses_to_cup c = bonus_addr[2] used = int(b)*int(c) temp_bal = bal - used if temp_bal<0: logger.info('User {} has not enouth money'.format(user.first_name)) return update.message.reply_text(RU.notenothpoints.format(bal), parse_mode=ParseMode.HTML) else: db.magic('update memb set bal = (?) where nid = {}'.format(str(bonus_addr[1])), data=(temp_bal,)) logger.info('User {} used {} POINTS from {} account '.format(user.first_name, used, bonus_addr[1])) update.message.reply_text(RU.pointsused.format(used, temp_bal), parse_mode=ParseMode.HTML) bot.send_message(account[2], RU.clientpointsused.format(account[1], used, temp_bal), parse_mode=ParseMode.HTML) elif len(bonus_addr) == 2: used = int(RU.bonuses_to_cup) temp_bal = bal - int(RU.bonuses_to_cup) if temp_bal<0: logger.info('User {} has not enouth money'.format(user.first_name)) return update.message.reply_text(RU.notenothpoints.format(bal), parse_mode=ParseMode.HTML) else: db.magic('update memb set bal = (?) where nid = {}'.format(bonus_addr[1]), data=(temp_bal,)) logger.info('User {} give 1 CUP to {}'.format(user.first_name,bonus_addr[1] )) update.message.reply_text(RU.pointsused.format(used, temp_bal), parse_mode=ParseMode.HTML) bot.send_message(account[2], RU.clientpointsused.format(account[1], used, temp_bal), parse_mode=ParseMode.HTML) else: return update.message.reply_text(RU.usehelp, parse_mode=ParseMode.HTML)
def create_table(db, table, schema): q = f"CREATE TABLE IF NOT EXISTS {table} {schema}" with SQLite(db) as c: c.execute(q) print("Created Table!")
def query(db, q): with SQLite(db) as c: return list(c.execute(q))
def count_rows(db, table): q = f"SELECT COUNT(*) FROM {table}" with SQLite(db) as c: count = list(c.execute(q))[0][0] print(f"There are {count} rows")