def post_response(request_dict, keep_connection, client_ip): if request_dict['Content-Type'][0] != 'multipart/form-data': return header_maker('400', keep_connection=False) boundary = None for content_info in request_dict['Content-Type']: if content_info.startswith('boundary='): boundary = content_info[9:] if boundary is None: return header_maker('400', keep_connection=False) info_list = request_dict['body'].split('--' + boundary) info_list = info_list[1:-1] for index, item in enumerate(info_list): info_list[index] = item[2:-2] contents_dicts = [{} for thank_you_frenkel in range(len(info_list))] for info_num, info in enumerate(info_list): contents_dicts[info_num]['header'] = info.split('\r\n\r\n')[0] contents_dicts[info_num]['data'] = info.split('\r\n\r\n')[1] for item_num, item in enumerate(contents_dicts): header = item['header'].split('\r\n') for line in header: if line.startswith('Content-Disposition: form-data; '): variables = line[32:].split('; ') variables_dict = {} for variable in variables: variables_dict[variable.split('=')[0]] = variable.split('=')[1][1:-1] contents_dicts[item_num].update(variables_dict) file_ending = None file_name = None file_password = None file_data = None for content in contents_dicts: if content['name'] == 'name': file_name = content['data'] elif content['name'] == 'password': file_password = content['data'] elif content['name'] == 'file': if len(content['filename'].split('.')) == 1: file_ending = '' else: file_ending = content['filename'].split('.')[-1] file_data = content['data'] if file_name is None or Utility.all_chars(file_name.replace('%20', ' '), ' ') or file_data is None: return header_maker('400', keep_connection=False) if file_ending != '': file_name = '%s.%s' % (file_name, file_ending) if file_password is None: file_password = '' file_saved = MemoryHandler.hash_save_file(file_name, file_password, file_data) if file_saved: message = '<i>file saved, you can get it at:</i><br><u>http://%s/getfile?name=%s' % (MemoryHandler.get_server_settings()['domain'], file_name.replace(' ', '%20')) if file_password != '': message += '&password='******' ', '%20') message += '</u>' else: message = 'file not saved' got_file, replay_file = MemoryHandler.get_server_file('uploadfile.html') if not got_file: return header_maker('500', keep_connection=False) new_replay_text = Utility.add_to_mark(replay_file, message) return header_maker('200', content_len=str(len(new_replay_text)), download_file=False, keep_connection=keep_connection, file_name='uploadfile.html') + new_replay_text
def __init__(self): self.velocidade = 0 self.gasolina = 0 self.pontos = 0 self.posicao = 0 self.rpm = 0 self.nitro = 0 self.gerenciadorMemoria = MemoryHandler("zsnesw.exe")
class carro(object): def __init__(self): self.velocidade = 0 self.gasolina = 0 self.pontos = 0 self.posicao = 0 self.rpm = 0 self.nitro = 0 self.gerenciadorMemoria = MemoryHandler("zsnesw.exe") def update(self): self.updateVel() self.updateGas() self.updatePontos() self.updatePosicao() self.updateRpm() self.updateNitro() def pack(self): data = '1;' + str(self.velocidade) + ';' + str( self.gasolina) + ';' + str(self.pontos) + ';' + str( self.posicao) + ';' + str(self.rpm) + ';' + str( self.nitro) + ';' return data def updatePosicao(self): self.posicao = (int)((self.gerenciadorMemoria.lerByte(CARROSAFRENTE)) + 1) def updateVel(self): self.velocidade = (int)( self.gerenciadorMemoria.lerPalavra(SPEEDMETER) / 10) pass def updateGas(self): self.gasolina = (int)(100 - (( (self.gerenciadorMemoria.lerByte(FUELCONSUMP)) * 100) / 20)) pass def updatePontos(self): self.pontos = self.gerenciadorMemoria.lerByte(POINTS) pass def updateRpm(self): self.rpm = 0 pass def updateNitro(self): self.nitro = (int)(self.gerenciadorMemoria.lerByte(0x00C64B06) - 53) pass
def build_meta_file(self, path, file_length, piece_length, pieces_hash): port = TRACKER_PORT.__str__() ip = [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1][0] #Gets the IP and port of the tracker. announce = "udp://" + ip + ":" + port #Creates an announce URL. filename = path.split("\\")[-1] temp = filename.split(".") temp[-1] = "torrent" torrent_name = temp[0] for i in temp[1:]: torrent_name += "." + i #turns the file into a .torrent file info = {'name' : filename, 'piece length': piece_length, 'length': file_length, 'pieces': pieces_hash } file = {"announce" : announce, "info" : info} #Builds the info dictionary and the file print file MemoryHandler.save_file(torrent_name, bencode.bencode(file)) #Saves them as bencoded data return self.hash_piece(bencode.bencode(info)) #Returns the info_hash
def get_response(request_dict, keep_connection, client_ip): parameter_dict = {} message = '' file_name = '' url = request_dict['header'][1].split('?') if url[0].startswith('/getfile') and len(url) == 2: parameters_list = url[1].replace(';', '&').split('&') for parameter in parameters_list: if len(parameter.split('=')) == 2: parameter_dict[parameter.split('=')[0]] = parameter.split('=')[1] if 'name' not in parameter_dict: return header_maker('400', keep_connection=False) file_name = parameter_dict['name'].replace('%20', ' ') file_password = '' if 'password' in parameter_dict: file_password = parameter_dict['password'].replace('%20', ' ') has_file, requested_file = MemoryHandler.hash_get_file(file_name, file_password) if has_file: file_text = requested_file.read() file_name = os.path.basename(requested_file.name) requested_file.close() print 'Sending the file "%s" to: %s' % (file_name, client_ip) return header_maker('200', content_len=str(len(file_text)), download_file=True, keep_connection=keep_connection, file_name=file_name) + file_text else: print 'Can`t get the file "%s" for: %s' % (file_name, client_ip) file_name = 'getfile.html' message = 'Wrong file name or password' if file_name == '': if url[0] == '/': file_name = 'index.html' elif url[0] == '/getfile': file_name = 'getfile.html' elif url[0] == '/uploadfile': file_name = 'uploadfile.html' elif url[0] == '/delfile': file_name = 'delfile.html' else: file_name = url[0][1:] file_found, file_data = MemoryHandler.get_server_file(file_name) if file_found: if file_name == 'getfile.html': file_data = Utility.add_to_mark(file_data, message) print 'Sending the server file "%s" to: %s' % (file_name, client_ip) return header_maker('200', content_len=str(len(file_data)), download_file=False, keep_connection=True, file_name=file_name) + file_data return header_maker('404', keep_connection=False)
def __init__(self): self.open_http_sockets = [] self.open_https_sockets = [] self.settings = MemoryHandler.get_server_settings() self.http_socket = socket.socket() self.http_socket.bind((self.settings['http_ip'], int(self.settings['http_port']))) self.http_socket.listen(10) self.https_socket = socket.socket() self.https_socket.bind((self.settings['https_ip'], int(self.settings['https_port']))) self.https_socket.listen(10)
def delete_response(request_dict, keep_connection): if request_dict['Content-Type'][0] != 'multipart/form-data': return header_maker('400', keep_connection=False) boundary = None for content_info in request_dict['Content-Type']: if content_info.startswith('boundary='): boundary = content_info[9:] if boundary is None: return header_maker('400', keep_connection=False) info_list = request_dict['body'].split('--' + boundary) info_list = info_list[1:-1] for index, item in enumerate(info_list): info_list[index] = item[2:-2] contents_dicts = [{} for thank_you_frenkel in range(len(info_list))] for info_num, info in enumerate(info_list): contents_dicts[info_num]['header'] = info.split('\r\n\r\n')[0] contents_dicts[info_num]['data'] = info.split('\r\n\r\n')[1] for item_num, item in enumerate(contents_dicts): header = item['header'].split('\r\n') for line in header: if line.startswith('Content-Disposition: form-data; '): variables = line[32:].split('; ') variables_dict = {} for variable in variables: variables_dict[variable.split('=')[0]] = variable.split('=')[1][1:-1] contents_dicts[item_num].update(variables_dict) file_name = None file_password = None for content in contents_dicts: if content['name'] == 'name': file_name = content['data'] elif content['name'] == 'password': file_password = content['data'] if file_name is None: return header_maker('400', keep_connection=False) if file_password is None: file_password = '' deleted_file, message = MemoryHandler.hash_delete_file(file_name, file_password) got_file, replay_file = MemoryHandler.get_server_file('delfile.html') if not got_file: return header_maker('500', keep_connection=False) new_replay_text = Utility.add_to_mark(replay_file, message) return header_maker('200', content_len=str(len(new_replay_text)), download_file=False, keep_connection=keep_connection, file_name='uploadfile.html') + new_replay_text
def __init__(self,nomeProcesso): self.geracao = 0 self.gerenciadorMemoria = MemoryHandler(nomeProcesso) self.controladorTeclado = keyController() self.sonic = Sonic(self.gerenciadorMemoria) self.melhorSolucao = solucao() for i in range (0,TAMANHOGER): individuo = solucao() individuo.geracao=0 individuo.gerarSolucaoAleatoria() self.vetorSolucoes.append(individuo)
def request_checker(request_dict): server_settings = MemoryHandler.get_server_settings() header_list = request_dict['header'] if len(header_list) != 3 or header_list[2].split('/')[0] != server_settings['version'].split('/')[0]: return '400' if header_list[2].split('/')[1] != server_settings['version'].split('/')[1]: return '505' valid_type = False for request_type in server_settings['request_types'].split('/'): if header_list[0] == request_type: valid_type = True if not valid_type: return '501' return None
def header_maker(code, content_len='0', download_file=False, keep_connection=False, file_name=''): server_settings = MemoryHandler.get_server_settings() header = server_settings['version'] + ' ' + server_settings[code] + '\r\n' header_dict = {'Date': time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime())} file_type = file_name.split('.')[-1] if file_type == 'txt': content_type = 'text/plain' elif file_type == 'html' or file_type == 'htm': content_type = 'text/html' elif file_type == 'pdf': content_type = 'application/pdf' elif file_type == 'exe': content_type = 'application/octet-stream' elif file_type == 'zip': content_type = 'application/zip' elif file_type == 'doc': content_type = 'application/msword' elif file_type == 'xls': content_type = 'application/vnd.ms-excel' elif file_type == 'ppt': content_type = 'application/vnd.ms-powerpoint' elif file_type == 'ico': content_type = 'image/x-icon' elif file_type == 'gif': content_type = 'image/gif' elif file_type == 'png': content_type = 'image/png' elif file_type == 'jpeg' or file_type == 'jpg': content_type = 'image/jpg' else: content_type = 'application/force-download' if download_file: header_dict['Content-disposition'] = 'attachment; filename=' + file_name header_dict['Pragma'] = 'public' header_dict['Expires'] = '0' header_dict['Cache-Control'] = 'private, must-revalidate, post-check=0, pre-check=0' header_dict['Content-Type'] = content_type + '; charset=UTF-8' header_dict['Content-Length'] = content_len if keep_connection: header_dict['Connection'] = 'keep' else: header_dict['Connection'] = 'close' for key in header_dict: header += key + ': ' + header_dict[key] + '\r\n' header += '\r\n' return header
class GamePlayer(object): processo = "zsnesw.exe" gameManager = None controladorTeclado = None populacao = [] pontosComputados = True jafezJogada = False melhorIndividuo = None def __init__(self): self.obterIndividuoExistente() sleep(3) self.gameManager = MemoryHandler(self.processo) self.controladorTeclado = keyController() self.criarPopulacaoInicial() def Player(self): individuoSelecionado = 0 while True: individuo = self.populacao[individuoSelecionado] statusJogo = self.estadoJogo() quantidadeBolasAntesJogada = self.obterQuantidadeBolas() if statusJogo == AGUARDANDO_JOGADA and self.pontosComputados: quantidadeBolasAntesJogada = self.obterQuantidadeBolas() if (individuo.jogadaAtual < QUANTIDADE_JOGADAS): self.executarJogada(individuo) else: individuo.jogadasInvalidas = LIMITEJOGADASSEMPONTO statusJogo = self.estadoJogo() if statusJogo == AGUARDANDO_JOGADA and self.pontosComputados == False: self.computarPontoIndividuo(quantidadeBolasAntesJogada, individuo) if individuo.jogadasInvalidas >= LIMITEJOGADASSEMPONTO: individuo.jogadasInvalidas = 0 individuo.fitness = individuo.fitness - 2 individuoSelecionado = individuoSelecionado + 1 print("Pula Individuo " + str(individuoSelecionado)) print("Fitness: " + str(individuo.fitness)) self.controladorTeclado.pressionar(2, 0.4) if (individuoSelecionado >= len(self.populacao)): individuoSelecionado = 0 self.gerarNovaPopulacao() def executarJogada(self, individuo): self.controladorTeclado.pressionar(1, 0.5) self.controladorTeclado.pressionar(0, 0.5) jogadaAtual = individuo.obterJogadaAtual() angulo, forca = self.obterForcaEAngulo( individuo.listaAngulos[jogadaAtual], individuo.listaForca[jogadaAtual]) self.gameManager.escreverByte(ANGULO, angulo) self.gameManager.escreverByte(FORCA, forca) sleep(0.08) self.controladorTeclado.pressionar(0, 0.5) sleep(1.1) self.pontosComputados = False while (self.estadoJogo() == EM_MOVIMENTO): sleep(0.01) def obterForcaEAngulo(self, forca, angulo): angulo_byte = angulo.to_bytes(1, byteorder="little") forca_byte = forca.to_bytes(1, byteorder="little") return forca_byte, angulo_byte def estadoJogo(self): movimento = self.gameManager.lerByte(BALL_MOVING) if movimento == 0: return AGUARDANDO_JOGADA if movimento == 1: return AGUARDANDO_TACADA if movimento == 2: return EM_MOVIMENTO def jogadasRestantes(self): jogadas_restantes = self.gameManager.lerByte(TENTATIVAS) print(jogadas_restantes) return self.gameManager.lerByte(TENTATIVAS) def obterQuantidadeBolas(self): return self.gameManager.lerByte(BOLAS_ENCACAPADAS) def computarPontoIndividuo(self, bolasAntesdaJogada, individuo): bolasDepoisJogada = self.obterQuantidadeBolas() delta = bolasDepoisJogada - bolasAntesdaJogada if (delta > 0): individuo.fitness = FATORPONTOS * delta + individuo.fitness individuo.jogadasInvalidas = 0 else: individuo.jogadasInvalidas = individuo.jogadasInvalidas + 1 self.pontosComputados = True def criarPopulacaoInicial(self): self.populacao = [] populacaoTotal = TAMANHOPOPULACAO if (self.melhorIndividuo != None): self.populacao.append(copy(self.melhorIndividuo)) populacaoTotal = populacaoTotal - 1 for i in range(0, populacaoTotal): individuo = Jogada() self.populacao.append(individuo) def gerarNovaPopulacao(self): print("Construindo nova populacao") todosZerados = True for individuo in self.populacao: if (individuo.fitness != 0): todosZerados = False if todosZerados: self.criarPopulacaoInicial() else: self.obterMelhorInividuo() self.construirNovaPopulacao() def construirNovaPopulacao(self): listaNovosIndividuos = [] for i in range(0, int(TAMANHOPOPULACAO * TAXAINDIVIDUOSPERSISTENTES)): novoIndividuo = self.crossingOver(self.populacao[i], self.melhorIndividuo) listaNovosIndividuos.append(novoIndividuo) quantidadeRestante = int(TAMANHOPOPULACAO - (TAMANHOPOPULACAO * TAXAINDIVIDUOSPERSISTENTES)) for i in range(0, quantidadeRestante): novoIndividuo = Jogada() listaNovosIndividuos.append(novoIndividuo) self.populacao = listaNovosIndividuos def obterMelhorInividuo(self): self.populacao.sort(key=attrgetter('fitness'), reverse=True) if (self.melhorIndividuo == None): self.melhorIndividuo = copy(self.populacao[0]) else: if (self.melhorIndividuo.fitness < self.populacao[0].fitness): f = open("best.txt", "w") self.melhorIndividuo = copy(self.populacao[0]) for i in range(0, len(self.melhorIndividuo.listaForca)): f.write( str(self.melhorIndividuo.listaForca[i]) + " " + str(self.melhorIndividuo.listaAngulos[i]) + "\n") print("Fitness Melhor Invidiuo: " + str(self.melhorIndividuo.fitness)) def crossingOver(self, individuoA, individuoB): novoIndividuo = Jogada() novoIndividuo.limparIndividuo() for i in range(0, QUANTIDADE_JOGADAS): percentual = random.uniform(0, 1) if (percentual > 0.5): novoIndividuo.listaAngulos.append(individuoA.listaAngulos[i]) novoIndividuo.listaForca.append(individuoA.listaForca[i]) else: novoIndividuo.listaAngulos.append(individuoB.listaAngulos[i]) novoIndividuo.listaForca.append(individuoB.listaForca[i]) mutacao = random.uniform(0, 1) if (mutacao <= TAXAMUTACAO): novoIndividuo.listaAngulos[i] = random.randint(0, 255) novoIndividuo.listaForca[i] = random.randint(0, 33) return novoIndividuo def obterIndividuoExistente(self): if (path.exists("best.txt")): f = open("best.txt", 'r') linhas = f.readlines() individuo = Jogada() individuo.limparIndividuo() for linha in linhas: forca, angulo = linha.split(' ') individuo.listaAngulos.append(int(angulo)) individuo.listaForca.append(int(forca)) self.melhorIndividuo = copy(individuo)
def __init__(self): self.obterIndividuoExistente() sleep(3) self.gameManager = MemoryHandler(self.processo) self.controladorTeclado = keyController() self.criarPopulacaoInicial()