def remove_receiver(self, mail_addr): index = self.in_receiver_list(mail_addr) if index != -1: removed_receiver = self.receiver_addrs.pop(index) LOG(msg='%s <%s> is removed from the recipients list' % (removed_receiver[0], removed_receiver[1]), log=Logs.INFO) return True LOG(msg='%s is not in the recipients list' % mail_addr, log=Logs.INFO) return False
def delete(self, recNo): try: records = DataConn().records() if self.read(int(recNo))[-1] == 0: DataConn().set_byte_flag_true_and_clear_values(records[int(recNo)][0], records[int(recNo)][1]) LOG('info', self.only_log).message('Registro %i deletado.' % recNo) else: LOG('debug', self.only_log).message('Tentativa de exclusão de registro ja deletado. recNo: ' + str(recNo)) raise RecordNotFoundException except IndexError: LOG('debug', self.only_log).message('RecordNotFoundException no delete. recNo: ' + str(recNo)) raise RecordNotFoundException
def update(self, recNo, data): try: recNo = int(recNo) if self.read(recNo)[-1] == 0: self.update_any_record(recNo, data) LOG('info', self.only_log).message('Registro %i alterado para: %s' % (recNo, str(data))) else: LOG('debug', self.only_log).message('Tentativa de update do registro %i que não pode ser alterado.' % recNo) raise RecordNotFoundException except: LOG('debug', self.only_log).message('RecordNotFoundException em update. Registro numero: %i' % recNo) raise RecordNotFoundException
def add_image_file(self, file_name): if not isfile(file_name): LOG(msg='The file does not exist: Filename: %s' % file_name, log=Logs.INFO) return False elif file_name in self.image_files: LOG(msg='The file is already in the list', log=Logs.INFO) return False self.image_files.append(file_name) LOG(msg='The image file is added', log=Logs.INFO) return True
def connect(self): try: self.smtp_server = smtplib.SMTP(self.server_addr) self.smtp_server.starttls() self.smtp_server.login(self.uname, self.passwd) except Exception as e: LOG(msg='Unable to connect to SMTP mail server: %s: %s' % (self.server_addr if self.server_addr else 'None', e.message), log=Logs.ERROR) return False LOG(msg='Connection to the SMTP server is established.', log=Logs.INFO) return True
def send_message(self): mail = self.__package_mail() if mail: self.smtp_server.sendmail( self.sender_addr[1], [receiver_addr for _, receiver_addr in self.receiver_addrs], mail.as_string()) LOG(msg='Your mail has been sent successfully...', log=Logs.INFO) return True LOG(msg='Unexpected error occurred.', log=Logs.ERROR) return False
def __init__(self, WS=False): self.log = LOG(prnt=False, level=1) self.connected = False self.dconn = 0 self.mqtt_topic_electricity = "power_meter/electricity" self.mqtt_topic_temperature = "power_meter/temperature" self.mqtt_topic_water = "power_meter/water" self.mqtt_topic_gas = "power_meter/gas" self.mqtt_topic_status = "power_meter/status/A" self.mqtt_topic_last_will = "power_meter/status/L" self.mqtt_client = mqtt.Client(client_id="lcd_logger") self.mqtt_client.will_set(topic=self.mqtt_topic_last_will, payload="offline", qos=0, retain=True) self.mqtt_client.on_connect = self.on_connect self.mqtt_client.on_message = self.on_message self.mqtt_client.on_disconnect = self.on_disconnect self.mqtt_client.on_log = self.on_log self.mqtt_client.disconnect() # Just in case self.mqtt_client.connect(MQTT_SERVER, 1883, 60) self.my_gui = MY_GUI(WS)
def _on_logout(self, _): self._write_respose(Result.OKEY) LOG(LOG.INFO, 'Logout. Player:%s', self._player.name) self.transport.close() self._game.stop() del self._game self._game = None
def process_fecth(process_name, process_codes): total = len(process_codes) threads = [] THREAD_NUM = 30 if (total % THREAD_NUM): count = (total / THREAD_NUM) + 1 else: count = (total / THREAD_NUM) #print "%s threads (%s) start ... each num: %s" %(process_name,count,THREAD_NUM) for i in range(count): thread_name = "%s_thread_%d" % (process_name, i) thread_codes_start = i * THREAD_NUM thread_codes_end = i * THREAD_NUM + THREAD_NUM start = 0 end = 0 if thread_codes_start <= total: start = thread_codes_start if thread_codes_end <= total: end = thread_codes_end else: end = total thread_codes = process_codes[start:end] logger = LOG(thread_name) mylogger = logger.get_logger() th = threading.Thread(name=thread_name, target=thread_fetch, args=(thread_codes, thread_name, mylogger)) threads.append(th) #print thread_name,len(thread_codes) for t in threads: t.start() t.join()
def rotate(iImg, angle): LOG(None, 'Rotation Angle: ' + str(angle)) if 90 == angle: oImg = Image(Image.BY_DATA, cv2.rotate(iImg.data,rotateCode = cv2.ROTATE_90_CLOCKWISE)) elif 180 == angle: oImg = Image(Image.BY_DATA, cv2.rotate(iImg.data,rotateCode = cv2.ROTATE_180)) elif 270 == angle: oImg = Image(Image.BY_DATA, cv2.rotate(iImg.data,rotateCode = cv2.ROTATE_90_COUNTERCLOCKWISE)) else: # Calculate Rotation Matrix h, w, _ = iImg.data.shape cx = w >> 1 cy = h >> 1 rotMatrix = cv2.getRotationMatrix2D((w >> 1, h >> 1), -angle, 1.0) cos = np.abs(rotMatrix[0, 0]) sin = np.abs(rotMatrix[0, 1]) # compute the new bounding dimensions of the image nW = int((h * sin) + (w * cos)) nH = int((h * cos) + (w * sin)) # adjust the rotation matrix to take into account translation rotMatrix[0, 2] += (nW / 2) - cx rotMatrix[1, 2] += (nH / 2) - cy # perform the actual rotation and return the image oImg = Image(Image.BY_DATA, cv2.warpAffine(iImg.data, rotMatrix, (nW, nH))) return oImg
def __init__(self, config, sgdb=None): Main._check_configuration(config) self.cli = CLI() self.config = config self.log = LOG(self.config.get("log_dir", None)) self.sgdb = sgdb if self.sgdb is None and not self.config.get("new_migration", None): if self.config.get("database_engine") == 'mysql': from mysql import MySQL self.sgdb = MySQL(config) elif self.config.get("database_engine") == 'oracle': from oracle import Oracle self.sgdb = Oracle(config) elif self.config.get("database_engine") == 'mssql': from mssql import MSSQL self.sgdb = MSSQL(config) elif self.config.get("database_engine") == 'postgresql': from postgresql import PostgreSQL self.sgdb = PostgreSQL(config) else: raise Exception("engine not supported '%s'" % self.config.get("database_engine")) self.db_migrate = SimpleDBMigrate(self.config)
def find(self, criteria): if criteria['search_and']: and_or = 'e' else: and_or = 'ou' records = DataConn().records() positions = [] positions_name = [] positions_location = [] if criteria['name'] == '' and criteria['location'] == '': for line in range(len(records)): positions.append(line) return positions LOG('info', self.only_log).message('Busca feita por: "' + criteria['name'] + '" ' + and_or + ' "' + criteria['location'] + '"') if criteria['name']: for line in range(len(records)): if records[line][0].lower().find(criteria['name'].lower()) == 0: positions_name.append(line) if criteria['location']: for line in range(len(records)): if records[line][1].lower().find(criteria['location'].lower()) == 0: positions_location.append(line) if criteria['search_and']: line_records = list(set(positions_name).intersection(set(positions_location))) else: positions_name.extend(positions_location) line_records = list(set(positions_name)) line_records.sort() return line_records
def set_from(self, mail_address_alias): mail_address = mail_address_alias.split(',') alias = mail_address[0].strip() mail_address = mail_address[-1].strip() if re.match(MAIL_PATTERN, mail_address): if alias is None: alias = mail_address self.sender_addr = (alias, mail_address) LOG(msg='Sender mail address: %s <%s>' % (self.sender_addr[0], self.sender_addr[1]), log=Logs.INFO) return True LOG(msg='Invalid mail address: %s' % mail_address, log=Logs.ERROR) return False
def read(self, recNo): try: records = DataConn().records() line_value = records[recNo] return line_value except IndexError: LOG('debug', self.only_log).message('IndexError no read. recNo = ' + str(recNo)) raise RecordNotFoundException
def add_player(self, player): if not player.idx in self.__players: LOG(LOG.INFO, "Game: Add player [%s]", player.name) player.set_home(self.map.point[1]) train = Train(idx=len(self.__trains)) player.add_train(train) self.__trains.append(train) self.map.add_train(train) self.__players[player.idx] = player
def set_credentials_from_file(self, filename): try: fp = open(filename, 'r') except IOError: LOG(msg='Unable to open credential file: %s' % filename, log=Logs.ERROR) self.uname = None self.passwd = None return False data = fp.read().strip().split('\n') self.uname = data[0] self.passwd = data[1] LOG(msg='Credentials have been set. Username:%s - Password:%s' % (self.uname, self.passwd), log=Logs.INFO) return True
def data_received(self, data): if self.data: data = self.data + data self.data = b"" if self._process_data(data): LOG(LOG.INFO, str(Action(self._action))) method = self.COMMAND_MAP[self._action] if method: method(self, self.message) self._action = None
def __init__(self): self.headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36" } self.orm = ORM() self.log = LOG() self.logger = self.log.get_logger() self.logger.info('*'*25) self.logger.info("Star:"+datetime.datetime.now().strftime("%Y-%m-%d")) self.logger.info('*' * 25)
def __init__(self, name): Thread.__init__(self, name=name) self.__players = {} self.map = Map('map01') self.name = name LOG(LOG.INFO, "Create game: %s", self.name) self.__trains = [] self.__stop_event = Event() Thread.start(self) self.__pass_next_tick = False self.__next_train_move = {}
def _on_login(self, json_string_data): data = json.loads(json_string_data) if 'name' in data: self._game = Game.create('Game of {}'.format(data['name'])) self._player = Player(data['name']) self._game.add_player(self._player) LOG(LOG.INFO, "Login player: %s", data['name']) message = self._player.to_json_str() self._write_respose(Result.OKEY, message) else: self._write_respose(Result.BAD_COMMAND)
def _on_get_map(self, json_string_data): data = json.loads(json_string_data) if 'layer' in data.keys(): layer = data['layer'] if layer in (0, 1, 10): LOG(LOG.INFO, "Load map layer=%d", layer) message = self._game.map.layer_to_json_str(layer) self._write_respose(Result.OKEY, message) else: self._write_respose(Result.RESOURCE_NOT_FOUND) else: self._write_respose(Result.BAD_COMMAND)
def onClickOK(self): imageResized = self.resizeImage() options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getSaveFileName( None, "Save Image File", "", "Image Files (*.bmp *.dib *.jpeg *.jpg *.png *.pbm *.pgm *.ppm *.tiff *.tif)", options=options) LOG(self, "File path: " + fileName) cv2.imwrite(fileName, imageResized) self.close()
def add_to(self, mail_address_alias): mail_address = mail_address_alias.split(',') alias = mail_address[0].strip() mail_address = mail_address[-1].strip() if re.match(MAIL_PATTERN, mail_address): if alias is None: alias = mail_address if (alias, mail_address) not in self.receiver_addrs: self.receiver_addrs.append((alias, mail_address)) LOG(msg='Receiver mail address is added: %s <%s>' % (self.receiver_addrs[-1][0], self.receiver_addrs[-1][1]), log=Logs.INFO) else: LOG(msg='Receiver mail address is already in the list: %s' % mail_address, log=Logs.WARN) return True LOG(msg='Invalid mail address: %s' % mail_address, log=Logs.ERROR) return False
def tick(self): LOG(LOG.INFO, "Game Tick") for train in self.__trains: if train.line_idx in self.map.line: line = self.map.line[train.line_idx] if train.speed > 0: if train.position < line.length: train.position += 1 if train.position == line.length: self.train_in_point(train, line.point[1]) if train.speed < 0: if train.position > 0: train.position -= 1 if train.position == 0: self.train_in_point(train, line.point[0])
def __init__(self, config=None, sgdb=None, db_migrate=None, execution_log=None): self.cli = CLI() self.config = config or {} self.log = LOG(self.config.get("log_dir", None)) self.sgdb = sgdb if self.sgdb is None and not self.config.get("new_migration", None): if self.config.get("db_engine") is 'mysql': from mysql import MySQL self.sgdb = MySQL(config) elif self.config.get("db_engine") is 'oracle': from oracle import Oracle self.sgdb = Oracle(config) self.db_migrate = db_migrate or SimpleDBMigrate(config) if execution_log: self.execution_log = execution_log
def train_in_point(self, train, point): LOG(LOG.INFO, "Train:%d arrive to point:%d pos:%d", train.idx, point, train.position) post_id = self.map.point[point].post_id if post_id is not None: self.train_in_post(train, self.map.post[post_id]) if train.idx in self.__next_train_move: next_move = self.__next_train_move[train.idx] train.speed = next_move["speed"] train.line_idx = next_move["line_idx"] if train.speed > 0: train.position = 0 elif train.speed < 0: train.position = self.map.line[train.line_idx].length else: train.speed = 0 # has not next move data
def __init__(self): self.L = LOG() self.w = IRQ_DATA(0) self.g = IRQ_DATA(0.0) self.e = IRQ_DATA(0.0) self.hour = int(time.strftime('%M')) % 24 # self.hour = int(time.strftime('%H')) self.sdate = time.strftime('%d-%b-%y') self.mqtt_topic_water = "power_meter/water" self.mqtt_topic_gas = "power_meter/gas" self.mqtt_topic_electricity = "power_meter/electricity" self.mqtt_topic_last_will = "power_meter/status/A" self.cleared_mqtt = True self.new_day = False self.led_on = led_on self.led_off = led_off
def closeEvent(self, event): LOG(self, 'Closing ' + self.windowTitle() + ' Window') # Terminate sub-attributes/processes for subWidget in self.subWidgets: # Remove the link to Parent Widget subWidget.parentWidget = None subWidget.close() self.subWidgets.clear() # Notify Parent Widget if None != self.parentWidget: self.parentWidget.removeSubWidget(self) # Call QtWidgets.QMainWindow 's procedure if 3 > sys.version_info[0]: # Python 2 super(WindowWrapper, self).closeEvent(event) else: # Python 3 super().closeEvent(event)
def clear_receivers(self): self.receiver_addrs = list() LOG(msg='All recipients are removed...', log=Logs.INFO)
def __del__(self): LOG(self, 'Finalizing ' + self.windowTitle() + ' Window')