예제 #1
0
    def new_recipe(self):
        name = input("Please enter the NAME of the food\n")
        preparation = input("Please enter the PREPARATION of the food\n")
        type_name = input("Please enter the TYPE of the food\n")

        if self.type_is_exists(type_name):
            typef = Types_Of_Food.find_one_type(ttype=type_name)
            type_id = typef['_id']
        else:
            typef = Types_Of_Food(ttype=type_name)
            typef.save_type()
            typef = Types_Of_Food.find_one_type(ttype=type_name)
            type_id = typef['_id']

        food = Food(name, preparation, type_id)
        food.save_food()

        while True:
            one_more = input("Do you want to add (another) ingredient? Y/N")
            if one_more.lower() == "y":
                # ingredient, quantity, unit, food_id, _id=None
                ing_name = input("Ingredient NAME?\n")
                ing_quant = input("Ingredient QUANTITY?\n")
                ing_unit = input("Ingredient UNIT?\n")
                ing_food_id = food.get_id()
                ingredient = Ingredients(ingredient=ing_name, quantity=ing_quant, unit=ing_unit, food_id=ing_food_id)
                Ingredients.save_ingredient(ingredient)
            else:
                break
예제 #2
0
def create_food():
    food = Food(request.form['name'], request.form['description'],
                request.form['price'], request.form['image'],
                request.form['category_id'])
    food.new_food(food)
    return render_template('index.html', categories=Category.query.all(), foods=Food.query.all(), user=current_user, \
                           admin=admin_permission)
def home():
    if request.method == "GET":
        return render_template('food_form.html')
    elif request.method == "POST":
        form = request.form
        # print(form)
        t = form['title']
        l = form['link']
        f = Food(title=t, link=l)
        f.save()
        return redirect("/food/" + str(f.id))
예제 #4
0
파일: food.py 프로젝트: finkol/nott
def log_food(user_name, food_type, title, timestamp, score, picture, grams):
    try:
        user = db_session.query(User).filter(User.user_name == user_name.lower()).first()

        food = Food(user.id, food_type.lower(), title, timestamp, score, str(picture), grams)
        db_session.add(food)
        db_session.flush()
        return {"message": "Success", "food": food.get_dict()}
    except Exception as e:
        raise GenericError(e.message)
    except:
        raise GenericError("Unspecific error came up")
예제 #5
0
파일: app.py 프로젝트: linhkent/New-project
def add_food():
    if request.method == "GET":
        return render_template("food_form.html")
    elif request.method == "POST":
        form = request.form  # form la kieu dictionary   # form hay user trong register la ten dict, request.form thi form la form o trong file html
        # print(form)
        t = form["title"]
        l = form["link"]
        # print(t, l)
        f = Food(title=t, link=l)
        f.save()

        return redirect("/food/" + str(f.id))
예제 #6
0
def addWordFood():
    if request.method == "GET":
        return render_template("addWord.html")
    else:
        form = request.form
        add_word = Food(
            image=form["image"],
            word=form["word"],
            pronunciation=form["pronunciation"],
            mean=form["mean"],
            audio_link=form["audio_link"],
        )
        add_word.save()
        return redirect(url_for('admin'))
예제 #7
0
    def put(self, uid):
        """
        @apiDescription 修改食品
        @api {put} /shop/([0-9]+)/foods/? 修改
        @apiGroup food

        @apiParam {Number} fid 食品id
        @apiParam {String} [image] 照片地址
        @apiParam {String} [name] 食品名称
        @apiParam {Number} [seller] 卖家
        @apiParam {Number} [price] 价格

        @apiPermission seller
        """
        fid = int(self.get_argument("fid"))
        food = Food.get_instance_by_id(self.orm_session, fid)

        to_change = {
            "image": self.get_argument("image", None),
            "name": self.get_argument("name", None),
            "seller": int(self.get_argument("seller", 0)),
            "price": float(self.get_argument("price", 0)),  # TODO maybe bug because of precision
        }

        for key, value in to_change.items():
            if value:
                setattr(food, key, value)
        self.orm_session.commit()
        self.write({})
