Beispiel #1
0
 def __init__(self, maxInstanceIdx, secondTimeout):
     super().__init__(maxInstanceIdx, secondTimeout, name="NeuralAI")
     self._theoremName = ""
     self._theorem = ""
     # get Rule States
     self._trueRuleStates = []
     ruleStates = DarkLogic.getRuleStates()
     for ruleState in ruleStates:
         self._trueRuleStates.append(makeTrueState(ruleState))
     self._inputSize = (len(self._trueRuleStates) + 1) * NeuralAI.NbOperators * 19
     self._storeNodes = []
     self._db = Database(NeuralAI.DbName)
     self._gamesSinceLastLearning = 0
     if file_io.file_exists(NeuralAI.ModelFile):
         print("load DeepAI brain model")
         self._model = keras.models.load_model(NeuralAI.ModelFile)
     else:
         # create model
         print("create new DeepAI brain model")
         self._model = createModel(len(self._trueRuleStates) + 1)
         compileModel(self._model, NeuralAI.INIT_LR)
         self._model.save(NeuralAI.ModelFile)
     self._model = extractTestModel(self._model)
     self._modelMutex = Lock()
     self._elo = 1076  # 1418
Beispiel #2
0
 def __init__(self):
     """set up attributes"""
     self.green_line = colored("-----------------------------------------", "green")
     self.red_line = colored("-----------------------------------------", "red")
     self.touch_error = colored("Pour faire une sélection. Tapez son numéro", "red")
     self.database = Database()
     self.list_product = []
     self.cat = 0
     self.sub = 0
Beispiel #3
0
    async def on_ready():
        """is called when Bot is ready
        """
        Database.create_database()
        Database.update_database(bot)
        change_status = ChangeStatus(bot)
        change_status.change_status.start()

        print('Bot is ready')
Beispiel #4
0
    async def on_guild_join(self, guild):
        """Function is called when Bot joins to server

        :param guild: contains information about server
        :type guild: discord.Guild
        """

        Database.add_guild(guild.id)
        for member in guild.members:
            Database.add_member(member.guild_id, guild.id)
 def execOpenWindow(self):
     dialog = QtGui.QDialog()
     dialog.ui = Ui_Dialog_Open()
     dialog.ui.setupUi(dialog)
     dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
     dialog.exec_()
     if dialog.ui.accepted():
         db_name = dialog.ui.getNameToOpen()
         self.db = Database(db_name)
         self.uploadTable()
         self.uploadLabels()
         self.rows_added = 0
Beispiel #6
0
def parser():
    DarkLogic.init(0)
    db = Database("Test/dbtest.csv")
    dbStates = db.getDatas()
    print("Total number of theorems in database: " + str(len(dbStates)))
    for dbState in dbStates.values():
        thCreated = DarkLogic.makeTheorem(dbState.theoremName(),
                                          dbState.theoremContent())
        assert thCreated, "Theorem name: " + dbState.theoremName() + ", " \
                             "content: " + dbState.theoremContent() + " has not been created"
        dlContent = DarkLogic.toStrTheorem()
        assert dlContent == dbState.theoremContent(), "Bad parsing! content in darklogic is '"\
            + dlContent + "', but original was " + dbState.theoremContent()
Beispiel #7
0
    async def change_prefix(self, ctx, prefix: CheckLength.check_length):
        """Changes server's command prefix

        :param ctx: the context in which a command is called
        :type ctx: discord.ext.commands.Context
        :param prefix: new prefix which invokes commands
        :type prefix: str
        """
        old_prefix = \
            Database.get_one(Database.db_servers, {'_id': ctx.guild.id}, selection={'settings.prefix': 1, '_id': 0})[
                'settings']['prefix']
        # Zapytanie w MongoDB, aby wejsc glebiej do slownika po kluczach uzywamy '.'
        if Database.update_one(Database.db_servers, {'_id': ctx.guild.id}, {'settings.prefix': prefix}):
            await ctx.send(f'Pomyślnie zmienio prefix z {old_prefix} na {prefix}')
 def execNewWindow(self):
     dialog = QtGui.QDialog()
     dialog.ui = Ui_Dialog_New()
     dialog.ui.setupUi(dialog)
     dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
     dialog.exec_()
     if dialog.ui.accepted():
         db_name, value_init = dialog.ui.getDbNameAndValue()
         self.db = Database(db_name)
         self.db.set_salary(value_init)
         self.uploadTable()
         self.salary = self.db.get_salary()
         self.addCosts()
         self.uploadLabels()
         self.rows_added = 0
Beispiel #9
0
 def from_mongo(query):
     mongo_data = Database.find_one_data(collection='books',
                                         query={'isbn': int(query)})
     if mongo_data == None:
         return None
     else:
         return dict(mongo_data)
Beispiel #10
0
 async def check_for_user_detail(query):
     mongo_email = [
         mongo_email
         for mongo_email in Database.find_data(collection='users',
                                               query={'email': query})
     ]
     return mongo_email
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(462, 715)
        style = "QMainWindow {background-color:" \
                " QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #616161," \
                " stop: 0.5 #505050, stop: 0.6 #434343, stop:1 #656565);}"
        MainWindow.setStyleSheet(style)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.initToolBar(MainWindow)
        self.db = Database()
        self.initCalendar()
        self.initTableWidget()
        self.initInputs()
        self.initButtons()
        self.initLabels()
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QObject.connect(self.calendarWidget, QtCore.SIGNAL(_fromUtf8("clicked(QDate)")), self.dateTimeEdit.setDate)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), self.buttonAccepted)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), self.tableWidget.scrollToBottom)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), self.buttonRejected)
        QtCore.QObject.connect(self.actionNew, QtCore.SIGNAL(_fromUtf8("triggered()")), self.action_new)
        QtCore.QObject.connect(self.actionOpen, QtCore.SIGNAL(_fromUtf8("triggered()")), self.action_open)
        QtCore.QObject.connect(self.actionSave, QtCore.SIGNAL(_fromUtf8("triggered()")), self.save_changes)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
Beispiel #12
0
 def main_menu(self):
     """first menu et creation of database in second choice"""
     print(self.green_line)
     print(colored("1. Utiliser application", "yellow",))
     print(colored("2. Supression/Création de la database", "magenta"))
     print(colored("0. Quitter l'application ", "red"))
     print(self.green_line)
     choice_main = input(colored("\n ---> ", "green"))
     try:
         choice_main = int(choice_main)
     except ValueError:
         choice_main = -1
     if choice_main == 1:
         self.api_menu()
     elif choice_main == 2:
         database()
         data = Database()
         request = Request()
         request.create_database(data)
         self.main_menu()
     elif choice_main == 0:
         self.bye()
     else:
         print(self.touch_error)
         self.main_menu()
Beispiel #13
0
 async def find_isbn_mongo(query):
     isbn_book = [
         isbn_book
         for isbn_book in Database.find_data(collection='books',
                                             query={'isbn': int(query)})
     ]
     return isbn_book
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(462, 715)
        style = "QMainWindow {background-color:" \
                " QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #616161," \
                " stop: 0.5 #505050, stop: 0.6 #434343, stop:1 #656565);}"
        MainWindow.setStyleSheet(style)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.initToolBar(MainWindow)
        self.db = Database()
        self.initCalendar()
        self.initTableWidget()
        self.initInputs()
        self.initButtons()
        self.initLabels()
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QObject.connect(self.calendarWidget,
                               QtCore.SIGNAL(_fromUtf8("clicked(QDate)")),
                               self.dateTimeEdit.setDate)
        QtCore.QObject.connect(self.buttonBox,
                               QtCore.SIGNAL(_fromUtf8("accepted()")),
                               self.buttonAccepted)
        QtCore.QObject.connect(self.buttonBox,
                               QtCore.SIGNAL(_fromUtf8("accepted()")),
                               self.tableWidget.scrollToBottom)
        QtCore.QObject.connect(self.buttonBox,
                               QtCore.SIGNAL(_fromUtf8("rejected()")),
                               self.buttonRejected)
        QtCore.QObject.connect(self.actionNew,
                               QtCore.SIGNAL(_fromUtf8("triggered()")),
                               self.action_new)
        QtCore.QObject.connect(self.actionOpen,
                               QtCore.SIGNAL(_fromUtf8("triggered()")),
                               self.action_open)
        QtCore.QObject.connect(self.actionSave,
                               QtCore.SIGNAL(_fromUtf8("triggered()")),
                               self.save_changes)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
 def execOpenWindow(self):
     dialog = QtGui.QDialog()
     dialog.ui = Ui_Dialog_Open()
     dialog.ui.setupUi(dialog)
     dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
     dialog.exec_()
     if dialog.ui.accepted():
         db_name = dialog.ui.getNameToOpen()
         self.db = Database(db_name)
         self.uploadTable()
         self.uploadLabels()
         self.rows_added = 0
