コード例 #1
0
ファイル: Airgun.py プロジェクト: e-al/airgun_downloader
    def __init__(self):
        self.xml_str += '<warehouse>'

        for url in self.category_urls:
            category = Category(url)
            self.xml_str += category.get_xml_str()

        self.xml_str += '</warehouse>'
コード例 #2
0
 def deleteCategory(self):
     # here delete category from list,
     # also open up questiondb and delete every question with category
     currentSelection = self.listCategories.curselection()
     selectedCategory = self.listCategories.get(currentSelection)
     self.listCategories.selection_clear(currentSelection)
     Category.deleteCategory(selectedCategory)
     self.getAvailableCategories()
コード例 #3
0
    def test_that_for_file_returns_true_if_header_filename_matches_filename(
            self):
        headerFilename = "test"
        cat = Category("anything",
                       None,
                       None,
                       None,
                       None,
                       None,
                       headerFilename=headerFilename)

        assert_that(cat.for_file(headerFilename), is_(True))
コード例 #4
0
    def __init__(self):

        self.app = Flask(__name__)
        self.host = "0.0.0.0"
        self.port = 5001
        self.server = ''
        self.database = ''
        self.url = "http://" + self.host + ":" + str(
            self.port) + "/ol-ti-itcpfegem-beta/billService?wsdl"
        self.category = Category()
        self.client = Client()
        self.product = Product()
        self.sale = Sale()
        self.user = User()
コード例 #5
0
    def test_backend_type_list_yields_all_attributes_after_id(self):
        cat = Category(None, None, None, None, None, None)
        attrs = self._mock_attributes()
        cat.attrs = attrs  # This is a bit abusive, could add each attr via the public interface

        results = cat.backend_type_list()

        results.next()  # Discard id
        for attr in attrs.values():
            try:
                name, type_name = results.next()
            except StopIteration:
                self.fail('Not enough results returned from backend_type_list')
            assert_that(name, is_(attr.name))
            assert_that(type_name, is_(attr.type_name))
コード例 #6
0
def getAndCreatedCategory():
	status = 200
	data = None
	print("Request parameters passed : "+ str(request.args))
	if request.method == 'GET':
		print("get triggered")
	elif request.method == 'POST':
		category_name = request.args.get('categoryName')
		category = Category(category_name, datetime.now())
		category.save()
		print('Yay')

	json_data = json.dumps(data)
	
	return Response(json_data, status = 200, mimetype='application/json')
コード例 #7
0
 def test_backend_type_list_yields_all_attributes_after_id(self):
     cat = Category(None, None, None, None, None, None)        
     attrs = self._mock_attributes()        
     cat.attrs = attrs   # This is a bit abusive, could add each attr via the public interface
      
     results = cat.backend_type_list()
     
     results.next() # Discard id         
     for attr in attrs.values():
         try:
             name, type_name = results.next()
         except StopIteration:
             self.fail('Not enough results returned from backend_type_list')            
         assert_that(name, is_(attr.name))
         assert_that(type_name, is_(attr.type_name))
コード例 #8
0
 def getcategory(self):
     file = "categories.json"
     if os.stat(file).st_size == 0:
         c.createSuggestedCategory()
     with open(file, "r", encoding='utf-8') as f:
         categories = json.load(f)
     cat = input('Category : ')
     if cat in categories:
         return cat
     else:
         print('choose correct category or create new one : ')
         if input('new one') == 'y':
             c.createOwnCategory(anotherCategory=cat, categories=categories)
         else:
             print('nothing')
