def solution():
    ingredients = [Ingredient.parse_line(line) for line in input_data]
    max_score = -float('inf')
    for ratios in generate_divisions(100, len(ingredients)):
        sum_ingredients = Ingredient.empty_ingredient()
        for ingredient, ratio in zip(ingredients, ratios):
            sum_ingredients += ingredient.get_amount(ratio)

        score = sum_ingredients.get_full_score()
        if score > max_score:
            max_score = score
    return max_score
Example #2
0
 def make_ingredient_one_modifier():
     ingred = "Salt"
     cups = 0.06
     ounces = ''
     grams = 16
     modifiers = ["Morton's Kosher"]
     return Ingredient(ingred, cups,
                       ounces, grams, modifiers)
def main():
##    train_for(['alter', 'Rum and Coke', 'alcoholic'], ['command_training.csv', 'drink_training.csv', 'flavor_training.csv'])
    #make me a <drink>
##    train_many('make', drinks = create_presets.getdrinks())
    #make me a <flavor> drink
##    train_many('make', flavors = Ingredient.flavorlist())
    #make me a <flavor> <drink>
    train_many('make', drinks = create_presets.getdrinks(), flavors = Ingredient.flavorlist())
Example #4
0
 def make_ingredient_two_modifiers():
     ingred = "Apples"
     cups = "1.00"
     ounces = "3.00"
     grams = 85
     modifiers = ["dried", "diced"]
     return Ingredient(ingred, cups,
                       ounces, grams, modifiers)
 def addIngredient(self,name,quantity):
     ''' Used to add an ingredient into the coffee_machine.
         Parameters:
             name of type str
             quantity of type int
     '''
     i = Ingredient(name,quantity)
     self.ingredients[name]=i
     return True
Example #6
0
  def get(self):
    rec_key = ndb.Key("Recipe", "Fried Chicken")
    q = Ingredient.query(ancestor=rec_key)

    rec = rec_key.get()
    recipes = [rec.name]

    path = os.path.join(os.path.dirname(__file__) + '../../views', 'index.html')
    self.response.write(template.render(path, {"recipes": recipes}))
Example #7
0
def ingredients_from_file(filename):
    ingredients = []
    with open(filename) as file:
        for line in file:
            divided_line = line.split(" ", 2)
            ounces = float(divided_line[0])
            name = divided_line[2]
            ingredients.append(Ingredient(ounces, name))

    return ingredients
Example #8
0
def test_us2_3(sys):

    frenchFriess1 = Ingredient("French Fries", sys.getStockBasePrice("Small French Fries"), 2)
    frenchFriesl1 = Ingredient("French Fries", sys.getStockBasePrice("Large French Fries"), 2)

    cokel = Ingredient("Coca Cola", sys.getStockBasePrice("Bottle Coca Cola"), 2)
    cokes = Ingredient("Coca Cola", sys.getStockBasePrice("Can Coca Cola"), 3)

    side23 = Extra()
    side23.addExtra(frenchFriess1)
    side23.addExtra(frenchFriesl1)
    side23.addExtra(cokel)
    side23.addExtra(cokes)
    assert len(side23.ingredient) == 4
    print("========= receipt ===========")
    order23 = sys.makeOrder([], [side23], 'preparing', 23)
    print("=============================")
    print('')
    print("test us2_3 finishes \n")
Example #9
0
    def less_healthy(self):
        num_items_replaced = 0
        for i in range(len(self.ingredients)):
            found = None
            for kind, matches in less_healthy_conversions.items():
                for match in matches:
                    if match in self.ingredients[i].name:
                        found = kind
                        break

            if found is None:
                continue

            old = self.ingredients[i].name
            if self.ingredients[i].measure == 'item':
                self.ingredients[i].quantity /= 2.0
                self.ingredients[i].measure = 'cup'
            descs = ' '.join(self.ingredients[i].descriptors)
            descs = descs + ' ' + ' '.join(self.ingredients[i].preparations)
            descs.strip()
            new_ing = Ingredient('{} {} {} {}'.format(
                self.ingredients[i].quantity, self.ingredients[i].measure,
                descs, found))
            self.ingredients[i] = new_ing

            new = self.ingredients[i].name

            num_items_replaced += 1
            yield old, new

        if num_items_replaced == 0:
            # guess new ingredient
            ing_str, stp_str = random.choice(less_healthy_conversions)

            # add new ingredient
            new_ing = Ingredient(ing_str)
            self.ingredients.append(new_ing)

            # add new step
            new_stp = Step(stp_str, self.ingredients)
            self.steps.append(new_stp)

            yield None, new_ing.name
Example #10
0
    def test_add_food(self):
        old_size = len(self.list.food)
        banana_split = Food(
            "banana_split"
        )  # So that the food that we compare have at least two ingredients
        banana_ing = Ingredient("banana", 75, 60, 0, 5)
        banana_split.add_ingredient(banana_ing, 100, 100)
        cream_ing = Ingredient("cream", 190, 100, 10, 50)
        banana_split.add_ingredient(cream_ing, 25, 45, True)
        sandwich = Food("sandwich")
        bread_ing = Ingredient("bread", 100, 80, 0, 20)
        ham_ing = Ingredient("ham", 60, 5, 30, 10)
        sandwich.add_ingredient(bread_ing, 100, 100)
        sandwich.add_ingredient(ham_ing, 100, 100)

        self.list.add_food(banana_split)  # We add the food to the list
        self.list.add_food(sandwich)  # We add the food to the list
        self.assertEqual(old_size + 2, len(
            self.list.food))  # We check if the list is bigger by one element
Example #11
0
def test_view_menu(gourmet_fixture):
    print("Test viewing menu options")

    assert len(gourmet_fixture.inventory.find_in_stock()) == 31
    gourmet_fixture.inventory.update_stock(Ingredient('Onion', 2, 300, 1), 0)
    assert len(gourmet_fixture.inventory.find_in_stock()) == 31

    in_stock = gourmet_fixture.inventory.find_in_stock()
    for item in in_stock:
        assert item.name != None and item.price != None and item.calories != None
