Ejemplo n.º 1
0
def checkProducts(new_product_list, old_product_list):

    #For each element in the first list, the loop goes through the second list, finds the respective "old product" (from previous csv file)
    #The index of the product in the old list is stored in the index variable

    for element in range(len(new_product_list) - 1):
        if (Product.FindProduct(new_product_list[element], old_product_list) !=
                -1):
            index = Product.FindProduct(new_product_list[element],
                                        old_product_list)

            #Creating the new and old product objects for each iteration of the loop
            updated_product = new_product_list[element]
            #print("The new product", updated_product.quantity)
            old_product = old_product_list[index]

            price_change = changeInPrice(updated_product, old_product)

            #Checking how the price has changed within
            if (price_change < 0):
                print(new_product_list[element].title,
                      "has dropped in price by", price_change)
            elif (price_change > 0):
                print(new_product_list[element].title,
                      "has increased in price by", price_change)
            else:
                print(new_product_list[element].title,
                      "has not changed its price")
            new_product_list[element].title = price_change
            #Checking how many more units have been sold
            #print("SENDING", updated_product.title, "AND", old_product.title)
            quantity_change = changeInQuantity(updated_product, old_product)
            #print(updated_product.title, "has sold", quantity_change, "additional units")
            new_product_list[element].quantity_change = quantity_change
Ejemplo n.º 2
0
def test_applied_attributes():
    product = get_default_product()
    for spec in ATTR_SPECS:  # This loop sets each attribute twice. That's okay.
        attr = Attribute.objects.get(identifier=spec["identifier"])
        pa, _ = ProductAttribute.objects.get_or_create(product=product, attribute=attr)
        _populate_applied_attribute(pa)
        pa.save()
        if not attr.is_translated:
            product.set_attribute_value(attr.identifier, pa.value)

    assert product.get_attribute_value("bogomips") == 320, "integer attribute loaded neatly"
    product.set_attribute_value("bogomips", 480)
    assert product.get_attribute_value("bogomips") == 480, "integer attribute updated neatly"
    Product.cache_attributes_for_targets(
        applied_attr_cls=ProductAttribute,
        targets=[product],
        attribute_identifiers=[a["identifier"] for a in ATTR_SPECS],
        language=get_language()
    )
    assert (get_language(), "bogomips",) in product._attr_cache, "integer attribute in cache"
    assert product.get_attribute_value("bogomips") == 480, "integer attribute value in cache"
    assert product.get_attribute_value("ba:gelmips", default="Britta") == "Britta", "non-existent attributes return default value"
    assert product._attr_cache[(get_language(), "ba:gelmips")] is NoSuchAttributeHere, "cache miss saved"
    attr_info = product.get_all_attribute_info(language=get_language(), visibility_mode=AttributeVisibility.SHOW_ON_PRODUCT_PAGE)
    assert set(attr_info.keys()) <= set(a["identifier"] for a in ATTR_SPECS), "get_all_attribute_info gets all attribute info"
Ejemplo n.º 3
0
def product_added(request):
    if (
        "name" in request.GET
        and request.GET["name"]
        and "manufacturer" in request.GET
        and request.GET["manufacturer"]
        and "cate" in request.GET
        and request.GET["cate"]
        and "minrestock" in request.GET
        and request.GET["minrestock"]
    ):
        name = request.GET["name"]
        manufacturer = request.GET["manufacturer"]
        cate = request.GET["cate"]
        minrestock = request.GET["minrestock"]
        if cate == "Other":
            category = request.GET["category"]
        else:
            category = cate
        products = Product.objects.all().order_by("-product_id")
        if not products:
            pid = 1
        else:
            pid = products[0].product_id + 1
        p = Product(product_id=pid, name=name, manufacturer=manufacturer, category=category, min_restock=minrestock)
        p.save()
        pr = p
        products = Product.objects.all()
        message = "The following product has been successfully added. "
        context = {"pr": pr, "message": message, "products": products}
        return render(request, "view_product.html", context)
