Exemplo n.º 1
0
def create_product(product_name, product_attribute_fields, category):
    product_attributes = []
    loop = True
    while loop:
        attributes = input(
            f"Introduce the {product_attribute_fields} for the {product_name}, each attribute separated by a comma\n"
        )
        product_attributes = attributes.split(',')
        if product_attributes.__len__() != 6:
            product_attributes.clear()
            option_to_go = int(
                input(
                    "Please make sure to include all the attributes. Input 1 to try again or any other number to return to the store menu:\n"
                ))
            if option_to_go != 1:
                return
        else:
            loop = False
    result = getattr(product, product_name)
    new_product = result(category, product_attributes[0],
                         product_attributes[1], product_attributes[2],
                         product_attributes[3], product_attributes[4],
                         product_attributes[5])
    Products.add_product(new_product)
    input(
        f"{product_name} product added successfully. Press enter key in order to continue\n"
    )
    def test_get_products(self):
        """test get method for products"""

        sample_product_from_db = {'name': 'breakfast burrito', 'cost': 2.02, 'ingredients': 'eggs, flour tortilla, refried beans'}

        product_instance = Products()
        test = product_instance.get_products()
        self.assertEqual(test[0], sample_product_from_db)
def delete_product():
    if request.method == 'POST':
        name = request.form['product-name']

        product_instance = Products()
        product_instance.delete_product(name)
        return redirect('/products')
    else:
        return render_template('delete_product.html')
Exemplo n.º 4
0
def crawl_products():
    try:
        products = Products()
        products = products.go(request.args.get('url'))
        return jsonify(products)
    except Exception as e:
        resp = jsonify({'errcode': 500, 'errmsg': '抓取产品列表异常: ' + str(e)})
        resp.status_code = 500
        return resp
def add_new_product():
    if request.method == 'POST':
        name = request.form['product-name']
        cost = request.form['product-cost']
        ingredients = request.form['product-ingredients']

        product_instance = Products()
        product_instance.add_product(name, cost, ingredients)
        return redirect('/products')
    else:
        return render_template('add_new_product.html')
    def test_add_product(self):
        """test add product method for products"""
        product_to_add = {'name': 'cucumber', 'cost': 5.55, 'ingredients': None}

        product_instance = Products()

        # method should return object added if successful
        test = product_instance.add_product(product_to_add["name"], product_to_add["cost"], product_to_add["ingredients"])
        self.assertEqual(test, product_to_add)

        # method should return 0 if object already exists
        product_to_add_key_already_exists = {'name': 'chips', 'cost': 2.22, 'ingredients': None}
        test2 = product_instance.add_product(product_to_add_key_already_exists["name"], product_to_add_key_already_exists["cost"], product_to_add_key_already_exists["ingredients"])
        self.assertEqual(test2, 0)
    def test_delete_product(self):
        """test delete product method for products"""
        product_key_to_delete = 'cucumber'

        product_instance = Products()

        # method should return object added if successful
        test = product_instance.delete_product(product_key_to_delete)
        self.assertEqual(test, {'name': product_key_to_delete})

        # method should return 0 if the key does not exist
        product_key_to_delete_2 = 'apple pie'
        test2 = product_instance.delete_product(product_key_to_delete_2)
        self.assertEqual(test2, 0)
Exemplo n.º 8
0
 def sell_product(self, id):
     for i in self.list_of_products:
         if i.id == id:
             Products.print_info(i)
             self.list_of_products.remove(i)
             print("\nThank you for your purchase!\n")
             print("\n", "*" * 50, "\n")
             in_inventory = True
         else:
             in_inventory = False
             pass
     if in_inventory == False:
         print("\nThat ID is not in our inventory!")
         print("\n", "*" * 50, "\n")
     return self
