def shopping(): if fm.getAllFruitQuantity() > 0: while True: fm.buyerViewFruits() fruitName = input( "Please select fruit name (select '*' to exit): ").strip() if fruitName == "*": break f: Fruit = fm.getFruitByName(fruitName) if f is None: print( "\nThe fruit name you want to select does not exist or out of stock. Please try again.\n" ) continue print("You selected: " + fruitName) quantity = getFruitQuantity(f) f.setQuantity(f.getQuantity() - quantity) ff = Fruit() ff.setId(f.getId()) ff.setName(f.getName()) ff.setOrigin(f.getOrigin()) ff.setQuantity(quantity) ff.setPrice(f.getPrice()) c = Cart() c.addFruitToCart(ff) name = input("Input your name: ") order.addToOrder(name, c) print("Successfully added to your order.") choice = input("Do you want to continue ordering? (Y/N): ") if choice == "N" or choice == "n": break else: print("\nThis fruit store is out of stock. Please come back later.\n")
def test_mark_up_prices(self): print() mark_up_prices_index = 0 for i in range(0, len(list_of_cart_jsons)): print("Testing Cart JSON File: " + list_of_cart_jsons[i]) #Testing Cart and BasePriceDB Class cart_json = return_json_data(list_of_cart_jsons[i]) rb_cart = Cart(cart_json) price_json = return_json_data(list_of_price_jsons[0]) base_price_db = BasePriceDB(price_json) list_of_cart_items = rb_cart.get_product_items() for product in list_of_cart_items: print("Type - " + product.get_product_type()) print("With Options - " + str(json.dumps(product.get_options()))) print("With Artist Markup - " + str(product.get_artist_markup())) print("With Quantitiy - " + str(product.get_quantity())) print("Expected Final Price is:" + str(list_of_mark_up_prices[mark_up_prices_index])) print("Actual Final Price: " + \ str(base_price_db.get_price_point(product)), end = "") self.assertEqual(base_price_db.get_price_point(product),\ list_of_mark_up_prices[mark_up_prices_index]) mark_up_prices_index = mark_up_prices_index + 1 print(" - PASS") print() print(list_of_cart_jsons[i] + " = PASS") print() print( "----------------------------------------------------------------\ -------")
def main_menu_loop(): book_shelf = Shelf() my_cart = Cart() inp = -1 while inp is not 5: inp = -1 print("\n*****Welcome to the Library Application Main Menu*****") print("1) Add a book to my cart by viewing all books") print("2) Add a book to my cart by searching") print("3) View my cart") print("4) Print my receipt") print("5) Exit") while inp < 1 or inp > 5: inp = get_integer( message= "Select an option by inputting a whole number within the above list." ) if inp is 1: view_books_no_filter(book_shelf, my_cart) elif inp is 2: view_books_with_filter(book_shelf, my_cart) elif inp is 3: print("******List of books within cart******") print(my_cart.get_books()) elif inp is 4: save_receipt_to_file(my_cart) print("****RECEIPT GENERATED IN ROOT FOLDER****") print("\n***Closing application. Goodbye!***")
def __init__(self): self.products = [] self.customers = [] self.owners = [] self.orders = [] self.login_user = None self.load_data() self.cart = Cart()
def testCantAddProductNotSellByCompany(self): aCart = Cart(self.defaultCatalog()) aProduct = self.invalidProduct() try: aCart.add(aProduct, 1) self.fail() except Exception as e: self.assertEquals(e.message, Cart._invalidProductErrorMessage) self.assertTrue(aCart.isEmpty())
def testCantAddlessThanOneProduct(self): aCart = Cart(self.defaultCatalog()) someProduct = 2 try: aCart.add(someProduct, 0) self.fail() except Exception as e: self.assertEquals(e.message, Cart._quantityErrorMessage) self.assertTrue(aCart.isEmpty())
def test_cart_prices_json(self): print() print("Following Tests tested with Base Price File: " + \ list_of_price_jsons[0] + ":") print() for i in range(0, len(list_of_cart_jsons)): print("Testing Cart JSON File: " + list_of_cart_jsons[i] + \ " with Expected Cart Value of " + str(list_of_checkout_prices[i])) #Testing Base - calculate_the_price.py cart_json = return_json_data(list_of_cart_jsons[i]) price_json = return_json_data(list_of_price_jsons[0]) rb_cart = Cart(cart_json) base_price_db = BasePriceDB(price_json) price_calculator = PriceCalculator(rb_cart, base_price_db) actual_cart_value = price_calculator.get_price_cents() print("Actual Cart Value: " + \ str(price_calculator.get_price_cents()), end = '') self.assertEqual(actual_cart_value, list_of_checkout_prices[i]) print(" - PASS") print() print( "----------------------------------------------------------------\ -------")
def crossover(cart1, cart2): maxScoreDif = 20000 brain = cart2.brain getWeights1 = cart1.brain.get_weights() getWeights2 = cart2.brain.get_weights() scoreDif = cart1.score - cart2.score pickChance1 = (scoreDif + maxScoreDif) / (maxScoreDif * 2) if pickChance1 < 0: pickChance1 = 0 elif pickChance1 > 1: pickChance1 = 1 for layer in range(len(getWeights2)): if getWeights2[layer].ndim == 2: # print(getWeights[layer]) for i in range(len(getWeights2[layer])): for j in range(len(getWeights2[layer][i])): if (random.random() < pickChance1): getWeights2[layer][i][j] = getWeights1[layer][i][j] brain.set_weights(getWeights2) return Cart(brain)
def __init__(self, cart_mass, pole_mass, pole_half_length, start_position, start_velocity, start_angle, start_angular_velocity): self.track_limits = 3 self.start_position = start_position self.start_velocity = start_velocity self.start_angle = start_angle self.start_angular_velocity = start_angular_velocity self.cart = Cart(cart_mass, start_position, start_velocity) self.pole = Pole(pole_half_length, pole_mass, start_angle, start_angular_velocity)
def create_carts(document_dict): """ Creates a list of carts out of the document """ cart_list = [] for cartDict in document_dict["carts"]: cart_list.append(Cart(cartDict)) return cart_list
def testCanAddMultipleItemsToCart(self): aCart = Cart(self.defaultCatalog()) aProduct = self.productSellByCompany() anotherProduct = self.otherProductSellByCompany() aCart.add(aProduct, 1) aCart.add(anotherProduct, 1) self.assertTrue(aCart.contains(aProduct)) self.assertTrue(aCart.contains(anotherProduct))
def testCashierCantCheckoutEmptyCart(self): aCart = Cart(self.defaultCatalog()) try: salesBook = [] aCashier = Cashier(MerchantProccesorAdapterSpy(), aCart, self.validCard(), self.aClient(), salesBook) aCashier.checkout() self.fail() except Exception as e: self.assertTrue(e.message, Cashier.CAN_NOT_CHECKOUT_EMPTY_CART)
def main(): stock = Stock() cart = Cart() stock.load_items("stock.txt") display_separator() display_intro() display_separator() main_menu(stock, cart) display_separator() stock.save_items("stock2.txt")
def main(): """ main Function for the Redbubble Coding Challenge of Calculating the Price in the Redbubble Shopping Cart in terms of Cents. Args: self (none): None. Returns: (void): No return value. Just prints the Total Price in the Cart in Cents """ # ------------------------------------------------------------------------ # # Constructs Argument Parser for Parsing Arguments # ------------------------------------------------------------------------ # argument_parser = argparse.ArgumentParser(description='Price Calculator') argument_parser.add_argument("-c", "--cart", required=True, \ help="PATH TO CART JSON") argument_parser.add_argument("-p", "--price", required=True, \ help="PATH TO BASE PRICE JSON") argument_parser.add_argument("-d", "--discount", required=True, \ help="PATH TO DISCOUNT JSON") arguments = vars(argument_parser.parse_args()) # ------------------------------------------------------------------------ # # Get and Load JSON Paths for Cart, Base Prices, and Discounts # ------------------------------------------------------------------------ # path_to_cart = arguments['cart'] path_to_price = arguments['price'] path_to_discount = arguments['discount'] cart_json = return_json_data(path_to_cart) price_json = return_json_data(path_to_price) discount_json = return_json_data(path_to_discount) # ------------------------------------------------------------------------ # # Initialize Cart with Each Item # ------------------------------------------------------------------------ # rb_cart = Cart(cart_json) # ------------------------------------------------------------------------ # # Initialize Base Price DataBase with Cart and Discount # ------------------------------------------------------------------------ # base_price_db = BasePriceDB(price_json, discount_json, rb_cart) # ------------------------------------------------------------------------ # # Initialize Price Calculator # ------------------------------------------------------------------------ # price_calculator = PriceCalculator(rb_cart, base_price_db) # ------------------------------------------------------------------------ # # Output Price of Shopping Cart Compared to Base Prices # ------------------------------------------------------------------------ # print(price_calculator.get_price_cents()) return
def testCanAddMoreThanOneProduct(self): aCart = Cart(self.defaultCatalog()) aProduct = self.productSellByCompany() aCart.add(aProduct, 3) self.assertFalse(aCart.isEmpty()) self.assertTrue(aCart.contains(aProduct)) self.assertEquals(aCart.numberOf(aProduct), 3)
def order(message): if message.text.isalpha(): with open('db.json', 'r+') as file: data = json.load(file) cart = Cart(message.chat.id) cart['order'] = { # 'name': name # 'adress': adress } else: da('test', 1)
def test_cart_item_count(self): for i in range(0, len(list_of_cart_jsons)): print("Testing Cart JSON File: " + list_of_cart_jsons[i] + \ " with Expected Cart Item Amount of " + \ str(list_of_cart_item_count[i])) #Testing Cart Class cart_json = return_json_data(list_of_cart_jsons[i]) rb_cart = Cart(cart_json) actual_cart_item_amount = len(rb_cart.get_product_items()) print("Actual Cart Item Amount: " + str(actual_cart_item_amount), \ end = "") self.assertEqual(actual_cart_item_amount, \ list_of_cart_item_count[i]) print(" - PASS") print() print( "----------------------------------------------------------------\ -------")
def add(call): cart = Cart(call.message.chat.id) # bot.delete_message(call.message.chat.id, call.message.message_id) id = call.data.split('_')[-1] global last_mes prod = cart.add(id) keyboard = types.InlineKeyboardMarkup() key = types.InlineKeyboardButton('Заказать', callback_data='order') key_2 = types.InlineKeyboardButton('Очистить', callback_data='clear') keyboard.add(key, key_2) # bot.edit_message_text('adsad', call.message.chat.id) # if prod['quantity'] == 1: # t = [f"{prod['quantity']}x {prod['name']} - {prod['price']}р.\n" for prod in cart] # t = '🛒 Продукты у Вас в корзине:\n\n' + '\n'.join(t) + \ # f'\nИтого: {cart.get_total_price()}р.' t = [ f"{prod['quantity']}x {prod['name']} - {prod['price']}р.\n" for prod in cart ] t = '🛒 Продукты у Вас в корзине:\n\n' + '\n'.join(t) + \ f'\nИтого: {cart.get_total_price()}р.' try: if last_mes.message_id > call.message.message_id: bot.edit_message_text(t, call.message.chat.id, last_mes.message_id, reply_markup=keyboard) else: # bot.delete_message(last_mes.chat.id,last_mes.message_id) last_mes = bot.send_message(call.message.chat.id, t, reply_markup=keyboard) except: last_mes = bot.send_message(call.message.chat.id, t, reply_markup=keyboard)
def init_population(numGamesPerCart): carts = [Cart(mkBrain()) for i in range(initialGames)] for cart in carts: runCart(cart, numGamesPerCart) print("done") for cart in carts: print(cart.score) bestCarts = getGroupOfGoodCarts(carts, 7) return bestCarts
def crossover(cart1, cart2): maxScoreDif = 1000 brain = mkBrain() getWeights1 = cart1.brain.get_weights() getWeights2 = cart2.brain.get_weights() scoreDif = cart1.score-cart2.score pickChance1 = (scoreDif+maxScoreDif)/(maxScoreDif*2) print("Chance " + str(pickChance1)) if pickChance1 < 0: pickChance1 = 0 elif pickChance1 > 1: pickChance1 = 1 changed = 0 totalTrue = 0 total = 0 for layer in range(len(getWeights2)): if getWeights2[layer].ndim == 2: for i in range(len(getWeights2[layer])): for j in range(len(getWeights2[layer][i])): if (random.random() < pickChance1): totalTrue += 1 one = getWeights2[layer][i][j] getWeights2[layer][i][j] = getWeights1[layer][i][j] if (one != getWeights2[layer][i][j]): changed += 1 total += 1 print(changed) print(totalTrue) print(total) print("") brain.set_weights(getWeights2) return Cart(brain)
def katalog(message): bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) cart = Cart(message.chat.id) text = message.text if text == 'Каталог': keyboard = types.InlineKeyboardMarkup() r = requests.get(url + 'category') for category in r.json(): if category['categories']: key = types.InlineKeyboardButton( text=category['name'], callback_data=('cat_' + str(category['id']))) keyboard.add(key) # for category in r.json()['categories']: # key = types.InlineKeyboardButton( # text=category['name'], callback_data=category['id']) # keyboard.add(key) bot.send_message(message.chat.id, text='Выбери категорию', reply_markup=keyboard) elif text == 'Корзина': # bot.edit_message_text(chat_id=message.chat.id, # message_id=message.message_id-1, text='test') keyboard = types.InlineKeyboardMarkup() key = types.InlineKeyboardButton('Заказать', callback_data='order') key_2 = types.InlineKeyboardButton('Очистить', callback_data='clear') keyboard.add(key, key_2) t = [ f"{prod['quantity']}x {prod['name']} - {prod['price']}р. - {prod['total_price']}р.\n" for prod in cart ] t = 'Корзина\n\n' + '\n'.join(t) + \ f'\nИтого: {cart.get_total_price()}р.' if cart: bot.send_message(message.chat.id, text=t, reply_markup=keyboard) else: bot.send_message(message.chat.id, text=t)
class DiscountsTestCase(unittest.TestCase): def setUp(self): self.user = User('username', 'askgha') self.cart = Cart(self.user) def test_discount_gt_1000(self): self.cart.add(Item('item1', 100), 10) self.assertEqual(self.cart.discount(), 50) def test_discount_lt_1000(self): self.cart.add(Item('item1', 10), 10) self.assertEqual(self.cart.discount(), 3) # def test_discount_bday(self): # self.user = User('username', 'askgha', bday = date.today()) # self.cart.add(Item('item1', 100)) # self.assertEqual(self.cart.discount(), 10) def test_bday_discount(self): cart = Mock() cart.user.bday = date.today() cart.total.return_value = 100 self.assertEqual(bday_discount(cart), 10)
model.add(Dense(units=16, activation='relu')) model.add(Dense(units=12, activation='relu')) return model def infoToArray(info): infoArray = np.array([0] * 7) infoArray[0] = info["health"] infoArray[1] = info["enemyHealth"] infoArray[2] = info["posx"] infoArray[3] = info["posxEnemy"] infoArray[4] = info["jumpHeight"] infoArray[5] = info["isAttacking"] infoArray[6] = info["attackIndex"] return infoArray json_file = open('model7.json', 'r') loaded_model_json = json_file.read() json_file.close() brain = model_from_json(loaded_model_json) brain.load_weights("GoodCarts/model7Gen81.h5") cart = Cart(brain) runCart(cart, 1, True)
# ------ Menu Definition ------ # menu_def = [ ['File', ['Open', 'Save', 'Exit', 'Properties']], [ 'Edit', ['Paste', [ 'Special', 'Normal', ], 'Undo'], ], ['Help', 'About...'], ] i = Item('Hamburger', 5) cart = Cart() cart.add_to_cart(i) cart.add_to_cart(Item('Fries', 3)) cart.add_to_cart(Item('Drinks', 3)) gui = cart.get_cart_viewable(input=True) # ------ Column Definition ------ # column1 = [ [ sg.Text('Number of Items', background_color='#F7F3EC', justification='center', size=(15, 1)) ], [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 1')],
def testCartAreCreatedEmpty(self): aCart = Cart(self.defaultCatalog()) self.assertTrue(aCart.isEmpty())
def clear(call): cart = Cart(call.message.chat.id) bot.delete_message(call.message.chat.id, call.message.message_id) cart.clear() bot.send_message(call.message.chat.id, 'Корзина пуста')
def testCartContainsAddedIsInCart(self): aCart = Cart(self.defaultCatalog()) aProduct = self.productSellByCompany() aCart.add(aProduct, 1) self.assertTrue(aCart.contains(aProduct))
def testCartIsNotEmptyAfterAddingProducts(self): aCart = Cart(self.defaultCatalog()) aProduct = self.productSellByCompany() aCart.add(aProduct, 1) self.assertFalse(aCart.isEmpty())
def regetCart(self): self.cart = Cart(self.getName())
def __init__(self, name, pw, em, phone, q, a): User.__init__(self, name, pw, em, phone, q, a) self.cart = Cart(name)