Exemple #1
0
 def iconChooser(self):
     ' Choose a Icon and copy it to clipboard '
     #
     from .std_icon_naming import std_icon_naming as a
     #
     prv = QDialog(self.dock)
     prv.setWindowFlags(Qt.FramelessWindowHint)
     prv.setAutoFillBackground(True)
     prv.setGeometry(self.fileView.geometry())
     table = QTableWidget(prv)
     table.setColumnCount(1)
     table.setRowCount(len(a))
     table.verticalHeader().setVisible(True)
     table.horizontalHeader().setVisible(False)
     table.setShowGrid(True)
     table.setIconSize(QSize(128, 128))
     for index, icon in enumerate(a):
         item = QTableWidgetItem(QIcon.fromTheme(icon), '')
         # item.setData(Qt.UserRole, '')
         item.setToolTip(icon)
         table.setItem(index, 0, item)
     table.clicked.connect(lambda: QApplication.clipboard().setText(
       'QtGui.QIcon.fromTheme("{}")'.format(table.currentItem().toolTip())))
     table.doubleClicked.connect(prv.close)
     table.resizeColumnsToContents()
     table.resizeRowsToContents()
     QLabel('<h3> <br> 1 Click Copy, 2 Clicks Close </h3>', table)
     table.resize(prv.size())
     prv.exec_()
Exemple #2
0
    def setSnapshotTabWindow(self, eventNames, eventTs, eventIds):
        tabWidget = None
        isNew = True
        
        for i in range(len(eventIds)):
            if self.tabWindowDict.has_key(eventIds[i]):
                tabWidget = self.tabWindowDict[eventIds[i]]
            else:
                tabWidget = QTableWidget()
                self.tabWindowDict[eventIds[i]] = tabWidget
                QObject.connect(tabWidget, SIGNAL(_fromUtf8("cellDoubleClicked (int,int)")), self.__showArrayData)
            
            data = self.retrieveMasarData(eventid=eventIds[i])
            if data:
                if isNew:
                    for j in range(self.snapshotTabWidget.count(), 0, -1):
                        self.snapshotTabWidget.removeTab(j)
            
                    self.pv4cDict.clear()
                    self.data4eid.clear()
                    self.arrayData.clear()
                    isNew = False

                tabWidget.clear()
                self.setSnapshotTable(data, tabWidget, eventIds[i])
                tabWidget.resizeColumnsToContents()
                ts = eventTs[i].split('.')[0]
                
                label = QString.fromUtf8((eventNames[i]+': ' + ts))
                self.snapshotTabWidget.addTab(tabWidget, label)
                self.snapshotTabWidget.setTabText(i+1, label)
                self.pv4cDict[str(eventIds[i])] = data['PV Name']
                self.data4eid[str(eventIds[i])] = data
            
        self.snapshotTabWidget.setCurrentIndex(1)
Exemple #3
0
    def getMachinePreviewAction(self):
        selectedConfig = self.configTableWidget.selectionModel().selectedRows()
        lc = len(selectedConfig)
        if lc != 1:
            QMessageBox.warning(self,
                "Warning",
                "Please select one configuration, and one only.")
            return

        self.previewId = None
        self.previewConfName = None
        
        cname = str(self.configTableWidget.item(selectedConfig[0].row(), 0).text())
        result = self.getMachinePreviewData(cname)
        if result:
            eid = result[0]
            data = result[1]
            self.pv4cDict[str(eid)] = data['PV Name']
            self.data4eid[str(eid)] = data
            
            try:
                tabWidget = self.tabWindowDict['preview']
                index = self.snapshotTabWidget.indexOf(tabWidget)
            except:
                tabWidget = QTableWidget()
                index = self.snapshotTabWidget.count()
                self.tabWindowDict['preview'] = tabWidget
                QObject.connect(tabWidget, SIGNAL(_fromUtf8("cellDoubleClicked (int,int)")), self.__showArrayData)
            
            self.setSnapshotTable(data, tabWidget, eid)
            tabWidget.resizeColumnsToContents()
            label = QString.fromUtf8((cname+': Preview'))
            self.snapshotTabWidget.addTab(tabWidget, label)
    
            self.snapshotTabWidget.setTabText(index, label)        
            self.snapshotTabWidget.setCurrentIndex(index)
            
            self.previewId = eid
            self.previewConfName = cname
            self.isPreviewSaved = False
    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)
class ViewTableForm(QWidget):
    def __init__(self, visualization, parent_widget = None):
        QWidget.__init__(self, parent_widget)
        self.inGui = False

        self.widgetLayout = QVBoxLayout(self)

        self.tableWidget = QTableWidget(self)
        self.tableWidget.setObjectName("tableWidget")
        size = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.tableWidget.setSizePolicy(size)
        self.widgetLayout.addWidget(self.tableWidget)

        self.tabIcon = QIcon(":/Images/Images/map.png")

        self.tabLabel = visualization.table_name

        self.load_table(visualization = visualization)

    def load_table(self, visualization, limit = 10000):

        storage = StorageFactory().get_storage(
                       type = '%s_storage'%visualization.output_type,
                       storage_location = visualization.storage_location)
        table_data = storage.load_table(
                                table_name = visualization.table_name)

        try:
            primary_keys = visualization.indicators[0].primary_keys
        except:
            primary_keys = []

        keys = primary_keys + [key for key in table_data.keys()
                                   if key not in primary_keys]
        num_rows = min(len(table_data[keys[0]]), limit)
        num_cols = len(keys)

        self.tableWidget.clear()
        self.tableWidget.setColumnCount(num_cols)
        self.tableWidget.setRowCount(num_rows)

        j = 0
        for key in keys:
            col = QTableWidgetItem()
            col.setText(QString(key))
            self.tableWidget.setHorizontalHeaderItem(j,col)
            j += 1

        self.tableWidget.resizeColumnsToContents()

        order = sorted(enumerate(table_data[keys[0]]), lambda (i,v),(j,v2): int(v*100)-int(v2*100))

        for i, (idx,v) in enumerate(order):
            row = QTableWidgetItem()
            self.tableWidget.setVerticalHeaderItem(i,row)
            j = 0
            for key in keys:
                item = QTableWidgetItem()
                item.setText(QString(str(table_data[key][idx])))
                self.tableWidget.setItem(i,j,item)
                j += 1
            if i > limit:
                msg = 'The table %s has been truncated to %i rows because of memory limitations.'%(visualization.table_name,limit)
                detailed_msg = '<qt>To view the full results, open the following file:<br><br><small>%s</small></qt>'%visualization.get_file_path()
                MessageBox.warning(mainwindow = self,
                                  text = msg,
                                  detailed_text = detailed_msg)
                break


        #self.tableWidget.resizeRowsToContents()
    def removeElement(self):
        return True