Ejemplo n.º 4
0
def basic_test():
    state = State()

    prod1 = Product(5, 5)
    prod2 = Product(10, 10)
    state.products.append(prod1)
    state.products.append(prod2)

    robot1 = Robot(0, 0)

    robot2 = Robot(1, 1)
    robot2.state = "on_delivery"
    robot2.time = 12

    state.idle.append(robot1)
    state.delivery.append(robot2)

    pack = Pack(3, 3)
    state.packs.append(pack)

    order1 = Order(prod1, pack)
    order2 = Order(prod2, pack)

    state.orders.append(order1)
    state.orders.append(order2)

    return state
Ejemplo n.º 5
0
def product_added(request):
    if 'name' in request.GET and request.GET[
            'name'] and 'manufacturer' in request.GET and request.GET[
                'manufacturer'] and 'cate' in request.GET and request.GET[
                    'cate'] and 'minrestock' in request.GET and request.GET[
                        'minrestock']:
        name = request.GET['name']
        manufacturer = request.GET['manufacturer']
        cate = request.GET['cate']
        minrestock = request.GET['minrestock']
        if cate == 'Other':
            category = request.GET['category']
        else:
            category = cate
        products = Product.objects.all().order_by('-product_id')
        if not products:
            pid = 1
        else:
            pid = products[0].product_id + 1
        p = Product(product_id=pid,
                    name=name,
                    manufacturer=manufacturer,
                    category=category,
                    min_restock=minrestock)
        p.save()
        pr = p
        products = Product.objects.all()
        message = 'The following product has been successfully added. '
        context = {'pr': pr, 'message': message, 'products': products}
        return render(request, 'view_product.html', context)
Ejemplo n.º 6
0
def test_formatted_decimal_field():
    """
    Test that FormattedDecimalField doesn't return value in scientific
    notation.
    """

    class TestModelForm(ModelForm):
        class Meta:
            model = Product
            fields = ["width"]

    values = [
        "0E-9", "0E-30", "1E-9", "123E-10", "-123E-10", "1.12345666666666E20"
    ]

    for value in values:
        product = Product(width=Decimal(value))
        form = TestModelForm(instance=product)
        rendered_form = force_text(form)
        rendered_value = re.search('value="(.*?)"', rendered_form).group(1)
        rendered_step = re.search('step="(.*?)"', rendered_form).group(1)
        assert rendered_value and "E" not in rendered_value
        assert rendered_step and "E" not in rendered_step

    # Extremely large exponents should raise an exception so as not to
    # produce excessively large files
    large_value = "1.23E-10000"
    product = Product(width=Decimal(large_value))
    with pytest.raises(ValueError):
        form = TestModelForm(instance=product)
Ejemplo n.º 7
0
def test_modelform_persistence():
    with translation.override("en"):
        test_product = Product(barcode="666")
        test_product.set_current_language("en")
        test_product.name = "foo"
        frm = MultiProductForm(languages=["en"], instance=test_product, default_language="en")
        assert frm["barcode"].value() == test_product.barcode
        assert frm.initial["name"] == test_product.name
Ejemplo n.º 8
0
def run_stop(status):
    if status.active:
        status.active = False
    else:
        program.initialize_parameters(status)
        program.create_objects(status)
        #user_input('Enter number of particles')
        status.active = True
Ejemplo n.º 9
0
 def __init__(self):
     self.cost = 0
     self.payment = 0
     self.cart = []
     self.inventory = []
     self.inventory.append(Product(101, "pen", 2, 1))
     self.inventory.append(Product(102, "bag", 9, 2))
     self.inventory.append(Product(103, "bread", 4, 1))