예제 #8
0
def food():
    user = session.get('username')
    allWordSave = Reviews.objects()
    numberOfWords = 0
    for i in allWordSave:
        if i.username == user:
            numberOfWords += 1
    list_audio = []
    list_word = []
    list_image = []
    list_pronunciation = []
    list_id = []
    # get all document from dabase
    total_food = Food.objects()
    for i in total_food:
        audio = i.audio_link
        word = i.word
        image = i.image
        pronunciation = i.pronunciation
        id = i.id
        list_audio.append(audio)
        list_word.append(word)
        list_image.append(image)
        list_pronunciation.append(pronunciation)
        list_id.append(id)
    return render_template("food.html",
                           list_audio=list_audio,
                           list_word=list_word,
                           list_image=list_image,
                           list_pronunciation=list_pronunciation,
                           list_id=list_id,
                           user=user,
                           numberOfWords=numberOfWords)
예제 #9
0
def show_spec(food_name, id):
    food = Food.get_or_none(id == id)

    if food:
        reviews = Review.select().where(Review.food_id == id)
        criterion_z1_list = [e.criterion_z1 for e in reviews]
        criterion_z2_list = [e.criterion_z2 for e in reviews]
        criterion_z3_list = [e.criterion_z3 for e in reviews]
        criterion_z4_list = [e.criterion_z4 for e in reviews]
        criterion_z5_list = [e.criterion_z5 for e in reviews]
        reviewers_list = []
        food_pic_list = []

        for i in [e.food_picture for e in reviews]:
            food_pic_list.append(S3_LOCATION + i)

        for i in [reviewer.user_id for reviewer in reviews]:
            reviewers_list.append(User.get_by_id(i).name)

        return jsonify({
            "criterion_z1_list": criterion_z1_list,
            "criterion_z2_list": criterion_z2_list,
            "criterion_z3_list": criterion_z3_list,
            "criterion_z4_list": criterion_z4_list,
            "criterion_z5_list": criterion_z5_list,
            "reviewers_list": reviewers_list,
            "food_pic_list": food_pic_list,
            "food_latitude": food.latitude,
            "food_longitude": food.longitude
        })

    else:
        return jsonify({"err": "Food dish does not exist"}), 400
예제 #10
0
 def test_eating_food_is_done_correctly(self):
     self.python.set_head()
     self.python.set_body()
     size = len(self.python.get_body_coords())
     self.game_world.set_cell(Cell(Food(), Vector2D(5, 6)))
     self.python.move('d')
     size_n = len(self.python.get_body_coords())
     self.assertEqual(size_n - size, 1)
예제 #11
0
 def get(self, *args, **kwargs):
     id = int(self.get_argument('id', [0])[0])
     info = session.query(Food).filter_by(id=id).first()
     if info is None:
         info = Food()
     cat_list = session.query(FoodCat).all()
     current = 'index'
     self.render("food/set.html",
                 info=info,
                 cat_list=cat_list,
                 current=current)
def update_food(food_id):
    f = Food.objects().with_id(food_id)
    if request.method == "GET":
        return render_template("update_food_form.html", food=f)
    elif request.method == "POST":
        form = request.form
        t = form["title"]
        l = form["link"]
        # Update - Automic Update
        f.update(set__title=t, set__link=l)
        return "OK"
예제 #13
0
    def delete(self, uid):
        """
        @apiDescription 删除食品
        @api {delete} /shop/([0-9]+)/foods/? 删除
        @apiGroup food

        @apiParam {Number} fid 食品id

        @apiPermission seller
        """
        uid = int(uid)
        user = User.get_instance_by_id(self.orm_session, uid)
        fid = int(self.get_argument("fid"))
        if not user:
            self.write(dict(
                status=1,
                msg="user not exist",
            ))
            return

        Food.delete(self.orm_session, user.id, fid)
        self.write({})
예제 #14
0
    def find_ingredients(selected):
        food = Food.find_one_food_by_name(name=selected)
        print(food.get_id())
        ingredients = Ingredients.find_ingredients(food.get_id())

        for ingredient in ingredients:
            print(
                "ID: {}, ingredient: {}, quantity: {}, unit: {}, food_ID: {}".format(ingredient['_id'],
                                                                                     ingredient['ingredient'],
                                                                                     ingredient['quantity'],
                                                                                     ingredient['unit'],
                                                                                     ingredient['food_id'])
            )
