def read_configuration(): global messages, users, dwld_dir if DOCKER_MODE == 1: users = file_operations.read_file("/src/users.txt") else: users = file_operations.read_file("users.txt") return
def list_movies(self, store_type="f"): """ Function created to delete registers of movies from a json file or from database :param store_type: store_type: db (database) or f (file). By default it considers db (database). :return: True of False """ if store_type.lower() == "f": file = file_operations.read_file("Movie_Registration.json") result_list = self._create_dataframe_list(file) else: with DatabaseConnection(self.path_db) as cursor: cursor.execute("select * from tb_movies") movies = cursor.fetchall() # creates the same structure that the json file has and create the dataframe list_movies = [] for row in movies: row_dict = {} row_dict["movie_name"] = row[0] row_dict["director_name"] = row[1] row_dict["movie_year"] = row[2] row_dict["name_main_actor_actress"] = row[3] row_dict["read"] = row[4] list_movies.append(row_dict) result_list = self._create_dataframe_list(list_movies) return result_list
def get_time_session(timetable_file): timetable = file_operations.read_file(timetable_file) time_numsession_dict = {} for line in timetable: time = line.split(" ")[0] numsession = line.split(" ")[-1] time_numsession_dict[time] = numsession return time_numsession_dict
def help_move(userId, moveText): parties = read_file('parties.txt') move = find_move_flavor_text(moveText) if not move: return 'That is not a valid move' else: return move
def party_view(userId): parties = read_file('parties.txt') for p in parties: party = party_parser(p) if (party['userId'] == str(userId)): return f'Your current party is {party["pokemonName"]} with the moveset {find_move_names(party["pokemon"]["moves"])}' return 'Your party is empty!'
def delete(userId, opponentId): duels = read_file("duels.txt") file = [] for d in duels: splitDuel = d.split("[:]") if splitDuel[0] != (str(userId) or str(opponentId)) and splitDuel[2] != ( str(userId) or str(opponentId)): file.append(d) save_file("duels.txt", file)
def get_temp(userId, opponentId): temp = read_file('temp.txt') for line in temp: split_line = line.split('[:]') if (str(userId) == split_line[0] and str(opponentId) == split_line[3]) or (str(userId) == split_line[3] and str(opponentId) == split_line[0]): return temp_parser(line) return None
def fight(userId, fightingId, move): parties = read_file('parties.txt') userParty = None fightingParty = None for p in parties: party = party_parser(p) if party['userId'] == str(userId): userParty = party if party['userId'] == str(fightingId): fightingParty = party
def party_abandon(userId): parties = read_file('parties.txt') file = [] for party in parties: split_party = party.split('[:]') if split_party[0] != str(userId): file.append(party) save_file('parties.txt', file) return f'<@!{userId}> Successfully abandoned your party'
def read_configuration(): global messages, imap_users, smtp_users if DOCKER_MODE == 1: smtp_users = file_operations.read_file("/src/smtp_users.txt") imap_users = file_operations.read_file("/src/imap_users.txt") messages = file_operations.read_file("/src/messages.txt") else: smtp_users = file_operations.read_file("smtp_users.txt") imap_users = file_operations.read_file("imap_users.txt") messages = file_operations.read_file("messages.txt") return
def forbidden_profile(profile_id): """Проверка на то, является ли профиль запрещенным (если отослать на него письмо, то наш аккаунт заблочат) Keyword arguments: profile_id -- ID профиля которому будет отправлено сообщение """ # Собираем информацию о профиле data = collect_info_from_profile(profile_id) # Якорные слова которые обозначают профиль как ловушку anchor_words = read_file("anchor_words.csv").splitlines()[1:] # ищем якоря в DESCRIPTION for anchor in anchor_words: if anchor in data["Description"]: return True # Если нету, то False return False
def party_add(userId, pokemonName): pokemon = find_pokemon(pokemonName.lower()) if pokemon != None: parties = read_file('parties.txt') for party in parties: split_party = party.split('[:]') if (split_party[0] == str(userId)): return f'<@!{userId}> You already have a party, you must abandon it to create a new one!' parties.append(f'{userId}[:]{pokemonName}[:]{pokemon}\n') save_file('parties.txt', parties) return f'Adding {pokemonName} to your party! Your move set will be {find_move_names(pokemon["moves"])}' else: return 'Could not find that pokemon, also note that only gen 1 is allowed'
def _write_movie_file(self, content, type_operation, filename="Movie_Registration.json"): """ Private function created to write into a Movie's json file :param content, type_operation, filename: Content is a dataset with Movie's data type_operation is the type of operation: "a" (to add data) or other to overwrite. filename by default considers "Movie_Registration.json". :return: True of False """ file = file_operations.read_file(filename) if type_operation.lower() == "a": file.append(content) else: file = content if file == []: return False else: check_save_file = file_operations.save_to_file(file, filename, "o") return check_save_file
def _delete_movie_file(self, movie_name, filename="Movie_Registration.json"): """ Private function created to write into a Movie's json file :param movie_name, filename: movie_name desired to be deleted. filename by default considers "Movie_Registration.json". :return: True of False """ file = file_operations.read_file(filename) movie_found = 0 for row in file: if row["movie_name"].lower() == movie_name.lower(): file.remove(row) movie_found = 1 if movie_found == 1: result = self._write_movie_file(file, "o") else: result = False return result
def _apply_read_movie_file(self, movie_name, filename="Movie_Registration.json") -> bool: """ Private function created to read from Movie's json file :param movie_name, filename: movie_name desired to be deleted. filename by default considers "Movie_Registration.json". :return: True of False """ file = file_operations.read_file(filename) row_position = 0 movie_found = 0 for row in file: if row["movie_name"].lower() == movie_name.lower(): file[row_position]["read"] = 1 movie_found = 1 row_position += 1 if movie_found == 1: result = self._write_movie_file(file, "r") else: result = False return result
def read_configuration(): global messages, users, livestr_site_list, intranet_http_site_list, intranet_https_site_list, tapas_dir if DOCKER_MODE == 1: intranet_http_site_list = file_operations.read_file( "/src/http_websites.txt") intranet_https_site_list = file_operations.read_file( "/src/https_websites.txt") livestr_site_list = file_operations.read_file("/src/livestr.txt") tapas_dir = "/src" else: intranet_http_site_list = file_operations.read_file( "{0}/src/http/http_websites.txt".format(HOME_DIR)) intranet_https_site_list = file_operations.read_file( "{0}/src/http/https_websites.txt".format(HOME_DIR)) livestr_site_list = file_operations.read_file( "{0}/src/http/livestr.txt".format(HOME_DIR)) tapas_dir = "{0}/src/http".format(HOME_DIR) return
PASCAL_OPERATORS = [ '+', '-', '*', '/', '%', # Arithmetic Operators '=', '<>', '>', '<', '>=', '<=', '><', # Relational Operators '&', '|', '!', '~', '<<', '>>', # Bit Operators ':=', ';', 'and', 'and then', 'or', 'or else', 'not' # Boolean Operators ] def single_operator_in_line(text, operators=PASCAL_OPERATORS): output = text for operator in operators: if operator in text: output = sub(r'{}'.format(escape(operator)), '\g<0>\n', output) return output if __name__ == '__main__': from file_operations import create_output_folder, read_file, write_to_file file_path = argv[1] file_name = os.path.basename(file_path) output_folder_path = '{}/output'.format(os.path.dirname(os.path.realpath(__file__))) create_output_folder(output_folder_path) text = single_operator_in_line(read_file(file_path)) write_to_file(output_folder_path, file_name, text)
def get_website(): if DOCKER_MODE == 1: website_list = fifo.read_file("/src/websites.txt") else: website_list = fifo.read_file("websites.txt") return website_list
def save_temp(userId, speed, effect, opponentId): temp = read_file('temp.txt') temp.append(f'{userId}[:]{speed}[:]{effect}[:]{opponentId}') save_file('temp.txt', temp)
def duel(userId, opponentId, level): if userId == opponentId: return "You cant duel yourself, stupid, dumb, white, idiot" parties = read_file("parties.txt") userParty = None opponentParty = None for p in parties: party = party_parser(p) if party["userId"] == userId: userParty = party elif party["userId"] == opponentId: opponentParty = party print(userParty) if userParty is None: return f'<@!{userId}>, you do not have a party' elif opponentParty is None: return f"<@!{opponentId}>, you do not have a party" duels = read_file('duels.txt') for d in duels: split_duel = d.split('[:]') if (split_duel[0] == str(userId)) and split_duel[2] == str(opponentId): return "You already got a battle with this fella!" userParty['pokemon']['stats'] = { 'hp': calculate_health(userParty['pokemon']['stats']['hp'], level), 'attack': calculate_stat(userParty['pokemon']['stats']['attack'], level), 'defense': calculate_stat(userParty['pokemon']['stats']['defense'], level), 'special-attack': calculate_stat(userParty['pokemon']['stats']['special-attack'], level), 'special-defense': calculate_stat(userParty['pokemon']['stats']['special-defense'], level), 'speed': calculate_stat(userParty['pokemon']['stats']['speed'], level), } opponentParty['pokemon']['stats'] = { 'hp': calculate_health(opponentParty['pokemon']['stats']['hp'], level), 'attack': calculate_stat(opponentParty['pokemon']['stats']['attack'], level), 'defense': calculate_stat(opponentParty['pokemon']['stats']['defense'], level), 'special-attack': calculate_stat(opponentParty['pokemon']['stats']['special-attack'], level), 'special-defense': calculate_stat(opponentParty['pokemon']['stats']['special-defense'], level), 'speed': calculate_stat(opponentParty['pokemon']['stats']['speed'], level), } duels.append( f'{userId}[:]{userParty["pokemon"]}[:]{opponentId}[:]{opponentParty["pokemon"]}[:]{level}' ) save_file("duels.txt", duels) return "Duel!"
import file_operations # from file_operations import save_to_file, read_file file_operations.save_to_file('Rolf', 'data.txt') name = file_operations.read_file('data.txt') print(name)
def get_website(link_file): website_list = fifo.read_file(link_file) return website_list
import os from re import sub, findall from sys import argv def convert_ascii(match): return chr(int(match.group(1))) def string_consts_to_file(text): output = sub(r'(?<!\'{1})\'\s*\+\s*\'', '', text) output = sub(r'\'\s*#(\d+)\s*\'', convert_ascii, output) output = findall('(?<=\').*(?=\')', output) return '\n'.join(output) if __name__ == '__main__': from file_operations import create_output_folder, read_file, write_to_file file_path = argv[1] file_name = os.path.basename(file_path) output_folder_path = '{}/output'.format( os.path.dirname(os.path.realpath(__file__))) create_output_folder(output_folder_path) text = string_consts_to_file(read_file(file_path)) write_to_file(output_folder_path, file_name, text)
def executeMove(moveText, defenderId, userId): duels = read_file("duels.txt") defender = None attacker = None effects = [] for d in duels: selected_duel = duel_parser(d) if selected_duel["userId"] == userId and selected_duel[ "opponentId"] == defenderId: attacker = selected_duel["userPokemon"] defender = selected_duel["opponentPokemon"] elif selected_duel["userId"] == defenderId and selected_duel[ "opponentId"] == userId: attacker = selected_duel["opponentPokemon"] defender = selected_duel["userPokemon"] move = None moves = attacker["moves"] for m in moves: print(m["name"]) if moveText == m["name"]: move = m if move is None: return "That is not a valid move, fool" if move["pp"] == 0: return f"<@!{userId}> has no pp, zero" move["pp"] = int(move["pp"]) - 1 accuracy = move["accuracy"] if random.randint(0, 100) >= accuracy: save_temp(userId, 0, [], defenderId) return "You missed your attack" power = move["power"] moveType = move["type"] attackerLevel = attacker["level"] attackingStat = attacker["stats"]["attack"] specialAttackingStat = attacker["stats"]["special-attack"] attackerTypeList = attacker["types"] defendingAttack = defender["stats"]["defense"] defendingSpecialAttack = defender["stats"]["special-defense"] defendingTypesList = defender["types"] damageType = move["damage_class"]["type"] rightHalf = None for element in move["stat_changes"]: statChange = element["change"] if statChange > 0: effects.append({ "action": element["name"], "target": "self", "change": statChange }) #statusMove(attacker,statChange,element["name"]) elif statChange < 0: effects.append({ "action": element["name"], "target": "opponent", "change": statChange }) # statusMove(attacker,statChange,element["name"]) if damageType == "status": return "You did status" if damageType == "physical": rightHalf = rightHalfEquation(attackingStat, defendingAttack, power) elif damageType == "special": rightHalf = rightHalfEquation(specialAttackingStat, defendingSpecialAttack, power) finalModifier = modifier(moveType, attackerTypeList, (random.randint(85, 100)) / 100, move["damage_class"]["relations"], defendingTypesList) print(attackerLevel, rightHalf, finalModifier) damage = -round( ((((((2 * attackerLevel) / 5) + 2) * rightHalf) / 50) + 2) * finalModifier, 2) print("Took", damage, "points of damage") print(move["pp"]) effects.append({"action": "hp", "target": "opponent", "change": damage}) speed = attacker["stats"]["speed"] var = get_temp(userId, defenderId) moveList = "" if var is not None: if int(speed) > int(var["speed"]): for effect in effects: if effect["target"] == "self": if effect["action"] in attacker["stats"]: attacker["stats"][effect["action"]] += round( effect["change"], 2) else: move[effect["target"]] += round(effect["change"], 2) moveList = moveList + f'<@!{userId}> increased their {effect["action"]} by {effect["change"]}\n' else: if effect["action"] in defender["stats"]: defender["stats"][effect["action"]] += round( effect["change"], 2) moveList = moveList + f'<@!{userId}> decreased <@!{defenderId}>\'s {effect["action"]} by {effect["change"]}\n' for effect in var["effects"]: if effect["target"] == "self": if effect["action"] in defender["stats"]: defender["stats"][effect["action"]] += round( effect["change"], 2) moveList = moveList + f'<@!{defenderId}> increased their {effect["action"]} by {effect["change"]}\n' else: if effect["action"] in attacker["stats"]: attacker["stats"][effect["action"]] += round( effect["change"], 2) moveList = moveList + f'<@!{defenderId}> decreased <@!{userId}>\'s {effect["action"]} by {effect["change"]}\n' else: for effect in var["effects"]: if effect["target"] == "self": if effect["action"] in defender["stats"]: defender["stats"][effect["action"]] += round( effect["change"], 2) moveList = moveList + f'<@!{defenderId}> increased their {effect["action"]} by {effect["change"]}\n' else: if effect["action"] in attacker["stats"]: attacker["stats"][effect["action"]] += round( effect["change"], 2) moveList = moveList + f'<@!{defenderId}> decreased <@!{userId}>\'s {effect["action"]} by {effect["change"]}\n' for effect in effects: if effect["target"] == "self": if effect["action"] in attacker["stats"]: attacker["stats"][effect["action"]] += round( effect["change"], 2) moveList = moveList + f'<@!{userId}> increased their {effect["action"]} by {effect["change"]}\n' else: if effect["action"] in defender["stats"]: defender["stats"][effect["action"]] += round( effect["change"], 2) moveList = moveList + f'<@!{userId}> decreased <@!{defenderId}>\'s {effect["action"]} by {effect["change"]}\n' temp = read_file('temp.txt') file = [] for t in temp: split_temp = t.split('[:]') if split_temp[0] != (str(userId) or str(defenderId)) and split_temp[3] != ( str(userId) or str(defenderId)): file.append(t) save_file('temp.txt', file) else: save_temp(userId, speed, effects, defenderId) return "mover recorded good sir" update_file( "duels.txt", f'{userId}[:]{attacker}[:]{defenderId}[:]{defender}[:]{attackerLevel}') if int(attacker["stats"]["hp"]) <= 0: moveList = moveList + f'<@!{userId}> fainted! <@!{defenderId}> is the winner with {defender["stats"]["hp"]} remaining!!' delete(userId, defenderId) elif int(defender["stats"]["hp"]) <= 0: moveList = moveList + f'<@!{defenderId}> fainted! <@!{userId}> is the winner with {attacker["stats"]["hp"]} remaining!!' delete(userId, defenderId) else: moveList = moveList + f'<@!{userId}>\'s health is {attacker["stats"]["hp"]} and <@!{defenderId}>\'s health is {defender["stats"]["hp"]}' return moveList