def get_inventory(player_id): conn = None try: conn = psycopg2.connect(host="localhost", database="roleplay", user="******", password="******") cur = conn.cursor() sql = 'SELECT weapon.id, weapon.name, weapon.rang_id, weapon.power, player_has_weapon.id FROM ' \ 'player_has_weapon JOIN weapon ON player_has_weapon.weapon_id = weapon.id ' \ 'where player_has_weapon.player_id = %s ' cur.execute(sql, (player_id, )) records = cur.fetchall() items = [] for record in records: item = Weapon(name=record[1], rang=record[2], power=record[3], item_id=record[4]) items.append(item) sql = 'SELECT armor.id, armor.armor_type, armor.name, armor.rang_id, armor.defense, player_has_armor.id FROM ' \ 'player_has_armor JOIN armor ON player_has_armor.armor_id = armor.id ' \ 'where player_has_armor.player_id = %s ' cur.execute(sql, (player_id, )) records = cur.fetchall() for record in records: item = Armor.armor_from_db(armor_type_name=record[1], name=record[2], rang=record[3], defense=record[4], item_id=record[5]) items.append(item) sql = 'SELECT potion.id, potion.name, rang.meaning, potion.effect_type_id, ' \ ' potion_effect.meaning, ' \ 'potion.value FROM potion ' \ 'JOIN player_has_potion ON potion.id = player_has_potion.potion_id ' \ 'JOIN potion_effect ON potion_effect.id = potion.effect_type_id ' \ 'JOIN rang ON potion.rang_id = rang.id ' \ 'WHERE player_id = %s AND player_has_potion.used = false' cur.execute(sql, (player_id, )) records = cur.fetchall() for record in records: item = Potion.potion_from_db(name=record[1], rang=record[2], effect_name=record[4], effect_value=record[5]) items.append(item) cur.close() return Inventory(items) except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close()
def recgetdata(self, data): numberOfRequestedInventoryItems, lengthOfVarint = decodeVarint( data[:10]) if len(data) < lengthOfVarint + (32 * numberOfRequestedInventoryItems): logger.debug('getdata message does not contain enough data. Ignoring.') return self.antiIntersectionDelay(True) # only handle getdata requests if we have been connected long enough for i in xrange(numberOfRequestedInventoryItems): hash = data[lengthOfVarint + ( i * 32):32 + lengthOfVarint + (i * 32)] logger.debug('received getdata request for item:' + hexlify(hash)) if self.objectHashHolderInstance.hasHash(hash): self.antiIntersectionDelay() else: if hash in Inventory(): self.sendObject(hash, Inventory()[hash].payload) else: self.antiIntersectionDelay() logger.warning('%s asked for an object with a getdata which is not in either our memory inventory or our SQL inventory. We probably cleaned it out after advertising it but before they got around to asking for it.' % (self.peer,))
def test_inventory(self): """Tests for Inventory dictionary output""" my_inv = Inventory(product_code=12, description='an apple', market_price=2, rental_price=1.5) inv_dict = my_inv.return_as_dictionary() assert inv_dict['product_code'] == 12 assert inv_dict['description'] == 'an apple' assert inv_dict['market_price'] == 2 assert inv_dict['rental_price'] == 1.5
def main(): parser = argparse.ArgumentParser( description='Execute run inventory workflow') parser.add_argument('-i', '--input-path', required=True, dest='input_path', metavar='PATH', action='store', help='Path of input file to use with test') parser.add_argument('-q', '--inventory-qty', dest='inventory_qty', type=int, action='store', help='Setting for initial inventory quantity, ' 'default is 100') # COLLECT COMMAND LINE ARGUMENTS cl_args = parser.parse_args() csv_input_file = cl_args.input_path # SET INITIAL INVENTORY WITH EACH PRODUCT QUANTITY EQUAL TO 100 qty_per_product = cl_args.inventory_qty if cl_args else 100 inventory = Inventory() for product in PRODUCTS: inventory.add(product, qty_per_product) # Test example inventory with uneven quantities # inventory.add('A', 2) # inventory.add('B', 3) # inventory.add('C', 1) # inventory.add('D', 0) # inventory.add('E', 0) # READ IN CSV FILE OF ORDERS AND CONVERT TO A DICT OBJECT file_rows = [] with open(csv_input_file, 'rU') as f: f_csv = csv.DictReader(f) for row in f_csv: file_rows.append(row) # TRANSFORM EACH RECORD INTO A PRODUCT ORDER OBJECT order_history = [] for index, csv_row in enumerate(file_rows): header = csv_row['Header'] lines = csv_row['Lines'] order_lines = lines.replace('"', '') try: order = ProductOrder(header, order_lines) inventory_depleted, order_status = process_order(order, inventory) if not inventory_depleted: order_history.append(order_status) else: break except ValueError as e: print(e) print_order_history(order_history)
def inventory(connector): conn = MagicMock() connector.connect.return_value = conn return Inventory( username="******", password="******", host="127.0.0.1", port=3306, ssl_skip_verify="True", database="database", )
def __init__(self, name, starting_room, starting_items=[]): # Player info self.name = name self.current_room = starting_room self.previous_room = None # Player inventory self.inventory = Inventory(starting_items) # Movement text for easier printing later self.directions = {"n": "north", "s": "south", "e": "east", "w": "west"}
def from_disk(self, path, url_prefix, inventory=None): """Create or extend inventory with resources from disk scan Assumes very simple disk path to URL mapping: chop path and replace with url_path. Returns the new or extended Inventory object. If a inventory is specified then items are added to that rather than creating a new one. mb = InventoryBuilder() m = inventory_from_disk('/path/to/files','http://example.org/path') """ num = 0 # Either use inventory passed in or make a new one if (inventory is None): inventory = Inventory() # for each file: create Resource object, add, increment counter for dirpath, dirs, files in os.walk(path, topdown=True): for file_in_dirpath in files: try: if self.exclude_file(file_in_dirpath): continue # get abs filename and also URL file = os.path.join(dirpath, file_in_dirpath) if (not os.path.isfile(file) or not (self.include_symlinks or not os.path.islink(file))): continue rel_path = os.path.relpath(file, start=path) if (os.sep != '/'): # if directory path sep isn't / then translate for URI rel_path = rel_path.replace(os.sep, '/') url = url_prefix + '/' + rel_path file_stat = os.stat(file) except OSError as e: sys.stderr.write("Ignoring file %s (error: %s)" % (file, str(e))) continue mtime = file_stat.st_mtime lastmod = datetime.fromtimestamp(mtime).isoformat() r = Resource(uri=url, lastmod=lastmod) if (self.do_md5): # add md5 r.md5 = compute_md5_for_file(file) if (self.do_size): # add size r.size = file_stat.st_size inventory.add(r) # prune list of dirs based on self.exclude_dirs for exclude in self.exclude_dirs: if exclude in dirs: dirs.remove(exclude) return (inventory)
def __init__(self): self.transactionNum = 0 self.inventory = Inventory() self.cart = Cart() self.todayDate = date.today() self._customerOption = "" self._menuOption = 0 self._transactionOption = 0 self._addInput = [] self._cashAmount = 0.0 self._rmvOption = 0
def checkAlreadyHave(self): """ Check if we already have the object (so that we don't duplicate it in inventory or advertise it unnecessarily) """ # if it's a stem duplicate, pretend we don't have it if Dandelion().hasHash(self.inventoryHash): return if self.inventoryHash in Inventory(): raise BMObjectAlreadyHaveError()
def handleReceivedInventory(self, hashId): if haveBloom: self.invBloom.add(hashId) try: with self.objectsNewToThemLock: del self.objectsNewToThem[hashId] except KeyError: pass if hashId not in Inventory(): with self.objectsNewToMeLock: self.objectsNewToMe[hashId] = True
def menu(): menu_text = 'Welcome to the movie management platform!\n\n(a) Search for customer by email\n(b) Retrive all customers\n(c) Search for movie\n(d) Return movie\n(e) List all unreturned films\n(x) Exit: ' while True: menu_ctrl = input(menu_text) customer = Customer() inventory = Inventory() rental = Rental() if menu_ctrl == 'a': searched_cust = customer.search_by_email( input("Please write the email you'd like to search for: ")) if searched_cust == None: print('Sorry, we couldnt find that customer') else: print( f'Customer found!\n_______________\nFull Name: {searched_cust.first_name} {searched_cust.last_name}\nEmail: {searched_cust.email}\nStore ID: {searched_cust.store_id}\nAddress ID: {searched_cust.address_id}\nCreated: {searched_cust.create_date}\nUpdated: {searched_cust.last_update}' ) elif menu_ctrl == 'b': all_custs = customer.get_all() for cust in all_custs: print( f'_______________\nCustomer ID: {cust.customer_id}\nFull Name: {cust.first_name} {cust.last_name}\nEmail: {cust.email}' ) elif menu_ctrl == 'c': text = input('Please enter your search term: ') search_results = inventory.search_by_text(text, 1) for result in search_results: print( f'Movie details:\n______________\nInventory ID: {result.inventory_id}\nFilm ID: {result.film_id}\nFilm Title: {result.title}\nFilm Description: {result.description}\nRating: {result.rating}\nRental rate: {result.rental_rate}\n\n' ) elif menu_ctrl == 'd': return_film = int( input('Please enter the id for the film you are returning: ')) rental.return_rental(return_film) elif menu_ctrl == 'e': film_list = rental.all_unreturned() for film in film_list: print( f"Unreturned rental details\n_________________________\nRental ID: {film.rental_id}\nRental Date: {film.rental_date}\nCustomer Name: {film.cust_name}\nCustomer Email: {film.email}\nPostal Address: {film.postal_code}\nTotal Due: ${film.compute_owed(film.rental_id)}" ) sub_menu_ctrl = input( 'Please type in a rental ID to return or press (x) to return to main menu' ) if sub_menu_ctrl != 'x': #write better logic to validate input if input('Are you certain? Y/N: ') == 'Y': rental.return_rental(int(sub_menu_ctrl)) print('Returned successfully\n\n') elif menu_ctrl == 'x': break
def _checkAndShareBroadcastWithPeers(data): if len(data) < 180: logger.debug( 'The payload length of this broadcast packet is unreasonably low.' ' Someone is probably trying funny business. Ignoring message.') return embeddedTime, = unpack('>Q', data[8:16]) readPosition = 20 # bypass the nonce, time, and object type broadcastVersion, broadcastVersionLength = \ decodeVarint(data[readPosition:readPosition + 10]) readPosition += broadcastVersionLength if broadcastVersion >= 2: streamNumber, streamNumberLength = \ decodeVarint(data[readPosition:readPosition + 10]) readPosition += streamNumberLength if streamNumber not in state.streamsInWhichIAmParticipating: logger.debug( 'The streamNumber %i isn\'t one we are interested in.', streamNumber ) return if broadcastVersion >= 3: tag = data[readPosition:readPosition+32] else: tag = '' inventoryHash = calculateInventoryHash(data) if inventoryHash in Inventory(): logger.debug( 'We have already received this broadcast object. Ignoring.') return # It is valid. Let's let our peers know about it. objectType = 3 Inventory()[inventoryHash] = ( objectType, streamNumber, data, embeddedTime, tag) # This object is valid. Forward it to peers. logger.debug('advertising inv with hash: %s', hexlify(inventoryHash)) protocol.broadcastToSendDataQueues( (streamNumber, 'advertiseobject', inventoryHash)) # Now let's queue it to be processed ourselves. objectProcessorQueue.put((objectType, data))
def get(self,url,inventory=None): """Get a inventory from url Will either create a new Inventory object or add to one supplied. """ # Either use inventory passed in or make a new one if (inventory is None): inventory = Inventory() inventory_fh = URLopener().open(url) Sitemap().inventory_parse_xml(fh=inventory_fh, inventory=inventory) return(inventory)
def __init__(self, name): self.name = name self.level = 1 self.hp_max = 10 self.hp = self.hp_max self.damage_min = 0 self.damage_max = 3 self.heal_min = 2 self.heal_max = 4 self.level_kills = 0 self.total_kills = 0 self.inventory = Inventory()
def setUp(self): self.item1 = Item(1, 'fries', 12.95) self.item2 = Item(2, 'cheese burger', 4.75) self.item3 = Item(3, 'chicken burger', 2.75) self.item4 = Item(4, 'milk shike', 4.00) #add items self.inven = Inventory() self.inven.addItem(self.item1) self.inven.addItem(self.item2) self.inven.addItem(self.item3) self.inven.addItem(self.item4)
def _checkAndShareUndefinedObjectWithPeers(data): embeddedTime, = unpack('>Q', data[8:16]) readPosition = 20 # bypass nonce, time, and object type objectVersion, objectVersionLength = decodeVarint( data[readPosition:readPosition + 9]) readPosition += objectVersionLength streamNumber, streamNumberLength = decodeVarint( data[readPosition:readPosition + 9]) if not streamNumber in state.streamsInWhichIAmParticipating: logger.debug('The streamNumber %s isn\'t one we are interested in.', streamNumber) return inventoryHash = calculateInventoryHash(data) if inventoryHash in Inventory(): logger.debug('We have already received this undefined object. Ignoring.') return objectType, = unpack('>I', data[16:20]) Inventory()[inventoryHash] = ( objectType, streamNumber, data, embeddedTime,'') logger.debug('advertising inv with hash: %s', hexlify(inventoryHash)) broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
def remote_inv_with_pants(): rsp = MagicMock() rsp.status = 200 rsp.read.return_value = json.dumps({ 'name': 'Pants', 'price': 50.00, 'quantity': 10 }) client = create_autospec(HTTPConnection) client.getresponse.return_value = rsp return Inventory(client=client)
def __init__(self, game): """ Create rooms and items for the appropriate 'game' version. """ self.rooms = self.load_rooms(f"data/{game}Rooms.txt") self.load_items(f"data/{game}Items.txt") self.inventory = Inventory() self.current_room = None # define win conditions as winning room being the last self.winning_room_id = self.rooms[-1].id self.wonb = False
def __init__(self): self.name = None self.hp = None # healing points self.mp = None # magic points self.f_def = None # defense points self.m_def = None self.p_attack = None # attack points self.m_attack = None self.weapon = None self.armor = None self.inventory = Inventory() self.alive = True
def run(self): """ runs the value stream simulation """ start_inv = Inventory(json.loads(str(self.inventory))) lines = self._init_lines(self.streamconfig) print("", file=self.outfile) print('{} value stream {} run started' .format(self.clock, self.stream_id), file=self.outfile) print('{} description "{}"' .format(self.clock, self.streamconfig['description']), file=self.outfile) while self.clock.step(): for line in lines: line.step(self.clock) for line in lines: line.step(self.clock) print('{} value stream {} run complete' .format(self.clock, self.stream_id), file=self.outfile) end_inv = Inventory(json.loads(str(self.inventory))) self.summarize_run(lines, start_inv, end_inv)
def appearance(self, msg, client): subcommand = msg[1].split(".")[2] if subcommand == "rnn": if len(msg[2]["unm"]) > const.MAX_NAME_LEN: return self.server.redis.lset(f"uid:{client.uid}:appearance", 0, msg[2]["unm"]) user_data = self.server.get_user_data(client.uid) client.send([ "a.apprnc.rnn", { "res": { "slvr": user_data["slvr"], "enrg": user_data["enrg"], "emd": user_data["emd"], "gld": user_data["gld"] }, "unm": msg[2]["unm"] } ]) elif subcommand == "save": apprnc = msg[2]["apprnc"] current_apprnc = self.server.get_appearance(client.uid) if not current_apprnc: self.update_appearance(apprnc, client) self.server.inv[client.uid] = Inventory( self.server, client.uid) if apprnc["g"] == 1: weared = ["boyShoes8", "boyPants10", "boyShirt14"] available = ["boyUnderdress1"] else: weared = ["girlShoes14", "girlPants9", "girlShirt12"] available = ["girlUnderdress1", "girlUnderdress2"] for item in weared + available: self.server.inv[client.uid].add_item(item, "cls") for item in weared: self.server.inv[client.uid].change_wearing(item, True) for item in const.room_items: self.server.modules["frn"].add_item( item, "livingroom", client.uid) for i in range(1, 6): self.server.modules["frn"].add_item( item, str(i), client.uid) else: if apprnc["g"] != current_apprnc["g"]: logging.error("gender doesn't match!") return self.update_appearance(apprnc, client) client.send([ "a.apprnc.save", { "apprnc": self.server.get_appearance(client.uid) } ])
def read(self, uri=None, inventory=None): """Read sitemap from a URI including handling sitemapindexes Returns the inventory. Includes the subtlety that if the input URI is a local file and the """ if (inventory is None): inventory = Inventory() # try: fh = URLopener().open(uri) except IOError as e: raise Exception( "Failed to load sitemap/sitemapindex from %s (%s)" % (uri, str(e))) etree = parse(fh) # check root element: urlset (for sitemap), sitemapindex or bad self.sitemaps_created = 0 if (etree.getroot().tag == '{' + SITEMAP_NS + "}urlset"): self.inventory_parse_xml(etree=etree, inventory=inventory) self.sitemaps_created += 1 elif (etree.getroot().tag == '{' + SITEMAP_NS + "}sitemapindex"): if (not self.allow_multifile): raise Exception( "Got sitemapindex from %s but support for sitemapindex disabled" % (uri)) sitemaps = self.sitemapindex_parse_xml(etree=etree) sitemapindex_is_file = self.is_file_uri(uri) # now loop over all entries to read each sitemap and add to inventory for sitemap_uri in sorted(sitemaps.resources.keys()): if (sitemapindex_is_file): if (not self.is_file_uri(sitemap_uri)): # Attempt to map URI to local file remote_uri = sitemap_uri sitemap_uri = self.mapper.src_to_dst(remote_uri) else: # FIXME - need checks on sitemap_uri values: # 1. should be in same server/path as sitemapindex URI pass try: fh = URLopener().open(sitemap_uri) except IOError as e: raise Exception( "Failed to load sitemap from %s listed in sitemap index %s (%s)" % (sitemap_uri, uri, str(e))) self.inventory_parse_xml(fh=fh, inventory=inventory) self.sitemaps_created += 1 #print "%s : now have %d resources" % (sitemap_uri,len(inventory.resources)) else: raise ValueError("XML is not sitemap or sitemapindex") return (inventory)
def __init__(self, game): """ Create rooms and items for the appropriate 'game' version. """ self.rooms = self.load_rooms(f"data/{game}Rooms.txt") self.current_room = self.rooms[1] # use self.over to determine if the game if over self.over = 0 self.load_items(f"data/{game}Items.txt") self.inventory = Inventory() # synonyms self.synonyms = {} self.load_synonyms("data/SmallSynonyms.txt")
def __init__(self): self.name = "" self.p_race = "" self.p_class = "" self.max_hp = 10 self.current_hp = 10 self.base_attack = 1 self.base_defence = 1 self.c_ability = "None" self.inventory = Inventory(self) self.world_view = Artist(20) self._DM = DM(party=self, vision=self.world_view) self.quest = Land(traveler=self, artist=self.world_view)
def __init__(self): self.name = 'Unnamed' self.attack = 0 self.max_health = 0 self.health = 0 self.defence = 0 self.magic = 0 self.description = "" self.weapon = "" self.inventory = Inventory() self.inventory.add(Item('gold'), 10) self.commands = self.getCommands()
def create_player(x, y): return Entity( Player(), Position(x, y, Position.ORDER_PLAYER), Actor(100, player_act), FOV(10), Movement(), Renderable(player_tex), Blocker(blocks_movement=True), Health(100), Fighter(1, 0), Inventory(), )
def execute_actions(goal, sites, exchange): goal['consumption'] = Inventory({}) for item in goal['actions']: action = item['action'] site_name = item['site'] ticker = item['id'] site = sites[site_name] report.major_break() report.output_general('{} {} at {}'.format(action, ticker, site_name)) if action == 'build': consumption = build(site, ticker, exchange) goal['consumption'].add_all(consumption.items) return goal['consumption']
def parseDefault(self, res): try: self._state.eggs.ParseFromString(res.returns[1]) self._state.inventory.ParseFromString(res.returns[2]) self._state.badges.ParseFromString(res.returns[3]) self._state.settings.ParseFromString(res.returns[4]) except Exception as e: logging.error(e) raise GeneralPogoException("Error parsing response. Malformed response") # Finally make inventory usable item = self._state.inventory.inventory_delta.inventory_items self.inventory = Inventory(item)
def _checkAndShareGetpubkeyWithPeers(data): if len(data) < 42: logger.info( 'getpubkey message doesn\'t contain enough data. Ignoring.') return if len(data) > 200: logger.info( 'getpubkey is abnormally long. Sanity check failed. Ignoring object.' ) embeddedTime, = unpack('>Q', data[8:16]) readPosition = 20 # bypass the nonce, time, and object type requestedAddressVersionNumber, addressVersionLength = decodeVarint( data[readPosition:readPosition + 10]) readPosition += addressVersionLength streamNumber, streamNumberLength = decodeVarint( data[readPosition:readPosition + 10]) if not streamNumber in state.streamsInWhichIAmParticipating: logger.debug('The streamNumber %s isn\'t one we are interested in.' % streamNumber) return readPosition += streamNumberLength inventoryHash = calculateInventoryHash(data) if inventoryHash in Inventory(): logger.debug( 'We have already received this getpubkey request. Ignoring it.') return objectType = 0 Inventory()[inventoryHash] = (objectType, streamNumber, data, embeddedTime, '') # This getpubkey request is valid. Forward to peers. logger.debug('advertising inv with hash: %s' % hexlify(inventoryHash)) protocol.broadcastToSendDataQueues( (streamNumber, 'advertiseobject', inventoryHash)) # Now let's queue it to be processed ourselves. objectProcessorQueue.put((objectType, data))
def __init__(self): # Public properties self.name = input('Enter your character name: ') self.attack_damage = random.randint(8, 12) self.heal_amount = random.randint(8, 12) self.max_health = 100 self.health = self.max_health self.max_mana = 50 self.mana = self.max_mana self.level = 1 self.experience_point = 0 self.max_experience_point = 100 self.inventory = Inventory() self.skill = Skill(self)