Exemple #6
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()
Exemple #7
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
Exemple #8
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()
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)
Exemple #10
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())
class ActionEditorDialog(QWidget):

    # Redefine the tr() function for this class.
    def tr(self, text):
    
        return qApp.translate("ActionEditorDialog", text)

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

        help = QLabel(translate("Shortcut Settings", '<b>Double click a cell in the Shortcut Column' \
            ' to <br />modify the key sequence.</b>'))
        
        self.actionTable = QTableWidget(self)
        self.actionTable.setSelectionBehavior(QTableWidget.SelectRows)
        self.actionTable.setEditTriggers(QTableWidget.DoubleClicked)
        self.actionTable.setColumnCount(2)
        self.actionTable.setHorizontalHeaderLabels(
            [translate("Shortcut Settings", "Description"),
            translate("Shortcut Settings", "Shortcut")]
            )
        self.actionTable.horizontalHeader().setStretchLastSection(True)
        self.actionTable.verticalHeader().hide()
        self.actionTable.setItemDelegate(ActionEditorDelegate(self))
        
        self.connect(self.actionTable, SIGNAL("cellChanged(int, int)"),
                     self.validateAction)
        
        row = 0
        for action in self.actions:
        
            if action.text().isEmpty():
                continue
            
            self.actionTable.insertRow(self.actionTable.rowCount())
            
            item = QTableWidgetItem()
            item.setText(action.text())
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
            self.actionTable.setItem(row, 0, item)
            
            item = QTableWidgetItem()
            item.setText(action.shortcut().toString())
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable)
            item.oldShortcutText = item.text()
            self.actionTable.setItem(row, 1, item)
            
            row += 1
        
        self.actionTable.resizeColumnsToContents()
                
        mainLayout = QVBoxLayout()
        mainLayout.addWidget(help)
        mainLayout.setMargin(8)
        mainLayout.setSpacing(8)
        mainLayout.addWidget(self.actionTable)
        self.setLayout(mainLayout)
        self._model = self.actionTable.model()
        self._model.edited = False
        self.actionTable.model().edited = False
        
        self.setWindowTitle(translate("Shortcut Settings", "Edit Shortcuts"))
    
    def applySettings(self, control=None):
        if not self._model.edited:
            return
    
        row = 0
        for action in self.actions:
        
            if not action.text().isEmpty():
                action.setText(self.actionTable.item(row, 0).text())
                action.setShortcut(QKeySequence(self.actionTable.item(row, 1).text()))
                row += 1
        self.saveSettings(self.actions)
        self._model.edited = False
    
    def _loadSettings(self, actions):
        
        cparser = PuddleConfig(os.path.join(CONFIGDIR, 'user_shortcuts'))

        for action in actions:
            shortcut = cparser.get('shortcuts', unicode(action.text()), '')
            if shortcut:
                action.setShortcut(QKeySequence(shortcut))
    
    _loadSettings = classmethod(_loadSettings)
    
    def saveSettings(self, actions):
        
        cparser = PuddleConfig(os.path.join(CONFIGDIR, 'user_shortcuts'))
        for action in actions:
            shortcut = unicode(action.shortcut().toString())
            cparser.set('shortcuts', unicode(action.text()), shortcut)
    
    saveSettings = classmethod(saveSettings)
    
    def validateAction(self, row, column):
    
        if column != 1:
            return
        
        item = self.actionTable.item(row, column)
        shortcutText = QKeySequence(item.text()).toString()
        thisRow = self.actionTable.row(item)
        
        if not shortcutText.isEmpty():
            for row in range(self.actionTable.rowCount()):
                if row == thisRow:
                    continue
                
                other = self.actionTable.item(row, 1)
                
                if other.text() == shortcutText:
                    other.setText(item.oldShortcutText)
                    break
            
            item.setText(shortcutText)
            item.oldShortcutText = shortcutText
        
        self.actionTable.resizeColumnToContents(1)
Exemple #12
0
class RLibraryBrowser(QDialog):

    def __init__(self, parent=None, paths=None):
        QDialog.__init__(self, parent)
        QShortcut(QKeySequence("Escape"), self, self.reject)
        self.setWindowTitle("manageR - Library Browser")
        self.resize(500, 500)
        port = robjects.r('tools:::httpdPort')[0]
        if not port > 0:
            robjects.r('tools::startDynamicHelp()')
            port = robjects.r('tools:::httpdPort')[0]
        robjects.r("""make.packages.html()""")
        host = "localhost"
        home = "/doc/html/packages.html"
        #splitter = QSplitter(self)
        #splitter.setOrientation(Qt.Vertical)
        #splitter.setFrameStyle(QFrame.StyledPanel|QFrame.Sunken)
        labels = QStringList(["Loaded", "Package",
                              "Title",  "Path"])
        self.parent = parent
        self.home = home
        self.packageTable = QTableWidget(0, 4, self)
        self.htmlViewer = HtmlBrowser(self, host, port, home, paths)
        #splitter.addWidget(self.packageTable)
        #splitter.addWidget(self.htmlViewer)
        vbox = QVBoxLayout(self)
        #hbox.addWidget(splitter)
        vbox.addWidget(self.packageTable)
        vbox.addWidget(self.htmlViewer)
        self.packageTable.setHorizontalHeaderLabels(labels)
        self.packageTable.setShowGrid(True)
        self.packageTable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.packageTable.setSelectionMode(QAbstractItemView.SingleSelection)
        self.packageTable.setAlternatingRowColors(True)
        self.updatePackages()
        self.connect(self.packageTable,
            SIGNAL("itemChanged(QTableWidgetItem*)"), self.loadPackage)
        self.connect(self.packageTable,
            SIGNAL("itemDoubleClicked(QTableWidgetItem*)"), self.showPackage)

    def setSource(self, source):
        self.htmlViewer.setSource(source)

    def showPackage(self, item):
        row = item.row()
        tmp = self.packageTable.item(row, 1)
        package = tmp.text()
        home = QUrl(self.home)
        curr = QUrl("../../library/%s/html/00Index.html" % package)
        self.htmlViewer.setSource(home.resolved(curr))

    def loadPackage(self, item):
        row = item.row()
        tmp = self.packageTable.item(row, 1)
        package = tmp.text()
        if item.checkState() == Qt.Checked:
            command = "library(%s)" % package
        else:
            command = "detach('package:%s')" % package
        robjects.r(command)
        #self.emit(SIGNAL(...(command)

    def updatePackages(self):
        library_ = robjects.r.get('library', mode='function')
        packages_ = robjects.r.get('.packages', mode='function')
        loaded = list(packages_())
        packages = list(library_()[1])
        length = len(packages)
        self.packageTable.clearContents()
        #self.table.setRowCount(length/3)
        packageList = []
        for i in range(length/3):
            package = unicode(packages[i])
            if not package in packageList:
                packageList.append(package)
                self.packageTable.setRowCount(len(packageList))
                item = QTableWidgetItem("Loaded")
                item.setFlags(
                Qt.ItemIsUserCheckable|Qt.ItemIsEnabled|Qt.ItemIsSelectable)
                if package in loaded:
                    item.setCheckState(Qt.Checked)
                else:
                    item.setCheckState(Qt.Unchecked)
                self.packageTable.setItem(i, 0, item)
                item = QTableWidgetItem(unicode(packages[i]))
                item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable)
                self.packageTable.setItem(i, 1, item)
                item = QTableWidgetItem(unicode(packages[i+(2*(length/3))]))
                item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable)
                self.packageTable.setItem(i, 2, item)
                item = QTableWidgetItem(unicode(packages[i+(length/3)]))
                item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable)
                self.packageTable.setItem(i, 3, item)
        self.packageTable.resizeColumnsToContents()
