def main(settings: dict, tags: str, discard_tags: str): global log_file_name global folder_path global log_lock global exist_files_dict end = threading.Event() data = queue.Queue(80) log_lock = threading.Lock() lock = threading.Condition() log_file_name = 'log_{}.txt'.format(time.strftime('%Y%m%d-%H%M%S')) if settings['tag_search']: folder_path = settings['folder_path'] + '/' + tags elif settings['date_separate']: folder_path = settings['folder_path'] + '/' + time.strftime('%Y%m%d') log_file_name = 'log_{}.txt'.format(time.strftime('%H%M%S')) else: folder_path = settings['folder_path'] Function.create_folder(folder_path) # 遍历文件存放目录,获取所有已有文件名。不检索子目录。 exist_files_dict = Function.existing(folder_path) # 将排除tags转换为列表 discard_tags = discard_tags.strip(' ').split(' ') # 将易读的空格分隔转换为加号分隔,urllib无法处理空格,会报错 tags = tags.replace(' ', '+') # 建立线程 # 只启用了单线程,低内存设备不建议启用多线程 get_data(lock, data, end, settings, tags, discard_tags) parallel_task(lock, data, end, settings).join()
def train(self): #训练函数:训练数据集 dm, dn = np.shape(self.dataMat) grid = self.init_grid() self.w = np.random.random(size=(self.M * self.N, dn)) #初始化权重向量 if self.steps < 5 * dm: self.steps = 5 * dm for i in range(self.steps): #主循环:训练权重向量w lrate, r = self.ratecacl(i) #求出本次迭代的学习率和聚类半径 self.lratelist.append(lrate) self.rlist.append(r) #1 随机取出一个样本 k = np.random.randint(0, dm) mySample = self.dataMat[k, :] #2 计算出竞争层的最优节点 minIndx = (fun.distM(np.mat(mySample), np.mat(self.w))).argmin() #3 计算邻域 d1 = int(np.floor(minIndx / self.M)) d2 = np.mod(minIndx, self.N) #求出最优节点对应的类别向量 disMat = fun.distM(np.mat([d1, d2]), grid) nodelindx = (disMat < r).nonzero()[1] for j in range(self.M * self.N): if nodelindx.__contains__(j): self.w[j, :] += lrate * (mySample[0] - self.w[j, :]) #主循环结束 #为dataMat的每条数据判定类别 self.classLabel = [] for i in range(dm): kind_i = (fun.distM(np.mat(self.dataMat[i, :]), self.w)).argmin() self.classLabel.append(kind_i) self.classLabel = np.mat(self.classLabel)
def query(ip, query): pk_id = func.random_pktid(const.LENGTH_PKTID) port = func.format_string(const.PORT, const.LENGTH_PORT, "0") step = func.format_string(const.TTL, const.LENGTH_TTL, "0") query = func.format_string(query, const.LENGTH_QUERY, " ") pack = bytes(const.CODE_QUERY, "ascii") + bytes(pk_id, "ascii") + bytes(ip, "ascii") + bytes(port, "ascii") + bytes(step, "ascii") + bytes(query, "ascii") return pack
def logout(ip55, t_host, sessionID): tfunc.warning("\n>>> LOGOUT") result = -1 pk = pack.request_logout(sessionID) s = sFunc.create_socket_client(func.roll_the_dice(t_host[0]), t_host[1]); if s is None: tfunc.error("Errore nella creazione della socket per il logout.") else: try: s.sendall(pk) ricevutoByte = s.recv(const.LENGTH_PACK) if str(ricevutoByte[:4], "ascii") == pack.CODE_LOGOUT_DENIED: tfunc.error("Siamo spiacenti ma il logout risulta impossibile poichè si è in possesso di parti di file uniche.\n" + \ "Sono state scaricate " + str(int(ricevutoByte[4:])) + " parti del file, fatevi il conto di quante ne mancano.") elif str(ricevutoByte[:4], "ascii") == pack.CODE_ANSWER_LOGOUT: tfunc.success("Logout eseguito con successo.\nAvevi " + str(int(ricevutoByte[4:])) + " parti, peccato tu te ne vada, addio.\nAttendi " + str(const.TIME_TO_UPDATE) + " secondi e potrai scomparire.") time.sleep(const.TIME_TO_UPDATE) pk = pack.close() sD = sFunc.create_socket_client(func.roll_the_dice(ip55), const.PORT); if sD is None: pass #tfunc.error("Errore nella chiusura del demone") else: sD.sendall(pk) sD.close() tfunc.success("Chiusura del peer eseguito con successo, arrivederci.\n\n") result = 1 else: tfunc.error("Errore nel codice di logout.") s.close() except: tfunc.error("Errore nel logout a causa del tracker.") s.close() return result
def test_one_shot(root_dir, net, ctx): avg_acc = 0 for running in os.listdir(root_dir): cur_dir = os.path.join(root_dir, running) f = open(os.path.join(cur_dir, 'class_labels.txt'), 'r') cls_id = 1 img_map = {} train_img_list = [] test_img_list = [] for line in f.readlines(): line = line.strip('\n') test_file, train_file = line.split(' ') img_map[train_file] = cls_id img_map[test_file] = cls_id train_img_list.append(train_file) test_img_list.append(test_file) cls_id += 1 train_loader = Function.get_class_loader(root_dir, train_img_list, img_map, (28, 28)) test_loader = Function.get_class_loader(root_dir, test_img_list, img_map, (28, 28)) ProtoNet.attach_labels(net, train_loader, ctx) label, acc = ProtoNet.predict(net, test_loader, ctx) avg_acc += acc print('%s: %4f' % (running, acc)) print('avg: %4f' % (avg_acc / 20))
def init(self): _func_edit = Function.Edit() filepaths = _func_edit.open_files() if filepaths: file_dic = { filepaths[i]: open(filepaths[i], 'r').read() for i in range(len(filepaths)) } print(time.strftime("%M%S")) text = '' # 把选的文章放在一个text里 for i in file_dic: text += file_dic[i] _func_cal = Function.Calculate() text = Function.strip_html(text) list_sorted = _func_cal.frequency_to_str( text, ' ') # 没有用kmp是因为不需要得到每个值的具体位置,只需要加1即可,所以kmp更麻烦 _translate = QtCore.QCoreApplication.translate for i in range(0, 19): item = self.tableWidget_Freq.item( i, 0) # 需要在设计ui时初始化每个item的值,要不然就报错不知道为啥_(:з」∠)_ item.setText(_translate("Dialog", str(list_sorted[i][0]))) item = self.tableWidget_Freq.item(i, 1) item.setText(_translate("Dialog", str(list_sorted[i][1]))) self.textBrowser.setText(str(list_sorted)) print(time.strftime("%M%S"))
def punish(f, a1, a2, x0): mu = 0.5 eps = 10**(-8) x = array(x0) def q(_mu): def _q(x_): r = f(x_) for i in range(0, size(a1)): a = a1[i] r += 0.5 / _mu * a(x_)**2 for i in range(0, size(a2)): r = r + 1 / 2 / _mu * (min(a2[i](x_), 0))**2 return r return _q while True: q_mu = q(mu) Q = Function(q_mu) x = simu_newton(q_mu, x.tolist()) print(x) if Q.norm(x) < eps: return x else: mu = mu / 2
def testXNYN(self): x3 = Function.Function_xn(3) self.assertAlmostEquals(27, x3.evaluate(3, 2), delta=1e-12) y2 = Function.Function_yn(2) self.assertAlmostEquals(4, y2.evaluate(3, 2), delta=1e-12) g2 = x3 + y2 self.assertAlmostEquals(31, g2.evaluate(3, 2), delta=1e-12)
def category(message): "лист категорий анекдотов" list = [ 'о водителях', 'общественный транспорт', 'об адвокатах и судьях', 'василий иваныч и петька', 'про актеров и актрис', 'животные', 'о браке', 'армия', 'о вовочке', 'о жизни' ] chat_id = message.chat.id text = message.text.lower() if text in list: ans = F.category(text)[0] n = F.category(text)[1] F.ap(chat_id, n, F.dictionary) msg = bot.send_message(chat_id, 'Держи анекдот \n' + ans + '\n оцени его, пожалуйста, по шкале от 1 до 5', reply_markup=m.raiting_markup) bot.register_next_step_handler(msg, raiting) elif text == 'б': ans1 = F.category_B() msg = bot.send_message(chat_id, 'Это можно читать если тебе есть 18 лет. \n' + ans1 + '', reply_markup=m.whattodo_markup) bot.register_next_step_handler(msg, whattodo) else: msg = bot.send_message( chat_id, 'Я не знаю как на это ответит, давай начнем сначала. Нажми привет', reply_markup=m.start_markup) bot.register_next_step_handler(msg, askWhattodo) return
def askSource(message): chat_id = message.chat.id text = message.text.lower() if text == 'по категориям': msg = bot.send_message(chat_id, 'Выбирай категорию', reply_markup=m.category_markup) bot.register_next_step_handler(msg, category) elif text == 'лучшие': ans = F.top()[0] n = F.top()[1] F.ap(chat_id, n, F.dictionary) msg = bot.send_message(chat_id, 'Держи анекдот \n' + ans + '\n оцени его, пожалуйста, по шкале от 1 до 5', reply_markup=m.raiting_markup) bot.register_next_step_handler(msg, raiting) else: msg = bot.send_message( chat_id, 'Я не знаю как на это ответит, давай начнем сначала. Нажми привет', reply_markup=m.start_markup) bot.register_next_step_handler(msg, askWhattodo) return
def test_clear(self): poissonForm = PoissonFormulation.PoissonFormulation(2, True) poissonBF = poissonForm.bf() mesh = MeshFactory.MeshFactory_rectilinearMesh(poissonBF, [1.0, 1.0], [2, 3], 4) s = Solution.Solution_solution(mesh) x = Function.Function_xn(1) one = Function.Function_constant(1) zero = Function.Function_constant(0) phi = poissonForm.phi( ) # VarPtr for main, scalar-valued variable in Poisson problem psi = poissonForm.psi() # VarPtr for gradient of psi, vector-valued s = Solution.Solution_solution(mesh) s.projectOntoMesh({ phi.ID(): x, psi.ID(): Function.Function_vectorize(one, zero) }) s.addSolution(s, 1.0, [phi.ID()]) self.assertNotEqual( 0.0, s.L2NormOfSolution(0)) # not zero since addSolution s.clear() self.assertIsNotNone( s) #make sure some object still exists since should be in tact self.assertEqual( 0, s.L2NormOfSolution(0)) # zero since zero solutions now
def testoperatorplus(self): f = Function.Function_constant(22) + Function.Function_constant(18) self.assertAlmostEqual(40, f.evaluate(8, -7), delta=1e-12) f = Function.Function_constant(16) + 16 self.assertAlmostEqual(32, f.evaluate(5, 4), delta=1e-12) f = 12 + Function.Function_constant(14) self.assertAlmostEqual(f.evaluate(1, 2), 26, delta=1e-12)
def handle_events(): global select_menu events = get_events() for event in events: if event.type == SDL_QUIT: game_framework.quit() else: if ((event.type, event.button) == (SDL_MOUSEBUTTONDOWN, SDL_BUTTON_RIGHT)): if select_menu == 0: game_framework.pop_state() else: select_menu = 0 elif ((event.type, event.button) == (SDL_MOUSEBUTTONDOWN, SDL_BUTTON_LEFT)): if Function.PointInRect(event.x, event.y, 0, 113, 51, 149): select_menu = 1 elif Function.PointInRect(event.x, event.y, 0, 113, 151, 249): select_menu = 2 elif Function.PointInRect(event.x, event.y, 0, 113, 251, 349): select_menu = 3 if select_menu == 1: if Function.PointInRect(event.x, event.y, 125, 260, 130, 160): game_framework.change_state(prepare_battle) select_menu = 0
def MarkovChain(Data, EoS, Para, chi2, D, P, ParaSet, chi2Set, Accept, t): # In individual process, process S steps to renew the Cov ---------------------------------------------------------- S = 100 # Metropolis process ----------------------------------------------------------------------------------------------- s = 1 # In the 1st step, Do the Accept and ParaSet initialization while s <= S: Para1 = Function.GeneratePara(t, Para, D, P) chi21 = Function.chi2(Para1, Data, EoS) if chi21 < chi2: alpha = 1 # Will accept with probability alpha = 1 else: alpha = e**(-(1 / 2) * (chi21 - chi2) ) # Accept with probability alpha < 1 beta = random.rand() if beta < alpha: # Accept --------------------------------------------------------------------------------------------------- Para = Para1 chi2 = chi21 Accept = hstack((1, Accept)) chi2Set = hstack((chi2, chi2Set)) ParaSet = vstack((Para, ParaSet)) else: # Reject --------------------------------------------------------------------------------------------------- Accept[0] += 1 s += 1 # Return the results ----------------------------------------------------------------------------------------------- [ParaSet, chi2Set, Accept] = Rearrange(ParaSet, chi2Set, Accept) # The returned arguments had been rearranged Para = ParaSet[0] chi2 = chi2Set[0] [D, P, mu, Cov] = RenewCov(ParaSet, Accept) return [Para, chi2, D, P, ParaSet, chi2Set, Accept, mu, Cov]
def testLinearTermAdd(self): # Sets up test variables varFact = VarFactory.VarFactory() test1 = varFact.fieldVar("x") test2 = varFact.fieldVar("y") test3 = varFact.fieldVar("2x") test4 = varFact.fieldVar("2y") varFunctions = {test1.ID(): Function.Function_xn(1), test2.ID(): Function.Function_yn(1), test3.ID(): Function.Function_xn(1) * 2, test4.ID(): Function.Function_yn(1) * 2} #add overloads ltp = test1 + test2 eval = ltp.evaluate(varFunctions) self.assertEqual(eval.evaluate(1,1), 2.0) #var + var (x+y) ltp2 = ltp + test3 eval = ltp2.evaluate(varFunctions) self.assertEqual(eval.evaluate(1,1), 4.0) #LinearTerm + Var (x + y + 2x) ltp2 = test3 + test4 ltp3 = ltp + ltp2 eval = ltp3.evaluate(varFunctions) self.assertEqual(eval.evaluate(1,1), 6.0) #LinearTerm + LinearTerm (x + y + 2x + 2y) ltp = test3 + ltp2 eval = ltp.evaluate(varFunctions) self.assertEqual(eval.evaluate(1,1), 6.0)
def gold_division(_f, val, d, dur): eps = 0.001 def _fi(_alpha): return _f(array(val) + _alpha * array(d)) fi = Function(_fi) lamb = dur[0] + 0.382 * (dur[1] - dur[0]) mu = dur[0] + 0.618 * (dur[1] - dur[0]) fi_lamb = fi.value(lamb) fi_mu = fi.value(mu) while True: if fi_lamb > fi_mu: if dur[1] - lamb < eps: return mu else: dur[0] = lamb lamb = mu mu = dur[0] + 0.618 * (dur[1] - dur[0]) else: if mu - dur[0] < eps: return lamb else: dur[1] = mu mu = lamb lamb = dur[0] + 0.382 * (dur[1] - dur[0])
def __init__(self, name='', nodes=0, id='', nodeNames=[], firstNode=0): n = len(nodeNames) if len(nodeNames) > 0 else nodes self.functions = Function(self) self.name = name self.id = id self.nodeNames = ["Node%d" % (x) for x in range(n)] if n > 0 else [] self.nodeNames = nodeNames if len(nodeNames) > 0 else self.nodeNames self.nodes = [ Node(self, id=x, name="%s" % (self.nodeNames[x]), function=self.getFunctionName(self.nodeNames[x])) for x in range(len(self.nodeNames)) ] if len(self.nodeNames) > 0 else [] self.firstNode = firstNode self.iterations = 0 self.width = len(self.nodeNames) self.height = len(self.nodeNames) self.connects = np.zeros((n, n), dtype=float) self.factor = 0 self.finnish = np.zeros((n, n), dtype=float) self.factFinnish = 0 self.start = np.zeros((n, n), dtype=float) self.factStart = 0 self.flow = [] self.data = None
def findPaddingLength(cipherText, oracle): """ Discovers the padding length of the cipher text. It works by affecting the penultimate bytes to therefore affect the byte with padding. If a byte containing padding is corrupted we can therefore determine where the padding starts and therefore how long it is """ # Discover padding length targetBlock = -2 # Works it way through the entire byte for x in range(16): blocks = Function.splitBase64IntoBlocks(cipherText) blockBytes = Function.splitBase64IntoBlocks(blocks[targetBlock], 1) # Random change to that byte blockBytes[x] = Function.XOR.b64_Xor(blockBytes[x], base64.b64encode(b"x")) # Saves any changes made to the blocks blocks[targetBlock] = Function.Base64_To.concat(blockBytes) cipherTextPrime = Function.Base64_To.concat(blocks) cipherTextPrimeHex = Function.Base64_To.hexadecimal(cipherTextPrime) if not oracle.query(cipherTextPrimeHex): return 16 - x
def handle_events(): global select_count global attack events = get_events() for event in events: if event.type == SDL_QUIT: game_framework.quit() else: if ((event.type, event.key) == (SDL_KEYDOWN, SDLK_SPACE)): game_framework.change_state(battle_result) if ((event.type, event.button) == (SDL_MOUSEBUTTONDOWN, SDL_BUTTON_LEFT)): print(event.x, event.y) if Function.PointInRect(event.x, event.y, 260, 340, 597, 567): attack = True for i in range(0, 9): if Function.PointInRect(event.x, event.y, 17 + (110 * (i % 3)), 113 + (110 * (i % 3)), 349 + (45 * (i // 3)), 381 + (45 * (i // 3))) and select_count < 3: select.append(i) select_count += 1 print(attack)
def start(): input=self.txtInput.get(1.0, END) if(input.strip() == ''): messagebox.showinfo("ERROR","You need to specify an Input County PDF") return output=self.txtOutput.get(1.0, END) if(output.strip() == ''): messagebox.showinfo("ERROR", "You need to specify an Output FileName") return state=self.txtstate.get(1.0, END) if(state.strip() == ''): messagebox.showinfo("ERROR", "You need to specify an Input State PDF") v = gui_support.v.get() if v == '': messagebox.showinfo("Error No Selected Type","You need to select a pdf type either Births or Teenagers") return try: if v == '1': i = Function.Birthfunction(input.strip(), output.strip(), state.strip()) if v == '2': i = Function.Fertilityfunction(input.strip(),output.strip(), state.strip()) messagebox.showinfo("Results", i) return except: messagebox.showinfo("Error", "The Files did not match needed formats.") return
def testoperatordiv(self): f = Function.Function_constant(-50) / Function.Function_constant(10) self.assertAlmostEqual(-5, f.evaluate(4, -123), delta=1e-12) f = Function.Function_constant(6) / 3.0 self.assertAlmostEqual(2, f.evaluate(10, -6), delta=1e-12) f = 12 / Function.Function_constant(4) self.assertAlmostEqual(3, f.evaluate(0, 0), delta=1e-12)
def testRank(self): #Create Functions x3 = Function.Function_xn(3) y4 = Function.Function_yn(4) c4 = Function.Function_constant(4.0) #Take Derivatives dxx3 = x3.dx() dyx3 = x3.dy() dxy4 = y4.dx() dyy4 = y4.dy() dxc4 = c4.dx() dyc4 = c4.dy() #Utilize Functions sum = x3+y4 vector = Function.Function_vectorize(dxx3,dyy4) gradient = sum.grad() composed = Function.Function_composedFunction(sum,gradient) diverg = gradient.div() #Check Ranks self.assertEqual(x3.rank(),0,"x3 rank is not 0") self.assertEqual(y4.rank(),0,"y4 rank is not 0") self.assertEqual(c4.rank(),0,"c4 rank is not 0") self.assertEqual(sum.rank(),0,"sum rank is not 0") self.assertEqual(vector.rank(),1,"vector rank is not 1") self.assertEqual(gradient.rank(),1,"gradient rank is not 1") self.assertEqual(diverg.rank(),0,"diverg rank is not 1")
def add_log(content): # 给输出加锁。避免文件写入冲突与UI输出异常。 log_lock.acquire() print(content) # 因为没有错误处理所以要将日志立刻写入文件防止丢失 Function.add(folder_path, log_file_name, content + '\n') log_lock.release()
def forward(pk, addr, l): # Non andrebbe fatto generico? if pk != bytes(const.ERROR_PKT, "ascii"): for x in l: if addr != x[0]: s = func.create_socket_client(func.roll_the_dice(x[0]), x[1]) if not(s is None): s.sendall(pk) #write_daemon_success("Daemon", "-", "Forward da " + addr + " a " + x[0]) s.close()
def forward(pk, addr, l): # Non andrebbe fatto generico? if pk != bytes(const.ERROR_PKT, "ascii"): for x in l: if addr != x[0]: s = func.create_socket_client(func.roll_the_dice(x[0]), x[1]) if not (s is None): s.sendall(pk) #write_daemon_success("Daemon", "-", "Forward da " + addr + " a " + x[0]) s.close()
def forward(pk, addr, listNeighbor): if pk != bytes(const.ERROR_PKT, "ascii"): if not [pk[20:75], pk[75:80]] in listNeighbor: for x in listNeighbor: if addr != x[0]: s = func.create_socket_client(func.roll_the_dice(x[0]), x[1]) if not(s is None): s.sendall(pk) s.close()
def testoperatorminus(self): f = Function.Function_constant(22) - Function.Function_constant(18) self.assertAlmostEqual(4, f.evaluate(2, 469), delta=1e-12) f = Function.Function_constant(0) - -10 self.assertAlmostEqual(10, f.evaluate(12, 46), delta=1e-12) f = -5 - Function.Function_constant(-4) self.assertAlmostEqual(-1, f.evaluate(8, 46), delta=1e-12) f = -Function.Function_constant(9) self.assertAlmostEqual(-9, f.evaluate(-43, 12), delta=1e-12)
def run(self): lock = self.lock data = self.queue end = self.event settings = self.settings tag_on = settings['tag_search'] page = settings['start_page'] stop_page = settings['stop_page'] if tag_on: last_stop_id = settings['tagSearch_last_stop_id'] else: last_stop_id = settings['last_stop_id'] while not end.is_set(): with lock: if data.qsize() < 20: if page <= stop_page or not stop_page: add_log('正在读取第{}页……'.format(str(page))) origin = Yandere.get_li( Yandere.get_json(page, tag_on, self.tags)) if len(origin): if page == settings['start_page']: post = origin[0] if post['id'] > last_stop_id: # 考虑开始页不是第一页的情况 if tag_on: settings[ 'tagSearch_last_stop_id'] = post[ 'id'] else: settings['last_stop_id'] = post['id'] Function.write(settings['folder_path'], 'config.json', Yandere.return_json(settings), True) # 我超尖欸 if tag_on: settings[ 'tagSearch_last_stop_id'] = last_stop_id else: settings['last_stop_id'] = last_stop_id for post in origin: if post['id'] <= last_stop_id: add_log('达到上次爬取终止位置') end.set() break post['id'] = str(post['id']) if judge(post, settings, self.discard_tags): data.put(post) page += 1 lock.notify(1) else: end.set() lock.notify_all() add_log('页面为空\n所有页面读取完毕') else: end.set() else: lock.wait()
def forward(pk, addr, listNeighbor): if pk != bytes(const.ERROR_PKT, "ascii"): if not [pk[20:75], pk[75:80]] in listNeighbor: for x in listNeighbor: if addr != x[0]: s = func.create_socket_client(func.roll_the_dice(x[0]), x[1]) if not (s is None): s.sendall(pk) s.close()
def __init__(self, k): self.k = k self.iterations = 0 self.point_count = 2**self.k self.anchor_path = os.path.abspath(os.path.dirname(__file__)) self.f = Function('1/(1-z)') self.f.expand_eval(0, 0.5 + 0.5j) self.setupGlut() self.sd = SharedDevice(self.vbo, self.k) self.compute()
def writeHelp(): func.warning("\nPOSSIBILI ARGOMENTI:") print("Super Nodo\t-sn") print("Set Default Ip\t-ip group identifier") print("Change Port\t-p port") print("Change Port SN\t-pSN port") print("Change time\t-t time") print("Change ttl\t-ttl ttl") print("") sys.exit(-1)
def enter(): global background global battle_ui, button_set, button_act, button_charge, button_reset, down_arrow global enemy global assist global enemy_assist background = load_image('bgi\\bg_battle_game.png') battle_ui = load_image('bgi\\bg_battle_up.png') button_set = load_image('image\\button_battle_set.png') button_act = load_image('image\\button_act.png') button_charge = load_image('image\\button_charge.png') button_reset = load_image('image\\button_reset.png') down_arrow = load_image('image\\danmaku_down.png') assist = load_image('image\\image_55.png') enemy = load_image('image\\q_stand_mao.png') enemy_assist = load_image('image\\image_mao.png') for i in range(50, 72): story.append(load_image('story\\tutorial\\K-' + str(i) + '.png')) my_doll.append( [load_image('image\\q_stand_38.png'), Function.charactor('reimu')]) my_doll.append( [load_image('image\\q_stand_24.png'), Function.charactor('mari')]) my_doll.append( [load_image('image\\q_stand_44.png'), Function.charactor('sanae')]) spell.append( load_image('image\\' + str(my_doll[0][1].battle_spell_1.name) + '.png')) spell.append( load_image('image\\' + str(my_doll[0][1].battle_spell_2.name) + '.png')) spell.append( load_image('image\\' + str(my_doll[0][1].battle_spell_3.name) + '.png')) spell.append(load_image('image\\image_24_card06.png')) spell.append(load_image('image\\image_zako_card01.png')) spell.append(load_image('image\\image_zako_card02.png')) spell.append(load_image('image\\image_zako_card03.png')) spell.append(load_image('image\\image_44_card04.png')) spell.append( load_image('image\\' + str(my_doll[0][1].battle_spell_1.name) + 'g.png')) spell.append( load_image('image\\' + str(my_doll[0][1].battle_spell_2.name) + 'g.png')) spell.append( load_image('image\\' + str(my_doll[0][1].battle_spell_3.name) + 'g.png')) tuto_atk.append(load_image('image\\q_atk_38.png')) tuto_atk.append(load_image('image\\q_atk_44.png')) tuto_atk.append(load_image('image\\q_atk_mao.png'))
def testInstance(self): x3 = Function.Function_xn(3) #test xn rank self.assertEqual(x3.rank(),0,"x3 rank is not 0") y4 = Function.Function_yn(4) #test yn rank self.assertEqual(y4.rank(),0,"y4 rank is not 0") c4 = Function.Function_constant(4.0) #test const rank self.assertEqual(y4.rank(),0,"y4 rank is not 0") #test evaluate on xn yn and const for i in range (0,10): self.assertAlmostEquals(c4.evaluate((10+i),i),4.0,delta=1e-12) self.assertAlmostEquals(x3.evaluate((10+i),i),math.pow(10+i,3),delta=1e-12) self.assertAlmostEquals(y4.evaluate((10+i),i),math.pow(i,4),delta=1e-12) dxx3 = x3.dx() dyx3 = x3.dy() dxy4 = y4.dx() dyy4 = y4.dy() dxc4 = c4.dx() dyc4 = c4.dy() #test evaluate on dy and dx for i in range (0,10): self.assertAlmostEquals(dxx3.evaluate(i,i),3*math.pow(i,2),delta=1e-12) self.assertAlmostEquals(dyx3.evaluate(i,i),0,delta=1e-12) self.assertAlmostEquals(dxy4.evaluate(i,i),0,delta=1e-12) self.assertAlmostEquals(dyy4.evaluate(i,i),4*math.pow(i,3),delta=1e-12) self.assertAlmostEquals(dxc4.evaluate(i,i),0,delta=1e-12) self.assertAlmostEquals(dyc4.evaluate(i,i),0,delta=1e-12) sum = x3+y4 #test rank after summation self.assertEqual(sum.rank(),0,"sum rank is not 0") vector = Function.Function_vectorize(dxx3,dyy4) gradient = sum.grad() #test rank of vectorize and gradient self.assertEqual(vector.rank(),1,"vector rank is not 1") self.assertEqual(gradient.rank(),1,"gradient rank is not 1") #test evaluate of x and y components of vectors for i in range (0,10): self.assertAlmostEquals(vector.x().evaluate(i,i),dxx3.evaluate(i,i),delta = 1e-12) self.assertAlmostEquals(gradient.x().evaluate(i,i),dxx3.evaluate(i,i),delta = 1e-12) self.assertAlmostEquals(vector.y().evaluate(i,i),dyy4.evaluate(i,i),delta = 1e-12) self.assertAlmostEquals(gradient.y().evaluate(i,i),dyy4.evaluate(i,i),delta = 1e-12) #test composition of functions composed = Function.Function_composedFunction(sum,gradient) for i in range (0,10): self.assertAlmostEquals(composed.evaluate(i,i),sum.evaluate((3*math.pow(i,2)),(4*math.pow(i,3))),delta = 1e-12) #test divergence diverg = gradient.div() for i in range(0,10): self.assertAlmostEquals(diverg.evaluate(i+1,i),dxx3.dx().evaluate(i+1,i)+dyy4.dy().evaluate(i+1,i),delta = 1e-12)
def login(host, SN, SN_host, listPkt): s = func.create_socket_client(func.roll_the_dice(SN_host[0]), SN_host[1]) pk = pack.request_login(host) if s is None: func.error("Errore nell'apertura della socket per il login") update_network(host, SN, listPkt) else: s.sendall(pk) ricevutoByte = s.recv(const.LENGTH_PACK) sessionID = ricevutoByte[4:20] s.close() return sessionID
def download(selectFile): print ("\n>>> DOWNLOAD") md5 = selectFile[1] nomeFile = selectFile[2].decode("ascii").strip() ip = selectFile[3] port = selectFile[4] # Con probabilità 0.5 invio su IPv4, else IPv6 ip = func.roll_the_dice(ip.decode("ascii")) print("Connessione con:", ip) # Mi connetto al peer sP = func.create_socket_client(ip, port) if sP is None: print ('Error: could not open socket in download') else: pk = pack.request_download(md5) sP.sendall(pk) nChunk = int(sP.recv(const.LENGTH_HEADER)[4:10]) ricevutoByte = b'' i = 0 while i != nChunk: ricevutoLen = sP.recv(const.LENGTH_NCHUNK) while (len(ricevutoLen) < const.LENGTH_NCHUNK): ricevutoLen = ricevutoLen + sP.recv(const.LENGTH_NCHUNK - len(ricevutoLen)) buff = sP.recv(int(ricevutoLen)) while(len(buff) < int(ricevutoLen)): buff = buff + sP.recv(int(ricevutoLen) - len(buff)) ricevutoByte = ricevutoByte + buff i = i + 1 sP.close() # Salvare il file data open((const.FILE_COND + nomeFile),'wb').write(ricevutoByte) print("File scaricato correttamente, apertura in corso...") try: os.system("open " + const.FILE_COND + nomeFile) except: try: os.system("start " + const.FILE_COND + nomeFile) except: print("Apertura non riuscita")
def add(ip55, sessionID, t_host, listPartOwned): tfunc.warning("\n>>> ADD FILE") fileName = input("Quale file vuoi inserire?\n") if fileName != "0": if os.path.exists(const.FILE_COND + fileName): fileToRead = open((const.FILE_COND + fileName),'rb') lenFile = os.stat(const.FILE_COND + fileName).st_size m = hashlib.md5() for x in range(0, pfunc.calculate_part(lenFile, const.LENGTH_PART)): m.update(fileToRead.read(const.LENGTH_PART)) m.update(bytes(ip55, "ascii")) md5File = m.hexdigest() fileToRead.close() pk = pack.request_add_file(sessionID, lenFile, md5File, tfunc.format_string(fileName, const.LENGTH_FILENAME, " ")) s = sfunc.create_socket_client(func.roll_the_dice(t_host[0]), t_host[1]); if s is None: tfunc.error("Errore, tracker non attivo.") else: s.sendall(pk) ricevutoByte = s.recv(const.LENGTH_PACK) if(ricevutoByte[:4].decode("ascii") == pack.CODE_ANSWER_ADDFILE): tfunc.success("Il file " + fileName + " è stato aggiunto con successo.\nÈ stato diviso in " + str(int(ricevutoByte[4:])) + " parti.") pfunc.add_to_list_owner(md5File, lenFile, const.LENGTH_PART, listPartOwned, fileName) else: tfunc.error("Errore nella ricezione del codice di aggiunta file.") s.close() else: tfunc.error("Errore: file non esistente.")
def _sim_matrix(self, algts, D, gap): """ @summary: Calculates the similarity matrix for the set of alignments @param algts: A list of alignments @type algts: ListType @param D: Retention time tolerance parameter for pairwise alignments @type D: FloatType @param gap: Gap parameter for pairwise alignments @type gap: FloatType @author: Woon Wai Keen @author: Vladimir Likic """ n = len(algts) total_n = n * (n - 1) / 2 print " Calculating pairwise alignments for %d alignments (D=%.2f, gap=%.2f)" % \ (n, D, gap) sim_matrix = numpy.zeros((n,n), dtype='f') for i in range(n - 1): for j in range(i + 1, n): ma = Function.align(algts[i], algts[j], D, gap) sim_matrix[i,j] = sim_matrix[j,i] = ma.similarity total_n = total_n - 1 print " -> %d pairs remaining" % total_n return sim_matrix
def run(self): global mutex sP = sfunc.create_socket_client(func.roll_the_dice(self.peer[0]), self.peer[1]) if sP is None: #tfunc.error('Error: could not open socket in download') var = "" # giusto per fargli fare qualcosa else: try: if mutex.acquire(timeout = const.TIME_TO_UPDATE): dnl.update_own_memory(self.md5, self.partN, self.listPartOwned, "2") mutex.release() #tfunc.gtext("Start download della parte " + str(self.partN) + " da " + str(self.peer[0], "ascii")) pk = pack.request_download(self.md5, self.partN) sP.sendall(pk) ricevutoByte = sP.recv(const.LENGTH_HEADER) if str(ricevutoByte[0:4], "ascii") == pack.CODE_ANSWER_DOWNLOAD: nChunk = int(ricevutoByte[4:10]) ricevutoByte = b'' i = 0 while i != nChunk: ricevutoLen = sP.recv(const.LENGTH_NCHUNK) while (len(ricevutoLen) < const.LENGTH_NCHUNK): ricevutoLen = ricevutoLen + sP.recv(const.LENGTH_NCHUNK - len(ricevutoLen)) buff = sP.recv(int(ricevutoLen)) while(len(buff) < int(ricevutoLen)): buff = buff + sP.recv(int(ricevutoLen) - len(buff)) ricevutoByte = ricevutoByte + buff i = i + 1 sP.close() # Modifico nel file la parte che ho appena scaricato, se il file non esiste lo creo (es b'00000') dnl.create_part(ricevutoByte, self.fileName, self.partN, self.lenFile, self.lenPart) if mutex.acquire(timeout = const.TIME_TO_UPDATE): # Aggiorno la mia memoria dnl.update_own_memory(self.md5, self.partN, self.listPartOwned, "1") mutex.release() pfunc.part_all(self.listPartOwned[self.md5][0]) # Invio l'update al tracker send_update(self.t_host, self.sessionID, self.md5, self.partN, self.listPartOwned, self.peer) else: raise Exception("Error Download Code") else: raise Exception("Error Download Code") else: raise Exception("Error Download Code") except Exception as e: #tfunc.write_daemon_error(self.name, str(self.peer[0], "ascii"), "ERRORE DOWNLOAD: {0}".format(e)) dnl.update_own_memory(self.md5, self.partN, self.listPartOwned, "0")
def try_connection(host): s = sfunc.create_socket_client(func.roll_the_dice(host), const.TPORT) pk = pack.confirm() if s is None: sys.exit(-1) else: s.sendall(pk) s.close()
def forward_neighbor(pack): step = modify_ttl(pack[80:82]) if step != 0: step = func.format_string(str(step), const.LENGTH_TTL, "0") pack = pack[0:80] + bytes(step, "ascii") return pack else: return bytes(const.ERROR_PKT, "ascii")
def updateReference(self): """ Set up the position when the local node move.""" # The node is the center of a local bench mark. relative_position = Function.relativePosition(self.position, globalvars.me.position) self.local_position = [ long(relative_position[0] - globalvars.me.position[0]), long(relative_position[1] - globalvars.me.position[1]), ]
def search_file(query, listFiles, listUsers): listResultQuery = [] for f in listFiles: if query in f[1]: for i in listUsers: if i[2] == f[2]: listResultQuery.append([f[0], bytes(func.format_string(str(f[1],"ascii"), const.LENGTH_FILENAME, " "),"ascii"), i[0], i[1]]) break return listResultQuery
def __init__(self): wpf.LoadComponent(self, 'WpfApplication1.xaml') self.CommandTextBox.IsEnabled = False self.ScenarioRadio.IsEnabled = False self.ScenariolistView.IsEnabled = False self.PlaybackRadio.IsEnabled = False self.RecordFilePathTextBox.IsEnabled = False self.LoadRecordFileButton.IsEnabled = False self.CommandTextBox.IsEnabled = False self.GUIRadio.IsEnabled = False self.CommandRadio.IsEnabled = False self.ExcuteScriptButton.IsEnabled = False self.ExecPlaybackButton.IsEnabled = False self.PhoneSelect_1.IsEnabled = False self.PhoneSelect_2.IsEnabled = False self.PlaybackNumTextBox.IsEnabled = False Function.mkdir_p(self.__auto_log_root) self.__auto_save_path = self.__auto_log_root+'\\'+time.strftime('%Y-%m-%d-%H-%M-%S')+'.txt'
def request_memory_of_hitpeer(t_host, sessionID, md5): s = sfunc.create_socket_client(func.roll_the_dice(t_host[0]), t_host[1]); if s is None: #tfunc.error("Tracker non attivo.") return bytes(const.ERROR_PKT, "ascii") else: pk = pack.request_hitpeer(sessionID, md5) s.sendall(pk) return s.recv(4 * const.LENGTH_PACK)
def quit(ip55): tfunc.warning("\n>>> QUIT") pk = pack.close() s = sFunc.create_socket_client(func.roll_the_dice(ip55), const.TPORT); if s is None: tfunc.error("Errore nella chiusura del demone tracker") else: s.sendall(pk) s.close() tfunc.success("Chiusura del demone tracker eseguito con successo, arrivederci.\n\n")
def updateNeighbor(myHost, listNeighbor): del listNeighbor[:] pk = pack.neighbor(myHost) # Se avevo già dei vicini vado a testare se sono ancora attivi """if len(listNeighbor) != 0: for neighbor in listNeighbor: s = func.create_socket_client(func.roll_the_dice(neighbor[0]), neighbor[1]); # Se non sono più attivi lo segnalo e li cancello dalla lista if s is None: func.error(str(neighbor[0], "ascii") + " non è più attivo.") del neighbor else: func.success(str(neighbor[0], "ascii") + " ancora attivo.") s.close() # Se prima ero al completo e sono ancora tutti attivi lo segnalo e esco if len(listNeighbor) == const.NUM_NEIGHBOR: func.success("Lista vicini completa!") # Se invece dopo il controllo ho meno vicini del numero massimo mando a ogni vicino una richiesta di vicinato elif len(listNeighbor) > 0: for neighbor in listNeighbor: s = func.create_socket_client(func.roll_the_dice(neighbor[0]), neighbor[1]); if s is None: func.error("Mamma che sfiga, sto vicino è andato giù proprio ora.") else: s.sendall(pk) s.close() # Alla fine gestisco la possibilità che tutti i vicini che avevo siano andati giù e quindi passo all'inserimento manuale. if len(listNeighbor) == 0: """ while True: print ("\n>>> SCELTA PEER VICINO") nGroup = input("Numero del gruppo: ") if nGroup is 0: break nElement = input("Numero dell'elemento del gruppo: ") if nElement is 0: break nPort = input("Inserire la porta su cui il vicino è in ascolto: ") if nPort is 0: break hostN = func.roll_the_dice("172.030." + func.format_string(nGroup, const.LENGTH_SECTION_IPV4, "0") + "." + func.format_string(nElement, const.LENGTH_SECTION_IPV4, "0") + "|fc00:0000:0000:0000:0000:0000:" + func.format_string(nGroup, const.LENGTH_SECTION_IPV6, "0") + ":" + func.format_string(nElement, const.LENGTH_SECTION_IPV6, "0")) s = func.create_socket_client(hostN, nPort); if s is None: func.error("Errore nella scelta del primo peer vicino, scegline un altro.") break else: s.sendall(pk) s.close() break
def logout(ip): print ("\n>>> LOGOUT") i = 0 pk = pack.logout() s = func.create_socket_client(func.get_ipv4(ip), const.PORT); if s is None: func.error("Errore nella chiusura del demone:" + func.get_ipv4(ip)) else: s.sendall(pk) s.close() i = i + 1 s = func.create_socket_client(func.get_ipv6(ip), const.PORT); if s is None: func.error("Errore nella chiusura del demone:" + func.get_ipv6(ip)) else: s.sendall(pk) s.close() i = i + 1 if i is 2: print ("Logout eseguito con successo.")
def send_update(t_host, sessionID, md5, partN, listPartOwned, peer): s = sfunc.create_socket_client(func.roll_the_dice(t_host[0]), t_host[1]) if s is None: tfunc.error('Error: could not open socket to update Tracker') else: pk = pack.request_update_tracker(sessionID, md5, partN) s.sendall(pk) ricevutoByte = s.recv(const.LENGTH_PACK) if str(ricevutoByte[0:4], "ascii") == pack.CODE_ANSWER_UPDATE_PART: tfunc.dnl_success("Download eseguito della parte " + str(partN) + " da " + str(peer[0], "ascii") + "\nAttualmente in possesso di " + str(int(ricevutoByte[4:])) + "/" + str(len(listPartOwned[md5][0])) + " parti del file.") s.close()
def create_socket_server(myHost, port): s = None if len(myHost) < 55: for res in socket.getaddrinfo(myHost, int(port), socket.AF_UNSPEC,socket.SOCK_STREAM, 0, socket.AI_PASSIVE): af, socktype, proto, canonname, sa = res try: s = socket.socket(af, socktype, proto) except socket.error as msg: s = None continue try: s.bind(sa) s.listen(10) except socket.error as msg: s.close() s = None continue break else: func.error("Errore dimensione IP.") return s
def updatePos(self, new_pos): """ update the position of the entity""" # update position old_position = self.position self.position = new_pos relative_position = Function.relativePosition(self.position, globalvars.me.position) self.local_position = [ long(relative_position[0] - globalvars.me.position[0]), long(relative_position[1] - globalvars.me.position[1]), ] # compute delta delta_pos = [] delta_pos.append(self.position[0] - old_position[0]) delta_pos.append(self.position[1] - old_position[1]) # update lists globalvars.me.ccwAdjacents.replace(self) globalvars.me.distAdjacents.replace(self) # send message to Media if globalvars.me.GUIConnected: stringVar = "POS" stringVariation = str(delta_pos[0]) + ", " + str(delta_pos[1]) for media in globalvars.me.media.values(): if media.push: resul = media.thread.modNode(self.id, stringVar, stringVariation) if not resul: if ( media.thread.newNode( self.id, self.local_position[0], self.local_position[1], self.caliber, self.pseudo, self.ori, ) == -1 ): sys.stderr.write("error in modNode updateOri") if media.addBug(): del globalvars.me.media[media.id] else: media.bug = 0 elif resul == -1: if media.addBug(): del globalvars.me.media[media.id] else: media.bug = 0
def add_file(fileName, sessionID, SN, SN_host, host, listPkt): if os.path.exists("FileCondivisi/" + fileName): md5File = hashlib.md5(open(("FileCondivisi/" + fileName),'rb').read()).hexdigest() pk = pack.request_add_file(sessionID, md5File, func.format_string(fileName, const.LENGTH_FILENAME, " ")) s = func.create_socket_client(func.roll_the_dice(SN_host[0]), SN_host[1]); if s is None: func.error("Errore, super nodo non attivo.") update_network(host, SN, listPkt) else: s.sendall(pk) s.close() else: func.error("Errore: file non esistente.")
def send_afin(conn, listResultQuery): if len(listResultQuery) != 0: nMd5 = 0 listResultQuery.sort() md5 = b'' for x in listResultQuery: if md5 != x[0]: md5 = x[0] nMd5 += 1 pk = bytes(const.CODE_ANSWER_SEARCH, "ascii") + bytes(func.format_string(str(nMd5), const.LENGTH_NIDMD5, "0"), "ascii") actualMd5 = b'' for i in listResultQuery: if i[0] != actualMd5: #actualMd5 = listResultQuery[0][0] # calcolo numero copie actualMd5 = i[0] copy = 0 for x in listResultQuery: if x[0] == actualMd5: copy += 1 pk = pk + i[0] + i[1] + bytes(func.format_string(str(copy), const.LENGTH_NCOPY, "0"), "ascii") pk = pk + i[2] + i[3] else: pk = bytes(const.CODE_ANSWER_SEARCH, "ascii") + bytes("0" * const.LENGTH_NIDMD5, "ascii") conn.sendall(pk)
def run(self): # Creazione socket s = sfunc.create_socket_server(func.roll_the_dice(self.host), self.port) if s is None: tfunc.write_daemon_error(self.name, self.host, 'Error: Daemon could not open socket.') else: while 1: try: conn, addr = s.accept() daemonUpl = threading.Thread(target = daemonUpload, args = (conn, self.name, addr, self.listPartOwned, )) daemonUpl.start() except Exception as ex: #print(ex) continue s.close()
def login(host, t_host): if t_host[0] == "": nGroup = input("Inserire il numero del gruppo del tracker: ") nElement = input("Inserire il numero dell'elemento del gruppo del tracker: ") t_host = [("172.030." + tfunc.format_string(nGroup, const.LENGTH_SECTION_IPV4, "0") + "." + tfunc.format_string(nElement, const.LENGTH_SECTION_IPV4, "0") + "|fc00:0000:0000:0000:0000:0000:" + tfunc.format_string(nGroup, const.LENGTH_SECTION_IPV6, "0") + ":" + tfunc.format_string(nElement, const.LENGTH_SECTION_IPV6, "0")), const.TPORT] tfunc.warning("\n>>> LOGIN") s = sfunc.create_socket_client(func.roll_the_dice(t_host[0]), t_host[1]) pk = pack.request_login(host) if s is None: tfunc.error("Errore nell'apertura della socket per il login") return t_host, bytes(const.ERROR_LOG, "ascii") else: s.sendall(pk) ricevutoByte = s.recv(const.LENGTH_PACK) sessionID = ricevutoByte[4:20] s.close() return t_host, sessionID
def confirm(self, pos, ori, ar, ca, pseudo): """ confirm and update informations: to detect liars""" self.ok = 1 # update informations about this entity. self.position = pos relative_position = Function.relativePosition(self.position, globalvars.me.position) self.local_position = [ relative_position[0] - globalvars.me.position[0], relative_position[1] - globalvars.me.position[1], ] self.awareness_radius = ar self.pseudo = pseudo self.caliber = ca self.ori = ori # send informations to media if globalvars.me.GUIConnected: for media in globalvars.me.media.values(): if media.push: if ( media.thread.newNode( self.id, self.local_position[0], self.local_position[1], self.caliber, self.pseudo, self.ori ) == -1 ): sys.stderr.write("error in newNode " + self.pseudo + "\n") if media.addBug(): del globalvars.me.media[media.id] else: media.bug = 0 # we save a trace of this entity for further connection globalvars.me.met[(self.host, self.port)] = 1 globalvars.me.nb_met += 1 return 1
def __init__(self, id, host, port, pos, ori, awareness_radius, caliber, pseudo): """ Create a new Entity and keep information about it""" # identifier self.id = id # network data self.host = host self.port = int(port) # position and relative position self.position = pos relative_position = Function.relativePosition(self.position, globalvars.me.position) self.local_position = [ relative_position[0] - globalvars.me.position[0], relative_position[1] - globalvars.me.position[1], ] # awareness radius, caliber, pseudo, orientation self.awareness_radius = awareness_radius self.caliber = caliber self.pseudo = pseudo self.ori = ori # two boolean variables indicating that # we received a message from this entity self.message_received = 1 # we sent a message to this entity self.message_sent = 0 # services provided by entity # {id_service: [desc_service, host, port], ...} self.services = {} # boolean confirmation of the accuracy of informations self.ok = 0
def answer_neighbor(pktID, ip): port = func.format_string(const.PORT, const.LENGTH_PORT, "0") return bytes(const.CODE_ANSWER_NEAR, "ascii") + pktID + bytes(ip, "ascii") + bytes(port, "ascii")
def answer_query(pktID, ip, md5, fileName): port = func.format_string(const.PORT, const.LENGTH_PORT, "0") fileName = func.format_string(fileName, const.LENGTH_FILENAME, " ") return bytes(const.CODE_ANSWER_QUERY, "ascii") + pktID + bytes(ip, "ascii") + bytes(port, "ascii") + bytes(md5, "ascii") + bytes(fileName, "ascii")