Exemplo n.º 9
0
def list_categories():
    # display the existing categories or the categories with the products
    option_list_categories = int(
        input(
            "List the categories only or the categories with products?\n1. Categories only\n2. Categories and products\n3. Go back\n"
        ))
    if option_list_categories == 1:
        try:
            categories = Categories.load_categories()
            for index, cat in enumerate(categories, start=1):
                print(f"{index}. {cat.name}")
            input("Press enter key in order to continue\n")
        except JSONDecodeError:
            input(
                "Error on retrieving the categories. Press enter key in order to continue\n"
            )
    elif option_list_categories == 2:
        try:
            categories = Categories.load_categories()
            products = Products.load_products()
            for index, cat in enumerate(categories, start=1):
                print(f"{index}. {cat.name}")
                for prod in products:
                    if prod.get_category_name() == cat.name:
                        print(f"\t{prod}")
            input("Press enter key in order to continue\n")
        except JSONDecodeError:
            input(
                "Error on retrieving the categories. Press enter key in order to continue\n"
            )
    elif option_list_categories == 3:
        print("Going back...\n")
    else:
        error_handler()
        list_categories()
Exemplo n.º 10
0
def get_products():
    resource = '/Products'

    try:
        client = ApiClient(URI, HEADERS, USERNAME, PASSWORD)

        while True:
            response = client.GET(resource)
            if response.status_code == 200 and response.is_json:
                products = Products(response.json)
                for product in products:
                    print("{0:38} {1:40} {2:20} {3}".format(
                        product.id, product.Description[:40]
                        if product.Description != None else '',
                        product.SearchName[:20]
                        if product.SearchName != None else '', product.Price))
            else:
                print("response error: %d - %s" %
                      (response.status_code, response.text))

            # paging
            resource = response.next_link
            if (resource == None or response.status_code != 200):
                break

    except ValueError:
        print("Unexpected data: ", response.text)
    except:
        print("Unexpected error:", sys.exc_info()[0])
Exemplo n.º 11
0
def display_products():
    # display all existing products
    try:
        products = Products.load_products()
        for index, prod in enumerate(products, start=1):
            print(f"{index}. {prod}")
        input("\nPress enter key in order to continue\n")
    except JSONDecodeError:
        input(
            "Error on retrieving the products. Press enter key in order to continue\n"
        )
Exemplo n.º 12
0
def remove_product():
    option_remove_product_menu = int(
        input(
            "You will have to input the index of the product you would like to remove. If you need to see the list of products, "
            "select option 2.\n1. Remove product\n2. Display all products\n3. Go back\n"
        ))
    if option_remove_product_menu == 1:
        index_product_to_remove = int(
            input(
                "Introduce the index of the product to be removed(starting from 1):\n"
            ))
        try:
            products = Products.load_products()
            if 0 < index_product_to_remove <= products.__len__():
                product_to_remove = products[index_product_to_remove - 1]
                Products.remove_product(product_to_remove)
                input(
                    "Product -" + str(product_to_remove) +
                    "- removed successfully\nPress enter key in order to continue\n"
                )
            else:
                product_option = int(
                    input(
                        "This product does not exist in the list. Input 1 to try again or any other number to return to the store menu:\n"
                    ))
                if product_option == 1:
                    remove_product()
        except JSONDecodeError:
            input(
                "Error on retrieving the products. Press enter key in order to continue\n"
            )
    elif option_remove_product_menu == 2:
        display_products()
        remove_product()
    elif option_remove_product_menu == 3:
        print("Going back...\n")
    else:
        error_handler()
        remove_product()
Exemplo n.º 13
0
def predict(receipt):

    ## predict vendor
    vendor = Vendor(receipt.rawText, receipt.lines)
    vendor.run()
    receipt.ruleBasedPrediction['vendor'] = vendor._result

    ## predict tax rate
    taxRate = TaxRate(receipt.rawText, receipt.lines, receipt.graph,
                      receipt.words)
    taxRate.run()
    receipt.ruleBasedPrediction['tax_rate'] = taxRate._result

    ## predict total price
    totalPrice = TotalPrice(receipt.rawText, receipt.lines)
    totalPrice.run()
    receipt.ruleBasedPrediction['total_price'] = totalPrice._result

    ## predict date
    date = Date(receipt.rawText, receipt.lines)
    date.run()
    receipt.ruleBasedPrediction['date'] = date._result

    ## predict currency
    currency = Currency(receipt.rawText)
    currency.run()
    receipt.ruleBasedPrediction['currency'] = currency._result

    ## predict address
    address = Address(receipt.linesText)
    address.run()
    receipt.ruleBasedPrediction['address'] = address._result

    ## predict products
    products = Products(receipt.rawText, receipt.lines, receipt.linesText)
    products.run()
    receipt.ruleBasedPrediction['products'] = products._result
