def hmac_calc(self): buff = Util.getBuff(self.txthmac_input.toPlainText(),self.chkhmac_ishex.isChecked()) if len(buff) <= 0: self.appendLog("hmac input未输入正确数据") return buff_key=Util.getBuff(self.txthmac_key.text(),self.chkhmac_key_ishex.isChecked()) if self.chkhmac_key_ishex.isChecked(): self.txthmac_key.setText(Util.b2hexSpace(buff_key)) cmbidx = self.cmbhmac.currentIndex() if cmbidx == 1: m = hashlib.sha1 elif cmbidx == 2: m = hashlib.sha224 elif cmbidx == 3: m = hashlib.sha256 elif cmbidx == 4: m = hashlib.sha512 else: m = hashlib.md5 try: h = hmac.new(buff_key,buff,digestmod=m) self.txthmac_output.setPlainText(h.hexdigest()) except Exception as ex: self.appendLog(str(ex)) self.txthmac_output.setPlainText("")
def run(self): while self._running: if GlobalBean.midiBySelected == None: print("未选中midi,无法演奏") break pattern = midi.read_midifile(GlobalBean.midiBySelected) seq = Util.resloveMidiEvent(pattern) tickPer = 1 # 单位微秒 for event in seq: if GlobalBean.midiPlayStatus == False: break if type(event) == midi.TimeSignatureEvent: tickPer = (1/4)/(1/event.denominator)*pattern.resolution elif type(event) == midi.SetTempoEvent: tickPer = (60000000 / int(event.bpm)) / tickPer elif type(event) == midi.NoteOnEvent and event.tick != 0: time.sleep((tickPer * event.tick) / 1000000) elif type(event) == midi.NoteOffEvent: # print(event) temp = PITCH_KEY_MAP.get(midi.NOTE_VALUE_MAP_FLAT[event.pitch], -1); # print(midi.NOTE_VALUE_MAP_FLAT[event.pitch]) if temp == -1: pass if type(temp) == list: Util.makeupKey(GlobalBean.hwnd, temp[0], temp[1]) else: Util.simpleKey(GlobalBean.hwnd, temp) if event.tick != 0: # print((tickPer * event.tick) / 1000000) time.sleep((tickPer * event.tick) / 1000000 - 0.1 if (tickPer * event.tick) / 1000000 - 0.1 > 0 else 0)
def leave_one_out_error(self): correct = 0 numPoints = len(self.full_set) for i, x in enumerate(self.X): print("LOO Progress:", i + 1, "/", numPoints) known_label = self.labels[i] beta = 0 if i == 0: # Begining beta = self.__optimize__(self.full_set[1:], self.labels[1:]) elif i == numPoints - 1: # End beta = self.__optimize__(self.full_set[:numPoints - 1], self.labels[:numPoints - 1]) else: # Middle beta = self.__optimize__( (Util.combineSets(self.full_set[:i], self.full_set[i + 1:])), Util.combineSets(self.labels[:i], self.labels[i + 1:])) if self.classify(x, beta) == known_label: correct += 1 incorrect = numPoints - correct return 100 * (incorrect / numPoints)
def zlib_calc(self): inputdata=Util.getBuff(self.txtzlib_input.toPlainText(),self.chkzlib_ishex.isChecked()) try: res=Util.zlib_compress(inputdata) self.txtzlib_output.setPlainText(res) except Exception as ex: self.appendLog(str(ex)) self.txtzlib_output.setPlainText("")
def zlib_calc_unzlib(self): inputdata =Util.getBuff(self.txtzlib_input.toPlainText(),True) try: res = Util.zlib_decompress(inputdata) self.txtzlib_output.setPlainText(res) except Exception as ex: self.appendLog(str(ex)) self.txtzlib_output.setPlainText("")
def binformat_calc_str(self): inputdata = self.txtbinformat_input.toPlainText() try: buff = Util.StrToHexSplit(inputdata) res = Util.hex2str(buff) self.txtbinformat_output.setPlainText(res) except Exception as ex: self.appendLog("转换异常:" + str(ex)) self.txtbinformat_output.setPlainText("")
def binformat_calc_bytes(self): inputdata=self.txtbinformat_input.toPlainText() try: res = Util.str2hex(inputdata) self.txtbinformat_output.setPlainText(Util.b2hexSpace(res)) cnt = len(res) self.lbbinformat_cnt.setText("<span style=' color:#ff0000;'>[{}]</span>".format(cnt)) except Exception as ex: self.appendLog("转换异常:" + str(ex)) self.txtbinformat_output.setPlainText("")
def attack(self, scene): """ Enemy attack player """ from Entity.Arrow import Arrow from common.events import MsgArrowBorn if self.is_dead(): return if self.is_stunning(): return if self.attack_player is None: # attack no one return if self.attack_player.is_dead(): return if Util.vector3_distance( self.position, self.attack_position ) > self.configuration['attack_stop_distance']: # not close enough return now = time.time() if self.last_attack_time and now - self.last_attack_time < self.configuration[ 'time_between_attack']: return self.last_attack_time = now # Attack if self.configuration['attack_mode'] == 0: # near attack self.attack_player.get_hurt(self.configuration['damage'], scene) else: # remote attack # generate an arrow of atype -1 aid = scene.generate_arrow_id() pos = self.position apos = self.attack_player.position direct = Util.vector3_normalize( [apos[0] - pos[0], 0, apos[2] - pos[2]]) # born in front of body born_pos = Util.vector3_add( Util.vector3_inner_product(direct, self.configuration['body_radius']), pos) arrow = Arrow( aid, -1, [born_pos[0], self.configuration['height'] / 2, born_pos[2]], direct, None, scene.arrow_conf['enemy_arrow_prefab']) scene.arrows[aid] = arrow # broadcast message msg = MsgArrowBorn(aid, -1, born_pos[0], self.configuration['height'] / 2, born_pos[2], direct[0], direct[1], direct[2]) scene.broadcast(msg)
def varint_calc_decode(self): inputdata = self.txtvarint_input.toPlainText() if len(inputdata)<=0: self.appendLog("varint input为空") return try: if " " not in inputdata: inputdata=Util.ByteToHexStr(inputdata) buff = Util.StrToHexSplit(inputdata) res = Util.varint_decode(buff) self.txtvarint_output.setPlainText(str(res)) except Exception as ex: self.appendLog(str(ex)) self.txtvarint_output.setPlainText("")
def register(request): """ 注册逻辑 """ if not request.method == 'POST': return Util.json_response(False, '用户注册仅接受POST请求') username = request.POST.get('username') password = request.POST.get('password') password_confirm = request.POST.get('password_confirm') email = request.POST.get('email') if not username: return Util.json_response(False, '用户名不能为空') if not password: return Util.json_response(False, '密码不能为空') if not password_confirm: return Util.json_response(False, '确认密码不能为空') # if not email: # return Util.json_response(False, '邮箱不能为空') if not Util.equals(password, password_confirm): return Util.json_response(False, '密码也确认密码不一致') try: user = User.objects.create_user(username=username, email=email, password=password) except Exception as e: return Util.json_response(False, "用户名"+username+"已经注册了") user.is_active = True user.save return Util.json_response(True)
def plotHyperplane(self): w = self.optimals['w'] b = self.optimals['b'] # Hyperplane x_points = numpy.linspace(int(min(self.fullSetX)), int(max(self.fullSetX)), len(self.fullSet)) y_points =[] for x in x_points: y_points.append(self.predict(x,w,b)) plt.plot(x_points,y_points, color='purple', label='Classifier') # Soft Margin self.margin = (1/Util.norm(w)) # Plot Margins (Offset Based) soft_upper = [] soft_lower = [] for wNum, wVal in enumerate(w): offset_distance = (1/wVal)/2 upper_bounds = [] lower_bounds = [] for i,x in enumerate(x_points): if wNum == 0: upper_bounds.append(x + offset_distance) lower_bounds.append(x - offset_distance) elif wNum == 1: upper_bounds.append(y_points[i] + offset_distance) lower_bounds.append(y_points[i] - offset_distance) soft_upper.append(upper_bounds) soft_lower.append(lower_bounds) plt.plot(soft_upper[0],soft_upper[1], linestyle=':', color='grey', label='Margin') plt.plot(soft_lower[0],soft_lower[1], linestyle=':', color='grey')
def __init__(self, classA=False, classB=False, *, C=1, plotNow=False, printReport=False, brute_loo=True, brute_mute=False): # Initialize Variables and Parameters self.optimized = False self.plotPrepared = False self.constantC = C self.supportVectors = [] self.margin = 0 self.printReport = printReport self.brute = brute_loo self.brute_mute = False # Generate Random Data or Accept Provided Sets if classA and classB: self.classA = classA self.classB = classB self.fullSet = Util.combineSets(self.classA, self.classB) self.fullSetX, self.fullSetY = self.fullSet.T else: self.classA, self.classB, self.fullSetX, self.fullSetY, self.fullSet = RandomData.random_data() self.labels = RandomData.linear_labels() # Dimension of Class Data self.dimensions = len(self.classA[len(self.classA)-1]) # Optimize and Plot or Report if Needed if plotNow or printReport: self.optimize() if plotNow: print("Graphing SVM, Report Will Generate After Graph Is Closed If Requested.") self.plot() if printReport: self.preparePlot() print(self)
def spawn_one_enemy(self): """ Spawn one enemy with random type and random position """ import random from common import Util if self.last_group_end_time is not None and \ time.time() - self.last_group_end_time < self.scene_conf['time_between_enemy_group']: return if self.already_spawn_count >= self.scene_conf['enemy_group_num'][self.spawn_group_id]: return self.already_spawn_count += 1 # random prefab enemy_prefabs = self.enemy_conf['enemy_prefab'] enemy_prefab_idx = Util.get_random_index_with_distribution(self.scene_conf['enemy_spawn_distribution']) # random spawn transform spawn_transforms = self.scene_conf['enemy_spawn_transforms'] spawn_transform_idx = random.randint(0, len(spawn_transforms) - 1) spawn_transform = deepcopy(spawn_transforms[spawn_transform_idx]) # create enemy ep = enemy_prefabs[enemy_prefab_idx] eid = self.generate_enemy_id() enemy = Enemy(eid, spawn_transform[0:3], spawn_transform[3:6], deepcopy(self.scene_conf['target_position']), ep) self.enemies[eid] = enemy # send spawn message spawn_msg = enemy.generate_spawn_msg() self.broadcast(spawn_msg)
def hexdump_calc(self): inputdata=self.txthexdump_input.toPlainText() try: if " " in inputdata: res=Util.HexdumpReplaceLeftRight(inputdata) self.txthexdump_output.setPlainText(res) else: res=Util.ByteToHexStr(inputdata) self.txthexdump_output.setPlainText(res) cmbidx=self.cmbhexdump.currentIndex() if cmbidx>=1 and cmbidx<=2: res=Util.hexSplit(self.txthexdump_output.toPlainText(),cmbidx) self.txthexdump_output.setPlainText(res) except Exception as ex: self.appendLog("转换异常:" + str(ex)) self.txthexdump_output.setPlainText("")
def getAndCompareAll(): # 从传感器中获取所有传感器数据 plantData = PlantData() for sensor in sensorList: sensor.read(plantData) if not RaspberryConfig._PLANTTYPE: print '该次检测无植物类型设定,不进行比较' return plantData # 持久化植物生长数据 DBUtil.addPlantData(plantData) # 与植物生长模型比较 # todo 从数据库中获取植物生长模型,目前根据植物种类获取 plantModel = getPlantModelByPlantType() compareResult = DataUtil.compare(plantData, plantModel) # 处理比较后的结果 doSthForCompareResult[compareResult.result_code]() detail = '' for key in compareResult.result: result = compareResult.result[key] detail += key + result.__str__() + '\r\n' result = '{} :本次读取植物环境数据为:{},结果为{}\r\n具体信息:{}'.format( Util.getCurrentTime(), plantData.__str__(), ResultEnum[compareResult.result_code], detail) print(result) print('-----------------------------') return result
def varint_calc_encode(self): inputdata=self.txtvarint_input.toPlainText() try: if "0x" in inputdata: inputdata=inputdata.replace("0x","") inputNum=int(inputdata,16) res = Util.varint_encode(inputNum) self.txtvarint_output.setPlainText(Util.b2hexSpace(res)) return else: inputNum = int(inputdata, 10) res = Util.varint_encode(inputNum) self.txtvarint_output.setPlainText(Util.b2hexSpace(res)) except Exception as ex: self.appendLog(str(ex)) self.txtvarint_output.setPlainText("")
def rc2_calc_decrypt(self): inputdata = Util.getBuff(self.txtrc2_input.toPlainText(), self.chkrc2_ishex.isChecked()) if len(inputdata) <= 0: self.appendLog("rc2 input为空") return try: buff_key = Util.getBuff(self.txtrc2_key.text(), True) buff_iv = Util.getBuff(self.txtrc2_iv.text(), self.chkrc2_iv_ishex.isChecked()) if self.cmbrc2_mode.currentIndex() == 1: res = CryptoUtil.rc2_ebc_decrypt(buff_key, inputdata) else: res = CryptoUtil.rc2_cbc_decrypt(buff_key, buff_iv, inputdata) self.txtrc2_output.setPlainText(res) except Exception as ex: self.appendLog(str(ex)) self.txtrc2_output.setPlainText("")
def login(request): """ 登录逻辑 """ if not request.method == 'POST': return Util.json_response(False, '用户登录仅接受POST请求') username = request.POST.get('username') password = request.POST.get('password') if not username: return Util.json_response(False, '用户名不能为空') if not password: return Util.json_response(False, '密码不能为空') user = auth.authenticate(username=username, password=password) if not user: return Util.json_response(False, '用户名或密码不正确') auth.login(request, user) return Util.json_response(True)
def capturePic(filename=''): # 生成文件名(planttype+timestamp.jpg) if not filename: prifex = Util.getCurrentTime('%Y%m%d%H%M%S_') filename = prifex + RaspberryConfig._PLANTTYPE + PIC_SUFFIX piccamera.capture(filepath + filename) return filename
def asm_calc_disasm(self): inputdata = self.txtasm_input.toPlainText() try: buff=Util.StrToHexSplit(inputdata) res=AsmUtil.disasm(self.cmbasm.currentIndex(),buff) self.txtasm_output.setPlainText(res) except Exception as ex: self.appendLog("解析异常.请检查数据和模式是否正确."+str(ex)) self.txtasm_output.setPlainText("")
def recordVideo(time=10, filename=''): if not filename: prifex = Util.getCurrentTime('%Y%m%d%H%M%S_') filename = prifex + RaspberryConfig._PLANTTYPE + VIDEO_SUFFIX piccamera.resolution = (640, 480) piccamera.start_recording(filename) piccamera.wait_recording(time) piccamera.stop_recording()
def base64_calc_decode(self): try: base64_input = self.txtbase64_input.toPlainText() res = Util.newBase64(self.txtbase64_key.text(), base64_input, False) self.txtbase64_output.setPlainText(res) if self.chkHexOutput.isChecked(): self.hex_toggled() except Exception as ex: self.appendLog(str(ex)) self.txtbase64_output.setPlainText("")
def adler32_calc(self): buff = Util.getBuff(self.txtadler32_input.toPlainText(),self.chkadler32_ishex.isChecked()) if len(buff) <= 0: self.appendLog("adler32 input未输入正确数据") return try: res = zlib.adler32(buff) self.txtadler32_output.setPlainText(str(res)) except Exception as ex: self.appendLog(str(ex)) self.txtadler32_output.setPlainText("")
def check_escape(self, escape_range): """ Is enemy run away successfully """ if self.is_dead(): return False # check escape if Util.vector3_distance(self.position, self.target_position) <= escape_range: return True return False
def hit_me(self, pos): """ Check arrow hit body, assume arrow always before enemy, FIX ME !!! """ if pos[1] > self.configuration['height'] or pos[1] < 0: # print "too high: ", self.position, self.configuration['height'] return False dis = Util.vector2_distance([pos[0], pos[2]], [self.position[0], self.position[2]]) if dis <= self.configuration['body_radius']: return True # print "dis: ", dis, self.configuration['body_radius'] return False
def md5_calc(self): buff =Util.getBuff(self.txtmd5_input.toPlainText(),self.chkmd5_ishex.isChecked()) if len(buff) <= 0: self.appendLog("md5 input未输入正确数据") return try: m= hashlib.md5() m.update(buff) res = m.hexdigest() self.txtmd5_output.setPlainText(res) except Exception as ex: self.appendLog(str(ex)) self.txtmd5_output.setPlainText("")
def hit_me(self, pos): """ Check arrow hit body, assume arrow always before player, FIX ME !!! """ from common import Util if pos[1] > self.configuration['height'] or pos[1] < 0: # print "too high: ", self.position, self.configuration['height'] return False dis = Util.vector2_distance([pos[0], pos[2]], [self.position[0], self.position[2]]) if dis <= self.configuration['body_radius'] / 2: # Enemy too powerful, FIX ME !!! return True # print "dis: ", dis, self.configuration['body_radius'] return False
def check_move_distance_legal(self, new_pos): """ Max distance estimation, not accurate enough """ if self.is_dead(): return False from common import Util now = time.time() max_dis = (now - self.last_move_time) * self.configuration['move_speed'] + self.configuration[ 'move_delay_error'] dis = Util.vector3_distance(self.position, new_pos) if dis > max_dis: return False return True
def update_position(self, players, scene_grid): """ Update enemy position base on players and scene_grid """ if self.is_dead(): return if self.is_stunning(): return if self.check_slow(): return close_player = None min_dis = None for player in players: if player is None: continue if player.is_dead(): continue dis = Util.vector3_distance(player.position, self.position) # print player.position if dis < self.configuration['visible_range']: if not close_player or dis < min_dis: min_dis = dis close_player = player if close_player: # find player self.attack_player = close_player # Assume visible range > attack_stop_distance if min_dis < self.configuration[ 'attack_stop_distance']: # no need to move self.is_position_update = False self.attack_position = [x for x in player.position] return else: # need to move self.find_next_position(close_player, scene_grid) else: # go to target position if self.attack_position or self.path is None: # enemy attack player recently, need to find a new path self.attack_position = None self.attack_player = None new_path = PathFinding.run(self.position, self.target_position, scene_grid) if new_path: # assign when we find a path self.path = new_path else: # should log here print "Find path error" # update position self.update_position_from_path()
def find_next_position(self, player, scene_grid): """ Find next position, may need to find a new path. """ if not (self.attack_position and Util.vector3_equal(self.attack_position, player.position)): self.attack_position = [x for x in player.position] new_path = PathFinding.run(self.position, self.attack_position, scene_grid) if new_path: # assign when we find a path self.path = new_path else: # should log here print "Find path error" # update position self.update_position_from_path()
def save_file(self): output=self.txtbase64_output.toPlainText() if len(output)<=2: self.appendLog("错误的输出结果.无法保存") return savefile= QFileDialog.getSaveFileName()[0] if len(savefile)<=0: self.appendLog("取消选择文件") return try: res=Util.StrToHexSplit(output) #开始保存 with open(savefile,"wb") as myfile: myfile.write(res) self.appendLog("保存成功到:"+savefile) except Exception as ex: self.appendLog(str(ex))
def select_file(self): filename= QFileDialog.getOpenFileName()[0] if len(filename)<=0: return try: self.txtbase64file.setText(filename) with open(filename,"rb") as myfile: mydata= myfile.read() res = Util.newBase64(self.txtbase64_key.text(),mydata, self.rdobase64_encode.isChecked()) if self.chkIsHex.isChecked(): outres = "" for mych in res: outres += "%02x " % mych res = outres self.txtbase64_output.setPlainText(res) except Exception as ex: self.appendLog(str(ex))
def process_exception(self, request, exception): BR = "<br/>" error = "" user = request.user if not user: user = "******" remote_addr = request.META.get('REMOTE_ADDR') remote_addr_ip, remote_addr_num, remote_addr_ars = Util.getip_chinaz(remote_addr) uri = request.META.get('PATH_INFO', '') is_ajax = request.is_ajax() user_agent_str = request.META.get('HTTP_USER_AGENT', '') print('user_agent_str: ', user_agent_str) user_agent_os, user_agent_browser = useragent.check_user_agent(user_agent_str) method = request.method params = {} if method == 'POST': for k, v in request.POST.items(): params[k] = v if method == "GET": for k, v in request.GET.items(): params[k] = v error += "发生时间:" + str(datetime.now()) + BR error += "客户端地址:" + remote_addr_ip + "   " + remote_addr_ars + BR error += "请求URI:" + uri + BR error += "请求方式:" + method + BR error += "是否为AJAX请求:" + str(is_ajax) + BR error += "请求BODY:" + str(params) + BR error += "User-Agent:" + user_agent_str + BR error += "操作系统:" + user_agent_os.name + BR error += "浏览器:" + user_agent_browser.name + BR error += "登录用户:" + str(user) + BR error += "异常类型:" + exception.__class__.__name__ + BR error += "异常信息:" + str(exception) + BR error += "异常追踪信息:" + BR + BR.join(traceback.format_exception(*sys.exc_info())) + BR emailUtil.send_mail_text(['*****@*****.**'], 'Pystudease Error Report', error, sub_type='html') return HttpResponse("出现异常:" + BR + error)
def logout(request): """ 退出登录 """ auth.logout(request) return Util.json_response(True)