コード例 #9
0
def availabe_netStock():
    print('Preparing to calculate net stock:')
    print('Catergories.........')
    displayAllCategories()
    print('Stocks..............')
    displayStocks()
    category_id = input('Please select the category:')
    cid = Category.find(category_id)
    # cate = getCategoriesId(category_id)

    user_choice = input(
        f'Are you sure want to calculatae net amount of stock  net ammount: y/n:'
    )
    if (user_choice == 'y'):
        # increaseAmount = int(input('How do you want to increse :'))

        # cid = int(category_id)
        stock_id = int(
            input('Enter the stock_id for the category that you input above:'))
        sid = Stock.find(stock_id)
        # cursor.execute('SELECT * FROM assignweek3.stocks where categories_id = %s and id = %s;',[cid,s])
        # for sii in cursor.fetchall():
        # sin = sid.stockin
        # sout = sid.stockout
        cid.stock = (int(sid.stockin) + int(cid.stock)) - int(sid.stockout)
        print('This is your update')
        cid.update()
        # mydb.commit()
        print('Categories.....')
        displayAllCategories()
コード例 #10
0
 def add_ctg(cls, category: Category = None) -> None:
     """Add a Category to the NFO."""
     if category is None:
         cls.categories.append(
             Category(input('Enter the new category\'s name\n> ')))
     else:
         cls.categories.append(category)
コード例 #11
0
    def test_should_add_a_product_into_already_existing_category(self):
        existingCategory = Category('existingCategory')
        firstProduct = Product('firstProduct', 100.0, existingCategory)
        secondProduct = Product('secondProduct', 200.0, existingCategory)
        self.cart.addItem(firstProduct, 1)
        self.cart.addItem(secondProduct, 1)

        expectedCategoryProductCount = 2
        expectedCategoryCurrentPrice = 300.0
        expectedSecondProductCount = 1
        expectedSecondProductCurrentPrice = 200.0

        self.assertEqual(
            self.cart.categories['existingCategory']['productCount'],
            expectedCategoryProductCount)
        self.assertEqual(
            self.cart.categories['existingCategory']['currentPrice'],
            expectedCategoryCurrentPrice)
        self.assertEqual(
            self.cart.categories['existingCategory']['products']
            ['secondProduct']['count'], expectedSecondProductCount)
        self.assertEqual(
            self.cart.categories['existingCategory']['products']
            ['secondProduct']['currentPrice'],
            expectedSecondProductCurrentPrice)
コード例 #12
0
    def test_should_apply_a_campaign_to_child_categories(self):
        vegetable = Category('vegetable', self.food)
        tomato = Product('tomato', 100.0, vegetable)
        self.cart.addItem(tomato, 1)

        curCategoryCurrentPrice = self.cart.categories['vegetable'][
            'currentPrice']
        curTomatoProductCurrentPrice = self.cart.categories['vegetable'][
            'products']['tomato']['currentPrice']

        expectedCategoryDiscount = curCategoryCurrentPrice * (
            self.campaign1.discount / 100.0)
        expectedCategoryCurrentPrice = curCategoryCurrentPrice - expectedCategoryDiscount

        expectedTomatoProductDiscount = curTomatoProductCurrentPrice * (
            self.campaign1.discount / 100.0)
        expectedTomatoProductCurrentPrice = curTomatoProductCurrentPrice - expectedTomatoProductDiscount

        self.cart.applyDiscounts(self.campaign1)

        self.assertEqual(self.cart.categories['vegetable']['currentPrice'],
                         expectedCategoryCurrentPrice)
        self.assertEqual(
            self.cart.categories['vegetable']['products']['tomato']
            ['currentPrice'], expectedTomatoProductCurrentPrice)
コード例 #13
0
 def __init__(self):
     self.transactionFactory = TransactionFactory()
     self.categoryFactory = CategoryFactory()
     self.transactions = dict()
     self.completedTransactions = dict()
     self.categories = dict()
     self.categories["Unhandled"] = Category("Unhandled")
