Exemple #1
0
class MainForm(QMainWindow):
    """Basic Calculator app"""
    def __init__(self):
        super(MainForm, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.btn_calculate.clicked.connect(self.calculation)

    def calculation(self):
        result = ""

        for i in range(4):
            if i == 0:
                result += str(
                    int(self.ui.num1_input.text()) +
                    int(self.ui.num2_input.text())) + "\n"
            if i == 1:
                result += str(
                    int(self.ui.num1_input.text()) -
                    int(self.ui.num2_input.text())) + "\n"
            if i == 2:
                result += str(
                    int(self.ui.num1_input.text()) *
                    int(self.ui.num2_input.text())) + "\n"
            if i == 3:
                result += str(
                    int(self.ui.num1_input.text()) /
                    int(self.ui.num2_input.text())) + "\n"

            self.ui.result_show.setText(result)
Exemple #2
0
class mywindow(QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pushButton.clicked.connect(self.formatString)
        self.ui.SortWordInLineCheckBox.clicked.connect(self.ChangeWidgetState)

    def ChangeWidgetState(self):
        self.ui.widget.setEnabled(
            bool(self.ui.SortWordInLineCheckBox.isChecked()))

    def formatString(self):
        strFmt = StringFormatter(self.ui.InputLineEdit.text())

        if self.ui.DeleteWordShortestThanCheckBox.isChecked():
            strFmt.DeleteWordsShortestThat(self.ui.spinBox.value())

        if self.ui.ExchangeSymbolsCheckBox.isChecked():
            strFmt.MaskDecimal()

        if self.ui.InsertWhitespaceCheckBox.isChecked():
            strFmt.InsertWhiteSpace()

        if self.ui.SortWordInLineCheckBox.isChecked():
            if self.ui.radioButtonSortBySize.isChecked():
                strFmt.SortWordBySize()

            if self.ui.radioButtonSortByLexicographic.isChecked():
                strFmt.SortLexycographic()

        self.ui.OutputLineEdit.setText(strFmt.getText())
Exemple #3
0
class MainWindow(QMainWindow):
    u"""Entire gui stuff goes here."""
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pushButton_1.clicked.connect(
            lambda name: self.get_directory_name(self.ui.lineEdit_1
                                                 ))  # Diamond Edition Exe
        self.ui.pushButton_2.clicked.connect(
            lambda name: self.get_directory_name(
                self.ui.lineEdit_2))  # Local directory for diamond
        self.ui.pushButton_3.clicked.connect(
            lambda name: self.get_directory_name(self.ui.lineEdit_3))  # EE exe
        self.ui.pushButton_4.clicked.connect(
            lambda name: self.get_directory_name(self.ui.lineEdit_4
                                                 ))  # Local directory for EE
        self.ui.pushButton_5.clicked.connect(
            lambda name: self.get_directory_name(self.ui.lineEdit_5
                                                 ))  # NWNTool dir

    def get_directory_name(self, placeholder):
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.FileMode.Directory)
        path = dialog.getExistingDirectory(self, "Select Directory")
        placeholder.setText(path)
        logger.debug(f"Set Text {path} for {placeholder}")
Exemple #4
0
class MainWindow_main(QMainWindow):
    def __init__(self):
        super(MainWindow_main, self).__init__()
        self.ui = Ui_MainWindow_main()
        self.ui.setupUi(self)
        self.stock = None
        self.portfolio = None
        self.initUI()

    def initUI(self):
        self.ui.button_stocks.clicked.connect(self.stocks)
        self.ui.button_portfolio.clicked.connect(self.portfolio_fun)

    def stocks(self):
        self.stock = Stocks()
        self.stock.setWindowTitle("Stocker")
        self.stock.setWindowIcon(QtGui.QIcon("images\portfolio.png"))
        self.stock.show()
        self.close()

    def portfolio_fun(self):
        self.portfolio = Portfolio()
        self.portfolio.setWindowTitle("Stocker")
        self.portfolio.setWindowIcon(QtGui.QIcon("images\portfolio.png"))
        self.portfolio.show()
        self.close()
Exemple #5
0
class Editor(QtGui.QMainWindow):

    def __init__(self):
        super(Editor, self).__init__()
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.show()
Exemple #6
0
class query_window(QtWidgets.QMainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.loginButton.clicked.connect(self.query_formula)
        # 给button 的 点击动作绑定一个事件处理函数
        self.ui.lineEdit_2.returnPressed.connect(self.log_returnPressed)

    def query_formula(self):
        # 此处编写具体的业务逻辑
        self.login()

    def log_returnPressed(self):
        self.login()

    def login(self):
        name = self.ui.lineEdit.text()
        passwd = self.ui.lineEdit_2.text()
        # if name == "admin" and passwd == "admin":
        if 1 == 1:
            QMessageBox.information(self, '密码正确', '点击确认进去软件')
            win_main.show()
            self.close()

        else:
            QMessageBox.critical(self, '错误', '用户名或密码错误')
Exemple #7
0
class Login(QMainWindow):
    """Dialog."""

    def __init__(self, parent=None):
        QMainWindow.__init__(self)
        self.main_ui = Ui_MainWindow()
        self.main_ui.setupUi(self)
Exemple #8
0
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.connectSignalsAndSlots()
        self.show()

    def initUI(self):
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)


# pushButton, pushButton_2, pushButton_3, pushButton_4, label_3, lcdNumber_2, label_2

    def connectSignalsAndSlots(self):
        self.ui.pushButton.clicked.connect(self.onClicked(self.ui.pushButton))
        self.ui.pushButton_2.clicked.connect(
            self.onClicked(self.ui.pushButton_2))
        self.ui.pushButton_3.clicked.connect(
            self.onClicked(self.ui.pushButton_3))
        self.ui.pushButton_4.clicked.connect(
            self.onClicked(self.ui.pushButton_4))

    def onClicked(self, button):
        pass
Exemple #9
0
class Mainwindow(QMainWindow):
    def __init__(self):
        #Iniciar el objeto QMainWindow
        QMainWindow.__init__(self)
        self.obj_form_main = Ui_MainWindow()
        self.obj_form_main.setupUi(self)
        self.obj_form_main.actionALTA_ASOCIADO.triggered.connect(
            self.ALTA_ASOCIADO)
        self.obj_form_main.actionACTUALIZACI_N_ASOCIADO.triggered.connect(
            self.ACTUALIZACI_N_ASOCIADO)
        self.obj_form_main.actionMOVIMIENTOS.triggered.connect(
            self.MOVIMIENTOS)
        self.obj_form_main.actionALTA_COOPERATIVA.triggered.connect(
            self.ALTA_COOPERATIVA)
        self.obj_form_main.actionC_A.triggered.connect(self.nomina_cargos)
        self.obj_form_main.actionACTAS.triggered.connect(self.ACTAS)
        self.obj_form_main.boton_modulo_asociados.clicked.connect(
            self.ALTA_ASOCIADO)
        self.obj_form_main.boton_modulo_capital.clicked.connect(
            self.ACTUALIZACI_N_ASOCIADO)
        self.obj_form_main.boton_modulo_contable.clicked.connect(
            self.MOVIMIENTOS)
        self.obj_form_main.boton_modulo_coope.clicked.connect(
            self.ALTA_COOPERATIVA)
        self.obj_form_main.boton_modulo_notas.clicked.connect(self.ACTAS)
        self.obj_form_main.boton_modulo_cargos.clicked.connect(
            self.nomina_cargos)
        self.obj_form_main.actionLISTA_DE_ASOCIADOS.triggered.connect(
            self.LISTA_DE_ASOCIADOS)

    def LISTA_DE_ASOCIADOS(self):
        self.obj_reporte_asoc = reporte_asoc()
        self.obj_reporte_asoc.show()

    def ACTAS(self):
        self.notas = notas()
        self.notas.show()

    def nomina_cargos(self):
        self.nomina_cargos = nomina_cargos()
        self.nomina_cargos.show()

    def ALTA_COOPERATIVA(self):
        self.cooperativa_alta = cooperativa_alta()
        self.cooperativa_alta.show()

    def MOVIMIENTOS(self):
        self.form_movimientos = movimientos()
        self.form_movimientos.show()

    def ALTA_ASOCIADO(self):

        self.form_asociado_alta = asociado_alta()
        self.form_asociado_alta.show()

    def ACTUALIZACI_N_ASOCIADO(self):

        self.form_creditos_refinanciar = asociado_actualizar()
        self.form_creditos_refinanciar.show()
Exemple #10
0
class mainwindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mainwindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        ser = scom.spopen()
        if (ser == 0):
            print("fail")
        else:
            self.ui.button_C_0.clicked.connect(lambda: myslot.btn_C_0_clicked(
                ser, self.ui.button_C_0.isChecked()))
            self.ui.button_C_1.clicked.connect(lambda: myslot.btn_C_1_clicked(
                ser, self.ui.button_C_1.isChecked()))
        # self.ui.button_C_2.clicked.connect(myslot.btn_C_2_clicked(ser))
        # self.ui.button_C_3.clicked.connect(myslot.btn_C_3_clicked(ser))
        # self.ui.button_C_4.clicked.connect(myslot.btn_C_4_clicked(ser))
        # self.ui.button_C_5.clicked.connect(myslot.btn_C_5_clicked(ser))
        # self.ui.button_C_6.clicked.connect(myslot.btn_C_6_clicked(ser))
        # self.ui.button_C_7.clicked.connect(myslot.btn_C_7_clicked(ser))
        # self.ui.button_C_8.clicked.connect(myslot.btn_C_8_clicked(ser))
        # self.ui.button_C_9.clicked.connect(myslot.btn_C_9_clicked(ser))

        # self.timer = QTimer(self)
        # self.timer.timeout.connect(lambda : self.update(ser))
        # self.timer.start(100)
        # self.update(ser)

        self.update = updateThread(ser)
        self.update.start()
        self.update.trigger.connect(self.updateSwitch)

        self.switchTable = {
            "C": [
                self.ui.button_C_0, self.ui.button_C_1, self.ui.button_C_2,
                self.ui.button_C_3, self.ui.button_C_4, self.ui.button_C_5,
                self.ui.button_C_6, self.ui.button_C_7, self.ui.button_C_8,
                self.ui.button_C_9
            ]
        }

    # def update(self, ser):
    #     data = ser.read(10)
    #     if data != b'':
    #         print('receive data is :', data)
    # QtWidgets.QApplication.processEvents()

    def updateSwitch(self, report):
        print(report)
        portNum = int(report[1])
        portState = int(report[2])
        switch = self.switchTable[report[0]][portNum]
        print(switch.isChecked())
        if (report[2] == '0'):
            if (not switch.isChecked()):
                switch.toggle()
        if (report[2] == '1'):
            if (switch.isChecked()):
                switch.toggle()
Exemple #11
0
class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(ApplicationWindow, self).__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.label.setFont(QtGui.QFont('SansSerif',
                                          30))  # change font type and size

        self.ui.pushButton.clicked.connect(
            self.btnClicked
        )  # connecting the clicked signal with btnClicked slot
        # self.ui.pushButton_2.clicked.connect(self.close) # connecting the clicked signal with btnClicked slot
        self.ui.pushButton_2.clicked.connect(
            self.btnsolve
        )  # connecting the clicked signal with btnClicked slot

        self._createDisplay()

    def _createDisplay(self):
        """Create the display."""
        # Create the display widget
        self.btnClicked()

        # Add the display to the general layout
        # self.ui.generalLayout.addWidget(self.display)
    def btnClicked(self):

        for i in range(81):
            self.ui.block[i].setText(".")

    def btnsolve(self):

        question = [[".", ".", ".", ".", ".", ".", ".", ".", "."],
                    [".", ".", ".", ".", ".", ".", ".", ".", "."],
                    [".", ".", ".", ".", ".", ".", ".", ".", "."],
                    [".", ".", ".", ".", ".", ".", ".", ".", "."],
                    [".", ".", ".", ".", ".", ".", ".", ".", "."],
                    [".", ".", ".", ".", ".", ".", ".", ".", "."],
                    [".", ".", ".", ".", ".", ".", ".", ".", "."],
                    [".", ".", ".", ".", ".", ".", ".", ".", "."],
                    [".", ".", ".", ".", ".", ".", ".", ".", "."]]
        x = 0
        y = 0
        for i in range(81):
            x = (i % 9)
            y = (i // 9)
            question[y][x] = self.ui.block[i].text()

        s = Solution()

        s.solveSudoku(question)

        for i in range(81):
            x = (i % 9)
            y = (i // 9)
            self.ui.block[i].setText(question[y][x])
class MyWin(QtWidgets.QMainWindow):
    tray_icon = None
    curProp = None
    acceptSignal = pyqtSignal(properties.Properties)

    # construct window
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.curProp = properties.load()

        self.ui.sizeSpinBox.setValue(self.curProp.size)
        self.ui.mailLineEdit.setText(self.curProp.address)
        self.ui.modeCheckBox.setChecked(self.curProp.silenceMode)

        self.ui.okButton.clicked.connect(self.accept)
        self.ui.cancelButton.clicked.connect(self.canceled)

        #self.tray_icon = QSystemTrayIcon(self)
        #self.tray_icon.setIcon(QIcon(os.getcwd() + "/tray.png"))#QQQQQ
        #show_action = QAction("Show", self)
        #quit_action = QAction("Exit", self)
        #hide_action = QAction("Hide", self)
        #show_action.triggered.connect(self.show)
        #hide_action.triggered.connect(self.hide)
        #quit_action.triggered.connect(qApp.quit)
        #tray_menu = QMenu()
        #tray_menu.addAction(show_action)
        #tray_menu.addAction(hide_action)
        #tray_menu.addAction(quit_action)
        #self.tray_icon.setContextMenu(tray_menu)
        #self.tray_icon.show()
        #self.hide()QQQ

    def accept(self):
        cur = properties.Properties(self.ui.modeCheckBox.isChecked(),
                                    self.ui.mailLineEdit.text(),
                                    self.ui.sizeSpinBox.value())
        self.acceptSignal.emit(cur)
        self.curProp = cur
        self.refresh()
        self.hide()

    def canceled(self):
        self.hide()

    def refresh(self):
        self.ui.sizeSpinBox.setValue(self.curProp.size)
        self.ui.mailLineEdit.setText(self.curProp.address)
        self.ui.modeCheckBox.setChecked(self.curProp.silenceMode)

    def closeEvent(self, QCloseEvent):
        QCloseEvent.ignore()
        self.hide()  #QQQQ
Exemple #13
0
class AppWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.show()


    def main_text_replace(self, string):
        self.ui.textEdit.setText(string)
Exemple #14
0
class ControlMainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(ControlMainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.exit_button.clicked.connect(self.CloseProgram)

    @QtCore.Slot()
    def CloseProgram(self):
        sys.exit()
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

    def resizeEvent(self, event):
        x = self.size().width()
        y = self.size().height()

        self.ui.verticalLayoutWidget.resize(x - 50, y - 50)
Exemple #16
0
class gui_does(QtGui.QMainWindow):
   def __init__(self):
      QtGui.QMainWindow.__init__(self)
      self.ui = Ui_MainWindow()
      self.ui.setupUi(self)

	   self.setWindowTitle('To-SSH Droplet')
	   # to accept drops
      self.setAcceptDrops(True) 
	   self.ui.lineEdit.setText("/home/wishi/")
	   self.statusBar().showMessage('Ready')
Exemple #17
0
 def setupUi(self, MainWindow):
     Ui_MainWindow.setupUi(self, MainWindow)
     self.tracksLayout = self.verticalLayout_6
     self.connect_signals_slots()
     self.lasso = LassoManager(self.plotWidget.figure.canvas)
     self.lasso.add_listener(self)
     # analysis form
     self.analysis_widget = QtWidgets.QDockWidget(MainWindow)
     self.analysis_form = analysis_form()
     self.analysis_form.setupUi(self.analysis_widget)
     MainWindow.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.analysis_widget)
     self.analysis_widget.hide()
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, app):
        super().__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.actionSetting.triggered.connect(self.show_setting_dialog)

    def show_setting_dialog(self):
        plane_text, result = SettingDialog(self).plane_text()
        if result:
            self.ui.textBrowser.setPlainText(plane_text)
Exemple #19
0
class ScriptRunnerMainWindow(QtGui.QMainWindow):
    """
    This class initializes the main window for Script Runner
    """

    def __init__(self):
        """
        Set up the user interface from Designer.
        """
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
Exemple #20
0
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.model = Model(self)
        self.model.column = 100

        self.ui.tableView.setModel(self.model)
        self.ui.tableView.setItemDelegate(Delegate())
        self.ui.tableView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.ui.tableView.customContextMenuRequested.connect(self.contextMenu)
        self.ui.pushButton.clicked.connect(self.insertRow)
        self.ui.pushButton_2.clicked.connect(self.delItem)

    def contextMenu(self, point):
        self.menu = QtWidgets.QMenu(self)
        self.menu.addAction('Insert', self.insertRow)
        self.menu.addAction('Delete', self.delItem)
        self.menu.exec_( self.focusWidget().mapToGlobal(point) )
 
    def insertRow(self):
        indexes = self.ui.tableView.selectedIndexes()
        
        if len(indexes) == 0:
            item = [ str(self.model.rowCount()) + str(i) for i in range(self.model.column) ]
            self.model.addItem( self.model.rowCount(), item )
            return
        
        indexes2 = []
        for index in indexes[::-1]:
            if not index.row() in [ index2.row() for index2 in indexes2 ]:
                indexes2.append(index)

        for index in indexes2:
            item = [ str(self.model.rowCount()) + str(i) for i in range(self.model.column) ]
            self.model.addItem( index.row() + 1, item )

    def delItem(self):
        indexes = self.ui.tableView.selectedIndexes()
        
        if self.model.rowCount() == 0:
            return

        if len(indexes) == 0:
            self.model.removeItem( self.model.rowCount()-1 )
            return
        
        rows = set( [ index.row() for index in indexes ] )
        for row in list(rows)[::-1]:
            self.model.removeItem( row )
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self._numScheduledScalings = 0
        self.ui.graphicsView.wheelEvent = self.wheelEvent

    def exec_context_menu(self, point):
        self.menu = QtWidgets.QMenu(self)
        self.menu.addAction('Close', self.close)
        self.menu.exec( self.focusWidget().mapToGlobal(point) )

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls() and len(event.mimeData().urls()) == 1:
            event.accept()
            return
        event.ignore()

    def dropEvent(self, event):
        event.accept()
        path = event.mimeData().urls()[0]
        pixmap = QtGui.QPixmap(path.toLocalFile())
        pixmap_item = QtWidgets.QGraphicsPixmapItem(pixmap)
        pixmap_item.setFlags(QtWidgets.QGraphicsItem.ItemIsMovable)
        scene = QtWidgets.QGraphicsScene(self)
        scene.addItem(pixmap_item)
        self.ui.graphicsView.setScene(scene)
        self.ui.graphicsView.scale(1.0, 1.0)

    def wheelEvent(self, event):
        numDegrees = event.angleDelta().y() / 8
        numSteps = numDegrees / 15
        self._numScheduledScalings += numSteps
        if self._numScheduledScalings * numSteps < 0:
            self._numScheduledScalings = numSteps
        anim = QtCore.QTimeLine(350, self)
        anim.setUpdateInterval(20)
        anim.valueChanged.connect(self.scalingTime)
        anim.finished.connect(self.animFinished)
        anim.start()

    def scalingTime(self, x):
        factor = 1.0 + float(self._numScheduledScalings) / 300.0
        self.ui.graphicsView.scale(factor, factor)

    def animFinished(self):
        if self._numScheduledScalings > 0:
            self._numScheduledScalings -= 1
        else:
            self._numScheduledScalings += 1
Exemple #22
0
class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()        
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.Init()
    
    def Init(self):
        self.ui.pushButton.clicked.connect(self.close)
        
    

        
        
Exemple #23
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.value = 0
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.btnClicker.clicked.connect(self.inc)

    def text(self):
        return f"You clicked {self.value} times"

    def inc(self):
        self.value += 1
        self.ui.label.setText(self.text())
Exemple #24
0
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # print available styles
        print(QtWidgets.QStyleFactory.keys())

        # Signals
        self.ui.my_button.clicked.connect(self.test)

    def test(self):
        print("test!")
Exemple #25
0
class ClientWindow(QtGui.QMainWindow):
    Image = 'kukeliku.png'
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.firstCard.setPixmap(QtGui.QPixmap(self.Image))

        self.ui.firstCard = NewLabel(self)
        self.ui.firstCard.move(0,0)
        QtCore.QObject.connect(self.ui.firstCard, QtCore.SIGNAL("clicked()"), self.fix)

    def fix(self):
        self.ui.label.setText('Suck it')
Exemple #26
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.actionQuit.triggered.connect(QtCore.QCoreApplication.instance().quit)
        self.ui.pkgList.itemClicked.connect(self._showPackageDetail)
        self.ui.installedBtn.clicked.connect(self._showInstalled)
        self.ui.availableBtn.clicked.connect(self._showAvailable)
        self.ui.karmaWidget.hide()
        #menu = QtGui.QMenu(self)
        #menu.addAction("Description")
        #menu.addAction("Comments")
        #menu.addAction("Related packages")
        #menu.addAction("Test cases")
        #menu.activated.connect(self._showPage)
        #self.ui.moreBtn.setMenu(menu)

    def _showInstalled(self):
        self.ui.availableBtn.setChecked(False)

    def _showAvailable(self):
        self.ui.installedBtn.setChecked(False)

    def _switchView(self, n):
        if not self.ui.pkgDetailWidget.isHidden():
            if n == -10: # XXX weird values
                self.ui.karmaWidget.show()
            elif n == -11:
                self.ui.karmaWidget.hide()

    #def _showPage(self, n):
        # TODO setCurrentIndex
    #    self.ui.descPage.hide()
    #    self.ui.commentPage.hide()
    #    self.ui.relatedPkgPage.hide()
    #    self.ui.testCasePage.hide()
    #    pages = {-5:self.ui.descPage, -6:self.ui.commentPage, -7:self.ui.relatedPkgPage, -8:self.ui.testCasePage} # XXX weird values
    #    pages[n].show() # XXX KeyError

    def _showPackageDetail(self, item):
        if self.ui.installedBtn.isChecked():
            self.ui.karmaWidget.show()
        else:
            self.ui.karmaWidget.hide()

        self._setData(item)

    def _setData(self, item):
        self.ui.pkgNameLabel.setText(item.text())
Exemple #27
0
class MyWindowClass(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        QtCore.QObject.connect(self.ui.StartButton, QtCore.SIGNAL('clicked()'), self.doFitting)
        QtCore.QObject.connect(self.ui.fileDialog, QtCore.SIGNAL('clicked()'), self.showFileInput)
        
    

    def doFitting(self):
        #t = np.arange(1.0, 5.0, 0.01)
        #s = np.sin(2*np.pi*t)
        #self.ui.xplot.canvas.ax.plot(t, s)
        #self.ui.xplot.canvas.draw()

        filename = self.ui.fileOutput.toPlainText()
        self.ui.FitResultsSummary.setPlainText("These are fitting results")
        self.ui.ErrorMessages.setPlainText("")
        try: 
            data = file1.make_numpyarray(filename)
        except:
            self.ui.ErrorMessages.setPlainText("Something went wrong with fitting")
            return None
        fit1 = file1.fit_axis(data,0)
        report = fit_report(fit1[2])
        self.ui.FitResultsSummary.append(report)
        
        # rotating by 90 degrees on the other axis doesn't work well yet
        #t = np.arange(1.0, 5.0, 0.01)
        #s = np.sin(2*np.pi*t)
        #self.myplot = self.ui.yplot.canvas.ax.plot(t, s)
        #self.rotated = ndimage.rotate(self.myplot,90)
        #self.rotated.draw()

        self.ui.BeamDisplay.canvas.ax.pcolorfast(data)
        self.ui.BeamDisplay.canvas.draw()

    def showFileInput(self):

        fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file', 
                '/home/Oleksiy/Desktop/PythonCode')
        self.ui.fileOutput.setText(fname)



    def keyPressEvent(self, e):
        
        if e.key() == QtCore.Qt.Key_Escape:
            self.close()
Exemple #28
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Monospace fonts setzen
        font =  QtGui.QFont("Monospace");
        font.setStyleHint(QtGui.QFont.TypeWriter);
        self.ui.codeEdit.setFont(font);
        self.ui.syntaxTreeEdit.setFont(font);
        self.ui.binaryEdit.setFont(font);
        self.ui.assemblyEdit.setFont(font);

    def compileAction(self):
        # Editoren loeschen
        self.ui.syntaxTreeEdit.document().setPlainText("")
        self.ui.binaryEdit.document().setPlainText("")
        self.ui.assemblyEdit.document().setPlainText("")

        # Syntax Baum generieren
        text = clear_comments(self.ui.codeEdit.toPlainText())
        self.ui.codeEdit.document().setPlainText(text)
        parser = c_parser.CParser()
        try:
            ast = parser.parse(text, filename='')
        except:
            self.ui.syntaxTreeEdit.document().setPlainText("Fehler beim Uebersetzen")
            return

        # Syntax grob ueberpruefen
        synv = SyntaxVisitor(self.ui.syntaxTreeEdit)
        synv.visit(ast)

        # Syntax Baum laden, wenn keine Fehler angezeigt wurden
        if self.ui.syntaxTreeEdit.toPlainText() == "":
            stream = StringIO.StringIO()
            ast.ext[0].show(buf=stream)
            self.ui.syntaxTreeEdit.document().setPlainText(stream.getvalue() + "\n")
            stream.close()

            # Syntax Baum zu Binaercode uebersetzen
            asmv = AssemblyVisitor(self.ui.syntaxTreeEdit)
            asmv.visit(ast)
            asmv.finish()
            # Assembly anzeigen (mit Kommentaren)
            self.ui.assemblyEdit.document().setPlainText(asmv.assembly())
            # Binaercode anzeigen (mit Kommentaren)
            self.ui.binaryEdit.document().setPlainText(asmv.binary())
Exemple #29
0
class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.systemInformation()
    
    def systemInformation(self):
        subprocess.call('ps -ef > processlist.txt', shell=True)

       
        with open('processlist.txt', 'r') as processList:
            lines = processList.read().split('\n')
            
            firstLine = lines[0].split()[::-1]
            
            model = QtGui.QStandardItemModel(2,3,self)
          
            increment = 0
            first = True
            for line in lines:
                
                line = line.split()
                fullCMD = ''
                size = len(line)
                incrementor = 7
                while incrementor < size:
                    fullCMD = fullCMD + ' ' + line.pop(-1)
                    incrementor = incrementor + 1
                
                line.append(fullCMD)
                
                line = line[::-1]
                
                columnIncrement = 0
                for column in line:
                    if first:
                        model.setHorizontalHeaderItem(columnIncrement, QtGui.QStandardItem(column))
                    else:
                        model.setItem(increment, columnIncrement, QtGui.QStandardItem(column))
                    
                    columnIncrement = columnIncrement + 1
                
                if first:
                    first = False
                else:
                    increment = increment + 1
 
            self.ui.tableView.setModel(model)
Exemple #30
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.threadclass = ThreadClass()
        self.threadclass.setWindow(self)
        self.threadclass.start()

        self.c = Communicate()
        self.c.updateCpu.connect(self.update_cpu_usage)

    def update_cpu_usage(self, val):
        self.ui.progressBar.setValue(val)
Exemple #31
0
class Main(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.loadVidButton.clicked.connect(self.open_file)

    def open_file(self):
        options = QtWidgets.QFileDialog.Options()
        options |= QtWidgets.QFileDialog.DontUseNativeDialog
        fname, _filter = QtWidgets.QFileDialog.getOpenFileName(
            self, "Open File", '.', "(*.mp4 *.mpg *.mkv *.avi)")
        if fname:
            self.ui.file_path = fname
            self.ui.setFilePathLabel(fname)
Exemple #32
0
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

    def button_clicked(self):
        self.set_text(self.ui.pushButton.text())

    def set_text(self, text):
        self.ui.textBrowser.setText(text)
        childTextBrowser = self.ui.dockWidget.findChild(QtWidgets.QTextBrowser)
        childTextBrowser.setText(text)
        childTextBrowser = self.ui.dockWidget_2.findChild(
            QtWidgets.QTextBrowser)
        childTextBrowser.setText(text)
Exemple #33
0
class QmyMaindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self._ui = Ui_MainWindow()
        self._ui.setupUi(self)
        self.__Build()

    def __Build(self):
        self.model = QFileSystemModel(self)
        print(QDir.currentPath())
        self.model.setRootPath('')
        self._ui.treeView.setModel(self.model)
        self._ui.listView.setModel(self.model)
        self._ui.tableView.setModel(self.model)
        self._ui.treeView.clicked.connect(self._ui.listView.setRootIndex)
        self._ui.treeView.clicked.connect(self._ui.tableView.setRootIndex)
Exemple #34
0
class QTTest(QMainWindow):
    def __init__(self, pandaCallback):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #fills widget with found models on dataset folder
        self.fillPool()

        self.setWidgetEvents()

        # this basically creates an idle task
        self.timer = QTimer(self)
        self.connect(self.timer, SIGNAL("timeout()"), pandaCallback)
        self.timer.start(0)

        self.tp = TerrainPool(self.ui.terrainPool, self.ui.createTerrainButton,
                              self.ui.modifyTerrainButton)

        self.ui.actionPPL.triggered.connect(
            myEventHandler.togglePerPixelLighting)
        self.ui.actionAmbientOcclusion.triggered.connect(
            myEventHandler.toggleAmbientOcclusion)
        self.ui.actionToonShading.triggered.connect(
            myEventHandler.toggleToonShading)

    def setWidgetEvents(self):
        self.ui.eggPool.itemDoubleClicked.connect(self.sendNewModel)
        self.ui.treeWidget.itemDoubleClicked.connect(self.toolTriggered)

    '''
	gui requests will be broadcasted
	'''

    def toolTriggered(self, item, column):
        print "broadcasting: ", item.text(0)
        messenger.send(item.text(0).__str__())

    def fillPool(self):
        self.ui.eggPool.clear()
        files = Utilities.getFilesIn("dataset")
        for e in files:
            self.ui.eggPool.addItem(e)

    def sendNewModel(self, item):
        filepath = str(item.text())  #casting due to compatibility issues
        messenger.send("addobject", [filepath])
Exemple #35
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pushButton.clicked.connect(self.updateText)
        self.setStyleSheet(open('Obit.qss').read())

    def updateText(self):
        #should really be using default values...
        start = self.ui.StartNumberEdit.text()
        end = self.ui.EndNumberEdit.text()
        length = self.ui.WordCountEdit.text()

        word = self.ui.ChosenWordEdit.text()

        #makes sure input is valid
        if (not (start == "" or end == "")):
            immortaltext = scourFrom(int(start), int(end))
        else:
            immortaltext = scour(10)

        immortaltext = immortaltext.lower()
        immortaltext = stripPunctuation(immortaltext)

        mark = markov()

        dist = mark.addText(immortaltext)
        if (not mark.wordInside(word)):
            word = mark.randomWord()

        #makes sure length is valid
        if (length == ""):
            length = 100
        else:
            length = int(length)

        sentence = ""

        # builds me a sentence with 100 words in it
        for x in range(length):
            sentence += word + " "
            word = mark.nextWord(word)

        print(sentence)
        self.ui.textBrowser.setText(sentence)
Exemple #36
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pushButton.clicked.connect(self.button_pushed)

        self.manager = TdPManager()
        self.manager.estrazione()
        self.simulation = Simulation(self.manager.corrono,
                                     self.ui.graphicsView, self.ui.pushButton2,
                                     self.ui.verticalSlider)

    def button_pushed(self):
        self.simulation.start = True
        self.simulation.run()
Exemple #37
0
class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(ApplicationWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

    def run_gui(self):
        self.startButton.clicked.connect(self.run_camera)
        self.detectButton.clicked.connect(self.run_model)

    #self.resultButton.clicked.connect(self.get_result)

    def run_camera(self):
        store_images()

    def run_model(self):
        model()
Exemple #38
0
class webwindow(QtWidgets.QMainWindow):
    """
        Class that is derived from the mainWindow.ui file
        which defines the browser window.
    """
    def __init__(self, parent=None):
        """
            Web browser constructor.
            Sets the event handlers, as well as loading the UI
            from the mainWindow.ui file.
        """
        super(webwindow, self).__init__(parent)
        self.ui = Ui_MainWindow()  # define the UI
        self.ui.setupUi(self)

        homeurl = "http://www.google.com"
        self.ui.lineEdit.setText(homeurl)  # set the homepage

        #load the home page after
        self.ui.webView.setUrl(QtCore.QUrl(homeurl))

        # tell the browser we want to handle the link clicking ourselves
        self.ui.webView.page().setLinkDelegationPolicy(QtWebKitWidgets.QWebPage.DelegateAllLinks)

        # hook up the url bar to RETURN KEYPRESS and GO button
        self.ui.pushButton.clicked.connect(self.change_page)
        self.ui.lineEdit.returnPressed.connect(self.change_page)
        self.ui.webView.linkClicked.connect(self.clicked_link)

    def change_page(self):
        """
            Change page event handler (what happens when the html page changes)
        """
        url = self.ui.lineEdit.text()
        print(url)
        self.ui.webView.setUrl(QtCore.QUrl(url))

    def clicked_link(self, url):
        """
            Overrides the original clickedlink handler
        """
        self.ui.webView.setUrl(QtCore.QUrl(url))
        self.ui.lineEdit.clear()
        self.ui.lineEdit.insert(url.toString())
        self.ui.lineEdit.home(False)
class QTTest(QMainWindow): 
	def __init__(self,pandaCallback): 
		QMainWindow.__init__(self)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		
		#fills widget with found models on dataset folder
		self.fillPool()
		
		self.setWidgetEvents()
		
		# this basically creates an idle task
		self.timer = QTimer(self)
		self.connect( self.timer, SIGNAL("timeout()"), pandaCallback )
		self.timer.start(0)
		
		self.tp = TerrainPool(self.ui.terrainPool, self.ui.createTerrainButton, self.ui.modifyTerrainButton)
		
		self.ui.actionPPL.triggered.connect(myEventHandler.togglePerPixelLighting)
		self.ui.actionAmbientOcclusion.triggered.connect(myEventHandler.toggleAmbientOcclusion)
		self.ui.actionToonShading.triggered.connect(myEventHandler.toggleToonShading)
		
	def setWidgetEvents(self):
		self.ui.eggPool.itemDoubleClicked.connect(self.sendNewModel)
		self.ui.treeWidget.itemDoubleClicked.connect(self.toolTriggered)
	
	'''
	gui requests will be broadcasted
	'''
	def toolTriggered(self, item, column):
		print "broadcasting: ", item.text(0)
		messenger.send(item.text(0).__str__())
	
	def fillPool(self):
		self.ui.eggPool.clear()
		files = Utilities.getFilesIn("dataset")
		for e in files:
			self.ui.eggPool.addItem(e)
	
	def sendNewModel(self,item):
		filepath = str(item.text())  #casting due to compatibility issues
		messenger.send("addobject", [filepath])
Exemple #40
0
class MyMainWindow(QtGui.QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pushButton_led.clicked.connect(self.run_led_demo)
        self.ui.pushButton_buzzer.clicked.connect(self.run_buzzer_demo)
        self.ui.pushButton_move.clicked.connect(self.run_move_demo)

    def run_led_demo(self):
        dialog = led_demo.LedDemo(self.ui.lineEdit_serialId.text())
        dialog.exec()

    def run_buzzer_demo(self):
        dialog = buzzer_demo.BuzzerDemo(self.ui.lineEdit_serialId.text())
        dialog.exec()

    def run_move_demo(self):
        dialog = move_demo.MoveDemo(self.ui.lineEdit_serialId.text())
        dialog.exec()
class ScriptRunnerMainWindow(QtGui.QMainWindow):
    """
    This class initializes the main window for Script Runner
    """

    def __init__(self):
        """
        Set up the user interface from Designer.
        """
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.settings = QtCore.QSettings()

    def closeEvent(self, event):
        self.settings.setValue("ScriptRunner/geometry", self.saveGeometry())
        #settings.setValue("ScriptRunner/window_state", self.saveState())
        #self.closeEvent(event)

    def moveEvent(self, event):
        self.settings.setValue("ScriptRunner/geometry", self.saveGeometry())
Exemple #42
0
class QTranslator(QtGui.QMainWindow):
      def __init__(self, parent=None):
            QtGui.QWidget.__init__(self, parent)
            self.ui = Ui_MainWindow()
            self.ui.setupUi(self)

            self.thread = QtranslateThread()
            self.thread.processDone.connect(self.showTranslatedText)
            self.thread.isTranslating.connect(self.setStatus)


            QtCore.QObject.connect(self.ui.actionTranslate, QtCore.SIGNAL("activated()"), self.Translate)
            QtCore.QObject.connect(self.ui.actionAbout, QtCore.SIGNAL("activated()"), self.About)

      def About(self):
            global ABOUT_TEXT
            QtGui.QMessageBox.information(self, 'About QTranslate',ABOUT_TEXT, QtGui.QMessageBox.Ok)

      def Translate(self):
            global BING_APP_ID
            textOriginal = self.ui.txtOriginal.toPlainText()
            if not textOriginal:
                  QtGui.QMessageBox.warning(self, 'Hey dude!','Please provide me some text to translate...', QtGui.QMessageBox.Ok)
                  return False

            self.thread.appId = BING_APP_ID
            self.thread.theText = textOriginal
            self.thread.langFrom = str(self.ui.cbFrom.currentText())
            self.thread.langTo = str(self.ui.cbTo.currentText())

            self.thread.start()

      def showTranslatedText(self, string):
            self.ui.txtResult.setText(QtCore.QString(string))

      def setStatus(self, status):
            if status:
                  self.ui.lblStatus.setText('Loading...')
            else:
                  self.ui.lblStatus.setText('Ready...')
class ApplesApplication(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        # Set up the user interface from Designer.
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.actionOpen_configuration.triggered.connect(self.load_config)
        self.ui.actionOpen_report.triggered.connect(self.load_report)
        self.ui.showButton.clicked.connect(self.build_report)
        self.ui.deleteButton.clicked.connect(self.remove_rows)
        self.ui.addButton.clicked.connect(self.add_filter)
        self.ui.actionSave_report.triggered.connect(self.save_report)
        self.ui.chooseStorage.currentIndexChanged.connect(self.storage_changed)
        self.ui.actionExit.triggered.connect(self.close)
        self.name2storage = dict()
        self.storages = dict()
        self.dimensions = []
        self.filter = []

        self.do_load_config('config.xml')

    def add_filter(self):
        storage_name = str(self.ui.chooseStorage.currentText())
        current_storage = self.name2storage[storage_name]
        filter_dialog = AddFilterDialog(self, self.do_add_filter)
        filter_dialog.apply_storage(current_storage)
        filter_dialog.setModal(True)
        filter_dialog.show()

    def do_add_filter(self, dimension, sign, value):
        row_index = self.ui.filterTable.rowCount()
        self.ui.filterTable.insertRow(row_index)
        self.ui.filterTable.setItem(row_index, 0, QTableWidgetItem(dimension))
        self.ui.filterTable.setItem(row_index, 1, QTableWidgetItem(sign))
        self.ui.filterTable.setItem(row_index, 2, QTableWidgetItem(value))

    def save_report(self):
        file_dialog = QFileDialog()
        report_filename = file_dialog.getSaveFileName(self, 'Save report', filter='*.xml')
        if report_filename == '' or report_filename is None:
            return
        report = self.gather_report()
        report.saveToFile(report_filename)


    def clear_filters(self):
        for x in xrange(self.ui.filterTable.rowCount()):
            self.ui.filterTable.removeRow(0)
        self.filter = []

    def storage_changed(self):
        self.clear_filters()
        self.dimensions = []
        self.load_dimensions()

    def remove_rows(self):
        for row in sorted(list({item.row() for item in self.ui.filterTable.selectedItems()}), reverse=True):
            self.ui.filterTable.removeRow(row)

    def load_config(self):
        file_dialog = QFileDialog()
        config_filename = file_dialog.getOpenFileName(self, 'Open configuration', filter='*.xml')
        if config_filename == '' or config_filename is None:
            return
        self.do_load_config(config_filename)

    def do_load_config(self, filename):
        try:
            self.storages = parseConfigFile(str(filename))
            self.name2storage = {v.path: v for k, v in self.storages.iteritems()}
        except Exception as ex:
            QMessageBox.critical(self, 'Error while loading config', 'Error while loading config: %s' % ex.message);
            return

        self.ui.chooseStorage.clear()
        self.ui.chooseStorage.addItems(self.name2storage.keys())
        self.ui.chooseStorage.setCurrentIndex(0);

    def load_report(self):
        file_dialog = QFileDialog()
        report_filename = file_dialog.getOpenFileName(self, 'Open report', filter='*.xml')
        if report_filename == '' or report_filename is None:
            return
        self.do_load_report(str(report_filename))

    def do_load_report(self, filename):
        report = Report()
        try:
            report.initFromFile(filename, self.storages)
        except Exception as ex:
            QMessageBox.critical(self, 'Error while loading report', 'Error while loading report: %s' % ex.message);
            return
        self.filters = []
        for filter in report.filters:
            self.filters.extend(filter.get_trivial())

        self.show_filters()

    def show_filters(self):
        self.clear_filters()
        self.ui.filterTable.setRowCount(len(self.filters))
        for x, filter in enumerate(self.filters):
            if type(filter) is InequalityFilter:
                self.ui.filterTable.setItem(x, 0, QTableWidgetItem(str(filter.dimension.name)))
                self.ui.filterTable.setItem(x, 1, QTableWidgetItem(str(filter.sign)))
                self.ui.filterTable.setItem(x, 2, QTableWidgetItem(str(filter.value)))
            else:
                self.ui.filterTable.setItem(x, 0, QTableWidgetItem(str(filter.dimension.name)))
                self.ui.filterTable.setItem(x, 1, QTableWidgetItem(str(filter.sign)))
                self.ui.filterTable.setItem(x, 2, QTableWidgetItem(str(filter.value)))

    def load_dimensions(self):
        storage_name = str(self.ui.chooseStorage.currentText())
        self.dimensions = self.name2storage[storage_name].dimensions.keys()
        self.ui.chooseVerticalDimension.clear()
        self.ui.chooseHorizontalDimension.clear()
        self.ui.chooseVerticalDimension.addItems(self.dimensions)
        self.ui.chooseHorizontalDimension.addItems(self.dimensions)
        self.ui.chooseVerticalDimension.setCurrentIndex(0)
        self.ui.chooseHorizontalDimension.setCurrentIndex(1)

    def gather_filters(self):
        storage_name = str(self.ui.chooseStorage.currentText())
        current_storage = self.name2storage[storage_name]
        result = []
        for row in xrange(self.ui.filterTable.rowCount()):
            dimension = current_storage.getDimensionByName(str(self.ui.filterTable.item(row, 0).text()))
            sign = str(self.ui.filterTable.item(row, 1).text())
            value = str(self.ui.filterTable.item(row, 2).text())
            if sign == '=':
                result.append(EqualityFilter([value], dimension))
            elif sign == '<=':
                result.append(InequalityFilter(dimension, {'to': value}))
            else:
                result.append(InequalityFilter(dimension, {'from': value}))
        return result

    def gather_report(self):
        storage_name = str(self.ui.chooseStorage.currentText())
        vertical_dimension = str(self.ui.chooseVerticalDimension.currentText())
        horizontal_dimension = str(self.ui.chooseHorizontalDimension.currentText())
        if vertical_dimension == horizontal_dimension:
            raise Exception('Build report error: You must specify different '
                                                'horizontal and vertical dimensions')
            return

        current_storage = self.name2storage[storage_name]
        report = Report()
        report.setStorage(current_storage)
        report.setHorizontalDimension(current_storage.getDimensionByName(horizontal_dimension))
        report.setVerticalDimension(current_storage.getDimensionByName(vertical_dimension))
        report.setFilters(self.gather_filters())
        return report

    def set_fixed_size(self):
        self.setFixedHeight(420)
        self.setFixedWidth(420)

    def build_report(self):
        report = self.gather_report()
        result = report.executeQuery()
        horizontal_header, vertical_header, data = result

        resultTable = Table(self, horizontal_header, vertical_header, data)
        resultTable.show()
Exemple #44
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, repo, options, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.repo = repo
        self.options = options

        self.createConfigurationWidget()
        self.createLayout()

        # initialize stuff
        self.splitChanged(split_list.index(self.options.split))  # fetch + redraw

    def createConfigurationWidget(self):
        self.configurationwidget = QtGui.QGroupBox()
        self.cwui = Ui_ConfigurationWidget()
        self.cwui.setupUi(self.configurationwidget)

        # set initial values
        self.cwui.splitComboBox.setCurrentIndex(split_list.index(self.options.split))
        if self.options.filename:
            self.cwui.filenameLineEdit.setText(self.options.filename)
        if self.options.imagetitle:
            self.cwui.imageTitleLineEdit.setText(self.options.imagetitle)
        if self.options.skipmerges:
            self.cwui.skipMergesCheckBox.setCheckState(QtCore.Qt.Checked)
        if self.options.showtags:
            self.cwui.showTagsCheckBox.setCheckState(QtCore.Qt.Checked)
        if self.options.uselines:
            self.cwui.uselinesCheckBox.setCheckState(QtCore.Qt.Checked)
        self.cwui.maxcaptionSpinBox.setValue(self.options.maxcaptions)

        # overall min/max
        self.cwui.startDateEdit.setMinimumDate(self.options.repo_datemin)
        self.cwui.endDateEdit.setMaximumDate(self.options.repo_datemax)
        # initial value
        if self.options.datemin == None:
            self.cwui.startDateEdit.setDate(self.options.repo_datemin)
        else:
            self.cwui.startDateEdit.setDate(self.options.datemin)
        if self.options.datemax == None:
            self.cwui.endDateEdit.setDate(self.options.repo_datemax)
        else:
            self.cwui.endDateEdit.setDate(self.options.datemax)
        if self.options.datemin != None or self.options.datemax != None:
            self.timerangeUpdate(4)  # 4 = custom
            self.cwui.timerangeComboBox.setCurrentIndex(4)
        else:
            self.timerangeUpdate(0)  # 0 = whole range
            self.cwui.timerangeComboBox.setCurrentIndex(0)

        #
        # connect them all
        #
        self.connect(self.cwui.splitComboBox, QtCore.SIGNAL("currentIndexChanged(int)"), self.splitChanged)
        self.connect(self.cwui.timerangeComboBox, QtCore.SIGNAL("currentIndexChanged(int)"), self.timerangeChanged)
        self.connect(self.cwui.filenameLineEdit, QtCore.SIGNAL("textChanged(const QString)"), self.filenameChanged)
        self.connect(self.cwui.imageTitleLineEdit, QtCore.SIGNAL("textChanged(const QString)"), self.imageTitleChanged)
        self.connect(self.cwui.skipMergesCheckBox, QtCore.SIGNAL("stateChanged(int)"), self.skipMergesChanged)
        self.connect(self.cwui.showTagsCheckBox, QtCore.SIGNAL("stateChanged(int)"), self.showTagsChanged)
        self.connect(self.cwui.uselinesCheckBox, QtCore.SIGNAL("stateChanged(int)"), self.uselinesChanged)
        self.connect(self.cwui.maxcaptionSpinBox, QtCore.SIGNAL("valueChanged(int)"), self.maxcaptionChanged)

        self.connect(self.cwui.startDateEdit, QtCore.SIGNAL("dateChanged(const QDate&)"), self.timerangeChanged)
        self.connect(self.cwui.endDateEdit, QtCore.SIGNAL("dateChanged(const QDate&)"), self.timerangeChanged)

        #
        # remaining mainwindow stuff
        #
        self.connect(self.ui.action_About, QtCore.SIGNAL("triggered()"), self.about)
        self.connect(self.ui.action_Quit, QtCore.SIGNAL("triggered()"), QtGui.qApp.quit)

    def createLayout(self):
        # layout
        vbox = QtGui.QVBoxLayout()
        hbox = QtGui.QHBoxLayout()

        self.fig = Figure()
        self.fig.add_subplot(111)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.ui.centralWidget)
        self.canvas.setMinimumSize(50, 50)
        hbox.addWidget(self.canvas, 1.0)
        hbox.addWidget(self.configurationwidget)

        vbox.addLayout(hbox, 1)
        label = QtGui.QLabel(
            "You can copy paste this command line to get the same result with no graphical interface:",
            self.ui.centralWidget,
        )
        vbox.addWidget(label)
        self.commandline = QtGui.QLineEdit(self.ui.centralWidget)
        self.commandline.setReadOnly(True)
        vbox.addWidget(self.commandline)

        self.ui.centralWidget.setLayout(vbox)
        self.setCentralWidget(self.ui.centralWidget)

    def skipMergesChanged(self, value):
        "This is heavy : we need to refetch everything"
        self.options.skipmerges = not not value
        self.dates = collect_data(self.repo.changelog, self.options)
        self.redraw()

    def showTagsChanged(self, value):
        self.options.showtags = not not value
        self.redraw()

    def uselinesChanged(self, value):
        "This is heavy : we need to refetch everything"
        self.options.uselines = not not value
        self.dates = collect_data(self.repo.changelog, self.options)
        self.redraw()

    def splitChanged(self, index):
        "This is heavy : we need to refetch everything"
        self.options.split = split_list[index]
        if index == 0:
            # disable maxcaptions
            self.cwui.maxcaptionSpinBox.setEnabled(False)
            self.cwui.maxcaptionsLabel.setEnabled(False)
        else:
            # enable maxcaptions
            self.cwui.maxcaptionSpinBox.setEnabled(True)
            self.cwui.maxcaptionsLabel.setEnabled(True)
        self.dates = collect_data(self.repo.changelog, self.options)
        self.redraw()

    def timerangeUpdate(self, index):
        now = datetime.now()
        self.options.datemax = None
        if index == 0:
            self.options.datemin = None
        elif index == 1:
            self.options.datemin = now - timedelta(365)
        elif index == 2:
            self.options.datemin = now - timedelta(30)
        elif index == 3:
            self.options.datemin = now - timedelta(7)

        if index == 4:
            # custom
            self.cwui.startDateEdit.setEnabled(True)
            self.cwui.endDateEdit.setEnabled(True)

            self.options.datemin = datetime.combine(self.cwui.startDateEdit.date().toPyDate(), time())
            self.options.datemax = datetime.combine(self.cwui.endDateEdit.date().toPyDate(), time())
        else:
            self.cwui.startDateEdit.setEnabled(False)
            self.cwui.endDateEdit.setEnabled(False)
            if self.options.datemin == None:
                self.cwui.startDateEdit.setDate(self.options.repo_datemin)
            else:
                self.cwui.startDateEdit.setDate(self.options.datemin)
            if self.options.datemax == None:
                self.cwui.endDateEdit.setDate(self.options.repo_datemax)
            else:
                self.cwui.endDateEdit.setDate(self.options.datemax)

    def timerangeChanged(self):
        "This is heavy : we need to refetch everything"
        index = self.cwui.timerangeComboBox.currentIndex()
        self.timerangeUpdate(index)
        self.dates = collect_data(self.repo.changelog, self.options)
        self.redraw()

    def maxcaptionChanged(self, newvalue):
        self.options.maxcaptions = newvalue
        self.redraw()

    def imageTitleChanged(self, newtext):
        self.options.imagetitle = newtext
        self.recomputeLineCommand()

    def filenameChanged(self, newtext):
        self.options.filename = newtext
        self.recomputeLineCommand()

    def redraw(self):
        draw_graph(self.fig, self.options, self.dates)
        self.canvas.draw()
        self.recomputeLineCommand()

    def recomputeLineCommand(self):
        line = "hg activity"
        if self.options.imagetitle != self.repo.root:
            line += " -t='%s'" % self.options.imagetitle
        if self.options.filename != "activity.png":
            line += " -o='%s'" % self.options.filename
        if self.options.skipmerges:
            line += " --skipmerges"
        if self.options.showtags:
            line += " --showtags"
        if self.options.uselines:
            line += " --uselines"
        if self.options.split != "none":
            line += " --split=%s" % self.options.split
            if self.options.maxcaptions != 4:
                line += " --maxcaptions=%d" % self.options.maxcaptions
        if self.options.datemin != None:
            line += " --datemin=%s" % self.options.datemin.strftime("%Y-%m-%d")
        if self.options.datemax != None:
            line += " --datemax=%s" % self.options.datemax.strftime("%Y-%m-%d")

        self.commandline.setText(line)

    def about(self):
        msg = """
<h2>About</h2>
hgactivity is an extension for <a href="http://mercurial.selenic.com/">mercurial</a>
that creates an image displaying the activity for a repository.
<br/> <br/>
The official homepage is <a href="http://labs.freehackers.org/projects/hgactivity">http://labs.freehackers.org/projects/hgactivity</a>.
<br/> <br/>
More information can be found on the <a href="http://labs.freehackers.org/projects/hgactivity/wiki">wiki</a>
and on <a href="http://labs.freehackers.org/projects/hgactivity/wiki/documentation">the documentation page</a>.
<h2>Design & Coding</h2>
Thomas Capricelli <*****@*****.**>
<br/>
<a href="http://www.freehackers.org/thomas/free-software/">http://www.freehackers.org/thomas/free-software/</a>
"""
        box = QtGui.QDialog(self)
        label = QtGui.QLabel(box)
        label.setOpenExternalLinks(True)
        label.setWordWrap(True)
        label.setWindowTitle("About hg activity (qt interface)")
        label.setText(msg)
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(label)
        box.setLayout(vbox)
        button = QtGui.QPushButton("Ok", box)
        box.connect(button, QtCore.SIGNAL("clicked()"), box.accept)
        vbox.addWidget(button)
        box.exec_()
Exemple #45
0
class StartQT4(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.dataPath = None
        self.ui.imageView.setHorizontalScrollBarPolicy( QtCore.Qt.ScrollBarAlwaysOff )
        self.ui.imageView.setVerticalScrollBarPolicy( QtCore.Qt.ScrollBarAlwaysOff )

        #QtCore.QObject.connect(self.ui.processDataButton, QtCore.SIGNAL("clicked()"), self.processData)
        QtCore.QObject.connect(self.ui.pcaOnlyCheckbox, QtCore.SIGNAL("clicked()"), self.setPcaOnly)
        QtCore.QObject.connect(self.ui.kmeansOnlyCheckbox, QtCore.SIGNAL("clicked()"), self.setKmeansOnly)
        QtCore.QObject.connect(self.ui.runButton, QtCore.SIGNAL("clicked()"), self.runData)
        QtCore.QObject.connect(self.ui.dataPath, QtCore.SIGNAL("returnPressed()"), self.setDataPath)
        QtCore.QObject.connect(self.ui.resultsFile, QtCore.SIGNAL("currentIndexChanged(int)"), self.setResultsPath)
        QtCore.QObject.connect(self.ui.digit, QtCore.SIGNAL("currentIndexChanged(int)"), self.setDigit)
    
    def processData(self):
        sourceFilepath = QtGui.QFileDialog.getOpenFileName(self, "Select data file", "", "*.txt")
        if os.path.isfile(sourceFilepath):
            destinationPath = None
            if self.dataPath:
                destinationPath = self.dataPath + "/"
            else:
                destinationPath = "./"
            destinationFilename = QtCore.QString(sourceFilepath).replace(QtCore.QRegExp(".*/"), "")
            print("DestinationPath: %s" % destinationPath)
            print("DestinationFilename: %s" % destinationFilename)
            
            ToPickle.parse( str(sourceFilepath), str(destinationPath + destinationFilename.replace(".txt", ".pkl")) )
            ToColmat.parse( str(destinationPath + destinationFilename), str(destinationPath + destinationFilename.replace(".pkl", "_colmat.pkl")) )
            self.ui.dataSet.addItem(destinationFilename)
            self.ui.trainingSet.addItem(destinationFilename)
            
    def setDataPath(self):
        self.dataPath = QtGui.QFileDialog.getExistingDirectory(self, "Select directory", "", QtGui.QFileDialog.ShowDirsOnly)
        self.ui.dataPath.insert(self.dataPath)

        self.updateDataSets()
        self.updateResults()
    
    def setPcaOnly(self):
        self.ui.kmeansOnlyCheckbox.setChecked(False)
    
    def setKmeansOnly(self):
        self.ui.pcaOnlyCheckbox.setChecked(False)
    
    def runData(self):
        if self.ui.pcaOnlyCheckbox.isChecked():
            self.runPcaOnly()
        elif self.ui.kmeansOnlyCheckbox.isChecked():
            self.runKmeansOnly()
        else:
            self.runCombination()
    
    def runPcaOnly(self):
        print("Running PCA Only...")
        inputFilepath  = self.dataPath + "/" + self.ui.dataSet.currentText()
        inputTrainingFilepath  = self.dataPath + "/" + self.ui.trainingSet.currentText()
        outputFilepath = QtCore.QString(inputFilepath).replace("_colmat.pkl", "_result_pca.pkl")
        outputDirpath  = QtCore.QString(outputFilepath).replace(".pkl", "")
        QtCore.QDir().mkdir(outputDirpath)
        PCA.run( str(inputFilepath), str(inputTrainingFilepath), str(outputFilepath), str(outputDirpath), 1, self.ui.pcaNumComp.value() )
        self.updateResults()
    
    def runKmeansOnly(self):
        print("Running K-Means Only...")
        inputFilepath  = self.dataPath + "/" + self.ui.trainingSet.currentText()
        outputFilepath = QtCore.QString(inputFilepath).replace("_colmat.pkl", "_result_kmeans.pkl")
        outputDirpath  = QtCore.QString(outputFilepath).replace(".pkl", "")
        QtCore.QDir().mkdir(outputDirpath)
        KMeans.run( str(inputFilepath), str(outputFilepath), str(outputDirpath), self.ui.kmeansNumClust.value() )
        self.updateResults()
    
    def runCombination(self):
        print("Running Combination...")
        inputFilepath  = self.dataPath + "/" + self.ui.dataSet.currentText()
        inputTrainingFilepath  = self.dataPath + "/" + self.ui.trainingSet.currentText()
        outputFilepath = QtCore.QString(inputFilepath).replace("_colmat.pkl", "_result_combination.pkl")
        outputDirpath  = QtCore.QString(outputFilepath).replace(".pkl", "")
        QtCore.QDir().mkdir(outputDirpath)
        PCA.run( str(inputFilepath), str(inputTrainingFilepath), str(outputFilepath), str(outputDirpath), self.ui.kmeansNumClust.value(), self.ui.pcaNumComp.value() )
        self.updateResults()

    def updateDataSets(self):
        filelist = QtCore.QDir(self.dataPath).entryList()
        self.ui.dataSet.clear()
        self.ui.dataSet.addItems(filelist.filter("_colmat.pkl"))
        self.ui.trainingSet.clear()
        self.ui.trainingSet.addItems(filelist.filter("_colmat.pkl"))

    def updateResults(self):
        dirlist = QtCore.QDir(self.dataPath).entryList(QtCore.QDir.Dirs)
        self.ui.resultsFile.clear()
        self.ui.resultsFile.addItems(dirlist.filter("result"))
        self.updateDigits()
    
    def setResultsPath(self, value):
        self.updateDigits()
        
    def updateDigits(self):
        self.digitsPath = QtCore.QString(self.dataPath + "/" + self.ui.resultsFile.currentText())

        filelist = QtCore.QDir(self.digitsPath).entryList()
        self.ui.digit.clear()
        self.ui.digit.addItems(filelist.filter(".png"))
    
    def setDigit(self):
        imageFilepath = QtCore.QString(self.digitsPath + "/" + self.ui.digit.currentText())
        print("Selected Image: %s" % imageFilepath)

        if os.path.isfile(imageFilepath):
            img = QtGui.QImage(imageFilepath)
            pixMap = QtGui.QPixmap.fromImage(img)

            scene = QtGui.QGraphicsScene()
            self.ui.imageView.setScene(scene)
            pixMap = pixMap.scaled(self.ui.imageView.size())
            scene.clear()
            scene.addPixmap(pixMap)
            self.ui.imageView.repaint()
            self.ui.imageView.show()
            print("Image updated")
            self.updateConfusion()
        else:
            scene = QtGui.QGraphicsScene()
            self.ui.imageView.setScene(scene)
            scene.clear()
            self.ui.imageView.repaint()
            self.ui.imageView.show()
            print("No Image file found")
    
    def updateConfusion(self):
        filepath = self.digitsPath + "/conf_" + self.ui.digit.currentText().replace(".png", ".pkl")
        print("filepath %s" % filepath)
        confusionData = pickle.load(open(filepath))[1]
      
        cell1 = QtGui.QTableWidgetItem(str(confusionData[0][0]))
        cell1.setBackground(QtGui.QBrush(QtGui.QColor( 0, 255, 0, 100 )))
        cell1.setTextAlignment(QtCore.Qt.AlignCenter)
        cell2 = QtGui.QTableWidgetItem(str(confusionData[0][1]))
        cell2.setBackground(QtGui.QBrush(QtGui.QColor( 255, 0, 0, 100 )))
        cell2.setTextAlignment(QtCore.Qt.AlignCenter)
        cell3 = QtGui.QTableWidgetItem(str(confusionData[1][0]))
        cell3.setBackground(QtGui.QBrush(QtGui.QColor( 255, 0, 0, 100 )))
        cell3.setTextAlignment(QtCore.Qt.AlignCenter)
        cell4 = QtGui.QTableWidgetItem(str(confusionData[1][1]))
        cell4.setBackground(QtGui.QBrush(QtGui.QColor( 0, 255, 0, 100 )))
        cell4.setTextAlignment(QtCore.Qt.AlignCenter)
        
        self.ui.confusion.setItem(0,0, cell1)
        self.ui.confusion.setItem(0,1, cell2)
        self.ui.confusion.setItem(1,0, cell3)
        self.ui.confusion.setItem(1,1, cell4)
        
        print("Updating confusion to: %s" % filepath)
class StartQT4(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.have_auth = False
        self.have_mess = False

        ###############
        ##### set up signals/slots
        ###############

        ##### menu items

        # use the trick from http://eli.thegreenplace.net/2011/04/25/passing-extra-arguments-to-pyqt-slot
        # to use same callback for two menu items
        self.ui.actionImport_auth.triggered.connect(lambda: self.importData("auth"))
        self.ui.actionImport_messy.triggered.connect(lambda: self.importData("messy"))
        self.ui.actionRun_matching.triggered.connect(self.runMatching)
        self.ui.actionExport_CSV.triggered.connect(self.exportCSV)
        self.ui.actionPreferences.triggered.connect(self.setPreferences)
        self.ui.actionQuit.triggered.connect(QtCore.QCoreApplication.instance().quit)

        ##### GUI elements

        self.ui.match_table.currentCellChanged.connect(self.updateTopHits)
        self.ui.tophit_list.itemDoubleClicked.connect(self.clickAssign)
        self.ui.createAuthority_button.clicked.connect(self.createAuth)
        self.ui.deleteAuthority_button.clicked.connect(self.deleteMatch)

        ###### default preferences

        self.cutoffs = {"lev": 10, "damlev": 10, "jaro": 0.6, "jarowink": 0.6, "mrac": 9999}
        self.display_similarity = True

    def importData(self, data_type):
        fname = str(QtGui.QFileDialog.getOpenFileName(self, "Open file", "~"))
        filename, file_extension = os.path.splitext(fname)

        if file_extension == ".csv":
            csv_fileh = open(fname, 'rU')
            try:
                dialect = csv.Sniffer().sniff(csv_fileh.read(1024))
                csv_fileh.seek(0)
                reader = csv.DictReader(csv_fileh, dialect=dialect)
                self.header = reader.next().keys()
            except csv.Error:
                QtGui.QMessageBox.warning(self, 'Warning', 'File does not appear to be valid CSV')
                return

            # everything's okay, so reopen the file and read some sample data to pass to column selector dialog

            csv_fileh.close()
            csv_fileh = open(fname, 'rU')
            reader = csv.DictReader(csv_fileh, dialect=dialect)
            self.sample = [ reader.next() for i in range(20) ]

            dlg = StartSelectColumns(self)
            if dlg.exec_(): 
                selected_column = dlg.getValues()
            else:
                return

            # read the data from the selected column. reopen file for safety (even though it's absurdly inefficient)

            csv_fileh.close()
            csv_fileh = open(fname, 'rU')
            reader = csv.DictReader(csv_fileh, dialect=dialect)

            data = list()
            for row in reader:
                data.append(row[selected_column])

            data = [i for i in data if i != ""]
            data = list(set(data))
 

        elif file_extension == ".txt":
            QtGui.QMessageBox.information(self, 'Information', 'Flat text import not yet supported.')
        elif file_extension == ".xlsx":
            QtGui.QMessageBox.information(self, 'Information', 'Excel .xlsx import not yet supported')
        elif file_extension == ".xls":
            QtGui.QMessageBox.information(self, 'Information', 'Excel .xls import not yet supported')
        else:
            QtGui.QMessageBox.warning(self, 'Warning', 'File type {} is not supported'.format(file_extension))
            return

        if data_type == "auth":
            self.authorities = data
            self.have_auth = True
        elif data_type == "messy":
            self.mess = data
            self.have_mess = True
        else:
            QtGui.QMessageBox.critical(self, 'Warning', 'Internal error: importData received unexpected argument')

        if self.have_auth and self.have_mess:
            self.ui.actionRun_matching.setEnabled(True)

    def runMatching(self):
        dlg = StartRunDialog() 
        if dlg.exec_(): 
            match_method = dlg.getValues() 
        else:
            return

        if match_method == "lev":
            match_function = jellyfish.levenshtein_distance
        elif match_method == "damlev":
            match_function = jellyfish.damerau_levenshtein_distance
        elif match_method == "jaro":
            match_function = jellyfish.jaro_distance
        elif match_method == "jarowink":
            match_function = jellyfish.jaro_winkler
        elif match_method == "mrac":
            match_function = jellyfish.match_rating_comparison
        else:
            QtGui.QMessageBox.critical(self, 'Warning', 'Internal error: runMatching received unexpected argument')

        self.all_scores = list()
        self.matched_authorities = list()

        for m in self.mess: # ideally, we want a progress bar for this loop
            scores = [ [x, match_function(m, unicode(x))] for x in self.authorities ]
            scores = sorted(scores, key=lambda score: -score[1])[0:10]
            self.all_scores.append(scores)
            cutoff = self.cutoffs[match_method]
            if match_method == "lev" or match_method == "damlev":
                self.matched_authorities.append(scores[0][0] if scores[0][1] < cutoff else False)
            else:
                self.matched_authorities.append(scores[0][0] if scores[0][1] > cutoff else False)

        self.ui.match_table.setRowCount(len(self.mess))
        self.ui.match_table.clearContents()
        self.updateTable()
        self.ui.actionExport_CSV.setEnabled(True)

    def exportCSV(self):
        fname = QtGui.QFileDialog.getSaveFileNameAndFilter(self, 'Export CSV', '~', "*.csv")
        print "got {}".format(fname)

        with open(fname[0], 'wb') as csvfile:
            csvwriter = csv.writer(csvfile)
            csvwriter.writerow(["Messy term", "Authority term"])

            for i in range(len(self.mess)):
                if self.matched_authorities[i]:
                    csvwriter.writerow([self.mess[i], self.matched_authorities[i]])

    def setPreferences(self):
        dlg = StartPreferences(self) 
        if dlg.exec_(): 
            preferences = dlg.getValues() 
        else:
            return

        self.display_similarity = preferences["display_similarity"]
        self.cutoffs = preferences["cutoffs"]

    def updateTable(self):
        for row in range(len(self.mess)):
            self.ui.match_table.setItem(row, 0, QtGui.QTableWidgetItem(self.mess[row]))
            if self.matched_authorities[row]:
                self.ui.match_table.setItem(row, 1, QtGui.QTableWidgetItem(self.matched_authorities[row]))

    def updateTopHits(self, row, column, oldrow, oldcolumn):
        self.ui.tophit_list.clear()
        for i in range(10):
            text = self.all_scores[row][i][0]
            if self.display_similarity:
                text = "{} ({:.3})".format(text, float(self.all_scores[row][i][1]))
            item = QtGui.QListWidgetItem(text)
            self.ui.tophit_list.addItem(item)

        if row != -1: # row gets set to -1 after deleteMatch(): ignore it and keep the old current_row
            self.current_row = row
        
    def clickAssign(self, item):
        self.matched_authorities[self.current_row] = item.text()
        self.updateTable()

    def createAuth(self):
        self.matched_authorities[self.current_row] = self.ui.new_authority.text()
        self.updateTable()

    def deleteMatch(self):
        self.matched_authorities[self.current_row] = False

        # there doesn't seem to be any way to clear a single cell (?!?)
        # so clear the entire table before re-rendering it
        self.ui.match_table.clearContents()
        self.updateTable()
        self.ui.match_table.setCurrentCell(self.current_row, 0)
Exemple #47
0
class MainWindow(QtGui.QMainWindow):


    def __init__(self):

        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.set_listeners()
        self.load_animals()
        self.load_types()
        self.create_folder()

    def about(self):
        """
        Ventana con los integrantes del grupo
        """
        message = u'Integrantes: \n- Nicolas Aravena\n- Sebastian Matamala\n- Arturo Reyes'
        self.ui.aboutUs = QtGui.QMessageBox.information(self, 'Acerca de Animales', message)

    def delete(self):
    	"""
        Elimina un animal de la base de datos mediante el controlador
        """
        model = self.ui.tableView.model()
        index = self.ui.tableView.currentIndex()
        if index.row() == -1: 
            self.ui.errorMessageDialog = QtGui.QMessageBox.information(self, 'Error',
                                            u"Debe seleccionar el animal que desea eliminar",
                                            QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
            return False
        else:
            self.ui.confirmMessage = QtGui.QMessageBox.question(self, 'Eliminar animal',
                                    u"Está seguro que desea eliminar el animal seleccionado?",
                                    QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
            if self.ui.confirmMessage == QtGui.QMessageBox.Yes:
                animal = model.index(index.row(), 1, QtCore.QModelIndex()).data()
                if (controller.delete(animal)):
                    self.load_animals()
                    self.ui.msgBox = QtGui.QMessageBox.information(self, u'Atención',
                                    u"El animal fue eliminado con éxito")
                    return True
                else:
                    self.ui.errorMessageDialog = QtGui.QMessageBox.information(self, 'Error',
                                            u"Error al eliminar el animal",
                                            QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
                    return False

    def create_folder(self):
    	"""
        Crea carpeta de imagenes si no existe
        """
        self.directory = QDir.root()
        if not os.path.exists(self.directory.currentPath()+"/images"):
            os.makedirs(self.directory.currentPath()+"/images")

    def load_types(self):
        """
        Carga los tipos de animales en el comboBox
        """
        types = controller.get_types()
        self.ui.searchBox.addItem("Todos", -1)
        for type1 in types: 
            self.ui.searchBox.addItem(type1["nombre"], type1["id_tipo"])
        self.ui.searchBox.setEditable(False)

    def load_animals(self, animals=None):
        """
        Carga los animales en pantalla
        """
        if animals is None:
            animals = controller.get_animals()
        self.model = QtGui.QStandardItemModel(len(animals), 1)        
        self.model.setHorizontalHeaderItem(0, QtGui.QStandardItem(u"Imagen"))
        self.model.setHorizontalHeaderItem(1, QtGui.QStandardItem(u"Animal"))
        r = 0
        self.display = QGraphicsView()
        for row in animals:
            index = self.model.index(r, 1, QtCore.QModelIndex())
            self.model.setData(index, row['nombre_comun'])

            index = self.model.index(r, 0, QtCore.QModelIndex())
            id_animal = controller_form.get_id_animal(animals[r][1])
            self.image = controller_form.get_image(id_animal)
            if self.image:
                self.path = QDir.currentPath() + "/images/" + self.image[0] + self.image[1]
                Ifile = QFileInfo(self.path)
                pixImage = controller_form.get_root_image(self.path)
                item = QGraphicsPixmapItem(pixImage.scaled(25,25))
                scene = QGraphicsScene()
                scene.addItem(item)
                self.display.setScene(scene)
                self.model.setData(index, self.display.setScene(scene))
            else:
                noimage = controller_form.no_image()
                item = QGraphicsPixmapItem(noimage.scaled(25,25))
                scene = QGraphicsScene()
                scene.addItem(item)
                self.display.setScene(scene)
                self.model.setData(index, self.display.setScene(scene))
            r += 1
        self.ui.tableView.setModel(self.model)
        self.ui.tableView.setColumnWidth(0, 105)
        self.ui.tableView.setColumnWidth(1, 325)

    def load_products_by_search(self):
        """
        Carga los animales despues de aplicar un filtro
        """
        word = self.ui.search.text()
        animalslist = controller.get_animals_name()
        animals = controller.search_animal(word)
        self.load_animals(animals)
        completer = QtGui.QCompleter(animalslist, self)
        completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        completer.setCompletionMode(QtGui.QCompleter.InlineCompletion)
        self.ui.search.setCompleter(completer)

    def load_animals_by_type(self):
        """
        Carga los animales por tipo
        """ 
        id_tipo = self.ui.searchBox.itemData(self.ui.searchBox.currentIndex())
        if id_tipo == -1: 
            animals = controller.get_animals()
        else: 
            animals = controller.get_animals_by_type(id_tipo)
        self.load_animals(animals)

    def set_listeners(self):
    	"""
        Sets up button listeners
        """
        self.ui.btn_delete.triggered.connect(self.delete)
        self.ui.add.triggered.connect(self.show_add_form)
        self.ui.edit.triggered.connect(self.show_edit_form)
        self.ui.quit.triggered.connect(self.close)
        self.ui.tableView.clicked.connect(self.display_data)
        self.ui.searchBox.activated[int].connect(self.load_animals_by_type)
        self.ui.search.textChanged.connect(self.load_products_by_search)
        self.ui.actionAcerca_de.triggered.connect(self.about)

    def show_add_form(self):
    	"""
        Muestra la ventana de agregar animales
        """
        form = view_form.Form(self)
        form.rejected.connect(self.load_animals)
        form.exec_()

    def show_edit_form(self):
    	"""
        Muestra la ventana de editar productos
        """
        model = self.ui.tableView.model()
        index = self.ui.tableView.currentIndex()
        if index.row() == -1: 
            self.ui.msgBox = QtGui.QMessageBox.information(self, u'Error',
                                    u"Debe seleccionar el animal que desea editar")
            return False
        else:
            animal = model.index(index.row(), 1, QtCore.QModelIndex()).data()
            form = view_form.Form(self, animal)
            form.rejected.connect(self.load_animals)
            form.exec_()

    def display_data(self):
        """
        Modificado display para que muestre la imagen que se solicita
        """
        model = self.ui.tableView.model()
        index = self.ui.tableView.currentIndex()
        data = model.index(index.row(),1,QtCore.QModelIndex()).data()
        animal = controller.get_animal(data)
        tipo = controller.get_type(data)
        id_animal = controller_form.get_id_animal(animal[1])
        pixImage = controller_form.get_image_pix(id_animal)
        self.ui.common.setText(animal[1])
        self.ui.cientific.setText(animal[2])
        self.ui.type.setText(tipo[0])
        self.ui.data.setWordWrap(True)
        self.ui.data.setText(animal[3])
        if pixImage:
            item = QGraphicsPixmapItem(pixImage.scaled(375,285))
            self.scene = QGraphicsScene()
            self.ui.graphicsView.setSceneRect(0,0,375,285)
            self.ui.graphicsView.setScene(self.scene)
            self.scene.addItem(item)
        else:
            noimage = controller_form.no_image()
            item = QGraphicsPixmapItem(noimage.scaled(375,285))
            self.scene = QGraphicsScene()
            self.ui.graphicsView.setSceneRect(0,0,375,285)
            self.ui.graphicsView.setScene(self.scene)
            self.scene.addItem(item)
Exemple #48
0
class CMain(QtGui.QMainWindow):
        def __init__(self):
                QtGui.QMainWindow.__init__(self)
                self.ui = Ui_MainWindow()
                self.ui.setupUi(self)
                
                self.ui.startBtn.clicked.connect(self.startBtn_Clicked)
                self.ui.resetCounterBtn.clicked.connect(self.resetCounterBtn_Clicked)
                self.ui.exitBtn.clicked.connect(self.exitBtn_Clicked)
                self.ui.paramBtn.clicked.connect(self.paramBtn_Clicked)
                
                self.ui.lcdClock.display(time.strftime("%H"+":"+"%M"+":"+"%S"))
                
                #timer input czy jest rozkaz od maszyny
                self.check_run_motor = QtCore.QTimer()
                self.check_run_motor.timeout.connect(self.checkRunMotor)
                
                #timer input czy doliczyc cykl maszyny
                self.check_cycle = QtCore.QTimer()
                self.check_cycle.timeout.connect(self.checkCycle)
                
                self.check_cycle.stop()
                self.check_run_motor.stop()
                self.ilosc_obrotow = 0


                
        #przelic obroty silnika na pojedyncze kroki 
        def rot_to_steps(self, turns):
                steps = 200.*config.microstep*turns
                return steps

        def vel_to_pause(self, vel):
                pause = 1.0/(200.*config.microstep*vel)/2.0
                return pause
                
        #zakrec silnik
        def move_motor(self, channel):
                if config.enable is True:
			#GPIO.setup(20,GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
			#time.sleep(0.5)                        
			pause = self.vel_to_pause(float(config.velocity))
                        steps = self.rot_to_steps(float(config.rotates_per_cycle))
                        print "obracam motor o {}".format(steps)
                        print datetime.datetime.now()
                        for i in range(int(steps)):
                            GPIO.output(21,GPIO.HIGH)
                            time.sleep(pause)
                            GPIO.output(21,GPIO.LOW)
                            time.sleep(pause)
                        print "koniec obrotu"
                else:
                        print "probowalem w trybie zabronionym"
        
        def checkRunMotor(self):
                if GPIO.input(20):
                        self.ilosc_obrotow = self.ilosc_obrotow + 1
                        if config.enable is True:
                                self.move_motor(20) 
                                time.sleep(0.2)
                                print "zakrecone {}".format(self.ilosc_obrotow)
                                self.check_cycle.start(1)
                                self.check_run_motor.stop()
                        else:
                                print "probowalem w trybie zabronionym"
                        
        def checkCycle(self):
                        self.ui.lcdClock.display(time.strftime("%H"+":"+"%M"+":"+"%S"))
                        if GPIO.input(12):
                                cycle_done(12)
                                self.check_cycle.stop()
                                self.check_run_motor.start(10)
                        self.ui.lcdCounter.display(config.cycles)

        def resetCounterBtn_Clicked(self):
                config.cycles = 0
                GPIO.output(19,GPIO.HIGH)
                self.ui.lcdCounter.display(config.cycles)
                
        def startBtn_Clicked(self):
                if self.ui.startBtn.isChecked() == True:
                        print "wcisnalem"
                        config.enable = True
                        self.check_cycle.start(1)
                        self.check_run_motor.start(10)
			#GPIO.add_event_detect(20, GPIO.RISING, callback = self.move_motor, bouncetime = 3000)
			#GPIO.add_event_detect(12, GPIO.RISING, callback = cycle_done, bouncetime = 1000)
                        self.ui.startBtn.setStyleSheet(_fromUtf8("background: red; color: white"))
                        self.ui.startBtn.setText("stop")
                        if config.cycles >= config.cycles_to_reset:
                               GPIO.output(19,GPIO.LOW)
                        else:
                               GPIO.output(19,GPIO.HIGH)
                else:
                        print "odcisnalem"
                        config.enable = False

                        GPIO.output(19,GPIO.HIGH)
                        GPIO.output(21,GPIO.LOW)
                        self.check_cycle.stop()
                        self.check_run_motor.stop()
#			GPIO.remove_event_detect(12)
#			GPIO.remove_event_detect(20)
                        self.ui.startBtn.setStyleSheet(_fromUtf8("background: green; color: white"))
                        self.ui.startBtn.setText("start")
        
        def paramBtn_Clicked(self):
                param_window.showFullScreen()
        
        def exitBtn_Clicked(self):
                self.close()
                self.check_cycle.stop()
                #self.check_input.stop()
                GPIO.cleanup()
Exemple #49
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, peaks, *args):
        self.peaks = peaks

        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.findPeakButton.clicked.connect(self.findPeaksCallback)
        self.ui.fileButton.clicked.connect(self.loadFileCallback)
        self.ui.saveButton.clicked.connect(self.savePeaksCallback)

    def addPlot(self):
        """
        Populate central widget with matplotlib canvas (and toolbar)
        """

        self.fig = Figure(figsize=(600, 600), dpi=72, facecolor=(1,1,1), edgecolor=(0,0,0))
        self.ax = self.fig.add_subplot(111)
        self.canvas = FigureCanvasQTAgg(self.fig)
        self.ui.canvasLayout.addWidget(self.canvas)


        self.navi_toolbar = NavigationToolbar2QT(self.canvas, self)
        self.ui.canvasLayout.addWidget(self.navi_toolbar)

    def loadFileCallback(self):
        """
        Qt "slot" called by "Load file..." button
        """

        filename, _ = QtGui.QFileDialog.getOpenFileName(self, 'Open data file',)

        if filename:
            self.peaks.load(filename)
            self.update()

            self.ui.filenameLabel.setText("File: %s" % os.path.split(filename)[-1])
            self.ui.statusBar.showMessage("File opened: %s" % os.path.split(filename)[-1])

    def findPeaksCallback(self):
        """
        Qt "slot" called by "Find peaks" button
        """

        self.peaks.setMinMax( int(self.ui.minEntry.text()), int(self.ui.maxEntry.text()) )
        self.ui.statusBar.showMessage("Calculating peaks")
        self.peaks.findPeaks()
        self.update()
        self.ui.statusBar.showMessage("Calculation done")

    def savePeaksCallback(self):
        """
        Qt "slot" called by "Save to..." button
        """

        filename, _ = QtGui.QFileDialog.getSaveFileName(self, 'Save peaks to',)
        if filename:
            with open(filename, 'w') as f:
                f.write(self.ui.peaksText.toPlainText())

            self.ui.statusBar.showMessage("Peaks saved to: %s" % os.path.split(filename)[-1])

    def update(self):
        """
        Refresh plot widget (usually after loading a new file or asking peaks)
        """

        self.ax.cla()

        self.ax.plot(self.peaks.x, self.peaks.y)
        if self.peaks.peaks:
            self.ax.plot(self.peaks.peaks, [self.peaks.y[i] for i in self.peaks.peaks], 'ro')

            self.ui.peaksText.setPlainText("\n".join(["%s; %s" % (p, v) for p, v in zip(self.peaks.peaks, [self.peaks.y[i] for i in self.peaks.peaks])]))

        self.canvas.draw()
Exemple #50
0
class MainWindow(QtWidgets.QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.connect_signals()
        self.cont = 0
        self.title = self.windowTitle()

    def connect_signals(self):
        self.ui.actionProfissional_de_Imprensa.\
                triggered.connect(lambda: self.add_widget('pi'))
        self.ui.actionTipo_Credencial.triggered.\
                connect(lambda: self.add_widget('tipocred'))
        self.ui.actionComite.triggered.\
                connect(lambda: self.add_widget('comite'))
        self.ui.actionOrg_o_de_Imprensa.triggered.\
                connect(lambda: self.add_widget('oi'))
        self.ui.actionLimites_Comite.triggered.\
                connect(lambda: self.add_widget('limitescomite'))
        self.ui.actionLimites_Org_o_de_Imprensa.triggered.\
                connect(lambda: self.add_widget('limitesoi'))
        self.ui.actionOrg_os_de_Imprensa.triggered.\
                connect(lambda: self.add_widget('buscaoi'))
        self.ui.actionProfissionais_de_Imprensa.triggered.\
                connect(lambda: self.add_widget('buscapi'))
        self.ui.actionComit.triggered.\
                connect(lambda: self.add_widget('buscacomite'))

    def add_widget(self, tipo):
        for item in self.children():
            if isinstance(item, QtWidgets.QDockWidget):
                item.hide()
        self.dw = QtWidgets.QDockWidget(self)
        self.dw.setMinimumWidth(400)
        self.dw.setFeatures(QtWidgets.QDockWidget.DockWidgetClosable)

        if(tipo == 'pi'):
            self.widget = addpi_tela.add_pi(self.dw.widget())
        elif(tipo == 'tipocred'):
            self.widget = addtipocred_tela.add_tipocred(self.dw.widget())
        elif(tipo == 'comite'):
            self.widget = addcomite_tela.add_comite(self.dw.widget())
        elif(tipo == 'oi'):
            self.widget = addoi_tela.add_oi(self.dw.widget())
        elif(tipo == 'limitescomite'):
            self.widget = editlimitescomite_tela.edit_limitescomite(self.dw.widget())
            self.dw.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)
        elif(tipo == 'limitesoi'):
            self.widget = editlimitesoi_tela.edit_limitesoi(self.dw.widget())
            self.dw.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)
        elif(tipo == 'buscaoi'):
            self.widget = buscaoi1_tela.busca_oi1(self.dw.widget())
            self.dw.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)
        elif(tipo == 'buscapi'):
            self.widget = buscapi_tela.busca_pi(self.dw.widget())
            self.dw.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)
        elif(tipo == 'buscacomite'):
            self.widget = buscacomite_tela.busca_comite(self.dw.widget())
            self.dw.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)
        self.setWindowTitle(self.widget.windowTitle())
        self.dw.setWidget(self.widget)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dw)

    def change_text(self):
        self.cont += 1
Exemple #51
0
class CMain(QtGui.QMainWindow):
        def __init__(self):
                QtGui.QMainWindow.__init__(self)
                self.ui = Ui_MainWindow()
                self.ui.setupUi(self)
                
                self.ui.startBtn.clicked.connect(self.startBtn_Clicked)
                self.ui.resetCounterBtn.clicked.connect(self.resetCounterBtn_Clicked)
                self.ui.blockScreenBtn.clicked.connect(self.blockScreenBtn_Clicked)
                self.ui.exitBtn.clicked.connect(self.exitBtn_Clicked)
                self.ui.paramBtn.clicked.connect(self.paramBtn_Clicked)
                
                self.ui.lcdClock.display(time.strftime("%H"+":"+"%M"+":"+"%S"))
                #timer input czy jest rozkaz od maszyny
#                self.check_input = QtCore.QTimer()
#                self.check_input.timeout.connect(self.checkInput)
                
                #timer input czy doliczyc cykl maszyny
                self.check_cycle = QtCore.QTimer()
                self.check_cycle.timeout.connect(self.checkCycle)
                
                self.check_cycle.stop()
                #self.check_input.stop()


                
        #przelic obroty silnika na pojedyncze kroki 
        def rot_to_steps(self, turns):
                steps = 200.*config.microstep*turns
                return steps

        def vel_to_pause(self, vel):
                pause = 1.0/(200.*config.microstep*vel)/2.0
                return pause

	def cycle_done(self, channel): 
	                count = 0
	                while(count<10):
                                if GPIO.input(12) == 0:
                                        count=count+1
                                        time.sleep(0.01)
                                        print "cycle done {}".format(count)
                                else:
                                        print "fake cycle sygnal"
                                        return            
			config.cycles = config.cycles + 1
                        if config.cycles >= config.cycles_to_reset:
                               GPIO.output(19,GPIO.LOW)
			time.sleep(1.5)
			self.ui.lcdClock.display(time.strftime("%H"+":"+"%M"+":"+"%S"))

	def reset_ext_btn(self, channel): 
	                count = 0
	                while(count<5):
                                if GPIO.input(16) == 0:
                                        count=count+1
                                        time.sleep(0.01)
                                        print "button pressed {}".format(count)
                                else:
                                        print "fake button sygnal"
                                        return            
			
                        resetCounterBtn_Clicked()

                
        #zakrec silnik
        def move_motor(self, channel):
                count = 0
                while (count < 10):
                        if GPIO.input(20) == 0:
                                count=count+1
                                time.sleep(0.03)
                                print "move motor {}".format(count)
                        else:
                                print "fake motor sygnal"
                                return                
                if config.enable is True:
			#GPIO.setup(20,GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
			#time.sleep(0.5)                        
			pause = self.vel_to_pause(float(config.velocity))
                        steps = self.rot_to_steps(float(config.rotates_per_cycle))
			move_time = 2*pause*steps
			print move_time

                        print "obracam motor o {}".format(steps)
                        print datetime.datetime.now()
                        for i in range(int(steps)):
                            GPIO.output(21,GPIO.HIGH)
                            time.sleep(pause)
                            GPIO.output(21,GPIO.LOW)
                            time.sleep(pause)
                        print "koniec obrotu"
			if move_time <2.2:
				time.sleep(2.2-move_time)
			else:
				pass 
                else:
                        print "probowalem w trybie zabronionym"
                        
        def checkCycle(self):
                        self.ui.lcdClock.display(time.strftime("%H"+":"+"%M"+":"+"%S"))
                        self.ui.lcdCounter.display(config.cycles)

        def resetCounterBtn_Clicked(self):
                config.cycles = 0
                GPIO.output(19,GPIO.HIGH)
                self.ui.lcdCounter.display(config.cycles)
                
        def startBtn_Clicked(self):
                if self.ui.startBtn.isChecked() == True:
                        print "wcisnalem"
                        config.enable = True
                        self.check_cycle.start(10)
                        #self.check_input.start(1)
			GPIO.add_event_detect(20, GPIO.FALLING, callback = self.move_motor)
			GPIO.add_event_detect(12, GPIO.FALLING, callback = self.cycle_done)
			GPIO.add_event_detect(16, GPIO.FALLING, callback = self.reset_ext_btn)
                        self.ui.startBtn.setStyleSheet(_fromUtf8("background: red; color: white"))
                        self.ui.startBtn.setText("stop")
                        if config.cycles >= config.cycles_to_reset:
                               GPIO.output(19,GPIO.LOW)
                        else:
                               GPIO.output(19,GPIO.HIGH)
                else:
                        print "odcisnalem"
                        enable = False

                        GPIO.output(19,GPIO.HIGH)
                        GPIO.output(21,GPIO.LOW)
                        self.check_cycle.stop()
                        #self.check_input.stop()
			GPIO.remove_event_detect(12)
			GPIO.remove_event_detect(16)
			GPIO.remove_event_detect(20)
                        self.ui.startBtn.setStyleSheet(_fromUtf8("background: green; color: white"))
                        self.ui.startBtn.setText("start")
        
        def paramBtn_Clicked(self):
                param_window.showFullScreen()
        
        def blockScreenBtn_Clicked(self):
                QtGui.QMessageBox.information(self,'Info',"Blokada ekranu",QtGui.QMessageBox.Cancel)
        
        def exitBtn_Clicked(self):
                self.close()
                self.check_cycle.stop()
                #self.check_input.stop()
                GPIO.cleanup()
                
                '''try:
Exemple #52
0
class Main(QtGui.QMainWindow):
    
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        # Setup the main window
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)

        # Set date to today
        self.date = QtCore.QDate.currentDate()
        self.ui.calendarWidget.setSelectedDate(self.date)

        # Date format for SQLite
        self.date_format = "yyyy-MM-dd"

        # Used to remember the Students Id
        self.student_dict = {}
        
        # Create Attendance DB Connection Object
        self.db = AttendDB()

        # Create list models
        self.availModel = QtGui.QStandardItemModel(0, 2)
        self.attendModel = QtGui.QStandardItemModel(0, 2)

        self.ui.availListView.setModel(self.availModel)
        self.ui.attendListView.setModel(self.attendModel)

        # Connect signals to handlers
        self.connect(self.ui.addButton, QtCore.SIGNAL("clicked()"), \
                self.on_add_clicked)
        self.connect(self.ui.removeButton, QtCore.SIGNAL("clicked()"), \
                self.on_remove_clicked)
        self.connect(self.ui.calendarWidget, \
                QtCore.SIGNAL("selectionChanged()"), \
                self.on_date_change)

        self.connect(self.ui.actionEdit_Students, \
                QtCore.SIGNAL("triggered()"), \
                self.on_edit_students_select)
        # Update the lists to reflect the current date
        self.update_views()

    def on_edit_students_select(self):
        """Open the editing student window."""
        edit_window = Students()
        edit_window.exec_()

    def on_date_change(self):
        """Update views when the date is changed."""
        self.date = self.ui.calendarWidget.selectedDate()
        self.update_views()

    def update_views(self):
        """Refresh the students available and attending for the given date."""
        # Get correct date format
        self.date_string = self.date.toString(self.date_format)
        
        # Clear Models
        self.availModel.clear()
        self.attendModel.clear()
        
        for student in self.db.get_attendance_for_date(self.date_string):
            if student[1] != None and student[1] != '':
                name = str(student[1])
            else:
                name = str(student[2]) + ' ' + str(student[3])
            # Add student to the attended list view
            itemlist = [QtGui.QStandardItem(name), \
                    QtGui.QStandardItem(str(student[0]))]
            self.attendModel.appendRow(itemlist)


        for student in self.db.get_students():
            # Don't add them to available list if they attended given date
            if student[1] != None and student[1] != '':
                name = str(student[1])
            else:
                name = str(student[2]) + ' ' + str(student[3])
            # Add student to available list view
            itemlist = [QtGui.QStandardItem(name), \
                    QtGui.QStandardItem(str(student[0]))]
            if self.attendModel.findItems(name) == []:
                self.availModel.appendRow(itemlist)


        self.availModel.sort(0)
        self.attendModel.sort(0)

    
    def on_add_clicked(self):
        """Move student from available to attended list."""
        selected_indexes = self.ui.availListView.selectedIndexes()
        for index in selected_indexes:
            row = self.availModel.itemFromIndex(index).row()
            #rowList = self.availModel.takeRow(row)
            student = self.availModel.item(row, 0).text()
            sid = self.availModel.item(row, 1).text()
            try:
                # Actually add the student for the date into the database
                self.db.student_attend(sid, self.date_string)
            except KeyError:
                # Display error window if student missing
                err_msg = QtGui.QErrorMessage()
                err_msg.showMessage("Sid not found for student %s" % student)

        self.update_views()
        


    def on_remove_clicked(self):
        """Move student from attended to available list."""
        selected_indexes = self.ui.attendListView.selectedIndexes()
        for index in selected_indexes:
            row = self.attendModel.itemFromIndex(index).row()
            student = self.attendModel.item(row, 0).text()
            sid = self.attendModel.item(row, 1).text()
            try:
                # Actually add the student for the date into the database
                self.db.student_deattend(sid, self.date_string)
            except KeyError:
                # Display error window if student missing
                err_msg = QtGui.QErrorMessage()
                err_msg.showMessage("Sid not found for student %s" % student)

        self.update_views()
class MapCreatorApp(QtGui.QMainWindow):
    '''
    classdocs
    '''

    def __init__(self, parent=None):
        '''
        Constructor
        '''
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.mapView.setScene(QtGui.QGraphicsScene(0, 0, 1000, 1000))
        self.ui.mapView.scene().mousePressEvent = self.mouseClickedOnMap
#        self.ui.mapView_2.setScene(QtGui.QGraphicsScene(0, 0, 1000, 1000))
        self.ui.mapView_2.setScene(self.ui.mapView.scene())
        self.ui.mapView_3.setScene(self.ui.mapView.scene())
#        self.ui.mapView_2.scene().mousePressEvent = self.mouseClickedOnMap
        self.regions = {}
        self.continents = {} # dict of lists
        self.continentBonus = {} #dict of ints
        self.continentState = 0 # 0 = initial, 1 = addRegion 2 = removeRegion
        self.currentContinent = None
        self.chooseRegion(None)
        self.currentTabIndex = self.ui.tabWidget.currentIndex()
        self.formLinking = False
        self.removeLinking = False
        self.selectedRegion = None
        self.imageF = None
        
    def log(self, message):
#        if(self.currentTabIndex == 0):
        self.ui.logText.appendPlainText(message)
        self.ui.logText_2.appendPlainText(message)
        self.ui.logText_3.appendPlainText(message)
#        elif(self.currentTabIndex == 1):
#            self.ui.logText_2.appendPlainText(message)

    def refreshRegionList(self):
        self.ui.regionList.clear()
        for name in self.regions.keys():
            self.ui.regionList.addItem(name)

    def refreshNeighbourList(self):
        self.ui.neighbourList.clear()
        for reg in self.regions.values():
            item = ""
            item += reg.name + " : "
            for n in reg.neighbours:
                item += n + " "
            self.ui.neighbourList.addItem(item)
        #self.ui.neighbourList.addItem(reg.name + " : ")

    def startLinking(self):
        self.log("Clicked start linking button")
        if(self.currentRegion is None):
            self.log("A region has to be selected")
        elif(not (self.currentRegion is None)):
            self.formLinking = True

    def endLinking(self):
        self.log("Clicked end linking button")
        if(self.currentRegion is None):
            self.log("A region has to be selected")
        else:
            self.formLinking = False
            self.chooseRegion(None)

    def startRemoving(self):
        self.log("Clicked start canceling button")
        if(self.currentRegion is None):
            self.log("A region has to be selected")
        elif(not (self.currentRegion is None)):
            self.removeLinking = True

    def endRemoving(self):
        self.log("Clicked end canceling button")
        if(self.currentRegion is None):
            self.log("A region has to be selected")
        else:
            self.removeLinking = False
            self.chooseRegion(None)

    def beginRegion(self):
        self.log("Clicked begin region button")
        if(not (self.currentRegion is None) and not self.currentRegion.done):
            self.log("Current region is not finished")
            return 
        name = self.ui.regionName.text()
        if(name is None or name == ""):
            self.log("Region name can not be null")
        elif(name in self.regions):
            self.log("Name %s already in regions" % name)
        else:
            self.log("Adding region %s " % name)
            r = Region(name)
            self.chooseRegion(r)
            self.regions[name] = r
            self.refreshPolygon(r)
           
    def endRegion(self):
        self.log("Clicked end region button")
        if(self.currentRegion is None):
            self.log("No region to end")
        else:
            self.chooseRegion(None)
        self.refreshRegionList()
        
    def clearRegion(self):
        self.log("Clicked clear region button")
        if(self.currentRegion is None):
            self.log("No region to clear")
        else:
            id = self.currentRegion.itemp
            self.ui.mapView.scene().removeItem(id)
            del self.regions[self.currentRegion.name]
            self.chooseRegion(None)
        self.refreshRegionList()
            
    def mouseClickedOnMap(self, event):
        self.log("Mouse clicked on %f, %f" % (event.scenePos().x(), event.scenePos().y()))
        if(self.currentTabIndex == 0):
            if(self.currentRegion is None):
                point = event.scenePos()
                for v in self.regions.values():
                    p = QtGui.QPolygonF()
                    p.insert(0, point)
                    point.setX(point.x() + 1)
                    p.insert(1, point)
                    point.setY(point.y() + 1)
                    p.insert(2, point)
                    i = v.polygon.intersected(p)
                    if(i.count() > 1):
                        self.chooseRegion(v)
                        self.log("Selected region: %s" % v.name)
                        break
            else:
                self.currentRegion.addPoint(event.scenePos())
                self.refreshPolygon(self.currentRegion)
        elif(self.currentTabIndex == 1):
            point = event.scenePos()
            for v in self.regions.values():
                p = QtGui.QPolygonF()
                p.insert(0, point)
                point.setX(point.x() + 1)
                p.insert(1, point)
                point.setY(point.y() + 1)
                p.insert(2, point)
                i = v.polygon.intersected(p)
                if(i.count() > 1):
                    if((not self.formLinking) and (not self.removeLinking)):
                        self.chooseRegion(v)
                    elif(self.formLinking and (not self.removeLinking)):
                        self.addNeighbour(v)
                    elif(self.removeLinking and (not self.formLinking)):
                        self.removeNeighbour(v)
                    self.log("Selected region: %s" % v.name)
                    return
        elif(self.currentTabIndex == 2):
            point = event.scenePos()
            for v in self.regions.values():
                p = QtGui.QPolygonF()
                p.insert(0, point)
                point.setX(point.x() + 1)
                p.insert(1, point)
                point.setY(point.y() + 1)
                p.insert(2, point)
                i = v.polygon.intersected(p)
                if(i.count() > 1):
                    self.log("Clicked region: %s" % v.name)
                    if(self.continentState == 0):
                        self.log("Insignificant action")  
                    elif(self.continentState == 1):
                        if(v.continent is None):
                            self.continents[self.currentContinent].append(v.name)
                            v.continent = self.currentContinent
                            self.log("%s is added in continent %s" % (v.name, v.continent))
                        else:
                            self.log("%s is already in continent %s" % (v.name, v.continent))
                    else:
                        if(v.name in self.currentContinent and v.continent == self.currentContinent):
                            self.continents[self.currentContinent].remove(v.name)
                            v.continent = None
                            self.log("%s is removed from continent %s" % (v.name, self.currentContinent))
                        else:
                            self.log("%s is not in continent %s" % (v.name, self.currentContinent))
                    return

    def addNeighbour(self, r):
        if(r.name == self.currentRegion.name):
            self.log("%s cannot be added its own neighbours" %(r.name))
        else:
            if(not (r.name in self.currentRegion.neighbours)):
                self.currentRegion.neighbours.append(r.name)
                r.neighbours.append(self.currentRegion.name)
                self.log("%s has been added to neighbours of %s" %(r.name, self.currentRegion.name))
                self.refreshNeighbourList()
            else:
                self.log("%s has already been a neighbour of %s" %(r.name, self.currentRegion.name))

    def removeNeighbour(self, r):
        if(r.name in self.currentRegion.neighbours):
            self.currentRegion.neighbours.remove(r.name)
            r.neighbours.remove(self.currentRegion.name)
            self.log("%s has been removed from neighbours of %s" %(r.name, self.currentRegion.name))
            self.refreshNeighbourList()
        else:
            self.log("%s is not a neighbour of %s" %(r.name, self.currentRegion.name))

    def refreshPolygon(self, region):
        scene = self.ui.mapView.scene()
        scene.removeItem(region.itemp)
        region.itemp = scene.addPolygon(region.polygon, brush=QtGui.QBrush(QtGui.QColor("lightgray"), style=Qt.Qt.Dense4Pattern))

    def tabChange(self):
        if(not (self.currentRegion is None) and not self.currentRegion.done):
            self.log("Region creation is not finished")
            self.ui.tabWidget.setCurrentIndex(self.currentTabIndex)
        else:
            self.currentTabIndex = self.ui.tabWidget.currentIndex()
            if(self.currentTabIndex == 1):
                self.ui.mapView_2.setScene(self.ui.mapView.scene())

    def actionOpen(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, "Open an Image")
        self.imageF = filename
        try:
            image = QtGui.QPixmap(filename)
            item = QtGui.QGraphicsPixmapItem(image)
            self.ui.mapView.scene().clear()
            self.ui.mapView.scene().addItem(item)
            self.regions.clear()
            self.chooseRegion(None)
            self.log("opened file %s" % filename)
        except Exception as e:
            self.log("%s" % (e))

    def actionSave(self):
        self.log("Clicked save menu")
        filename = QtGui.QFileDialog.getSaveFileName(self, "Select file to save")
        self.log("Saving to file %s" % filename)
        if(self.imageF is None):
            self.log("No image file")
        else:
            copyfile(self.imageF, filename+"_image")
            self.log("Saved image file at %s" % self.imageF)
        f = open(filename, "w")
        f.write(str(len(self.regions))+"\n")
        for r in self.regions.values():
            f.write(r.name+ ",")
            f.write(r.continent+":")
            for n in r.neighbours:
                f.write(n+",")
            f.write(":")
            for i in range(r.polygon.count()):
                p = r.polygon.at(i)
                f.write(str(p.x())+"-"+str(p.y())+",")
            f.write("\n");
        f.write(str(len(self.continents))+ "\n")
        for c in self.continents:
            f.write(c+","+str(self.continentBonus[c])+"\n")
        f.flush()
        f.close()
        
    def chooseRegion(self, r):
        self.currentRegion = r
    def createContinent(self):
        self.log("Create Continent clicked")
        name = self.ui.continentNameEdit.text()
        bonus = int(self.ui.continentBonusEdit.text())
        if(name == "" or bonus <= 0 ):
            self.log("Invalid values for continent name or bonus")
        elif(name in self.continents):
            self.log("Continent %s is already defined" % name)
        else:
            self.log("Created continent %s %d" % (name, bonus))
            self.continents[name] = []
            self.continentBonus[name] = bonus
            self.ui.continentList.addItem(name)
    
    def deleteContinent(self):
        self.log("Delete Continent clicked")
        if(self.currentContinent is None):
            self.log("No continent selected")
        else:
            del self.continentBonus[self.currentContinent]
            for regionName in self.continents[self.currentContinent]:
                self.regions[regionName].continent = None
            del self.continents[self.currentContinent]
            self.ui.continentList.takeItem(self.ui.continentList.currentRow())
            self.currentContinent = None
    def addRegionToContinent(self):
        self.log("Add Region To Continent clicked")
        if(self.currentContinent is None):
            self.log("Select a continent first")
        else:
            self.continentState = 1
            self.log("Now select regions...")
    def removeRegionFromContinent(self):
        self.log("Remove Region From Continent clicked")
        if(self.currentContinent is None):
            self.log("Select a continent first")
        else:
            self.continentState = 2
            self.log("Now select regions...")
    def selectContinent(self, continent):
        self.log("Continent Selected %s " % continent.text())
        self.currentContinent = continent.text()
        self.log("Regions are:")
        for reg in self.continents[self.currentContinent]:
            self.log("\t%s" % reg)
Exemple #54
0
class MyWindowClass(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        QtCore.QObject.connect(self.ui.StartButton, QtCore.SIGNAL('clicked()'), self.doFitting_stream)
        QtCore.QObject.connect(self.ui.fitFromFile, QtCore.SIGNAL('clicked()'), self.doFitting_file)
        QtCore.QObject.connect(self.ui.fileDialog, QtCore.SIGNAL('clicked()'), self.showFileInput)
        QtCore.QObject.connect(self.ui.PauseButton, QtCore.SIGNAL('clicked()'), self.close)

    
    def fitting(self,data):
        
        print("Doing fitting")
        print(data.shape)
        scale_pixels_mm = self.ui.pixelSizeInput.value()*10e-3
    

        fit0 = frt.fit_axis(data,1) # NOTE! Axes and array indexing are messed up
        fit1 = frt.fit_axis(data,0)
        #report0 = fit_report(fit0[2])
        
        fitted_params_horiz = fit0[2].params.valuesdict()
        axis0_pos = fitted_params_horiz["r_zero"]*scale_pixels_mm
        axis0_omega = fitted_params_horiz["omega_zero"]*scale_pixels_mm
        self.ui.FitResultsHorizontal.setPlainText("")
        self.ui.FitResultsHorizontal.append("Units: mm")
        self.ui.FitResultsHorizontal.append("Peak position %.3f" % axis0_pos)
        self.ui.FitResultsHorizontal.append("Beam width %.3f" % axis0_omega)
        #self.ui.FitResultsHorizontal.append("Height above bgr %.3f" % fitted_params_horiz["I_zero"])

        fitted_params_vert = fit1[2].params.valuesdict()
        axis1_pos = fitted_params_vert["r_zero"]*scale_pixels_mm
        axis1_omega = fitted_params_vert["omega_zero"]*scale_pixels_mm
        self.ui.FitResultsVertical.setPlainText("")
        self.ui.FitResultsVertical.append("Units: mm")
        self.ui.FitResultsVertical.append("Peak position %.3f" % axis1_pos)
        self.ui.FitResultsVertical.append("Beam width %.3f" % axis1_omega)
        #self.ui.FitResultsVertical.append("Height above bgr %.2f" % fitted_params_vert["I_zero"])


        total_power = np.sum(data)
        self.ui.PowerMeter.display(total_power*10e-9)

        
        
        # Showing the beam profile itself 
        canvas_forbeam = self.ui.BeamDisplay.canvas
        canvas_forbeam.ax.pcolorfast(data)
        canvas_forbeam.draw()

        # Showing the horizontal axis fit (needs to be improved)
        canvas_forHorizFit = self.ui.xplot.canvas
        canvas_forHorizFit.ax.plot(fit0[0],fit0[1],"b-",fit0[0],mm.residual_G1D(fit0[2].params,fit0[0]),"r-")
        canvas_forHorizFit.draw()

        # Showing the vertical axis fit (needs to be improved)
        canvas_forVertFit = self.ui.yplot.canvas
        canvas_forVertFit.ax.plot(fit1[1],fit1[0],"b-",mm.residual_G1D(fit1[2].params,fit1[0]),fit1[0],"r-")
        canvas_forVertFit.draw()

    def doFitting_file(self):
        filename = self.ui.fileOutput.toPlainText()
        
        try: 
            data = frt.make_numpyarray(filename)
            self.ui.ErrorMessages.setPlainText("")
            self.fitting(data)
        except:
            self.ui.FitResultsHorizontal.setPlainText("")
            self.ui.FitResultsVertical.setPlainText("")
            self.ui.ErrorMessages.setPlainText("Something went wrong with fitting")
            return None

    def doFitting_stream(self):
        while True:
            data = imageUSB.get_image(0)
            #print(type(data[1]))
            #print(data[1].shape)
            #break
            if data[0]:
                print(data[0])
                self.fitting(data[1])
                break #somehow for now it cannot run normally in a loop, it doesn't display images and crashes
            else:
                self.ui.ErrorMessages.setPlainText("Cannot get data from camera") 
       
        

        

    def showFileInput(self):

        fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file', 
             '/home/Oleksiy/Desktop/PythonCode')
        self.ui.fileOutput.setText(fname)


    def keyPressEvent(self, e):
        
        if e.key() == QtCore.Qt.Key_Escape:
            self.close()
Exemple #55
0
class CrossingSwords(QtGui.QMainWindow):

    def gameEnded(self):
        self.playerModel.clear()
        self.players = []
        self.AIs = []
        cs_player.reset_names()

    @QtCore.Slot()
    def on_btnAddAI_clicked(self):
        self.ui.btnAddAI.setEnabled(False)
        print len(self.players) + len(self.AIs)
        if len(self.players)+len(self.AIs) >= 16:
            self.ui.btnAddAI.setEnabled(True)
            return
        name_ai = "AI%d"%len(self.AIs)
        self.playerModel.appendRow(QtGui.QStandardItem(name_ai))
        self.AIs.append(cs_player.AI())
        self.ui.btnAddAI.setEnabled(True)

    @QtCore.Slot()
    def on_leName_returnPressed(self):
        self.on_btnAddHuman_clicked()
    @QtCore.Slot()
    def on_btnAddHuman_clicked(self):
        if len(self.players)+len(self.AIs) >= 16:
            return
        if len(self.ui.leName.text()) < 1:
            return

        self.playerModel.appendRow(QtGui.QStandardItem(self.ui.leName.text()))
        self.players.append(cs_player.PlayerHuman(self.ui.leName.text()))
        self.ui.leName.setText("")

    @QtCore.Slot()
    def on_btnQuit_clicked(self):
        self.close()

    @QtCore.Slot()
    def on_btnStart_clicked(self):
        if len(self.players) + len(self.AIs) < 2:
            return

        self.game = CrossGame(self.players, self.AIs, self)
        self.game.show()
        self.hide()

    def closeEvent(self, event): 
        event.accept()

    def __init__(self, parent=None):
        super(CrossingSwords, self).__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.playerModel = QtGui.QStandardItemModel()
        self.ui.listPlayer.setModel(self.playerModel)
        
        self.setWindowTitle("Crossing Swords")

        self.players = []
        self.AIs = []
Exemple #56
0
class ControlMainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):
        super(ControlMainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.actionNew.triggered.connect(self.new)
        self.ui.actionOpen.triggered.connect(self.open)
        self.ui.actionSave.triggered.connect(self.save)

        def next_frame():
            self.change_frame(1)
        self.ui.button_next.clicked.connect(next_frame)

        def previous_frame():
            self.change_frame(-1)
        self.ui.button_previous.clicked.connect(previous_frame)

        self.tree_view_model = None
        self.ui.tree_view.clicked[QtCore.QModelIndex].connect(self.select_anim)
        self.sprite = None
        self.selected_animation = None
        self.current_frame = 0
        if ARGS.infile:
            self.load_yd(ARGS.infile.name)

    def new(self):
        pass

    def open(self):
        file_name, attr = QtGui.QFileDialog.getOpenFileName(self, 'Open file')
        try:
            self.load_yd(file_name)
        except Exception as e:
            QtGui.QMessageBox.warning(self, "Error",
                                      "Cannot load file {} ({})".format(file_name, e))
            if ARGS.verbose:
                raise

    def load_yd(self, file_name):
        self.sprite = Sprite(file_name)
        self.ui.widget_frame.setImage(self.sprite.texture)
        self.tree_view_model = QtGui.QStandardItemModel()
        parent_item = self.tree_view_model.invisibleRootItem()
        sprite_item = QtGui.QStandardItem(self.sprite.name)
        parent_item.appendRow(sprite_item)
        for anim in self.sprite.animations:
            sprite_item.appendRow(QtGui.QStandardItem(anim))
        self.ui.tree_view.setModel(self.tree_view_model)

    def select_anim(self, index):
        item = self.tree_view_model.itemFromIndex(index)
        if item.parent():
            # Item is an animation
            self.selected_animation = self.sprite.animations[item.text()]
            self.current_frame = 0
            self.ui.widget_frame.setImage(
                self.selected_animation.frames[0].texture)
        else:
            # Item is the top level sprite
            self.ui.widget_frame.setImage(self.sprite.texture)

    def change_frame(self, offset=1):
        if self.selected_animation:
            self.current_frame = (self.current_frame + offset) % len(
                self.selected_animation.frames)
            # Item is an animation
            self.ui.widget_frame.setImage(
                self.selected_animation.frames[self.current_frame].texture)

    def save(self):
        self.sprite.save()
Exemple #57
0
class VisualGit(QtGui.QMainWindow):
    """
    The main application window

    Attributes:
        open_repos: A map of absolute paths to open LocalRepositories_
    """

    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        # Load UI
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self._connect_signals_to_slots()

        # Initialize attributes
        self.open_repos = {}

    def _connect_signals_to_slots(self):
        """
        Connect all signals to their corresponding slots
        """

        # Connect action signals to their slots
        self.ui.action_open.triggered.connect(self._open_repo)

        # Connect all other signals to their slots
        self.ui.tabs_canvas.tabCloseRequested.connect(self._close_canvas_tab)

    @pyqtSlot()
    def _open_repo(self):
        """
        Prompt the user to select a local git repository to open
        """

        # Prompt the user to select a local repo with a file chooser dialog
        repo_path = QFileDialog.getExistingDirectory(self, "Open a Local Git Repository",
                                                     options=QFileDialog.ShowDirsOnly)
        # Open the selected local repo
        if repo_path:
            # If the selected repo is not already open
            if repo_path not in self.open_repos:
                # Get commit history and branches for selected repository
                repo = LocalRepository(repo_path)
                root_commit = repo.get_commit_graph()
                branches = repo.branches

                # Show the root commit's details by default
                self._show_commit_details(root_commit)

                # Add selected repo to the set of open repos
                self.open_repos[repo_path] = repo

                # Add a new Canvas tab for the repo
                canvas = QtGui.QGraphicsView()
                canvas.repo_path = repo_path
                repo_name = repo_path.rsplit("/", 1)[1]
                index = self.ui.tabs_canvas.addTab(canvas, repo_name)
                self.ui.tabs_canvas.widget(index).setStatusTip(repo_path)

                # Display repo's commit graph on a new Canvas
                q_graphics_scene = GGraphicsScene()
                canvas.setScene(q_graphics_scene)
                q_graphics_scene.render_scene(root_commit, branches)
                self.ui.tabs_canvas.setCurrentWidget(canvas)

                # Setup signals for the Canvas
                q_graphics_scene.commitnode_selected.connect(self._show_commit_details)
            else:
                # Show existing tab containing selected repo
                for i in range(0, self.ui.tabs_canvas.count()):
                    if repo_path == self.ui.tabs_canvas.widget(i).repo_path:
                        self.ui.tabs_canvas.setCurrentIndex(i)

    @pyqtSlot(int)
    def _close_canvas_tab(self, index):
        """
        Close the Canvas tab at the given index and it's corresponding
        LocalRepository_
        """

        self.open_repos.pop(self.ui.tabs_canvas.widget(index).repo_path)
        self.ui.tabs_canvas.removeTab(index)

    @pyqtSlot(Commit)
    def _show_commit_details(self, commit):
        """
        Display the details of the given commit in the Commit Explorer

        :param commit: The Commit to display
        """

        self.ui.lbl_commit_msg_header.setText(commit.message.splitlines()[0])
        self.ui.txt_commit_sha.setText(commit.sha.name)
        self.ui.txt_author_name.setText(commit.author.name)
        self.ui.txt_author_email.setText(commit.author.email)
        self.ui.txt_author_date.setText(commit.date_authored.strftime("%x"))
        self.ui.txt_author_time.setText(commit.date_authored.strftime("%X"))
        self.ui.txt_committer_name.setText(commit.committer.name)
        self.ui.txt_committer_email.setText(commit.committer.email)
        self.ui.txt_commit_date.setText(commit.date_committed.strftime("%x"))
        self.ui.txt_commit_time.setText(commit.date_committed.strftime("%X"))
        self.ui.txt_commit_msg.setText(commit.message)
from mainwindow import Ui_MainWindow
import subprocess
import os
import sys

useWindowOfMain = {}


def main():
    print()
    # refresh
    # show window


if __name__ == "__main__":
    infoCls = stockInfoCls()
    infoCls.loadIni()
    infoCls.stockInfoMaking()
    print(useWindowOfMain)

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)

    ui.sendInfoClsInst(infoCls)
    ui.do_refresh()

    MainWindow.show()
    sys.exit(app.exec_())
Exemple #59
0
def main():
    """
    The main function of the application.
     Check the input file for correctness.
     Creates the main window, the thread pool, etc.
     Connects all handlers
    :return: None
    """
    if len(sys.argv) != 2:
        sys.exit("Usage: ./main.py <video file>")
    if not os.path.isfile(sys.argv[1]):
        sys.exit("Video file is not found")

    orig_filename = os.path.abspath(sys.argv[1])
    splitted = os.path.splitext(orig_filename)
    result_filename = splitted[0] + "_edited" + splitted[1]

    try:
        ffmpeg_parse_infos(orig_filename)
    except IOError:
        sys.exit("Can't detect valid video in specified file")

    app = QtGui.QApplication([])
    app.setApplicationName("Title machine")
    window = QtGui.QMainWindow()

    ui = Ui_MainWindow()
    ui.setupUi(window)

    ui.video_seek = SeekSlider(ui.layoutWidget)
    ui.video_seek.setIconVisible(False)
    ui.video_seek.setPageStep(1000)
    ui.video_seek.setSingleStep(200)
    ui.v_layout_1.addWidget(ui.video_seek)

    ui.video_canvas = VideoCanvas()
    ui.video_canvas.set_source(orig_filename)
    ui.video_seek.setMediaObject(ui.video_canvas.media)
    ui.v_layout_1.insertWidget(0, ui.video_canvas)

    pool = Pool(1)
    log_watcher = QtCore.QFileSystemWatcher([os.path.dirname(result_filename)])

    ui.button_process.clicked.connect(
        on_process_clicked(ui, orig_filename, result_filename, pool))
    ui.button_add_caption.clicked.connect(on_add_caption_clicked(ui))
    ui.button_remove_caption.clicked.connect(on_remove_caption_clicked(ui))
    ui.table_captions.cellChanged.connect(on_tablewidget_cell_changed(ui))

    ui.button_play_pause.clicked.connect(on_button_play_pause_clicked(ui))
    ui.video_canvas.media.stateChanged.connect(on_video_state_changed(ui))
    ui.video_canvas.media.tick.connect(on_video_tick(ui))
    ui.video_canvas.media.totalTimeChanged.connect(on_video_total_time_changed)

    log_watcher.directoryChanged.connect(on_log_dir_changed(log_watcher, result_filename))
    log_watcher.fileChanged.connect(on_log_file_changed(ui, log_watcher))
    app.lastWindowClosed.connect(on_app_quit(ui, pool))

    ui.textbrowser_log.insertPlainText("Welcome to Title Machine!")
    ui.video_canvas.media.pause()
    window.show()

    app.exec_()
Exemple #60
0
class MainWindow(QMainWindow):
    def __init__(self, args, parent=None):
        super(MainWindow, self).__init__(parent)
        self.timeoutFunction = None
        self.staticAlertMessage = ""
        self.timeoutLength = 15
     
        self.openfile = None
        self.filename = "UNKNOWN FILE"

        # Store Ui() as class variable self.ui
        self.ui = Ui()
        self.ui.setupUi(self)
        self.setWindowTitle('Qif') 

        self.ui.accountsWidget.setStatusTip("Accounts")
        self.ui.accountsWidget.setFrameShape(PySide.QtGui.QFrame.Box)
        self.ui.accountsWidget.installEventFilter(self)
        self.ui.accountsWidget.itemDoubleClicked.connect(self.doubleClickAccount)
        self.ui.accountsWidget.itemClicked.connect(self.singleClickAccount)
        #print self.ui.accountsWidget.__dict__.keys()

        self.ui.totalsAccounts.setStatusTip("Account Totals")
        self.ui.totalsAccounts.setFrameShape(PySide.QtGui.QFrame.Box)
        self.ui.totalsAccounts.installEventFilter(self)

        self.ui.categoriesWidget.setStatusTip("Spending/Saving Categories")
        self.ui.categoriesWidget.setFrameShape(PySide.QtGui.QFrame.Box)
        self.ui.categoriesWidget.installEventFilter(self)
        self.ui.categoriesWidget.itemDoubleClicked.connect(self.doubleClickCategory)
        self.ui.categoriesWidget.itemClicked.connect(self.singleClickCategory)

        self.ui.totalsCategories.setStatusTip("Category Totals")
        self.ui.totalsCategories.setFrameShape(PySide.QtGui.QFrame.Box)
        self.ui.totalsCategories.installEventFilter(self)

        self.ui.textEdit.setStatusTip("File Editor")
        self.ui.textEdit.setFrameShape(PySide.QtGui.QFrame.Box)
        self.ui.textEdit.installEventFilter(self)
        self.ui.textEdit.setAcceptRichText(False)
        
        wincol = self.palette().color(QPalette.Window); 
        self.ui.lineEdit.setStyleSheet("background-color: %s;"%wincol.name())
        self.ui.lineEdit.setStatusTip("Command Line")
        self.ui.lineEdit.installEventFilter(self)

        self.ui.centralWidget.installEventFilter(self)

        self.history = History()
        
        # read in settings to determine whether we should use single click or not.
        #self.ui.actionSingleClickToOpen.setChecked(True)
        self.ui.actionSaveFile.triggered.connect(self.saveOpenFile)

        # read in settings to determine if there's a working directory:
        root = "." # use this as a guess for root directory
        self.rootdir, self.YYYY, self.mm = getrootYYYYmm(args, root)
        self.showAll()

        self.ui.centralWidget.setFocus(QtCore.Qt.OtherFocusReason)

    def requestDirectory(self):
        self.rootdir = QFileDialog.getExistingDirectory(self, 
            "Set Working Directory", ".",
            QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks)
        self.showAll()

    def about(self):
        '''Popup a box with about message.'''
        QMessageBox.about(self, "About Qif, PySide, and Platform",
                """<b> qif.py version %s </b> 
                <p>Copyright &copy; 2016 by Lucas Wagner, MIT License.</p> 
                <p>Python %s -  PySide version %s - Qt version %s on %s""" %
                (__version__, platform.python_version(), PySide.__version__,
                 PySide.QtCore.__version__, platform.system()))                        

    def eventFilter(self, widget, event):
        if event.type() == QtCore.QEvent.KeyPress:
            key = event.key()
            if widget == self.ui.lineEdit: # command line
                if key == QtCore.Qt.Key_Escape:
                    self.history.clearCommand(self.ui.lineEdit.text())
                    self.ui.lineEdit.setText("")
                    self.ui.centralWidget.setFocus(QtCore.Qt.OtherFocusReason)
                    return True
                elif key == QtCore.Qt.Key_Return:
                    thetext = self.ui.lineEdit.text()
                    self.execute(thetext)
                    self.history.appendCommand(thetext)
                    self.ui.lineEdit.setText("")
                    return True
                elif key == QtCore.Qt.Key_Up:
                    self.ui.lineEdit.setText(
                        self.history.previousCommand(self.ui.lineEdit.text())
                    )
                    return True
                elif key == QtCore.Qt.Key_Down:
                    self.ui.lineEdit.setText(
                        self.history.nextCommand(self.ui.lineEdit.text())
                    )
                    return True
            else:
                if key == QtCore.Qt.Key_Escape:
                    if widget == self.ui.centralWidget:
                        self.ui.lineEdit.setFocus(QtCore.Qt.OtherFocusReason)
                    else:
                        self.ui.centralWidget.setFocus(QtCore.Qt.OtherFocusReason)
                    return True
                elif widget == self.ui.textEdit:
                    # we're in the textEdit
                    #if self.openfile:
                    #    self.alert("Editing %s"%self.filename)
                    return False
                    # don't return True, we want the key to go through to the textEdit
                elif (key == QtCore.Qt.Key_Slash or 
                    key == QtCore.Qt.Key_Question or 
                    key == QtCore.Qt.Key_Colon or
                    key == QtCore.Qt.Key_Semicolon):
                    self.ui.lineEdit.setFocus(QtCore.Qt.OtherFocusReason)
                    return True
                elif widget == self.ui.centralWidget:
                    if key == QtCore.Qt.Key_S:
                        self.saveOpenFile()
                        return True
                else:
                    if key == QtCore.Qt.Key_Return:
                        if widget == self.ui.categoriesWidget:
                            selitems = widget.selectedItems()
                            if selitems:
                                self.loadCategoryItem(selitems[0])
                        elif widget == self.ui.accountsWidget:
                            selitems = widget.selectedItems()
                            if selitems:
                                self.loadAccountItem(selitems[0])
                        return True
        return False

    def singleClickAccount(self, account):
        if self.ui.actionSingleClickToOpen.isChecked():
            self.loadAccountItem(account)

    def doubleClickAccount(self, account):
        if not self.ui.actionSingleClickToOpen.isChecked():
            self.loadAccountItem(account)
    
    def singleClickCategory(self, category):
        if self.ui.actionSingleClickToOpen.isChecked():
            self.loadCategoryItem(category)

    def doubleClickCategory(self, category):
        if not self.ui.actionSingleClickToOpen.isChecked():
            self.loadCategoryItem(category)

    def loadAccountItem(self, account):
        filename = account.text().split("\n")[0]
        # find first parentheses group:
        filename = filename[0:filename.find(" ")]
        self.ui.categoriesWidget.clearSelection()
        self.loadFile(filename)

    def loadCategoryItem(self, category):
        filename = category.text().split("\n")[0]
        if "BUSINESS" not in filename:
            self.ui.accountsWidget.clearSelection()
            self.loadFile(filename)
    
    def clearAlert(self):
        self.ui.statusBar.showMessage(self.staticAlertMessage)
        
    def alert(self, text, timeout=0):
        if self.timeoutFunction is not None:
            self.timeoutFunction.cancel()
        self.ui.statusBar.showMessage(text)
        if timeout <= 0:
            self.staticAlertMessage = text
            return
        self.timeoutFunction = Timer(timeout, self.clearAlert)
        self.timeoutFunction.start()

    def execute(self, command):
        if len(command) > 0:
            if command == "q" or command == "quit" or command == "exit":
                self.close()
            elif command[0].isnumeric():
                try:
                    result = eval_math(command)
                    self.ui.statusBar.showMessage(str(result)+"     = "+command)
                except:
                    self.ui.statusBar.showMessage("invalid math")
            else:
                split = command.split()
                if split[0] == "s" or split[0] == "save":
                    self.saveOpenFile()

                elif split[0] == "e" or split[0] == "edit":
                    if len(split) == 1:
                        self.loadFile("scratch")
                    else: 
                        self.loadFile(split[1])
                    return # return to avoid setting focus to the default

                elif split[0] == "load" or split[0] == "open" or split[0] == "o":
                    if len(split) == 1:
                        self.alert("use load YYYY/mm, or open mm", self.timeoutLength)
                    else:
                        root, YYYY, mm = getrootYYYYmm(split, self.rootdir)
                        if root:
                            self.rootdir = root
                            self.YYYY = YYYY
                            self.mm = mm
                            self.showAll()
                        else:
                            self.alert("Invalid directory!", self.timeoutLength)
                
                elif split[0] == "reload":
                    self.showAll()

                elif command == "generate":
                    if self.month.generatenextmonth():
                        self.alert("next month already exists.  type GENERATE to force.", self.timeoutLength)
                    else:
                        self.alert("%s generated!"%self.month.nextyearmonth, self.timeoutLength)
                
                elif command == "GENERATE":
                    self.month.generatenextmonth( True )
                    self.alert("%s re-generated!"%self.month.nextyearmonth, self.timeoutLength)

                else:
                    self.alert('unknown command: '+command, self.timeoutLength)

        self.ui.centralWidget.setFocus(QtCore.Qt.OtherFocusReason) # default focus after running a command

    def resizeEvent(self, event):
        super(MainWindow, self).resizeEvent(event)
        h = event.size().height()
        w = event.size().width()
        if sys.platform == "darwin":
            if w < h or w < 600:
                # not very wide.
                self.ui.accountsWidget.resize(w/2-4, h/2-28)
                self.ui.accountsWidget.move(2,2)
                self.ui.totalsAccounts.resize(w/2-4,80)
                self.ui.totalsAccounts.move(2,h/2-22)
                self.ui.categoriesWidget.resize(w/2-4, h/2-28)
                self.ui.categoriesWidget.move(w/2+2, 2)
                self.ui.totalsCategories.resize(w/2-4,80)
                self.ui.totalsCategories.move(w/2+2,h/2-22)

                self.ui.textEdit.resize(w-4, h/2-104)
                self.ui.textEdit.move(2, h/2+62)
                
                self.ui.lineEdit.resize(w-4, 32)
                self.ui.lineEdit.move(2, h-50)
            else:
                # wide screen
                self.ui.accountsWidget.resize(w/4-4, h-138)
                self.ui.accountsWidget.move(2,2)
                self.ui.totalsAccounts.resize(w/4-4,80)
                self.ui.totalsAccounts.move(2,h-132)
                self.ui.categoriesWidget.resize(w/4-4, h-138)
                self.ui.categoriesWidget.move(w/4+2, 2)
                self.ui.totalsCategories.resize(w/4-4,80)
                self.ui.totalsCategories.move(w/4+2,h-132)

                self.ui.textEdit.resize(w/2-4, h-54)
                self.ui.textEdit.move(w/2+2, 2)
                
                self.ui.lineEdit.resize(w-4, 32)
                self.ui.lineEdit.move(2, h-50)
        else: # linux and windows
            if w < h or w < 600:
                # not very wide.
                self.ui.accountsWidget.resize(w/2-4, h/2-46)
                self.ui.accountsWidget.move(2,0)
                self.ui.totalsAccounts.resize(w/2-4,120)
                self.ui.totalsAccounts.move(2,h/2-42)
                self.ui.categoriesWidget.resize(w/2-4, h/2-46)
                self.ui.categoriesWidget.move(w/2+2, 0)
                self.ui.totalsCategories.resize(w/2-4,120)
                self.ui.totalsCategories.move(w/2+2,h/2-42)

                self.ui.textEdit.resize(w-4, h/2-169)
                self.ui.textEdit.move(2, h/2+82)
                
                self.ui.lineEdit.resize(w-4, 32)
                self.ui.lineEdit.move(2, h-86)
            else:
                # wide screen
                self.ui.accountsWidget.resize(w/4-4, h-172)
                self.ui.accountsWidget.move(2,0)
                self.ui.totalsAccounts.resize(w/4-4,80)
                self.ui.totalsAccounts.move(2,h-168)
                self.ui.categoriesWidget.resize(w/4-4, h-172)
                self.ui.categoriesWidget.move(w/4+2, 0)
                self.ui.totalsCategories.resize(w/4-4,80)
                self.ui.totalsCategories.move(w/4+2,h-168)

                self.ui.textEdit.resize(w/2-4, h-88)
                self.ui.textEdit.move(w/2+2, 0)
                
                self.ui.lineEdit.resize(w-4, 32)
                self.ui.lineEdit.move(2, h-86)
   
    def showAll(self):
        self.ui.accountsWidget.clear()
        self.ui.totalsAccounts.clear()
        self.ui.categoriesWidget.clear()
        self.ui.totalsCategories.clear()

        if self.rootdir:
            self.month = Month(self.rootdir, self.YYYY, self.mm)
            self.month.grandtotal()
            self.showAccounts()
            self.showCategories()
        else:
            self.ui.accountsWidget.addItem("Choose a working directory.")

    def showAccounts(self):
        starttotaldough = Dough(0)
        endtotaldough = Dough(0)

        accounts = self.month.accountlist.keys()
        accounts.sort()
        for account in accounts:
            accountname = self.month.accountlist[account]
            itemtext = [ account, " (%s):"%accountname ]
            try:
                sbalance = self.month.categories[account.upper()].metavalues["startingbalance"]
            except KeyError:
                sbalance = Dough(0)
            itemtext.append("\n start ")
            itemtext.append(str(sbalance))
            starttotaldough += sbalance

            ebalance = self.month.categories[account.upper()].metavalues["endingbalance"]
            itemtext.append("\n   end ")
            itemtext.append(str(ebalance))
            endtotaldough += ebalance
            
            self.ui.accountsWidget.addItem("".join(itemtext))

        self.ui.totalsAccounts.addItem("Totals:")
        self.ui.totalsAccounts.addItem(" start "+ str(starttotaldough.clean()))
        self.ui.totalsAccounts.addItem(" delta "+ str(endtotaldough-starttotaldough))
        self.ui.totalsAccounts.addItem("   end "+ str(endtotaldough.clean()))

    def showCategory(self, cat):
        # if not an account, it's a category we can analyze more
        if cat.metaflags["business"]:
            itemtext = ["Business ", str(cat.name)]
        else:
            itemtext = [str(cat.name)]

        if cat.metaflags["income"]:
            catactual = cat.metavalues["changeactual"]
            catbudget = cat.metavalues["changebudget"]
            if catactual != catbudget:
                catend = cat.metavalues["endingbalance"]
                if catend != 0:
                    itemtext.append("\n average "+str(catbudget)) 
                    itemtext.append("\n   swing "+str(catend)) 
                else:
                    itemtext.append("\n     got "+str(catactual)) 
                    itemtext.append("\n average "+str(catbudget)) 
            else:
                itemtext.append("\n     got "+str(catactual)) 
        else:
            try:
                catbudget = cat.metavalues["budget"].clean()
                #budgetenough = False
            except KeyError:
                # assume budget enough
                #budgetenough = True
                catbudget = -cat.metavalues["changebudget"].clean()
          
            if not cat.metaflags["business"]:
                itemtext.append("\n budget "+str(catbudget))

            try:
                catchange = -cat.metavalues["changeactual"]
            except KeyError:
                catchange = Dough(0)
           
            if catchange != 0:
                itemtext.append("\n  spent "+str(catchange))
            
            try:
                catbalance = cat.metavalues["endingbalance"]
            except KeyError:
                catbalance = Dough(0)
            
            if catbalance != Dough(0):
                itemtext.append("\n   left "+str(catbalance))

        self.ui.categoriesWidget.addItem("".join(itemtext))

    def showCategories(self):
        sortedcategories = (self.month.categories.keys())
        sortedcategories.sort()
        businesscats = []
        showbusiness = False
        for category in sortedcategories:
            cat = self.month.categories[category]
            # don't print accounts here, or business categories (yet)
            if not cat.metaflags["account"]: 
                if cat.metaflags["business"]:
                    businesscats.append(cat)
                else:
                    self.showCategory(cat)
        
        delta = (self.month.monthlyexpectedincome-self.month.monthlyexpectedoutpour)
        delta.clean()
        self.ui.totalsCategories.addItem(
            "Budgeted income - outpour:\n  %s"%delta
        )
        self.ui.totalsCategories.addItem(
            "Accumulated anti-savings:\n  %s"%self.month.accumulatedantisavings
        )

       
        if businesscats:
            self.ui.categoriesWidget.addItem("BUSINESS CATEGORIES")
            # now print business categories
            for cat in businesscats:
                self.showCategory(cat)
        else:
            self.ui.categoriesWidget.addItem("NO BUSINESS")

    def loadFile(self, filename):
        self.openfile = None
        print("Loading file", filename)
        if " " not in filename:
            if filename == "scratch":
                self.openfile = os.path.join(self.rootdir, filename)
            else: 
                self.openfile = os.path.join(self.rootdir, self.YYYY, self.mm, filename)
            self.filename = filename
        else:
            filename = filename.split(" ")
            if len(filename) == 2 and filename[0] == "Business":
                self.filename = filename[1]
                self.openfile = os.path.join(self.rootdir, self.YYYY, self.mm, self.filename)

        lines = unicode("LOAD ERROR")
        if self.openfile:
            self.alert("Editing %s"%self.filename)
            self.ui.textEdit.setStatusTip("Editing %s"%self.filename)
            self.ui.textEdit.setFocus(QtCore.Qt.OtherFocusReason)
            with open(self.openfile, 'r') as f:
                lines = f.read()
        self.ui.textEdit.setText(lines)
   
    def saveOpenFile(self):
        if self.openfile:
            with open(self.openfile, 'w') as f:
                f.write(self.ui.textEdit.toPlainText())
            self.showAll()
            self.alert("%s saved!"%self.filename, self.timeoutLength)
        else:
            self.alert("No file opened, cannot save", self.timeoutLength)