Exemple #13
0
class Search(QDialog):

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

        self.create_layout()
        self.create_connections()

    def create_layout(self):
        label = QLabel("Your query:")
        self.query_edit = QLineEdit()
        self.find_button = QPushButton("Search")
        self.get_button = QPushButton("Get selected books")

        self.table = QTableWidget()
        self.table.setColumnCount(3)
        self.table.setHorizontalHeaderLabels(['Select', 'Name', 'URL'])

        hbox = QHBoxLayout()
        hbox.addWidget(label)
        hbox.addWidget(self.query_edit)
        hbox.addWidget(self.find_button)

        vbox = QVBoxLayout()
        vbox.addLayout(hbox)
        vbox.addWidget(self.table)
        vbox.addWidget(self.get_button)

        self.setLayout(vbox)

    def create_connections(self):
        self.connect(self.find_button, SIGNAL('clicked()'), self.render_result)
        self.connect(self.get_button, SIGNAL('clicked()'), self.download)

    def render_result(self):
        query = self.query_edit.text()
        if not query:
            return

        self.feed = FeedBooks()
        response = self.feed.search(str(query))

        if not response:
            QMessageBox.critical(self, 'Error', 'Could not get any result')
            return

        self.table.clear()
        self.table.setHorizontalHeaderLabels(['Select', 'Title', 'URL'])
        self.table.setRowCount(len(response[1]))

        for i, name in enumerate(zip(response[1], response[3])):
            item = QTableWidgetItem(1)
            item.data(Qt.CheckStateRole)
            item.setCheckState(Qt.Checked)
            self.table.setItem(i, 0, item)

            for j in range(2):
                item = QTableWidgetItem(name[j])
                item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                self.table.setItem(i, j+1, item)

        self.table.resizeColumnsToContents()

    def download(self):
        rows = self.table.rowCount()

        progress = QProgressDialog("Downloading books...", "Abort download", 0,
                                   rows, self)
        progress.setWindowModality(Qt.WindowModal)
        progress.show()

        to_download = [self.table.item(row, 2).text() for row in range(rows) if
                       self.table.item(row, 0).checkState() == Qt.Checked]

        for i, book in enumerate(to_download):
            progress.setValue(i)
            book_id = self.feed.download(str(book))
            if not book_id:
                QMessageBox.critical(self, 'Error', 'Could not download the '
                                     'book')
            elif book_id != -1:
                book = Book(book_id)
                insert_library(book)

            if progress.wasCanceled():
                break

        progress.setValue(rows)
        progress.close()
        self.parent().library.refresh()