コード例 #14
0
    def get_categories(self):
        total_clues = 0
        for round_counter in range(self.rounds):
            self.Clues.append([])
            self.Categories.append([])
            for category_counter in range(self.amt_of_categories):
                curr_URL = URL + 'categories'
                offset = randint(1, MAX_CATEGORIES)
                total_clues = 0
                while total_clues < self.amt_of_clues:
                    # Resets/Sets Params
                    offset = randint(1, MAX_CATEGORIES)
                    PARAMS = {'offset': offset}

                    # Gets current category
                    r = requests.get(curr_URL, params=PARAMS)
                    data = r.json()
                    if str(data) != "[]":
                        total_clues = (data[0]['clues_count'])
                        id = (data[0]['id'])
                        title = title_cleaner(str(data[0]['title']))
                        clues_count = data[0]['clues_count']
                        if clues_count >= self.amt_of_clues:
                            total_clues = self.get_clues(id, round_counter)
                            curr_category = Category(id, title, clues_count)

                self.Categories[round_counter].append(curr_category)
コード例 #15
0
def addNewCategories():

    category = Category()
    category.category = input(
        "Please enter the type of category item(laptop,phone,accessories etc..) :"
    )
    category.brand = input(
        'Please enter the type of brand(Apple,Samsung,Xiaomi etc..)')
    category.itemDescription = input(
        'Enter item description for your item (eg. macbook 13inches,Mi9T,Remaxspeaker)'
    )
    category.serial_number = input(
        'Enter serial number for your item(eg,ZT79LV1379M)')
    category.price = input('Enter the price of your item:')
    category.stock = input('Enter the available stock.')

    category.save()
コード例 #16
0
    def setUp(self):
        self.food = Category('food')
        self.home = Category('home')
        self.apple = Product('apple', 100.0, self.food)
        self.almond = Product('almond', 50.0, self.food)
        self.chair = Product('chair', 100.0, self.home)

        self.cart = ShoppingCart()
        self.cart.addItem(self.apple, 3)
        self.cart.addItem(self.almond, 1)
        self.cart.addItem(self.chair, 2)

        self.costPerDelivery = 10.0
        self.costPerProduct = 10.0
        self.fixedPrice = 80.0
        self.deliveryCostCalculator = DeliveryCostCalculator(
            self.costPerDelivery, self.costPerProduct, self.fixedPrice)
コード例 #17
0
def add_to_categories(line):
    category_name = line[0]
    category_sentence = line[1]
    category_sentence = START + category_sentence
    if category_name not in categories:
        categories.append(Category(category_name))

    categories[categories.index(category_name)].add_sentence(category_sentence)
コード例 #18
0
 def __init__(self, tuple_data=None):
     if (tuple_data):
         self.id = tuple_data[0]
         self.categories_id = tuple_data[1]
         self.category = Category.find(self.categories_id)
         self.stockin = tuple_data[2]
         self.stockout = tuple_data[3]
         self.stock_date = tuple_data[4]
コード例 #19
0
 def save(self):
     Database._cursor.execute(
         'insert into stocks(categories_id,stockin,stockout,stock_date) values (%s,%s,%s,%s)',
         [self.categories_id, self.stockin, self.stockout, self.stock_date])
     Database._db.commit()
     self.id = Database._cursor.lastrowid
     self.category = Category.find(self.categories_id)
     self.display()
コード例 #20
0
    def get_categories_list():
        categories_list = []
        for filename in os.listdir("D:/projekty/FoodCheck/databases"):
            name = (filename.split("."))[0]
            new_category = Category(name)
            """
            if name == "Favorites":
                categories_list.insert(0, new_category)
            elif name == "Expired":
                categories_list.insert(0, new_category)
            else:
                categories_list.append(new_category)
            """
            categories_list.append(new_category)
            new_category.set_foods_list(DatabaseHandler.get_foods_list(name))

        return categories_list
