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 search_similar_restaurants(self, restaurant, lat_lon=None, bearing=None):
        #  rest not closed, matching cats, limit 15
        if not lat_lon:
            lat_lon = '37.7872247,-122.39926'
        lat, lon = lat_lon.split(',')
        if not bearing:
            results = yelp_request(
                'search',
                {
                    'term': 'restaurant',
                    'limit': 15,
                    'category_filter': restaurant.get_categories().lower(),
                    'sort': 1,
                    'll': lat_lon,
                },
                self.consumer_key,
                self.consumer_secret,
                self.token,
                self.token_secret
            )
        else:
            lat1, lon1, lat2, lon2 = get_yelp_coordinates(lat, lon, bearing, 2)
            # lat2, lon2 = pointRadialDistance(lat, lon, bearing, 5.8)
            print "L1: %s" % lat_lon
            print "L2: %s,%s" % (lat2, lon2)
            results = yelp_request(
                'search',
                {
                    'term': 'restaurant',
                    'limit': 15,
                    'category_filter': restaurant.get_categories().lower(),
                    'sort': 1,
                    'bounds': "%s,%s|%s,%s" % (lat1, lon1, lat2 ,lon2)
                },
                self.consumer_key,
                self.consumer_secret,
                self.token,
                self.token_secret
            )

        # Put them on a list except the closed ones
        restaurants = []
        if not results.get('businesses'):
            return []
        for result in results.get('businesses', None):
            if not result.get('is_closed') and \
                    result.get('id') != restaurant.yelp_id:
                r = Restaurant()
                r.load_data(result)
                restaurants.append(r)

        # Sort by rating
        restaurants = sorted(restaurants, key=lambda r: r.rating, reverse=True)

        # Keep top 3
        restaurants = restaurants[1:4]

        return restaurants
Esempio n. 3
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. 4
0
    def testFunction(self):
        r = Restaurant("sample")

        self.assertEqual(-1, r.test_grades(["A", "B"]))

        self.assertEqual(1, r.test_grades(["C", "B", "B"]))

        self.assertEqual(0, r.test_grades(["A"]))

        self.assertEqual(0, r.test_grades(["C", "B", "C"]))
Esempio n. 5
0
def main():
    start = timeit.default_timer()

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

    stop = timeit.default_timer()
    print('Time: ', stop - start)
Esempio n. 6
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)
Esempio n. 7
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. 8
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. 9
0
 def get_restaurant(self, restaurant_id):
     result = yelp_request(
         'business',
         {'id': restaurant_id},
         self.consumer_key,
         self.consumer_secret,
         self.token,
         self.token_secret
     )
     restaurant = Restaurant()
     restaurant.load_data(result)
     return restaurant
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. 11
0
class TestRestaurant(unittest.TestCase):

    def setUp(self):
        self.restaurant = Restaurant(
            {"rice" : 3, "noodles" : 2})

    def tearDown(self):
        pass

    def test_restaurant(self):
        self.assertEqual(0, self.restaurant.cost())
        self.assertEqual(15, self.restaurant.cost(
                {"rice" : 1, "noodles" : 1},
                {"rice" : 2, "noodles" : 2}))
Esempio n. 12
0
class RestaurantTest(unittest.TestCase):
    """Unit Tests for the Restaurant Class"""
    def setUp(self):
        restaurant_name = "Bob's Burgers"
        cusine_type = "American"
        number_served = 20
        self.restaurant = Restaurant(restaurant_name, cusine_type,
                                     number_served)

    def test_number_served_int(self):
        served = 30
        self.restaurant.set_number_served(served)
        self.assertEqual(self.restaurant.number_served, 30)

    def test_number_served_string(self):
        served = "30"
        self.restaurant.set_number_served(served)
        self.assertEqual(self.restaurant.number_served, 30)

    def test_increment_served_float(self):
        served = 30.5
        self.restaurant.increment_number_served(served)
        self.assertEqual(self.restaurant.number_served, 50.5)

    def test_increment_served_string(self):
        served = "40"
        self.restaurant.increment_number_served(served)
        self.assertEqual(self.restaurant.number_served, 60)