Beispiel #16
0
 def from_mongo_purchase(user_id):
     ls = []
     pipeline = ([
         {"$match": {"user_id": int(user_id)}},
         {"$group":
              {"_id": int(user_id),
               "purchases": {"$addToSet": "$purchase_detail"}, "email": {"$first": "$email"}
               }},
         {"$project": {"purchases": 1, "_id": 1, "email": 1}}
     ])
     user_purchases = [user_purchases for user_purchases in  Database.aggregate(collection='purchase', pipeline=pipeline)]
     return user_purchases
 def execNewWindow(self):
     dialog = QtGui.QDialog()
     dialog.ui = Ui_Dialog_New()
     dialog.ui.setupUi(dialog)
     dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
     dialog.exec_()
     if dialog.ui.accepted():
         db_name, value_init = dialog.ui.getDbNameAndValue()
         self.db = Database(db_name)
         self.db.set_salary(value_init)
         self.uploadTable()
         self.salary = self.db.get_salary()
         self.addCosts()
         self.uploadLabels()
         self.rows_added = 0
Beispiel #18
0
    def get_server_prefix(bot, message):
        """Gets server id from sent message

        :param bot: instance of Bot
        :type bot: discord.ext.commands.bot.Bot
        :param message: contains information about message
        :type message: discord.Message
        :return: server's prefix
        :rtype: str
        """

        prefix = None
        try:
            prefix = Database.get_one(Database.db_servers, {'_id': message.guild.id})['settings']['prefix']
        except:
            pass

        if prefix is None:
            return default_prefix
        return prefix
Beispiel #19
0
from Database.post import Book
from Database.login import User
from Database.search import Search
from Database.purchase import Purchase
import datetime
from Module import validation
from typing import List, Union

app = FastAPI()
'''calls the Book class, User class, and Purchase class in database.py'''
mongo_book = Book
mongo_user = User
mongo_purchase = Purchase
mongo_search = Search
'''initializes Database connection to deault port 27017'''
Database.intialize()
'''------------------------------------------Purchase Collection-----------------------------------------------------'''


@app.get('/purcahse/{user_id}/{isbn}',
         status_code=HTTP_201_CREATED,
         tags=['Purchases'])