예제 #15
0
def show(username):
    user = User.get_or_none(name=username)
    if user is not None:
        reviews = user.all_user_reviews
        review_food_pic_list = []
        food_name_list = []
        food_latitude_list = []
        food_longitude_list = []
        food_price_list = []

        for review in [review.food_picture for review in reviews]:
            review_food_pic_list.append(S3_LOCATION + review)

        for review_id in [review.food_id for review in reviews]:
            food = Food.get_or_none(Food.id == review_id)
            food_name_list.append(food.name)
            food_latitude_list.append(food.latitude)
            food_longitude_list.append(food.longitude)
            food_price_list.append(str(food.price))

        return jsonify({
            "name":
            user.name,
            # "profile_image": user.profile_image,
            "review_id_list": [review.id for review in reviews],
            "food_id_list": [review.food_id for review in reviews],
            "review_criterion_z1_list":
            [review.criterion_z1 for review in reviews],
            "review_criterion_z2_list":
            [review.criterion_z2 for review in reviews],
            "review_criterion_z3_list":
            [review.criterion_z3 for review in reviews],
            "review_criterion_z4_list":
            [review.criterion_z4 for review in reviews],
            "review_criterion_z5_list":
            [review.criterion_z5 for review in reviews],
            "review_food_pic_list":
            review_food_pic_list,
            "food_name_list":
            food_name_list,
            "food_latitude_list":
            food_latitude_list,
            "food_longitude_list":
            food_longitude_list,
            "food_price_list":
            food_price_list
            # "reviews": reviews
        })
    else:
        return jsonify({"err": "Something went wrong"}), 400
예제 #16
0
 def post(self, request):
     # 创建食品
     owner = request.u
     store = owner.store
     name = request.json.get("name")
     description = request.json.get("description")
     price = float(request.json.get("price"))
     stock = int(request.json.get("stock"))
     image_ids = request.json.get("image_ids")
     if not all([store, name, description, price, stock]):
         return JsonErrorResponse("store, name, description, price, stock are needed", 400)
     new_food = Food(
         name=name,
         description=description,
         price=price,
         stock=stock,
         image_ids=image_ids,
         store=store
     )
     try:
         new_food.save()
     except Exception, e:
         print e
         return JsonErrorResponse("Fail:" + e.message)
예제 #17
0
def queryFood():
    request_json = request.get_json()
    name = request_json['food']
    if request.method == 'POST':
        tmp = Food(name, None, None, None, None)
        search = "%{}%".format(name)
        query = session.query(Food).filter(Food.food_name.like(search))
        if query is None:
            return "False"
        else:
            query = query.all()
            dictlist = []
            for food in query:
                dictlist.append(dict(food.asDict()))
            return json.dumps(dictlist)
    return "Not Okay"
예제 #18
0
def admin():
    user = session.get('username')
    if user is None:
        return redirect(url_for('login'))
    else:
        total_vegetablesAndFruits = Vegetablesfruits.objects()
        total_animals = Animals.objects()
        total_food = Food.objects()
        total_actions = Actions.objects()
        x = len(total_vegetablesAndFruits)
        y = len(total_animals)
        z = len(total_food)
        if request.method == 'GET':
            videos = Video.objects()
            return render_template(
                "admin.html",
                total_vegetablesAndFruits=total_vegetablesAndFruits,
                total_animals=total_animals,
                total_food=total_food,
                total_actions=total_actions,
                x=x,
                y=y,
                z=z,
                videos=videos)
        elif request.method == 'POST':
            form = request.form
            link = form['link']

            ydl = YoutubeDL()

            data = ydl.extract_info(link, download=False)

            title = data['title']
            thumbnail = data['thumbnail']
            views = data['view_count']
            youtube_id = data['id']
            link = link
            video = Video(
                title=title,
                thumbnail=thumbnail,
                views=views,
                youtube_id=youtube_id,
                link=link,
            )
            video.save()
            return redirect(url_for('admin'))