Example #12
0
def search():
    ingredient = request.args.get('ingredient',
                                  default='organic bananas',
                                  type=str)
    app.logger.debug(f'searching for {ingredient}')
    ingredient = Ingredient.retrieve_by_name(ingredient)
    if ingredient:
        products = Product.search_contains_ingredient(ingredient.id)
        return jsonify({'total': len(products), 'products': products})
    else:
        return jsonify([])
Example #13
0
 def __init__(self, ingredient: Union[Ingredient, str], quantity: complex,
              measurement: Optional[str]=None,
              condition: Optional[str]=None):
     self.ingredient: Ingredient
     if isinstance(ingredient, Ingredient):
         self.ingredient = ingredient
     else:
         self.ingredient = Ingredient(ingredient)
     self.quantity: complex = quantity
     self.measurement: Optional[str] = measurement
     self.condition: Optional[str] = condition
Example #14
0
 def _calcflavorlevels(self):
     """Calculates the drink's value for each flavor
     """
     ingredients = self.ingredients
     #find the current level of each flavor
     for flavor in Ingredient.flavorlist():
         level = 0
         for ingredient, num_parts in ingredients.iteritems():
             level += ingredient.flavorvalue(flavor) * num_parts
         level /= self.total_parts
         self.levels[flavor] = level
Example #15
0
def edit_recipe(recipe_id):
    form = EditRecipeForm()

    recipe = Recipe.find_by_id(recipe_id)

    ingredients = Ingredient.get_by_recipe_id(recipe_id)

    # set default username
    form.name.data = recipe.name
    form.description.data = recipe.description
    form.instructions.data = recipe.instructions

    # if form is valid
    if form.validate_on_submit():

        sql = sqlite3.connect("database.db")

        try:

            conn = sql.cursor()

            # get user info and save it
            recipe.name = request.form["name"]
            recipe.description = request.form["description"]
            recipe.instructions = request.form["instructions"]

            recipe.save(conn)

            number_of_ingredients = int(request.form["number-of-ingredients"])

            for i in range(0, len(ingredients)):
                index = str(ingredients[i].id)

                ingredients[i].name = request.form["ingredient-name-" + index]
                ingredients[i].quantity = request.form["ingredient-quantity-" +
                                                       index]
                ingredients[i].unit = request.form["ingredient-unit-" + index]

                ingredients[i].save(conn)

            return redirect("/")

        except sql.Error:

            conn.rollback()

            return redirect("/error")

    # template edit_profile form
    return render_template("edit_recipe.html",
                           form=form,
                           recipe=recipe,
                           ingredients=ingredients)
Example #16
0
def test_us2_1_2(sys):

    burger12 = Burger()
    sweetbun12 = Ingredient("Sweet Bun", sys.getStockBasePrice("Sweet Bun"), 2)
    chickpatty12 = Ingredient("Chicken Patty", sys.getStockBasePrice('Chicken Patty'), 1)
    error12 = burger12.addBuns(sweetbun1)
    error12 = burger12.addPatties(chickpatty1)

    burger12 = Burger()
    sweetbun12 = Ingredient("Sweet Bun", sys.getStockBasePrice("Sweet Bun"), 2)
    chickpatty12 = Ingredient("Chicken Patty", sys.getStockBasePrice('Chicken Patty'), 1)
    error13 = burger12.addBuns(sweetbun12)
    error14 = burger12.addPatties(chickpatty12)

    error1 =  sys.reduceStock()
    assert error13 == None
    assert error12 == None
    assert error1 == 'Sorry it is out stock'
    assert error14 == None

    print('test us2_1_2 has finished')
Example #17
0
def burger_fixture():
	system = RestaurantSystem()
	
	bun_list = ['Bun', 'Sandwich']
	patty_list = ['Chicken Patty', 'Vegetarian Patty', 'Beef Patty']
	ingredient_list = ['Tomato', 'Lettuce', 'Tomato Sauce', 'Chili Sauce', 'Mayonnaise Sauce', 'Cheddar Cheese', 'Sweet Cheese']
	for name in bun_list:
		system.ingredients.append(Ingredient(name, 2, 300, 1))
		system.inventory.update_stock(Ingredient(name, 2, 300, 1),300)
	for name in patty_list:
		system.ingredients.append(Ingredient(name, 5, 600, 1))
		system.inventory.update_stock(Ingredient(name, 5, 600, 1),200)
	for name in ingredient_list:
		system.ingredients.append(Ingredient(name, 0.5, 50, 1))
		system.inventory.update_stock(Ingredient(name, 0.5, 50, 1),100)
	
	side_list = ['Nugget', 'Chips', 'Salad', 'Rice', 'Grilled Corn']
	contained_list = ['Water', 'Coca Cola', 'Fanta', 'Sprite', 'Sunkist']
	juice_list = ['Orange Juice', 'Watermelon', 'Pineapple', 'Apple']
	for name in side_list:
		system.sides_drinks.append(SideDrink(name, 'Side', 'Small', 2, 200, 75))
		system.sides_drinks.append(SideDrink(name, 'Side', 'Medium', 2.5, 300, 125))
		system.sides_drinks.append(SideDrink(name, 'Side', 'Large', 3, 400, 175))
		system.inventory.update_stock(SideDrink(name, 'Side', 'Stock', 2, 200, 1), 5000)
	for name in contained_list:
		system.sides_drinks.append(SideDrink(name, 'Drink', 'Can', 2, 100, 1))
		system.sides_drinks.append(SideDrink(name, 'Drink', 'Bottle', 3, 200, 1))
		system.inventory.update_stock(SideDrink(name, 'Drink', 'Can', 2, 100, 1), 30)
		system.inventory.update_stock(SideDrink(name, 'Drink', 'Bottle', 3, 200, 1), 30)
	for name in juice_list:
		system.sides_drinks.append(SideDrink(name, 'Drink', 'Small', 4, 150, 250))
		system.sides_drinks.append(SideDrink(name, 'Drink', 'Medium', 5, 200, 450))
		system.inventory.update_stock(SideDrink(name, 'Drink', 'Stock', 4, 150, 400), 3000)
	
	return system