Esempio n. 13
0
class TestRestaurant(unittest.TestCase):
    def setUp(self):
        restaurant_name = "Cafe Fromage"
        cuisine_type = "Mongolian"
        number_served = 1000
        self.restaurant = Restaurant(restaurant_name, cuisine_type,
                                     number_served)

    def test_set_number_served_integer(self):
        new_number_served = 56
        self.restaurant.set_number_served(new_number_served)
        self.assertEqual(56, self.restaurant.number_served)

    def test_set_number_served_string(self):
        new_number_served = "998"
        self.restaurant.set_number_served(new_number_served)
        self.assertEqual(998, self.restaurant.number_served)

    def test_increment_number_served_integer(self):
        increment_number_by = 16
        self.restaurant.increment_number_served(increment_number_by)
        self.assertEqual(1016, self.restaurant.number_served)

    def test_increment_number_served_string(self):
        increment_number_by = "4815161342"
        self.restaurant.increment_number_served(increment_number_by)
        self.assertEqual(4815162342, self.restaurant.number_served)
Esempio n. 14
0
class TestRestaurant(unittest.TestCase):
    """Tests for class Restaurant"""

    def setUp(self):
        """Create a restaurant and responses for use in test methods"""
        restaurantName = "my house"
        typeCuisine = "any"
        numberServed = 201
        self.my_restaurant = Restaurant(restaurantName, typeCuisine, numberServed)
    
    def test_set_number_served_int(self):
        """Tests the set_number_served fx"""
        newNumberServed = 248
        self.my_restaurant.set_number_served(newNumberServed)
        self.assertEqual(self.my_restaurant.number_served, 248)

    def test_set_number_served_str(self):
        """Tests set number served fx if a string is passed to it"""
        newNumberServed = "248"
        self.my_restaurant.set_number_served(newNumberServed)
        self.assertEqual(self.my_restaurant.number_served, 248)
    
    def test_increment_number_served_int(self):
        """Tests the increment number fx"""
        incrementNumberBy = 42
        self.my_restaurant.increment_number_served(incrementNumberBy)
        self.assertEqual(self.my_restaurant.number_served, 243)
        
    
    def test_increment_number_served_str(self):
        """Tests the increment number fx if a string is passed"""
        incrementNumberBy = "42"
        self.my_restaurant.increment_number_served(incrementNumberBy)
        self.assertEqual(self.my_restaurant.number_served, 243)
Esempio n. 15
0
class TestRestaurant(unittest.TestCase):
    def setUp(self):
        restaurant_name = "Bubbas"
        cuisine_type = "American"
        number_served = 10
        self.restaurant = Restaurant(restaurant_name, cuisine_type,
                                     number_served)

    def test_number_served_int(self):
        number_served = 15
        self.restaurant.set_number_served(number_served)
        self.assertEqual(self.restaurant.number_served, 15)

    def test_number_served_string(self):
        number_served = "15"
        self.restaurant.set_number_served(number_served)
        self.assertEqual(self.restaurant.number_served, 15)

    def test_increment_number_served_int(self):
        restaurant = 25
        self.restaurant.increment_number_served(restaurant)
        self.assertEqual(self.restaurant.number_served, 35)

    def test_increment_number_served_string(self):
        restaurant = "25"
        self.restaurant.increment_number_served(restaurant)
        self.assertEqual(self.restaurant.number_served, 35)
Esempio n. 16
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. 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
class TestRestaurant(unittest.TestCase):

    def setUp(self):
        restaurant_name="Cheezy's Pizza"
        cuisine_type="Pizza"
        number_served=12000
        self.restaurant = Restaurant(restaurant_name, cuisine_type, number_served)

    def test_set_number_served(self):
        self.restaurant.set_number_served()
        self.assertEqual(self.restaurant.number_served,"12001")

    def test_increment_number_served(self):
        self.restaurant.increment_number_served()
        self.assertEqual(self.restaurant.number_served, 12001)
Esempio n. 19
0
def get_address(start_index, count):
    g = geocoders.GeocoderDotUS()
    num = Restaurant.select().count()
    x = start_index
    while x < start_index + count and x <= num:
        r = Restaurant.selectBy(id = x).getOne()
        try:
            print "Geocoding %s located at %s" % (r.id, r.original)
            place, (lat, lng) = g.geocode(r.original + ', Chicago, IL')
            r.address = place
            r.lat = lat
            r.lng = lng
        except Exception, e:
            print "Error: %s" % e
        x = x + 1
Esempio n. 20
0
def computeSumforDiffBoro(df):
    '''
    For the last part of question 4 
    '''
    all_boros = df['BORO'].unique()
    for boro in all_boros:
        # get the data of the corresponding boro
        df_boro = df[df['BORO'] == boro]
        count = 0
        all_ids = df_boro['CAMIS'].unique()
        for id in all_ids:
            r = Restaurant(id)
            count = count + r.test_restaurant_grades(df_boro)
        
        text = boro + ': the total change in restaurant grades is ' + str(count)
        print text