Ejemplo n.º 10
0
def product_created(request, s_id):
    store = Store.objects.get(store_id=s_id)
    if 'name' in request.GET and request.GET['name']:
        name = request.GET['name']
    else:
        name = ' '
    if 'manufacturer' in request.GET and request.GET['manufacturer']:
        manufacturer = request.GET['manufacturer']
    else:
        manufacturer = ' '
    if 'category' in request.GET and request.GET['category']:
        category = request.GET['category']
    else:
        category = ' '
    if 'minqty' in request.GET and request.GET['minqty']:
        minqty = request.GET['minqty']
    else:
        minqty = ' '
    if 'sp' in request.GET and request.GET['sp']:
        sp = request.GET['sp']
    else:
        sp = ' '

    if 'stock' in request.GET and request.GET['stock']:
        qty = request.GET['stock']
    else:
        qty = ' '

    if 'ed' in request.GET and request.GET['ed']:
        ed = request.GET['ed']
    else:
        ed = ' '

    product = Product.objects.filter(name=name,
                                     manufacturer=manufacturer,
                                     category=category)
    if not product:
        pr = Product(name=name, manufacturer=manufacturer, category=category)
        pr.save()
        pid = pr.id
    else:
        pid = product[0].id
    e_d = ed.replace('-', '')
    p_id = str(pid)
    x = p_id + e_d
    b_id = Decimal(x)
    batch = Batch(store_id_id=s_id,
                  product_id_id=pid,
                  minimum_qty=minqty,
                  qty=qty,
                  selling_price=sp,
                  expiry_date=ed,
                  batch_id=b_id)
    batch.save()
    store = Store.objects.get(id=s_id)
    p = Product.objects.get(id=pr.id)
    context = {'store': store, 'p': p}
    return render(request, 'product_created.html', context)
Ejemplo n.º 11
0
def product_created(request, s_id):
    store = Store.objects.get(store_id=s_id)
    if "name" in request.GET and request.GET["name"]:
        name = request.GET["name"]
    else:
        name = " "
    if "manufacturer" in request.GET and request.GET["manufacturer"]:
        manufacturer = request.GET["manufacturer"]
    else:
        manufacturer = " "
    if "category" in request.GET and request.GET["category"]:
        category = request.GET["category"]
    else:
        category = " "
    if "minqty" in request.GET and request.GET["minqty"]:
        minqty = request.GET["minqty"]
    else:
        minqty = " "
    if "sp" in request.GET and request.GET["sp"]:
        sp = request.GET["sp"]
    else:
        sp = " "

    if "stock" in request.GET and request.GET["stock"]:
        qty = request.GET["stock"]
    else:
        qty = " "

    if "ed" in request.GET and request.GET["ed"]:
        ed = request.GET["ed"]
    else:
        ed = " "

    product = Product.objects.filter(name=name, manufacturer=manufacturer, category=category)
    if not product:
        pr = Product(name=name, manufacturer=manufacturer, category=category)
        pr.save()
        pid = pr.id
    else:
        pid = product[0].id
    e_d = ed.replace("-", "")
    p_id = str(pid)
    x = p_id + e_d
    b_id = Decimal(x)
    batch = Batch(
        store_id_id=s_id,
        product_id_id=pid,
        minimum_qty=minqty,
        qty=qty,
        selling_price=sp,
        expiry_date=ed,
        batch_id=b_id,
    )
    batch.save()
    store = Store.objects.get(id=s_id)
    p = Product.objects.get(id=pr.id)
    context = {"store": store, "p": p}
    return render(request, "product_created.html", context)
Ejemplo n.º 12
0
def cache_product_things(request, products, language=None, attribute_identifiers=("author",)):
    # Cache necessary things for products. WARNING: This will cause queryset iteration.
    language = language or get_language()
    # TODO: Should we cache prices here?
    if attribute_identifiers:
        Product.cache_attributes_for_targets(
            ProductAttribute, products,
            attribute_identifiers=attribute_identifiers,
            language=language)
    products = cache_translations(products, (language,))
    return products
Ejemplo n.º 13
0
    def add(self, name):
        product_info = Product()
        product_info.set_name(name)
        print("enter the type of " + str(name))
        product_info.set_type(self.utility.input_str_data())
        print("enter the price of " + str(name))
        product_info.set_price(self.utility.input_int_data())
        print("enter the weight of " + str(name))
        product_info.set_weight(self.utility.input_int_data())

        return product_info