Example #18
0
def test_us_7(sys):

    # add some different sizes of sides and drinks in to inventory
    frenchFriesS7 = Ingredient("Small French Fries", sys.getStockBasePrice("Small French Fries"),5)
    frenchFriesL7 = Ingredient("Large French Fries", sys.getStockBasePrice("Large French Fries"),5)
    frenchFriesM7= Ingredient("Medium French Fries", sys.getStockBasePrice("Medium French Fries"),5)
    cokeL7 = Ingredient("Large Coca Cola", sys.getStockBasePrice("Large Coca Cola"),2)
    cokeS7 = Ingredient("Small Coca Cola", sys.getStockBasePrice("Small Coca Cola"),3)

    side7 = Extra()
    drink7 = Extra()

    side7.addExtra(frenchFriesS7)
    side7.addExtra(frenchFriesL7)
    side7.addExtra(frenchFriesM7)

    drink7.addExtra(cokeL7)
    drink7.addExtra(cokeS7)

    print(side7)
    print(drink7)
    print("test us7 has finished\n")
Example #19
0
    def veganify(self):
        for i in range(len(self.ingredients)):
            found = None
            for kind, matches in meat_types.items():
                for match in matches:
                    if match in self.ingredients[i].name:
                        found = kind
                        break

            if found is None:
                for replacement, matches in vegan_to_meat.items():
                    for match in matches:
                        if match in self.ingredients[i].name.lower():
                            old = self.ingredients[i].name
                            new = replacement
                            new_ing = Ingredient('{} {} {}'.format(
                                self.ingredients[i].quantity,
                                self.ingredients[i].measure, new))
                            self.ingredients[i] = new_ing
                            yield old, new
                continue

            old = self.ingredients[i].name
            new = random.choice(meat_to_veg[found])
            if self.ingredients[i].measure == 'item':
                self.ingredients[i].quantity /= 2.0
                self.ingredients[i].measure = 'cup'
            descs = ' '.join(self.ingredients[i].descriptors)
            descs = descs + ' ' + ' '.join(self.ingredients[i].preparations)
            descs.strip()
            new_ing = Ingredient('{} {} {} {}'.format(
                self.ingredients[i].quantity, self.ingredients[i].measure,
                descs, new))
            new_ing = Ingredient('{} {} {}'.format(
                self.ingredients[i].quantity, self.ingredients[i].measure,
                new))
            self.ingredients[i] = new_ing

            yield old, new
Example #20
0
    def add_ingredient(self):
        """Helper function for the mutate function, adds an ingredient uniformly selected at random."""
        # ensures that we don't break the program if all the ingredients are in a recipe
        if len(self.ingredients) == len(self.master_ingredients):
            return

        ingredient_names = [ingredient.name for ingredient in self.ingredients]

        # take the difference between the master set and this recipe's names
        new_ingredient_name = random.choice(
            tuple(self.master_ingredients - set(ingredient_names)))
        self.ingredients.append(
            Ingredient(round(random.uniform(0, 16), 2), new_ingredient_name))
 def createNewIngredient(
     self, ingredientName, pricePerUnit, initialQuantity
 ):  #Creates a new instance of Ingredient. Does NOT assign it to any dictionaries.
     try:
         validNewIngredientCheck(ingredientName, pricePerUnit,
                                 initialQuantity)
     except FieldTypeError as error:
         print(error)
     except IngredientFieldError as error:
         print(error)
     else:
         self.storeIngredient(
             Ingredient(ingredientName, pricePerUnit, initialQuantity))
Example #22
0
 def get_ingredients(self, page):
     soup = BeautifulSoup(self.get_page(page), 'html.parser')
     ingredients = []
     tbody = soup.find('tbody')
     for tr in tbody.find_all('tr'):
         tds = tr.find_all('td')
         date = datetime.now().date()
         ingredients.append(
             Ingredient(date, date, tds[0].text.strip(), int(tds[1].text),
                        float(tds[2].text.replace(',', '.')),
                        float(tds[3].text.replace(',', '.')),
                        float(tds[4].text.replace(',', '.')),
                        self.BASE_URL + tds[0].find('a')['href']))
     return ingredients
Example #23
0
def test_us_6(sys):

    #frenchFriesS = Inventory("Small French Fries", 3, 130)
    assert sys.frenchFriesS.quantity == 130
    side6 = Extra()
    frenchFries6 = Ingredient("Small French Fries", sys.getStockBasePrice("Small French Fries"), 2)
    assert frenchFries6.quantity == 2
    side6.addExtra(frenchFries6)
    sys.reduceStock(frenchFries6)
    assert sys.frenchFriesS.quantity == 128
    sys.refillStock("Small French Fries", 4)
    assert sys.frenchFriesS.quantity == 132

    print("test us6 has finished\n")
Example #24
0
def test_us4_1_2(sys):

    # order some drinks
    drink412 = Extra()
    fanta1 = Ingredient('Fanta', sys.getStockBasePrice('Fanta'), 5)
    drink412.addExtra(fanta1)

    # order a burger
    burger412 = Burger()
    whiteBun412 = Ingredient('White Bun', sys.getStockBasePrice('White Bun'), 4)
    beefPatty412 = Ingredient("Beef Patty", sys.getStockBasePrice('Beef Patty'), 2)
    lettuce412 = Ingredient("Lettuce", sys.getStockBasePrice("Lettuce"), 3)
    burger412.addIngredient(whiteBun412)
    burger412.addIngredient(lettuce412)
    burger412.addPatties(beefPatty412)

    # order a side
    side412 = Extra()
    frenchFries412 = Ingredient("friess",sys.getStockBasePrice('Small French Fries'),2)
    side412.addExtra(frenchFries412)
    print("========= receipt ===========")
    o = sys.makeOrder([burger412],[drink412,side412],'preparing',6)
    assert o.totalPrice() == 52
    print("test us4_1_2 has finished \n")