Esempio n. 21
0
 def GET(self, q):
     #TODO: this really ought to make a lookup into an index, but for now let's just search the database
     like_string = "%" + q + "%"
     print "\n"
     rq = Restaurant.q
     print self.display_results(
         Restaurant.select(LIKE(rq.name, like_string)).limit(50))
Esempio n. 22
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. 23
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. 24
0
 def delete(self, id):
   restaurant = Restaurant.find_by_id(id)
   if restaurant:
     restaurant.destroy()
     return restaurant.json()
   else:
     return { "error": "Not found" }, 404
Esempio n. 25
0
    def test_create_from_line(self):
        # test 1
        line = "R1,4C,1,3A,2,2P,1,100,200,200,100,100"
        rest = Restaurant.create_from_line(line)

        self.assertEqual(rest.id, 'R1')
        self.assertEqual(len(rest.departments), 3)
	def loadRestaurants(self):
		current_restaurants = []
		with open(self.restaurantsFile, 'r') as f:
			current_restaurants = json.load(f)

		for restaurantJson in current_restaurants:
			self.loadedRestaurants.add(Restaurant.fromJson(restaurantJson))
def getRes():
    output = []
    for res in Restaurant.scan():
        res_data = vars(res)['attribute_values']
        if 'priceRange' not in res_data:
            continue
        output.append(res_data)
    return jsonify(output)
Esempio n. 28
0
    def test_check_inventory(self):

        # test1
        line = "R1,4C,1,3A,2,2P,1,100,200,200,100,100"
        rest = Restaurant.create_from_line(line)
        line = "R1,2020-12-08 19:15:31,O1,BLT,LT,VLT"
        order = Order.create_from_line(line)
        bool = rest.check_inventory(order)
        self.assertEqual(bool, True)

        # test2
        line = "R1,4C,1,3A,2,2P,1,0,200,200,100,100"
        rest = Restaurant.create_from_line(line)
        line = "R1,2020-12-08 19:15:31,O1,BLT,LT,VLT"
        order = Order.create_from_line(line)
        bool = rest.check_inventory(order)
        self.assertEqual(bool, False)
Esempio n. 29
0
 def patch(self, id):
   restaurant = Restaurant.find_by_id(id)
   data = parser.parse_args()
   if restaurant:
     restaurant.name = data['name']
     restaurant.save()
     return restaurant.json()
   else:
     return { "error": "Not found" }, 404
Esempio n. 30
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. 31
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. 32
0
    def test_commit_inventory(self):
        line = "R1,4C,1,3A,2,2P,1,100,200,200,100,100"
        rest = Restaurant.create_from_line(line)
        self.assertNotEqual(rest.inventory, rest.cache_inventory)

        rest.cache_inventory = [100, 200, 200, 100, 99]
        rest.commit_inventory()
        self.assertListEqual(list(rest.inventory.as_array()),
                             list(rest.cache_inventory))
Esempio n. 33
0
def getSearchResult():
    search_input = request.json["input"]
    output = set()
    for res in Restaurant.scan():
        if search_input in res.category1:
            output.add(res.category1)
        if search_input in res.category2:
            output.add(res.category2)
    return jsonify(list(output))
Esempio n. 34
0
    def test_check_order(self):
        line = "R1,4C,1,3A,2,2P,1,100,200,200,100,100"
        rest = Restaurant.create_from_line(line)

        line = "R1,2020-12-08 19:15:31,O1,BLT,LT,VLT"
        order = Order.create_from_line(line)

        order = rest.check_order(order, 21 * 60)
        self.assertEqual('ACCEPTED', order.status)
Esempio n. 35
0
    def test_reverse_required_time(self):
        line = "R1,4C,1,3A,2,2P,1,100,200,200,100,100"
        rest = Restaurant.create_from_line(line)

        with patch.object(Department,
                          'reverse_required_time',
                          return_value='TESTING') as mock_method:
            rest.reverse_required_time()
            mock_method.assert_called()
            self.assertEqual(3, mock_method.call_count)
Esempio n. 36
0
def getResByCat():
    category = request.json["category"]
    output = []
    for res in Restaurant.scan():
        if res.category1 is None or res.category2 is None:
            continue
        if category in res.category1 or category in res.category2:
            res_data = vars(res)["attribute_values"]
            output.append(res_data)
    return jsonify(output)