class SentenceFillDlg(QDialog, ui_sentencefilldlg.Ui_SentenceFillDlg):
	
	def __init__(self, tableName, rangeValues, parent=None):
		super(SentenceFillDlg, self).__init__(parent)
		self.tableName = tableName
		self.rangeValues = rangeValues
		self.setupUi(self)
		self.initUI()
		
	def initUI(self):
		fontLabel = QFont('SansSerif', 14)
		
		self.setMinimumSize(1200, 600)
		self.resize(1200, 600)
		
		self.sentenceToFillTable = QTableWidget(5, 1, self)
		self.sentenceToFillTable.setGeometry(QRect(70, 60, 800, 400))
		
		self.sentenceToFillTable.setColumnCount(1)
		
		item = QTableWidgetItem()
		item.setText('Sentences To Match')
		font = QFont()
		font.setBold(True)
		font.setWeight(75)
		item.setFont(font)
		self.sentenceToFillTable.setHorizontalHeaderItem(0, item)
		self.sentenceToFillTable.resizeColumnsToContents()
		self.sentenceToFillTable.horizontalHeader().setStretchLastSection(True)
		self.sentenceToFillTable.verticalHeader().setStretchLastSection(True)
		
		self.sentenceList = []
		self.getSentencesFromDatabase()
		
		# split the sentences into chunks of 5
		# Map to hold the anwers
		self.rightWordList = {}
		
		self.iteration = 0
		self.sentenceMasterList = []
		self.sentenceSlaveList = []
		
		if len(self.sentenceList) > 0:			
			for sentence in self.sentenceList:
				if len(self.sentenceSlaveList) < 5:
					self.sentenceSlaveList.append(sentence)
				else:
					self.sentenceMasterList.append(self.sentenceSlaveList)
					self.sentenceSlaveList = []
					self.sentenceSlaveList.append(sentence)
					
			if len(self.sentenceSlaveList) <= 5:
				self.sentenceMasterList.append(self.sentenceSlaveList)
				
			self.maxIteration = len(self.sentenceMasterList)
		
		
		## set the row height
		self.tableHeightSize = 0
		## Only if there is atleast one sentence fetched from the database
		if len(self.sentenceList) > 0:			
			for index in range(0, 5):
				if len(self.sentenceList[index]) < 150:
					self.sentenceToFillTable.verticalHeader().resizeSection(index, 80)
					self.tableHeightSize = self.tableHeightSize + 90
				elif len(self.sentenceList[index]) < 200:
					self.sentenceToFillTable.verticalHeader().resizeSection(index, 100)
					self.tableHeightSize = self.tableHeightSize + 100
				else:
					self.sentenceToFillTable.verticalHeader().resizeSection(index, 120)
					self.tableHeightSize = self.tableHeightSize + 120
			
				
			# split words from databse into chunks of 5
		
			self.refIteration = 0
			self.refWordMasterList = []
			self.refWordSlaveList = []
			for wordList in self.wordMap.values():
				if len(self.refWordSlaveList) < 5:
					self.refWordSlaveList.append(wordList)
				else:
					self.refWordMasterList.append(self.refWordSlaveList)
					self.refWordSlaveList = []
					self.refWordSlaveList.append(wordList)
			
			if len(self.refWordSlaveList) <= 5:
				self.refWordMasterList.append(self.refWordSlaveList)
				
			self.refMaxIteration = len(self.refWordMasterList)
		
			self.insertSentencesInTable()
		
		self.connect(self.sentenceToFillTable, SIGNAL("cellClicked(int, int)"), self.itemSelect)
		
		# create next, submit and close buttons
		self.nextButton = QPushButton('Next', self)
		self.nextButton.move(170, 520)
		self.nextButton.setEnabled(False)  
		
		self.submitButton = QPushButton('Submit', self)
		self.submitButton.move(380, 520)
		
		self.closeButton = QPushButton('Close', self)
		self.closeButton.move(600, 520)
		
		self.connect(self.closeButton, SIGNAL('clicked()'), self.closeClicked)
		
		self.connect(self.submitButton, SIGNAL('clicked()'), self.onSubmitClicked)
		
		self.connect(self.nextButton, SIGNAL('clicked()'), self.onNextClicked)
		
		self.setWindowTitle('Sentence Fill')
		
		#self.setGeometry(10, 80, 1100, 750)


	def getSentencesFromDatabase(self):
		self.twoTypeList = data.Data().getSentencesFromDatabase(self.tableName, self.rangeValues)
		if len(self.twoTypeList) == 2:
			self.sentenceList = self.twoTypeList[0]
			self.wordMap = self.twoTypeList[1]

	def closeClicked(self):
		reply = QMessageBox.question(self,
					"Fill the Sentences",
					"You want to close the application",
					QMessageBox.Yes | QMessageBox.No)
		if reply == QMessageBox.Yes:
			self.reject()
			
	def onNextClicked(self):
		if not self.iteration < self.maxIteration:
			QMessageBox.information(self,
					"Fill the Sentences",
					"All Sentences are matched",
					QMessageBox.Ok)
		else:
			self.sentenceToFillTable.clearContents()
			## Fetch the next records
			self.refIteration = self.refIteration + 1
			self.rightWordList = {}
			## clear the contents of the combo box
			self.wordListComboBox.clear()
			self.insertSentencesInTable()
	
	# validate whether the user has matched the blanks with a value during next and submit button clicks
	def onNextSubmitValidation(self):
		self.textNotFilled = False
		for row in range(0, len(self.currentSentenceListInTable)):
			if self.sentenceToFillTable.item(row, 0).text() == self.currentSentenceListInTable[row]:
				self.textNotFilled = True
		if self.textNotFilled:
			QMessageBox.information(self,
						"Fill the sentences",
						"Match all the sentences in the table",
						QMessageBox.Ok)
			self.nextButton.setEnabled(False)
			
			
	def onSubmitClicked(self):
		self.wordsMatched = True
		self.allWordsMatched = True
		brushRed = QBrush(QColor(255,0,0))
		brushRed.setStyle(Qt.SolidPattern)
		
		brushGreen = QBrush(QColor(0,255,0))
		brushGreen.setStyle(Qt.SolidPattern)
		
		# validate whether the user all matched the blanks with a value
		#self.onNextSubmitValidation()
		textNotFilled = False
		for row in range(0, len(self.currentSentenceListInTable)):
			if self.sentenceToFillTable.item(row, 0).text() == self.currentSentenceListInTable[row]:
				textNotFilled = True
		if textNotFilled:
			QMessageBox.information(self,
						"Fill the sentences",
						"Match all the sentences in the table",
						QMessageBox.Ok)
		else:
			splittedSentence = []
			foundWordInSentence = ""
			self.rightWordListCopy = self.rightWordList
			for row in range(0, len(self.currentSentenceListInTable)):
				sentenceFilled = str(self.sentenceToFillTable.item(row, 0).text())
				newSplittedSentence = [word.strip() for word in sentenceFilled.split()]
				splittedSentence = []
				for word in newSplittedSentence:
					match = re.search(r'\w+', word)
					if match:
						splittedSentence.append(str(match.group()))
				
				wordList = self.rightWordListCopy[row]
				
				if len(wordList) > 1:
					firstWord = wordList[0].strip()
					secondWord = wordList[1].strip()
					if ' ' in firstWord:
						for word in firstWord.split():
							if word not in splittedSentence:
								self.wordsMatched = False
					else:
						if firstWord not in splittedSentence:
							self.wordsMatched = False
					
					if self.wordsMatched: ## check is valid only if the first word is matched
						if ' ' in secondWord:
							for word in secondWord.split():
								if word not in splittedSentence:
									self.wordsMatched = False
						else:
							if secondWord not in splittedSentence:
								self.wordsMatched = False
				elif len(wordList) == 1:
					word = wordList[0].strip()
					if word not in splittedSentence:
						self.wordsMatched = False
				
				if self.wordsMatched:
					self.sentenceToFillTable.item(row, 0).setBackground(brushGreen)
				else:
					self.sentenceToFillTable.item(row, 0).setBackground(brushRed)
					self.allWordsMatched = False
				
				self.wordsMatched = True
					
			if self.allWordsMatched:
				self.nextButton.setEnabled(True)
				QMessageBox.information(self,
								"Fill the sentences",
								"All sentences are matched",
								QMessageBox.Ok)

	def insertSentencesInTable(self):
		if self.iteration < self.maxIteration:
			cellList = []
			self.col = 0
			self.currentSentenceListInTable = self.sentenceMasterList[self.iteration]
			for sentence in self.currentSentenceListInTable:
				item = QTableWidgetItem(QString(sentence))
				item.setFlags(Qt.ItemFlags(Qt.ItemIsSelectable |
								Qt.ItemIsEnabled))
				cellList.append(item)
			cellList.reverse()
			
			for index in range(0, len(self.currentSentenceListInTable)):
				self.sentenceToFillTable.setItem(index, self.col, cellList.pop())
				
			self.sentenceToFillTable.setRowCount(len(self.sentenceMasterList[self.iteration]))
			
			self.sentenceToFillTable.setFixedHeight(self.tableHeightSize)
			
			# increment the count for the next button click
			self.iteration = self.iteration + 1
			
	def createComboBox(self, rowIndex):
		self.xAxis = 1000
		self.yAxis = 80
		
		if self.refIteration < self.refMaxIteration:
			wordListWithFiveArrays = self.refWordMasterList[self.refIteration]
			requiredWordList = wordListWithFiveArrays[rowIndex]
			
			## Create a combo box
			self.wordListComboBox = QComboBox(self)
			self.wordListComboBox.setGeometry(900, 80, 100, 20)
			self.connect(self.wordListComboBox, SIGNAL("currentIndexChanged(int)"),
							self.wordSelected)
			self.wordListComboBox.show()
			
			## save the right word
			if len(requiredWordList) > 0:
				if rowIndex not in self.rightWordList.keys():
					if len(requiredWordList) > 0:
						wordList = requiredWordList[0].split('&')
						self.rightWordList[rowIndex] = wordList

			## insert words in the combo box
			random.shuffle(requiredWordList)
			random.shuffle(requiredWordList)
			
			self.wordListComboBox.addItem('         ')
			self.wordListComboBox.addItems(requiredWordList)
	
	def wordSelected(self):
		## Avoid the blank option
		if len(str(self.wordListComboBox.currentText()).strip()) > 0:
			sentence = self.currentSentenceListInTable[self.selectedSentenceIndex]
			splittedText = sentence.split('-')
			if len(splittedText) == 2:
				item = QTableWidgetItem(QString(splittedText[0] +
						str(self.wordListComboBox.currentText()) + ' ' + splittedText[1].strip()))
				item.setFlags(Qt.ItemFlags(Qt.ItemIsSelectable | 
								Qt.ItemIsEnabled))
				self.sentenceToFillTable.setItem(self.selectedSentenceIndex, 0, item)
			elif len(splittedText) > 2:
				wordsFromCombobox = str(self.wordListComboBox.currentText()).split('&')
				item = QTableWidgetItem(QString(splittedText[0] + wordsFromCombobox[0]
							+ splittedText[1] + wordsFromCombobox[1] + ' ' + splittedText[2].strip()))
				item.setFlags(Qt.ItemFlags(Qt.ItemIsSelectable | 
							Qt.ItemIsEnabled))
				self.sentenceToFillTable.setItem(self.selectedSentenceIndex, 0, item)
	
	def createIndexForWords(self):
		self.indexForWords = {}
		self.nextIndex = 0
		for word in self.refWordListForIndex:
			if self.nextIndex == 5:
				break
			self.indexForWords[word] = self.nextIndex
			self.nextIndex = self.nextIndex + 1
	
	def itemSelect(self,rowIndex):
		self.createComboBox(rowIndex)
		self.selectedSentenceIndex = rowIndex
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()
Exemple #16
0
class edycja_proby(QDialog):
    def __init__(self, sample, defpol={}, defpol_order=[], parent=None):
        ''' defpol and defpol_order should contains the same values, it will
        not be checked in this class is it valid, pay attention to it'''
        super(edycja_proby, self).__init__(parent)

        # self.dane = globals()["daneW"][0]
        # self.defpol = globals()["daneW"][1]
        # globals()["daneW"] = []
        self.sample = copy.deepcopy(sample)
        self.sample._edytowany = 'E'
        self.org_sample = sample
        self.newName = self.sample.KeyCode()

        self.setWindowTitle("Sample: " + self.sample.KeyCode())
        self.resize(691, 749)
        self.setMinimumSize(QSize(691, 749))
        # self.setMaximumSize(QSize(691, 749))

        # Prepare headers
        self.defpol = defpol
        self.defpol_order = defpol_order
        self.prepareDefPol()
        self.selected = []  # list with index of selected ring in sample

        # ustawienie pol z danymi
        self.p_naglowek = QTableWidget()
        self.p_naglowek.setObjectName("p_naglowek")
        self.p_naglowek.setColumnCount(1)
        self.p_naglowek.setRowCount(len(self.headers))
        self.p_naglowek.setHorizontalHeaderLabels(["Value"])
        self.p_naglowek.setVerticalHeaderLabels(self.headers)
        self.p_naglowek.setAlternatingRowColors(True)
        self.p_naglowek.setSortingEnabled(False)

        self.p_dane = QTableWidget()
        self.p_dane.setObjectName("p_dane")
        self.p_dane.setColumnCount(10)
        self.p_dane.setHorizontalHeaderLabels(
            ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"])

        self.dodaj = QPushButton("Add")
        self.usun = QPushButton("Delete")
        self.przerysuj = QPushButton("Redraw")
        self.podziel = QPushButton("Divide")
        self.polacz = QPushButton("Join")
        self.anuluj = QPushButton("Cancel")
        self.wykonaj = QPushButton("Update")

        self.vbl = QVBoxLayout()
        self.qmc = Qt4MplCanvas(self)
        self.ntb = NavigationToolbar(self.qmc, self)
        self.vbl.addWidget(self.qmc)
        self.vbl.addWidget(self.ntb)

        self.updateHeaderTable()
        self.wpisz_pomiary()
        self.przerysuj_wykres()

        # ustawiamy wyglad okna
        layout = QGridLayout()
        layout.addWidget(self.p_naglowek, 0, 0)

        layout1 = QGridLayout()
        layout1.addWidget(self.p_dane, 0, 0, 1, 5)
        layout1.addWidget(self.dodaj, 1, 0)
        layout1.addWidget(self.usun, 1, 1)
        layout1.addWidget(self.podziel, 1, 2)
        layout1.addWidget(self.polacz, 1, 3)
        layout1.addWidget(self.przerysuj, 1, 4)
        layout1.setRowMinimumHeight(1, 25)
        layout1.setRowStretch(0, 1)

        layout.addLayout(layout1, 0, 1)
        layout.addLayout(self.vbl, 1, 0, 1, 2)
        layout.addWidget(self.anuluj, 2, 0)
        layout.addWidget(self.wykonaj, 2, 1)
        layout.setColumnMinimumWidth(0, 290)
        layout.setColumnStretch(1, 1)
        layout.setRowStretch(0, 1)
        layout.setRowMinimumHeight(0, 350)
        self.setLayout(layout)

        # Sygnaly
        self.connect(self.anuluj, SIGNAL("clicked()"), self.schowaj)
        self.connect(self.wykonaj, SIGNAL("clicked()"), self.wykonaj_odczytanie)
        self.connect(self.dodaj, SIGNAL("clicked()"), self.dodaj_wartosc)
        self.connect(self.przerysuj, SIGNAL("clicked()"), self.przerysuj_wykres)
        self.connect(self.usun, SIGNAL("clicked()"), self.usun_wartosc)
        self.connect(self.podziel, SIGNAL("clicked()"), self.podziel_wartosc)
        self.connect(self.polacz, SIGNAL("clicked()"), self.polacz_wartosc)
        self.p_naglowek.cellChanged.connect(self.edytowana_kom_nagl)
        self.p_dane.itemSelectionChanged.connect(self.przerysuj_wykres)
        self.p_dane.cellChanged.connect(self.przerysuj_wykres)

    def prepareDefPol(self):
        """Prepare Headers for metadata,
        BEAWARE! measurements are delete on the end"""
        self.headers = [
                        'KeyCode',
                        'DateBegin',
                        'DateEnd',
                        'Length',
                        'Gat',
                        'SapWoodRings',
                        'measurements',
                        ]
        add_table = []
        if len(self.defpol_order):
            add_table = self.defpol_order[:]
        elif len(self.defpol.keys()):
            add_table = sorted(list(self.defpol.keys()))
        else:
            add_table = sorted(self.sample.unikalneNaglowki())

        for val in add_table:
            if val not in self.headers:
                self.headers.append(val)
        self.headers.remove('measurements')

    def updateHeaderTable(self):
        # Dodaj wartosci wierszow dla tabeli naglowka proby
        self.p_naglowek.blockSignals(True)
        for i, val in enumerate(self.headers):
            if self.sample.wypiszMetadana(val):
                komorka = QTableWidgetItem(str(self.sample.wypiszMetadana(val)))
            else:
                komorka = QTableWidgetItem('---')

            if val == 'Length':
                komorka.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

            self.p_naglowek.setItem(i, 0, komorka)
        self.p_naglowek.blockSignals(False)

    def wykonaj_odczytanie(self):
        # spisz cala probe z edytowanych tabel i zapisz ja do zmiennej globalnej
        # daneW
        self.odczytaj_dane(origin='org')
        self.newName = self.org_sample.KeyCode()
        self.hide()

    def przerysuj_wykres(self):
        self.odczytaj_dane()
        self.updateHeaderTable()
        self.chartData = [
                     [],  # X axis - years
                     [],  # Y axis - measurements
                    ]

        self.chartData[1] = self.sample.wypiszPomiary()
        self.chartData[0] = range(1, self.sample.Length() + 1)

        self.qmc.axes.clear()
        # draw sample curve
        self.qmc.axes.plot(self.chartData[0], self.chartData[1])

        # draw selected years
        Xpoints = []
        Ypoints = []
        self.selected = []
        j = 0
        for i in range(self.sample.Length()):
            if i == 11:
                j += 1
            item = self.p_dane.item(j, i-(j*10))
            if item.isSelected():
                Xpoints.append(i+1)
                self.selected.append(i)
                Ypoints.append(int(item.text()))
        self.qmc.axes.plot(Xpoints, Ypoints, 'ro')

        # formatting of support lines
        self.qmc.axes.xaxis.set_major_locator(MultipleLocator(10))
        self.qmc.axes.xaxis.set_minor_locator(MultipleLocator(2))

        # Prepare axis dimensions
        Xmax = 40
        if self.sample.Length() > 40:
            Xmax = self.sample.Length() + 2
        Ymax = max(self.sample.wypiszPomiary()) + 30
        self.qmc.axes.axis([0, Xmax, 0, Ymax])

        self.qmc.axes.xaxis.grid(
            True,
            'minor',
            linewidth=0.4,
            ls='-',
            color='0.20')
        self.qmc.axes.xaxis.grid(
            True,
            'major',
            linewidth=1,
            ls='-',
            color='0.80')
        self.qmc.axes.tick_params(axis='both', which='major', labelsize=10)
        self.qmc.axes.set_axisbelow(True)
        # ustawienie obszaru wykresu
        self.qmc.axes.set_position([0.03, 0.05, 0.96, 0.94])
        self.qmc.draw()

    def odczytaj_dane(self, origin='copy'):
        """update sample - read all metadata and measurements which could be
            altered by user. If origin of sample has to be modified use any
            string in origin
        """
        if origin == 'copy':
            target = self.sample
        else:
            target = self.org_sample

        for i, head in enumerate(self.headers):
            ins = unicode(self.p_naglowek.item(i, 0).text())
            if head not in ['Length'] and ins not in ['---', 0]:
                target.wpiszMetadana(
                    head,
                    ins
                    )

        rowNum = self.p_dane.rowCount()
        colNum = self.p_dane.columnCount()
        measurements = []
        check = 'ok'
        redraw = 0
        for w in range(rowNum):
            for k in range(colNum):
                item = self.p_dane.item(w, k)
                try:
                    if int(item.text()) != 0 and str(item.text()).isdigit:
                        measurements.append(int(item.text()))
                        # if after notOk we find number there is something wrong
                        # and we neef to reread measuremnts to tabel
                        if check == 'notOk':
                            redraw = 1
                except:
                    check = 'notOk'

        target.uaktualnijPom(measurements)
        if redraw == 1:
            self.wpisz_pomiary()

    def dodaj_wartosc(self):
        kk = 0
        self.ile_wierszy = self.p_dane.rowCount()
        self.ile_kol = self.p_dane.columnCount()
        for wiersz in range(self.ile_wierszy):
            for kolumna in range(self.ile_kol):
                item = self.p_dane.item(wiersz, kolumna)
                if self.p_dane.isItemSelected(item) == True and kk == 0:
                    kk = 1
                    text, ok = QInputDialog.getText(
                        self, 'Value', 'inser value: ')
                    if ok:
                        measurements = self.sample.wypiszPomiary()
                        measurements.insert((wiersz*10)+kolumna, int(text))
                        self.sample.uaktualnijPom(measurements)
        self.wpisz_pomiary()
        self.przerysuj_wykres()

    def usun_wartosc(self):
        sel = self.selected[:]
        sel.reverse()
        for s in sel:
            self.sample.usunOstatniPomiar(position=int(s))
        self.wpisz_pomiary()
        self.przerysuj_wykres()

    def wpisz_pomiary(self):
        # przygotowanie labelek poziomych dla tablicy z pomiarami
        self.w = (len(self.sample.wypiszPomiary()))/10
        if (len(self.sample.wypiszPomiary())) % 10 > 0:
            self.w += 1
        i = 0
        self.ww = []
        while i < self.w:
            self.ww.append(str(i*10))
            i += 1
        self.p_dane.blockSignals(True)
        self.p_dane.clear()
        self.p_dane.setRowCount(self.w)
        self.p_dane.setVerticalHeaderLabels(self.ww)
        self.p_dane.setAlternatingRowColors(True)
        self.p_dane.setSortingEnabled(False)

        # Dodajemy wartosci pomiarow
        i = 0
        j = 0
        k = 0
        measurements = self.sample.wypiszPomiary()
        while k < len(measurements):
            if j == 10:
                j = 0
                i += 1
            komorka = QTableWidgetItem(str(measurements[k]))
            self.p_dane.setItem(i, j, komorka)
            j += 1
            k += 1
        # uzupelniamy pozostale pola pustymi wartosciami
        while j % 10 != 0:
            komorka = QTableWidgetItem("")
            self.p_dane.setItem(i, j, komorka)
            j += 1
        self.p_dane.resizeColumnsToContents()
        self.p_dane.blockSignals(False)

    def podziel_wartosc(self):
        if len(self.selected) != 1:
            pass
        else:
            measurements = self.sample.wypiszPomiary()
            val = measurements[self.selected[0]]
            self.divideWindow = okno_podzialu(val)
            self.divideWindow.exec_()
            measurements.pop(self.selected[0])
            self.sample.uaktualnijPom(measurements)
            self.sample.dodajPomiar(self.divideWindow.val1,
                                    position=self.selected[0])
            self.sample.dodajPomiar(self.divideWindow.val0,
                                    position=self.selected[0])

            self.wpisz_pomiary()
            self.przerysuj_wykres()

    def polacz_wartosc(self):
        measurements = self.sample.wypiszPomiary()
        i = len(measurements) - 1
        selectionRange = []
        newMeasurements = []
        while i > -1:
            if i in self.selected:
                selectionRange.append(measurements[i])
            elif i not in self.selected:
                if len(selectionRange) > 0:
                    newMeasurements.append(sum(selectionRange))
                    selectionRange = []
                newMeasurements.append(measurements[i])
            i -= 1
        if len(selectionRange) > 0:
            newMeasurements.append(selectionRange)
        newMeasurements.reverse()
        self.sample.uaktualnijPom(newMeasurements)

        self.wpisz_pomiary()
        self.przerysuj_wykres()

    def schowaj(self):
        self.odczytaj_dane()
        self.hide()

    def edytowana_kom_nagl(self):
        # neccessary to maintain user specific date, otherwise it will be
        # shuflled
        row = self.p_naglowek.currentRow()
        self.p_naglowek.blockSignals(True)
        if self.headers[row] in ['DateBegin', 'DateEnd']:
            head_temp = self.headers[row]
            if head_temp == "DateBegin":
                self.sample.ustawDateBegin(
                    int(self.p_naglowek.item(row, 0).text()))
                it = QTableWidgetItem(str(self.sample.DateEnd()))
                self.p_naglowek.setItem(self.headers.index("DateEnd"), 0, it)
            if head_temp == "DateEnd":
                self.sample.ustawDateEnd(
                    int(self.p_naglowek.item(row, 0).text()))
                it = QTableWidgetItem(str(self.sample.DateBegin()))
                self.p_naglowek.setItem(self.headers.index("DateBegin"), 0, it)
        self.p_naglowek.blockSignals(False)
        self.przerysuj_wykres()
Exemple #17
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)
Exemple #18
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)
Exemple #19
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()
Exemple #20
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())
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])
class TableCatalogOTF(QObject):

    runCatalog = pyqtSignal(str)

    def __init__(self):
        def initGui():
            self.tableWidget.setWindowTitle("Catalog OTF")
            self.tableWidget.setSortingEnabled(False)
            msgtrans = QCoreApplication.translate("CatalogOTF", "Layer,Total")
            headers = msgtrans.split(',')
            self.tableWidget.setColumnCount(len(headers))
            self.tableWidget.setHorizontalHeaderLabels(headers)
            self.tableWidget.resizeColumnsToContents()

        super(TableCatalogOTF, self).__init__()
        self.tableWidget = QTableWidget()
        initGui()

    def _getRowLayerID(self, layerID):
        for row in range(self.tableWidget.rowCount()):
            if layerID == self.tableWidget.cellWidget(row, 0).objectName():
                return row
        return -1

    def _changedText(self, layerID, name, column):
        row = self._getRowLayerID(layerID)
        if row != -1:
            wgt = self.tableWidget.cellWidget(
                row, column) if column == 0 else self.tableWidget.item(
                    row, column)
            wgt.setText(name)
            wgt.setToolTip(name)
            self.tableWidget.resizeColumnsToContents()

    @pyqtSlot()
    def _onRunCatalog(self):
        btn = self.sender()
        icon = QIcon(joinPath(dirname(__file__), 'cancel_red.svg'))
        btn.setIcon(icon)
        layerID = btn.objectName()
        self.runCatalog.emit(layerID)

    @pyqtSlot()
    def _onSelectionChanged(self):
        layer = self.sender()
        row = self._getRowLayerID(layer.id())
        if row != -1:
            wgt = self.tableWidget.cellWidget(row, 0)
            nameIcon = 'check_green.svg' if layer.selectedFeatureCount(
            ) == 0 else 'check_yellow.svg'
            icon = QIcon(joinPath(dirname(__file__), nameIcon))
            wgt.setIcon(icon)

    @pyqtSlot("QgsVectorLayer")
    def insertRow(self, layer):
        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)

        column = 0  # Layer
        layerName = layer.name()
        nameIcon = 'check_green.svg' if layer.selectedFeatureCount(
        ) == 0 else 'check_yellow.svg'
        icon = QIcon(joinPath(dirname(__file__), nameIcon))
        btn = QPushButton(icon, layerName, self.tableWidget)
        btn.setObjectName(layer.id())
        btn.setToolTip(layerName)
        btn.clicked.connect(self._onRunCatalog)
        layer.selectionChanged.connect(self._onSelectionChanged)
        self.tableWidget.setCellWidget(row, column, btn)

        column = 1  # Total

        msgtrans = QCoreApplication.translate("CatalogOTF", "None")
        item = QTableWidgetItem(msgtrans)
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        self.tableWidget.setItem(row, column, item)

        self.tableWidget.resizeColumnsToContents()

    @pyqtSlot(str)
    def removeRow(self, layerID):
        row = self._getRowLayerID(layerID)
        if row != -1:
            self.tableWidget.removeRow(row)

    @pyqtSlot(str, str)
    def changedNameLayer(self, layerID, name):
        self._changedText(layerID, name, 0)

    @pyqtSlot(str, str)
    def changedTotal(self, layerID, value):
        self._changedText(layerID, value, 1)

    @pyqtSlot(str, bool)
    def changedIconRun(self, layerID, selected):
        row = self._getRowLayerID(layerID)
        if row != -1:
            btn = self.tableWidget.cellWidget(row, 0)
            nameIcon = 'check_green.svg' if not selected else 'check_yellow.svg'
            icon = QIcon(joinPath(dirname(__file__), nameIcon))
            btn.setIcon(icon)
            btn.setEnabled(True)

    @pyqtSlot(str)
    def killed(self, layerID):
        row = self._getRowLayerID(layerID)
        if row != -1:
            btn = self.tableWidget.cellWidget(row, 0)
            btn.setEnabled(False)

    def widget(self):
        return self.tableWidget