コード例 #21
0
 def parse(cls, path: Path) -> None:
     """Parse the file located at path to load its structure in NFO Maker.
     The operation can fail if the file hasn't been generated with NFO Maker.
     If a line is only made of the same character, then it does not give any information, so it is ignored,
     except if it's made of '=', then it is considered as a new unnamed Category.
     """
     file = open(str(path.absolute()), 'r', encoding='utf8')
     nfo = None
     tmp_ctg = None
     for line in file:
         if not (len(line.strip()) > 0
                 and line.strip() == len(line.strip()) * line.strip()[0]):
             if nfo is None:
                 nfo = NFO(line[:-1].strip())
                 NFO.set_path(path)
             elif re.match(r".*=+ .* =+.*", line):
                 if tmp_ctg is not None:
                     NFO.add_ctg(tmp_ctg)
                 tmp_ctg = Category(re.findall(r".*=+ (.*) =+.*", line)[0])
             elif re.match(r".* : .*", line):
                 name, value = re.findall(r"(.*) : (.*)", line)[0]
                 name = name.rstrip()
                 value = value.lstrip()
                 tmp_ctg.add_line(Line(tmp_ctg, name, value))
             elif line.strip(
             ) != '' and tmp_ctg is not None and tmp_ctg.contains_line():
                 tmp_ctg[-1].value += ' ' + line[:-1]
         elif len(line.strip()) > 0 and line.strip() == len(
                 line.strip()) * '=':
             if tmp_ctg is not None:
                 NFO.add_ctg(tmp_ctg)
             tmp_ctg = Category(None)
     if tmp_ctg is not None:
         NFO.add_ctg(tmp_ctg)
コード例 #22
0
 def fromJson(experiment):
     categories = Categories(experiment, None, [], None)
     with open(categories.output_directory + 'categories.json', 'r') as f:
         obj = json.load(f)
         categories.num_categories = len(obj)
         categories.categories = []
         for c in range(categories.num_categories):
             categories.categories.append(Category.fromJson(obj[str(c)]))
     return categories
コード例 #23
0
ファイル: User.py プロジェクト: DrBee-thollv/SaveMuney
    def AddCategory(self, info):
        """Appends a new instance of category to the users account

        Parameters
        ------------------------------------
        info : 
            a list containing the parameters to set the new category being added
        """
        self.categories.append(Category(info))
コード例 #24
0
ファイル: UI.py プロジェクト: snelson3/py-ranker
 def __init__(self):
     self.path = DATA_PATH
     self.availableCategories = self._findCategories()
     while 1:
         self.category = Category(os.path.join(DATA_PATH, self.select_category()))
         while self.category:
             action = self.category_menu()
             while action == 'rate':
                 r = self._rank2()
                 if r < 0:
                     action = None
             if action == 'config':
                 self._setConfig()
             elif action == 'view':
                 self.view_items()
             elif action == 'rank':
                 self.rank_items_menu()
             elif action == 'back':
                 self.category = None
コード例 #25
0
 def add_child(self, name, desc, extremum, amount):
     cat_id = CategoryBuilder.cat_count
     CategoryBuilder.cat_count += 1
     cat = Category(self.root, cat_id, name, desc, extremum, amount)
     if (self.root is None):
         self.root = cat
         CategoryBuilder.cat_select = cat
     else:
         self.root.children.append(cat)
     CategoryBuilder.id_cat_map[cat_id] = cat
コード例 #26
0
ファイル: MySql.py プロジェクト: spec45as/EDropScrap
    def getAllCategories(self):
        allCategories = {}
        try:
            sql = "SELECT `categoryIndex`, `jsonContent` FROM `categories_light`"
            cursor = self.connection.cursor()
            cursor.execute(sql)
            for result in cursor:
                jsonData = json.loads(result['jsonContent'])
                category = Category()
                category.load(jsonData)
                allCategories[result['categoryIndex']] = category

            cursor.close()

            return allCategories

        except Exception as error:
            print(error)
            return None
コード例 #27
0
ファイル: MySql.py プロジェクト: spec45as/EDropScrap
    def getCategory(self, categoryIndex):
        try:
            with self.connection.cursor() as cursor:
                sql = "SELECT `categoryIndex`, `jsonContent` FROM `categories_light` WHERE `categoryIndex`=%s"
                cursor.execute(sql, (categoryIndex,))
                result = cursor.fetchone()

                if result is None:
                    return None

                jsonData = json.loads(result['jsonContent'])
                category = Category()
                category.load(jsonData)

                return category

        except Exception as error:
            print(error)
            return None