예제 #19
0
def main():
    game = GameWorld(20)
    cell1 = Cell(Food(), Vector2D(4, 4))
    cell2 = Cell(Food(), Vector2D(6, 7))
    cell3 = Cell(Food(), Vector2D(6, 8))
    cell4 = Cell(Food(), Vector2D(2, 1))
    cell5 = Cell(Food(), Vector2D(0, 17))
    cell6 = Cell(Food(), Vector2D(13, 15))
    cell7 = Cell(Food(), Vector2D(14, 2))
    cell8 = Cell(Wall(), Vector2D(5, 5))
    cell9 = Cell(Wall(), Vector2D(7, 6))
    cell10 = Cell(Wall(), Vector2D(8, 9))
    cell11 = Cell(Wall(), Vector2D(11, 15))
    cell12 = Cell(Wall(), Vector2D(18, 12))
    cell13 = Cell(Wall(), Vector2D(19, 1))
    cell14 = Cell(BlackHole(), Vector2D(2, 2))
    game.add_content([cell1, cell2, cell3, cell4, cell5, cell6, cell7, cell8,
                      cell9, cell10, cell11, cell12, cell13, cell14])
    p = Python(game, (5, 2), 5, Python.DOWN)
    p.set_head()
    p.set_body()
    game.print_world()
    direction = getch.getch()
    with start_log('game_start.txt', 'a') as s:
        pass
    while direction:
        os.system('clear')
        p.move(direction)
        with move_log('move_log.txt', 'a',
                      p.direction_by_ascii_code(direction)) as f:
            pass
        flag = p.is_dead()
        try:
            if not flag:
                game.print_world()
                direction = getch.getch()
            else:
                raise DeathError
        except DeathError:
            print("GAME OVER")
            break
        if game.no_food_board():
            print("GAME WON!")
            break
    with end_log('game_end.txt', 'a') as e:
                pass
예제 #20
0
 def get(self, *args, **kwargs):
     resp_data = {}
     id = int(self.get_argument('id', 0))
     info = Food(id=0,
                 name='',
                 cat_id='',
                 price='',
                 main_image='',
                 summary='',
                 stock='',
                 tags='')
     if id != 0:
         info = session.query(Food).filter_by(id=id).first()
     if not info:
         self.redirect('/food/index')
     cat_list = session.query(FoodCat).all()
     resp_data['info'] = info
     resp_data['cat_list'] = cat_list
     resp_data['current'] = 'index'
     self.render("food/set.html", **resp_data)
예제 #21
0
    def find_recipe():
        foods = Database.find(collection='food', query={}
                              )
        for food in foods:
            print(
                "ID: {}, name: {}, preparation: {}, type_ID: {}".format(food['_id'], food['name'], food['preparation'],
                                                                        food['type_id'])
            )
        filt = input("Do you want to filter by type? Y/N\n")
        if filt.lower() == "y":
            enter_type = input("Enter the type!\n")
            type_item = Types_Of_Food.find_one_type(enter_type)
            foods = Food.find_foods_by_type(type_item.get_id())

            for food in foods:
                print(
                    "ID: {}, name: {}, preparation: {}, type_ID: {}".format(food['_id'], food['name'],
                                                                            food['preparation'],
                                                                            food['type_id'])
                )
예제 #22
0
    def get(self, uid):
        """
        @apiDescription 获取uid所提供的食品
        @api {get} /shop/([0-9]+)/foods/? 获取某uid提供的食品
        @apiGroup food

        @apiPermission user

        @apiSuccess {Array} foods 某uid所提供的食品信息,格式如下:
        @apiSuccess {Number} fid 食品id
        @apiSuccess {String} image 图片路径
        @apiSuccess {String} name 食品名称
        @apiSuccess {JSON} seller 用户信息, 见获取用户信息API
        @apiSuccess {String} create_at 创建时间
        @apiSuccess {Number} price 食品价格
        @apiSuccess {Array} grades 评价的array
        @apiSuccess {Number} avg_grade 平均评分,如果没有评论则取4分

        @apiSuccessExample {json} Success Response:
        {
            "foods": [
                {
                    "fid": 4,
                    "price": 0,
                    "create_at": "1456317627",
                    "seller": 11,
                    "name": "炸酱面",
                    "image": ""
                },
                ...
            ],
        }
        """
        uid = int(uid)

        foods = list(map(self._get_food_info, Food.get_food_by_seller(self.orm_session, uid)))

        self.write(dict(
            foods=foods,
        ))
