def get_store_metrics(numRegisters, itemPerMinE, itemPerMinS, chanceSelfCheckout, customerSpawnRate): """ get_store_metrics takes in 5 parameters and returns metrics on how the business has done given the parameters. :param: numRegisters: The number of registers in the store. :param: itemPerMinE: The average number of items processed by employees. :param: itemPerMinS: The average number of items processed by customers in self-checkout. :param: checkSelfCheckout: The chance that given a new CheckOut location, the CheckOut location is a self-checkout kiosk. :param: customerSpawnRate: The chance on a customer-spawn-tick that the customer actually spawns, alternatively no customer will be generated on that tick. :return: Average Wait, Total Customers, Total Customers Processed, Num of Employee Registers, Num of Self-Checkout Kiosks. """ # Get all store store = Store(numRegisters, itemPerMinE, itemPerMinS, chanceSelfCheckout, customerSpawnRate) simTime = 86400 start = time.process_time() print("Starting simulation suite") for t in range(simTime): store.run_step() totalProcessed = 0 # tracks the number actually processed by each register to compare with total analytical number for register in store.store: totalProcessed += register.customersProcessed totalCustomers = store.totalCustomers totalWaitTime = 0 self_kiosks = 0 emp_regs = 0 self_type = type(SelfCheckOutAgent(0, 0, 15)) emp_type = type(EmployeeCheckOutAgent(0, 0, 25)) for each in store.store: totalWaitTime += each.totalWaitingTime val = 1 if type(each) == self_type else 0 self_kiosks += val val = 1 if type(each) == emp_type else 0 emp_regs += val # print(f"Avg Waiting Time: {totalWaitTime / (60 * store.temp_total)}") # print(f"Total waiting time: {totalWaitTime / 60} minutes.") # print("Time to run simulation:", time.process_time() - start, "seconds") # print("Total customers:", totalCustomers) # print(f"Actual Total Customers: {store.temp_total}") # print("Customers Processed: ", totalProcessed) # print("Time per person: ", round(simTime / (totalProcessed / numRegisters), 2), "seconds per customer") return totalWaitTime / ( 60 * store.temp_total ), store.temp_total, totalProcessed, emp_regs, self_kiosks
def test_sell_product(self): new_store = Store("Laptop.bg") new_product = Smartphone('Hack Phone', 500, 820, 7, 10) new_store.load_new_products(new_product,2) self.assertTrue(new_store.sell_product(new_product)) self.assertTrue(new_store.sell_product(new_product)) self.assertFalse(new_store.sell_product(new_product))
def test_4(self): """"tests to see if product is added to store""" p1 = Product("889", "Rodent of unusual size", "when a rodent of the usual size just won't do", 33.45, 8) myStore = Store() myStore.add_product(p1) self.assertIn(p1, myStore._inventory)
def __init__(self): print "entered the class Storage, and initializing the values" print "[Storage.__init__()] initializing self.storage dictionary to blank dictionary" self.storage = {} self.currentBucket = "" print "[Storage.__init__()] printing blank dictionary to check if it has been initialized" self.storeObj = Store() print self.storage
def main(): """ Drives the Store program. """ print("Welcome to our Holiday Store!") store = Store() while store.display_menu(): pass
def setUp(self): self.s1 = Store() self.p1 = Product("1", "Apple", "ea", 5.00, "SA", 14) self.p1.addBatch(10) self.p1.addBatch(5) self.p1.batches.append( Batch("3", 5.00, 10, datetime.date.today() - datetime.timedelta(days=12), 14)) self.p1.updateDiscount()
def test_4(self): with self.assertRaises(InvalidCheckoutError): p1 = Product("111", "Orange Juice", "Off Brand OJ with pulp", 3.99, 3) c1 = Customer("Jun", "ABC", True) myStore = Store() myStore.add_product(p1) myStore.add_member(c1) myStore.add_product_to_member_cart("111", "ABC") result = myStore.check_out_member("ABD")
def test_5(self): p1 = Product("111", "Orange Juice", "Off Brand OJ with pulp", 3.99, 3) c1 = Customer("Jun", "ABC", False) myStore = Store() myStore.add_product(p1) myStore.add_member(c1) myStore.add_product_to_member_cart("111", "ABC") result = myStore.check_out_member("ABC") self.assertFalse(c1.is_premium_member())
def test_assert_raises_InvalidCheckoutError(self): """ tests the basic functionality of the InvalidCheckoutError class and its appropriate use in the checkout_member() method """ with self.assertRaises(InvalidCheckoutError): c1 = Customer("Yinsheng", "QWF", False) myStore = Store() myStore.add_member(c1) myStore.check_out_member("NOTAVALIDCUSTID") with self.assertRaises(InvalidCheckoutError): myStore = Store() myStore.check_out_member("NOTAVALIDCUSTID")
def test_2(self): p1 = Product("111", "Orange Juice", "Off Brand OJ with pulp", 3.99, 3) c1 = Customer("Jun", "ABC", True) myStore = Store() myStore.add_product(p1) myStore.add_member(c1) myStore.add_product_to_member_cart("111", "ABC") result = myStore.check_out_member("ABC") self.assertAlmostEqual(result,3.99)
def test_3(self): p1 = Product("112", "Milk", "2% Milk fat", 2.00, 7) p2 = Product("113", "Toilet Paper", "To wipe away the coronavirus", 100.00, 7) c1 = Customer("Jun", "ABC", True) myStore = Store() myStore.add_product(p1) myStore.add_product(p2) myStore.add_member(c1) myStore.add_product_to_member_cart("112", "ABC") myStore.add_product_to_member_cart("113", "ABC") result = myStore.check_out_member("ABC") self.assertAlmostEqual(result,102.00)
def test_1(self): first_product = Product(1, "Lemon", "Fresh lemons", 3, 10) first_customer = Customer("Mohammad", 31343, True) first_store = Store() test_bool = first_customer.is_premium_member() self.assertTrue(test_bool)
def test_populateInventory(): store=Store() c=Product("CH1", "Chai", float(3.11)) a=Product("AP1", "Apples", float(6.00)) cf=Product("CF1", "Coffee", float(11.23)) m=Product("MK1", "Milk", float(4.75)) o=Product("OM1", "Oatmeal", float(3.69)) inventory={ "CH1": c, "AP1": a, "CF1": cf, "MK1": m, "OM1": o } store.populateInventory() assert store.inventory == inventory
def ResetSettings(): """ Revert Settings to defaults. """ Settings = Store(defaultSettings) Settings.Save(CONF_FILE) try: with io.open(CONF_FILE.replace('json', 'js'), 'w+', encoding='utf-8') as fp: fp.write('var settings = {}'.format(str(Settings).encode('utf-8'))) Settings.save(CONF_FILE) Log('Settings Reset') except Exception as error: Log(error, 'ResetSettings') return
class Main(object): def __init__(self): self.line = "__________________________\n" self.store = Store() def start(self): option = input( "What would you like to do? \n1. Add to cart\n2. Check current cart\n3. Checkout\nEnter 1,2,3\nOption: " ) print(self.line) while option != "1" and option != "2" and option != "3": option = input("Not a valid option. Please enter 1,2,3\nOption: ") while option == "1" or option == "2": if option == "1": self.option1() elif option == "2": self.option2() option = input( "What would you like to do? \n1. Add to cart\n2. Check current cart\n3. Checkout\nEnter 1,2,3\nOption: " ) print(self.line) while option != "1" and option != "2" and option != "3": option = input( "Not a valid option. Please enter 1,2,3\nOption: ") if option == "3": self.option3() #User wants to add to cart def option1(self): item = input("What item would you like to add? \nItem: ").upper() print(self.line) while item not in self.store.inventory: item = input( "That item does not exist! Please enter a valid item.\nItem: " ).upper() print(self.line) self.store.addtoCart(item) print("{} added to cart!".format(self.store.getName(item))) print(self.line) #User wants to check current cart status def option2(self): print("Here is your current cart:\n") self.store.printReceipt() print(self.line) #User wants to check out cart def option3(self): print("Checkout: \n") self.store.printReceipt() print("\nHave a nice day!")
def __init__(self): """ Initialize an UserMenu """ self.store = Store() self.user_menu_map = { "1": self.store.menu_order_processing, "2": self.store.check_inventory, "3": self.store.daily_transaction_report }
def load(self, data, store_name): with open(data, "r") as f: for k, v in json.load(f).items(): store = Store(id=k, name=store_name, branch=v['name'] if 'name' in v else '-', businessHour=v['business_hour'] if 'business_hour' in v else '-', phone=v['phone'] if 'phone' in v else '-', address=v['address'] if 'address' in v else '-') self.stores[store.id] = store
def test_2(self): second_test_product_1 = Product(121, "Banana", "Yellow Banana", 2.50, 10) second_test_product_2 = Product(220, "Mango", "Tropical Mango", 4, 5) second_test_product_3 = Product(5778, "Doritos", "Cool Ranch Doritos", 3.99, 3) second_test_customer = Customer("Rondo", 778304, False) second_store = Store() # Add Customer to store second_store.add_member(second_test_customer) # Add products to cart second_store.add_product(second_test_product_1) second_store.add_product(second_test_product_2) second_store.add_product(second_test_product_3) total_price = second_store.check_out_member(778304) self.assertAlmostEqual(total_price, 11.2243)
def init_data(): customers = [Customer("01223", "Peter Parker", "Qo'yliq", 2.2, "90-932-75-98", ["Silver", 'Gold']), Customer("75884", "Sherlock Holmes", "Backer street", 31415, "90-987-65-43", ["Regular", 'VIP']), Customer("70070", "James Bond", "NY City", 450, "90-900-90-90", ["Silver", 'Gold'])] store = Store('U1510375', "John's Mall", "Ziyolar-9", "90-123-45-67") staff_members = [Staff("0", "02213", "Uncle Ben", "Manager"), Staff("1", "45646", "Aunt May", "Cashier"), Staff('2', "12345", "John Doe", "Owner")] products = [Product(69, "Cucumber", "Fresh and long cucumber", 69.69, 666), Product(666, "Tomatoes", "Red and plump", 12.14, 314), Product(123, "_Candies_", "Sweet sweet candies", 50, 100), Product(314, "_Bananas_", "My favorite", 42, 450)] return products, customers, staff_members, store
def test_store_get_product_from_id(self): """ tests the basic functionality of the Store method get_product_from_id() """ p1 = Product("889", "Rodent of unusual size", "when a rodent of the usual size just won't do", 33.45, 8) p2 = Product("755", "Plunger", "dislodge clogs", 15.00, 3) p3 = Product("1000", "key-chain", "hold your keys", 0.99, 35) myStore = Store() myStore.add_product(p1) myStore.add_product(p2) myStore.add_product(p3) self.assertEqual(myStore.get_product_from_id("889"), p1) self.assertEqual(myStore.get_product_from_id("755"), p2) self.assertEqual(myStore.get_product_from_id("1000"), p3) self.assertEqual(myStore.get_product_from_id("10"), None)
def __init__(self, parent=None): super().__init__() # bool to check if it is available self.available = False # set store gui self.gui = Store() # set graphics self.setPixmap(QPixmap('./res/imgs/blue_chest.png').scaled(80, 80, Qt.KeepAspectRatio)) # create points vector points = [QPointF(1, 0), QPointF(2, 0), QPointF(3, 1), QPointF(3, 2), QPointF(2, 3), QPointF(1, 3), QPointF(0, 2), QPointF(0, 1)] # scale points SCALE_FACTOR = 100 points = [p * SCALE_FACTOR for p in points] # create polygon self.polygon = QPolygonF(points) # create QGraphicsPolygonItem self.available_area = QGraphicsPolygonItem(self.polygon, self) self.available_area.setPen(QPen(Qt.DotLine)) # move the polygon poly_center = QPointF(1.5 * SCALE_FACTOR, 1.5 * SCALE_FACTOR) poly_center = self.mapToScene(poly_center) store_center = QPointF(self.x() + 40, self.y() + 40) ln = QLineF(poly_center, store_center) self.available_area.setPos(self.x() + ln.dx(), self.y() + ln.dy()) # connect the timer to acquire_champion self.timer = QTimer() self.timer.timeout.connect(self.acquire_champion) self.timer.start(1000)
def main(): crawler = Crawler() for user in config['users']: user = User(user) OutputService.prettyJSON('User:'******'Store:', store.__dict__) blocks = crawler.extractProducts(store_data) OutputService.prettyJSON('Blocks:', blocks)
def __init__(self, *args, **kwargs): super(LogOutputTest, self).__init__(*args, **kwargs) self.log = LogOutput() self.store = Store() self.store.createStore() self.store.addWorker("Werknemer", "Nummer 1", 5) self.store.addWorker("Werknemer", "Nummer 2", 10) self.store.addUser("Christoph", "Ronken", "*****@*****.**") self.store.addUser("Cedric", "Hollanders", "*****@*****.**") self.store.getUser("*****@*****.**").createOrder(1) self.store.getUser("*****@*****.**").addWhiteChocolateShot() for i in range(0, 10): self.store.restockBrownChocolateShot(2000) self.store.restockWhiteChocolateShot(2000) self.store.restockDarkChocolateShot(2000) self.store.restockMilkChocolateShot(2000) self.store.restockChilipepper(2000) self.store.restockHoney(2000) self.store.restockMarshmallow(2000)
def test_5(self): fifth_test_customer = Customer("Robot", 3000, True) fifth_test_product_1 = Product(2345, "Box of Apples", "Box of six green apples", 1, 1) fifth_store = Store() fifth_store.add_member(fifth_test_customer) fifth_store.add_product(fifth_test_product_1) result = fifth_store.add_product_to_member_cart(2345, 3000) self.assertEqual(result, "Product added to cart")
def test_3(self): third_test_customer_1 = Customer("FIRST CUSTOMER", 12345, True) third_test_customer_2 = Customer("SECOND CUSTOMER", 23456, False) third_test_customer_3 = Customer("THIRD CUSTOMER", 34567, False) third_store = Store() third_store.add_member(third_test_customer_1) third_store.add_member(third_test_customer_2) third_store.add_member(third_test_customer_3) test_3 = third_store.lookup_member_from_id(23456) self.assertIs(test_3, "SECOND CUSTOMER")
def __init__( self, config=None ) : """ Create a new 'hood' for people to hang out in. The 'config' argument can optionally point to a python file that defines config. """ self.config = Config( config ) store = self.config.getKey( "global/store" ) if isinstance( store, str ) : store = eval( "import %s as store; return store" % store ) self.__store = Store( store ) self.__store.validate()
def test_store_product_search(self): """ tests the basic functionality of the Store method product_search() """ p1 = Product("889", "Rodent of unusual size", "when a rodent of the usual size just won't do", 33.45, 8) p2 = Product("755", "Plunger", "dislodge clogs", 15.00, 3) p3 = Product("1000", "key-chain", "hold your keys", 0.99, 35) p4 = Product("88", "rat trap", "traps rodents", 3.99, 50) p5 = Product("001", "mouse pad", "not a RODENT's house", 9.95, 20) myStore = Store() myStore.add_product(p1) myStore.add_product(p3) myStore.add_product(p4) myStore.add_product(p2) myStore.add_product(p5) self.assertEqual(myStore.product_search("RoDeNt"), ["001", "88", "889"])
def test_store_get_member_from_id(self): """ tests the basic functionality of the Store method get_member_from_id() """ c1 = Customer("Yinsheng", "QWF", False) c2 = Customer("Alan", "ABC", True) c3 = Customer("Kirk", "EEF", True) myStore = Store() myStore.add_member(c1) myStore.add_member(c2) myStore.add_member(c3) self.assertEqual(myStore.get_member_from_id("QWF"), c1) self.assertEqual(myStore.get_member_from_id("ABC"), c2) self.assertEqual(myStore.get_member_from_id("EEF"), c3) self.assertEqual(myStore.get_member_from_id("DLL"), None)
def printing_receipt(): # Dummy Data store = Store(1111, "Nozima's & Darhon's Store", "Ziyollilar,9", 998908889900) staff = Staff(1234, 2222, entry_Name.get(), "Ziyollilar,9", "Manager", 1234) customer = Customer(entry_CustomerID.get(), "ban", "ddd", 122, 23232323, ["VIP"]) order = Order(store, customer, staff) if not are_product_cells_empty(): if are_product_cells_valid(): for entries in products: product = get_product(entries) quantity = int(entries[quantity_index].get()) order.add_product(product, quantity) # RECEIPT WINDOW t = Toplevel() t.wm_title("Receipt") labeltest = Label(t, text=str(order.generate_receipt()), font=("Courier", 12)) labeltest.pack() def array_clear(): del products[:] t.destroy() close_receipt_Button = Button(t, text="Close", bg="#386fe5", width=8, font=("Courier", 12, "bold"), command=array_clear) close_receipt_Button.pack(pady=10) t.protocol("WM_DELETE_WINDOW", array_clear) else: tkinter.messagebox.showinfo( "Warning!", "Price must be FLOAT or INTEGER\nPoints, Quantity - MUST be INTEGER" ) else: tkinter.messagebox.showinfo( "Warning!", "Firstly fill all the gaps, then you can Print!")
def test_1(self): """"tests to see if product not added to store remains not in store""" p1 = Product("889", "Rodent of unusual size", "when a rodent of the usual size just won't do", 33.45, 8) p2 = Product("48", "Balding Spray", "when a bald spot of the usual size just won't do", 330.45, 2) c1 = Customer("Yinsheng", "QWF", False) myStore = Store() myStore.add_product(p1) myStore.add_member(c1) self.assertNotIn(p2, myStore._members)
def Init(): ''' [REQUIRED] - ChatBot Constructor function ''' # check if the settings directory exists and create it if it doesn't if not os.path.exists(CONF_DIR): os.makedirs(CONF_DIR) # check if the settings file already exists and save default configuration if it doesn't if not os.path.exists(CONF_FILE): Settings.save(CONF_FILE) else: # load settings if the file exists Settings.load(CONF_FILE) if os.path.exists(STAT_FILE): # load stats file if it exists Game.load(STAT_FILE) for uid in Game.keys(): Game.update({uid: Store(Game[uid])}) if Settings.update: UpdateCheck() return
def __init__(self, parent): """Constructor --""" gtk.TreeView.__init__(self) self.par = parent self.stateFilter = False self.store = Store( gtk.gdk.Pixbuf, str, int, parent=self.par, objectStore=self.getApplication().getObjectStore() ) # Icon, Name, ID, type self.filterstore = FilterStore( gtk.gdk.Pixbuf, str, int, parent=self.par, objectStore=self.getApplication().getObjectStore() ) self.context = TreeContextMenu(self) self.set_model(self.store) self.col_id = gtk.TreeViewColumn(_("Environment")) # self.col_name = gtk.TreeViewColumn("ObjectId") self.append_column(self.col_id) # self.append_column(self.col_name) self.renderer_name = gtk.CellRendererText() self.renderer_icon = gtk.CellRendererPixbuf() # self.renderer_id = gtk.CellRendererText() self.col_id.pack_start(self.renderer_icon, False) self.col_id.pack_start(self.renderer_name, True) # self.col_name.pack_start(self.renderer_id,True) self.col_id.add_attribute(self.renderer_icon, "pixbuf", 0) self.col_id.add_attribute(self.renderer_name, "text", 1) # self.col_name.add_attribute(self.renderer_id,'text',2) # self.col_name.set_cell_data_func(self.renderer_id,self.renderId) # self.col_name.set_sort_column_id(1) self.col_id.set_resizable(True) # self.col_name.set_resizable(True) self.set_search_column(1) self.set_rules_hint(True) self.connect("row-activated", self.cb_RowActivated) # self.connect("row-expanded",self.cb_RowExpanded) self.connect("button_press_event", self.cb_ButtonPressed) self.changeHandler = self.connect("cursor-changed", self.cb_CursorChanged)
def ReloadSettings(data): """ [OPTIONAL] Chatbot callback for when the user save the settings in the Application. Saves *.json and *.js Settings file. Parameters ---------- data : str JSON String """ try: d = Store(json.loads(data, encoding='utf-8')) Settings.update(d) with io.open(CONF_FILE.replace('json', 'js'), 'w+', encoding='utf-8') as fp: fp.write('var settings = {}'.format(str(Settings).encode('utf-8'))) Settings.save(CONF_FILE) Log('Settings Reloaded') except Exception as error: Log(error, 'ReloadSettings') return
class Tree(gtk.TreeView): def __init__(self, parent): """Constructor --""" gtk.TreeView.__init__(self) self.par = parent self.stateFilter = False self.store = Store( gtk.gdk.Pixbuf, str, int, parent=self.par, objectStore=self.getApplication().getObjectStore() ) # Icon, Name, ID, type self.filterstore = FilterStore( gtk.gdk.Pixbuf, str, int, parent=self.par, objectStore=self.getApplication().getObjectStore() ) self.context = TreeContextMenu(self) self.set_model(self.store) self.col_id = gtk.TreeViewColumn(_("Environment")) # self.col_name = gtk.TreeViewColumn("ObjectId") self.append_column(self.col_id) # self.append_column(self.col_name) self.renderer_name = gtk.CellRendererText() self.renderer_icon = gtk.CellRendererPixbuf() # self.renderer_id = gtk.CellRendererText() self.col_id.pack_start(self.renderer_icon, False) self.col_id.pack_start(self.renderer_name, True) # self.col_name.pack_start(self.renderer_id,True) self.col_id.add_attribute(self.renderer_icon, "pixbuf", 0) self.col_id.add_attribute(self.renderer_name, "text", 1) # self.col_name.add_attribute(self.renderer_id,'text',2) # self.col_name.set_cell_data_func(self.renderer_id,self.renderId) # self.col_name.set_sort_column_id(1) self.col_id.set_resizable(True) # self.col_name.set_resizable(True) self.set_search_column(1) self.set_rules_hint(True) self.connect("row-activated", self.cb_RowActivated) # self.connect("row-expanded",self.cb_RowExpanded) self.connect("button_press_event", self.cb_ButtonPressed) self.changeHandler = self.connect("cursor-changed", self.cb_CursorChanged) def render(self): filterString = self.getApplication().mainwin.getFilterText() if filterString != "": self.filterstore.render(filterString) self.disconnect(self.changeHandler) self.set_model(self.filterstore) self.set_cursor((0,)) self.stateFilter = True else: self.set_model(self.store) self.changeHandler = self.connect("cursor-changed", self.cb_CursorChanged) self.stateFilter = False def cb_CursorChanged(self, data): selection = self.get_selection() rowiter = selection.get_selected()[1] if rowiter is None or not self.store.iter_is_valid(rowiter): return nr = self.store.get_value(rowiter, 2) if nr is not None and not nr >= 0: self.getPar().getToolbar().clearButtons() return obj = self.store.objectStore.getLocalObjectById(nr) self.getPar().getToolbar().renderContextButtons(obj) self.getPar().getTabs().openPage(obj, False) def cb_ButtonPressed(self, widget=None, event=None, data=None): if event.button == 3: x = int(event.x) y = int(event.y) pathinfo = self.get_path_at_pos(x, y) if pathinfo is not None: self.grab_focus() self.set_cursor(pathinfo[0], pathinfo[1], 0) selection = self.get_selection() rowiter = selection.get_selected()[1] nr = self.store.get_value(rowiter, 2) if nr == -2: # is Root-object: self.getPar().getToolbar().clearButtons() return obj = self.store.objectStore.getLocalObjectById(nr) self.context.popup(obj, event.button, event.get_time()) self.getPar().getToolbar().renderContextButtons(obj) def cb_RowActivated(self, treeview, rowiter, path, wdata=None): """This callbackmethod defines behaviour after doubleclicking a row. It is calling open match if the currently selected treeelement is representing a match""" selection = self.get_selection() rowiter = selection.get_selected()[1] if self.stateFilter: nr = self.filterstore.get_value(rowiter, 2) else: nr = self.store.get_value(rowiter, 2) if nr >= 0: object = self.getApplication().getLocalObjectById(nr) self.getPar().getTabs().openPage(object) def setActiveObject(self, obj): rowiter = self.store.getIterById(obj.getLocalId()) path = self.store.get_path(rowiter) self.set_cursor(path) def getPar(self): return self.par def getApplication(self): return self.par.getApplication()
class Hood( object ) : def __init__( self, config=None ) : """ Create a new 'hood' for people to hang out in. The 'config' argument can optionally point to a python file that defines config. """ self.config = Config( config ) store = self.config.getKey( "global/store" ) if isinstance( store, str ) : store = eval( "import %s as store; return store" % store ) self.__store = Store( store ) self.__store.validate() def defaultContext( self ) : keys = self.config.getKeys( "hood/defaultContext" ) c = {} for k in keys : v = eval( str(self.config.getKey(k)) ) if v : c[ k.split("/")[-1] ] = v return Context( c ) def checkin( self, user, context, timeout=None ) : """ Check a user into a context, the optional 'timeout' parameter should be an object that supports + with a datetime object. Contexts are simply { "str" : value, ... } dicts. Checking in starts a 'sting' in the context. """ if timeout is None : timeout = self.config.getKey( "checkin/defaultTimeout" ) now = datetime.now() expiry = now + timeout if timeout else None if not isinstance( context, Context ) : context = Context( context ) stint = Stint() stint.user = user stint.context = context stint.timestamp = now stint.expires = expiry self.__store.transactionBegin() self.__store.registerStint( stint ) self.__store.transactionEnd() def checkout( self, user, context=None ) : """ Checks a user out of the specified context, or all contexts if context is None. """ if context and not isinstance( context, Context ) : context = Context( context ) self.__store.transactionBegin() self.__store.removeStint( user = user, context = context ) self.__store.transactionEnd() def contexts( self, user=None, readable=False ) : """ Returns a list of Contexts the 'hood' is aware of. """ self.__store.transactionBegin() if readable : return [ str(c) for c in self.__store.contexts( user ) ] else : return self.__store.contexts( user ) self.__store.transactionEnd() def stints( self, user=None, context=None, expired=False, readable=False ) : """ Returns a list of all the stints currently in the 'hood'. """ self.__store.transactionBegin() stints = self.__store.stints() if user : stints = [ s for s in stints if s.user ==user ] self.__store.transactionEnd() if not expired : stints = [ s for s in stints if not s.expired() ] if context : if not isinstance( context, Context ) : context = Context( context ) validStints = [] for s in stints: stintRelevant = False for k in context.attribtues : if k in s.context.attribtues : stintRelevant = True if s.context.attribtues[k] != context.attribtues[k] : stintRelevant = False break if stintRelevant : validStints.append( s ) stints = validStints if readable : return [ str(s) for s in stints ] else : return stints def janitor( self ) : """Cleans out any expired stints, and empty contexts.""" self.__store.transactionBegin( lock=True ) now = datetime.now() activeContexts = set() for s in self.__store.stints() : if s.expired( now ) : self.__store.removeStint( user = s.user, context = s.context ) else : activeContexts.add( s.context.hash() ) for c in self.__store.contexts() : if c.hash() not in activeContexts : self.__store.removeContext( c ) self.__store.transactionEnd()
def __init__(self, project): # super(Store, self).__init__(project) Store.__init__(self, project)
def test_total_income(self): new_store = Store("Laptop.bg") new_product = Product('Mock',50,100) new_store.load_new_products(new_product,2) self.assertEqual(100,new_store.total_income())
def __init__(self): Store.__init__(self) self.database = {}
class Storage(): storage = {} bucketList = [] def __init__(self): print "entered the class Storage, and initializing the values" print "[Storage.__init__()] initializing self.storage dictionary to blank dictionary" self.storage = {} self.currentBucket = "" print "[Storage.__init__()] printing blank dictionary to check if it has been initialized" self.storeObj = Store() print self.storage def createBucket(self, bucketName): print "[Storage.createBucket()] received bucket name and file name" createAttempt = self.createBucketHelper(bucketName) if createAttempt is "success": print "the bucket was created!" self.currentBucket = bucketName else: print "there was a problem in creating the bucket" def creator(self, afile, filePath): print "[Storage.creator()] calling the createObject() and createFileObject()" self.createObject(afile) self.createFileObject(afile, filePath) def setCurrentBucket(self, bname): self.currentBucket = bname def createObject(self, afile): print "[Storage.CreateObject()] populating the storage dictionary with the file that has been sent" ''' the dictionary will contain the file as the value pointed to it by the timestamp that it came at this will help us to know if the file is the latest copy when retrieving The object for file will then be created into our own object for file, where we will enter the metadata This will be retrieved with the entry for the file in the storage array ''' dt = time.strftime("%Y-%m-%d %H:%M") # adding into the list so that the access can search this. This will later be put into a database self.storage[dt] = afile def createFileObject(self, afile, filePath): print "[Storage.createFileObject()] serializing the file object before it can be stored" ''' The serialized object will then get stored in the backend The backend for now is a block storage based directory We will give the parameters required by the constructor of the fileobject class and create an object this will help the constructor of the fileobject class to enter the metadata ''' # using a placeholder file till figuring out how to pass the file path and the file to this function fullname = os.path.basename(filePath) firstname = os.path.splitext(fullname)[0] dtToSend = time.strftime("%Y-%m-%d %H:%M") tempFile = FileObject(afile, firstname, dtToSend) print "[Storage.createFileObject()] printing a class variable from returned file object :: " + tempFile.filename print "[Storage.createFileObject()] trying to serialize and store the object into bucket: " + self.currentBucket insertionattempt = self.storeObj.insertIntoStoreList(self.currentBucket, tempFile) if insertionattempt is "success": print "[!Storage.createFileObject.insertionattempt!] the object has been stored!" else: print "[!Storage.createFileObject.insertionattempt!] there was an error, please check logs!" print "[!Storage.createFileObject.insertionattempt!] printing return message:: " + insertionattempt print "[Storage.createFileObject()] the object has been initialized. Please check debug comments starting with FileObject" # TODO: awful name, change! def createBucketHelper(self, bucketName): print self.bucketList print "[Storage.createBucketHelper()] received request for bucket with bucket name " + bucketName ''' create a bucket with the bucket name that was passed as a parameter The bucket name needs to be unique, and hence we have to check if the bucket already exists. This is checked in the bucketList and if the name already exists, we will return an error If the name does not exist, then the bucket will be created with the name as specified, at the path as specified ''' ''' for i in self.bucketList: if bucketName is i: print "[Storage.createBucketHelper()] ERROR: The bucket with the specified name already exists\n" print "The bucket names have to be unique." return "duplicate" ''' bucketCreatorForStore = self.storeObj.createEmptyBucket(bucketName) if bucketCreatorForStore is "error": print "there was a problem in creating the bucket, please check the logs for Store" else: print "[Storage.createBucketHelper()] the name is not duplicate, inseriting name into bucketList[]" self.bucketList.append(bucketName) return "success" def listBuckets(self): """ only lists the buckets in the current bucket list. This is just for the reference please query the backend list for the list of buckets that are actually created in the backend """ print "[Storage.listBuckets()] listing the buckets" return self.bucketList def getMainContentsDirFromStore(self): mainContentsDir = self.storeObj.getMainContentsDirectory() return mainContentsDir def printOnlyBuckets(self): print "----------------------list of buckets-------------------" for i in self.bucketList: print "bucket name | " + i print "--------------------------------------------------------" def printMainContentsDirFromStore(self): mainContentsDir = self.storeObj.getMainContentsDirectory() for j in mainContentsDir.keys(): print "bucket name:: " + j print "contents:: " tempArrayOfContents = mainContentsDir[j] for k in tempArrayOfContents: print k.filename def checkIfBucketExists(self, bname): print self.bucketList for i in self.bucketList: print "if " + bname + " is " + i if bname == i: print "returning true!" return True return False def startBackup(self): print "backup prior to cleaning" def cleanup(self): print "THIS IS THE CLEANUP FUNCTION!!! IT WILL DESTROY EVERYTHING AT THE BACKEND" userPass = raw_input("please enter the password for the server so that this function can proceed:: ") if userPass == "hastalavista": self.storeObj.destroyStore() else: print "wrong password, sober up and try again!"
def __init__(self, project): # super(Store, self).__init__(project) Store.__init__(self, project) self.start_time = datetime.datetime.now() self.counter = 0