コード例 #28
0
 def __init__(self, tuple_data=None):
     if (tuple_data):
         self.id = tuple_data[0]
         self.name = tuple_data[1]
         self.sale_price = tuple_data[2]
         self.purchase_price = tuple_data[3]
         self.stock_in_qty = tuple_data[4]
         self.stock_out_qty = tuple_data[5]
         self.category_id = tuple_data[6]
         self.category = Category.find(self.category_id)
コード例 #29
0
def remove_category():
    '''Function used to remove a category from the txt database'''

    # read the input and create a new python object
    categoryToRemove = Category(input('What category you want to remove?\n'))

    # remove the category
    Categories.remove_category(categoryToRemove)

    print("The category was removed.")
    input(READ_ENTER_KEY)
コード例 #30
0
def add_category():
    '''Function used to display the jewlery menu in the console'''

    # read the input and create a new python object
    newCategory = Category(input('What category you want to add?\n'))

    # load the new category in the txt database
    Categories.add_category(newCategory)

    print( str(newCategory) + ' added successfully')
    input("\nPress enter key in order to continue\n")
コード例 #31
0
 def save(self):
     Database._cursor.execute(
         "insert into stocks(name, sale_price, purchase_price,stock_in_qty,stock_out_qty,category_id)values( %s, %s, %s, 0, 0, %s)",
         [
             self.name, self.sale_price, self.purchase_price,
             self.category_id
         ])
     Database._db.commit()
     self.id = Database._cursor.lastrowid
     self.category = Category.find(self.category_id)
     self.display()
コード例 #32
0
    def test_backend_type_list_yields_all_collections_after_attributes(self):
        cat = Category(None, None, None, None, None, None)
        attrs = self._mock_attributes()
        colls = self._mock_collections()
        cat.attrs = attrs  # This is a bit abusive, could add each attr via the public interface
        cat.colls = colls  # This is a bit abusive, could add each coll via the public interface

        results = cat.backend_type_list()

        # Discard id and attributes
        results.next()
        for _ in attrs.values():
            results.next()
        for coll in colls.keys():
            try:
                name, type_name = results.next()
            except StopIteration:
                self.fail('Not enough results returned from backend_type_list')
            assert_that(name, is_(coll))
            assert_that(type_name, is_('string'))
コード例 #33
0
 def test_backend_type_list_yields_all_collections_after_attributes(self):
     cat = Category(None, None, None, None, None, None)                
     attrs = self._mock_attributes()                
     colls = self._mock_collections()
     cat.attrs = attrs   # This is a bit abusive, could add each attr via the public interface
     cat.colls = colls   # This is a bit abusive, could add each coll via the public interface
              
     results = cat.backend_type_list()
     
     # Discard id and attributes
     results.next() 
     for _ in attrs.values():
         results.next() 
     for coll in colls.keys():
         try:
             name, type_name = results.next()
         except StopIteration:
             self.fail('Not enough results returned from backend_type_list')            
         assert_that(name, is_(coll))
         assert_that(type_name, is_('string'))
         
コード例 #34
0
    def add_category(self, name, description, image, parent, childs):
        """

        @rtype : Category
        """
        try:
            self.get_category_by_name(name)
        except ValueError:
            if len(name) < 2 or len(description) < 2:
                raise AssertionError('Name or description are too short')
            if parent < -1 or parent > Category.id:
                raise AssertionError('Parent id given is wrong')
            try:
                self.get_category_by_name(name)
                raise AssertionError('Category already exists')
            except ValueError:
                pass
            if parent >= 0:
                try:
                    self.get_category_by_id(parent)
                except ValueError:
                    raise AssertionError('Parent id doesn\'t exists')
            for child_id in childs:
                try:
                    child = self.get_category_by_id(child_id)
                    if child.get_parent() >= 0:
                        raise AssertionError('Child has already a parent')
                except ValueError:
                    raise AssertionError('Child category with id [' + child_id + '] does not exists.')
            category = Category(name, description, image, parent, childs)
            self.categories.append(category)
            for child_id in category.get_childs():
                child = self.get_category_by_id(child_id)
                child.parent = category.get_id()
            return category
        raise ValueError("Category [" + name + "] already exists.")