async def user_purchase(user_id, isbn):
    user_detail = await get_by_user_id(user_id=int(user_id))
    user = {
        'user_name': user_detail['user_name'],
        'email': user_detail['email'],
        'user_id': int(user_id)
    }
    book_detail = await get_book_by_isbn(isbn=isbn)
    book = {
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(462, 715)
        style = "QMainWindow {background-color:" \
                " QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #616161," \
                " stop: 0.5 #505050, stop: 0.6 #434343, stop:1 #656565);}"
        MainWindow.setStyleSheet(style)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.initToolBar(MainWindow)
        self.db = Database()
        self.initCalendar()
        self.initTableWidget()
        self.initInputs()
        self.initButtons()
        self.initLabels()
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QObject.connect(self.calendarWidget,
                               QtCore.SIGNAL(_fromUtf8("clicked(QDate)")),
                               self.dateTimeEdit.setDate)
        QtCore.QObject.connect(self.buttonBox,
                               QtCore.SIGNAL(_fromUtf8("accepted()")),
                               self.buttonAccepted)
        QtCore.QObject.connect(self.buttonBox,
                               QtCore.SIGNAL(_fromUtf8("accepted()")),
                               self.tableWidget.scrollToBottom)
        QtCore.QObject.connect(self.buttonBox,
                               QtCore.SIGNAL(_fromUtf8("rejected()")),
                               self.buttonRejected)
        QtCore.QObject.connect(self.actionNew,
                               QtCore.SIGNAL(_fromUtf8("triggered()")),
                               self.action_new)
        QtCore.QObject.connect(self.actionOpen,
                               QtCore.SIGNAL(_fromUtf8("triggered()")),
                               self.action_open)
        QtCore.QObject.connect(self.actionSave,
                               QtCore.SIGNAL(_fromUtf8("triggered()")),
                               self.save_changes)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def execOpenWindow(self):
        dialog = QtGui.QDialog()
        dialog.ui = Ui_Dialog_Open()
        dialog.ui.setupUi(dialog)
        dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        dialog.exec_()
        if dialog.ui.accepted():
            db_name = dialog.ui.getNameToOpen()
            self.db = Database(db_name)
            self.uploadTable()
            self.uploadLabels()
            self.rows_added = 0

    def action_open(self):
        if self.changesWereSaved():
            self.execOpenWindow()
        else:
            dialog = QtGui.QDialog()
            dialog.ui = Ui_Dialog_SaveMsg()
            dialog.ui.setupUi(dialog)
            dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
            dialog.exec_()
            if dialog.ui.mustSave():
                self.save_changes()
            self.execOpenWindow()

    def execNewWindow(self):
        dialog = QtGui.QDialog()
        dialog.ui = Ui_Dialog_New()
        dialog.ui.setupUi(dialog)
        dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        dialog.exec_()
        if dialog.ui.accepted():
            db_name, value_init = dialog.ui.getDbNameAndValue()
            self.db = Database(db_name)
            self.db.set_salary(value_init)
            self.uploadTable()
            self.salary = self.db.get_salary()
            self.addCosts()
            self.uploadLabels()
            self.rows_added = 0

    def action_new(self):
        if self.changesWereSaved():
            self.execNewWindow()
        else:
            dialog = QtGui.QDialog()
            dialog.ui = Ui_Dialog_SaveMsg()
            dialog.ui.setupUi(dialog)
            dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
            dialog.exec_()
            if dialog.ui.mustSave():
                self.save_changes()
            self.execNewWindow()

    def initToolBar(self, MainWindow):
        self.toolBar = QtGui.QToolBar(MainWindow)
        self.toolBar.setObjectName(_fromUtf8("toolBar"))
        self.toolBar.setStyleSheet("background-color:#2E2E2E;")
        MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
        self.actionOpen = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/images/open.png")),
                       QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionOpen.setIcon(icon)
        self.actionOpen.setObjectName(_fromUtf8("actionOpen"))
        self.actionNew = QtGui.QAction(MainWindow)
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(_fromUtf8(":/images/new.png")),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionNew.setIcon(icon1)
        self.actionNew.setObjectName(_fromUtf8("actionNew"))
        self.actionSave = QtGui.QAction(MainWindow)
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap(_fromUtf8(":/images/save.png")),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionSave.setIcon(icon2)
        self.actionSave.setObjectName(_fromUtf8("actionSave"))
        self.toolBar.addAction(self.actionNew)
        self.toolBar.addAction(self.actionOpen)
        self.toolBar.addAction(self.actionSave)

    def initCalendar(self):
        self.calendarWidget = QtGui.QCalendarWidget(self.centralwidget)
        self.calendarWidget.setGeometry(QtCore.QRect(5, 0, 448, 180))
        self.calendarWidget.setObjectName(_fromUtf8("calendarWidget"))
        self.calendarWidget.setGridVisible(True)
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.calendarWidget.setFont(font)
        style = "background-color: #575756; padding: 1px;" \
                " border-style: solid; border: 1px solid #656565;" \
                " border-radius: 5; color: #363534;" \
                " alternate-background-color: #BDB9B5"
        self.calendarWidget.setStyleSheet(style)
        self.today = self.calendarWidget.selectedDate()

    def initTableWidget(self):
        self.tableWidget = QtGui.QTableWidget(self.centralwidget)
        self.tableWidget.setGeometry(QtCore.QRect(5, 190, 451, 370))
        self.tableWidget.setObjectName(_fromUtf8("tableWidget"))
        style = "QTableWidget {background-color:" \
                " QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1," \
                " stop: 0 #4d4d4d, stop: 0 #646464, stop: 1 #BDB9B5);" \
                " top: 5px; border: 1px solid #656565;" \
                " gridline-color: #BAB0A7} " \
                "QHeaderView::section {background-color:" \
                " QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #616161," \
                " stop: 0.5 #505050, stop: 0.6 #434343, stop:1 #656565);" \
                " color: %s; padding-left: 4px;" \
                " border: 1px solid #6c6c6c;}" \
                "QTableCornerButton::section {" \
                " background: #505050; border: 2px outset #505050;} " \
                "QScrollBar:horizontal {background:" \
                " QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1," \
                " stop: 0.0 #121212, stop: 0.2 #282828, stop: 1 #484848);} " \
                "QScrollBar::vertical {background:" \
                " QLinearGradient( x1: 1, y1: 0, x2: 1, y2: 0," \
                " stop: 0.0 #121212, stop: 0.2 #282828," \
                " stop: 1 #484848);}" % COLOR
        self.tableWidget.setStyleSheet(style)
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.tableWidget.setFont(font)
        self.rows_added = 0
        self.tableWidget.setColumnCount(4)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(COL_PRODUCT, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(COL_PRICE, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(COL_DATE, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(COL_BUYER, item)
        self.line = QtGui.QFrame(self.centralwidget)
        self.line.setGeometry(QtCore.QRect(0, 560, 451, 16))
        self.line.setFrameShape(QtGui.QFrame.HLine)
        self.line.setFrameShadow(QtGui.QFrame.Sunken)
        self.line.setObjectName(_fromUtf8("line"))
        self.line.setStyleSheet("border: 1px solid #656565")

    def initInputs(self):
        self.lineEdit_1 = QtGui.QLineEdit(self.centralwidget)
        self.lineEdit_1.setGeometry(QtCore.QRect(10, 610, 113, 27))
        self.lineEdit_1.setObjectName(_fromUtf8("lineEdit_1"))
        style = "QLineEdit {background-color:" \
                " QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1," \
                " stop: 0 #4d4d4d, stop: 0 #646464, stop: 1 #BDB9B5);" \
                " padding: 1px; border-style: solid;" \
                " border: 1px solid #656565; border-radius: 5;}"
        self.lineEdit_1.setStyleSheet(style)
        self.doubleSpinBox = QtGui.QDoubleSpinBox(self.centralwidget)
        self.doubleSpinBox.setGeometry(QtCore.QRect(130, 610, 62, 27))
        self.doubleSpinBox.setMaximum(MAXIMUM)
        self.doubleSpinBox.setObjectName(_fromUtf8("doubleSpinBox"))
        style = "QDoubleSpinBox {background-color:" \
                " QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1," \
                " stop: 0 #4d4d4d, stop: 0 #646464, stop: 1 #BDB9B5);" \
                " padding: 1px; border-style: solid;" \
                " border: 1px solid #656565; border-radius: 5;} " \
                "QDoubleSpinBox::up-button {border: 1px solid #656565;} " \
                "QDoubleSpinBox::down-button {border: 1px solid #656565;}"
        self.doubleSpinBox.setStyleSheet(style)
        self.dateTimeEdit = QtGui.QDateTimeEdit(self.centralwidget)
        self.dateTimeEdit.setGeometry(QtCore.QRect(200, 610, 131, 27))
        self.dateTimeEdit.setObjectName(_fromUtf8("dateTimeEdit"))
        style = "QDateTimeEdit {background-color:" \
                " QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1," \
                " stop: 0 #4d4d4d, stop: 0 #646464, stop: 1 #BDB9B5);" \
                " padding: 1px; border-style: solid;" \
                " border: 1px solid #656565; border-radius: 5;} " \
                "QDateTimeEdit::up-button {border: 1px solid #656565;} " \
                "QDateTimeEdit::down-button {border: 1px solid #656565;}"
        self.dateTimeEdit.setStyleSheet(style)
        self.time_zero = self.dateTimeEdit.time()
        self.lineEdit_2 = QtGui.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(340, 610, 113, 27))
        self.lineEdit_2.setObjectName(_fromUtf8("lineEdit_2"))
        style = "QLineEdit {background-color:" \
                " QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1," \
                " stop: 0 #4d4d4d, stop: 0 #646464, stop: 1 #BDB9B5);" \
                " padding: 1px; border-style: solid;" \
                " border: 1px solid #656565; border-radius: 5;}"
        self.lineEdit_2.setStyleSheet(style)

    def initButtons(self):
        self.buttonBox = QtGui.QDialogButtonBox(self.centralwidget)
        self.buttonBox.setGeometry(QtCore.QRect(280, 645, 176, 27))
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel
                                          | QtGui.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
        style = "background-color: QLinearGradient(" \
                " x1: 0, y1: 0, x2: 0, y2: 1," \
                " stop: 0 #4d4d4d, stop: 0 #646464, stop: 1 #BDB9B5);"
        self.buttonBox.setStyleSheet(style)

    def initLabels(self):
        self.label1 = QtGui.QLabel(self.centralwidget)
        self.label1.setGeometry(QtCore.QRect(10, 580, 350, 20))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label1.setFont(font)
        self.label1.setObjectName(_fromUtf8("label2"))
        self.label1.setStyleSheet("color : %s" % COLOR)
        self.label2 = QtGui.QLabel(self.centralwidget)
        self.label2.setGeometry(QtCore.QRect(160, 580, 350, 20))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label2.setFont(font)
        self.label2.setObjectName(_fromUtf8("label2"))
        self.label2.setStyleSheet("color : %s" % COLOR)
        self.label3 = QtGui.QLabel(self.centralwidget)
        self.label3.setGeometry(QtCore.QRect(310, 580, 350, 20))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label3.setFont(font)
        self.label3.setObjectName(_fromUtf8("label3"))
        self.label3.setStyleSheet("color : %s" % COLOR)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(
            _translate("MainWindow", "Control de Gastos", None))
        self.setActions()
        self.setColumnName()
        self.uploadTable()
        self.uploadLabels()

    def setActions(self):
        self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar", None))
        self.actionOpen.setText(_translate("MainWindow", "&Open", None))
        self.actionOpen.setShortcut(_translate("MainWindow", "Ctrl+O", None))
        self.actionNew.setText(_translate("MainWindow", "&New", None))
        self.actionNew.setShortcut(_translate("MainWindow", "Ctrl+N", None))
        self.actionSave.setText(_translate("MainWindow", "&Save", None))
        self.actionSave.setShortcut(_translate("MainWindow", "Ctrl+S", None))

    def setColumnName(self):
        item = self.tableWidget.horizontalHeaderItem(COL_PRODUCT)
        item.setText(_translate("MainWindow", "Producto", None))
        item = self.tableWidget.horizontalHeaderItem(COL_PRICE)
        item.setText(_translate("MainWindow", "Precio", None))
        item = self.tableWidget.horizontalHeaderItem(COL_DATE)
        item.setText(_translate("MainWindow", "Fecha", None))
        item = self.tableWidget.horizontalHeaderItem(COL_BUYER)
        item.setText(_translate("MainWindow", "Comprador", None))

    def uploadTable(self):
        self.rowCount = self.db.get_row_count()
        db_products = self.db.get_products()
        db_prices = self.db.get_prices()
        db_dates = self.db.get_date()
        db_buyers = self.db.get_buyer()
        self.tableWidget.setRowCount(self.rowCount)
        for row in range(self.rowCount):
            item = QtGui.QTableWidgetItem()
            self.tableWidget.setItem(row, COL_PRODUCT, item)
            item = QtGui.QTableWidgetItem()
            self.tableWidget.setItem(row, COL_PRICE, item)
            item = QtGui.QTableWidgetItem()
            self.tableWidget.setItem(row, COL_DATE, item)
            item = QtGui.QTableWidgetItem()
            self.tableWidget.setItem(row, COL_BUYER, item)
        __sortingEnabled = self.tableWidget.isSortingEnabled()
        self.tableWidget.setSortingEnabled(False)
        for row in range(self.rowCount):
            item = self.tableWidget.item(row, COL_PRODUCT)
            item.setText(_translate("MainWindow", db_products[row], None))
            item = self.tableWidget.item(row, COL_PRICE)
            item.setText(_translate("MainWindow", db_prices[row], None))
            item = self.tableWidget.item(row, COL_DATE)
            item.setText(_translate("MainWindow", db_dates[row], None))
            item = self.tableWidget.item(row, COL_BUYER)
            item.setText(_translate("MainWindow", db_buyers[row], None))
        self.tableWidget.setSortingEnabled(__sortingEnabled)

    def buttonAccepted(self):
        self.tableWidget.insertRow(self.rowCount)
        for column in range(4):
            item = QtGui.QTableWidgetItem()
            self.tableWidget.setItem(self.rowCount, column, item)
        text1 = self.lineEdit_1.text()
        value = self.doubleSpinBox.value()
        dateTime = self.dateTimeEdit.dateTime()
        dateTime = dateTime.toString("ddd d MMM yyyy hh:mm")
        dateTime = delete_accent(dateTime)
        text2 = self.lineEdit_2.text()
        __sortingEnabled = self.tableWidget.isSortingEnabled()
        self.tableWidget.setSortingEnabled(False)
        item = self.tableWidget.item(self.rowCount, COL_PRODUCT)
        item.setText(_translate("MainWindow", text1, None))
        item = self.tableWidget.item(self.rowCount, COL_PRICE)
        item.setText(_translate("MainWindow", str(value), None))
        item = self.tableWidget.item(self.rowCount, COL_DATE)
        item.setText(_translate("MainWindow", dateTime, None))
        item = self.tableWidget.item(self.rowCount, COL_BUYER)
        item.setText(_translate("MainWindow", text2, None))
        self.tableWidget.setSortingEnabled(__sortingEnabled)
        self.rows_added += 1
        self.rowCount += 1
        self.expense += value
        self.rest -= value
        self.label2.setText(
            _translate("MainWindow", "Gastos: %6.2f" % self.expense, None))
        self.label3.setText(
            _translate("MainWindow", "Resto: %6.2f" % self.rest, None))

    def buttonRejected(self):
        self.lineEdit_1.clear()
        self.lineEdit_2.clear()
        self.doubleSpinBox.setValue(0)
        self.calendarWidget.setSelectedDate(self.today)
        self.dateTimeEdit.setDate(self.today)
        self.dateTimeEdit.setTime(self.time_zero)
        item = self.tableWidget.item(0, 0)

    def save_changes(self):
        for row in range(self.rowCount - self.rows_added, self.rowCount):
            item = self.tableWidget.item(row, COL_PRODUCT)
            product = item.text()
            item = self.tableWidget.item(row, COL_PRICE)
            price = item.text()
            item = self.tableWidget.item(row, COL_DATE)
            date = item.text()
            item = self.tableWidget.item(row, COL_BUYER)
            name = item.text()
            self.db.insert_data(str(product), float(price), str(date),
                                str(name))
        self.rows_added = 0

    def addCosts(self):
        self.expense = 0
        for row in range(self.rowCount):
            item = self.tableWidget.item(row, COL_PRICE)
            self.expense += float(item.text())
        self.rest = self.salary - self.expense

    def uploadLabels(self):
        self.salary = self.db.get_salary()
        self.addCosts()
        self.label1.setText(
            _translate("MainWindow", "Inicial: %6.2f" % self.salary, None))
        self.label2.setText(
            _translate("MainWindow", "Gastos: %6.2f" % self.expense, None))
        self.label3.setText(
            _translate("MainWindow", "Resto: %6.2f" % self.rest, None))

    def changesWereSaved(self):
        return not self.rows_added > 0
Beispiel #21
0
 def query_score_page(page_no):
     range1 = page_no - 50
     range2 = page_no + 50
     query = {'book_detail.pages': {'$gte': range1, '$lte': range2}}
     cursor = Database.find_data(collection='books', query=query)
     return cursor
Beispiel #22
0
 def purchase_to_mongo(data):
     Database.insert(collection='purchase', data= data)
Beispiel #23
0
 def add_user_to_mongo(data):
     Database.insert(collection='users', data=data)
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(462, 715)
        style = "QMainWindow {background-color:" \
                " QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #616161," \
                " stop: 0.5 #505050, stop: 0.6 #434343, stop:1 #656565);}"
        MainWindow.setStyleSheet(style)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.initToolBar(MainWindow)
        self.db = Database()
        self.initCalendar()
        self.initTableWidget()
        self.initInputs()
        self.initButtons()
        self.initLabels()
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QObject.connect(self.calendarWidget, QtCore.SIGNAL(_fromUtf8("clicked(QDate)")), self.dateTimeEdit.setDate)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), self.buttonAccepted)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), self.tableWidget.scrollToBottom)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), self.buttonRejected)
        QtCore.QObject.connect(self.actionNew, QtCore.SIGNAL(_fromUtf8("triggered()")), self.action_new)
        QtCore.QObject.connect(self.actionOpen, QtCore.SIGNAL(_fromUtf8("triggered()")), self.action_open)
        QtCore.QObject.connect(self.actionSave, QtCore.SIGNAL(_fromUtf8("triggered()")), self.save_changes)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def execOpenWindow(self):
        dialog = QtGui.QDialog()
        dialog.ui = Ui_Dialog_Open()
        dialog.ui.setupUi(dialog)
        dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        dialog.exec_()
        if dialog.ui.accepted():
            db_name = dialog.ui.getNameToOpen()
            self.db = Database(db_name)
            self.uploadTable()
            self.uploadLabels()
            self.rows_added = 0

    def action_open(self):
        if self.changesWereSaved():
            self.execOpenWindow()
        else:
            dialog = QtGui.QDialog()
            dialog.ui = Ui_Dialog_SaveMsg()
            dialog.ui.setupUi(dialog)
            dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
            dialog.exec_()
            if dialog.ui.mustSave():
                self.save_changes()
            self.execOpenWindow()

    def execNewWindow(self):
        dialog = QtGui.QDialog()
        dialog.ui = Ui_Dialog_New()
        dialog.ui.setupUi(dialog)
        dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        dialog.exec_()
        if dialog.ui.accepted():
            db_name, value_init = dialog.ui.getDbNameAndValue()
            self.db = Database(db_name)
            self.db.set_salary(value_init)
            self.uploadTable()
            self.salary = self.db.get_salary()
            self.addCosts()
            self.uploadLabels()
            self.rows_added = 0

    def action_new(self):
        if self.changesWereSaved():
            self.execNewWindow()
        else:
            dialog = QtGui.QDialog()
            dialog.ui = Ui_Dialog_SaveMsg()
            dialog.ui.setupUi(dialog)
            dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
            dialog.exec_()
            if dialog.ui.mustSave():
                self.save_changes()
            self.execNewWindow()

    def initToolBar(self, MainWindow):
        self.toolBar = QtGui.QToolBar(MainWindow)
        self.toolBar.setObjectName(_fromUtf8("toolBar"))
        self.toolBar.setStyleSheet("background-color:#2E2E2E;")
        MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
        self.actionOpen = QtGui.QAction(MainWindow)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/images/open.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionOpen.setIcon(icon)
        self.actionOpen.setObjectName(_fromUtf8("actionOpen"))
        self.actionNew = QtGui.QAction(MainWindow)
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(_fromUtf8(":/images/new.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionNew.setIcon(icon1)
        self.actionNew.setObjectName(_fromUtf8("actionNew"))
        self.actionSave = QtGui.QAction(MainWindow)
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap(_fromUtf8(":/images/save.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionSave.setIcon(icon2)
        self.actionSave.setObjectName(_fromUtf8("actionSave"))
        self.toolBar.addAction(self.actionNew)
        self.toolBar.addAction(self.actionOpen)
        self.toolBar.addAction(self.actionSave)

    def initCalendar(self):
        self.calendarWidget = QtGui.QCalendarWidget(self.centralwidget)
        self.calendarWidget.setGeometry(QtCore.QRect(5, 0, 448, 180))
        self.calendarWidget.setObjectName(_fromUtf8("calendarWidget"))
        self.calendarWidget.setGridVisible(True)
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.calendarWidget.setFont(font)
        style = "background-color: #575756; padding: 1px;" \
                " border-style: solid; border: 1px solid #656565;" \
                " border-radius: 5; color: #363534;" \
                " alternate-background-color: #BDB9B5"
        self.calendarWidget.setStyleSheet(style)
        self.today = self.calendarWidget.selectedDate()

    def initTableWidget(self):
        self.tableWidget = QtGui.QTableWidget(self.centralwidget)
        self.tableWidget.setGeometry(QtCore.QRect(5, 190, 451, 370))
        self.tableWidget.setObjectName(_fromUtf8("tableWidget"))
        style = "QTableWidget {background-color:" \
                " QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1," \
                " stop: 0 #4d4d4d, stop: 0 #646464, stop: 1 #BDB9B5);" \
                " top: 5px; border: 1px solid #656565;" \
                " gridline-color: #BAB0A7} " \
                "QHeaderView::section {background-color:" \
                " QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #616161," \
                " stop: 0.5 #505050, stop: 0.6 #434343, stop:1 #656565);" \
                " color: %s; padding-left: 4px;" \
                " border: 1px solid #6c6c6c;}" \
                "QTableCornerButton::section {" \
                " background: #505050; border: 2px outset #505050;} " \
                "QScrollBar:horizontal {background:" \
                " QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1," \
                " stop: 0.0 #121212, stop: 0.2 #282828, stop: 1 #484848);} " \
                "QScrollBar::vertical {background:" \
                " QLinearGradient( x1: 1, y1: 0, x2: 1, y2: 0," \
                " stop: 0.0 #121212, stop: 0.2 #282828," \
                " stop: 1 #484848);}" % COLOR
        self.tableWidget.setStyleSheet(style)
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.tableWidget.setFont(font)
        self.rows_added = 0
        self.tableWidget.setColumnCount(4)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(COL_PRODUCT, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(COL_PRICE, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(COL_DATE, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(COL_BUYER, item)
        self.line = QtGui.QFrame(self.centralwidget)
        self.line.setGeometry(QtCore.QRect(0, 560, 451, 16))
        self.line.setFrameShape(QtGui.QFrame.HLine)
        self.line.setFrameShadow(QtGui.QFrame.Sunken)
        self.line.setObjectName(_fromUtf8("line"))
        self.line.setStyleSheet("border: 1px solid #656565")

    def initInputs(self):
        self.lineEdit_1 = QtGui.QLineEdit(self.centralwidget)
        self.lineEdit_1.setGeometry(QtCore.QRect(10, 610, 113, 27))
        self.lineEdit_1.setObjectName(_fromUtf8("lineEdit_1"))
        style = "QLineEdit {background-color:" \
                " QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1," \
                " stop: 0 #4d4d4d, stop: 0 #646464, stop: 1 #BDB9B5);" \
                " padding: 1px; border-style: solid;" \
                " border: 1px solid #656565; border-radius: 5;}"
        self.lineEdit_1.setStyleSheet(style)
        self.doubleSpinBox = QtGui.QDoubleSpinBox(self.centralwidget)
        self.doubleSpinBox.setGeometry(QtCore.QRect(130, 610, 62, 27))
        self.doubleSpinBox.setMaximum(MAXIMUM)
        self.doubleSpinBox.setObjectName(_fromUtf8("doubleSpinBox"))
        style = "QDoubleSpinBox {background-color:" \
                " QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1," \
                " stop: 0 #4d4d4d, stop: 0 #646464, stop: 1 #BDB9B5);" \
                " padding: 1px; border-style: solid;" \
                " border: 1px solid #656565; border-radius: 5;} " \
                "QDoubleSpinBox::up-button {border: 1px solid #656565;} " \
                "QDoubleSpinBox::down-button {border: 1px solid #656565;}"
        self.doubleSpinBox.setStyleSheet(style)
        self.dateTimeEdit = QtGui.QDateTimeEdit(self.centralwidget)
        self.dateTimeEdit.setGeometry(QtCore.QRect(200, 610, 131, 27))
        self.dateTimeEdit.setObjectName(_fromUtf8("dateTimeEdit"))
        style = "QDateTimeEdit {background-color:" \
                " QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1," \
                " stop: 0 #4d4d4d, stop: 0 #646464, stop: 1 #BDB9B5);" \
                " padding: 1px; border-style: solid;" \
                " border: 1px solid #656565; border-radius: 5;} " \
                "QDateTimeEdit::up-button {border: 1px solid #656565;} " \
                "QDateTimeEdit::down-button {border: 1px solid #656565;}"
        self.dateTimeEdit.setStyleSheet(style)
        self.time_zero = self.dateTimeEdit.time()
        self.lineEdit_2 = QtGui.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(340, 610, 113, 27))
        self.lineEdit_2.setObjectName(_fromUtf8("lineEdit_2"))
        style = "QLineEdit {background-color:" \
                " QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1," \
                " stop: 0 #4d4d4d, stop: 0 #646464, stop: 1 #BDB9B5);" \
                " padding: 1px; border-style: solid;" \
                " border: 1px solid #656565; border-radius: 5;}"
        self.lineEdit_2.setStyleSheet(style)

    def initButtons(self):
        self.buttonBox = QtGui.QDialogButtonBox(self.centralwidget)
        self.buttonBox.setGeometry(QtCore.QRect(280, 645, 176, 27))
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
        style = "background-color: QLinearGradient(" \
                " x1: 0, y1: 0, x2: 0, y2: 1," \
                " stop: 0 #4d4d4d, stop: 0 #646464, stop: 1 #BDB9B5);"
        self.buttonBox.setStyleSheet(style)

    def initLabels(self):
        self.label1 = QtGui.QLabel(self.centralwidget)
        self.label1.setGeometry(QtCore.QRect(10, 580, 350, 20))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label1.setFont(font)
        self.label1.setObjectName(_fromUtf8("label2"))
        self.label1.setStyleSheet("color : %s" % COLOR)
        self.label2 = QtGui.QLabel(self.centralwidget)
        self.label2.setGeometry(QtCore.QRect(160, 580, 350, 20))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label2.setFont(font)
        self.label2.setObjectName(_fromUtf8("label2"))
        self.label2.setStyleSheet("color : %s" % COLOR)
        self.label3 = QtGui.QLabel(self.centralwidget)
        self.label3.setGeometry(QtCore.QRect(310, 580, 350, 20))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label3.setFont(font)
        self.label3.setObjectName(_fromUtf8("label3"))
        self.label3.setStyleSheet("color : %s" % COLOR)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "Control de Gastos", None))
        self.setActions()
        self.setColumnName()
        self.uploadTable()
        self.uploadLabels()

    def setActions(self):
        self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar", None))
        self.actionOpen.setText(_translate("MainWindow", "&Open", None))
        self.actionOpen.setShortcut(_translate("MainWindow", "Ctrl+O", None))
        self.actionNew.setText(_translate("MainWindow", "&New", None))
        self.actionNew.setShortcut(_translate("MainWindow", "Ctrl+N", None))
        self.actionSave.setText(_translate("MainWindow", "&Save", None))
        self.actionSave.setShortcut(_translate("MainWindow", "Ctrl+S", None))

    def setColumnName(self):
        item = self.tableWidget.horizontalHeaderItem(COL_PRODUCT)
        item.setText(_translate("MainWindow", "Producto", None))
        item = self.tableWidget.horizontalHeaderItem(COL_PRICE)
        item.setText(_translate("MainWindow", "Precio", None))
        item = self.tableWidget.horizontalHeaderItem(COL_DATE)
        item.setText(_translate("MainWindow", "Fecha", None))
        item = self.tableWidget.horizontalHeaderItem(COL_BUYER)
        item.setText(_translate("MainWindow", "Comprador", None))

    def uploadTable(self):
        self.rowCount = self.db.get_row_count()
        db_products = self.db.get_products()
        db_prices = self.db.get_prices()
        db_dates = self.db.get_date()
        db_buyers = self.db.get_buyer()
        self.tableWidget.setRowCount(self.rowCount)
        for row in range(self.rowCount):
            item = QtGui.QTableWidgetItem()
            self.tableWidget.setItem(row, COL_PRODUCT, item)
            item = QtGui.QTableWidgetItem()
            self.tableWidget.setItem(row, COL_PRICE, item)
            item = QtGui.QTableWidgetItem()
            self.tableWidget.setItem(row, COL_DATE, item)
            item = QtGui.QTableWidgetItem()
            self.tableWidget.setItem(row, COL_BUYER, item)
        __sortingEnabled = self.tableWidget.isSortingEnabled()
        self.tableWidget.setSortingEnabled(False)
        for row in range(self.rowCount):
            item = self.tableWidget.item(row, COL_PRODUCT)
            item.setText(_translate("MainWindow", db_products[row], None))
            item = self.tableWidget.item(row, COL_PRICE)
            item.setText(_translate("MainWindow", db_prices[row], None))
            item = self.tableWidget.item(row, COL_DATE)
            item.setText(_translate("MainWindow", db_dates[row], None))
            item = self.tableWidget.item(row, COL_BUYER)
            item.setText(_translate("MainWindow", db_buyers[row], None))
        self.tableWidget.setSortingEnabled(__sortingEnabled)

    def buttonAccepted(self):
        self.tableWidget.insertRow(self.rowCount)
        for column in range(4):
            item = QtGui.QTableWidgetItem()
            self.tableWidget.setItem(self.rowCount, column, item)
        text1 = self.lineEdit_1.text()
        value = self.doubleSpinBox.value()
        dateTime = self.dateTimeEdit.dateTime()
        dateTime = dateTime.toString("ddd d MMM yyyy hh:mm")
        dateTime = delete_accent(dateTime)
        text2 = self.lineEdit_2.text()
        __sortingEnabled = self.tableWidget.isSortingEnabled()
        self.tableWidget.setSortingEnabled(False)
        item = self.tableWidget.item(self.rowCount, COL_PRODUCT)
        item.setText(_translate("MainWindow", text1, None))
        item = self.tableWidget.item(self.rowCount, COL_PRICE)
        item.setText(_translate("MainWindow", str(value), None))
        item = self.tableWidget.item(self.rowCount, COL_DATE)
        item.setText(_translate("MainWindow", dateTime, None))
        item = self.tableWidget.item(self.rowCount, COL_BUYER)
        item.setText(_translate("MainWindow", text2, None))
        self.tableWidget.setSortingEnabled(__sortingEnabled)
        self.rows_added += 1
        self.rowCount += 1
        self.expense += value
        self.rest -= value
        self.label2.setText(_translate("MainWindow", "Gastos: %6.2f" % self.expense, None))
        self.label3.setText(_translate("MainWindow", "Resto: %6.2f" % self.rest, None))

    def buttonRejected(self):
        self.lineEdit_1.clear()
        self.lineEdit_2.clear()
        self.doubleSpinBox.setValue(0)
        self.calendarWidget.setSelectedDate(self.today)
        self.dateTimeEdit.setDate(self.today)
        self.dateTimeEdit.setTime(self.time_zero)
        item = self.tableWidget.item(0, 0)

    def save_changes(self):
        for row in range(self.rowCount-self.rows_added, self.rowCount):
            item = self.tableWidget.item(row, COL_PRODUCT)
            product = item.text()
            item = self.tableWidget.item(row, COL_PRICE)
            price = item.text()
            item = self.tableWidget.item(row, COL_DATE)
            date = item.text()
            item = self.tableWidget.item(row, COL_BUYER)
            name = item.text()
            self.db.insert_data(str(product), float(price), str(date), str(name))
        self.rows_added = 0

    def addCosts(self):
        self.expense = 0
        for row in range(self.rowCount):
            item = self.tableWidget.item(row, COL_PRICE)
            self.expense += float(item.text())
        self.rest = self.salary - self.expense

    def uploadLabels(self):
        self.salary = self.db.get_salary()
        self.addCosts()
        self.label1.setText(_translate("MainWindow", "Inicial: %6.2f" % self.salary, None))
        self.label2.setText(_translate("MainWindow", "Gastos: %6.2f" % self.expense, None))
        self.label3.setText(_translate("MainWindow", "Resto: %6.2f" % self.rest, None))

    def changesWereSaved(self):
        return not self.rows_added > 0
Beispiel #25
0
class Main:
    """implementation of different menus"""

    def __init__(self):
        """set up attributes"""
        self.green_line = colored("-----------------------------------------", "green")
        self.red_line = colored("-----------------------------------------", "red")
        self.touch_error = colored("Pour faire une sélection. Tapez son numéro", "red")
        self.database = Database()
        self.list_product = []
        self.cat = 0
        self.sub = 0

    def main_menu(self):
        """first menu et creation of database in second choice"""
        print(self.green_line)
        print(colored("1. Utiliser application", "yellow",))
        print(colored("2. Supression/Création de la database", "magenta"))
        print(colored("0. Quitter l'application ", "red"))
        print(self.green_line)
        choice_main = input(colored("\n ---> ", "green"))
        try:
            choice_main = int(choice_main)
        except ValueError:
            choice_main = -1
        if choice_main == 1:
            self.api_menu()
        elif choice_main == 2:
            database()
            data = Database()
            request = Request()
            request.create_database(data)
            self.main_menu()
        elif choice_main == 0:
            self.bye()
        else:
            print(self.touch_error)
            self.main_menu()

    def api_menu(self):
        """second menu, use the application"""
        print(self.green_line)
        print(colored("1. Choix d'une catégorie", "yellow"))
        print(colored("2. Afficher sauvegarde", "yellow"))
        print(colored("0. Quitter le programme", "red"))
        print(self.green_line)
        choice_api = input(colored("\n ---> ", "green"))
        print(self.green_line)
        try:
            choice_api = int(choice_api)
        except ValueError:
            choice_api = -1
        if choice_api == 1:
            self.cat_menu()
        elif choice_api == 2:
            check = self.database.check_favorite()
            if check == 0:
                print(colored("*.backup is empty", "yellow"))
                print(self.green_line)
                self.api_menu()
            else:
                prod = self.database.search_favorite()
                for i, values in enumerate(prod):
                    favorite = Favorite(
                        prod[i][0], prod[i][1], prod[i][2], prod[i][3], prod[i][4],
                    )
                    print(
                        i + 1,
                        ".\t",
                        favorite.nutriscore,
                        "\t",
                        favorite.name,
                        "\n",
                        "..\t",
                        favorite.url,
                        "\n",
                        "..\t",
                        "store:",
                        favorite.market,
                        "\n",
                        "......................................",
                    )
                print(self.green_line)
                self.api_menu()
        elif choice_api == 0:
            self.bye()
        else:
            print(self.touch_error)
            self.api_menu()

    def cat_menu(self):
        """categorie's menu, choice categorie"""
        cat = self.database.search_categorie()
        for i, values in enumerate(cat):
            category = Category(cat[i][0], cat[i][1])
            print(i + 1, category.name)
        print(self.green_line)
        print(colored("Choix de la catégorie", "yellow"))
        cat = input(colored("\n ---> ", "green"))
        try:
            cat = int(cat)
        except ValueError:
            print(self.red_line)
            print(self.touch_error)
            print(self.red_line)
            self.cat_menu()
        if cat <= i + 1:
            self.prod_menu(cat, i)
        else:
            print(self.red_line)
            print(self.touch_error)
            print(self.red_line)
            self.cat_menu()

    def prod_menu(self, cat, i):
        """product menu, product choice"""
        list_nb = []
        prod = self.database.search_product(cat)
        for i, values in enumerate(prod):
            product = Product(
                prod[i][0], prod[i][1], prod[i][2], prod[i][3], prod[i][4],
            )
            print(
                i + 1, ".\t", product.nutriscore, "\t", product.name,
            )
            list_nb.append(i + 1)
        print(colored("Choix d'un produit", "yellow"))
        choice_prod = input(colored("\n ---> ", "green"))
        try:
            choice_prod = int(choice_prod)
        except ValueError:
            choice_prod != list_nb
        if choice_prod in list_nb:
            self.sub_menu(cat)
        else:
            print(self.red_line)
            print(self.touch_error)
            print(self.red_line)
            self.prod_menu(cat, i)

    def sub_menu(self, cat):
        """substitute menu, substitute choice"""
        list_nb = []
        subst = self.database.search_better_products(cat)
        for i, values in enumerate(subst):
            product = Product(
                subst[i][0], subst[i][1], subst[i][2], subst[i][3], subst[i][4],
            )
            print(
                i + 1, ".\t", product.nutriscore, "\t", product.name,
            )
            list_nb.append(i + 1)
        print(colored("Choix d'un substitut", "yellow"))
        sub = input(colored("\n ---> ", "green"))
        try:
            sub = int(sub)
        except ValueError:
            sub != list_nb
        if sub in list_nb:
            self.save_menu(cat, sub)
        else:
            print(self.touch_error)
            self.sub_menu(cat)

    def save_menu(self, cat, sub):
        """save menu, Adding substitute in the database"""
        print(colored("Voulez-vous sauvegarder: 1(Oui) 2(Non)", "yellow"))
        choice_save = input(colored("\n ---> ", "green"))
        try:
            choice_save = int(choice_save)
        except ValueError:
            choice_save = -1
        if choice_save == 1:
            try:
                self.database.save_favorite(cat, sub)
                print(self.red_line)
                print(colored("favoris enregistrer", "green"))
                print(self.red_line)
                self.main_menu()
            except mysql.connector.errors.IntegrityError:
                print(self.red_line)
                print(colored("Le favoris est déjà enregistrer", "yellow"))
                print(self.red_line)
                self.main_menu()
        elif choice_save == 2:
            self.main_menu()
        else:
            print(self.red_line)
            print(self.touch_error)
            print(self.red_line)
            self.save_menu(cat, sub)

    def bye(self):
        """say goodbye"""
        print(colored("**********************************************", "green"))
        print(colored("----------------------------------------------", "cyan"))
        print(colored("                  Au revoir !                 ", "yellow"))
        print(colored("----------------------------------------------", "cyan"))
        print(colored("**********************************************", "green"))
        quit()
Beispiel #26
0
class NeuralAI(AI):
    MaxNbNode = 100
    NbDiffOperators = 7
    OperatorParams = NbDiffOperators + 2
    NbOperators = 30
    NbTerms = NbOperators
    OpeStateSize = NbOperators + NbDiffOperators
    MaxDepth = 25
    MultExamples = 500
    MaxGameBefLearning = 50
    INIT_LR = 4 * 10 ** -6
    ModelFile = "AI/deepAIModel"
    DbName = "Database/deepaiMemory.csv"

    def __init__(self, maxInstanceIdx, secondTimeout):
        super().__init__(maxInstanceIdx, secondTimeout, name="NeuralAI")
        self._theoremName = ""
        self._theorem = ""
        # get Rule States
        self._trueRuleStates = []
        ruleStates = DarkLogic.getRuleStates()
        for ruleState in ruleStates:
            self._trueRuleStates.append(makeTrueState(ruleState))
        self._inputSize = (len(self._trueRuleStates) + 1) * NeuralAI.NbOperators * 19
        self._storeNodes = []
        self._db = Database(NeuralAI.DbName)
        self._gamesSinceLastLearning = 0
        if file_io.file_exists(NeuralAI.ModelFile):
            print("load DeepAI brain model")
            self._model = keras.models.load_model(NeuralAI.ModelFile)
        else:
            # create model
            print("create new DeepAI brain model")
            self._model = createModel(len(self._trueRuleStates) + 1)
            compileModel(self._model, NeuralAI.INIT_LR)
            self._model.save(NeuralAI.ModelFile)
        self._model = extractTestModel(self._model)
        self._modelMutex = Lock()
        self._elo = 1076  # 1418
        # self._train()

    def getTrueState(self, threadIdx):
        return [makeTrueState(DarkLogic.getState(threadIdx))] + self._trueRuleStates

    """def getTrueState(self):
        return [makeTrueState(DarkLogic.getState())] + self._trueRuleStates"""

    def setTheoremInfo(self):
        self._theoremName = DarkLogic.theoremName()
        self._theorem = DarkLogic.toNormStrTheorem()

    """
    nodeLists: 
    - type is list of list of node
    """

    def evaluate(self, nodes, trueStates):
        # evaluate states
        trueStates = np.array(trueStates)
        self._modelMutex.acquire()
        out = self._model.predict(trueStates, batch_size=len(trueStates), workers=multiprocessing.cpu_count(),
                                  use_multiprocessing=True)
        self._modelMutex.release()
        realOuts = eval(out)
        for node, realOut in zip(nodes, realOuts):
            node.setAIValue(realOut)

    def explore(self, dbNode, threadId):
        self._crtNode.exploreDeep(dbNode.actions(), threadId)

    def _train(self):
        x = []
        y = []
        print("DeepAI is preparing for training...")
        # node.getTrainNodes(x, y)
        dbStates = self._db.getDatas()
        nbExcludedTh = 0
        class_nb = {}
        for cl in range(NeuralAI.MaxDepth + 1):
            class_nb[cl] = 0
        print("Total number of theorems in database: " + str(len(dbStates)))
        dbStateIdx = -1
        remDbStates = list(dbStates.values())
        rand.shuffle(remDbStates)
        # NbMax = 200000
        NbMax = 200000
        if NbMax < len(dbStates):
            NbMaxUnevaluatedThm = NbMax - self._db.nbEvaluatedThm() if NbMax > self._db.nbEvaluatedThm() else 0
            NbMaxEvaluatedThm = NbMax - NbMaxUnevaluatedThm
        else:
            NbMaxUnevaluatedThm = len(dbStates) - self._db.nbEvaluatedThm()
            NbMaxEvaluatedThm = self._db.nbEvaluatedThm()
        print("Must select " + str(NbMaxUnevaluatedThm) + " unevaluated theorems")
        print("Must select " + str(NbMaxEvaluatedThm) + " evaluated theorems")
        NbEvaluated = 0
        NbUnevaluated = 0
        lastEvalPrint = 0
        lastUnevalPrint = 0
        for dbState in remDbStates:
            dbStateIdx += 1
            if NbEvaluated > lastEvalPrint and NbEvaluated % 10000 == 0:
                lastEvalPrint = NbEvaluated
                print(str(NbEvaluated) + " evaluated theorems have been seen")
            if NbUnevaluated > lastUnevalPrint and NbUnevaluated % 10000 == 0:
                lastUnevalPrint = NbUnevaluated
                print(str(NbUnevaluated) + " unevaluated theorems have been seen")
            DarkLogic.makeTheorem(dbState.theoremName(), dbState.theoremContent())
            state = DarkLogic.getState()
            DarkLogic.clearAll()
            if len(state.operators()) > NeuralAI.NbOperators:
                if dbState.isEvaluated() and NbMaxEvaluatedThm == self._db.nbEvaluatedThm():
                    NbMaxUnevaluatedThm += 1
                    NbMaxEvaluatedThm -= 1
                continue
            if dbState.isEvaluated():
                if NbEvaluated == NbMaxEvaluatedThm:
                    continue
                cl = dbState.value() if dbState.value() < NeuralAI.MaxDepth else NeuralAI.MaxDepth
                class_nb[cl] += 1
                l = list(range(len(self._trueRuleStates)))
                rand.shuffle(l)
                x.append([makeTrueState(state), l])
                # y.append(nthColounmOfIdentiy(cl))
                y.append(cl)
                NbEvaluated += 1
                if NbUnevaluated == NbMaxUnevaluatedThm and NbEvaluated == NbMaxEvaluatedThm:
                    break
            else:
                if NbUnevaluated == NbMaxUnevaluatedThm:
                    continue
                l = list(range(len(self._trueRuleStates)))
                rand.shuffle(l)
                x.append([makeTrueState(state), l])
                # y.append(createZeroTab(DeepAI.MaxDepth + 1))
                y.append(-1)
                NbUnevaluated += 1
                if NbUnevaluated == NbMaxUnevaluatedThm and NbEvaluated == NbMaxEvaluatedThm:
                    break

        print("Selected " + str(NbUnevaluated) + " unevaluated theorems")
        print("Selected " + str(NbEvaluated) + " evaluated theorems")

        # if we keep some examples
        if len(x):
            # check class_weight
            class_nb[-1] = 1 / NbUnevaluated
            print("Keep " + str(len(x)) + " examples")
            class_weights = {}
            for val in class_nb:
                nb_cl = class_nb[val]
                if nb_cl >= len(x) - 1:
                    print("[WARNING] Useless to train if almost all examples are from one class! Exit")
                    return
                if nb_cl != 0:
                    class_weights[val] = 1 / nb_cl
                else:
                    class_weights[val] = 0

            # shuffle examples
            print("shuffle " + str(len(x)) + " examples ...")
            randList = list(range(len(x)))
            newX = []
            newY = []
            newValues = []
            for pos in range(len(x)):
                newX.append(x[pos])
                newY.append(y[pos])
            x = newX
            y = newY
            values = newValues

            # prepare for training
            batch_size = 100
            nb_epochs = 1000
            pos = int(0.9 * len(x))
            # x = np.array(x)
            # y = np.array(y)
            values = np.array(values)
            x_train = x[:pos]
            x_test = x[pos:]
            y_train = y[:pos]
            y_test = y[pos:]
            print("training on " + str(len(x_train)) + " examples")
            # earlyStop = keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0.001, patience=20, verbose=1)
            trainBatches_x = []
            trainBatches_y = []
            testBatches_x = []
            testBatches_y = []
            batch_x = []
            batch_y = []
            # prepare train batches
            for k in range(len(x_train)):
                batch_x.append(x_train[k])
                batch_y.append(y_train[k])
                if len(batch_x) == batch_size:
                    trainBatches_x.append(batch_x)
                    batch_x = []
                    trainBatches_y.append(batch_y)
                    batch_y = []
            if len(batch_x) > 0:
                trainBatches_x.append(batch_x)
                batch_x = []
                trainBatches_y.append(batch_y)
                batch_y = []

            # prepare test batches
            for k in range(len(x_test)):
                batch_x.append(x_test[k])
                batch_y.append(y_test[k])
                if len(batch_x) == batch_size:
                    testBatches_x.append(batch_x)
                    batch_x = []
                    testBatches_y.append(batch_y)
                    batch_y = []
            if len(batch_x) > 0:
                testBatches_x.append(batch_x)
                batch_x = []
                testBatches_y.append(batch_y)
                batch_y = []

            # fit
            lr = NeuralAI.INIT_LR
            minLoss = 10 ** 100
            lastDecLoss = 0  # last epoch since loss has decreased
            # init minValLoss
            print("Validation of current model")
            if file_io.file_exists(NeuralAI.ModelFile):
                # load best model
                print("load last model")
                self._model = keras.models.load_model(NeuralAI.ModelFile)
                compileModel(self._model, lr)
            print("__________________________________________________________________________")
            crtMinValLoss, val_acc = validation(self._model, testBatches_x, testBatches_y,
                                                batch_size, class_weights, self._trueRuleStates, self._inputSize)
            print("VAL_LOSS = " + str(crtMinValLoss))
            print("VAL_ACCURACY = " + str(val_acc))
            minValLoss = 10 ** 100
            lastDecValLoss = 0  # last epoch since loss has decreased

            print("create new model")
            self._model = createModel(len(self._trueRuleStates) + 1)
            compileModel(self._model, lr)
            for epoch in range(nb_epochs):
                print("epoch n°" + str(epoch + 1) + "/" + str(nb_epochs))
                # training...
                loss, accuracy = training(self._model, trainBatches_x, trainBatches_y,
                                          batch_size, class_weights, self._trueRuleStates, self._inputSize)
                print("LOSS = " + str(loss))
                print("ACCURACY = " + str(accuracy))
                if loss < minLoss:
                    print("LOSS decreasing!")
                    minLoss = loss
                    lastDecLoss = 0
                else:
                    print("LOSS increasing!")
                    lastDecLoss += 1

                # validation...
                val_loss, val_accuracy = validation(self._model, testBatches_x, testBatches_y,
                                                    batch_size, class_weights, self._trueRuleStates, self._inputSize)
                print("VAL_LOSS = " + str(val_loss))
                print("VAL_ACCURACY = " + str(val_accuracy))
                if val_loss < minValLoss:
                    print("VAL_LOSS decreasing")
                    minValLoss = val_loss
                    lastDecValLoss = 0
                    if minValLoss < crtMinValLoss:
                        print("Improvement compared to old model!!!")
                        crtMinValLoss = minValLoss
                else:
                    print("VAL_LOSS increasing")
                    lastDecValLoss += 1

                if lastDecLoss == 3:
                    lr = lr / 10
                    print("adapt learning rate: " + str(lr))
                    compileModel(self._model, lr)
                    lastDecLoss = 0
                    minLoss = loss  # keep latest loss for minimal loss
                    print("new current minimal loss: "+str(minLoss))
                if lastDecValLoss == 10:
                    print("Early-stopping!")
                    break

                if val_loss <= crtMinValLoss:
                    print("Save model")
                    self._model.save(NeuralAI.ModelFile)
                print("_______________________________________________________________________________________")
            if file_io.file_exists(NeuralAI.ModelFile):
                # load best model
                print("load best model")
                self._model = keras.models.load_model(NeuralAI.ModelFile)
                self._model = extractTestModel(self._model)
            print("_______________________________________________________________________________________")

    def _storeCrtNode(self):
        self._storeNodes.append(self._crtNode)

    def meditate(self):
        if len(self._storeNodes) > 0:
            self._gamesSinceLastLearning += 1
            DarkLogic.makeTheorem(self._theoremName, self._theorem)
            # update if deepAI found a demonstration
            revNodes = self._storeNodes[::-1]
            if revNodes[0].value() < NeuralAI.MaxDepth:
                val = revNodes[0].value()
                for k in range(1, len(revNodes)):
                    node = revNodes[k]
                    node.setValue(val + k)
            self._db.export(self._storeNodes[0].getDbStates())
            if self._gamesSinceLastLearning == NeuralAI.MaxGameBefLearning:
                self._train()
                self._gamesSinceLastLearning = 0
            self._storeNodes.clear()
            DarkLogic.clearAll()
        super().meditate()

    def getTrainingStates(self, val, x, y):
        trueState = makeTrueState(DarkLogic.getState())
        hasToMult = True
        if val > NeuralAI.MaxDepth:
            val = NeuralAI.MaxDepth + 1
            hasToMult = False
        trueOut = nthColounmOfIdentiy(val)
        # print("shape = "+str(np.shape(trueOut)))
        mult = NeuralAI.MultExamples if hasToMult else 1
        for k in range(mult):
            crtState = [trueState]
            l = list(range(len(self._trueRuleStates)))
            rand.shuffle(l)
            for pos in l:
                crtState.append(self._trueRuleStates[pos])
            x.append(crtState)
            y.append(trueOut)

    def getBestNode(self):
        return self._crtNode.getDeepBestNode()

    def value(self):
        if self._crtNode.isAIValuated():
            return self._crtNode.aiValue()
        return self._crtNode.value()

    def canEvaluate(self, state):
        return len(state.operators()) < NeuralAI.NbOperators and len(state.terms()) < NeuralAI.NbTerms
Beispiel #27
0
 def add_to_mongo_directly(data):
     mongo_data = Database.insert(collection='books', data=data)
     return mongo_data
Beispiel #28
0
 def update_mongo_book(query, updates):
     Database.update(collection='books',
                     myquery={'isbn': int(query)},
                     updates={'$set': updates})
Beispiel #29
0
 async def on_member_join(self, ctx, member):
     Database.add_member(member.guild_id, guild.guild_id)
Beispiel #30
0
 def get_user_mongo(query):
     mongo_user = Database.find_one_data(collection='users',
                                         query={'user_id': query})
     return mongo_user
Beispiel #31
0
import sqlite3
import traceback
import sys
import os
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from decimal import Decimal

from Database.database import Database
from ParseData.parsedata import Parse

conn = sqlite3.connect("test.db")
print('opened successfully')
database = Database()
parse = Parse()
parse1 = Parse()

while (1):
    print(
        '\n1. Create table\n2. Insert data\n3. Display\n4. Drop Table\n5. Parse\n6. Store the data\n7. Plot Graph\n8. Exit\n'
    )
    ch = int(input("Enter ur choice: "))
    if (ch == 1):
        database.create_table(conn)
    elif (ch == 2):
        database.insert_into_table(conn)
    elif (ch == 3):
        database.display_data(conn)
    elif (ch == 4):
        database.drop_table(conn)