Example #25
0
	def __importData(self):
		"""Import data from Excel file and remove the old data""" 
		
		for aIdxRow in xrange(self.__sheetNutriments.nrows):
			if aIdxRow > 3 : # Pull title rows
				aTestNum = self.__sheetNutriments.cell(rowx=aIdxRow,colx=self.__valuesColsNutriments["numero"]).value
				try: # Test to avoid other titles
					int(aTestNum)
				except:
					continue
				
				aIngredient = Ingredient()
				
				# Set of each nutriment
				aIngredient.numero = self.__sheetNutriments.cell(rowx=aIdxRow,colx=self.__valuesColsNutriments["numero"]).value
				aIngredient.nom = (self.__sheetNutriments.cell(rowx=aIdxRow,colx=self.__valuesColsNutriments["nom"]).value).encode('utf-8')
				aIngredient.calories = self.__sheetNutriments.cell(rowx=aIdxRow,colx=self.__valuesColsNutriments["calories"]).value
				aIngredient.carbo = self.__sheetNutriments.cell(rowx=aIdxRow,colx=self.__valuesColsNutriments["carbo"]).value
				aIngredient.proteine = self.__sheetNutriments.cell(rowx=aIdxRow,colx=self.__valuesColsNutriments["proteine"]).value
				aIngredient.lipide = self.__sheetNutriments.cell(rowx=aIdxRow,colx=self.__valuesColsNutriments["lipide"]).value
				aIngredient.fibre = self.__sheetNutriments.cell(rowx=aIdxRow,colx=self.__valuesColsNutriments["fibre"]).value
				aIngredient.sodium = self.__sheetNutriments.cell(rowx=aIdxRow,colx=self.__valuesColsNutriments["sodium"]).value
				
				# Append to the imported data list
				self.__ingredients.append(aIngredient)
				
		for aIdxRow in xrange(self.__sheetGrease.nrows):
			if aIdxRow > 3 : # Go to the beginning
				aTestNum = self.__sheetGrease.cell(rowx=aIdxRow,colx=self.__valuesColsGrease["numero"]).value
				try:
					int(aTestNum) # Test to avoid Excel titles
				except:
					continue
				aNumSature = self.__sheetGrease.cell(rowx=aIdxRow,colx=self.__valuesColsGrease["numero"]).value
				self.__ingredients[int(aNumSature)-1].sature = self.__sheetGrease.cell(rowx=aIdxRow,colx=self.__valuesColsGrease["sature"]).value
		
		aDataFile = open(self.__dataFilePath, 'w')
		
		pickle.dump(self.__ingredients, aDataFile)
		
		aDataFile.close()
Example #26
0
    def fromDictionary(cls, dictionary):
        title = dictionary["Title"].replace("\r", "")
        title = title.replace("\n", "")
        rating = dictionary["Rating"]
        instructions = dictionary["Instructions"]
        ingredientStrings = dictionary["IngredientList"]
        description = dictionary["Description"]

        ingredientList = []
        for s in ingredientStrings:
            newIngredient = Ingredient.fromString(s)
            if not newIngredient == None:
                ingredientList.append(newIngredient)

        return cls(ingredientList, title, description, instructions, rating)
Example #27
0
def testMKOrder(sys):
    #order = Order('parparing',1)
    burger = Burger()
    muffinBun1 = Ingredient("Muffin Bun", sys.getStockBasePrice("Muffin Bun"), 2)
    beefPatty1 = Ingredient("Beef Patty", sys.getStockBasePrice('Beef Patty'), 1)
    sys.reduceStock(muffinBun1)
    sys.reduceStock(beefPatty1)
    burger.addBuns(muffinBun1)
    burger.addPatties(beefPatty1)

    side = Extra()
    chickenNuggetL1 = Ingredient('Large Chicken Nuggets',sys.getStockBasePrice("Large Chicken Nuggets"),1)

    side.addExtra(chickenNuggetL1)

    print("======= receipt ========")
    order1 = sys.makeOrder([burger],[side],'parparing',1)
    print('========================')
    #assert error == None
    assert burger.calculatePrice() == 18
    assert side.calculatePrice() == 7
    assert order1.totalPrice() == 25
    #assert len(sys.orders) == 1
    print('test 1 passed')
Example #28
0
def parse_ingredients(content_lines):
    ingredients = []
    pattern = re.compile(INPUT_PATTERN)

    for line in content_lines:
        values = pattern.match(line).groupdict()

        for key in values:
            try:
                values[key] = int(values[key])
            except ValueError:
                continue

        ingredients.append(Ingredient(**values))

    return ingredients
Example #29
0
def test_MKOrder_alt4(sys):

    drink = Extra()
    fanta1 = Ingredient('Fanta',sys.getStockBasePrice('Fanta'),5)

    drink.addExtra(fanta1)

    assert drink.calculatePrice() == 15

    print("======= receipt ========")
    order4 = sys.makeOrder([],[drink],'preparing',4)
    print('=========================')
    assert order4.totalPrice() == 15
    assert order4.mainFoods == []
    #assert  len(sys.orders) == 3
    print("test 5 passed")
    def _parse_ingredient(self, description):
        """ Parse the ingredient information """

        # ingredients = []
        blob = TextBlob(description)
        name_words = []

        quantity = float(0)
        format = ""
        name = ""
        unit = ""
        for word in blob.tags:

            # Extract ingredient quantity
            if word[1] == unicode('CD') or word[0] == '2':
                if re.sub('[a-zA-Z\s]', '', word[0]) != '':
                    quantity = float(1)
                    quantity = quantity * self._to_float(word[0])

            # Extract unit measurement and name
            elif word[1] in ("NN", "NNS", "NNP", "NNPS", "VBG", "JJ"):
                if str(word[0]) == "flour":
                    w = str(word[0])
                else:
                    w = str(word[0].singularize())

                if w in self.unit_measures:
                    unit = self.unit_measures[w]
                else:
                    name_words.append(w)

            # Extract format
            else:
                format += str(word[0])

        if unit == "":
            unit = "each"

        if quantity == float(0):
            unit = "each"
            quantity = 1

        name = self._extract_name(name_words)
        ingredient = Ingredient(name, unit, quantity, format, description)

        return ingredient
    def create_ingredients(self):
        ingredients = input('enter recipe ingrediants: ')
        ingr_name_list = ingredients.split(', ')

        for ingr in ingr_name_list:
            #check if ingredient sharing name exists
            found = shelf.master_list.find_ing_by_name(ingr)
            if not found and ingr is not '':
                print(f'new ingredient \'{ingr}\' enter additional info')
                cost = input('enter ingrediant cost: ')
                location = input('enter ingrediant location: ')
                servings = input('enter ingrediant servings: ')
                new_ingr = Ingredient(ingr, cost, location, servings)
                shelf.master_list.ingredients.append(new_ingr)
            elif found and ingr is not '':
                print(f'    ingredient with name \'{ingr}\' already exists')
            else:
                print('    invalid ingredient name')