예제 #23
0
def post_food(store_id):
    """
    Creates a Food
    """
    store = storage.get(Store, store_id)
    if not store:
        abort(404)
    if not request.get_json():
        abort(400, description="Not a JSON")
    if 'name' not in request.get_json():
        abort(400, description="Missing name")

    data = request.get_json()
    instance = Food(**data)
    instance.store_id = store.id
    instance.save()
    return make_response(jsonify(instance.to_dict()), 201)
예제 #24
0
파일: app.py 프로젝트: linhkent/New-project
def food_detail(food_id):
    f = Food.objects().with_id(food_id)
    # Invalid Id, Not Found
    return render_template("food_detail.html", food=f)
예제 #25
0
파일: app.py 프로젝트: linhkent/New-project
def menu():
    if "token" in session:
        food_objects = Food.objects()
        return render_template("menu.html", food_list=food_objects)
    else:
        return "Forbidden"
import mlab
from models.food import Food
import pyexcel
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile

mlab.connect()
df = pd.read_excel('Crawdata.xlsx', sheet_name='pyexcel_sheet1')

for i in df.index:
  food = Food(title=df['title'][i], img=df['img'][i], nguyenlieu=df['nguyenlieu'][i].strip("\n").replace(" ",""), cachlam=df['cachlam'][i])
  # food.save()
print("Completed")
예제 #27
0
    def post(cls):
        ##################REFACTOR##############
        data = {
            'type': request.args.get('type'),
            'sr': request.args.get('sr'),
            'ndbno': int(request.args.get('ndbno')),
            'name': request.args.get('name'),
            'sd': request.args.get('sd'),
            'fg': request.args.get('fg'),
            'ds': request.args.get('ds'),
            'food_list_id': int(request.args.get('food_list_id'))
        }

        schema = {
            'type': {
                'type': 'string'
            },
            'sr': {
                'type': 'string'
            },
            'quantity': {
                'type': 'integer'
            },
            'ndbno': {
                'required': True,
                'type': 'integer'
            },
            'name': {
                'required': True,
                'type': 'string'
            },
            'sd': {
                'required': True,
                'type': 'string'
            },
            'fg': {
                'required': True,
                'type': 'string'
            },
            'ds': {
                'required': True,
                'type': 'string'
            },
            'food_list_id': {
                'required': True,
                'type': 'integer'
            }
        }

        v = Validator(schema)
        if not v(data):
            return {
                'message':
                'Something wrong with your Validators: {}'.format(v.errors)
            }, 400

        try:
            food = Food(**data).save_to_db()
            return 'Food has been saved'
        except Exception as e:
            return 'Food could not be saved, {}'.format(e)
예제 #28
0
 def setUp(self):
     self.cell = Cell(Food())
예제 #29
0
import mlab
from models.food import Food

mlab.connect()

# 1. Create
# B1: Create a food
f = Food(title="Banh sai", link="<<link sai>>")
# B2: Save it
# f.save()

# 2. Read
# B1: Get cursor
f_objects = Food.objects()  # Lazy loading # Same as list
# B2: Process cursor
# f_first = f_objects[0] # Thực sự truyền dữ liệu
# print(f_first.title)
# print(f_first.link)

# print(len(f_objects))
# print(f_objects.count()) # Bảo database đếm

# for f in f_objects:
#     print(f.title)
#     print(f.link)
#     print("----------------")

# f = f_objects[4]
# f.update(set__title= "Banh rat rat ngon", set__link= "Link ngon")
#             #op__prop: hành động __ cần thay đổi
#             # chỉ xảy ra trong database
예제 #30
0
#!/usr/bin/python3
from models.base import BaseModel
from models.store import Store
from models.food import Food
from models.drink import Drink
from models.order import Order
from models import storage
from models.confirmation import Confirmation

my_store = Store(name="JV")
my_store.save()

my_food = Food(price=4000, store_id=my_store.id, name="Tinto")
my_food.save()

my_drink = Drink(price=5000, store_id=my_store.id, name="Cafe")
my_drink.save()

my_order = Order(order_number=1,
                 drink_id=my_drink.id,
                 store_id=my_store.id,
                 user_name="Juan")
my_order.save()
all_order = storage.all(Order)

my_confirmation = Confirmation(store_id=my_store.id,
                               order_id=my_order.id,
                               order_number=3,
                               status="In Progress")