コード例 #35
0
ファイル: EasyDrop.py プロジェクト: spec45as/EDropScrap
    def getAllCategories(self, updateCategories=False):
        if updateCategories:
            print('Составление новых категорий дропов...')
        else:
            print('Загрузка категорий дропов...')

        if not updateCategories:
            self.allCategories = self.mysqlManager.getAllCategories()
            if (self.allCategories is None) or (self.allCategories == {}):
                raise Exception('Couldn\'t load item categories')
            else:
                print('Загрузка категорий дропов завершена')
                return True
        allSiteCategories = {}
        try:
            webPage = self.seleniumLoader.loadCategories()
            if webPage is None:
                raise PageCouldntBeLoadedException()
            webPage.make_links_absolute(self.baseURL)
            allSiteCategories = webPage.find_class('item')
            if allSiteCategories is None:
                raise PageCouldntBeLoadedException()
        except PageCouldntBeLoadedException as error:
            print('Can\'t load main Page with categories')
            return False

        for currentCategory in allSiteCategories:
            try:
                indexName = currentCategory.get('href').split('/')
                indexName = createIndexStringFromHashName(indexName[len(indexName) - 1])
                price = int(currentCategory.findtext('span'))
                categoryObject = self.mysqlManager.getCategory(indexName)

                if categoryObject is None:
                    try:
                        newCategory = Category(currentCategory.findtext('strong'))
                        newCategory.marketIconURL = currentCategory.find_class('picture')[0].getchildren()[0].get('src')
                        newCategory.marketURL = currentCategory.get('href')
                        newCategory.price = price
                        newCategory.indexName = indexName
                        self.mysqlManager.addCategory(newCategory.indexName, newCategory.getJsonData())
                    except:
                        print('Error during creating of new Category')

            except:
                print('Error during category register')
                continue

        return self.getAllCategories(False)
コード例 #36
0
ファイル: ToDosDocument.py プロジェクト: Joey-Lee/pyobjc
 def categories(self):
     return Category.allCategories()
コード例 #37
0
 def test_that_backend_type_list_yields_id_first(self):
     cat = Category(None, None, None, None, None, None)
     
     name, type_name = cat.backend_type_list().next()
     assert_that(name, is_('id'))
     assert_that(type_name, is_('string'))
コード例 #38
0
 def test_that_for_file_returns_true_if_file_is_term_plus_dot_h(self):
     term = "something"
     cat = Category(term, None, None, None, None, None)
     
     assert_that(cat.for_file(term + ".h"), is_(True))
コード例 #39
0
 def test_that_for_file_returns_true_if_header_filename_matches_filename(self):
     headerFilename = "test"
     cat = Category("anything", None, None, None, None, None, headerFilename = headerFilename)
     
     assert_that(cat.for_file(headerFilename), is_(True))
コード例 #40
0
 def test_that_for_file_returns_false_if_file_is_none(self):
     cat = Category("anything", None, None, None, None, None)
     
     assert_that(cat.for_file(None), is_(False))
コード例 #41
0
#-*-coding:utf-8-*-
from Category import Category 
from Cookbook import Cookbook 
from Category import Category 

import sys

cookbooks = Cookbook.objects()
cats = Category.objects()
total = 0
for c in cats:
    print c.name, c.count,c.url
    total += c.count
#print total
sys.exit()

for c in cats:
    c.count = 0
    c.save()

for cb in cookbooks :
    #去重
    if len(cb.category) != len(set(cb.category)):
        cb.category = list(set(cb.category))
        cb.save()
        print 'save'

    #计算各分类cookbook数
    for c in cb.category:
        if c.count is None:
            c.count = 0