Exemplo n.º 14
0
def remove_category():
    option_remove_category = int(
        input(
            "Warning! Deleting a category will also delete all the products inside of it.\n1. Continue\n2. Go back\n"
        ))
    if option_remove_category == 1:
        category_to_remove = Category(
            input("Introduce the name of the category to be removed:\n"))
        try:
            categories = Categories.load_categories()
            if categories.count(category_to_remove) > 0:
                products = Products.load_products()
                for prod in products:
                    if prod.get_category_name() == category_to_remove.name:
                        Products.remove_product(prod)
                Categories.remove_category(category_to_remove)
                input(
                    "Category -" + str(category_to_remove) +
                    "- and all its products were removed successfully.\nPress enter key in order to continue\n"
                )
            else:
                category_option = int(
                    input(
                        "This category does not exist in the list. Input 1 to try entering another category or any other number to return to the store menu:\n"
                    ))
                if category_option == 1:
                    remove_category()
        except JSONDecodeError:
            input(
                "Error on retrieving the categories. Press enter key in order to continue\n"
            )
    elif option_remove_category == 2:
        print("Going back...\n")
    else:
        error_handler()
        remove_category()
Exemplo n.º 15
0
def place_order():
    option_place_order = int(
        input(
            "You will have to input the index of the product you would like to order. If you need to see the list of products, "
            "select option 2.\n1. Prepare order\n2. Display all products\n3. Go back\n"
        ))
    if option_place_order == 1:
        index_product = int(
            input(
                "Introduce the index of the product you want to order(starting from 1):\n"
            ))
        try:
            products = Products.load_products()
            if 0 < index_product <= products.__len__():
                product_to_order = products[index_product - 1]
                quantity = 0
                loop = True
                while loop:
                    quantity = int(
                        input(
                            "How many products of this kind you would like to order?\n"
                        ))
                    if quantity > 0:
                        loop = False
                delivery_address = input(
                    "Please write the address where this order should be delivered:\n"
                )
                prepared_order = Order(product_to_order.__dict__,
                                       type(product_to_order).__name__,
                                       quantity, delivery_address)
                Orders.add_order(prepared_order)
                input(
                    f"Your order has been placed successfully. Press enter key in order to continue\n"
                )
        except JSONDecodeError:
            input(
                "Error on retrieving the products. Press enter key in order to continue\n"
            )
    elif option_place_order == 2:
        display_products()
        place_order()
    elif option_place_order == 3:
        print("Going back...\n")
    else:
        error_handler()
        remove_product()
Exemplo n.º 16
0
 def inflation(self, percent_increase):
     self.products.price = Products.update_price(percent_increase, True)
Exemplo n.º 17
0
        return self

    def sell_product(self, id):
        self.products.remove(self.products[id])

        return self

    def inflation(self, percent_increase):
        self.products.price = Products.update_price(percent_increase, True)

    def set_clearance(self, category, percent_discount):
        pass


myStore = Store("Michael's Store")
myShirt = Products("Shirt", 30, "Top")
myPants = Products("Jeans", 50, "Bottoms")
myHat = Products("Hat", 25, " Hat")

myStore.add_product(myShirt).add_product(myPants).add_product(myHat)
myStore.sell_product(0)
myStore.inflation(10)

# print(myStore.products)


def print_products_list():
    for product_list in myStore.products:
        print(product_list.name, product_list.price, product_list.category)

Exemplo n.º 18
0
from flask import Flask, render_template, jsonify, request, Blueprint
from flask_paginate import Pagination, get_page_parameter, get_page_args
from urllib import parse
import contentful
from forms import SearchBar
from math import ceil
from products import Products
from decouple import config





get_products = Products()

app = Flask(__name__)
app.config['SECRET_KEY'] = config('SECRET_KEY')
# mod = Blueprint('product_page', __name__)
# app.register_blueprint(mod)


@app.template_filter('get_image')
def get_image(input):
    try:
        return input.image[0]['secure_url']
    except AttributeError:
        pass

@app.route('/')
def home():
    products = get_products.get_discount_items()
