Example #1
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        client = MongoClient()
        db = client.silverpos
        self.users = db.users
        self.products = db.stocks
        self.notify = Notify()

        product_code = []
        product_name = []
        spinvals = []
        for product in self.products.find():
            product_code.append(product["product_code"])
            name = product["product_name"]
            if len(name) > 30:
                name = name[:30] + "..."
            product_name.append(name)
        for x in range(len(product_code)):
            line = ' | '.join([product_code[x], product_name[x]])
            spinvals.append(line)
        self.ids.target_product.values = spinvals

        content = self.ids.scrn_contents
        users = self.get_users()
        userstable = DataTable(table=users)
        content.add_widget(userstable)

        # Display Products
        product_scrn = self.ids.scrn_product_contents
        products = self.get_products()
        prod_table = DataTable(table=products)
        product_scrn.add_widget(prod_table)
Example #2
0
def main():
    global backup_index
    try:
        check_backup_home()
        fetch_backup()
    except Exception as e:
        msg = '%s\nbackup auto restore error\n %s' % (hostname, str(e))
        logger.error(msg)
        Notify.notify_error(msg)
    finally:
        backup_index = None
Example #3
0
def get_bindname_info(bidname):
    bid_info = eos_api.get_bindname_info(bidname, url=api)
    if not bid_info:
        return
    name = 'name: %s' % bidname
    bidder = 'bidder: %s' % bid_info['high_bidder']
    amount = 'amount: %s' % (float(bid_info['high_bid']) / 10000)
    timestamp = int(bid_info['last_bid_time'])
    time_format_str = time.strftime("%F %T %Z",
                                    time.localtime(timestamp / 1000000))
    time_str = 'date: %s' % time_format_str
    timestamp = 'time: %s' % timestamp
    result = [name, bidder, amount, time_str, timestamp]
    logger.info(result)
    Notify.notify_status(name, bidder, amount, time_str, timestamp)
Example #4
0
def handle_reponse(bidname, json):
    bid_info = json['rows'][0]
    if bidname != bid_info['newname']:
        logger.info('%s finish or not start bid', bidname)
        return
    name = 'name: %s' % bidname
    bidder = 'bidder: %s' % bid_info['high_bidder']
    amount = 'amount: %s' % (float(bid_info['high_bid']) / 10000)
    timestamp = int(bid_info['last_bid_time'])
    time_format_str = time.strftime("%F %T %Z", time.localtime(timestamp / 1000000))
    time_str = 'date: %s' % time_format_str
    timestamp = 'time: %s' % timestamp
    result = [name, bidder, amount, time_str, timestamp]
    logger.info(result)
    Notify.notify_status(name, bidder, amount, time_str, timestamp)
 def __init__(self, app, hub, debug=False):
     BaseWebUI.__init__(self, "index.html", app, hub, debug)
     self.html = index.html
     
     self.agent = '%s v%s' % (USER_AGENT, '.'.join(str(v) for v in VERSION))
     log("Starting [%s]..." % self.agent, LEVEL_INFO)
     
     # Setup the system tray icon
     if sys.platform == 'darwin':
         tray_icon = 'evominer_16x16_mac.png'
     elif sys.platform == "win32":
         tray_icon = 'evominer_16x16.png'
     else:
         tray_icon = 'evominer_32x32_ubuntu.png'
     
     self.trayIcon = QSystemTrayIcon(self._getQIcon(tray_icon))
     self.trayIcon.setToolTip(tray_icon_tooltip)
     
     # Setup the tray icon context menu
     self.trayMenu = QMenu()
     
     self.showAppAction = QAction('&Show %s' % APP_NAME, self)
     f = self.showAppAction.font()
     f.setBold(True)
     self.showAppAction.setFont(f)
     self.trayMenu.addAction(self.showAppAction)
     
     
     self.aboutAction = QAction('&About...', self)
     self.trayMenu.addAction(self.aboutAction)
     
     self.trayMenu.addSeparator()
     self.exitAction = QAction('&Exit', self)
     self.trayMenu.addAction(self.exitAction)
     # Add menu to tray icon
     self.trayIcon.setContextMenu(self.trayMenu)
           
     # connect signals
     self.trayIcon.activated.connect(self._handleTrayIconActivate)
     self.exitAction.triggered.connect(self.handleExitAction)
     self.aboutAction.triggered.connect(self.handleAboutAction)
     self.showAppAction.triggered.connect(self._handleShowAppAction)
     self.app.aboutToQuit.connect(self._handleAboutToQuit)
     
     # Setup notification support
     self.system_tray_running_notified = False
     self.notifier = Notify(APP_NAME)
     self.trayIcon.show()