Ejemplo n.º 14
0
def test2():
    state = State()
    r1 = Robot(20, 14)
    r2 = Robot(20, 20)
    r3 = Robot(20, 0)

    r1.time = 14
    r2.time = 8
    r3.time = 8

    r1.state = "on_delivery"
    r2.state = "on_delivery"
    r3.state = "on_delivery"

    insort(state.delivery, r1)
    insort(state.delivery, r2)
    insort(state.delivery, r3)

    pack1 = Pack(20, 0)
    pack2 = Pack(20, 10)
    pack3 = Pack(20, 20)

    state.packs.append(pack1)
    state.packs.append(pack2)
    state.packs.append(pack3)

    prod1 = Product(0, 0)
    prod2 = Product(0, 10)
    prod3 = Product(0, 20)

    state.products.append(prod1)
    state.products.append(prod2)
    state.products.append(prod3)

    ord1 = Order(prod1, pack1)
    ord2 = Order(prod1, pack2)
    ord3 = Order(prod1, pack3)
    ord4 = Order(prod2, pack1)
    ord5 = Order(prod2, pack2)
    ord6 = Order(prod2, pack3)
    ord7 = Order(prod3, pack1)
    ord8 = Order(prod3, pack2)
    ord9 = Order(prod3, pack3)

    state.orders.append(ord1)
    state.orders.append(ord2)
    state.orders.append(ord3)
    state.orders.append(ord4)
    state.orders.append(ord5)
    state.orders.append(ord6)
    state.orders.append(ord7)
    state.orders.append(ord8)
    state.orders.append(ord9)
    return state
Ejemplo n.º 15
0
    def test_product_different(self):
        """
		Verify that two products are different. 
		"""

        product_1 = Product('Jorgito', 10000, 100)
        product_2 = Product('Capitan del espacio', 10000, 100)
        product_3 = Product('Jorgito', 200, 10)

        self.assertNotEqual(product_1, product_2)
        self.assertNotEqual(product_2, product_3)
        self.assertEqual(product_1, product_3)
Ejemplo n.º 16
0
    def jsonToObject(self, prod):

        product = prod["product"]
        price = prod["price"]
        quantityAvailable = prod["quantityAvailable"]
        productObj = Product.ProductClass(product, price, quantityAvailable)
        self.prodList.append(productObj)
Ejemplo n.º 17
0
def test_roi_quicklook_partly():
    logger.info("test_roi_quicklook_partly")
    p_venus = Product.Product_zip_venus(
        TEST_DATA_PATH + "VENUS-XS_20200402-191352-000_L2A_GALLOP30_D.zip",
        logger)
    r_partly_cloudy = Roi.Roi([33, 678644, 4246106], 500, logger)
    b = p_venus.get_band_subset(p_venus.find_band("SRE_B3."),
                                roi=r_partly_cloudy,
                                scalef=p_venus.sre_scalef)
    g = p_venus.get_band_subset(p_venus.find_band("SRE_B4."),
                                roi=r_partly_cloudy,
                                scalef=p_venus.sre_scalef)
    r = p_venus.get_band_subset(p_venus.find_band("SRE_B7."),
                                roi=r_partly_cloudy,
                                scalef=p_venus.sre_scalef)
    assert type(b) is numpy.ndarray
    assert type(g) is numpy.ndarray
    assert type(r) is numpy.ndarray
    is_quicklook = utilities.make_quicklook_rgb(r,
                                                g,
                                                b,
                                                logger,
                                                outfile="partly.png",
                                                vmax=None)
    assert is_quicklook == 0

    is_quicklook = utilities.make_quicklook_rgb(r,
                                                g,
                                                b,
                                                logger,
                                                outfile="partly.jpg",
                                                vmax=None)
    assert is_quicklook == 0
Ejemplo n.º 18
0
    def parse_metadata_and_vocabulary(self, file, dir):

        words_list = list()
        words_indexes_list = list()

        with open(file, 'r', encoding='ISO-8859-1') as data:
            for line in data.readlines():
                if re.match('^product', line):
                    prod = line.split(': ')[1].strip('\n')
                elif re.match('^review/helpfulness', line):
                    helpfulness = line.split(': ')[1].strip('\n')
                elif re.match('^review/score', line):
                    score = line.split(': ')[1].strip('\n')
                elif re.match('^review/text', line):
                    text = line.split(': ')[1].strip('\n')

                elif re.match('^\s*$', line):
                    product = p.Product(prod)
                    review = r.Review(product.get_product_id(), helpfulness,
                                      score, text)

                    # write review to the metadata file
                    self.write_to_metadata(review, dir)

                    words_list.extend(review.get_text())

        print('Created Metadata file')
        words_list = self.remove_duplicates(words_list)
        # append words and indexes to the lists
        wordlist_asa_string = self.append_to_wordlonglist(
            words_list, words_indexes_list)
        # write data to vocabulary
        self.write_to_vocabulary(wordlist_asa_string, words_indexes_list, dir)