Exemplo n.º 19
0
from product import Product
from products import Products
from order import Order
from orders import Orders
import pickle

products = None
orders = None

try:
    f = open('data.pkl', 'rb')
except IOError:
    print 'Cannot open file!!!'
    products = Products()
    orders = Orders()
    data = {}
else:
    data = pickle.load(f)
    products = Products(data['products'], data['plast'])
    orders = Orders(data['orders'])
    f.close()
    if not products.empty():
        print 'Data has been loaded'
    else:
        print 'File has been found, but it has any data'


def select_menu():
    print "\n1. 'products'\n2. 'orders'\n3. Back"
    while True:
        key = raw_input("Select table: ")
Exemplo n.º 20
0
#!/usr/bin/env python3

import pyhop2
from a_star import astar
from gbfs import gbfs
from map import Map
from renderer import Renderer
from robot_path_controller.srv import Path, PathResponse
from robot_path_controller.msg import WayPoint
import rospy
from gazebo_msgs.srv import GetModelState
from check_result import check_result, pause, set_trace
from products import Products
import numpy as np

prod = Products()
prod.seed(1)
item_list = prod.get_random_list()
item_list.append('cashier')
renderer = Renderer()

#########################################################
## Grocery Plan #########################################
# loc = {'robot': (7.4, 12.85), 'brocoli': (1.54, 5.4), 'cucumber': (1.54, 7.91), 'salt': (8.39, 4.79), 'watermelon': (5.1, 8.44), 'strawberry': (2.31, 6.36), 'potato': (3.58, 7.44), 'hamburger': (7.4, 12.85)}

domain_name = 'groceryplan'


# Create a new domain to contain the methods and operators
pyhop2.Domain(domain_name)
Exemplo n.º 21
0
from products import Products
from store import Store

BuyLow = Store("BuyLow")
MasonMart = Store("MasonMart")

cereal = Products(2.50, "cereal", "breakfast")
pastries = Products(3.50, "pastries", "breakfast")
steak = Products(2.25, "steak", "meat")
chicken = Products(2.00, "chicken", "meat")
ham = Products(1.25, "ham", "meat")
apple = Products(.50, "apple", "produce")
banana = Products(.35, "banana", "produce")
milk = Products(2.88, "milk", "dairy")
cheese = Products(3.00, "cheese", "dairy")

BuyLow.addProduct(cheese, "dairy")
BuyLow.addProduct(milk, "dairy")
BuyLow.addProduct(banana, "produce")
BuyLow.addProduct(apple, "produce")
BuyLow.addProduct(ham, "meat")
BuyLow.addProduct(chicken, "meat")
BuyLow.addProduct(steak, "meat")
BuyLow.addProduct(pastries, "breakfast")
BuyLow.addProduct(cereal, "breakfast")

BuyLow.availableProducts("dairy")

BuyLow.availableProducts("dairy")
def products():
    product_instance = Products()
    data = product_instance.get_products()
    return render_template('products.html', products=data)
Exemplo n.º 23
0
from products import Products
from store import Store

apple = Products({"category": "fruit", "name": "apple", "price": .5})
orange = Products({"category": "fruit", "name": "orange", "price": .8})
banana = Products({"category": "fruit", "name": "banana", "price": .6})

carrot = Products({"category": "vegetable", "name": "carrot", "price": 1})
potato = Products({"category": "vegetable", "name": "potato", "price": 2})
onion = Products({"category": "vegetable", "name": "onion", "price": 1.5})

hat = Products({"category": "clothing", "name": "hat", "price": 10})
boots = Products({"category": "clothing", "name": "boots", "price": 20})
gloves = Products({"category": "clothing", "name": "gloves", "price": 6})

store_1 = Store("Bob's Store")
store_2 = Store("Bill's Store")

store_1.add_product(apple).add_product(carrot).add_product(gloves).add_product(
    onion).list_of_inventory()
store_1.sell_product(3).list_of_inventory().inflation(
    .2).list_of_inventory().set_clearance("clothing", .1).list_of_inventory()
