Beispiel #1
2
    def view(self):
        """create view and import layers"""
        layer = QgsMapLayerRegistry.instance().mapLayer(
                self.current_layers[0] )
        uri = QgsDataSourceURI(layer.source())
        mtch = re.match(r'(.+)_([^_]+)_rev_(head|\d+)', uri.schema())
        schema = mtch.group(1)
        assert(schema)
        dlg = QDialog()
        layout = QVBoxLayout(dlg)
        button_box = QDialogButtonBox(dlg)
        button_box.setStandardButtons(
                QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
        button_box.accepted.connect(dlg.accept)
        button_box.rejected.connect(dlg.reject)

        pcur = versioning_base.Db( psycopg2.connect(self.pg_conn_info()) )
        pcur.execute("SELECT rev, commit_msg, branch, date, author "
            "FROM "+schema+".revisions")
        revs = pcur.fetchall()
        pcur.close()
        tblw = QTableWidget( dlg )
        tblw.setRowCount(len(revs))
        tblw.setColumnCount(5)
        tblw.setSortingEnabled(True)
        tblw.setHorizontalHeaderLabels(['Revision', 'Commit Message',
                                      'Branch', 'Date', 'Author'])
        tblw.verticalHeader().setVisible(False)
        for i, rev in enumerate(revs):
            for j, item in enumerate(rev):
                tblw.setItem(i, j, QTableWidgetItem( str(item) ))
        layout.addWidget( tblw )
        layout.addWidget( button_box )
        dlg.resize( 600, 300 )
        if not dlg.exec_() :
            return

        rows = set()
        for i in tblw.selectedIndexes():
            rows.add(i.row())
        for row in rows:
            branch = revs[row][2]
            rev = revs[row][0]
            versioning_base.add_revision_view(uri.connectionInfo(),
                    schema, branch, rev )
            grp_name = branch+' revision '+str(rev)
            grp_idx = self.iface.legendInterface().addGroup( grp_name )
            for layer_id in reversed(self.current_layers):
                layer = QgsMapLayerRegistry.instance().mapLayer(layer_id)
                new_uri = QgsDataSourceURI(layer.source())
                new_uri.setDataSource(schema+'_'+branch+'_rev_'+str(rev),
                        new_uri.table(),
                        new_uri.geometryColumn(),
                        new_uri.sql(),
                        new_uri.keyColumn())
                display_name =  QgsMapLayerRegistry.instance().mapLayer(layer_id).name()
                src = new_uri.uri().replace('()','')
                new_layer = self.iface.addVectorLayer( src,
                        display_name, 'postgres')
                self.iface.legendInterface().moveLayer( new_layer, grp_idx)
Beispiel #2
0
class ApHlasConfDlg(QDialog):
    def __init__(self, width, height, parent = None):
        super(ApHlasConfDlg, self).__init__(parent)
        
        table1 = QTableWidget(5, 5)
        table1.connect(table1, SIGNAL("cellActivated(int, int)"), self.showTags)
        table1.connect(table1, SIGNAL("cellClicked(int, int)"), self.showTags)
        it1 = QTableWidgetItem("Hello")
        table1.setItem(0, 0, it1)

        hdview = QHeaderView(Qt.Horizontal)
        hdview.setStretchLastSection(True)
        self.tagsTable = QTableWidget(5,1)
        self.tagsTable.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        self.tagsTable.setHorizontalHeader(hdview)
        self.tagsTable.setHorizontalHeaderLabels(['tags'])
        l = QHBoxLayout(self)
        l.addWidget(table1)
        l.addWidget(self.tagsTable)

    def showTags(self, row, col):
        for i in range(3):
            print i
            it = self.tagsTable.item(i, 0)
            if it is None: 
                print "New an item at ", i, 0
                it = QTableWidgetItem("tags: %d (%d,%d)" % (i, row, col))
                self.tagsTable.setItem(i, 0, it)
            else:
                print "Existing item", i, 0
                it.setText("this is a very long tags: %d (%d,%d)" % (i, row, col))
Beispiel #3
0
def createList(labelText, slot, changedSlot, validator=None):
    widget = QWidget()
    layout = QVBoxLayout()
    layout.setObjectName('listLayout')
    widget.setLayout(layout)
    hboxWidget = QWidget()
    hboxLayout = QHBoxLayout()
    hboxLayout.setObjectName('hboxLayout for tableWidget')
    hboxWidget.setLayout(hboxLayout)
    tableWidget = QTableWidget(0, 2)
    tableWidget.setAlternatingRowColors(True)
    widget.connect(tableWidget, SIGNAL('cellChanged(int, int)'), changedSlot)
    tableWidget.setHorizontalHeaderLabels(createQStringList([labelText, '']))
    tableWidget.setColumnWidth(INPUT_IDX, contentColumnWidth)
    tableWidget.setColumnWidth(BUTTON_IDX, deleteButtonColumnWidth)
    hboxLayout.addWidget(tableWidget)

    add = QWidget()
    addLayout = QHBoxLayout()
    addLayout.setObjectName('addLayout')
    add.setLayout(addLayout)
    addLineEdit = createLineEdit(add, None, validator)
    addButton = createButton(translate('MainWindow', 'Add'), add, add,
            slot)
    add.connect(addLineEdit, SIGNAL('returnPressed()'), slot)
    for wid in addLineEdit, addButton:
        addLayout.addWidget(wid)

    for wid in add, hboxWidget:
        layout.addWidget(wid)
    return (widget, tableWidget, addLineEdit)
Beispiel #4
0
    def create_weights_widget(self):
        def add_item():
            row = table_widget.rowCount()
            item = QTableWidgetItem()
            item.setData(Qt.EditRole, 1.)
            table_widget.insertRow(row)
            table_widget.setItem(row, 0, item)

        def change_all_rows(new_rows):
            for i in xrange(table_widget.rowCount(), -1, -1):
                table_widget.removeRow(i)
            for i, value in enumerate(new_rows):
                item = QTableWidgetItem()
                item.setData(Qt.EditRole, value)
                table_widget.insertRow(i)
                table_widget.setItem(i, 0, item)

        def change_item(x, y):
            val = float(table_widget.item(x, y).text())
            self.signals.change_weight.emit(x, val)

        table_widget = QTableWidget(0, 1)
        table_widget.verticalHeader().setDefaultSectionSize(20)
        table_widget.setHorizontalHeaderLabels([QString("weights")])
        self.signals.new_point.connect(add_item)
        self.signals.delete_point.connect(table_widget.removeRow)
        self.signals.change_weights.connect(change_all_rows)
        table_widget.cellChanged.connect(change_item)
        return table_widget
def create_table_widget(table, parent):
    formats = table.getColFormats()
    names = table.getColNames()
    indices_of_visible_columns = [
        j for (j, f) in enumerate(formats) if f is not None
    ]
    headers = ["ok"] + [names[j] for j in indices_of_visible_columns]
    n_rows = len(table)

    widget = QTableWidget(n_rows,
                          1 + len(indices_of_visible_columns),
                          parent=parent)
    widget.setHorizontalHeaderLabels(headers)
    widget.setMinimumSize(200, 200)

    widget.horizontalHeader().setResizeMode(QHeaderView.Interactive)

    for i, row in enumerate(table.rows):
        item = QTableWidgetItem()
        item.setCheckState(Qt.Unchecked)
        item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable
                      | Qt.ItemIsUserCheckable)
        widget.setItem(i, 0, item)
        for j0, j in enumerate(indices_of_visible_columns):
            value = row[j]
            formatter = table.colFormatters[j]
            item = QTableWidgetItem(formatter(value))
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
            widget.setItem(i, j0 + 1, item)
    return widget
Beispiel #6
0
def create_table_widget(table, parent):
    formats = table.getColFormats()
    names = table.getColNames()
    indices_of_visible_columns = [j for (j, f) in enumerate(formats) if f is not None]
    headers = ["ok"] + [names[j] for j in indices_of_visible_columns]
    n_rows = len(table)

    widget = QTableWidget(n_rows, 1 + len(indices_of_visible_columns), parent=parent)
    widget.setHorizontalHeaderLabels(headers)
    widget.setMinimumSize(200, 200)

    widget.horizontalHeader().setResizeMode(QHeaderView.Interactive)

    for i, row in enumerate(table.rows):
        item = QTableWidgetItem()
        item.setCheckState(Qt.Unchecked)
        item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable)
        widget.setItem(i, 0, item)
        for j0, j in enumerate(indices_of_visible_columns):
            value = row[j]
            formatter = table.colFormatters[j]
            item = QTableWidgetItem(formatter(value))
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
            widget.setItem(i, j0 + 1, item)
    return widget
Beispiel #7
0
    def view(self):
        """create view and import layers"""
        layer = QgsMapLayerRegistry.instance().mapLayer(self.current_layers[0])
        uri = QgsDataSourceURI(layer.source())
        mtch = re.match(r'(.+)_([^_]+)_rev_(head|\d+)', uri.schema())
        schema = mtch.group(1)
        assert (schema)
        dlg = QDialog()
        layout = QVBoxLayout(dlg)
        button_box = QDialogButtonBox(dlg)
        button_box.setStandardButtons(QDialogButtonBox.Cancel
                                      | QDialogButtonBox.Ok)
        button_box.accepted.connect(dlg.accept)
        button_box.rejected.connect(dlg.reject)

        pcur = versioning_base.Db(psycopg2.connect(self.pg_conn_info()))
        pcur.execute("SELECT rev, commit_msg, branch, date, author "
                     "FROM " + schema + ".revisions")
        revs = pcur.fetchall()
        pcur.close()
        tblw = QTableWidget(dlg)
        tblw.setRowCount(len(revs))
        tblw.setColumnCount(5)
        tblw.setSortingEnabled(True)
        tblw.setHorizontalHeaderLabels(
            ['Revision', 'Commit Message', 'Branch', 'Date', 'Author'])
        tblw.verticalHeader().setVisible(False)
        for i, rev in enumerate(revs):
            for j, item in enumerate(rev):
                tblw.setItem(i, j, QTableWidgetItem(str(item)))
        layout.addWidget(tblw)
        layout.addWidget(button_box)
        dlg.resize(600, 300)
        if not dlg.exec_():
            return

        rows = set()
        for i in tblw.selectedIndexes():
            rows.add(i.row())
        for row in rows:
            branch = revs[row][2]
            rev = revs[row][0]
            versioning_base.add_revision_view(uri.connectionInfo(), schema,
                                              branch, rev)
            grp_name = branch + ' revision ' + str(rev)
            grp_idx = self.iface.legendInterface().addGroup(grp_name)
            for layer_id in reversed(self.current_layers):
                layer = QgsMapLayerRegistry.instance().mapLayer(layer_id)
                new_uri = QgsDataSourceURI(layer.source())
                new_uri.setDataSource(
                    schema + '_' + branch + '_rev_' + str(rev),
                    new_uri.table(), new_uri.geometryColumn(), new_uri.sql(),
                    new_uri.keyColumn())
                display_name = QgsMapLayerRegistry.instance().mapLayer(
                    layer_id).name()
                src = new_uri.uri().replace('()', '')
                new_layer = self.iface.addVectorLayer(src, display_name,
                                                      'postgres')
                self.iface.legendInterface().moveLayer(new_layer, grp_idx)
class FindHandleDialog(QDialog):
    def __init__(self, model, parent):
        super().__init__(parent)
        self.model = model
        self.setModal(False)
        self.setAttribute(Qt.WA_DeleteOnClose)
        # QDialogs at least in GNOME do not have a close button by default
        self.setWindowFlags(Qt.Window | Qt.WindowSystemMenuHint | Qt.WindowCloseButtonHint)
        self.setWindowTitle('Linux Process Explorer Search')
        self.setGeometry(0, 0, 900, 500)
        self.move((parent.width() - self.width()) / 2 + parent.x(),
                  (parent.height() - self.height()) / 2 + parent.y())

        lblSearch = QLabel('Descriptor or Lib substring:')
        self.txtSearch = QLineEdit()
        btnSearch = QPushButton('&Search')
        btnSearch.clicked.connect(self.onBtnSearchClicked)
        btnCancel = QPushButton('&Cancel')
        searchLayout = QHBoxLayout()
        searchLayout.addWidget(lblSearch)
        searchLayout.addWidget(self.txtSearch)
        searchLayout.addWidget(btnSearch)
        searchLayout.addWidget(btnCancel)
        self.tblResults = QTableWidget(0, 4)
        self.tblResults.setHorizontalHeaderLabels(('Process', 'PID', 'Type', 'Name'))
        self.tblResults.horizontalHeader().setStretchLastSection(True)
        self.tblResults.verticalHeader().setVisible(False)
        self.tblResults.setShowGrid(False)
        self.tblResults.setSelectionBehavior(QTableWidget.SelectRows)
        self.tblResults.verticalHeader().setDefaultSectionSize(24)
        mainLayout = QVBoxLayout()
        mainLayout.addLayout(searchLayout)
        mainLayout.addWidget(self.tblResults)
        self.setLayout(mainLayout)

    @pyqtSlot(bool)
    def onBtnSearchClicked(self, checked=False):
        handleSubstr = self.txtSearch.text()
        if handleSubstr:
            results = self.model.findHandlesBySubstr(handleSubstr)
            self.tblResults.setRowCount(len(results))
            for row, res in enumerate(results):
                for col, prop in enumerate(res):
                    item = QTableWidgetItem(str(prop))
                    item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                    self.tblResults.setItem(row, col, item)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Enter and self.txtSearch.hasFocus():
            self.onBtnSearchClicked()
            return
        super().keyPressEvent(event)
Beispiel #9
0
class AccountManagerDialog(QDialog):
    def __init__(self, emails, types, parent):
        self.emails, self.types = emails, types
        QDialog.__init__(self, parent)
        self.resize(560, 350)
        self.gridLayout = QGridLayout(self)
        self.tableWidget = QTableWidget(0, 2, self)
        self.tableWidget.setAlternatingRowColors(True)
        self.tableWidget.setSelectionBehavior(1)  # Rows
        self.tableWidget.setSelectionMode(1)  # Single
        self.tableWidget.horizontalHeader().setResizeMode(0, 1)  # 1 = Stretch
        self.tableWidget.setHorizontalHeaderLabels(['Email', 'Type'])
        self.addBtn = QPushButton('+', self)
        self.removeBtn = QPushButton('-', self)
        self.closeBtn = QPushButton('Close', self)
        self.spacer = QWidget(self)
        self.spacer.setSizePolicy(1 | 2 | 4, 1 | 4)
        self.gridLayout.addWidget(self.tableWidget, 0, 0, 1, 4)
        self.gridLayout.addWidget(self.addBtn, 1, 0, 1, 1)
        self.gridLayout.addWidget(self.removeBtn, 1, 1, 1, 1)
        self.gridLayout.addWidget(self.spacer, 1, 2, 1, 1)
        self.gridLayout.addWidget(self.closeBtn, 1, 3, 1, 1)
        self.addBtn.clicked.connect(self.addAccount)
        self.removeBtn.clicked.connect(self.removeAccount)
        self.closeBtn.clicked.connect(self.accept)
        for i in range(len(self.emails)):
            self.tableWidget.insertRow(i)
            self.tableWidget.setItem(i, 0, QTableWidgetItem(emails[i]))
            self.tableWidget.setItem(i, 1, QTableWidgetItem(types[i]))

    def addAccount(self):
        dialog = AddAccountDialog(self)
        if dialog.exec_() != QDialog.Accepted: return
        email = unicode(dialog.emailEdit.text())
        passwd = unicode(dialog.passwordEdit.text())
        ac_type = unicode(dialog.typeCombo.currentText())
        self.tableWidget.insertRow(0)
        self.tableWidget.setItem(0, 0, QTableWidgetItem(email))
        self.tableWidget.setItem(0, 1, QTableWidgetItem(ac_type))
        self.emails.insert(0, email)
        self.types.insert(0, ac_type)
        kr = Keyring()
        kr.setPassword(email, passwd)

    def removeAccount(self):
        row = self.tableWidget.selectionModel().selectedRows()[0].row()
        email = self.tableWidget.item(row, 0).text()
        kr = Keyring()
        kr.deletePassword(email)
        self.tableWidget.removeRow(row)
        self.emails.pop(row)
        self.types.pop(row)
Beispiel #10
0
 def addWidgets(self):
     layout = QVBoxLayout()
     self.setLayout(layout)
     preamble = QLabel(self)
     layout.addWidget(preamble)
     self.preamble = preamble
     layout.addSpacing(10)
     table = QTableWidget(self)
     layout.addWidget(table)
     table.setShowGrid(False)
     table.setSelectionBehavior(QTableWidget.SelectRows)
     table.setSelectionMode(QTableWidget.SingleSelection)
     table.setMinimumWidth(400)
     table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     table.setColumnCount(4)
     table.hideColumn(0)
     table.setHorizontalHeaderLabels(
         ['ID', 'Vault', '# of Items', '# of Peers'])
     table.setFocusPolicy(Qt.NoFocus)
     table.itemSelectionChanged.connect(self.rowSelected)
     hhead = table.horizontalHeader()
     hhead.setResizeMode(QHeaderView.Stretch)
     hhead.setHighlightSections(False)
     vhead = table.verticalHeader()
     vhead.hide()
     self.table = table
     hbox = QHBoxLayout()
     layout.addLayout(hbox)
     button = QPushButton('Create Vault', self)
     button.clicked.connect(self.createVault)
     hbox.addWidget(button)
     button = QPushButton('Connect to Vault', self)
     backend = QApplication.instance().backend()
     available = backend.locator_is_available()
     if available:
         button.clicked.connect(self.connectVault)
     else:
         button.setEnabled(False)
     hbox.addWidget(button)
     removebtn = QPushButton('Remove Vault', self)
     removebtn.setEnabled(False)
     removebtn.clicked.connect(self.removeVault)
     self.removebtn = removebtn
     hbox.addWidget(removebtn)
Beispiel #11
0
 def addWidgets(self):
     layout = QVBoxLayout()
     self.setLayout(layout)
     preamble = QLabel(self)
     layout.addWidget(preamble)
     self.preamble = preamble
     layout.addSpacing(10)
     table = QTableWidget(self)
     layout.addWidget(table)
     table.setShowGrid(False)
     table.setSelectionBehavior(QTableWidget.SelectRows)
     table.setSelectionMode(QTableWidget.SingleSelection)
     table.setMinimumWidth(400)
     table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     table.setColumnCount(4)
     table.hideColumn(0)
     table.setHorizontalHeaderLabels(['ID', 'Vault', '# of Items', '# of Peers'])
     table.setFocusPolicy(Qt.NoFocus)
     table.itemSelectionChanged.connect(self.rowSelected)
     hhead = table.horizontalHeader()
     hhead.setResizeMode(QHeaderView.Stretch)
     hhead.setHighlightSections(False)
     vhead = table.verticalHeader()
     vhead.hide()
     self.table = table
     hbox = QHBoxLayout()
     layout.addLayout(hbox)
     button = QPushButton('Create Vault', self)
     button.clicked.connect(self.createVault)
     hbox.addWidget(button)
     button = QPushButton('Connect to Vault', self)
     backend = QApplication.instance().backend()
     available = backend.locator_is_available()
     if available:
         button.clicked.connect(self.connectVault)
     else:
         button.setEnabled(False)
     hbox.addWidget(button)
     removebtn = QPushButton('Remove Vault', self)
     removebtn.setEnabled(False)
     removebtn.clicked.connect(self.removeVault)
     self.removebtn = removebtn
     hbox.addWidget(removebtn)
    def __init__(self, parent=None, vertical_header=list(), horizontal_header=list(), data=list()):
        super(Table, self).__init__(parent)
        layout = QHBoxLayout()
        resultTable = QTableWidget()

        resultTable.setRowCount(len(vertical_header))
        resultTable.setColumnCount(len(horizontal_header))
        resultTable.setHorizontalHeaderLabels(horizontal_header)
        resultTable.setVerticalHeaderLabels(vertical_header)
        resultTable.horizontalHeader().setResizeMode(1)
        resultTable.verticalHeader().setResizeMode(1)
        resultTable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        for x, row in enumerate(data):
            for y, item in enumerate(row):
                resultTable.setItem(x, y, QTableWidgetItem(str(item)))
        self.table = resultTable
        layout.addWidget(self.table)
        self.setLayout(layout)
        self.setMinimumWidth(min(len(horizontal_header) * 250, 800))
        self.setMinimumHeight(min(len(vertical_header) * 70, 800))
        self.setWindowTitle("Report result")
Beispiel #13
0
    def build_preview(self):
        data = self.t.light_parser(self.node)

        self.layout.addWidget(QLabel("File name : " + data['File']))

        tmp_widget = QWidget()
        tmp_layout = QHBoxLayout(tmp_widget)

        tmp_layout.addWidget(QLabel("Oldest chunk : " + data['Oldest']))
        tmp_layout.addWidget(QLabel("Current chunk : " + data['Current']))
        tmp_layout.addWidget(QLabel("Next record : " + data['Next']))
        tmp_layout.addWidget(
            QLabel("Version : " + data['Maj'] + "." + data['Min']))
        tmp_layout.addWidget(QLabel("Chunk number : " + data['chunk_nb']))
        self.layout.addWidget(tmp_widget)

        data_list = QTableWidget()
        data_list.setColumnCount(4)

        data_list.setHorizontalHeaderLabels(
            ['Chunk number', 'First record', 'Last record', 'Offset'])
        data_list.horizontalHeader().setStretchLastSection(True)
        data_list.verticalHeader().hide()
        data_list.setSortingEnabled(False)
        data_list.setSelectionBehavior(QAbstractItemView.SelectRows)
        data_list.setEditTriggers(QAbstractItemView.NoEditTriggers)

        data_list.setRowCount(int(data['chunk_nb']))
        for chunk_count in range(int(data['chunk_nb'])):
            rec = data[str(chunk_count)]

            data_list.setItem(chunk_count, 0,
                              QTableWidgetItem(str(chunk_count)))
            data_list.setItem(chunk_count, 1, QTableWidgetItem(rec[0]))
            data_list.setItem(chunk_count, 2, QTableWidgetItem(rec[1]))
            data_list.setItem(chunk_count, 3, QTableWidgetItem(rec[2]))

        self.layout.addWidget(data_list)
Beispiel #14
0
 def addWidgets(self):
     layout = QVBoxLayout()
     self.setLayout(layout)
     preamble = QLabel(self)
     preamble.setWordWrap(True)
     layout.addWidget(preamble)
     self.preamble = preamble
     layout.addSpacing(10)
     table = QTableWidget(self)
     layout.addWidget(table)
     table.setShowGrid(False)
     table.setSelectionBehavior(QTableWidget.SelectRows)
     table.setSelectionMode(QTableWidget.SingleSelection)
     table.setMinimumWidth(400)
     table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     table.setColumnCount(4)
     table.hideColumn(0)
     table.setHorizontalHeaderLabels(['ID', 'Vault', 'Source', 'On Node'])
     table.setFocusPolicy(Qt.NoFocus)
     table.itemSelectionChanged.connect(self.rowSelected)
     hhead = table.horizontalHeader()
     hhead.setResizeMode(QHeaderView.Stretch)
     hhead.setHighlightSections(False)
     vhead = table.verticalHeader()
     vhead.hide()
     self.table = table
     hbox = QHBoxLayout()
     layout.addLayout(hbox)
     cancelbtn = QPushButton('Cancel', self)
     cancelbtn.clicked.connect(self.vaultmgr.hide)
     hbox.addWidget(cancelbtn)
     self.cancelbtn = cancelbtn
     connectbtn = QPushButton('Connect', self)
     connectbtn.setEnabled(False)
     connectbtn.clicked.connect(self.connectVault)
     hbox.addWidget(connectbtn)
     self.connectbtn = connectbtn
     hbox.addStretch(100)
Beispiel #15
0
 def addWidgets(self):
     layout = QVBoxLayout()
     self.setLayout(layout)
     preamble = QLabel(self)
     preamble.setWordWrap(True)
     layout.addWidget(preamble)
     self.preamble = preamble
     layout.addSpacing(10)
     table = QTableWidget(self)
     layout.addWidget(table)
     table.setShowGrid(False)
     table.setSelectionBehavior(QTableWidget.SelectRows)
     table.setSelectionMode(QTableWidget.SingleSelection)
     table.setMinimumWidth(400)
     table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     table.setColumnCount(4)
     table.hideColumn(0)
     table.setHorizontalHeaderLabels(['ID', 'Vault', 'Source', 'On Node'])
     table.setFocusPolicy(Qt.NoFocus)
     table.itemSelectionChanged.connect(self.rowSelected)
     hhead = table.horizontalHeader()
     hhead.setResizeMode(QHeaderView.Stretch)
     hhead.setHighlightSections(False)
     vhead = table.verticalHeader(); vhead.hide()
     self.table = table
     hbox = QHBoxLayout()
     layout.addLayout(hbox)
     cancelbtn = QPushButton('Cancel', self)
     cancelbtn.clicked.connect(self.vaultmgr.hide)
     hbox.addWidget(cancelbtn)
     self.cancelbtn = cancelbtn
     connectbtn = QPushButton('Connect', self)
     connectbtn.setEnabled(False)
     connectbtn.clicked.connect(self.connectVault)
     hbox.addWidget(connectbtn)
     self.connectbtn = connectbtn
     hbox.addStretch(100)
Beispiel #16
0
class OrbitCorrGeneral(QtGui.QWidget):
    """
    A general orbit correction or local bump panel.
    """
    def __init__(self, bpms, cors, parent = None):
        super(OrbitCorrGeneral, self).__init__(parent)

        self.bpms, self.cors = bpms, cors
        self.sb = [bpm.sb for bpm in self.bpms]
        self.x0, self.y0 = None, None
        self._update_current_orbit()

        self.table = QTableWidget(len(self.bpms), 9)
        self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        hdview = QHeaderView(Qt.Horizontal)
        self.table.setHorizontalHeaderLabels(
            ['BPM Name', 's', "Beta X", "Beta Y",
             "Eta X", 'X Bump', 'Y Bump', "Target X", "Target Y"])
        self._twiss = getTwiss([b.name for b in self.bpms],
                               ["s", "betax", "betay", "etax"])
        for i,bpm in enumerate(self.bpms):
            it = QTableWidgetItem(bpm.name)
            it.setFlags(it.flags() & (~Qt.ItemIsEditable))
            self.table.setItem(i, 0, it)

            it = QTableWidgetItem(str(bpm.sb))
            it.setFlags(it.flags() & (~Qt.ItemIsEditable))
            #it.setMinimumWidth(80)
            self.table.setItem(i, 1, it)
            self.table.setItem(i, 2,
                               QTableWidgetItem("%.4f" % self._twiss[i,1]))
            self.table.setItem(i, 3,
                               QTableWidgetItem("%.4f" % self._twiss[i,2]))
            self.table.setItem(i, 4,
                               QTableWidgetItem("%.4f" % self._twiss[i,3]))

            for j in range(5, 9):
                it = QTableWidgetItem(str(0.0))
                it.setData(Qt.DisplayRole, str(0.0))
                it.setFlags(it.flags() | Qt.ItemIsEditable)
                self.table.setItem(i, j, it) 
            # use the current orbit 
            #self.table.item(i,4).setData(Qt.DisplayRole, str(self.x0[i]))
            #self.table.item(i,5).setData(Qt.DisplayRole, str(self.y0[i]))

        #self.connect(self.table, SIGNAL("cellClicked(int, int)"),
        #             self._cell_clicked)
        self.table.resizeColumnsToContents()
        #self.table.horizontalHeader().setStretchLastSection(True)
        #for i in range(4):
        #    print "width", i, self.table.columnWidth(i)
        #self.table.setColumnWidth(0, 300)
        self.table.setColumnWidth(1, 80)

        vbox1 = QtGui.QVBoxLayout()
        frmbox = QFormLayout()
        self.base_orbit_box = QtGui.QComboBox()
        #self.base_orbit_box.addItems([
        #        "Current Orbit", "All Zeros"])
        self.base_orbit_box.addItems(["All Zeros", "Current Orbit"])
        frmbox.addRow("Orbit Base", self.base_orbit_box)
        grp = QtGui.QGroupBox("Local Bump")
        grp.setLayout(frmbox)
        vbox1.addWidget(grp)

        frmbox = QFormLayout()
        hln1 = QtGui.QFrame()
        hln1.setLineWidth(3)
        hln1.setFrameStyle(QtGui.QFrame.Sunken)
        hln1.setFrameShape(QtGui.QFrame.HLine)
        frmbox.addRow(hln1)
        self.repeatbox = QSpinBox()
        self.repeatbox.setRange(1, 20)
        self.repeatbox.setValue(3)
        # or connect the returnPressed() signal
        frmbox.addRow("&Repeat correction", self.repeatbox)

        self.rcondbox = QLineEdit()
        self.rcondbox.setValidator(QDoubleValidator(0, 1, 0, self))
        self.rcondbox.setText("1e-2")
        frmbox.addRow("r&cond for SVD", self.rcondbox)

        self.scalebox = QDoubleSpinBox()
        self.scalebox.setRange(0.01, 5.00)
        self.scalebox.setSingleStep(0.01)
        self.scalebox.setValue(0.68)
        frmbox.addRow("&Scale correctors", self.scalebox)

        #hln2 = QtGui.QFrame()
        #hln2.setLineWidth(3)
        #hln2.setFrameStyle(QtGui.QFrame.Sunken)
        #hln2.setFrameShape(QtGui.QFrame.HLine)
        #frmbox.addRow(hln2)

        self.progress = QProgressBar()
        self.progress.setMaximum(self.repeatbox.value())
        self.progress.setMaximumHeight(15)
        frmbox.addRow("Progress", self.progress)
        grp = QtGui.QGroupBox("Correction")
        grp.setLayout(frmbox)
        vbox1.addWidget(grp)

        #vbox.addStretch(1.0)
        #self.qdb = QDialogButtonBox(self)
        #self.qdb.addButton("APP", QDialogButtonBox.ApplyRole)
        #self.qdb.addButton("R", QDialogButtonBox.ResetRole)
        #btn.setDefault(True)
        #self.qdb.addButton(QDialogButtonBox.Cancel)
        #self.qdb.addButton(QDialogButtonBox.Help)

        gbox = QtGui.QGridLayout()
        btn = QPushButton("Clear")
        self.connect(btn, SIGNAL("clicked()"), self.resetBumps)
        gbox.addWidget(btn, 0, 1)
        self.correctOrbitBtn = QPushButton("Apply")
        #self.correctOrbitBtn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.correctOrbitBtn.setStyleSheet("QPushButton:disabled { color: gray }");
        self.connect(self.correctOrbitBtn, SIGNAL("clicked()"), self.call_apply)
        self.correctOrbitBtn.setDefault(True)
        gbox.addWidget(self.correctOrbitBtn, 1, 1)
        gbox.setColumnStretch(0, 1)

        vbox1.addStretch()
        vbox1.addLayout(gbox)
        
        hbox1 = QtGui.QHBoxLayout()
        hbox1.addWidget(self.table, 2)
        hbox1.addLayout(vbox1, 0)
        self.setLayout(hbox1)

        self.connect(self.base_orbit_box,
                     SIGNAL("currentIndexChanged(QString)"), 
                     self.updateTargetOrbit)
        self.connect(self.repeatbox, SIGNAL("valueChanged(int)"),
                     self.progress.setMaximum)
        self.connect(self.table, SIGNAL("cellChanged (int, int)"),
                     self.updateBump)

        #self.updateTargetOrbit(self.base_orbit_box.currentText())

    def _update_current_orbit(self):
        pvx = [bpm.pv(field="x", handle="readback")[0] for bpm in self.bpms]
        pvy = [bpm.pv(field="y", handle="readback")[0] for bpm in self.bpms]
        self.x0 = [float(v) if v.ok else np.nan for v in catools.caget(pvx)]
        self.y0 = [float(v) if v.ok else np.nan for v in catools.caget(pvy)]

    def resetBumps(self):
        jx0, jy0 = 5, 6
        for i in range(self.table.rowCount()):
            self.table.item(i, jx0).setData(Qt.DisplayRole, str(0.0))
            self.table.item(i, jy0).setData(Qt.DisplayRole, str(0.0))
        #self.updateTargetOrbit(self.base_orbit_box.currentText())

    def call_apply(self):
        #print "apply the orbit"
        obt = []
        jx, jy = 7, 8
        for i in range(self.table.rowCount()):
            x1,err = self.table.item(i, jx).data(Qt.DisplayRole).toFloat()
            y1,err = self.table.item(i, jy).data(Qt.DisplayRole).toFloat()
            obt.append([x1, y1])

        self.correctOrbitBtn.setEnabled(False)
        nrepeat = self.repeatbox.value()
        kw = { "scale": float(self.scalebox.text()),
               "rcond": float(self.rcondbox.text()) }
        self.progress.setValue(0)
        QApplication.processEvents()
        for i in range(nrepeat):
            err, msg = setLocalBump(self.bpms, self.cors, obt, **kw)
            self.progress.setValue(i+1)
            QApplication.processEvents()
            if err != 0:
                QtGui.QMessageBox.critical(
                    self, "Local Orbit Bump", 
                    "ERROR: {0}\nAbort.".format(msg),
                    QtGui.QMessageBox.Ok)
                #self.progress.setValue(0)
                break
       
        self.correctOrbitBtn.setEnabled(True)

    def getTargetOrbit(self):
        x = [self.table.item(i,7).data(Qt.DisplayRole).toFloat()[0]
             for i in range(self.table.rowCount())]
        y = [self.table.item(i,8).data(Qt.DisplayRole).toFloat()[0]
             for i in range(self.table.rowCount())]
        return (self.sb, x), (self.sb, y)

    def updateTargetOrbit(self, baseobt):
        if baseobt == "All Zeros":
            jx0, jx1 = 5, 7
            jy0, jy1 = 6, 8
            for i in range(self.table.rowCount()):
                it0 = self.table.item(i, jx0)
                it1 = self.table.item(i, jx1)
                it1.setData(Qt.DisplayRole, it0.data(Qt.DisplayRole))
                it0 = self.table.item(i, jy0)
                it1 = self.table.item(i, jy1)
                it1.setData(Qt.DisplayRole, it0.data(Qt.DisplayRole))
        elif baseobt == "Current Orbit":
            self._update_current_orbit()
            jx0, jx1 = 5, 7
            jy0, jy1 = 6, 8
            for i in range(self.table.rowCount()):
                dx0,err = self.table.item(i, jx0).data(Qt.DisplayRole).toFloat()
                it = self.table.item(i, jx1)
                it.setData(Qt.DisplayRole, self.x0[i] + dx0)

                dy0,err = self.table.item(i, jy0).data(Qt.DisplayRole).toFloat()
                it = self.table.item(i, jy1)
                it.setData(Qt.DisplayRole, self.y0[i] + dy0)
        #self._update_orbit_plot()
        x, y = self.getTargetOrbit()
        self.emit(SIGNAL("targetOrbitChanged(PyQt_PyObject, PyQt_PyObject)"),
                  x, y)

    def updateBump(self, row, col):
        #print "updating ", row, col
        if col == 5 or col == 6:
            self.updateTargetOrbit(self.base_orbit_box.currentText())
Beispiel #17
0
class Widget(QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        buttonHelp1 = QPushButton('help')
        buttonHelp1.setEnabled(False)
        buttonHelp1.setToolTip('The table below, with the exception of the last row and column, describe the network\n' +
                               'in terms of the weight coefficient values. The value of a cell in the n-th row and m-th\n' +
                               'column is the weight of the n-th feature for the m-th animal class.\n\n' +
                               'As you can see, each animal class has its own neuron that recognizes it, and each of\n' +
                               'these neurons has inputs that receive individual feature values.\n\n' +
                               'The last column represents the input vector, and the last row contains the network\n' +
                               'output values.')
        buttonHelp2 = QPushButton('help')
        buttonHelp2.setEnabled(False)
        buttonHelp2.setToolTip('If you show the winner, you will see the neuron whose response was the strongest.\n' +
                               'This neuron indicates the animal class the examined object will most probably fall into.\n' +
                               'The table below, with the exception of the last row and column, describe the network\n' +
                               'in terms of the weight coefficient values. The value of a cell in the n-th row and m-th\n' +
                               'column is the weight of the n-th feature for the m-th animal class.\n\n' +
                               'As you can see, each animal class has its own neuron that recognizes it, and each of\n' +
                               'these neurons has inputs that receive individual feature values.\n\n' +
                               'The last column represents the input vector, and the last row contains the network\n' +
                               'output values.')

        hBoxLayout1 = QHBoxLayout()
        hBoxLayout1.addWidget(QLabel('The neural network in this example uses five features to recognize\n' +
                                     'three classes of animals. Its weight coefficients are predefined and shown in the table below.\n\n' +
                                     'To test the network behavior, enter the input signals in the rightmost column and read the output\n' +
                                     'values from the bottom row.'))
        hBoxLayout1.addWidget(buttonHelp1)

        self.checkBoxWinner = QCheckBox()
        self.checkBoxWinner.setText('Show the winner')

        hBoxLayout2 = QHBoxLayout()
        hBoxLayout2.addWidget(self.checkBoxWinner)
        hBoxLayout2.addWidget(buttonHelp2)

        self.tableWidget = QTableWidget()
        self.labelNeuron = QLabel('(There is no winner.)')
        self.labelType = QLabel('This is something strange!')
        self.spinBoxThreshold = QDoubleSpinBox()
        self.spinBoxThreshold.setValue(5.0)

        self.groupBox = QGroupBox('Show the winner')
        gridLayout = QGridLayout()
        gridLayout.addWidget(QLabel('And the winner is...'), 0, 0)
        gridLayout.addWidget(self.labelNeuron, 0, 1)
        gridLayout.addWidget(QLabel('Because of this, the network claims:'), 1, 0)
        gridLayout.addWidget(self.labelType, 1, 1)
        gridLayout.addWidget(QLabel('Threshold:'), 2, 0)
        gridLayout.addWidget(self.spinBoxThreshold, 2, 1)
        self.groupBox.setLayout(gridLayout)
        self.groupBox.setVisible(False)

        vBoxLayout = QVBoxLayout()
        vBoxLayout.addLayout(hBoxLayout1)
        vBoxLayout.addWidget(self.tableWidget)
        vBoxLayout.addLayout(hBoxLayout2)
        vBoxLayout.addWidget(self.groupBox)

        self.setLayout(vBoxLayout)
        self.setWindowTitle('Simple linear neural network (example2)')

        self.classNames = ['mammal', 'bird', 'fish']

        self.tableWidget.setColumnCount(5)
        self.tableWidget.setRowCount(6)
        self.tableWidget.verticalHeader().hide()
        self.tableWidget.setHorizontalHeaderLabels(['Feature'] + self.classNames +  ['Input vector'])
        self.tableWidget.setCellWidget(0, 0, QLabel('number of legs'))
        self.tableWidget.setCellWidget(1, 0, QLabel('lives in water'))
        self.tableWidget.setCellWidget(2, 0, QLabel('can fly'))
        self.tableWidget.setCellWidget(3, 0, QLabel('has feathers'))
        self.tableWidget.setCellWidget(4, 0, QLabel('egg-laying'))
        self.tableWidget.setCellWidget(5, 0, QLabel('Output'))

        weights = [
            [   4,     0.01,   0.01,   -1,     -1.5 ],
            [   2,     -1,     2,      2.5,    2    ],
            [   -1,    3.5,    0.01,   -2,     1.5  ]
        ]

        for i in xrange(len(weights)):
            for j in xrange(len(weights[i])):
                self.tableWidget.setCellWidget(j, i + 1, QLabel('    ' + str(weights[i][j])))
        for i in xrange(len(weights)):
            self.tableWidget.setCellWidget(5, i + 1, QLabel(''))
        for i in xrange(len(weights[0])):
            doubleSpinBox = QDoubleSpinBox()
            doubleSpinBox.setValue(0.0)
            doubleSpinBox.setRange(-15.0, 15.0)
            self.tableWidget.setCellWidget(i, 4, doubleSpinBox)
        self.tableWidget.setCellWidget(5, 4, QPushButton('Calculate'))
        self.linearNetwork = LinearNetwork(initialWeights=weights)
        self.connect(self.checkBoxWinner, SIGNAL('stateChanged(int)'), self.visibleGrid)
        self.connect(self.tableWidget.cellWidget(5, 4), SIGNAL('clicked()'), self.updateResult)
        self.resize(600, 400)

    def visibleGrid(self, state):
        if state == 0:
            self.groupBox.setVisible(False)
        else:
            self.groupBox.setVisible(True)
            self.updateResult()

    def updateResult(self):
        inputColumn0 = self.tableWidget.cellWidget(0, 4).value()  # number of legs
        inputColumn1 = self.tableWidget.cellWidget(1, 4).value()  # lives in water
        inputColumn2 = self.tableWidget.cellWidget(2, 4).value()  # can fly
        inputColumn3 = self.tableWidget.cellWidget(3, 4).value()  # has feathers
        inputColumn4 = self.tableWidget.cellWidget(4, 4).value()  # egg-laying

        outputVector = self.linearNetwork.response([inputColumn0, inputColumn1, inputColumn2, inputColumn3, inputColumn4])

        if self.checkBoxWinner.checkState() == Qt.Checked:
            winner = LinearNetwork.winner(outputVector, self.spinBoxThreshold.value())
            for i in xrange(len(outputVector)):
                self.tableWidget.setCellWidget(5, i + 1, QLabel())
            if winner != -1:
                cellWinner = self.tableWidget.cellWidget(5, winner + 1)
                cellWinner.setStyleSheet('background-color: red;')

                self.labelNeuron.setText('Neuron ' + str(winner + 1))
                self.labelType.setText('This is a ' + self.classNames[winner])
            else:
                self.labelNeuron.setText('(There is no winner.)')
                self.labelType.setText('Thiss is something strange!')

        for i in xrange(len(outputVector)):
            self.tableWidget.cellWidget(5, i + 1).setText(str(outputVector[i]))
class OWdabam_height_profile(OWWidget):
    name = "DABAM Height Profile"
    id = "dabam_height_profile"
    description = "Calculation of mirror surface error profile"
    icon = "icons/dabam.png"
    author = "Luca Rebuffi"
    maintainer_email = "[email protected]; [email protected]"
    priority = 6
    category = ""
    keywords = ["dabam_height_profile"]

    outputs = [{"name": "PreProcessor_Data",
                "type": ShadowPreProcessorData,
                "doc": "PreProcessor Data",
                "id": "PreProcessor_Data"}]

    want_main_area = 1
    want_control_area = 1

    MAX_WIDTH = 1320
    MAX_HEIGHT = 700

    IMAGE_WIDTH = 860
    IMAGE_HEIGHT = 645

    CONTROL_AREA_WIDTH = 405
    TABS_AREA_HEIGHT = 618

    xx = None
    yy = None
    zz = None

    entry_number = Setting(1)

    shape=Setting(0)
    slope_error_from = Setting(0.0)
    slope_error_to = Setting(1.5)
    dimension_y_from = Setting(0.0)
    dimension_y_to = Setting(200.0)

    use_undetrended = Setting(0)

    step_x = Setting(1.0)
    dimension_x = Setting(10.0)

    center_y = Setting(1)
    modify_y = Setting(0)
    new_length = Setting(200.0)
    filler_value = Setting(0.0)

    scale_factor_y = Setting(1.0)
    renormalize_y = Setting(1)
    error_type_y = Setting(0)
    rms_y = Setting(0.9)

    dabam_profile_index = Setting(1)

    heigth_profile_file_name = Setting('mirror.dat')

    tab=[]

    def __init__(self):
        super().__init__()

        self.runaction = widget.OWAction("Calculate Height Profile", self)
        self.runaction.triggered.connect(self.calculate_heigth_profile_ni)
        self.addAction(self.runaction)

        self.runaction = widget.OWAction("Generate Height Profile File", self)
        self.runaction.triggered.connect(self.generate_heigth_profile_file_ni)
        self.addAction(self.runaction)

        geom = QApplication.desktop().availableGeometry()
        self.setGeometry(QRect(round(geom.width() * 0.05),
                               round(geom.height() * 0.05),
                               round(min(geom.width() * 0.98, self.MAX_WIDTH)),
                               round(min(geom.height() * 0.95, self.MAX_HEIGHT))))

        self.setMaximumHeight(self.geometry().height())
        self.setMaximumWidth(self.geometry().width())

        # DABAM INITIALIZATION
        self.server = dabam.dabam()
        self.server.set_input_silent(True)

        gui.separator(self.controlArea)

        button_box = oasysgui.widgetBox(self.controlArea, "", addSpace=False, orientation="horizontal")

        button = gui.button(button_box, self, "Calculate Height\nProfile", callback=self.calculate_heigth_profile)
        button.setFixedHeight(45)

        button = gui.button(button_box, self, "Generate Height\nProfile File", callback=self.generate_heigth_profile_file)
        font = QFont(button.font())
        font.setBold(True)
        button.setFont(font)
        palette = QPalette(button.palette())  # make a copy of the palette
        palette.setColor(QPalette.ButtonText, QColor('Dark Blue'))
        button.setPalette(palette)  # assign new palette
        button.setFixedHeight(45)
        button.setFixedWidth(150)

        button = gui.button(button_box, self, "Reset Fields", callback=self.call_reset_settings)
        font = QFont(button.font())
        font.setItalic(True)
        button.setFont(font)
        palette = QPalette(button.palette())  # make a copy of the palette
        palette.setColor(QPalette.ButtonText, QColor('Dark Red'))
        button.setPalette(palette)  # assign new palette
        button.setFixedHeight(45)

        gui.separator(self.controlArea)

        tabs_setting = gui.tabWidget(self.controlArea)
        tabs_setting.setFixedHeight(self.TABS_AREA_HEIGHT)
        tabs_setting.setFixedWidth(self.CONTROL_AREA_WIDTH-5)

        tab_input = oasysgui.createTabPage(tabs_setting, "DABAM Search Setting")
        tab_gener = oasysgui.createTabPage(tabs_setting, "DABAM Generation Setting")
        tab_out = oasysgui.createTabPage(tabs_setting, "Output")

        manual_box = oasysgui.widgetBox(tab_input, "Manual Entry", addSpace=True, orientation="vertical")

        oasysgui.lineEdit(manual_box, self, "entry_number", "Entry Number",
                           labelWidth=300, valueType=int, orientation="horizontal")

        gui.separator(manual_box)

        button = gui.button(manual_box, self, "Retrieve Profile", callback=self.retrieve_profile)
        button.setFixedHeight(35)
        button.setFixedWidth(self.CONTROL_AREA_WIDTH-35)

        input_box = oasysgui.widgetBox(tab_input, "Search Parameters", addSpace=True, orientation="vertical")

        gui.comboBox(input_box, self, "shape", label="Mirror Shape", labelWidth=300,
                     items=["All", "Plane", "Cylindrical", "Elliptical", "Toroidal", "Spherical"],
                     sendSelectedValue=False, orientation="horizontal")

        gui.separator(input_box)
        
        input_box_1 = oasysgui.widgetBox(input_box, "", addSpace=True, orientation="horizontal")

        oasysgui.lineEdit(input_box_1, self, "slope_error_from", "Slope Error From (" + u"\u03BC" + "rad)",
                           labelWidth=150, valueType=float, orientation="horizontal")
        oasysgui.lineEdit(input_box_1, self, "slope_error_to", "To (" + u"\u03BC" + "rad)",
                           labelWidth=60, valueType=float, orientation="horizontal")

        input_box_2 = oasysgui.widgetBox(input_box, "", addSpace=True, orientation="horizontal")

        self.le_dimension_y_from = oasysgui.lineEdit(input_box_2, self, "dimension_y_from", "Mirror Length From",
                           labelWidth=150, valueType=float, orientation="horizontal")
        self.le_dimension_y_to = oasysgui.lineEdit(input_box_2, self, "dimension_y_to", "To",
                           labelWidth=60, valueType=float, orientation="horizontal")

        table_box = oasysgui.widgetBox(tab_input, "Search Results", addSpace=True, orientation="vertical", height=290)

        self.overlay_search = Overlay(table_box, self.search_profiles)
        self.overlay_search.hide()

        button = gui.button(input_box, self, "Search", callback=self.overlay_search.show)
        button.setFixedHeight(35)
        button.setFixedWidth(self.CONTROL_AREA_WIDTH-35)

        gui.comboBox(table_box, self, "use_undetrended", label="Use Undetrended Profile", labelWidth=300,
                     items=["No", "Yes"], callback=self.table_item_clicked, sendSelectedValue=False, orientation="horizontal")

        gui.separator(table_box)

        self.scrollarea = QScrollArea()
        self.scrollarea.setMinimumWidth(self.CONTROL_AREA_WIDTH-35)

        table_box.layout().addWidget(self.scrollarea, alignment=Qt.AlignHCenter)

        self.table = QTableWidget(1, 5)
        self.table.setAlternatingRowColors(True)
        self.table.horizontalHeader().setResizeMode(QHeaderView.Fixed)
        self.table.verticalHeader().setVisible(False)

        self.table.setColumnWidth(0, 40)
        self.table.setColumnWidth(1, 70)
        self.table.setColumnWidth(2, 70)
        self.table.setColumnWidth(3, 85)
        self.table.setColumnWidth(4, 80)

        self.table.resizeRowsToContents()
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.itemClicked.connect(self.table_item_clicked)

        self.scrollarea.setWidget(self.table)
        self.scrollarea.setWidgetResizable(1)

        output_profile_box = oasysgui.widgetBox(tab_gener, "Surface Generation Parameters", addSpace=True, orientation="vertical", height=270)

        self.le_dimension_x = oasysgui.lineEdit(output_profile_box, self, "dimension_x", "Width",
                           labelWidth=300, valueType=float, orientation="horizontal")
        self.le_step_x = oasysgui.lineEdit(output_profile_box, self, "step_x", "Step Width",
                           labelWidth=300, valueType=float, orientation="horizontal")

        gui.comboBox(output_profile_box, self, "center_y", label="Center Profile in the middle of O.E.", labelWidth=300,
                     items=["No", "Yes"], sendSelectedValue=False, orientation="horizontal")

        gui.comboBox(output_profile_box, self, "modify_y", label="Modify Length?", labelWidth=240,
                     items=["No", "Rescale to new length", "Fit to new length (fill or cut)"], callback=self.set_ModifyY, sendSelectedValue=False, orientation="horizontal")

        self.modify_box_1 = oasysgui.widgetBox(output_profile_box, "", addSpace=False, orientation="vertical", height=50)

        self.modify_box_2 = oasysgui.widgetBox(output_profile_box, "", addSpace=False, orientation="vertical", height=50)
        oasysgui.lineEdit(self.modify_box_2, self, "scale_factor_y", "Scale Factor", labelWidth=300, valueType=float, orientation="horizontal")

        self.modify_box_3 = oasysgui.widgetBox(output_profile_box, "", addSpace=False, orientation="vertical", height=50)
        self.le_new_length = oasysgui.lineEdit(self.modify_box_3, self, "new_length", "New Length", labelWidth=300, valueType=float, orientation="horizontal")
        oasysgui.lineEdit(self.modify_box_3, self, "filler_value", "Filler Value (if new length > profile length) [nm]", labelWidth=300, valueType=float, orientation="horizontal")

        self.set_ModifyY()

        gui.comboBox(output_profile_box, self, "renormalize_y", label="Renormalize Length Profile to different RMS", labelWidth=300,
                     items=["No", "Yes"], callback=self.set_RenormalizeY, sendSelectedValue=False, orientation="horizontal")

        self.output_profile_box_1 = oasysgui.widgetBox(output_profile_box, "", addSpace=True, orientation="vertical")

        gui.comboBox(self.output_profile_box_1, self, "error_type_y", label="Normalization to", labelWidth=270,
                     items=["Figure Error (nm)", "Slope Error (" + u"\u03BC" + "rad)"],
                     sendSelectedValue=False, orientation="horizontal")

        oasysgui.lineEdit(self.output_profile_box_1, self, "rms_y", "Rms Value",
                           labelWidth=300, valueType=float, orientation="horizontal")

        self.set_RenormalizeY()

        output_box = oasysgui.widgetBox(tab_gener, "Outputs", addSpace=True, orientation="vertical")

        select_file_box = oasysgui.widgetBox(output_box, "", addSpace=True, orientation="horizontal")

        self.le_heigth_profile_file_name = oasysgui.lineEdit(select_file_box, self, "heigth_profile_file_name", "Output File Name",
                                                        labelWidth=120, valueType=str, orientation="horizontal")

        gui.button(select_file_box, self, "...", callback=self.selectFile)

        self.shadow_output = QTextEdit()
        self.shadow_output.setReadOnly(True)

        out_box = oasysgui.widgetBox(tab_out, "System Output", addSpace=True, orientation="horizontal", height=500)
        out_box.layout().addWidget(self.shadow_output)

        gui.rubber(self.controlArea)

        self.initializeTabs()

        gui.rubber(self.mainArea)

        self.overlay_search.raise_()

    def resizeEvent(self, event):
        self.overlay_search.resize(self.CONTROL_AREA_WIDTH - 15, 290)
        event.accept()

    def after_change_workspace_units(self):
        self.si_to_user_units = 1e2 / self.workspace_units_to_cm

        self.horHeaders = ["Entry", "Shape", "Length\n[" + self.workspace_units_label + "]", "Heights St.Dev.\n[nm]",  "Slopes St.Dev.\n[" + u"\u03BC" + "rad]"]
        self.table.setHorizontalHeaderLabels(self.horHeaders)
        self.plot_canvas[0].setGraphXLabel("Y [" + self.workspace_units_label + "]")
        self.plot_canvas[1].setGraphXLabel("Y [" + self.workspace_units_label + "]")
        self.axis.set_xlabel("X [" + self.workspace_units_label + "]")
        self.axis.set_ylabel("Y [" + self.workspace_units_label + "]")

        label = self.le_dimension_y_from.parent().layout().itemAt(0).widget()
        label.setText(label.text() + " [" + self.workspace_units_label + "]")
        label = self.le_dimension_y_to.parent().layout().itemAt(0).widget()
        label.setText(label.text() + " [" + self.workspace_units_label + "]")
        label = self.le_dimension_x.parent().layout().itemAt(0).widget()
        label.setText(label.text() + " [" + self.workspace_units_label + "]")
        label = self.le_step_x.parent().layout().itemAt(0).widget()
        label.setText(label.text() + " [" + self.workspace_units_label + "]")
        label = self.le_new_length.parent().layout().itemAt(0).widget()
        label.setText(label.text() + " [" + self.workspace_units_label + "]")

    def initializeTabs(self):
        self.tabs = gui.tabWidget(self.mainArea)

        self.tab = [gui.createTabPage(self.tabs, "Info"),
                    gui.createTabPage(self.tabs, "Heights Profile"),
                    gui.createTabPage(self.tabs, "Slopes Profile"),
                    gui.createTabPage(self.tabs, "PSD Heights"),
                    gui.createTabPage(self.tabs, "CSD Heights"),
                    gui.createTabPage(self.tabs, "ACF"),
                    gui.createTabPage(self.tabs, "Generated 2D Profile"),
        ]

        for tab in self.tab:
            tab.setFixedHeight(self.IMAGE_HEIGHT)
            tab.setFixedWidth(self.IMAGE_WIDTH)

        self.plot_canvas = [None, None, None, None, None, None]

        self.plot_canvas[0] = PlotWindow(roi=False, control=False, position=True, plugins=False)
        self.plot_canvas[0].setDefaultPlotLines(True)
        self.plot_canvas[0].setActiveCurveColor(color='darkblue')
        self.plot_canvas[0].setGraphYLabel("Z [nm]")
        self.plot_canvas[0].setGraphTitle("Heights Profile")
        self.plot_canvas[0].setDrawModeEnabled(True, 'rectangle')
        self.plot_canvas[0].setZoomModeEnabled(True)

        self.plot_canvas[1] = PlotWindow(roi=False, control=False, position=True, plugins=False)
        self.plot_canvas[1].setDefaultPlotLines(True)
        self.plot_canvas[1].setActiveCurveColor(color='darkblue')
        self.plot_canvas[1].setGraphYLabel("Zp [$\mu$rad]")
        self.plot_canvas[1].setGraphTitle("Slopes Profile")
        self.plot_canvas[1].setDrawModeEnabled(True, 'rectangle')
        self.plot_canvas[1].setZoomModeEnabled(True)

        self.plot_canvas[2] = PlotWindow(roi=False, control=False, position=True, plugins=False)
        self.plot_canvas[2].setDefaultPlotLines(True)
        self.plot_canvas[2].setActiveCurveColor(color='darkblue')
        self.plot_canvas[2].setGraphXLabel("f [m^-1]")
        self.plot_canvas[2].setGraphYLabel("PSD [m^3]")
        self.plot_canvas[2].setGraphTitle("Power Spectral Density of Heights Profile")
        self.plot_canvas[2].setDrawModeEnabled(True, 'rectangle')
        self.plot_canvas[2].setZoomModeEnabled(True)
        self.plot_canvas[2].setXAxisLogarithmic(True)
        self.plot_canvas[2].setYAxisLogarithmic(True)

        self.plot_canvas[3] = PlotWindow(roi=False, control=False, position=True, plugins=False)
        self.plot_canvas[3].setDefaultPlotLines(True)
        self.plot_canvas[3].setActiveCurveColor(color='darkblue')
        self.plot_canvas[3].setGraphXLabel("f [m^-1]")
        self.plot_canvas[3].setGraphYLabel("CSD [m^3]")
        self.plot_canvas[3].setGraphTitle("Cumulative Spectral Density of Heights Profile")
        self.plot_canvas[3].setDrawModeEnabled(True, 'rectangle')
        self.plot_canvas[3].setZoomModeEnabled(True)
        self.plot_canvas[3].setXAxisLogarithmic(True)

        self.plot_canvas[4] = PlotWindow(roi=False, control=False, position=True, plugins=False)
        self.plot_canvas[4].setDefaultPlotLines(True)
        self.plot_canvas[4].setActiveCurveColor(color='darkblue')
        self.plot_canvas[4].setGraphXLabel("Length [m]")
        self.plot_canvas[4].setGraphYLabel("ACF")
        self.plot_canvas[4].setGraphTitle("Autocovariance Function of Heights Profile")
        self.plot_canvas[4].setDrawModeEnabled(True, 'rectangle')
        self.plot_canvas[4].setZoomModeEnabled(True)

        self.figure = Figure(figsize=(self.IMAGE_HEIGHT, self.IMAGE_HEIGHT)) # QUADRATA!
        self.figure.patch.set_facecolor('white')

        self.axis = self.figure.add_subplot(111, projection='3d')

        self.axis.set_zlabel("Z [nm]")

        self.plot_canvas[5] = FigureCanvasQTAgg(self.figure)

        self.profileInfo = QTextEdit()
        self.profileInfo.setReadOnly(True)
        self.profileInfo.setMinimumHeight(self.IMAGE_HEIGHT-5)
        self.profileInfo.setMaximumHeight(self.IMAGE_HEIGHT-5)
        self.profileInfo.setMinimumWidth(310)
        self.profileInfo.setMaximumWidth(310)

        profile_box = oasysgui.widgetBox(self.tab[0], "", addSpace=True, orientation="horizontal", height = self.IMAGE_HEIGHT, width=320)
        profile_box.layout().addWidget(self.profileInfo)

        for index in range(0, 6):
            self.tab[index+1].layout().addWidget(self.plot_canvas[index])

        self.tabs.setCurrentIndex(1)

    def plot_dabam_graph(self, plot_canvas_index, curve_name, x_values, y_values, xtitle, ytitle, color='blue', replace=True):
        self.plot_canvas[plot_canvas_index].addCurve(x_values, y_values, curve_name, symbol='', color=color, replace=replace) #'+', '^', ','
        self.plot_canvas[plot_canvas_index].setGraphXLabel(xtitle)
        self.plot_canvas[plot_canvas_index].setGraphYLabel(ytitle)
        self.plot_canvas[plot_canvas_index].replot()

    def set_ModifyY(self):
        self.modify_box_1.setVisible(self.modify_y == 0)
        self.modify_box_2.setVisible(self.modify_y == 1)
        self.modify_box_3.setVisible(self.modify_y == 2)

    def set_RenormalizeY(self):
        self.output_profile_box_1.setVisible(self.renormalize_y==1)

    def table_item_clicked(self):
        if self.table.selectionModel().hasSelection():
            if not self.table.rowCount() == 0:
                if not self.table.item(0, 0) is None:
                    row = self.table.selectionModel().selectedRows()[0].row()
                    self.entry_number = int(self.table.item(row, 0).text())

                    self.retrieve_profile()

    def retrieve_profile(self):
        try:
            if self.entry_number is None or self.entry_number <= 0:
                raise Exception("Entry number should be a strictly positive integer number")

            self.server.load(self.entry_number)
            self.profileInfo.setText(self.server.info_profiles())
            self.plot_canvas[0].setGraphTitle(
                "Heights Profile. St.Dev.=%.3f nm" % (self.server.stdev_profile_heights() * 1e9))
            self.plot_canvas[1].setGraphTitle(
                "Slopes Profile. St.Dev.=%.3f $\mu$rad" % (self.server.stdev_profile_slopes() * 1e6))
            if self.use_undetrended == 0:
                self.plot_dabam_graph(0, "heights_profile", self.si_to_user_units * self.server.y,
                                      1e9 * self.server.zHeights, "Y [" + self.workspace_units_label + "]", "Z [nm]")
                self.plot_dabam_graph(1, "slopes_profile", self.si_to_user_units * self.server.y, 1e6 * self.server.zSlopes,
                                      "Y [" + self.workspace_units_label + "]", "Zp [$\mu$rad]")
            else:
                self.plot_dabam_graph(0, "heights_profile", self.si_to_user_units * self.server.y,
                                      1e9 * self.server.zHeightsUndetrended, "Y [" + self.workspace_units_label + "]",
                                      "Z [nm]")
                self.plot_dabam_graph(1, "slopes_profile", self.si_to_user_units * self.server.y,
                                      1e6 * self.server.zSlopesUndetrended, "Y [" + self.workspace_units_label + "]",
                                      "Zp [$\mu$rad]")
            y = self.server.f ** (self.server.powerlaw["hgt_pendent"]) * 10 ** self.server.powerlaw["hgt_shift"]
            i0 = self.server.powerlaw["index_from"]
            i1 = self.server.powerlaw["index_to"]
            beta = -self.server.powerlaw["hgt_pendent"]
            self.plot_canvas[2].setGraphTitle(
                "Power Spectral Density of Heights Profile (beta=%.2f,Df=%.2f)" % (beta, (5 - beta) / 2))
            self.plot_dabam_graph(2, "psd_heights_2", self.server.f, self.server.psdHeights, "f [m^-1]", "PSD [m^3]")
            self.plot_dabam_graph(2, "psd_heights_1", self.server.f, y, "f [m^-1]", "PSD [m^3]", color='green',
                                  replace=False)
            self.plot_dabam_graph(2, "psd_heights_3", self.server.f[i0:i1], y[i0:i1], "f [m^-1]", "PSD [m^3]", color='red',
                                  replace=False)
            self.plot_dabam_graph(3, "csd", self.server.f, self.server.csd_heights(), "f [m^-1]", "CSD [m^3]")
            c1, c2, c3 = dabam.autocorrelationfunction(self.server.y, self.server.zHeights)
            self.plot_canvas[4].setGraphTitle(
                "Autocovariance Function of Heights Profile.\nAutocorrelation Length (ACF=0.5)=%.3f m" % (c3))
            self.plot_dabam_graph(4, "acf", c1[0:-1], c2, "Length [m]", "Heights Autocovariance")
            # surface error removal
            if not self.zz is None and not self.yy is None and not self.xx is None:
                self.xx = None
                self.yy = None
                self.zz = None
                self.axis.set_title("")
                self.axis.clear()
                self.plot_canvas[5].draw()

            if (self.tabs.currentIndex()==6): self.tabs.setCurrentIndex(1)

        except Exception as exception:
            QMessageBox.critical(self, "Error",
                                 exception.args[0],
                                 QMessageBox.Ok)

            #raise exception


    def search_profiles(self):
        try:
            self.table.itemClicked.disconnect(self.table_item_clicked)
            self.table.clear()

            row_count = self.table.rowCount()
            for n in range(0, row_count):
                self.table.removeRow(0)

            self.table.setHorizontalHeaderLabels(self.horHeaders)

            profiles = dabam.dabam_summary_dictionary(surface=self.get_dabam_shape(),
                                                      slp_err_from=self.slope_error_from*1e-6,
                                                      slp_err_to=self.slope_error_to*1e-6,
                                                      length_from=self.dimension_y_from / self.si_to_user_units,
                                                      length_to=self.dimension_y_to / self.si_to_user_units)

            for index in range(0, len(profiles)):
                self.table.insertRow(0)

            for index in range(0, len(profiles)):
                table_item = QTableWidgetItem(str(profiles[index]["entry"]))
                table_item.setTextAlignment(Qt.AlignCenter)
                self.table.setItem(index, 0, table_item)
                table_item = QTableWidgetItem(str(profiles[index]["surface"]))
                table_item.setTextAlignment(Qt.AlignLeft)
                self.table.setItem(index, 1, table_item)
                table_item = QTableWidgetItem(str(numpy.round(profiles[index]["length"]*self.si_to_user_units, 3)))
                table_item.setTextAlignment(Qt.AlignRight)
                self.table.setItem(index, 2, table_item)
                table_item = QTableWidgetItem(str(numpy.round(profiles[index]["hgt_err"]*1e9, 3)))
                table_item.setTextAlignment(Qt.AlignRight)
                self.table.setItem(index, 3, table_item)
                table_item = QTableWidgetItem(str(numpy.round(profiles[index]["slp_err"]*1e6, 3)))
                table_item.setTextAlignment(Qt.AlignRight)
                self.table.setItem(index, 4, table_item)

            self.table.setHorizontalHeaderLabels(self.horHeaders)
            self.table.resizeRowsToContents()
            self.table.setSelectionBehavior(QAbstractItemView.SelectRows)

            self.table.itemClicked.connect(self.table_item_clicked)

            self.overlay_search.hide()

        except Exception as exception:
            self.overlay_search.hide()

            QMessageBox.critical(self, "Error",
                                 exception.args[0],
                                 QMessageBox.Ok)

    def get_dabam_shape(self):
        if self.shape == 0: return None
        elif self.shape == 1: return "plane"
        elif self.shape == 2: return "cylindrical"
        elif self.shape == 3: return "elliptical"
        elif self.shape == 4: return "toroidal"
        elif self.shape == 5: return "spherical"

    def calculate_heigth_profile_ni(self):
        self.calculate_heigth_profile(not_interactive_mode=True)

    def calculate_heigth_profile(self, not_interactive_mode=False):
        try:
            if self.server.y is None: raise Exception("No Profile Selected")

            sys.stdout = EmittingStream(textWritten=self.writeStdOut)

            self.check_fields()

            combination = "EF"

            if self.modify_y == 2:
                profile_1D_y_x_temp = self.si_to_user_units * self.server.y
                if self.use_undetrended == 0: profile_1D_y_y_temp = self.si_to_user_units * self.server.zHeights
                else: profile_1D_y_y_temp = self.si_to_user_units * self.server.zHeightsUndetrended

                first_coord = profile_1D_y_x_temp[0]
                second_coord  = profile_1D_y_x_temp[1]
                last_coord = profile_1D_y_x_temp[-1]
                step = numpy.abs(second_coord - first_coord)
                length = numpy.abs(last_coord - first_coord)
                n_points_old = len(profile_1D_y_x_temp)

                if self.new_length > length:
                    difference = self.new_length - length

                    n_added_points = int(difference/step)
                    if difference % step == 0:
                        n_added_points += 1
                    if n_added_points % 2 != 0:
                        n_added_points += 1


                    profile_1D_y_x = numpy.arange(n_added_points + n_points_old) * step
                    profile_1D_y_y = numpy.ones(n_added_points + n_points_old) * self.filler_value * 1e-9 * self.si_to_user_units
                    profile_1D_y_y[int(n_added_points/2) : n_points_old + int(n_added_points/2)] = profile_1D_y_y_temp
                elif self.new_length < length:
                    difference = length - self.new_length

                    n_removed_points = int(difference/step)
                    if difference % step == 0:
                        n_removed_points -= 1
                    if n_removed_points % 2 != 0:
                        n_removed_points -= 1

                    if n_removed_points >= 2:
                        profile_1D_y_x = profile_1D_y_x_temp[0 : (n_points_old - n_removed_points)]
                        profile_1D_y_y = profile_1D_y_y_temp[(int(n_removed_points/2) - 1) : (n_points_old - int(n_removed_points/2) - 1)]

                    else:
                        profile_1D_y_x = profile_1D_y_x_temp
                        profile_1D_y_y = profile_1D_y_y_temp
                else:
                    profile_1D_y_x = profile_1D_y_x_temp
                    profile_1D_y_y = profile_1D_y_y_temp

            else:
                if self.modify_y == 0:
                    profile_1D_y_x = self.si_to_user_units * self.server.y
                elif self.modify_y == 1:
                    profile_1D_y_x = self.si_to_user_units * self.server.y * self.scale_factor_y

                if self.use_undetrended == 0: profile_1D_y_y = self.si_to_user_units * self.server.zHeights
                else: profile_1D_y_y = self.si_to_user_units * self.server.zHeightsUndetrended


            if self.center_y:
                first_coord = profile_1D_y_x[0]
                last_coord = profile_1D_y_x[-1]
                length = numpy.abs(last_coord - first_coord)

                profile_1D_y_x_temp = numpy.linspace(-length/2, length/2, len(profile_1D_y_x))

                profile_1D_y_x = profile_1D_y_x_temp

            if self.renormalize_y == 0:
                rms_y = None
            else:
                if self.error_type_y == profiles_simulation.FIGURE_ERROR:
                    rms_y = self.si_to_user_units * self.rms_y * 1e-9   # from nm to user units
                else:
                    rms_y = self.rms_y * 1e-6 # from urad to rad

            xx, yy, zz = profiles_simulation.simulate_profile_2D(combination = combination,
                                                                 error_type_l = self.error_type_y,
                                                                 rms_l = rms_y,
                                                                 x_l = profile_1D_y_x,
                                                                 y_l = profile_1D_y_y,
                                                                 mirror_width = self.dimension_x,
                                                                 step_w = self.step_x,
                                                                 rms_w = 0.0)

            self.xx = xx
            self.yy = yy
            self.zz = zz # in user units

            self.axis.clear()

            x_to_plot, y_to_plot = numpy.meshgrid(xx, yy)
            z_to_plot = zz * 1e9 / self.si_to_user_units #nm

            self.axis.plot_surface(x_to_plot, y_to_plot, z_to_plot,
                                   rstride=1, cstride=1, cmap=cm.autumn, linewidth=0.5, antialiased=True)

            sloperms = profiles_simulation.slopes(zz.T, xx, yy, return_only_rms=1)

            title = ' Slope error rms in X direction: %f $\mu$rad' % (sloperms[0]*1e6) + '\n' + \
                    ' Slope error rms in Y direction: %f $\mu$rad' % (sloperms[1]*1e6)

            self.axis.set_xlabel("X [" + self.workspace_units_label + "]")
            self.axis.set_ylabel("Y [" + self.workspace_units_label + "]")
            self.axis.set_zlabel("Z [nm]")

            self.axis.set_title(title)
            self.axis.mouse_init()

            if not not_interactive_mode:
                try:
                    self.plot_canvas[5].draw()
                except:
                    pass

                self.tabs.setCurrentIndex(6)

                QMessageBox.information(self, "QMessageBox.information()",
                                        "Height Profile calculated: if the result is satisfactory,\nclick \'Generate Height Profile File\' to complete the operation ",
                                        QMessageBox.Ok)
        except Exception as exception:
            QMessageBox.critical(self, "Error",
                                 exception.args[0],
                                 QMessageBox.Ok)

            #raise exception

    def generate_heigth_profile_file_ni(self):
        self.generate_heigth_profile_file(not_interactive_mode=True)

    def generate_heigth_profile_file(self, not_interactive_mode=False):
        if not self.zz is None and not self.yy is None and not self.xx is None:
            try:
                congruence.checkDir(self.heigth_profile_file_name)

                sys.stdout = EmittingStream(textWritten=self.writeStdOut)

                ST.write_shadow_surface(self.zz, self.xx, self.yy, outFile=congruence.checkFileName(self.heigth_profile_file_name))
                if not not_interactive_mode:
                    QMessageBox.information(self, "QMessageBox.information()",
                                            "Height Profile file " + self.heigth_profile_file_name + " written on disk",
                                            QMessageBox.Ok)
                if self.modify_y == 0:
                    dimension_y = self.si_to_user_units * (self.server.y[-1] - self.server.y[0])
                if self.modify_y == 1:
                    dimension_y = self.si_to_user_units * (self.server.y[-1] - self.server.y[0]) * self.scale_factor_y
                elif self.modify_y == 2:
                    dimension_y = self.new_length

                self.send("PreProcessor_Data", ShadowPreProcessorData(error_profile_data_file=self.heigth_profile_file_name,
                                                                      error_profile_x_dim=self.dimension_x,
                                                                      error_profile_y_dim=dimension_y))
            except Exception as exception:
                QMessageBox.critical(self, "Error",
                                     exception.args[0],
                                     QMessageBox.Ok)

    def call_reset_settings(self):
        if ConfirmDialog.confirmed(parent=self, message="Confirm Reset of the Fields?"):
            try:
                self.resetSettings()
            except:
                pass

    def check_fields(self):
        self.dimension_x = congruence.checkStrictlyPositiveNumber(self.dimension_x, "Dimension X")
        self.step_x = congruence.checkStrictlyPositiveNumber(self.step_x, "Step X")
        if self.step_x > self.dimension_x/2:
            raise Exception("Step Width should be smaller than or equal to Width/2")
        if self.modify_y == 1:
            self.scale_factor_y = congruence.checkStrictlyPositiveNumber(self.scale_factor_y, "Scale Factor")
        elif self.modify_y == 2:
            self.new_length = congruence.checkStrictlyPositiveNumber(self.new_length, "New Length")

        if self.renormalize_y == 1:
            self.rms_y = congruence.checkPositiveNumber(self.rms_y, "Rms Y")

        congruence.checkDir(self.heigth_profile_file_name)

    def writeStdOut(self, text):
        cursor = self.shadow_output.textCursor()
        cursor.movePosition(QTextCursor.End)
        cursor.insertText(text)
        self.shadow_output.setTextCursor(cursor)
        self.shadow_output.ensureCursorVisible()

    def selectFile(self):
        self.le_heigth_profile_file_name.setText(oasysgui.selectFileFromDialog(self, self.heigth_profile_file_name, "Select Output File", file_extension_filter="Data Files (*.dat)"))
Beispiel #19
0
class MainForm(QDialog):
    def __init__(self, parent=None):
        super(MainForm, self).__init__(parent)

        self.words_to_be_learned_llist = []
        self.words2sentence_list = []

        self.files_table = QTableWidget()
        self.files_paths_list = []
        self.refresh_files_table()

        self.files_Button = QPushButton(u"添加文章")

        self.zhong_kao_CheckBox = QCheckBox(u"中考词汇")
        self.gao_kao_CheckBox = QCheckBox(u"高考词汇")
        self.analysis_Button = QPushButton(u"分析")

        self.files_layout =  QHBoxLayout()
        self.files_layout.addWidget(self.files_table)
        self.files_layout.addWidget(self.files_Button)

        self.a_g_layout = QHBoxLayout()
        self.a_g_layout.addWidget(self.zhong_kao_CheckBox)
        self.a_g_layout.addWidget(self.gao_kao_CheckBox)
        self.a_g_layout.addWidget(self.analysis_Button)
        # self.a_g_layout.addWidget(self.generate_Button)

        self.layout = QVBoxLayout()
        self.layout.addLayout(self.files_layout)
        self.layout.addLayout(self.a_g_layout)

        self.setLayout(self.layout)
        self.setWindowTitle(u"外文阅读工具")

        self.connect(self.files_Button, SIGNAL("clicked()"), self.addFiles)
        self.connect(self.analysis_Button, SIGNAL("clicked()"), self.analysis)

    def addFiles(self):
        print("addFiles")
        files = QFileDialog.getOpenFileNames(self, "Select Music Files",
            QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation))
        if not files:
            return
        self.files_paths_list = files
        print "len_list = {0}".format(len(self.files_paths_list))
        self.refresh_files_table()

    def refresh_files_table(self):
        print("refresh_files_table")
        self.files_table.clear()

        self.Y_MAX = len(self.files_paths_list)
        self.X_MAX = 1
        self.files_table.setColumnCount(self.X_MAX)
        self.files_table.setRowCount(self.Y_MAX)
        self.files_table.setHorizontalHeaderLabels([u'文章列表'])#tips:这一句必须在setHeaderLabels之后出现
        for y in range(self.Y_MAX):
            text = re.split("[^a-zA-Z0-9\_\.\(\)]",#这里用正则表达式,因为windows和linux下的斜杠不同
                            self.files_paths_list[y])[-1]
            item = QTableWidgetItem(u"{0}".format(text))
            self.files_table.setItem(y, 0, item)

    def analysis(self):
        print("in analysis")
        time1 = time.time()
        try:#每次读取known时建立一个.bak备份吧
            known_words = A_a.load_known_words()
            print "known_words",len(known_words)
        except:
            QMessageBox.warning(self, u"Error", u"known.txt not found!")
            return

        if len(self.files_paths_list) == 0:
            QMessageBox.warning(self, u"Error", u"文章列表不能为空!")
            return

        self.words_to_be_learned_llist = []#!!复原这个llist,别掉了self了
        self.words2sentence_list = []
        for _file in self.files_paths_list:
            words_to_be_learned, words_sentence = A_a.analysis_article(_file, known_words)
            self.words_to_be_learned_llist.append(words_to_be_learned)
            self.words2sentence_list.append(words_sentence)

        time_used = time.time() - time1
        Form_analysis = F_a.analysis_Form(time_used ,self.files_paths_list,
                                    self.words_to_be_learned_llist, self.words2sentence_list)
        if Form_analysis.exec_():
            pass
Beispiel #20
0
class LabelAssistDialog(QDialog):
    """
    A simple UI for showing bookmarks and navigating to them.

    FIXME: For now, this window is tied to a particular lane.
           If your project has more than one lane, then each one
           will have it's own bookmark window, which is kinda dumb.
    """
    def __init__(self, parent, topLevelOperatorView):
        super(LabelAssistDialog, self).__init__(parent)

        # Create thread router to populate table on main thread
        self.threadRouter = ThreadRouter(self)

        # Set object classification operator view
        self.topLevelOperatorView = topLevelOperatorView

        self.setWindowTitle("Label Assist")
        self.setMinimumWidth(500)
        self.setMinimumHeight(700)

        layout = QGridLayout()
        layout.setContentsMargins(10, 10, 10, 10)

        # Show variable importance table
        rows = 0
        columns = 4
        self.table = QTableWidget(rows, columns)
        self.table.setHorizontalHeaderLabels(
            ['Frame', 'Max Area', 'Min Area', 'Labels'])
        self.table.verticalHeader().setVisible(False)

        # Select full row on-click and call capture double click
        self.table.setSelectionBehavior(QTableView.SelectRows)
        self.table.doubleClicked.connect(self._captureDoubleClick)

        layout.addWidget(self.table, 1, 0, 3, 2)

        # Create progress bar
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(0)
        self.progressBar.hide()
        layout.addWidget(self.progressBar, 4, 0, 1, 2)

        # Create button to populate table
        self.computeButton = QPushButton('Compute object info')
        self.computeButton.clicked.connect(self._triggerTableUpdate)
        layout.addWidget(self.computeButton, 5, 0)

        # Create close button
        closeButton = QPushButton('Close')
        closeButton.clicked.connect(self.close)
        layout.addWidget(closeButton, 5, 1)

        # Set dialog layout
        self.setLayout(layout)

    def _triggerTableUpdate(self):
        # Check that object area is included in selected features
        featureNames = self.topLevelOperatorView.SelectedFeatures.value

        if 'Standard Object Features' not in featureNames or 'Count' not in featureNames[
                'Standard Object Features']:
            box = QMessageBox(
                QMessageBox.Warning, 'Warning',
                'Object area is not a selected feature. Please select this feature on: \"Standard Object Features > Shape > Size in pixels\"',
                QMessageBox.NoButton, self)
            box.show()
            return

        # Clear table
        self.table.clearContents()
        self.table.setRowCount(0)
        self.table.setSortingEnabled(False)
        self.progressBar.show()
        self.computeButton.setEnabled(False)

        # Compute object features and number of labels per frame
        def compute_features():
            features = self.topLevelOperatorView.ObjectFeatures([]).wait()
            labels = self.topLevelOperatorView.LabelInputs([]).wait()
            return features, labels

        req = Request(compute_features)
        req.notify_finished(self._populateTable)
        req.submit()

    @threadRouted
    def _populateTable(self, features_and_labels):
        features, labels = features_and_labels
        self.progressBar.hide()
        self.computeButton.setEnabled(True)

        for frame, objectFeatures in features.iteritems():
            # Insert row
            rowNum = self.table.rowCount()
            self.table.insertRow(self.table.rowCount())

            # Get max and min object areas
            areas = objectFeatures['Standard Object Features']['Count']
            maxObjArea = numpy.max(areas[numpy.nonzero(areas)])
            minObjArea = numpy.min(areas[numpy.nonzero(areas)])

            # Get number of labeled objects
            labelNum = numpy.count_nonzero(labels[frame])

            # Load fram number
            item = QTableWidgetItem(str(frame))
            item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
            self.table.setItem(rowNum, 0, item)

            # Load max object areas
            item = QTableWidgetItemWithFloatSorting(
                str("{: .02f}".format(maxObjArea)))
            item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
            self.table.setItem(rowNum, 1, item)

            # Load min object areas
            item = QTableWidgetItemWithFloatSorting(
                str("{: .02f}".format(minObjArea)))
            item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
            self.table.setItem(rowNum, 2, item)

            # Load label numbers
            item = QTableWidgetItemWithFloatSorting(
                str("{: .01f}".format(labelNum)))
            item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
            self.table.setItem(rowNum, 3, item)

        # Resize column size to fit dialog size
        self.table.horizontalHeader().setResizeMode(QHeaderView.Stretch)

        # Sort by max object area
        self.table.setSortingEnabled(True)
        self.table.sortByColumn(1)

    def _captureDoubleClick(self):
        # Navigate to selected frame
        index = self.table.selectedIndexes()[0]
        frameStr = self.table.model().data(index).toString()

        if frameStr:
            frameNum = int(frameStr)
            self.parent().editor.posModel.time = frameNum
Beispiel #21
0
class KeywordTable(HelpedWidget):
    """Shows a table of key/value pairs. The data structure expected and sent to the getter and setter is a dictionary of values."""
    def __init__(self, model, table_label="", help_link=""):
        HelpedWidget.__init__(self, table_label, help_link)

        self.table = QTableWidget(self)
        self.table.setColumnCount(2)
        self.setColumnHeaders()
        self.table.verticalHeader().setHidden(True)
        self.table.setColumnWidth(0, 150)
        self.table.horizontalHeader().setStretchLastSection(True)

        self.table.setMinimumHeight(110)
        self.table.setSelectionMode(QAbstractItemView.SingleSelection)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.addWidget(self.table)

        self.addWidget(AddRemoveWidget(self.addItem, self.removeItem))

        self.connect(self.table, SIGNAL('cellChanged(int,int)'), self.tableChanged)

        assert isinstance(model, DictionaryModelMixin)
        self.model = model
        model.observable().attach(DictionaryModelMixin.DICTIONARY_CHANGED_EVENT, self.modelChanged)
        self.modelChanged()


    def setColumnHeaders(self, keyword_name="Keyword", value_name="Value"):
        self.headers = [keyword_name, value_name]
        self.table.setHorizontalHeaderLabels(self.headers)

    def addItem(self):
        """Called by the add button to insert a new keyword"""
        title = "New %s" % self.headers[0]
        description = "Enter new %s:" % self.headers[0]
        (new_keyword, ok) = QInputDialog.getText(self, title, description, QLineEdit.Normal)

        if ok:
            new_keyword = str(new_keyword).strip()
            self.model.addKey(new_keyword)

    def removeItem(self):
        """Called by the remove button to remove a selected keyword"""
        current_row = self.table.currentRow()

        if current_row >= 0:
            do_delete = QMessageBox.question(self, "Delete row?", "Are you sure you want to delete the key/value pair?", QMessageBox.Yes | QMessageBox.No )

            if do_delete:
                key_item = self.table.item(current_row, 0)
                if key_item is not None:
                    key = str(key_item.text()).strip()
                    self.model.removeKey(key)


    def tableChanged(self, row, column):
        """Called whenever the contents of a cell changes."""
        key_item = self.table.item(row, 0)

        if key_item is not None:
            key = str(key_item.text()).strip()
            value_item = self.table.item(row, 1)

            if value_item is not None:
                value = str(value_item.text()).strip()

                self.model.setValueForKey(key, value)


    def modelChanged(self):
        """Retrieves data from the model and inserts it into the table."""
        values = self.model.getDictionary()

        blocked = self.table.blockSignals(True)

        for row in reversed(range(self.table.rowCount())):
            self.table.removeRow(row)

        row = 0
        for key in values:
            key_item = QTableWidgetItem(str(key))
            key_item.setFlags(key_item.flags() ^ Qt.ItemIsEditable)
            value_item = QTableWidgetItem(str(values[key]))
            self.table.insertRow(row)
            self.table.setItem(row, 0, key_item)
            self.table.setItem(row, 1, value_item)
            row += 1

        self.table.blockSignals(blocked)
Beispiel #22
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        logging.info(u'创建主窗口...')

        QtGui.QMainWindow.__init__(self, parent)

        tabs = QtGui.QTabWidget(self)

        tab2 = QtGui.QWidget()
        tab3 = QtGui.QWidget()

        self.console = MyConsole(parent=self)

        # tab2 - self.console
        self.console.setMinimumSize(1500, 800)
        scroll = QtGui.QScrollArea()
        scroll.setWidget(self.console)
        scroll.setAutoFillBackground(True)
        scroll.setWidgetResizable(True)
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(scroll)
        tab2.setLayout(vbox)

        # tab3 -
        self.viewEntry = QTableWidget(0, 12)
        self.viewEntry.setHorizontalHeaderLabels(
                [u'期数', u'时间', u'冠军', u'亚军', u'第三名', u'第四名', u'第五名', u'第六名', u'第七名', u'第八名', u'第九名', u'第十名'])
        self.viewEntry.horizontalHeader().setStretchLastSection(True)
        self.viewEntry.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)

        vbox3 = QtGui.QVBoxLayout()
        vbox3.addWidget(self.viewEntry)
        tab3.setLayout(vbox3)
        tabs.addTab(tab2, u"控制台")
        tabs.addTab(tab3, u"开奖结果")

        tabs.resize(1500, 800)
        self.resize(1500, 800)
        self.tabs = tabs
        self.tab2 = tab2
        self.tab3 = tab3
        self.scroll = scroll
        # 禁止最大化
        self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint)

        from myutil.tool.Overlay import Overlay
        self.setCentralWidget(self.tabs)
        self.overlay = Overlay(self.centralWidget())
        self.overlay.hide()

        self.show()

    @pyqtSlot(str)
    def mySetWindowTitle(self, title):
        self.setWindowTitle(title)

    @pyqtSlot(str, list)
    def completeHistoryResultData(self, timesnow, open_balls):
        logging.info(u"【主窗口-历史数据展板-填充之】")
        for i in range(len(open_balls)):
            newItem = QTableWidgetItem(str(open_balls[i]))
            self.viewEntry.setItem(0, 2 + i, newItem)
        logging.info(u"【主窗口-历史数据展板-填充完毕】")

    @pyqtSlot(str, list)
    def appendHistoryResultData(self, timesnow, open_balls):
        logging.info(u"【主窗口-历史数据展板-追加】")
        time_str = MyTool.getCurrentTimeStr()
        self.viewEntry.insertRow(0)
        # 期数
        newItem = QTableWidgetItem(str(int(timesnow) - 1))
        self.viewEntry.setItem(0, 0, newItem)
        # 时间
        newItem = QTableWidgetItem(time_str)
        self.viewEntry.setItem(0, 1, newItem)

        for i in range(len(open_balls)):
            newItem = QTableWidgetItem(str(open_balls[i]))
            self.viewEntry.setItem(0, 2 + i, newItem)
        logging.info(u"【主窗口-历史数据展板-追加完毕】")

    @pyqtSlot(list)
    def updateHistoryResultData(self, data_list):
        logging.info(u"【主窗口-历史数据展板-大更新】################START HistoryResultData################")
        # 先清空...
        self.viewEntry.clearContents()
        self.viewEntry.setRowCount(0)

        for period in data_list:
            # 添加一行
            row = self.viewEntry.rowCount()
            self.viewEntry.insertRow(row)

            # 期数
            newItem = QTableWidgetItem(period[0])
            self.viewEntry.setItem(row, 0, newItem)

            # 时间
            newItem = QTableWidgetItem(str(period[1]))
            self.viewEntry.setItem(row, 1, newItem)
            if self.console.play_mode in [common.PLAYMODE_PK10, common.PLAYMODE_XYFT]:
                for i in range(10):
                    newItem = QTableWidgetItem(str(period[2 + i]))
                    self.viewEntry.setItem(row, 2 + i, newItem)
            else:
                for i in range(5):
                    newItem = QTableWidgetItem(str(period[2 + i]))
                    self.viewEntry.setItem(row, 2 + i, newItem)

        logging.info(u"【主窗口-历史数据展板-大更新】################END HistoryResultData################")

    def closeEvent(self, event):
        reply = QtGui.QMessageBox.question(self, u'退出', u"您确定离开吗?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
        if reply == QtGui.QMessageBox.Yes:
            # 关闭http连接...
            from common.common import req_session
            req_session.close()

            event.accept()
        else:
            event.ignore()

    def resizeEvent(self, event):
        self.overlay.resize(event.size())
        event.accept()
Beispiel #23
0
class LicenseFrontend(ScrollArea):
    COMPONENT = 'license'
    LABEL = tr('Activation keys')
    REQUIREMENTS = ('license',)
    ICON = ':/icons/add_new_key.png'

    def __init__(self, client, parent):
        ScrollArea.__init__(self)
        if not EDENWALL:
            message_area = MessageArea()
            message_area.critical(
                "nuFirewall",
                tr(
                    "This EAS version does not support the Activation Key frontend but it seems that your appliance does. "
                    "Please check if another EAS version is available."
                    )
                    )
            self.setWidget(message_area)
            return
        self.client = client
        self.mainwindow = parent
        self._modified = False
        self.error_message = ''
        self._not_modifying = True
        try:
            self.ID = self.client.call("license", 'getID')
        except RpcdError:
            self.__disable("Could not fetch activation key info")

        self.buildInterface()
        self.getValidLicenses()

    @staticmethod
    def get_calls():
        """
        services called by initial multicall
        """
        return (("license", 'getID'),)

    def __disable(self, reason):
        self.mainwindow.addToInfoArea(
            tr("The activation key management interface is disabled."),
            COLOR_ERROR
            )
        self.mainwindow.addToInfoArea(
            reason,
            COLOR_ERROR
            )
        self.close()
        raise NuConfModuleDisabled(reason)

    def buildInterface(self):
        frame = QFrame()
        layout = QVBoxLayout(frame)
        self.setWidget(frame)
        self.setWidgetResizable(True)

        title = u'<h1>%s</h1>' % self.tr('EdenWall activation keys')
        layout.addWidget(QLabel(title))

        sn = "<strong>%s</strong>" % self.ID
        self.IDLabel = QLabel(tr('This appliance serial number is %s.') % sn)
        self.IDLabel.setTextInteractionFlags(
            Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse)
        sendLicenseButton = NuConfPageKit.createButton(
            tr('Upload an activation key'), frame, self.mainwindow,
            self.chooseAndSendFile, QIcon(":/icons/up"))
        self.mainwindow.writeAccessNeeded(sendLicenseButton)

        self.table = QTableWidget(0, 4, frame)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.table.setSelectionMode(QAbstractItemView.NoSelection)
        self.table.horizontalHeader().setStretchLastSection(True)
        self.table.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
        self.table.setHorizontalHeaderLabels([
                unicode(translate('MainWindow', 'Activation key owner')),
                unicode(translate('MainWindow', 'Valid until')),
                unicode(translate('MainWindow', 'Days left')),
                unicode(translate('MainWindow', 'Type'))])

        for widget in (self.IDLabel, sendLicenseButton, self.table):
            layout.addWidget(widget)
        layout.addStretch(100)

    def developOptions(self, licenses):
        """Return a list of licenses with only one option each."""
        developpedOptions = []
        for license in licenses:
            for option in license[INDEX_OPTION].split():
                developpedOption = license[:]
                developpedOption[INDEX_OPTION] = option
                if option == DPI_OPTION_NAME:
                    developpedOption[INDEX_VALIDITY] = "unlimited"
                    developpedOption[INDEX_DAYS_LEFT] = ""
                developpedOptions.append(developpedOption)
        return developpedOptions

    def getValidLicenses(self):
        """Display valid licenses in the table."""
        try:
            licenses = self.client.call("license", 'getValidLicenses')
        except RpcdError, err:
            licenses = []
            self.mainwindow.addToInfoArea(exceptionAsUnicode(err),
                                          category=COLOR_CRITICAL)
        developpedOptions = self.developOptions(licenses)
        self.table.setRowCount(len(developpedOptions))
        for row, developpedOption in enumerate(developpedOptions):
            for col, item in enumerate(developpedOption):
                if col == INDEX_DAYS_LEFT:
                    self.table.setItem(row, col, NumberItem(unicode(item)))
                else:
                    self.table.setItem(row, col,
                        QTableWidgetItem(option_decode(unicode(item))))
class RemoveSentencesDlg(QDialog):
	
	def __init__(self):
		super(RemoveSentencesDlg, self).__init__()
		self.removeList = {}
		self.initUI()
		
	def initUI(self):
		## create a font type for the label
		fontLabel = QFont('SansSerif', 14)
		## create a label 
		self.label = QLabel(self)
		self.label.setAutoFillBackground(True)
		self.label.setAlignment(Qt.AlignCenter)
		self.label.setGeometry(QRect(200, 10, 400, 40))
		self.label.setFont(fontLabel)
		
		## set the text for the Label
		self.label.setText('Remove the Sentences')
		
		## Create a Table to hold all the sentences
		self.sentenceTable = QTableWidget(self)
		## set the size and the position of the table
		self.sentenceTable.setGeometry(QRect(10, 60, 800, 400))
		
		## set the column count for the table
		self.sentenceTable.setColumnCount(1)
		
		sentenceHeaderList = ['Sentences From Table']
		
		self.sentenceTable.setHorizontalHeaderLabels(sentenceHeaderList)
		self.sentenceTable.resizeColumnsToContents()
		self.sentenceTable.horizontalHeader().setStretchLastSection(True)
		self.sentenceTable.verticalHeader().setStretchLastSection(True)
		
		# Create a Remove button
		self.removeButton = QPushButton('Remove', self)
		self.removeButton.move(350, 600)
		
		# Create a close button
		self.closeButton = QPushButton('Close', self)
		self.closeButton.move(450, 600)
		
		## Create signal for the remove button 
		self.connect(self.removeButton, SIGNAL("clicked()"), self.onRemoveClicked)
		
		## Create signal for the close button
		self.connect(self.closeButton, SIGNAL("clicked()"), self.closeClicked)
		
		## Create signal for the sentence table
		self.connect(self.sentenceTable, SIGNAL('cellClicked(int, int)'), self.sentenceStateChanged)
		
		## Get sentences from the database table
		self.getSentencesFromDatabase()
		
		
		self.setGeometry(800, 800, 900, 650)
		
	def getSentencesFromDatabase(self):
		## returns the sentence and the corresponding word associated with it
		self.twoTypeList = data.Data().getSentencesFromDatabase()
		if len(self.twoTypeList) == 2:
			self.sentenceList = self.twoTypeList[0]
			
		## load the sentences in the Table Widget
		self.loadSentencesInTable()
	
	def loadSentencesInTable(self):
		self.col = 0
		if len(self.sentenceList) > 0:
			self.sentenceTable.setRowCount(len(self.sentenceList))
			cellList = []
			## Create QTableWidgetItems from the sentence list
			for sentence in self.sentenceList:
				item = QTableWidgetItem(QString(sentence))
				item.setFlags(Qt.ItemFlags(Qt.ItemIsSelectable |
								Qt.ItemIsUserCheckable | Qt.ItemIsEnabled))
				item.setCheckState(Qt.Unchecked)
				cellList.append(item)
			cellList.reverse()
			# set the widget items in the table
			for item in range(0, len(self.sentenceList)):
				self.sentenceTable.setItem(item, self.col, cellList.pop())
			
			for index in range(0, len(self.sentenceList)):
				self.sentenceTable.verticalHeader().resizeSection(index, 100)
			
			if len(self.sentenceList) == 5:
				self.sentenceTable.setFixedHeight(500)
			if len(self.sentenceList) == 4:
				self.sentenceTable.setFixedHeight(400)
			elif len(self.sentenceList) == 3:
				self.sentenceTable.setFixedHeight(300)
			elif len(self.sentenceList) == 2:
				self.sentenceTable.setFixedHeight(200)
			elif len(self.sentenceList) == 1:
				self.sentenceTable.setFixedHeight(100)
		else:
			self.sentenceTable.clearContents()
		
	def sentenceStateChanged(self, row, col):
		if (self.sentenceTable.item(row, col).checkState() == 2):
			self.removeList[row] = self.sentenceTable.item(row, col).text()
			self.sentenceTable.item(row, col).setFlags(Qt.ItemFlags(Qt.ItemIsEditable |
									Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable))
		else:
			self.sentenceTable.item(row,col).setFlags(Qt.ItemFlags(Qt.ItemIsSelectable |
									Qt.ItemIsUserCheckable | Qt.ItemIsEnabled))
			del self.removeList[row]
	
	def onRemoveClicked(self):
		if len(self.removeList) == 0:
			QMessageBox.information(self, 'Remove Sentences',
					'Select the Sentences to Delete')
		else:
			reply = QMessageBox.question(self,
						'Remove Sentences',
						'You want to delete the selected sentences',
						QMessageBox.Yes | QMessageBox.No)
			if reply == QMessageBox.Yes:
				for sentence in self.removeList:
					if sentence in self.sentenceList:
						self.sentenceList.remove(sentence)
				
				## clear the contents of the Table
				self.sentenceTable.clearContents()
				
				cellList = []
				## Add the new entries into the table
				for sentence in self.sentenceList:
					item = QTableWidgetItem(QString(sentence))
					item.setFlags(Qt.ItemFlags(Qt.ItemIsSelectable |
									Qt.ItemIsUserCheckable | Qt.ItemIsEnabled))
					item.setCheckState(Qt.Unchecked)
					cellList.append(item)
				cellList.reverse()
				
				for index in range(0, len(self.sentenceList)):
					self.sentenceTable.setItem(index, self.col, cellList.pop())
					
				self.sentenceTable.setRowCount(len(self.sentenceList))
				
				deleteSentences = []
				for sentence in self.removeList.values():
					deleteSentences.append(sentence)
				
				rowsDeletec = data.Data().deleteSentencesFromDatabase(deleteSentences)
				self.getSentencesFromDatabase()
				
				self.removeList = {}
	
	def closeClicked(self):
		reply = QMessageBox.question(self,
				"Remove Sentences",
				"Do you want to close the application",
				QMessageBox.Yes | QMessageBox.No)
		if reply == QMessageBox.Yes:
			self.reject()
Beispiel #25
0
class typicalWindow(QtGui.QMainWindow):
	def __init__(self, parent=None):
		super(typicalWindow, self).__init__(parent)
		# QtGui.QMainWindow.__init__(self)
		
		#window
		self.setWindowTitle(winTitle)
		self.central_widget=QWidget(self)
		self.setCentralWidget(self.central_widget)
		self.masterLayout=QGridLayout(self.central_widget)
		self.masterLayout.setAlignment(QtCore.Qt.AlignTop)
		
		#mainlayout
		self.vertical_order_layout=QtGui.QBoxLayout(2)
		self.vertical_order_layout.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignVCenter)
		self.masterLayout.addLayout(self.vertical_order_layout, 0,0,1,1)
		
		self.topDivideLayout=QGridLayout()
		self.botDivideLayout=QGridLayout()
		self.upper_layout=QGridLayout()
		
		
		self.topDivideLayout.addLayout(self.upper_layout, 0,0,1,1)
		
		self.lower_layout=QGridLayout()
		self.lower_layout.setAlignment(QtCore.Qt.AlignTop)
		self.botDivideLayout.addLayout(self.lower_layout, 0,0,1,1)
		
		self.midLayout=QGridLayout()
		self.midLayout.setAlignment(QtCore.Qt.AlignTop)
		
		self.base_layout=QGridLayout()
		self.base_layout.setAlignment(QtCore.Qt.AlignTop)
		self.botDivideLayout.addLayout(self.base_layout, 4,0,1,1)
		
		#sshFile=open(os.path.join(__location__, styleSheetFile+".stylesheet"), 'r')
		#self.styleData=sshFile.read()
		#sshFile.close
		
		#self.setStyleSheet(self.styleData)
		self.top=QtGui.QFrame(self)
		self.top.setFrameShape(QtGui.QFrame.StyledPanel)
		self.top.setLayout(self.topDivideLayout)
		
		self.bottom=QtGui.QFrame(self)
		self.bottom.setFrameShape(QtGui.QFrame.StyledPanel)
		self.bottom.setLayout(self.botDivideLayout)
		
		self.splitPlane=QtGui.QSplitter(QtCore.Qt.Vertical)
		self.splitPlane.addWidget(self.top)
		self.splitPlane.addWidget(self.bottom)
		self.splitPlane.setSizes([650, 650])
		self.vertical_order_layout.addWidget(self.splitPlane)
		
		#layouts
		self.window_layer_00=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_00, 0,0,1,1)
		
		self.window_layer_01=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_01,1,0,1,1)
		
		self.window_layer_02=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_02, 2,0,1,1)
		
		self.window_layer_03=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_03,3,0,1,1)
		
		self.window_layer_04=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_04, 4,0,1,1)
		
		self.window_layer_05=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_05,5,0,1,1)
		
		self.window_layer_06=QGridLayout()
		self.midLayout.addLayout(self.window_layer_06, 6,0,1,1)
		
		self.frame_layout=QGridLayout()
		self.frame_layout.setAlignment(QtCore.Qt.AlignTop)
		self.lower_layout.addLayout(self.frame_layout, 0,0,1,1)
		
		
		self.frameWidget=QtGui.QGridLayout()
		self.frameWidget.setContentsMargins(5,10,5,10)
		self.frameOverride=QtGui.QFrame()
		self.frameOverride.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;")
		self.frameOverride.setFixedHeight(100)
		self.frame_layout.addLayout(self.frameWidget, 0,0,1,1)
		self.frame_layout.addWidget(self.frameOverride, 0,0,1,1)
		
		
		self.frame_title_layout=QGridLayout()
		self.frameWidget.addLayout(self.frame_title_layout, 0,0,1,1)
		self.frame_radio_layout=QGridLayout()
		self.frameWidget.addLayout(self.frame_radio_layout, 1,0,1,1)
		self.frame_btn_layout=QGridLayout()
		self.frameWidget.addLayout(self.frame_btn_layout, 2,0,1,1)
	
		self.btm_btn_layout=QtGui.QGridLayout()
		self.btm_btn_layout.setAlignment(QtCore.Qt.AlignTop)
		self.btm_btn_layout.setContentsMargins(5,10,5,10)	
		self.wbFrame=QtGui.QFrame()
		self.wbFrame.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;")
		self.btm_over_layout=QtGui.QGridLayout()
		self.btm_over_layout.setAlignment(QtCore.Qt.AlignTop)
		self.btm_over_layout.addLayout(self.btm_btn_layout, 0,0,1,1)
		self.btm_over_layout.addWidget(self.wbFrame, 0,0,1,1)
		
		self.pkt_layout= QGridLayout()
		self.pkt_layout.setAlignment(QtCore.Qt.AlignTop)
		self.pkt_widget=QGridLayout()
		self.pkt_widget.setContentsMargins(5,5,5,5)	
		self.pkt_frame=QFrame()
		self.pkt_frame.setMinimumWidth(650)
		self.pkt_frame.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;")
		self.base_layout.addLayout(self.pkt_layout, 0,0,1,1)
		
		self.wndw_layer_pkt=QtGui.QGridLayout()
		self.wndw_layer_pkt.setAlignment(QtCore.Qt.AlignTop)
		self.pkt_widget.addLayout(self.wndw_layer_pkt, 0,0,1,1)
		
		self.park_btn_pkt=QtGui.QBoxLayout(2)
		self.park_btn_pkt.setAlignment(QtCore.Qt.AlignTop)
		self.park_btn_pkt.setContentsMargins(5,2,5,8)
		self.wndw_layer_pkt.addLayout(self.park_btn_pkt, 0,0,1,1)
		self.park_frame=QtGui.QFrame()
		self.park_frame.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;")
		
		
		#widgets
		self.drop_lbl_01=QLabel()
		self.drop_lbl_01.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
		self.drop_lbl_01.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.window_layer_01.addWidget(self.drop_lbl_01, 0,0,1,1)
		
		self.drop_01=QComboBox()
		self.window_layer_01.addWidget(self.drop_01, 0,1,1,1)
		self.drop_01.addItems(prjFileName)
		self.drop_01.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.drop_01.customContextMenuRequested.connect(self.onRightClick)

		# self.drop_01.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		# self.connect(self.drop_lbl_01, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)
		
		self.drop_lbl_02=QLabel()
		self.drop_lbl_02.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
		self.drop_lbl_02.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.window_layer_01.addWidget(self.drop_lbl_02, 0,2,1,1)
		
		self.drop_02=QComboBox()
		self.window_layer_01.addWidget(self.drop_02, 0,3,1,1)
		# QtCore.QObject.connect(self.drop_02, SIGNAL("currentIndexChanged(QString)"),
		# 						self.on_drop_01_changed)
		self.drop_02.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.drop_lbl_01, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)
		
		QtCore.QObject.connect(self.drop_01, SIGNAL("currentIndexChanged(QString)"),
								self.on_drop_01_changed)

		self.button_01=QPushButton("Set")
		self.button_01.setToolTip("set")
		self.connect(self.button_01, SIGNAL('clicked()'), self.listCreate)
		self.window_layer_01.addWidget(self.button_01, 0,4,1,1)
		
		self.button_02=QPushButton("Set2")
		self.button_02.setToolTip("set2")
		self.connect(self.button_02, SIGNAL('clicked()'), self.connectButton01)
		self.window_layer_01.addWidget(self.button_02, 0,5,1,1)

		self.drop_lbl_03=QLabel()
		self.drop_lbl_03.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
		self.drop_lbl_03.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.window_layer_02.addWidget(self.drop_lbl_03, 0,0,1,1)
		
		self.drop_03=QComboBox()
		self.window_layer_02.addWidget(self.drop_03, 0,1,1,1)
		# QtCore.QObject.connect(self.drop_03, SIGNAL("currentIndexChanged(QString)"),
		# 						self.on_drop_01_changed)
		self.drop_03.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.drop_03, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)

		self.button_03=QPushButton("button_03")
		self.button_03.setToolTip("button_03")
		self.connect(self.button_03, SIGNAL('clicked()'), self.connectButton01)
		self.window_layer_02.addWidget(self.button_03, 0,2,1,1)
		
		self.button_04=QPushButton("button_04")
		self.button_04.setToolTip("button_04")
		self.connect(self.button_04, SIGNAL('clicked()'), self.connectButton01)
		self.window_layer_02.addWidget(self.button_04, 0,3,1,1)
		
		self.button_05=QPushButton("button_05")
		self.button_05.setToolTip("button_05")
		self.connect(self.button_05, SIGNAL('clicked()'), self.connectButton01)
		self.window_layer_02.addWidget(self.button_05, 0,4,1,1)

		self.drop_04=QComboBox()
		self.window_layer_04.addWidget(self.drop_04, 0,2,1,1)
		# QtCore.QObject.connect(self.drop_04, SIGNAL("currentIndexChanged(QString)"),
		# 						self.on_drop_01_changed)
		self.drop_04.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.drop_04, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)

		self.list_frame=QFrame()
		self.list_frame.setStyleSheet("color: rgb"+str(buttonColoursDict.get("red")))
		self.list_layout=QHBoxLayout()
		self.list_frame.setLayout(self.list_layout)
		
		self.drop_list_builder_05=QComboBox()
		self.drop_list_builder_05.addItems(get_a_play_list)
		QtCore.QObject.connect(self.drop_list_builder_05, SIGNAL("currentIndexChanged(QString)"),
								self.build)
		self.drop_list_builder_05.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.drop_list_builder_05, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)
		self.list_layout.addWidget(self.drop_list_builder_05)
		self.window_layer_04.addWidget(self.list_frame, 0,3,1,1)

		self.drop_list_06=QComboBox()
		# QtCore.QObject.connect(self.drop_list_06, SIGNAL("currentIndexChanged(QString)"),self.load)
		self.drop_list_06.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.drop_list_06, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)
		#if len(pres)<1:
			#self.drop_list_06.setEnabled(0)
		#else:
			#self.drop_list_06.setEnabled(1)
		self.drop_list_06.addItems(alist2)
		self.list_layout.addWidget(self.drop_list_06)
		
		self.type_list_drop=QComboBox()
		self.type_list_drop.addItems(typesOfStuffInList)
		QtCore.QObject.connect(self.type_list_drop, SIGNAL("currentIndexChanged(QString)"),
								self.on_drop_01_changed)
		self.window_layer_04.addWidget(self.type_list_drop, 0,5,1,1)
		
		self.button_06=QPushButton("button_06")
		self.button_06.setToolTip("button_06")
		self.connect(self.button_06, SIGNAL('clicked()'), self.connectButton01)	
		self.window_layer_04.addWidget(self.button_06, 0,6,0,1)



		headers = ('Name', 'Date', 'Path')

		self.listWidg = QTableWidget(1, 3)
		# self.listWidg.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
		# self.listWidg.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
		# self.listWidg.cellPressed.connect(self.clicked)
		
		# self.listWidg=QTableWidget(0, 3)
		self.listWidg.setHorizontalHeaderLabels(headers)
		# tableWidget=self.listWidg
		self.listWidg.setEditTriggers(QAbstractItemView.DoubleClicked | QAbstractItemView.SelectedClicked)		
		col1, col2, col3= 240, 160, 500
		self.listWidg.setColumnWidth(0, col1)
		self.listWidg.setColumnWidth(1, col2)
		self.listWidg.setColumnWidth(2, col3)
		self.listWidg.setSelectionBehavior(QAbstractItemView.SelectRows)
		self.listWidg.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.listWidg.customContextMenuRequested.connect(self.RightClick)
		# self.listWidg.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)		
		self.connect(self.listWidg, SIGNAL("itemClicked(QTableWidgetItem *)"), self.clicked)
		self.connect(self.listWidg, SIGNAL("itemDoubleClicked(QTableWidgetItem *)"), self.dclicked)
		self.window_layer_05.addWidget(self.listWidg, 0,2,1,1)


		self.status_lbl=QLabel()
		self.status_lbl.setStyleSheet('background-color:transparent')
		self.status_lbl.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter)
		self.frame_title_layout.addWidget(self.status_lbl, 0,2,1,1)

		self.spaceHold=QLabel()
		self.spaceHold.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.spaceHold.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter)
		self.frame_title_layout.addWidget(self.spaceHold, 0,0,1,1)


		self.checkbox=QCheckBox("add")
		self.checkbox.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		# self.checkbox.setContentsMargins(5,0,0,0)
		self.checkbox.setChecked(1)
		self.frame_title_layout.addWidget(self.checkbox, 0,1,1,1)
		
		self.radiobox=QGridLayout()

		self.radio=QRadioButton("radio")
		self.radio.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radio.setChecked(1)
		self.radiobox.addWidget(self.radio, 0,0,1,1)
		
		
		self.newradio=QRadioButton("newradio")
		self.newradio.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.newradio, 0,2,1,1)
		
		self.frame_len_layout=QGridLayout()
		self.frame_len_layout.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter)
		#self.frame_title_layout.addWidget(self.frame_len_layout, 1,3,1,1)
		
		self.spaceHold=QLabel()
		self.spaceHold.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.spaceHold.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter)
		self.frame_title_layout.addWidget(self.spaceHold, 0,3,1,1)
		
		self.over=QRadioButton("over")
		self.over.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.over, 1,1,1,1)
		
		self.head_lbl=QLabel("from")
		self.head_lbl.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.head_lbl, 1, 4,1,1)
		
		self.head_field=QTextEdit("")
		self.head_field.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.head_field, 1, 5,1,1)
		
		self.toe_lbl=QLabel("til")
		self.toe_lbl.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.toe_lbl, 1, 6,1,1)
		
		self.toe_field=QTextEdit("")
		self.toe_field.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.toe_field, 1, 7,1,1)
		
		self.fieldBox=QLineEdit()
		self.fieldBox.setVisible(0)
		self.fieldBox.setText(defaultText)
		
		self.play_in_rv_button=QPushButton("play in RV")
		self.connect(self.play_in_rv_button, SIGNAL('clicked()'), self.play_in_rv)
		self.frame_btn_layout.addWidget(self.play_in_rv_button, 0,0,0,1)
		
		self.look_btn=QPushButton("compare")
		self.connect(self.look_btn, SIGNAL('clicked()'), self.compare_in_rv)
		self.frame_btn_layout.addWidget(self.look_btn, 0,1, 0,1)


		# self.link_btn=QPushButton("link")
		# self.connect(self.link_btn, SIGNAL('clicked()'), self.play_in_rv)
		# self.frame_btn_layout.addWidget(self.link_btn, 0,2,1,1)
		
		self.create_btn=QPushButton("Publish")
		self.connect(self.create_btn, SIGNAL('clicked()'), self.pub_to_shotgun)
		self.frame_btn_layout.addWidget(self.create_btn, 0,3, 1,1)
		
		self.pocketTitle=QPushButton("title")
		self.pocketTitle.setObjectName('label')
		#self.pocketTitle.setStyleSheet("QPushButton#label{font-weight:500; color: rgb"str(buttonColorDict).get("yello"))+"; button-color: rgba(255,255,255,0); font-size: 10pt; border-width: 0px; font-style: bold;}")
		self.connect(self.pocketTitle, SIGNAL('clicked()'), self.send)
		self.connect(self.pocketTitle, SIGNAL('customContextMenuRequested(QPoint)'), lambda: self.send())
		self.park_btn_pkt.addWidget(self.pocketTitle)

		self.a_btn=QPushButton("a_btn")
		#self.a_btn.setStyleSheet("background-color: rgb"str(buttonColorDict).get("yello")))
		self.connect(self.a_btn, SIGNAL('clicked()'), self.play_in_rv)
		self.park_btn_pkt.addWidget(self.a_btn)
		
		self.card_menu=QMenu("card")
		self.card_menuBar=self.menuBar()
		self.card_menuBar.addMenu(self.card_menu)
		self.park_btn_pkt.addWidget(self.card_menuBar)
		buttonGrp.append(self.card_menuBar)
		
		self.card_btn=QToolButton()
		self.card_btn.setPopupMode(QToolButton.MenuButtonPopup)
		self.card_btn.setMenu(self.card_menu)
		self.card_special_btn=QPushButton("card special")
		self.connect(self.card_special_btn, SIGNAL('clicked()'), self.card_special_callup)
		action=QtGui.QWidgetAction(self.card_btn)
		action.setDefaultWidget(self.card_special_btn)
		self.card_btn.menu().addAction(action)

		self.B_card_btn=QToolButton()
		self.B_card_btn.setPopupMode(QToolButton.MenuButtonPopup)
		self.B_card_btn.setMenu(self.card_menu)
		self.B_card_special_btn=QPushButton("card special")
		self.connect(self.B_card_special_btn, SIGNAL('clicked()'),self.B_card_special_callup)
		action=QtGui.QWidgetAction(self.B_card_btn)
		action.setDefaultWidget(self.B_card_special_btn)
		self.B_card_btn.menu().addAction(action)

		self.start_window()

	def start_window(self):
		# self.connectButton01
		print PROJECT		
		print SCENE
		print SHOT
		index = self.drop_01.findText(SCENE, QtCore.Qt.MatchFixedString)
		self.drop_01.setCurrentIndex(index)
		self.get_scene()
		index2 = self.drop_02.findText(SHOT, QtCore.Qt.MatchFixedString)
		self.drop_02.setCurrentIndex(index2)		
		self.listCreate()

	def buttonToggle(self):
		get_a_layout=self.park_btn_pkt
		get_size=get_a_layout.getContentsMargine()
		if get_size==(0,0,0,0):
			self.setvisible()
		else:
			self.setinvisible()
			
	def setinvisible(self):
		for each in buttonGrp:
			each.setVisible(0)
		self.park_btn_pkt.setContentsMargine(0,0,0,0)
		
	def setvisible(self):
		for each in buttonGrp:
			each.setVisible(1)
		self.park_btn_pkt.setContentsMargine(5,8,5,8)


	def get_scene(self):
		scene=self.drop_01
		scene=scene.currentText()		
		getPath='/jobs/'+PROJECT+'/'+scene
		get_items=os.listdir(getPath)
		get_items=sorted(get_items)
		# get_items=set(get_items)
		# get_items=sorted(get_items)
		self.get_shot(get_items)

	def get_shot(self, get_items):
		getDropScene=self.drop_02
		getDropScene.clear()
		getDropScene.addItems(get_items)		

	def onRightClick(self):
		scene=self.drop_01
		scene=scene.currentText()		
		path='/jobs/'+PROJECT+'/'+scene+"/"
		self.launch_folder(path)


	def launch_folder(self, path):
		# command="xdg-open '%s'"%path
		command="dolphin '%s'"%path
		subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
		
	def on_drop_01_changed(self):
		self.get_scene()
		newcol1=self.listWidg.columnWidth(0)
		newcol2=self.listWidg.columnWidth(1)
		newcol3=self.listWidg.columnWidth(2)
		if newcol1==0:
			col1, col2, col3= 240, 160, 500
		else:
			col1, col2, col3= newcol1, newcol2, newcol3
		# findproject=self.drop_01
		self.listWidg.clear()
		self.status_lbl.clear()
		# self.listCreate()
		# self.makeList(listpath, newUser, self.listWidg, model, stat_lab, listtype)
		# self.drop_03.addItems(get_items)
		# model, countdata, listArray	=self.get_listStuff()	
		# if self.on_drop_01=="item1":
		# 	buildListPath=pathList.get("listpathtype").replace(getUser, newUser)
		# 	self.makeList(listpath, newUser, self.listWidg, model, stat_lab, listtype)
		# elif self.on_drop_01=="item2":
		# 	buildListPath=pathList.get("listpathtype2").replace(getUser, newUser)
		# 	self.makeList(listpath, newUser, self.listWidg, model, stat_lab, listtype)
			
	def clicked(self):
		print "hi"
		
	def dclicked(self):
		print "hello"
		
	def get_listStuff(self):
		listArray=self.listWidg
		countdata=listArray.rowCount()
		model=listArray.model()
		return model, countdata, listArray
		
	def getListWidgetData(self):
		model, countdata, listArray	=self.get_listStuff()	
		dataInListWidget=[]
		for row in range(model.rowCount()):
			dataInListWidget.append([])
			for column in range(model.columnCount()):
				index = model.index(row, column)
				dataInListWidget[row].append(str(model.data(index).toString()))
		return dataInListWidget, countdata
		
	def grab_folder_items(self):
		directory=rvFolder
		getstuff=os.listdir(directory)
		getUser=M_USER
		(dataInListWidget, countdata)=self.getListWidgetData()
		# self.listWidg.setRowCount(0)
		# self.listWidg.setColumnCount(0)
		try:
			getFiles=[os.path.join(directory, o) for o in os.listdir(directory) if os.path.isdir(os.path.join(directory, o))]
			pass
		except:
			print "nothing found"
			return
		getFile=[(each) for each in getFiles if getpwuid(stat(each).st_uid).pw_name==getUser]
		getFiles.sort(key=lambda x: os.path.getmtime(x))
		fileDict=[]
		for each in getFiles:
			statbuf=os.stat(each)
			timeFormat=time.strftime('%m/%d/%Y', time.gmtime(os.path.getctime(each)))
			getAccTime=time.ctime(os.path.getmtime(each))
			if "  " in str(getAccTime):
				getAccTime=getAccTime.split("  ")
				getAccTime=getAccTime[1].split(" ")[1]
			else:
				getAccTime=getAccTime.split("  ")[3]
			timeFormat=timeFormat+"  "+getAccTime
			makeDict=(each, timeFormat)
			fileDict.append(makeDict)
		count=len(fileDict)
		fileDict=reversed(fileDict)
		dictItems=fileDict
		return fileDict, count


	def listCreate(self):
		self.listWidg.setColumnCount(3)
		fileDict, count=self.grab_folder_items()		
		self.listWidg.setRowCount(count)
		for row, item in enumerate(fileDict):
			key=item[0].split('/')[-1]
			path=item[0]
			value=item[1]
			self.listWidg.setItem(row, 0, QTableWidgetItem(key))
			self.listWidg.setItem(row, 1, QTableWidgetItem(value))
			self.listWidg.setItem(row, 2, QTableWidgetItem(path))



	def is_listWid_item_selected(self):
		listW=self.listWidg
		(dataInListWidget, countdata)=self.getListWidgetData()
		get_string_id=[]
		for index in xrange(countdata):
			get=listW.item(index, 0).isSelected()
			if get==True:
				getObj=listW.item(index, 2).text()
				getObj=str(getObj)
				get_string_id.append(getObj)
			else:
				get=listW.item(index, 1).isSelected()
				if get==True:
					getObj=listW.item(index, 2).text()
					getObj=str(getObj)
					get_string_id.append(getObj)
				else:
					get=listW.item(index, 2).isSelected()
					if get==True:
						getObj=listW.item(index, 2).text()
						getObj=str(getObj)
						get_string_id.append(getObj)
		return get_string_id
		
	def build(self):
		list_build=self.drop_list_builder_05
		list_build_function=list_build.currentText()
		selected_in_list=self.is_listWid_item_selected()
		allthePaths=('//', '//')
		allthePathsDic={"firstPath":'//', "secondPath":'//'}
		#drop_list_builder_05
		getlisttype=self.type_list_drop
		listtype=getlisttype.currentText()
		if selected_in_list>1:
			getItems=[(each) for each in selected_in_list]
			nameToSave=' '.join(getItems)
			if listtype=="firstPath":
				suffixAppend="first"
				path=allthePathsDic.get("firstPath")
			if listtype=="secondPath":
				suffixAppend="second"
				path=allthePathsDic.get("secondPath")
		compareBucket=[]
		getitems=[(suffixAppend+":"+each.split("/")[-1]) for each in selected_in_list]
		name_to_save=' '.join(getitems)
		if list_build_function==get_a_play_list[1]:
			prompt="name of list:"
			getcomment=self.makeBody(prompt)
			if getComment==None:
				print "needs name"
				return
			else:
				pass
			getComment=getComment.replace(' ', '_')
			#shotList=suffixAppend+"_"+getComment+"storedText.txt"
			fileBuild=path+shotList
			copyfilemessage="creating in "+fileBuild
			replay = QtGui.QMessageBox.question(None, 'Message' ,copyfilemessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
			if reply == QtGui.QMessageBox.Yes:
				if os.path.isfile(fileBuild)==True:
					cmessage="create over "+fileBuild
					replay = QtGui.QMessageBox.question(None, 'Message' ,cmessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
					if reply == QtGui.QMessageBox.Yes:
						inp=open(fileBuild, "w+")
						inp.write(name_to_save)
						inp.close()
						print "created "+fileBuild
					else:
						print "cancelled"
						return
				else:
					inp=open(fileBuild, "w+")
					inp.write(name_to_save)
					inp.close()
					print "created "+fileBuild
			else:
				print "cancelled"
				return
		elif list_build_function==get_a_play_list[2]:
			fileDict, list=self.getAllLists(allthePaths)
					
	def getAllLists(self, stuff):
		fileDict={}
		for each in stuff:
			getList, getnamesdic=self.obtain_presets(each)
			getnames=getnamesdic.keys()
			for eachp in eachn in map(None, getList, getnames):
				dictlist={eachn:eachp}
				fileDict.update(dictlist)
		return fileDict, getList
			
	def obtain_presets(self, morestuff):
		preset=False
		format=".txt"
		getpreset=[os.path.join(dirpath, name) for dirpath, dirnames, files in os.walk(morestuff) for name in files if name.lower().endswith(format)]
		preset=[(each) for each in getpreset if "storedText" in each]
		getlistnames={}
		for each in preset:
			getName=each.split("/")[-1]
			nam=getName.split("_")
			getpletename='_'.join(nam[:-1])
			diction={getpletename:nam[0]}
			getlistnames.update(diction)
		return preset, getlistnames
		
		
	def makeBody(self, prompt):
		text, ok=QtGui.QInputDialog.getText(None, 'Intput Dialog', prompt)
		if ok:
			project=(str(text))
		else:
			return
		return project
		
	def makeBodyFilled(self, prompt, message):
		text, ok=QtGui.QInputDialog.getText(None, 'Intput Dialog', prompt, QtGui.QLineEdit.Normal, message)
		if ok and text:
			project=(str(text))
		else:
			return
		return project

	def load(self):
		list_load=self.drop_list_06
		list_load_function=list_load.currentText()
		allthePaths=('//', '//')
		allthePathsDic={"firstPath":'//', "secondPath":'//'}
		if list_load_function==presetlist[0]:
			prompt="name of list:"
			getcomment=self.makeBody(prompt)
			if getComment==None:
				print "needs name"
				return
			else:
				pass
			getComment=getComment.replace(' ', '_')
			shotList=suffixAppend+"_"+getComment+"storedText.txt"
			fileBuild=path+shotList
			copyfilemessage="creating in "+fileBuild
			replay = QtGui.QMessageBox.question(None, 'Message', copyfilemessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
			if reply == QtGui.QMessageBox.Yes:
				if os.path.isfile(fileBuild)==True:
					cmessage="create over "+fileBuild
					replay = QtGui.QMessageBox.question(None, 'Message' ,cmessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
					if reply == QtGui.QMessageBox.Yes:
						inp=open(fileBuild, "w+")
						inp.write(name_to_save)
						inp.close()
						print "created "+fileBuild
					else:
						print "cancelled"
						return
				else:
					inp=open(fileBuild, "w+")
					inp.write(name_to_save)
					inp.close()
					print "created "+fileBuild
			else:
				print "cancelled"
				return
		elif list_build_function==list_build[2]:
			fileDict, list=self.getAllLists(allthePaths)
			
	def reset_callup(self):
		allthePaths=('//', '//')
		allthePathsDic={"firstPath":'//', "secondPath":'//'}
		getlisttype=self.type_list_drop
		listtype=getlisttype.currentText()
		if listtype=="firstPath":
			directory=allthePathsDic.get("firstPath")
		getUser=getUser
		self.directory_for_taking(getUser, directory)
		
	def directory_for_taking(self, getUser, directory):
		model, countdata, listArray	=self.get_listStuff()
		# self.status_lbl

	def connectButton01(self):
		print "hi"
		self.listCreate()


	def RightClick(self):
		selected_in_list=self.is_listWid_item_selected()
		path=str(selected_in_list[0])+"/"
		# command="xdg-open '%s'"%path
		self.launch_folder(path)


	def play_in_rv(self):
		selected_in_list=self.is_listWid_item_selected()
		command="rv "+str(selected_in_list[0])+"/*"
		print "you are running command: "+command
		subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)


	def compare_in_rv(self):
		selected_in_list=self.is_listWid_item_selected()
		if len(selected_in_list)<2:
			print "must select more than one object in list"
		else:
			command="rv -wipe "+str(selected_in_list[0])+"/* "+str(selected_in_list[1])+"/*"
			print "you are running command: "+command
			subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)


	def pub_to_shotgun(self):
		selected_in_list=self.is_listWid_item_selected()
		getPath=selected_in_list[0]+'/'+foldertypeplay+"/"
		get_items=os.listdir(getPath)
		getFileName=get_items[0].split(".")[0]
		print getFileName
		# getFileName=str(getFileName)+"-"+str(typeplay)
		# print getFileName
		format="_jpg"
		# command='msubmitCmd -p "'+str(selected_in_list[0])+getFileName+'.%04d'+formatEXT+'"'+' -s '+str(startFR)+' -e '+str(endFR)+' -t review -n='+comment+' --task techanim -audio '+audioFile+' -audioOffset 0'
		command='msubmitCmd -p "'+str(selected_in_list[0])+'/'+typeplay+format+'/'+getFileName+'.%04d'+formatEXT+'"'+' -s '+str(startFR)+' -e '+str(endFR)+' -t review -n="'+comment+'" --task '+DEPT
		# command="rv "+str(selected_in_list[0])+"/*"
		print "you are running command: "+command
		subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)


	def send(self):
		print "end"

	def card_special_callup(self):
		print "card_special_callup"
		
	def Bcard_special_callup(self):
		print "B_card_special_callup"
		
		
	def B_card_special_callup(self):
		print "B_card_special_callup"
Beispiel #26
0
class OrbitCorrGeneral(QtGui.QWidget):
    """
    A general orbit correction or local bump panel.
    """
    def __init__(self, bpms, cors, parent = None):
        super(OrbitCorrGeneral, self).__init__(parent)

        self.bpms, self.cors = bpms, cors
        self.sb = [bpm.sb for bpm in self.bpms]
        self.x0, self.y0 = None, None
        self._update_current_orbit()

        self.table = QTableWidget(len(self.bpms), 9)
        self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        hdview = QHeaderView(Qt.Horizontal)
        self.table.setHorizontalHeaderLabels(
            ['BPM Name', 's', "Beta X", "Beta Y",
             "Eta X", 'X Bump', 'Y Bump', "Target X", "Target Y"])
        self._twiss = getTwiss([b.name for b in self.bpms],
                               ["s", "betax", "betay", "etax"])
        for i,bpm in enumerate(self.bpms):
            it = QTableWidgetItem(bpm.name)
            it.setFlags(it.flags() & (~Qt.ItemIsEditable))
            self.table.setItem(i, 0, it)

            it = QTableWidgetItem(str(bpm.sb))
            it.setFlags(it.flags() & (~Qt.ItemIsEditable))
            #it.setMinimumWidth(80)
            self.table.setItem(i, 1, it)
            self.table.setItem(i, 2,
                               QTableWidgetItem("%.4f" % self._twiss[i,1]))
            self.table.setItem(i, 3,
                               QTableWidgetItem("%.4f" % self._twiss[i,2]))
            self.table.setItem(i, 4,
                               QTableWidgetItem("%.4f" % self._twiss[i,3]))

            for j in range(5, 9):
                it = QTableWidgetItem(str(0.0))
                it.setData(Qt.DisplayRole, str(0.0))
                it.setFlags(it.flags() | Qt.ItemIsEditable)
                self.table.setItem(i, j, it)
            # use the current orbit
            #self.table.item(i,4).setData(Qt.DisplayRole, str(self.x0[i]))
            #self.table.item(i,5).setData(Qt.DisplayRole, str(self.y0[i]))

        #self.connect(self.table, SIGNAL("cellClicked(int, int)"),
        #             self._cell_clicked)
        self.table.resizeColumnsToContents()
        #self.table.horizontalHeader().setStretchLastSection(True)
        #for i in range(4):
        #    print "width", i, self.table.columnWidth(i)
        #self.table.setColumnWidth(0, 300)
        self.table.setColumnWidth(1, 80)

        vbox1 = QtGui.QVBoxLayout()
        frmbox = QFormLayout()
        self.base_orbit_box = QtGui.QComboBox()
        #self.base_orbit_box.addItems([
        #        "Current Orbit", "All Zeros"])
        self.base_orbit_box.addItems(["All Zeros", "Current Orbit"])
        frmbox.addRow("Orbit Base", self.base_orbit_box)
        grp = QtGui.QGroupBox("Local Bump")
        grp.setLayout(frmbox)
        vbox1.addWidget(grp)

        frmbox = QFormLayout()
        hln1 = QtGui.QFrame()
        hln1.setLineWidth(3)
        hln1.setFrameStyle(QtGui.QFrame.Sunken)
        hln1.setFrameShape(QtGui.QFrame.HLine)
        frmbox.addRow(hln1)
        self.repeatbox = QSpinBox()
        self.repeatbox.setRange(1, 20)
        self.repeatbox.setValue(3)
        # or connect the returnPressed() signal
        frmbox.addRow("&Repeat correction", self.repeatbox)

        self.rcondbox = QLineEdit()
        self.rcondbox.setValidator(QDoubleValidator(0, 1, 0, self))
        self.rcondbox.setText("1e-2")
        frmbox.addRow("r&cond for SVD", self.rcondbox)

        self.scalebox = QDoubleSpinBox()
        self.scalebox.setRange(0.01, 5.00)
        self.scalebox.setSingleStep(0.01)
        self.scalebox.setValue(0.68)
        frmbox.addRow("&Scale correctors", self.scalebox)

        #hln2 = QtGui.QFrame()
        #hln2.setLineWidth(3)
        #hln2.setFrameStyle(QtGui.QFrame.Sunken)
        #hln2.setFrameShape(QtGui.QFrame.HLine)
        #frmbox.addRow(hln2)

        self.progress = QProgressBar()
        self.progress.setMaximum(self.repeatbox.value())
        self.progress.setMaximumHeight(15)
        frmbox.addRow("Progress", self.progress)
        grp = QtGui.QGroupBox("Correction")
        grp.setLayout(frmbox)
        vbox1.addWidget(grp)

        #vbox.addStretch(1.0)
        #self.qdb = QDialogButtonBox(self)
        #self.qdb.addButton("APP", QDialogButtonBox.ApplyRole)
        #self.qdb.addButton("R", QDialogButtonBox.ResetRole)
        #btn.setDefault(True)
        #self.qdb.addButton(QDialogButtonBox.Cancel)
        #self.qdb.addButton(QDialogButtonBox.Help)

        gbox = QtGui.QGridLayout()
        btn = QPushButton("Clear")
        self.connect(btn, SIGNAL("clicked()"), self.resetBumps)
        gbox.addWidget(btn, 0, 1)
        self.correctOrbitBtn = QPushButton("Apply")
        #self.correctOrbitBtn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.correctOrbitBtn.setStyleSheet("QPushButton:disabled { color: gray }");
        self.connect(self.correctOrbitBtn, SIGNAL("clicked()"), self.call_apply)
        self.correctOrbitBtn.setDefault(True)
        gbox.addWidget(self.correctOrbitBtn, 1, 1)
        gbox.setColumnStretch(0, 1)

        vbox1.addStretch()
        vbox1.addLayout(gbox)

        hbox1 = QtGui.QHBoxLayout()
        hbox1.addWidget(self.table, 2)
        hbox1.addLayout(vbox1, 0)
        self.setLayout(hbox1)

        self.connect(self.base_orbit_box,
                     SIGNAL("currentIndexChanged(QString)"),
                     self.updateTargetOrbit)
        self.connect(self.repeatbox, SIGNAL("valueChanged(int)"),
                     self.progress.setMaximum)
        self.connect(self.table, SIGNAL("cellChanged (int, int)"),
                     self.updateBump)

        #self.updateTargetOrbit(self.base_orbit_box.currentText())

    def _update_current_orbit(self):
        pvx = [bpm.pv(field="x", handle="readback")[0] for bpm in self.bpms]
        pvy = [bpm.pv(field="y", handle="readback")[0] for bpm in self.bpms]
        self.x0 = [float(v) if v.ok else np.nan for v in catools.caget(pvx)]
        self.y0 = [float(v) if v.ok else np.nan for v in catools.caget(pvy)]

    def resetBumps(self):
        jx0, jy0 = 5, 6
        for i in range(self.table.rowCount()):
            self.table.item(i, jx0).setData(Qt.DisplayRole, str(0.0))
            self.table.item(i, jy0).setData(Qt.DisplayRole, str(0.0))
        #self.updateTargetOrbit(self.base_orbit_box.currentText())

    def call_apply(self):
        #print "apply the orbit"
        obt = []
        jx, jy = 7, 8
        for i in range(self.table.rowCount()):
            x1,err = self.table.item(i, jx).data(Qt.DisplayRole).toFloat()
            y1,err = self.table.item(i, jy).data(Qt.DisplayRole).toFloat()
            obt.append([x1, y1])

        self.correctOrbitBtn.setEnabled(False)
        nrepeat = self.repeatbox.value()
        kw = { "scale": float(self.scalebox.text()),
               "rcond": float(self.rcondbox.text()) }
        self.progress.setValue(0)
        QApplication.processEvents()
        for i in range(nrepeat):
            err, msg = setLocalBump(self.bpms, self.cors, obt, **kw)
            self.progress.setValue(i+1)
            QApplication.processEvents()
            if err != 0:
                QtGui.QMessageBox.critical(
                    self, "Local Orbit Bump",
                    "ERROR: {0}\nAbort.".format(msg),
                    QtGui.QMessageBox.Ok)
                #self.progress.setValue(0)
                break

        self.correctOrbitBtn.setEnabled(True)

    def getTargetOrbit(self):
        x = [self.table.item(i,7).data(Qt.DisplayRole).toFloat()[0]
             for i in range(self.table.rowCount())]
        y = [self.table.item(i,8).data(Qt.DisplayRole).toFloat()[0]
             for i in range(self.table.rowCount())]
        return (self.sb, x), (self.sb, y)

    def updateTargetOrbit(self, baseobt):
        if baseobt == "All Zeros":
            jx0, jx1 = 5, 7
            jy0, jy1 = 6, 8
            for i in range(self.table.rowCount()):
                it0 = self.table.item(i, jx0)
                it1 = self.table.item(i, jx1)
                it1.setData(Qt.DisplayRole, it0.data(Qt.DisplayRole))
                it0 = self.table.item(i, jy0)
                it1 = self.table.item(i, jy1)
                it1.setData(Qt.DisplayRole, it0.data(Qt.DisplayRole))
        elif baseobt == "Current Orbit":
            self._update_current_orbit()
            jx0, jx1 = 5, 7
            jy0, jy1 = 6, 8
            for i in range(self.table.rowCount()):
                dx0,err = self.table.item(i, jx0).data(Qt.DisplayRole).toFloat()
                it = self.table.item(i, jx1)
                it.setData(Qt.DisplayRole, self.x0[i] + dx0)

                dy0,err = self.table.item(i, jy0).data(Qt.DisplayRole).toFloat()
                it = self.table.item(i, jy1)
                it.setData(Qt.DisplayRole, self.y0[i] + dy0)
        #self._update_orbit_plot()
        x, y = self.getTargetOrbit()
        self.emit(SIGNAL("targetOrbitChanged(PyQt_PyObject, PyQt_PyObject)"),
                  x, y)

    def updateBump(self, row, col):
        #print "updating ", row, col
        if col == 5 or col == 6:
            self.updateTargetOrbit(self.base_orbit_box.currentText())
Beispiel #27
0
class FilesUIManager(QWidget):

    def __init__(self, winged, pref):
        QWidget.__init__(self)
        self.winged = winged
        self.pref = pref
        self._vbox = QVBoxLayout(self)
        self._hbox = QHBoxLayout()
        self._table = QTableWidget(1, 3)
        self._table.setHorizontalHeaderLabels(['Access', 'File Name', 'Size'])
        self._table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self._table.verticalHeader().hide()
        self._table.removeRow(0)
        self._table.setColumnWidth(0, 80)
        self._table.setColumnWidth(1, 480)
        self._hbox.addWidget(self._table)

        self._btnDownload = QPushButton(QIcon(config.images['download']), '')
        self._btnDownload.setToolTip('Download')
        self._btnFacebook = QPushButton(QIcon(config.images['facebook']), '')
        self._btnFacebook.setToolTip('Share on Facebook')
        self._btnTwitter = QPushButton(QIcon(config.images['twitter']), '')
        self._btnTwitter.setToolTip('Share on Twitter')
        self._btnLink = QPushButton(QIcon(config.images['link']), '')
        self._btnLink.setToolTip('Copy Link')
        self.connect(self._btnDownload, SIGNAL("clicked()"), self._save)
        self.connect(self._btnFacebook, SIGNAL("clicked()"), self._facebook)
        self.connect(self._btnTwitter, SIGNAL("clicked()"), self._twitter)
        self.connect(self._btnLink, SIGNAL("clicked()"), self._copy_link)

    def _save(self):
        file_ = self._files[self._table.currentRow()]
        if file_['accesibility'] == '2':
            if self.pref.get('ask', True):
                folderName = str(QFileDialog.getExistingDirectory(self, 'Save File in...'))
            else:
                folderName = self.pref.get('folder', '')
            if folderName != '':
                self.winged.save_file(file_, folderName)
        else:
            QMessageBox.information(self, 'Download Fail', 'You can only download public files\nwith WingedBox-Client.')

    def _facebook(self):
        file_ = self._files[self._table.currentRow()]
        self.winged.thread.api.facebook(file_)

    def _twitter(self):
        file_ = self._files[self._table.currentRow()]
        self.winged.thread.api.twitter(file_)

    def _copy_link(self):
        clipboard = QApplication.clipboard()
        file = self._files[self._table.currentRow()]
        clipboard.setText('http://wingedbox.com/downloads/' + file['id'] + "-" + file['file-name'])

    def find(self, text):
        items = self._table.findItems(text, Qt.MatchContains)
        rows = [i.row() for i in items]
        rowsCount = range(self._table.rowCount())
        rowsCount.reverse()
        for i in rowsCount:
            if i not in rows:
                self._table.removeRow(i)

    def load_table(self, files):
        self._files = files
        r = 0
        for file in files:
            self._table.insertRow(r)
            if len(file['name']) > 0:
                item = QTableWidgetItem(file['name'])
            else:
                item = QTableWidgetItem(file['file-name'])
            item.setFlags( Qt.ItemIsSelectable |  Qt.ItemIsEnabled )
            self._table.setItem(r, 1, item)
            item = QTableWidgetItem(str(file['file-size'] / 1024) + ' kb')
            item.setFlags( Qt.ItemIsSelectable |  Qt.ItemIsEnabled )
            self._table.setItem(r, 2, item)
            imageFile = config.type.get(file['type'], config.typeBlank)
            access = config.access[file['accesibility']]
            item = QTableWidgetItem(QIcon(imageFile), access[3])
            item.setBackgroundColor(QColor(access[0], access[1], access[2]))
            item.setFlags( Qt.ItemIsSelectable |  Qt.ItemIsEnabled )
            self._table.setItem(r, 0, item)
            r += 1
        self._table.resizeRowsToContents()
        self._table.resizeColumnsToContents()
        self._table.horizontalHeader().setStretchLastSection(True)
Beispiel #28
0
class CorrectorViewer(QtGui.QWidget):
    """
    List all corrector and select part to lower table
    """
    def __init__(self, cors, field, parent=None, nmax=4):
        super(CorrectorViewer, self).__init__(parent)
        self._nmax  = nmax
        self._field = field
        self._cors  = cors
        self._corlst1 = QtGui.QTreeWidget()
        self._header = dict([("Element", 0), ("Family", 1), ("s [m]", 2),
                             ("Alpha X", 3), ("Alpha Y", 4), ("Beta X", 5),
                             ("Beta Y", 6), ("Phi X", 7), ("Phi Y", 8),
                             ("Eta X", 9)])
        self._twiss = np.zeros((len(self._cors), 8), 'd')
        self._tunes = getTunes(source="database")
        self._corlst1.setColumnCount(len(self._header))
        self._corlst1.setHeaderLabels(
            sorted(self._header, key=self._header.get))
        self._corlst1.header().setStretchLastSection(False)
        prevcell = None
        for i,c in enumerate(self._cors):
            if c.cell and (prevcell is None or c.cell != prevcell.text(0)):
                # a new parent
                prevcell = QtGui.QTreeWidgetItem()
                prevcell.setText(0, c.cell)
                self._corlst1.addTopLevelItem(prevcell)
            it = QtGui.QTreeWidgetItem()
            it.setData(0, Qt.UserRole, i)
            it.setText(self._header["Element"], c.name)
            it.setText(self._header["Family"], c.family)
            it.setText(self._header["s [m]"], "%.3f" % c.sb)
            try:
                tw = getTwiss(c.name, 
                              ["s", "alphax", "alphay", "betax", "betay",
                               "phix", "phiy", "etax"])
                self._twiss[i,:] = tw[0,:]
                it.setText(self._header["Alpha X"], "%.4f" % self._twiss[i,1])
                it.setText(self._header["Alpha Y"], "%.4f" % self._twiss[i,2])
                it.setText(self._header["Beta X"],  "%.4f" % self._twiss[i,3])
                it.setText(self._header["Beta Y"],  "%.4f" % self._twiss[i,4])
                it.setText(self._header["Phi X"],   "%.4f" % self._twiss[i,5])
                it.setText(self._header["Phi Y"],   "%.4f" % self._twiss[i,6])
                it.setText(self._header["Eta X"],   "%.4f" % self._twiss[i,7])
            except:
                it.setDisabled(True)
                pass

            if c.cell:
                prevcell.addChild(it)
            else:
                self._corlst1.addTopLevelItem(it)
                prevcell = it
            for j in range(2, len(self._header)):
                it.setTextAlignment(j, Qt.AlignRight)
        self._corlst1.expandAll()
        for i in range(len(self._header)):
            self._corlst1.resizeColumnToContents(i)
        #self._corlst1.setColumnWidth(0, 150)

        #self.elemlst.setSelectionMode(QAbstractItemView.MultiSelection)
        columns = ['Corrector', 's', 'Alpha', 'Beta',
                   'Phi', "dPhi", "Initial Bump", "Cur. Sp", "dBump",
                   "Final Rb"]
        self.table4 = QTableWidget(0, len(columns))
        #self.table4.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        hdview = QHeaderView(Qt.Horizontal)
        self.table4.setHorizontalHeaderLabels(columns)
        #for i in range(4):
        #    for j in range(len(columns)):
        #        it = QTableWidgetItem()
        #        if j > 0: it.setTextAlignment(
        #            Qt.AlignRight | Qt.AlignVCenter)
        #        if columns[j] != "dKick":
        #            it.setFlags(it.flags() & (~Qt.ItemIsEditable))
        #        self.table4.setItem(i, j, it)
        #self.table4.resizeColumnsToContents()
        #self.table4.horizontalHeader().setStretchLastSection(True)
        #hrow = self.table4.rowHeight(0)
        #htbl = (hrow * 4) + self.table4.horizontalHeader().height() +\
        #    2*self.table4.frameWidth()
        #self.table4.setMinimumHeight(htbl + 10)
        #self.table4.setMaximumHeight(htbl + 15)
        #self.table4.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        #print "Size:", htbl + 10
        self.table4.resize(self.table4.width(), 150)

        splitter = QtGui.QSplitter(Qt.Vertical)
        splitter.addWidget(self._corlst1)
        splitter.addWidget(self.table4)
        vbox1 = QtGui.QVBoxLayout()
        vbox1.addWidget(splitter)
        self.setLayout(vbox1)

        self.connect(self._corlst1, SIGNAL("doubleClicked(QModelIndex)"),
                     self.addCorrector)
        #self.connect(self.src, SIGNAL("returnPressed()"),
        #             self._calc_source)
        #self.connect(self.table4, SIGNAL("cellChanged(int, int)"),
        #             self.updateTable)

        #self.connect(self.table4, SIGNAL("doubleClicked(QModelIndex)"),
        #             self.delCorrector)
        self._x0 = fget(self._cors, "x", handle="setpoint", unitsys=None)
        self._y0 = fget(self._cors, "y", handle="setpoint", unitsys=None)


    def addCorrector(self, idx):
        if not self._corlst1.selectedItems(): return
        #print self._corlst1.itemFromIndex(idx).text(0)
        nrow = self.table4.rowCount()
        if nrow >= self._nmax:
            QtGui.QMessageBox.critical(
                self, "Local Orbit Bump", 
                "ERROR: We need only {0} correctors.".format(self._nmax),
                QtGui.QMessageBox.Ok)
                #self.progress.setValue(0)
            return
        self.table4.setRowCount(nrow+1)
        it0 = self._corlst1.selectedItems()[-1]
        icor, ok = it0.data(0, Qt.UserRole).toInt()
        if icor < 0: return
        newc = self._cors[icor]
        for j in range(self.table4.columnCount()):
            it = QTableWidgetItem()
            if j > 0: it.setTextAlignment(
                Qt.AlignRight | Qt.AlignVCenter)
            header = self.table4.horizontalHeaderItem(j)
            if header.text() != "dBump":
                it.setFlags(it.flags() & (~Qt.ItemIsEditable))
            else:
                it.setData(Qt.DisplayRole, "0")
                it.setData(Qt.UserRole, 0.0)
            self.table4.setItem(nrow, j, it)
        self.table4.item(nrow,0).setData(Qt.UserRole, icor)
        for j,h in [(0, "Element"), (1, "s [m]")]:
            self.table4.item(nrow,j).setData(Qt.DisplayRole,
                                          it0.text(self._header[h]))
        for j in range(self._corlst1.columnCount()):
            it0.setForeground(j, Qt.red)
        it0.setDisabled(True)
        self.emit(SIGNAL("correctorAdded(PyQt_PyObject)"), newc)
        # use initial values

        self.updateTwiss()
        self.updateCorReadings()
        self.table4.resizeColumnsToContents()
        if self.table4.rowCount() == self._nmax:
            #print "All correctors are ready"
            self.emit(SIGNAL("correctorsComplete()"))

    def updateTwiss(self):
        if self._field == "x":
            jl = [self._header[h] for h in ["Alpha X", "Beta X", "Phi X"]]
            nu = self._tunes[0]
        elif self._field == "y":
            jl = [self._header[h] for h in ["Alpha Y", "Beta Y", "Phi Y"]]
            nu = self._tunes[1]
        else:
            raise RuntimeError("unknown cor field {0}".format(self._field))
        #print "index:", jl
        # if rows provided use it, otherwise use all
        for i in range(self.table4.rowCount()):
            elemname = self.table4.item(i,0).data(Qt.DisplayRole).toString()
            it0 = self._corlst1.findItems(
                elemname, Qt.MatchExactly | Qt.MatchRecursive)[0]
            
            self.table4.item(i,2).setText(it0.text(jl[0]))
            self.table4.item(i,3).setText(it0.text(jl[1]))
            self.table4.item(i,4).setText(it0.text(jl[2]))
            self.table4.item(i,4).setData(Qt.UserRole, float(it0.text(jl[2])))

            if i == 0:
                self.table4.item(i,5).setText("0.0")
                self.table4.item(i,5).setData(Qt.UserRole, 0.0)
            else:
                dph, ok = self.table4.item(i-1,5).data(Qt.UserRole).toFloat()
                ph0, ok = self.table4.item(i-1,4).data(Qt.UserRole).toFloat()
                ph1, ok = self.table4.item(i,4).data(Qt.UserRole).toFloat()
                dph = dph + ph1 - ph0
                if ph1 < ph0:
                    dph = dph + 2.0*np.pi*nu
                #print "Updating twiss:", i, dph
                self.table4.item(i,5).setData(Qt.UserRole, dph)
                self.table4.item(i,5).setText("%.5g" % dph)
            icor, ok = self.table4.item(i,0).data(Qt.UserRole).toInt()
            #c = self._cors[icor]
            #kick = self._cors[icor].get(self._field, unitsys=None)
            #self.table4.item(i,6).setData(Qt.UserRole, kick)
            #self.table4.item(i,6).setText("%.5g" % kick)
        #self.updateKickReadings(col=0)

    def clear(self):
        for i in range(self.table4.rowCount()):
            elemname = self.table4.item(i,0).data(Qt.DisplayRole).toString()
            it0 = self._corlst1.findItems(
                elemname, Qt.MatchExactly | Qt.MatchRecursive)[0]
            it0.setDisabled(False)
            for j in range(self._corlst1.columnCount()):
                it0.setForeground(j, Qt.black)
        self.table4.setRowCount(0)
    
    def updateCorReadings(self):
        for i in range(self.table4.rowCount()):
            icor, ok = self.table4.item(i,0).data(Qt.UserRole).toInt()
            cor = self._cors[icor]
            if self._field == "x":
                self.table4.item(i,6).setData(Qt.UserRole, self._x0[icor])
                self.table4.item(i,6).setText("%.5g" % self._x0[icor])
            elif self._field == "y":
                self.table4.item(i,6).setData(Qt.UserRole, self._y0[icor])
                self.table4.item(i,6).setText("%.5g" % self._y0[icor])
            kicksp = cor.get(self._field, handle="setpoint", unitsys=None)
            self.table4.item(i,7).setData(Qt.UserRole, float(kicksp))
            self.table4.item(i,7).setText("%.5g" % kicksp)
            kickrb = cor.get(self._field, handle="readback", unitsys=None)
            self.table4.item(i,9).setData(Qt.UserRole, float(kickrb))
            self.table4.item(i,9).setText("%.5g" % kickrb)


    def updateDbump(self, dkick):
        nrow = min(self.table4.rowCount(), len(dkick))
        for i in range(nrow):
            # dbump column is 8
            it = self.table4.item(i, 8)
            if dkick[i] is None:
                it.setData(Qt.DisplayRole, "")
                it.setData(Qt.UserRole, 0.0)
            else:
                it.setData(Qt.UserRole, float(dkick[i]))
                it.setData(Qt.DisplayRole, "{0}".format(dkick[i]))
        self.updateCorReadings()
        self.table4.resizeColumnsToContents()
        #print "(0,7)", self.table4.item(0, 7).data(Qt.UserRole).toFloat()
        #print "(0,7)", self.table4.item(0, 7).data(Qt.DisplayRole).toFloat()

    def applyKick(self):
        nrow = self.table4.rowCount()
        for i in range(nrow):
            icor, ok = self.table4.item(i,0).data(Qt.UserRole).toInt()
            cor = self._cors[icor]
            # Current SP: 7, dBump 8
            k0, ok = self.table4.item(i, 7).data(Qt.UserRole).toFloat()
            dk, ok = self.table4.item(i, 8).data(Qt.UserRole).toFloat()
            #print "Setting {0} {1}+{2} [A]".format(cor.name, k0, dk)
            cor.put(self._field, k0+dk, unitsys=None)

        # update the final readings
        self.updateCorReadings()

    def getTwiss(self):
        tw = {"s": [], "Alpha": [], "Beta": [],
              "Phi": [], "dPhi": []}
        nrow = self.table4.rowCount()
        for j in range(self.table4.columnCount()):
            header = self.table4.horizontalHeaderItem(j)
            if header.text() not in tw.keys():
                continue
            k = str(header.text())
            for i in range(nrow):
                it = self.table4.item(i, j)
                v0, ok0 = it.data(Qt.UserRole).toFloat()
                v1, ok1 = it.data(Qt.DisplayRole).toFloat()
                if ok0:
                    tw[k].append(v0)
                elif ok1:
                    tw[k].append(v1)
                else:
                    tw[k].append(np.nan)
        return tw

    def selectedCorrectors(self):
        ret = []
        for i in range(self.table4.rowCount()):
            icor, ok = self.table4.item(i,0).data(Qt.UserRole).toInt()
            ret.append(self._cors[icor])
        return ret

    def resetCorrectors(self):
        for i in range(self.table4.rowCount()):
            icor, ok = self.table4.item(i,0).data(Qt.UserRole).toInt()
            cor = self._cors[icor]
            if self._field == "x":
                kick = self._x0[icor]
            elif self._field == "y":
                kick = self._y0[icor]
            cor.put(self._field, kick, unitsys=None)
Beispiel #29
0
    def view(self):
        """create view and import layers"""
        layer = QgsMapLayerRegistry.instance().mapLayer(
                self.current_layers[0] )
        uri = QgsDataSourceURI(layer.source())
        mtch = re.match(r'(.+)_([^_]+)_rev_(head|\d+)', uri.schema())
        schema = mtch.group(1)
        assert(schema)
        dlg = QDialog()
        layout = QVBoxLayout(dlg)
        button_box = QDialogButtonBox(dlg)
        button_box.setStandardButtons(
                QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
        button_box.accepted.connect(dlg.accept)
        button_box.rejected.connect(dlg.reject)

        user_msg1 = QgsMessageBar(dlg)
        user_msg1.pushInfo("Select:", "one [many] for single [multiple] "
        "revisions.  Fetching may take time.")

        pcur = versioning_base.Db( psycopg2.connect(self.pg_conn_info()) )
        pcur.execute("SELECT rev, commit_msg, branch, date, author "
            "FROM "+schema+".revisions")
        revs = pcur.fetchall()
        pcur.close()
        tblw = QTableWidget( dlg )
        tblw.setRowCount(len(revs))
        tblw.setColumnCount(6)
        tblw.setSortingEnabled(True)
        tblw.setHorizontalHeaderLabels(['Select','Revision', 'Commit Message',
                                      'Branch', 'Date', 'Author'])
        tblw.verticalHeader().setVisible(False)
        for i, rev in enumerate(revs):
            for j, item in enumerate(rev):
                chkBoxItem = QTableWidgetItem()
                chkBoxItem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                chkBoxItem.setCheckState(Qt.Unchecked)
                tblw.setItem(i, 0, chkBoxItem)
                tblw.setItem(i, j+1, QTableWidgetItem( str(item) ))

        layout.addWidget( user_msg1 )
        layout.addWidget( tblw )
        layout.addWidget( button_box )
        dlg.resize( 650, 300 )
        if not dlg.exec_() :
            return

        rows = set()
        revision_number_list = []
        for i in range(len(revs)):
            if  tblw.item(i,0).checkState():
                print "Revision "+ str(i + 1) +" will be fetched"
                revision_number_list.append(i + 1)
                rows.add(tblw.item(i,0).row())

        progressMessageBar = self.iface.messageBar().createMessage("Querying "
        "the database for revision(s) "+str(revision_number_list))
        progress = QProgressBar()
        progress.setMaximum(len(rows))
        progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter)
        progressMessageBar.layout().addWidget(progress)
        self.iface.messageBar().pushWidget(progressMessageBar, self.iface.messageBar().INFO)
        progress.setValue(0)

        for i, row in enumerate(rows):
            progress.setValue(i+1)
            branch = revs[row][2]
            rev = revs[row][0]
            versioning_base.add_revision_view(uri.connectionInfo(),
                    schema, branch, rev )
            grp_name = branch+' revision '+str(rev)
            grp_idx = self.iface.legendInterface().addGroup( grp_name )
            for layer_id in reversed(self.current_layers):
                layer = QgsMapLayerRegistry.instance().mapLayer(layer_id)
                new_uri = QgsDataSourceURI(layer.source())
                new_uri.setDataSource(schema+'_'+branch+'_rev_'+str(rev),
                        new_uri.table(),
                        new_uri.geometryColumn(),
                        new_uri.sql(),
                        new_uri.keyColumn())
                display_name =  QgsMapLayerRegistry.instance().mapLayer(layer_id).name()
                src = new_uri.uri().replace('()','')
                new_layer = self.iface.addVectorLayer( src,
                        display_name, 'postgres')
                self.iface.legendInterface().moveLayer( new_layer, grp_idx)
        self.iface.messageBar().clearWidgets()
Beispiel #30
0
class UpdateDialog(QDialog):

    def __init__(self, update_script):
        super(UpdateDialog, self).__init__(None, Qt.Window)
        self.updates_to_run = []
        self.setWindowTitle("emzed updates")
        self.setWindowModality(Qt.WindowModal)
        self.setMinimumWidth(600)
        self.update_script = update_script
        self.setup_widgets()
        self.setup_layout()
        self.connect_signals()

        wd = QApplication.desktop().width()
        hd = QApplication.desktop().height()
        w = self.size().width()
        h = self.size().height()
        self.move((wd - w) / 2, (hd - h) / 2)

    def showEvent(self, evt):

        self.setCursor(Qt.WaitCursor)

        class WorkerThread(QThread):

            def run(self, script=self.update_script, parent=self):
                try:
                    for method, args in script(parent.add_info_line, parent.add_update_info):
                        self.emit(SIGNAL("execute_method(PyQt_PyObject, PyQt_PyObject)"), method, args)
                except:
                    import traceback
                    tb = traceback.format_exc()
                    self.emit(SIGNAL("execute_method(PyQt_PyObject, PyQt_PyObject)"), parent.add_info_line, (tb,))
                self.emit(SIGNAL("update_query_finished()"))


        self.t = WorkerThread()
        self.connect(self.t, SIGNAL("update_query_finished()"), self.start_to_interact)
        self.connect(
            self.t, SIGNAL("execute_method(PyQt_PyObject,PyQt_PyObject)"), self.execute_method)

        try:
            self.t.start()
        finally:
            self.setCursor(Qt.ArrowCursor)

    def execute_method(self, meth, args):
        meth(*args)

    def start_to_interact(self):
        self.ok_button.setEnabled(True)

    def setup_widgets(self):
        self.label_info = QLabel("updates from exchange folder:")
        self.info = QTextEdit(self)
        self.info.setReadOnly(1)

        self.label_updates = QLabel("updates from internet:")
        self.updates = QTableWidget(0, 3)
        self.updates.setHorizontalHeaderLabels(["updater", "info", "try updatde ?"])
        self.updates.verticalHeader().hide()
        self.updates.horizontalHeader().setResizeMode(0, QHeaderView.Stretch)
        self.updates.horizontalHeader().setResizeMode(1, QHeaderView.Stretch)

        self.ok_button = QPushButton("OK")
        self.ok_button.setEnabled(False)

    def setup_layout(self):
        layout = QVBoxLayout()
        self.setLayout(layout)
        layout.addWidget(self.label_info)
        layout.addWidget(self.info)
        layout.addWidget(self.label_updates)
        layout.addWidget(self.updates)
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        button_layout.addWidget(self.ok_button)
        layout.addLayout(button_layout)

    def connect_signals(self):
        self.connect(self.ok_button, SIGNAL("pressed()"), self.accept)

    def ok_button_pressed(self):
        self.info.append("hi")
        self.add_update_info("updater", "info")

    def _item(self, content, is_checkable):
        item = QTableWidgetItem(str(content))
        if is_checkable:
            item.setCheckState(Qt.Unchecked)
        item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable)
        return item

    def add_update_info(self, updater_id, info, with_checkbox=True):
        i = self.updates.rowCount()
        self.updates.insertRow(i)
        self.updates.setItem(i, 0, self._item(updater_id, False))
        self.updates.setItem(i, 1, self._item(info, False))
        if True or with_checkbox:
            self.updates.setItem(i, 2, self._item("", True))

    def add_info_line(self, txt):
        self.info.append(txt)

    def get_updates_to_run(self):
        return self.updates_to_run

    def accept(self):
        for i in range(self.updates.rowCount()):
            updater_id = str(self.updates.item(i, 0).text())
            item = self.updates.item(i, 2)
            if item is not None:  # some cells in column are empty
                checked = self.updates.item(i, 2).checkState() == Qt.Checked
                if checked:
                    self.updates_to_run.append(updater_id)
        super(UpdateDialog, self).accept()
Beispiel #31
0
class UpdateDialog(QDialog):

    def __init__(self, update_script):
        super(UpdateDialog, self).__init__(None, Qt.Window)
        self.updates_to_run = []
        self.setWindowTitle("emzed updates")
        self.setWindowModality(Qt.WindowModal)
        self.setMinimumWidth(600)
        self.update_script = update_script
        self.setup_widgets()
        self.setup_layout()
        self.connect_signals()

        wd = QApplication.desktop().width()
        hd = QApplication.desktop().height()
        w = self.size().width()
        h = self.size().height()
        self.move((wd - w) / 2, (hd - h) / 2)

    def showEvent(self, evt):

        self.setCursor(Qt.WaitCursor)

        class WorkerThread(QThread):

            def run(self, script=self.update_script, parent=self):
                try:
                    for method, args in script(parent.add_info_line, parent.add_update_info):
                        self.emit(SIGNAL("execute_method(PyQt_PyObject, PyQt_PyObject)"), method, args)
                except:
                    import traceback
                    tb = traceback.format_exc()
                    self.emit(SIGNAL("execute_method(PyQt_PyObject, PyQt_PyObject)"), parent.add_info_line, (tb,))
                self.emit(SIGNAL("update_query_finished()"))


        self.t = WorkerThread()
        self.connect(self.t, SIGNAL("update_query_finished()"), self.start_to_interact)
        self.connect(
            self.t, SIGNAL("execute_method(PyQt_PyObject,PyQt_PyObject)"), self.execute_method)

        try:
            self.t.start()
        finally:
            self.setCursor(Qt.ArrowCursor)

    def execute_method(self, meth, args):
        meth(*args)

    def start_to_interact(self):
        self.ok_button.setEnabled(True)

    def setup_widgets(self):
        self.label_info = QLabel("updates from exchange folder:")
        self.info = QTextEdit(self)
        self.info.setReadOnly(1)

        self.label_updates = QLabel("updates from internet:")
        self.updates = QTableWidget(0, 3)
        self.updates.setHorizontalHeaderLabels(["updater", "info", "try updatde ?"])
        self.updates.verticalHeader().hide()
        self.updates.horizontalHeader().setResizeMode(0, QHeaderView.Stretch)
        self.updates.horizontalHeader().setResizeMode(1, QHeaderView.Stretch)

        self.ok_button = QPushButton("OK")
        self.ok_button.setEnabled(False)

    def setup_layout(self):
        layout = QVBoxLayout()
        self.setLayout(layout)
        layout.addWidget(self.label_info)
        layout.addWidget(self.info)
        layout.addWidget(self.label_updates)
        layout.addWidget(self.updates)
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        button_layout.addWidget(self.ok_button)
        layout.addLayout(button_layout)

    def connect_signals(self):
        self.connect(self.ok_button, SIGNAL("pressed()"), self.accept)

    def ok_button_pressed(self):
        self.info.append("hi")
        self.add_update_info("updater", "info")

    def _item(self, content, is_checkable):
        item = QTableWidgetItem(content)
        if is_checkable:
            item.setCheckState(Qt.Unchecked)
        item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable)
        return item

    def add_update_info(self, updater_id, info, with_checkbox=True):
        i = self.updates.rowCount()
        self.updates.insertRow(i)
        self.updates.setItem(i, 0, self._item(updater_id, False))
        self.updates.setItem(i, 1, self._item(info, False))
        if True or with_checkbox:
            self.updates.setItem(i, 2, self._item("", True))

    def add_info_line(self, txt):
        self.info.append(txt)

    def get_updates_to_run(self):
        return self.updates_to_run

    def accept(self):
        for i in range(self.updates.rowCount()):
            updater_id = str(self.updates.item(i, 0).text())
            item = self.updates.item(i, 2)
            if item is not None:  # some cells in column are empty
                checked = self.updates.item(i, 2).checkState() == Qt.Checked
                if checked:
                    self.updates_to_run.append(updater_id)
        super(UpdateDialog, self).accept()
    def _init_layout(self):
        """
        Create the GUI widgets (but leave them empty).
        """
        hostname_combobox = QComboBox(parent=self)
        self._hostname_combobox = hostname_combobox
        hostname_combobox.setEditable(True)
        hostname_combobox.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Maximum )
        for hostname in self._suggested_hostnames:
            hostname_combobox.addItem( hostname )

        # EventFilter is installed after everything else is initialized. (See below.)
        #hostname_combobox.installEventFilter(self)

        self._connect_button = QPushButton("Connect", parent=self, clicked=self._handle_new_hostname)

        hostname_layout = QHBoxLayout()
        hostname_layout.addWidget( hostname_combobox )
        hostname_layout.addWidget( self._connect_button )

        hostinfo_table = QTableWidget()
        hostinfo_table.setColumnCount(len(SERVER_INFO_FIELDS))
        hostinfo_table.setHorizontalHeaderLabels(SERVER_INFO_FIELDS)
        hostinfo_table.horizontalHeader().setVisible(True)
        hostinfo_table.verticalHeader().setVisible(False)
        hostinfo_table.setRowCount(1)
        hostinfo_table.setItem(0,0, QTableWidgetItem("Placeholder"))
        hostinfo_table.setVisible(False)
        hostinfo_table.resizeRowsToContents()
        hostinfo_table.horizontalHeader().setStretchLastSection(True)
        table_height = hostinfo_table.verticalHeader().sectionSize(0) + hostinfo_table.rowHeight(0)
        hostinfo_table.resize( QSize( hostinfo_table.width(), table_height ) )
        hostinfo_table.setMaximumSize( QSize( 1000, table_height ) )
        hostinfo_table.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)

        host_layout = QVBoxLayout()
        host_layout.addLayout(hostname_layout)
        host_layout.addWidget(hostinfo_table)

        host_groupbox = QGroupBox("DVID Host", parent=self)
        host_groupbox.setLayout( host_layout )
        host_groupbox.setSizePolicy( QSizePolicy.Preferred, QSizePolicy.Preferred )
        
        repo_treewidget = QTreeWidget(parent=self)
        repo_treewidget.setHeaderLabels( TREEVIEW_COLUMNS ) # TODO: Add type, shape, axes, etc.
        repo_treewidget.setSizePolicy( QSizePolicy.Preferred, QSizePolicy.Preferred )
        repo_treewidget.itemSelectionChanged.connect( self._handle_data_selection )

        data_layout = QVBoxLayout()
        data_layout.addWidget( repo_treewidget )
        data_groupbox = QGroupBox("Data Volumes", parent=self)
        data_groupbox.setLayout( data_layout )
        
        node_listwidget = QListWidget(parent=self)
        node_listwidget.setSizePolicy( QSizePolicy.Preferred, QSizePolicy.Preferred )
        node_listwidget.itemSelectionChanged.connect( self._update_status )

        node_layout = QVBoxLayout()
        node_layout.addWidget( node_listwidget )
        node_groupbox = QGroupBox("Nodes", parent=self)
        node_groupbox.setLayout( node_layout )

        new_data_edit = QLineEdit(parent=self)
        new_data_edit.textEdited.connect( self._update_status )
        full_url_label = QLabel(parent=self)
        full_url_label.setSizePolicy( QSizePolicy.Preferred, QSizePolicy.Maximum )
        text_flags = full_url_label.textInteractionFlags()
        full_url_label.setTextInteractionFlags( text_flags | Qt.TextSelectableByMouse )

        new_data_layout = QVBoxLayout()
        new_data_layout.addWidget( new_data_edit )
        new_data_groupbox = QGroupBox("New Data Volume", parent=self)
        new_data_groupbox.setLayout( new_data_layout )
        new_data_groupbox.setSizePolicy( QSizePolicy.Preferred, QSizePolicy.Maximum )

        buttonbox = QDialogButtonBox( Qt.Horizontal, parent=self )
        buttonbox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Cancel )
        buttonbox.accepted.connect( self.accept )
        buttonbox.rejected.connect( self.reject )
        buttonbox.button(QDialogButtonBox.Ok).setEnabled(False)

        layout = QVBoxLayout()
        layout.addWidget( host_groupbox )
        layout.addWidget( data_groupbox )
        layout.addWidget( node_groupbox )
        if self._mode == "specify_new":
            layout.addWidget( new_data_groupbox )
        else:
            new_data_groupbox.hide()
        layout.addWidget( full_url_label )
        layout.addWidget( buttonbox )

        # Stretch factors
        layout.setStretchFactor(data_groupbox, 3)
        layout.setStretchFactor(node_groupbox, 1)
        
        self.setLayout(layout)
        self.setWindowTitle( "Select DVID Volume" )
        self.resize(1000, 1000)

        # Initially disabled
        data_groupbox.setEnabled(False)
        node_groupbox.setEnabled(False)
        new_data_groupbox.setEnabled(False)
        
        # Set tab order
        self.setTabOrder(hostname_combobox, repo_treewidget)
        self.setTabOrder(repo_treewidget, node_listwidget)
        self.setTabOrder(node_listwidget, buttonbox)

        # Save instance members
        self._hostinfo_table = hostinfo_table
        self._data_groupbox = data_groupbox
        self._node_groupbox = node_groupbox
        self._new_data_groupbox = new_data_groupbox
        self._repo_treewidget = repo_treewidget
        self._node_listwidget = node_listwidget
        self._new_data_edit = new_data_edit
        self._full_url_label = full_url_label
        self._buttonbox = buttonbox

        # Finally install eventfilter (after everything is initialized)
        hostname_combobox.installEventFilter(self)
class VerifySetpoint(QDialog):
    def __init__(self, configFile, rowCount, verifyWindowDict, parent=None):
        super(VerifySetpoint, self).__init__(parent, Qt.CustomizeWindowHint|Qt.WindowTitleHint)
        self.configFile = configFile
        self.rowCount = rowCount
        self.verifyWindowDict = verifyWindowDict
        self.setWindowTitle('%s: setpoint v.s. readback'%self.configFile.split('/')[-1])  
        resolution = QDesktopWidget().screenGeometry()
        #self.setGeometry(resolution.width(), resolution.height() ,250, 150)
        self.setGeometry(resolution.width(),0, 250, 150)
        self.startUpdate = 1   
        self.keys = []       
        
        fd = open(self.configFile)
        lines = fd.readlines()
        #print(lines)
        setpointPVList = []
        readbackPVList = []
        self.allPVList = []
        #thresholdList = []
        rampRatePVList = []
        for line in lines:
            #print(line.split())
            setpointPVList.append(str(line.split()[0]))
            readbackPVList.append(str(line.split()[1]))
            if len(line.split())>2:
                #thresholdList.append(str(line.split()[2]))
                rampRatePVList.append(str(line.split()[2]))
        self.allPVList = setpointPVList + readbackPVList + rampRatePVList
        self.pvListColumn = 3
        #print(setpointPVList)
        #print(readbackPVList)
        #print(self.allPVList)
        #print(thresholdList) 
        #print(rampRatePVList)      
        
        layout = QGridLayout(self)  
        self.label = QLabel()
        if self.rowCount > len(readbackPVList):
            self.label.setText("%d PVs in the original snapshot, but only %d pairs of setpoint &\
readback PVs in this table because some setpoint PVs don't have readbacks\n\nPlease click the \
button below to update data\n"%(self.rowCount,len(readbackPVList)))   
        else:
            self.label.setText("%d pairs of setpoint & readback PVs in this table\n\n \
Please click the button below to update data\n"%(len(readbackPVList)))             
        layout.addWidget(self.label, 0, 0, 1, 2)
         
        self.table = QTableWidget()
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.table.sizePolicy().hasHeightForWidth())
        self.table.setSizePolicy(sizePolicy)
        self.table.setMinimumSize(QSize(700, 500))
        self.table.resize(self.table.sizeHint())
        
        self.table.setRowCount(len(setpointPVList))
        #if len(thresholdList):
        if len(rampRatePVList):
            #self.keys = ['setpoint PV','readback PV','SP value','RB value','diff', 'threshold']
            self.keys = ['setpoint PV','readback PV','SP value (Amp)','RB value (Amp)','diff', 'ramp-rate (Amp/Sec)']
        else:
            self.keys = ['setpoint PV','readback PV','SP value','RB value','diff']
        
        self.table.setColumnCount(len(self.keys))
        self.table.setHorizontalHeaderLabels(self.keys)             
        layout.addWidget(self.table, 1, 0, 1, 2)    

        #=======================================================================
        # toggleButton = QPushButton('Updating started', self)
        # toggleButton.clicked.connect(self.toggle)
        # layout.addWidget(toggleButton, 2, 0, 1, 1)
        #=======================================================================
        
        updateButton = QPushButton('Update Table', self)
        updateButton.clicked.connect(self.updateTable)
        layout.addWidget(updateButton, 2, 0, 1, 1)
        
        self.quit = QPushButton('Close Widget', self)
        #self.connect(self.quit, SIGNAL('clicked()'), self.close)
        #self.destroyed.connect(self.cleanup())
        #self.deleteLater.connect(self.cleanup())
        self.connect(self.quit, SIGNAL('clicked()'), self.cleanup)
        layout.addWidget(self.quit, 2, 1, 1, 1)
        self.setLayout(layout)    
        #self.timer = cothread.Timer(2, self.updateTable, retrigger=True, reuse=True)
        self.updateTable()
        #camonitor(self.allPVList, self.callback)
        #t = threading.Timer(2, self.updateTable)
        #t.start()  
    
    #===========================================================================
    # def toggle(self):
    #    source = self.sender()
    #    if self.startUpdate:
    #        source.setText("Updating stopped")
    #        self.startUpdate = 0
    #    else:
    #        source.setText("Updating started")
    #        self.startUpdate = 1
    #    print(self.startUpdate)    
    #===========================================================================
            
 
    def __setTableItem(self, table, row, col, text):
        item = table.item(row, col)
        if item:
            item.setText(text)
        else:
            newitem = QTableWidgetItem(text)
            newitem.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable)
            table.setItem(row, col, newitem)    
        
    #def updateTable(self):
        #camonitor(self.allPVList, self.callback)
        #cothread.WaitForQuit()
       
    def updateTable(self):
    #def callback(self, value, index):
        #while(True):
            #if self.startUpdate: 
        disConnectedPVs = []
        connectedPVs = []
        self.table.clear()
        self.table.setHorizontalHeaderLabels(self.keys) 
        self.table.setSortingEnabled(False)
        #print("update table:")
        #print(self.allPVList)
        #cothread.Sleep(2)
        connnectionStatus = connect(self.allPVList, cainfo=True, wait=False, timeout=2, throw=False)
        for status in connnectionStatus:
            if status.ok != True:
                disConnectedPVs.append(status.name)
            else:
                connectedPVs.append(status.name)
        
        if len(disConnectedPVs) > 0:
            print("%d PVs seem disconnected: \n"%len(disConnectedPVs))
            print(disConnectedPVs)
            self.label.setText("%d PVs in the original snapshot, but only %d pairs of setpoint &\
readback in this table because some PVs don't have readbacks or they are disconnected\n\nPlease click the \
button below to update data\n"%(self.rowCount,len(connectedPVs)))
            self.allPVList = connectedPVs
        
        try:
            pvValues = caget(self.allPVList)
        except:
            print("Oops: can't get PV values to verify setpoint and readback")
            self.label.setText("Oops: can't get PV values to verify setpoint and readback\n\n")
            traceback.print_exc()
            return
        #print(pvValues)
        
        for i in range(int(len(self.allPVList)/self.pvListColumn)):
            self.__setTableItem(self.table, i, 0, str(self.allPVList[i]))#setpoint PV name
            self.__setTableItem(self.table, i, 1, str(self.allPVList[i+int(len(self.allPVList)/self.pvListColumn)]))
            self.__setTableItem(self.table, i, 2, str(pvValues[i]))
            self.__setTableItem(self.table, i, 3, str(pvValues[i+int(len(self.allPVList)/self.pvListColumn)]))
            diff_ = abs(pvValues[i] - pvValues[i+int(len(self.allPVList)/self.pvListColumn)])
            diff = diff_.__format__('.9f')
            self.__setTableItem(self.table, i, 4, str(diff))
            self.__setTableItem(self.table, i, 5, str(pvValues[i+int((self.pvListColumn-1)*len(self.allPVList)/self.pvListColumn)]))
    
        #self.table.resize(self.table.sizeHint())
        self.table.setSortingEnabled(True)
        self.table.sortItems(4,1)
        self.table.resizeColumnsToContents()
        #print("end of update table:")
        #return 2
        #self.timer.reset(2, retrigger=True)
                #time.sleep(2)
    def cleanup(self):
        del self.verifyWindowDict[self.configFile]#closed verifyWindow can be opened again
        self.close()
        
Beispiel #34
0
 def process(self, node):
   for idx in xrange(0, self.tabs.count()):
     widget = self.tabs.widget(idx)
     del widget
   self.tabs.clear()
   self.node = node
   file = self.node.open()
   tags = EXIF.process_file(file)
   if len(tags) == 0:
     self.nometa.setSizePolicy(self.tabs.sizePolicy())
     self.tabs.hide()
     self.nometa.show()
   else:
     self.tabs.show()
     self.nometa.hide()
     sortedTags = {}
     for tag in tags.keys():
       if tag not in ('JPEGThumbnail', 'TIFFThumbnail', 'Filename', 'EXIF MakerNote'):
         spaceidx = tag.find(" ")
         ifd = tag[:spaceidx].strip()
         if ifd == "Image":
           ifd = "IFD 0 (Image)"
         if ifd == "Thumbnail":
           ifd = "IFD 1 (Thumbnail)"
         key = tag[spaceidx:].strip()
         try:
           val = str(tags[tag])
         except:
           val = "cannot be decoded"
         if ifd not in sortedTags.keys():
           sortedTags[ifd] = []
         sortedTags[ifd].append((key, val))
     for ifd in sortedTags.keys():
       table = QTableWidget(len(sortedTags[ifd]), 2)
       table.setShowGrid(False)
       table.setAlternatingRowColors(True)
       table.verticalHeader().hide()
       table.horizontalHeader().setClickable(False)
       table.horizontalHeader().setStretchLastSection(True)
       table.setHorizontalHeaderLabels(["Tag", "Value"])
       table.setSelectionBehavior(QAbstractItemView.SelectRows)
       self.tabs.addTab(table, ifd)
       row = 0
       for res in sortedTags[ifd]:
         key = QTableWidgetItem(res[0])
         key.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)
         val = QTableWidgetItem(res[1])
         val.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)
         table.setItem(row, 0, key)
         table.setItem(row, 1, val)
         row += 1
     if 'JPEGThumbnail' in tags.keys():
       label = QLabel()
       img = QImage()
       img.loadFromData(tags['JPEGThumbnail'])
       label.setPixmap(QPixmap.fromImage(img))
       label.setAlignment(Qt.AlignCenter)
       self.tabs.addTab(label, "Embedded Thumbnail")
     if 'TIFFThumbnail' in tags.keys():
       label = QLabel()
       img = QImage()
       img.loadFromData(tags['TIFFThumbnail'])
       label.setPixmap(QPixmap.fromImage(img))
       label.setAlignment(Qt.AlignCenter)
       self.tabs.addTab(label, "Embedded Thumbnail")
     file.close()	
Beispiel #35
0
    def setupTabs(self):
        #self.tabs.currentChanged.disconnect(self.currentTabChanged)
        while(self.tabs.count() > 0):
            self.tabs.removeTab(0)

        self.tables = {}
        allcounters = Counter.findAll()
        for c in allcounters:
            tab = QWidget(self.tabs)
            hl = QHBoxLayout()
            tab.setLayout(hl)
            
            recordings = Recording.findByIdCounter(c.id)

            tw = QTableWidget(len(recordings), 5)
            self.tables["%i"%c.id] = tw
            column_names = ("Id","Counter", "Date", "Value", "Remove ?")
            tw.setHorizontalHeaderLabels(column_names)

            # Fill the table with the recordings
            for i, r in enumerate(recordings):
                # The id of the recording in the table of recordings
                item = QTableWidgetItem("{}".format(r.id))
                item.setFlags(QtCore.Qt.NoItemFlags)
                tw.setItem (i, 0, item)
                
                # The id of the associated counter
                item = QTableWidgetItem("{}".format(r.idcounter))
                item.setFlags(QtCore.Qt.NoItemFlags)
                tw.setItem (i, 1, item)

                # The date when the recording has been made
                item = QTableWidgetItem(r.date.strftime("%Y-%m-%d %H:%M:%S"))
                item.setFlags(QtCore.Qt.NoItemFlags)
                tw.setItem (i, 2, item)

                # The value can be edited
                item = QTableWidgetItem("{}".format(r.value))
                item.setFlags(QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled)

                tw.setItem (i, 3, item)

                but = QPushButton("Remove")
                but.clicked.connect(partial(self.on_removeClicked, counter_id=c.id, recording_id=r.id))
                #item = QTableWidgetItem(but)
                #tw.setItem(i, 4, but)
                #tw.setIndexWidget()
                tw.setCellWidget(i, 4, but)

            tw.cellChanged.connect(partial(self.on_cellChanged, counter_id=c.id))

            # We allow sorting and we sort by decreasing date
            # to get the most recent recordings at the top
            tw.setSortingEnabled(True)
            tw.sortByColumn(2, QtCore.Qt.DescendingOrder)

            # Ajust the width of the columns to better see the contents
            tw.resizeColumnsToContents()
            tw.setFixedWidth(600)
            hl.addWidget(tw)

            #### Plot the data
            canvas = self.plot_data(recordings)
            hl.addWidget(canvas)


            self.tabs.addTab(tab,str(c.id) + "-" + c.name)   
Beispiel #36
0
    def view(self):
        """create view and import layers"""
        layer = QgsMapLayerRegistry.instance().mapLayer(self.current_layers[0])
        uri = QgsDataSourceURI(layer.source())
        mtch = re.match(r'(.+)_([^_]+)_rev_(head|\d+)', uri.schema())
        schema = mtch.group(1)
        assert (schema)
        dlg = QDialog()
        layout = QVBoxLayout(dlg)
        button_box = QDialogButtonBox(dlg)
        button_box.setStandardButtons(QDialogButtonBox.Cancel
                                      | QDialogButtonBox.Ok)
        button_box.accepted.connect(dlg.accept)
        button_box.rejected.connect(dlg.reject)

        user_msg1 = QgsMessageBar(dlg)
        user_msg1.pushInfo(
            "Select:", "one [many] for single [multiple] "
            "revisions.  Fetching may take time.")

        pcur = versioning_base.Db(psycopg2.connect(self.pg_conn_info()))
        pcur.execute("SELECT rev, commit_msg, branch, date, author "
                     "FROM " + schema + ".revisions")
        revs = pcur.fetchall()
        pcur.close()
        tblw = QTableWidget(dlg)
        tblw.setRowCount(len(revs))
        tblw.setColumnCount(6)
        tblw.setSortingEnabled(True)
        tblw.setHorizontalHeaderLabels([
            'Select', 'Revision', 'Commit Message', 'Branch', 'Date', 'Author'
        ])
        tblw.verticalHeader().setVisible(False)
        for i, rev in enumerate(revs):
            for j, item in enumerate(rev):
                chkBoxItem = QTableWidgetItem()
                chkBoxItem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                chkBoxItem.setCheckState(Qt.Unchecked)
                tblw.setItem(i, 0, chkBoxItem)
                tblw.setItem(i, j + 1, QTableWidgetItem(str(item)))

        layout.addWidget(user_msg1)
        layout.addWidget(tblw)
        layout.addWidget(button_box)
        dlg.resize(650, 300)
        if not dlg.exec_():
            return

        rows = set()
        revision_number_list = []
        for i in range(len(revs)):
            if tblw.item(i, 0).checkState():
                print "Revision " + str(i + 1) + " will be fetched"
                revision_number_list.append(i + 1)
                rows.add(tblw.item(i, 0).row())

        progressMessageBar = self.iface.messageBar().createMessage(
            "Querying "
            "the database for revision(s) " + str(revision_number_list))
        progress = QProgressBar()
        progress.setMaximum(len(rows))
        progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        progressMessageBar.layout().addWidget(progress)
        self.iface.messageBar().pushWidget(progressMessageBar,
                                           self.iface.messageBar().INFO)
        progress.setValue(0)

        for i, row in enumerate(rows):
            progress.setValue(i + 1)
            branch = revs[row][2]
            rev = revs[row][0]
            versioning_base.add_revision_view(uri.connectionInfo(), schema,
                                              branch, rev)
            grp_name = branch + ' revision ' + str(rev)
            grp_idx = self.iface.legendInterface().addGroup(grp_name)
            for layer_id in reversed(self.current_layers):
                layer = QgsMapLayerRegistry.instance().mapLayer(layer_id)
                new_uri = QgsDataSourceURI(layer.source())
                new_uri.setDataSource(
                    schema + '_' + branch + '_rev_' + str(rev),
                    new_uri.table(), new_uri.geometryColumn(), new_uri.sql(),
                    new_uri.keyColumn())
                display_name = QgsMapLayerRegistry.instance().mapLayer(
                    layer_id).name()
                src = new_uri.uri().replace('()', '')
                new_layer = self.iface.addVectorLayer(src, display_name,
                                                      'postgres')
                self.iface.legendInterface().moveLayer(new_layer, grp_idx)
        self.iface.messageBar().clearWidgets()
Beispiel #37
0
class UserDialog(QDialog):

    holdc = {}

    def __init__(self, parent=None):
        super(UserDialog, self).__init__(parent)
        self.pagetitle = self.sessionname
        self.tableFont = QFont('Century Gothic', 8)
        self.table = QTableWidget()
        self.cols = [
            'SN', 'ITEM', 'QUANTITY', 'UNIT AMOUNT', 'TOTAL AMOUNT', 'DATE'
        ]
        self.h1_pull_box = QVBoxLayout()

        #self.tableFont.setFamily('Century Gothic')
        self.tableHeaderStyle = "::section {" "background-color: teal; color:white}"
        #pull all CA
        self.editID = 0
        self.hold_unit = {}
        self.hold_store = {}
        self.hold_storeGroup = {}
        self.hold_borrowed = {}

        from_label = QLabel('From:')
        to_label = QLabel('To:')
        self.fromData = QDateEdit()
        self.toData = QDateEdit()
        currentDate = QDate()
        self.fromData.setDate(currentDate.currentDate())
        self.fromData.setCalendarPopup(True)
        self.toData.setDate(currentDate.currentDate())
        self.toData.setCalendarPopup(True)
        menu = QMenu()
        menu.addAction('All', lambda: self.reloadTable(0))
        menu.addAction('In-Stock', lambda: self.reloadTable(1))
        menu.addAction('Out-Stock', lambda: self.reloadTable(2))
        menu.addAction('Damaged', lambda: self.reloadTable(3))
        menu.addAction('Borrowed', lambda: self.reloadTable(4))
        self.pull_btn = QPushButton()
        self.pull_btn.setText("Load")
        self.pull_btn.setMenu(menu)
        h_pull_box = QHBoxLayout()
        h_pull_box.addWidget(from_label)
        h_pull_box.addWidget(self.fromData)
        h_pull_box.addWidget(to_label)
        h_pull_box.addWidget(self.toData)
        h_pull_box.addWidget(self.pull_btn)

        storeGroup = self.pullGroupStore()
        unit = self.pullUnit()

        self.storeGroupText = QLabel('Category')
        self.storeGroupData = QComboBox()
        self.storeGroupData.currentIndexChanged.connect(self.reloadStore)
        self.storeText = QLabel('Items')
        self.storeData = QComboBox()

        self.amountText = QLabel('Total Cost')
        self.amountData = QLineEdit()
        self.amountData.setPlaceholderText('0000.00')
        self.tellerText = QLabel('Reciept No.')
        self.tellerData = QLineEdit()
        self.tellerData.setPlaceholderText('xxxxxxxxx')
        self.quantityText = QLabel('Quantity.')
        self.quantityData = QLineEdit()
        self.quantityData.setPlaceholderText('00.0')
        self.periodText = QLabel('Period (days)')
        self.periodData = QLineEdit()
        self.periodData.setPlaceholderText('00.0')
        self.personText = QLabel('Recieved By:')
        self.personData = QLineEdit()
        self.personData.setPlaceholderText('00.0')
        self.unitText = QLabel('Unit')
        self.unitData = QComboBox()
        self.borrowedText = QLabel('Borrowed')
        self.borrowedData = QComboBox()
        self.dateText = QLabel('Date')
        self.dateData = QDateEdit()
        self.dateData.setDate(currentDate.currentDate())
        self.dateData.setCalendarPopup(True)
        self.descriptionText = QLabel('Description')
        self.descriptionData = QPlainTextEdit()
        self.descriptionData.move(200, 100)
        self.borrowedText.hide()
        self.borrowedData.hide()

        mboz = QVBoxLayout()
        hboz = QHBoxLayout()
        self.state = QLabel('')
        self.r1 = QRadioButton('In-stock')
        self.r1.setChecked(True)
        self.r1.toggled.connect(lambda: self.changeStates())
        self.r2 = QRadioButton('Out-stock')
        self.r2.toggled.connect(lambda: self.changeStates())
        self.r3 = QRadioButton('Damaged')
        self.r3.toggled.connect(lambda: self.changeStates())
        self.r4 = QRadioButton('Borrowed')
        self.r4.toggled.connect(lambda: self.changeStates())
        self.r5 = QRadioButton('Returned')
        self.r5.toggled.connect(lambda: self.changeStates())
        hboz.addWidget(self.r1)
        hboz.addWidget(self.r2)
        hboz.addWidget(self.r3)
        hboz.addWidget(self.r4)
        hboz.addWidget(self.r5)

        i = 0
        for a in storeGroup:
            self.hold_storeGroup[i] = a['id']
            tex = str(a['name']).upper()
            self.storeGroupData.addItem(tex)
            i += 1

        i = 0
        str_key = self.hold_storeGroup[self.storeGroupData.currentIndex()]
        store = self.pullStore(str_key)
        for a in store:
            self.hold_store[i] = a['id']
            tex = str(a['name']).upper()
            self.storeData.addItem(tex)
            i += 1

        i = 0
        for a in unit:
            self.hold_unit[i] = a['id']
            tex = str(a['name']).upper()
            self.unitData.addItem(tex)
            i += 1

        self.reloadBorrowed()
        self.FormLayout = QFormLayout()
        self.FormLayout.addRow(self.storeGroupText, self.storeGroupData)
        self.FormLayout.addRow(self.storeText, self.storeData)
        self.FormLayout.addRow(self.tellerText, self.tellerData)
        self.FormLayout.addRow(self.quantityText, self.quantityData)
        self.FormLayout.addRow(self.amountText, self.amountData)
        self.FormLayout.addRow(self.dateText, self.dateData)
        self.FormLayout.addRow(self.periodText, self.periodData)
        self.FormLayout.addRow(self.borrowedText, self.borrowedData)
        self.FormLayout.addRow(self.personText, self.personData)
        self.FormLayout.addRow(self.descriptionText, self.descriptionData)
        self.periodText.hide()
        self.periodData.hide()

        mboz.addLayout(hboz)
        mboz.addLayout(self.FormLayout)
        mboz.addWidget(self.state)

        groupBox1 = QGroupBox('Add Store Item')
        groupBox1.setLayout(mboz)

        self.pb = QPushButton()
        self.pb.setObjectName("Add")
        self.pb.setText("Add Store Item")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Edit")
        self.pb1.setText("Edit Row")
        self.pb1.setEnabled(False)

        self.pb2 = QPushButton()
        self.pb2.setObjectName("Close")
        self.pb2.setText("Close")

        self.pb3 = QPushButton()
        self.pb3.setObjectName("Delete")
        self.pb3.setText("Delete Row")
        self.pb3.setEnabled(False)

        self.pb4 = QPushButton()
        self.pb4.setObjectName("Reset")
        self.pb4.setText("Reset")
        self.pb4.hide()

        self.pb5 = QPushButton()
        self.pb5.setObjectName("Change")
        self.pb5.setText("Change Store")
        self.pb5.hide()

        self.pb6 = QPushButton()
        self.pb6.setObjectName("Clear")
        self.pb6.setText("Clear Selection")
        self.pb6.setEnabled(False)

        hbo = QHBoxLayout()
        hbo.addWidget(self.pb)
        hbo.addWidget(self.pb5)
        hbo.addWidget(self.pb4)
        hbo.addWidget(self.pb2)
        groupBox2 = QGroupBox('Store Data')
        groupBox2.setLayout(hbo)

        al = self.pullStoreData(0)
        if al and len(al) > 0:
            al = al
        else:
            al = {}

        self.storeData.currentIndexChanged.connect(
            lambda: self.reloadBorrowed())

        header = self.table.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)
        header.setStyleSheet(self.tableHeaderStyle)
        vheader = self.table.verticalHeader()
        vheader.setStyleSheet(self.tableHeaderStyle)
        # Body
        self.table.setWindowTitle("Store")
        self.table.setStyleSheet("color:white")
        self.table.resize(300, 250)
        self.table.setFont(self.tableFont)
        self.table.setSortingEnabled(2)
        #self.table.resizeColumnsToContents()
        self.table.setRowCount(len(al))
        self.table.setColumnCount(len(self.cols))
        self.table.setHorizontalHeaderLabels(self.cols)
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.handleHeaderMenu)
        self.table.hideColumn(0)
        self.table.setSelectionMode(QAbstractItemView.MultiSelection)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        i = 0
        for q in al:
            #row id
            if q['state'] == 1:
                color = QColor(100, 0, 0)
            elif q['state'] == 2:
                color = QColor(100, 100, 0)
            elif q['state'] == 3:
                color = QColor(100, 0, 100)
            elif q['state'] == 4:
                color = QColor(0, 100, 100)
            else:
                color = QColor(0, 50, 150)

            self.table.setItem(i, 0, QTableWidgetItem(str(q['id'])))
            self.table.item(i, 0).setBackground(color)
            self.table.setItem(i, 1,
                               QTableWidgetItem(str(q['itemname']).upper()))
            self.table.item(i, 1).setBackground(color)
            self.table.setItem(i, 2,
                               QTableWidgetItem(str(q['quantity']).upper()))
            self.table.item(i, 2).setBackground(color)
            try:
                zamt = str("{:,}".format(float(q['amount'])))
            except:
                zamt = ''
            self.table.setItem(i, 3, QTableWidgetItem(zamt))
            self.table.item(i, 3).setBackground(color)
            try:
                if len(q['amount']) > 0 and float(q['amount']) > 0:
                    tot = float(q['amount']) * float(q['quantity'])
                else:
                    tot = 0
            except:
                tot = 0
            self.table.setItem(i, 4, QTableWidgetItem(str(tot).upper()))
            self.table.item(i, 4).setBackground(color)
            damz = float(q['datepaid'])
            damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
            self.table.setItem(i, 5, QTableWidgetItem(str(damt)))
            self.table.item(i, 5).setBackground(color)
            i += 1
        self.table.itemSelectionChanged.connect(self.confirmSelection)
        self.table.resizeRowsToContents()
        v_pull_box = QVBoxLayout()

        self.h1_pull_box.addWidget(self.table)
        v_pull_box.addLayout(h_pull_box)
        v_pull_box.addLayout(self.h1_pull_box)
        h2_pull_box = QHBoxLayout()
        h2_pull_box.addWidget(self.pb1)
        h2_pull_box.addWidget(self.pb3)
        h2_pull_box.addWidget(self.pb6)
        v_pull_box.addLayout(h2_pull_box)

        groupBox3 = QGroupBox()
        groupBox3.setLayout(hbo)
        groupBox2.setLayout(v_pull_box)

        grid = QGridLayout()
        grid.addWidget(groupBox1, 0, 0)
        grid.addWidget(groupBox2, 0, 1, 2, 1)
        grid.addWidget(groupBox3, 1, 0)

        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_editshow())
        self.connect(self.pb2, SIGNAL("clicked()"),
                     lambda: self.button_close(self))
        self.connect(self.pb3, SIGNAL("clicked()"),
                     lambda: self.button_delete())
        self.connect(self.pb4, SIGNAL("clicked()"),
                     lambda: self.button_reset())
        self.connect(self.pb5, SIGNAL("clicked()"), lambda: self.button_edit())
        self.connect(self.pb6, SIGNAL("clicked()"),
                     lambda: self.button_clear())
        #self.connect(self.pull_btn, SIGNAL("clicked()"), lambda x =1: self.reloadTable(x))

        self.setWindowTitle(self.pagetitle)

    def stateReciept(self):
        self.amountText.show()
        self.amountData.show()
        self.tellerText.show()
        self.tellerData.show()
        self.tellerText.setText('Reciept No.')
        self.periodText.hide()
        self.periodData.hide()
        self.personText.setText('Recieved By:')
        self.personData.setPlaceholderText('Fullname or department')
        self.borrowedText.hide()
        self.borrowedData.hide()
        self.reloadTable(1)

    def stateIssue(self):
        self.amountText.hide()
        self.amountData.hide()
        self.tellerText.show()
        self.tellerData.show()
        self.tellerText.setText('Issue No.')
        self.periodText.hide()
        self.periodData.hide()
        self.personText.setText('Issued to:')
        self.personData.setPlaceholderText('Fullname or department issued to')
        self.borrowedText.hide()
        self.borrowedData.hide()
        self.reloadTable(2)

    def stateDamage(self):
        self.amountText.hide()
        self.amountData.hide()
        self.tellerText.hide()
        self.tellerData.hide()
        self.periodText.hide()
        self.periodData.hide()
        self.personText.setText('Reported By:')
        self.personData.setPlaceholderText('Fullname or department')
        self.borrowedText.hide()
        self.borrowedData.hide()
        self.reloadTable(3)

    def stateBorrowed(self):
        self.amountText.hide()
        self.amountData.hide()
        self.tellerText.hide()
        self.tellerData.hide()
        self.periodText.show()
        self.periodData.show()
        self.personText.setText('Given to:')
        self.personData.setPlaceholderText(
            'Fullname or department borrowed to')
        self.borrowedText.hide()
        self.borrowedData.hide()
        self.reloadTable(4)

    def stateReturned(self):
        self.amountText.hide()
        self.amountData.hide()
        self.tellerText.hide()
        self.tellerData.hide()
        self.periodText.hide()
        self.periodData.hide()
        self.personText.setText('Returned By:')
        self.personData.setPlaceholderText(
            'Fullname or department borrowed to')
        self.borrowedText.show()
        self.borrowedData.show()
        self.reloadBorrowed()
        self.reloadTable(5)

    def changeStates(self):
        self.getQuantity()
        if self.r1.isChecked():
            self.stateReciept()
        elif self.r2.isChecked():
            self.stateIssue()
        elif self.r3.isChecked():
            self.stateDamage()
        elif self.r4.isChecked():
            self.stateBorrowed()
        elif self.r5.isChecked():
            self.stateReturned()

    def handleHeaderMenu(self, pos):
        print('column(%d)' % self.table.horizontalHeader().logicalIndexAt(pos))
        menu = QMenu()
        menu.addAction('Add')
        menu.addAction('Delete')
        menu.exec_(QCursor.pos())

    def pullGroupStore(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 23, "active": 0})
        return arr

    def pullStore(self, a):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"subID": a})
        return arr

    def pullUnit(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 20, "active": 0})
        return arr

    def pullStoreData(self, a=None):
        st_date = self.fromData.date().toPyDate()
        en_date = self.toData.date().toPyDate()
        st_date = time.mktime(st_date.timetuple())
        en_date = time.mktime(en_date.timetuple())

        db = 'school_stores' + str(self.session)
        cn = Db()
        arr = cn.selectStoreDate(db, st_date, en_date, a)
        return arr

    def mySelectTable(self):
        '''
        get the selected rpws in a table
        returns list or row ids
        '''
        sels = self.table.selectedIndexes()
        sels = self.table.selectionModel().selectedRows()

        park = []
        park1 = []
        for j in sels:
            park.append(j.row())

        for i in set(park):
            selected = self.table.item(i, 0).text()
            park1.append(selected)

        return park1

    def editRow(self, a):
        _session = self.session
        g = Db()
        db = 'school_stores' + str(_session)
        data = g.selectn(db, '', 1, {'id': a})
        if len(data) > 0:
            try:
                amt = float(data['amount'])
                qty = float(data['quantity'])
                if amt > 0 and qty > 0:
                    cost = amt * qty
                else:
                    cost = 0
            except:
                cost = 0
                amt = 0
                qty = 0

            if data['state'] == 1:
                self.r1.setChecked(True)
            elif data['state'] == 2:
                self.r2.setChecked(True)
            elif data['state'] == 3:
                self.r3.setChecked(True)
            elif data['state'] == 4:
                self.r4.setChecked(True)
            elif data['state'] == 5:
                self.r5.setChecked(True)

            self.amountData.setText(str(cost))
            self.descriptionData.clear()
            self.descriptionData.insertPlainText(str(data['description']))
            self.tellerData.setText(str(data['teller']))
            self.periodData.setText(str(data['period']))
            self.personData.setText(str(data['person']))
            self.quantityData.setText(str(qty))
            stID = self.hold_store.keys()[self.hold_store.values().index(
                data['itemID'])]
            self.storeData.setCurrentIndex(stID)

    def reloadBorrowed(self):
        self.getQuantity()
        _store = self.hold_store[self.storeData.currentIndex()]
        _session = self.session
        g = Db()
        db = 'school_stores' + str(_session)
        data = g.selectn(db, '', '', {'itemID': _store, 'state': 4})
        fig = 0
        self.borrowedData.clear()
        self.hold_borrowed = {}
        i = 0
        for a in data:
            ret = g.selectStoreReturned(db, a['id'])

            if ret:
                retu = ret['qty']
            else:
                retu = 0

            fig = float(a['quantity']) - float(retu)
            damz = float(a['datepaid'])
            if float(fig) > 0:
                self.hold_borrowed[i] = a['id']
                damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
                tex = str(damt) + " " + str(
                    a['person']).upper() + " (" + str(fig).upper() + ")"
                self.borrowedData.addItem(tex)
                i += 1

    def reloadStore(self):
        self.getQuantity()
        cat = self.hold_storeGroup[self.storeGroupData.currentIndex()]
        store = self.pullStore(cat)
        self.storeData.clear()
        self.hold_store = {}
        i = 0
        for a in store:
            self.hold_store[i] = a['id']
            tex = str(a['name']).upper()
            self.storeData.addItem(tex)
            i += 1

    def getQuantity(self):
        if self.storeData.currentIndex() > -1:
            s = self.hold_store[self.storeData.currentIndex()]
            _session = self.session
            g = Db()
            db = 'school_stores' + str(_session)
            fi = g.selectStoreQuantity(db, s)
            remain = 0
            arr = {}
            for a in fi:
                arr[a['state']] = a['qty']

            if 1 in arr:
                re = arr[1]
            else:
                re = 0

            if 2 in arr:
                isu = arr[2]
            else:
                isu = 0

            if 3 in arr:
                dam = arr[3]
            else:
                dam = 0

            if 4 in arr:
                bor = arr[4]
            else:
                bor = 0

            if 5 in arr:
                ret = arr[5]
            else:
                ret = 0

            borrowed = float(bor) - float(ret)
            issued = float(isu) + float(borrowed) + float(dam)
            remain = float(re) - float(issued)
            self.quantityText.setText('QTY: ' + str(remain))
            if remain == 0 and (self.r2.isChecked() or self.r3.isChecked()
                                or self.r4.isChecked()):
                self.quantityData.setEnabled(False)
            else:
                self.quantityData.setEnabled(True)
            return remain

    def reloadTable(self, a):
        self.getQuantity()
        if not a == 0:
            data = self.pullStoreData(a)
        else:
            data = self.pullStoreData()

        self.table.close()
        self.table = QTableWidget()
        header = self.table.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)
        header.setStyleSheet(self.tableHeaderStyle)
        vheader = self.table.verticalHeader()
        vheader.setStyleSheet(self.tableHeaderStyle)
        # Body
        self.table.setWindowTitle("Stores")
        self.table.setStyleSheet("color:white")
        self.table.resize(300, 250)
        self.table.setFont(self.tableFont)
        self.table.setSortingEnabled(2)
        self.table.resizeColumnsToContents()
        self.table.setRowCount(len(data))
        self.table.setColumnCount(len(self.cols))
        self.table.setHorizontalHeaderLabels(self.cols)
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.handleHeaderMenu)
        self.table.hideColumn(0)
        self.table.setSelectionMode(QAbstractItemView.MultiSelection)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        i = 0
        for q in data:
            #row id

            if q['state'] == 1:
                color = QColor(100, 0, 0)
            elif q['state'] == 2:
                color = QColor(100, 100, 0)
            elif q['state'] == 3:
                color = QColor(100, 0, 100)
            elif q['state'] == 4:
                color = QColor(0, 100, 100)
            else:
                color = QColor(0, 50, 150)

            self.table.setItem(i, 0, QTableWidgetItem(str(q['id'])))
            self.table.item(i, 0).setBackground(color)
            self.table.setItem(i, 1,
                               QTableWidgetItem(str(q['itemname']).upper()))
            self.table.item(i, 1).setBackground(color)
            self.table.setItem(i, 2,
                               QTableWidgetItem(str(q['quantity']).upper()))
            self.table.item(i, 2).setBackground(color)
            try:
                zamt = str("{:,}".format(float(q['amount'])))
            except:
                zamt = ''
            self.table.setItem(i, 3, QTableWidgetItem(zamt))
            self.table.item(i, 3).setBackground(color)
            try:
                if len(q['amount']) > 0 and float(q['amount']) > 0:
                    tot = float(q['amount']) * float(q['quantity'])
                else:
                    tot = 0
            except:
                tot = 0
            self.table.setItem(i, 4, QTableWidgetItem(str(tot).upper()))
            self.table.item(i, 4).setBackground(color)
            damz = float(q['datepaid'])
            damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
            self.table.setItem(i, 5, QTableWidgetItem(str(damt)))
            self.table.item(i, 5).setBackground(color)
            i += 1
        self.table.itemSelectionChanged.connect(self.confirmSelection)
        self.table.resizeRowsToContents()
        self.h1_pull_box.addWidget(self.table)
        self.table.show()

    def pullOnes(self, a, b):
        cn = Db()
        arr = cn.selectn(a, '', 1, {'id': b})
        return arr

    def confirmSelection(self):
        item = self.mySelectTable()
        if len(item) == 1:
            self.pb1.setEnabled(True)
            self.pb3.setEnabled(True)
            self.pb6.setEnabled(True)
        elif len(item) > 1:
            self.pb1.setEnabled(False)
            self.pb3.setEnabled(True)
            self.pb6.setEnabled(True)
        else:
            self.pb1.setEnabled(False)
            self.pb3.setEnabled(False)
            self.pb6.setEnabled(False)

    def button_close(self, b):
        b.close()

    def button_editshow(self):
        item = self.mySelectTable()
        self.editRow(item[0])
        self.pb.hide()
        self.pb4.show()
        self.pb5.show()

    def button_delete(self):
        item = self.mySelectTable()
        _session = self.session
        g = Db()
        db = 'school_stores' + str(_session)
        for j in item:
            g.delete(db, {'id': j})
        self.reloadTable(1)

    def button_edit(self):
        _session = self.session
        _amounts = self.amountData.text()
        _teller = self.tellerData.text()
        _quantity = self.quantityData.text()
        _person = self.personData.text()
        _period = self.periodData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())
        _description = self.descriptionData.toPlainText()
        _store = self.hold_store[self.storeData.currentIndex()]
        _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()]

        arr = {}
        #recieved
        if self.r1.isChecked() and _amounts and not (
                _amounts == 0) and int(_store) > 0 and int(_quantity) > 0:
            _amount = float(_amounts) / float(_quantity)
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 1
        #issued
        elif self.r2.isChecked() and int(_store) > 0 and int(_quantity) > 0:
            _amount = float(_amounts) / float(_quantity)
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 2
        #damaged
        elif self.r3.isChecked() and int(_store) > 0 and int(_quantity) > 0:
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 3

        elif self.r4.isChecked() and int(_store) > 0 and int(_quantity) > 0:
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['period'] = _period
            arr['state'] = 4

        elif self.r5.isChecked() and int(_store) > 0 and int(_quantity) > 0:
            _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()]
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['period'] = _period
            arr['active'] = _borrowed
            arr['state'] = 5

        ups = {}
        ups['id'] = self.editID
        if int(self.editID) > 0 and len(arr) > 0:
            db = 'school_stores' + str(_session)
            g = Db()
            g.update(db, arr, ups)
            if int(self.editID) > 0:
                self.button_reset()

    def button_reset(self):
        self.getQuantity()
        self.reloadTable(1)
        self.amountData.setText('')
        self.descriptionData.clear()
        self.tellerData.setText('')
        self.personData.setText('')
        self.periodData.setText('')
        self.quantityData.setText('')
        self.pb4.hide()
        self.pb5.hide()
        self.pb.show()
        self.editID = 0
        self.button_clear()
        self.confirmSelection()
        self.reloadBorrowed()

    def button_clear(self):
        self.table.selectionModel().clearSelection()

    def button_click(self):
        _session = self.session
        _amounts = self.amountData.text()
        _teller = self.tellerData.text()
        _quantity = self.quantityData.text()
        _person = self.personData.text()
        _period = self.periodData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())
        _description = self.descriptionData.toPlainText()
        _store = self.hold_store[self.storeData.currentIndex()]

        arr = {}
        #recieved
        if self.r1.isChecked() and _amounts and not (
                _amounts == 0) and int(_store) > 0 and int(_quantity) > 0:
            _amount = float(_amounts) / float(_quantity)
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 1
        #issued
        elif self.r2.isChecked() and _amounts and not (
                _amounts == 0) and int(_store) > 0 and int(_quantity) > 0:
            _amount = float(_amounts) / float(_quantity)
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 2
        #damaged
        elif self.r3.isChecked() and int(_store) > 0 and int(
                float(_quantity)) > 0:
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 3

        elif self.r4.isChecked() and int(_store) > 0 and int(
                float(_quantity)) > 0:
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['period'] = _period
            arr['state'] = 4

        elif self.r5.isChecked() and int(_store) > 0 and int(
                float(_quantity)) > 0 and self.borrowedData.currentIndex() > 0:
            _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()]
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['period'] = _period
            arr['active'] = _borrowed
            arr['state'] = 5

        if len(arr) > 0:
            db = 'school_stores' + str(_session)
            g = Db()
            ins = g.insert(db, arr)
            if int(ins) > 0:
                self.button_reset()
Beispiel #38
0
class GraphDialog(QDialog):

    edit_patterns = 0
    edit_curves = 1

    titles = {edit_patterns: 'Pattern editor', edit_curves: 'Curve editor'}

    labels = {edit_patterns: 'Patterns', edit_curves: 'Curves'}

    def __init__(self, dockwidget, parent, params, edit_type):

        QDialog.__init__(self, parent)
        main_lay = QVBoxLayout(self)
        self.dockwidget = dockwidget
        self.params = params
        self.edit_type = edit_type

        self.x_label = ''
        self.y_label = ''

        self.setMinimumWidth(600)
        self.setMinimumHeight(400)

        self.setWindowTitle(self.titles[edit_type])  # TODO: softcode
        self.setWindowModality(QtCore.Qt.ApplicationModal)

        self.current = None

        self.current_saved = False

        # File
        self.lbl_file = QLabel('File:')
        self.fra_file = QFrame()
        self.fra_file.setContentsMargins(0, 0, 0, 0)
        fra_file_lay = QHBoxLayout(self.fra_file)

        if edit_type == self.edit_patterns:
            self.txt_file = QLineEdit(self.params.patterns_file)
        elif edit_type == self.edit_curves:
            self.txt_file = QLineEdit(self.params.curves_file)

        self.txt_file.setReadOnly(True)
        self.txt_file.setAlignment(QtCore.Qt.AlignLeft
                                   | QtCore.Qt.AlignVCenter)
        self.txt_file.setSizePolicy(QSizePolicy.MinimumExpanding,
                                    QSizePolicy.Minimum)
        fra_file_lay.addWidget(self.txt_file)
        self.btn_file = QPushButton('Change')  # TODO: softcode
        self.btn_file.clicked.connect(self.import_file)
        fra_file_lay.addWidget(self.btn_file)
        fra_file_lay.setContentsMargins(0, 0, 0, 0)

        self.lbl_list = QLabel(self.labels[edit_type])
        self.lst_list = QListWidget()
        self.lst_list.currentItemChanged.connect(self.list_item_changed)

        # Form
        self.fra_form = QFrame()
        fra_form1_lay = QFormLayout(self.fra_form)
        fra_form1_lay.setContentsMargins(0, 0, 0, 0)
        fra_form1_lay.addRow(self.lbl_list, self.lst_list)

        # Buttons
        self.fra_buttons = QFrame()
        fra_buttons_lay = QHBoxLayout(self.fra_buttons)
        fra_buttons_lay.setContentsMargins(0, 0, 0, 0)

        if self.edit_type == self.edit_patterns:
            ele_name = 'pattern'
        elif self.edit_type == self.edit_curves:
            ele_name = 'curve'

        self.btn_new = QPushButton('New ' + ele_name)  # TODO: softcode
        self.btn_new.clicked.connect(self.new_element)
        fra_buttons_lay.addWidget(self.btn_new)

        self.btn_import = QPushButton('Import ' + ele_name +
                                      's')  # TODO: softcode
        self.btn_import.clicked.connect(self.import_file)
        fra_buttons_lay.addWidget(self.btn_import)

        self.btn_save = QPushButton('Save current ' +
                                    ele_name)  # TODO: softcode
        self.btn_save.clicked.connect(self.save)
        fra_buttons_lay.addWidget(self.btn_save)

        self.btn_del = QPushButton('Delete current ' +
                                   ele_name)  # TODO: softcode
        self.btn_del.clicked.connect(self.del_item)
        fra_buttons_lay.addWidget(self.btn_del)

        # ID
        self.lbl_id = QLabel('ID:')
        self.txt_id = QLineEdit()
        self.txt_id.setSizePolicy(QSizePolicy.Maximum,
                                  QSizePolicy.MinimumExpanding)
        self.lbl_desc = QLabel('Desc.:')
        self.txt_desc = QLineEdit()

        self.fra_id = QFrame()
        fra_id_lay = QHBoxLayout(self.fra_id)
        fra_id_lay.addWidget(self.lbl_id)
        fra_id_lay.addWidget(self.txt_id)
        fra_id_lay.addWidget(self.lbl_desc)
        fra_id_lay.addWidget(self.txt_desc)

        # Table form
        self.table = QTableWidget(self)
        self.rows_nr = 24
        self.cols_nr = 2
        self.table.setRowCount(self.rows_nr)
        self.table.setColumnCount(self.cols_nr)
        self.table.verticalHeader().setVisible(False)

        # Initialize empty table
        self.clear_table()

        self.table.itemChanged.connect(self.data_changed)

        self.fra_table = QFrame()
        fra_table_lay = QVBoxLayout(self.fra_table)
        fra_table_lay.setContentsMargins(0, 0, 0, 0)

        if edit_type == self.edit_curves:
            self.fra_pump_type = QFrame()
            fra_pump_type_lay = QFormLayout(self.fra_pump_type)

            self.lbl_pump_type = QLabel('Curve type:')  # TODO: softcode
            self.cbo_pump_type = QComboBox()

            for key, name in Curve.type_names.iteritems():
                self.cbo_pump_type.addItem(name, key)

            fra_pump_type_lay.addRow(self.lbl_pump_type, self.cbo_pump_type)

            fra_table_lay.addWidget(self.fra_pump_type)

            self.cbo_pump_type.activated.connect(self.cbo_pump_type_activated)

        fra_table_lay.addWidget(self.table)
        self.btn_add_row = QPushButton('Add row')
        self.btn_add_row.clicked.connect(self.add_row)
        fra_table_lay.addWidget(self.btn_add_row)

        # Graph canvas
        self.fra_graph = QFrame()
        self.static_canvas = StaticMplCanvas(self.fra_graph,
                                             width=5,
                                             height=4,
                                             dpi=100)
        fra_graph_lay = QVBoxLayout(self.fra_graph)
        fra_graph_lay.addWidget(self.static_canvas)

        # Top frame
        self.fra_top = QFrame()
        fra_top_lay = QVBoxLayout(self.fra_top)
        fra_top_lay.addWidget(self.fra_form)
        fra_top_lay.addWidget(self.fra_id)
        fra_top_lay.addWidget(self.fra_buttons)

        # Bottom frame
        self.fra_bottom = QFrame()
        fra_bottom_lay = QHBoxLayout(self.fra_bottom)
        fra_bottom_lay.addWidget(self.fra_table)
        fra_bottom_lay.addWidget(self.fra_graph)

        # Main
        main_lay.addWidget(self.fra_top)
        main_lay.addWidget(self.fra_bottom)

        # Get existing patterns/curves
        self.need_to_update_graph = False
        if self.edit_type == self.edit_patterns:
            for pattern_id, pattern in self.params.patterns.iteritems():
                self.lst_list.addItem(pattern.id)

        elif self.edit_type == self.edit_curves:
            for curve_id, curve in self.params.curves.iteritems():
                self.lst_list.addItem(curve.id)

        if self.lst_list.count() > 0:
            self.lst_list.setCurrentRow(0)
            self.txt_id.setEnabled(True)
            self.txt_desc.setEnabled(True)
            self.btn_save.setEnabled(True)
            self.btn_del.setEnabled(True)
            self.table.setEnabled(True)
            self.table.setEditTriggers(QAbstractItemView.AllEditTriggers)
        else:
            self.txt_id.setEnabled(False)
            self.txt_desc.setEnabled(False)
            self.btn_save.setEnabled(False)
            self.btn_del.setEnabled(False)
            self.table.setEnabled(False)
            self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        self.new_dialog = None
        self.need_to_update_graph = True

    def cbo_pump_type_activated(self):
        self.update_table_headers()
        self.update_graph()

    def add_row(self):
        row_pos = self.table.rowCount()
        self.table.insertRow(row_pos)
        col = 0
        item = QTableWidgetItem(str(row_pos))

        if self.edit_type == self.edit_patterns:
            self.table.setItem(row_pos, col, item)
            item.setFlags(QtCore.Qt.ItemIsSelectable)

    def setVisible(self, bool):
        QDialog.setVisible(self, bool)

        self.update_table_headers()
        self.update_graph()

    def list_item_changed(self):

        p_index = self.lst_list.currentRow()

        flags = Qt.ItemFlags()
        flags != Qt.ItemIsEnabled

        # Clear table
        self.clear_table()

        self.need_to_update_graph = False
        if p_index >= 0:

            self.table.setRowCount(0)

            if self.edit_type == self.edit_patterns:
                self.current = self.params.patterns[
                    self.lst_list.currentItem().text()]
                for v in range(len(self.current.values)):

                    row_pos = self.table.rowCount()
                    self.table.insertRow(row_pos)

                    item = QTableWidgetItem(str(v))
                    item.setFlags(flags)
                    self.table.setItem(v, 0, item)
                    self.table.setItem(
                        v, 1, QTableWidgetItem(str(self.current.values[v])))

            elif self.edit_type == self.edit_curves:
                self.current = self.params.curves[
                    self.lst_list.currentItem().text()]
                for v in range(len(self.current.xs)):

                    row_pos = self.table.rowCount()
                    self.table.insertRow(row_pos)

                    self.table.setItem(
                        v, 0, QTableWidgetItem(str(self.current.xs[v])))
                    self.table.setItem(
                        v, 1, QTableWidgetItem(str(self.current.ys[v])))

                curve_type = self.current.type
                self.cbo_pump_type.setCurrentIndex(curve_type)

            # Update GUI
            self.txt_id.setText(self.current.id)
            self.txt_desc.setText(self.current.desc)

            self.update_table_headers()

            # Update graph
            self.need_to_update_graph = True
            self.update_graph()

        else:

            # No curves
            self.txt_id.setText('')
            self.txt_desc.setText('')

            # Update table and chart
            self.need_to_update_graph = False
            for v in range(self.table.columnCount()):
                self.table.setItem(v, 1, QTableWidgetItem(''))

            self.need_to_update_graph = True
            self.update_graph()

    def import_file(self):

        config_file = ConfigFile(Parameters.config_file_path)

        directory = None
        if self.edit_type == GraphDialog.edit_curves:
            directory = self.params.last_curves_dir
        elif self.edit_type == GraphDialog.edit_patterns:
            directory = self.params.last_patterns_dir

        if directory is None:
            directory = self.params.last_project_dir

        file_path = QFileDialog.getOpenFileName(self, 'Select file', directory,
                                                'Files (*.txt *.inp)')

        if file_path is None or file_path == '':
            return
        else:
            if self.edit_type == GraphDialog.edit_patterns:
                # Save patterns file path in configuration file
                config_file.set_patterns_file_path(file_path)
                Parameters.patterns_file = file_path
            elif self.edit_type == GraphDialog.edit_curves:
                # Save curve file path in configuration file
                config_file.set_curves_file_path(file_path)
                Parameters.curves_file = file_path

        self.read(file_path)

    def read(self, file_path):

        self.lst_list.clear()

        if self.edit_type == self.edit_patterns:
            InpFile.read_patterns(self.params, file_path)
            for pattern_id, pattern in self.params.patterns.iteritems():
                # desc = ' (' + pattern.desc + ')' if pattern.desc is not None else ''
                self.lst_list.addItem(pattern.id)
                self.params.patterns[pattern.id] = pattern

        elif self.edit_type == self.edit_curves:
            InpFile.read_curves(self.params, file_path)
            for curve_id, curve in self.params.curves.iteritems():
                # desc = ' (' + curve.desc + ')' if curve.desc is not None else ''
                self.lst_list.addItem(curve.id)
                self.params.curves[curve.id] = curve

        if self.lst_list.count() > 0:
            self.lst_list.setCurrentRow(0)

    def new_element(self):

        old_ids = []
        if self.edit_type == self.edit_patterns:
            for pattern in self.params.patterns.itervalues():
                old_ids.append(pattern.id)
        elif self.edit_type == self.edit_curves:
            for curve in self.params.curves.itervalues():
                old_ids.append(curve.id)
        self.new_dialog = NewIdDialog(self, old_ids)
        self.new_dialog.exec_()

        new_id = self.new_dialog.get_newid()
        description = self.new_dialog.get_description()
        if new_id is None or description is None:
            return

        if self.edit_type == self.edit_patterns:
            new_pattern = Pattern(new_id, description)
            self.params.patterns[new_pattern.id] = new_pattern
            self.lst_list.addItem(new_pattern.id)
        elif self.edit_type == self.edit_curves:
            curve_type = self.cbo_pump_type.itemData(
                self.cbo_pump_type.currentIndex())
            new_curve = Curve(new_id, curve_type, desc=description)
            self.params.curves[new_curve.id] = new_curve
            self.lst_list.addItem(new_curve.id)

        self.lst_list.setCurrentRow(self.lst_list.count() - 1)

        self.txt_id.setText(new_id)
        self.txt_desc.setText(description)

        # Clear table
        self.clear_table()
        self.static_canvas.axes.clear()

        self.txt_id.setEnabled(True)
        self.txt_desc.setEnabled(True)
        self.btn_save.setEnabled(True)
        self.btn_del.setEnabled(True)
        self.table.setEnabled(True)
        self.table.setEditTriggers(QAbstractItemView.AllEditTriggers)

    def save(self):

        self.need_to_update_graph = False

        # Check for ID
        if not self.txt_id.text():
            QMessageBox.warning(
                self,
                Parameters.plug_in_name,
                u'Please specify the ID.',  # TODO: softcode
                QMessageBox.Ok)
            return

        if self.edit_type == GraphDialog.edit_patterns:
            values = []
            for row in range(self.table.rowCount()):
                item = self.table.item(row, 1)
                if item is not None and item.text() != '':
                    values.append(self.from_item_to_val(item))
                else:
                    values.append('0')

            pattern = Pattern(self.txt_id.text(), self.txt_desc.text(), values)

            old_patterns = self.params.patterns
            old_patterns[pattern.id] = pattern
            self.params.patterns = old_patterns

            self.lst_list.currentItem().setText(pattern.id)

        elif self.edit_type == GraphDialog.edit_curves:

            # Check for ID unique
            xs = []
            ys = []
            for row in range(self.table.rowCount()):
                item_x = self.table.item(row, 0)
                item_y = self.table.item(row, 1)

                if item_x.text() != '' and item_y.text() != '':
                    xs.append(self.from_item_to_val(item_x))
                    ys.append(self.from_item_to_val(item_y))

            curve_type = self.cbo_pump_type.itemData(
                self.cbo_pump_type.currentIndex())
            curve = Curve(self.txt_id.text(), curve_type, self.txt_desc.text())
            for v in range(len(xs)):
                curve.append_xy(xs[v], ys[v])

            old_curves = self.params.curves
            old_curves[curve.id] = curve
            self.params.curves = old_curves

            self.lst_list.currentItem().setText(curve.id)

            # Update GUI
            self.dockwidget.update_curves_combo()

        # self.read()
        self.need_to_update_graph = True

    def clear_table(self):

        self.need_to_update_graph = False
        for r in range(self.table.rowCount()):
            self.table.setItem(r, 0, QTableWidgetItem(None))
            self.table.setItem(r, 1, QTableWidgetItem(None))

        for row in range(self.rows_nr):
            for col in range(self.cols_nr):
                if self.edit_type == self.edit_patterns:
                    if col == 0:
                        item = QTableWidgetItem(str(row))
                        self.table.setItem(row, col, item)
                        item.setFlags(QtCore.Qt.ItemIsSelectable)
                    # elif col == 1 and row == 0:
                    #     item = QTableWidgetItem(str(1))
                    #     self.table.setItem(row, col, item)
                    #     item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)

                # elif self.edit_type == self.edit_curves:
                # if row == 0:
                # item = QTableWidgetItem(str(0))
                # self.table.setItem(row, 0, item)
                # item = QTableWidgetItem(str(1))
                # self.table.setItem(row, 1, item)
                # item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
        self.need_to_update_graph = True

    def del_item(self):
        selected_row = self.lst_list.currentRow()
        name = self.lst_list.currentItem().text()
        if selected_row < 0:
            return

        self.lst_list.takeItem(selected_row)
        if self.lst_list.count() == 0:
            self.txt_id.setEnabled(False)
            self.txt_desc.setEnabled(False)
            self.btn_save.setEnabled(False)
            self.btn_del.setEnabled(False)
            self.table.setEnabled(False)
            self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        if self.edit_type == GraphDialog.edit_curves:
            del self.params.curves[name]
            # Update GUI
            self.dockwidget.update_curves_combo()
        elif self.edit_type == GraphDialog.edit_patterns:
            del self.params.patterns[name]
            # Update GUI
            self.dockwidget.update_patterns_combo()

    def data_changed(self):

        if self.need_to_update_graph:
            self.update_graph()

    def update_table_headers(self):
        if self.edit_type == self.edit_patterns:
            self.x_label = 'Time period'
            self.y_label = 'Multiplier'
        elif self.edit_type == self.edit_curves:
            cbo_data = self.cbo_pump_type.itemData(
                self.cbo_pump_type.currentIndex())
            if cbo_data == Curve.type_efficiency:
                self.x_label = 'Flow ' + '[' + self.params.options.flow_units + ']'
                self.y_label = 'Efficiency ' + '[' + self.params.options.units_deltaz[
                    self.params.options.units] + ']'
            if cbo_data == Curve.type_headloss:
                self.x_label = 'Flow ' + '[' + self.params.options.flow_units + ']'
                self.y_label = 'Headloss ' + '[' + self.params.options.units_deltaz[
                    self.params.options.units] + ']'
            if cbo_data == Curve.type_pump:
                self.x_label = 'Flow ' + '[' + self.params.options.flow_units + ']'
                self.y_label = 'Head ' + '[' + self.params.options.units_deltaz[
                    self.params.options.units] + ']'
            if cbo_data == Curve.type_volume:
                self.x_label = 'Height ' + '[' + self.params.options.flow_units + ']'
                self.y_label = 'Volume ' + '[' + self.params.options.units_deltaz[
                    self.params.options.units] + ']'

        self.table.setHorizontalHeaderLabels([self.x_label,
                                              self.y_label])  # TODO: softcode

    def update_graph(self):

        if not self.need_to_update_graph:
            return

        xs = []
        ys = []

        for row in range(self.table.rowCount()):
            item = self.table.item(row, 0)
            x = self.from_item_to_val(item)
            item = self.table.item(row, 1)
            y = self.from_item_to_val(item)

            if x is not None:
                xs.append(float(x))
            if y is not None:
                ys.append(float(y))

        if len(xs) == 0 or len(ys) == 0:
            self.static_canvas.clear()
            return

        xys_t = zip(xs, ys)
        xys_t.sort()

        xys = zip(*xys_t)
        xs = xys[0]
        ys = xys[1]

        if self.edit_type == self.edit_patterns:
            y_axis_label = 'Mult. avg.: ' + '{0:.2f}'.format(
                (numpy.average(ys)))
            self.static_canvas.draw_bars_graph(
                ys,
                time_period=self.params.times.pattern_timestep,
                y_axes_label=y_axis_label)

        elif self.edit_type == self.edit_curves:

            # Account for different types of curves
            cbo_data = self.cbo_pump_type.itemData(
                self.cbo_pump_type.currentIndex())

            series_length = min(len(xs), len(ys))

            # Need to account for different types of curves
            if cbo_data == Curve.type_efficiency or cbo_data == Curve.type_headloss or cbo_data == Curve.type_volume:
                self.static_canvas.draw_line_graph(xs[:series_length],
                                                   ys[:series_length],
                                                   self.x_label, self.y_label)

            elif cbo_data == Curve.type_pump:
                if series_length == 1 or series_length == 3:
                    if series_length == 1:
                        # 3 curve points
                        curve_xs = [0, xs[0], xs[0] * 2]
                        curve_ys = [ys[0] * 1.33, ys[0], 0]
                        # y = a * x^2 + b * x + c

                    elif series_length == 3:
                        # 3 curve points
                        curve_xs = [xs[0], xs[1], xs[2]]
                        curve_ys = [ys[0], ys[1], ys[2]]

                    (a, b, c) = numpy.polyfit(curve_xs, curve_ys, 2)

                    # Create a few interpolated values
                    interp_xs = []
                    interp_ys = []
                    n_vals = 30
                    for v in range(n_vals + 1):
                        x = (curve_xs[2] - curve_xs[0]) / n_vals * v
                        interp_xs.append(x)
                        y = a * x**2 + b * x + c
                        interp_ys.append(y)

                    self.static_canvas.draw_line_graph(interp_xs, interp_ys,
                                                       self.x_label,
                                                       self.y_label)

                else:
                    self.static_canvas.draw_line_graph(xs[:series_length],
                                                       ys[:series_length],
                                                       self.x_label,
                                                       self.y_label)

    def from_item_to_val(self, item):

        if item is None:
            value = None
        else:
            value = item.text()
        try:
            value = float(value)
            value = max(value, 0)

        except:
            value = None

        return value
class DataItemWidget(QWidget):
    __EXTRA_COLUMN_WIDTH = 20

    def __init__(self, me_cls, data):
        QWidget.__init__(self)
        self.__me_cls = me_cls
        self.__setup_ui()
        self.__data = data
        self.__init_data()
        self.__connect_slot()

    def __setup_ui(self):

        v_layout = QVBoxLayout()

        self.__tool_widget = ToolWidget()

        self.__tool_widget.setMaximumHeight(40)

        self.__data_table_widget = QTableWidget()
        self.__data_table_widget.horizontalHeader().setStretchLastSection(True)
        self.__data_table_widget.horizontalHeader().setResizeMode(
            0, QHeaderView.Fixed)

        v_layout.setSpacing(0)
        v_layout.setContentsMargins(0, 0, 0, 0)
        v_layout.addWidget(self.__tool_widget, 0)
        v_layout.addWidget(self.__data_table_widget, 1)
        self.setLayout(v_layout)

    def __connect_slot(self):
        pass
        #self.connect(self.__tool_widget,SIGNAL('refresh_btn_clicked()'), self ,SLOT('__on_refresh_signal()'))

    def __init_data(self):

        self.__data_table_widget.clearContents()

        # init header
        #self.__colume_names = yt_connection.get_table_colume_names(self.__table_name)
        self.__colume_names = [x.field.name for x in self.__me_cls.attributes]
        #self.__colume_names.insert(0,'entity_id')

        #print self.__colume_names

        self.__data_table_widget.setColumnCount(len(self.__colume_names))
        head_list = QStringList()
        for colume in self.__colume_names:
            head_list << colume

        self.__data_table_widget.setHorizontalHeaderLabels(head_list)

        # default the header column both sides are coverd, these codes add __EXTRA_COLUMN_WIDTH to the header column width
        # and reise column width in function self.__adjust_table_colume()
        self.__data_table_widget.horizontalHeader().setResizeMode(
            QHeaderView.ResizeToContents)
        self.__record_colume_header_width()
        self.__data_table_widget.horizontalHeader().setResizeMode(
            QHeaderView.Interactive)

        self.__record_colume_header_width()

        show_data = []
        for entity_id, value in self.__data.items():
            item = value.obj_data.copy()
            item['managed_entity_id'] = entity_id
            show_data.append(item)

        self.__update_table(show_data)

        # init data
        # data = yt_connection.get_table_data(self.__table_name)
        #
        # self.__update_table(data)
        self.__adjust_table_colume()

    def __record_colume_header_width(self):
        count = self.__data_table_widget.columnCount()
        self.__column_widths = []
        for i in range(count):
            self.__column_widths.append(
                self.__data_table_widget.columnWidth(i) +
                self.__EXTRA_COLUMN_WIDTH)

    '''
    data like this
    [
    {u'direction': 'to-lport', 
    u'name': '[]', 
    u'priority': '100', 
    u'log': 'true', 
    u'action': 'drop', 
    u'external_ids': '{"neutron:lport"="5fb77332-2035-4f72-8e57-7415b02489c9"}', 
    u'match': '"outport==\\"inside-vm2\\""', 
    u'severity': '[]',
    'uuid': '2890a832-1c83-4b8e-8b40-2928817012cc'}
    ]

    '''

    def __update_table(self, data):
        self.__data_table_widget.clearContents()

        row_num = 0
        for row in data:
            self.__data_table_widget.insertRow(row_num)
            colume_num = 0
            for colume in self.__colume_names:
                if row.has_key(colume):
                    item_str = str(row[colume])
                else:
                    item_str = 'None'
                table_wid_item = QTableWidgetItem(item_str)
                table_wid_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)

                self.__data_table_widget.setItem(row_num, colume_num,
                                                 table_wid_item)
                colume_num += 1
            row_num += 1

    def __clear_table_data(self):
        row_count = self.__data_table_widget.rowCount()
        rev = [i for i in range(row_count)]
        rev.reverse()
        for i in rev:
            self.__data_table_widget.removeRow(i)

    def __adjust_table_colume(self):
        self.__data_table_widget.resizeColumnsToContents()
        count = self.__data_table_widget.columnCount()
        for i in range(count):
            col_wid = self.__data_table_widget.columnWidth(i)
            if col_wid < self.__column_widths[i]:
                self.__data_table_widget.setColumnWidth(
                    i, self.__column_widths[i])
Beispiel #40
0
def make_widget(main, show=True):

    id = main.persistant['id']
    table = QTableWidget()
    table.controller = ROITableController(table, main)
    table.setGeometry(QRect(20, 33, 496, 296))
    table.setWindowTitle('ceilingfaan - ROI Table - Work in progress')
    analysis = s.query(Analysis).order_by(Analysis.date.desc()).all()
    table.setRowCount(len(analysis))
    table.setColumnCount(4)
    table.setHorizontalHeaderLabels(
        QString('CONTROL,DATE,MOUSE,FILENAME').split(','))

    current_analysis = None
    on_render = table.controller.on('render')
    on_import = table.controller.on('import')
    for nrow, entity in enumerate(analysis):
        if entity.id == id:
            print 'Found matching analysis data', id, 'at nrow:', nrow
            current_analysis = entity
            current_nrow = nrow
            continue

        for ncol, attr in enumerate('date mouse_id filename'.split()):
            field = getattr(entity, attr)
            item = QTableWidgetItem(str(field))
            item.setFlags(Qt.ItemIsEnabled)
            table.setItem(nrow, ncol + 1, item)

        render_btn = QPushButton('Render', checkable=True)
        render_btn.setStyleSheet('font-size: 9px; background-color: skyblue;')
        import_btn = QPushButton('Import')
        import_btn.setStyleSheet('font-size: 9px;')

        btn_layout = QHBoxLayout()
        btn_layout.setContentsMargins(5, 0, 5, 0)
        btn_layout.addWidget(render_btn)
        btn_layout.addWidget(import_btn)

        btn_widget = QWidget()
        btn_widget.nrow = nrow
        btn_widget.analysis_id = entity.id
        btn_widget.ext_roi_set = None
        btn_widget.setLayout(btn_layout)
        table.setCellWidget(nrow, 0, btn_widget)

        render_btn.clicked.connect(on_render)
        import_btn.clicked.connect(on_import)

    if current_analysis:
        table.removeRow(current_nrow)
        table.insertRow(0)
        item = QTableWidgetItem('Current Analysis')
        item.setFlags(Qt.ItemIsEnabled)
        item.setTextAlignment(Qt.AlignCenter)
        table.setItem(0, 0, item)
        for ncol, attr in enumerate('date mouse_id filename'.split()):
            field = getattr(current_analysis, attr)
            item = QTableWidgetItem(str(field))
            item.setFlags(Qt.ItemIsEnabled)
            table.setItem(0, ncol + 1, item)
        # debug.enter()

    table.setSelectionBehavior(QTableWidget.SelectRows)
    table.setSelectionMode(QTableWidget.NoSelection)
    table.resizeColumnsToContents()
    table.horizontalHeader().setStretchLastSection(True)

    if show: table.show()

    return table
Beispiel #41
0
class PvTunerDlg(QDialog):
    COL = 6
    COL_ELEMENT  = 0
    COL_FIELD    = 1
    COL_PV       = 2
    COL_STEPSIZE = 3
    COL_READBACK = 4
    COL_SETPOINT = 5
    FMT_READBACK = "%.4e"
    def __init__(self, parent=None):  
        super(PvTunerDlg, self).__init__(parent)

        self.setAttribute(Qt.WA_DeleteOnClose)

        #self.inputBox = QLineEdit("PL2G2C01A.x")
        #self.inputBox = QLineEdit("CXH2G6C01B.x")
        self.inputBox = QLineEdit("PL2G2C01A")

        addPvBtn = QPushButton("add")

        self.table = QTableWidget(0, PvTunerDlg.COL)
        self.table.setHorizontalHeaderLabels(["Element", "Field", "PV",
                 "Stepsize", "Readback", "setpoint"])
        #self.table.horizontalHeader().setStretchLastSection(True)
        #self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)

        box = QGridLayout()
        box.addWidget(self.inputBox, 0, 0)
        box.addWidget(addPvBtn, 0, 1)
        box.addWidget(self.table, 1, 0, 1, 2)
        box.addWidget(buttonBox, 2, 0)

        self.setLayout(box)

        self.pvs_rb = []
        self.pvs_rb_val_flat = []
        self.pvs_sp = []
        self.pvmoni = []
        self.spinbox = []
        self.connect(addPvBtn, SIGNAL("clicked()"), self.addPv)
        self.connect(buttonBox, SIGNAL("accepted()"), self.accept)
        #self.connect(self.table, SIGNAL("cellChanged"), self.updatePv)
        self.connect(buttonBox.button(QDialogButtonBox.Ok),
                     SIGNAL("clicked()"), self.close)
        self.connect(self.table, SIGNAL("cellClicked(int, int)"),
                     self._cell_clicked)


    def _cell_clicked(self, row, column):
        #print row, column
        if column in [self.COL_PV, self.COL_STEPSIZE]:
            item = self.table.item(row, column)
            if not item: return
            item.setFlags(item.flags() | Qt.ItemIsEditable)

    def _appendRecord(self, name):
        vec = name.split('.')
        if len(vec) > 2:
            QMessageBox.critical(None, "ERROR", "format is wrong")
            return

        if len(vec) == 1:
            elem, field = vec[0], 'value'
        elif len(vec) == 2:
            elem, field = vec

        elemobj = hla.getElements(elem)
        if elemobj:
            # pvsrb is a list
            pvsrb = elemobj.pv(field=field, handle='readback')
            self.pvs_rb.append(pvsrb)
            pvssp = elemobj.pv(field=field, handle='setpoint')
            self.pvs_sp.append(pvssp)
        else:
            QMessageBox.critical(None, "ERROR", "element %s not found" % elem)
            return

        # expand one row
        m, n = self.table.rowCount(), self.table.columnCount()
        self.table.insertRow(m)

        # add cells
        item = QTableWidgetItem(elem)
        item.setFlags(item.flags() & (~Qt.ItemIsEditable))
        self.table.setItem(m, self.COL_ELEMENT, item)
        
        item = QTableWidgetItem(field)
        item.setFlags(item.flags() & (~Qt.ItemIsEditable))
        self.table.setItem(m, self.COL_FIELD, item)

        
        item = QTableWidgetItem(', '.join(pvsrb))
        #item.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)
        self.table.setItem(m, self.COL_PV, item)

        readval = ['%.4e' % v for v in caget(pvsrb)]
        item = QTableWidgetItem(', '.join(readval))
        item.setFlags(item.flags() & (~Qt.ItemIsEditable))
        self.table.setItem(m, self.COL_READBACK, item)

        # set the stepsize of PV
        stepsize = 0.00001
        if pvssp:
            item = QTableWidgetItem('%f' % stepsize)
            item.setFlags(item.flags() & (~Qt.ItemIsEditable))
            self.table.setItem(m, self.COL_STEPSIZE, item)

            self.spinbox.append(QDoubleSpinBox(self.table))
            self.spinbox[-1].setRange(-100, 100)
            #self.spinbox[-1].setValue(float(10.0))
            self.spinbox[-1].setSingleStep(stepsize)
            self.spinbox[-1].setDecimals(10)
            
            self.spinbox[-1].valueChanged.connect(self._writePv)
            
            self.table.setCellWidget(m, self.COL_SETPOINT, self.spinbox[-1])

            sp = float(caget(pvssp)[0])
            #print "setpoint:", pvssp, sp, type(sp)
            self.spinbox[-1].setValue(-1e-5)
            #print "connected", self.spinbox[-1].value()
        else:
            item = self.table.item(m, self.COL_STEPSIZE)
            if item: item.setFlags(item.flags() & (~Qt.ItemIsEditable))
            item = self.table.item(m, self.COL_SETPOINT)
            if item: item.setFlags(item.flags() & (~Qt.ItemIsEditable))
            self.spinbox.append(None)

        self.table.resizeColumnsToContents()

        
    def addPv(self):
        self._appendRecord(str(self.inputBox.text()))
        self._updateMonitors()

    def minimalSizeHint(self):
        return QSize(800, 600)


    def _writePv(self, v):
        """
        """
        c = QObject.sender(self)
        i = self.spinbox.index(c)
        #print i, c.text(), "changed"

        #print self.pvs_sp[i], v
        caput(self.pvs_sp[i], v)

    def _updateMonitors(self):
        """
        prepare the PV list for camonitor
        """
        #print "Updating monitors"
        pvs = []
        self.pvs_rb_val = []
        for i in range(self.table.rowCount()):
            for j in range(len(self.pvs_rb[i])):
                self.pvs_rb_val.append([i, 0.0])
            pvs.extend(self.pvs_rb[i])
        
        for p in self.pvmoni: p.close()
        self.pvmoni = camonitor(pvs, self._updatePvValues)
        #print self.pvmoni
        #print pvs
        #print self.pvs_rb_val


    def _updatePvValues(self, val, idx):
        #print idx, val
        s = []
        for i, v in enumerate(self.pvs_rb_val):
            if v[0] == self.pvs_rb_val[idx][0]:
                s.append(self.FMT_READBACK % val)
        #print s
        item = self.table.item(self.pvs_rb_val[idx][0], self.COL_READBACK)
        item.setText(','.join(s))

    def closePvMonitors(self):
        #print "Closing PV Monitors"
        for p in self.pvmoni: p.close()

        pass

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

    def close(self):
        self.closePvMonitors()
        return True
Beispiel #42
0
class PatternsTable(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.grid = QGridLayout()
        self.setLayout(self.grid)
        self.patternArea()
        self.patternTable()

    def createPattern(self, name, x):
        label = name.lower() + "Label"
        type = name.lower() + "Type"
        entry = name.lower() + "Entry"
        setattr(self, label, QLabel(name))
        setattr(self, entry, QLineEdit())
        setattr(self, type, QComboBox())
        labelobj = getattr(self, label)
        typeobj = getattr(self, type)
        entryobj = getattr(self, entry)
        typeobj.addItem("Hexadecimal")
        typeobj.addItem("String")
        self.grid.addWidget(labelobj, x, 0)
        self.grid.addWidget(entryobj, x, 1)
        self.grid.addWidget(typeobj, x, 2)


    def patternArea(self):
        self.filetypeLabel = QLabel("File type")
        self.filetype = QLineEdit()
        self.alignedLabel = QLabel("block aligned")
        self.aligned = QCheckBox()
        self.windowLabel = QLabel("Window size")
        self.window = QSpinBox()
        self.window.setSuffix(" bytes")
        self.window.setRange(0, 2500000)
        self.window.setSingleStep(100)
        self.addEntry = QPushButton("add")
        self.connect(self.addEntry, SIGNAL("clicked()"), self.insertPattern)
        self.grid.addWidget(self.filetypeLabel, 0, 0)
        self.grid.addWidget(self.filetype, 0, 1, 1, 2)
        self.createPattern("Header", 2)
        self.createPattern("Footer", 3)
        self.grid.addWidget(self.windowLabel, 4, 0)
        self.grid.addWidget(self.window, 4, 1)
        self.grid.addWidget(self.alignedLabel, 5, 0)
        self.grid.addWidget(self.aligned, 5, 1)
        self.grid.addWidget(self.addEntry, 6, 1)


    def patternTable(self):
        self.patterns = QTableWidget()
        self.patterns.setShowGrid(False)
        self.patterns.setColumnCount(5)
        self.patterns.setHorizontalHeaderLabels(["Filetype", "Header", "Footer", "Window", "Block aligned"])
        self.patterns.horizontalHeader().setStretchLastSection(True)
        self.connect(self.patterns.verticalHeader(), SIGNAL("sectionClicked(int)"), self.patterns.removeRow)
        self.grid.addWidget(self.patterns, 7, 0, 1, 3)
        

    def warning(self, msg):
        msgBox = QMessageBox(self)
        msgBox.setText(msg)
        msgBox.setIcon(QMessageBox.Warning)
        msgBox.exec_()

    def validate(self, **kwargs):
        msg = ""

        if len(kwargs["type"]) == 0:
            msg = "Type must be defined"
        else:
            for i in kwargs["type"]:
                if i not in string.letters:
                    msg = "Type's characters must be in the following set\n\n" + string.letters
                    break
            rowCount = self.patterns.rowCount()
            for row in range(0, rowCount):
                if str(self.patterns.item(row, 0).text()) == kwargs["type"]:
                    msg = "Type <" + kwargs["type"] + " > already defined"
        if msg != "":
            self.warning(msg)
            return False

        if kwargs["headerType"] == "Hexadecimal" and not self.isHex(kwargs["header"]):
            msg = "Header must be an even number of chars"
            self.warning(msg)
            return False
        
        if len(kwargs["header"]) == 0:
            msg = "Header must be provided"
            self.warning(msg)
            return False

        if kwargs["footerType"] == "Hexadecimal" and not self.isHex(kwargs["header"]):
            msg = "Footer must be an even number of chars"
            self.warning(msg)
            return False

        if kwargs["window"] <= 0:
            msg = "Window size must be greater than 0"
            self.warning(msg)
            return False

        return True


    def insertPattern(self):
        filetype = str(self.filetype.text())
        header = str(self.headerEntry.text())
        headerType = str(self.headerType.currentText())
        footer = str(self.footerEntry.text())
        footerType = str(self.footerType.currentText())
        window = self.window.text()
        aligned = self.aligned.isChecked()

        #Validate most of provided items
        kwargs = {"type": filetype, "header": header, "headerType": headerType, 
                  "footer": footer, "footerType": footerType, "window": int(window.replace(" bytes", ""))}
        if not self.validate(**kwargs):
            return

        filetypeItem = QTableWidgetItem(filetype)
        headerItem = QTableWidgetItem(header + " (" + headerType[0:3] + ")")
        footerItem = QTableWidgetItem(footer + " (" + footerType[0:3] + ")")
        windowItem = QTableWidgetItem(window)
        alignedItem = QTableWidgetItem(str(aligned))
        self.patterns.insertRow(self.patterns.rowCount())
        vertHeader = QTableWidgetItem(QIcon(":closetab.png"), "")
        row = self.patterns.rowCount() - 1
        self.patterns.setVerticalHeaderItem(row, vertHeader)
        self.patterns.setItem(row, 0, filetypeItem)
        self.patterns.setItem(row, 1, headerItem)
        self.patterns.setItem(row, 2, footerItem)
        self.patterns.setItem(row, 3, windowItem)
        self.patterns.setItem(row, 4, alignedItem)
        self.patterns.resizeRowToContents(row)

        
    def isHex(self, str):
        HEXCHAR = "0123456789abcdefABCDEF"
        hexStr = ""
        even = False
        for i in range(len(str)):
            if str[i] in HEXCHAR:
                if even == True:
                    even = False
                else:
                    even = True
            else:
                return False
        if even:
            return False
        return True
    

    def toHex(self, str):
        HEXCHAR = "0123456789abcdefABCDEF"
        hexStr = ""
        evenhex = ""
        for i in range(len(str)):
            if str[i] in HEXCHAR:
                if len(evenhex) == 1:
                    hexStr += chr(int(evenhex+str[i], 16))
                    evenhex = ""
                else:
                    evenhex = str[i]
            else:
                raise ValueError, "argument 'str' contains not valid characters"
        if len(evenhex) != 0:
            raise ValueError, "argument 'str' must be an even number of char"
        return hexStr


    def textToPattern(self, text):
        idx = text.find("(")
        pattern = ""
        if idx != -1:
            type = text[idx+1:idx+4]
            pattern = text[0:idx-1]
            if type == "Hex":
                pattern = self.toHex(pattern)
        return pattern


    def selectedItems(self):
        selected = {}
        rowCount = self.patterns.rowCount()
        for row in range(0, rowCount):
            filetype = str(self.patterns.item(row, 0).text())
            selected[filetype] = []
            pattern = []
            pattern.append(self.textToPattern(str(self.patterns.item(row, 1).text())))
            pattern.append(self.textToPattern(str(self.patterns.item(row, 2).text())))
            pattern.append(int(self.patterns.item(row, 3).text().replace(" bytes", "")))
            selected[filetype].append([pattern])
            if self.patterns.item(row, 4).text() == "True":
                selected[filetype].append(True)
            else:
                selected[filetype].append(False)
        return selected
Beispiel #43
0
class ScanRecordTable(QGroupBox):
    """ GUI component. Displays a list of previous scan results. Selecting a scan causes
    details of the scan to appear in other GUI components (list of barcodes in the barcode
    table and image of the puck in the image frame).
    """
    COLUMNS = [
        'Date', 'Time', 'Plate Barcode', 'Plate Type', 'Valid', 'Invalid',
        'Empty'
    ]

    def __init__(self, barcode_table, image_frame, options,
                 to_run_on_table_clicked):
        super(ScanRecordTable, self).__init__()

        # Read the store from file
        self._store = Store(options.store_directory.value(),
                            options.store_capacity, FileManager())
        self._options = options

        self._barcodeTable = barcode_table
        self._imageFrame = image_frame

        self.setTitle("Scan Records")
        self._init_ui(to_run_on_table_clicked)

        self._load_store_records()

    def _init_ui(self, to_run_on_table_clicked):
        # Create record table - lists all the records in the store
        self._table = QTableWidget()
        self._table.setFixedWidth(440)
        self._table.setFixedHeight(600)
        self._table.setColumnCount(len(self.COLUMNS))
        self._table.setHorizontalHeaderLabels(self.COLUMNS)
        self._table.setColumnWidth(0, 70)
        self._table.setColumnWidth(1, 55)
        self._table.setColumnWidth(2, 85)
        self._table.setColumnWidth(3, 70)
        self._table.setColumnWidth(4, 45)
        self._table.setColumnWidth(5, 50)
        self._table.setColumnWidth(6, 45)
        self._table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        self._table.cellPressed.connect(to_run_on_table_clicked)
        self._table.cellPressed.connect(self._record_selected)

        # Delete button - deletes selected records
        btn_delete = QtGui.QPushButton('Delete')
        btn_delete.setToolTip('Delete selected scan/s')
        btn_delete.resize(btn_delete.sizeHint())
        btn_delete.clicked.connect(self._delete_selected_records)

        hbox = QHBoxLayout()
        hbox.setSpacing(10)
        hbox.addWidget(btn_delete)
        hbox.addStretch(1)

        vbox = QVBoxLayout()
        vbox.addWidget(self._table)
        vbox.addLayout(hbox)

        self.setLayout(vbox)

    def add_record_frame(self, holder_barcode, plate, holder_img, pins_img):
        """ Add a new scan frame - creates a new record if its a new puck, else merges with previous record"""
        self._store.merge_record(holder_barcode, plate, holder_img, pins_img)
        self._load_store_records()
        if self._options.scan_clipboard.value():
            self._barcodeTable.copy_to_clipboard()

    def _load_store_records(self):
        """ Populate the record table with all of the records in the store.
        """
        self._table.clearContents()
        self._table.setRowCount(self._store.size())

        for n, record in enumerate(self._store.records):
            items = [
                record.date, record.time, record.holder_barcode,
                record.plate_type, record.num_valid_barcodes,
                record.num_unread_slots, record.num_empty_slots
            ]

            if (record.num_valid_barcodes +
                    record.num_empty_slots) == record.num_slots:
                color = self._options.col_ok()
            else:
                color = self._options.col_bad()

            color.a = 192
            for m, item in enumerate(items):
                new_item = QtGui.QTableWidgetItem(str(item))
                new_item.setBackgroundColor(color.to_qt())
                new_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                self._table.setItem(n, m, new_item)

        # Display the first (most recent) record
        self._table.setCurrentCell(0, 0)
        self._record_selected()

    def _record_selected(self):
        """ Called when a row is selected, causes details of the selected record to be
        displayed (list of barcodes in the barcode table and image of the scan in the
        image frame).
        """
        try:
            row = self._table.selectionModel().selectedRows()[0].row()
            record = self._store.get_record(row)
            self._barcodeTable.populate(record.holder_barcode, record.barcodes)
            marked_image = record.marked_image(self._options)
            self._imageFrame.display_puck_image(marked_image)
        except IndexError:
            self._barcodeTable.clear()
            self._imageFrame.clear_frame(
                "Record table empty\nNothing to display")

    def _delete_selected_records(self):
        """ Called when the 'Delete' button is pressed. Deletes all of the selected records
        (and the associated images) from the store and from disk. Asks for user confirmation.
        """
        # Display a confirmation dialog to check that user wants to proceed with deletion
        quit_msg = "This operation cannot be undone.\nAre you sure you want to delete these record/s?"
        reply = QtGui.QMessageBox.warning(self, 'Confirm Delete', quit_msg,
                                          QtGui.QMessageBox.Yes,
                                          QtGui.QMessageBox.No)

        # If yes, find the appropriate records and delete them
        if reply == QtGui.QMessageBox.Yes:
            rows = self._table.selectionModel().selectedRows()
            records_to_delete = []
            for row in rows:
                index = row.row()
                record = self._store.get_record(index)
                records_to_delete.append(record)

            self._store.delete_records(records_to_delete)
            self._load_store_records()

    def is_latest_holder_barcode(self, holder_barcode):
        return self._store.is_latest_holder_barcode(holder_barcode)
Beispiel #44
0
class wavListDialog(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.prm = self.parent().parent().prm
        self.audioManager = audioManager(self)
        self.currLocale = self.parent().parent().prm['currentLocale']
        self.currLocale.setNumberOptions(
            self.currLocale.OmitGroupSeparator
            | self.currLocale.RejectGroupSeparator)
        self.isPlaying = False

        self.sizer = QGridLayout()
        self.v1Sizer = QVBoxLayout()

        self.wavsTableWidget = QTableWidget()
        self.wavsTableWidget.setColumnCount(4)
        self.wavsTableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.wavsTableWidget.setSelectionMode(
            QAbstractItemView.ExtendedSelection)

        self.wavsTableWidget.setHorizontalHeaderLabels(
            [self.tr("File"),
             self.tr('Use'),
             self.tr("RMS Level"), 'id'])
        self.quidColumn = 3
        self.wavsTableWidget.hideColumn(self.quidColumn)
        self.wavsTableWidget.cellDoubleClicked[int, int].connect(
            self.onCellDoubleClicked)

        #ADD wav BUTTON
        self.addWavButton = QPushButton(self.tr("Add Wav"), self)
        self.addWavButton.clicked.connect(self.onClickAddWavButton)
        #REMOVE wav BUTTON
        self.removeWavButton = QPushButton(self.tr("Remove Wav"), self)
        self.removeWavButton.clicked.connect(self.onClickRemoveWavButton)

        #PLAY wav BUTTON
        self.playWavButton = QPushButton(self.tr("Play Wav"), self)
        self.playWavButton.clicked.connect(self.onClickPlayWavButton)
        #STOP wav BUTTON
        self.stopWavButton = QPushButton(self.tr("Stop Playing"), self)
        self.stopWavButton.clicked.connect(self.onClickStopWavButton)

        self.v1Sizer.addWidget(self.addWavButton)
        self.v1Sizer.addWidget(self.removeWavButton)
        self.v1Sizer.addWidget(self.playWavButton)
        self.v1Sizer.addWidget(self.stopWavButton)

        self.v1Sizer.addStretch()

        self.wavsList = {}

        for i in range(len(self.parent().wavsPref['endMessageFiles'])):
            currCount = i + 1
            thisID = self.parent().wavsPref['endMessageFilesID'][i]
            self.wavsList[thisID] = {}
            self.wavsList[thisID]['file'] = self.parent(
            ).wavsPref['endMessageFiles'][i]
            self.wavsList[thisID]['use'] = self.parent(
            ).wavsPref['endMessageFilesUse'][i]
            self.wavsList[thisID]['level'] = self.parent(
            ).wavsPref['endMessageLevels'][i]
            self.wavsTableWidget.setRowCount(currCount)
            n = 0
            newItem = QTableWidgetItem(self.wavsList[thisID]['file'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount - 1, n, newItem)
            n = n + 1
            newItem = QTableWidgetItem(self.wavsList[thisID]['use'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount - 1, n, newItem)
            n = n + 1
            newItem = QTableWidgetItem(
                self.currLocale.toString(self.wavsList[thisID]['level']))
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount - 1, n, newItem)
            n = n + 1
            self.wavsList[thisID]['qid'] = QTableWidgetItem(thisID)
            self.wavsTableWidget.setItem(currCount - 1, n,
                                         self.wavsList[thisID]['qid'])

        buttonBox = QDialogButtonBox(QDialogButtonBox.Apply
                                     | QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        self.sizer.addLayout(self.v1Sizer, 0, 0)
        self.sizer.addWidget(self.wavsTableWidget, 0, 1)
        self.sizer.addWidget(buttonBox, 1, 1)
        self.setLayout(self.sizer)
        self.setWindowTitle(self.tr("Edit Wavs"))
        self.show()

    def onCellDoubleClicked(self, row, col):
        if col == 0:
            pass
        elif col == 1:
            self.onEditUse()
        elif col == 2:
            self.onEditLevel()

    def onEditLevel(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(
                self, self.tr('Warning'),
                self.tr('Only one item can be edited at a time'))
        elif len(ids) < 1:
            pass
        else:
            selectedSound = ids[0]
            msg = self.tr('RMS Level:')
            text, ok = QInputDialog.getDouble(
                self, self.tr('Input Dialog'), msg,
                self.wavsList[selectedSound]['level'])
            if ok:
                self.wavsTableWidget.item(
                    self.wavsList[selectedSound]['qid'].row(),
                    2).setText(self.currLocale.toString(text))
                self.wavsList[selectedSound]['level'] = text

    def onEditUse(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(
                self, self.tr('Warning'),
                self.tr('Only one item can be edited at a time'))
        elif len(ids) < 1:
            pass
        else:
            selectedSound = ids[0]
            if self.wavsTableWidget.item(
                    self.wavsList[selectedSound]['qid'].row(),
                    1).text() == "\u2012":
                self.wavsTableWidget.item(
                    self.wavsList[selectedSound]['qid'].row(),
                    1).setText("\u2713")
                self.wavsList[selectedSound]['use'] = "\u2713"
            else:
                self.wavsTableWidget.item(
                    self.wavsList[selectedSound]['qid'].row(),
                    1).setText("\u2012")
                self.wavsList[selectedSound]['use'] = "\u2012"

    def findSelectedItemIds(self):
        selItems = self.wavsTableWidget.selectedItems()
        selItemsRows = []
        for i in range(len(selItems)):
            selItemsRows.append(selItems[i].row())
        selItemsRows = unique(selItemsRows)
        selItemsIds = []
        for i in range(len(selItemsRows)):
            selItemsIds.append(
                str(
                    self.wavsTableWidget.item(selItemsRows[i],
                                              self.quidColumn).text()))
        return selItemsIds

    def permanentApply(self):
        self.wavListToPass = {}
        self.wavListToPass['endMessageFiles'] = []
        self.wavListToPass['endMessageFilesUse'] = []
        self.wavListToPass['endMessageFilesID'] = []
        self.wavListToPass['endMessageLevels'] = []

        keys = sorted(self.wavsList.keys())
        for key in keys:
            self.wavListToPass['endMessageFiles'].append(
                str(self.wavsList[key]['file']))
            self.wavListToPass['endMessageFilesUse'].append(
                self.wavsList[key]['use'])
            self.wavListToPass['endMessageLevels'].append(
                self.wavsList[key]['level'])
            self.wavListToPass['endMessageFilesID'].append(key)

    def onClickAddWavButton(self):
        fName = QFileDialog.getOpenFileName(
            self, self.tr("Choose wav file to load"), '',
            self.tr("wav files (*.wav);;All Files (*)"))[0]
        if len(fName) > 0:  #if the user didn't press cancel

            if len(self.wavsList.keys()) > 0:
                keys = sorted(self.wavsList.keys())
                thisID = str(int(keys[-1]) + 1)
            else:
                thisID = "1"
            currCount = self.wavsTableWidget.rowCount() + 1

            self.wavsList[thisID] = {}
            self.wavsList[thisID]['file'] = fName
            self.wavsList[thisID]['use'] = "\u2713"
            self.wavsList[thisID]['level'] = 60
            self.wavsTableWidget.setRowCount(currCount)
            n = 0
            newItem = QTableWidgetItem(self.wavsList[thisID]['file'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount - 1, n, newItem)
            n = n + 1
            newItem = QTableWidgetItem(self.wavsList[thisID]['use'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount - 1, n, newItem)
            n = n + 1
            newItem = QTableWidgetItem(
                self.currLocale.toString(self.wavsList[thisID]['level']))
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.wavsTableWidget.setItem(currCount - 1, n, newItem)
            n = n + 1
            self.wavsList[thisID]['qid'] = QTableWidgetItem(thisID)
            self.wavsTableWidget.setItem(currCount - 1, n,
                                         self.wavsList[thisID]['qid'])

    def onClickRemoveWavButton(self):
        ids = self.findSelectedItemIds()
        for i in range(len(ids)):
            selectedWavs = ids[i]
            self.wavsTableWidget.removeRow(
                self.wavsList[selectedWavs]['qid'].row())
            del self.wavsList[selectedWavs]

    def onClickPlayWavButton(self):
        ids = self.findSelectedItemIds()
        if len(ids) < 1:
            QMessageBox.warning(self, self.tr('Warning'),
                                self.tr('No files selected for playing'))
        else:
            if len(ids) > 1:
                pass  #maybe say on the status bar that only the first one will be played
            selectedWav = ids[0]
            fName = self.wavsList[selectedWav]['file']
            level = self.wavsList[selectedWav]['level']
            nBits = self.currLocale.toInt(
                self.parent().parent().nBitsChooser.currentText())[0]
            maxLevel = float(self.prm['phones']['phonesMaxLevel'][
                self.parent().parent().phonesChooser.currentIndex()])
            msgSnd, fs = self.audioManager.loadWavFile(fName, level, maxLevel,
                                                       'Both')
            self.isPlaying = True
            if self.prm['pref']['sound']['playCommand'] in [
                    "alsaaudio", "pyaudio"
            ]:
                self.playThread = threadedAudioPlayer(self.parent().parent())
            else:
                self.playThread = threadedExternalAudioPlayer(
                    self.parent().parent())
            self.playThread.playThreadedSound(
                msgSnd, fs, nBits, self.prm['pref']['sound']['playCommand'],
                False, 'tmp.wav')
            if self.playThread.isFinished == True:
                self.isPlaying = False

    def onClickStopWavButton(self):
        if self.isPlaying == True:
            self.playThread.terminate()

    def closeEvent(self, event):
        if self.isPlaying == True:
            self.playThread.terminate()
        event.accept()

    def accept(self):  #reimplement accept (i.e. ok button)
        if self.isPlaying == True:
            self.playThread.terminate()
        QDialog.accept(self)

    def reject(self):  #reimplement reject
        if self.isPlaying == True:
            self.playThread.terminate()
        QDialog.reject(self)
    def __init__(self, named_importances, *args, **kwargs):
        super(VariableImportanceDialog, self).__init__(*args, **kwargs)
        self.setWindowTitle("Variable Importance Table")
        self.setMinimumWidth(700)
        self.setMinimumHeight(800)

        layout = QGridLayout() 
        layout.setContentsMargins(10, 10, 10, 10)
               
        if named_importances:
            # Show variable importance table
            rows = len(named_importances.items())
            columns = 5
            table = QTableWidget(rows, columns)   
            table.setHorizontalHeaderLabels(['Variable Name', 'Class #0', 'Class #1', 'Overall', 'Gini'])
            table.verticalHeader().setVisible(False)      
            
            importances_mins = map(min, zip(*named_importances.values()))
            importances_maxs = map(max, zip(*named_importances.values()))
            
            for i, (variable, importances) in enumerate(named_importances.items()):     
                # Remove non-ASCII characters to get rid of the sigma character in the variable names.
                variable = re.sub(r'[^\x00-\x7F]+','s', variable)
                
                item = QTableWidgetItem(variable)
                item.setFlags( Qt.ItemIsSelectable |  Qt.ItemIsEnabled )
                table.setItem(i, 0, item)

                for j, importance in enumerate(importances):
                    # Get color based on the importance value
                    val = importances[j]
                    imin = importances_mins[j]
                    imax = importances_maxs[j]
                    range = importances_maxs[j] - importances_mins[j]
                    color = int( 255 - ( (val-imin) * 200) / range )    

                    # Load items as strings
                    item = QTableWidgetItemWithFloatSorting(str("{: .05f}".format(importance)))
                    item.setFlags( Qt.ItemIsSelectable |  Qt.ItemIsEnabled )
                    item.setBackground(QColor(color,255,color))
                    table.setItem(i, j+1, item)
                    
            table.resizeColumnsToContents()  
            
            table.setSortingEnabled(True)
            table.sortByColumn(3) # Sort by overall importance

            layout.addWidget(table, 1, 0, 3, 2)  
            
        else:
            # Classifier is not trained. Show warning message.
            msg = ('To enable this feature, you must choose the following classifier type via the menu Advanced > Classifier:\n\n'
                   '"Parallel Random Forest Classifier with Variable Importance (VIGRA)"\n\n'
                   '...and then RETRAIN your classifier (press "Live Update").')
            warningLabel = QLabel(msg)
            warningLabel.setAlignment(Qt.AlignCenter)
            warningLabel.setWordWrap(True) 
            layout.addWidget(warningLabel, 3, 0, 1 ,2)

        # Create and add close button
        closeButton = QPushButton("Close")
        closeButton.clicked.connect(self.close)
        layout.addWidget(closeButton, 4, 1)
        
        self.setLayout(layout)
Beispiel #46
0
    def initUI(self):               

        exitAction = QtGui.QAction('Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)

#         infoAction = QtGui.q
#         infoAction.triggered.connect()
        
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('File')
        fileMenu.addAction(exitAction)
        fileMenu = menubar.addMenu('Help');
#         fileMenu.addAction(infoAction)
        
        # toolbar = self.addToolBar('Exit')
        # toolbar.addAction(exitAction)
        
        # Button
#         redb = QtGui.QPushButton('Play', self)
#         redb.move(10, 22)
        
        # Slider
        sld = QtGui.QSlider(QtCore.Qt.Horizontal, self)
        # Do not accept keyboard shortcuts to focus
        sld.setFocusPolicy(QtCore.Qt.NoFocus)
        # Initial X, Initial Y, Width, Height
        sld.setGeometry(10, 210, 500, 15)
        sld.valueChanged[int].connect(self.updateSlider)
        
        # Table of songs
        table = QTableWidget(self)
        table.setColumnCount(4)
        table.setRowCount(4)
        table.setHorizontalHeaderLabels(['Title', 'Artist', 'Album', 'Year'])
        table.move(10, 30)
        table.resize(580, 170)
        table.setColumnWidth(0, 250)
        table.setColumnWidth(1, 130)
        table.setColumnWidth(2, 120)
        table.setColumnWidth(3, 60)
        
        # Play
        self.playb = QtGui.QLabel(self)
        # Todo: Change icon
        self.playb.setPixmap(QtGui.QPixmap('D:\Documents\Pictures\L.jpg'))
        self.playb.setGeometry(15, 235, 40, 40)
        self.playb.setScaledContents(True)
        self.connect(self.playb, QtCore.SIGNAL("clicked()"), self.play)
        self.playb.pressed.connect(self.play)
        
        # Pause
        self.label = QtGui.QLabel(self)
        # Todo: Change icon
        self.label.setPixmap(QtGui.QPixmap('D:\Documents\Pictures\L.jpg'))
        self.label.setGeometry(65, 235, 40, 40)
        self.label.setScaledContents(True)
        
        # Timer
        self.timer = QtGui.QLabel(self)
        # Todo: Change icon
        self.timer.setText("00:00")
        self.timer.setStyleSheet("font: 15pt;")
        self.timer.setGeometry(520, 195, 60, 40)
        self.timer.setScaledContents(True)
        
        # Initial X, Initial Y, Width, Height
        self.setGeometry(100, 100, 600, 300)
        self.setWindowTitle('Music Player')
        # Todo: Change icon path
        self.setWindowIcon(QtGui.QIcon('D:\Documents\Pictures\L.jpg'))           
        self.show()
Beispiel #47
0
class OWxsh_waviness(widget.OWWidget):
    name = "xsh_waviness"
    id = "orange.widgets.preprocessor.xsh_waviness"
    description = "xoppy application to compute..."
    icon = "icons/waviness.png"
    author = "Luca Rebuffi"
    maintainer_email = "[email protected]; [email protected]"
    priority = 10
    category = ""
    keywords = ["xoppy", "xsh_waviness"]

    outputs = [{"name": "PreProcessor_Data",
                "type": ShadowPreProcessorData,
                "doc": "PreProcessor Data",
                "id": "PreProcessor_Data"}]

    want_main_area = 1
    want_control_area = 1

    WIDGET_WIDTH = 1100
    WIDGET_HEIGHT = 650

    xx = None
    yy = None
    zz = None

    number_of_points_x = Setting(10)
    number_of_points_y = Setting(100)

    dimension_x = Setting(20.1)
    dimension_y = Setting(113.1)

    estimated_slope_error = Setting(0.9)
    montecarlo_seed = Setting(2387427)

    waviness_file_name = Setting('waviness.dat')

    harmonic_maximum_index = Setting(60)

    data = Setting({'c': ['0.3',
                          '0.1',
                          '0.1',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.3',
                          '0.0',
                          '0.0',
                          '0.3',
                          '0.0',
                          '0.0',
                          '0.5',
                          '0.0',
                          '0.0',
                          '0.2',
                          '0.2',
                          '0.2',
                          '0.9',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.4',
                          '0.0',
                          '0.0',
                          '0.4',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.6',
                          '0.6',
                          '0.0',
                          '0.4',
                          '0.4',
                          '0.0',
                          '0.4',
                          '0.4',
                          '0.1',
                          '0.4',
                          '0.4',
                          '0.1',
                          '0.2',
                          '0.2',
                          '0.0',
                          '0.2',
                          '0.2',
                          '0.0',
                          '0.3',
                          '0.3',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.0'],
                    'y': ['0.0',
                          '-0.1',
                          '-0.1',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.03',
                          '0.0',
                          '0.0',
                          '0.2',
                          '0.0',
                          '0.0',
                          '0.2',
                          '0.0',
                          '0.0',
                          '0.1',
                          '0.1',
                          '0.1',
                          '0.1',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.01',
                          '0.0',
                          '0.0',
                          '0.03',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.02',
                          '0.02',
                          '0.0',
                          '0.1',
                          '0.1',
                          '0.0',
                          '0.1',
                          '0.1',
                          '0.0',
                          '0.1',
                          '0.1',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.3',
                          '0.3',
                          '0.0',
                          '0.2',
                          '0.2',
                          '0.0',
                          '0.2',
                          '0.2',
                          '0.0',
                          '0.2',
                          '0.2',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.0'],
                    'g': ['0.0',
                          '0.3',
                          '0.3',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.05',
                          '0.0',
                          '0.0',
                          '0.05',
                          '0.0',
                          '0.0',
                          '0.1',
                          '0.0',
                          '0.0',
                          '0.05',
                          '0.05',
                          '0.05',
                          '0.2',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.1',
                          '0.0',
                          '0.0',
                          '0.1',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.2',
                          '0.2',
                          '0.0',
                          '0.1',
                          '0.1',
                          '0.0',
                          '0.1',
                          '0.1',
                          '0.0',
                          '0.1',
                          '0.1',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.1',
                          '0.1',
                          '0.0',
                          '0.2',
                          '0.2',
                          '0.0',
                          '0.1',
                          '0.1',
                          '0.0',
                          '0.1',
                          '0.1',
                          '0.0',
                          '0.0',
                          '0.0',
                          '0.0']})

    def __init__(self):
        super().__init__()

        geom = QApplication.desktop().availableGeometry()
        self.setGeometry(QRect(round(geom.width() * 0.05),
                               round(geom.height() * 0.05),
                               round(min(geom.width() * 0.98, self.WIDGET_WIDTH)),
                               round(min(geom.height() * 0.95, self.WIDGET_HEIGHT))))

        gen_box = ShadowGui.widgetBox(self.controlArea, "Waviness Parameters", addSpace=True, orientation="horizontal",
                                      width=500)

        tabs_setting = gui.tabWidget(gen_box)

        tab_input = ShadowGui.createTabPage(tabs_setting, "Input Parameter")
        tab_harmonics = ShadowGui.createTabPage(tabs_setting, "Harmonics")
        tab_out = ShadowGui.createTabPage(tabs_setting, "Output")

        self.input_box = ShadowGui.widgetBox(tab_input, "Inputs", addSpace=True, orientation="vertical", width=470)

        gui.button(self.input_box, self, "Load xsh_waviness input file ...", callback=self.load_inp_file)

        gui.separator(self.input_box)

        ShadowGui.lineEdit(self.input_box, self, "number_of_points_x", "Number of Points (<201)           X (width)",
                           labelWidth=300, valueType=int, orientation="horizontal")
        ShadowGui.lineEdit(self.input_box, self, "number_of_points_y",
                           "                                                 Y (length)", labelWidth=300, valueType=int,
                           orientation="horizontal")

        gui.separator(self.input_box)

        ShadowGui.lineEdit(self.input_box, self, "dimension_x", "Dimensions [cm]                        X (width)",
                           labelWidth=300, valueType=float, orientation="horizontal")
        ShadowGui.lineEdit(self.input_box, self, "dimension_y",
                           "                                                 Y (length)", labelWidth=300,
                           valueType=float, orientation="horizontal")

        gui.separator(self.input_box)

        ShadowGui.lineEdit(self.input_box, self, "estimated_slope_error", "Estimated slope error [arcsec]",
                           labelWidth=300, valueType=float, orientation="horizontal")
        ShadowGui.lineEdit(self.input_box, self, "montecarlo_seed", "Monte Carlo initial seed", labelWidth=300,
                           valueType=int, orientation="horizontal")

        self.output_box = ShadowGui.widgetBox(tab_input, "Outputs", addSpace=True, orientation="vertical", width=470)

        self.select_file_box = ShadowGui.widgetBox(self.output_box, "", addSpace=True, orientation="horizontal")

        gui.separator(self.output_box)

        gui.button(self.output_box, self, "Write xsh_waviness input file (optional) ...", callback=self.write_inp_file)

        ShadowGui.lineEdit(self.select_file_box, self, "waviness_file_name", "Output File Name", labelWidth=120,
                           valueType=str, orientation="horizontal")

        self.harmonics_box = ShadowGui.widgetBox(tab_harmonics, "Harmonics", addSpace=True, orientation="vertical",
                                                 width=470, height=690)

        ShadowGui.lineEdit(self.harmonics_box, self, "harmonic_maximum_index", "Harmonic Maximum Index", labelWidth=300,
                           valueType=int, orientation="horizontal", callback=self.set_harmonics)

        gui.separator(self.harmonics_box)

        self.scrollarea = QScrollArea()
        self.scrollarea.setMaximumWidth(400)

        self.harmonics_box.layout().addWidget(self.scrollarea, alignment=Qt.AlignHCenter)

        self.shadow_output = QTextEdit()
        self.shadow_output.setReadOnly(True)

        out_box = ShadowGui.widgetBox(tab_out, "System Output", addSpace=True, orientation="horizontal", height=600)
        out_box.layout().addWidget(self.shadow_output)

        button_box = ShadowGui.widgetBox(self.controlArea, "", addSpace=False, orientation="horizontal")

        button = gui.button(button_box, self, "Calculate Waviness", callback=self.calculate_waviness)
        button.setFixedHeight(45)
        button.setFixedWidth(170)

        button = gui.button(button_box, self, "Generate Waviness File", callback=self.generate_waviness_file)
        font = QFont(button.font())
        font.setBold(True)
        button.setFont(font)
        palette = QPalette(button.palette())  # make a copy of the palette
        palette.setColor(QPalette.ButtonText, QColor('Dark Blue'))
        button.setPalette(palette)  # assign new palette
        button.setFixedHeight(45)
        button.setFixedWidth(200)

        button = gui.button(button_box, self, "Reset Fields", callback=self.call_reset_settings)
        font = QFont(button.font())
        font.setItalic(True)
        button.setFont(font)
        palette = QPalette(button.palette())  # make a copy of the palette
        palette.setColor(QPalette.ButtonText, QColor('Dark Red'))
        button.setPalette(palette)  # assign new palette
        button.setFixedHeight(45)
        button.setFixedWidth(120)

        gui.rubber(self.controlArea)

        self.figure = Figure(figsize=(600, 600))
        self.figure.patch.set_facecolor('white')

        self.axis = self.figure.add_subplot(111, projection='3d')

        self.axis.set_xlabel("X (cm)")
        self.axis.set_ylabel("Y (cm)")
        self.axis.set_zlabel("Z (µm)")

        self.figure_canvas = FigureCanvasQTAgg(self.figure)
        self.mainArea.layout().addWidget(self.figure_canvas)

        gui.rubber(self.mainArea)

    def restoreWidgetPosition(self):
        super().restoreWidgetPosition()

        self.table = QTableWidget(self.harmonic_maximum_index + 1, 3)
        self.table.setAlternatingRowColors(True)
        self.table.horizontalHeader().setResizeMode(QHeaderView.Fixed)

        for i in range(0, 3):
            self.table.setColumnWidth(i, 70)

        horHeaders = []
        verHeaders = []

        for n, key in enumerate(sorted(self.data.keys())):
            horHeaders.append(key)

            for m, item in enumerate(self.data[key]):
                table_item = QTableWidgetItem(str(item))
                table_item.setTextAlignment(Qt.AlignRight)
                self.table.setItem(m, n, table_item)
                verHeaders.append(str(m))

        self.table.setHorizontalHeaderLabels(horHeaders)
        self.table.setVerticalHeaderLabels(verHeaders)
        self.table.resizeRowsToContents()

        self.table.itemChanged.connect(self.table_item_changed)

        self.scrollarea.setWidget(self.table)
        self.scrollarea.setWidgetResizable(1)

        gui.rubber(self.controlArea)

    def reload_harmonics_table(self):
        horHeaders = []
        verHeaders = []

        self.table.itemChanged.disconnect(self.table_item_changed)

        self.table.clear()

        row_count = self.table.rowCount()

        for n in range(0, row_count):
            self.table.removeRow(0)

        for index in range(0, self.harmonic_maximum_index + 1):
            self.table.insertRow(0)

        for n, key in enumerate(sorted(self.data.keys())):
            horHeaders.append(key)

            for m, item in enumerate(self.data[key]):
                table_item = QTableWidgetItem(str(item))
                table_item.setTextAlignment(Qt.AlignRight)
                self.table.setItem(m, n, table_item)
                verHeaders.append(str(m))

        self.table.setHorizontalHeaderLabels(horHeaders)
        self.table.setVerticalHeaderLabels(verHeaders)

        self.table.resizeRowsToContents()

        for i in range(0, 3):
            self.table.setColumnWidth(i, 70)

        self.table.itemChanged.connect(self.table_item_changed)

    def table_item_changed(self):
        dict = {}
        message = ""
        error_row_index = -1
        error_column_index = -1
        previous_value = ""

        try:
            row_count = self.harmonic_maximum_index + 1

            for column_index in range(0, self.table.columnCount()):
                column_name = self.table.horizontalHeaderItem(column_index).data(0)

                row_content = []

                for row_index in range(0, row_count):
                    if not self.table.item(row_index, column_index) is None:
                        message = "Value at row " + str(
                            row_index) + " and column \'" + column_name + "\' is not numeric"
                        error_row_index = row_index
                        error_column_index = column_index
                        previous_value = self.data[column_name][row_index]

                        value = float(self.table.item(row_index, column_index).data(0))  # to raise exception

                        row_content.append(str(value))

                dict[column_name] = row_content

            self.data = dict
        except ValueError:
            QMessageBox.critical(self, "QMessageBox.critical()",
                                 message + "\nValue is reset to previous value",
                                 QMessageBox.Ok)

            table_item = QTableWidgetItem(previous_value)
            table_item.setTextAlignment(Qt.AlignRight)
            self.table.setItem(error_row_index, error_column_index, table_item)
            self.table.setCurrentCell(error_row_index, error_column_index)

        except Exception as exception:
            QMessageBox.critical(self, "QMessageBox.critical()",
                                 exception.args[0],
                                 QMessageBox.Ok)

    def set_harmonics(self):
        if self.harmonic_maximum_index < 0:
            QMessageBox.critical(self, "QMessageBox.critical()",
                                 "Harmonic Maximum Index should be a positive integer number",
                                 QMessageBox.Ok)
        else:
            row_count = len(self.data["c"])

            if self.harmonic_maximum_index + 1 > row_count:
                for n, key in enumerate(sorted(self.data.keys())):
                    for m in range(row_count, self.harmonic_maximum_index + 1):
                        self.data[key].append('0.0')
            else:
                for n, key in enumerate(sorted(self.data.keys())):
                    self.data[key] = copy.deepcopy(self.data[key][0: self.harmonic_maximum_index + 1])

            self.reload_harmonics_table()

    def load_inp_file(self):
        file_name = QFileDialog.getOpenFileName(self, "Select a input file for XSH_WAVINESS", ".", "*.inp")

        if not file_name is None:
            sys.stdout = EmittingStream(textWritten=self.writeStdOut)

            if not file_name.strip() == "":
                dict = ST.waviness_read(file=file_name)

                self.number_of_points_x = dict["npointx"]
                self.number_of_points_y = dict["npointy"]
                self.dimension_y = dict["xlength"]
                self.dimension_x = dict["width"]
                self.estimated_slope_error = dict["slp"]
                self.montecarlo_seed = dict["iseed"]
                self.waviness_file_name = dict["file"].strip('\n\r').strip()
                self.harmonic_maximum_index = dict["nharmonics"]

                self.data["c"] = self.to_str_array(dict["c"])
                self.data["y"] = self.to_str_array(dict["y"])
                self.data["g"] = self.to_str_array(dict["g"])

                self.reload_harmonics_table()

    def write_inp_file(self):
        try:
            sys.stdout = EmittingStream(textWritten=self.writeStdOut)

            self.check_fields()

            file_name = self.waviness_file_name.strip().split(sep=".dat")[0] + ".inp"

            dict = {}

            dict["npointx"] = self.number_of_points_x
            dict["npointy"] = self.number_of_points_y
            dict["xlength"] = self.dimension_y
            dict["width"] = self.dimension_x
            dict["slp"] = self.estimated_slope_error
            dict["iseed"] = self.montecarlo_seed
            dict["file"] = self.waviness_file_name.strip('\n\r')
            dict["nharmonics"] = self.harmonic_maximum_index

            dict["c"] = self.to_float_array(self.data["c"])
            dict["y"] = self.to_float_array(self.data["y"])
            dict["g"] = self.to_float_array(self.data["g"])

            ST.waviness_write(dict, file=file_name)

            QMessageBox.information(self, "QMessageBox.information()",
                                    "File \'" + file_name + "\' written to disk",
                                    QMessageBox.Ok)

        except Exception as exception:
            QMessageBox.critical(self, "QMessageBox.critical()",
                                 exception.args[0],
                                 QMessageBox.Ok)

    def calculate_waviness(self):
        try:
            sys.stdout = EmittingStream(textWritten=self.writeStdOut)

            self.check_fields()

            xx, yy, zz = ST.waviness_calc(npointx=self.number_of_points_x,
                                          npointy=self.number_of_points_y,
                                          width=self.dimension_x,
                                          xlength=self.dimension_y,
                                          slp=self.estimated_slope_error,
                                          nharmonics=self.harmonic_maximum_index,
                                          iseed=self.montecarlo_seed,
                                          c=self.to_float_array(self.data["c"]),
                                          y=self.to_float_array(self.data["y"]),
                                          g=self.to_float_array(self.data["g"]))
            self.xx = xx
            self.yy = yy
            self.zz = zz

            self.axis.clear()

            x_to_plot, y_to_plot = numpy.meshgrid(xx, yy)
            z_to_plot = []

            for y_index in range(0, len(yy)):
                z_array = []
                for x_index in range(0, len(xx)):
                    z_array.append(1e4 * float(zz[x_index][y_index]))  # to micron
                z_to_plot.append(z_array)

            z_to_plot = numpy.array(z_to_plot)

            self.axis.plot_surface(x_to_plot, y_to_plot, z_to_plot,
                                   rstride=1, cstride=1, cmap=cm.autumn, linewidth=0.5, antialiased=True)

            slope, sloperms = ST.slopes(zz, xx, yy)

            title = ' Slope error rms in X direction: %f arcsec' % (sloperms[0]) + '\n' + \
                    '                                            : %f urad' % (sloperms[2]) + '\n' + \
                    ' Slope error rms in Y direction: %f arcsec' % (sloperms[1]) + '\n' + \
                    '                                            : %f urad' % (sloperms[3])

            self.axis.set_xlabel("X (cm)")
            self.axis.set_ylabel("Y (cm)")
            self.axis.set_zlabel("Z (µm)")
            self.axis.set_title(title)
            self.axis.mouse_init()

            self.figure_canvas.draw()

            QMessageBox.information(self, "QMessageBox.information()",
                                    "Waviness calculated: if the result is satisfactory,\nclick \'Generate Waviness File\' to complete the operation ",
                                    QMessageBox.Ok)
        except Exception as exception:
            QMessageBox.critical(self, "QMessageBox.critical()",
                                 exception.args[0],
                                 QMessageBox.Ok)


    def generate_waviness_file(self):
        if not self.zz is None and not self.yy is None and not self.xx is None:
            if not self.waviness_file_name is None:
                self.waviness_file_name = self.waviness_file_name.strip()

                if self.waviness_file_name == "": raise Exception("Output File Name missing")
            else:
                raise Exception("Output File Name missing")

            sys.stdout = EmittingStream(textWritten=self.writeStdOut)

            ST.write_shadow_surface(self.zz.T, self.xx, self.yy, outFile=self.waviness_file_name)
            QMessageBox.information(self, "QMessageBox.information()",
                                    "Waviness file " + self.waviness_file_name + " written on disk",
                                    QMessageBox.Ok)

            self.send("PreProcessor_Data", ShadowPreProcessorData(waviness_data_file=self.waviness_file_name))

    def call_reset_settings(self):
        if ConfirmDialog.confirmed(parent=self, message="Confirm Reset of the Fields?"):
            try:
                self.resetSettings()
                self.reload_harmonics_table()
            except:
                pass

    def check_fields(self):
        self.number_of_points_x = ShadowGui.checkStrictlyPositiveNumber(self.number_of_points_x, "Number of Points X")
        self.number_of_points_y = ShadowGui.checkStrictlyPositiveNumber(self.number_of_points_y, "Number of Points Y")

        self.dimension_x = ShadowGui.checkStrictlyPositiveNumber(self.dimension_x, "Dimension X")
        self.dimension_y = ShadowGui.checkStrictlyPositiveNumber(self.dimension_y, "Dimension Y")

        self.estimated_slope_error = ShadowGui.checkPositiveNumber(self.estimated_slope_error, "Estimated slope error")
        self.montecarlo_seed = ShadowGui.checkPositiveNumber(self.montecarlo_seed, "Monte Carlo initial seed")

        self.harmonic_maximum_index = ShadowGui.checkPositiveNumber(self.harmonic_maximum_index,
                                                                    "Harmonic Maximum Index")

        if not self.waviness_file_name is None:
            self.waviness_file_name = self.waviness_file_name.strip()

            if self.waviness_file_name == "": raise Exception("Output File Name missing")
        else:
            raise Exception("Output File Name missing")


    def to_float_array(self, string_array):
        float_array = []

        for index in range(len(string_array)):
            float_array.append(float(string_array[index]))

        return float_array

    def to_str_array(self, float_array):
        string_array = []

        for index in range(len(float_array)):
            string_array.append(str(float_array[index]))

        return string_array

    def writeStdOut(self, text):
        cursor = self.shadow_output.textCursor()
        cursor.movePosition(QTextCursor.End)
        cursor.insertText(text)
        self.shadow_output.setTextCursor(cursor)
        self.shadow_output.ensureCursorVisible()
Beispiel #48
0
class Ventana(QWidget):

	def __init__(self):
		super(Ventana, self).__init__()
		self.algoritmos = {"FCFS":FCFS, "SJF":SJF, "SRTF":SRTF, "Prioridad":Prioridad, "Round Robin":RoundRobin, "Colas multiples retroalimentadas":MulticolasRetro}
		self.iniciar = QPushButton("INICIAR")
		self.bloquear = QPushButton("BLOQUEAR")
		self.tablaGantt = QTableWidget(5, 0)
		self.tablaDatos = QTableWidget(0, 9)
		self.temporizador = QTimer(self)
		self.contenedor = None
		self.cant = 0
		self.terminados = 0
		self.fila = 0
		self.columna = 0
		self.bloqueo = False
		
		self._inicializar()
	
	def _inicializar(self):
		self.setWindowTitle("Algoritmos de planificacion ")
		
		#------------------------------------#
		#	ELEMENTOS DEL PANEL SUPERIOR 	 #
		#------------------------------------#
		
		tituloS = QLabel("DIAGRAMA DE GANTT")
		
		tituloS.adjustSize()
		
		fila1 = QHBoxLayout()
		fila2 = QHBoxLayout()
		
		fila1.addWidget(tituloS)
		fila2.addWidget(self.tablaGantt)
		
		cajaSuperior = QVBoxLayout()
		
		cajaSuperior.addLayout(fila1)
		cajaSuperior.addLayout(fila2)
		
		#------------------------------------#
		#	ELEMENTOS DEL PANEL INFERIOR 	 #
		#------------------------------------#
		
		tituloI = QLabel("DATOS DE LOS PROCESOS")
		
		tituloI.adjustSize()
		
		fila3 = QHBoxLayout()
		fila4 = QHBoxLayout()
		fila5 = QHBoxLayout()
		
		fila3.addWidget(tituloI)
		fila4.addWidget(self.tablaDatos)
		fila5.addWidget(self.iniciar)
		fila5.addWidget(self.bloquear)
		
		cajaInferior = QVBoxLayout()
		
		cajaInferior.addLayout(fila3)
		cajaInferior.addLayout(fila4)
		cajaInferior.addLayout(fila5)
		
		#------------------------------------#
						
		#agregar el segundo nivel de layout al panel
		panelSuperior = QFrame(self)
		panelSuperior.setFrameShape(QFrame.StyledPanel)
		panelSuperior.setLayout(cajaSuperior)
		
		#agregar el segundo nivel de layout al panel
		panelInferior = QFrame(self)
		panelInferior.setFrameShape(QFrame.StyledPanel)
		panelInferior.setLayout(cajaInferior)
		
		#agregar el panel al separador
		separador = QSplitter(Qt.Vertical)
		separador.addWidget(panelSuperior)
		separador.addWidget(panelInferior)
		
		#agregar el separador al primer layout
		caja = QVBoxLayout(self)
		caja.addWidget(separador)
		
		#agregar el layout a la ventana
		self.setLayout(caja)
		
		self.setFixedSize(1200, 900)
		self._configurar()
		self.show()
		
	def _configurar(self):
		self.iniciar.clicked.connect(self._comenzar)
		self.bloquear.clicked.connect(self._bloquear)
		self.bloquear.setEnabled(False)
		self.temporizador.timeout.connect(self._actualizar)
		self.tablaGantt.setEditTriggers(QAbstractItemView.NoEditTriggers)
		self.tablaGantt.setDragDropOverwriteMode(False)
		
		self.tablaDatos.setEditTriggers(QAbstractItemView.NoEditTriggers)
		self.tablaDatos.setDragDropOverwriteMode(False)
		datos = ["PROCESO", "LLEGADA", "RAFAGA", "PRIORIDAD", "EDAD", "COMIENZO", "FINALIZACION", "RETORNO", "ESPERA"]
		self.tablaDatos.setHorizontalHeaderLabels(QStringList(datos))

	def _comenzar(self):
		ok = 0
		eleccion, ok1 = QInputDialog.getItem(self, "Algoritmos", "Seleccione un algoritmo", self.algoritmos.keys())
		if ok1:
			self.contenedor = self.algoritmos[str(eleccion)]()
			self.cant, ok = QInputDialog.getInt(self, "Duracion", "Indique la duracion de la simulacion", min=0, max=60)
		if ok and ok1:
			self.setWindowTitle(self.windowTitle() + " --" +str(eleccion))
			self.temporizador.start(1000)
			self.iniciar.setEnabled(False)
			self.bloquear.setEnabled(True)
		self._inicializarDatos()
			
	def _bloquear(self):
		self.bloqueo = True
	
	def _actualizar(self):
		momento = round(clock())
		if momento < self.cant:
			proceso = self.contenedor.agregarProcesos(momento)
			if proceso:
				if proceso.listo():
					self._actualizarDatosNuevo(proceso)
					self.tablaGantt.insertRow(self.fila)
					self.fila += 1
		estados = [p.estado for p in self.contenedor.procesos]
		if self.contenedor.procesos and ("listo" in estados or "ejecutando" in estados):
			proceso = self.contenedor.administrarProcesos(momento, self.bloqueo)
			if self.bloqueo:
				self.bloqueo = False
			if proceso or proceso==0:
				if self.contenedor[proceso].terminado() and not self.contenedor[proceso].actualizado:
					self._actualizarDatosFinalizado(self.contenedor[proceso], proceso)
					self.contenedor[proceso].actualizado = True
					self.terminados += 1
			self._actualizarGantt()
			if isinstance(self.contenedor, Prioridad):
				self._actualizarDatosDinamicos()
			
		else:
			msj = QMessageBox.information(self, "Terminado", "El proceso de simulacion ha terminado")
			self.temporizador.stop()	
			del msj 
		
	def _actualizarGantt(self):
		self.tablaGantt.insertColumn(self.columna)
		for i in range(len(self.contenedor)):
			item = QTableWidgetItem()
			if self.contenedor[i].ejecutando():
				if isinstance(self.contenedor, MulticolasRetro):
					if self.contenedor[i].prioridad == 1:
						item.setBackgroundColor(QColor(0,128,0))
					elif self.contenedor[i].prioridad == 2:
						item.setBackgroundColor(QColor(0,255,0))
					elif self.contenedor[i].prioridad == 3:
						item.setBackgroundColor(QColor(128,255,128))
				else:
					item.setBackgroundColor(Qt.green) 
			elif self.contenedor[i].listo():
				if isinstance(self.contenedor, MulticolasRetro):
					if self.contenedor[i].prioridad == 1:
						item.setBackgroundColor(QColor(128,0,0))
					elif self.contenedor[i].prioridad == 2:
						item.setBackgroundColor(QColor(255,0,0))
					elif self.contenedor[i].prioridad == 3:
						item.setBackgroundColor(QColor(255,128,128))
				else:
					item.setBackgroundColor(Qt.red) 
			elif self.contenedor[i].bloqueado():
				item.setBackgroundColor(Qt.blue)
			self.tablaGantt.setItem(i, self.columna, item)
		self.columna += 1
		self.tablaGantt.resizeColumnsToContents()

	def _actualizarDatosNuevo(self, proceso):
		self.tablaDatos.insertRow(self.fila)
		self.tablaDatos.setItem(self.fila, 0, QTableWidgetItem(str(proceso.nombre)))
		self.tablaDatos.setItem(self.fila, 1, QTableWidgetItem(str(proceso.llegada)))
		self.tablaDatos.setItem(self.fila, 2, QTableWidgetItem(str(proceso.rafaga)))
		if isinstance(self.contenedor, Prioridad):
			self.tablaDatos.setItem(self.fila, 3, QTableWidgetItem(str(proceso.prioridad)))
			self.tablaDatos.setItem(self.fila, 4, QTableWidgetItem(str(proceso.edad)))
		self.tablaDatos.resizeColumnsToContents()

	def _actualizarDatosDinamicos(self):
		for i in range(len(self.contenedor)):
			self.tablaDatos.setItem(i, 3, QTableWidgetItem(str(self.contenedor[i].prioridad)))
			self.tablaDatos.setItem(i, 4, QTableWidgetItem(str(self.contenedor[i].edad)))

	def _actualizarDatosFinalizado(self, proceso, i):
		self.tablaDatos.setItem(i, 5, QTableWidgetItem(str(proceso.comienzo)))
		self.tablaDatos.setItem(i, 6, QTableWidgetItem(str(proceso.finalizacion)))
		self.tablaDatos.setItem(i, 7, QTableWidgetItem(str(proceso.finalizacion - proceso.llegada)))
		self.tablaDatos.setItem(i, 8, QTableWidgetItem(str(proceso.comienzo - proceso.llegada)))
	
	def _inicializarDatos(self):
		for i in range(len(self.contenedor)):
			self.tablaDatos.insertRow(self.fila)
			self.tablaDatos.setItem(self.fila, 0, QTableWidgetItem(str(self.contenedor[i].nombre)))
			self.tablaDatos.setItem(self.fila, 1, QTableWidgetItem(str(self.contenedor[i].llegada)))
			self.tablaDatos.setItem(self.fila, 2, QTableWidgetItem(str(self.contenedor[i].rafaga)))
			if isinstance(self.contenedor, Prioridad):
				self.tablaDatos.setItem(self.fila, 3, QTableWidgetItem(str(self.contenedor[i].prioridad)))
				self.tablaDatos.setItem(self.fila, 4, QTableWidgetItem(str(self.contenedor[i].edad)))
			self.fila += 1
		self.tablaDatos.resizeColumnsToContents()
class ProcExpWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        # setup menu bar
        exitItem = QAction('Exit', self)
        exitItem.setShortcut('Ctrl+Q')
        exitItem.setStatusTip('Exit application')
        exitItem.triggered.connect(self.close)
        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu('&File')
        fileMenu.addAction(exitItem)

        # setup widgets
        self.model = ProcTableModel(self)
        self.procTable = ProcTableWidget(self.model)
        self.procTable.clicked.connect(self.showDescriptors)
        self.handlesTable = QTableWidget()
        self.handlesTable.setColumnCount(2)
        self.handlesTable.setHorizontalHeaderLabels(('Type', 'Object Name'))
        self.handlesTable.verticalHeader().setVisible(False)
        self.handlesTable.setShowGrid(False)
        self.handlesTable.setSelectionBehavior(QTableWidget.SelectRows)
        self.handlesTable.horizontalHeader().setStretchLastSection(True)

        # TODO: find a way to get the row height from the QTreeView
        self.handlesTable.verticalHeader().setDefaultSectionSize(24)

        mainSplitter = QSplitter(Qt.Vertical)
        mainSplitter.addWidget(self.procTable)
        mainSplitter.addWidget(self.handlesTable)
        self.setCentralWidget(mainSplitter)

        desktopGeometry = QApplication.desktop().screenGeometry()
        self.setGeometry(0, 0, 1280, 700)
        self.move((desktopGeometry.width() - self.width()) / 2,
                  (desktopGeometry.height() - self.height()) / 2)
        self.setWindowTitle('Linux Process Explorer')

        # find handle dialog
        self.findDialog = None

    @pyqtSlot(int)
    def removeFindDialog(self):
        self.findDialog = None

    def keyPressEvent(self, event):
        modifiers = event.modifiers()
        if event.key() == Qt.Key_F and modifiers & Qt.ControlModifier:
            if self.findDialog is None:
                self.findDialog = FindHandleDialog(self.model, self)
                self.findDialog.finished.connect(self.removeFindDialog)
                self.findDialog.show()
            else:
                self.findDialog.activateWindow()
        else:
            super().keyPressEvent(event)

    @pyqtSlot(QModelIndex)
    def showDescriptors(self, processMIdx):
        try:
            self.handlesTable.setRowCount(0)
            self.handlesTable.clearContents()
            descriptors = self.model.getProcDescriptors(processMIdx)
            libs = self.model.getProcLibraries(processMIdx)
            self.handlesTable.setRowCount(len(descriptors) + len(libs))
        except PermissionError:
            self.handlesTable.setRowCount(1)
            self.handlesTable.setSpan(0, 0, 1, 2)
            permDeniedMsg = QTableWidgetItem('<Permission Denied>')
            permDeniedMsg.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
            permDeniedMsg.setTextAlignment(Qt.AlignCenter)
            permDeniedMsg.setTextColor(QColor(255, 0, 0))
            self.handlesTable.setItem(0, 0, permDeniedMsg)
        else:
            for row, descriptor in enumerate(descriptors):
                typeItem = QTableWidgetItem(descriptor.type)
                typeItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                nameItem = QTableWidgetItem(descriptor.name)
                nameItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                self.handlesTable.setItem(row, 0, typeItem)
                self.handlesTable.setItem(row, 1, nameItem)

            for row, libName in enumerate(libs, start=len(descriptors)):
                typeItem = QTableWidgetItem('Shared Library')
                typeItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                nameItem = QTableWidgetItem(libName)
                nameItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                self.handlesTable.setItem(row, 0, typeItem)
                self.handlesTable.setItem(row, 1, nameItem)
Beispiel #50
0
class LabelAssistDialog(QDialog):
    """
    A simple UI for showing bookmarks and navigating to them.

    FIXME: For now, this window is tied to a particular lane.
           If your project has more than one lane, then each one
           will have it's own bookmark window, which is kinda dumb.
    """
    def __init__(self, parent, topLevelOperatorView):
        super(LabelAssistDialog, self).__init__(parent)
        
        # Create thread router to populate table on main thread
        self.threadRouter = ThreadRouter(self)
        
        # Set object classification operator view
        self.topLevelOperatorView = topLevelOperatorView
        
        self.setWindowTitle("Label Assist")
        self.setMinimumWidth(500)
        self.setMinimumHeight(700)

        layout = QGridLayout() 
        layout.setContentsMargins(10, 10, 10, 10)
                       
        # Show variable importance table
        rows = 0
        columns = 4
        self.table = QTableWidget(rows, columns)   
        self.table.setHorizontalHeaderLabels(['Frame', 'Max Area', 'Min Area', 'Labels'])
        self.table.verticalHeader().setVisible(False)     
        
        # Select full row on-click and call capture double click
        self.table.setSelectionBehavior(QTableView.SelectRows);
        self.table.doubleClicked.connect(self._captureDoubleClick)
                
        layout.addWidget(self.table, 1, 0, 3, 2) 

        # Create progress bar
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(0)
        self.progressBar.hide()
        layout.addWidget(self.progressBar, 4, 0, 1, 2)

        # Create button to populate table
        self.computeButton = QPushButton('Compute object info')
        self.computeButton.clicked.connect(self._triggerTableUpdate)
        layout.addWidget(self.computeButton, 5, 0)
        
        # Create close button
        closeButton = QPushButton('Close')
        closeButton.clicked.connect(self.close)
        layout.addWidget(closeButton, 5, 1)
        
        # Set dialog layout
        self.setLayout(layout)       


    def _triggerTableUpdate(self):
        # Check that object area is included in selected features
        featureNames = self.topLevelOperatorView.SelectedFeatures.value
        
        if 'Standard Object Features' not in featureNames or 'Count' not in featureNames['Standard Object Features']:
            box = QMessageBox(QMessageBox.Warning,
                  'Warning',
                  'Object area is not a selected feature. Please select this feature on: \"Standard Object Features > Shape > Size in pixels\"',
                  QMessageBox.NoButton,
                  self)
            box.show()
            return 
        
        # Clear table
        self.table.clearContents()
        self.table.setRowCount(0)
        self.table.setSortingEnabled(False)
        self.progressBar.show()
        self.computeButton.setEnabled(False)

        def compute_features_for_frame(tIndex, t, features): 
            # Compute features and labels (called in parallel from request pool)
            roi = [slice(None) for i in range(len(self.topLevelOperatorView.LabelImages.meta.shape))]
            roi[tIndex] = slice(t, t+1)
            roi = tuple(roi)

            frame = self.topLevelOperatorView.SegmentationImages(roi).wait()           
            frame = frame.squeeze().astype(numpy.uint32, copy=False)
            
            # Dirty trick: We don't care what we're passing here for the 'image' parameter,
            # but vigra insists that we pass *something*, so we'll cast the label image as float32.
            features[t] = vigra.analysis.extractRegionFeatures(frame.view(numpy.float32),
                                                               frame,
                                                               ['Count'],
                                                               ignoreLabel=0)
            
        tIndex = self.topLevelOperatorView.SegmentationImages.meta.axistags.index('t')
        tMax = self.topLevelOperatorView.SegmentationImages.meta.shape[tIndex]     
        
        features = {}
        labels = {}

        def compute_all_features():
            # Compute features in parallel
            pool = RequestPool()
            for t in range(tMax):
                pool.add( Request( partial(compute_features_for_frame, tIndex, t, features) ) )
            pool.wait()
            
        # Compute labels
        labels = self.topLevelOperatorView.LabelInputs([]).wait()
            
        req = Request(compute_all_features)
        req.notify_finished( partial(self._populateTable, features, labels) )
        req.submit()

    @threadRouted
    def _populateTable(self, features, labels, *args):
        self.progressBar.hide()
        self.computeButton.setEnabled(True)
                
        for time, feature in features.iteritems():
            # Insert row
            rowNum = self.table.rowCount()
            self.table.insertRow(self.table.rowCount())
            
            # Get max and min object areas
            areas = feature['Count']#objectFeatures['Standard Object Features']['Count']
            maxObjArea = numpy.max(areas[numpy.nonzero(areas)])
            minObjArea = numpy.min(areas[numpy.nonzero(areas)])
            
            # Get number of labeled objects
            labelNum = numpy.count_nonzero(labels[time])
            
            # Load fram number
            item = QTableWidgetItem(str(time))
            item.setFlags( Qt.ItemIsSelectable |  Qt.ItemIsEnabled )
            self.table.setItem(rowNum, 0, item) 

            # Load max object areas
            item = QTableWidgetItemWithFloatSorting(str("{: .02f}".format(maxObjArea)))
            item.setFlags( Qt.ItemIsSelectable |  Qt.ItemIsEnabled )
            self.table.setItem(rowNum, 1, item)
                
            # Load min object areas
            item = QTableWidgetItemWithFloatSorting(str("{: .02f}".format(minObjArea)))
            item.setFlags( Qt.ItemIsSelectable |  Qt.ItemIsEnabled )
            self.table.setItem(rowNum, 2, item)
            
            # Load label numbers
            item = QTableWidgetItemWithFloatSorting(str("{: .01f}".format(labelNum)))
            item.setFlags( Qt.ItemIsSelectable |  Qt.ItemIsEnabled )
            self.table.setItem(rowNum, 3, item)
        
        # Resize column size to fit dialog size
        self.table.horizontalHeader().setResizeMode(QHeaderView.Stretch)   
        
        # Sort by max object area
        self.table.setSortingEnabled(True)                         
        self.table.sortByColumn(1) 
        

    def _captureDoubleClick(self):
        # Navigate to selected frame
        index = self.table.selectedIndexes()[0]
        frameStr = self.table.model().data(index).toString()
        
        if frameStr:
            frameNum = int(frameStr)
            self.parent().editor.posModel.time = frameNum
Beispiel #51
0
class phonesDialog(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.prm = self.parent().prm
        self.currLocale = self.parent().prm['currentLocale']
        self.currLocale.setNumberOptions(
            self.currLocale.OmitGroupSeparator
            | self.currLocale.RejectGroupSeparator)
        screen = QDesktopWidget().screenGeometry()
        self.resize(screen.width() / 2.5, screen.height() / 3)
        self.isPlaying = False
        #self.audioManager = audioManager(self)
        #self.playThread = threadedPlayer(self)

        self.sizer = QGridLayout()
        self.v1Sizer = QVBoxLayout()
        self.v2Sizer = QVBoxLayout()
        self.calibSizer = QGridLayout()

        self.phonesTableWidget = QTableWidget()
        self.phonesTableWidget.setColumnCount(4)
        self.phonesTableWidget.setSelectionBehavior(
            QAbstractItemView.SelectRows)
        self.phonesTableWidget.setSelectionMode(
            QAbstractItemView.ExtendedSelection)

        self.phonesTableWidget.setHorizontalHeaderLabels([
            self.tr('Phones'),
            self.tr('Max Level'),
            self.tr('Default'), 'id'
        ])
        self.phonesTableWidget.hideColumn(3)
        self.phonesTableWidget.cellDoubleClicked[int, int].connect(
            self.onCellDoubleClicked)

        #RENAME Phones BUTTON
        self.renamePhonesButton = QPushButton(self.tr("Rename Phones"), self)
        self.renamePhonesButton.clicked.connect(self.onEditLabel)
        #Change Level Phones BUTTON
        self.changeLevelPhonesButton = QPushButton(self.tr("Change Max Level"),
                                                   self)
        self.changeLevelPhonesButton.clicked.connect(self.onEditMaxLevel)

        #ADD Phones BUTTON
        self.addPhonesButton = QPushButton(self.tr("Add Phones"), self)
        self.addPhonesButton.clicked.connect(self.onClickAddPhonesButton)
        #REMOVE Phones BUTTON
        self.removePhonesButton = QPushButton(self.tr("Remove Phones"), self)
        self.removePhonesButton.clicked.connect(self.onClickRemovePhonesButton)
        #Set Default Phones BUTTON
        self.setDefaultPhonesButton = QPushButton(self.tr("Set Default"), self)
        self.setDefaultPhonesButton.clicked.connect(self.onEditDefault)

        self.v1Sizer.addWidget(self.renamePhonesButton)
        self.v1Sizer.addWidget(self.changeLevelPhonesButton)
        self.v1Sizer.addWidget(self.addPhonesButton)
        self.v1Sizer.addWidget(self.removePhonesButton)
        self.v1Sizer.addWidget(self.setDefaultPhonesButton)
        self.v1Sizer.addStretch()
        self.phonesList = {}

        for i in range(len(self.prm['phones']['phonesChoices'])):
            currCount = i + 1
            thisID = self.prm['phones']['phonesID'][i]
            self.phonesList[thisID] = {}
            self.phonesList[thisID]['label'] = self.prm['phones'][
                'phonesChoices'][i]
            self.phonesList[thisID]['maxLevel'] = self.prm['phones'][
                'phonesMaxLevel'][i]
            self.phonesList[thisID]['default'] = self.prm['phones'][
                'defaultPhones'][i]
            self.phonesTableWidget.setRowCount(currCount)
            newItem = QTableWidgetItem(self.phonesList[thisID]['label'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.phonesTableWidget.setItem(currCount - 1, 0, newItem)
            newItem = QTableWidgetItem(
                self.currLocale.toString(self.phonesList[thisID]['maxLevel']))
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.phonesTableWidget.setItem(currCount - 1, 1, newItem)
            newItem = QTableWidgetItem(self.phonesList[thisID]['default'])
            newItem.setFlags(QtCore.Qt.ItemIsSelectable
                             | QtCore.Qt.ItemIsEnabled)
            self.phonesTableWidget.setItem(currCount - 1, 2, newItem)
            self.phonesList[thisID]['qid'] = QTableWidgetItem(thisID)
            self.phonesTableWidget.setItem(currCount - 1, 3,
                                           self.phonesList[thisID]['qid'])

        ##CALIBRATION TONE
        n = 0
        self.calLabel = QLabel(self.tr('Calibration Tone:'), self)
        self.calibSizer.addWidget(self.calLabel, n, 0, 1, 2)
        n = n + 1
        self.toneFreqLabel = QLabel(self.tr('Frequency (Hz)'), self)
        self.toneFreqTF = QLineEdit("1000")
        self.toneFreqTF.setValidator(QDoubleValidator(self))
        self.calibSizer.addWidget(self.toneFreqLabel, n, 0)
        self.calibSizer.addWidget(self.toneFreqTF, n, 1)
        n = n + 1
        self.toneLevLabel = QLabel(self.tr('Level (dB)'), self)
        self.toneLevTF = QLineEdit("60")
        self.toneLevTF.setValidator(QDoubleValidator(self))
        self.calibSizer.addWidget(self.toneLevLabel, n, 0)
        self.calibSizer.addWidget(self.toneLevTF, n, 1)
        n = n + 1
        self.toneDurLabel = QLabel(self.tr('Duration (ms)'), self)
        self.toneDurTF = QLineEdit("980")
        self.toneDurTF.setValidator(QDoubleValidator(self))
        self.calibSizer.addWidget(self.toneDurLabel, n, 0)
        self.calibSizer.addWidget(self.toneDurTF, n, 1)
        n = n + 1
        self.toneRampsLabel = QLabel(self.tr('Ramps (ms)'), self)
        self.toneRampsTF = QLineEdit("10")
        self.toneRampsTF.setValidator(QDoubleValidator(self))
        self.calibSizer.addWidget(self.toneRampsLabel, n, 0)
        self.calibSizer.addWidget(self.toneRampsTF, n, 1)
        n = n + 1
        self.earLabel = QLabel(self.tr('Ear:'), self)
        self.earChooser = QComboBox()
        self.earChooser.addItems(
            [self.tr("Right"),
             self.tr("Left"),
             self.tr("Both")])
        self.calibSizer.addWidget(self.earLabel, n, 0)
        self.calibSizer.addWidget(self.earChooser, n, 1)
        n = n + 1
        self.playCalibButton = QPushButton(self.tr("Play"), self)
        self.playCalibButton.clicked.connect(self.onClickPlayCalibButton)
        self.playCalibButton.setIcon(
            QIcon.fromTheme("media-playback-start",
                            QIcon(":/media-playback-start")))
        self.calibSizer.addWidget(self.playCalibButton, n, 0, 1, 2)
        n = n + 1
        self.stopCalibButton = QPushButton(self.tr("Stop"), self)
        self.stopCalibButton.clicked.connect(self.onClickStopCalibButton)
        self.stopCalibButton.setIcon(
            QIcon.fromTheme("media-playback-stop",
                            QIcon(":/media-playback-stop")))
        self.calibSizer.addWidget(self.stopCalibButton, n, 0, 1, 2)
        if self.prm['pref']['sound']['playCommand'] in [
                "alsaaudio", "pyaudio"
        ]:
            self.stopCalibButton.show()
        else:
            self.stopCalibButton.hide()

        buttonBox = QDialogButtonBox(QDialogButtonBox.Apply
                                     | QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
        buttonBox.button(QDialogButtonBox.Apply).clicked.connect(
            self.permanentApply)

        self.sizer.addLayout(self.v1Sizer, 0, 0)
        self.v2Sizer.addLayout(self.calibSizer)
        self.v2Sizer.addStretch()
        self.sizer.addWidget(self.phonesTableWidget, 0, 1)
        self.sizer.addLayout(self.v2Sizer, 0, 2)
        self.sizer.addWidget(buttonBox, 1, 1, 1, 2)
        self.sizer.setColumnStretch(1, 2)
        self.setLayout(self.sizer)
        self.setWindowTitle(self.tr("Edit Phones"))
        self.show()

    def onCellDoubleClicked(self, row, col):
        if col == 0:
            self.onEditLabel()
        elif col == 1:
            self.onEditMaxLevel()
        elif col == 2:
            self.onEditDefault()

    def onEditLabel(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(
                self, self.tr('Warning'),
                self.tr('Only one label can be renamed at a time'))
        elif len(ids) < 1:
            pass
        else:
            selectedSound = ids[0]
            msg = self.tr('New name:')
            text, ok = QInputDialog.getText(self, self.tr('Input Dialog'), msg)
            if ok:
                self.phonesTableWidget.item(
                    self.phonesList[selectedSound]['qid'].row(),
                    0).setText(text)
                self.phonesList[selectedSound]['label'] = text

    def onEditMaxLevel(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(
                self, self.tr('Warning'),
                self.tr('Only one item can be edited at a time'))
        elif len(ids) < 1:
            pass
        else:
            selectedSound = ids[0]
            msg = self.tr('Level:')
            text, ok = QInputDialog.getDouble(
                self, self.tr('Input Dialog'), msg,
                self.phonesList[selectedSound]['maxLevel'])
            if ok:
                self.phonesTableWidget.item(
                    self.phonesList[selectedSound]['qid'].row(),
                    1).setText(self.currLocale.toString(text))
                self.phonesList[selectedSound]['maxLevel'] = text

    def onEditDefault(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(
                self, self.tr('Warning'),
                self.tr('Only one item can be edited at a time'))
        elif len(ids) < 1:
            pass
        else:
            selectedSound = ids[0]
            for i in range(self.phonesTableWidget.rowCount()):
                self.phonesTableWidget.item(i, 2).setText("\u2012")
                self.phonesList[str(self.phonesTableWidget.item(
                    i, 3).text())]['default'] = "\u2012"
            self.phonesTableWidget.item(
                self.phonesList[selectedSound]['qid'].row(),
                2).setText("\u2713")
            self.phonesList[selectedSound]['default'] = "\u2713"

    def findSelectedItemIds(self):
        selItems = self.phonesTableWidget.selectedItems()
        selItemsRows = []
        for i in range(len(selItems)):
            selItemsRows.append(selItems[i].row())
        selItemsRows = unique(selItemsRows)
        selItemsIds = []
        for i in range(len(selItemsRows)):
            selItemsIds.append(
                str(self.phonesTableWidget.item(selItemsRows[i], 3).text()))
        return selItemsIds

    def permanentApply(self):
        self.prm['phones']['phonesChoices'] = []
        self.prm['phones']['phonesMaxLevel'] = []
        self.prm['phones']['defaultPhones'] = []
        self.prm['phones']['phonesID'] = []

        keys = sorted(self.phonesList.keys())
        for key in keys:
            self.prm['phones']['phonesChoices'].append(
                str(self.phonesList[key]['label']))
            self.prm['phones']['phonesMaxLevel'].append(
                self.phonesList[key]['maxLevel'])
            self.prm['phones']['defaultPhones'].append(
                self.phonesList[key]['default'])
            self.prm['phones']['phonesID'].append(key)
        f = open(self.parent().prm['phonesPrefFile'], 'wb')
        pickle.dump(self.parent().prm['phones'], f)
        f.close()
        for i in range(self.parent().phonesChooser.count()):
            self.parent().phonesChooser.removeItem(0)
        self.parent().phonesChooser.addItems(
            self.prm['phones']['phonesChoices'])

    def onClickAddPhonesButton(self):
        keys = sorted(self.phonesList.keys())
        thisID = str(int(keys[-1]) + 1)
        currCount = self.phonesTableWidget.rowCount() + 1

        self.phonesList[thisID] = {}
        self.phonesList[thisID]['label'] = 'Phones' + ' ' + str(currCount)
        self.phonesList[thisID]['maxLevel'] = 100
        self.phonesList[thisID]['default'] = "\u2012"
        self.phonesTableWidget.setRowCount(currCount)
        newItem = QTableWidgetItem(self.phonesList[thisID]['label'])
        newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
        self.phonesTableWidget.setItem(currCount - 1, 0, newItem)
        newItem = QTableWidgetItem(
            self.currLocale.toString(self.phonesList[thisID]['maxLevel']))
        newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
        self.phonesTableWidget.setItem(currCount - 1, 1, newItem)
        newItem = QTableWidgetItem(self.phonesList[thisID]['default'])
        newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
        self.phonesTableWidget.setItem(currCount - 1, 2, newItem)
        self.phonesList[thisID]['qid'] = QTableWidgetItem(thisID)
        self.phonesTableWidget.setItem(currCount - 1, 3,
                                       self.phonesList[thisID]['qid'])

    def onClickRemovePhonesButton(self):
        if self.phonesTableWidget.rowCount() == 1:
            ret = QMessageBox.warning(
                self, self.tr("Warning"),
                self.tr("Only one phone left. Cannot remove!"), QMessageBox.Ok)
        else:
            ids = self.findSelectedItemIds()
            wasDefault = False
            for i in range(len(ids)):
                selectedPhones = ids[i]
                if self.phonesTableWidget.item(
                        self.phonesList[selectedPhones]['qid'].row(),
                        2).text() == "\u2713":
                    wasDefault = True
                self.phonesTableWidget.removeRow(
                    self.phonesList[selectedPhones]['qid'].row())
                del self.phonesList[selectedPhones]
            if wasDefault == True:
                self.phonesTableWidget.item(0, 2).setText("\u2713")
                self.phonesList[str(self.phonesTableWidget.item(
                    0, 3).text())]['default'] = "\u2713"

    def onClickPlayCalibButton(self):
        ids = self.findSelectedItemIds()
        if len(ids) > 1:
            QMessageBox.warning(
                self, self.tr('Warning'),
                self.tr('Only one label can be renamed at a time'))
            return
        elif len(ids) < 1:
            QMessageBox.warning(self, self.tr('Warning'),
                                self.tr('Please, select a phone in the table'))
            return
        else:
            selectedSound = ids[0]
            calMaxLev = self.phonesList[selectedSound]['maxLevel']
            frequency = self.currLocale.toDouble(self.toneFreqTF.text())[0]
            level = self.currLocale.toDouble(self.toneLevTF.text())[0]
            duration = self.currLocale.toDouble(self.toneDurTF.text())[0]
            ramp = self.currLocale.toDouble(self.toneRampsTF.text())[0]
            channel = self.earChooser.currentText()
            fs = self.currLocale.toInt(self.parent().sampRateTF.text())[0]
            nBits = self.currLocale.toInt(
                self.parent().nBitsChooser.currentText())[0]
            calTone = pureTone(frequency, 0, level, duration, ramp, channel,
                               fs, calMaxLev)
            self.isPlaying = True
            if self.prm['pref']['sound']['playCommand'] in [
                    "alsaaudio", "pyaudio"
            ]:
                self.playThread = threadedAudioPlayer(self.parent())
            else:
                self.playThread = threadedExternalAudioPlayer(self.parent())
            self.playThread.playThreadedSound(
                calTone, fs, nBits, self.prm['pref']['sound']['playCommand'],
                True, 'calibrationTone.wav')
            if self.playThread.isFinished() == True:
                self.isPlaying = False

    def onClickStopCalibButton(self):
        if self.isPlaying == True:
            self.playThread.terminate()
            #self.playThread.__del__()

    def closeEvent(self, event):
        if self.isPlaying == True:
            #self.playThread.__del__()
            self.playThread.terminate()
        event.accept()

    def accept(self):  #reimplement accept (i.e. ok button)
        if self.isPlaying == True:
            #self.playThread.__del__()
            self.playThread.terminate()
        QDialog.accept(self)

    def reject(self):  #reimplement reject
        if self.isPlaying == True:
            #self.playThread.__del__()
            self.playThread.terminate()
        QDialog.reject(self)
    def _init_layout(self):
        """
        Create the GUI widgets (but leave them empty).
        """
        hostname_combobox = QComboBox(parent=self)
        self._hostname_combobox = hostname_combobox
        hostname_combobox.setEditable(True)
        hostname_combobox.setSizePolicy(QSizePolicy.Expanding,
                                        QSizePolicy.Maximum)
        for hostname in self._suggested_hostnames:
            hostname_combobox.addItem(hostname)

        # EventFilter is installed after everything else is initialized. (See below.)
        #hostname_combobox.installEventFilter(self)

        self._connect_button = QPushButton("Connect",
                                           parent=self,
                                           clicked=self._handle_new_hostname)

        hostname_layout = QHBoxLayout()
        hostname_layout.addWidget(hostname_combobox)
        hostname_layout.addWidget(self._connect_button)

        hostinfo_table = QTableWidget()
        hostinfo_table.setColumnCount(len(SERVER_INFO_FIELDS))
        hostinfo_table.setHorizontalHeaderLabels(SERVER_INFO_FIELDS)
        hostinfo_table.horizontalHeader().setVisible(True)
        hostinfo_table.verticalHeader().setVisible(False)
        hostinfo_table.setRowCount(1)
        hostinfo_table.setItem(0, 0, QTableWidgetItem("Placeholder"))
        hostinfo_table.setVisible(False)
        hostinfo_table.resizeRowsToContents()
        hostinfo_table.horizontalHeader().setStretchLastSection(True)
        table_height = hostinfo_table.verticalHeader().sectionSize(
            0) + hostinfo_table.rowHeight(0)
        hostinfo_table.resize(QSize(hostinfo_table.width(), table_height))
        hostinfo_table.setMaximumSize(QSize(1000, table_height))
        hostinfo_table.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)

        host_layout = QVBoxLayout()
        host_layout.addLayout(hostname_layout)
        host_layout.addWidget(hostinfo_table)

        host_groupbox = QGroupBox("DVID Host", parent=self)
        host_groupbox.setLayout(host_layout)
        host_groupbox.setSizePolicy(QSizePolicy.Preferred,
                                    QSizePolicy.Preferred)

        repo_treewidget = QTreeWidget(parent=self)
        repo_treewidget.setHeaderLabels(
            TREEVIEW_COLUMNS)  # TODO: Add type, shape, axes, etc.
        repo_treewidget.setSizePolicy(QSizePolicy.Preferred,
                                      QSizePolicy.Preferred)
        repo_treewidget.itemSelectionChanged.connect(
            self._handle_data_selection)

        data_layout = QVBoxLayout()
        data_layout.addWidget(repo_treewidget)
        data_groupbox = QGroupBox("Data Volumes", parent=self)
        data_groupbox.setLayout(data_layout)

        node_listwidget = QListWidget(parent=self)
        node_listwidget.setSizePolicy(QSizePolicy.Preferred,
                                      QSizePolicy.Preferred)
        node_listwidget.itemSelectionChanged.connect(self._update_status)

        node_layout = QVBoxLayout()
        node_layout.addWidget(node_listwidget)
        node_groupbox = QGroupBox("Nodes", parent=self)
        node_groupbox.setLayout(node_layout)

        new_data_edit = QLineEdit(parent=self)
        new_data_edit.textEdited.connect(self._update_status)
        full_url_label = QLabel(parent=self)
        full_url_label.setSizePolicy(QSizePolicy.Preferred,
                                     QSizePolicy.Maximum)
        text_flags = full_url_label.textInteractionFlags()
        full_url_label.setTextInteractionFlags(text_flags
                                               | Qt.TextSelectableByMouse)

        new_data_layout = QVBoxLayout()
        new_data_layout.addWidget(new_data_edit)
        new_data_groupbox = QGroupBox("New Data Volume", parent=self)
        new_data_groupbox.setLayout(new_data_layout)
        new_data_groupbox.setSizePolicy(QSizePolicy.Preferred,
                                        QSizePolicy.Maximum)

        buttonbox = QDialogButtonBox(Qt.Horizontal, parent=self)
        buttonbox.setStandardButtons(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        buttonbox.accepted.connect(self.accept)
        buttonbox.rejected.connect(self.reject)
        buttonbox.button(QDialogButtonBox.Ok).setEnabled(False)

        layout = QVBoxLayout()
        layout.addWidget(host_groupbox)
        layout.addWidget(data_groupbox)
        layout.addWidget(node_groupbox)
        if self._mode == "specify_new":
            layout.addWidget(new_data_groupbox)
        else:
            new_data_groupbox.hide()
        layout.addWidget(full_url_label)
        layout.addWidget(buttonbox)

        # Stretch factors
        layout.setStretchFactor(data_groupbox, 3)
        layout.setStretchFactor(node_groupbox, 1)

        self.setLayout(layout)
        self.setWindowTitle("Select DVID Volume")
        self.resize(1000, 1000)

        # Initially disabled
        data_groupbox.setEnabled(False)
        node_groupbox.setEnabled(False)
        new_data_groupbox.setEnabled(False)

        # Set tab order
        self.setTabOrder(hostname_combobox, repo_treewidget)
        self.setTabOrder(repo_treewidget, node_listwidget)
        self.setTabOrder(node_listwidget, buttonbox)

        # Save instance members
        self._hostinfo_table = hostinfo_table
        self._data_groupbox = data_groupbox
        self._node_groupbox = node_groupbox
        self._new_data_groupbox = new_data_groupbox
        self._repo_treewidget = repo_treewidget
        self._node_listwidget = node_listwidget
        self._new_data_edit = new_data_edit
        self._full_url_label = full_url_label
        self._buttonbox = buttonbox

        # Finally install eventfilter (after everything is initialized)
        hostname_combobox.installEventFilter(self)
Beispiel #53
0
class ExpensesDialog(QDialog):

    holdc = {}

    def __init__(self, session, parent=None):
        super(ExpensesDialog, self).__init__(parent)
        self.session = session
        session = self.pullOnes('session', session)
        self.sessionname = str(session['name']) + ' Session'
        self.pagetitle = self.sessionname
        self.tableFont = QFont('Century Gothic', 8)
        #self.tableFont.setFamily('Century Gothic')
        self.tableHeaderStyle = "::section {" "background-color: teal; color:white}"
        #pull all CA
        self.editID = 0
        self.hold_account = {}
        self.hold_expenses = {}
        self.hold_expensesGroup = {}

        from_label = QLabel('From:')
        to_label = QLabel('To:')
        self.fromData = QDateEdit()
        self.toData = QDateEdit()
        currentDate = QDate()
        self.fromData.setDate(currentDate.currentDate())
        self.fromData.setCalendarPopup(True)
        self.toData.setDate(currentDate.currentDate())
        self.toData.setCalendarPopup(True)
        self.pull_btn = QPushButton()
        self.pull_btn.setText("Load")
        h_pull_box = QHBoxLayout()
        h_pull_box.addWidget(from_label)
        h_pull_box.addWidget(self.fromData)
        h_pull_box.addWidget(to_label)
        h_pull_box.addWidget(self.toData)
        h_pull_box.addWidget(self.pull_btn)

        expensesGroup = self.pullGroupExpenses()
        account = self.pullAccount()

        self.expenseGroupText = QLabel('Category')
        self.expenseGroupData = QComboBox()
        self.expenseGroupData.currentIndexChanged.connect(self.reloadExpenses)
        self.expenseText = QLabel('Expenses')
        self.expenseData = QComboBox()
        self.amountText = QLabel('Amount')
        self.amountData = QLineEdit()
        self.amountData.setPlaceholderText('0000.00')
        self.tellerText = QLabel('Teller/Reciept No.')
        self.tellerData = QLineEdit()
        self.tellerData.setPlaceholderText('xxxxxxxxx')
        self.accountText = QLabel('Account')
        self.accountData = QComboBox()
        self.dateText = QLabel('Date')
        self.dateData = QDateEdit()
        self.dateData.setDate(currentDate.currentDate())
        self.dateData.setCalendarPopup(True)
        self.descriptionText = QLabel('Brief Description')
        self.descriptionData = QPlainTextEdit()
        self.descriptionData.move(200, 100)
        hboz = QHBoxLayout()
        self.gender = QLabel('State')
        self.r1 = QRadioButton('Expenses')
        self.r1.setChecked(True)
        self.r2 = QRadioButton('Refund')
        hboz.addWidget(self.r1)
        hboz.addWidget(self.r2)

        i = 0
        for a in expensesGroup:
            self.hold_expensesGroup[i] = a['id']
            tex = str(a['name']).upper()
            self.expenseGroupData.addItem(tex)
            i += 1

        i = 0
        exp_key = self.hold_expensesGroup[self.expenseGroupData.currentIndex()]
        expenses = self.pullExpenses(exp_key)
        for a in expenses:
            self.hold_expenses[i] = a['id']
            tex = str(a['name']).upper()
            self.expenseData.addItem(tex)
            i += 1

        i = 0
        for a in account:
            self.hold_account[i] = a['id']
            tex = str(a['name']).upper()
            self.accountData.addItem(tex)
            i += 1

        self.FormLayout = QFormLayout()
        self.FormLayout.addRow(self.expenseGroupText, self.expenseGroupData)
        self.FormLayout.addRow(self.expenseText, self.expenseData)
        self.FormLayout.addRow(self.accountText, self.accountData)
        self.FormLayout.addRow(self.tellerText, self.tellerData)
        self.FormLayout.addRow(self.amountText, self.amountData)
        self.FormLayout.addRow(self.gender, hboz)
        self.FormLayout.addRow(self.dateText, self.dateData)
        self.FormLayout.addRow(self.descriptionText, self.descriptionData)

        groupBox1 = QGroupBox('Add Expenses')
        groupBox1.setLayout(self.FormLayout)

        self.pb = QPushButton()
        self.pb.setObjectName("Add")
        self.pb.setText("Add Expenses")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Edit")
        self.pb1.setText("Edit Row")
        self.pb1.setEnabled(False)

        self.pb2 = QPushButton()
        self.pb2.setObjectName("Close")
        self.pb2.setText("Close")

        self.pb3 = QPushButton()
        self.pb3.setObjectName("Delete")
        self.pb3.setText("Delete Row")
        self.pb3.setEnabled(False)

        self.pb4 = QPushButton()
        self.pb4.setObjectName("Reset")
        self.pb4.setText("Reset")
        self.pb4.hide()

        self.pb5 = QPushButton()
        self.pb5.setObjectName("Change")
        self.pb5.setText("Change Expenses")
        self.pb5.hide()

        self.pb6 = QPushButton()
        self.pb6.setObjectName("Clear")
        self.pb6.setText("Clear Selection")
        self.pb6.setEnabled(False)

        hbo = QHBoxLayout()
        hbo.addWidget(self.pb)
        hbo.addWidget(self.pb5)
        hbo.addWidget(self.pb4)
        hbo.addWidget(self.pb2)
        groupBox2 = QGroupBox('Expenses Data')
        groupBox2.setLayout(hbo)

        self.cols = ['SN', 'EXPENSES', 'ACCOUNT', 'AMOUNT', 'DATE']
        al = self.pullExpensesData()
        if len(al) > 0:
            al = al
        else:
            al = {}

        self.table = QTableWidget()
        header = self.table.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)
        header.setStyleSheet(self.tableHeaderStyle)
        vheader = self.table.verticalHeader()
        vheader.setStyleSheet(self.tableHeaderStyle)
        # Body
        self.table.setWindowTitle("Expenses")
        self.table.resize(300, 250)
        self.table.setFont(self.tableFont)
        self.table.setSortingEnabled(2)
        #self.table.resizeColumnsToContents()
        self.table.setRowCount(len(al))
        self.table.setColumnCount(len(self.cols))
        self.table.setHorizontalHeaderLabels(self.cols)
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.handleHeaderMenu)
        self.table.hideColumn(0)
        self.table.setSelectionMode(QAbstractItemView.MultiSelection)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        i = 0
        for q in al:
            #row id
            self.table.setItem(i, 0, QTableWidgetItem(str(q['id'])))
            self.table.setItem(i, 1,
                               QTableWidgetItem(str(q['expensename']).upper()))
            self.table.setItem(i, 2,
                               QTableWidgetItem(str(q['accountname']).upper()))
            zamt = str("{:,}".format(float(q['amount'])))
            self.table.setItem(i, 3, QTableWidgetItem(zamt))
            damz = float(q['datepaid'])
            damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
            self.table.setItem(i, 4, QTableWidgetItem(str(damt)))
            i += 1
        self.table.itemSelectionChanged.connect(self.confirmSelection)
        self.table.resizeRowsToContents()
        v_pull_box = QVBoxLayout()
        self.h1_pull_box = QVBoxLayout()
        self.h1_pull_box.addWidget(self.table)
        v_pull_box.addLayout(h_pull_box)
        v_pull_box.addLayout(self.h1_pull_box)
        h2_pull_box = QHBoxLayout()
        h2_pull_box.addWidget(self.pb1)
        h2_pull_box.addWidget(self.pb3)
        h2_pull_box.addWidget(self.pb6)
        v_pull_box.addLayout(h2_pull_box)

        groupBox3 = QGroupBox()
        groupBox3.setLayout(hbo)
        groupBox2.setLayout(v_pull_box)

        grid = QGridLayout()
        grid.addWidget(groupBox1, 0, 0)
        grid.addWidget(groupBox2, 0, 1, 2, 1)
        grid.addWidget(groupBox3, 1, 0)

        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_editshow())
        self.connect(self.pb2, SIGNAL("clicked()"),
                     lambda: self.button_close(self))
        self.connect(self.pb3, SIGNAL("clicked()"),
                     lambda: self.button_delete())
        self.connect(self.pb4, SIGNAL("clicked()"),
                     lambda: self.button_reset())
        self.connect(self.pb5, SIGNAL("clicked()"), lambda: self.button_edit())
        self.connect(self.pb6, SIGNAL("clicked()"),
                     lambda: self.button_clear())
        self.connect(self.pull_btn,
                     SIGNAL("clicked()"),
                     lambda x=1: self.reloadTable(x))

        self.setWindowTitle(self.pagetitle)

    def handleHeaderMenu(self, pos):
        print('column(%d)' % self.table.horizontalHeader().logicalIndexAt(pos))
        menu = QMenu()
        menu.addAction('Add')
        menu.addAction('Delete')
        menu.exec_(QCursor.pos())

    def pullGroupExpenses(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 15, "active": 0})
        return arr

    def pullExpenses(self, a):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"subID": a})
        return arr

    def pullAccount(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 20, "active": 0})
        return arr

    def pullExpensesData(self):
        st_date = self.fromData.date().toPyDate()
        en_date = self.toData.date().toPyDate()
        st_date = time.mktime(st_date.timetuple())
        en_date = time.mktime(en_date.timetuple())

        db = 'school_expenses' + str(self.session)
        cn = Db()
        arr = cn.selectExpenseDate(db, st_date, en_date)
        return arr

    def mySelectTable(self):
        '''
        get the selected rpws in a table
        returns list or row ids
        '''
        sels = self.table.selectedIndexes()
        sels = self.table.selectionModel().selectedRows()

        park = []
        park1 = []
        for j in sels:
            park.append(j.row())

        for i in set(park):
            selected = self.table.item(i, 0).text()
            park1.append(selected)

        return park1

    def editRow(self, a):
        _session = self.session
        g = Db()
        db = 'school_expenses' + str(_session)
        data = g.selectn(db, '', 1, {'id': a})
        if len(data) > 0:
            self.editID = int(data['id'])
            if float(data['amount']) < 0:
                amt = float(data['amount']) * -1
                self.amountData.setText(str(amt))
                self.r1.setChecked(True)
            else:
                amt = float(data['amount'])
                self.amountData.setText(str(amt))
                self.r2.setChecked(True)

            self.descriptionData.clear()
            self.descriptionData.insertPlainText(str(data['description']))
            self.tellerData.setText(str(data['teller']))
            acID = self.hold_account.keys()[self.hold_account.values().index(
                data['accountID'])]
            self.accountData.setCurrentIndex(acID)
            exID = self.hold_expenses.keys()[self.hold_expenses.values().index(
                data['expenseID'])]
            self.expenseData.setCurrentIndex(exID)

    def reloadExpenses(self):
        cat = self.hold_expensesGroup[self.expenseGroupData.currentIndex()]
        expenses = self.pullExpenses(cat)
        self.expenseData.clear()
        self.hold_expenses = {}
        i = 0
        for a in expenses:
            self.hold_expenses[i] = a['id']
            tex = str(a['name']).upper()
            self.expenseData.addItem(tex)
            i += 1

    def reloadTable(self, a):
        data = self.pullExpensesData()
        self.table.close()
        self.table = QTableWidget()
        header = self.table.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)
        header.setStyleSheet(self.tableHeaderStyle)
        vheader = self.table.verticalHeader()
        vheader.setStyleSheet(self.tableHeaderStyle)
        # Body
        self.table.setWindowTitle("Expenses")
        self.table.resize(300, 250)
        self.table.setFont(self.tableFont)
        self.table.setSortingEnabled(2)
        self.table.resizeColumnsToContents()
        self.table.setRowCount(len(data))
        self.table.setColumnCount(len(self.cols))
        self.table.setHorizontalHeaderLabels(self.cols)
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.handleHeaderMenu)
        self.table.hideColumn(0)
        self.table.setSelectionMode(QAbstractItemView.MultiSelection)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        i = 0
        for q in data:
            #row id
            self.table.setItem(i, 0, QTableWidgetItem(str(q['id'])))
            self.table.setItem(i, 1,
                               QTableWidgetItem(str(q['expensename']).upper()))
            self.table.setItem(i, 2,
                               QTableWidgetItem(str(q['accountname']).upper()))
            zamt = str("{:,}".format(float(q['amount'])))
            self.table.setItem(i, 3, QTableWidgetItem(zamt))
            damz = float(q['datepaid'])
            damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
            self.table.setItem(i, 4, QTableWidgetItem(str(damt)))
            i += 1
        self.table.itemSelectionChanged.connect(self.confirmSelection)
        self.table.resizeRowsToContents()
        self.h1_pull_box.addWidget(self.table)
        self.table.show()

    def pullOnes(self, a, b):
        cn = Db()
        arr = cn.selectn(a, '', 1, {'id': b})
        return arr

    def confirmSelection(self):
        item = self.mySelectTable()
        if len(item) == 1:
            self.pb1.setEnabled(True)
            self.pb3.setEnabled(True)
            self.pb6.setEnabled(True)
        elif len(item) > 1:
            self.pb1.setEnabled(False)
            self.pb3.setEnabled(True)
            self.pb6.setEnabled(True)
        else:
            self.pb1.setEnabled(False)
            self.pb3.setEnabled(False)
            self.pb6.setEnabled(False)

    def button_close(self, b):
        b.close()

    def button_editshow(self):
        item = self.mySelectTable()
        self.editRow(item[0])
        self.pb.hide()
        self.pb4.show()
        self.pb5.show()

    def button_delete(self):
        item = self.mySelectTable()
        _session = self.session
        g = Db()
        db = 'school_expenses' + str(_session)
        for j in item:
            g.delete(db, {'id': j})

        self.reloadTable(1)

    def button_edit(self):
        _session = self.session
        _amount = self.amountData.text()
        _teller = self.tellerData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())
        _description = self.descriptionData.toPlainText()
        _account = self.hold_account[self.accountData.currentIndex()]
        _expense = self.hold_expenses[self.expenseData.currentIndex()]
        if self.r1.isChecked():
            _amount = float(_amount)
        else:
            _amount = float(_amount) * -1

        arr = {}
        if _amount and not (_amount
                            == 0) and int(_expense) > 0 and int(_account) > 0:
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['accountID'] = _account
            arr['expenseID'] = _expense
            arr['teller'] = _teller

            ups = {}
            ups['id'] = self.editID
            if int(self.editID) > 0:
                db = 'school_expenses' + str(_session)
                g = Db()
                g.update(db, arr, ups)
                if int(self.editID) > 0:
                    self.button_reset()

    def button_reset(self):
        self.reloadTable(1)
        self.amountData.setText('')
        self.descriptionData.clear()
        self.tellerData.setText('')
        self.pb4.hide()
        self.pb5.hide()
        self.pb.show()
        self.editID = 0
        self.button_clear()
        self.confirmSelection()

    def button_clear(self):
        self.table.selectionModel().clearSelection()

    def button_click(self):
        _session = self.session
        _amount = self.amountData.text()
        _teller = self.tellerData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())
        _description = self.descriptionData.toPlainText()
        _account = self.hold_account[self.accountData.currentIndex()]
        _expense = self.hold_expenses[self.expenseData.currentIndex()]
        if self.r1.isChecked():
            _amount = float(_amount)
        else:
            _amount = float(_amount) * -1

        arr = {}
        if _amount and not (_amount
                            == 0) and int(_expense) > 0 and int(_account) > 0:
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['accountID'] = _account
            arr['expenseID'] = _expense
            arr['teller'] = _teller

            db = 'school_expenses' + str(_session)
            g = Db()
            ins = g.insert(db, arr)
            if int(ins) > 0:
                self.button_reset()
Beispiel #54
0
class ApBbaDlg(QDialog):
    def __init__(self, parent=None, **kwargs):
        super(ApBbaDlg, self).__init__(parent)

        self.bpms = []
        self.quads = []
        self.corrs = []
        self.quad_dkicks = []
        self.cor_dkicks = []

        self.bba = ap.bba.BbaBowtie()

        self.table = QTableWidget(0, 5)
        self.table.setMinimumHeight(120)
        self.table.setMinimumWidth(500)
        self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        hdview = QHeaderView(Qt.Horizontal)
        self.table.setHorizontalHeaderLabels(
            ['QUAD', 'BPM.field', 'BPM center', "Corr", "Kick"])

        fmbox = QFormLayout()
        self.subprogress = QProgressBar()
        self.subprogress.setTextVisible(True)
        self.subprogress.setSizePolicy(QSizePolicy.MinimumExpanding,
                                       QSizePolicy.Fixed)
        self.progress = QProgressBar()
        self.progress.setTextVisible(True)
        self.progress.setSizePolicy(QSizePolicy.MinimumExpanding,
                                    QSizePolicy.Fixed)
        fmbox.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow)
        fmbox.addRow("Current BPM", self.subprogress)
        fmbox.addRow("All Alignment", self.progress)
        #self.progress.setMaximum(self.repeatbox.value())
        vbox = QVBoxLayout()
        vbox.addWidget(self.table)
        vbox.addLayout(fmbox)

        #hbox.addStretch()
        self.widtab = QTabWidget()

        vbox.addWidget(self.widtab)

        self.setLayout(vbox)

        self.connect(self.widtab, SIGNAL("currentChanged(int)"),
                     self.activateResult)
        self.connect(self.table, SIGNAL("cellClicked(int, int)"),
                     self.activateResult)
        #self.bbathread = ApBbaThread()
        #self.connect(self.bbathread,
        #             SIGNAL("aligned(QString, QString, float, float)"),
        #             self.setResult)
        #self.connect(self.bbathread,
        #             SIGNAL("startAlign(QString, QString, QString)"),
        #             self.appendRecord)

        #self.connect(self.bbathread,
        #             SIGNAL("aligned(QString, QString, float, float)"),
        #             self.bbadlg.appendResult)

    def setInput(self, **kwargs):
        self.bpms = kwargs.get('bpms', [])
        self.quads = kwargs.get('quads', [])
        self.cors = kwargs.get('cors', [])
        self.quad_dkicks = kwargs.get('quad_dkicks', [])
        self.cor_dkicks = kwargs.get('cor_dkicks', [])

    def runAlignment(self, **kwargs):
        self.setInput(**kwargs)
        #self.bbathread.start()
        print "Starting %d measurements" % len(self.bpms)
        self.progress.setMaximum(len(self.bpms))
        self.subprogress.setMaximum(100)
        from cothread.catools import caget, caput
        print __file__, "BBA align", caget('V:2-SR:C30-BI:G2{PH1:11}SA:X')
        self.table.setRowCount(len(self.bpms))
        for i, bpmrec in enumerate(self.bpms):
            print i, bpmrec[0].name, self.quads[i][0].name
            self.bba.setInput(bpmrec, self.quads[i], self.cors[i],
                              self.quad_dkicks[i], self.cor_dkicks[i])
            #self.emit(SIGNAL("startAlign(QString, QString, QString)"),
            #          self.quads[i][0].name, bpmrec[0].name, bpmrec[1])
            self.setNames(i, self.quads[i][0].name, bpmrec[0].name, bpmrec[1],
                          self.cors[i][0].name)
            self.bba.align(verbose=2,
                           guihook=QApplication.processEvents,
                           logger=None,
                           progress=self.subprogress)

            cv1 = BbaMplCanvas()
            cv2 = BbaMplCanvas()
            self.bba.plot(cv1.axes, cv2.axes, factor=(1e6, 1e6))
            cv1.draw()
            cv2.draw()

            wid = QWidget(self)
            hbox = QHBoxLayout()
            hbox.addWidget(cv1)
            hbox.addWidget(cv2)
            wid.setLayout(hbox)
            self.widtab.addTab(wid, "%s.%s" % (bpmrec[0].name, bpmrec[1]))
            self.widtab.setCurrentIndex(i)

            #time.sleep(.1)

            #self.emit(SIGNAL("aligned(QString, QString, float, float)"),
            #          bpmrec[0].name, bpmrec[1], 0.0, 0.0)
            self.setResult(i, bpmrec[0].name, bpmrec[1], self.bba.bpm_fitted,
                           self.bba.cor_fitted)
            self.progress.setValue(i + 1)

    def activateResult(self, i=0, j=0):
        if i < self.widtab.count() and i != self.widtab.currentIndex():
            self.widtab.setCurrentIndex(i)
        if i < self.table.rowCount() and i != self.table.currentRow():
            self.table.setCurrentCell(i, 1)

    def setNames(self, i, quadname, bpmname, fld, corname):
        self.table.setItem(i, 0, QTableWidgetItem(quadname))
        self.table.setItem(i, 1,
                           QTableWidgetItem("{0}.{1}".format(bpmname, fld)))
        self.table.setItem(i, 3, QTableWidgetItem(corname))

    def setResult(self, i, bpmname, fld, bpmval, corval):
        #self.table.setItem(n, 1, QTableWidgetItem(bpmname))
        #self.table.setItem(n, 2, QTableWidgetItem(fld))
        self.table.setItem(i, 2, QTableWidgetItem("%g" % bpmval))
        self.table.setItem(i, 4, QTableWidgetItem("%g" % corval))
        self.table.setCurrentCell(i, 1)
Beispiel #55
0
class PatternsTable(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.grid = QGridLayout()
        self.setLayout(self.grid)
        self.patternArea()
        self.patternTable()

    def createPattern(self, name, x):
        label = name.lower() + "Label"
        type = name.lower() + "Type"
        entry = name.lower() + "Entry"
        setattr(self, label, QLabel(name))
        setattr(self, entry, QLineEdit())
        setattr(self, type, QComboBox())
        labelobj = getattr(self, label)
        typeobj = getattr(self, type)
        entryobj = getattr(self, entry)
        typeobj.addItem("Hexadecimal")
        typeobj.addItem("String")
        self.grid.addWidget(labelobj, x, 0)
        self.grid.addWidget(entryobj, x, 1)
        self.grid.addWidget(typeobj, x, 2)


    def patternArea(self):
        self.filetypeLabel = QLabel("File type")
        self.filetype = QLineEdit()
        self.alignedLabel = QLabel("block aligned")
        self.aligned = QCheckBox()
        self.windowLabel = QLabel("Window size")
        self.window = QSpinBox()
        self.window.setSuffix(" bytes")
        self.window.setRange(0, 2500000)
        self.window.setSingleStep(100)
        self.addEntry = QPushButton("add")
        self.connect(self.addEntry, SIGNAL("clicked()"), self.insertPattern)
        self.grid.addWidget(self.filetypeLabel, 0, 0)
        self.grid.addWidget(self.filetype, 0, 1, 1, 2)
        self.createPattern("Header", 2)
        self.createPattern("Footer", 3)
        self.grid.addWidget(self.windowLabel, 4, 0)
        self.grid.addWidget(self.window, 4, 1)
        self.grid.addWidget(self.alignedLabel, 5, 0)
        self.grid.addWidget(self.aligned, 5, 1)
        self.grid.addWidget(self.addEntry, 6, 1)


    def patternTable(self):
        self.patterns = QTableWidget()
        self.patterns.setShowGrid(False)
        self.patterns.setColumnCount(5)
        self.patterns.setHorizontalHeaderLabels(["Filetype", "Header", "Footer", "Window", "Block aligned"])
        self.patterns.horizontalHeader().setStretchLastSection(True)
        self.connect(self.patterns.verticalHeader(), SIGNAL("sectionClicked(int)"), self.patterns.removeRow)
        self.grid.addWidget(self.patterns, 7, 0, 1, 3)
        

    def warning(self, msg):
        msgBox = QMessageBox(self)
        msgBox.setText(msg)
        msgBox.setIcon(QMessageBox.Warning)
        msgBox.exec_()

    def validate(self, **kwargs):
        msg = ""

        if len(kwargs["type"]) == 0:
            msg = "Type must be defined"
        else:
            for i in kwargs["type"]:
                if i not in string.letters:
                    msg = "Type's characters must be in the following set\n\n" + string.letters
                    break
            rowCount = self.patterns.rowCount()
            for row in range(0, rowCount):
                if str(self.patterns.item(row, 0).text()) == kwargs["type"]:
                    msg = "Type <" + kwargs["type"] + " > already defined"
        if msg != "":
            self.warning(msg)
            return False

        if kwargs["headerType"] == "Hexadecimal" and not self.isHex(kwargs["header"]):
            msg = "Header must be an even number of chars"
            self.warning(msg)
            return False
        
        if len(kwargs["header"]) == 0:
            msg = "Header must be provided"
            self.warning(msg)
            return False

        if kwargs["footerType"] == "Hexadecimal" and not self.isHex(kwargs["footer"]):
            msg = "Footer must be an even number of chars"
            self.warning(msg)
            return False

        if kwargs["window"] <= 0:
            msg = "Window size must be greater than 0"
            self.warning(msg)
            return False

        return True


    def insertPattern(self):
        filetype = str(self.filetype.text())
        header = str(self.headerEntry.text())
        headerType = str(self.headerType.currentText())
        footer = str(self.footerEntry.text())
        footerType = str(self.footerType.currentText())
        window = self.window.text()
        aligned = self.aligned.isChecked()

        #Validate most of provided items
        kwargs = {"type": filetype, "header": header, "headerType": headerType, 
                  "footer": footer, "footerType": footerType, "window": int(window.replace(" bytes", ""))}
        if not self.validate(**kwargs):
            return

        filetypeItem = QTableWidgetItem(filetype)
        headerItem = QTableWidgetItem(header + " (" + headerType[0:3] + ")")
        footerItem = QTableWidgetItem(footer + " (" + footerType[0:3] + ")")
        windowItem = QTableWidgetItem(window)
        alignedItem = QTableWidgetItem(str(aligned))
        self.patterns.insertRow(self.patterns.rowCount())
        vertHeader = QTableWidgetItem(QIcon(":closetab.png"), "")
        row = self.patterns.rowCount() - 1
        self.patterns.setVerticalHeaderItem(row, vertHeader)
        self.patterns.setItem(row, 0, filetypeItem)
        self.patterns.setItem(row, 1, headerItem)
        self.patterns.setItem(row, 2, footerItem)
        self.patterns.setItem(row, 3, windowItem)
        self.patterns.setItem(row, 4, alignedItem)
        self.patterns.resizeRowToContents(row)

        
    def isHex(self, hstr):
        HEXCHAR = "0123456789abcdefABCDEF"
        if len(hstr) % 2 != 0:
            return False
        even = False
        for i in range(len(hstr)):
            if hstr[i] not in HEXCHAR:
                return False
        return True
    

    def toHex(self, str):
        HEXCHAR = "0123456789abcdefABCDEF"
        hexStr = ""
        evenhex = ""
        for i in range(len(str)):
            if str[i] in HEXCHAR:
                if len(evenhex) == 1:
                    hexStr += chr(int(evenhex+str[i], 16))
                    evenhex = ""
                else:
                    evenhex = str[i]
            else:
                raise ValueError, "argument 'str' contains not valid characters"
        if len(evenhex) != 0:
            raise ValueError, "argument 'str' must be an even number of char"
        return hexStr


    def textToPattern(self, text):
        idx = text.find("(")
        pattern = ""
        if idx != -1:
            type = text[idx+1:idx+4]
            pattern = text[0:idx-1]
            if type == "Hex":
                pattern = self.toHex(pattern)
        return pattern


    def selectedItems(self):
        selected = {}
        rowCount = self.patterns.rowCount()
        for row in range(0, rowCount):
            filetype = str(self.patterns.item(row, 0).text())
            selected[filetype] = []
            pattern = []
            pattern.append(self.textToPattern(str(self.patterns.item(row, 1).text())))
            pattern.append(self.textToPattern(str(self.patterns.item(row, 2).text())))
            pattern.append(int(self.patterns.item(row, 3).text().replace(" bytes", "")))
            selected[filetype].append([pattern])
            if self.patterns.item(row, 4).text() == "True":
                selected[filetype].append(True)
            else:
                selected[filetype].append(False)
        return selected
Beispiel #56
0
class PvTunerDlg(QDialog):
    COL = 6
    COL_ELEMENT = 0
    COL_FIELD = 1
    COL_PV = 2
    COL_STEPSIZE = 3
    COL_READBACK = 4
    COL_SETPOINT = 5
    FMT_READBACK = "%.4e"

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

        self.setAttribute(Qt.WA_DeleteOnClose)

        #self.inputBox = QLineEdit("PL2G2C01A.x")
        #self.inputBox = QLineEdit("CXH2G6C01B.x")
        self.inputBox = QLineEdit("PL2G2C01A")

        addPvBtn = QPushButton("add")

        self.table = QTableWidget(0, PvTunerDlg.COL)
        self.table.setHorizontalHeaderLabels(
            ["Element", "Field", "PV", "Stepsize", "Readback", "setpoint"])
        #self.table.horizontalHeader().setStretchLastSection(True)
        #self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)

        box = QGridLayout()
        box.addWidget(self.inputBox, 0, 0)
        box.addWidget(addPvBtn, 0, 1)
        box.addWidget(self.table, 1, 0, 1, 2)
        box.addWidget(buttonBox, 2, 0)

        self.setLayout(box)

        self.pvs_rb = []
        self.pvs_rb_val_flat = []
        self.pvs_sp = []
        self.pvmoni = []
        self.spinbox = []
        self.connect(addPvBtn, SIGNAL("clicked()"), self.addPv)
        self.connect(buttonBox, SIGNAL("accepted()"), self.accept)
        #self.connect(self.table, SIGNAL("cellChanged"), self.updatePv)
        self.connect(buttonBox.button(QDialogButtonBox.Ok),
                     SIGNAL("clicked()"), self.close)
        self.connect(self.table, SIGNAL("cellClicked(int, int)"),
                     self._cell_clicked)

    def _cell_clicked(self, row, column):
        #print row, column
        if column in [self.COL_PV, self.COL_STEPSIZE]:
            item = self.table.item(row, column)
            if not item: return
            item.setFlags(item.flags() | Qt.ItemIsEditable)

    def _appendRecord(self, name):
        vec = name.split('.')
        if len(vec) > 2:
            QMessageBox.critical(None, "ERROR", "format is wrong")
            return

        if len(vec) == 1:
            elem, field = vec[0], 'value'
        elif len(vec) == 2:
            elem, field = vec

        elemobj = hla.getElements(elem)
        if elemobj:
            # pvsrb is a list
            pvsrb = elemobj.pv(field=field, handle='readback')
            self.pvs_rb.append(pvsrb)
            pvssp = elemobj.pv(field=field, handle='setpoint')
            self.pvs_sp.append(pvssp)
        else:
            QMessageBox.critical(None, "ERROR", "element %s not found" % elem)
            return

        # expand one row
        m, n = self.table.rowCount(), self.table.columnCount()
        self.table.insertRow(m)

        # add cells
        item = QTableWidgetItem(elem)
        item.setFlags(item.flags() & (~Qt.ItemIsEditable))
        self.table.setItem(m, self.COL_ELEMENT, item)

        item = QTableWidgetItem(field)
        item.setFlags(item.flags() & (~Qt.ItemIsEditable))
        self.table.setItem(m, self.COL_FIELD, item)

        item = QTableWidgetItem(', '.join(pvsrb))
        #item.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)
        self.table.setItem(m, self.COL_PV, item)

        readval = ['%.4e' % v for v in caget(pvsrb)]
        item = QTableWidgetItem(', '.join(readval))
        item.setFlags(item.flags() & (~Qt.ItemIsEditable))
        self.table.setItem(m, self.COL_READBACK, item)

        # set the stepsize of PV
        stepsize = 0.00001
        if pvssp:
            item = QTableWidgetItem('%f' % stepsize)
            item.setFlags(item.flags() & (~Qt.ItemIsEditable))
            self.table.setItem(m, self.COL_STEPSIZE, item)

            self.spinbox.append(QDoubleSpinBox(self.table))
            self.spinbox[-1].setRange(-100, 100)
            #self.spinbox[-1].setValue(float(10.0))
            self.spinbox[-1].setSingleStep(stepsize)
            self.spinbox[-1].setDecimals(10)

            self.spinbox[-1].valueChanged.connect(self._writePv)

            self.table.setCellWidget(m, self.COL_SETPOINT, self.spinbox[-1])

            sp = float(caget(pvssp)[0])
            #print "setpoint:", pvssp, sp, type(sp)
            self.spinbox[-1].setValue(-1e-5)
            #print "connected", self.spinbox[-1].value()
        else:
            item = self.table.item(m, self.COL_STEPSIZE)
            if item: item.setFlags(item.flags() & (~Qt.ItemIsEditable))
            item = self.table.item(m, self.COL_SETPOINT)
            if item: item.setFlags(item.flags() & (~Qt.ItemIsEditable))
            self.spinbox.append(None)

        self.table.resizeColumnsToContents()

    def addPv(self):
        self._appendRecord(str(self.inputBox.text()))
        self._updateMonitors()

    def minimalSizeHint(self):
        return QSize(800, 600)

    def _writePv(self, v):
        """
        """
        c = QObject.sender(self)
        i = self.spinbox.index(c)
        #print i, c.text(), "changed"

        #print self.pvs_sp[i], v
        caput(self.pvs_sp[i], v)

    def _updateMonitors(self):
        """
        prepare the PV list for camonitor
        """
        #print "Updating monitors"
        pvs = []
        self.pvs_rb_val = []
        for i in range(self.table.rowCount()):
            for j in range(len(self.pvs_rb[i])):
                self.pvs_rb_val.append([i, 0.0])
            pvs.extend(self.pvs_rb[i])

        for p in self.pvmoni:
            p.close()
        self.pvmoni = camonitor(pvs, self._updatePvValues)
        #print self.pvmoni
        #print pvs
        #print self.pvs_rb_val

    def _updatePvValues(self, val, idx):
        #print idx, val
        s = []
        for i, v in enumerate(self.pvs_rb_val):
            if v[0] == self.pvs_rb_val[idx][0]:
                s.append(self.FMT_READBACK % val)
        #print s
        item = self.table.item(self.pvs_rb_val[idx][0], self.COL_READBACK)
        item.setText(','.join(s))

    def closePvMonitors(self):
        #print "Closing PV Monitors"
        for p in self.pvmoni:
            p.close()

        pass

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

    def close(self):
        self.closePvMonitors()
        return True
Beispiel #57
0
class ElemCompDialog(QtGui.QDialog):

    def __init__(self,mz, mass,xp,parent=None):
        QtGui.QDialog.__init__(self, parent)
        settings = QSettings()
        size = settings.value("MainWindow/Size",QVariant(QSize(1024,650))).toSize()
        self.resize(size)

        self.setWindowTitle('Elenmental Composition')
        self.xp=xp
        self.mass=mass
        self.mz=mz
        print mz
        self.initControls()
#        self.initPlots()
    def initControls(self):
        self.plot1 = Qwt.QwtPlot(self)
        self.plot1.setCanvasBackground(Qt.white)
        self.plot2 = Qwt.QwtPlot(self)
        self.plot2.setCanvasBackground(Qt.white)
        self.list = QTreeWidget()
        self.list.setColumnCount(11)
        self.list.setColumnWidth(0,80)
        self.list.setColumnWidth(1,80)
        self.list.setColumnWidth(2,60)
        self.list.setColumnWidth(3,60)
        self.list.setColumnWidth(4,60)
        self.list.setColumnWidth(5,150)
        self.list.setColumnWidth(7,30)
        self.list.setColumnWidth(8,30)
        self.list.setColumnWidth(9,30)
        self.list.setColumnWidth(10,30)
        self.list.setHeaderLabels(['Mass','Calc.Mass','mDa','PPM','DBE','Formula','Fit Conf %','C','H','N','O'])
        self.list.setSortingEnabled(True)
        
        self.table = QTableWidget(1,11)
        self.table.setColumnWidth(0,80)
        self.table.setColumnWidth(1,80)
        self.table.setColumnWidth(2,60)
        self.table.setColumnWidth(3,60)
        self.table.setColumnWidth(4,60)
        self.table.setColumnWidth(5,150)
        self.table.setColumnWidth(7,30)
        self.table.setColumnWidth(8,30)
        self.table.setColumnWidth(9,30)
        self.table.setColumnWidth(10,30)
        self.table.setHorizontalHeaderLabels(['Mass','Calc.Mass','mDa','PPM','DBE','Formula','Fit Conf %','C','H','N','O'])
        self.table.setEditTriggers(QTableWidget.NoEditTriggers)  
        self.table.setSelectionBehavior(QTableWidget.SelectRows)  
        self.table.setSelectionMode(QTableWidget.SingleSelection)  
        self.table.setAlternatingRowColors(True)
        print self.connect(self.table, SIGNAL("itemActivated(QTableWidgetItem*)"), self.tableClicked)
#        self.connect(self.library_list, SIGNAL("itemSelectionChanged()"), self.libraryListClicked)
        up_hbox=QVBoxLayout()
        up_hbox.addWidget(self.table)
        down_hbox = QVBoxLayout()
        down_hbox.addWidget(self.plot1)
        down_hbox.addWidget(self.plot2)
        hbox = QVBoxLayout()
        hbox.addLayout(up_hbox, 3.5)
        hbox.addLayout(down_hbox, 3.5)
        self.setLayout(hbox)
        self.cal_mass()
    def tableClicked(self,item):
        self.C=self.table.item(item.row(),7).text()
        self.H=self.table.item(item.row(),8).text()
        self.N=self.table.item(item.row(),9).text()
        self.O=self.table.item(item.row(),10).text()
        self.cal_isotopic()
        self.initPlots()
    def initPlots(self):
        self.plot1.clear()
#        self.plot1.setTitle("Observed Isotope Distribution")
#        self.plot1.setAxisTitle(Qwt.QwtPlot.xBottom, 'Raman shift (cm-1)')
#        self.plot1.setAxisTitle(Qwt.QwtPlot.yLeft, 'Intensity')
#        grid = Qwt.QwtPlotGrid()
        pen = QPen(Qt.DotLine)
        pen.setColor(Qt.black)
        pen.setWidth(0)
#        grid.setPen(pen)
#        grid.attach(self.plot1)
        self.mass1=self.mass/self.massy*100
        self.plot1.setAxisScale(self.plot1.xBottom,self.x_min,self.x_max)
        self.plot1.setAxisScale(self.plot1.yLeft,0,1.1*100)
        color = QColor('black')
        curve = Qwt.QwtPlotCurve("test1")
        pen = QPen(color)
        pen.setWidth(1)
        curve.setPen(pen)
        curve.setData(self.mass_x,self.mass_y)
        curve.setStyle(Qwt.QwtPlotCurve.Sticks)
        curve.attach(self.plot1)  
        self.plot1.replot()
        
        self.plot2.clear()
#        self.plot2.setTitle("Theoretical Isotope Distribution")
#        self.plot2.setAxisTitle(Qwt.QwtPlot.xBottom, 'Raman shift (cm-1)')
#        self.plot2.setAxisTitle(Qwt.QwtPlot.yLeft, 'Intensity')
#        grid = Qwt.QwtPlotGrid()
        pen = QPen(Qt.DotLine)
        pen.setColor(Qt.blue)
        
        self.plot2.setAxisScale(self.plot1.xBottom,self.x_min,self.x_max)
        self.plot2.setAxisScale(self.plot1.yLeft,0,1.1*100)
        color = QColor('blue')
        curve = Qwt.QwtPlotCurve("test1")
        pen = QPen(color)
        pen.setWidth(1)
        curve.setPen(pen)
#        self.axis= np.arange(len(self.mass))
        curve.setData(self.x,self.y)
        curve.setStyle(Qwt.QwtPlotCurve.Sticks)
        curve.attach(self.plot2)  
        pen.setWidth(0)
#        grid.setPen(pen)
#        grid.attach(self.plot2)
        self.plot2.replot()

    def cal_mass(self):
#        charge=0.0
        tol = 10.0
#        electron=0.000549
        measured_mass=np.round(self.xp)
        limit_lo = measured_mass - (tol/1000.0)
        limit_hi = measured_mass + (tol/1000.0)
        mass=[]
        mass.append((12.000000000,2.0,"C"))
        #mass.append((78.9183376,-1.0,"Br"))
        #mass.append((34.96885271,-1.0,"Cl"))
        #mass.append((31.97207069,0.0,"S"))
        #mass.append((30.97376151,1.0,"P"))
        #mass.append((27.9769265327,2.0,"Si"))
        #mass.append((22.98976967,-1.0,"Na"))
        #mass.append((18.99840320,-1.0,"F"))
        mass.append((15.9949146221,0.0,"O"))
        mass.append((14.0030740052,1.0,"N"))
        mass.append((1.0078250321,-1.0,"H"))
        print range(1,10)
        print mass[0][0]
        print mass[1][0]
        print mass[2][0]
        calc_mass=[]
        for i in range(1,int(floor(measured_mass/mass[0][0]))+1):
            for j in range(0,int(floor((measured_mass-mass[0][0]*i)/mass[1][0]))+1):
                for k in range(0,int(floor((measured_mass-mass[0][0]*i-mass[1][0]*j)/mass[2][0]))+1):
        #            rr=(measured_mass-mass[0][0]*i-mass[1][0]*j-mass[2][0]*k)/mass[3][0]
        #            rrr=round((measured_mass-mass[0][0]*i-mass[1][0]*j-mass[2][0]*k)/mass[3][0])
        #            rrrr=int(round((measured_mass-mass[0][0]*i-mass[1][0]*j-mass[2][0]*k)/mass[3][0]))
        #            print "rr:%s"%rr+" rrr:%s"%rrr+" rrrr:%s"%rrrr
                    r=int(round((measured_mass-mass[0][0]*i-mass[1][0]*j-mass[2][0]*k)/mass[3][0]))
                    calmass=mass[0][0]*i+mass[1][0]*j+mass[2][0]*k+mass[3][0]*r
                    if (mass[0][1]*i+mass[2][1]*k+mass[3][1]*r)>=-1 and calmass>limit_lo and calmass<limit_hi:
                        calc_mass.append((calmass,i,j,k,r))
        print len(calc_mass)
        for ii in range(0,len(calc_mass)):
            mda=(measured_mass-calc_mass[ii][0])*1000
            ppm=(measured_mass-calc_mass[ii][0])/measured_mass*1000000
            DBE=(calc_mass[ii][1]*2+calc_mass[ii][3]-calc_mass[ii][4]+2)/2.0
            self.calmass="%.4f"%calc_mass[ii][0]
            self.mda="%.1f"%mda
            self.ppm="%.1f"%ppm
            self.DBE="%.1f"%DBE
            self.C="%s"%calc_mass[ii][1]
            self.H="%s"%calc_mass[ii][4]
            self.N="%s"%calc_mass[ii][3]
            self.O="%s"%calc_mass[ii][2]
            self.Formula="C%2s"%self.C+" H%2s"%self.H+" N%2s"%self.N+" O%2s"%self.O
            mass=str(self.xp)
#            if not(ii==0):
#                mass=""
            self.cal_isotopic()
            self.initPlots()
            self.conf="%.1f"%self.mass_diff
            self.table.insertRow(ii)
            self.table.setRowHeight(ii,20)
            self.table.setItem(ii, 0,QTableWidgetItem(mass))  
            self.table.setItem(ii, 1,QTableWidgetItem(self.calmass))
            self.table.setItem(ii, 2,QTableWidgetItem(self.mda))
            self.table.setItem(ii, 3,QTableWidgetItem(self.ppm))
            self.table.setItem(ii, 4,QTableWidgetItem(self.DBE))
            self.table.setItem(ii, 5,QTableWidgetItem(self.Formula))
            self.table.setItem(ii, 6,QTableWidgetItem(self.conf))
            self.table.setItem(ii, 7,QTableWidgetItem(self.C))
            self.table.setItem(ii, 8,QTableWidgetItem(self.H))
            self.table.setItem(ii, 9,QTableWidgetItem(self.N))
            self.table.setItem(ii, 10,QTableWidgetItem(self.O))

            item=QTreeWidgetItem([mass,str(self.calmass),str(self.mda),str(self.ppm),str(self.DBE),self.Formula,str(self.conf),str(self.C),str(self.H),str(self.N),str(self.O)])
            self.list.addTopLevelItem(item)
        self.table.removeRow(len(calc_mass))
        self.table.setSortingEnabled(True)
       
#        self.table.sortByColumn(1,Qt.DescendingOrder)
    def next2pow(self):
        return 2**int(np.ceil(np.log(float(self.xx))/np.log(2.0)))
    def cal_isotopic(self):
        MAX_ELEMENTS=5+1  # add 1 due to mass correction 'element'
        MAX_ISOTOPES=4    # maxiumum # of isotopes for one element
        CUTOFF=1e-4       # relative intensity cutoff for plotting
        
        WINDOW_SIZE = 500
        #WINDOW_SIZE=input('Window size (in Da) ---> ');
        
        #RESOLUTION=input('Resolution (in Da) ----> ');  % mass unit used in vectors
        RESOLUTION = 1
        if RESOLUTION < 0.00001:#  % minimal mass step allowed
          RESOLUTION = 0.00001
        elif RESOLUTION > 0.5:  # maximal mass step allowed
          RESOLUTION = 0.5
        
        R=0.00001/RESOLUTION#  % R is used to scale nuclide masses (see below)
        
        WINDOW_SIZE=WINDOW_SIZE/RESOLUTION; 
        self.xx=WINDOW_SIZE  # convert window size to new mass units
        WINDOW_SIZE=self.next2pow();  # fast radix-2 fast-Fourier transform algorithm
        
        if WINDOW_SIZE < np.round(496708*R)+1:
          WINDOW_SIZE = self.next2pow(np.round(496708*R)+1)  # just to make sure window is big enough
        
        
        #H378 C254 N65 O75 S6
        M=np.array([int(self.H),int(self.C),int(self.N),int(self.O),0,0]) #% empiric formula, e.g. bovine insulin
        
        # isotopic abundances stored in matrix A (one row for each element)
        A=np.zeros((MAX_ELEMENTS,MAX_ISOTOPES,2));
        
        A[0][0,:] = [100783,0.9998443]#                 % 1H
        A[0][1,:] = [201410,0.0001557]#                 % 2H
        A[1][0,:] = [100000,0.98889]#                   % 12C
        A[1][1,:] = [200336,0.01111]#                   % 13C
        A[2][0,:] = [100307,0.99634]#                   % 14N
        A[2][1,:] = [200011,0.00366]#                   % 15N
        A[3][0,:] = [99492,0.997628]#                  % 16O
        A[3][1,:] = [199913,0.000372]#                  % 17O
        A[3][2,:] = [299916,0.002000]#                  % 18O
        A[4][0,:] = [97207,0.95018]#                   % 32S
        A[4][1,:] = [197146,0.00750]#                   % 33S
        A[4][2,:] = [296787,0.04215]#                   % 34S
        A[4][3,:] = [496708,0.00017]#                   % 36S
        A[5][0,:] = [100000,1.00000]#                   % for shifting mass so that Mmi is
        #                                             % near left limit of window
        
        Mmi=np.array([np.round(100783*R), np.round(100000*R),\
                     np.round(100307*R),np.round(99492*R), np.round(97207*R), 0])*M#  % (Virtual) monoisotopic mass in new units
        Mmi = Mmi.sum()
        #% mass shift so Mmi is in left limit of window:
        FOLDED=np.floor(Mmi/(WINDOW_SIZE-1))+1#  % folded FOLDED times (always one folding due to shift below)
        #% shift distribution to 1 Da from lower window limit:
        M[MAX_ELEMENTS-1]=np.ceil(((WINDOW_SIZE-1)-np.mod(Mmi,WINDOW_SIZE-1)+np.round(100000*R))*RESOLUTION)
        
        MASS_REMOVED=np.array([0,11,13,15,31,-1])*M#% correction for 'virtual' elements and mass shift
        begin=WINDOW_SIZE*RESOLUTION+MASS_REMOVED.sum()
        end=2*(WINDOW_SIZE-1)*RESOLUTION+MASS_REMOVED.sum()
        
        ptA=np.ones(WINDOW_SIZE);
        t_fft=0
        t_mult=0
        
        for i in xrange(MAX_ELEMENTS):
        
            tA=np.zeros(WINDOW_SIZE)
            for j in xrange(MAX_ISOTOPES):
                if A[i][j,0] != 0:
                    #removed +1 after R)+1 --we're using python
                    tA[np.round(A[i][j,0]*R)]=A[i][j,1]#;  % put isotopic distribution in tA
            t0 = time.clock()
            tA=F.fft(tA) # FFT along elements isotopic distribution  O(nlogn)
            t_fft = time.clock()-t0
            t0 = time.clock()
            tA=tA**M[i]#  % O(n)
            #################
            ptA = ptA*tA#  % O(n)#this is where it is messing UP
            #################
            t1 = time.clock()
            t_mult=t1-t0
        

        t0=time.clock()
        ptA=F.ifft(ptA).real#;  % O(nlogn)

        t0=time.clock()
        
        MA=np.linspace(begin,end,WINDOW_SIZE-1)
        ind=np.where(ptA>CUTOFF)[0]
        
        self.x = MA[ind]
        self.y = ptA[ind]
        self.x_min=int(np.min(self.x)-(np.max(self.x)-np.min(self.x)))
        self.x_max=int(np.min(self.x)+(np.max(self.x)-np.min(self.x)))
        
        self.mass_y=np.ones(len(self.x))
        mass_diff=np.ones(len(self.x))
        
        mzInd= np.logical_and((self.mz>=self.x_min),(self.mz<=self.x_max))
        self.mass_y=self.mass[mzInd]
        self.mass_x=self.mz[mzInd]
        
        
#         for i in range(len(self.x)):
#             self.mass_y[i]=self.mass[int(self.x[i])]
        self.massy=np.max(self.mass_y)
        print self.massy
        self.mass_y=self.mass_y/max(self.mass_y)*100
        self.y=self.y/max(self.y)*100
#        k=(self.mass_y*self.y).sum()/(self.mass_y*self.mass_y).sum()
#        self.fit=((k*self.mass_y-self.y)*(k*self.mass_y-self.y)).sum()/(self.y*self.y).sum()
        for i in range(len(self.y)):
            mass_diff[i]=np.abs(self.mass_y[i]-self.y[i])/(self.mass_y[i]+self.y[i])
        self.mass_diff=(1-mass_diff.sum()/len(mass_diff))*100