class ViewTableForm(QWidget):
    def __init__(self, visualization, parent_widget=None):
        QWidget.__init__(self, parent_widget)
        self.inGui = False

        self.widgetLayout = QVBoxLayout(self)

        self.tableWidget = QTableWidget(self)
        self.tableWidget.setObjectName("tableWidget")
        size = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.tableWidget.setSizePolicy(size)
        self.widgetLayout.addWidget(self.tableWidget)

        self.tabIcon = QIcon(":/Images/Images/map.png")

        self.tabLabel = visualization.table_name

        self.load_table(visualization=visualization)

    def load_table(self, visualization, limit=10000):

        storage = StorageFactory().get_storage(
            type='%s_storage' % visualization.output_type,
            storage_location=visualization.storage_location)
        table_data = storage.load_table(table_name=visualization.table_name)

        try:
            primary_keys = visualization.indicators[0].primary_keys
        except:
            primary_keys = []

        keys = primary_keys + [
            key for key in table_data.keys() if key not in primary_keys
        ]
        num_rows = min(len(table_data[keys[0]]), limit)
        num_cols = len(keys)

        self.tableWidget.clear()
        self.tableWidget.setColumnCount(num_cols)
        self.tableWidget.setRowCount(num_rows)

        j = 0
        for key in keys:
            col = QTableWidgetItem()
            col.setText(QString(key))
            self.tableWidget.setHorizontalHeaderItem(j, col)
            j += 1

        self.tableWidget.resizeColumnsToContents()

        order = sorted(enumerate(table_data[keys[0]]), lambda (i, v),
                       (j, v2): int(v * 100) - int(v2 * 100))

        for i, (idx, v) in enumerate(order):
            row = QTableWidgetItem()
            self.tableWidget.setVerticalHeaderItem(i, row)
            j = 0
            for key in keys:
                item = QTableWidgetItem()
                item.setText(QString(str(table_data[key][idx])))
                self.tableWidget.setItem(i, j, item)
                j += 1
            if i > limit:
                msg = 'The table %s has been truncated to %i rows because of memory limitations.' % (
                    visualization.table_name, limit)
                detailed_msg = '<qt>To view the full results, open the following file:<br><br><small>%s</small></qt>' % visualization.get_file_path(
                )
                MessageBox.warning(mainwindow=self,
                                   text=msg,
                                   detailed_text=detailed_msg)
                break

        #self.tableWidget.resizeRowsToContents()
    def removeElement(self):
        return True