Exemplo n.º 24
0
    def __init__(self, radius=0.177, clearance=0.15):
        super().__init__(radius, clearance)

        self.blank_image = np.ones(shape=[1400, 1600, 3], dtype=np.uint8)

        self.font = cv2.FONT_ITALIC

        self.products = Products()

        self.cashier_coord = (1465.5536, 1400 - 304.2128)

        distance = (radius + clearance) * 100

        boundrec1 = np.array(
            [[[0, 1400], [0, 1400 - 476.5123], [119.9979, 1400 - 476.5123],
              [119.9979, 1400 - 974.8759], [113.0248, 1400 - 1093.9484],
              [326.3999, 1400 - 1215.5476], [803.7341, 1400 - 1345.3712],
              [1052.8966, 1400 - 1345.3712], [1161.2505, 1400 - 1301.1247],
              [1505.3117, 1400 - 953.9164], [1544.8179, 1400 - 891.2024],
              [1544.8179, 1400]]], np.int32)

        cv2.fillConvexPoly(self.blank_image, boundrec1, (255, 255, 255))

        x1 = ((self.line2.coeff[1] - self.line1.coeff[1]) /
              (self.line1.coeff[0] - self.line2.coeff[0]))
        y1 = (x1 * self.line1.coeff[0] + self.line1.coeff[1])

        x2 = ((self.line3.coeff[1] - self.line2.coeff[1]) /
              (self.line2.coeff[0] - self.line3.coeff[0]))
        y2 = (x2 * self.line2.coeff[0] + self.line2.coeff[1])

        x2 = ((self.line3.coeff[1] - self.line2.coeff[1]) /
              (self.line2.coeff[0] - self.line3.coeff[0])) * 100
        y2 = (x2 / 100 * self.line2.coeff[0] + self.line2.coeff[1]) * 100

        boundrec2 = np.array(
            [[[0 + distance, 1400 - distance],
              [0 + distance, 1400 - 476.5123 + distance],
              [119.9979 + distance, 1400 - 476.5123 + distance],
              [119.9979 + distance, 1400 - 974.8759],
              [x1 * 100, 1400 - y1 * 100], [x2 * 100, 1400 - y2 * 100],
              [803.7341, 1400 - 1345.3712 + distance],
              [1052.8966, 1400 - 1345.3712 + distance],
              [1161.2505, 1400 - 1301.1247], [1505.3117, 1400 - 953.9164],
              [1544.8179 - distance, 1400 - 891.2024],
              [1544.8179 - distance, 1400 - distance]]], np.int32)

        cv2.fillConvexPoly(self.blank_image, boundrec2, (211, 211, 211))

        # Cashiers
        cashier1_d = np.array(
            [[[525.1926 - distance, 1400 - 224.6674 + distance],
              [525.1926 - distance, 1400 - 369.3339 - distance],
              [603.5216 + distance, 1400 - 369.3339 - distance],
              [603.5216 + distance, 1400 - 224.6674 + distance]]], np.int32)
        cashier2_d = np.array(
            [[[717.2170 - distance, 1400 - 224.6674 + distance],
              [717.2170 - distance, 1400 - 369.3339 - distance],
              [797.5383 + distance, 1400 - 369.3339 - distance],
              [797.5383 + distance, 1400 - 224.6674 + distance]]], np.int32)
        cashier3_d = np.array(
            [[[904.0226 - distance, 1400 - 224.6674 + distance],
              [904.0226 - distance, 1400 - 369.3339 - distance],
              [983.2662 + distance, 1400 - 369.3339 - distance],
              [983.2662 + distance, 1400 - 224.6674 + distance]]], np.int32)
        cashier4_d = np.array(
            [[[1093.1436 - distance, 1400 - 224.6674 + distance],
              [1093.1436 - distance, 1400 - 369.3339 - distance],
              [1175.5313 + distance, 1400 - 369.3339 - distance],
              [1175.5313 + distance, 1400 - 224.6674 + distance]]], np.int32)
        cashier5_d = np.array(
            [[[1283.3400 - distance, 1400 - 224.6674 + distance],
              [1283.3400 - distance, 1400 - 369.3339 - distance],
              [1364.6369 + distance, 1400 - 369.3339 - distance],
              [1364.6369 + distance, 1400 - 224.6674 + distance]]], np.int32)
        cv2.fillPoly(self.blank_image, cashier1_d, (255, 255, 255))
        cv2.fillPoly(self.blank_image, cashier2_d, (255, 255, 255))
        cv2.fillPoly(self.blank_image, cashier3_d, (255, 255, 255))
        cv2.fillPoly(self.blank_image, cashier4_d, (255, 255, 255))
        cv2.fillPoly(self.blank_image, cashier5_d, (255, 255, 255))

        cashier1 = np.array(
            [[[525.1926, 1400 - 224.6674], [525.1926, 1400 - 369.3339],
              [603.5216, 1400 - 369.3339], [603.5216, 1400 - 224.6674]]],
            np.int32)
        cashier2 = np.array(
            [[[717.2170, 1400 - 224.6674], [717.2170, 1400 - 369.3339],
              [797.5383, 1400 - 369.3339], [797.5383, 1400 - 224.6674]]],
            np.int32)
        cashier3 = np.array(
            [[[904.0226, 1400 - 224.6674], [904.0226, 1400 - 369.3339],
              [983.2662, 1400 - 369.3339], [983.2662, 1400 - 224.6674]]],
            np.int32)
        cashier4 = np.array(
            [[[1093.1436, 1400 - 224.6674], [1093.1436, 1400 - 369.3339],
              [1175.5313, 1400 - 369.3339], [1175.5313, 1400 - 224.6674]]],
            np.int32)
        cashier5 = np.array(
            [[[1283.3400, 1400 - 224.6674], [1283.3400, 1400 - 369.3339],
              [1364.6369, 1400 - 369.3339], [1364.6369, 1400 - 224.6674]]],
            np.int32)
        cv2.fillPoly(self.blank_image, cashier1, (0, 0, 0))
        cv2.fillPoly(self.blank_image, cashier2, (0, 0, 0))
        cv2.fillPoly(self.blank_image, cashier3, (0, 0, 0))
        cv2.fillPoly(self.blank_image, cashier4, (0, 0, 0))
        cv2.fillPoly(self.blank_image, cashier5, (0, 0, 0))

        #Circles

        cv2.circle(self.blank_image, (341, 1400 - 578), 78 + int(distance),
                   (255, 255, 255), -1)
        cv2.circle(self.blank_image, (341, 1400 - 578), 78, (0, 0, 0), -1)

        # Shelves

        shelf1_d = np.array(
            [[[625.3904 - distance, 1400 - 1076.4730 - distance],
              [625.3904 - distance, 1400 - 977.5013 + distance],
              [960.5268 + distance, 1400 - 977.5013 + distance],
              [960.5268 + distance, 1400 - 1076.4730 - distance]]], np.int32)
        shelf1 = np.array(
            [[[625.3904, 1400 - 1076.4730], [625.3904, 1400 - 977.5013],
              [960.5268, 1400 - 977.5013], [960.5268, 1400 - 1076.4730]]],
            np.int32)
        cv2.fillPoly(self.blank_image, shelf1_d, (255, 255, 255))
        cv2.fillPoly(self.blank_image, shelf1, (0, 0, 0))

        shelf2_d = np.array(
            [[[625.3904 - distance, 1400 - 620.9282 - distance],
              [625.3904 - distance, 1400 - 526.6344 + distance],
              [960.5268 + distance, 1400 - 526.6344 + distance],
              [960.5268 + distance, 1400 - 620.9282 - distance]]], np.int32)
        shelf2 = np.array(
            [[[625.3904, 1400 - 620.9282], [625.3904, 1400 - 526.6344],
              [960.5268, 1400 - 526.6344], [960.5268, 1400 - 620.9282]]],
            np.int32)
        cv2.fillPoly(self.blank_image, shelf2_d, (255, 255, 255))
        cv2.fillPoly(self.blank_image, shelf2, (0, 0, 0))

        shelf3_d = np.array(
            [[[625.3904 - distance, 1400 - 843.2007 - distance],
              [625.3904 - distance, 1400 - 750.5381 + distance],
              [722.7457 + distance, 1400 - 750.5381 + distance],
              [722.7457 + distance, 1400 - 843.2007 - distance]]], np.int32)
        shelf3 = np.array(
            [[[625.3904, 1400 - 843.2007], [625.3904, 1400 - 750.5381],
              [722.7457, 1400 - 750.5381], [722.7457, 1400 - 843.2007]]],
            np.int32)
        cv2.fillPoly(self.blank_image, shelf3_d, (255, 255, 255))
        cv2.fillPoly(self.blank_image, shelf3, (0, 0, 0))

        shelf4_d = np.array(
            [[[862.2844 - distance, 1400 - 843.2007 - distance],
              [862.2844 - distance, 1400 - 750.5381 + distance],
              [961.0721 + distance, 1400 - 750.5381 + distance],
              [961.0721 + distance, 1400 - 843.2007 - distance]]], np.int32)
        shelf4 = np.array(
            [[[862.2844, 1400 - 843.2007], [862.2844, 1400 - 750.5381],
              [961.0721, 1400 - 750.5381], [961.0721, 1400 - 843.2007]]],
            np.int32)
        cv2.fillPoly(self.blank_image, shelf4_d, (255, 255, 255))
        cv2.fillPoly(self.blank_image, shelf4, (0, 0, 0))

        shelf5_d = np.array(
            [[[270.2442 - distance, 1400 - 882.7066 - distance],
              [270.2442 - distance, 1400 - 784.6692 + distance],
              [392.6082 + distance, 1400 - 784.6692 + distance],
              [392.6082 + distance, 1400 - 882.7066 - distance]]], np.int32)
        shelf5 = np.array(
            [[[270.2442, 1400 - 882.7066], [270.2442, 1400 - 784.6692],
              [392.6082, 1400 - 784.6692], [392.6082, 1400 - 882.7066]]],
            np.int32)
        cv2.fillPoly(self.blank_image, shelf5_d, (255, 255, 255))
        cv2.circle(self.blank_image, (393, 1400 - 835), 70 + int(distance),
                   (255, 255, 255), -1)
        cv2.fillPoly(self.blank_image, shelf5, (0, 0, 0))
        cv2.circle(self.blank_image, (393, 1400 - 835), 70, (0, 0, 0), -1)

        shelf6_d = np.array(
            [[[1316.0530 - distance, 1400 - 616.5968 - distance],
              [1316.0530 - distance, 1400 - 468.7012 + distance],
              [1393.9310 + distance, 1400 - 468.7012 + distance],
              [1393.9310 + distance, 1400 - 616.5968 - distance]]], np.int32)
        shelf6 = np.array(
            [[[1316.0530, 1400 - 616.5968], [1316.0530, 1400 - 468.7012],
              [1393.9310, 1400 - 468.7012], [1393.9310, 1400 - 616.5968]]],
            np.int32)
        cv2.fillPoly(self.blank_image, shelf6_d, (255, 255, 255))
        cv2.fillPoly(self.blank_image, shelf6, (0, 0, 0))

        shelf6_d = np.array(
            [[[1097.8244 - distance, 1400 - 968.7450 - distance],
              [1097.8244 - distance, 1400 - 632 + distance],
              [1197.4152 + distance, 1400 - 632 + distance],
              [1197.4152 + distance, 1400 - 968.7450 - distance]]], np.int32)
        shelf6 = np.array(
            [[[1097.8244, 1400 - 968.7450], [1097.8244, 1400 - 632],
              [1197.4152, 1400 - 632], [1197.4152, 1400 - 968.7450]]],
            np.int32)
        cv2.fillPoly(self.blank_image, shelf6_d, (255, 255, 255))
        cv2.fillPoly(self.blank_image, shelf6, (0, 0, 0))
