Esempio n. 1
0
    def test_overall(self):
        print("Testing Multiple Restaurants")
        requiredMeals = 50
        requiredInfo = Object()
        requiredInfo.vegetarian = 5
        requiredInfo.glutenFree = 7
        requiredInfo.nutFree = 0
        requiredInfo.fishFree = 0

        restaurants = []
        restaurants.append(Restaurant("A", 5, 4, 0, 0, 0, 36))
        restaurants.append(Restaurant("B", 3, 20, 20, 0, 0, 60))  # sorted by rating

        order = calculateRestaurants(requiredMeals, requiredInfo, restaurants)

        self.assertEqual(order[0].vegetarian, 4)
        self.assertEqual(order[0].glutenFree, 0)
        self.assertEqual(order[0].nutFree, 0)
        self.assertEqual(order[0].fishFree, 0)
        self.assertEqual(order[0].regular, 36)

        self.assertEqual(order[1].vegetarian, 1)
        self.assertEqual(order[1].glutenFree, 7)
        self.assertEqual(order[1].nutFree, 0)
        self.assertEqual(order[1].fishFree, 0)
        self.assertEqual(order[1].regular, 2)
Esempio n. 2
0
def main():
    restaurant = Restaurant("ROLL", 'chinese')
    restaurant.describe_restaurant()
    restaurant.open_restaurant()

    restaurant_two = Restaurant('HU FAMILY', 'Chinese')
    restaurant_three = Restaurant('FISH AND RICE', 'CHINESE')
    restaurant_two.describe_restaurant()
    restaurant_three.describe_restaurant()

    restaurant.number_served = 13  # 对类里的属性进行直接修改
    print(restaurant.number_served)
    restaurant.set_number_served(37)
    print(restaurant.number_served)
    restaurant.increment_number_served(39)
    restaurant.increment_number_served(39)
    print(restaurant.number_served)
    user1 = User('Lily', 'Albert', 23)
    user2 = User('Moris', 'Hamilton', 24)
    user3 = User('Jeff', 'Churchill', 27)
    user1.describe_user()
    user1.greet_user()
    user2.describe_user()
    user2.greet_user()
    user3.describe_user()
    user3.greet_user()

    user1.increment_login_attempts()
    user1.increment_login_attempts()
    print(user1.login_attempts)
    user1.reset_login_attempts()
    print(user1.login_attempts)
    pass
Esempio n. 3
0
def seed_restaurants():
    """Seed restaurants with test data."""
    r1 = Restaurant(name="Chef Zhao's")
    r2 = Restaurant(name="Fu Lam Mum")
    r3 = Restaurant(name="Chef Chu's")
    r4 = Restaurant(name="Queen House")
    r5 = Restaurant(name="Cafe Macs")
    db_session.add(r1)
    db_session.add(r2)
    db_session.add(r3)
    db_session.add(r4)
    db_session.commit()
Esempio n. 4
0
def parseRestaurantItems():
    rest_info = json.load(open('data/test_restaurants.json'))
    rest_reviews = json.load(open('data/test_reviews.json'))
    restaurant_list = []
    for i in range(len(rest_info)):
        # Creates list of item NAMES to be stored in the restaurant object
        item_names = []
        items_list = rest_info[i]['items']
        for item in items_list:
            item_names.append(item['name'])

        review_list = rest_reviews[i]['reviews']

        #Creates a list of item REVIEWS to be stored in the restaurant object
        review_comments = []
        for review in review_list:
            review_comments.append(review['comment'])

        #Creates a list of item REVIEWS to be stored in the restaurant object
        review_ratings = []
        for review in review_list:
            review_ratings.append(review['rating'])

        # Adds Restaurant object to a list of all restaurants
        restaurant_list.append(
            Restaurant(rest_info[i]['id'], rest_info[i]['name'], item_names,
                       review_comments, review_ratings))
    return restaurant_list