Example #32
0
  def get(self):
    recname = "Fried Chicken"
    rec = Recipe(id=recname, name=recname, totalprice=8.50, totaltime=0.5, healthrating=2, notes="Don't cook on high heat!")
    rec_key = rec.put()

    ingred = Ingredient(parent=rec.key, id="Chicken", name="Chicken", price=2.50)
    ingred.put()

    ingred1 = Ingredient(parent=rec.key, id="Flour", name="Flour", price=0.10)
    ingred1.put()

    ##key = ndb.Key("Recipe", "Fried Chicken")
    ##key.delete()

    self.response.write("Data filled!")
Example #33
0
def test_us3_245(sys):

    # make a burger
    burger32 = Burger()
    whiteBun32 = Ingredient('White Bun', sys.getStockBasePrice('White Bun'), 4)
    beefPatty32 = Ingredient("Beef Patty", sys.getStockBasePrice('Beef Patty'), 2)
    lettuce32 = Ingredient("Lettuce", sys.getStockBasePrice("Lettuce"), 4)
    burger32.addBuns(whiteBun32)
    burger32.addPatties(beefPatty32)
    burger32.addIngredient(lettuce32)

    burger_price = burger32.calculatePrice()
    assert burger_price == 32

    #make a wrap
    wrap32 = Wrap()
    wholemealWrap32 = Ingredient('Wholemeal Wrap', sys.getStockBasePrice('Wholemeal Wrap'), 1)
    chickenPatty32 = Ingredient("Chicken Patty", sys.getStockBasePrice('Chicken Patty'), 2)
    beefPatty3 = Ingredient("Beef Patty", sys.getStockBasePrice('Beef Patty'), 1)
    wrap32.addIngredient(wholemealWrap32)
    wrap32.addPatties(chickenPatty32)
    wrap32.addPatties(beefPatty3)

    wrap_price = wrap32.calculatePrice()
    assert wrap_price == 21

    drink32 = Extra()
    coke32 = Ingredient("Small Coca Cola", sys.getStockBasePrice("Can Coca Cola"), 2)
    drink32.addExtra(coke32)
    assert coke32.quantity == 2

    drink_price = drink32.calculatePrice()
    assert drink_price == 6
    print("========= receipt ===========")
    order = sys.makeOrder([burger32,wrap32], [drink32],'Preparing', 4)
    print("=============================")
    assert order.totalPrice() == 59
    #assert len([]) == 2
    #assert len(order32.extraFoods) == 1
    #totalPrice = order32.totalPrice()
    #assert totalPrice == 59

    print("test us3_245 have finished\n")
Example #34
0
	def parse(db, raw_recipe):
		"""parsing recipe download into recipe structure"""
		(raw_name, raw_ingredients, raw_directions) = raw_recipe
                tokenized_dirs = [ nltk.word_tokenize(d) for d in raw_directions]
                tagged_directions = [ 
                        nltk.pos_tag(d) for d in tokenized_dirs
                ]
		name = raw_name
		ingredients = [Ingredient.parse(db, i) for i in raw_ingredients]

		directions = [
                        Direction.parse(d, ingredients)
                        for d in tagged_directions
                ]
		methods = Method.find_methods(directions)
                tok_text = [
                        word
                        for d in tokenized_dirs
                        for word in d                        
                ]
		tools   = Tool.find_tools(tok_text)
		return Recipe(name, ingredients, tools, methods, directions)
Example #35
0
 def add_ingredient(self): #TODO broken! needs to add ingredient to shelf and add id to recipe
     # dont think this is broken any more...
     ingredients = input('enter recipe ingredients: ')
     comp_name_list = ingredients.split(', ').lower()
     
     for comp_name in comp_name_list:
         #check if ingredient sharing name exists
         found = shelf.master_list.find_comp_by_name(comp_name)
         if not found and comp_name is not '':
             print(f'new ingredient {comp_name} enter additional info')
             cost = input('enter ingredient cost: ')
             location = input('enter ingredient location: ').lower()
             servings = input('enter ingredient servings: ')
             new_ingr = Ingredient(comp_name, cost, location, servings)
             shelf.master_list.ingredients.append(new_ingr)
             self.get_rec().ingredients.append(new_ingr.id)
             print(f'    {new_ingr.name} added')
         elif found and comp_name is not '':
             self.get_rec().ingredients.append(found.id)
             print(f'    {found.name} added')
         else:
             print('    \'\' is not valid component name')
Example #36
0
    def __init__(self, url):
        self.ingredients = []
        self.tools = []
        self.prep_methods = []
        self.step_methods = []
        self.steps = []

        raw_recipe = parse_recipe(url)
        raw_ingredients = raw_recipe['ingredients']
        raw_directions = raw_recipe['directions']
        self.recipe_name = raw_recipe['name']

        for ingredient in raw_ingredients:
            try:
                processed_ingredient = Ingredient(ingredient)
            except ValueError:
                continue
            self.ingredients.append(processed_ingredient)
            for tool in processed_ingredient.tools:
                if tool not in self.tools:
                    self.tools.append(tool)
            for method in processed_ingredient.methods:
                if method not in self.prep_methods:
                    self.prep_methods.append(method)

        for direction in raw_directions:
            for sentence in direction.split('.'):
                sentence = sentence.strip()
                if len(sentence) > 0:
                    processed_step = Step(sentence, self.ingredients)
                    self.steps.append(processed_step)
                    for tool in processed_step.tools:
                        if tool not in self.tools:
                            self.tools.append(tool)
                    for method in processed_step.methods:
                        if method not in self.step_methods:
                            self.step_methods.append(method)