Exemplo n.º 25
0
class Content:

  pagination = None

  def __init__(self):
    self.products = Products()
    self.pagination = Pagination()
    self.item = Item()

  def handle(self,cat,link):

    self.pagination.reset()

    while True:

      logging.info( 'Scraping [%s] page, checking products.' % str(self.pagination.actual))

      req = self.req(link)

      if req is False:
        self.pagination.next()
        time.sleep(1)
        continue

      soup_page = BeautifulSoup(req,'html.parser')
      if self.check_has_products(soup_page) is False:
        logging.info( 'No more products found in this category, going to next.')
        break

      elements = self.select_products(soup_page)

      logging.info( 'More products founded on page [%s], scraping them.' % str(self.pagination.actual))
      logging.info( 'Total products [%s].' % str(len(elements)))

      self.handle_elements(elements, cat)

      self.pagination.next()
      time.sleep(1)

  def check_has_products(self,page):

    elements = self.select_products(page)

    if len(elements) > 0:
      return True
    else:
      return False

  def req(self,link):

    url = "%s%s" % (link,str(self.pagination))

    try:
      req = requests.get(url,timeout=10)
      req.raise_for_status()
      return req.text
    except requests.exceptions.Timeout as Timeout:
      logging.info('Timeout exception, sleeping and repeat...')
      time.sleep(30)
      return self.req(link)
    except requests.exceptions.RequestException as RequestException:
      logging.info('A Request exception ocurred, ending scraping. [status_code=%s]' % req.status_code)
      return False

  def select_products(self,page):
    return page.findAll("section", {"class": "listagem-box"})

  def handle_elements(self,elements,cat):

    while len(elements) > 0:
      el = elements.pop(0)
      scraped_item = self.item.scrap(el,cat)

      if self.products.check_in('code',scraped_item['code']) is not True:
        self.products.append(scraped_item)

    self.products.save()
