def main(): parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('-l', '--list', help='Lists all scans in database.', action='store_true') group.add_argument('-st', '--stats', help='Lists stats about database contents.', action='store_true') group.add_argument('-sc', '--scan', help='Scan a location and add to the database.', type=str) group.add_argument( '-qs', '--quickscan', help='Scan a location ignoring hashes and add to the database.', type=str) parser.add_argument('-v', '--version', action='version', version='0.0.1') parser.add_argument("database", help="Location of the database (Default files.db).", type=str) args = parser.parse_args() if args.database: file_database = database.DataBase(args.database + '.db') else: file_database = database.DataBase('files.db') if args.scan: file_database.add_scan(args.scan) scan_id = file_database.get_last_scan_id() for root, dirnames, files in os.walk(args.scan): for file in files: file_data = file_metadata.FileMetadata(root, file) file_database.add_file(file_data, scan_id) cont = file_database.print_all() print_table(cont) file_database.dissconect() elif args.quickscan: file_database.add_quick_scan(args.quickscan) scan_id = file_database.get_last_scan_id() for root, dirnames, files in os.walk(args.quickscan): for file in files: file_data = file_metadata.FileMetadata(root, file, quick=True) file_database.add_quick_file(file_data, scan_id) cont = file_database.print_all() print_table(cont) file_database.dissconect() elif args.list: cont = file_database.list_scans() print_table(cont) file_database.dissconect() elif args.stats: cont = file_database.show_stats() print_table(cont) file_database.dissconect()
def check_balance_repleh(): date_today = get_datetime_today()[-2:] date_month = database.DataBase().get_data_balance_old() print(date_month) print(date_today) if int(date_month) == int(date_today): print('WEa') database.DataBase().replenishment_balance()
def test_one(self): db = database.DataBase() db.removeAll() assert len(db.constraint) == 0 assert len(db.listRu) == 0
def run(self): ''' Every CONSIDER_DIED_MINS minutes it checks in database if there are controllers which didn't send its corresponding keep alive message. It wakes up every EXIT_CHECK_TIME seconds to see if the main thread ask it to finish. ''' #First of all, the database should be connected by the execution of this thread self.dataBase = database.DataBase(DB_HOST, DB_USER, DB_PASSWD, DB_DATABASE, self) while True: #Blocking until EXIT_CHECK_TIME expires time.sleep(EXIT_CHECK_TIME) self.checkExit() if self.iteration >= self.ITERATIONS: logMsg = 'Checking controller alivnesses.' self.logger.debug(logMsg) deadCtrllers = self.dataBase.setCtrllersNotReachable() for deadCtrller in deadCtrllers: self.toRtEventQueue.put(deadCtrller) self.iteration = 0 else: self.iteration += 1
def check_to_balance() -> BalanceMessage: # checking from db balance user try: answer_balance = database.DataBase().check_balance() return BalanceMessage(month=answer_balance[1], ) except: pass
def add_budjet_month(price_month: int) -> MessageUser: # add to db budjet user try: database.DataBase().insert_budjet(price_month) return MessageUser(message='Бюджет на месяц успешно изменен') except: pass
def delete_all() -> MessageUser: # truncate table from db try: database.DataBase().delete_all() return MessageUser(message='Все данные о покупках удалены') except: return MessageUser(message='Произошла ошибка')
def main(): try: args = parse_args() if args.about: print(get_about_info()) return dbpath = args.path if args.path else DB_PATH db = database.DataBase(dbpath) public_id = db.get_public_id() set_output_path('%s/%s/' % (get_output_path(), public_id)) if not os.path.isdir(get_output_path()): os.makedirs(get_output_path()) if args.clear_output: #clean output contents files = glob.glob('%s/*' % (get_output_path())) for f in files: os.remove(f) common.common_data(db) common.alltop_data(db, 10) common.zero_data(db) common.authors_data(db) attachments.attachments_data(db) attachments.polls_info(db, 20) text_parse.popular_words(db, 200) text_parse.get_topics(db) timing.drawplots(db) except BaseException as e: print(e) traceback.print_exc() exit(1)
def __init__(self): # super(myWindow, self).__init__() self.ui = uic.loadUi(os.path.join(uiFilePath, 'test.ui')) self.ui.allButton.pressed.connect(self.allBtnClick) self.ui.serialNoButton.pressed.connect(self.slNoBtnClick) self.ui.itemTypeButton.pressed.connect(self.itBtnClick) self.ui.locationButton.pressed.connect(self.locBtnClick) self.ui.userButton.pressed.connect(self.usrBtnClick) # self.ui.searchButton.clicked.connect(self.search) self.ui.comboBox.currentIndexChanged.connect(self.search) if user in authUsers: self.ui.addButton.clicked.connect(self.add) self.ui.updateButton.clicked.connect(self.update) self.ui.logButton.clicked.connect(self.log) self.ui.setWindowTitle('GRANTHA') self.ui.setWindowIcon(QtGui.QIcon('granthaLogo.png')) self.ui.tableWidget.customContextMenuRequested.connect( self.viewParentPopUp) self.center() self.ui.show() self.db = database.DataBase()
def __init__(self, sys_path: str = "", time_delta_hour: int = 3, base_name: str = "Default"): # инициализация времени и часового пояса self.time_delta_hour = time_delta_hour self.time_delta = datetime.timedelta(hours=self.time_delta_hour, minutes=0) # инициализация системной папки self.sys_path = sys_path # виды полей для ответа self.ANS_PEER_ID = "peer_id" self.ANS_MESSAGE = "message" self.AMS_RAND_ID = "random_id" self.ANS_KEYBOARD = "keyboard" self.ANS_ATTACHMENT = "attachment" # виды клавиатур self.KBRD_MENU = "menu" self.KBRD_TIMETABLE = "timetable" self.KBRD_ACC_PLAN = "academic_plan" self.KBRD_SETTINGS = "settings" self.KBRD_MORNING_M = "morning_mailing" self.KBRD_EVENING_M = "evening_mailing" self.KBRD_EMPTY = "empty" # модуль расписания self.timetale = timetable.Timetable(self.sys_path, self.time_delta_hour) # модуль клавиатур self.keyboards = keyboard.KeyBoard() # инициализация клавиатур self._init_keyboards() # база данных self.base_name = base_name self.database = database.DataBase(sys_path, self.base_name)
def run(self): ''' ''' self.dataBase = database.DataBase(DB_FILE) for eventIds, toReSendEvents in self.dataBase.getNEvents(RE_SEND_EVTS_QUANT): eventsSent = False while not eventsSent: self.netMngr.reSendEvents(toReSendEvents) try: eventsResponse = self.netToReSnd.get(timeout=WAIT_RESP_TIME) if eventsResponse == 'OK': self.logger.debug('The server confirms the reception of the events.') self.dataBase.delEvents(eventIds) eventsSent = True else: self.logger.warning('The server could not save the events correctly.') raise queue.Empty except queue.Empty: logMsg = ("Sleeping for {} secs to retry sending events." "".format(self.REAL_RE_SEND_TIME) ) self.logger.info(logMsg) for i in range(self.SLEEP_TURNS): self.checkExit() time.sleep(EXIT_CHECK_TIME) self.resenderAlive.clear() sys.exit(self.exitCode)
def __init__(self, api_token: str = "", group_id: int = 0, sys_path: str = "", base_name: str = "Default", server_name: str = "Empty", time_delta_hour: int = 3): # инициализируем часовой пояс self.time_delta_hour = time_delta_hour self.time_delta = datetime.timedelta(hours=self.time_delta_hour, minutes=0) # Даем серверу имя self.server_name = server_name # запоминаем id группы self.group_id = group_id # создаем папку сервера self.folder_path = sys_path + "\\" + server_name if not os.path.exists(self.folder_path): os.makedirs(self.folder_path) # -------------------------------------------------------------------------------------------------------------- # Для Long Poll self.vk = vk_api.VkApi(token=api_token) # Для использования Long Poll API self.long_poll = VkBotLongPoll(self.vk, group_id) # Для вызова методов vk_api self.vk_api = self.vk.get_api() # -------------------------------------------------------------------------------------------------------------- # инициализация базы данных self.base_name = base_name self.database = database.DataBase(self.folder_path, self.base_name) # -------------------------------------------------------------------------------------------------------------- # инициализация класса, обрабатывающего команды self.command_hm = command_headman.Command_headman(self.folder_path, self.time_delta_hour, self.base_name) self.command = command.Command(self.folder_path, self.time_delta_hour, self.base_name) self.log = logining.Logining(self.folder_path, self.time_delta_hour)
def add_purchase(self): self.debt = int(self.price) // (len(self.names) + 1) db = database.DataBase() db.connect('purchases') for i in self.names: db.db_command( 'INSERT INTO purchases VALUES ("{}", "{}", "{}", "{}", "{}")'. format(self.user_name, self.item, self.price, i, self.debt)) try: answer = Bookkeeper.send_message('collector') random_num = str(randint(0, len(answer) - 1)) [ bot.send_message( i, answer[random_num].format(self.user_name, self.item, self.price, self.debt)) for i in self.names ] [ bot.send_message( i, Bookkeeper.send_message('table').format( self.user_name, self.item, self.price, self.debt, self.phone)) for i in self.names ] except telebot.apihelper.ApiException: pass db.disconnect()
def __init__(self): super(GUI_window, self).__init__() self.prompt = None #for selecting things self.data = db.DataBase() #stores the data to be plotted self.version = 0x050 #Should be equal to version in header comment (without periods) self.objectCounter = 0 self.initUI()
def __init__(self, options, daemon_url): """ Setup objects: Methods WorkSpaces """ self.config = configfile.get_config(options.config, verbose=False) self.debug = options.debug self.daemon_url = daemon_url # check config file configfile.sanity_check(self.config) self._update_methods() self.target_workdir = self.config['target_workdir'] self.source_workdirs = {self.target_workdir} | self.config.get('source_workdirs', set()) self.workspaces = {} for name, data in self.config['workdir'].items(): if name in self.source_workdirs: path = data[0] slices = data[1] self.workspaces[name] = workspace.WorkSpace(name, path, slices) undefined_workdirs = self.source_workdirs - set(self.workspaces) if undefined_workdirs: print('\nERROR: Workdir(s) missing definition: ' + ', '.join('\"' + x + '\"' for x in undefined_workdirs) + '.') exit(1) check_slices = set(self.workspaces[name].slices for name in self.workspaces) if len(check_slices) > 1: print('\nERROR: Not all workdirs have the same number of slices!') exit(1) put_workspaces({k: v.path for k, v in self.workspaces.items()}) self.DataBase = database.DataBase(self) self.update_database() self.broken = False
def thread_func(self): # Debug self.DB = database.DataBase() print("Thread criada para cliente:", self.conAddr) while True: try: data = self.conSock.recv(1024) except: if self.user is not None: print("Closing thread for user " + self.user.login) else: print("Closing thread without user") self.DB.closeDB() self.conSock.close() return None if (len(data) < 1): continue data = data.decode() # Debug print("Mensagem recebida de", self.conAddr, ":", data) c = self.check_command(data) if (c == -1): print("Closing connection to", self.conAddr) self.DB.closeDB() self.conSock.close() break self.execute(c, data)
def replenishment_balance_date(data_balance): # return data_balance next month database.DataBase().insert_data_balance(data_balance) date_today = get_datetime_today()[:5] cnt_month = int(get_datetime_today()[5:7]) + 1 # new month result = str(date_today) + '0' + str(cnt_month) + '-' + str( data_balance) # new format data return result
def room_book(): db = database.DataBase('./data.db') params = request.json print(params) ret = db.BookRoom(params['team'], params['room'], params['date'], params['reason']) code = 200 if ret else 500 return jsonify({'status': code}), code
def add_to_db(self): db = DB.DataBase(DB.path) with db.Session() as session: self.add_annual_report_to_db(session) self.add_auditors_to_db(session) self.add_kams_and_kam_tags_to_db(session)
def deleter(self): db = database.DataBase() db.connect('purchases') for i in self.names: db.db_command( 'DELETE FROM purchases WHERE item = "{}" AND debtor_id = "{}"'. format(self.item, i)) db.disconnect()
def find_id(self, user_name): db = database.DataBase() db.connect('users') db.db_command( 'SELECT user_id FROM users WHERE name LIKE "{}"'.format(user_name)) self.db_feedback = db.feedback [self.names.append(i[0]) for i in self.db_feedback] db.disconnect()
def getKey(json, user): """Get key from user.""" if not user: """In here we need to connect to the WS, pass parameters and get a new key""" key = "X86NOH6II01P7R24" # Tests else: db = database.DataBase() key = db.returnKey(json) return key
def other_users(self): db = database.DataBase() db.connect('users') db.db_command( 'SELECT user_id FROM users WHERE user_id NOT LIKE "{}"'.format( self.user_id)) self.db_feedback = db.feedback [self.names.append(i[0]) for i in self.db_feedback] db.disconnect()
def teacher_login(): params = request.json db = database.DataBase('./data.db') info = db.GetTeacherInfo(params['name']) if info: if info[2] == params['password']: log(params['name'] + ' has logined') return jsonify({'status': 200}), 200 return jsonify({'status': 500}), 500
def is_register(self): db = database.DataBase() db.connect('users') db.db_command( 'SELECT name, phone FROM users WHERE user_id LIKE "{}"'.format( self.user_id)) self.db_feedback = [i for i in db.feedback] self.user_name = self.db_feedback[0][0] self.phone = self.db_feedback[0][1] db.disconnect()
def out_expenses() -> List[MessageExpense]: # return last expenses default :10 data_all = [] try: tuple_expenses = database.DataBase().fetchall() for i in tuple_expenses: data_all.append(MessageExpense(name=i[0], amount=i[1], date=i[2])) return data_all except Exception as e: print(e)
def __init__(self): print "Generating Key...\n" self._key = Key() self.database = database.DataBase() self.baseLink = 'http://www.primewire.ag/' self.searchLink = '?search_keywords=' self.keyLink = '&key=' self.key = self._key.key self.sectionLink = '&search_section=' self.debug = False
def finder(self): db = database.DataBase() db.connect('users') db.db_command( 'SELECT name, phone FROM users WHERE user_id NOT LIKE "{}"'.format( self.user_id)) self.db_feedback = [i for i in db.feedback] for i in self.db_feedback: self.people += '• {} - {}\n'.format(i[0], i[1]) db.disconnect()
def PUT(self): path = 'tmp' for root, dirs, files in os.walk(path): for file in files: path = os.path.join(path, file) os.remove(path) bc = stocks.BhavCopy() bc.download_zip() red = database.DataBase() red.delete_all() red.load_csv_to_db() return self.common()
def __init__(self, parent, title, pos, size=(300, 250)): wx.Frame.__init__(self, parent, -1, title, pos, size) self.pheno = None self.make_panels() if db_loaded: self.db = database.DataBase() else: self.db = None self.playing = False self.Bind(wx.EVT_IDLE, self.monit) self.editor = None