def main():
    c1 = Customer([
        "207633439", "Israel", "Hamsa", "Male", "Final Space", "055-555-1555"
    ])
    p1 = Product("Track", 1, 10000, "Ford")
    sale1 = Sale(c1.id, p1.id, p1.price, "31/03/2020")
    print(sale1)
    def __init__(self, file_name, phone_file, ref_file):
        self.Prod_list = []
        if file_name != "empty":
            with open(file_name, "r") as csv_file:
                csv_file.readline()
                for r in csv_file:
                    listing = r.rstrip().split(",")
                    self.Prod_list.append(
                        Product(listing[1], listing[2], listing[3], listing[4],
                                listing[0]))

        if ref_file != "empty":
            with open(ref_file, "r") as csv_file:
                csv_file.readline()
                for r in csv_file:
                    listing = r.rstrip().split(",")
                    self.Prod_list.append(
                        Refrigerator(listing[1], listing[2], listing[3],
                                     listing[4], listing[0], listing[5],
                                     listing[6]))

        if phone_file != "empty":
            with open(phone_file, "r") as csv_file:
                csv_file.readline()
                for r in csv_file:
                    listing = r.rstrip().split(",")
                    self.Prod_list.append(
                        Phone(listing[1], listing[2], listing[3], listing[4],
                              listing[0], listing[5], listing[6]))
Ejemplo n.º 21
0
    def test_product_del_invalid_quantity_stock(self):
        """
		Verify del invalid quantity stock to a product.
		"""

        product = Product('Jorgito', 100, 10)
        self.assertRaises(InvalidAmount, product.del_stock, -10)
Ejemplo n.º 22
0
def test_product_hdf_acix():
    p_hdf_acix = Product.Product_hdf_acix(TEST_DATA_PATH + "vermote_carpentras/refsrs2-L1C_T31TFJ_A012260_20171027T103128-Carpentras.hdf", logger)
    assert p_hdf_acix.sre_scalef == 10000
    b7 = p_hdf_acix.get_band(p_hdf_acix.find_band("band07"), scalef=p_hdf_acix.sre_scalef)
    assert type(b7) is numpy.ndarray
    assert b7[12,5] == 0.1829
    assert b7[899,899] == 0.2021
def addProduct():
    form = AddProductForm(request.form)
    if request.method == 'POST' and form.validate():
        db = shelve.open('GoFit.db', 'w')
        products_dict = {}

        try:
            products_dict = db['Products']
        except:
            print("Error in retrieving Users from storage.db")

        try:
            img_filename = image.save(request.files['product_img'])

            product = Product.add_product(img_filename, form.product_name.data,
                                          form.product_price.data)
            products_dict[product.get_product_name()] = product

            db['Products'] = products_dict

            db.close()
        except UploadNotAllowed:
            flash(f'File Type Unsupported, Please try again!',
                  category='danger')
            return redirect(url_for('addProduct'))
        except RequestEntityTooLarge:
            flash(f'File Size Exceeded, Please Try again!', category='danger')
            return redirect(url_for('addProduct'))

        flash(f'Product Successfully added!', category='success')

        return redirect(url_for('to_newshop'))

    return render_template('addProduct.html', form=form)
Ejemplo n.º 24
0
    def read_file(self, file_input):

        #  Разделяем данные с файла по ,
        data_file = [
            string.replace(' ', '').split(',') for string in file_input
        ]

        product = None
        customers = list()
        sellers = list()
        auctions = list()
        """
             Проверем какого типа данные, создаем нужные и заполняем списки, тк у одного аукциона
             может быть неограниченное число продавцов и товаров
        """
        for data in data_file:
            for value in data:
                if value == 'product':
                    product = Product(data[1], data[2], data[3], data[4],
                                      data[5])
                elif value == 'customer':
                    customers.append(Customer(data[1], data[2], product))
                elif value == 'seller':
                    sellers.append(Seller(data[1], data[2], product))
                elif value == 'auction':
                    auctions.append(
                        Auction(data[1], data[2], data[3], data[4], customers,
                                sellers))
                    sellers = list()
                    customers = list()
                else:
                    continue

        return auctions