Exemplo n.º 26
0
from flask import Flask, render_template, request
from products import Products

app = Flask(__name__)
db = Products()

@app.route("/")
def products():
    return render_template("products.html", products=db.products)

@app.route("/search", methods=["GET", "POST"])
def search():
    
    if request.method == "GET":
        return render_template("form.html")
    
    elif request.method == "POST":

        hasresults = False
        output = []

        if request.form["name"] != "":
            output = db.findbyName(request.form["name"])
        elif request.form["price"] != "":
            output = db.findbyPrice(request.form["price"])
        elif request.form["qty"] != "":
            output = db.findbyQty(request.form["qty"])

        if len(output) > 0:
            hasresults = True
        else:
Exemplo n.º 27
0
import sys, os
from products import Products
from orders import Orders
from product import Product
from order import Order
from datetime import datetime
import pickle

products = Products()
orders = Orders()
menu_actions  = {}  
memoryP = []
memoryO = []
index = 0

def main_menu():
    os.system('clear')
    print ("Please choose the menu you want to start:")
    print ("1. Show products")
    print ("2. Enter products ")
    print ("3. Edit product ")
    print("4. Delete product")
    print("====================")
    print ("5. Show orders")
    print ("6. Make an order")
    print ("7. Edit order")
    print("8. Delete order")
    print("00. Search")
    print("11. pickle dump")
    print("22. pickle load")
    print ("\n0. Quit")
