def add_anime(): anime_data = request.get_json(force=True, silent=True) if anime_data == None: return "Bad request", 400 anime = Anime(anime_data["title"], anime_data["image"], anime_data["studio"], anime_data["episodes"], anime_data["seasons"], None) anime.save() return json.dumps(anime.to_dict()), 201
def __init__(self, client_id: str, client_secret: str): Authenticator.__init__(self, { 'client_id': client_id, 'client_secret': client_secret }) Session.__init__(self) self.anime, self.manga = Anime(), Manga()
def test_single_call_favorite(self): """ favoriteメソッドを1回だけコールして正常に登録できたかテストする """ anime_title = '日常' anime = Anime() anime.favorite(anime_title) self.assertEqual(anime_title, anime.favorite_animes[0])
def easy_to_use_anime_instance(self): """ テストで使いやすいように初期データを登録したAnimeインスタンスを返す :return Anime """ anime = Anime() for anime_title in self.easy_to_use_anime_titles: anime.favorite(anime_title) return anime
def test_least_favorite_with_nodata(self): """ お気に入りアニメリストに存在しないアニメを削除しようとしたときに例外が送出されるかテスト """ anime =Anime() with self.assertRaises(Exception) as e: anime.least_favorite('ワンピース') self.assertEqual('指定したアニメはお気に入りリストに存在しません', e.exception.args[0])
async def anime_list(session, username): global jikan if jikan is None: jikan = AioJikan(session=session) d = await jikan.user(username, "animelist", "completed") return [ Anime(x["title"], int(x["start_date"].split("-")[0])) for x in d["anime"] ]
def test_favorite_send_duplication_anime(self): """ お気に入りアニメのタイトルを重複して登録されないかテストする """ anime_title = '日常' anime = Anime() anime.favorite(anime_title) anime.favorite(anime_title) self.assertEqual(len(anime.favorite_animes), 1) self.assertEqual(anime_title, anime.favorite_animes[0])
def getAllRank(self): html = urllib.request.urlopen(self.ann_rank_url) soupRank = BeautifulSoup(html) animeList = [] for tr in soupRank.findAll('tr', {"bgcolor": "#EEEEEE"}): (rank, name, rating, _) = map(lambda w: w.contents[0], tr.findAll('td')) soupName = BeautifulSoup(str(name)) name = name.text url = (soupName.find('a', href=True)['href']) animeList.append(Anime(rank, name, rating, self.ann_base_url + url)) return animeList
def get_anime(self, library: str) -> List[Anime]: """ Loads all the shows and seasons in a library into a list of anime objects. :param library: The Plex library to look through. :return: A list of Anime objects representing the shows in the targeted library. """ anime = [] for show in self.get_shows(library): tvdb_id = show.guid.rsplit('/')[-1].split('?')[0] for season in [x for x in show.seasons() if x.title.lower() != 'specials']: watched_episodes = len([x for x in season.episodes() if x.isWatched]) anime.append(Anime(show.title, tvdb_id, str(season.seasonNumber), watched_episodes)) return anime
def parse(animeElement: Element): anime = Anime( animeId=AnimeXMLParser.parseId(animeElement), title=AnimeXMLParser.parseTitle(animeElement), mediaType=AnimeXMLParser.parseMediaType(animeElement), genres=AnimeXMLParser.parseGenres(animeElement), themes=AnimeXMLParser.parseThemes(animeElement), vintage=AnimeXMLParser.parseVintage(animeElement), summary=AnimeXMLParser.parseSummary(animeElement), cast=AnimeXMLParser.parseCast(animeElement), staff=AnimeXMLParser.parseStaff(animeElement), companies=AnimeXMLParser.parseCompany(animeElement), averageRating=AnimeXMLParser.parseAverageRating(animeElement), totalVotes=AnimeXMLParser.parseTotalVotes(animeElement) ) return anime
def getRecommendations(userId): url = 'https://stateless.pythonanywhere.com/animewebapi/recommendations?userId=' + str( userId) response = session.get(url) response.raise_for_status anime = [] animejson = response.json()['anime'] for a in animejson: anime.append( Anime(a['title'], a['japaneseTitles']['romaji'], a['japaneseTitles']['native'], a['description'], a['score'], a['links']['anilist'], a['links']['mal'], a['image'])) return anime
async def anime_list(session, username): async with session.post("https://graphql.anilist.co", json={ "query": q, "variables": { "userName": username } }) as resp: d = await resp.json() o = [] for l in d["data"]["MediaListCollection"]["lists"]: if l["name"] == "Completed": for entry in l["entries"]: o.append( Anime(entry["media"]["title"]["romaji"], entry["media"]["startDate"]["year"], entry["media"]["title"]["english"])) return o
def getAnime(animeId): url = 'https://stateless.pythonanywhere.com/anilist/anime?id=' + str( animeId) response = session.get(url, timeout=4) response.raise_for_status animejson = response.json()['anime'] if animejson: anime = Anime(animejson['title'], animejson['japaneseTitles']['romaji'], animejson['japaneseTitles']['native'], animejson['description'], animejson['score'], animejson['links']['anilist'], animejson['links']['mal'], animejson['image'], animeId) return anime return None
def index(status=None): add = Watch(request.form) if request.method == 'GET' and status: return redirect('/') if request.method == 'POST' and add.validate(): anime = Anime(add.name.data, add.subber.data, add.format.data, add.quality.data, add.email.data) anime.save() flash(''' You are now watching [{0}] {1}. To unwatch this click <a href="/unsubscribe/{2}">here</a>. '''.format(add.subber.data, add.name.data, anime.h)) return redirect('/success') return render_template('index.html', title='Watch My Anime', form=add, status=status)
def main(args): r_list = [[12, 11, 5, 3], [17, 7, 5, 3]] anim = False n_tests = 50 # liczba testów opt_cnt = 0 # licznik światów, w których została znaleziona trasa najbardziej optymalna fail_cnt = 0 # licznik światów, w których nie udało się znaleźć trasy mean_exc = 0 # średnia bezwzględna nadmiarowość trasy random_seed = 1 for i in range(n_tests): w = Wourld(r_list, random_seed) w.combine2Rooms() w.calcTargets() agent = Agent(w.agent_start_point, w.targets) if not agent.backtracking_algorithm(w): print(i, w.shortest_route, "NIE UDAŁO SIĘ ZNALEŹĆ ŚCIEŻKI") fail_cnt = fail_cnt + 1 else: if not agent.backtracking_algorithm(w): print(i, w.shortest_route, "NIE UDAŁO SIĘ ZNALEŹĆ ŚCIEŻKI") fail_cnt = fail_cnt + 1 else: track = agent.track[0] + agent.track[1] len_track = len(track) # iteration, Shortest track,robot track if len_track == w.shortest_route: opt_cnt = opt_cnt + 1 print(i, w.shortest_route, len(track)) mean_exc = mean_exc + len_track - w.shortest_route if anim: anime = Anime(w, agent, 'm') input() random_seed = random_seed + 1 mean_exc = mean_exc / n_tests print("- liczba testów: ", n_tests) print("- liczba tras najbardziej optymalnych: ", opt_cnt) print("- liczba tras nieznalezionych: ", fail_cnt) print("- średni współczynnik bezwzględnej nadmiarowości tras: ", mean_exc) return 0
def add_anime(self, title: str, data: dict[str, Union[str, list[str]]]) -> None: """Add an anime into this graph """ if title not in self._anime: self._anime[title] = Anime(data)
def game(): group = pygame.sprite.Group() player_anim = Anime(group, (228, 288)) board = Board.load_map(None, name) board.set_view(30, 30, 30) lst = [] if sum(board.hero[0]): player = Player(screen, player_anim, board, board.hero[0]) player_anim.resize(30) if sum(board.hero[1]): tverdolobiy = Tverdolobiy(group, board.hero[1], board, player) tverdolobiy.resize(30) lst.append(tverdolobiy) if sum(board.hero[2]): merzopakostniy = Merzopakostniy(group, board.hero[2], board, player) merzopakostniy.resize(30) if sum(board.hero[3]): legushka = Legushka(group, board.hero[3], board, player) legushka.resize(30) lst.append(legushka) running = True c = 0 while running: c += 1 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN: board.get_click(event.pos) if event.type == pygame.KEYDOWN: if event.key in up: player.set_dir('up') if event.key in down: player.set_dir('down') if event.key in left: player.set_dir('left') if event.key in right: player.set_dir('right') if event.key == pygame.K_LEFT: player.set_dir('left') if event.key == pygame.K_RIGHT: player.set_dir('right') if event.key == pygame.K_UP: player.set_dir('up') if event.key == pygame.K_DOWN: player.set_dir('down') screen.fill((0, 0, 0)) board.render() if not len(board.check_points): board.check_points.add(None) if not board.are_left(): board.reset() player.move([]) player_anim.rect.x, player_anim.rect.y = player.x, player.y if sum(board.hero[2]): merzopakostniy.move() if not c % 2: if sum(board.hero[3]): legushka.move() if sum(board.hero[1]): tverdolobiy.move() group.draw(screen) if c % 20 == 0: player_anim.update() if sum(board.hero[2]): check = Check(player, merzopakostniy.num_bomb() + lst) elif sum(board.hero[0]): check = Check(player, lst) if check.checkaed(): running = False draw(str(len(board.check_points) - 1 + board.count)) pygame.display.flip() Finish(group, str(len(board.check_points) - 1 + board.count))
def __init__(self): global game_exit global mute team1 = 'black' team2 = 'white' drag = False isSockOn = 'AI' if len(sys.argv) > 2: isSockOn = sys.argv[2] if len(sys.argv) > 1: team2 = sys.argv[1] if sys.argv[1] == 'black': team1 = 'white' chess_board = Board(team2) chess_board.set_template('wood') m = Move() m.start() t = Tim() t.start() animation = Anime(chess_board) animation.start() flag_move = 0 history = [] possible_move = [] chess_board.draw_board() chess_board.draw_piece() p1 = Player(team1) p2 = Player(team2) p1.set_type(isSockOn) if (team2 == 'black'): Move.player_team = 'w' threading.Thread(target=p1.move).start() p1.next_round() p2.next_round() while not game_exit: chess_board.draw_board() t.show() for event in pygame.event.get(): if event.type == pygame.QUIT: game_exit = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_m: if Sound.mute == False: Sound.mute = True else: Sound.mute = False if event.key == pygame.K_r: chess_board.reset_board(team2) history = [] t.reset() p1.next_round() p2.next_round() algorithm.check = False elif event.key == pygame.K_q: game_exit = True elif event.key == pygame.K_z and len(history) > 0: pos = history.pop( ) #TO DO : this part use to reverse move (undo move) elif event.type == pygame.MOUSEBUTTONDOWN: possible_move = [] animation.set_type() if animation.type and p2.can_move( ) and p2.team[0] == animation.type[0]: animation.drag_init() history.append(animation.position) m.set_value(str(animation.type), animation.position) if not algorithm.check: possible_move = m.possible_moves() if animation.type == 'b_king': possible_move = m.possible_moves() animation.type = m.name animation.highlight_possible_move(possible_move) drag = True elif event.type == pygame.MOUSEBUTTONUP: move_done = animation.drag_done( possible_move) # check if is it possible to move if not move_done and len(history) > 0: history.pop() possible_move = [] if move_done: algorithm.check = False if isSockOn == "SOCKET": so = sock() so.send() so.close() p1.next_round() p2.next_round() drag = False if drag: animation.highlight_possible_move(possible_move) if not drag: animation.highlight(pygame.mouse.get_pos()) chess_board.draw_piece() if drag: # i check drag two time beacuse if i merge them then in the result the draged piece show under enemy solder animation.drag( pygame.mouse.get_pos() ) # in the other hand if i create piece first the highlight will stay on piece so player cant see piece if (p1.can_move()): threading.Thread(target=p1.move).start() p1.next_round() p2.next_round() if algorithm.check: pygame.draw.rect(screen, RED, (100 * algorithm.king_X_pos, 100 * algorithm.king_Y_pos, 100, 100), 5) pygame.display.flip() clock.tick(40) pygame.quit()
if not any(character in x for x in json[anime]['characters']): json[anime]['characters'].append( {character: { 'quotes': [], 'image': img }}) for i in json[anime]['characters']: character_json = i if character in i: # print(type(tags.split(','))) q = Quote(html_quote, tags.split(','), 0, 0) i[character]['quotes'].append(q) ANIME = [] for anime_name in json: # print(json[anime_name]['image']) anime = Anime(anime_name, json[anime_name]['image'], [], 0) for char in json[anime_name]['characters']: for character_name in char: quotes = char[character_name]['quotes'] image = char[character_name]['image'] character = Character(character_name, image, quotes, 0) anime.set_characters(character) ANIME.append(anime) with open('db.pickle', 'wb') as db: pickle.dump(ANIME, db)
def parse_anime(soup, write_image=False) -> Anime: ''' Данная функция производит парсинг страницы аниме с сайта world-art; на вход принимается объекта типа BeautifulSoup, установленный на корень страницы, на выходе выдаётся заполненный объект Anime; ''' # object to fill anime = Anime( name='', fields={ 'engname': { 'hint': 'Название', 'tr': null }, 'genre': { 'hint': 'Жанр', 'tr': genre_parse }, 'target': { 'hint': 'Целевая аудитория', 'tr': null }, 'type': { 'hint': 'Тип', 'tr': type_parse }, 'base': { 'hint': 'Основа', 'tr': null }, 'season': { 'hint': 'Сезон', 'tr': season_parse }, 'director': { 'hint': 'Режиссёр', 'tr': null }, 'score': { 'hint': 'Средний балл', 'tr': score_parse }, 'voted': { 'hint': 'Проголосовало', 'tr': voted_parse }, 'rating': { 'hint': 'Место в рейтинге', 'tr': rating_parse }, }, tags={ # 'tagname' : { # 'desc' : 'description...', # 'score' : float # } }, annotation=None, coms=[]) # get name namesoup = soup.find(lambda tag: tag.name == 'font' and tag.has_attr( 'size') and tag['size'] == '5') if namesoup is None: return None anime.name = namesoup.text # fields table = (soup.body.center.find_all('table')[6].tr.td.table.tr.contents[4]. find_all('table')[1].find_all('tr')[1].contents[2]) for f in anime.fields: tag = table.find(lambda tag: re.match(anime.fields[f][ 'hint'], tag.text) is not None and tag.b is not None and tag.b.text .startswith(anime.fields[f]['hint'])) if tag is None: anime.fields[f] = None else: anime.fields[f] = anime.fields[f]['tr']( tag.find_all('td')[2].text.strip()) if anime.fields['season'] is None: tag = table.find(lambda tag: re.match('Выпуск', tag.text) is not None) if tag is not None: anime.fields['season'] = date_parse( tag.find_all('td')[2].text.strip()) else: tag = table.find( lambda tag: re.match('Премьера', tag.text) is not None) if tag is not None: anime.fields['season'] = date_parse( tag.find_all('td')[2].text.strip()) # tags for tag in soup.select('.newtag'): anime.tags[tag.a.text] = { 'desc': tag.a['title'], 'score': float(tag.font.text) } # annotation try: anime.annotation = (soup.center.find_all( 'table')[6].tr.td.table.tr.contents[4].contents[14].tr.td.p) if (anime.annotation.text.strip( ) == "Для этого аниме есть описание (1), но вы можете написать ещё одно." ): anime.annotation = None else: anime.annotation = anime.annotation.prettify() except: pass # comments try: anime.coms = [None, None, None] bestcoms = soup.find( lambda tag: tag.text.strip() == 'Лучшие отзывы на это аниме') t = nsib(bestcoms, 5) anime.coms[0] = t.p.prettify() t = nsib(t, 6) anime.coms[1] = t.p.prettify() t = nsib(t, 6) anime.coms[2] = t.p.prettify() except: pass if not write_image or anime.fields['rating'] in [1233, 3016, 3334]: return anime rt = str(anime.fields['rating']) fname = '0' * (4 - len(rt)) + rt + '. ' + anime.name fname = re.sub(r'/', '|', fname) src = soup.find(lambda tag: tag.name == 'img' and tag.has_attr('alt') and tag['alt'].startswith('постер аниме'))['src'] content = None while content is None: content = req.get(src).content if content.startswith('<html>'.encode()): content = None time.sleep(0.1) with open('images/' + fname + re.search(r'(\.\w+)$', src).group(1), 'wb') as file: file.write(content) return anime
def __init__(self): self.load_config() self.anime = Anime(self.cache_dir) self.downloader = Subscribe(self.list_path, self.cache_dir, self.aria2_url, self.aria2_dir)