def Run(self): with self.protocol.lockCmd: if not self.Authorized(): self.SendUnauthorizedResp() return CBaseCommand.Run(self) with SBDB.session_scope() as session: password = self.body.get(BaseCommand.PN_PASSWORD) email = self.body.get(BaseCommand.PN_EMAIL) language_name = self.body.get(BaseCommand.PN_LANGUAGENAME) mobile_phone = self.body.get(BaseCommand.PN_MOBLEPHONE) respond = self.GetResp() try: account = ( session.query(SBDB_ORM.Account).filter(SBDB_ORM.Account.id == self.protocol.account_id).one() ) if password is not None: account.password = Util.hash_password(password) if email is not None: account.email = email if language_name is not None: for language in session.query(SBDB_ORM.Language).all(): if language.language == language_name: account.language_id = language.id if mobile_phone is not None: account.mobile_phone = mobile_phone session.commit() except SQLAlchemyError, e: respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION) logging.error("transport %d:%s", id(self.protocol.transport), e) session.rollback() respond.Send()
def Decode(self, data): """ return a tuple: new data,command """ if self.HeaderTagType < 0: # not decide if data[:4] == self.factory.SBMP_HEADERTAG: self.HeaderTagType = 1 else: self.HeaderTagType = 0 if self.HeaderTagType == 1: tag_position = data.find(self.factory.SBMP_HEADERTAG) if tag_position < 0: return (data, None) data = data[tag_position + 4 :] # remove head tag length, command_id = struct.unpack("!2I", data[:8]) command = None if length <= len(data): command_data = data[:length] if Command.dicInt_Type.has_key(command_id): try: command = Command.dicInt_Type[command_id](command_data, self) except Exception, e: logging.error( "build command exception in transport %d: %s :%s", id(self.transport), str(e), Util.asscii_string(command_data), ) command = None else: command = Command.BaseCommand.CMesscodeCommand(command_data, self) data = data[length:]
def evaluate(self,model,dataEvaluation,attributeCount): attributesCount = attributeCount-1 dataset = np.empty((0,attributesCount),int) for element in dataEvaluation: temp = Util.interpretData(element) dataset = np.append(dataset, [np.array(temp)], axis=0) self.evaluation = self.getPredictions(model,dataset)
def processData(self,data,attributeCount): dataset = np.empty((0,attributeCount),int) for element in data: #making sure G3 is the last element out = int(element.pop("G3",None)) temp = Util.interpretData(element) temp.append(out) dataset = np.append(dataset, [np.array(temp)], axis=0) self.trainSet, self.testSet = Util.splitDataset(dataset, 0.67) model = self.summarizeClass(self.trainSet) results = self.getPredictions(model,self.testSet) self.predictions = results self.confidence = self.getAccuracy(self.testSet,results) return model
def GetResp(self): TypeResp=type(self).TypeResp command_id=Util.int32_to_uint32(self.command_id)|0x80000000 if TypeResp == object: cmd_resp=CBaseRespCommand(protocol=self.protocol,request=self,command_id=command_id) return cmd_resp else: return TypeResp(protocol=self.protocol,request=self,command_id=command_id)
def hash_password(): session = SBDB.GetSession() accounts = session.query(SBDB_ORM.Account).with_lockmode("update").all() for account in accounts: account.password = Util.hash_password(account.password) session.commit()
def put(self): args = self.parser.parse_args() if (not Util._isValidStatus(args["status"])): return app.config["INVALID_STATUS"], 405 try: id = int(args['id']) except ValueError: return app.config["INVALID_ID_ERROR"], 400 try: Pet.objects.get(id=id) pet = Pet(**args).save() pet = Util._formatPetToJson(pet) return pet, 200 except Pet.DoesNotExist: return app.config["NOT_FOUND_ERROR"], 404 pass
def main(): data = Util.readInterpretData('evaluation-dataset.csv') data2 = Util.readInterpretData('evaluation-dataset.csv') evaluation = Util.readInterpretData("evaluation-evaluation.csv") #Genetic #algo = LearningStrategy(algorithm=Genetics) #gen_data = algo.learn(data,evaluation,LearningStrategy(algorithm=BayesNaive)) #gen_data = algo.learn(data,LearningStrategy(algorithm=kNN)) #Bayes #algo = LearningStrategy(algorithm=BayesNaive) #bayes_data = algo.learn(data,evaluation) #algo.showResult() #kNN algo = LearningStrategy(algorithm=kNN) knn_data = algo.learn(data2, evaluation) algo.showResult()
def __init__(self, projectFolder,packageName) : self.mProjectOutput = projectFolder self.mJavaSourceOutput = projectFolder + "/src/"+ Util.convertPageToFolderPath(packageName) self.templateFolder= projectFolder + "/"+ Constants.TEMPLATE_FOLDER + "/ListViewGenerator.stg" # self.mGroup = StringTemplateGroupLoader(self.templateFolder, "UTF-8", '<', '>') self.stMain = self.mGroup.getInstanceOf("main") self.mPackageName = packageName self.stMain.setAttribute("packageName", self.mPackageName) self.stBaseAdapter = self.mGroup.getInstanceOf("baseadapter") self.stBaseAdapter.setAttribute("packageName", self.mPackageName)
def main(): data = Util.readInterpretData('evaluation-dataset.csv') data2 = Util.readInterpretData('evaluation-dataset.csv') evaluation = Util.readInterpretData("evaluation-evaluation.csv") #Genetic #algo = LearningStrategy(algorithm=Genetics) #gen_data = algo.learn(data,evaluation,LearningStrategy(algorithm=BayesNaive)) #gen_data = algo.learn(data,LearningStrategy(algorithm=kNN)) #Bayes #algo = LearningStrategy(algorithm=BayesNaive) #bayes_data = algo.learn(data,evaluation) #algo.showResult() #kNN algo = LearningStrategy(algorithm=kNN) knn_data = algo.learn(data2,evaluation) algo.showResult()
def get(self): # preparing query status = request.args.getlist("status") allPets = [] for stat in status: if (not Util._isValidStatus(stat)): return app.config["INVALID_STATUS"], 400 pets = Pet.objects(status=stat) allPets.extend(pets) # prepare result for response petsList = [] for pet in allPets: pet = Util._formatPetToJson(pet) petsList.append(pet) return petsList, 200 pass
def view_bulletin(): bulletin_id = request.args.get('id') q = request.args.get('q') if q is not None: return redirect(url_for('view_bulletins', page=1, q=q)) form = BulletinForm(request.form) if request.method == 'POST' and form.validate(): if form.id.data: bulletin = orm.Bulletin.query.get(int(form.id.data)) bulletin.dt = form.dt.data bulletin.title = form.title.data bulletin.content = form.content.data bulletin.source = form.source.data bulletin.author = form.author.data orm.db.session.commit() else: bulletin = orm.Bulletin(form.dt.data, form.title.data, form.content.data, form.source.data, form.author.data) orm.db.session.add(bulletin) orm.db.session.commit() form.id.data = bulletin.id if request.form.has_key('upload'): file = request.files['image'] if file: file_server = str(uuid.uuid1()) + Util.file_extension( file.filename) pathfile_server = os.path.join(UPLOAD_PATH, file_server) file.save(pathfile_server) if os.stat(pathfile_server).st_size < 1 * 1024 * 1024: bulletinimage = orm.Bulletinimage(bulletin.id, file_server) orm.db.session.merge(bulletinimage) orm.db.session.commit() else: os.remove(pathfile_server) else: return redirect(url_for('view_bulletin')) elif request.method == 'GET' and bulletin_id: form = logic.GetBulletinFormById(bulletin_id) logic.LoadBasePageInfo('修改公告', '输入并确定', form) else: form.dt.data = datetime.datetime.now() logic.LoadBasePageInfo('新建公告', '输入并确定', form) if form.id.data: bulletin = orm.Bulletin.query.get(int(form.id.data)) form.bulletin = bulletin if form.bulletin: form.bulletinimages = form.bulletin.bulletinimages return render_template('view_bulletin.html', form=form)
def post(self, id): args = self.parser.parse_args() id = Util._isValidId(id) if not id: return app.config["INVALID_ID_ERROR"], 400 if (not Util._isValidStatus(args["status"])): return app.config["INVALID_STATUS"], 405 try: pet = Pet.objects.get(id=id) pet.name = args["name"] pet.status = args["status"] pet.save() pet = Util._formatPetToJson(pet) return pet, 200 except Pet.DoesNotExist: return app.config["NOT_FOUND_ERROR"], 404 pass
def onkeypress(event): global img_file,xml_file global qtd if event.key == 'q': exit() elif event.key == ' ': plt.close() elif event.key == 'f1': os.system('mv {old} {new}'.format(old = xml_file,new = trash_xml)) os.system('mv {old} {new}'.format(old = img_file.path,new = trash_img)) qtd -= 1 plt.close() elif event.key == 'f5': os.system('mv {old} {new}'.format(old = xml_file,new = trash_xml)) qtd -=1 plt.close() elif event.key == 'enter': Util.exibe_imagem(img_file,xml_file,ax,fig) elif event.key == 'e': os.system('gedit ' + xml_file)
def AddSubscribeServer(listServer,serverType=SBDB.CV_TYPE_SERVER_FUNCTION): global MyServerID, MyServerAddress, MyServerType,dictServerInfo listMyIPs=Util.GetMachineIPs() for server in listServer: if server[1] not in listSubscribedServer: socketSubscribe.connect("tcp://%s:%d" % (server[1],PORT_PUBSUB)) listSubscribedServer.append(server[1]) dictServerInfo[server[0]]=server[2] if server[1] in listMyIPs: MyServerID=server[0] MyServerAddress=server[1] if MyServerType!=SBDB.CV_TYPE_SERVER_SUPERVISION: MyServerType=serverType
def predict(agent=None): util = Util() g_size = 1079712 top_nodes_idx, adj_lists, edge_weight, features, node2idx, idx2node, num_used_nodes = util.load_data( "./dataset/test/", k) # top_nodes_idx, adj_lists, nodes_nbr_weight, features, node2idx, idx2node, num_used_nodes = util.load_data("./dataset/train/", k) if agent is None: agent = Agent(model_dir, k, lr, gamma, mem_size, g_size, layer_infos) reward, seeds = validate(agent, features, top_nodes_idx, adj_lists, edge_weight, node2idx, idx2node, num_used_nodes, dataset_type="test") # reward, seeds = validate(agent, features, top_nodes_idx, adj_lists, node2idx, idx2node, num_used_nodes, dataset_type="train") return reward, seeds
def GetResp(self): TypeResp = type(self).TypeResp command_id = Util.int32_to_uint32(self.command_id) | 0x80000000 if TypeResp == object: cmd_resp = CBaseRespCommand(protocol=self.protocol, request=self, command_id=command_id) return cmd_resp else: return TypeResp(protocol=self.protocol, request=self, command_id=command_id)
def legenda(): Util.hb1() print('[Space] - Proxima imagem') print('[F1] - Mover imagem e xml para a pasta trash') print('[F5] - Mover xml para a pasta trash') print('[E] - Editar XML') print('[Enter] - Recarregar imagem') Util.plt_legenda() print('[Q] - Sair') _,_,qtd_arqs,msg = c_count.count() Util.hb1() print(msg) Util.hb1() print('N: ',qtd, '/',qtd_arqs)
def view_bulletin(): bulletin_id = request.args.get('id') q = request.args.get('q') if q is not None: return redirect(url_for('view_bulletins', page=1, q=q)) form = BulletinForm(request.form) if request.method == 'POST' and form.validate(): if form.id.data: bulletin = orm.Bulletin.query.get(int(form.id.data)) bulletin.dt = form.dt.data bulletin.title = form.title.data bulletin.content = form.content.data bulletin.source = form.source.data bulletin.author = form.author.data orm.db.session.commit() else: bulletin = orm.Bulletin(form.dt.data, form.title.data, form.content.data, form.source.data, form.author.data) orm.db.session.add(bulletin) orm.db.session.commit() form.id.data = bulletin.id if request.form.has_key('upload'): file = request.files['image'] if file : file_server = str(uuid.uuid1())+Util.file_extension(file.filename) pathfile_server = os.path.join(UPLOAD_PATH, file_server) file.save(pathfile_server) if os.stat(pathfile_server).st_size <1*1024*1024: bulletinimage = orm.Bulletinimage(bulletin.id,file_server) orm.db.session.merge(bulletinimage) orm.db.session.commit() else: os.remove(pathfile_server) else: return redirect(url_for('view_bulletin')) elif request.method =='GET' and bulletin_id: form = logic.GetBulletinFormById(bulletin_id) logic.LoadBasePageInfo('修改公告','输入并确定',form) else: form.dt.data = datetime.datetime.now() logic.LoadBasePageInfo('新建公告','输入并确定',form) if form.id.data: bulletin = orm.Bulletin.query.get(int(form.id.data)) form.bulletin = bulletin if form.bulletin: form.bulletinimages = form.bulletin.bulletinimages return render_template('view_bulletin.html',form = form)
def post_post_account(result=None, **kw): """Accepts a single argument, `result`, which is the dictionary representation of the created instance of the model. 新建用户后,向用户手机发送验证码(为用户的POST请求而增加) """ if result and result.has_key(restful.ITEM_ID): account = orm.Account.query.get(int(result.get(restful.ITEM_ID))) account.checkcode = str(random.randint(100001, 999999)) orm.db.session.commit() #send sms verification here message = '您的验证码为%s, 请勿告诉他人,15分钟有效 【学莫愁】' % account.checkcode Util.SendSMSByZA(account.telephone, message) # 实际发送验证码 return result pass
def create_db(self): conn = sqlite3.connect(self.DB_address) cur = conn.cursor() cur.execute( "create table {config_table_name} (date text, space_size int)". format(config_table_name=self.config_table_name)) cur.execute( "create table {wall_table_name} (image_name text, hash text)". format(wall_table_name=self.wall_table_name)) conn.commit() cur.close() conn.close() wall_dir_size = Util.get_instance().get_wall_dir_size() self.insert_config_data('', wall_dir_size)
def get_rand_image(self): def_project_dir = Util.get_instance().get_project_dir() if os.path.exists(def_project_dir) and len(os.listdir(def_project_dir)) > 1: listdir = os.listdir(def_project_dir) random_image = listdir.__getitem__(random.randint(0, len(listdir) - 1)) image_address = def_project_dir + os.sep + random_image elif os.path.exists(self.os_default_picture_path) and len(os.listdir(self.os_default_picture_path)) > 2: os_listdir = os.listdir(self.os_default_picture_path) random_image = os_listdir.__getitem__(random.randint(0, len(os_listdir) - 1)) image_address = self.os_default_picture_path + os.sep + random_image else: def_proj_image_dir = "image" def_proj_image_name = "def_wall.jpg" image_address = Util.get_instance().get_project_root() \ + os.sep \ + def_proj_image_dir \ + os.sep \ + def_proj_image_name return image_address
def RunTransmitMessage(message): if message.operation in [OPER_REQUEST, OPER_RESPONSE]: length, command_id = struct.unpack("!2I", message.body[:8]) command = None try: command = Command.dicInt_Type[command_id](message.body, protocolInternal) except Exception, e: logging.error( "build command exception in protocolInternal transport %d: %s :%s", id(protocolInternal.transport), str(e), Util.asscii_string(message.body)) command = None command.internalMessage = message #threads.deferToThread(command.Run) command.Run()
def delete(self, id): api_key = request.headers.get('api_key') if (not (api_key == app.config["API_KEY"])): return app.config["INVALID_API_KEY"], 400 id = Util._isValidId(id) if not id: return app.config["INVALID_ID_ERROR"], 400 try: pet = Pet.objects.get(id=id) res = pet.delete() return app.config["DELETE_SUCCESS"], 200 except Pet.DoesNotExist: return app.config["NOT_FOUND_ERROR"], 404 pass
def AddDataAndDecode(self,lock,data): print "data received in transport %d : %s (%s)" % (id(self.transport),Util.asscii_string(data),data) self.m_buffer+=data while len(self.m_buffer)>=Command.BaseCommand.CBaseCommand.HEAD_LEN : self.m_buffer,command,=self.Decode(self.m_buffer) if command == None: break if waitList.has_key(command.command_seq): requestCmd=waitList[command.command_seq] requestCmd.respond=command requestCmd.lock.release() requestCmd.cond.acquire() requestCmd.cond.notifyAll() requestCmd.cond.release() threads.deferToThread(command.Run) lock.release()
def Run(self): with self.protocol.lockCmd: CBaseCommand.Run(self) user_name=self.body.get(BaseCommand.PN_USERNAME) if user_name is not None: user_name=user_name.strip() password=self.body[BaseCommand.PN_PASSWORD] email=self.body.get(BaseCommand.PN_EMAIL) if email is not None: email=email.strip() mobile_phone=self.body.get(BaseCommand.PN_MOBLEPHONE) if mobile_phone is not None: mobile_phone=mobile_phone.strip() respond=self.GetResp() with SBDB.session_scope() as session : if user_name is None and password is None and email is None: respond.SetErrorCode(BaseCommand.CS_PARAMLACK) elif user_name is not None and (session.query(SBDB_ORM.Account).filter(or_(SBDB_ORM.Account.user_name==user_name,SBDB_ORM.Account.email==user_name,SBDB_ORM.Account.mobile_phone==user_name)).first() is not None or len(user_name)<2): respond.SetErrorCode(BaseCommand.CS_USERNAME) elif email is not None and (session.query(SBDB_ORM.Account).filter(or_(SBDB_ORM.Account.user_name==email,SBDB_ORM.Account.email==email,SBDB_ORM.Account.mobile_phone==email)).first() is not None or not Util.validateEmail(email)): respond.SetErrorCode(BaseCommand.CS_EMAIL) elif mobile_phone is not None and (session.query(SBDB_ORM.Account).filter(or_(SBDB_ORM.Account.user_name==mobile_phone,SBDB_ORM.Account.email==mobile_phone,SBDB_ORM.Account.mobile_phone==mobile_phone)).first() is not None or not Util.validateMobilePhone(mobile_phone)): respond.SetErrorCode(BaseCommand.CS_MOBILEPHONE) else: try: account=SBDB_ORM.Account() account.language_id=2 account.email=email #account.password=password account.password=Util.hash_password(password) account.user_name=user_name account.mobile_phone=mobile_phone account.version=0 apartment=SBDB_ORM.Apartment() apartment.arm_state=BaseCommand.PV_ARM_OFF apartment.name="Home" apartment.scene_id=None apartment.version=0 account.apartments.append(apartment) session.add(account) session.commit() respond.body[BaseCommand.PN_VERSION]=apartment.version respond.body[BaseCommand.PN_APARTMENTID]=apartment.id respond.body[BaseCommand.PN_NAME]=apartment.name except SQLAlchemyError as e: respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION) logging.error("transport %d:%s",id(self.protocol.transport),e) session.rollback() respond.Send()
def Run(self): with self.protocol.lockCmd: CBaseCommand.Run(self) user_name=self.body.get(BaseCommand.PN_USERNAME) if user_name is not None: user_name=user_name.strip() password=self.body[BaseCommand.PN_PASSWORD] email=self.body.get(BaseCommand.PN_EMAIL) if email is not None: email=email.strip() mobile_phone=self.body.get(BaseCommand.PN_MOBLEPHONE) if mobile_phone is not None: mobile_phone=mobile_phone.strip() respond=self.GetResp() with SBDB.session_scope() as session : if user_name is None and password is None and email is None: respond.SetErrorCode(BaseCommand.CS_PARAMLACK) elif user_name is not None and (session.query(SBDB_ORM.Account).filter(or_(SBDB_ORM.Account.user_name==user_name,SBDB_ORM.Account.email==user_name,SBDB_ORM.Account.mobile_phone==user_name)).first() is not None or len(user_name)<2): respond.SetErrorCode(BaseCommand.CS_USERNAME) elif email is not None and (session.query(SBDB_ORM.Account).filter(or_(SBDB_ORM.Account.user_name==email,SBDB_ORM.Account.email==email,SBDB_ORM.Account.mobile_phone==email)).first() is not None or not Util.validateEmail(email)): respond.SetErrorCode(BaseCommand.CS_EMAIL) elif mobile_phone is not None and (session.query(SBDB_ORM.Account).filter(or_(SBDB_ORM.Account.user_name==mobile_phone,SBDB_ORM.Account.email==mobile_phone,SBDB_ORM.Account.mobile_phone==mobile_phone)).first() is not None or not Util.validateMobilePhone(mobile_phone)): respond.SetErrorCode(BaseCommand.CS_MOBILEPHONE) else: try: account=SBDB_ORM.Account() account.language_id=2 account.email=email #account.password=password account.password=Util.hash_password(password) account.user_name=user_name account.mobile_phone=mobile_phone account.version=0 apartment=SBDB_ORM.Apartment() apartment.arm_state=BaseCommand.PV_ARM_OFF apartment.name="Home" apartment.scene_id=None apartment.version=0 account.apartments.append(apartment) session.add(account) session.commit() respond.body[BaseCommand.PN_VERSION]=apartment.version respond.body[BaseCommand.PN_APARTMENTID]=apartment.id respond.body[BaseCommand.PN_NAME]=apartment.name except SQLAlchemyError,e: respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION) logging.error("transport %d:%s",id(self.protocol.transport),e) session.rollback() respond.Send()
def AddDataAndDecode(self,lock,data): print(("data received in transport %d : %s (%s)" % (id(self.transport),Util.asscii_string(data),data))) self.m_buffer+=data while len(self.m_buffer)>=Command.BaseCommand.CBaseCommand.HEAD_LEN : self.m_buffer,command,=self.Decode(self.m_buffer) if command == None: break if command.command_seq in waitList: requestCmd=waitList[command.command_seq] requestCmd.respond=command requestCmd.lock.release() requestCmd.cond.acquire() requestCmd.cond.notifyAll() requestCmd.cond.release() threads.deferToThread(command.Run) lock.release()
def Send_Real(self): reactor.callFromThread(self.protocol.transport.write,self.data) # p=0 # len_data=len(self.data) # max_block=200 # while p<len_data: # if len_data-p>max_block: # #self.protocol.transport.write(self.data[p:p+max_block]) # reactor.callFromThread(self.protocol.transport.write,self.data[p:p+max_block]) # p=p+max_block # else: # #self.protocol.transport.write(self.data[p:]) # reactor.callFromThread(self.protocol.transport.write,self.data[p:]) # p=len_data # if p<len_data: # time.sleep(0.2) print "data sent in transport %d : %s (%s)" % (id(self.protocol.transport),Util.asscii_string(self.data),self.data)
def remove_oldest_files(self, overflow_size): """delete oldest file base on modified time""" paths = sorted(Path(Util.get_instance().project_dir).iterdir(), key=os.path.getmtime) tmp_size = 0 index = 0 for file in paths: print(file) if file.exists() and file.is_file(): tmp_size += (os.path.getsize(Path(file)) / (1024 * 1024)) index = paths.index(file) if tmp_size >= overflow_size: break for i in range(len(paths) - 1): if i <= index: file = paths.__getitem__(i) if file.exists() and file.is_file(): os.remove(Path(file)) else: break
def RunTransmitMessage(message): if message.operation in [OPER_REQUEST, OPER_RESPONSE]: length, command_id = struct.unpack("!2I", message.body[:8]) command = None try: command = Command.dicInt_Type[command_id](message.body, protocolInternal) except Exception as e: logging.error( "build command exception in protocolInternal transport %d: %s :%s", id(protocolInternal.transport), str(e), Util.asscii_string(message.body)) command = None command.internalMessage = message #threads.deferToThread(command.Run) command.Run() elif message.operation == OPER_REDIRECT: notify = RedirectNotify.CRedirectNotify(client_id=message.destId, addr=message.addition) notify.Notify()
def AddDataAndDecode(self,lock,data): print "data received in transport %d : %s (%s)" % (id(self.transport),Util.asscii_string(data),data) self.m_buffer+=data while len(self.m_buffer)>=Command.BaseCommand.CBaseCommand.HEAD_LEN : self.m_buffer,command,=self.Decode(self.m_buffer) if command == None: break #the maximum pending command is set to equal with connection count, one command for one connection by average if SBProtocol.countPendingCmd<Config.count_connection/100: threads.deferToThread(self.RunCommand,command) with self.factory.lockPendingCmd: SBProtocol.countPendingCmd=SBProtocol.countPendingCmd+1 else: try: cmd_resp=command.GetResp() cmd_resp.SetErrorCode(Command.BaseCommand.CS_SERVERBUSY) cmd_resp.Send() except: pass lock.release()
def AddDataAndDecode(self, lock, data): print "data received in transport %d : %s (%s)" % (id(self.transport), Util.asscii_string(data), data) self.m_buffer += data while len(self.m_buffer) >= Command.BaseCommand.CBaseCommand.HEAD_LEN: self.m_buffer, command, = self.Decode(self.m_buffer) if command == None: break # the maximum pending command is set to equal with connection count, one command for one connection by average if SBProtocol.countPendingCmd < Config.count_connection / 100: threads.deferToThread(self.RunCommand, command) with self.factory.lockPendingCmd: SBProtocol.countPendingCmd = SBProtocol.countPendingCmd + 1 else: try: cmd_resp = command.GetResp() cmd_resp.SetErrorCode(Command.BaseCommand.CS_SERVERBUSY) cmd_resp.Send() except: pass lock.release()
def GetDeviceForcely(session,device_code,model_name=None): device=session.query(SBDB_ORM.Device).filter_by(uni_code=device_code).with_lockmode('update').first() if device is None: model=GetDeviceModelByName(session,model_name) if model is None: return None device=SBDB_ORM.Device() device.uni_code=device_code device.device_model_id=model.id obj_dev_model=model for obj_dev_key in obj_dev_model.device_keys: obj_dev_key_code=SBDB_ORM.DeviceKeyCode() obj_dev_key_code.device_key_id=obj_dev_key.id #obj_dev_key_code.key_code=hex(string.atoi(dev_code,16)+obj_dev_key.seq)[2:] obj_dev_key_code.key_code=Util.hex8(string.atoi(device_code,16)+obj_dev_key.seq)[2:] device.device_key_codes.append(obj_dev_key_code) session.add(device) session.commit() return device
def Decode(self, data): ''' return a tuple: new data,command ''' length, command_id = struct.unpack("!2I", data[:8]) command = None if length <= len(data): command_data = data[:length] if (Command.dicInt_Type.has_key(command_id)): try: command = Command.dicInt_Type[command_id](command_data, self) except Exception, e: logging.error( "build command exception in transport %d: %s :%s", id(self.transport), str(e), Util.asscii_string(command_data)) command = None else: command = Command.BaseCommand.CMesscodeCommand( command_data, self) data = data[length:]
def Decode(self, data): ''' return a tuple: new data,command ''' if self.HeaderTagType < 0: # not decide if data[:4] == self.factory.SBMP_HEADERTAG: self.HeaderTagType = 1 else: self.HeaderTagType = 0 if self.HeaderTagType == 1: tag_position = data.find(self.factory.SBMP_HEADERTAG) if tag_position < 0: return (data, None) data = data[tag_position + 4:] # remove head tag length, command_id = struct.unpack("!2I", data[:8]) command = None if length <= len(data): command_data = data[:length] if command_id in Command.dicInt_Type: try: command = Command.dicInt_Type[command_id](command_data, self) except Exception as e: print(traceback.format_exc()) logging.error( "build command exception in transport %d: %s :%s", id(self.transport), str(e), Util.asscii_string(command_data)) command = None else: command = Command.BaseCommand.CMesscodeCommand( command_data, self) data = data[length:] else: if self.HeaderTagType == 1: # if command is not completed, add the head tag again data = self.factory.SBMP_HEADERTAG + data return (data, command)
def Run(self): with self.protocol.lockCmd: CBaseCommand.Run(self) with SBDB.session_scope() as session: respond = self.GetResp() email = self.body.get(BaseCommand.PN_EMAIL, None) account_id, = session.query(SBDB_ORM.Account.id).filter( SBDB_ORM.Account.email == email).first() if email is None: respond.SetErrorCode(BaseCommand.CS_NOTFOUNDEMAIL) elif account_id is None: respond.SetErrorCode(BaseCommand.CS_NOTFOUNDEMAIL) # elif 'dt_restore_require' in dir(self.protocol) and (datetime.datetime.now()-self.protocol.dt_restore_require).seconds<Config.second_restore_require: # respond.SetErrorCode(BaseCommand.CS_TRYLATER) else: try: content = open( os.path.join(Config.dir_local_static, "restore_confirm.html"), 'r').read() url = Util.GenRestoreURL(account_id) content = content.replace("{{url_restore}}", url) #emaillib.SendEmail("Honeywell Smart Home: reset password confirm", content, [self.protocol.account.email]) threading.Thread( target=emaillib.SendEmail, args=( "Honeywell Smart Home: reset password confirm", content, [email]), daemon=True).start() self.protocol.dt_restore_require = datetime.datetime.now( ) except SQLAlchemyError as e: respond.SetErrorCode(BaseCommand.CS_DBEXCEPTION) logging.error("transport %d:%s", id(self.protocol.transport), e) session.rollback() respond.Send()
def RunTransmitMessage(message): if message.operation in [OPER_REQUEST,OPER_RESPONSE]: length,command_id=struct.unpack("!2I",message.body[:8]) command=None try: command=Command.dicInt_Type[command_id](message.body,protocolInternal) except Exception,e: logging.error("build command exception in protocolInternal transport %d: %s :%s",id(protocolInternal.transport),str(e),Util.asscii_string(message.body)) command=None command.internalMessage=message #threads.deferToThread(command.Run) command.Run()
def PublishMessageCallback(lock, data): socketPublish.send_multipart(data) print(("data sent of InternalMessage %s:%s:%s (%s%s%s)" % (data[0], data[1], data[2], Util.asscii_string(data[0]), Util.asscii_string(data[1]), Util.asscii_string(data[2])))) lock.release()
def ProcessMessage(head,from_filter,body): global countPendingCmd,lockPendingCmd print "data received of InternalMessage %s:%s:%s (%s%s%s)" % (head,from_filter,body,Util.asscii_string(head),Util.asscii_string(from_filter),Util.asscii_string(body)) message=CInternalMessage(head,from_filter,body) typeMessage=message.destType[0] if dictProcessor.has_key(typeMessage): dictProcessor[typeMessage](message) with lockPendingCmd: countPendingCmd=countPendingCmd-1
import sys, os reload(sys) sys.setdefaultencoding('utf8') from Utils import Util if Util.isWindows(): activate_this = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir, 'venv/Scripts/activate_this.py') execfile(activate_this, dict(__file__=activate_this)) else: #linux activate_this = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir, 'venv/bin/activate_this.py') execfile(activate_this, dict(__file__=activate_this))
def PublishMessageCallback(lock,data): socketPublish.send_multipart(data) print "data sent of InternalMessage %s:%s:%s (%s%s%s)" % (data[0],data[1],data[2],Util.asscii_string(data[0]),Util.asscii_string(data[1]),Util.asscii_string(data[2])) lock.release()
def Decode(self,data): ''' return a tuple: new data,command ''' length,command_id=struct.unpack("!2I",data[:8]) command=None if length<=len(data): command_data=data[:length] if(Command.dicInt_Type.has_key(command_id)) : try: command=Command.dicInt_Type[command_id](command_data,self) except Exception,e: logging.error("build command exception in transport %d: %s :%s",id(self.transport),str(e),Util.asscii_string(command_data)) command=None else: command=Command.BaseCommand.CMesscodeCommand(command_data,self) data=data[length:]
def view_institution(): institution_id = request.args.get('id') q = request.args.get('q') if q is not None: return redirect(url_for('view_institutions', page=1, q=q)) form = InstitutionForm(request.form) form.area_id.choices = logic.g_choices_area form.feature_ids.choices = logic.g_choices_feature form.agespan_id.choices = logic.g_choices_agespan form.feetype_id.choices = logic.g_choices_feetype form.timeopen.data = datetime.time(8,30) form.timeclose.data = datetime.time(22,00) # form.message = form.data if request.method == 'POST' and form.validate(): if form.id.data: institution = orm.Institution.query.get(int(form.id.data)) institution.name = form.name.data institution.agespan_id = form.agespan_id.data institution.area_id = form.area_id.data institution.address = form.address.data institution.location = form.location.data institution.website = form.website.data institution.telephone = form.telephone.data institution.feedesc = form.feedesc.data institution.timeopen = form.timeopen.data institution.timeclose = form.timeclose.data institution.feetype_id = form.feetype_id.data institution.longitude = form.longitude.data institution.latitude = form.latitude.data orm.db.session.commit() else: institution = orm.Institution(form.name.data, form.agespan_id.data, form.area_id.data, form.address.data, form.location.data, form.website.data, form.telephone.data, form.feedesc.data, form.timeopen.data, form.timeclose.data, form.feetype_id.data, form.longitude.data, form.latitude.data, None) orm.db.session.add(institution) orm.db.session.commit() form.id.data = institution.id logic.SetInstitutionFeatures(int(form.id.data),form.feature_ids.data) if request.form.has_key('upload'): file = request.files['image'] if file : file_server = str(uuid.uuid1())+Util.file_extension(file.filename) pathfile_server = os.path.join(UPLOAD_PATH, file_server) file.save(pathfile_server) if os.stat(pathfile_server).st_size <1*1024*1024: institutionimage = orm.Institutionimage(institution.id,file_server) orm.db.session.merge(institutionimage) orm.db.session.commit() else: os.remove(pathfile_server) else: return redirect(url_for('view_institution')) elif request.method =='GET' and institution_id: form = logic.GetInstitutionFormById(institution_id) logic.LoadBasePageInfo('修改培训机构','输入并确定',form) else: logic.LoadBasePageInfo('新建培训机构','输入并确定',form) if form.id.data: institution = orm.Institution.query.get(int(form.id.data)) form.institution = institution if form.institution: form.institutionimages = form.institution.institutionimages return render_template('view_institution.html',form = form)
def Regist(request_body): """ Add a new record into data table 'account'. If the username has been exist, raise exception Otherwize, return the inserted account. """ account = orm.Account(ProtocolItem.VALUE_LANGUAGE_DEFAULT, request_body[ProtocolItem.USERNAME], Util.hash_password(request_body[ProtocolItem.PASSWORD]), request_body[ProtocolItem.EMAIL], request_body[ProtocolItem.MOBILE]) orm.db.session.add(account) orm.db.session.commit() return account
def Run(self): with self.protocol.lockCmd: CBaseCommand.Run(self) if 'role' in dir(self.protocol): self.protocol.releaseFromDict() role=self.body[BaseCommand.PN_TERMINALTYPE] resp=self.GetResp() resp.body[BaseCommand.PN_RESULT]=BaseCommand.PV_E_OK if cmp(role,BaseCommand.PV_ROLE_SUPERBOX)==0: sb_code=self.body[BaseCommand.PN_SB_CODE] self.protocol.superbox_id=SBDB.GetSuperboxIdForcely(sb_code) self.protocol.role=role with self.protocol.factory.lockDict: self.protocol.factory.dictSuperbox[self.protocol.superbox_id]=self.protocol #logging.info("transport %d: superbox %s login pass",id(self.protocol.transport),sb_code) threads.deferToThread(SBDB.UpdateAuthTimeSuperbox,self.protocol.superbox_id) elif cmp(role,BaseCommand.PV_ROLE_HUMAN)==0: #self.protocol.account=SBDB.GetAccount(self.body[BaseCommand.PN_USERNAME], self.body[BaseCommand.PN_PASSWORD]) with SBDB.session_scope() as session : account=SBDB.GetAccount(session,self.body[BaseCommand.PN_USERNAME]) if account is not None and not Util.check_password(self.body[BaseCommand.PN_PASSWORD], account.password) : account=None if account is None: resp.body[BaseCommand.PN_RESULT]=BaseCommand.PV_E_USERPASS resp.body[BaseCommand.PN_ERRORSTRING]="user/password mismatch" resp.SetErrorCode(BaseCommand.CS_LOGINFAIL) else: self.protocol.account_id=account.id self.protocol.role=role self.protocol.client_id=-1 self.protocol.rcv_alarm=self.body.get(BaseCommand.PN_RCVALARM,"False") listApartment=[] for apartment in account.apartments: elementApartment={} elementApartment[BaseCommand.PN_ID]=apartment.id listApartment.append(elementApartment) resp.body[BaseCommand.PN_APARTMENTS]=listApartment dictAccount=self.protocol.factory.dictAccounts for superboxId in SBDB.GetSuperboxIDsByAccountId(self.protocol.account_id): with self.protocol.factory.lockDict: if dictAccount.has_key(superboxId): dictAccount[superboxId].append(self.protocol) else: dictAccount[superboxId]=[self.protocol,] #set client information os=self.body.get(BaseCommand.PN_OS,BaseCommand.PV_OS_IOS) token=self.body.get(BaseCommand.PN_TOKEN) last_token=self.body.get(BaseCommand.PN_LASTTOKEN) balance=self.body.get(BaseCommand.PN_BALANCE) #terminal_code=self.body.get(BaseCommand.PN_TERMINALCODE,datetime.datetime.now().strftime("%Y%m%d%H%M%S")+str(random.uniform(0,4000))) if token=='' or token is None: terminal_code=self.body.get(BaseCommand.PN_TERMINALCODE,datetime.datetime.now().strftime("%Y%m%d%H%M%S")+str(random.uniform(0,4000))) else: terminal_code=self.body.get(BaseCommand.PN_TERMINALCODE,token) try: ###for temply use if token is not None: session.query(SBDB_ORM.Client).filter(and_(SBDB_ORM.Client.account_id!=self.protocol.account_id,SBDB_ORM.Client.device_token==token.strip())).delete() ###------------- if last_token is not None and token <> last_token: #session.query(SBDB_ORM.Client).filter(and_(SBDB_ORM.Client.account_id==self.protocol.account_id,SBDB_ORM.Client.device_token==last_token.strip())).delete() session.query(SBDB_ORM.Client).filter(SBDB_ORM.Client.device_token==last_token.strip()).delete() client=session.query(SBDB_ORM.Client).filter(SBDB_ORM.Client.terminal_code==terminal_code.strip()).first() if client is None: if token is not None: session.query(SBDB_ORM.Client).filter(SBDB_ORM.Client.device_token==token.strip()).delete() client=SBDB_ORM.Client() client.device_token=token client.enable_alarm=True client.os=os session.add(client) client.account_id=self.protocol.account_id client.terminal_code=terminal_code client.dt_auth=client.dt_active=datetime.datetime.now() client.server_id=InternalMessage.MyServerID session.commit() self.protocol.client_id=client.id #logging.info("transport %d: user %s login pass ",id(self.protocol.transport),self.body[BaseCommand.PN_USERNAME]) if balance is None: balance='n' threads.deferToThread(SBDB.UpdateAuthTimeHuman,client.id,balance,id(self.protocol.transport)) except SQLAlchemyError,e: resp.SetErrorCode(BaseCommand.CS_DBEXCEPTION) logging.error("transport %d:%s",id(self.protocol.transport),e) session.rollback() else:
def Send_Real(self): reactor.callFromThread(self.protocol.transport.write,self.data) print "data sent in transport %d : %s (%s)" % (id(self.protocol.transport),Util.asscii_string(self.data),self.data)
def projectCompile(projectInfo): Util.run(projectInfo.mPath + "//gradlew assembleDebug")
def setup(projectInfo): if (os.path.exists(projectInfo.mPath)): Util.run("rmdir /s /q " + projectInfo.mPath) createProject(projectInfo)
def verify_password(self, password): return self.passwd == password or Util.check_password(password, self.passwd)
import sys,os reload(sys) sys.setdefaultencoding('utf8') from Utils import Util if Util.isWindows(): activate_this = os.path.join(os.path.dirname(os.path.abspath(__file__)),os.path.pardir,'venv/Scripts/activate_this.py') execfile(activate_this, dict(__file__=activate_this)) else: #linux activate_this = os.path.join(os.path.dirname(os.path.abspath(__file__)),os.path.pardir,'venv/bin/activate_this.py') execfile(activate_this, dict(__file__=activate_this))
''' Created on 2013-7-31 @author: Changlong ''' from Utils import Util if Util.isWindows(): from twisted.internet import iocpreactor iocpreactor.install() elif Util.isMac(): from twisted.internet import kqreactor kqreactor.install() else: from twisted.internet import epollreactor epollreactor.install() import SBPS.ProtocolReactor as ProtocolReactor import logging logging.basicConfig(filename='example.log', level=logging.INFO, format="%(asctime)s-%(name)s-%(levelname)s-%(message)s") if __name__ == '__main__': logging.info("Relayer Server starting...") print("Relayer Server starting...") ProtocolReactor.Run() # run until stop
def Run(self): logging.error("MesscodeCommand in transport %d : %s",id(self.protocol.transport),Util.asscii_string(self.data))
def view_school(): school_id = request.args.get('id') q = request.args.get('q') if q is not None: return redirect(url_for('view_schools', page=1, q=q)) form = SchoolForm(request.form) form.area_id.choices = logic.g_choices_area form.schooltype_id.choices = logic.g_choices_schooltype form.feature_ids.choices = logic.g_choices_feature # form.message = form.data if request.method == 'POST' and form.validate(): print "longitude:",form.longitude.data if form.id.data: school = orm.School.query.get(int(form.id.data)) school.name = form.name.data school.area_id = form.area_id.data school.teachdesc = form.teachdesc.data school.address = form.address.data school.schooltype_id = form.schooltype_id.data school.website = form.website.data school.distinguish = form.distinguish.data school.leisure = form.leisure.data school.threashold = form.threashold.data school.partner = form.partner.data school.artsource = form.artsource.data school.feedesc = form.feedesc.data school.longitude = form.longitude.data school.latitude = form.latitude.data orm.db.session.commit() else: school = orm.School(form.name.data, form.area_id.data, form.teachdesc.data, form.address.data, form.schooltype_id.data, form.website.data, form.distinguish.data, form.leisure.data, form.threashold.data, form.partner.data, form.artsource.data, form.feedesc.data, form.longitude.data, form.latitude.data) orm.db.session.add(school) orm.db.session.commit() form.id.data = school.id logic.SetSchoolFeatures(int(form.id.data),form.feature_ids.data) if request.form.has_key('upload'): file = request.files['image'] if file : file_server = str(uuid.uuid1())+Util.file_extension(file.filename) pathfile_server = os.path.join(UPLOAD_PATH, file_server) file.save(pathfile_server) if os.stat(pathfile_server).st_size <1*1024*1024: schoolimage = orm.Schoolimage(school.id,file_server) orm.db.session.merge(schoolimage) orm.db.session.commit() else: os.remove(pathfile_server) else: return redirect(url_for('view_school')) elif request.method =='GET' and school_id: form = logic.GetSchoolFormById(school_id) logic.LoadBasePageInfo('修改学校','输入并确定',form) else: logic.LoadBasePageInfo('新建学校','输入并确定',form) if form.id.data: school = orm.School.query.get(int(form.id.data)) form.school = school if form.school: form.schoolimages = form.school.schoolimages return render_template('view_school.html',form = form)