def createIngredient():
    if request.method == "POST":
        if request.form.get("createIngredient"):
            ingredName = request.form.get("nameField")
            quantity = request.form.get("quantityField")
            price = request.form.get("priceField")
            ingredDict = request.form.get("dictSelect")

            try:
                validNewIngredientCheck(ingredName, float(price),
                                        int(quantity))
            except FieldTypeError as error:
                print(error)
                return render_template("createIngredient.html", error=error)
            except IngredientFieldError as error:
                print(error)
                return render_template("createIngredient.html", error=error)
            except ValueError as error:
                print(error)
            else:
                newIngred = Ingredient(ingredName, price, quantity)
                if ingredDict == "Main":
                    print("About to add to mains ")
                    GourmetBurgers.pantry.addMainIngredient(newIngred)
                elif ingredDict == "Side":
                    print("About to add to sides")
                    GourmetBurgers.pantry.addSideIngredient(newIngred)
                elif ingredDict == "Dessert":
                    GourmetBurgers.pantry.addDessertIngredient(newIngred)
                return render_template("createIngredient.html",
                                       ingred=newIngred)

        elif request.form.get("cancel"):
            return redirect(url_for("inventoryCheck"))

    return render_template("createIngredient.html")
Example #38
0
class IO(object):
    
    '''
    Input output luokka, jolla ladataan raaka-aineet, reseptit ja varastolistaus tiedostoista. Tämän lisäksi nämä voidaan tallentaa tiedostoihin annetusta listasta.
    '''

    def loadIngredients(self, inputLines):

        '''
        Tämä metodi lukee raaka-aineet tiedostosta ja palauttaa ne listana.
        
        Args:
            :inputLines: tiedoston kahva (fileIO), josta tiedot luetaan.
        
        Returns:
            :ingredientList: Raaka-aine oliot listana
            :successCount: Montako luettiin onnistuneesti sisään
            :errorCount: Montako jäi virheeseen luettaessa
        Raises:
            :CorruptedFileError: Jos kohdataan tuntematon tiedostotyyppi
        '''

        self.date = False
        self.name = False
        self.density = False
        self.success = True
        self.ingredientList = []
        
        self.succesCount = 0
        self.errorCount = 0
        
 
        currentLine = ''

        try:

    

            currentLine = inputLines.readline()
            headerParts = currentLine.split(" ")

            # Process the data we just read.

            if headerParts[0].strip() != "INGREDIENTLIST":
                raise CorruptedFileError("Unknown file type")



            currentLine = inputLines.readline()
            headerParts = currentLine.split(" ")
            while currentLine != '':
         
                if headerParts[0].strip().lower() == '#ingredient':
                        self.ingredient = Ingredient()
                        currentLine = inputLines.readline()
                        headerParts = currentLine.split(":")    
                        while currentLine != '':
                            try:
                                if currentLine[0] == '#':
                                    break
                                
                                if headerParts[0].strip().lower() == 'date':
                                    self.ingredient.setDate(headerParts[1].strip())
                                    self.date = True

                                    
                                elif headerParts[0].strip().lower() == 'name':
                                    self.ingredient.setName(headerParts[1].strip())
                                    self.name = headerParts[1].strip()

                                
                                elif headerParts[0].strip().lower() == 'density':
                                    self.ingredient.setDensity(headerParts[1].strip())
                                    self.density = True

                                
                                elif headerParts[0].strip().lower() == 'recipe':
                                    self.ingredient.setRecipe(headerParts[1].strip())
                                
                                elif headerParts[0].strip().lower() == 'allergen':
                                    self.ingredient.addAllergen(headerParts[1].strip())

                                        
                                currentLine = inputLines.readline()
                                headerParts = currentLine.split(":")   
                            except SetAttributeError as e:
                                print(str(e))
                                self.success = False
                                break 
                            
                        if not self.name or not self.density or not self.date or not self.success:
                            self.errorCount +=1
                            if self.name:
                                print("Seuraavan raaka-aineen lukeminen epäonnistui:", self.name)
                            else:
                                print("Raaka-aineen luku epäonnistui, jatketaan seuraavaan.")
                        else:
                            self.succesCount +=1
                            self.ingredientList.append(self.ingredient)
                            self.date = False
                            self.name = False
                            self.density = False
                            self.success = True
                        
                        
                else:
                    currentLine = inputLines.readline()
                    headerParts = currentLine.split(" ")
                    
            
    
            return self.ingredientList,self.succesCount,self.errorCount
        
        except IOError:


            raise CorruptedFileError("Raaka-aine tiedosto korruptoitunut")
     
        
    #################################################################################
        
    def loadRecipes(self, inputLines, ingredientsList):

        '''
        Tämä metodi lukee reseptit tiedostosta ja palauttaa ne listana.
                
        Args:
            :inputLines: tiedoston kahva (fileIO), josta tiedot luetaan.
            :ingredientList: Tunnetut raaka-aineet listana
        
        Returns:
            :recipesList: Resepti oliot listana
            :successCount: Montako luettiin onnistuneesti sisään
            :errorCount: Montako jäi virheeseen luettaessa
        Raises:
            :CorruptedFileError: Jos kohdataan tuntematon tiedostotyyppi
        '''

        self.date = False
        self.name = False
        self.time = False
        self.instructions = False
        self.ingredients = False
        self.outcome = False
        self.recipesList = []
        
        self.succesCount = 0
        self.errorCount = 0
 
        currentLine = ''

        try:

    

            currentLine = inputLines.readline()
            headerParts = currentLine.split(" ")

            # Process the data we just read.

            if headerParts[0].strip() != "RECIPELIST":
                raise CorruptedFileError("Unknown file type")



            currentLine = inputLines.readline()
            headerParts = currentLine.split(" ")
            while currentLine != '':
         
                if headerParts[0].strip().lower() == '#recipe':
                        self.recipe = Recipe()
                        currentLine = inputLines.readline()
                        headerParts = currentLine.split(":")    
                        while currentLine != '':
                            try:
                                if currentLine[0] == '#':
                                    break
                                
                                if headerParts[0].strip().lower() == 'date':
                                    self.recipe.setDate(headerParts[1].strip())
                                    self.date = True
                                    
                                elif headerParts[0].strip().lower() == 'name':
                                    self.recipe.setName(headerParts[1].strip())
                                    self.name = headerParts[1].strip()
                                
                                elif headerParts[0].strip().lower() == 'time':
                                    self.recipe.setTime(headerParts[1].strip())
                                    self.time = True

                                    
                                elif headerParts[0].strip().lower() == 'instruction':
                                    self.recipe.addInstruction(headerParts[1].strip())
                                    self.instructions = True
                                
                                elif headerParts[0].strip().lower() == 'outcome':
                                    if len(headerParts) != 3: break
                                    self.recipe.setOutcomeSize(headerParts[1].strip()) 
                                    self.recipe.setOutcomeUnit(headerParts[2].strip())
                                    self.outcome = True
                                
                                elif headerParts[0].strip().lower() == 'ingredient':
                                    if len(headerParts) != 4: 
                                        self.ingredients = False
                                        break
                                    self.ingredientContainer = IngredientContainer()
                                    self.ingredientContainer.setIngredient(headerParts[1].strip(), ingredientsList)
                                    self.ingredientContainer.setQuantity(headerParts[2].strip())
                                    self.ingredientContainer.setUnit(headerParts[3].strip())
                                    self.recipe.addIngredientContainer(self.ingredientContainer)
                                    self.ingredients = True
                                    
                                currentLine = inputLines.readline()
                                headerParts = currentLine.split(":")    
                                
                            except SetAttributeError as e:
                                print(str(e))
                                break
                            
                        if not self.name or not self.date or not self.time or not self.instructions or not self.ingredients or not self.outcome:
                            self.errorCount += 1
                            if self.name:
                                print("Seuraavan reseptin lukeminen epäonnistui:", self.name)
                            else:
                                print("Reseptin luku epäonnistui, jatketaan silti.")
                        else:
                            self.succesCount += 1
                            self.recipesList.append(self.recipe)
                            self.date = False
                            self.name = False
                            self.time = False
                            self.instructions = False
                            self.ingredients = False
                            self.outcome = False
                        
                        
                else:
                    currentLine = inputLines.readline()
                    headerParts = currentLine.split(" ")
                    
            
            return self.recipesList,self.succesCount,self.errorCount

            
        except IOError:


            raise CorruptedFileError("Reseptitiedosto korruptoitunut")
                             
        ########################################################################
        
        
    def loadStorage(self, inputLines, ingredientsList):

        '''
        Tämä metodi lukee varastolistauksen tiedostosta ja palauttaa ne listana.
                
        Args:
            :inputLines: tiedoston kahva (fileIO), josta tiedot luetaan.
            :ingredientList: Tunnetut raaka-aineet listana
        
        Returns:
            :storageList: Raaka-aine oliot listana
            :successCount: Montako luettiin onnistuneesti sisään
            :errorCount: Montako jäi virheeseen luettaessa
        Raises:
            :CorruptedFileError: Jos kohdataan tuntematon tiedostotyyppi
        '''

        self.success = None
        self.storageList = []
        
        self.succesCount = 0
        self.errorCount = 0
 
        currentLine = ''

        try:

    

            currentLine = inputLines.readline()
            headerParts = currentLine.split(";")

            # Process the data we just read.

            if headerParts[0].strip() != "STORAGELIST":
                raise CorruptedFileError("Unknown file type")
         
            currentLine = inputLines.readline()
            headerParts = currentLine.split(";")   
            while currentLine != '':
                try:
                    if len(headerParts) >2:
                        self.ingredientContainer = IngredientContainer()
                        self.ingredientContainer.setIngredient(headerParts[0].strip(), ingredientsList)
                        self.ingredientContainer.setQuantity(headerParts[1].strip()) 
                        self.ingredientContainer.setUnit(headerParts[2].strip())
                        self.success = True
                except SetAttributeError as e:
                    print(str(e))
                    self.success = False
                    
                if not self.success:
                    self.errorCount += 1
                    print("Varastorivin luku epäonnistui, jatketaan silti.")
                    self.success = None
                elif self.success:
                    self.succesCount += 1
                    self.storageList.append(self.ingredientContainer)
                    self.success = None
                    
                currentLine = inputLines.readline()
                headerParts = currentLine.split(";")   
                
                    
                    
            
            return self.storageList,self.succesCount,self.errorCount

            
        except IOError:


            raise CorruptedFileError("Varastotiedosto korruptoitunut")
        
        
    def saveRecipes(self,fileName, recipesList):
        
        '''
        Tämä metodi tallentaa reseptit tiedostoon ohjelman luettavassa muodossa. Tiedot tallennetaan ensin temp.rec tiedostoon, jonka jälkeen kyseinen tiedosto nimetään uudelleen halutun nimiseksi.
                
        Args:
            :fileName: Tiedostonimi, johon reseptit tallennetaan
            :recipesList: Resepti oliot listana

        '''

        tempFileName = "temp.rec"
        try:
            os.remove(tempFileName)
        except FileNotFoundError:
            pass
        with open(tempFileName, "w+") as tempFile:
            tempFile.write("RECIPELIST\n")
            for recipe in recipesList:
                tempFile.write("\n#Recipe\n")
                tempFile.write("Date                   : " + recipe.getDate() +"\n")
                tempFile.write("Name                   : " + recipe.getName() +"\n")
                tempFile.write("Time                   : " + str(recipe.getTime()) +"\n")
                tempFile.write("Outcome                : " +  str(recipe.getOutcomeSize()) + " : " + recipe.getOutcomeUnit() + "\n")
                for ingredient in recipe.getIngredients():
                    tempFile.write("Ingredient             : " + ingredient.getName() + " : " + str(ingredient.getQuantity()) + " : " + ingredient.getUnit() + "\n")
                for instruction in recipe.getInstructions():
                    tempFile.write("Instruction            : " + instruction + "\n")
        tempFile.close()
        try:
            os.remove(fileName)
        except FileNotFoundError:
            pass
        os.rename(tempFileName, fileName)

    
    def saveIngredients(self,fileName, ingredientsList):
        '''
        Tämä metodi tallentaa raaka-aineet tiedostoon ohjelman luettavassa muodossa. Tiedot tallennetaan ensin temp.ing tiedostoon, jonka jälkeen kyseinen tiedosto nimetään uudelleen halutun nimiseksi.
                
        Args:
            :fileName: Tiedostonimi, johon raaka-aineet tallennetaan
            :ingredientList: Raaka-aine oliot listana

        '''
        tempFileName = "temp.ing"
        try:
            os.remove(tempFileName)
        except FileNotFoundError:
            pass
        with open(tempFileName, "w+") as tempFile:
            tempFile.write("INGREDIENTLIST\n")
            for ingredient in ingredientsList:
                tempFile.write("\n#Ingredient\n")
                tempFile.write("Date                   : " + ingredient.getDate() +"\n")
                tempFile.write("Name                   : " + ingredient.getName() +"\n")
                tempFile.write("Density                : " + str(ingredient.getDensity()) +"\n")
                for allergen in ingredient.getAllergens():
                    tempFile.write("Allergen               : " + allergen + "\n")
                if ingredient.getRecipe():
                    tempFile.write("Recipe                 : " + ingredient.getRecipeGUI()+ "\n")
        tempFile.close()
        try:
            os.remove(fileName)
        except FileNotFoundError:
            pass
        os.rename(tempFileName, fileName)

    def saveStorage(self,fileName, storageList):
        '''
        Tämä metodi tallentaa varastossa olevat raaka-aineet tiedostoon ohjelman luettavassa muodossa. Tiedot tallennetaan ensin temp.sto tiedostoon, jonka jälkeen kyseinen tiedosto nimetään uudelleen halutun nimiseksi.
                
        Args:
            :fileName: Tiedostonimi, johon varaston raaka-aineet tallennetaan
            :storageList: Varaston raaka-aine oliot listana

        '''
        tempFileName = "temp.sto"
        try:
            os.remove(tempFileName)
        except FileNotFoundError:
            pass
        with open(tempFileName, "w+") as tempFile:
            tempFile.write("STORAGELIST\n")
            for ingredient in storageList:
                tempFile.write(ingredient.getName())
                tempFile.write(";")
                tempFile.write(str(ingredient.getQuantity()))
                tempFile.write(";")
                tempFile.write(ingredient.getUnit())
                tempFile.write("\n")
        tempFile.close()
        try:
            os.remove(fileName)
        except FileNotFoundError:
            pass
        os.rename(tempFileName, fileName)    
              
              
    def loadRecipesForIngredients(self,ingredientsList,recipesList):
        ''' 
        Tällä metodilla voidaan ladata kaikkien raaka-aineiden reseptit. Käytännössä tämä metodi kutsuu raaka-aineen loadrecipe() metodia
        
        Args:
            :ingredientList: Raaka-aine oliot listana
            :recipesList: Reseptio oliot listana
        '''
        
        for ingredient in ingredientsList:
            try:
                ingredient.loadRecipe(recipesList)
            except SetAttributeError as e:
                print(str(e))
                           