Esempio n. 37
0
    def search_restaurant(self, string):
        results = yelp_request(
            'search',
            {
                'term': string,
                'location': 'San Francisco',
                'category_filter': 'restaurants',
                'limit': 5
            },
            self.consumer_key,
            self.consumer_secret,
            self.token,
            self.token_secret
        )

        restaurants = []
        for result in results.get('businesses', None):
            r = Restaurant()
            r.load_data(result)
            restaurants.append(r)
        return restaurants
Esempio n. 38
0
def main():
    """ Test the restaurant module.
    """

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

    guests = [g1, g2, g3]
    choice = int (raw_input ('Where would you like to eat? \nEnter 1 For the Restaurant \nEnter 2 For the Fancy Restaurant\n' ))
    while (choice != 1 and choice != 2 ):
        print ('Invalid Input') 
        choice = int (raw_input ('Where would you like to eat? \nEnter 1 For the Restaurant \nEnter 2 For the Fancy Restaurant\n' ))
    if (choice == 1):    
        r = Restaurant(2)
    else:
        r = FancyRestaurant(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. 39
0
 def GET(self, query, s_top, s_bot, s_left, s_right):
     top = Decimal(s_top)
     bot = Decimal(s_bot)
     left = Decimal(s_left)
     right = Decimal(s_right)
     
     like_string = "%" + query + "%"
     
     rq = Restaurant.q
     results = Restaurant.select(AND(
         rq.lat >= bot,
         rq.lat <= top,
         rq.lng >= left,
         rq.lng <= right,
         LIKE(rq.name, like_string)  
     ))
     print self.display_results(results)
Esempio n. 40
0
    def test_it_runs(self):
        equipment = [{"name": "Lame Pizza Oven",
                      "attributes": {"capabilities": ["oven", "pizza", "steak"],
                                     "cook_time_mean":7, "cook_time_std":1,
                                     "quality_mean":0.5, "quality_std":0.4,
                                     "difficulty_rating":0.2, "cost":300,
                                     "daily_upkeep":5, "reliability":0.2}},
                     {"name": "Lame Pizza Oven",
                      "attributes": {"capabilities": ["oven", "pizza", "steak"],
                                     "cook_time_mean":7, "cook_time_std":1,
                                     "quality_mean":0.5, "quality_std":0.4,
                                     "difficulty_rating":0.2, "cost":300,
                                     "daily_upkeep":5, "reliability":0.2}},
                     {"name": "Lame Pizza Oven",
                      "attributes": {"capabilities": ["oven", "pizza", "steak"],
                                     "cook_time_mean":7, "cook_time_std":1,
                                     "quality_mean":0.5, "quality_std":0.4,
                                     "difficulty_rating":0.2, "cost":300,
                                     "daily_upkeep":5, "reliability":0.2}},
                     {"name": "Lame Pizza Oven",
                      "attributes": {"capabilities": ["oven", "pizza", "steak"],
                                     "cook_time_mean":7, "cook_time_std":1,
                                     "quality_mean":0.5, "quality_std":0.4,
                                     "difficulty_rating":0.2, "cost":300,
                                     "daily_upkeep":5, "reliability":0.2}},
                     {"name": "Lame Pizza Oven",
                      "attributes": {"capabilities": ["oven", "pizza", "steak"],
                                     "cook_time_mean":7, "cook_time_std":1,
                                     "quality_mean":0.5, "quality_std":0.4,
                                     "difficulty_rating":0.2, "cost":300,
                                     "daily_upkeep":5, "reliability":0.2}},

                     {"name": "Awesome Pizza Oven",
                      "attributes": {"capabilities": ["oven", "pizza", "steak"],
                                     "cook_time_mean":1, "cook_time_std":0.1,
                                     "quality_mean":0.7, "quality_std":0.1,
                                     "difficulty_rating":0.8, "cost":4000,
                                     "daily_upkeep":10, "reliability":0.9}},
                     {"name": "Awesome Pizza Oven",
                      "attributes": {"capabilities": ["oven", "pizza", "steak"],
                                     "cook_time_mean":1, "cook_time_std":0.1,
                                     "quality_mean":0.7, "quality_std":0.1,
                                     "difficulty_rating":0.8, "cost":4000,
                                     "daily_upkeep":10, "reliability":0.9}},
                     {"name": "Bar 1",
                      "attributes": {"capabilities": ["alcohol"],
                                     "cook_time_mean": 0.3, "cook_time_std":0.5,
                                     "quality_mean":0.6, "quality_std":0.1,
                                     "difficulty_rating":0.5, "cost":2000,
                                     "daily_upkeep":200, "reliability":0.8}}
                     ]
        tables = [{"name": "Table 1",
                   "attributes": {"x": 0.21, "y": 0.27, "radius": 4, "seats": 2, "cost": 300, "daily_upkeep": 1}},
                  # {"name":"Table 2",
                  # "attributes":{"x":4.1,"y":5.7,"radius":7,"seats":5,"cost":800,"daily_upkeep":1}},
                  # {"name":"Table 1",
                  # "attributes":{"x":12.1,"y":5.7,"radius":4,"seats":5,"cost":800,"daily_upkeep":1}},
                  {"name": "Table 2",
                   "attributes": {"x": 0.31, "y": 0.37, "radius": 4, "seats": 5, "cost": 800, "daily_upkeep": 1}},
                  {"name": "Table 3",
                   "attributes": {"x": 0.1, "y": 0.7, "radius": 4, "seats": 5, "cost": 800, "daily_upkeep": 1}},
                  {"name": "Bar 1",
                   "attributes": {"x": 0.7, "y": 0.3, "radius": 0.2, "seats": 8, "cost": 1000, "daily_upkeep": 1}}]

        staff = [{'x': 0.2, 'y': 0.6}, {'x': 0.4, 'y': 0.4}]  # ,{'x': 0.7, 'y': 0.7}]
        r = Restaurant("Sophie's Kitchen", equipment, tables, staff)
        r.simulate(days=30)
        # r.ledger.read_messages()
        r.env.ledger.generate_final_report()
        self.assertEqual(1+1, 2)
Esempio n. 41
0
# Please edit the Restaurant class in the file restaurant.py

from restaurant import Restaurant

# These are test cases

mcdowells = Restaurant("McDowell's Hamgurger Emporium")
print mcdowells.is_yummy()

chez_bananas = Restaurant("Chez Bananas Crib of Contentment")
print chez_bananas.is_yummy()
# Please edit the Restaurant class in the file restaurant.py

from restaurant import Restaurant

# These are test cases

mcdowells = Restaurant("McDowell's Hamgurger Emporium", "Cleo McDowell", "Chef Queasy")


# test case:

print mcdowells.__str__() == "McDowell's Hamgurger Emporium (Owner: Cleo McDowell, Chef: Chef Queasy)"
Esempio n. 43
0
# You should edit only this file and do not change restaurant.py
# change something here so that chez_bananas.is_yummy() returns True

from restaurant import Restaurant

# These are test cases

mcdowells = Restaurant("McDowell's Hamgurger Emporium")
mcdowells.is_yummy()

chez_bananas = Restaurant("Chez Bananas Crib of Contentment")
chez_bananas.is_yummy()

#test case:
print "Test is:", chez_bananas.is_yummy() == True
Esempio n. 44
0
 def GET(self, q):
     #TODO: this really ought to make a lookup into an index, but for now let's just search the database
     like_string = "%" + q + "%"
     print "\n"
     rq = Restaurant.q
     print self.display_results(Restaurant.select(LIKE(rq.name, like_string)).limit(50))
Esempio n. 45
0
import urllib2
import re
from sqlobject import *
import os
sqlhub.processConnection = connectionForURI('sqlite:%s' % os.path.abspath('restaurants.db'))

from restaurant import Restaurant

cuisine = re.compile('\$+?.+?<font.+?\>(\S+?)<br>')
phone = re.compile('Phone:\s</b>(\S+?)<br>')
hours = re.compile('Hours.+?<pre.+?>(.+?)</pre>')

def getdata(data, retype):
    d = retype.findall(data)
    if len(d) > 0:
        return d[0]
    else:
        return None

for r in Restaurant.select():
    data =  urllib2.urlopen(r.url).read().replace('\n', '').replace('\r','')
    print "Currently processing restaurant id %s" % r.id
    r.cuisine = getdata(data, cuisine) #.findall(data)[0]
    r.phone = getdata(data, phone) #.findall(data)[0]
    r.hours = getdata(data, hours) #.findall(data)[0]
Esempio n. 46
0
def parse(client_id, client_secret, ll, query):
	"""
	Parameters:
		client_id: foursquare api client id
		client_secret: foursquare api client client_secret
		ll: lat/long coordinates as a string separated by comma
		query: what the user wants, ex: sushi

	Returns:
		A list of restaurant ids that satisfy this query. If 
			the restaurant id does not exist in our database,
			we add it.
	"""
	url = "https://api.foursquare.com/v2/venues/search?client_id=" + str(client_id) + "&client_secret=" + str(client_secret) + "&v=20130815&ll=" + str(ll) + "&query=" + str(query)

	response = urllib.urlopen(url);
	data = json.loads(response.read())
	result = []
	
	# actual read of data
	venues = data["response"]["venues"]
	for v in venues:

		location = v["location"]
		rid = v["id"].encode("utf-8")

		if "address" in location:

			if restaurant.isUnique(rid):

				name = ""
				address = ""
				city = ""
				state = ""
				zipCode = ""
				lat = ""
				lng = ""
				phone = ""
				website = ""
				twitter = ""
				contact = ""
				
				if "name" in v:
					name = v["name"].encode("utf-8")
				if "address" in location:
					address = location["address"].encode("utf-8")
				if "city" in location:
					city = location["city"].encode("utf-8")
				if "state" in location:
					state = location["state"].encode("utf-8")
				if "postalCode" in location:
					zipCode = location["postalCode"].encode("utf-8")
				if "lat" in location:
					lat = round(float(location["lat"]), 6)
				if "lng" in location:
					lng = round(float(location["lng"]), 6)
				if "contact" in v:
					contact = v["contact"]
					if "formattedPhone" in contact:
						phone = contact["formattedPhone"].encode("utf-8")
					if "url" in contact:
						website = contact["url"].encode("utf-8")
					if "twitter" in contact:
						twitter = contact["twitter"].encode("utf-8")

				#Create Restaurant object
				rest = Restaurant(rid, name, address, city, state, zipCode, phone, website, twitter, lat, lng)
				rest.save()

			#append to result
			result.append(rid)
	return result
Esempio n. 47
0
 def setUp(self):
     self.restaurant = Restaurant(
         {"rice" : 3, "noodles" : 2})
Esempio n. 48
0
# Task.9.10. Импортирование класса Restaurant: взять последнюю версию 
# класса Restaurant и сохранить ее в модуле. Создать отдельный файл, 
# импортирующий класс Restaurant. Создать экземпляр Restaurant и вызвать 
# один из методов Restaurant, чтоб показать что команда import работает 
# правильно.

from restaurant import Restaurant
print ("Task 9.10")
restaurant = Restaurant ('ilpatio','italian')
restaurant.describe_restaurant()

# Task.9.11. Импортирование класса Admin: начать с версии класса из 
# упражнения 9.8. Создать классы User, Privileges и Admin в одном модуле. 
# Создать отдельный файл, создать экземпляр Admin, и вызвать метод 
# show_privileges(), чтобы показать, что все работает правильно.

import user
print ("\nTask 9.11")
admin = user.Admin('vova','malov','oslo',31)
admin.privileges.show_privileges()

# Task.9.12. Множественные модули: сохранить класс User в одном модуле, 
# а классы Privileges и Admin в другом. В отдельном файле создать экземпляр
# Admin и вызвать метод show_privileges(), чтобы показать, что все
# работает правильно.

from new_user import User
from privileges import Admin, Privileges
print ("\nTask 9.12")
admin = Admin('vova','malov','oslo',31)
admin.privileges.show_privileges()
from restaurant import Restaurant

burger_king = Restaurant("bUrger King", 'Noble')
print(burger_king.restaurant_name)
print(burger_king.cuisine_type)
burger_king.describe_restaurant()
burger_king.open_restaurant()
print(str(burger_king.number_served) + " served so far")
burger_king.increment_number_served(100)
print(str(burger_king.number_served) + " served so far")

gs = Restaurant("golden sun", 'chinese')
sw = Restaurant("sapphire wednesday", "american")

gs.describe_restaurant()
sw.describe_restaurant()
from restaurant import Restaurant

channel_club = Restaurant("The channel club", "steak and seafood")
channel_club.describe_restaurant() 
channel_club.open_restaurant()

Esempio n. 51
0
# Please edit the Restaurant class in the file restaurant.py

from restaurant import Restaurant

# These are test cases

mcdowells = Restaurant("McDowell's Hamgurger Emporium")
mcdowells.is_yummy()

chez_bananas = Restaurant("Chez Bananas Crib of Contentment")
chez_bananas.is_yummy()
Esempio n. 52
0
def get_restra(location, area, page):
    r = Restaurant(location=location, area=area, page=page)
    data = r.getAll()
    return data