Example #6
0
class WebUI(BaseWebUI):
    def __init__(self, app, hub, debug=False):
        BaseWebUI.__init__(self, "index.html", app, hub, debug)
        self.html = index.html

        self.agent = '%s v%s' % (USER_AGENT, '.'.join(str(v) for v in VERSION))
        log("Starting [%s]..." % self.agent, LEVEL_INFO)

        # Setup the system tray icon
        if sys.platform == 'darwin':
            tray_icon = 'ombre_16x16.png'
        elif sys.platform == "win32":
            tray_icon = 'ombre_16x16.png'
        else:
            tray_icon = 'ombre_32x32.png'

        self.trayIcon = QSystemTrayIcon(self._getQIcon(tray_icon))
        self.trayIcon.setToolTip(tray_icon_tooltip)

        # Setup the tray icon context menu
        self.trayMenu = QMenu()

        self.showAppAction = QAction('&Show %s' % APP_NAME, self)
        f = self.showAppAction.font()
        f.setBold(True)
        self.showAppAction.setFont(f)
        self.trayMenu.addAction(self.showAppAction)

        self.aboutAction = QAction('&About...', self)
        self.trayMenu.addAction(self.aboutAction)

        self.trayMenu.addSeparator()
        self.exitAction = QAction('&Exit', self)
        self.trayMenu.addAction(self.exitAction)
        # Add menu to tray icon
        self.trayIcon.setContextMenu(self.trayMenu)

        # connect signals
        self.trayIcon.activated.connect(self._handleTrayIconActivate)
        self.exitAction.triggered.connect(self.handleExitAction)
        self.aboutAction.triggered.connect(self.handleAboutAction)
        self.showAppAction.triggered.connect(self._handleShowAppAction)
        self.app.aboutToQuit.connect(self._handleAboutToQuit)

        # Setup notification support
        self.system_tray_running_notified = False
        self.notifier = Notify(APP_NAME)
        self.trayIcon.show()

    def run(self):
        # load user's pool list
        # load_pools(self.app.property("AppPath"))

        self.view.loadFinished.connect(self._load_finished)
        #         self.view.load(qt_core.QUrl(self.url))
        self.view.setHtml(index.html, qt_core.QUrl(self.url))

        self.resetWindowSize()
        self.center()

        self.timer = QTimer(self)
        self.timer.timeout.connect(self._updateHashRate)
        self.timer.start(2000)

        self.wait(1)

        self.timer2 = QTimer(self)
        self.timer2.timeout.connect(self._reportError)
        self.timer2.start(2000)

        self.trayIcon.show()
        self.show()

    def closeEvent(self, event):
        """ Override QT close event
        """
        event.ignore()
        self.hide()
        if not self.system_tray_running_notified:
            self.notify("%s is still running at system tray." % APP_NAME,
                        "Running Status")
            self.system_tray_running_notified = True

    def resetWindowSize(self):
        ws = qt_core.QSize(
            WINDOW_WIDTH, HEAD_ROW_HEIGHT + POOL_ROW_HEIGHT *
            (len([p
                  for p in self.hub.pools.all_pools if not p['is_hidden']])) +
            BOTTOM_MARGIN)
        self.setFixedSize(ws)

    def _getQIcon(self, icon_file):
        _icon_path = os.path.join(self.app.property("ResPath"), 'icons',
                                  icon_file)
        return QIcon(_icon_path)

    def _handleTrayIconActivate(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.showNormal()
            self.activateWindow()

    def handleExitAction(self, show_confirmation=False):
        reply = QMessageBox.No
        if show_confirmation:
            reply = QMessageBox.question(self, 'Exit %s?' % APP_NAME,
                                         "Are you sure to exit %s?" % APP_NAME,
                                         QMessageBox.Yes, QMessageBox.No)
        if not show_confirmation or reply == QMessageBox.Yes:
            self.trayIcon.hide()
            QTimer.singleShot(250, self.app.quit)

    def _handleShowAppAction(self):
        self.showNormal()
        self.activateWindow()

    def handleAboutAction(self):
        self.showNormal()
        self.about()

    def _reportError(self):
        for pool_info in self.hub.pools.all_pools:
            if 'error' in pool_info:
                if pool_info['error'] is not None:
                    self.hub.report_error(pool_info['id'], pool_info['error'])
                else:
                    self.hub.report_error(pool_info['id'], 'ERROR_END')
                    pool_info.pop("error", None)

    def _updateHashRate(self):
        _sum_hashrates = 0.
        for pool_info in self.hub.pools.all_pools:
            _json = {'pool_id': pool_info['id']}
            hash_rates = pool_info[
                'hash_report'] if 'hash_report' in pool_info else {}
            if len(hash_rates) > 0:
                _hash_rates = dict(hash_rates)
                _total_hash_rate = reduce(
                    lambda x, y: x + y, [_hash_rates[k] for k in _hash_rates])
                _json['hash_rate'] = _total_hash_rate
                _sum_hashrates += _total_hash_rate
                pool_info['total_hashrate'] = _total_hash_rate
            else:
                _json['hash_rate'] = 0.0
            # reset hashrate
            if 'hash_report' in pool_info and 'thr_list' in pool_info:
                if pool_info['thr_list'] is not None:
                    for thr in pool_info['thr_list']:
                        pool_info['hash_report'].update(
                            {'%d' % thr._thr_id: 0.0})

            work_report = pool_info[
                'work_report'] if 'work_report' in pool_info else {}
            if 'work_submited' in work_report and work_report[
                    'work_submited'] > 0:
                _json['shares_good'] = work_report[
                    'work_accepted'] if 'work_accepted' in work_report else 0
                _json['shares_total'] = work_report['work_submited']
                _json['shares_pct'] = "%.2f%%" % (
                    _json['shares_good'] * 100.0 / _json['shares_total'], )
            else:
                _json['shares_good'] = 0
                _json['shares_total'] = 0
                _json['shares_pct'] = "0.00%"

            if 'difficulty' in work_report:
                _json['difficulty'] = "%.f" % work_report['difficulty']
            else:
                _json['difficulty'] = "0"

            self.hub.update_hashrate(json.dumps(_json))

        self.trayIcon.setToolTip(
            "%s\nHashrate: %s" %
            (tray_icon_tooltip, human_readable_hashrate(_sum_hashrates)))

    def _load_finished(self):
        #This is the actual context/frame a webpage is running in.
        # Other frames could include iframes or such.
        main_page = self.view.page()
        main_frame = main_page.mainFrame()
        # ATTENTION here's the magic that sets a bridge between Python to HTML
        main_frame.addToJavaScriptWindowObject("app_hub", self.hub)

        if self.is_first_load:  ## Avoid re-settings on page reload (if happened)
            change_setting = main_page.settings().setAttribute
            settings = web_core.QWebSettings
            change_setting(settings.DeveloperExtrasEnabled, self.debug)
            change_setting(settings.LocalStorageEnabled, True)
            change_setting(settings.OfflineStorageDatabaseEnabled, True)
            change_setting(settings.OfflineWebApplicationCacheEnabled, True)
            change_setting(settings.JavascriptCanOpenWindows, True)
            change_setting(settings.PluginsEnabled, False)

            # Show web inspector if debug on
            if self.debug:
                self.inspector = web_core.QWebInspector()
                self.inspector.setPage(self.view.page())
                self.inspector.show()
        #Tell the HTML side, we are open for business
        main_frame.evaluateJavaScript("app_ready()")
        # send pool list to HTML for rendering
        self.hub.create_pool_list()
        # Resize main window to fit web content (avoid scroll bars showed)
        main_page.setViewportSize(main_frame.contentsSize())
        #self.setFixedSize(860, 360)

        # resume mining jobs
        for p in self.hub.pools.all_pools:
            if 'is_mining' in p and p['is_mining']:
                self.hub.start_stop_mining(p['id'])

        self.is_first_load = False

    def _handleAboutToQuit(self):
        log("%s is about to quit..." % APP_NAME, LEVEL_INFO)
        for pool_info in self.hub.pools.all_pools:
            if not 'thr_list' in pool_info or pool_info['thr_list'] is None:
                pool_info['is_mining'] = False
            else:
                # shut down threads
                for thr in pool_info['thr_list']:
                    thr.shutdown()
                    thr.join()
                # shut down RPC client
                pool_info['rpc'].shutdown()
                pool_info['rpc'].join()
                pool_info[
                    'is_mining'] = True  # save mining status to resume on next start

        if manager: manager.shutdown()
        # save pool list
        self.hub.pools.save_all()

    def notify(self, message, title="", icon=None, msg_type=None):
        if self.notifier.notifier is not None:
            self.notifier.notify(title, message, icon)
        else:
            self.showMessage(message, title, msg_type)

    def showMessage(self, message, title="", msg_type=None, timeout=2000):
        """Displays 'message' through the tray icon's showMessage function,
        with title 'title'. 'type' is one of the enumerations of
        'common.MessageTypes'.
        """
        if msg_type is None or msg_type == MSG_TYPE_INFO:
            icon = QSystemTrayIcon.Information

        elif msg_type == MSG_TYPE_WARNING:
            icon = QSystemTrayIcon.Warning

        elif msg_type == MSG_TYPE_CRITICAL:
            icon = QSystemTrayIcon.Critical

        title = "%s - %s" % (APP_NAME, title) if title else APP_NAME
        self.trayIcon.showMessage(title, message, icon, timeout)

    def about(self):
        QMessageBox.about(self, "About", \
            u"%s <br><br>Copyright© 2017 - Sumokoin Projects<br><br>\
            <b>www.sumokoin.org</b>"                                     % self.agent)

    def wait(self, timeout=1):
        for _ in range(timeout * 10):
            sleep(0.1)
            self.app.processEvents()
Example #7
0
def notify(msg):
    log(msg)
    Notify.notify_error(bp_name, msg)
Example #8
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     self.ids.username_field.focus = True
     self.notify = Notify()
Example #9
0
class SigninWindow(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.ids.username_field.focus = True
        self.notify = Notify()

    def cb(self, dt):
        self.notify.dismiss()
        self.notify.clear_widgets()

    def validate_user(self):
        client = MongoClient()
        db = client.silverpos
        users = db.users

        user = self.ids.username_field
        pwd = self.ids.pwd_field
        #info = self.ids.info

        uname = user.text
        passw = pwd.text

        #user.text = ''
        #pwd.text = ''

        if not uname and not passw:
            self.notify.add_widget(
                Label(text='[color=#FFFFFF][b]Username and Password are Required[/b][/color]', markup=True))
            self.notify.open()
            Clock.schedule_once(self.cb, 1.1)
        elif not uname:
            self.notify.add_widget(
                Label(text='[color=#FFFFFF][b]Username is Required[/b][/color]', markup=True))
            self.notify.open()
            Clock.schedule_once(self.cb, 1.1)
            # info.text = "[color=#FF0000]Username required ![/color]"
        elif passw == '':
            self.notify.add_widget(
                Label(text='[color=#FFFFFF][b]Password is Required[/b][/color]', markup=True))
            self.notify.open()
            Clock.schedule_once(self.cb, 1.1)
            # info.text = "[color=#FF0000]Password required ![/color]"
        else:
            user = users.find_one(({'user_name': uname}))
            if user == None:
                self.notify.add_widget(
                    Label(text='[color=#FF0000][b]Invalid Username[/b][/color]', markup=True))
                self.notify.open()
                Clock.schedule_once(self.cb, 1.1)
            # info.text = "[color=#FF0000]Invalid Username ![/color]"
            else:
                passw = hashlib.sha256(passw.encode()).hexdigest()
                if passw == user['password']:
                    des = user['designation']
                    self.notify.add_widget(
                        Label(text='[color=#00FF00][b]Success Login[/b][/color]', markup=True))
                    self.notify.open()
                    Clock.schedule_once(self.cb, 1.3)
                    self.parent.parent.parent.ids.scrn_op.children[0].ids.loggedin_user.text = uname
                    if des == 'Administrator':
                        self.parent.parent.current = 'scrn_admin'
                    else:
                        self.parent.parent.current = 'scrn_op'
                else:
                    self.notify.add_widget(
                        Label(text='[color=#FF0000][b]Invalid Password[/b][/color]', markup=True))
                    self.notify.open()
                    Clock.schedule_once(self.cb, 1.1)
Example #10
0
def log_and_notify(*args):
    Notify.notify_error(*args)
Example #11
0
def notify(*args):
    Notify.notify_error(*args)
# Change labels to categorical values for Keras
y_train = np_utils.to_categorical(train_labels_r, k)
y_test = np_utils.to_categorical(test_labels_r, k)

train_points_rotate = rotate_point_cloud(train_points_r)
train_points_jitter = jitter_point_cloud(train_points_rotate)

print("[INFO] Rotated and Jittered Point Clouds")

# Compiling Model
optimizer = Adam(lr=LEARNING_RATE)
model.compile(optimizer=optimizer,
              loss='categorical_crossentropy',
              metrics=['accuracy'])

notifyCB = Notify()
callbacks = [
    keras.callbacks.TensorBoard(log_dir='./logs',
                                histogram_freq=0,
                                write_graph=True,
                                write_images=False),
    keras.callbacks.ModelCheckpoint(os.path.join(WEIGHTS_PATH,
                                                 'weights{epoch:08d}.h5'),
                                    verbose=0,
                                    save_weights_only=True), notifyCB
]
# Training Model
model.fit(train_points_jitter,
          y_train,
          batch_size=BATCH_SIZE,
          epochs=EPOCHS,
Example #13
0
def notify(*args):
    logger.info(args)
    Notify.notify_status(*args)
Example #14
0
class AdminWindow(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        client = MongoClient()
        db = client.silverpos
        self.users = db.users
        self.products = db.stocks
        self.notify = Notify()

        product_code = []
        product_name = []
        spinvals = []
        for product in self.products.find():
            product_code.append(product["product_code"])
            name = product["product_name"]
            if len(name) > 30:
                name = name[:30] + "..."
            product_name.append(name)
        for x in range(len(product_code)):
            line = ' | '.join([product_code[x], product_name[x]])
            spinvals.append(line)
        self.ids.target_product.values = spinvals

        content = self.ids.scrn_contents
        users = self.get_users()
        userstable = DataTable(table=users)
        content.add_widget(userstable)

        # Display Products
        product_scrn = self.ids.scrn_product_contents
        products = self.get_products()
        prod_table = DataTable(table=products)
        product_scrn.add_widget(prod_table)

    def logout(self):
        self.parent.parent.current = 'scrn_si'

    def add_user_fields(self):
        target = self.ids.ops_fields
        target.clear_widgets()
        crud_first = TextInput(hint_text="First Name", multiline=False)
        crud_last = TextInput(hint_text="Last Name", multiline=False)
        crud_user = TextInput(hint_text="User Name", multiline=False)
        crud_pwd = TextInput(hint_text="Password", multiline=False)
        crud_des = Spinner(text="Operator",
                           values=["Operator", "Administrator"])
        crud_submit = Button(text="Add",
                             background_color=(87 / 255.0, 189 / 255.0,
                                               24 / 255.0, .9),
                             size_hint_x=None,
                             width=100,
                             on_release=lambda x: self.add_user(
                                 crud_first.text, crud_last.text, crud_user.
                                 text, crud_pwd.text, crud_des.text))

        target.add_widget(crud_first)
        target.add_widget(crud_last)
        target.add_widget(crud_user)
        target.add_widget(crud_pwd)
        target.add_widget(crud_des)
        target.add_widget(crud_submit)

    def add_product_fields(self):
        target = self.ids.ops_fields_p
        target.clear_widgets()

        crud_code = TextInput(hint_text="Product Code", multiline=False)
        crud_name = TextInput(hint_text="Product Name", multiline=False)
        crud_weight = TextInput(hint_text="Product Weight", multiline=False)
        crud_stock = TextInput(hint_text="Product Stock", multiline=False)
        crud_sold = TextInput(hint_text="Product Sold", multiline=False)
        crud_order = TextInput(hint_text="Product Order", multiline=False)
        crud_purchase = TextInput(hint_text="Product Purchase",
                                  multiline=False)
        crud_submit = Button(
            text="Add",
            background_color=(87 / 255.0, 189 / 255.0, 24 / 255.0, .9),
            size_hint_x=None,
            width=100,
            on_release=lambda x: self.add_product(
                crud_code.text, crud_name.text, crud_weight.text, crud_stock.
                text, crud_sold.text, crud_order.text, crud_purchase.text),
        )

        target.add_widget(crud_code)
        target.add_widget(crud_name)
        target.add_widget(crud_weight)
        target.add_widget(crud_stock)
        target.add_widget(crud_sold)
        target.add_widget(crud_order)
        target.add_widget(crud_purchase)
        target.add_widget(crud_submit)

    def add_product(self, code, name, weight, stock, sold, order, purchase):
        if code == '' or name == '' or weight == '' or stock == '' or order == '':
            self.notify.add_widget(
                Label(text='[color=#FF0000][b]All Fields Required[/b][/color]',
                      markup=True))
            self.notify.open()
            Clock.schedule_once(self.killswitch, 1)
        else:
            self.products.insert_one({
                "product_code": code,
                "product_name": name,
                "product_weight": weight,
                "in_stock": stock,
                "sold": sold,
                "order": order,
                "last_purchase": purchase
            })
            content = self.ids.scrn_product_contents
            content.clear_widgets()
            # sql = 'INSERT INTO users(first_name,last_name,user_name,password,designation,date) VALUES(%s,%s,%s,%s,%s,%s)'
            # values = [first, last, user, pwd, des, datetime.now()]
            # self.mycursor.execute(sql, values)
            # self.mydb.commit()
            prodz = self.get_products()
            stocktable = DataTable(table=prodz)
            content.add_widget(stocktable)

    def add_user(self, first, last, user, pwd, des):
        pwd = hashlib.sha256(pwd.encode()).hexdigest()
        if first == '' or last == '' or user == '' or pwd == '':
            self.notify.add_widget(
                Label(text='[color=#FF0000][b]All Fields Required[/b][/color]',
                      markup=True))
            self.notify.open()
            Clock.schedule_once(self.killswitch, 1)
        else:
            self.users.insert_one({
                "first_name": first,
                "last_name": last,
                "user_name": user,
                "password": pwd,
                "designation": des,
                "date": datetime.now()
            })
            content = self.ids.scrn_contents
            content.clear_widgets()
            # sql = 'INSERT INTO users(first_name,last_name,user_name,password,designation,date) VALUES(%s,%s,%s,%s,%s,%s)'
            # values = [first, last, user, pwd, des, datetime.now()]
            # self.mycursor.execute(sql, values)
            # self.mydb.commit()
            users = self.get_users()
            userstable = DataTable(table=users)
            content.add_widget(userstable)

    def killswitch(self, dtx):
        self.notify.dismiss()
        self.notify.clear_widgets()

    def update_user(self, first, last, user, pwd, des):
        pwd = hashlib.sha256(pwd.encode()).hexdigest()
        if user == '':
            self.notify.add_widget(
                Label(text='[color=#FF0000][b]All Fields Required[/b][/color]',
                      markup=True))
            self.notify.open()
            Clock.schedule_once(self.killswitch, 1)
        else:
            user = self.users.find_one({'user_name': user})
            if user == None:
                self.notify.add_widget(
                    Label(
                        text='[color=#FF0000][b]Invalid Username[/b][/color]',
                        markup=True))
                self.notify.open()
                Clock.schedule_once(self.killswitch, 1)
            else:
                if first == "":
                    first = user['first_name']
                if last == "":
                    last = user['last_name']
                if pwd == "":
                    pwd = user['password']
                if des == "":
                    des = user['designation']
                content = self.ids.scrn_contents
                content.clear_widgets()
                self.users.update_one({"user_name": user}, {
                    "$set": {
                        "first_name": first,
                        "last_name": last,
                        "user_name": user,
                        "password": pwd,
                        "designation": des,
                        "date": datetime.now()
                    }
                })
                # sql = 'UPDATE users SET first_name=%s,last_name=%s,user_name=%s,password=%s,designation=%s WHERE user_name=%s'
                # values = [first,last,user,pwd,des,user]
                # self.mycursor.execute(sql,values)
                # self.mydb.commit()
                users = self.get_users()
                userstable = DataTable(table=users)
                content.add_widget(userstable)

    def update_user_fields(self):
        target = self.ids.ops_fields
        target.clear_widgets()
        crud_first = TextInput(hint_text="First Name", multiline=False)
        crud_last = TextInput(hint_text="Last Name", multiline=False)
        crud_user = TextInput(hint_text="User Name", multiline=False)
        crud_pwd = TextInput(hint_text="Password", multiline=False)
        crud_des = Spinner(text="Operator",
                           values=["Operator", "Administrator"])
        crud_submit = Button(text="Update",
                             background_color=(189 / 255.0, 126 / 255.0,
                                               24 / 255.0, 1),
                             size_hint_x=None,
                             width=100,
                             on_release=lambda x: self.update_user(
                                 crud_first.text, crud_last.text, crud_user.
                                 text, crud_pwd.text, crud_des.text))

        target.add_widget(crud_first)
        target.add_widget(crud_last)
        target.add_widget(crud_user)
        target.add_widget(crud_pwd)
        target.add_widget(crud_des)
        target.add_widget(crud_submit)

    def update_product_fields(self):
        target = self.ids.ops_fields_p
        target.clear_widgets()

        crud_code = TextInput(hint_text="Product Code", multiline=False)
        crud_name = TextInput(hint_text="Product Name", multiline=False)
        crud_weight = TextInput(hint_text="Product Weight", multiline=False)
        crud_stock = TextInput(hint_text="Product Stock", multiline=False)
        crud_sold = TextInput(hint_text="Product Sold", multiline=False)
        crud_order = TextInput(hint_text="Product Order", multiline=False)
        crud_purchase = TextInput(hint_text="Product Purchase",
                                  multiline=False)
        crud_submit = Button(
            text="Update",
            background_color=(189 / 255.0, 126 / 255.0, 24 / 255.0, 1),
            size_hint_x=None,
            width=100,
            on_release=lambda x: self.update_product(
                crud_code.text, crud_name.text, crud_weight.text, crud_stock.
                text, crud_sold.text, crud_order.text, crud_purchase.text),
        )

        target.add_widget(crud_code)
        target.add_widget(crud_name)
        target.add_widget(crud_weight)
        target.add_widget(crud_stock)
        target.add_widget(crud_sold)
        target.add_widget(crud_order)
        target.add_widget(crud_purchase)
        target.add_widget(crud_submit)

    def update_product(self, code, name, weight, stock, sold, order, purchase):
        if code == '':
            self.notify.add_widget(
                Label(text='[color=#FF0000][b]Code Required[/b][/color]',
                      markup=True))
            self.notify.open()
            Clock.schedule_once(self.killswitch, 1)
        else:
            target_code = self.products.find_one({'product_code': code})
            if target_code == None:
                self.notify.add_widget(
                    Label(text=
                          '[color=#FF0000][b]All Fields Required[/b][/color]',
                          markup=True))
                self.notify.open()
                Clock.schedule_once(self.killswitch, 1)
            else:
                if name == '':
                    name = target_code['product_name']
                if weight == '':
                    weight = target_code['product_weight']
                if stock == '':
                    stock = target_code['in_stock']
                if sold == '':
                    sold = target_code['sold']
                if order == '':
                    order = target_code['order']
                if purchase == '':
                    purchase = target_code['last_purchase']
                content = self.ids.scrn_product_contents
                content.clear_widgets()
                self.products.update_one(
                    {"product_code": code},
                    {
                        "$set": {
                            "product_code": code,
                            "product_name": name,
                            "product_weight": weight,
                            "in_stock": stock,
                            "sold": sold,
                            "order": order,
                            "last_purchase": purchase
                        }
                    },
                )
                prodz = self.get_products()
                stocktable = DataTable(table=prodz)
                content.add_widget(stocktable)

    def remove_user_fields(self):
        target = self.ids.ops_fields
        target.clear_widgets()
        crud_user = TextInput(hint_text="User Name")
        crud_submit = Button(
            text="Remove",
            size_hint_x=None,
            width=100,
            background_color=(189 / 255.0, 43 / 255.0, 24 / 255.0, .9),
            on_release=lambda x: self.remove_user(crud_user.text))

        target.add_widget(crud_user)
        target.add_widget(crud_submit)

    def remove_product_fields(self):
        target = self.ids.ops_fields_p
        target.clear_widgets()
        crud_code = TextInput(hint_text="Product Code")
        crud_submit = Button(
            text="Remove",
            background_color=(189 / 255.0, 43 / 255.0, 24 / 255.0, .9),
            size_hint_x=None,
            width=100,
            on_release=lambda x: self.remove_product(crud_code.text))

        target.add_widget(crud_code)
        target.add_widget(crud_submit)

    def remove_user(self, user):
        if user == '':
            self.notify.add_widget(
                Label(text='[color=#FF0000][b]UserName Required[/b][/color]',
                      markup=True))
            self.notify.open()
            Clock.schedule_once(self.killswitch, 1)
        else:
            target_user = self.users.find_one({'user_name': user})
            if target_user == None:
                self.notify.add_widget(
                    Label(
                        text='[color=#FF0000][b]Invalid User Name[/b][/color]',
                        markup=True))
                self.notify.open()
                Clock.schedule_once(self.killswitch, 1)
            else:
                content = self.ids.scrn_contents
                content.clear_widgets()
                self.users.delete_one({"user_name": user})

                users = self.get_users()
                userstable = DataTable(table=users)
                content.add_widget(userstable)

    def remove_product(self, code):
        if code == '':
            self.notify.add_widget(
                Label(
                    text='[color=#FF0000][b]Product Code Required[/b][/color]',
                    markup=True))
            self.notify.open()
            Clock.schedule_once(self.killswitch, 1)
        else:
            target_code = self.products.find_one({'product_code': code})
            if target_code == None:
                self.notify.add_widget(
                    Label(text=
                          '[color=#FF0000][b]Invalid Product Code[/b][/color]',
                          markup=True))
                self.notify.open()
                Clock.schedule_once(self.killswitch, 1)
            else:
                content = self.ids.scrn_product_contents
                content.clear_widgets()
                self.products.delete_one({"product_code": code})

                prodz = self.get_products()
                stocktable = DataTable(table=prodz)
                content.add_widget(stocktable)

    def get_users(self):
        client = MongoClient()
        db = client.silverpos
        users = db.users
        _users = OrderedDict()
        _users["first_names"] = {}
        _users["last_names"] = {}
        _users["user_names"] = {}
        _users["passwords"] = {}
        _users["designations"] = {}
        first_names = []
        last_names = []
        user_names = []
        passwords = []
        designations = []
        for user in users.find():
            # first_names.append(user['first_name'])
            # last_names.append(user['last_name'])
            # user_names.append(user['user_name'])
            # pwd = user['password']
            # if len(pwd) > 10:
            #    pwd = pwd[:10] + '...'
            # passwords.append(pwd)
            # designations.append(user['designation'])
            first_names.append(user.get("first_name"))
            last_names.append(user.get("last_name"))
            user_names.append(user.get("user_name"))
            l = user.get("password")
            if len(l) > 10:
                l = l[:10] + "..."
            passwords.append(l)
            designations.append(user.get("designation"))
        # print(designations)
        users_length = len(first_names)
        idx = 0
        while idx < users_length:
            _users["first_names"][idx] = first_names[idx]
            _users["last_names"][idx] = last_names[idx]
            _users["user_names"][idx] = user_names[idx]
            _users["passwords"][idx] = passwords[idx]
            _users["designations"][idx] = designations[idx]

            idx += 1

        return _users

    def get_products(self):
        client = MongoClient()
        db = client.silverpos
        products = db.stocks
        _stocks = OrderedDict()
        _stocks["product_code"] = {}
        _stocks["product_name"] = {}
        _stocks["product_weight"] = {}
        _stocks["in_stock"] = {}
        _stocks["sold"] = {}
        _stocks["order"] = {}
        _stocks["last_purchase"] = {}

        product_code = []
        product_name = []
        product_weight = []
        in_stock = []
        sold = []
        order = []
        last_purchase = []

        for product in products.find():
            product_code.append(product["product_code"])
            name = product["product_name"]
            if len(name) > 10:
                name = name[:10] + "..."
            product_name.append(name)
            product_weight.append(product["product_weight"])
            in_stock.append(product["in_stock"])
            try:
                sold.append(product["sold"])
            except KeyError:
                sold.append("")  # add nothing !
            try:
                order.append(product["order"])
            except KeyError:
                order.append("")
            try:
                last_purchase.append(product["last_purchase"])
            except KeyError:
                last_purchase.append("")
        # print(designations)
        products_length = len(product_code)
        idx = 0
        while idx < products_length:
            _stocks["product_code"][idx] = product_code[idx]
            _stocks["product_name"][idx] = product_name[idx]
            _stocks["product_weight"][idx] = product_weight[idx]
            _stocks["in_stock"][idx] = in_stock[idx]
            _stocks["sold"][idx] = sold[idx]
            _stocks["order"][idx] = order[idx]
            _stocks["last_purchase"][idx] = last_purchase[idx]

            idx += 1

        return _stocks

    '''
    pip install pandas, matplotlib
    garden install matplotlib    
    '''

    def view_stats(self):
        plt.cla()
        self.ids.analysis_res.clear_widgets()
        target_product = self.ids.target_product.text
        target = target_product[:target_product.find(' | ')]
        name = target_product[target_product.find(' | '):]

        df = pd.read_csv('admin\products_purchase.csv')
        purchases = []
        dates = []
        count = 0
        for x in range(len(df)):
            if str(df.Product_Code[x]) == target:
                purchases.append(df.Purchased[x])
                dates.append(count)
                count += 1

        plt.bar(dates, purchases, color='teal', label=name)
        plt.ylabel('Total Purchases')
        plt.xlabel('day')
        self.ids.analysis_res.add_widget(FCK(plt.gcf()))

    def change_screen(self, instance):
        if instance.text == "Manage Products":
            self.ids.scrn_mngr.current = "scrn_product_content"
        elif instance.text == "Manage Users":
            self.ids.scrn_mngr.current = "scrn_content"
        else:
            self.ids.scrn_mngr.current = "scrn_analysis"