Esempio n. 5
0
def calculateRestaurants(requiredMeals, requiredInfo, restaurants):
    order = []
    for i in range(0, len(restaurants)):
        if requiredMeals > 0:  # only process until all required meals are ordered
            tempRestaurant = Object()  # empty object
            for type in ['vegetarian', 'glutenFree', 'nutFree', 'fishFree'
                         ]:  # iterate through the types of required food
                retVal, tempRequired, requiredMeals = calculator(
                    getattr(requiredInfo, type), type, requiredMeals,
                    restaurants[i])
                setattr(
                    tempRestaurant, type, retVal
                )  # set the temp restaurant's values ie: number of type of meal
                setattr(requiredInfo, type,
                        tempRequired)  # update the required number of meals

            if requiredMeals != 0:  # once all special meals are satisfied, calculate number of regular meals required
                # follows same algorithm as in calculator function
                regular = restaurants[i].regular
                requiredMeals -= regular
                if requiredMeals < 0:
                    regular += requiredMeals
                    requiredMeals = 0
            else:
                regular = 0
        order.append(
            Restaurant(restaurants[i].name,
                       0,
                       vegetarian=tempRestaurant.vegetarian,
                       glutenFree=tempRestaurant.glutenFree,
                       nutFree=tempRestaurant.nutFree,
                       fishFree=tempRestaurant.fishFree,
                       regular=regular))
    return order
Esempio n. 6
0
    def __init__(self):
        self.item_costs_A = data.items_price_restaurant_A
        self.power_A = data.power_A
        self.restaurant_A = Restaurant(self.power_A, self.item_costs_A)

        self.item_costs_B = data.items_price_restaurant_B
        self.power_B = data.power_B
        self.restaurant_B = Restaurant(self.power_B, self.item_costs_B)

        self.item_costs_C = data.items_price_restaurant_C
        self.power_C = data.power_C
        self.restaurant_C = Restaurant(self.power_C, self.item_costs_C)

        self.restaurants = {
            "A": self.restaurant_A,
            "B": self.restaurant_B,
            "C": self.restaurant_C
        }
Esempio n. 7
0
def main():
    food_one = MenuItem("Pasta", "Delicious", 15)
    food_two = MenuItem("Lasanga", "Fat", 20)
    og = Restaurant()

    og.add(food_one)
    og.add(food_two)

    print(og)
Esempio n. 8
0
def main():
    start = timeit.default_timer()

    ### Editable software part ###
    rest = Restaurant()
    rest.solve()
    ##############################

    stop = timeit.default_timer()
    print('Time: ', stop - start)
Esempio n. 9
0
    def test_calc(self):
        print("Testing Calculator")
        required = 5
        type = 'vegetarian'
        mealsRequired = 10
        restaurant = Restaurant("TestRestaurant", 5, 6, 0, 0, 0, 30)

        meals, outRequired, outMealsRequired = calculator(required, type, mealsRequired, restaurant)
        self.assertEqual(meals, 5)
        self.assertEqual(outRequired, 0)
        self.assertEqual(outMealsRequired, 5)
Esempio n. 10
0
def restaurant_endpoint(table_id=''):
    """
    Handles creation and queries for restaurant data.
    :param table_id: hub device ID.
    :return: JSON or CSV response body and status code.
    """

    if request.method == 'GET':
        hub_id = request.args.get('table_id', table_id)

        hub = Hub('')
        hub.get_restaurant_id(hub_id=hub_id)

        # if Mime Type is CSV, respond with simple restaurant ID string.
        if request.content_type == 'text/csv':
            print hub.restaurant_id
            if hub.restaurant_id:
                return hub.restaurant_id, OK
            else:
                return 'error', BAD_REQUEST

        # Otherwise, respond in JSON format.
        else:
            if hub.restaurant_id:
                return jsonify({
                    'table_id': hub_id,
                    'restaurant_id': hub.restaurant_id
                }), OK
            else:
                return jsonify({
                    'table_id':
                    hub_id,
                    'error':
                    'Specified table ID is not affiliated with a restaurant.'
                }), BAD_REQUEST

    elif request.method == 'POST':
        request_body = flask.request.get_json()

        # Restaurant name must be supplied in request body.
        if 'name' in request_body:
            restaurant_name = request_body['name']
        else:
            request_body.update({'error': 'Restaurant name not specified.'})
            return jsonify(request_body), BAD_REQUEST

        # Create new restaurant, and return result to user.
        restaurant = Restaurant(restaurant_id='')
        restaurant_info = restaurant.create(name=restaurant_name)

        if 'error' in restaurant_info:
            return jsonify(restaurant_info), SERVER_ERROR
        else:
            return jsonify(restaurant_info), OK
Esempio n. 11
0
def update_db(db_file):
    with DBHelper(db_file) as db:
        for item in restaurants:
            res = Restaurant(item)
            db.setup(res.id, "ID INT UNIQUE, YEAR INT, WEEK INT, WEEKDAY TEXT, MENUFI TEXT, MENUSE TEXT, MENUEN TEXT")
            for link in res.links:
                if res.type == 'unica':
                    unica_parser(res.query(link.items()[0][1]), link.items()[0][0], res, db)
                if res.type == 'studentlunch':
                    studentlunch_parser(res.query(link.items()[0][1]), link.items()[0][0], res, db)
            print "Database for {r} setup succesfully".format(r=res.title)