my_confirmation.save()
예제 #31
0
def create():

    logged_in_user_id = request.form.get('user_id')
    food_name = request.form.get('food_name')
    criterion_z1 = int(request.form.get('criterion_z1'))
    criterion_z2 = int(request.form.get('criterion_z2'))
    criterion_z3 = int(request.form.get('criterion_z3'))
    criterion_z4 = int(request.form.get('criterion_z4'))
    criterion_z5 = int(request.form.get('criterion_z5'))
    food_picture = request.files['food_picture']
    latitude = float(request.form.get('latitude'))
    longitude = float(request.form.get('longitude'))
    price = float(request.form.get('price'))

    # logged_in_user_id = request.json.get("user_id")
    # food_name = request.json.get('food_name')
    # criterion_z1 = request.json.get('criterion_z1')
    # criterion_z2 = request.json.get('criterion_z2')
    # criterion_z3 = request.json.get('criterion_z3')
    # criterion_z4 = request.json.get('criterion_z4')
    # criterion_z5 = request.json.get('criterion_z5')
    # food_picture = request.json.get('food_picture')
    # latitude = request.json.get('latitude')
    # longitude = request.json.get('longitude')
    # price = request.json.get('price')
    # tag_list = request.json.get('tag_list')

    food_already_exist = Food.select().where(
        Food.name == food_name, Food.latitude > latitude - 0.0002,
        Food.latitude < latitude + 0.0002, Food.longitude > longitude - 0.0002,
        Food.longitude < longitude + 0.0002)

    # print(food_already_exist, "FOOD ALREADY EXIST OBJECT")
    food_already_exist_id_arr = [
        food_already_exist_element.id
        for food_already_exist_element in food_already_exist
    ]

    # print(food_already_exist_id_arr, "FOOD ALREADY EXIST ARRAY")
    # print(food_already_exist_id_arr[0], "FIRST INDEX FOOD ALREADY EXIST")
    if food_already_exist:

        review_already_exist = Review.get_or_none(
            user_id=logged_in_user_id, food_id=food_already_exist_id_arr[0])
        # print(review_already_exist, "REVIEW ALREADY EXIST")

        if review_already_exist:
            print("HELLO WORLD I WENT IN ")
            return jsonify({
                "status":
                "failed",
                "message":
                "You have already submitted a review for this dish in this location"
            }), 400
        else:
            print("I AM CREATING A REVIEW INSTANCE")
            new_review_instance = Review(user_id=logged_in_user_id,
                                         food_picture=food_picture,
                                         criterion_z1=criterion_z1,
                                         criterion_z2=criterion_z2,
                                         criterion_z3=criterion_z3,
                                         criterion_z4=criterion_z4,
                                         criterion_z5=criterion_z5,
                                         food_id=food_already_exist_id_arr[0])
            if new_review_instance.save():
                file = request.files['food_picture']
                if file and allowed_file(file.filename):
                    file.filename = secure_filename(file.filename)
                    output = upload_file_to_s3(file, S3_BUCKET_NAME)
                    food_picture = str(output)
                    new_review_instance = Review(
                        user_id=logged_in_user_id,
                        food_picture=food_picture,
                        criterion_z1=criterion_z1,
                        criterion_z2=criterion_z2,
                        criterion_z3=criterion_z3,
                        criterion_z4=criterion_z4,
                        criterion_z5=criterion_z5,
                        food_id=food_already_exist_id_arr[0])
                    if new_review_instance.save():
                        # Creation of tag
                        # for tag_element in tag_list:
                        #     tag_already_exist = Tag.get_or_none(name = tag_element)
                        #     if tag_already_exist:
                        #         new_tag_review_instance = TagReview(review_id = new_review_instance.id, tag_id = tag_already_exist.id)
                        #         new_tag_review_instance.save()
                        #     else:
                        #         new_tag_instance = Tag(name = tag_element)
                        #         new_tag_instance.save()
                        #         new_tag_instance_id = Tag.get_or_none(name = tag_element).id
                        #         new_tag_review_instance = TagReview(review_id = new_review_instance.id, tag_id = new_tag_instance_id)
                        #         new_tag_review_instance.save()
                        # if food image upload success
                        return jsonify({
                            "logged_in_user_id": logged_in_user_id,
                            "food_picture": food_picture,
                            "criterion_z1": criterion_z1,
                            "criterion_z2": criterion_z2,
                            "criterion_z3": criterion_z3,
                            "criterion_z4": criterion_z4,
                            "criterion_z5": criterion_z5,
                            "food_id": food_already_exist.id,
                            "price": price,
                            "latitude": latitude,
                            "longitude": longitude
                            # "tag_list": tag_list
                        }), 200
                    else:
                        # if jsonify error
                        return jsonify({"err": "Something went wrong"}), 400
                else:
                    return jsonify({"err": "Something went wrong"}), 400
                    # if image fail to upload
    else:
        new_food_instance = Food(name=food_name,
                                 longitude=longitude,
                                 latitude=latitude,
                                 price=price)
        if new_food_instance.save():
            print(food_picture)
            # print(food_picture.files)
            file = request.files['food_picture']
            print(file.filename)
            if file and allowed_file(file.filename):
                file.filename = secure_filename(file.filename)
                output = upload_file_to_s3(file, S3_BUCKET_NAME)
                food_picture = str(output)

                # print(food_name,"NAME OF FOOD")

                # print(latitude, "LATTITUDE")
                # print(longitude, "LONGITUDE")
                # print(type(latitude), "LATITUDE TYPE OF")
                # print(type(longitude), "LONTITUDE TYPE OF")

                latitude = str(latitude)
                longitude = str(longitude)
                # print(latitude, "LATTITUDE 2")
                # print(longitude, "LONGITUDE 2")

                # print(type(latitude), "LATITUDE TYPE OF 2")
                # print(type(longitude), "LONTITUDE TYPE OF 2")

                new_food_instance = Food.get_or_none(name=food_name,
                                                     longitude=longitude,
                                                     latitude=latitude)
                # print(new_food_instance, "REVIEW INSTANCE")
                # print(new_food_instance.id, "REVIEW INSTANCE ID")
                new_review_instance = Review(user_id=logged_in_user_id,
                                             food_picture=food_picture,
                                             criterion_z1=criterion_z1,
                                             criterion_z2=criterion_z2,
                                             criterion_z3=criterion_z3,
                                             criterion_z4=criterion_z4,
                                             criterion_z5=criterion_z5,
                                             food_id=new_food_instance.id)
                if new_review_instance.save():
                    # Creation of tag
                    # for tag_element in tag_list:
                    #     tag_already_exist = Tag.get_or_none(name = tag_element)
                    #     if tag_already_exist:
                    #         new_tag_review_instance = TagReview(review_id = new_review_instance.id, tag_id = tag_already_exist.id)
                    #         new_tag_review_instance.save()
                    #     else:
                    #         new_tag_instance = Tag(name = tag_element)
                    #         new_tag_instance.save()
                    #         new_tag_instance_id = Tag.get_or_none(name = tag_element).id
                    #         new_tag_review_instance = TagReview(review_id = new_review_instance.id, tag_id = new_tag_instance_id)
                    #         new_tag_review_instance.save()
                    # if food image upload success
                    return jsonify({
                        "logged_in_user_id": logged_in_user_id,
                        "food_picture": food_picture,
                        "criterion_z1": criterion_z1,
                        "criterion_z2": criterion_z2,
                        "criterion_z3": criterion_z3,
                        "criterion_z4": criterion_z4,
                        "criterion_z5": criterion_z5,
                        "food_id": new_food_instance.id,
                        "price": price,
                        "latitude": float(latitude),
                        "longitude": float(longitude)
                        # "tag_list": tag_list
                    }), 200
                else:
                    # if jsonify error
                    return jsonify({"err": "Something went wrong"}), 400
            else:
                return jsonify({"err": "Something went wrong"}), 400
                # if image fail to upload
        else:
            return jsonify({"err": "Something went wrong"}), 400