Example #39
0
    def loadIngredients(self, inputLines):

        '''
        Tämä metodi lukee raaka-aineet tiedostosta ja palauttaa ne listana.
        
        Args:
            :inputLines: tiedoston kahva (fileIO), josta tiedot luetaan.
        
        Returns:
            :ingredientList: Raaka-aine oliot listana
            :successCount: Montako luettiin onnistuneesti sisään
            :errorCount: Montako jäi virheeseen luettaessa
        Raises:
            :CorruptedFileError: Jos kohdataan tuntematon tiedostotyyppi
        '''

        self.date = False
        self.name = False
        self.density = False
        self.success = True
        self.ingredientList = []
        
        self.succesCount = 0
        self.errorCount = 0
        
 
        currentLine = ''

        try:

    

            currentLine = inputLines.readline()
            headerParts = currentLine.split(" ")

            # Process the data we just read.

            if headerParts[0].strip() != "INGREDIENTLIST":
                raise CorruptedFileError("Unknown file type")



            currentLine = inputLines.readline()
            headerParts = currentLine.split(" ")
            while currentLine != '':
         
                if headerParts[0].strip().lower() == '#ingredient':
                        self.ingredient = Ingredient()
                        currentLine = inputLines.readline()
                        headerParts = currentLine.split(":")    
                        while currentLine != '':
                            try:
                                if currentLine[0] == '#':
                                    break
                                
                                if headerParts[0].strip().lower() == 'date':
                                    self.ingredient.setDate(headerParts[1].strip())
                                    self.date = True

                                    
                                elif headerParts[0].strip().lower() == 'name':
                                    self.ingredient.setName(headerParts[1].strip())
                                    self.name = headerParts[1].strip()

                                
                                elif headerParts[0].strip().lower() == 'density':
                                    self.ingredient.setDensity(headerParts[1].strip())
                                    self.density = True

                                
                                elif headerParts[0].strip().lower() == 'recipe':
                                    self.ingredient.setRecipe(headerParts[1].strip())
                                
                                elif headerParts[0].strip().lower() == 'allergen':
                                    self.ingredient.addAllergen(headerParts[1].strip())

                                        
                                currentLine = inputLines.readline()
                                headerParts = currentLine.split(":")   
                            except SetAttributeError as e:
                                print(str(e))
                                self.success = False
                                break 
                            
                        if not self.name or not self.density or not self.date or not self.success:
                            self.errorCount +=1
                            if self.name:
                                print("Seuraavan raaka-aineen lukeminen epäonnistui:", self.name)
                            else:
                                print("Raaka-aineen luku epäonnistui, jatketaan seuraavaan.")
                        else:
                            self.succesCount +=1
                            self.ingredientList.append(self.ingredient)
                            self.date = False
                            self.name = False
                            self.density = False
                            self.success = True
                        
                        
                else:
                    currentLine = inputLines.readline()
                    headerParts = currentLine.split(" ")
                    
            
    
            return self.ingredientList,self.succesCount,self.errorCount
        
        except IOError:


            raise CorruptedFileError("Raaka-aine tiedosto korruptoitunut")