def format_response(response):
    restaurants = response.json()['response']['venues']

    if len(restaurants) == 0: return None

    restaurant = restaurants[0]

    name = format_name(restaurant)
    address = format_address(restaurant)
    image_url = format_image(restaurant)

    return Restaurant(name, address, image_url)
Esempio n. 13
0
def main():
    # to try a different algorithm, just replace seater with another
    # class - the class will only be called by seater.find_seats

    seaters = {
        #'seat_wherever' : SeatWherever(),
        #'round_robin' : RoundRobin(TABLES),
        #'smallest_available' : SmallestAvailable(),
        #'tight_seating' : TightSeating(),
        #'only_small' : SmallParties(),
        #'fewest_people' : FewestPeople(TABLES),
        'combining': SmallestCombining(TABLES, 6),
    }

    restaurant = Restaurant(TABLES)

    for name, seater in seaters.items():
        print('\n{}\n'.format(name))
        restaurant = Restaurant(TABLES)
        pprint(
            monte_carlo(restaurant, seater, var_arrival, sample_seated_time,
                        renege_time, OPEN_TIME))
def loadYelpToDB():
    output = yelp_data().json()['businesses']
    for res in output:
        if 'price' not in res:
            continue
        resDB_data = Restaurant(resName=res['name'],
                                city=res['location']['city'],
                                category1=res['categories'][0]['alias'],
                                category2=res['categories'][0]['title'],
                                rating=res['rating'],
                                image_url=res['image_url'],
                                priceRange=res['price'],
                                address=res['location']['address1'])
        resDB_data.save()
Esempio n. 15
0
    def completelynew(
        self, user
    ):  # suggests a cuisine they have never tried before (returns a restaurant name)
        # go through list of all the cuisines that user has tried
        # look at total cuisine list
        # look at cuisines a user hasnt tried
        # pick a random cuisine
        data = user.getData()
        rest_ids = list(data.keys())
        API = Api()
        cuisine_list = []
        for rest_id in rest_ids:
            rest_name = API.getRestaurant(
                rest_id)  # gets the name of the restaurant from the id
            rest = Restaurant(rest_name, user.getCity())
            cuisine_list.append(rest.getRestaurantCuisines())
        cus_list = []
        for str in cuisine_list:  # parses cuisine data and stores all cuisines that user has been to
            x = str.split(", ")
            for ele in x:
                if ele in cus_list:
                    pass
                else:
                    cus_list.append(ele)

        all_cuisines = API.getAllCuisines(user.getCity())
        for c in all_cuisines:  # parses cuisine data and finds all cuisines that user has not visited
            if c in cus_list:
                all_cuisines.remove(c)
        choice = random.choice(all_cuisines)
        BIGD = API.fillCuisine(choice, user.getCity(
        ))  # given the cuisine name, finds the cuisine id to use with api
        chosen_cuisine = None
        for ele in BIGD:
            temp = ele["cuisine"]
            if temp["cuisine_name"] == choice:
                #print(temp)
                cuisine_id = temp["cuisine_id"]
                chosen_cuisine = Cuisine(choice, cuisine_id)

        rest_data = API.getRestaurantsgivenCuisine(
            user.getCity(),
            chosen_cuisine)  # list of possible restaurants in json form
        #print(rest_data["results_found"])
        rest_list = []
        for rest in rest_data['restaurants']:
            rest_list.append(rest["restaurant"]["name"])
        fin = random.choice(rest_list)
        return fin
Esempio n. 16
0
def fixture_fooshi_bar():
    """Returns a Restaurant instance with a great menu."""
    return Restaurant(
        "Fooshi Bar",
        location="Buenos Aires",
        menu=[
            "Ebi Nigiri",
            "Edamame",
            "Inarizushi",
            "Kappa Maki",
            "Miso Soup",
            "Sake Nigiri",
            "Tamagoyaki",
        ],
    )
Esempio n. 17
0
def send_restaurant_suggestion(web_client: slack.WebClient, user_id: str,
                               channel: str):
    # Create a new onboarding tutorial.
    restaurant = Restaurant(channel)

    # Get the onboarding message payload
    message = restaurant.get_message_payload()

    # Post the onboarding message in Slack
    response = web_client.chat_postMessage(**message)

    # Capture the timestamp of the message we've just posted so
    # we can use it to update the message after a user
    # has completed an onboarding task.
    restaurant.timestamp = response["ts"]
