def test_add(self): b1 = bag.Bag(1, 2, 3) b2 = bag.Bag(4, 5, 6) b3 = b1 + b2 self.assertIn(1, b3) self.assertIn(4, b3) self.assertEqual(len(b3), 6)
def parse_pages(start_page, pages, debug, sql_table, creds, proxy_pass): import url parse_page = url.Url(start_page) first_page = html_page.HtmlPage(parse_page.get_url()) html = first_page.get_html(creds, proxy_pass) if html: soup = BeautifulSoup(html, 'html.parser') # 1st page arts_dict = {} for i in soup.findAll('div', class_="j-card-item"): art_num = re.search(r'\d+', i.get('data-popup-nm-id')) arts_dict[art_num[0]] = i.find('a')['href'] for art, link in arts_dict.items(): if not sql_table.table_check_presence(art, creds[6]): handbag = bag.Bag() if not link.startswith('https'): link = "https://www.wildberries.ru" + link handbag.get_bag_page(art, link, debug, creds, proxy_pass) sql_table.table_append(handbag) sql_table.cnx.commit() # after 1st page if parse_page.check_key('page'): return 0 parse_page.add_key('page', '1') # 2nd page and further for i in range(2, pages + 1): parse_page.change_key('page', str(i)) print(parse_page.get_url()) have_a_try = 3 if have_a_try: further_page = html_page.HtmlPage(parse_page.get_url()) arts_dict = further_page.get_wb_page(creds, proxy_pass) if arts_dict: for art, url in arts_dict.items(): if not sql_table.table_check_presence(art, creds[6]): handbag = bag.Bag() handbag.get_bag_page(art, url, debug, creds, proxy_pass) sql_table.table_append(handbag) sql_table.cnx.commit() continue else: sql_table.cnx.commit() print(f"Page {str(i)} parse error. Trying again.") have_a_try -= 1 else: sql_table.cnx.commit() print(f"No luck. Next page.")
def testRun(): firstTurn = True theBag = bag.Bag() theBoard = board.Board(15, (7, 7)) boardY = 7 for boardX in range(4, 11): testTile = tile.Tile("A", 1) theBoard.squares[boardY][boardX] = ( testTile, theBoard.squares[boardX][boardY][1]) theBoard.squares[boardY][boardX][0].locked = True printBoard(theBoard) players = [] h = heuristic.notEndGameHeuristic(heuristic.tileQuantileHeuristic( 0.1, 1.0)) players.append(ai.AI(theBoard, theBag, theHeuristic=h, theDifficulty=10.0)) active = 0 print "OK" #calculate the move rack = "SERPENT" max = 9 for x in range(0, 1000000): players[active].tray = setTray(rack) playedMove = players[active].executeTurn(firstTurn) #play that move.. if it played success = players[active].play(firstTurn) #printBoard(theBoard) firstTurn = False
def test_len(self): b = bag.Bag() self.assertEqual(len(b), 0) b.add(1) self.assertEqual(len(b), 1)
def verify_hash(self, hash): """Returns True iff the hash passes a basic test (based on general requirements for pathways) This method is used for pruning the search tree. """ if ( self.pruning_method == 'PP' ): # this method has the same assumptions as Melendez-Hevia's paper about the pentose phosephate cycle for (nodes, bonds) in parse_hash( hash): # check each of the molecules in the hash node_bag = bag.Bag() for atom in nodes: (base_atom, valence, hydrogens, charge, chirality) = parse_atom(atom) node_bag[base_atom] += 1 if (node_bag['C'] in [1, 2]): # this is a 1 or 2 carbon sugar - invalid! return False elif (node_bag['C'] > 0 and node_bag['PO3'] == 0): # this is a unphosphorylated sugar - invalid! return False elif (node_bag['C'] == 0 ): # this is not a sugar (might be PO3 or H2O) - valid! pass else: # this is a phosphorylated sugar with at least 3 carbons - valid! pass return True
def merge(bagfile_in, bagfile_out, start=None, end=None, topic_set=None): """ merge rosbags into one """ print(topic_set) bag_out = rosbag.Bag(bagfile_out, True) if bag_out is not None: for bag in bagfile_in: bag_in = rosbag.Bag(bag) for topic, msg, msgtype, t in bag_in.read_messages( [tp for tp in topic_set]): if start is not None and t / 1e9 < start: continue if end is not None and t / 1e9 > end: continue bag_out.write(topic, msg, msgtype, raw=True, t=t) bag_in.close()
def test_pop(self): # also test init... b = bag.Bag(1, 2, 3, 4) self.assertIn(b.pop(), (1, 2, 3, 4)) self.assertIn(b.pop(), (1, 2, 3, 4)) self.assertIn(b.pop(), (1, 2, 3, 4)) self.assertIn(b.pop(), (1, 2, 3, 4))
def test_push(self): b = bag.Bag() b.add(1) b.add(2) b.add(3).add(4) self.assertIn(b.pop(), (1, 2, 3, 4)) self.assertIn(b.pop(), (1, 2, 3, 4)) self.assertIn(b.pop(), (1, 2, 3, 4)) self.assertIn(b.pop(), (1, 2, 3, 4))
def test_iter(self): b = bag.Bag(1, 2, 3, 4, 5) l = list(b) l.sort() self.assertListEqual(l, [1, 2, 3, 4, 5]) for i in b: self.assertIn(i, (1, 2, 3, 4, 5))
def game(amount_player_human, amount_player_computer): print('Начинаем игру') list_players = [] for n_player in range(amount_player_human): player = pl.HumanPlayer(f'{n_player+1}') list_players.append(player) for n_player in range(amount_player_computer): player = pl.ComputerPlayer(f'{n_player+1}') list_players.append(player) random.shuffle(list_players) print() print( 'Внимание!!! Порядок ходов игроков задается сейчас в произвольном порядке' ) print() print('Игроки и их карточки:') for player in list_players: player.print_card() print() bag = bg.Bag() print() print('*** ПОЕХАЛАЛИ ***') print() while True: barrel = bag.get_barrel() if barrel is None: print('Бочонков больше нет. Игра окончена') return print( f'Новый бочонок: {barrel.get_num()} (осталось {bag.get_count()})') for player in list_players: player.print_card() print() for player in list_players: ret = player.ask_for_barrel(barrel, delegate_ask) if not ret: print(f'{player.name} - ошибка. Вы проиграли Игра Окончена') return if player.is_winner(): print(f'{player.name} - Вы выиграли') return print() print('*** следующий раунд ***') print()
def __init__(self, slots): """ :param slots: eg. ["left_hand", "right_hand", "head"] :return: """ self._bag = bag.Bag(len(slots)) self._name2index = {} self._index2name = slots for i in range(len(slots)): self._name2index[slots[i]] = i
def test_repr(self): b = bag.Bag() self.assertEqual(repr(b), 'bag.Bag()') b.add(1) self.assertEqual(repr(b), 'bag.Bag(1)') b.add(2) self.assertEqual(repr(b), 'bag.Bag(1, 2)') b.add(b) self.assertEqual(repr(b), 'bag.Bag(1, 2, ...)')
def compute_motifs(max_size): motifs_bag = bag.Bag() for compound in sorted(compound2graph.keys()): graph = compound2graph[compound] if (check_nodes_and_bonds(graph)): motifs = gather_motifs(graph, max_size) motifs_bag.update(motifs) # DEBUG info #print >> debug_file, compound #for motif in motifs: # print >> debug_file, motif return motifs_bag._data
def __init__(self, screen): self.m_bag = bag.Bag() # Loads the images self.menu_image = pygame.image.load( "resc\images\menu_screens\g_menu.png") self.cursor = pygame.image.load( "resc\images\menu_screens\m_cursor.png") self.pokemon_menu_image = pygame.image.load( "resc\images\menu_screens\m_pokemon.png") self.pokemon_bag_image = pygame.image.load( "resc\images\menu_screens\m_bag.png") # Assigns the screen self.screen = screen # Gets dimensions of screen menu and cursor self.screen_width, self.screen_height = pygame.display.get_surface( ).get_size() self.image_width, self.image_height = self.menu_image.get_rect().size self.cursor_width, self.cursor_height = self.cursor.get_rect().size # Places cursor on screen self.cursor_x, self.cursor_y = (self.screen_width - self.image_width) + 32, 40 self.bag_cursor_x, self.bag_cursor_y = (98 * 4 - (9 * 4), 48) # Amount of options in the menu (for knowing where the cursor is) self.text_items = 3 # The main menu loop self.run_menu = True # The pokemon menu and bag menu loops self.run_pokemon_menu = False self.run_bag_menu = False # The amount of items in your bag self.items_in_bag = [] # Adds pokeballs and potions to your bag self.items_in_bag.append("POTION x " + str(self.m_bag.get_potions())) self.items_in_bag.append("POKe BALL x " + str(self.m_bag.get_pokeballs())) #print self.items_in_bag[0] # Amount of potions and pokeballs in your bag self.potions = 0 self.pokeballs = 0 self.pokemon_menu_obj = pokemon_menu.Pokemon_Menu(self.screen)
def test_nz(self): b = bag.Bag() t1 = False t2 = False if b: t1 = True b.add(1) if b: t2 = True self.assertFalse(t1) self.assertTrue(t2)
def balance_reaction(self, substrate, product): """ Balances the reaction (by counting atoms) """ atom_gap = compound2graph(substrate).node_bag() - compounds2graph( product).node_bag() extra_bag = bag.Bag() extra_bag['CO2'] = atom_gap['C'] extra_bag['H2O'] = atom_gap['O'] + atom_gap['N'] - 2 * atom_gap['C'] extra_bag['PO3'] = atom_gap['PO3'] for (atom, count) in atom_gap.itercounts(): if (not atom in ['C', 'O', 'N', 'PO3'] and count != 0): raise Exception( "cannot balance the number of '%s' atoms, between %s and %s" % (atom, substrate, product)) for (metabolite, count) in extra_bag.itercounts(): if (count > 0): product += (" + " + metabolite) * count if (count < 0): substrate += (" + " + metabolite) * (-count) return (substrate, product)
def generate_initial_population( population_size=constants.initial_population_size): gift_frame = get_gift_weight_frame() gift_name_list, gift_weight_list = list(gift_frame['GiftId'].values), list( gift_frame['weight'].values) population_solution_list = list([]) for i in range(population_size): total_population_weight = 0.0 random_solution = bag.RandomSolution() taken_array = generate_mask_array(len(gift_frame)) max_try_counter = 0 while (max_try_counter < constants.max_tries) and ( total_population_weight < (constants.max_bag_capacity * constants.max_number_of_bags - 1000.0)): random_bag = bag.Bag() random_gifts = generate_random_numbers_range(0, len(gift_frame), batch_size=2000) max_try_counter += 1 for gift_index in random_gifts: if not taken_array[gift_index]: random_gift_name, random_gift_weight = gift_name_list[ gift_index], gift_weight_list[gift_index] random_bag.calculate_total_weight() if random_bag.total_weight >= constants.max_bag_capacity - 1.0: break if random_bag.total_weight + random_gift_weight < constants.max_bag_capacity: random_bag.add_gift_item(random_gift_name, random_gift_weight) taken_array[gift_index] = True random_solution.add_bag(random_bag) random_solution.calculate_solution_value() total_population_weight = random_solution.total_solution_value population_solution_list.append(random_solution) return population_solution_list
def run(gridSize, startPosition, playBoard, rack, difficulty): #print "runRun" if difficulty not in range(1, 10): print "difficulty range error" raise NameError("Invalid difficulty") return False #wordsmith handles active = 0 players = [] #print "bag" theBag = bag.Bag() #print theBag theBoard = board.Board(gridSize, startPosition) #print "board" #print theBoard #setup our board data we recieved for boardY in range(gridSize): for boardX in range(gridSize): try: playTile = playBoard[boardY][boardX] except: continue try: playLetter = playTile['letter'] except: continue try: playScore = playTile['score'] except: playScore = 1 if playLetter == '': continue wsTile = tile.Tile(playTile['letter'], playScore) theBoard.squares[boardY][boardX] = ( wsTile, theBoard.squares[boardX][boardY][1]) theBoard.squares[boardY][boardX][0].locked = True #todo fix this up / no hard coded spots firstTurn = True if theBoard.squares[7][7][0]: firstTurn = False print "FIRST TURN?" print firstTurn #print "***PLAYING THE BOARD***" #printBoard(theBoard) print "RACK:" print rack #print "engine!" h = heuristic.notEndGameHeuristic(heuristic.tileQuantileHeuristic( 0.5, 1.0)) #print "playeru!" players.append( ai.AI(theBoard, theBag, theHeuristic=h, theDifficulty=difficulty)) #print "TRAY!" players[active].tray = setTray(rack) #print "EXECUTE!!" playedMove = players[active].executeTurn(firstTurn) #print "OK!" if playedMove: # print "PLAYED!" success = players[active].play(firstTurn) else: #pass return False # remap for our game returnPlay = [] for move in playedMove: for what in move: #where was it was in the rack index = rack.index(what[1].letter) rack = rack[0:index] + '*' + rack[index + 1:len(rack)] returnPlay.append({ 'letter': what[1].letter, 'x': what[0][1], 'y': what[0][0], 'index': index }) return returnPlay
import bag bags = bag.Bag() bags.add_bag({"wow"},3) import pickle def save_object(obj, filename): with open(filename, 'wb') as output: # Overwrites any existing file. pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL) def load_object(filename): with open(filename, 'rb') as input: tech_companies = pickle.load(input) return tech_companies ## A set is an arry of 2 elements one is a set and the other is an integer def add_word_to_set(dictionary, SET, new_word, counter): if new_word in dictionary: new_SET = dictionary[new_word][0] else: new_SET = [{new_word}, 0] dictionary[new_word]= [new_SET, counter, 0] SET[0] = SET[0].union(new_SET[0]) for x in new_SET[0]: dictionary[x][0] = SET ###create bags### d = {} HEAD_WORD = None HEAD_SET = None BAGS = []
def test_bag(self): test_bag = bag.Bag() self.assertTrue(isinstance(test_bag.barrels, set))
def test_bag_get_barrel(self): test_bag = bag.Bag() bag_count = test_bag.get_count() self.assertEqual(bag_count, 90)
def test_bag_get_barrel(self): test_bag = bag.Bag() test_barrel = test_bag.get_barrel() self.assertEqual(test_bag.get_count(), 89) self.assertFalse(test_barrel in test_bag.barrels)
def test_bag_90(self): test_bag = bag.Bag() for _ in range(90): test_barrel = test_bag.get_barrel() self.assertTrue(test_bag.get_barrel() is None)
current_scene.enter(self.name, self.bag) class Map(object): sceneList = { 'entry': scenes.CaveEntry(), 'cave': scenes.Cave(), 'ballRun': scenes.BallRun(), 'puzzleRoom': scenes.PuzzleRoom(), 'treasureRoom': scenes.TreasureRoom(), 'death': scenes.Death(), 'finish': scenes.Finish(), } def __init__(self, start_scene): self.start = start_scene def next_scene(self, scene_name): return self.sceneList.get(scene_name) def opening_scene(self): Val = self.next_scene(self.start) return Val aBag = bag.Bag() aMap = Map('entry') game = Engine(aMap, aBag) game.play()
def runGame(USERDATA, useHintBox=False): theBag = bag.Bag() theBoard = board.Board() players = [] h = heuristic.notEndGameHeuristic(heuristic.tileQuantileHeuristic(.5, 1.0)) players.append(human.Human("Player", theBoard, theBag)) players.append(ai.AI(theBoard, theBag, theHeuristic=h, theDifficulty=10.0)) #players.append(ai.AI(theBoard, theBag)) active = 0 computerTurn = isinstance(players[active], ai.AI) firstTurn = True gameOver = False gameMenu = menu.GameMenu(useHintBox) redrawEverything(theBoard, players[active], players, gameOver, gameMenu) inHand = None stillPlaying = True AIstuck = False while stillPlaying: mouseClicked = False mouseMoved = False actionKeyHit = False shuffleKeyHit = False hintKeyHit = False for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == MOUSEMOTION: mouseX, mouseY = event.pos mouseMoved = True elif event.type == MOUSEBUTTONUP: mouseX, mouseY = event.pos mouseClicked = True elif event.type == KEYUP: if event.key == K_SPACE or event.key == K_RETURN: actionKeyHit = True if event.key == K_r: shuffleKeyHit = True if event.key == K_h and useHintBox: hintKeyHit = True #GAME MENU BUTTONS if mouseMoved: gameMenu.update(mouseX, mouseY) if mouseClicked: SELECTION = gameMenu.execute(mouseX, mouseY) if SELECTION == menu.GameMenu.PLAY_TURN: actionKeyHit = True elif SELECTION == menu.GameMenu.RESHUFFLE: shuffleKeyHit = True elif SELECTION == menu.GameMenu.HINT_TURN: hintKeyHit = True elif SELECTION == menu.GameMenu.MAIN_MENU: stillPlaying = False if (hintKeyHit or TRAINING_FLAG) and not computerTurn and not gameOver: tilesPulled = theBoard.removeTempTiles() if tilesPulled != None: #take the tiles back for t in tilesPulled: players[active].take(t) players[active].executeTurn(firstTurn, DISPLAYSURF) TICTIC.play() if (actionKeyHit or TRAINING_FLAG or computerTurn) and not gameOver: #If it's the computer turn, we need to process its move first! if computerTurn: playedMove = players[active].executeTurn( firstTurn, DISPLAYSURF) else: playedMove = True if playedMove: success = players[active].play(firstTurn) if success == "END": gameOver = True endGame(players, active, useHintBox, USERDATA) elif success: DINGDING.play() players[active].pulseScore() firstTurn = False active += 1 if active >= len(players): active = 0 computerTurn = isinstance(players[active], ai.AI) #If we were stuck before, we aren't anymore if computerTurn: AIstuck = False else: if TRAINING_FLAG: AIstuck = True TICTIC.play() if computerTurn: print "AI thinks it has a good move, but it doesn't" else: players[active].shuffle() #Let the player know the AI shuffled players[active].lastScore = 0 players[active].pulseScore() if theBag.isEmpty(): AIstuck = True active += 1 if active >= len(players): active = 0 computerTurn = isinstance(players[active], ai.AI) redrawEverything(theBoard, players[active], players, gameOver, gameMenu) if (shuffleKeyHit or (AIstuck and TRAINING_FLAG)) and not computerTurn and not gameOver: SCRIFFLE.play() players[active].shuffle() active += 1 if active >= len(players): active = 0 computerTurn = isinstance(players[active], ai.AI) #If we're stuck AND the AI is stuck, end the game without subtracting points if AIstuck: gameOver = True endGame(players, active, useHintBox, USERDATA, stuck=True) redrawEverything(theBoard, players[active], players, gameOver, gameMenu) if mouseClicked and not computerTurn and not gameOver: inHand = tileGrab(mouseX, mouseY, inHand, theBoard, players[active]) redrawEverything(theBoard, players[active], players, gameOver, gameMenu) if gameOver and TRAINING_FLAG: #automatically start a new game for training purposes stillPlaying = False redrawNecessary(theBoard, players, gameOver) pygame.display.update()
def setUp(self): self.b = bag.Bag()
util._mkdir(html_path + "/" + pathway) html_filename = html_path + "/" + pathway + ".html" html_file = open(html_filename, "w") prev_line_bag = None reaction_titles = [] reaction_compounds = [] line_number = 0 for line in util.parse_text_file(pathway_path + "/" + pathway + ".pth"): line_number += 1 if (line[0:2] == "//"): prev_line_bag = None reaction_titles.append("*"*60 + " " + line[2:] + " " + "*"*60) reaction_compounds.append(None) elif (prev_line_bag == None): prev_line_bag = bag.Bag().from_string(line) else: curr_line_bag = bag.Bag().from_string(line) common_bag = curr_line_bag.intersection(prev_line_bag) side_bags = [prev_line_bag - common_bag, curr_line_bag - common_bag, common_bag] # left-side, right-side, common side_strings = ["", "", ""] side_graphs = (ChemGraph(), ChemGraph(), ChemGraph()) for side in range(3): side_strings[side] += str(side_bags[side]) for (compound, cnt) in sorted(side_bags[side].itercounts()): for i in range(cnt): side_graphs[side].add(molfile2graph(mol_path + "/" + compound + ".mol")) if (side_graphs[0].node_bag() != side_graphs[1].node_bag()): raise Exception("Unbalanced reaction at lines %d - %d\n%s = %s (common: %s)" %\
def setUp(self): '''create a Bag to use in all tests''' self.bag = bag.Bag() for item in ITEMS: self.bag.add_item(item)
if pages > 200: pages = 200 print(f"{str(pages)} страниц") ((push_and_pull if pages > 100 else parse_pages)(link.get_url(), pages, args.debug, mysql_table, cred_tuple, args.noproxy)) check_list = mysql_table.table_check_material() have_a_try = 3 while len(check_list) and have_a_try: print(f"Пустых {len(check_list)} материалов. Заполняем...") for index in check_list: secs = int(random.random() * int(cred_tuple[4])) time.sleep(secs) empty_math_page = html_page.HtmlPage( f"https://www.wildberries.ru/catalog/{index[1]}/detail.aspx") text = empty_math_page.get_html(cred_tuple, args.noproxy) if text: empty_soup = BeautifulSoup(text, 'html.parser') empty_bag = bag.Bag() empty_bag.set_material(empty_soup, args.debug) mysql_table.table_update_material(index[0], empty_bag.material) mysql_table.cnx.commit() check_list = mysql_table.table_check_material() have_a_try -= 1 print("Готово.") mysql_table.end_table_connect()