Ejemplo n.º 25
0
def generate_case():
    state = State()

    #Generating ROBOTS
    for i in range(0, randint(2, 4)):
        robot = Robot(randint(0, 10), randint(0, 10))
        if (randint(0, 10) < 4):
            robot.state = "on_delivery"
            robot.time = randint(3, 22)
            insort(state.delivery, robot)
        else:
            state.idle.append(robot)

    total_prods = randint(1, 4)

    #GENERATING PRODUCTS
    for i in range(0, total_prods):
        prod = Product(randint(0, 10), randint(0, 10))
        state.products.append(prod)

    total_packs = randint(1, 4)

    #GENERATING PACKING STATIONS
    for i in range(0, total_packs):
        pack = Pack(randint(0, 10), randint(0, 10))
        state.packs.append(pack)

    #GENERATING ORDERS
    for i in range(1, 5):
        product = state.products[randint(0, total_prods - 1)]
        packing = state.packs[randint(0, total_packs - 1)]
        order = Order(product, packing)
        state.orders.append(order)
    return state
Ejemplo n.º 26
0
    def test_product_del_more_stock(self):
        """
		Verify del more quantity stock to a stock product.
		"""

        product = Product('Jorgito', 100, 10)
        self.assertRaises(MenorStock, product.del_stock, 101)
Ejemplo n.º 27
0
    def loadinventory(self):
        results = []
        invinput = self.c.execute('select * from items')

        for i in invinput:
            results.append(Product.Product(i[0], i[1], i[2]))

        return results
Ejemplo n.º 28
0
    def test_product_add_invalid_stock(self):
        """
		Verify add invalid stock to a product.
		"""

        product = Product('Jorgito', 100, 10)

        self.assertRaises(InvalidAmount, product.add_stock, -30)
Ejemplo n.º 29
0
def add_product(connection, product: Product):
    product_type = product.getType()
    if product_type == 'Tshirt':
        add_tshirt(connection, product)
    if product_type == 'Sneakers':
        add_sneakers(connection, product)
    if product_type == 'Customizable_Sneakers':
        add_customizable_sneakers(connection, product)
Ejemplo n.º 30
0
def test_formatted_decimal_field_default():
    class TestModelForm(ModelForm):
        class Meta:
            model = Product
            fields = ["width"]

    rendered_form = force_text(TestModelForm(instance=Product()))
    rendered_value = re.search('value="(.*?)"', rendered_form).group(1)
    assert rendered_value == "0"
Ejemplo n.º 31
0
    def parseData(self, productData):
        product = Product.Product()

        self.parseCategory(product, productData)
        self.parseProductExtension(product, productData)
        self.parseSupplier(product, productData)
        self.parseGeneral(product, productData)
        self.parseproductUnitExchangeList(product, productData)

        return product
Ejemplo n.º 32
0
def productCreateNewEntry(productCategory,productInfo):
    newProduct = Product(
        productId = productInfo[0],
        name = productInfo[1],
        currentPrice = productInfo[2],
        savePrice = productInfo[3],
        imagePath = productInfo[4],
        updateDate = datetime.today(),
        category = productCategory
    )
Ejemplo n.º 33
0
def main():
	x = 0
	with open('products.csv') as f:
	    while True:
	        line1 = f.readline()
	        if not line1:
	            break
	        line2 = f.readline()
	        line3 = f.readline()
	        line4 = f.readline()
	        urls = [line1, line2, line3, line4]
	        thread1 = Product.myThread(x, "Thread-" + str(x), urls, lines)
	        thread1.start()
	        x+=1
	f.close()
Ejemplo n.º 34
0
from flask import Flask, url_for
import Buyer, Dealer, Brand, Product
app = Flask(__name__)
app.config['SECRET_KEY'] = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

@app.route("/")
def home():
  try:
    return app.send_static_file("index.html")
  except Exception as e:
    return str(e)

Buyer.add_routes(app)
Dealer.add_routes(app)
Brand.add_routes(app)
Product.add_routes(app)

if __name__ == "__main__":
  app.run()