Esempio n. 18
0
def main():
    print("Welcome to Restaurant Chooser")
    numRestaurants = int(
        input('Enter the number of restaurants to choose from: '))

    restaurants = []

    for num in range(0, numRestaurants):
        name = input("\nPlease enter the name of the restaurant: ")
        rating = getValidInt(
            "Please enter a rating for " + name +
            " between 1 and 5 inclusive: ", True)
        veg = getValidInt("# of vegetarian meals " + name + " can provide: ",
                          False)
        gf = getValidInt("# of gluten-free meals " + name + " can provide: ",
                         False)
        nf = getValidInt("# of nut-free meals " + name + " can provide: ",
                         False)
        ff = getValidInt("# of fish-free meals " + name + " can provide: ",
                         False)
        reg = getValidInt("# of total meals " + name + " can provide: ", False)

        reg = reg - veg - gf - nf - ff  # regular meals = total meals - special meals
        restaurants.append(Restaurant(name, rating, veg, gf, nf, ff, reg))

    requiredMeals = getValidInt(
        "\nEnter number of total meals required for your team: ", False)

    requiredInfo = Object()
    requiredInfo.vegetarian = getValidInt(
        "Enter number of vegetarian meals your team requires: ", False)
    requiredInfo.glutenFree = getValidInt(
        "Enter number of gluten-free meals your team requires: ", False)
    requiredInfo.nutFree = getValidInt(
        "Enter number of nut-free meals your team requires: ", False)
    requiredInfo.fishFree = getValidInt(
        "Enter number of fish-free meals your team requires: ", False)

    # sort the restaurants array by highest rated first. makes processing much faster/easier
    restaurants = sorted(restaurants,
                         key=lambda restaurant: restaurant.rating,
                         reverse=True)

    order = calculateRestaurants(requiredMeals, requiredInfo, restaurants)

    printOrder(order)
Esempio n. 19
0
def main():
    """ Test the restaurant module.
    """

    g1 = Guest("Alice",1)
    g2 = Guest("John",2)
    g3 = Guest("Mary",3)

    guests = [g1, g2, g3]

    r = Restaurant(2)

    # As long as there are still guests waiting in front of the 
    # Restaurant
    while guests: 
        if r.seat(guests[-1]): # Try to seat the next guest
            guests.pop()
        r.serve()              # Serve a guest 
Esempio n. 20
0
def load_restaurant_data():
    table = {
        '업소명': 'name',
        '업태명': 'kind',
        '소재지(지번)': 'address',
        '소재지전화번호': 'phone',
        '주취급음식': 'food'
    }
    # 데이터 출처: https://www.data.go.kr/dataset/3053840/fileData.do
    with open('restaurant.csv', encoding='euc-kr') as f:
        reader = csv.DictReader(f)
        for row in reader:
            if any(not row[x] for x in table.keys()):
                next
            data = {table[x]: row[x] for x in table.keys()}
            restaurant = Restaurant(**data)
            restaurants.append(restaurant)
            print(restaurant)
    print('--- loading complete ---')
Esempio n. 21
0
File: yelp.py Progetto: amni/SMSmart
def buildResponse(response, counter, location, verbose):
    name = response['name']
    if 'categories' in response:
        name +=  ' (' + response['categories'][0][0]+ ')' 
    if 'location' in response:
        endLocation = response['location']['display_address'][0] + ', ' + response['location']['city'] + ', ' + response['location']['state_code'] + ' ' + response['location']['postal_code']
    else:
        endLocation = 'location unavailable'
    if 'phone' in response:
        phone = formatPhone(str(response['phone'])) 
    else:
        phone = 'phone unavailabe'
    if 'rating' in response:
        rating = str(response['rating']) + " stars" 
    else:
        rating = 'rating unavailable'
    status = 'open' if (str(response['is_closed']) == 'False') else 'closed'
    isClosed = status 
    ret = Restaurant(counter, name, endLocation, phone, rating, isClosed)
    return ret
Esempio n. 22
0
def get_available_restaurants():
    """
    Convert json object to Restaurants objects
    :return: list Restaurant objects
    """
    restaurants = []
    restaurants_data = get_data_from_json_file()
    for restaurant_json in restaurants_data:
        restaurant = Restaurant(blurhash=restaurant_json[BLURHASH],
                                launch_date=restaurant_json[LAUNCH_DATE],
                                location=restaurant_json[LOCATION],
                                name=restaurant_json[NAME],
                                online=restaurant_json[ONLINE],
                                popularity=restaurant_json[POPULARITY])

        restaurant.launched_days = get_launched_days(restaurant.launch_date)

        restaurants.append(restaurant)

    return restaurants