예제 #32
0
    def test_no_food_board_on_set_food_cell(self):
        self.game_world.set_cell(Cell(Food(), Vector2D(3, 4)))

        self.assertFalse(self.game_world.no_food_board())
예제 #33
0
snake_dir = 'east'

# Game variables
gameOver = False
gameStarted = False
score = 0
highscore = 0

pygame.init()

pygame.display.set_caption("Snake Game")
window = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

grid = Grid(window, SCREEN_WIDTH, SCREEN_HEIGHT, SQUARE_SIZE)
snake = Snake(snake_pos_x, snake_pos_y, snake_dir, SQUARE_SIZE)
food = Food(15, 15, SCREEN_WIDTH / SQUARE_SIZE, SCREEN_HEIGHT / SQUARE_SIZE,
            SQUARE_SIZE)
menu = Menu(window, SCREEN_WIDTH, SCREEN_HEIGHT)

clock = pygame.time.Clock()

while True:
    pygame.time.delay(40)
    clock.tick(10)

    if gameStarted == False:
        menu.draw(score, highscore)

    if gameOver == False and gameStarted:
        grid.draw(snake, food)

        snake.move()
예제 #34
0
def show(food_name):
    # food_name = request.json.get('food_name')
    all_of_that_food = Food.select().where(Food.name == food_name)

    if len(all_of_that_food) != 0:
        food_id_arr = [food.id for food in all_of_that_food]
        food_name_arr = [food.name for food in all_of_that_food]
        food_price_arr = [str(food.price) for food in all_of_that_food]
        food_latitude_arr = [food.latitude for food in all_of_that_food]
        food_longitude_arr = [food.longitude for food in all_of_that_food]
        criterion_z1_list = []
        criterion_z2_list = []
        criterion_z3_list = []
        criterion_z4_list = []
        criterion_z5_list = []
        average_c1 = []
        average_c2 = []
        average_c3 = []
        average_c4 = []
        average_c5 = []
        first_review_food_pic = []

        for food_id_element in food_id_arr:
            criterion_z1_list.append([
                e.criterion_z1 for e in Review.select().join(
                    Food, on=(Food.id == Review.food_id)).where(
                        Food.id == food_id_element)
            ])
            criterion_z2_list.append([
                e.criterion_z2 for e in Review.select().join(
                    Food, on=(Food.id == Review.food_id)).where(
                        Food.id == food_id_element)
            ])
            criterion_z3_list.append([
                e.criterion_z3 for e in Review.select().join(
                    Food, on=(Food.id == Review.food_id)).where(
                        Food.id == food_id_element)
            ])
            criterion_z4_list.append([
                e.criterion_z4 for e in Review.select().join(
                    Food, on=(Food.id == Review.food_id)).where(
                        Food.id == food_id_element)
            ])
            criterion_z5_list.append([
                e.criterion_z5 for e in Review.select().join(
                    Food, on=(Food.id == Review.food_id)).where(
                        Food.id == food_id_element)
            ])
            first_review_food_pic.append(S3_LOCATION + [
                e.food_picture for e in Review.select().join(
                    Food, on=(Food.id == Review.food_id)).where(
                        Food.id == food_id_element)
            ][0])

        for criterion in criterion_z1_list:
            average_c1.append(floor(sum(criterion) / len(criterion)))
        for criterion in criterion_z2_list:
            average_c2.append(floor(sum(criterion) / len(criterion)))
        for criterion in criterion_z3_list:
            average_c3.append(floor(sum(criterion) / len(criterion)))
        for criterion in criterion_z4_list:
            average_c4.append(floor(sum(criterion) / len(criterion)))
        for criterion in criterion_z5_list:
            average_c5.append(floor(sum(criterion) / len(criterion)))

        return jsonify({
            # "all_of_that_food": all_of_that_food
            "food_id_arr": food_id_arr,
            "food_name_arr": food_name_arr,
            "food_price_arr": food_price_arr,
            "food_latitude_arr": food_latitude_arr,
            "food_longitude_arr": food_longitude_arr,
            "criterion_z1_list": criterion_z1_list,
            "criterion_z2_list": criterion_z2_list,
            "criterion_z3_list": criterion_z3_list,
            "criterion_z4_list": criterion_z4_list,
            "criterion_z5_list": criterion_z5_list,
            "average_c1": average_c1,
            "average_c2": average_c2,
            "average_c3": average_c3,
            "average_c4": average_c4,
            "average_c5": average_c5,
            "first_review_food_pic": first_review_food_pic
        })
    else:
        return jsonify({"err": "Food dish does not exist"}), 400