Exemplo n.º 28
0
def new_product():
    resp = helpers.get_response(request)
    loginmanager.verify_token(resp)
    product = Products().new(resp)
    product.save()
    return jsonify({"product": product._to_json()})
Exemplo n.º 29
0
import numpy as np
from map import Map
from products import Products

map = Map(radius=0.177)

collision = map.check_collision(15, 15)

prod = Products()
prod.seed(100)

new_list = prod.get_random_list()

print(new_list)
new_list1 = prod.get_random_list()
print(new_list1)
print(collision)

for product, coord in prod.product_list.items():

    collision = map.check_collision(coord[0], coord[1])
    if (collision == True):
        print(product, " collides")
Exemplo n.º 30
0
from flask import Flask, jsonify, request, abort, make_response
from products import Products
from sales import Sales

app = Flask(__name__)

product = Products()
sales = Sales()
# Error Handling

@app.errorhandler(400)
def bad_request(error):
    return make_response(jsonify({'error': 'Bad Request'}), 400)

@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Server Not Found'}), 404)

# Routes

@app.route('/store_manager/api/v1/user/products', methods=['GET'])
def get_products():
    return jsonify({'products': product.get_all_products()}), 200

@app.route('/store_manager/api/v1/admin/products', methods=['POST'])
def create_product():
    return jsonify({'product': product.create_pdt()}), 201

@app.route('/store_manager/api/v1/user/products/<int:pdt_id>', methods=['GET'])
def get_product(pdt_id):
    return jsonify({'product': product.get_pdt(pdt_id)}), 200
Exemplo n.º 31
0
 def __init__(self):
   self.products = Products()
   self.pagination = Pagination()
   self.item = Item()