Esempio n. 23
0
    def do_POST(self):
        try:
            if self.path.endswith("/restaurant/new"):
                ctype, pdict = cgi.parse_header(
                    self.headers.getheader('content-type'))
                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    messagecontent = fields.get('restaurant')

                    # Create new Restaurant Object
                    newRestaurant = Restaurant(name=messagecontent[0])
                    session.add(newRestaurant)
                    session.commit()

                    self.send_response(301)
                    self.send_header('Content-type', 'text/html')
                    self.send_header('Location', '/restaurant')
                    self.end_headers()

        except:
            pass
Esempio n. 24
0
def main():
    print("\n------Restaurant class Testing------")
    storeR = Restaurant("CumIn Restaurant", "28, State Street", "open", 6.25,
                        150, 14.99)
    print("%s is %s" % (storeR.get_s_name(), storeR.get_s_status()))
    print(storeR.seat_patrons(75))
    print("Number of people served: %d " % storeR.serve_patrons(25))
    print("Current occupancy: %d" % storeR.checkout_patrons(30))
    print("Total sales : $%.2f" % (float(storeR.calculate_total_sales())))
    print("Total sales tax: $%.2f" %
          (float(storeR.calculate_total_sales_tax())))
    print(
        "Total Amount due: $%.2f" %
        (storeR.calculate_total_sales() + storeR.calculate_total_sales_tax()))
    print("\n----Checking when input value more than capacity----")
    print(storeR.seat_patrons(185))
    print("Testing Restaurant class is done\n")
    print("--------------------------------------------")
    print("GroceryStore class Testing")
    storeG = GroceryStore("AllInOne Grocery Store", "2801 S king drive",
                          "open", 6.45, "independent")
    print("Grocery Store %s is %s" %
          (storeG.get_s_name(), storeG.get_s_status()))
    print("Total revenue of store after selling 4 rice bags @14.75 = $%.2f " %
          (storeG.sell_item(4, 14.75)))
    print("Total revenue of store after selling 6 milk @2.75 = $%.2f" %
          (storeG.sell_item(6, 2.75)))
    print("Total revenue of store after selling 2 Bread @1.75 = $%.2f" %
          (storeG.sell_item(2, 1.75)))
    print("\nTotal sales tax: $%.2f" % (storeG.calculate_total_sales_tax()))
    print(
        "Total cost of sales with tax: $%.2f" %
        (storeG.calculate_total_sales_tax() + storeG.calculate_total_sales()))
    print("\n----checking the Status attribute of store ----")
    storeG.set_s_status("closed")
    print("Grocery Store %s is %s" %
          (storeG.get_s_name(), storeG.get_s_status()))
    print("End of testing GroceryStore class")
from restaurant import Restaurant

restaurant = Restaurant('全聚德', '北京烤鸭')
restaurant.describe_restaurant()
Esempio n. 26
0
from restaurant import Restaurant

my_restaurant = Restaurant('quan ju de', 'roast_duck')
my_restaurant.describe_restaurant()
Esempio n. 27
0
from restaurant import Restaurant

restaurant = Restaurant('malaychan', '東南アジア料理')
restaurant.describe_restaurant()
restaurant.open_restaurant()
Esempio n. 28
0
from restaurant import Restaurant

Eddies = Restaurant("Eddies", "American")
Eddies.describe_restaurant()
Esempio n. 29
0
from restaurant import Restaurant, IceCreamStand

restaurant = Restaurant("Lo de Charly", "parrilla")
print(restaurant.restaurant_name)
print(restaurant.cuisine_type)
restaurant.describe_restaurant()
restaurant.open()

restaurant_luigi = Restaurant("Lugi's Manssion", "Italian cuisine")
restaurant_sushi = Restaurant("Itamae sushi", "Oriental food")

restaurant_luigi.describe_restaurant()
restaurant_luigi.open()
restaurant_sushi.describe_restaurant()
restaurant_sushi.open()

griddo = IceCreamStand("Griddo", "heladeria")
griddo.describe_restaurant()
griddo.show_flavors()

from restaurant import Restaurant

restaurant = Restaurant("beagelbar", "bagels")
restaurant.describe_restaurant()
print("number of customers served: " + str(restaurant.number_served))
restaurant.number_served = 654
print("number of customers served: " + str(restaurant.number_served))
restaurant.set_number_served(784)
print("number of customers served: " + str(restaurant.number_served))
restaurant.increment_number_served(76)
print("number of customers served: " + str(restaurant.number_served))