Exemple #24
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)   
Exemple #25
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
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()
        
    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)
Exemple #28
0
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()
Exemple #29
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
Exemple #30
0
class FormTable(QWidget):

    # -------------------------------------------------------------------------------------
    # Form signal(s)
    closingFormTable = pyqtSignal()
    deletingFormTable = pyqtSignal()
    # -------------------------------------------------------------------------------------

    # -------------------------------------------------------------------------------------
    # Method init
    def __init__(self, parent=None):

        # -------------------------------------------------------------------------------------
        # Constructor
        super(FormTable, self).__init__(parent)

        self.setWindowTitle('Section Table')

        oLayout = QVBoxLayout()

        self.TableWidget = QTableWidget()

        self.BtnSave = QPushButton('Save', self)
        self.BtnCancel = QPushButton('Cancel', self)

        # Define layout
        oLayout.addWidget(self.TableWidget)
        oLayout.addWidget(self.BtnSave)
        oLayout.addWidget(self.BtnCancel)

        # Set layout
        self.setLayout(oLayout)
        self.oLayout = oLayout

        # Define action(s)
        self.BtnSave.pressed.connect(self.saveTable)
        self.BtnCancel.pressed.connect(self.cancelTable)

        # Show widget
        self.show()
        # -------------------------------------------------------------------------------------

    # -------------------------------------------------------------------------------------

    # -------------------------------------------------------------------------------------
    # Method to set data
    def setData(self, oData):
        # Check data table
        if oData:

            iDataRows = len(oData)
            iDataCols = len(oData[0])

            self.TableWidget.setRowCount(iDataRows)
            self.TableWidget.setColumnCount(iDataCols)

            self.TableWidget.setHorizontalHeaderLabels(oFormSectionHeader)

            oTableHeader = self.TableWidget.horizontalHeader()
            oTableHeader.setStretchLastSection(True)

            iNL = None
            for iID, a1oLine in enumerate(oData):

                if iNL is None:
                    iNL = len(a1oLine)
                    a2oTable = [[] for iL in range(iNL)]
                else:
                    pass

                for iElemID, oElemVal in enumerate(a1oLine):
                    a2oTable[iElemID].append(oElemVal)

                    oItem = QTableWidgetItem(oElemVal)
                    oItem.setFlags(Qt.ItemIsSelectable)
                    self.TableWidget.setItem(iID, iElemID, oItem)

            self.TableWidget.resizeColumnsToContents()
            self.TableWidget.update()
            #self.TableWidget.repaint()

            self.TableWidget.setEditTriggers(QAbstractItemView.CurrentChanged)

        else:
            # Nullity table object
            #self.TableWidget.setRowCount(0)
            #self.TableWidget.setColumnCount(0)
            self.TableWidget.clearContents()
            self.TableWidget.setItem(0, 0, QTableWidgetItem("No data here ... "))
            #self.TableWidget.setHorizontalHeaderLabels(oFormSectionHeader)

    # -------------------------------------------------------------------------------------

    # -------------------------------------------------------------------------------------
    # Method to cancel table
    def cancelTable(self):
        self.deletingFormTable.emit()
    # -------------------------------------------------------------------------------------

    # -------------------------------------------------------------------------------------
    # Method to save table object to ascii file
    def saveTable(self):
        # Select output filename
        sFilePath = str(QFileDialog.getSaveFileName(self, 'Save File', '', 'ASCII (*.txt)'))
        # Check file definition by user
        if sFilePath is not None:
            # Save data to file
            writeTableObj(sFilePath, self.TableWidget)
        else:
            pass

    # -------------------------------------------------------------------------------------

    # -------------------------------------------------------------------------------------
    # Method to close event (destroy QWidget); closing plugin will destroy table form too
    def closeEvent(self, oEvent):
        oEvent.accept()
        self.closingFormTable.emit()