def stackPressMotor(self): self.ui.lbl_notification.hide() self.ui.tb_press_motor_forward_port.setText( str(DataBase.select('press_motor_forward_port'))) self.ui.tb_press_motor_backward_port.setText( str(DataBase.select('press_motor_backward_port'))) self.ui.tb_press_motor_time.setText( str(DataBase.select('press_motor_time'))) self.ui.StackSetting.setCurrentWidget(self.ui.pageSettingPressMotor)
def __init__(self, config): super().__init__(config) self.last_time = time.time() self.buffer = set() self.interval = self.config["datalog"]["dump_interval"] self.ipfs_endpoint = config["robonomics"]["ipfs_provider"] if config[ "robonomics"]["ipfs_provider"] else "/ip4/127.0.0.1/tcp/5001/http" self.db = DataBase(self.config) self.db.create_table()
def do_job(logger, from_serial=None, limit=1000): from utils.database import DataBase, CodeBook test_db = DataBase(DataBase.Configs.TEST_DB) try: logger.info('LAST_SERIAL\t%d', last_serial) # somethings finally: test_db.close() return
def stackSensor2Ports(self): self.ui.lbl_notification.hide() self.ui.tb_sensor2_trig_port.setText( str(DataBase.select('distance_sensor2_trig_port'))) self.ui.tb_sensor2_echo_port.setText( str(DataBase.select('distance_sensor2_echo_port'))) self.ui.tb_sensor2_depth_threshold.setText( str(DataBase.select('distance_sensor2_threshold_distance'))) self.ui.StackSetting.setCurrentWidget( self.ui.pageSettingDistanceSensor2)
def stackConveyorPort(self): self.ui.lbl_notification.hide() self.ui.tb_conveyor_motor_forward_port.setText( str(DataBase.select('conveyor_motor_forward_port'))) self.ui.tb_conveyor_motor_backward_port.setText( str(DataBase.select('conveyor_motor_backward_port'))) self.ui.tb_conveyor_motor_time_1.setText( str(DataBase.select('conveyor_motor_time'))) self.ui.tb_conveyor_motor_time_2.setText( str(DataBase.select('conveyor_motor_time_2'))) self.ui.StackSetting.setCurrentWidget(self.ui.pageSettingConveyorMotor)
def __init__(self, name='', pin_factory=None, active_high=False): forward_port = int(DataBase.select(name + '_forward_port')) backward_port = int(DataBase.select(name + '_backward_port')) time = float(DataBase.select(name + '_time')) self.forward_motor = DigitalOutputDevice(pin=forward_port, active_high=active_high) self.backward_motor = DigitalOutputDevice(pin=backward_port, active_high=active_high) self.time = time self.name = name print(self.name, 'ready')
def save(self): if self.id: db.query( "UPDATE `triggers` SET `request` = %s, `response` = %s, `type` = %s, `enable` = %s WHERE `id` = %s", (self.request, self.response, str( self.type), self.enable, self.id)) else: db.query( "INSERT INTO `triggers` (`request`, `response`, `type`) VALUES (%s, %s, %s)", (self.request, self.response, str(self.type))) self.id = db.query( "SELECT `id` FROM `triggers` WHERE `request` = %s ORDER BY `id` DESC LIMIT 1", self.request, fetch=True)['id']
def get_all_enabled(): result = db.query("SELECT * FROM `triggers` WHERE `enable` = True", fetch=True, as_list=True) triggers = list(map(Trigger, result)) return triggers
def api(): if flask.request.method == 'POST': global list_spam_threads global list_twitter_bot_users global database file_user_twitter = request.form['file_user_twitter'].replace('\\', '/') file_list_twitter_bot = open(file_user_twitter, encoding="utf8") for line in file_list_twitter_bot.readlines(): list_twitter_bot_users.append( {'username': line.split('|')[0], 'password': line.split('|')[1].replace('\n', '')}) file_user_data = request.form['file_user_data'].replace('\\', '/') file_proxy = request.form['file_proxy'].replace('\\', '/') list_proxy = open(file_proxy, encoding="utf8").readlines()[:] number_threads = int(request.form['number_threads']) database = DataBase(list_twitter_bot_users, file_user_data, list_proxy, number_threads) for i in range(0, number_threads): spam_thread = SpamThread(database) list_spam_threads.append(spam_thread) # do_thread(spam_thread) executor = ThreadPoolExecutor(1) executor.submit(do_thread, spam_thread) list_folders = [str(idx) for idx in range(1, len(database.list_dirs) + 1)] return Response(render_template('index.html', list_folders=list_folders), 200, mimetype='text/html') else: list_folders = [] return Response(render_template('index.html', list_folders=list_folders), 200, mimetype='text/html')
def stackDeviceMode(self): result = DataBase.select('device_mode') if result == 'manual': self.ui.rb_manual_device_mode_setting.setChecked(True) elif result == 'auto': self.ui.rb_auto_device_mode_setting.setChecked(True) self.ui.StackSetting.setCurrentWidget(self.ui.pageSettingDeviceMode)
def get_by_request(request): result = db.query( "SELECT * FROM `triggers` WHERE `enable` = True and `request` = %s", request, fetch=True, as_list=True) triggers = list(map(Trigger, result)) return triggers
def get_by_id(_id): result = db.query( "SELECT * FROM `triggers` WHERE `enable` = True and `id` = %s", _id, fetch=True) if result: return Trigger(result) else: return None
def stackSetting(self): self.setButton(self.ui.btn_left, function=self.stackStart, text='بازگشت', icon='images/icon/back.png', show=True) self.setButton(self.ui.btn_right, function=self.saveSetting, text='ذخیره', icon='images/icon/save.png', show=True) result = DataBase.select('device_mode') if result == 'manual': self.ui.rb_manual_device_mode_setting.setChecked(True) elif result == 'auto': self.ui.rb_auto_device_mode_setting.setChecked(True) self.ui.lbl_notification.hide() self.ui.StackSetting.setCurrentWidget(self.ui.pageSettingEmpty) self.ui.Stack.setCurrentWidget(self.ui.pageSetting)
def stackLicense(self): self.ui.tb_license.setText(str(DataBase.select('app_version'))) self.ui.StackSetting.setCurrentWidget(self.ui.pageSettingLicense)
def __init__(self): super(MainWindow, self).__init__() self.system_id = DataBase.select('system_id') self.device_version = DataBase.select('app_version') self.device_mode = DataBase.select('device_mode') loader = QUiLoader() self.ui = loader.load('main.ui', None) sp_retain = QSizePolicy() sp_retain.setRetainSizeWhenHidden(True) self.ui.btn_left.setSizePolicy(sp_retain) self.ui.btn_right.setSizePolicy(sp_retain) self.ui.lbl_device_info.setSizePolicy(sp_retain) self.ui.btn_setting.setSizePolicy(sp_retain) self.btnOwnerLogin = CustomButton() self.btnOwnerLogin.setGif("animations/Rolling-white.gif") self.ui.vLayoutSignInOwner.addWidget(self.btnOwnerLogin) self.ui.vLayoutSignInOwner.setAlignment(Qt.AlignHCenter) self.btnUserLoginID = CustomButton() self.btnUserLoginID.setGif("animations/Rolling-white.gif") self.lbl = QLabel(None) self.lbl.setStyleSheet(BTN_PASS_RECOVERY_STYLE) self.ui.vLayoutSignInUser.addWidget(self.btnUserLoginID) self.ui.vLayoutSignInUser.addWidget(self.lbl) self.ui.vLayoutSignInUser.setAlignment(Qt.AlignHCenter) self.btnUserLoginMobile = CustomButton() self.btnUserLoginMobile.setGif("animations/Rolling-white.gif") self.lbl = QLabel(None) self.lbl.setStyleSheet(BTN_PASS_RECOVERY_STYLE) # Threads self.auto_delivery_items_thread = AutoDeliveryItemsThread() self.rfid_thread = RFIDThread() self.rfid_thread.success_signal.connect(self.successTransferToRFIDCard) self.rfid_thread.fail_signal.connect(self.transferToRFIDCard) # signals self.ui.btn_refresh_loading.clicked.connect(self.refresh) self.ui.btn_main_menu_1.clicked.connect(self.checkDeviceMode) self.ui.btn_start.hide() #self.ui.btn_main_menu_3.clicked.connect(self.stackFastCharging) self.ui.btn_main_menu_4.clicked.connect(self.stackWalletServices) self.ui.btn_print_receipt_yes.clicked.connect(self.printReceipt) self.ui.btn_print_receipt_no.clicked.connect(self.stackStart) self.ui.btn_other_services_after_delivery.clicked.connect( self.stackWalletServices) self.ui.btn_no_exit_app_setting.clicked.connect(self.stackSetting) self.ui.btn_yes_exit_app_setting.clicked.connect(self.exitProgram) self.ui.btn_setting_start.clicked.connect(self.stackStart) self.ui.btn_setting_1.clicked.connect(self.stackDeviceMode) self.ui.btn_setting_5.clicked.connect(self.stackConveyorPort) self.ui.btn_setting_2.clicked.connect(self.stackPressMotor) # self.ui.btn_setting_10.clicked.connect(self.stackSeparationMotor) self.ui.btn_setting_3.clicked.connect(self.stackSensor1Ports) self.ui.btn_setting_9.clicked.connect(self.stackSensor2Ports) self.ui.btn_setting_6.clicked.connect(self.stackExitApp) self.ui.btn_wallet_services_1.clicked.connect( self.stackChargingResidentialUnit) self.ui.btn_wallet_services_2.clicked.connect(self.stackRFID) self.ui.btn_wallet_services_3.clicked.connect(self.stackCharity) self.ui.btn_wallet_services_4.clicked.connect( self.stackEnvirnmentalProtection) self.ui.btn_wallet_services_5.clicked.connect(self.stackWallet) self.ui.btn_plus_charity.clicked.connect(self.plusCharity) self.ui.btn_minus_charity.clicked.connect(self.minusCharity) self.ui.btn_plus_envirnmental_protection.clicked.connect( self.plusEnvirnment) self.ui.btn_minus_envirnmental_protection.clicked.connect( self.minusEnvirnment) self.ui.btn_plus_rfid.clicked.connect(self.plusRFID) self.ui.btn_minus_rfid.clicked.connect(self.minusRFID) self.ui.btn_confirm_transfer_to_RFIDcard.clicked.connect( self.transferToRFIDCard) self.ui.btn_charity_1.clicked.connect( lambda: self.ui.lbl_selected_charity.setText(self.ui.lbl_charity_1. text())) self.ui.btn_charity_2.clicked.connect( lambda: self.ui.lbl_selected_charity.setText(self.ui.lbl_charity_2. text())) self.ui.btn_charity_3.clicked.connect( lambda: self.ui.lbl_selected_charity.setText(self.ui.lbl_charity_3. text())) self.ui.btn_charity_4.clicked.connect( lambda: self.ui.lbl_selected_charity.setText(self.ui.lbl_charity_4. text())) self.ui.btn_envirnmental_protection_1.clicked.connect( lambda: self.ui.lbl_selected_envirnmental_protection.setText( self.ui.lbl_envirnmental_protection_1.text())) self.ui.btn_envirnmental_protection_2.clicked.connect( lambda: self.ui.lbl_selected_envirnmental_protection.setText( self.ui.lbl_envirnmental_protection_2.text())) self.ui.btn_envirnmental_protection_3.clicked.connect( lambda: self.ui.lbl_selected_envirnmental_protection.setText( self.ui.lbl_envirnmental_protection_3.text())) self.ui.btn_envirnmental_protection_4.clicked.connect( lambda: self.ui.lbl_selected_envirnmental_protection.setText( self.ui.lbl_envirnmental_protection_4.text())) self.ui.setWindowFlags(Qt.FramelessWindowHint | Qt.Dialog) self.ui.showMaximized() self.back_delivery_item_flag = False self.flag_system_startup_now = True self.delivery_state = 'none' # self.categories = Server.getCategories() self.image_classifier = ImageClassifier() self.predict_item_threshold = float( DataBase.select('predict_item_threshold')) self.initHardwares() self.readFile() self.stackSetting() self.playSound('audio2') self.refresh()
'name': 'log', 'attr': [ { 'key': 'id', 'db_type': 'INTEGER PRIMARY KEY AUTOINCREMENT', }, { 'key': 'content', 'db_type': 'TEXT', }, { 'key': 'user_id', 'db_type': 'INTEGER', }, { 'key': 'time', 'db_type': 'FLOAT', }, ], 'extra': [ 'FOREIGN KEY (user_id) REFERENCES user(id)', ], }, ] if __name__ == '__main__': pass db = DataBase('data.db', tables=__tables__)
def saveSetting(self): self.showNotification(SETTING_SAVE_MESSAGE) if self.ui.rb_manual_device_mode_setting.isChecked(): DataBase.update('device_mode', 'manual') elif self.ui.rb_auto_device_mode_setting.isChecked(): DataBase.update('device_mode', 'auto') self.device_mode = DataBase.select('device_mode') if self.ui.tb_sensor1_trig_port.text() != '': result = DataBase.update('distance_sensor1_trig_port', self.ui.tb_sensor1_trig_port.text()) if self.ui.tb_sensor1_echo_port.text() != '': result = DataBase.update('distance_sensor1_echo_port', self.ui.tb_sensor1_echo_port.text()) if self.ui.tb_sensor1_depth_threshold.text() != '': result = DataBase.update('distance_sensor1_threshold_distance', self.ui.tb_sensor1_depth_threshold.text()) if self.ui.tb_sensor2_trig_port.text() != '': result = DataBase.update('distance_sensor2_trig_port', self.ui.tb_sensor2_trig_port.text()) if self.ui.tb_sensor2_echo_port.text() != '': result = DataBase.update('distance_sensor2_echo_port', self.ui.tb_sensor2_echo_port.text()) if self.ui.tb_sensor2_depth_threshold.text() != '': result = DataBase.update('distance_sensor2_threshold_distance', self.ui.tb_sensor2_depth_threshold.text()) if self.ui.tb_press_motor_forward_port.text() != '': result = DataBase.update( 'press_motor_forward_port', self.ui.tb_press_motor_forward_port.text()) if self.ui.tb_press_motor_backward_port.text() != '': result = DataBase.update( 'press_motor_backward_port', self.ui.tb_press_motor_backward_port.text()) if self.ui.tb_press_motor_time.text() != '': result = DataBase.update('press_motor_time', self.ui.tb_press_motor_time.text()) # if self.ui.tb_separation_motor_forward_port.text() != '': # result = DataBase.update('separation_motor_forward_port', self.ui.tb_separation_motor_forward_port.text()) # if self.ui.tb_separation_motor_backward_port.text() != '': # result = DataBase.update('separation_motor_backward_port', self.ui.tb_separation_motor_backward_port.text()) # if self.ui.tb_separation_motor_time.text() != '': # result = DataBase.update('separation_motor_time', self.ui.tb_separation_motor_time.text()) if self.ui.tb_conveyor_motor_forward_port.text() != '': result = DataBase.update( 'conveyor_motor_forward_port', self.ui.tb_conveyor_motor_forward_port.text()) if self.ui.tb_conveyor_motor_backward_port.text() != '': result = DataBase.update( 'conveyor_motor_backward_port', self.ui.tb_conveyor_motor_backward_port.text()) if self.ui.tb_conveyor_motor_time_1.text() != '': result = DataBase.update('conveyor_motor_time', self.ui.tb_conveyor_motor_time_1.text()) if self.ui.tb_conveyor_motor_time_2.text() != '': result = DataBase.update('conveyor_motor_time_2', self.ui.tb_conveyor_motor_time_2.text()) self.initHardwares()
def initHardwares(self): try: if hasattr(self, 'press_motor'): self.press_motor.close() if hasattr(self, 'conveyor_motor'): self.conveyor_motor.close() if hasattr(self, 'distance_sensor1'): self.distance_sensor1.close() print("distance sensor 1 close") if hasattr(self, 'distance_sensor2'): self.distance_sensor2.close() print("distance sensor 2 close") except Exception as e: print("error:", e) try: self.press_motor = Motor(name='press_motor', pin_factory=factory) self.setButton(self.ui.btn_press_motor_forward_on, function=self.press_motor.forward) self.setButton(self.ui.btn_press_motor_backward_on, function=self.press_motor.backward) self.setButton(self.ui.btn_press_motor_off, function=self.press_motor.stop) except Exception as e: print("error:", e) ErrorLog.writeToFile( str(e) + ' In press_motor initHardwares Method') try: # normal # self.conveyor_motor = Motor(name='conveyor_motor', pin_factory=factory) # red relay self.conveyor_motor = Motor(name='conveyor_motor', pin_factory=factory, active_high=True) self.conveyor_motor_time_2 = float( DataBase.select('conveyor_motor_time_2')) self.setButton(self.ui.btn_conveyor_motor_forward_on, function=self.conveyor_motor.forward) self.setButton(self.ui.btn_conveyor_motor_backward_on, function=self.conveyor_motor.backward) self.setButton(self.ui.btn_conveyor_motor_off, function=self.conveyor_motor.stop) except Exception as e: print("error:", e) ErrorLog.writeToFile( str(e) + ' In conveyor_motor initHardwares Method') try: distance_sensor1_trig_port = int( DataBase.select('distance_sensor1_trig_port')) distance_sensor1_echo_port = int( DataBase.select('distance_sensor1_echo_port')) distance_sensor1_threshold_distance = float( DataBase.select('distance_sensor1_threshold_distance')) self.distance_sensor1 = DistanceSensor( distance_sensor1_echo_port, distance_sensor1_trig_port, max_distance=1, threshold_distance=distance_sensor1_threshold_distance / 100, pin_factory=factory) self.distance_sensor1.when_in_range = self.distanceSensor1WhenInRange self.distance_sensor1.when_out_of_range = self.distanceSensor1WhenOutOfRange print('distance sensor 1 ready') except Exception as e: print("error:", e) ErrorLog.writeToFile( str(e) + ' In distance_sensor1 initHardwares Method') try: distance_sensor2_trig_port = int( DataBase.select('distance_sensor2_trig_port')) distance_sensor2_echo_port = int( DataBase.select('distance_sensor2_echo_port')) distance_sensor2_threshold_distance = float( DataBase.select('distance_sensor2_threshold_distance')) self.distance_sensor2 = DistanceSensor( distance_sensor2_echo_port, distance_sensor2_trig_port, max_distance=1, threshold_distance=distance_sensor2_threshold_distance / 100, pin_factory=factory) self.distance_sensor2.when_in_range = self.distanceSensor2WhenInRange self.distance_sensor2.when_out_of_range = self.distanceSensor2WhenOutOfRange print('distance sensor 2 ready') except Exception as e: print("error:", e) ErrorLog.writeToFile( str(e) + ' In distance_sensor2 initHardwares Method') try: if not hasattr(self, 'rfid_sensor'): self.rfid_sensor = SimpleMFRC522() print('RFID sensor ready') except Exception as e: print("error:", e) ErrorLog.writeToFile( str(e) + ' In rfid_sensor initHardwares Method')
from pages.flat_page import FlatPage from parsers.flat_parser import FlatParser from utils.queries import get_page_content from utils.database import DataBase logging.basicConfig( format="%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s", datefmt='%m-%d-%Y %H:%M:%S', level=logging.DEBUG, filename="logs.txt") logger = logging.getLogger('scraping') logger.info('Loading first page with ads list...') db = DataBase() db.open_connection() # db.clear() base_url = 'https://kvadrat64.ru/' page_content = get_page_content(base_url + 'sellflatbank-50-1.html') page = AllFlatsPage(page_content) page_count = page.page_count deal_type = 'Продажа' print(f'Найдено {page_count} страниц с объявлениями о продаже квартир') for i in range(20): logger.debug(f'Opening {i+1} page with ads lists...') page_content = get_page_content(base_url + f'sellflatbank-50-{i+1}.html') page = AllFlatsPage(page_content)
class DatalogFeeder(IFeeder): """ The feeder is responsible for collecting measurements and publishing an IPFS hash to Robonomics on Substrate It requires the full path to `robonomics` execution binary and an account's private key """ def __init__(self, config): super().__init__(config) self.last_time = time.time() self.buffer = set() self.interval = self.config["datalog"]["dump_interval"] self.ipfs_endpoint = config["robonomics"]["ipfs_provider"] if config[ "robonomics"]["ipfs_provider"] else "/ip4/127.0.0.1/tcp/5001/http" self.db = DataBase(self.config) self.db.create_table() def feed(self, data: [StationData]): if self.config["datalog"]["enable"]: rospy.loginfo("DatalogFeeder:") for d in data: if d.measurement.public and d.measurement.model != PING_MODEL: rospy.logdebug(f"Adding data to buffer: {d.measurement}") self.buffer.add(d.measurement) if (time.time() - self.last_time) >= self.interval: if self.buffer: rospy.logdebug("About to publish collected data...") rospy.logdebug(f"Buffer is {self.buffer}") ipfs_hash, file_path = _get_multihash( self.buffer, self.db, self.ipfs_endpoint) self._pin_to_temporal(file_path) _pin_to_pinata(file_path, self.config) self.to_datalog(ipfs_hash) else: rospy.loginfo("Nothing to publish") # self.buffer = set() # self.last_time = time.time() else: rospy.loginfo("Still collecting measurements...") def _pin_to_temporal(self, file_path: str): username = self.config["datalog"]["temporal_username"] password = self.config["datalog"]["temporal_password"] if username and password: auth_url = "https://api.temporal.cloud/v2/auth/login" token_resp = requests.post(auth_url, json={ "username": username, "password": password }) token = token_resp.json() url_add = "https://api.temporal.cloud/v2/ipfs/public/file/add" headers = {"Authorization": f"Bearer {token['token']}"} resp = requests.post(url_add, files={ "file": open(file_path), "hold_time": (None, 1) }, headers=headers) if resp.status_code == 200: rospy.loginfo("File pinned to Temporal Cloud") def to_datalog(self, ipfs_hash: str): rospy.loginfo(ipfs_hash) self.last_time = time.time() self.buffer = set() robonomics_keypair = Keypair.create_from_mnemonic( self.config["frontier"]["suri"]) ipci_keypair = Keypair.create_from_seed(self.config["datalog"]["suri"]) robonomics_connect = _substrate_connect( endpoint=self.config["frontier"]["remote"]) ipci_connect = _substrate_connect( endpoint=self.config["datalog"]["remote"]) robonomics_call = _substrate_call(substrate=robonomics_connect, ipfs_hash=ipfs_hash) ipci_call = _substrate_call(substrate=ipci_connect, ipfs_hash=ipfs_hash) robonomics_extrinsic = robonomics_connect.create_signed_extrinsic( call=robonomics_call, keypair=robonomics_keypair) ipci_extrinsic = ipci_connect.create_signed_extrinsic( call=ipci_call, keypair=ipci_keypair) try: ipci_receipt = ipci_connect.submit_extrinsic( ipci_extrinsic, wait_for_inclusion=True) rospy.loginfo( f'Ipfs hash sent to DAO IPCI and included in block {ipci_receipt.block_hash}' ) except SubstrateRequestException as e: rospy.loginfo( f'Something went wrong during extrinsic submission to DAO IPCI: {e}' ) try: robonomics_receipt = robonomics_connect.submit_extrinsic( robonomics_extrinsic, wait_for_inclusion=True) rospy.loginfo( f'Ipfs hash sent to Robonomics and included in block {robonomics_receipt.block_hash}' ) self.db.update_status("sent", ipfs_hash) except SubstrateRequestException as e: rospy.loginfo( f'Something went wrong during extrinsic submission to Robonomics: {e}' )