Beispiel #1
1
    def initUI(self):
        self.setAutoFillBackground(True)
        palette = self.palette()
        palette.setColor(self.backgroundRole(), QColor('white'))
        self.setPalette(palette)
        
        self.setFrameShape(_frameShape)
        self.setFrameShadow(_frameShadow)
        self.setLineWidth(_lineWidth)
        self.setMidLineWidth(_midLineWidth)
        return    
        combo = QComboBox(self)
        
        self.flist = self.load_list()
        self.lbl = QLabel('', self)
        self.descr = QLabel('', self)
        self.descr.setWordWrap(True)
        self.onActivated(0)

        for x in self.flist:
            combo.addItem(x['name'])
        
        combo.move(50, 50)
        self.lbl.move(50, 150)
        self.descr.move(150, 50)

        combo.activated[int].connect(self.onActivated) 
Beispiel #2
1
class Actividad7(QWidget):
	def __init__(self):
		super().__init__()
		self.ventana()
		
	def ventana(self):
		#Etiquetas
		self.entrada = QLineEdit("Numero de datos", self)
		self.entrada.move(5,5)
		self.combo = QComboBox(self)
		self.combo.move(160,5)
		x= QLabel("X:", self)
		x.move(5,40)
		btn= QPushButton("Calcular", self)
		btn.move(190,35)
		y = QLabel("f(X):", self)
		y.move(5,70)
		self.entradax = QLineEdit(self)
		self.entradax.move(35,35)
		self.entraday = QLineEdit(self)
		self.entraday.move(35,65)
		btn2= QPushButton("Borrar Todo", self)
		btn2.move(190,65)
		self.valor = QLineEdit("Valor a estimar en",self)
		self.valor.move(5,95)
		self.ecuacion= QLabel("Y=",self)
		self.ecuacion.move(5,130)

		#Eventos
		self.entrada.textChanged[str].connect(self.combobox)
		self.combo.activated[str].connect(self.cambio)
		self.entradax.textChanged[str].connect(self.x)
		self.entraday.textChanged[str].connect(self.y)
		btn.clicked.connect(self.boton)
		self.entrada.selectionChanged.connect(self.sel1)
		self.entradax.selectionChanged.connect(self.sel2)
		self.entraday.selectionChanged.connect(self.sel3)
		self.valor.selectionChanged.connect(self.sel4)
		btn2.clicked.connect(self.borrar)
		#Ventana
		self.setGeometry(300, 300, 310, 150)
		self.setWindowTitle("Polinomios de interpolacion de Langrange")
		self.show()
	
	def combobox(self, text):
		self.combo.clear()
		self.entradax.clear()
		self.entraday.clear()
		if text =='':
			text='0'
		for c in range(int(text)):
			self.combo.addItem(str(c+1))
			if len(xl)<= c:
				xl.append(0.0)
				yl.append(0.0)
		if text != "0":
			self.entradax.setText(str(xl[self.combo.currentIndex()]))
			self.entraday.setText(str(yl[self.combo.currentIndex()]))
			
	def cambio(self, text):
		self.entradax.setText(str(xl[int(text)-1]))
		self.entraday.setText(str(yl[int(text)-1]))
	def x(self, text):
		if text == "" or text == '-':
			text= "0"
		xl[self.combo.currentIndex()]= float(text)
	def y(self, text):
		if text == "" or text == '-':
			text= "0"
		yl[self.combo.currentIndex()]= float(text)
	def boton(self):
		if self.valor.text() == "": #Si el usuario deja en blanco el valor a conocer se conocera que es 0
			self.valor.setText("0")
		datos= int(self.entrada.text()) #datos es el numero de datos ingresados por el usuario
		cx= float(self.valor.text())#cx sera el valor que el usuario quiera conocer
		suma=0 #Se declara la sumatoria
		for c in range(datos): #Este for funciona para movernos en I
			pro=1 #Se declara la variable producto
			for c2 in range(datos):#Este for funciona para movernos en J
				if c2!=c: #Si I es diferente a J se realizara la operacion producto 
					pro*= (cx-xl[c2])/(xl[c]-xl[c2]) #Producto de
			pro*= yl[c] #Al final de pasar por cada J se multiplica por f(X) en el cual I esta actualmente
			suma+= pro #pro pasa a ser parte de la Sumatoria
		self.ecuacion.setText("Y= " + str(suma)) #Al final se imprime la Sumatoria
		self.ecuacion.adjustSize()
	def sel1(self):
		self.entrada.clear()
	def sel2(self):
		self.entradax.clear()
	def sel3(self):
		self.entraday.clear()
	def sel4(self):
		self.valor.clear()
	def borrar(self):
		for c in range(len(xl)):
			xl[c]= 0.0
			yl[c]= 0.0
		self.sel1()
		self.sel2()
		self.sel3()
		self.sel4()
Beispiel #3
0
    def initUI(self):

        # lineedit
        self.lbl = QLabel(self)
        qle = QLineEdit(self)

        qle.move(20, 30)
        self.lbl.move(20, 10)

        qle.textChanged[str].connect(self.onChanged)

        # combobox
        self.lbl1 = QLabel('ubuntu', self)

        combo = QComboBox(self)
        combo.addItem('ubuntu')
        combo.addItem('mandriva')
        combo.addItem('fedora')
        combo.addItem('arch')
        combo.addItem('gentoo')

        combo.move(20, 70)
        self.lbl1.move(20, 100)

        combo.activated[str].connect(self.onActivated)

        self.setGeometry(300, 300, 300, 250)
        self.setWindowTitle('widget 1')
        self.show()
Beispiel #4
0
    def initUI(self, parent):    
        combo = QComboBox(self)
        self.title = QLabel(u'Выбор каталога:', self)
        self.lbl = QLabel('', self)
        self.descr = QLabel('', self)
        self.descr.setWordWrap(True)
        self.descr.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.onActivated(parent, parent.code_int)

        for x in parent.flist:
            combo.addItem(x['name'])
        
        combo.move(50, 50)
        self.title.move(5, 25)
        self.lbl.move(50, 100)
        self.descr.move(150, 50)
        
        def onact(ind):
            return self.onActivated(parent, ind)

        combo.activated[int].connect(onact) 
        
        self.setAutoFillBackground(True)
        palette = self.palette()
        palette.setColor(self.backgroundRole(), QColor('white'))
        self.setPalette(palette)
         
        self.setFrameShape(_frameShape)
        self.setFrameShadow(_frameShadow)
        self.setLineWidth(_lineWidth)
        self.setMidLineWidth(_midLineWidth)
 def initUI(self):
     
     self.setFixedSize(400, 260)
     
     self.setWindowTitle('Fomoire!')
     fomoire = QPixmap(os.path.join('./Pictures/', "fomoire.png"))
     logo = QLabel(self)
     logo.setPixmap(fomoire)
     logo.setFixedSize(fomoire.size())
     logo.move(400 / 2 - fomoire.width() / 2, 15)
     
     towerDefence = QLabel('A Tower Defence Game', self)
     towerDefence.move(130, 66)
     
     selectMap = QLabel('Select map:', self)
     selectMap.move(50, 105)
     
     mapList = QComboBox(self)
     mapList.addItem('No map selected')
     
     for mapFile in os.listdir('./Maps/'):
         mapList.addItem(mapFile)
     
     mapList.move(135, 102)
     mapList.activated[str].connect(self.selectMap)
     
     setSpeed = QLabel('Set game speed:', self)
     setSpeed.move(50, 140)
     
     slow = QLabel('Slow', self)
     slow.move(170, 140)
     
     slider = QSlider(Qt.Horizontal, self)
     slider.setFocusPolicy(Qt.NoFocus)
     slider.setSliderPosition(100 - self.gameSpeed)
     slider.setGeometry(210, 140, 100, 20)
     slider.valueChanged[int].connect(self.changeGameSpeed)
     
     fast = QLabel('Fast', self)
     fast.move(325, 140)
     
     start = QPushButton('Start game!', self)
     start.move(145, 175)
     start.clicked[bool].connect(self.startGame)
     
     quitButton = QPushButton('Quit', self)
     quitButton.move(168, 210)
     quitButton.clicked[bool].connect(qApp.quit)
     
     barbarian = QLabel(self)
     brbr = QPixmap(os.path.join('./Pictures/', "barbarian.png"))
     barbarian.setPixmap(brbr)
     barbarian.move(70, 185)
     
     berserker = QLabel(self)
     berber = QPixmap(os.path.join('./Pictures/', "berserker_left.png"))
     berserker.setPixmap(berber)
     berserker.move(290, 185)
     
     self.show()
Beispiel #6
0
class Example(QWidget):

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

    def initUI(self):
        config = configparser.ConfigParser()
        config.read('launcher.original.ini')
        Login = config.get('Options', 'Logins')
        addlogins = Login.split(",")

        self.lbl = QLabel("Logins", self)
        self.combo = QComboBox(self)
        self.combo.addItems(addlogins)

        self.combo.move(50, 50)
        self.lbl.move(50, 30)

        btn = QPushButton('Set', self)
        btn.setGeometry(230, 50, 42, 32)
        btn.clicked.connect(self.buttonSet)

        self.resize(350, 140)
        self.center()
        self.setWindowTitle('Message box')
        self.show()

        self.setWindowTitle('Launcher')
        self.show()

    def buttonSet(self):
        config = configparser.ConfigParser()
        config.read('launcher.ini')
        config.set('Options', 'Autologin', self.combo.currentText())
        with open('launcher.ini', 'w') as configfile:
            config.write(configfile)

    def center(self):

        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def closeEvent(self, event):

        reply = QMessageBox.question(self, 'Message',
                                     "Are you sure to quit?", QMessageBox.Yes |
                                     QMessageBox.No, QMessageBox.No)

        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()
Beispiel #7
0
    def initUI(self):

        # hbox = QHBoxLayout(self)
        #
        # pixmap = QPixmap("11.jpg")
        # lbl1 = QLabel(self)
        # lbl1.setPixmap(pixmap)

        # topleft = QFrame(self)
        # topleft.setFrameShape(QFrame.StyledPanel)
        # topright = QFrame(self)
        # topright.setFrameShape(QFrame.StyledPanel)
        # bottom = QFrame(self)
        # bottom.setFrameShape(QFrame.StyledPanel)
        #
        # spllitter1 = QSplitter(Qt.Horizontal)
        # spllitter1.addWidget(topleft)
        # spllitter1.addWidget(topright)
        # spllitter2 = QSplitter(Qt.Vertical)
        # spllitter2.addWidget(spllitter1)
        # spllitter2.addWidget(lbl1)
        #
        # hbox.addWidget(spllitter2)
        # self.setLayout(hbox)

        # 标签 文字
        self.lbl2 = QLabel(self)
        qle = QLineEdit(self)
        qle.move(10, 40)
        self.lbl2.move(10, 1)
        qle.textChanged[str].connect(self.onChanged)

        self.lbl3 = QLabel('Ubuntu',self)
        combo = QComboBox(self)
        combo.addItem('Ubuntu')
        combo.addItem('Madriva')
        combo.addItem('Fedora')
        combo.addItem('Arch')
        combo.addItem('Gentoo')
        combo.move(10, 70)
        self.lbl3.move(100, 75)
        combo.activated[str].connect(self.onActivated)

        self.setGeometry(100, 100, 300, 300)
        self.setWindowTitle('Widget2')
        self.show()
 def languages_button(self):
     lang_mssg = QMessageBox(self)
     lang_mssg.setWindowTitle(" ")
     lang_mssg.setStyleSheet(self.stylesheets.text_CSS)
     lang_mssg.setIconPixmap(self.mainwindow.blank_langmssg)
     lang_mssg.show()
     
     lang_options = QComboBox(lang_mssg)
     lang_options.move(10,10)
     lang_options.resize(160,60)
     
     for option in ("English","Español","Français","Deutsch",\
                     "한글","中文","日本語"):
         lang_options.addItem(option)
         
     lang_options.setCurrentIndex(self.lang_dict[self.language])
     lang_options.activated.connect(self.change_language)
     lang_options.show()
Beispiel #9
0
 def initUI(self):
     combo = QComboBox(self)
     combo.addItem("Text")
     combo.addItem("Video")
     combo.addItem("Image")
     combo.move(20, 20)
     combo.activated[str].connect(self.onActivated)
     self.addbtn = QPushButton('Add Rule', self)
     self.addbtn.move(100, 20)
     self.addbtn.clicked.connect(self.addRuleDialog)
     self.delbtn = QPushButton('Delete Rule', self)
     self.delbtn.move(200, 20)
     self.delbtn.clicked.connect(self.delRuleDialog)
     self.modbtn = QPushButton('Modify Rule', self)
     self.modbtn.move(310, 20)
     self.modbtn.clicked.connect(self.modRuleDialog)
     self.resize(500, 500)
     self.setWindowTitle('Magic Folder')
Beispiel #10
0
    def initUI(self):      

        self.lbl = QLabel("Ubuntu", self)

        combo = QComboBox(self)
        combo.addItem("Ubuntu")
        combo.addItem("Mandriva")
        combo.addItem("Fedora")
        combo.addItem("Arch")
        combo.addItem("Gentoo")

        combo.move(50, 50)
        self.lbl.move(50, 150)

        combo.activated[str].connect(self.onActivated)        
         
        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('QComboBox')
        self.show()
Beispiel #11
0
    def home(self):
        btn = QPushButton('quit', self)
        btn.clicked.connect(self.close_application)
        btn.resize(btn.minimumSizeHint())
        btn.move(0, 60)

        action = QAction(QIcon('../pics/pythonlogo.png'),
                         'Flee the Scene', self)
        action.triggered.connect(self.close_application)

        self.toolBar = self.addToolBar('Extraction')
        self.toolBar.addAction(action)

        checkBox = QCheckBox('Enlarge window', self)
        checkBox.move(50, 25)
        # checkBox.toggle()
        checkBox.stateChanged.connect(self.enlargeWindow)

        self.progress = QProgressBar(self)
        self.progress.setGeometry(100, 62, 250, 20)

        self.btn = QPushButton("Download", self)
        self.btn.clicked.connect(self.download)
        self.btn.resize(btn.minimumSizeHint())
        self.btn.move(100, 100)

        print(self.style().objectName())
        self.styleChoice = QLabel('Windows Vista', self)
        self.styleChoice.move(50, 200)

        comboBox = QComboBox(self)
        comboBox.addItem('motif')
        comboBox.addItem('Windows')
        comboBox.addItem('cde')
        comboBox.addItem('Plastique')
        comboBox.addItem('Cleanlooks')
        comboBox.addItem('windowsvista')
        comboBox.move(50, 250)

        comboBox.activated[str].connect(self.style_choice)

        self.show()
Beispiel #12
0
class ArchieveDialog(QtWidgets.QDialog):

    def __init__(self,parent, db):
        super(ArchieveDialog, self).__init__(parent)
        self.conversation = QTextEdit(self)
        self.combo = QComboBox(self)
        self.db = db
        self.initUI()

    def initUI(self):
        self.resize(300,300)
        for key, value in self.db.items():
            self.combo.addItem(key)
        self.conversation.move(0,20)
        self.combo.move(0, 0)
        self.combo.activated[str].connect(self.onActivated)

    def onActivated(self, text):
        self.conversation.clear()
        self.conversation.append(self.db[text])
    def themes_button(self):
        themes_mssg = QMessageBox(self)
        themes_mssg.setWindowTitle(" ")
        themes_mssg.setStyleSheet(self.stylesheets.text_CSS)
        themes_mssg.setIconPixmap(self.mainwindow.blank_thememssg)
        themes_mssg.show()
        
        
        themes_options = QComboBox(themes_mssg)
        themes_options.move(10,10)
        themes_options.resize(220,60)
        
        for option in ("Default", "Art Deco", "Cherry Soda", "Coffee", \
                        "Spring Green", "Victorian"):
            themes_options.addItem(option)

        themes_options.setCurrentIndex(self.theme_dict[self.theme])
        themes_options.activated.connect(self.change_theme)
        themes_options.show()
        
        ok_button = themes_mssg.children()[2].children()[1]
        ok_button.clicked.connect(self.change_appearance)
Beispiel #14
0
class AbilityCreator(QMainWindow):
    def __init__(self, parent=None):
        super(AbilityCreator, self).__init__(parent)
        self.parent = parent
        self.gui = parent.parent().parent()
        self.env = {
            "enemy":
            "Medium level keyword. This represents the enemy object, this is useful for advanced users that wish to user different attributes.",
            "ctx":
            "Low level keyword. This is the context object, it contains everything the code uses to process battles.",
            "self":
            "Medium level keyword. This is the unit object that the ability is attached to, same as with enemy",
            "objects":
            "Low level keyword. This represents the module itself and can be used to reach the base classes and compare certain attributes",
            "attack":
            "High level keyword. Can be used to check if the current phase of the battle is the inital attack",
            "counterattack":
            "High level keyword. Can be used to check if the current phase of the battle is the counter attack made by the defender",
            "attacking":
            "High level keyword. This can be used to check if the unit is currently attacking.",
            "defending":
            "High level keyword. This can be used to check if the unit is currently defending. ",
            "is_defender":
            "High level keyword. Can be used to check if the unit is the defending unit (unit on the right).",
            "is_attacker":
            "High level keyword. Can be used to check if the unit is the attacking unit (unit on the left).",
            "attacker_terrain":
            "Medium level keyword. Can be used to access attributes of the terrain the attacker is standing on.",
            "defender_terrain":
            "Medium level keyword. Can be used to access attributes of the terrain the defender is standing on.",
            "self_terrain":
            "Medium level keyword. This represents the terrain the unit for which abilities are currently being checked is standing on.",
            "enemy_terrain":
            "Medium level keyword. This represents the terrain the enemy of the unit for which abilities are currently being checked is standing on.",
            "infantry":
            "High level keyword. A unit type, can be compared to unit objects' type attribute, represents infantry units.",
            "ranged":
            "High level keyword. A unit type, can be compared to unit objects' type attribute, represents ranged units.",
            "cavalry":
            "High level keyword. A unit type, can be compared to unit objects' type attribute, represents cavalry units.",
            "siege":
            "High level keyword. A unit type, can be compared to unit objects' type attribute, represents siege units.",
            "structure":
            "High level keyword. A unit type, can be compared to unit objects' type attribute, represents structures.",
            "plain":
            "High level keyword. A terrain type, can be compared to terrain objects' type attribute, represents plains",
            "desert":
            "High level keyword. A terrain type, can be compared to terrain objects' type attribute, represents desert",
            "hill":
            "High level keyword. A terrain type, can be compared to terrain objects' type attribute, represents hills",
            "mountain":
            "High level keyword. A terrain type, can be compared to terrain objects' type attribute, represents mountains",
            "forest":
            "High level keyword. A terrain type, can be compared to terrain objects' type attribute, represents forests",
            "swamp":
            "High level keyword. A terrain type, can be compared to terrain objects' type attribute, represents swamps",
            "bridge":
            "High level keyword. A terrain type, can be compared to terrain objects' type attribute, represents bridges",
            "ford":
            "High level keyword. A terrain type, can be compared to terrain objects' type attribute, represents fords",
            "road":
            "High level keyword. A terrain sub type, can be compared to terrain objects' sub_type attribute, represents roads",
            "normal":
            "High level keyword. A terrain sub type, can be compared to terrain objects' sub_type attribute, represents non-road terrain"
        }

        self.levels = "<b>High level</b>: keyword representing a single value <br><b>Medium level</b>: keyword representing objects which have high level attributes which can be access through dot notation (medium_level.high_level)<br><b>Low level</b>: keyword representing objects with high, medium and low level attributes which can be access through dot notation."
        self.initUI()

        self.box = QMessageBox()
        self.box.setIcon(QMessageBox.Information)
        self.box.setText(
            "Reserved ability keywords are classified in three categories:")
        self.box.setInformativeText(self.levels)
        self.box.setWindowTitle("Keyword Levels")
        self.box.setWindowIcon(QIcon("icon.png"))
        self.box.setStandardButtons(QMessageBox.Ok)
        self.box.buttonClicked.connect(lambda: self.box.close())

    def initUI(self):
        QLabel("Name", self).move(50, 50)
        self.name = QLineEdit(self)
        self.name.move(150, 50)
        self.name.resize(200, 40)

        QLabel("Modifiers", self).move(50, 220)
        QLabel("If True", self).move(50, 250)
        self.modifier_true = QLineEdit(self)
        self.modifier_true.move(150, 250)
        self.modifier_true.setToolTip(
            "This is the modifier that will be added to the rest of the modifiers if the condition is fulfilled"
        )

        QLabel("If False", self).move(50, 280)
        self.modifier_false = QLineEdit(self)
        self.modifier_false.move(150, 280)
        self.modifier_false.setToolTip(
            "This is the modifier that will be added to the rest of the modifiers if the condition fails"
        )

        QLabel("Condition", self).move(50, 120)
        QLabel("if", self).move(50, 150)
        self.func = QLineEdit(self)
        self.func.move(75, 150)
        self.func.resize(600, 30)

        self.abilities_btn = QPushButton("Add Ability", self)
        self.abilities_btn.resize(self.abilities_btn.sizeHint())
        self.abilities_btn.move(50, 400)
        self.abilities_btn.clicked.connect(self.add_ability)

        self.levels_btn = QPushButton("Levels?", self)
        self.levels_btn.resize(self.levels_btn.sizeHint())
        self.levels_btn.move(600, 210)
        self.levels_btn.clicked.connect(lambda: self.box.show())

        self.text_box = QPlainTextEdit(self)
        self.text_box.setReadOnly(True)
        self.text_box.move(350, 270)
        self.text_box.resize(400, 200)
        self.text_box.insertPlainText(f'{self.env["enemy"]}')

        def editor(text):
            self.text_box.clear()
            self.text_box.insertPlainText(f'{self.env[text]}')

        self.tooltip_box = QComboBox(self)
        self.tooltip_box.addItems(self.env.keys())
        self.tooltip_box.resize(self.tooltip_box.sizeHint())
        self.tooltip_box.move(350, 220)
        self.tooltip_box.activated[str].connect(editor)

        self.set_default()

        self.setWindowTitle("Ability Creator")
        self.setWindowIcon(QIcon("icon.png"))
        self.setWindowModality(Qt.ApplicationModal)

    def add_ability(self):
        self.parent.parent().parent().custom_abilities[self.name.text(
        )] = f"{self.modifier_true.text()} if {self.func.text()} else {self.modifier_false.text()}"
        self.set_default()
        self.close()

    def set_default(self):
        self.name.setText("Ability Name")
        self.modifier_true.setText("0")
        self.modifier_false.setText("0")
        self.func.setText("True")
Beispiel #15
0
class Layout(QMainWindow):
    
    def __init__(self):
        super().__init__()
        self.pos = conf.position
        self.res = conf.resize
        self.statusText = 'Kullanıma Hazır !'
        self.initUI()

    def setURL(self,code):
        if len(code) == 11 :
            return conf.app.youTube_host + code

    def codeURL(self,url):
        url_data = urllib.parse.urlparse(url)
        query = urllib.parse.parse_qs(url_data.query)
        if len(query["v"][0]) and len(query["v"][0]) == 11 :
            return self.setURL(query["v"][0])
        return False


    def getSearch(self):
        searchTerm = self.searchBox.text()
        self.searchBtn.setDisabled(True)
        if len(searchTerm) == 0 :
            print('Temizlendi')
            self.infoClear()
        elif len(searchTerm) != 0 and self.searchBtn.isEnabled() == False :
            self.searchBtn.setDisabled(False)
            if len(searchTerm) == 11 :
                code = self.setURL(searchTerm)
                self.getVideo(code)

            elif len(searchTerm) == 43 :
                code = self.codeURL(searchTerm)
                if code == False :
                    self.statusBar().showMessage('Lütfen geçerli bir Youtube bağlantısı yada Video kodu girin !')
                self.getVideo(code)

            elif len(searchTerm) == 83 :
                code = self.codeURL(searchTerm)
                if code == False :
                    self.statusBar().showMessage('Lütfen geçerli bir Youtube bağlantısı yada Video kodu girin !')
                self.getVideo(code)

            else :
                self.statusBar().showMessage('Lütfen geçerli bir Youtube bağlantısı yada Video kodu girin !')
    def getVideo(self,code):
        self.setDisabled(True)
        self.statusBar().showMessage('Yükleniyor !')
        self.yt = YouTube(code)
        videos = self.yt.get_videos()
        quality = ['Kalite']
        for v in videos :
            if v.extension == 'mp4' :
                quality.append( v.resolution)
        quality = sorted(set(quality),reverse=True)
        self.quality.clear()
        self.quality.addItems(quality)
        self.quality.model().item(0).setEnabled(False)
        self.quality.show()
        self.filename = self.yt.filename
        self.info.setText(self.yt.filename)
        self.downloadBtn.show()
        self.statusBar().showMessage('Yüklendi !')
        self.setDisabled(False)

    def infoClear(self):
            self.downloadBtn.setDisabled(True)
            self.quality.clear()
            self.quality.hide()
            self.info.clear()
            self.downloadBtn.setDisabled(True)
            self.downloadBtn.hide()

    def searchChange(self):
        searchTerm = self.searchBox.text()
        if len(searchTerm) == 0 :
            self.infoClear()
            self.searchBtn.setDisabled(True)
            self.searchBtn.setDisabled(True)
            self.statusBar().showMessage(self.statusText)
        elif len(searchTerm) != 0 :
            self.statusBar().showMessage('Kullanıma Hazır !')
            self.searchBtn.setDisabled(False)


    def toolBarButtons(self):
        # Search Button
        self.searchBtn = QPushButton(conf.app.toolBar.searchBtn.title,self)
        self.searchBtn.clicked.connect(self.getSearch)
        self.searchBtn.setDisabled(True)
        self.searchBtn.move(conf.app.toolBar.searchBtn.pos.x,conf.app.toolBar.searchBtn.pos.y)
        # Download Button
        # downloadBtn = QPushButton(conf.app.toolBar.downloadBtn.title,self)
        # downloadBtn.move(conf.app.toolBar.downloadBtn.pos.x,conf.app.toolBar.downloadBtn.pos.y)

    def toolBar(self):
        self.toolBarButtons()
        self.searchBox = QLineEdit(self)
        self.searchBox.setFocus(True)
        self.searchBox.setFixedSize(conf.app.toolBar.searchBox.size.w,conf.app.toolBar.searchBox.size.h)
        self.searchBox.setClearButtonEnabled(True)
        self.searchBox.returnPressed.connect(self.searchChange)
        self.searchBox.textEdited.connect(self.searchChange)
        self.searchBox.setPlaceholderText(conf.app.toolBar.searchBox.placeholder)
        self.searchBox.move(conf.app.toolBar.searchBox.pos.x,conf.app.toolBar.searchBox.pos.y)


    def setStatusBar(self):
        self.statusBar().showMessage(self.statusText)
        # self.downloadBtn.setDisabled(False)


    def selectedQuality(self,text):
        infoText = self.filename
        self.info.setText(infoText + ' ' + text)
        self.downloadBtn.setDisabled(False)

    def disabledAll(self):
        self.setDisabled(True)

    def enableAll(self):
        self.setEnabled(True)

    def completed(self,path):
        self.enableAll()
        self.statusBar().showMessage(conf.app.download_dir + self.filename + '.mp4 indirildi !')
        self.infoClear()
        self.searchBtn.setDisabled(True)
        self.searchBox.clear()
        self.searchBox.setFocus(True)

    def downloadVideo(self):
        self.disabledAll()
        self.statusBar().showMessage('İndiriliyor...!')
        if self.isEnabled() == False :
            video = self.yt.get(conf.app.video.type,self.quality.currentText())
            sleep(5)
            video.download(path=conf.app.download_dir,force_overwrite=True,on_finish=self.completed)


    def initUI(self):
        self.toolBar()
        self.setStatusBar()
        self.info = QLabel(self)
        self.info.move(120,50)
        self.info.setMinimumWidth(450)

        self.quality = QComboBox(self)
        self.quality.move(120,80)
        self.quality.hide()
        self.quality.activated[str].connect(self.selectedQuality)

        self.downloadBtn = QPushButton('İndir',self)
        self.downloadBtn.move(250,80)
        self.downloadBtn.setDisabled(True)
        self.downloadBtn.hide()
        self.downloadBtn.clicked.connect(self.downloadVideo)

        self.setGeometry(self.pos.x,self.pos.y,self.res.w,self.res.h)
        self.setMaximumSize(self.res.w,self.res.h)
        self.setMinimumSize(self.res.w,self.res.h)
        self.setWindowTitle(conf.app.title + " - " + conf.app.version)
        self.show()
class CaiwuguanliUpdateDataBase(QDialog):
    def __init__(self):
        super(CaiwuguanliUpdateDataBase, self).__init__()
        self.label_dict = {'发票编号': 'money_id', '发票抬头': 'money_title'}
        self.init_gui()

    def init_gui(self):
        self.resize(300, 240)
        self.desktopRect = QApplication.desktop().screenGeometry()
        self.position_centerx = QApplication.desktop().width() - self.width()
        self.position_centery = QApplication.desktop().height() - self.height()
        self.move(self.position_centerx / 2, self.position_centery / 2)

        self.titlelbl = QLabel('更新数据', self)
        self.titlelbl.resize(100, 30)
        self.titlelbl.move((self.width() - self.titlelbl.width()) / 2, 5)
        self.titlelbl.setAlignment(Qt.AlignCenter)

        self.input_lbl = QLabel('输入信息', self)
        self.input_lbl.resize(60, 20)
        self.input_lbl.move(60, 40)
        self.locate_lbl = QLabel('经费额度', self)
        self.lianxifangshi_lbl = QLabel('报销时间', self)
        self.locate_lbl.resize(60, 20)
        self.locate_lbl.move(60, 80)
        self.lianxifangshi_lbl.resize(60, 20)
        self.lianxifangshi_lbl.move(60, 120)

        # 输入信息框
        self.input_line = QLineEdit(self)
        self.input_line.resize(100, 20)
        self.input_line.move(150, 40)
        self.locate_line = QLineEdit(self)
        self.locate_line.resize(100, 20)
        self.locate_line.move(150, 80)
        self.lianxifangshi_line = QLineEdit(self)
        self.lianxifangshi_line.resize(100, 20)
        self.lianxifangshi_line.move(150, 120)

        # 下拉菜单
        self.combo = QComboBox(self)
        self.combo.addItem("发票编号")
        self.combo.addItem("发票抬头")
        self.combo.move((self.width() - self.combo.width()) / 2, 160)

        # save button
        self.save_btn = QPushButton('更新', self)
        self.save_btn.move((self.width() - self.save_btn.width()) / 2, 200)
        self.show()

        self.save_btn.clicked.connect(self.clicked_method)

    def clicked_method(self):
        global text_string
        self.lianxifangshi_text = self.lianxifangshi_line.text()
        self.locate_text = self.locate_line.text()
        self.get_data_value = self.input_line.text()
        text = self.combo.currentText()
        for key, value in self.label_dict.items():
            if text == key:
                text_string = self.label_dict[key]
                break
        self.get_data_index = text_string

        print(self.lianxifangshi_text, self.locate_text, self.get_data_index)
        self.close()
    def create_ui(self):
        # 1.文字标签
        # QLabel(显示的文字, 父标签/放到哪个窗口上)
        label1 = QLabel('用户名:', self)
        # 一般不常用的移动坐标
        label1.move(50, 10)

        # 2.按钮
        btn1 = QPushButton('登录', self)
        btn1.move(50, 50)
        # css语法:选择器{属性1:属性值1; 属性2:属性值2;..}
        # color - 字体颜色,对应的值:颜色单词, rbg(255, 0, 0)
        #
        btn1.setStyleSheet('QPushButton{}')
        btn2 = QRadioButton('男', self)
        btn2.move(50, 100)
        btn3 = QCheckBox('篮球', self)
        btn3.move(50, 150)
        btn4 = QCommandLinkButton('hello', 'hellowword', self)
        btn4.move(50, 200)

        b1 = QDialogButtonBox.StandardButton.Ok
        b2 = QDialogButtonBox.StandardButton.Cancel
        btn5 = QDialogButtonBox(b2, self)
        btn5.move(50, 300)

        # 3.输入框
        input1 = QLineEdit(self)
        input1.move(150, 10)
        input2 = QLineEdit('admin', self)
        input2.move(150, 50)
        input1.setText('张三')
        # 富文本
        input3 = QTextEdit('张三', self)
        input3.move(50, 300)
        # 设置成只读
        input3.setReadOnly(True)
        # 只能显示纯文本
        input4 = QPlainTextEdit(self)
        input4.move(300, 10)
        # 输入数值
        input5 = QSpinBox(self)
        input5.move(100, 100)
        input5.setMinimum(10)
        input5.setMaximum(20)
        input5.setValue(15)
        print(input5.value())  # 获取当前值
        # 输入小数
        input6 = QDoubleSpinBox(self)
        input6.move(100, 150)
        # 下拉菜单
        input7 = QComboBox(self)
        input7.addItems(['item1', 'item2'])
        input7.move(150, 200)
        print(input7.currentText())  # 获取当前选中的选项,适用input8
        input8 = QFontComboBox(self)
        input8.move(350, 300)
        input8.setCurrentIndex(2)
        print(input8.currentText())
        label1.setFont(input8.currentFont())
        # 日期选择
        input9 = QDateEdit(date.today(), self)
        input9.move(300, 400)
        # 选择颜色
        input10 = QColorDialog(self)
        input10.move(400, 400)
        # input10.show()

        input11 = QDial(self)
        input11.move(300, 200)

        input12 = QSlider(self)
        input12.move(430, 350)
        input12.setMaximum(100)
        input12.setMinimum(-100)
        input12.setValue(20)
        input12.setOrientation(Qt.Horizontal)  # 设置为水平方向
Beispiel #18
0
    def initUI(self):
        self.setGeometry(300, 300, 600, 600)
        self.setWindowTitle('Drawing home')
        self.width = 175  #default settings
        self.height = 100
        self.roofHeight = 50
        self.mainColor1 = QColor(255, 255, 127)
        self.mainColor2 = QColor(255, 85, 0)
        self.roofColor = QColor(199, 250, 252)
        self.doorColor = QColor(255, 255, 255)
        self.lightColor = QColor(255, 219, 41)
        self.windowStyle = "Round window"
        self.roomNumber = 1

        drawButton = QPushButton(
            "Move cursor here to update the object, if it was not happened",
            self)
        drawButton.setFont(QFont("Comic Sans MS", 11, QFont.Normal))
        drawButton.move(40, 60)
        drawButton.adjustSize()
        #sliders etc.
        self.changeWidth = QSlider(Qt.Horizontal, self)
        self.changeWidth.setFocusPolicy(Qt.NoFocus)
        self.changeWidth.setStyleSheet(sldStyle)  #use our own style!
        self.changeWidth.setGeometry(30, 150, 100, 30)
        self.changeWidth.valueChanged[int].connect(self.changeWidthF)
        self.changeHeight = QSlider(Qt.Horizontal, self)
        self.changeHeight.setFocusPolicy(Qt.NoFocus)
        self.changeHeight.setStyleSheet(sldStyle)
        self.changeHeight.setGeometry(30, 220, 100, 30)
        self.changeHeight.valueChanged[int].connect(self.changeHeightF)
        self.changeRoofHeight = QSlider(Qt.Horizontal, self)
        self.changeRoofHeight.setFocusPolicy(Qt.NoFocus)
        self.changeRoofHeight.setStyleSheet(sldStyle)
        self.changeRoofHeight.setGeometry(30, 290, 100, 30)
        self.changeRoofHeight.valueChanged[int].connect(self.changeRoofHeightF)
        changeWindowStyle = QComboBox(self)
        changeWindowStyle.addItem("Round window")
        changeWindowStyle.addItem("2-part window")
        changeWindowStyle.addItem("No window")
        changeWindowStyle.move(30, 365)
        changeWindowStyle.setFont(QFont("Tahoma", 10, QFont.Normal))
        changeWindowStyle.activated[str].connect(self.changeWindowStyle)
        changeWindowStyle.adjustSize()
        changeIllumination = QCheckBox('Neon Light', self)
        changeIllumination.move(30, 410)
        changeIllumination.setFont(QFont("Segoe Print", 10, QFont.Normal))
        changeIllumination.adjustSize()
        changeIllumination.stateChanged.connect(self.changeIllumination)
        changeRoomNumber = QComboBox(self)
        changeRoomNumber.addItem("1")
        changeRoomNumber.addItem("2")
        changeRoomNumber.move(30, 505)
        changeRoomNumber.setFont(QFont("Tahoma", 10, QFont.Normal))
        changeRoomNumber.activated[int].connect(self.changeRoomNumber)
        #labels
        changeW = QLabel("Width", self)
        changeW.move(30, 120)
        changeW.setFont(QFont("Segoe Print", 10, QFont.Normal))
        changeH = QLabel("Height", self)
        changeH.move(30, 190)
        changeH.setFont(QFont("Segoe Print", 10, QFont.Normal))
        changeRH = QLabel("Roof level", self)
        changeRH.move(30, 260)
        changeRH.setFont(QFont("Segoe Print", 10, QFont.Normal))
        changeWS = QLabel("Window style", self)
        changeWS.move(30, 330)
        changeWS.setFont(QFont("Segoe Print", 10, QFont.Normal))
        changeWS.adjustSize()
        changeRN = QLabel("Number of rooms", self)
        changeRN.move(30, 450)
        changeRN.setFont(QFont("Segoe Print", 10, QFont.Normal))
        changeRN.adjustSize()
        changeRN1 = QLabel("on the 2nd floor", self)
        changeRN1.move(30, 470)
        changeRN1.setFont(QFont("Segoe Print", 10, QFont.Normal))
        changeRN1.adjustSize()
        #toolbar actions
        roofColorAction = QAction(QIcon('colorR.png'),
                                  'Change color of the roof', self)
        roofColorAction.triggered.connect(self.changeRoofColor)
        color1Action = QAction(QIcon('color2.png'),
                               'Change color of the upper part', self)
        color1Action.triggered.connect(self.changeColor1)
        color2Action = QAction(QIcon('color1.png'),
                               'Change color of the lower part', self)
        color2Action.triggered.connect(self.changeColor2)
        doorColorAction = QAction(QIcon('colorD.png'),
                                  'Change color of the door', self)
        doorColorAction.triggered.connect(self.changeDoorColor)
        randomizeAction = QAction(QIcon('random.png'), 'Randonize your house',
                                  self)
        randomizeAction.triggered.connect(self.randomize)
        toolbar = self.addToolBar('Menu')
        toolbar.setIconSize(QSize(45, 45))
        toolbar.addAction(roofColorAction)
        toolbar.addAction(color2Action)
        toolbar.addAction(color1Action)
        toolbar.addAction(doorColorAction)
        toolbar.addAction(randomizeAction)

        self.show()
Beispiel #19
0
class View(QMainWindow):
    def __init__(self):
        self.qapp = QApplication([])
        super().__init__()
        self.setFixedSize(1080, 700)
        self.move(100, 10)
        self.setWindowTitle(
            'Лабораторная работа №5 по моделированию.'
            'Жарова ИУ7-73Б'
        )

        self.normal_label = QLabel('Параметры\nклиентов', self)
        self.normal_label.setFixedSize(300, 50)
        self.normal_label.move(50, 50)

        self.client = 10
        self.client_label = QLabel('average =', self)
        self.client_label.setFixedSize(100, 50)
        self.client_label.move(50, 100)
        self.client_line_edit = QLineEdit(str(self.client), self)
        self.client_line_edit.setFixedSize(100, 50)
        self.client_line_edit.move(120, 100)

        self.client_delta = 2
        self.client_delta_label = QLabel(' +-', self)
        self.client_delta_label.setFixedSize(100, 50)
        self.client_delta_label.move(220, 100)
        self.client_delta_line_edit = QLineEdit(str(self.client_delta), self)
        self.client_delta_line_edit.setFixedSize(100, 50)
        self.client_delta_line_edit.move(250, 100)

        self.op_label = QLabel('Параметры\nоператоров', self)
        self.op_label.setFixedSize(300, 100)
        self.op_label.move(380, 20)

        self.op1_m = 20
        self.op1_m_label = QLabel('average1 =', self)
        self.op1_m_label.setFixedSize(100, 50)
        self.op1_m_label.move(380, 100)
        self.op1_m_line_edit = QLineEdit(str(self.op1_m), self)
        self.op1_m_line_edit.setFixedSize(100, 50)
        self.op1_m_line_edit.move(460, 100)

        self.op1_delta = 5
        self.op1_delta_label = QLabel(' +-', self)
        self.op1_delta_label.setFixedSize(100, 50)
        self.op1_delta_label.move(560, 100)
        self.op1_delta_line_edit = QLineEdit(str(self.op1_delta), self)
        self.op1_delta_line_edit.setFixedSize(100, 50)
        self.op1_delta_line_edit.move(590, 100)

        self.op2_m = 40
        self.op2_m_label = QLabel('average2 =', self)
        self.op2_m_label.setFixedSize(100, 50)
        self.op2_m_label.move(380, 160)
        self.op2_m_line_edit = QLineEdit(str(self.op2_m), self)
        self.op2_m_line_edit.setFixedSize(100, 50)
        self.op2_m_line_edit.move(460, 160)

        self.op2_delta = 10
        self.op2_delta_label = QLabel(' +-', self)
        self.op2_delta_label.setFixedSize(100, 50)
        self.op2_delta_label.move(560, 160)
        self.op2_delta_line_edit = QLineEdit(str(self.op2_delta), self)
        self.op2_delta_line_edit.setFixedSize(100, 50)
        self.op2_delta_line_edit.move(590, 160)

        self.op3_m = 40
        self.op3_m_label = QLabel('average3 =', self)
        self.op3_m_label.setFixedSize(100, 50)
        self.op3_m_label.move(380, 220)
        self.op3_m_line_edit = QLineEdit(str(self.op3_m), self)
        self.op3_m_line_edit.setFixedSize(100, 50)
        self.op3_m_line_edit.move(460, 220)

        self.op3_delta = 20
        self.op3_delta_label = QLabel(' +-', self)
        self.op3_delta_label.setFixedSize(100, 50)
        self.op3_delta_label.move(560, 220)
        self.op3_delta_line_edit = QLineEdit(str(self.op3_delta), self)
        self.op3_delta_line_edit.setFixedSize(100, 50)
        self.op3_delta_line_edit.move(590, 220)

        self.comp_label = QLabel('Параметры\nкомпьютеров', self)
        self.comp_label.setFixedSize(300, 100)
        self.comp_label.move(720, 20)

        self.comp1 = 15
        self.comp1_label = QLabel('const1 =', self)
        self.comp1_label.setFixedSize(100, 50)
        self.comp1_label.move(720, 100)
        self.comp1_m_line_edit = QLineEdit(str(self.comp1), self)
        self.comp1_m_line_edit.setFixedSize(100, 50)
        self.comp1_m_line_edit.move(785, 100)

        self.comp2 = 30
        self.comp2_label = QLabel('const2 =', self)
        self.comp2_label.setFixedSize(100, 50)
        self.comp2_label.move(720, 160)
        self.comp2_m_line_edit = QLineEdit(str(self.comp2), self)
        self.comp2_m_line_edit.setFixedSize(100, 50)
        self.comp2_m_line_edit.move(785, 160)

        self.method_label = QLabel('Метод рассчета', self)
        self.method_label.setFixedSize(200, 100)
        self.method_label.move(920, 14)

        self.method_box = QComboBox(self)
        self.method_box.addItems(['delta t', 'events'])
        self.method_box.setFixedSize(140, 60)
        self.method_box.move(920, 90)
        self.method_box.currentTextChanged.connect(self.select_method)

        self.dt = 0.01
        self.dt_label = QLabel('dt =', self)
        self.dt_label.setFixedSize(200, 100)
        self.dt_label.move(920, 135)
        self.dt_line_edit = QLineEdit(str(self.dt), self)
        self.dt_line_edit.setFixedSize(100, 50)
        self.dt_line_edit.move(960, 160)

        self.select_method()

        self.n = 300
        self.n_label = QLabel('Обработать \nзаявок (n) = ', self)
        self.n_label.setFixedSize(100, 50)
        self.n_label.move(50, 200)
        self.n_line_edit = QLineEdit(str(self.n), self)
        self.n_line_edit.setFixedSize(100, 50)
        self.n_line_edit.move(140, 200)

        self.system = system.System(
            client_law=UniformDistributionLaw(a=8, b=12),
            op1_law=UniformDistributionLaw(a=15, b=25),
            op2_law=UniformDistributionLaw(a=30, b=50),
            op3_law=UniformDistributionLaw(a=20, b=60),
            comp1_law=ConstantDistributionLaw(c=15),
            comp2_law=ConstantDistributionLaw(c=30),
            n=self.n, dt=1, method='delta t'
        )

        result = self.system.calculate()

        self.button = QPushButton('Провести рассчет', self)
        self.button.setFixedSize(500, 100)
        self.button.clicked.connect(self.calculate)
        self.button.move(100, 500)

        self.result_label = QLabel('Результаты рассчета', self)
        self.result_label.setFixedSize(200, 100)
        self.result_label.move(760, 280)

        self.generated_count_label = QLabel('Количество\nобработанных заявок =', self)
        self.generated_count_label.setFixedSize(300, 50)
        self.generated_count_label.move(720, 420)
        #self.generated_count_label.hide()
        self.generated_count_line_edit = QLineEdit(str(result['generated_count']), self)
        self.generated_count_line_edit.setFixedSize(100, 50)
        self.generated_count_line_edit.move(880, 420)
        #self.generated_count_line_edit.hide()

        self.processed_count_label = QLabel('Количество\nобработанных заявок =', self)
        self.processed_count_label.setFixedSize(300, 50)
        self.processed_count_label.move(720, 420)
        self.processed_count_label.hide()
        self.processed_count_line_edit = QLineEdit(str(result['processed_count']), self)
        self.processed_count_line_edit.setFixedSize(100, 50)
        self.processed_count_line_edit.move(880, 420)
        self.processed_count_line_edit.hide()

        self.rejected_count_label = QLabel('Количество\nпропущенных заявок =', self)
        self.rejected_count_label.setFixedSize(300, 50)
        self.rejected_count_label.move(720, 480)
        self.rejected_count_line_edit = QLineEdit(str(result['rejected_count']), self)
        self.rejected_count_line_edit.setFixedSize(100, 50)
        self.rejected_count_line_edit.move(880, 480)

        self.rejected_probability_label = QLabel('Вероятность\nотказа =', self)
        self.rejected_probability_label.setFixedSize(300, 50)
        self.rejected_probability_label.move(720, 540)
        self.rejected_probability_line_edit = QLineEdit(str(round(result['rejected_count'] / (result['generated_count'] + result['rejected_count']), 4)), self)
        self.rejected_probability_line_edit.setFixedSize(100, 50)
        self.rejected_probability_line_edit.move(880, 540)

    def start_application(self):
        self.update()
        self.show()
        self.qapp.exec_()

    def select_method(self):
        self.method = self.method_box.currentText()
        if self.method == 'events':
            self.dt_label.hide()
            self.dt_line_edit.hide()
        else:
            self.dt_label.show()
            self.dt_line_edit.show()

    def calculate(self):
        try:
            self.client = float(self.client_line_edit.text())
            self.client_delta = float(self.client_delta_line_edit.text())
            self.op1_m = float(self.op1_m_line_edit.text())
            self.op1_delta = float(self.op1_delta_line_edit.text())
            self.op2_m = float(self.op2_m_line_edit.text())
            self.op2_delta = float(self.op2_delta_line_edit.text())
            self.op3_m = float(self.op3_m_line_edit.text())
            self.op3_delta = float(self.op3_delta_line_edit.text())
            self.comp1 = float(self.comp1_m_line_edit.text())
            self.comp2 = float(self.comp2_m_line_edit.text())
            self.dt = float(self.dt_line_edit.text())
            self.n = int(self.n_line_edit.text())
        except ValueError as exc:
            print(exc)
            return
        self.system = system.System(
            client_law=UniformDistributionLaw(a=self.client-self.client_delta, b=self.client+self.client_delta),
            op1_law=UniformDistributionLaw(a=self.op1_m-self.op1_delta, b=self.op1_m+self.op1_delta),
            op2_law=UniformDistributionLaw(a=self.op2_m-self.op2_delta, b=self.op2_m+self.op2_delta),
            op3_law=UniformDistributionLaw(a=self.op3_m-self.op3_delta, b=self.op3_m+self.op3_delta),
            comp1_law=ConstantDistributionLaw(c=self.comp1),
            comp2_law=ConstantDistributionLaw(c=self.comp2),
            n=self.n, dt=self.dt, method=self.method
        )
        result = self.system.calculate()
        self.generated_count_line_edit.setText(str(result['generated_count']))
        self.processed_count_line_edit.setText(str(result['processed_count']))
        self.rejected_count_line_edit.setText(str(result['rejected_count']))
        self.rejected_probability_line_edit.setText(str(round(result['rejected_count'] / (result['generated_count'] + result['rejected_count']), 4)))
class GUI(QMainWindow, QThread):
    def __init__(self):
        super(GUI, self).__init__()
        self.initUI()
        self.webcam = Webcam()
        self.video = Video()
        self.input = self.webcam
        self.dirname = ""
        print("Input: webcam")
        self.statusBar.showMessage("Input: webcam", 5000)
        self.btnOpen.setEnabled(False)
        self.process = Process()
        self.status = False
        self.frame = np.zeros((10, 10, 3), np.uint8)
        # self.plot = np.zeros((10,10,3),np.uint8)
        self.bpm = 0

    def initUI(self):

        # set font
        font = QFont()
        font.setPointSize(16)

        # widgets
        self.btnStart = QPushButton("Start", self)
        self.btnStart.move(440, 520)
        self.btnStart.setFixedWidth(200)
        self.btnStart.setFixedHeight(50)
        self.btnStart.setFont(font)
        self.btnStart.clicked.connect(self.run)

        self.btnOpen = QPushButton("Open", self)
        self.btnOpen.move(230, 520)
        self.btnOpen.setFixedWidth(200)
        self.btnOpen.setFixedHeight(50)
        self.btnOpen.setFont(font)
        self.btnOpen.clicked.connect(self.openFileDialog)

        self.cbbInput = QComboBox(self)
        self.cbbInput.addItem("Webcam")
        self.cbbInput.addItem("Video")
        self.cbbInput.setCurrentIndex(0)
        self.cbbInput.setFixedWidth(200)
        self.cbbInput.setFixedHeight(50)
        self.cbbInput.move(20, 520)
        self.cbbInput.setFont(font)
        self.cbbInput.activated.connect(self.selectInput)
        # -------------------

        self.lblDisplay = QLabel(self)  # label to show frame from camera
        self.lblDisplay.setGeometry(10, 10, 640, 480)
        self.lblDisplay.setStyleSheet("background-color: #000000")

        self.lblROI = QLabel(self)  # label to show face with ROIs
        self.lblROI.setGeometry(660, 10, 200, 200)
        self.lblROI.setStyleSheet("background-color: #000000")

        self.lblHR = QLabel(self)  # label to show HR change over time
        self.lblHR.setGeometry(900, 20, 300, 40)
        self.lblHR.setFont(font)
        self.lblHR.setText("Frequency: ")

        self.lblHR2 = QLabel(self)  # label to show stable HR
        self.lblHR2.setGeometry(900, 70, 300, 40)
        self.lblHR2.setFont(font)
        self.lblHR2.setText("Heart rate: ")

        # self.lbl_Age = QLabel(self) #label to show stable HR
        # self.lbl_Age.setGeometry(900,120,300,40)
        # self.lbl_Age.setFont(font)
        # self.lbl_Age.setText("Age: ")

        # self.lbl_Gender = QLabel(self) #label to show stable HR
        # self.lbl_Gender.setGeometry(900,170,300,40)
        # self.lbl_Gender.setFont(font)
        # self.lbl_Gender.setText("Gender: ")

        # dynamic plot
        self.signal_Plt = pg.PlotWidget(self)

        self.signal_Plt.move(660, 220)
        self.signal_Plt.resize(480, 192)
        self.signal_Plt.setLabel('bottom', "Signal")

        self.fft_Plt = pg.PlotWidget(self)

        self.fft_Plt.move(660, 425)
        self.fft_Plt.resize(480, 192)
        self.fft_Plt.setLabel('bottom', "FFT")

        self.timer = pg.QtCore.QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(200)

        self.statusBar = QStatusBar()
        self.statusBar.setFont(font)
        self.setStatusBar(self.statusBar)

        # event close
        self.c = Communicate()
        self.c.closeApp.connect(self.close)

        # event change combobox index

        # config main window
        self.setGeometry(100, 100, 1160, 640)
        # self.center()
        self.setWindowTitle("Heart rate monitor")
        self.show()

    def update(self):
        # z = np.random.normal(size=1)
        # u = np.random.normal(size=1)
        self.signal_Plt.clear()
        self.signal_Plt.plot(self.process.samples[20:], pen='g')

        self.fft_Plt.clear()
        self.fft_Plt.plot(np.column_stack(
            (self.process.freqs, self.process.fft)),
                          pen='g')

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def closeEvent(self, event):
        reply = QMessageBox.question(self, "Message",
                                     "Are you sure want to quit",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.Yes)
        if reply == QMessageBox.Yes:
            event.accept()
            self.input.stop()
            cv2.destroyAllWindows()
        else:
            event.ignore()

    def selectInput(self):
        self.reset()
        if self.cbbInput.currentIndex() == 0:
            self.input = self.webcam
            print("Input: webcam")
            self.btnOpen.setEnabled(False)
            # self.statusBar.showMessage("Input: webcam",5000)
        elif self.cbbInput.currentIndex() == 1:
            self.input = self.video
            print("Input: video")
            self.btnOpen.setEnabled(True)
            # self.statusBar.showMessage("Input: video",5000)

    def mousePressEvent(self, event):
        self.c.closeApp.emit()

        # def make_bpm_plot(self):

        # plotXY([[self.process.times[20:],
        # self.process.samples[20:]],
        # [self.process.freqs,
        # self.process.fft]],
        # labels=[False, True],
        # showmax=[False, "bpm"],
        # label_ndigits=[0, 0],
        # showmax_digits=[0, 1],
        # skip=[3, 3],
        # name="Plot",
        # bg=None)

        # fplot = QImage(self.plot, 640, 280, QImage.Format_RGB888)
        # self.lblPlot.setGeometry(10,520,640,280)
        # self.lblPlot.setPixmap(QPixmap.fromImage(fplot))

    def key_handler(self):
        """
        cv2 window must be focused for keypresses to be detected.
        """
        # self.pressed = waitKey(1) & 255  # wait for keypress for 10 ms
        self.pressed = cv2.waitKey(1) & 255
        if self.pressed == 27:  # exit program on 'esc'
            print("[INFO] Exiting")
            self.webcam.stop()
            sys.exit()

    def openFileDialog(self):
        self.dirname = QFileDialog.getOpenFileName(
            self, 'OpenFile', r"C:\Users\uidh2238\Desktop\test videos")
        # self.statusBar.showMessage("File name: " + self.dirname,5000)

    def reset(self):
        self.process.reset()
        self.lblDisplay.clear()
        self.lblDisplay.setStyleSheet("background-color: #000000")

    @pyqtSlot()
    def main_loop(self):
        frame = self.input.get_frame()

        self.process.frame_in = frame
        self.process.run()

        cv2.imshow("Processed", frame)

        self.frame = self.process.frame_out  # get the frame to show in GUI
        self.f_fr = self.process.frame_ROI  # get the face to show in GUI
        # print(self.f_fr.shape)
        self.bpm = self.process.bpm  # get the bpm change over the time

        self.frame = cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR)
        cv2.putText(self.frame,
                    "FPS " + str(float("{:.2f}".format(self.process.fps))),
                    (20, 460), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 255, 255), 2)
        img = QImage(self.frame, self.frame.shape[1], self.frame.shape[0],
                     self.frame.strides[0], QImage.Format_RGB888)
        self.lblDisplay.setPixmap(QPixmap.fromImage(img))

        self.f_fr = cv2.cvtColor(self.f_fr, cv2.COLOR_RGB2BGR)
        # self.lblROI.setGeometry(660,10,self.f_fr.shape[1],self.f_fr.shape[0])
        self.f_fr = np.transpose(self.f_fr, (0, 1, 2)).copy()
        f_img = QImage(self.f_fr, self.f_fr.shape[1], self.f_fr.shape[0],
                       self.f_fr.strides[0], QImage.Format_RGB888)
        self.lblROI.setPixmap(QPixmap.fromImage(f_img))

        self.lblHR.setText("Freq: " + str(float("{:.2f}".format(self.bpm))))

        if self.process.bpms.__len__() > 50:
            if (
                    max(self.process.bpms - np.mean(self.process.bpms)) < 5
            ):  # show HR if it is stable -the change is not over 5 bpm- for 3s
                self.lblHR2.setText(
                    "Heart rate: " +
                    str(float("{:.2f}".format(np.mean(self.process.bpms)))) +
                    " bpm")

        # self.lbl_Age.setText("Age: "+str(self.process.age))
        # self.lbl_Gender.setText("Gender: "+str(self.process.gender))
        # self.make_bpm_plot()#need to open a cv2.imshow() window to handle a pause
        # QtTest.QTest.qWait(10)#wait for the GUI to respond
        self.key_handler()  # if not the GUI cant show anything

    def run(self, input):
        self.reset()
        input = self.input
        self.input.dirname = self.dirname
        if self.input.dirname == "" and self.input == self.video:
            print("choose a video first")
            # self.statusBar.showMessage("choose a video first",5000)
            return

        if self.status is False:
            self.status = True
            input.start()
            self.btnStart.setText("Stop")
            self.cbbInput.setEnabled(False)
            self.btnOpen.setEnabled(False)
            self.lblHR2.clear()
            while self.status is True:
                self.main_loop()

        elif self.status is True:
            self.status = False
            input.stop()
            self.btnStart.setText("Start")
            self.cbbInput.setEnabled(True)
Beispiel #21
0
class App(QMainWindow):
    def __init__(self):
        self.funcs = {
            0: self.drawTaskersPerLocation,
            1: self.drawSharedTaskers,
            2: self.draw_taskers_with_reviews,
            3: self.average_cost
        }
        super().__init__()
        self.left = 10
        self.top = 10
        self.title = 'TaskRabbit analysis app'
        self.width = 1300
        self.height = 800
        self.initUI()

    def initUI(self):
        self.current_plot = 0
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        canv = QWidget(self)
        canv.setMinimumHeight(800)
        canv.setMinimumWidth(1000)
        self.plotWidget = MplWidget(canv)
        self.plotWidget.setGeometry(QRect(0, 50, 1000, 700))
        self.comboBox = QComboBox(self)
        #self.comboBox.currentIndexChanged.connect(self.updateGraph)
        c.execute("SELECT name FROM cities;")
        for row in c:
            self.comboBox.addItem(row[0])

        self.city_name = str(self.comboBox.currentText())
        self.comboBox.currentIndexChanged.connect(self.update_city)

        l1 = self.create_label("Pick city:", subtitleFont)
        l1.move(1050, 10)

        self.comboBox.move(1050, 30)

        self.create_label("City details", subtitleFont).move(1050, 90)
        self.l_taskers = self.create_label("Num of taskers: 100000", textFont)
        self.l_reviews = self.create_label("Num of reviews: 200000", textFont)
        self.l_taskers.move(1050, 120)
        self.l_reviews.move(1050, 140)
        self.update_city()

        button = QPushButton('Total taskers', self)
        button.move(1000, 210)
        button.resize(160, 50)
        button.clicked.connect(lambda: self.plot_data(0))

        button = QPushButton('Shared taskers', self)
        button.setToolTip('Show how taskers are shared across locations')
        button.move(1000, 280)
        button.resize(160, 50)
        button.clicked.connect(lambda: self.plot_data(1))

        button = QPushButton('Taskers with reviews', self)
        button.move(1000, 350)
        button.resize(160, 50)
        button.clicked.connect(lambda: self.plot_data(2))

        button = QPushButton('Average cost', self)
        button.move(1000, 420)
        button.resize(160, 50)
        button.clicked.connect(lambda: self.plot_data(3))

    def update_city(self):
        self.city_name = str(self.comboBox.currentText())
        c.execute(
            "SELECT num_taskers, num_reviews FROM cities, city_details WHERE city_details.city_id = cities.city_id AND cities.name = '"
            + self.city_name + "';")
        city_details = c.fetchone()
        self.l_taskers.setText("Num of taskers: " + str(city_details[0]))
        self.l_reviews.setText("Num of reviews " + str(city_details[1]))
        self.plot_data(self.current_plot)

    def plot_data(self, i):
        self.current_plot = i
        self.plotWidget.canvas.ax.clear()
        f = self.funcs[i]
        f()

    def draw_key_value_bars(self, dict, title, xlabel, ylabel):
        keys = []
        vals = []
        for elem in dict.keys():
            keys.append(elem)
            vals.append(dict[elem])

        y_pos = np.arange(len(keys))

        self.plotWidget.canvas.ax.bar(keys, vals, align='center', alpha=0.5)
        labels = []
        for l in keys:
            labels.append("\n".join(l.split(" ")))
        self.plotWidget.canvas.ax.set_xticks(y_pos, labels)
        self.plotWidget.canvas.ax.set_xticklabels(labels)
        self.plotWidget.canvas.ax.set_ylabel(ylabel)
        self.plotWidget.canvas.ax.set_xlabel(xlabel)
        self.plotWidget.canvas.ax.set_title(title)
        self.plotWidget.canvas.draw()

    def drawTaskersPerLocation(self):
        locations = kh.get_locations_in_city(self.city_name)
        num_of_taskers = kh.get_num_taskers_per_location(locations)
        self.draw_key_value_bars(num_of_taskers,
                                 "Number of taskers across each area",
                                 "Areas in " + self.city_name,
                                 "Number of taskers")

    def drawSharedTaskers(self):
        locations = kh.get_locations_in_city(self.city_name)
        location_taskers = kh.get_taskers_per_location(locations)
        locations = [location[0] for location in locations]
        arrays = []
        for i in range(len(locations)):
            arr = []
            for location in locations:
                i_shared = sum([
                    1 if len([
                        x for x in location_taskers.keys()
                        if (not x == location)
                        and Counter(location_taskers[x])[tasker] > 0
                    ]) == i else 0 for tasker in location_taskers[location]
                ])
                arr.append(i_shared)
            arrays.append(arr)
        X = len(locations)
        for i, arr in enumerate(arrays):
            if i == 0:
                self.plotWidget.canvas.ax.bar(np.arange(X),
                                              arr,
                                              label="Unique")
            else:
                self.plotWidget.canvas.ax.bar(
                    np.arange(X),
                    arr,
                    bottom=[
                        sum(x) for x in zip(
                            *[a for j, a in enumerate(arrays) if j < i])
                    ],
                    label="Shared with " + str(i))
        self.plotWidget.canvas.ax.legend()
        self.plotWidget.canvas.ax.set_xticks(np.arange(X))
        labels = []
        for l in locations:
            labels.append("\n".join(l.split(" ")))
        self.plotWidget.canvas.ax.set_xticklabels(labels)
        self.plotWidget.canvas.ax.set_title("Taskers shared across locations")
        self.plotWidget.canvas.ax.set_ylabel("Number of taskers")
        self.plotWidget.canvas.ax.set_xlabel("Areas in " + self.city_name)
        self.plotWidget.canvas.draw()

    def draw_taskers_with_reviews(self):
        locations = kh.get_locations_in_city(self.city_name)
        num_of_taskers = kh.get_num_taskers_per_location(locations)
        taskers_with_review = {}
        for location in locations:
            c.execute(
                "SELECT count(*) FROM taskers, tasker_locations WHERE exists (SELECT * FROM reviews WHERE [tasker_id] = taskers.tasker_id) AND taskers.tasker_id = tasker_locations.tasker_id AND tasker_locations.location_id = "
                + str(location[1]) + ";")
            taskers_with_review[location[0]] = round(
                (c.fetchone()[0] / num_of_taskers[location[0]]) * 100, 2)

        self.draw_key_value_bars(
            taskers_with_review,
            "Percentage of taskers with reviews in each area",
            "Areas in " + self.city_name, "Taskers with reviews (%)")

    '''
    def draw_reviews_per_tasker(self):
        locations = kh.get_locations_in_city(self.city_name)
        num_of_taskers = kh.get_num_taskers_per_location(locations)
        taskers_with_review = {}
        for location in locations:
            c.execute("SELECT AVG()")
            c.execute(
                "SELECT count(*) FROM taskers, tasker_locations WHERE exists (SELECT * FROM reviews WHERE [tasker_id] = taskers.tasker_id) AND taskers.tasker_id = tasker_locations.tasker_id AND tasker_locations.location_id = " + str(
                    location[1]) + ";")
            taskers_with_review[location[0]] = round((c.fetchone()[0] / num_of_taskers[location[0]]) * 100, 2)

        self.draw_key_value_bars(taskers_with_review, "Percentage of taskers with reviews in each area",
                             "Areas in " + self.city_name, "Taskers with reviews (%)")
    '''

    def average_cost(self):
        locations = kh.get_locations_in_city(self.city_name)
        cost_per_locations = {}
        for location in locations:
            c.execute(
                "SELECT AVG(amount) FROM price_details INNER JOIN taskers ON taskers.tasker_id = price_details.tasker_id INNER JOIN tasker_locations ON tasker_locations.tasker_id = taskers.tasker_id INNER JOIN  locations ON locations.location_id = tasker_locations.location_id WHERE locations.name = '"
                + location[0] +
                "' GROUP BY locations.location_id ORDER BY AVG(amount) DESC;")

            cost_per_locations[location[0]] = c.fetchone()[0]
        self.draw_key_value_bars(cost_per_locations,
                                 "Average cost per service",
                                 "Areas in " + self.city_name,
                                 "Average cost of tasker in each location")

    def create_label(self, text, font):
        label = QLabel(self)
        label.setText(text)
        label.setFont(font)
        label.adjustSize()
        label.setAlignment(Qt.AlignCenter)
        return label
Beispiel #22
0
class NonTech(QWidget):

	def __init__(self):
		super().__init__()
		self.title = 'VAPT Report Generator'
		self.left = 10
		self.top = 10
		self.width = 1280
		self.height = 720
		self.__Img = None
		self.__doc = None
		self.doc = Print_document()
		self.doc.start_doc()
		self.doc.initialize_doc()

	def NonTechUI(self):
		self.setWindowTitle(self.title)
		self.setWindowIcon(QIcon("Pristine.png"))
		self.setGeometry(self.left, self.top, self.width, self.height)

		self.font = QFont()
		self.font.setFamily('Helvetica')
		self.font.setPointSize(16)

		self.VCompany = QLabel('Client Name:',self)
		self.VCompany.move(20, 5)
		self.VCompany.resize(250,50)
		self.VCompany.setFont(self.font)

		self.VCompanyBox = QLineEdit(self)
		self.VCompanyBox.move(260, 10)
		self.VCompanyBox.resize(600,30)
		self.VCompanyBox.setFont(self.font)
		self.VCompanyBox.setText('')

		self.VDate = QLabel('Start Date:',self)
		self.VDate.move(20, 50)
		self.VDate.resize(250,50)
		self.VDate.setFont(self.font)

		self.VDateBox = QLineEdit(self)
		self.VDateBox.move(260, 50)
		self.VDateBox.resize(600,30)
		self.VDateBox.setFont(self.font)

		self.VTitle = QLabel('Title:',self)
		self.VTitle.move(20, 110)
		self.VTitle.resize(250,50)
		self.VTitle.setFont(self.font)

		self.VTitleBox = QLineEdit(self)
		self.VTitleBox.move(260, 115)
		self.VTitleBox.resize(600,30)
		self.VTitleBox.setFont(self.font)
		self.VTitleBox.setText('')

		self.VAuthor = QLabel('Author:',self)
		self.VAuthor.move(20, 155)
		self.VAuthor.resize(250,50)
		self.VAuthor.setFont(self.font)

		self.VAuthorbox = QLineEdit(self)
		self.VAuthorbox.move(260, 160)
		self.VAuthorbox.resize(600,30)
		self.VAuthorbox.setText('')

		self.VManager = QLabel('Project Manager:',self)
		self.VManager.move(20, 195)
		self.VManager.resize(250,50)
		self.VManager.setFont(self.font)

		self.VManagerbox = QLineEdit(self)
		self.VManagerbox.move(260, 200)
		self.VManagerbox.resize(600,30)
		self.VManagerbox.setText('')

		self.VApproach = QLabel('Approach:',self)
		self.VApproach.move(20, 305)
		self.VApproach.resize(250,50)
		self.VApproach.setFont(self.font)

		self.VApproachbox = QComboBox(self)
		self.VApproachbox.addItem('White-Box',1)
		self.VApproachbox.addItem('Black-Box',2)
		self.VApproachbox.move(260, 310)
		self.VApproachbox.resize(600,30)

		self.Rname = QLabel('Recipient Name:',self)
		self.Rname.move(20, 385)
		self.Rname.resize(250,50)
		self.Rname.setFont(self.font)

		self.Rnamebox = QLineEdit(self)
		self.Rnamebox.move(260, 400)
		self.Rnamebox.resize(600,30)
		self.Rnamebox.setText('')

		self.Rtitle = QLabel('Recipient Title',self)
		self.Rtitle.move(20, 435)
		self.Rtitle.resize(250,50)
		self.Rtitle.setFont(self.font)

		self.Rtitlebox = QLineEdit(self)
		self.Rtitlebox.move(260, 440)
		self.Rtitlebox.resize(600,30)
		self.Rtitlebox.setText('')

		self.VersionC = QLabel('Version:',self)
		self.VersionC.move(20, 355)
		self.VersionC.resize(250,50)
		self.VersionC.setFont(self.font)

		self.VersionCbox = QLineEdit(self)
		self.VersionCbox.move(260, 360)
		self.VersionCbox.resize(600,30)
		self.VersionCbox.setText('')

		self.SaveButton = QPushButton('Back', self)
		self.SaveButton.move(480,580)
		self.SaveButton.clicked.connect(self.back)
		self.SaveButton.setFont(self.font)

		self.saveReport = QPushButton('Add Intro',self)
		self.saveReport.move(560,580)
		self.saveReport.clicked.connect(self.on_report)
		self.saveReport.setFont(self.font)

		self.ImgButton = QPushButton('Browse', self)
		self.ImgButton.move(400,580)
		self.ImgButton.setFont(self.font)

		self.show()

	@pyqtSlot()
	def back(self):
		self.ui = MainWindow.App1()
		self.ui.initUI()
		NonTech.hide(self)

	@pyqtSlot()
	def on_report(self):
		self.doc.setTitle()

		cname = self.VCompanyBox.text()
		rname = self.Rnamebox.text()
		rtitle = self.Rtitlebox.text()
		Author = self.VAuthorbox.text()
		PManager = self.VManagerbox.text()
		Title = self.VTitleBox.text()
		Date= self.VDateBox.text()
		Version = self.VersionCbox.text()
		Approach = self.VApproachbox.currentText()

		self.doc.setCName(cname)

		self.doc.pageBreak()

		self.doc.AuthorTable(Author,Approach,PManager,Title,Version)
		self.doc.RecipientTable(rname,rtitle,cname)
		self.doc.VersionTable(Version,Author,Date)

		self.doc.pageBreak()

		self.doc.setSummary()

		self.doc.pageBreak()

		self.doc.Intro(cname,PManager,Author)
		self.doc.pageBreak()

		self.doc.Savereport()
class MyAddReceptWindow(QWidget):
    """
    Класс окна добавления пользовательских рецептов.
    Принимает от пользователя все нужные данные,
    форматирует их для корректной дальнейшей обработки
    и загружает в базу данных.
    """
    def __init__(self, parent):
        super().__init__(parent)

        self.setGeometry(0, 0, *constants.SCREEN_SIZE)
        self.setFixedSize(*constants.SCREEN_SIZE)

        background_label = QLabel(self)
        background_label.setPixmap(
            QPixmap(constants.ADD_RECEPT_WINDOW_BACKGROUND_IMAGE))
        background_label.resize(*constants.SCREEN_SIZE)

        self.initUI()

    def initUI(self):
        """
        Метод инициализации UI.
        Создает на виджете кнопки, выпадающий список, поля ввода и поля для отображения текста.
        """

        self.widgets = []

        self.recept_title = QLineEdit(self)
        self.recept_title.resize(int(self.width() * 0.8),
                                 int(self.height() * 0.05))
        self.recept_title.move(int(self.width() * 0.025),
                               int(self.height() * 0.025))
        self.recept_title.setPlaceholderText('Введите название рецепта')
        self.widgets.append(self.recept_title)

        self.recept_compexity = QComboBox(self)
        self.recept_compexity.addItems(['1', '2', '3', '4', '5'])
        self.recept_compexity.setCurrentIndex(0)
        self.recept_compexity.resize(int(self.width() * 0.125),
                                     int(self.height() * 0.05))
        self.recept_compexity.move(int(self.width() * 0.85),
                                   int(self.height() * 0.025))
        self.widgets.append(self.recept_compexity)

        self.recept_discriptoin = QPlainTextEdit(self)
        self.recept_discriptoin.resize(int(self.width() * 0.95),
                                       int(self.height() * 0.15))
        self.recept_discriptoin.move(int(self.width() * 0.025),
                                     int(self.height() * 0.1))
        self.recept_discriptoin.setPlaceholderText(
            'Введите краткое описание блюда')
        self.widgets.append(self.recept_discriptoin)

        self.recept_ingridients = QPlainTextEdit(self)
        self.recept_ingridients.resize(int(self.width() * 0.95),
                                       int(self.height() * 0.2625))
        self.recept_ingridients.move(int(self.width() * 0.025),
                                     int(self.height() * 0.275))
        self.recept_ingridients.setReadOnly(True)
        self.recept_ingridients.setPlaceholderText(
            'Здесь будут отображаться используемые ингредиенты')
        self.widgets.append(self.recept_ingridients)

        self.enter_ingridient = QLineEdit(self)
        self.enter_ingridient.resize(int(self.width() * 0.5),
                                     int(self.height() * 0.05))
        self.enter_ingridient.move(int(self.width() * 0.025),
                                   int(self.height() * 0.5625))
        self.enter_ingridient.setPlaceholderText(
            'Введите следующий ингредиент без массы')
        self.widgets.append(self.enter_ingridient)

        add_entered_ingridient_button = QPushButton('Добавить', self)
        add_entered_ingridient_button.resize(int(self.width() * 0.2),
                                             int(self.height() * 0.05))
        add_entered_ingridient_button.move(int(self.width() * 0.55),
                                           int(self.height() * 0.5625))
        add_entered_ingridient_button.clicked.connect(
            self.add_entered_ingridient)

        delete_last_ingridient_button = QPushButton('Удалить', self)
        delete_last_ingridient_button.resize(int(self.width() * 0.2),
                                             int(self.height() * 0.05))
        delete_last_ingridient_button.move(int(self.width() * 0.775),
                                           int(self.height() * 0.5625))
        delete_last_ingridient_button.clicked.connect(
            self.delete_last_ingridient)

        self.recept_steps = QPlainTextEdit(self)
        self.recept_steps.resize(int(self.width() * 0.95),
                                 int(self.height() * 0.2))
        self.recept_steps.move(int(self.width() * 0.025),
                               int(self.height() * 0.6375))
        self.recept_steps.setReadOnly(True)
        self.recept_steps.setPlaceholderText(
            'Здесь будут отображаться этапы приготовления')
        self.widgets.append(self.recept_steps)

        self.enter_step = QLineEdit(self)
        self.enter_step.resize(int(self.width() * 0.5),
                               int(self.height() * 0.05))
        self.enter_step.move(int(self.width() * 0.025),
                             int(self.height() * 0.8625))
        self.enter_step.setPlaceholderText(
            'Введите следующий этап приготовления')
        self.widgets.append(self.enter_step)

        add_entered_step_button = QPushButton('Добавить', self)
        add_entered_step_button.resize(int(self.width() * 0.2),
                                       int(self.height() * 0.05))
        add_entered_step_button.move(int(self.width() * 0.55),
                                     int(self.height() * 0.8625))
        add_entered_step_button.clicked.connect(self.add_entered_step)

        delete_last_step_button = QPushButton('Удалить', self)
        delete_last_step_button.resize(int(self.width() * 0.2),
                                       int(self.height() * 0.05))
        delete_last_step_button.move(int(self.width() * 0.775),
                                     int(self.height() * 0.8625))
        delete_last_step_button.clicked.connect(self.delete_last_step)

        save_recept_button = QPushButton('Сохранить рецепт', self)
        save_recept_button.resize(int(self.width() * 0.30),
                                  int(self.height() * 0.05))
        save_recept_button.move(int(self.width() * 0.025),
                                int(self.height() * 0.925))
        save_recept_button.clicked.connect(self.save_recept)

        clear_form_button = QPushButton('Очистить форму', self)
        clear_form_button.resize(int(self.width() * 0.30),
                                 int(self.height() * 0.05))
        clear_form_button.move(int(self.width() * 0.35),
                               int(self.height() * 0.925))
        clear_form_button.clicked.connect(self.clear_form)

        return_to_menu_button = QPushButton('Вернуться в меню', self)
        return_to_menu_button.resize(int(self.width() * 0.30),
                                     int(self.height() * 0.05))
        return_to_menu_button.move(int(self.width() * 0.675),
                                   int(self.height() * 0.925))
        return_to_menu_button.clicked.connect(self.return_to_menu)

    def add_entered_ingridient(self):
        """
        Метод добавления ингридиента.
        Получает из QLineEdit строку и добавляет ее в соответствующее поле.
        """

        ingridient = self.enter_ingridient.text()
        if ingridient and ingridient != '\n':
            entered_ingridients = self.recept_ingridients.toPlainText().split(
                '\n')

            if entered_ingridients == ['']:
                entered_ingridients = []

            entered_ingridients.append(ingridient)
            self.recept_ingridients.setPlainText(
                '\n'.join(entered_ingridients))

        self.enter_ingridient.setText('')

    def delete_last_ingridient(self):
        """
        Метод удаления последнего ингредиента.
        Создает диалоговое окно подтверждения действия.
        При положительном ответе, удаляет последний добавленный ингредиент.
        """

        exit_message_box = MyExitMessageBox('add_recept_delete_last')
        user_answer = exit_message_box.exec()

        if user_answer == 1:
            return

        old_text = self.recept_ingridients.toPlainText()

        if old_text:
            self.recept_ingridients.setPlainText('\n'.join(
                old_text.split('\n')[:-1]))

    def add_entered_step(self):
        """
        Метод добавления этапа.
        Получает из QLineEdit строку и добавляет ее в соответствующее поле.
        """

        step = self.enter_step.text()

        if step:
            old_text = self.recept_steps.toPlainText().split('\n')
            if old_text in ([''], ['\n']):
                old_text = []
                last_number = 0
            else:
                last_number = int(old_text[-1].split('.')[0])
            old_text.append(str(last_number + 1) + '. ' + step)
            self.recept_steps.setPlainText('\n'.join(old_text))

        self.enter_step.setText('')

    def delete_last_step(self):
        """
        Метод удаления последнего этапа.
        Создает диалоговое окно подтверждения действия.
        При положительном ответе, удаляет последний добавленный этап.
        """

        exit_message_box = MyExitMessageBox('add_recept_delete_last')
        user_answer = exit_message_box.exec()

        if user_answer == 1:
            return

        old_text = self.recept_steps.toPlainText()

        if old_text:
            self.recept_steps.setPlainText('\n'.join(
                old_text.split('\n')[:-1]))

    def save_recept(self):
        """
        Метод сохранения рецепта в базу данных.
        Принимает из соответсвующих полей информацию и обрабатывает ее.
        Вызывает сообщение об ошибке, если не все поля заполнены.
        Делает к базе данных запрос о добавлении рецепта.
        Выводит сообщение об успехе.
        """

        title = self.recept_title.text().lower()
        complexity = int(self.recept_compexity.currentText())
        description = self.recept_discriptoin.toPlainText().lower()
        ingrigients = ';'.join(
            self.recept_ingridients.toPlainText().split('\n')).lower()
        recept = '&'.join(self.recept_steps.toPlainText().split('\n')).lower()

        if sum(
                map(lambda x: 1 if x else 0,
                    [title, complexity, description, ingrigients, recept
                     ])) != 5:
            QMessageBox.critical(self, 'Ошибка ', 'Вы заполнили не все поля',
                                 QMessageBox.Ok)
            return

        cur = self.parent().database_connection.cursor()
        cur.execute(
            f'INSERT INTO recepts(title, ingredients, description, recept, complexity) VALUES'
            f'("{title}", "{ingrigients}", "{description}", "{recept}", {complexity})'
        )
        self.parent().database_connection.commit()
        QMessageBox.information(self, 'Успех ', 'Рецепт успешно сохранен',
                                QMessageBox.Ok)

        self.clear_widgets()

        self.hide()
        self.parent().menu_window.show()

    def return_to_menu(self):
        """
        Метод возвращения в меню.
        """

        exit_message_box = MyExitMessageBox('add_recept_back_to_menu')
        user_answer = exit_message_box.exec()

        if user_answer == 1:
            return

        self.clear_widgets()

        self.hide()
        self.parent().menu_window.show()

    def clear_form(self):
        """
        Метод вызывает очистку всех полей формы
        при подтвреждении этого в диалоговом окне.
        """

        exit_message_box = MyExitMessageBox('add_recept_clean_form')
        user_answer = exit_message_box.exec()

        if user_answer == 1:
            return

        self.clear_widgets()

    def clear_widgets(self):
        """
        Метод непосредственно очищающих содержимое всех виджетов.
        """

        for widget in self.widgets:
            widget.clear()
        self.recept_compexity.addItems(['1', '2', '3', '4', '5'])
        self.recept_compexity.setCurrentIndex(0)
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self._Width = 475
        self._Height = 425
        global mainWinWidth
        global mainWinHeight
        self._X = int((mainWinWidth/2) - (self._Width/2))
        self._Y = int((mainWinHeight/2) - (self._Height/2))
        self._trainThread = trainThread()
        self._testThread = testThread()
        self.initUI()
    
    def initUI(self):
        self.setGeometry(self._X, self._Y, self._Width, self._Height)
        self.oldPos = self.pos()
        self.setFixedSize(self._Width, self._Height)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.setStyleSheet("QMainWindow{background-color: rgb(64, 64, 64); color: rgb(255, 255, 255);  border: 1px solid rgb(26, 26, 26);}")
        self.acceptDrops()

        self.title = QLabel(self)
        self.title.move(40, 3)
        self.title.setFixedWidth(200)
        self.title.setStyleSheet("QLabel {color: rgb(255, 255, 255); font-size: 9pt;}")
        self.title.setText("Smart Wardrobe")

        self.iconLabel = QLabel(self)
        self.displayIcon("app_icon.png")

        self.imgLabel = QLabel(self)

        x_pos = self._Width - 28
        y_pos = 8
        self.closeButton = QPushButton(self)
        self.closeButton.move(x_pos, y_pos)
        self.closeButton.resize(20, 20)
        self.closeButton.setStyleSheet("QPushButton {background-color: rgb(153, 0, 0); color: rgb(255, 255, 255); font-weight: bold;}")
        self.closeButton.setText("X")
        self.closeButton.clicked.connect(self.closeButtonClicked)

        x_pos -= 30
        self.minimizeButton = QPushButton(self)
        self.minimizeButton.move(x_pos, y_pos)
        self.minimizeButton.resize(20, 20)
        self.minimizeButton.setStyleSheet("QPushButton {background-color: rgb(0, 0, 51); color: rgb(255, 255, 255); font-weight: bold;}")
        self.minimizeButton.setText("_")
        self.minimizeButton.clicked.connect(self.minimizeButtonClicked)

        x_pos = 15
        y_pos = 50

        self.trainButton = QPushButton(self)
        self.trainButton.move(x_pos, y_pos)
        self.trainButton.resize(115, 30)
        self.trainButton.setStyleSheet("QPushButton {background-color: rgb(77, 0, 25); color: rgb(255, 255, 255);}")
        self.trainButton.setText("Train Model")
        self.trainButton.clicked.connect(self.trainButtonClicked)

        self.testButton = QPushButton(self)
        self.testButton.move(x_pos + 125, y_pos)
        self.testButton.resize(115, 30)
        self.testButton.setStyleSheet("QPushButton {background-color: rgb(77, 0, 25); color: rgb(255, 255, 255);}")
        self.testButton.setText("Test Model")
        self.testButton.clicked.connect(self.testButtonClicked)
        
        self._trainThread.trainDone.connect(self.trainComplete)
        self._testThread.testDone.connect(self.testComplete)

        y_pos += 40
        self.imgFileDialog = QPushButton(self)
        self.imgFileDialog.move(x_pos, y_pos)
        self.imgFileDialog.resize(30, 30)
        self.imgFileDialog.setStyleSheet("QPushButton {background-color: rgb(77, 0, 25); color: rgb(255, 255, 255);}")
        self.imgFileDialog.setIcon(QIcon("folder_icon.png"))
        self.imgFileDialog.setIconSize(QtCore.QSize(25, 25))
        self.imgFileDialog.clicked.connect(self.imgFileDialogClicked)

        self.imgFileComboBox = QComboBox(self)
        self.imgFileComboBox.move(x_pos + 40, y_pos + 2)
        self.imgFileComboBox.resize(200, 25)
        self.imgFileComboBox.setStyleSheet("QComboBox {background-color: rgb(30, 30, 30); color: rgb(255, 255, 255);}")
        self.imgFileComboBox.currentTextChanged.connect(self.imgFileChanged)

        y_pos +=30
        self.optimizerLabel = QLabel(self)
        self.optimizerLabel.move(x_pos, y_pos)
        self.optimizerLabel.setStyleSheet("QLabel {color: rgb(255, 255, 255);}")
        self.optimizerLabel.setText("Optimizer")

        y_pos += 27
        self.optimizerComboBox = QComboBox(self)
        self.optimizerComboBox.move(x_pos, y_pos)
        self.optimizerComboBox.resize(240, 25)
        self.optimizerComboBox.setStyleSheet("QComboBox {background-color: rgb(30, 30, 30); color: rgb(255, 255, 255);}")
        self.optimizerComboBox.addItems([
            "SGD",
            "RMSprop",
            "Adagrad",
            "Adadelta",
            "Adam",
            "Adamax",
            "Nadam"
        ])
        self.optimizerComboBox.setCurrentIndex(0)
        self.optimizerComboBox.currentIndexChanged.connect(self.optimzerChanged)

        y_pos +=25
        self.lossFunctionLabel = QLabel(self)
        self.lossFunctionLabel.move(x_pos, y_pos)
        self.lossFunctionLabel.setStyleSheet("QLabel {color: rgb(255, 255, 255);}")
        self.lossFunctionLabel.setText("Loss Function")

        y_pos += 27
        self.lossFunctionComboBox = QComboBox(self)
        self.lossFunctionComboBox.move(x_pos, y_pos)
        self.lossFunctionComboBox.resize(240, 25)
        self.lossFunctionComboBox.setStyleSheet("QComboBox {background-color: rgb(30, 30, 30); color: rgb(255, 255, 255);}")
        self.lossFunctionComboBox.addItems([
            "mean_squared_error",
            "mean_absolute_error",
            "mean_absolute_percentage_error",
            "mean_squared_logarithmic_error",
            "squared_hinge",
            "hinge",
            "categorical_hinge",
            "logcosh",
            "huber_loss",
            "categorical_crossentropy",
            "sparse_categorical_crossentropy",
            "binary_crossentropy",
            "kullback_leibler_divergence",
            "poisson",
            "cosine_proximity",
        ])
        self.lossFunctionComboBox.setCurrentIndex(10)
        self.lossFunctionComboBox.currentIndexChanged.connect(self.lossFunctionChanged)

        x_pos = 15
        y_pos = 240
        self.console = QTextEdit(self)
        self.console.move(x_pos, y_pos)
        self.console.resize(440, 170)
        self.console.setStyleSheet("QTextEdit {background-color: rgb(4, 4, 4); color: rgb(255, 255, 255); font: 8pt Courier;}")
        self.console.setReadOnly(True)
        self.console.setText("Smart Wardrobe (GUI) 1.0")

        self.show()
    
    def closeButtonClicked(self):
        self.close()
    
    def minimizeButtonClicked(self):
        self.showMinimized()

    def trainButtonClicked(self):
        global trainBusy
        global testBusy
        if trainBusy or testBusy:
            self.console.append("Please wait while the current process completes")
        else:
            self.console.append("Training model ...")
            self._trainThread.start()
    
    def trainComplete(self):
        global accuracyData
        plt.figure()
        plt.style.use("ggplot")
        plt.ylim(0, 1)
        x = ["epoch " + str(i + 1) for i in range(len(accuracyData))]
        x_pos = [i for i, _ in enumerate(x)]
        colorData = [((255 - (colorMappingFunction(accuracyData[i]) * 102))/255, (51 + (colorMappingFunction(accuracyData[i]) * 204))/255, (colorMappingFunction(accuracyData[i]) * 51)/255) for i in range(len(accuracyData))]
        plt.bar(x_pos, accuracyData, color = colorData)
        plt.xlabel("Epoch")
        plt.ylabel("Accuracy")
        plt.xticks(x_pos, x)
        plt.show()
        self.console.append("Training completed")
    
    def testButtonClicked(self):
        global trainBusy
        global testBusy
        global imgPrediction
        if trainBusy or testBusy:
            self.console.append("Please wait while the current process completes")
        elif self.imgFileComboBox.currentText() == "":
            self.console.append("Please select an image")
        else:
            self.console.append("Testing model ...")
            self._testThread.start()
    
    def testComplete(self):
        self.console.append("\nImage: " + str(self.imgFileComboBox.currentText()) + "\nObject: " + str(imgPrediction))
    
    def imgFileDialogClicked(self):
        fileName = QFileDialog.getOpenFileName(self, "Open Image", "img", "Image Files (*.png *.jpg *.bmp)")
        if fileName[0] != "":
            self.imgFileComboBox.addItem(fileName[0])
            self.imgFileComboBox.setCurrentIndex(self.imgFileComboBox.count() - 1)
    
    def imgFileChanged(self):
        global imgFile
        imgFile = self.imgFileComboBox.currentText()
        self.displayImage(imgFile)
    
    def optimzerChanged(self):
        global optimizer
        optimizer = self.optimizerComboBox.currentText()
    
    def lossFunctionChanged(self):
        global lossFunction
        lossFunction = self.lossFunctionComboBox.currentText()
    
    def displayIcon(self, filePath):
        self.iconLabel.setPixmap(QPixmap(filePath).scaled(34, 34, QtCore.Qt.KeepAspectRatio, QtCore.Qt.FastTransformation))
        self.iconLabel.resize(34, 34)
        self.iconLabel.move(5, 1)
    
    def displayImage(self, filePath):
        img = PIL.Image.open(filePath)
        imgWidth, imgHeight = img.size
        cropArea = (0, 0, imgWidth, imgHeight)
        if imgWidth > imgHeight:
            cropArea = ((imgWidth/2) - (imgHeight/2), 0, (imgWidth/2) + (imgHeight/2), imgHeight)
        elif imgWidth < imgHeight:
            cropArea = (0, (imgHeight/2) - (imgWidth/2), imgWidth, (imgHeight/2) + (imgWidth/2))
        img = img.crop(cropArea)
        img = img.resize((28, 28), Image.ANTIALIAS)

        img = ImageQt(img)
        self.imgLabel.setPixmap(QPixmap.fromImage(img).scaled(175, 175, QtCore.Qt.KeepAspectRatio, QtCore.Qt.FastTransformation))
        self.imgLabel.resize(175, 175)
        self.imgLabel.move(277, 47)
    
    def mousePressEvent(self, event):
        self.oldPos = event.globalPos()
    
    def mouseMoveEvent(self, event):
        delta = QPoint(event.globalPos() - self.oldPos)
        if QCursor().pos().x() < self.x() + self._Width - 60 and QCursor().pos().y() < self.y() + 30:
            self.move(self._X + delta.x(), self._Y + delta.y())
            self._X = self.x()
            self._Y = self.y()
            self.oldPos = event.globalPos()
    
    def paintEvent(self, event):
        self.painter = QPainter(self)
        
        tempColor = QColor(26, 26, 26)

        self.painter.setPen(QPen(tempColor, 8, QtCore.Qt.SolidLine))
        self.painter.setBrush(QBrush(tempColor, QtCore.Qt.SolidPattern))
        self.painter.drawRect(0, 0, self._Width, 30)

        self.painter.setPen(QPen(tempColor, 3, QtCore.Qt.DashLine))
        self.painter.setBrush(QBrush(tempColor, QtCore.Qt.NoBrush))
        self.painter.drawRoundedRect(275, 45, 179, 179, 5, 5)

        self.painter.end()
    
    def consoleWrite(self, text):
        self.console.append(text)
Beispiel #25
0
    class preferences(QWidget):
        def __init__(self, scale_factor):
            try:
                super().__init__()
            except TypeError:
                super(self.__class__, self).__init__()  # port to python2

            self.scale_factor = scale_factor
            self.config = ConfigParser.RawConfigParser()
            self.configurations = config_manager()
            self.configf = self.configurations.configf
            if os.path.exists(self.configf) is False:
                print('Config file does not exist!')
                self.configurations.config_defaults()
            self.read_defaults()
            self.initUI()

        def initUI(self):
            self.backend()
            self.codec()
            self.bitrate()
            self.samplerates()
            self.iconcolors()
            self.notifications()
            self.searchatlaunch()
            if platform == 'Linux':
                self.alsadevice()
            self.buttons()
            self.window()

        def backend(self):
            """
            Backend
            """
            backends_supported = [
                'node', 'ffmpeg', 'avconv', 'parec', 'gstreamer'
            ]
            self.backends = []
            if platform == 'Darwin':
                for item in backends_supported:
                    if (is_installed(item, PATH, debug) is True
                            and item != 'avconv' and item != 'gstreamer'):
                        self.backends.append(item)
            else:
                for item in backends_supported:
                    if (is_installed(item, PATH, debug) is True
                            and item != 'node' and item != 'gstreamer'):
                        self.backends.append(item)
                    # hardcoded gst-launch-1.0 for gstreamer
                    elif (is_installed('gst-launch-1.0', PATH, debug) is True
                          and item == 'gstreamer'):
                        self.backends.append(item)
            try:
                backend_index = self.backends.index(self.backend_conf)
            except ValueError:
                # No backend found
                backend_index = None
                pass
            self.backend = QLabel('Select Backend', self)
            self.backend.move(20 * self.scale_factor, 24 * self.scale_factor)
            self.qcbackend = QComboBox(self)
            self.qcbackend.move(180 * self.scale_factor,
                                20 * self.scale_factor)
            self.qcbackend.setMinimumContentsLength(7)
            for item in self.backends:
                self.qcbackend.addItem(item)

            if backend_index:
                self.qcbackend.setCurrentIndex(backend_index)

            self.qcbackend.activated[str].connect(self.onActivatedbk)

        def codec(self):
            """
            Codec
            """
            self.codec = QLabel('Audio Coding Format', self)
            self.codec.move(20 * self.scale_factor, 56 * self.scale_factor)
            self.qccodec = QComboBox(self)
            self.qccodec.clear()
            if self.backend_conf == 'node':
                self.codecs = ['mp3']
            else:
                self.codecs = ['mp3', 'ogg', 'aac', 'wav', 'flac']
            if debug is True:
                print(self.codecs)
            codecindex = self.codecs.index(self.codecconf)
            self.qccodec.move(180 * self.scale_factor, 54 * self.scale_factor)
            self.qccodec.setMinimumContentsLength(7)
            for item in self.codecs:
                self.qccodec.addItem(item)
            self.qccodec.setCurrentIndex(codecindex)
            self.qccodec.activated[str].connect(self.onActivatedcc)

        def bitrate(self):
            """
            Bitrate
            """
            self.bitrate = QLabel('Select Bitrate (kbit/s)', self)
            self.bitrate.move(20 * self.scale_factor, 88 * self.scale_factor)
            self.qcbitrate = QComboBox(self)
            self.qcbitrate.clear()
            self.qcbitrate.move(180 * self.scale_factor,
                                88 * self.scale_factor)
            self.qcbitrate.setMinimumContentsLength(7)
            if self.codecconf == 'wav':
                self.bitrates = ['None']
                bitrateindex = 0
            else:
                self.bitrates = [
                    '128', '160', '192', '224', '256', '320', '500'
                ]
                bitrateindex = self.bitrates.index(self.bitrateconf)
            for item in self.bitrates:
                self.qcbitrate.addItem(item)
            self.qcbitrate.setCurrentIndex(bitrateindex)
            self.qcbitrate.activated[str].connect(self.onActivatedbt)

        def samplerates(self):
            """
            Sample rate
            """
            self.samplerates = [
                '192000', '176400', '96000', '88200', '48000', '44100',
                '32000', '22050'
            ]
            sampleratesindex = self.samplerates.index(self.samplerateconf)
            self.samplerate = QLabel('Sample Rate (Hz)', self)
            self.samplerate.move(20 * self.scale_factor,
                                 120 * self.scale_factor)
            self.qcsamplerate = QComboBox(self)
            self.qcsamplerate.move(180 * self.scale_factor,
                                   120 * self.scale_factor)
            self.qcsamplerate.setMinimumContentsLength(7)
            for item in self.samplerates:
                self.qcsamplerate.addItem(item)
            self.qcsamplerate.setCurrentIndex(sampleratesindex)
            self.qcsamplerate.activated[str].connect(self.onActivatedsr)

        def iconcolors(self):
            """
            Icon colors
            """
            self.colors_list = ['black', 'blue', 'white']
            colorsindex = self.colors_list.index(self.searchcolorsconf)
            self.colors = QLabel('Icon Colors', self)
            self.colors.move(20 * self.scale_factor, 152 * self.scale_factor)
            self.qccolors = QComboBox(self)
            self.qccolors.move(180 * self.scale_factor,
                               152 * self.scale_factor)
            self.qccolors.setMinimumContentsLength(7)
            for item in self.colors_list:
                self.qccolors.addItem(item)
            self.qccolors.setCurrentIndex(colorsindex)
            self.qccolors.activated[str].connect(self.onActivatedcolors)

        def notifications(self):
            """
            Notifications
            """
            self.notifications_list = ['enabled', 'disabled']
            notindex = self.notifications_list.index(self.notifconf)
            self.notifications = QLabel('Notifications', self)
            self.notifications.move(20 * self.scale_factor,
                                    184 * self.scale_factor)
            self.qcnotifications = QComboBox(self)
            self.qcnotifications.move(180 * self.scale_factor,
                                      184 * self.scale_factor)
            self.qcnotifications.setMinimumContentsLength(7)
            for item in self.notifications_list:
                self.qcnotifications.addItem(item)
            self.qcnotifications.setCurrentIndex(notindex)
            self.qcnotifications.activated[str].connect(self.onActivatednotify)

        def searchatlaunch(self):
            """
            Search at launch
            """
            self.atlaunch_list = ['enabled', 'disabled']
            launchindex = self.atlaunch_list.index(self.satlaunchconf)
            self.atlaunch = QLabel('Search At Launch', self)
            self.atlaunch.move(20 * self.scale_factor, 214 * self.scale_factor)
            self.qcatlaunch = QComboBox(self)
            self.qcatlaunch.move(180 * self.scale_factor,
                                 214 * self.scale_factor)
            self.qcatlaunch.setMinimumContentsLength(7)
            for item in self.atlaunch_list:
                self.qcatlaunch.addItem(item)
            self.qcatlaunch.setCurrentIndex(launchindex)
            self.qcatlaunch.activated[str].connect(self.onActivatedatlaunch)

        def alsadevice(self):
            """
            Set the ALSA Device
            """
            self.alsadevice = QLabel('ALSA Device', self)
            self.alsadevice.move(20 * self.scale_factor,
                                 244 * self.scale_factor)
            self.qle = QLineEdit(self)
            self.qle.move(179 * self.scale_factor, 244 * self.scale_factor)
            self.qle.setFixedWidth(84 * self.scale_factor)
            self.read_defaults()
            if self.alsadeviceconf is not None:
                self.qle.setText(self.alsadeviceconf)
            self.qle.textChanged[str].connect(self.onActivatedalsadevice)

        def buttons(self):
            """
            Buttons
            """
            resetbtn = QPushButton("Reset Settings", self)
            resetbtn.move(10 * self.scale_factor, 274 * self.scale_factor)
            resetbtn.clicked.connect(self.reset_configuration)

            faqbtn = QPushButton("FAQ", self)
            faqbtn.move(138 * self.scale_factor, 274 * self.scale_factor)
            faqbtn.clicked.connect(lambda: webbrowser.open(
                'https://github.com/muammar/mkchromecast/wiki/FAQ'))

            donbtn = QPushButton("Donate :)", self)
            donbtn.move(204 * self.scale_factor, 274 * self.scale_factor)
            donbtn.clicked.connect(lambda: webbrowser.open(
                'https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=RZLF7TDCAXT9Q&lc=US&item_name=mkchromecast&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted'
            ))

        def window(self):
            """
            Geometry and window's title
            """
            self.setGeometry(300 * self.scale_factor, 300 * self.scale_factor,
                             300 * self.scale_factor, 200 * self.scale_factor)
            if platform == 'Darwin':
                # This is to fix the size of the window
                self.setFixedSize(310 * self.scale_factor,
                                  320 * self.scale_factor)
            else:
                # This is to fix the size of the window
                self.setFixedSize(282 * self.scale_factor,
                                  320 * self.scale_factor)
            self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint
                                | QtCore.Qt.WindowMinimizeButtonHint
                                | QtCore.Qt.WindowStaysOnTopHint)
            self.setWindowTitle('Mkchromecast Preferences')
            """
            Methods
            """

        def reset_configuration(self):
            self.configurations.write_defaults()
            self.reset_indexes()

        def reset_indexes(self):
            self.read_defaults()
            """
            Indexes of QCombo boxes are reset
            """
            backend_index = self.backends.index(self.backend_conf)
            codecindex = self.codecs.index(self.codecconf)
            self.bitrates = ['128', '160', '192', '224', '256', '320', '500']
            bitrateindex = self.bitrates.index(self.bitrateconf)
            self.qcbitrate.clear()
            for item in self.bitrates:
                self.qcbitrate.addItem(item)
            sampleratesindex = self.samplerates.index(self.samplerateconf)
            colorsindex = self.colors_list.index(self.searchcolorsconf)
            notindex = self.notifications_list.index(self.notifconf)
            launchindex = self.atlaunch_list.index(self.satlaunchconf)
            self.qcbackend.setCurrentIndex(backend_index)
            self.qccodec.setCurrentIndex(codecindex)
            self.qcbitrate.setCurrentIndex(bitrateindex)
            self.qcsamplerate.setCurrentIndex(sampleratesindex)
            self.qccolors.setCurrentIndex(colorsindex)
            self.qcnotifications.setCurrentIndex(notindex)
            self.qcatlaunch.setCurrentIndex(launchindex)

        def onActivatedbk(self, text):
            self.config.read(self.configf)
            self.config.set('settings', 'backend', text)
            self.write_config()
            self.read_defaults()
            self.qccodec.clear()
            if self.backend_conf == 'node':
                codecs = ['mp3']
                self.config.read(self.configf)
                self.config.set('settings', 'codec', 'mp3')
                self.write_config()
            else:
                codecs = ['mp3', 'ogg', 'aac', 'wav', 'flac']
            if debug is True:
                print('Codecs: %s.' % codecs)
            codecindex = codecs.index(self.codecconf)
            self.qccodec.move(180 * self.scale_factor, 54 * self.scale_factor)
            self.qccodec.setMinimumContentsLength(7)
            for item in codecs:
                self.qccodec.addItem(item)
            self.qccodec.setCurrentIndex(codecindex)
            self.qccodec.activated[str].connect(self.onActivatedcc)

        def onActivatedcc(self, text):
            self.config.read(self.configf)
            self.config.set('settings', 'codec', text)
            self.write_config()
            self.read_defaults()
            self.qcbitrate.clear()
            if self.codecconf == 'wav':
                bitrates = ['None']
                bitrateindex = 0
            else:
                self.configurations.chk_config()
                self.read_defaults()
                bitrates = ['128', '160', '192', '224', '256', '320', '500']
                bitrateindex = bitrates.index(self.bitrateconf)
            self.qcbitrate.move(180 * self.scale_factor,
                                88 * self.scale_factor)
            for item in bitrates:
                self.qcbitrate.addItem(item)
            self.qcbitrate.setCurrentIndex(bitrateindex)
            self.qcbitrate.activated[str].connect(self.onActivatedbt)

        def onActivatedbt(self, text):
            self.config.read(self.configf)
            self.config.set('settings', 'bitrate', text)
            self.write_config()
            self.read_defaults()

        def onActivatedsr(self, text):
            self.config.read(self.configf)
            self.config.set('settings', 'samplerate', text)
            self.write_config()
            self.read_defaults()

        def onActivatednotify(self, text):
            self.config.read(self.configf)
            self.config.set('settings', 'notifications', text)
            self.write_config()
            self.read_defaults()

        def onActivatedcolors(self, text):
            self.config.read(self.configf)
            self.config.set('settings', 'colors', text)
            self.write_config()
            self.read_defaults()

        def onActivatedatlaunch(self, text):
            self.config.read(self.configf)
            self.config.set('settings', 'searchatlaunch', text)
            self.write_config()
            self.read_defaults()

        def onActivatedalsadevice(self, text):
            self.config.read(self.configf)
            if not text:
                self.config.set('settings', 'alsadevice', None)
            else:
                self.config.set('settings', 'alsadevice', text)
            self.write_config()
            self.read_defaults()

        def read_defaults(self):
            self.backend_conf = ConfigSectionMap('settings')['backend']
            self.codecconf = ConfigSectionMap('settings')['codec']
            if self.backend_conf == 'node' and self.codecconf != 'mp3':
                self.config.read(self.configf)
                self.config.set('settings', 'codec', 'mp3')
                self.write_config()
                self.codecconf = ConfigSectionMap('settings')['codec']
            self.bitrateconf = ConfigSectionMap('settings')['bitrate']
            self.samplerateconf = ConfigSectionMap('settings')['samplerate']
            self.notifconf = ConfigSectionMap('settings')['notifications']
            self.searchcolorsconf = ConfigSectionMap('settings')['colors']
            self.satlaunchconf = ConfigSectionMap('settings')['searchatlaunch']
            self.alsadeviceconf = ConfigSectionMap('settings')['alsadevice']
            if debug is True:
                print(self.backend_conf, self.codecconf, self.bitrateconf,
                      self.samplerateconf, self.notifconf, self.satlaunchconf,
                      self.searchcolorsconf, self.alsadeviceconf)

        def write_config(self):
            """This method writes to configfile"""
            with open(self.configf, 'w') as configfile:
                self.config.write(configfile)
Beispiel #26
0
class Widget(QWidget):
    def __init__(self):
        super().__init__()
        self.img = None
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Save as')
        self.setFixedSize(400, 100)

        self.textbox = QLineEdit(self)
        self.textbox.move(90, 20)
        self.textbox.resize(130, 22)

        self.label1 = QLabel('Name:', self)
        self.label1.move(20, 22)

        self.label2 = QLabel('Size:', self)
        self.label2.move(20, 70)

        self.combo = QComboBox(self)
        self.combo.move(90, 65)
        self.combo.addItem('')
        self.combo.addItem('')
        self.combo.addItem('')
        self.combo.addItem('')
        self.combo.addItem('')
        self.combo.addItem('')
        self.combo.setItemText(0, '720 x 480 px')
        self.combo.setItemText(1, '1280 x 720 px')
        self.combo.setItemText(2, '1920 x 1080 px')
        self.combo.setItemText(3, 'A5 (2551 x 1819 px)')
        self.combo.setItemText(4, 'A4 (3579 x 2551 px)')
        self.combo.setItemText(5, 'A3 (5031 x 3579 px)')

        self.button = QPushButton('Save', self)
        self.button.move(300, 20)
        self.button.clicked.connect(self.save)

        self.show()

    def get_size(self) -> tuple:
        id = self.combo.currentIndex()
        if id == 0:
            size = (720, 480)
        elif id == 1:
            size = (1280, 720)
        elif id == 2:
            size = (1920, 1080)
        elif id == 3:
            size = (2551, 1819)
        elif id == 4:
            size = (3579, 2551)
        elif id == 5:
            size = (5031, 3579)
        return size

    def get_mosaic_img(self, mosaic):
        self.img = mosaic

    def save(self):
        name_to_save = self.textbox.text() + '.jpg'
        size_to_save = self.get_size()
        self.img = self.img.resize(size_to_save)
        self.img.save(name_to_save, 'JPEG')
        self.close()
Beispiel #27
0
class futureWindow(QWidget):
    def __init__(self, parent=None):
        super(futureWindow, self).__init__(parent)
        self.setFixedSize(800, 600)
        self.setWindowTitle('股票清單')
        self.lbl = QLabel("txf")
        self.stockcombo = QComboBox(self)

        self.start = QLabel("起始", self)
        self.end = QLabel("結束", self)
        self.k = QLabel("K線週期", self)
        self.year = QComboBox(self)
        self.month = QComboBox(self)
        self.day = QComboBox(self)
        self.year2 = QComboBox(self)
        self.month2 = QComboBox(self)
        self.day2 = QComboBox(self)
        self.Tcount = QComboBox(self)

        self.stockcombo.addItem("台指期")
        self.stockcombo.addItem("金指期")

        self.year.addItems([str(x) for x in range(1998, 2018)])
        self.month.addItems([str(y) for y in range(1, 13)])
        self.day.addItems([str(z) for z in range(1, 32)])
        self.year2.addItems([str(a) for a in range(1998, 2018)])
        self.month2.addItems([str(b) for b in range(1, 13)])
        self.day2.addItems([str(c) for c in range(1, 32)])

        self.Tcount.addItem("1 日")
        self.Tcount.addItem("10 日")
        self.Tcount.addItem("1 月")

        self.stockcombo.move(200, 100)
        self.lbl.move(200, 150)

        self.start.move(100, 250)
        self.year.move(150, 250)
        self.month.move(250, 250)
        self.day.move(350, 250)

        self.end.move(100, 300)
        self.year2.move(150, 300)
        self.month2.move(250, 300)
        self.day2.move(350, 300)

        self.k.move(100, 375)
        self.Tcount.move(200, 375)

        self.stockcombo.activated[str].connect(self.onActivated)

        subbutton = QPushButton('確認', self)
        subbutton.move(400, 500)

        self.num = ""

        #subbutton.clicked.connect(lambda:self.kline(num))
        subbutton.clicked.connect(self.tt)
        subbutton.clicked.connect(self.close)

    def tt(self):
        self.num = str(self.stockcombo.currentText())
        print("stockcombo is " + self.num)

        self.a = str(self.year.currentText()) + "-" + str(
            self.month.currentText()) + "-" + str(self.day.currentText())
        self.b = str(self.year2.currentText()) + "-" + str(
            self.month2.currentText()) + "-" + str(self.day2.currentText())
        if self.Tcount.currentText() == "1 日":
            self.tc = 1
        elif self.Tcount.currentText() == "10 日":
            self.tc = 10
        else:
            self.tc = 30
        #print(self.a)
        #print(self.b)

        self.kline(self.num, self.a, self.b, self.tc)

    def main():
        app = QApplication(sys.argv)
        mainwindow = MainWindow()
        mainwindow.show()

    def onActivated(self, text):

        self.lbl.setText(text)
        self.lbl.adjustSize()

    def kline(self, num, a, b, tc):

        self.graphicview = QtWidgets.QGraphicsView()  # 第一步,创建一个QGraphicsView
        self.graphicview.setObjectName("graphicview")

        dr = Figure_Canvas()
        #实例化一个FigureCanvas
        dr.test(num, a, b, tc)  # 画图
        graphicscene = QtWidgets.QGraphicsScene(
        )  # 第三步,创建一个QGraphicsScene,因为加载的图形(FigureCanvas)不能直接放到graphicview控件中,必须先放到graphicScene,然后再把graphicscene放到graphicview中
        graphicscene.addWidget(
            dr)  # 第四步,把图形放到QGraphicsScene中,注意:图形是作为一个QWidget放到QGraphicsScene中的
        self.graphicview.setScene(graphicscene)
        self.graphicview.show()  # 最后,调用show方法呈现图形!Voila!!
        #self.setCentralWidget(self.graphicview)
        self.graphicview.resize(1100, 500)
Beispiel #28
0
class SideFrame(QFrame):
    def __init__(self, parent, **args):
        super().__init__(parent)

        self.unit = units.Arbalests()
        self.terrain = terrains.Bridge()
        self.parent = parent
        self.name = args["name"]

        self.unit_construct()
        self.unit_set()

        self.terrain_construct()
        self.terrain_set()

    def unit_construct(self):
        self.UnitComboBox = QComboBox(self)
        QLabel(self.name, self).move(300, 35)
        self.UnitComboBox.addItems(self.parent.unit_list)
        self.UnitComboBox.activated[str].connect(self.unit_selected)
        self.UnitComboBox.move(395, 35)

        QLabel("Health", self).move(25, 100)
        self.health = QLineEdit(self)
        self.health.move(150, 100)
        self.health.textEdited.connect(
            lambda text: self.unit.set("health", int(text))
            if text.isdigit() else self.unit.set("health", 100))

        QLabel("Attack", self).move(25, 150)
        self.attack = QLineEdit(self)
        self.attack.move(150, 150)
        self.attack.textEdited.connect(
            lambda text: self.unit.set("attack", int(text))
            if text.isdigit() else self.unit.set("attack", 50))

        self.atk_upgrade = QCheckBox("Upgraded?", self)
        self.atk_upgrade.move(150, 185)
        self.atk_upgrade.stateChanged.connect(
            lambda state: self.unit.set("atk_upgrade", state == Qt.Checked))

        QLabel("Defense", self).move(25, 250)
        self.defense = QLineEdit(self)
        self.defense.move(150, 250)
        self.defense.textEdited.connect(
            lambda text: self.unit.set("defense", int(text))
            if text.isdigit() else self.unit.set("defense", 50))

        self.def_upgrade = QCheckBox("Upgraded?", self)
        self.def_upgrade.move(150, 285)
        self.def_upgrade.stateChanged.connect(
            lambda state: self.unit.set("def_upgrade", state == Qt.Checked))

        QLabel("Range", self).move(25, 350)
        self.range = QLineEdit(self)
        self.range.move(150, 350)
        self.range.textEdited.connect(
            lambda text: self.unit.set("range", int(text))
            if text.isdigit() else self.unit.set("range", 1))

        QLabel("Vision", self).move(450, 100)
        self.vision = QLineEdit(self)
        self.vision.move(575, 100)
        self.vision.textEdited.connect(
            lambda text: self.unit.set("vision", int(text))
            if text.isdigit() else self.unit.set("vision", 7))

        QLabel("Movement", self).move(450, 150)
        self.movement = QLineEdit(self)
        self.movement.move(575, 150)
        self.movement.textEdited.connect(
            lambda text: self.unit.set("movement", int(text))
            if text.isdigit() else self.unit.set("movement", 7))

        QLabel("Type", self).move(450, 200)
        self.type = QComboBox(self)
        self.type.addItems(self.parent.types)
        self.type.move(575, 200)
        self.type.activated[str].connect(
            lambda text: self.unit.set("type", objects.UnitType[text]))

        QLabel("Battles", self).move(450, 250)
        self.battles = QLineEdit(self)
        self.battles.move(575, 250)
        self.battles.textEdited.connect(
            lambda text: self.unit.set("battles", int(text))
            if text.isdigit() else self.unit.set("battles", 0))

        QLabel("Name", self).move(850, 100)
        self.c_name = QLineEdit(self)
        self.c_name.move(975, 100)
        self.c_name.textEdited.connect(
            lambda text: self.unit.set("name", text)
            if text.isalpha() else self.unit.set("name", self.unit.name))

        self.c_save = QPushButton("Save Unit", self)
        self.c_save.resize(self.c_save.sizeHint())
        self.c_save.move(1250, 100)
        self.c_save.clicked.connect(self.save_unit)

        self.unit_deleter = QPushButton("Delete Unit", self)
        self.unit_deleter.resize(self.unit_deleter.sizeHint())
        self.unit_deleter.move(1250, 150)
        self.unit_deleter.hide()
        self.unit_deleter.clicked.connect(self.remove_unit)

        self.abilities_btn = QPushButton("Ability Picker", self)
        self.abilities_btn.resize(self.abilities_btn.sizeHint())
        self.abilities_btn.move(1350, 350)
        self.abilities_btn.clicked.connect(self.init_picker)

    def unit_set(self):
        self.health.setText(str(self.unit.health))
        self.attack.setText(str(self.unit.attack))
        self.defense.setText(str(self.unit.defense))
        self.range.setText(str(self.unit.range))
        self.battles.setText(str(self.unit.battles))
        self.vision.setText(str(self.unit.vision))
        self.movement.setText(str(self.unit.movement))
        self.type.setCurrentIndex(self.parent.types.index(self.unit.type.name))
        self.atk_upgrade.setChecked(self.unit.atk_upgrade)
        self.def_upgrade.setChecked(self.unit.def_upgrade)
        self.c_name.setText(self.unit.name)
        if self.unit.name in self.parent.custom_units:
            self.unit_deleter.show()
        else:
            self.unit_deleter.hide()

    def init_picker(self):
        ability_picker = AbilityPicker(self)
        ability_picker.resize(800, 600)
        ability_picker.show()

    def terrain_construct(self):
        self.TerrainComboBox = QComboBox(self)
        QLabel("Terrain", self).move(300, 435)
        self.TerrainComboBox.addItems(self.parent.terrain_list)
        self.TerrainComboBox.activated[str].connect(self.terrain_selected)
        self.TerrainComboBox.move(400, 435)

        QLabel("Defense+", self).move(25, 500)
        self.tdefense = QLineEdit(self)
        self.tdefense.move(150, 500)
        self.tdefense.textEdited.connect(
            lambda text: self.terrain.set("def_bonus",
                                          float(text) / 100) if text.isdigit()
            else self.terrain.set("def_bonus", self.terrain.def_bonus))

        QLabel("Range+", self).move(25, 550)
        self.trange = QLineEdit(self)
        self.trange.move(150, 550)
        self.trange.textEdited.connect(lambda text: self.terrain.set(
            "rng_bonus", int(text)) if text.isdigit() else self.terrain.set(
                "rng_bonus", self.terrain.rng_bonus))

        QLabel("Vision+", self).move(25, 600)
        self.tvision = QLineEdit(self)
        self.tvision.move(150, 600)
        self.tvision.textEdited.connect(lambda text: self.terrain.set(
            "vis_bonus", int(text)) if text.isdigit() else self.terrain.set(
                "vis_bonus", self.terrain.vis_bonus))

        QLabel("Type", self).move(25, 650)
        self.ttype = QComboBox(self)
        self.ttype.addItems(self.parent.ttypes)
        self.ttype.move(150, 650)
        self.ttype.activated[str].connect(
            lambda text: self.terrain.set("type", objects.TerrainType[text]))

        QLabel("Movement", self).move(450, 500)
        self.tmovement = QLineEdit(self)
        self.tmovement.move(575, 500)
        self.tmovement.textEdited.connect(
            lambda text: self.terrain.set("mov_cost", int(text)) if text.
            isdigit() else self.terrain.set("mov_cost", self.terrain.mov_cost))

        QLabel("Vision", self).move(450, 550)
        self.tvis = QLineEdit(self)
        self.tvis.move(575, 550)
        self.tvis.textEdited.connect(
            lambda text: self.terrain.set("vis_cost", int(text)) if text.
            isdigit() else self.terrain.set("vis_cost", self.terrain.vis_cost))

        QLabel("Road?", self).move(450, 600)
        self.tsubtype = QCheckBox("", self)
        self.tsubtype.move(575, 600)
        self.tsubtype.stateChanged.connect(
            lambda state: self.terrain.set("sub_type", objects.TerrainSubType.
                                           road) if state == Qt.Checked else
            self.terrain.set("sub_type", objects.TerrainSubType.normal))

        QLabel("Name", self).move(850, 500)
        self.c_tname = QLineEdit(self)
        self.c_tname.move(975, 500)
        self.c_tname.textEdited.connect(
            lambda text: self.terrain.set("name", text)
            if text.isalpha() else self.terrain.set("name", self.terrain.name))

        self.c_tsave = QPushButton("Save Terrain", self)
        self.c_tsave.resize(self.c_save.sizeHint())
        self.c_tsave.move(1250, 500)
        self.c_tsave.clicked.connect(self.save_terrain)

        self.terrain_deleter = QPushButton("Delete Terrain", self)
        self.terrain_deleter.resize(self.terrain_deleter.sizeHint())
        self.terrain_deleter.move(1250, 550)
        self.terrain_deleter.hide()
        self.terrain_deleter.clicked.connect(self.remove_terrain)

    def terrain_set(self):
        self.tdefense.setText(str(self.terrain.def_bonus * 100))
        self.trange.setText(str(self.terrain.rng_bonus))
        self.tvision.setText(str(self.terrain.vis_bonus))
        self.tmovement.setText(str(self.terrain.mov_cost))
        self.tvis.setText(str(self.terrain.vis_cost))
        self.ttype.setCurrentIndex(
            self.parent.ttypes.index(self.terrain.type.name))
        self.tsubtype.setChecked(
            self.terrain.sub_type == objects.TerrainSubType.road)
        self.c_tname.setText(self.terrain.name)

        if self.unit.name in self.parent.custom_terrains:
            self.terrain_deleter.show()
        else:
            self.terrain_deleter.hide()

    def unit_selected(self, text):
        if text in dir(units):
            c = getattr(units, text)
            self.unit = c()
            self.unit_deleter.hide()
        elif text in self.parent.custom_units:
            u_dict = self.parent.custom_units[text].copy()
            u_dict["type"] = objects.UnitType[u_dict["type"]]
            self.unit = objects.Unit(**u_dict)
            self.unit.__class__.__name__ = self.unit.name
            self.unit_deleter.show()

        self.unit_set()

    def terrain_selected(self, text):
        if text in dir(terrains):
            c = getattr(terrains, text)
            self.terrain = c()
            self.terrain_deleter.hide()
        elif text in self.parent.custom_terrains:
            u_dict = self.parent.custom_terrains[text].copy()
            u_dict["type"] = objects.TerrainType[u_dict["type"]]
            u_dict["sub_type"] = objects.TerrainSubType[u_dict["sub_type"]]
            self.terrain = objects.Terrain(**u_dict)
            self.terrain.__class__.__name__ = self.terrain.name
            self.terrain_deleter.show()

        self.terrain_set()

    def save_unit(self):
        name = self.unit.name
        u_dict = self.unit.__dict__.copy()
        u_dict["type"] = u_dict["type"].name

        self.parent.custom_units[name] = u_dict
        self.parent.unit_list.append(name)
        self.UnitComboBox.addItem(name)
        self.UnitComboBox.setCurrentIndex(self.parent.unit_list.index(name))

        self.other.UnitComboBox.addItem(name)
        self.unit_deleter.show()

    def remove_unit(self):
        name = self.unit.name

        self.UnitComboBox.setCurrentIndex(0)
        self.UnitComboBox.removeItem(self.parent.unit_list.index(name))

        if self.other.unit.name == name:
            self.other.UnitComboBox.setCurrentIndex(0)
            self.other.UnitComboBox.removeItem(
                self.parent.unit_list.index(name))
            self.other.unit_selected("Arbalests")

        del self.parent.custom_units[name]
        self.parent.unit_list.remove(name)

        self.unit_selected("Arbalests")

    def save_terrain(self):
        name = self.terrain.name
        u_dict = self.terrain.__dict__.copy()
        u_dict["type"] = u_dict["type"].name
        u_dict["sub_type"] = u_dict["sub_type"].name

        self.parent.custom_terrains[name] = u_dict
        self.parent.terrain_list.append(name)
        self.TerrainComboBox.addItem(name)
        self.TerrainComboBox.setCurrentIndex(
            self.parent.terrain_list.index(name))

        self.other.TerrainComboBox.addItem(name)
        self.terrain_deleter.show()

    def remove_terrain(self):
        name = self.terrain.name

        self.TerrainComboBox.setCurrentIndex(0)
        self.TerrainComboBox.removeItem(self.parent.terrain_list.index(name))

        if self.other.terrain.name == name:
            self.other.TerrainComboBox.setCurrentIndex(0)
            self.other.TerrainComboBox.removeItem(
                self.parent.terrain_list.index(name))
            self.other.terrain_selected("Bridge")

        del self.parent.custom_terrains[name]
        self.parent.terrain_list.remove(name)

        self.terrain_selected("Bridge")
Beispiel #29
0
class SERIAL_UI(object):
    def __init__(self):
        super().__init__()
        self.resize(850, 600)
        self.center()

    def UI_init(self):
        lbl = QLabel("端口", self)
        lbl.move(20, 45)
        self.com = QComboBox(self)
        self.ComRelist()
        self.com.move(70, 45)
        self.com.resize(80, 25)

        self.RefreshCom = QPushButton("刷新串口", self)
        self.RefreshCom.move(30, 10)
        self.RefreshCom.resize(80, 25)

        lbl = QLabel("波特率", self)
        lbl.setFont(QFont("Microsoft YaHei"))
        lbl.move(20, 75)
        self.baudrate = QComboBox(self)
        self.baudrate.addItem("1200")
        self.baudrate.addItem("2400")
        self.baudrate.addItem("4800")
        self.baudrate.addItem("9600")
        self.baudrate.addItem("19200")
        self.baudrate.addItem("38400")
        self.baudrate.addItem("57600")
        self.baudrate.addItem("115200")
        self.baudrate.move(70, 75)
        self.baudrate.setCurrentIndex(3)  # 设置默认的下拉选项
        #		self.formLayout.setWidget(5, QtWidgets.QFormLayout.FieldRole, self.s1__box_5)
        self.baudrate.resize(80, 25)

        self.lbl = QLabel("校验位", self)
        self.lbl.move(20, 105)
        self.parity_bit = QComboBox(self)
        self.parity_bit.addItem("NONE")
        self.parity_bit.addItem("ODD")
        self.parity_bit.addItem("EVEN")
        self.parity_bit.move(70, 105)
        self.parity_bit.setCurrentIndex(2)
        self.parity_bit.resize(80, 25)

        lbl = QLabel("数据位", self)
        lbl.move(20, 135)
        self.data_bit = QComboBox(self)
        self.data_bit.addItem("5")
        self.data_bit.addItem("6")
        self.data_bit.addItem("7")
        self.data_bit.addItem("8")
        self.data_bit.move(70, 135)
        self.data_bit.setCurrentIndex(3)
        self.data_bit.resize(80, 25)

        lbl = QLabel("停止位", self)
        lbl.move(20, 165)
        self.stop_bit = QComboBox(self)
        self.stop_bit.addItem("1")
        self.stop_bit.addItem("2")
        self.stop_bit.move(70, 165)
        self.stop_bit.resize(80, 25)

        #		self.col = QColor(0, 0, 0)
        self.StartCom = QPushButton("打开串口", self)
        #		StartCom.setStyleSheet(''' text-align : center;
        #                                            background-color : NavajoWhite;
        #                                            height : 30px;
        #                                            border-style: outset;
        #                                           font : 13px  ''')

        self.StartCom.setCheckable(True)
        self.StartCom.move(40, 200)
        self.StartCom.resize(80, 30)

        #		self.square = QFrame(self)
        #		self.square.setGeometry(140, 245, 20, 20)
        #		self.square.setStyleSheet("QWidget { background-color:red}")

        self.OutputText = QTextEdit(self)
        self.OutputText.move(180, 20)
        self.OutputText.resize(650, 400)
        #		self.OutputText.setPlainText('Hello PyQt5!\n单击按钮')
        #		self.OutputText.append("close")
        self.InputText = QTextEdit(self)
        self.InputText.move(180, 470)
        self.InputText.resize(650, 60)

        self.HexSend = QCheckBox('Hex发送', self)
        self.HexSend.move(550, 540)
        self.HexSend.resize(100, 30)

        self.ClearSend = QPushButton("清发送区", self)
        self.ClearSend.move(650, 540)
        self.ClearSend.resize(80, 30)

        self.HexReceive = QCheckBox('Hex接收', self)
        self.HexReceive.move(550, 430)
        self.HexReceive.resize(100, 30)

        self.ClearReceive = QPushButton("清接收区", self)
        self.ClearReceive.move(650, 430)
        self.ClearReceive.resize(80, 30)

        self.TimerSendCheck = QCheckBox('定时发送', self)
        self.TimerSendCheck.move(350, 540)
        self.TimerSendCheck.resize(100, 30)
        self.TimerSendValue = QLineEdit(self)
        self.TimerSendValue.move(420, 540)
        self.TimerSendValue.resize(50, 30)
        self.TimerSendValue.setText("")
        lbl = QLabel("ms/次", self)
        lbl.move(470, 540)

        #		ClearReceive.setStyleSheet(''' text-align : center;
        #                                            background-color : NavajoWhite;
        #                                            height : 30px;
        #                                            border-style: outset;
        #                                           font : 13px  ''')
        self.InputSend = QPushButton("发送", self)
        self.InputSend.move(200, 540)
        self.InputSend.resize(80, 30)

        tmp = open('logo.png', 'wb')
        tmp.write(base64.b64decode(logo))
        tmp.close()

        self.statusBar()
        self.setWindowIcon(QIcon('logo.png'))
        self.setWindowTitle('Python串口调试助手     作者: 何苏平 QQ:398002463')
        self.show()

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def ComRelist(self):
        self.com.clear()
        for i in self.serial_list:
            self.com.addItem(i)
Beispiel #30
0
class GUI(QWidget):
    def __init__(self):
        super().__init__()
        self.unit_list = [
            'Arbalests', 'Archers', 'Axemen', 'Berserkers', 'Bombards',
            'Camels', 'Cavaliers', 'Champions', 'ChuKoNu', 'Crossbowmen',
            'EliteArchers', 'EliteAxemen', 'EliteBerserkers',
            'EliteJanissaries', 'EliteLongbowmen', 'EliteMameluks',
            'EliteMangudai', 'EliteMonks', 'ElitePikemen', 'EliteRaiders',
            'EliteSamurai', 'EliteSkirmishers', 'EliteTemplars',
            'ExpertSkirmishers', 'HandCanon', 'HeavyCamels',
            'HeavyHorseArchers', 'HeavyScorpions', 'HorseArchers',
            'Janissaries', 'Knights', 'LightCav', 'Longbowmen',
            'Longswordsmen', 'MaA', 'Mameluks', 'Mangudai', 'Milita', 'Monks',
            'Onager', 'Paladins', 'Pikemen', 'Raiders', 'Rams', 'Samurai',
            'Scorpions', 'ScoutCav', 'SiegeRams', 'Skirmishers', 'Spearmen',
            'Templars', 'Trebuchets', 'TwoHanded', 'Villager', 'WarElephants'
        ]
        self.terrain_list = [
            'Bridge', 'Desert', 'DesertRoad', 'Ford', 'Forest', 'Hill',
            'HillRoad', 'Mountain', 'MountainRoad', 'Plain', 'PlainRoad',
            'Swamp'
        ]
        self.types = ['cavalry', 'infantry', 'ranged', 'siege', 'structure']
        self.ttypes = [
            'bridge', 'desert', 'ford', 'forest', 'hill', 'mountain', 'plain',
            'structure', 'swamp'
        ]

        with open("custom_units.json", "r") as f:
            self.custom_units = json.load(f)

        self.unit_list += self.custom_units.keys()
        self.unit_list = sorted(self.unit_list)

        with open("custom_terrains.json", "r") as f:
            self.custom_terrains = json.load(f)

        self.terrain_list += self.custom_terrains.keys()
        self.terrain_list = sorted(self.terrain_list)

        with open("custom_abilities.json", "r") as f:
            self.custom_abilities = json.load(f)

        self.distance = 1
        self.debug = False

        self.initUI()

    def initUI(self):
        hbox = QHBoxLayout(self)

        self.left = SideFrame(self, name="Attacker")
        self.left.setFrameShape(QFrame.StyledPanel)

        self.right = SideFrame(self, name="Defender")
        self.right.setFrameShape(QFrame.StyledPanel)

        self.right.other = self.left
        self.left.other = self.right

        self.bottom = QFrame(self)
        self.bottom.setFrameShape(QFrame.StyledPanel)

        self.ability_creator = AbilityCreator(self.bottom)
        self.ability_creator.resize(800, 500)

        splitter1 = QSplitter(Qt.Horizontal)
        splitter1.addWidget(self.left)
        splitter1.addWidget(self.right)

        splitter2 = QSplitter(Qt.Vertical)
        splitter2.addWidget(splitter1)
        splitter2.addWidget(self.bottom)

        hbox.addWidget(splitter2)
        self.setLayout(hbox)

        splitter2.setSizes([400, 400])

        self.init_bottom()

        self.setGeometry(300, 300, 900, 900)
        self.setWindowTitle('AoE: Age of Kings Battle Simulator')
        self.showMaximized()
        self.setWindowIcon(QIcon("icon.png"))

        self.show()

    def init_bottom(self):
        self.fight_btn = QPushButton("Fight", self.bottom)
        self.fight_btn.resize(self.fight_btn.sizeHint())
        self.fight_btn.move(50, 50)
        self.fight_btn.clicked.connect(self.initiate)

        self.inv_btn = QPushButton("Inverse Units", self.bottom)
        self.inv_btn.resize(self.inv_btn.sizeHint())
        self.inv_btn.move(250, 50)
        self.inv_btn.clicked.connect(self.inverse_units)

        self.inv2_btn = QPushButton("Inverse Terrains", self.bottom)
        self.inv2_btn.resize(self.inv2_btn.sizeHint())
        self.inv2_btn.move(450, 50)
        self.inv2_btn.clicked.connect(self.inverse_terrain)

        QLabel("Distance", self.bottom).move(50, 150)
        self.dist_box = QComboBox(self.bottom)
        self.dist_box.addItems([str(x) for x in range(1, 7)])
        self.dist_box.activated[str].connect(
            lambda text: self.__setattr__("distance", int(text)))
        self.dist_box.move(150, 150)

        self.abilities_btn = QPushButton("Ability Creator", self.bottom)
        self.abilities_btn.resize(self.abilities_btn.sizeHint())
        self.abilities_btn.move(250, 150)
        self.abilities_btn.clicked.connect(lambda: self.ability_creator.show())

        self.b = QPlainTextEdit(self.bottom)
        self.b.setReadOnly(True)
        self.b.move(800, 50)
        self.b.resize(700, 500)
        sys.stdout = RedirectStream(self.b)

        self.inv2_btn = QPushButton("Clear", self.bottom)
        self.inv2_btn.resize(self.inv2_btn.sizeHint())
        self.inv2_btn.move(1350, 560)
        self.inv2_btn.clicked.connect(lambda: self.b.clear())

        self.debug_b = QCheckBox("Debug?", self.bottom)
        self.debug_b.move(650, 60)
        self.debug_b.stateChanged.connect(self.debug_checker)

        self.cmd = QPlainTextEdit(self.bottom)
        self.cmd.resize(700, 40)
        self.cmd.move(1550, 50)
        self.cmd.hide()

        self.cmd_run = QPushButton("Run", self.bottom)
        self.cmd_run.resize(self.cmd_run.sizeHint())
        self.cmd_run.move(1550, 110)
        self.cmd_run.clicked.connect(self.eval_code)
        self.cmd_run.hide()

    def debug_checker(self, state):
        self.__setattr__("debug", state == Qt.Checked)
        if state == Qt.Checked:
            self.cmd.show()
            self.cmd_run.show()
        else:
            self.cmd.hide()
            self.cmd_run.hide()

    def eval_code(self):
        try:
            eval(self.cmd.toPlainText())
        except Exception as e:
            print(e)
            traceback.format_exc()

    def closeEvent(self, event):
        reply = QMessageBox.question(
            self, 'Message', "Do you wish to save the changes you made?",
            QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
            QMessageBox.No)

        if reply == QMessageBox.Yes:
            with open("custom_units.json", "w") as f:
                json.dump(self.custom_units, f)

            with open("custom_terrains.json", "w") as f:
                json.dump(self.custom_terrains, f)

            with open("custom_abilities.json", "w") as f:
                json.dump(self.custom_abilities, f)

            event.accept()
        elif reply == QMessageBox.Cancel:
            event.ignore()
        else:
            event.accept()

    def battle(self, ctx):
        def priority_check():
            if "first strike" in ctx.attacker.abilities:
                return False

            if "first strike" in ctx.defender.abilities:
                return True

            if ctx.distance > 1:
                return False

            if "skirmish" in ctx.defender.abilities:
                return True

            if "anti-cavalry" in ctx.defender.abilities and ctx.attacker.type == objects.UnitType.cavalry:
                return True

            return False

        if priority_check():
            if ctx.distance <= ctx.defender.range:
                ctx.status = 1
                ctx.defender.fight(ctx, ctx.attacker)

            ctx.status = 0
            ctx.attacker.fight(ctx, ctx.defender)
        else:
            ctx.attacker.fight(ctx, ctx.defender)
            if ctx.distance <= ctx.defender.range:
                ctx.status = 1
                ctx.defender.fight(ctx, ctx.attacker)

            if "rapid fire" in ctx.attacker.abilities:
                ctx.attacker.fight(ctx, ctx.defender)

        if "zeal" in ctx.attacker.abilities and ctx.attacker.health > 0:
            ctx.attacker.health += 20 if ctx.attacker.health + 20 <= 100 else 100 - ctx.attacker.health

        if "zeal" in ctx.defender.abilities and ctx.defender.health > 0:
            ctx.defender.health += 20 if ctx.defender.health + 20 <= 100 else 100 - ctx.defender.health

        ctx.attacker.battles += 1
        ctx.defender.battles += 1

    def initiate(self):
        if self.left.unit.health == 0 or self.right.unit.health == 0:
            print("!One of the units is dead!\n")
            return

        ctx = objects.Context(attacker=self.left.unit,
                              defender=self.right.unit,
                              atk_terrain=self.left.terrain,
                              def_terrain=self.right.terrain,
                              distance=self.distance,
                              debug=self.debug,
                              custom_abilities=self.custom_abilities)

        print("[battle]")
        self.battle(ctx)

        print("[Final Stats]")
        self.left.unit = ctx.attacker
        self.right.unit = ctx.defender
        print(ctx.attacker)
        print("...")
        print(ctx.defender)

        print("")
        self.left.unit_set()
        self.right.unit_set()

    def inverse_units(self):
        self.right.UnitComboBox.setCurrentIndex(
            self.unit_list.index(self.left.unit.__class__.__name__))
        self.left.UnitComboBox.setCurrentIndex(
            self.unit_list.index(self.right.unit.__class__.__name__))

        self.left.unit, self.right.unit = self.right.unit, self.left.unit

        self.left.unit_set()
        self.right.unit_set()

    def inverse_terrain(self):
        self.right.TerrainComboBox.setCurrentIndex(
            self.terrain_list.index(self.left.terrain.name))
        self.left.TerrainComboBox.setCurrentIndex(
            self.terrain_list.index(self.right.terrain.name))

        self.left.terrain, self.right.terrain = self.right.terrain, self.left.terrain

        self.left.terrain_set()
        self.right.terrain_set()
class window(QMainWindow):

    csvFileName = ''
    courseList = []
    csvTrainingData = 'TrainingData.csv'
    predictedCourses = []
    predictedCoursesWeights = []
    Target_Student_Prev_Courses = []

    #Options which are common to the entire application are included inside the init method
    def __init__(self):
        #Setting up the window
        super(window, self).__init__()
        self.setGeometry(50, 50, 2000, 1000)
        self.setWindowTitle('DigiPen Course Recommender')
        self.setWindowIcon(QIcon('DigiPenLogo_new.png'))

        #Creating Menu
        extractAction = QAction('&Quit Application', self)
        extractAction.setShortcut('Ctrl+Q')
        extractAction.setStatusTip('leave the app')
        extractAction.triggered.connect(self.close_application)

        self.statusBar()

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&File')
        fileMenu.addAction(extractAction)

        #------------------------Calling-------Home Screen
        self.home()

    def home(self):

        SelectDataFileLabel = QLabel('Select Data File: ', self)
        SelectDataFileLabel.move(xPosition, yPosition)
        SelectDataFileLabel.setStyleSheet("Qlabel{font:30pt Comic Sans MS}")
        SelectDataFileLabel.setFont(QFont('Arial', 12))
        SelectDataFileLabel.resize(SelectDataFileLabel.sizeHint())

        chooseDataFilebtn = QPushButton(' Choose File ', self)
        chooseDataFilebtn.clicked.connect(self.file_open)
        chooseDataFilebtn.setFont(QFont('Arial', 12))
        chooseDataFilebtn.resize(chooseDataFilebtn.sizeHint())
        chooseDataFilebtn.move(xPosition + 120, yPosition)

        SelectDepartmentLabel = QLabel('Select Department: ', self)
        SelectDepartmentLabel.setFont(QFont('Arial', 12))
        SelectDepartmentLabel.move(xPosition, yPosition + 40)
        SelectDepartmentLabel.resize(SelectDepartmentLabel.sizeHint())

        department_List = [
            'ALL', 'Art', 'Computer Science', 'Math', 'Physics',
            'Social Science', 'Music'
        ]
        department_comboBox = QComboBox(self)
        department_comboBox.setFont(QFont('Arial', 12))
        department_comboBox.addItems(department_List)
        department_comboBox.resize(department_comboBox.sizeHint())
        department_comboBox.move(xPosition + 150, yPosition + 40)
        print(department_comboBox.currentIndex())

        SelectTargetCourse = QLabel('Select Target Course : ', self)
        SelectTargetCourse.move(xPosition + 500, yPosition + 40)
        SelectTargetCourse.setFont(QFont('Arial', 12))
        SelectTargetCourse.resize(SelectTargetCourse.sizeHint())

        self.target_courses_comboBox = QComboBox(self)
        self.target_courses_comboBox.addItems(self.courseList)
        self.target_courses_comboBox.setFont(QFont('Arial', 12))
        self.target_courses_comboBox.move(xPosition + 650, yPosition + 40)
        self.target_courses_comboBox.resize(200, 25)

        self.SelectTrainingCourses = QLabel('Select Training Courses : ', self)
        self.SelectTrainingCourses.move(xPosition, yPosition + 200)
        self.SelectTrainingCourses.setFont(QFont('Arial', 12))
        self.SelectTrainingCourses.resize(
            self.SelectTrainingCourses.sizeHint())

        self.Training_Courses_ComboBox = QComboBox(self)
        self.Training_Courses_ComboBox.move(xPosition, yPosition + 220)
        self.Training_Courses_ComboBox.setFont(QFont('Arial', 12))
        self.Training_Courses_ComboBox.resize(
            self.target_courses_comboBox.sizeHint())
        self.Training_Courses_ComboBox.resize(200, 25)

        AddTrainingCourseBtn = QPushButton('Add Training Course >>> ', self)
        AddTrainingCourseBtn.clicked.connect(self.Add_Training_Courses)
        AddTrainingCourseBtn.setFont(QFont('Arial', 12))
        AddTrainingCourseBtn.resize(AddTrainingCourseBtn.sizeHint())
        AddTrainingCourseBtn.move(xPosition, yPosition + 270)

        TrainingCoursesLabel = QLabel('Training Courses:', self)
        TrainingCoursesLabel.move(xPosition + 300, yPosition + 175)
        TrainingCoursesLabel.setFont(QFont('Arial', 12))
        TrainingCoursesLabel.resize(TrainingCoursesLabel.sizeHint())
        #self.cutomItem = QListWidgetItem('this is custom text')
        self.TrainingCourses = QListWidget(self)
        self.TrainingCourses.move(xPosition + 300, yPosition + 200)
        self.TrainingCourses.resize(300, 400)
        self.TrainingCourses.setFont(QFont('Arial', 12))

        PredictedCoursesLabel = QLabel('Predicted Courses Effect:', self)
        PredictedCoursesLabel.move(xPosition + 700, yPosition + 175)
        PredictedCoursesLabel.setFont(QFont('Arial', 12))
        PredictedCoursesLabel.resize(PredictedCoursesLabel.sizeHint())

        self.predictedCoursesListWidget = QListWidget(self)
        self.predictedCoursesListWidget.move(xPosition + 700, yPosition + 200)
        self.predictedCoursesListWidget.resize(300, 400)
        self.predictedCoursesListWidget.addItems(self.predictedCoursesWeights)
        self.predictedCoursesListWidget.setFont(QFont('Arial', 12))

        PredictedWeightsLabel = QLabel('Predicted Weights:', self)
        PredictedWeightsLabel.move(xPosition + 1000, yPosition + 175)
        PredictedWeightsLabel.setFont(QFont('Arial', 12))
        PredictedWeightsLabel.resize(PredictedWeightsLabel.sizeHint())
        self.predictedCoursesWeightWidget = QListWidget(self)
        self.predictedCoursesWeightWidget.move(xPosition + 1000,
                                               yPosition + 200)
        self.predictedCoursesWeightWidget.resize(300, 400)
        self.predictedCoursesWeightWidget.setFont(QFont('Arial', 12))
        self.predictedCoursesWeightWidget.addItems(
            self.predictedCoursesWeights)

        PredictBtn = QPushButton(' Build Weights ', self)
        PredictBtn.clicked.connect(self.Predict_Results)
        PredictBtn.clicked.connect(self.update_available_courses)
        PredictBtn.setFont(QFont('Arial', 12))
        PredictBtn.resize(PredictBtn.sizeHint())
        PredictBtn.move(xPosition + 375, yPosition + 625)

        SelectDataFileLabel = QLabel('Enter Grades Of Training Courses: ',
                                     self)
        SelectDataFileLabel.move(xPosition + 50, yPosition + 710)
        SelectDataFileLabel.setStyleSheet("Qlabel{font:30pt Comic Sans MS}")
        SelectDataFileLabel.setFont(QFont('Arial', 12))
        SelectDataFileLabel.resize(SelectDataFileLabel.sizeHint())
        # Create textbox
        self.GradeTextBox = QLineEdit(self)
        self.GradeTextBox.move(xPosition + 300, yPosition + 700)
        self.GradeTextBox.setFont(QFont('Arial', 12))
        self.GradeTextBox.resize(280, 40)

        PredictGradeBtn = QPushButton('Predict Grade', self)
        PredictGradeBtn.clicked.connect(self.Predict_Grade)
        PredictGradeBtn.move(xPosition + 375, yPosition + 750)
        PredictGradeBtn.setFont(QFont('Arial', 12))
        PredictGradeBtn.resize(PredictGradeBtn.sizeHint())

        PredictGradeHintLabel = QLabel('Predicted Grade: ', self)
        PredictGradeHintLabel.move(xPosition + 800, yPosition + 750)
        PredictGradeHintLabel.setStyleSheet("color: rgb(0,0,250);")
        PredictGradeHintLabel.setFont(QFont('Arial', 12))
        PredictGradeHintLabel.resize(PredictGradeHintLabel.sizeHint())

        self.PredictedGradeNumberLabel = QLabel('0', self)
        self.PredictedGradeNumberLabel.move(xPosition + 1000, yPosition + 750)
        self.PredictedGradeNumberLabel.setStyleSheet("color: rgb(0,0,250);")
        self.PredictedGradeNumberLabel.setFont(QFont('Arial', 12))
        self.PredictedGradeNumberLabel.resize(100, 20)

        RestartBtn = QPushButton('Reset', self)
        RestartBtn.clicked.connect(self.Restart_Prediction)
        RestartBtn.setFont(QFont('Arial', 12))
        RestartBtn.resize(RestartBtn.sizeHint())
        RestartBtn.move(xPosition + 700, yPosition + 850)

        self.show()

    def Predict_Grade(self):
        enteredGrades = self.GradeTextBox.text()
        floatGrades = []
        for grade in enteredGrades.split(','):
            floatGrades.append(float(grade))

        print("Entered Grades:", enteredGrades)
        print("Float Grades:", floatGrades)

        finalPredictedGrade = 0
        courseCounter = 0
        for grade in floatGrades:
            print("Multiplying Weight:",
                  self.predictedCoursesWeights[courseCounter], " and Grade:",
                  grade)
            finalPredictedGrade = finalPredictedGrade + grade * float(
                self.predictedCoursesWeights[courseCounter])
            courseCounter = courseCounter + 1

        print("Final Grade: ", finalPredictedGrade)
        finalPredictedGrade = format(finalPredictedGrade, '.2f')
        self.PredictedGradeNumberLabel.setText(str(finalPredictedGrade))

        #clearing the enteredGrades when prediction is done
        floatGrades.clear()

    def Restart_Prediction(self):
        print("Restarting Prediction")
        self.TrainingCourses.clear()
        self.predictedCoursesListWidget.clear()
        self.predictedCoursesWeightWidget.clear()
        self.Target_Student_Prev_Courses.clear()
        self.predictedCoursesWeights.clear()

        self.GradeTextBox.clear()
        self.PredictedGradeNumberLabel.setText("0")

    def Add_Training_Courses(self):
        training_Course = str(self.Training_Courses_ComboBox.currentText())
        print("Adding training course: ", training_Course)
        self.Target_Student_Prev_Courses.append(training_Course)
        self.TrainingCourses.addItem(training_Course)
        self.TrainingCourses.update()

    def Predict_Results(self):

        targetCourse = str(self.target_courses_comboBox.currentText())
        print("Target Course Selected: ", targetCourse)

        ID_Prev_Students = ExtractingStudents.Check_Target_Course(targetCourse)
        print("Num of Students Who Previously Took The Target Course: ",
              len(ID_Prev_Students))

        target_course_recorded_grades = ExtractingStudents.Record_Target_Course_Values(
            ID_Prev_Students, targetCourse)

        recordedCourseData = ExtractingStudents.Create_Data_To_Train(
            self.Target_Student_Prev_Courses, ID_Prev_Students)
        cleanedRecordedData = ExtractingStudents.Clean_Data_To_Train(
            recordedCourseData)

        ExtractingStudents.Merge_Target_Course_Grade_To_Cleaned_Data(
            cleanedRecordedData, target_course_recorded_grades)

        gradeTable = ExtractingStudents.Create_Grade_Table(cleanedRecordedData)
        ExtractingStudents.Array2D_to_CSV("TrainingData.csv", gradeTable)

        Model = GradientDescentGradePrediction.Perform_All_Data_Steps(
            self.csvTrainingData)

        self.Display_Predicted_Courses(Model)

    def Display_Predicted_Courses(self, Model):

        unScaledPredictedWeights = []
        SumOfPredictedWeights = 0
        for weight in Model.coef_[0]:
            #Ignoring the negative weights
            if weight > 0:
                SumOfPredictedWeights = SumOfPredictedWeights + weight
                unScaledPredictedWeights.append(weight)
            else:
                unScaledPredictedWeights.append(0)

        ScaledPredictedWeights = []
        for item in unScaledPredictedWeights:
            scaledItem = item / SumOfPredictedWeights
            scaledItem = format(scaledItem, '.4f')
            ScaledPredictedWeights.append(scaledItem)

        print("UnScaledPredicted Weights:", unScaledPredictedWeights)
        print("SumOfPredictedPositiveWeights:", SumOfPredictedWeights)
        print("ScaledPredictedWeight:", ScaledPredictedWeights)
        for weight in ScaledPredictedWeights:
            self.predictedCoursesWeights.append(str(weight))

        #print(self.predictedCoursesWeights)
        #self.predictedCoursesWeights = np.array_str(Model.coef_)
        Output_Weights = []
        Output_Subjects = []

        zipped = sorted(zip(self.Target_Student_Prev_Courses,
                            self.predictedCoursesWeights),
                        key=lambda x: x[1],
                        reverse=True)
        print("Zipped:", zipped)
        for item in zipped:
            print("Subject:", item[0], " Weight:", item[1])
            Output_Subjects.append(item[0])
            Output_Weights.append(item[1])

        self.predictedCoursesWeightWidget.addItems(Output_Weights)
        self.predictedCoursesListWidget.addItems(Output_Subjects)

        #clearing All data before next prediction
        zipped.clear()
        print("Zipped Clear: ", zipped)
        Output_Subjects.clear()
        Output_Weights.clear()
        unScaledPredictedWeights.clear()
        ScaledPredictedWeights.clear()
        SumOfPredictedWeights = 0

    def file_open(self):
        self.csvFileName, _ = QFileDialog.getOpenFileName(
            self, 'Open File', options=QFileDialog.DontUseNativeDialog)
        print("Opening Csv File: ", self.csvFileName)
        ExtractingStudents.Create_Dictionary_of_Dictionary(self.csvFileName)
        print("Creating Dictionary of Dictionary")
        self.update_available_courses()

    def update_available_courses(self):
        self.courseList = ExtractingStudents.AvailableCourses
        self.courseList.sort()
        self.target_courses_comboBox.addItems(self.courseList)
        self.Training_Courses_ComboBox.addItems(self.courseList)

    def close_application(self):

        choice = QMessageBox.question(self, 'Message', "Are you sure to quit?",
                                      QMessageBox.Yes | QMessageBox.No,
                                      QMessageBox.No)

        if choice == QMessageBox.Yes:
            print('quit application')
            sys.exit()
        else:
            pass
Beispiel #32
0
class OPEN_ROUTE(QWidget):
	def __init__(self,parent=None):
		super(OPEN_ROUTE,self).__init__(parent)

		self.Full_list=['']
		DB_sheet = csv2dict("DB.csv")
		for row in DB_sheet:
			self.Full_list.append(row["name"])
			
		self.resize(1000,800)
		QE_length = 400
		QE_hight = 20
		Y_start = 40
		Y_step = 30
		X10 =1080
		X11 = 1160
		X12 = 1240
		X13 = 1240


#COMMAND BUTTONS ON RIGHT		
#DB BUTTON
		Y_start=70	
		self.Lable_DB_DATE = QLabel("DB_Date",self)
		self.Lable_DB_DATE .move (X10,Y_start-Y_step*1)		
		self.DB_DATE = QLineEdit(self)
		self.DB_DATE.setText(GetFileDate('.\\DB.csv'))
		self.DB_DATE.setGeometry(QtCore.QRect(X11, Y_start-Y_step*1, QE_length/3.9, QE_hight))
		
		self.UPD_DB = QPushButton('UPD_DB',self)
		self.UPD_DB.move(X10,Y_start+Y_step*0)
		self.UPD_DB.clicked.connect(lambda:INITIALIZE_DB())
		
		self.UPD_DB = QPushButton('BACKUP_DB',self)
		self.UPD_DB.move(X11,Y_start+Y_step*0)
		self.UPD_DB.clicked.connect(lambda:BACKUP_DB())
		
		self.UPD_DB = QPushButton('Restore_DB',self)
		self.UPD_DB.move(X12,Y_start+Y_step*0)
		self.UPD_DB.clicked.connect(lambda:RestoreFile(".\\backup",".\\"))
#RULE ENGINE BUTTON		
		self.Lable_DB_DATE = QLabel("RULE_Date",self)
		self.Lable_DB_DATE .move (X10,Y_start+Y_step*1)		
		self.DB_DATE = QLineEdit(self)
		#GetFileDate(filename)
		#self.DB_DATE.setText(GetFileDate("DB.csv"))
		self.DB_DATE.setGeometry(QtCore.QRect(X11, Y_start+Y_step*1, QE_length/3.9, QE_hight))
		
		self.UPD_DB = QPushButton('UPD_RULE',self)
		self.UPD_DB.move(X10,Y_start+Y_step*2)
		self.UPD_DB.clicked.connect(self.UPDATE_DB)
		
		self.UPD_DB = QPushButton('BACKUP_RULE',self)
		self.UPD_DB.move(X11,Y_start+Y_step*2)
		self.UPD_DB.clicked.connect(self.UPDATE_DB)
		
		self.UPD_DB = QPushButton('Restore_RULE',self)
		self.UPD_DB.move(X12,Y_start+Y_step*2)
		self.UPD_DB.clicked.connect(lambda:RestoreFile(".\\backup",".\\"))
#RELOAD BUTTON

		self.Lable_DB_DATE = QLabel("Reload ListCaches",self)
		self.Lable_DB_DATE .move (X10,Y_start+Y_step*4)	
		self.Lable_DB_DATE = QLabel("Reload Rule",self)
		self.Lable_DB_DATE .move (X13,Y_start+Y_step*4)	
					
		self.Re_AP_LIST = QPushButton('Re_AP_LIST',self)
		self.Re_AP_LIST.move(X10,Y_start+Y_step*5)
		self.Re_AP_LIST.clicked.connect(lambda: Reload_Region_LIST("AP"))
		
		self.Re_EU_LIST = QPushButton('Re_EU_LIST',self)
		self.Re_EU_LIST.move(X10,Y_start+Y_step*6)
		self.Re_EU_LIST.clicked.connect(lambda: Reload_Region_LIST("EU"))
		
		self.Re_NA_LIST = QPushButton('Re_NA_LIST',self)
		self.Re_NA_LIST.move(X10,Y_start+Y_step*7)
		self.Re_NA_LIST.clicked.connect(lambda: Reload_Region_LIST("NA"))
		
		self.Re_AP_RULE = QPushButton('Re_AP_RULE',self)
		self.Re_AP_RULE.move(X13,Y_start+Y_step*5)
		self.Re_AP_RULE.clicked.connect(lambda: Reload_Region_RULE("AP"))
		
		self.Re_EU_RULE = QPushButton('Re_EU_RULE',self)
		self.Re_EU_RULE.move(X13,Y_start+Y_step*6)
		self.Re_EU_RULE.clicked.connect(lambda: Reload_Region_RULE("EU"))
		
		self.Re_NA_RULE = QPushButton('Re_NA_RULE',self)
		self.Re_NA_RULE.move(X13,Y_start+Y_step*7)
		self.Re_NA_RULE.clicked.connect(lambda: Reload_Region_RULE("NA"))

#send email
		
		self.Lable_DB_DATE = QLabel("Send Email to Peer",self)
		self.Lable_DB_DATE .move (X10,Y_start+Y_step*9+10)	

		self.New_Election = QPushButton('New_Election',self)
		self.New_Election.move(X10,Y_start+Y_step*10)
		self.New_Election.clicked.connect(lambda: Reload_Region_LIST("AP"))
		
		self.Provisoned = QPushButton('Provisoned',self)
		self.Provisoned.move(X10,Y_start+Y_step*11)
		self.Provisoned.clicked.connect(lambda: Reload_Region_LIST("EU"))

		Combo_LIST_PEER=['BICS NA','BICS_EU','VF','TATA','TeliaSonera','COSMOTE GREECE']
		self.Combo_Select_PEER = QComboBox(self)
		for i in Combo_LIST_PEER:
			self.Combo_Select_PEER.addItem(i)
		self.Combo_Select_PEER.move(X11,Y_start+Y_step*10)
		self.Combo_Select_PEER.setMaxVisibleItems (10)
		#self.Combo_Select_PEER.currentIndexChanged.connect(self.update_B)

## OPA and OPB
		Y_start=40	
## code for OPA only start
		X1 = 10 #label1 start
		X2 = 100#text1 start
		X3 = 200#labe2 start
		X4 = 250#text2 start
		X5 = 320#button3 start

		self.Lable_TADIG_A = QLabel("TADIG_A",self)
		self.Lable_TADIG_A.move (X4,Y_start-Y_step*1)		
		self.TADIG_A = QLineEdit(self)
		self.TADIG_A.setText("")
		self.TADIG_A.setGeometry(QtCore.QRect(X5, Y_start-Y_step*1, QE_length/2.2, QE_hight))
		
		self.Lable_SSID_A = QLabel("SSID_A",self)
		self.Lable_SSID_A.move (X1,Y_start-Y_step)		
		self.SSID_A = QLineEdit(self)
		self.SSID_A.setText("")
		self.SSID_A.setGeometry(QtCore.QRect(X2, Y_start-Y_step, QE_length/4, QE_hight))

		self.Lable_OP_A = QLabel("OP_A",self)
		self.Lable_OP_A.move (X1,Y_start)		
		self.OP_A = QLineEdit(self)
		self.OP_A.setText("")
		self.OP_A.setGeometry(QtCore.QRect(X2, Y_start, QE_length, QE_hight))
		
		self.Lable_Country_A = QLabel("Country_A",self)
		self.Lable_Country_A.move (X1,Y_start+Y_step*2)		
		self.Country_A = QLineEdit(self)
		self.Country_A.setText("")
		self.Country_A.setGeometry(QtCore.QRect(X2,Y_start+Y_step*2, QE_length, QE_hight))
		
		self.Lable_Realm_A = QLabel("Realm_A",self)
		self.Lable_Realm_A.move (X1,Y_start+Y_step*3)				
		self.realm_A = QLineEdit(self)
		self.realm_A.setText("")
		self.realm_A.setGeometry(QtCore.QRect(X2,Y_start+Y_step*3, QE_length, QE_hight))

		self.Lable_IMSI_A = QLabel("IMSI_A",self)
		self.Lable_IMSI_A.move (X1,Y_start+Y_step*4)				
		self.IMSI_A = QLineEdit(self)
		self.IMSI_A.setText("")
		self.IMSI_A.setGeometry(QtCore.QRect(X2,Y_start+Y_step*4, QE_length, QE_hight))
		
		self.Lable_LIST_A = QLabel("LIST_A",self)
		self.Lable_LIST_A.move(X1,Y_start+Y_step*5)		
		self.LIST_A = QLineEdit(self)
		self.LIST_A.setText("")
		self.LIST_A.setGeometry(QtCore.QRect(X2,Y_start+Y_step*5, QE_length, QE_hight))
		
		self.Label_Owner_A = QLabel("Owner_A",self)
		self.Label_Owner_A.move(X1,Y_start+Y_step*6)		
		self.Owner_A = QLineEdit(self)
		self.Owner_A.setText("")
		self.Owner_A.setGeometry(QtCore.QRect(X2,Y_start+Y_step*6, QE_length/3, QE_hight))
		
		self.Label_RMT_A = QLabel("RMT_A",self)
		self.Label_RMT_A.move(X4,Y_start+Y_step*6)		
		self.RMT_A = QLineEdit(self)
		self.RMT_A.setText("")
		self.RMT_A.setGeometry(QtCore.QRect(X5,Y_start+Y_step*6, QE_length/2.2, QE_hight))
		
		self.Lable_DRA_A = QLabel("DRA_A",self)
		self.Lable_DRA_A.move(X1,Y_start+Y_step*7)		
		self.DRA_A = QLineEdit(self)
		self.DRA_A.setText("")
		self.DRA_A.setGeometry(QtCore.QRect(X2,Y_start+Y_step*7, QE_length, QE_hight))		
		
		#self.Lable_HUB_A = QLabel("HUB_A",self)
		#self.Lable_HUB_A.move(X1,Y_start+Y_step*8)		
		#self.HUB_A = QLineEdit(self)
		#self.HUB_A.setText("")
		#self.HUB_A.setGeometry(QtCore.QRect(X2,Y_start+Y_step*8, QE_length, QE_hight))
		
		self.Lable_HUB_PLOICY_A = QLabel("HUB_PLOICY_A",self)
		self.Lable_HUB_PLOICY_A.move(X1,Y_start+Y_step*9)		
		self.HUB_PLOICY_A = QTextEdit(self)
		self.HUB_PLOICY_A.setText("")
		self.HUB_PLOICY_A.setGeometry(QtCore.QRect(X2,Y_start+Y_step*9, QE_length, QE_hight*3))
		
		self.Lable_TECH_COMMENT_A = QLabel("TECH_COMMENT_A",self)
		self.Lable_TECH_COMMENT_A.move(X1,Y_start+Y_step*12)		
		self.TECH_COMMENT_A = QTextEdit(self)
		self.TECH_COMMENT_A.LineWrapMode
		self.TECH_COMMENT_A.setText("")
		self.TECH_COMMENT_A.setGeometry(QtCore.QRect(X2,Y_start+Y_step*12, QE_length, QE_hight*8))				

#BUILD COMBO LIST_A WITH DROP DOWN SELECTION
		Combo_LIST_A=self.Full_list
		self.Combo_Select_A = QComboBox(self)
		for i in Combo_LIST_A:
			self.Combo_Select_A.addItem(i)
		self.Combo_Select_A.move(X2,Y_start+Y_step*1)
		self.Combo_Select_A.setMaxVisibleItems (10)
		self.Combo_Select_A.currentIndexChanged.connect(self.update_A)
		self.OP_A.returnPressed.connect(self.rebuild_A_list)

#Add LISTCACHE FUNCTION_A
		self.Combo_Region_A = QComboBox(self)
		for i in RegionList:
			self.Combo_Region_A.addItem(i)
		
		self.Combo_Region_A.move(X2,Y_start+Y_step*18)
		self.Combo_Region_A.setMaxVisibleItems (4)
		self.Lable_Region_A = QLabel("Normal Route",self)
		self.Lable_Region_A.move(X1,Y_start+Y_step*18)		

		self.B_Reams2A_LIST = QPushButton('B_Realms2A_List',self)
		self.B_Reams2A_LIST.move(X3,Y_start+Y_step*18)
		self.B_Reams2A_LIST.clicked.connect(lambda: ADD_REALMS2LIST(self.Combo_Region_A.currentText(),self.realm_B.displayText(),self.LIST_A.displayText()))
		
#Check DECIDE ROUTE	FUNCTION_A
		self.Check_TO_A_Route = QPushButton('Check to A route',self)
		self.Check_TO_A_Route.move(X5,Y_start+Y_step*18)
		self.Check_TO_A_Route.clicked.connect(lambda: CHECK_DECIDE_ROUTE2OP(self.Combo_Region_A.currentText(),self.realm_B.displayText(),self.realm_A.displayText()))
		
		
#Add K2R FUNCTION_A
		self.Lable_Region_K2R_A = QLabel("K2R Route",self)
		self.Lable_Region_K2R_A.move(X1,Y_start+Y_step*20)		

		self.K2R_B_Reams2A_LIST = QPushButton('K2R_B_Realms2A_List/ADD RequestFilter/UPD vzw LIST',self)
		self.K2R_B_Reams2A_LIST.move(X3,Y_start+Y_step*20)
		#PARA:REGION A, REALMs B, LIST A, REALMs A, Name A, Name B
		self.K2R_B_Reams2A_LIST.clicked.connect(lambda: K2R(self.Combo_Region_A.currentText(),self.realm_B.displayText(),self.LIST_A.displayText(),self.realm_A.displayText(),self.OP_A.displayText(),self.OP_B.displayText()))

		

## code for OPB only start
		distance=550
		X1 = distance+X1 #label1 start
		X2 = distance+X2#text1 start
		X3 = distance+X3#labe2 start
		X4 = distance+X4#text2 start
		X5 = distance+X5#button3 start

		self.Lable_TADIG_B = QLabel("TADIG_B",self)
		self.Lable_TADIG_B.move (X4,Y_start-Y_step*1)		
		self.TADIG_B = QLineEdit(self)
		self.TADIG_B.setText("")
		self.TADIG_B.setGeometry(QtCore.QRect(X5, Y_start-Y_step*1, QE_length/2.2, QE_hight))
		
		self.Lable_SSID_B = QLabel("SSID_B",self)
		self.Lable_SSID_B.move (X1,Y_start-Y_step)		
		self.SSID_B = QLineEdit(self)
		self.SSID_B.setText("")
		self.SSID_B.setGeometry(QtCore.QRect(X2, Y_start-Y_step, QE_length/4, QE_hight))

		self.Lable_OP_B = QLabel("OP_B",self)
		self.Lable_OP_B.move (X1,Y_start)		
		self.OP_B = QLineEdit(self)
		self.OP_B.setText("")
		self.OP_B.setGeometry(QtCore.QRect(X2, Y_start, QE_length, QE_hight))
		
		self.Lable_Country_B = QLabel("Country_B",self)
		self.Lable_Country_B.move (X1,Y_start+Y_step*2)		
		self.Country_B = QLineEdit(self)
		self.Country_B.setText("")
		self.Country_B.setGeometry(QtCore.QRect(X2,Y_start+Y_step*2, QE_length, QE_hight))
		
		self.Lable_Realm_B = QLabel("Realm_B",self)
		self.Lable_Realm_B.move (X1,Y_start+Y_step*3)				
		self.realm_B = QLineEdit(self)
		self.realm_B.setText("")
		self.realm_B.setGeometry(QtCore.QRect(X2,Y_start+Y_step*3, QE_length, QE_hight))

		self.Lable_IMSI_B = QLabel("IMSI_B",self)
		self.Lable_IMSI_B.move (X1,Y_start+Y_step*4)				
		self.IMSI_B = QLineEdit(self)
		self.IMSI_B.setText("")
		self.IMSI_B.setGeometry(QtCore.QRect(X2,Y_start+Y_step*4, QE_length, QE_hight))
		
		self.Lable_LIST_B = QLabel("LIST_B",self)
		self.Lable_LIST_B.move(X1,Y_start+Y_step*5)		
		self.LIST_B = QLineEdit(self)
		self.LIST_B.setText("")
		self.LIST_B.setGeometry(QtCore.QRect(X2,Y_start+Y_step*5, QE_length, QE_hight))
		
		self.Owner_B = QLabel("Owner_B",self)
		self.Owner_B.move(X1,Y_start+Y_step*6)		
		self.Owner_B = QLineEdit(self)
		self.Owner_B.setText("owner B")
		self.Owner_B.setGeometry(QtCore.QRect(X2,Y_start+Y_step*6, QE_length/4, QE_hight))
		
		self.Label_RMT_B = QLabel("RMT_B",self)
		self.Label_RMT_B.move(X4,Y_start+Y_step*6)		
		self.RMT_B = QLineEdit(self)
		self.RMT_B.setText("RMT B")
		self.RMT_B.setGeometry(QtCore.QRect(X5,Y_start+Y_step*6, QE_length/2.2, QE_hight))
		
		self.Lable_DRA_B = QLabel("DRA_B",self)
		self.Lable_DRA_B.move(X1,Y_start+Y_step*7)		
		self.DRA_B = QLineEdit(self)
		self.DRA_B.setText("")
		self.DRA_B.setGeometry(QtCore.QRect(X2,Y_start+Y_step*7, QE_length, QE_hight))		
		
		#self.Lable_HUB_B = QLabel("HUB_B",self)
		#self.Lable_HUB_B.move(X1,Y_start+Y_step*8)		
		#self.HUB_B = QLineEdit(self)
		#self.HUB_B.setText("")
		#self.HUB_B.setGeometry(QtCore.QRect(X2,Y_start+Y_step*8, QE_length, QE_hight))
		
		self.Lable_HUB_PLOICY_B = QLabel("HUB_PLOICY_B",self)
		self.Lable_HUB_PLOICY_B.move(X1,Y_start+Y_step*9)		
		self.HUB_PLOICY_B = QTextEdit(self)
		self.HUB_PLOICY_B.setText("")
		self.HUB_PLOICY_B.setGeometry(QtCore.QRect(X2,Y_start+Y_step*9, QE_length, QE_hight*3))
		
		self.Lable_TECH_COMMENT_B = QLabel("TECH_COMMENT_B",self)
		self.Lable_TECH_COMMENT_B.move(X1,Y_start+Y_step*12)		
		self.TECH_COMMENT_B = QTextEdit(self)
		self.TECH_COMMENT_B.LineWrapMode
		self.TECH_COMMENT_B.setText("")
		self.TECH_COMMENT_B.setGeometry(QtCore.QRect(X2,Y_start+Y_step*12, QE_length, QE_hight*8))				

#COMBO LIST_B WITH DROP DOWN SELECTION
		Combo_LIST_B=self.Full_list
		self.Combo_Select_B = QComboBox(self)
		for i in Combo_LIST_B:
			self.Combo_Select_B.addItem(i)
		self.Combo_Select_B.move(X2,Y_start+Y_step*1)
		self.Combo_Select_B.setMaxVisibleItems (10)
		self.Combo_Select_B.currentIndexChanged.connect(self.update_B)
		self.OP_B.returnPressed.connect(self.rebuild_B_list)

#Add LISTCACHE FUNCTION_B
		self.Combo_Region_B = QComboBox(self)
		for i in RegionList:
			self.Combo_Region_B.addItem(i)
		
		self.Combo_Region_B.move(X2,Y_start+Y_step*18)
		self.Combo_Region_B.setMaxVisibleItems (4)
		self.Lable_Region_B = QLabel("Normal Route",self)
		self.Lable_Region_B.move(X1,Y_start+Y_step*18)		

		self.A_Reams2B_LIST = QPushButton('A_Realms2B_List',self)
		self.A_Reams2B_LIST.move(X3,Y_start+Y_step*18)
		self.A_Reams2B_LIST.clicked.connect(lambda: ADD_REALMS2LIST(self.Combo_Region_B.currentText(),self.realm_A.displayText(),self.LIST_B.displayText()))
		
#Check DECIDE ROUTE	FUNCTION_B
		self.Check_TO_B_Route = QPushButton('Check to B route',self)
		self.Check_TO_B_Route.move(X5,Y_start+Y_step*18)
		self.Check_TO_B_Route.clicked.connect(lambda: CHECK_DECIDE_ROUTE2OP(self.Combo_Region_B.currentText(),self.realm_A.displayText(),self.realm_B.displayText()))
		
#Add K2R FUNCTION_B
		self.Lable_Region_K2R_B = QLabel("K2R Route",self)
		self.Lable_Region_K2R_B.move(X1,Y_start+Y_step*20)		

		self.K2R_B_Reams2B_LIST = QPushButton('K2R_A_Realms2B_List/ADD RequestFilter/UPD vzw LIST',self)
		self.K2R_B_Reams2B_LIST.move(X3,Y_start+Y_step*20)
		self.K2R_B_Reams2A_LIST.clicked.connect(lambda: K2R(self.Combo_Region_B.currentText(),self.realm_A.displayText(),self.LIST_B.displayText(),self.realm_B.displayText(),self.OP_B.displayText(),self.OP_A.displayText()))



	def update_A(self,ii):
		OPA_Name = self.Combo_Select_A.currentText()
		self.OP_A.setText(OPA_Name)

		for row in DB_sheet:
			if row["name"] == OPA_Name:
				self.SSID_A.setText(row["ssid"])
				self.IMSI_A.setText(row["imsi_prefix"])
				self.Country_A.setText(row["country"])
				self.realm_A.setText(row["realm_name"])
				self.LIST_A.setText(row["LIST"])
				self.Owner_A.setText(row["owner"])
				self.RMT_A.setText(row["status"])
				self.DRA_A.setText(row["dra"])
				#self.HUB_A.setText(row["hub"])
				self.HUB_PLOICY_A.setText(row["hub_policy"])
				self.TECH_COMMENT_A.setText(row["technicalcomment"])
				self.TADIG_A.setText(row["tagid"])
				self.Combo_Region_A.currentIndex=1		
	def update_B(self,ii):
		OPB_Name = self.Combo_Select_B.currentText()
		self.OP_B.setText(OPB_Name)

		for row in DB_sheet:
			if row["name"] == OPB_Name:
				self.SSID_B.setText(row["ssid"])
				self.IMSI_B.setText(row["imsi_prefix"])
				self.Country_B.setText(row["country"])
				self.realm_B.setText(row["realm_name"])
				self.LIST_B.setText(row["LIST"])
				self.Owner_B.setText(row["owner"])
				self.RMT_B.setText(row["status"])
				self.DRA_B.setText(row["dra"])
				#self.HUB_B.setText(row["hub"])
				self.HUB_PLOICY_B.setText(row["hub_policy"])
				self.TECH_COMMENT_B.setText(row["technicalcomment"])
				self.TADIG_B.setText(row["tagid"])
				self.Combo_Region_B.currentIndex=1

## code for OPB only end



		
	def rebuild_A_list(self):
		list=[]
		key= self.OP_A.text()
		print(key)
		for OP in self.Full_list:
			if key.lower() in OP.lower():
				list.append(OP)
		self.Combo_Select_A.clear()
		for i in list:
			self.Combo_Select_A.addItem(i)
			
				
		print(self.OP_A.text)
		print(list)

	def rebuild_B_list(self):
		list=[]
		key= self.OP_B.text()
		print(key)
		for OP in self.Full_list:
			if key.lower() in OP.lower():
				list.append(OP)
		self.Combo_Select_B.clear()
		for i in list:
			self.Combo_Select_B.addItem(i)




	def Reload_RULE(self,region):
		print("RELOAD RULE "+region)	

	def UPDATE_DB(self):
		print("DB updated")
Beispiel #33
0
class Window():
    
    defaultRegion = "North America"
    labelFont = QFont("Lucida Sans", 16, QFont.Bold)
    buttonFont = QFont("Lucida Sans", 10, QFont.Thin)
    inputFont = QFont("Century Gothic", 10, QFont.Thin)
    
    def __init__(self, version, width=600, height=420, dense = 6, title="Pie Legends", isDark=False):
        
        self.app = QApplication(sys.argv)
        self._window = QMainWindow()
        
        self.dense = dense
        
        self.window.statusBar().showMessage('Initiating..')
        self.initWindow(width, height, title, version, isDark)
        self.window.statusBar().showMessage('Ready..')
        
        sys.exit(self.app.exec_())
    
    @property
    def window(self):
        return self._window;

    def initWindow(self, width, height, title, version, isDark):       
        
        self.window.setWindowTitle(title  + " " + version)
        
        self.sizeWindow(width, height)
        
        self.window.statusBar().setSizeGripEnabled(False)
        
        self.centerWindow();
        
        self.window.setAutoFillBackground(True)
        self.window.setBackgroundRole(QPalette.AlternateBase if isDark else QPalette.Dark)
        
        self.window.setWindowIcon(QIcon('../assets/favicon.png'))
        
        QToolTip.setFont(QFont('SansSerif', 10))
        
        self.initCentralWidget(isDark);
        
        self.window.show()
        
    def sizeWindow(self, width, height):
        self.window.resize(width, height)
        self.window.setMaximumSize(width, height)
        self.window.setMinimumSize(width, height)
        self.window.setFixedSize(width, height)
        
    def centerWindow(self):
        qr = self.window.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.window.move(qr.topLeft())
        
    def initCentralWidget(self, isDark):
        
        """ Logo """
        self.window.setCentralWidget(QWidget())
        self.window.centralWidget().setAutoFillBackground(True)
        self.window.centralWidget().setBackgroundRole(QPalette.Dark if isDark else QPalette.AlternateBase)
        
        self.picLabel = QLabel(self.window.centralWidget())
        pic = QPixmap("../assets/logo.png")
        self.picLabel.setPixmap(pic)
        self.picLabel.move(self.window.width()/2-pic.width()/2, 15)
        
        funcLine = pic.height()+50;
        
        
        
        
        """ Champion Section """
        
        """ Initiate """
        self.championLabel = QLabel(self.window.centralWidget())
        self.championLabel.setText("Enter Champion")
        self.championLabel.setFont(self.labelFont)
        
        championLabelWidth = self.championLabel.fontMetrics().boundingRect(self.championLabel.text()).width()
        championLabelHeight = self.championLabel.fontMetrics().boundingRect(self.championLabel.text()).height()
        
        self.championEdit = QLineEdit(self.window.centralWidget())
        self.championEdit.setFont(self.inputFont)
        
        self.countersBtn = QPushButton('Counters', self.window.centralWidget())
        self.countersBtn.setToolTip('Champion counters!')
        self.countersBtn.resize(self.countersBtn.sizeHint())
        self.countersBtn.setFont(self.buttonFont)
        
        self.buildsBtn = QPushButton('Builds', self.window.centralWidget())
        self.buildsBtn.setToolTip('Champion builds!')
        self.buildsBtn.setFont(self.buttonFont)
        
        """ Resize """
        self.buildsBtn.resize(self.buildsBtn.sizeHint())
        self.championEdit.resize(self.countersBtn.width() + self.buildsBtn.width(), 20)
        
        """ Move """
        self.championEdit.move(self.window.width()/self.dense, funcLine + championLabelHeight + 3)
        
        self.countersBtn.move(self.championEdit.x(), self.championEdit.y() + self.countersBtn.height())
        
        self.championLabel.move(self.championEdit.x()+self.championEdit.width()/2-championLabelWidth/2, funcLine)
        
        self.buildsBtn.move(self.championEdit.x() + self.countersBtn.width(), self.championEdit.y() + self.buildsBtn.height())
        
        """ Event Handling """
        self.buildsBtn.clicked.connect(self.handleBuildsBtn)
        self.countersBtn.clicked.connect(self.handleCountersBtn)
        
        self.championEdit.returnPressed.connect(self.countersBtn.click)
        
        
        
        
        """ Player Section """
        
        """ Initiate """
        self.playerLabel = QLabel(self.window.centralWidget())
        self.playerLabel.setText("Enter Player")
        
        self.playerLabel.setFont(self.labelFont)
        
        playerLabelWidth = self.playerLabel.fontMetrics().boundingRect(self.playerLabel.text()).width()
        playerLabelHeight = self.playerLabel.fontMetrics().boundingRect(self.playerLabel.text()).height()
        
        self.regionCheck = QComboBox(self.window.centralWidget())
        self.regionCheck.addItems(["North America", "Europe West", "EU Nordic & East", "Korea", "Russia", "Oceania", "Brazil", "Turkey", "Latin America North", "Latin America South"])
        self.regionCheck.setCurrentText("North America")
        PieLegends.regionUpdate(self.regionCheck.currentText())
        
        self.playerEdit = QLineEdit(self.window.centralWidget())
        self.playerEdit.setFont(self.inputFont)
        
        self.playerBtn = QPushButton('Search', self.window.centralWidget())
        self.playerBtn.setToolTip('Pie a player!')
        self.playerBtn.setFont(self.buttonFont)
        
        """ Resize """
        self.playerBtn.resize(self.playerBtn.sizeHint())
        self.playerEdit.resize(self.playerBtn.width()*2, 20)
        
        """ Move """
        self.regionCheck.move(0, funcLine + playerLabelHeight + 3) # We move the Y first
        
        playerEditWidth = self.playerEdit.frameGeometry().width()
        
        self.playerEdit.move(self.window.width()-self.window.width()/self.dense-playerEditWidth, self.regionCheck.y() + self.regionCheck.height()-6)
        
        self.playerLabel.move(self.playerEdit.x() + self.playerEdit.width()/2 - playerLabelWidth/2, funcLine)
        
        self.regionCheck.move(self.playerEdit.x(), self.regionCheck.y()) # Now we move just the X after all the sizes been formed
        
        self.playerBtn.move(self.playerEdit.x() + self.playerEdit.width()/2 - self.playerBtn.width()/2, self.playerEdit.y() + self.playerBtn.height())
        
        """ Event Handling """
        self.playerBtn.clicked.connect(self.handlePlayerBtn)
        
        self.playerEdit.returnPressed.connect(self.playerBtn.click)
    
        self.regionCheck.activated[str].connect(self.handleRegionCheck)
    
    
    """ Buttons - Event Handling Methods """      
    def handleBuildsBtn(self):
        PieLegends.championBuilds(self.championEdit.text())
    
    def handleCountersBtn(self):
        PieLegends.championCounters(self.championEdit.text())
        
    def handlePlayerBtn(self):
        PieLegends.playerPie(self.playerEdit.text())
        
    """ Combo Box - Event Handling Methods """
    def handleRegionCheck(self, region):
        PieLegends.regionUpdate(region)
        
        
Beispiel #34
0
class App(QMainWindow):
    def __init__(self):
        super().__init__()
        self.title = 'Alarm'
        self.top = 10
        self.left = 10
        self.width = 500
        self.height = 600
        self.initUI()

    def initUI(self):

        dark = QColor(25, 25, 50)
        white = QColor(255, 255, 255)

        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), white)

        widgets = QWidget()
        ########################## I like my comments green! ########################
        self.select = QComboBox(self)
        self.select.move(325, 50)
        self.select.resize(125, 25)
        self.select.addItem("0:30:0")
        self.select.addItem("1:0:0")
        self.select.currentIndexChanged.connect(self.selectChange)

        self.newtimer = QPushButton(self)
        self.newtimer.move(5, 80)
        self.newtimer.setText("Add Timer")
        self.newtimer.clicked.connect(self.timer)

        self.starttimer = QPushButton(self)
        self.starttimer.move(325, 80)
        self.starttimer.setText("Start Timer")

        self.secondL = QLabel(self)
        self.secondL.move(190, 27)
        self.secondL.setText("Seconds:")

        self.minuteL = QLabel(self)
        self.minuteL.move(107, 27)
        self.minuteL.setText("Minutes:")

        self.hourl = QLabel(self)
        self.hourl.move(25, 27)
        self.hourl.setText("Hours:")

        self.hourIn = QLineEdit(self)
        self.hourIn.move(5, 50)
        self.hourIn.resize(80, 25)
        # self.hourIn.setStyleSheet("QLineEdit { background-color: rgb(25, 25, 50); color: rgb(255, 255, 255)}")

        self.minuteIn = QLineEdit(self)
        self.minuteIn.move(90, 50)
        self.minuteIn.resize(80, 25)

        self.secondIn = QLineEdit(self)
        self.secondIn.move(175, 50)
        self.secondIn.resize(80, 25)
        ######################################################################
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.setPalette(p)
        ######################################################################
        self.show()
        widgets.show()

    def selectChange(self):
        print(self.select.itemText(self.select.currentIndex()))

    def timer(self):
        h = self.hourIn.text()
        m = self.minuteIn.text()
        s = self.secondIn.text()
        if h.replace(" ", "") == "":
            h = 00
        if m.replace(" ", "") == "":
            m = 00
        if s.replace(" ", "") == "":
            s = 00
        try:
            t = (int(h) * 3600) + (int(m) * 60) + int(s)
            if t == 0:
                QMessageBox.about(
                    self, "Please fill out time",
                    "The timer must be at least one second long.")
                t = None
        except:
            self.hourIn.clear()
            self.minuteIn.clear()
            self.secondIn.clear()
            QMessageBox.about(
                self, "Wrong number type!",
                "Please type in an integer, no decimals or text! Numbers too big can also raise an error."
            )
        try:
            if t is not None:
                alarm.timer(t)
                self.select.addItem(str(h) + ":" + str(m) + ":" + str(s))
        except:
            pass
        self.hourIn.clear()
        self.minuteIn.clear()
        self.secondIn.clear()
Beispiel #35
0
    def initUI(self):

        self.homedir_init = r'S:\300-Projets_Transverses\300.56-Solflex\raman_data'
        self.homedir = r'S:\300-Projets_Transverses\300.56-Solflex\raman_data'
        self.crystalorientation = '110'
        self.ref_start = False
        self.ref_end = False
        self.time_coef = 1
        self.time_offset = 0
        self.PowerShift = 0
        #An exit action garanties you sucsesseful closing of the window(see def closeEvent)
        exitAction = QAction(QIcon('test.png'), '&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit Application')
        exitAction.triggered.connect(self.closeEvent)

        #A status bar in the left bottom corner of the window
        self.statusBar()
        self.statusBar().showMessage('Ready')

        #A button opens a dialog window to find a .tdms file(see def openTDMS)
        tdmsedit = QPushButton('Open tdms', self)
        tdmsedit.clicked.connect(self.openTDMS)
        tdmsedit.move(50, 60)

        #A line shows your .tdms file name
        self.tdmsline = QLineEdit(self)
        self.tdmsline.setReadOnly(True)
        self.tdmsline.setText('...')
        self.tdmsline.move(170, 60)

        #A button opens a dialog window to find a .txt file with Raman data(see def openRaman)
        ramanbtn = QPushButton('Open raman', self)
        ramanbtn.clicked.connect(self.openRaman)
        ramanbtn.move(50, 100)

        #A line shows your .txt file name
        self.ramanline = QLineEdit(self)
        self.ramanline.setReadOnly(True)
        self.ramanline.setText('...')
        self.ramanline.move(170, 100)

        #A button opens a dialog window to find a .txt file with Raman starting ref (see def openRefSart)
        RefStartBtn = QPushButton('Open ref start', self)
        RefStartBtn.clicked.connect(self.openRefSart)
        RefStartBtn.move(50, 300)

        #A line shows your .txt file name  for start ref
        self.RefStartLine = QLineEdit(self)
        self.RefStartLine.setReadOnly(True)
        self.RefStartLine.setText('...')
        self.RefStartLine.move(170, 300)

        #A button opens a dialog window to find a .txt file with Raman ending ref (see def openRefend)
        RefEndBtn = QPushButton('Open ref end', self)
        RefEndBtn.clicked.connect(self.openRefEnd)
        RefEndBtn.move(50, 350)

        #A line shows your .txt file name  for end ref
        self.RefEndLine = QLineEdit(self)
        self.RefEndLine.setReadOnly(True)
        self.RefEndLine.setText('...')
        self.RefEndLine.move(170, 350)

        # plot silicon strain (from .txt raman files) against macroscopic strain (from tdms file), see start function
        startbtn = QPushButton('Start!', self)
        startbtn.clicked.connect(self.start)
        startbtn.move(550, 450)

        #A tool where u can chose a crystal orientation
        cryor = QComboBox(self)
        cryor.addItems(['110', '100'])
        cryor.move(50, 140)
        cryor.activated[str].connect(self.crystalorientationset)
        self.b_uni = -337  # default value for [110] orientation

        #Group of line editers where you can see the value of length/width/thickness
        #from your .tdms file or set it manualy
        self.lenlab = QLabel(self)
        self.lenlab.setText('Length, mm')
        self.lenlab.move(450, 60)

        self.lenline = QLineEdit(self)
        self.lenline.setText('...')
        self.lenline.textChanged[str].connect(self.setLength)
        self.lenline.move(570, 60)

        self.widlab = QLabel(self)
        self.widlab.setText('Width, mm')
        self.widlab.move(450, 100)

        self.widline = QLineEdit(self)
        self.widline.setText('...')
        self.lenline.textChanged[str].connect(self.setWidth)
        self.widline.move(570, 100)

        self.thicklab = QLabel(self)
        self.thicklab.setText('Thickness, mm')
        self.thicklab.move(450, 140)

        self.thickline = QLineEdit(self)
        self.thickline.setText('...')
        self.lenline.textChanged[str].connect(self.setThick)
        self.thickline.move(570, 140)

        #text box to choose offset shift to do laser power
        self.powershift_lab = QLabel(self)
        self.powershift_lab.setText('power shift $cm^{-1}$')
        self.powershift_lab.move(450, 290)

        self.PowerShiftLine = QLineEdit(self)
        self.PowerShiftLine.setText('0')
        self.PowerShiftLine.textChanged[str].connect(self.setPowerShift)
        self.PowerShiftLine.move(570, 290)

        #text box to choose coefficient corresponding to the
        self.time_coeflab = QLabel(self)
        self.time_coeflab.setText('time coef')
        self.time_coeflab.move(450, 350)

        self.coefline = QLineEdit(self)
        self.coefline.setText('1')
        self.coefline.textChanged[str].connect(self.setTimeCoef)
        self.coefline.move(570, 350)

        #text box to choose time offset
        self.timeOffsetLab = QLabel(self)
        self.timeOffsetLab.setText('time(raman)+=')
        self.timeOffsetLab.move(450, 400)

        self.timeOffsetLine = QLineEdit(self)
        self.timeOffsetLine.setText('0')
        self.timeOffsetLine.textChanged[str].connect(self.setTimeOffset)
        self.timeOffsetLine.move(570, 400)

        #A button creates a dialog window when you can set up your home directory
        dirbtn = QPushButton('Set directory', self)
        dirbtn.clicked.connect(self.setHomeDir)
        dirbtn.move(50, 180)

        #        # Chosse x array to plot tdms values
        #        xcombo = QComboBox(self)
        #        xcombo.addItems(['Time', 'Force', 'Elongation', 'Stress'])
        #        xcombo.move(200, 220)
        #        xcombo.activated[str].connect(self.setX)
        #
        #        # choose y array to plot tdms values
        #        ycombo = QComboBox(self)
        #        ycombo.addItems(['Time', 'Force', 'Elongation', 'Stress'])
        #        ycombo.move(350, 220)
        #        ycombo.activated[str].connect(self.setY)
        #
        #        plot = QPushButton('Plot it!', self)
        #        #plot.clicked.connect(self.plotgraph(self.x, self.y))
        #        plot.move(500, 220)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&Menu')
        fileMenu.addAction(exitAction)

        self.setGeometry(300, 300, 700, 500)
        self.setWindowTitle('Raman Micromecha GUI')
        self.show()
    def home(self):

        SelectDataFileLabel = QLabel('Select Data File: ', self)
        SelectDataFileLabel.move(xPosition, yPosition)
        SelectDataFileLabel.setStyleSheet("Qlabel{font:30pt Comic Sans MS}")
        SelectDataFileLabel.setFont(QFont('Arial', 12))
        SelectDataFileLabel.resize(SelectDataFileLabel.sizeHint())

        chooseDataFilebtn = QPushButton(' Choose File ', self)
        chooseDataFilebtn.clicked.connect(self.file_open)
        chooseDataFilebtn.setFont(QFont('Arial', 12))
        chooseDataFilebtn.resize(chooseDataFilebtn.sizeHint())
        chooseDataFilebtn.move(xPosition + 120, yPosition)

        SelectDepartmentLabel = QLabel('Select Department: ', self)
        SelectDepartmentLabel.setFont(QFont('Arial', 12))
        SelectDepartmentLabel.move(xPosition, yPosition + 40)
        SelectDepartmentLabel.resize(SelectDepartmentLabel.sizeHint())

        department_List = [
            'ALL', 'Art', 'Computer Science', 'Math', 'Physics',
            'Social Science', 'Music'
        ]
        department_comboBox = QComboBox(self)
        department_comboBox.setFont(QFont('Arial', 12))
        department_comboBox.addItems(department_List)
        department_comboBox.resize(department_comboBox.sizeHint())
        department_comboBox.move(xPosition + 150, yPosition + 40)
        print(department_comboBox.currentIndex())

        SelectTargetCourse = QLabel('Select Target Course : ', self)
        SelectTargetCourse.move(xPosition + 500, yPosition + 40)
        SelectTargetCourse.setFont(QFont('Arial', 12))
        SelectTargetCourse.resize(SelectTargetCourse.sizeHint())

        self.target_courses_comboBox = QComboBox(self)
        self.target_courses_comboBox.addItems(self.courseList)
        self.target_courses_comboBox.setFont(QFont('Arial', 12))
        self.target_courses_comboBox.move(xPosition + 650, yPosition + 40)
        self.target_courses_comboBox.resize(200, 25)

        self.SelectTrainingCourses = QLabel('Select Training Courses : ', self)
        self.SelectTrainingCourses.move(xPosition, yPosition + 200)
        self.SelectTrainingCourses.setFont(QFont('Arial', 12))
        self.SelectTrainingCourses.resize(
            self.SelectTrainingCourses.sizeHint())

        self.Training_Courses_ComboBox = QComboBox(self)
        self.Training_Courses_ComboBox.move(xPosition, yPosition + 220)
        self.Training_Courses_ComboBox.setFont(QFont('Arial', 12))
        self.Training_Courses_ComboBox.resize(
            self.target_courses_comboBox.sizeHint())
        self.Training_Courses_ComboBox.resize(200, 25)

        AddTrainingCourseBtn = QPushButton('Add Training Course >>> ', self)
        AddTrainingCourseBtn.clicked.connect(self.Add_Training_Courses)
        AddTrainingCourseBtn.setFont(QFont('Arial', 12))
        AddTrainingCourseBtn.resize(AddTrainingCourseBtn.sizeHint())
        AddTrainingCourseBtn.move(xPosition, yPosition + 270)

        TrainingCoursesLabel = QLabel('Training Courses:', self)
        TrainingCoursesLabel.move(xPosition + 300, yPosition + 175)
        TrainingCoursesLabel.setFont(QFont('Arial', 12))
        TrainingCoursesLabel.resize(TrainingCoursesLabel.sizeHint())
        #self.cutomItem = QListWidgetItem('this is custom text')
        self.TrainingCourses = QListWidget(self)
        self.TrainingCourses.move(xPosition + 300, yPosition + 200)
        self.TrainingCourses.resize(300, 400)
        self.TrainingCourses.setFont(QFont('Arial', 12))

        PredictedCoursesLabel = QLabel('Predicted Courses Effect:', self)
        PredictedCoursesLabel.move(xPosition + 700, yPosition + 175)
        PredictedCoursesLabel.setFont(QFont('Arial', 12))
        PredictedCoursesLabel.resize(PredictedCoursesLabel.sizeHint())

        self.predictedCoursesListWidget = QListWidget(self)
        self.predictedCoursesListWidget.move(xPosition + 700, yPosition + 200)
        self.predictedCoursesListWidget.resize(300, 400)
        self.predictedCoursesListWidget.addItems(self.predictedCoursesWeights)
        self.predictedCoursesListWidget.setFont(QFont('Arial', 12))

        PredictedWeightsLabel = QLabel('Predicted Weights:', self)
        PredictedWeightsLabel.move(xPosition + 1000, yPosition + 175)
        PredictedWeightsLabel.setFont(QFont('Arial', 12))
        PredictedWeightsLabel.resize(PredictedWeightsLabel.sizeHint())
        self.predictedCoursesWeightWidget = QListWidget(self)
        self.predictedCoursesWeightWidget.move(xPosition + 1000,
                                               yPosition + 200)
        self.predictedCoursesWeightWidget.resize(300, 400)
        self.predictedCoursesWeightWidget.setFont(QFont('Arial', 12))
        self.predictedCoursesWeightWidget.addItems(
            self.predictedCoursesWeights)

        PredictBtn = QPushButton(' Build Weights ', self)
        PredictBtn.clicked.connect(self.Predict_Results)
        PredictBtn.clicked.connect(self.update_available_courses)
        PredictBtn.setFont(QFont('Arial', 12))
        PredictBtn.resize(PredictBtn.sizeHint())
        PredictBtn.move(xPosition + 375, yPosition + 625)

        SelectDataFileLabel = QLabel('Enter Grades Of Training Courses: ',
                                     self)
        SelectDataFileLabel.move(xPosition + 50, yPosition + 710)
        SelectDataFileLabel.setStyleSheet("Qlabel{font:30pt Comic Sans MS}")
        SelectDataFileLabel.setFont(QFont('Arial', 12))
        SelectDataFileLabel.resize(SelectDataFileLabel.sizeHint())
        # Create textbox
        self.GradeTextBox = QLineEdit(self)
        self.GradeTextBox.move(xPosition + 300, yPosition + 700)
        self.GradeTextBox.setFont(QFont('Arial', 12))
        self.GradeTextBox.resize(280, 40)

        PredictGradeBtn = QPushButton('Predict Grade', self)
        PredictGradeBtn.clicked.connect(self.Predict_Grade)
        PredictGradeBtn.move(xPosition + 375, yPosition + 750)
        PredictGradeBtn.setFont(QFont('Arial', 12))
        PredictGradeBtn.resize(PredictGradeBtn.sizeHint())

        PredictGradeHintLabel = QLabel('Predicted Grade: ', self)
        PredictGradeHintLabel.move(xPosition + 800, yPosition + 750)
        PredictGradeHintLabel.setStyleSheet("color: rgb(0,0,250);")
        PredictGradeHintLabel.setFont(QFont('Arial', 12))
        PredictGradeHintLabel.resize(PredictGradeHintLabel.sizeHint())

        self.PredictedGradeNumberLabel = QLabel('0', self)
        self.PredictedGradeNumberLabel.move(xPosition + 1000, yPosition + 750)
        self.PredictedGradeNumberLabel.setStyleSheet("color: rgb(0,0,250);")
        self.PredictedGradeNumberLabel.setFont(QFont('Arial', 12))
        self.PredictedGradeNumberLabel.resize(100, 20)

        RestartBtn = QPushButton('Reset', self)
        RestartBtn.clicked.connect(self.Restart_Prediction)
        RestartBtn.setFont(QFont('Arial', 12))
        RestartBtn.resize(RestartBtn.sizeHint())
        RestartBtn.move(xPosition + 700, yPosition + 850)

        self.show()
Beispiel #37
0
    class preferences(QWidget):
        def __init__(self, scale_factor):
            try:
                super().__init__()
            except TypeError:
                super(self.__class__, self).__init__()  # port to python2

            self.scale_factor = scale_factor
            self.config = ConfigParser.RawConfigParser()
            self.configurations = config_manager()
            self.configf = self.configurations.configf
            if os.path.exists(self.configf) is False:
                print('Config file does not exist!')
                self.configurations.config_defaults()
            self.read_defaults()
            self.initUI()

        def initUI(self):
            self.backend()
            self.codec()
            self.bitrate()
            self.samplerates()
            self.iconcolors()
            self.notifications()
            self.searchatlaunch()
            if platform == 'Linux':
                self.alsadevice()
            self.buttons()
            self.window()

        def backend(self):
            """
            Backend
            """
            backends_supported = ['node', 'ffmpeg', 'avconv', 'parec',
                                  'gstreamer']
            self.backends = []
            if platform == 'Darwin':
                for item in backends_supported:
                    if (is_installed(item, PATH, debug) is True and
                       item != 'avconv' and item != 'gstreamer'):
                        self.backends.append(item)
            else:
                for item in backends_supported:
                    if (is_installed(item, PATH, debug) is True and
                       item != 'node' and item != 'gstreamer'):
                        self.backends.append(item)
                    # hardcoded gst-launch-1.0 for gstreamer
                    elif (is_installed('gst-launch-1.0', PATH, debug) is
                          True and item == 'gstreamer'):
                        self.backends.append(item)
            try:
                backend_index = self.backends.index(self.backend_conf)
            except ValueError:
                # No backend found
                backend_index = None
                pass
            self.backend = QLabel('Select Backend', self)
            self.backend.move(20 * self.scale_factor, 24 * self.scale_factor)
            self.qcbackend = QComboBox(self)
            self.qcbackend.move(180 * self.scale_factor,
                                20 * self.scale_factor)
            self.qcbackend.setMinimumContentsLength(7)
            for item in self.backends:
                self.qcbackend.addItem(item)

            if backend_index:
                self.qcbackend.setCurrentIndex(backend_index)

            self.qcbackend.activated[str].connect(self.onActivatedbk)

        def codec(self):
            """
            Codec
            """
            self.codec = QLabel('Audio Coding Format', self)
            self.codec.move(20 * self.scale_factor, 56 * self.scale_factor)
            self.qccodec = QComboBox(self)
            self.qccodec.clear()
            if self.backend_conf == 'node':
                self.codecs = ['mp3']
            else:
                self.codecs = [
                    'mp3',
                    'ogg',
                    'aac',
                    'wav',
                    'flac'
                    ]
            if debug is True:
                print(self.codecs)
            codecindex = self.codecs.index(self.codecconf)
            self.qccodec.move(180 * self.scale_factor, 54 * self.scale_factor)
            self.qccodec.setMinimumContentsLength(7)
            for item in self.codecs:
                self.qccodec.addItem(item)
            self.qccodec.setCurrentIndex(codecindex)
            self.qccodec.activated[str].connect(self.onActivatedcc)

        def bitrate(self):
            """
            Bitrate
            """
            self.bitrate = QLabel('Select Bitrate (kbit/s)', self)
            self.bitrate.move(20 * self.scale_factor, 88 * self.scale_factor)
            self.qcbitrate = QComboBox(self)
            self.qcbitrate.clear()
            self.qcbitrate.move(180 * self.scale_factor,
                                88 * self.scale_factor)
            self.qcbitrate.setMinimumContentsLength(7)
            if self.codecconf == 'wav':
                self.bitrates = ['None']
                bitrateindex = 0
            else:
                self.bitrates = [
                    '128',
                    '160',
                    '192',
                    '224',
                    '256',
                    '320',
                    '500'
                    ]
                bitrateindex = self.bitrates.index(self.bitrateconf)
            for item in self.bitrates:
                self.qcbitrate.addItem(item)
            self.qcbitrate.setCurrentIndex(bitrateindex)
            self.qcbitrate.activated[str].connect(self.onActivatedbt)

        def samplerates(self):
            """
            Sample rate
            """
            self.samplerates = [
                '192000',
                '176400',
                '96000',
                '88200',
                '48000',
                '44100',
                '32000',
                '22050'
                ]
            sampleratesindex = self.samplerates.index(self.samplerateconf)
            self.samplerate = QLabel('Sample Rate (Hz)', self)
            self.samplerate.move(20 * self.scale_factor,
                                 120 * self.scale_factor)
            self.qcsamplerate = QComboBox(self)
            self.qcsamplerate.move(180 * self.scale_factor,
                                   120 * self.scale_factor)
            self.qcsamplerate.setMinimumContentsLength(7)
            for item in self.samplerates:
                self.qcsamplerate.addItem(item)
            self.qcsamplerate.setCurrentIndex(sampleratesindex)
            self.qcsamplerate.activated[str].connect(self.onActivatedsr)

        def iconcolors(self):
            """
            Icon colors
            """
            self.colors_list = [
                'black',
                'blue',
                'white'
                ]
            colorsindex = self.colors_list.index(self.searchcolorsconf)
            self.colors = QLabel('Icon Colors', self)
            self.colors.move(20 * self.scale_factor,
                             152 * self.scale_factor)
            self.qccolors = QComboBox(self)
            self.qccolors.move(180 * self.scale_factor,
                               152 * self.scale_factor)
            self.qccolors.setMinimumContentsLength(7)
            for item in self.colors_list:
                self.qccolors.addItem(item)
            self.qccolors.setCurrentIndex(colorsindex)
            self.qccolors.activated[str].connect(self.onActivatedcolors)

        def notifications(self):
            """
            Notifications
            """
            self.notifications_list = [
                'enabled',
                'disabled'
                ]
            notindex = self.notifications_list.index(self.notifconf)
            self.notifications = QLabel('Notifications', self)
            self.notifications.move(20 * self.scale_factor,
                                    184 * self.scale_factor)
            self.qcnotifications = QComboBox(self)
            self.qcnotifications.move(180 * self.scale_factor,
                                      184 * self.scale_factor)
            self.qcnotifications.setMinimumContentsLength(7)
            for item in self.notifications_list:
                self.qcnotifications.addItem(item)
            self.qcnotifications.setCurrentIndex(notindex)
            self.qcnotifications.activated[str].connect(self.onActivatednotify)

        def searchatlaunch(self):
            """
            Search at launch
            """
            self.atlaunch_list = [
                'enabled',
                'disabled'
                ]
            launchindex = self.atlaunch_list.index(self.satlaunchconf)
            self.atlaunch = QLabel('Search At Launch', self)
            self.atlaunch.move(20 * self.scale_factor,
                               214 * self.scale_factor)
            self.qcatlaunch = QComboBox(self)
            self.qcatlaunch.move(180 * self.scale_factor,
                                 214 * self.scale_factor)
            self.qcatlaunch.setMinimumContentsLength(7)
            for item in self.atlaunch_list:
                self.qcatlaunch.addItem(item)
            self.qcatlaunch.setCurrentIndex(launchindex)
            self.qcatlaunch.activated[str].connect(self.onActivatedatlaunch)

        def alsadevice(self):
            """
            Set the ALSA Device
            """
            self.alsadevice = QLabel('ALSA Device', self)
            self.alsadevice.move(20 * self.scale_factor,
                                 244 * self.scale_factor)
            self.qle = QLineEdit(self)
            self.qle.move(179 * self.scale_factor,
                          244 * self.scale_factor)
            self.qle.setFixedWidth(84*self.scale_factor)
            self.read_defaults()
            if self.alsadeviceconf is not None:
                self.qle.setText(self.alsadeviceconf)
            self.qle.textChanged[str].connect(self.onActivatedalsadevice)

        def buttons(self):
            """
            Buttons
            """
            resetbtn = QPushButton("Reset Settings", self)
            resetbtn.move(10 * self.scale_factor, 274 * self.scale_factor)
            resetbtn.clicked.connect(self.reset_configuration)

            faqbtn = QPushButton("FAQ", self)
            faqbtn.move(138 * self.scale_factor, 274 * self.scale_factor)
            faqbtn.clicked.connect(lambda: webbrowser.open('https://github.com/muammar/mkchromecast/wiki/FAQ'))

            donbtn = QPushButton("Donate :)", self)
            donbtn.move(204 * self.scale_factor, 274 * self.scale_factor)
            donbtn.clicked.connect(lambda: webbrowser.open('https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=RZLF7TDCAXT9Q&lc=US&item_name=mkchromecast&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted'))

        def window(self):
            """
            Geometry and window's title
            """
            self.setGeometry(300 * self.scale_factor,
                             300 * self.scale_factor,
                             300 * self.scale_factor,
                             200 * self.scale_factor)
            if platform == 'Darwin':
                # This is to fix the size of the window
                self.setFixedSize(310 * self.scale_factor,
                                  320 * self.scale_factor)
            else:
                # This is to fix the size of the window
                self.setFixedSize(282 * self.scale_factor,
                                  320 * self.scale_factor)
            self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint |
                                QtCore.Qt.WindowMinimizeButtonHint |
                                QtCore.Qt.WindowStaysOnTopHint)
            self.setWindowTitle('Mkchromecast Preferences')

            """
            Methods
            """
        def reset_configuration(self):
            self.configurations.write_defaults()
            self.reset_indexes()

        def reset_indexes(self):
            self.read_defaults()
            """
            Indexes of QCombo boxes are reset
            """
            backend_index = self.backends.index(self.backend_conf)
            codecindex = self.codecs.index(self.codecconf)
            self.bitrates = [
                '128',
                '160',
                '192',
                '224',
                '256',
                '320',
                '500'
                ]
            bitrateindex = self.bitrates.index(self.bitrateconf)
            self.qcbitrate.clear()
            for item in self.bitrates:
                self.qcbitrate.addItem(item)
            sampleratesindex = self.samplerates.index(self.samplerateconf)
            colorsindex = self.colors_list.index(self.searchcolorsconf)
            notindex = self.notifications_list.index(self.notifconf)
            launchindex = self.atlaunch_list.index(self.satlaunchconf)
            self.qcbackend.setCurrentIndex(backend_index)
            self.qccodec.setCurrentIndex(codecindex)
            self.qcbitrate.setCurrentIndex(bitrateindex)
            self.qcsamplerate.setCurrentIndex(sampleratesindex)
            self.qccolors.setCurrentIndex(colorsindex)
            self.qcnotifications.setCurrentIndex(notindex)
            self.qcatlaunch.setCurrentIndex(launchindex)

        def onActivatedbk(self, text):
            self.config.read(self.configf)
            self.config.set('settings', 'backend', text)
            self.write_config()
            self.read_defaults()
            self.qccodec.clear()
            if self.backend_conf == 'node':
                codecs = ['mp3']
                self.config.read(self.configf)
                self.config.set('settings', 'codec', 'mp3')
                self.write_config()
            else:
                codecs = [
                    'mp3',
                    'ogg',
                    'aac',
                    'wav',
                    'flac'
                    ]
            if debug is True:
                print('Codecs: %s.' % codecs)
            codecindex = codecs.index(self.codecconf)
            self.qccodec.move(180 * self.scale_factor, 54 * self.scale_factor)
            self.qccodec.setMinimumContentsLength(7)
            for item in codecs:
                self.qccodec.addItem(item)
            self.qccodec.setCurrentIndex(codecindex)
            self.qccodec.activated[str].connect(self.onActivatedcc)

        def onActivatedcc(self, text):
            self.config.read(self.configf)
            self.config.set('settings', 'codec', text)
            self.write_config()
            self.read_defaults()
            self.qcbitrate.clear()
            if self.codecconf == 'wav':
                bitrates = ['None']
                bitrateindex = 0
            else:
                self.configurations.chk_config()
                self.read_defaults()
                bitrates = [
                    '128',
                    '160',
                    '192',
                    '224',
                    '256',
                    '320',
                    '500'
                    ]
                bitrateindex = bitrates.index(self.bitrateconf)
            self.qcbitrate.move(180 * self.scale_factor,
                                88 * self.scale_factor)
            for item in bitrates:
                self.qcbitrate.addItem(item)
            self.qcbitrate.setCurrentIndex(bitrateindex)
            self.qcbitrate.activated[str].connect(self.onActivatedbt)

        def onActivatedbt(self, text):
            self.config.read(self.configf)
            self.config.set('settings', 'bitrate', text)
            self.write_config()
            self.read_defaults()

        def onActivatedsr(self, text):
            self.config.read(self.configf)
            self.config.set('settings', 'samplerate', text)
            self.write_config()
            self.read_defaults()

        def onActivatednotify(self, text):
            self.config.read(self.configf)
            self.config.set('settings', 'notifications', text)
            self.write_config()
            self.read_defaults()

        def onActivatedcolors(self, text):
            self.config.read(self.configf)
            self.config.set('settings', 'colors', text)
            self.write_config()
            self.read_defaults()

        def onActivatedatlaunch(self, text):
            self.config.read(self.configf)
            self.config.set('settings', 'searchatlaunch', text)
            self.write_config()
            self.read_defaults()

        def onActivatedalsadevice(self, text):
            self.config.read(self.configf)
            if not text:
                self.config.set('settings', 'alsadevice', None)
            else:
                self.config.set('settings', 'alsadevice', text)
            self.write_config()
            self.read_defaults()

        def read_defaults(self):
            self.backend_conf = ConfigSectionMap('settings')['backend']
            self.codecconf = ConfigSectionMap('settings')['codec']
            if self.backend_conf == 'node' and self.codecconf != 'mp3':
                self.config.read(self.configf)
                self.config.set('settings', 'codec', 'mp3')
                self.write_config()
                self.codecconf = ConfigSectionMap('settings')['codec']
            self.bitrateconf = ConfigSectionMap('settings')['bitrate']
            self.samplerateconf = ConfigSectionMap('settings')['samplerate']
            self.notifconf = ConfigSectionMap('settings')['notifications']
            self.searchcolorsconf = ConfigSectionMap('settings')['colors']
            self.satlaunchconf = ConfigSectionMap('settings')['searchatlaunch']
            self.alsadeviceconf = ConfigSectionMap('settings')['alsadevice']
            if debug is True:
                print(self.backend_conf, self.codecconf, self.bitrateconf,
                      self.samplerateconf, self.notifconf,
                      self.satlaunchconf, self.searchcolorsconf,
                      self.alsadeviceconf)

        def write_config(self):
            """This method writes to configfile"""
            with open(self.configf, 'w') as configfile:
                    self.config.write(configfile)
Beispiel #38
0
class GUI(QWidget):
    def __init__(self):
        super(GUI, self).__init__()

        self.initUI()
        self.play = Stick_game(equation=[])
        self.question_database = None

    class Digit():
        # Poverty
        # 1. show number
        # 2. possible to change certain line's color / type

        def __init__(self, loc=(0, 0)):
            self.length = 10
            self.width = 4
            self.line_gap = 1
            self.initUI(loc)
            self.num = {
                "0": [1, 1, 1, 0, 1, 1, 1],  #6
                "1": [0, 0, 1, 0, 0, 1, 0],  #2
                "2": [1, 0, 1, 1, 1, 0, 1],  #5
                "3": [1, 0, 1, 1, 0, 1, 1],  #5
                "4": [0, 1, 1, 1, 0, 1, 0],  #4
                "5": [1, 1, 0, 1, 0, 1, 1],  #5
                "6": [1, 1, 0, 1, 1, 1, 1],  #6
                "7": [1, 0, 1, 0, 0, 1, 0],  #3
                "8": [1, 1, 1, 1, 1, 1, 1],  #7
                "9": [1, 1, 1, 1, 0, 1, 1],  #6
                "None": [0, 0, 0, 0, 0, 0, 0]
            }

        def initUI(self, loc):
            """
            # number encoding order with:
            —— 1
            | 2 | 3
            —— 4
            | 5 | 6
            —— 7
            """
            def line_create():
                line = QPainter()
                line.setPen(QPen(Qt.black, 1, Qt.SolidLine))
                line.setBrush(QBrush(Qt.white, Qt.SolidPattern))
                return line

            self.line1 = QPainter(self)
            self.line1.setPen(QPen(Qt.black, 1, Qt.SolidLine))
            self.line1.setBrush(QBrush(Qt.white, Qt.SolidPattern))
            self.line1.drawRect(loc[0] + self.line_gap + self.width, loc[1],
                                self.length, self.width)

            self.line2 = QPainter(self)
            self.line2.setPen(QPen(Qt.black, 1, Qt.SolidLine))
            self.line2.setBrush(QBrush(Qt.white, Qt.SolidPattern))
            self.line2.drawRect(loc[0], loc[1] + self.line_gap, self.width,
                                self.length)

            self.line3 = QPainter(self)
            self.line3.setPen(QPen(Qt.black, 1, Qt.SolidLine))
            self.line3.setBrush(QBrush(Qt.white, Qt.SolidPattern))
            self.line3.drawRect(
                loc[0] + 2 * self.line_gap + self.length + self.width,
                loc[1] + self.line_gap, self.width, self.length)

            self.line4 = QPainter(self)
            self.line4.setPen(QPen(Qt.black, 1, Qt.SolidLine))
            self.line4.setBrush(QBrush(Qt.white, Qt.SolidPattern))
            self.line4.drawRect(
                loc[0] + self.line_gap + self.width,
                loc[1] + 2 * self.line_gap + self.length + self.width,
                self.length, self.width)

            self.line5 = QPainter(self)
            self.line5.setPen(QPen(Qt.black, 1, Qt.SolidLine))
            self.line5.setBrush(QBrush(Qt.white, Qt.SolidPattern))
            self.line5.drawRect(
                loc[0],
                loc[1] + 3 * self.line_gap + self.length + 2 * self.width,
                self.width, self.length)

            self.line6 = QPainter(self)
            self.line6.setPen(QPen(Qt.black, 1, Qt.SolidLine))
            self.line6.setBrush(QBrush(Qt.white, Qt.SolidPattern))
            self.line6.drawRect(
                loc[0] + 2 * self.line_gap + self.length + self.width,
                loc[1] + 3 * self.line_gap + self.length + 2 * self.width,
                self.width, self.length)

            self.line7 = QPainter(self)
            self.line7.setPen(QPen(Qt.black, 1, Qt.SolidLine))
            self.line7.setBrush(QBrush(Qt.white, Qt.SolidPattern))
            self.line7.drawRect(
                loc[0] + self.line_gap + self.width,
                loc[1] + 4 * self.line_gap + 2 * self.length + 2 * self.width,
                self.length, self.width)
            self.lines = [
                self.line1, self.line2, self.line3, self.line4, self.line5,
                self.line6, self.line7
            ]

    def initUI(self):

        QToolTip.setFont(QFont('SansSerif', 10))

        # question input
        title = QLabel(self)
        title.setText('题目输入:')
        title.move(50, 50)
        hint_in = QLabel(self)
        hint_in.setText('原题:')
        hint_in.move(20, 125)
        hint_out = QLabel(self)
        hint_out.setText('题解:')
        hint_out.move(20, 225)
        self.number1 = QLineEdit(self)
        self.number1.resize(75, 30)
        self.number1.move(150, 50)
        self.number1.textChanged[str].connect(
            lambda: self.number_update_display(self.number1.text(), 1))
        self.digit1_1 = QLabel(self)
        self.digit1_1.resize(64, 64)
        self.digit1_1.move(100, 100)
        self.digit1_2 = QLabel(self)
        self.digit1_2.resize(64, 64)
        self.digit1_2.move(150, 100)
        self.digit1_1_ans = QLabel(self)
        self.digit1_1_ans.resize(64, 64)
        self.digit1_1_ans.move(100, 200)
        self.digit1_2_ans = QLabel(self)
        self.digit1_2_ans.resize(64, 64)
        self.digit1_2_ans.move(150, 200)

        self.op1 = QComboBox(self)
        self.op1.move(250, 50)
        self.op1.addItems([' ', '+', '-', 'x', '='])
        self.op1.currentIndexChanged[str].connect(
            lambda: self.op_update_display(self.op1.currentText(), 1))
        # self.op1.highlighted[str].connect(lambda: self.op_update_display(self.op1.activated[str], 1))
        self.op1_show = QLabel(self)
        self.op1_show.resize(32, 32)
        self.op1_show.move(225, 120)
        self.op_show(self.op1.currentText(), self.op1_show)
        self.op1_show_ans = QLabel(self)
        self.op1_show_ans.resize(32, 32)
        self.op1_show_ans.move(225, 220)

        self.number2 = QLineEdit(self)
        self.number2.resize(75, 30)
        self.number2.move(320, 50)
        self.number2.textChanged[str].connect(
            lambda: self.number_update_display(self.number2.text(), 2))
        self.digit2_1 = QLabel(self)
        self.digit2_1.resize(64, 64)
        self.digit2_1.move(265, 100)
        self.digit2_2 = QLabel(self)
        self.digit2_2.resize(64, 64)
        self.digit2_2.move(315, 100)
        self.digit2_1_ans = QLabel(self)
        self.digit2_1_ans.resize(64, 64)
        self.digit2_1_ans.move(265, 200)
        self.digit2_2_ans = QLabel(self)
        self.digit2_2_ans.resize(64, 64)
        self.digit2_2_ans.move(315, 200)

        self.op2 = QComboBox(self)
        self.op2.move(420, 50)
        self.op2.addItems([' ', '+', '-', 'x', '='])
        self.op2.currentIndexChanged[str].connect(
            lambda: self.op_update_display(self.op2.currentText(), 2))
        # self.op2.highlighted[str].connect(lambda: self.op_update_display(self.op2.activated[str], 2))
        self.op2_show = QLabel(self)
        self.op2_show.resize(32, 32)
        self.op2_show.move(400, 120)
        self.op_show(self.op2.currentText(), self.op2_show)
        self.op2_show_ans = QLabel(self)
        self.op2_show_ans.resize(32, 32)
        self.op2_show_ans.move(400, 220)

        self.number3 = QLineEdit(self)
        self.number3.resize(75, 30)
        self.number3.move(490, 50)
        self.number3.textChanged[str].connect(
            lambda: self.number_update_display(self.number3.text(), 3))
        self.digit3_1 = QLabel(self)
        self.digit3_1.resize(64, 64)
        self.digit3_1.move(450, 100)
        self.digit3_2 = QLabel(self)
        self.digit3_2.resize(64, 64)
        self.digit3_2.move(500, 100)
        self.digit3_1_ans = QLabel(self)
        self.digit3_1_ans.resize(64, 64)
        self.digit3_1_ans.move(450, 200)
        self.digit3_2_ans = QLabel(self)
        self.digit3_2_ans.resize(64, 64)
        self.digit3_2_ans.move(500, 200)

        # Button 1: BFS Move One
        btn1 = QPushButton('一步法', self)
        btn1.clicked.connect(self.Solution_Step_One)
        btn1.resize(btn1.sizeHint())
        btn1.move(50, 300)

        # Button 2: BFS Move Two
        btn2 = QPushButton('两步法', self)
        btn2.clicked.connect(self.Solution_Step_Two)
        btn2.resize(btn2.sizeHint())
        btn2.move(200, 300)

        # Button 3: Question Generation 1
        btn3 = QPushButton('生成一步问题', self)
        btn3.clicked.connect(self.Generation_Step_One)
        btn3.resize(btn3.sizeHint())
        btn3.move(350, 300)

        # Button 4: Question Generation 4
        btn4 = QPushButton('生成两步问题', self)
        btn4.clicked.connect(self.Generation_Step_Two)
        btn4.resize(btn4.sizeHint())
        btn4.move(525, 300)

        # Button 5: Answer Question from file
        btn5 = QPushButton('从库中选择问题', self)
        btn5.clicked.connect(self.Question_from_Database)
        btn5.resize(btn5.sizeHint())
        btn5.move(600, 50)

        # Button 6: Quit
        qbtn = QPushButton('退出', self)
        qbtn.clicked.connect(QCoreApplication.instance().quit)
        qbtn.resize(qbtn.sizeHint())
        qbtn.move(700, 300)

        # Background
        palette1 = QPalette()
        palette1.setBrush(self.backgroundRole(),
                          QBrush(QPixmap('./image/bg.jpg')))
        self.setPalette(palette1)
        self.setAutoFillBackground(True)

        self.center()
        self.resize(800, 400)
        # self.setGeometry(300, 300, 900, 400) # 900*400
        self.setWindowTitle('Stick Game')
        self.setWindowIcon(QIcon('./image/ICON.png'))

        self.show()

    def digit_show(self, number, label):
        # https://www.iconfont.cn/collections/detail?spm=a313x.7781069.0.da5a778a4&cid=1108
        if number == None:
            label.clear()
        else:
            png = QPixmap('./image/%d.png' % number)
            png = png.scaled(64, 64)
            label.setPixmap(png)

    def op_show(self, op, label):
        # https://www.iconfont.cn/collections/detail?spm=a313x.7781069.0.da5a778a4&cid=18915
        if op != ' ':
            if op == '+':
                img_path = r'./image/add.png'
            elif op == '-':
                img_path = r'./image/sub.png'
            elif op == 'x':
                img_path = r'./image/mul.png'
            else:
                img_path = r'./image/equal.png'
            png = QPixmap(img_path)
            png = png.scaled(32, 32)
            label.setPixmap(png)
        else:
            label.clear()

    def center(self):

        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def closeEvent(self, event):

        reply = QMessageBox.question(self, '提示', "即将退出程序",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.Yes)

        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def op_update_display(self, op, op_index, is_ans=False):
        if not is_ans:
            if op_index == 1:
                op_show_label = self.op1_show
            else:
                op_show_label = self.op2_show
        else:
            if op_index == 1:
                op_show_label = self.op1_show_ans
            else:
                op_show_label = self.op2_show_ans
        self.op_show(op, op_show_label)

    def number_update_display(self, number, number_index, is_ans=False):
        if not is_ans:
            if number_index == 1:
                show_digit1 = self.digit1_1
                show_digit2 = self.digit1_2
            elif number_index == 2:
                show_digit1 = self.digit2_1
                show_digit2 = self.digit2_2
            else:
                show_digit1 = self.digit3_1
                show_digit2 = self.digit3_2
        else:
            if number_index == 1:
                show_digit1 = self.digit1_1_ans
                show_digit2 = self.digit1_2_ans
            elif number_index == 2:
                show_digit1 = self.digit2_1_ans
                show_digit2 = self.digit2_2_ans
            else:
                show_digit1 = self.digit3_1_ans
                show_digit2 = self.digit3_2_ans
        if number is not None:
            try:
                number = int(number)
                if number > 99:
                    reply = QMessageBox.information(self, '提示', "请输入两位数字",
                                                    QMessageBox.Ok,
                                                    QMessageBox.Ok)
                elif number > 9:
                    # number 2 digits
                    digit1 = number // 10
                    digit2 = number - digit1 * 10
                    self.digit_show(digit1, show_digit1)
                    self.digit_show(digit2, show_digit2)
                else:
                    self.digit_show(None, show_digit1)
                    self.digit_show(number, show_digit2)
            except:
                # clear!
                self.digit_show(None, show_digit1)
                self.digit_show(None, show_digit2)
                print('None')
        else:
            # clear!
            self.digit_show(None, show_digit1)
            self.digit_show(None, show_digit2)
            print('None')

    def Solution_Step_One(self):
        self.play.equation_update([
            '%d' % int(self.number1.text()),
            self.op1.currentText(),
            '%d' % int(self.number2.text()),
            self.op2.currentText(),
            '%d' % int(self.number3.text())
        ])
        ans = self.play.One_Stick()
        self.solution_info(ans)

    def Solution_Step_Two(self):
        self.play.equation_update([
            '%d' % int(self.number1.text()),
            self.op1.currentText(),
            '%d' % int(self.number2.text()),
            self.op2.currentText(),
            '%d' % int(self.number3.text())
        ])
        ans = self.play.Two_Stick()
        self.solution_info(ans)

    def solution_info(self, ans):
        if not ans:
            QMessageBox.information(self, '抱歉', "当前条件下,此问题没有解法",
                                    QMessageBox.Ok, QMessageBox.Ok)
            self.number_update_display(None, 1, is_ans=True)
            self.number_update_display(None, 2, is_ans=True)
            self.number_update_display(None, 3, is_ans=True)
            self.op_update_display(' ', 1, is_ans=True)
            self.op_update_display(' ', 2, is_ans=True)
        else:
            if len(ans) > 1:
                QMessageBox.information(self, '提示',
                                        "已找到%d个解\n将随机选择答案显示" % len(ans),
                                        QMessageBox.Ok, QMessageBox.Ok)
                answer = ans[randrange(len(ans))]
            else:
                QMessageBox.information(self, '提示', "已找到1个解", QMessageBox.Ok,
                                        QMessageBox.Ok)
                answer = ans[0]
            print(answer)
            self.number_update_display(int(answer[0]), 1, is_ans=True)
            self.number_update_display(int(answer[2]), 2, is_ans=True)
            self.number_update_display(int(answer[4]), 3, is_ans=True)
            self.op_update_display(answer[1], 1, is_ans=True)
            self.op_update_display(answer[3], 2, is_ans=True)

    def Generation_Ground_truth(self):
        reply = QMessageBox.question(self, '提示',
                                     "若以当前输入等式为答案生成问题,请选Yes\n否则,随机生成答案与问题",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)

        if reply == QMessageBox.Yes:
            if self.number1.text() and self.number2.text(
            ) and self.number3.text():
                tmp_equation = [
                    '%d' % int(self.number1.text()),
                    self.op1.currentText(),
                    '%d' % int(self.number2.text()),
                    self.op2.currentText(),
                    '%d' % int(self.number3.text())
                ]
                if self.play.equation_satisfy(tmp_equation):
                    return tmp_equation
                else:
                    QMessageBox.warning(self, '注意',
                                        "当前输入等式不满足,无法将其作为答案\n现在随机生成",
                                        QMessageBox.Ok, QMessageBox.Ok)
                    return None
            else:
                QMessageBox.warning(self, '注意', "当前输入等式不满足,无法将其作为答案\n现在随机生成",
                                    QMessageBox.Ok, QMessageBox.Ok)
                return None
        else:
            return None

    def Generation_Step_One(self):
        given_equation = self.Generation_Ground_truth()
        questions, equation_true = self.play.question_generate(
            is_generate_two=False, given_equation=given_equation)
        self.question_show = Question_GUI(parent=None,
                                          ans=equation_true,
                                          questions=questions)

    def Generation_Step_Two(self):
        given_equation = self.Generation_Ground_truth()
        questions, equation_true = self.play.question_generate(
            is_generate_two=True, given_equation=given_equation)
        self.question_show = Question_GUI(parent=None,
                                          ans=equation_true,
                                          questions=questions)

    def Question_from_Database(self):
        if not self.question_database:
            with open('questions.txt', 'r') as f:
                self.question_database = f.readlines()
        self.question = self.question_database[randrange(
            len(self.question_database))]
        print(" >> Random pick question as " + self.question)

        def op_set(op, loc):
            index = loc.findText(op, Qt.MatchFixedString)
            if index >= 0:
                loc.setCurrentIndex(index)

        # string to list
        self.question = self.question.replace('[', '')
        self.question = self.question.replace(']', '')
        self.question = self.question.replace("'", '')
        self.question = self.question.replace(" ", '')
        self.question = self.question.split(",")
        self.number1.setText(self.question[0])
        op_set(self.question[1], self.op1)
        self.number2.setText(self.question[2])
        op_set(self.question[3], self.op2)
        self.number3.setText(self.question[4])
        self.play.equation_update(self.question)
Beispiel #39
0
class MainWindow(QMainWindow):

    """Main Window Class

    Following class contains several public functions to implement GUI of the app.

    """

    def __init__(self):

        """Initialize Function

        Following function creates main window and executes all other initialization functions.

        Args:
            QMainWindow object: main window of the app.

        Returns:
            None

        """

        super().__init__()

        self.resize(600, 200)
        self.init_ui()
        self.setStyleSheet(__style__)

        self.show()

    def init_ui(self):

        """Initialize User Interface Function

        Following function executes all other initialization functions, defining whole look of the app.

        Args:
            QMainWindow object: main window of the app.

        Returns:
            None

        """

        self.init_combo_box()
        self.init_text_edit()
        self.init_push_button()

    def init_combo_box(self):

        """Initialize Combo Boxes Function

        Following function defines all of the combo boxes of the app.

        Args:
            QMainWindow object: main window of the app.

        Returns:
            None

        """

        self.adjust_query = QComboBox(self)
        self.adjust_query.resize(200, 40)
        self.adjust_query.move(150, 140)

    def init_text_edit(self):

        """Initialize Text Edits Function

        Following function defines all of the text edits of the app.

        Args:
            QMainWindow object: main window of the app.

        Returns:
            None

        """

        self.russian_text_edit = QTextEdit(self)
        self.russian_text_edit.setPlaceholderText('Введите термин')
        self.russian_text_edit.setStyleSheet(__style__)
        self.russian_text_edit.resize(250, 100)
        self.russian_text_edit.move(20, 20)

        self.english_text_edit = QTextEdit(self)
        self.english_text_edit.setPlaceholderText('Enter term')
        self.english_text_edit.setStyleSheet(__style__)
        self.english_text_edit.resize(250, 100)
        self.english_text_edit.move(330, 20)

    def init_push_button(self):

        """Initialize Buttons Function

        Following function defines all of the buttons of the app.

        Args:
            QMainWindow object: main window of the app.

        Returns:
            None

        """

        self.translate_to_english_button = QPushButton('>', self)
        self.translate_to_english_button.clicked.connect(self.translate_to_english_button_clicked)
        self.translate_to_english_button.resize(20, 20)
        self.translate_to_english_button.move(290, 40)

        self.translate_to_russian_button = QPushButton('<', self)
        self.translate_to_russian_button.clicked.connect(self.translate_to_russian_button_clicked)
        self.translate_to_russian_button.resize(20, 20)
        self.translate_to_russian_button.move(290, 80)

        self.adjust_query_button = QPushButton('Adjust query', self)
        self.adjust_query_button.clicked.connect(self.adjust_query_button_clicked)
        self.adjust_query_button.resize(100, 30)
        self.adjust_query_button.move(370, 140)

    def translate_to_english_button_clicked(self):

        """Translate to English Button Clicked Function

        Following function implements logic, executing when user wants to translate term into English.

        Args:
            QMainWindow object: main window of the app.

        Returns:
            None

        """

        term = self.russian_text_edit.toPlainText()
        self.language = 'ru'
        search_result = Translator.search_user_term(term, self.language)

        if Translator.translate_user_term(term, self.language)[0] == '0':
            self.adjust_query.clear()
            for i in range(len(search_result)):
                self.adjust_query.addItem(search_result[i])
            term = self.adjust_query.currentText()
            self.english_text_edit.setText(Translator.translate_user_term(term, self.language)[1:])
        else:
            QMessageBox.warning(self, 'Error', Translator.translate_user_term(term, self.language)[1:], QMessageBox.Ok)

    def translate_to_russian_button_clicked(self):

        """Translate to Russian Button Clicked Function

        Following function implements logic, executing when user wants to translate term into Russian.

        Args:
            QMainWindow object: main window of the app.

        Returns:
            None

        """

        term = self.english_text_edit.toPlainText()
        self.language = 'en'
        search_result = Translator.search_user_term(term, self.language)

        if Translator.translate_user_term(term, self.language)[0] == '0':
            self.adjust_query.clear()
            for i in range(len(search_result)):
                self.adjust_query.addItem(search_result[i])
            term = self.adjust_query.currentText()
            self.russian_text_edit.setText(Translator.translate_user_term(term, self.language)[1:])
        else:
            QMessageBox.warning(self, 'Error', Translator.translate_user_term(term, self.language)[1:], QMessageBox.Ok)

    def adjust_query_button_clicked(self):

        """Adjust Query Button Clicked Function

        Following function implements logic, executing when user wants to adjust query.

        Args:
            QMainWindow object: main window of the app.

        Returns:
            None

        """

        try:
            term = self.adjust_query.currentText()
            adjust_language = self.language
            search_result = Translator.search_user_term(term, adjust_language)

            if Translator.translate_user_term(term, adjust_language)[0] == '0':
                if adjust_language == 'en':
                    self.russian_text_edit.setText(Translator.translate_user_term(term, adjust_language)[1:])
                else:
                    self.english_text_edit.setText(Translator.translate_user_term(term, adjust_language)[1:])
            else:
                QMessageBox.warning(self, 'Error', Translator.translate_user_term(term, adjust_language)[1:], QMessageBox.Ok)
        except UnboundLocalError:
            QMessageBox.warning(self, 'Error', 'Input term to translate first', QMessageBox.Ok)
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.setMinimumSize(QSize(950, 610))
        self.setWindowTitle("Tanks and Alliances Tool")

        oImage = QImage("tank2.jpg")
        sImage = oImage.scaled(QSize(950, 610))  # resize Image to widgets size
        palette = QPalette()
        palette.setBrush(10, QBrush(sImage))  # 10 = Windowrole
        self.setPalette(palette)

        self.combo_label = QLabel(self)
        self.combo_label.setText('Graph type:')
        self.combo_label.move(20, 40)

        self.combo = QComboBox(self)
        self.combo.addItem("All Tanks")
        self.combo.addItem("All Alliances")
        self.combo.resize(150, 32)
        self.combo.move(130, 40)
        self.combo.activated[str].connect(self.onActivated)

        self.core_label = QLabel(self)
        self.core_label.setText('Cores:')
        self.core_label.move(20, 80)

        self.core_val = QLineEdit(self)
        self.core_val.move(130, 80)
        self.core_val.resize(150, 32)

        self.year_label = QLabel(self)
        self.year_label.setText('Alliances from:')
        self.year_label.move(20, 120)

        self.year_val = QLineEdit(self)
        self.year_val.move(130, 120)
        self.year_val.resize(150, 32)

        self.country_label = QLabel(self)
        self.country_label.setText('Country name:')
        self.country_label.move(370, 120)

        self.country_name = QLineEdit(self)
        self.country_name.move(480, 120)
        self.country_name.resize(150, 32)

        self.but_allie = QPushButton('Generate graph', self)
        self.but_allie.clicked.connect(self.clickMethodAllie)
        self.but_allie.resize(150, 32)
        self.but_allie.move(130, 160)

        self.but_tanks_for_country = QPushButton('Draw for country', self)
        self.but_tanks_for_country.clicked.connect(self.clickMethodCountry)
        self.but_tanks_for_country.resize(150, 32)
        self.but_tanks_for_country.move(480, 160)
        # --------------------------------------------------------------------------
        self.cb = QCheckBox('Generate more', self)
        self.cb.resize(150, 32)
        self.cb.move(20, 10)
        self.cb.toggle()
        self.cb.stateChanged.connect(self.changeTitle)
        # --------------------------------------------------------------------------
        self.check_1 = QCheckBox('Tanks distribution', self)
        self.check_1.resize(350, 32)
        self.check_1.toggle()
        self.check_1.move(370, 20)

        self.check_2 = QCheckBox('Number of all tanks of allies', self)
        self.check_2.resize(350, 32)
        self.check_2.toggle()
        self.check_2.move(370, 40)

        self.check_3 = QCheckBox('Number of all tanks of tank sellers', self)
        self.check_3.resize(380, 32)
        self.check_3.toggle()
        self.check_3.move(370, 60)

        self.combo_tanks = QComboBox(self)
        _, tank_names = zip(*sql.get_popular_tanks_by_number_of_owners(
            min_pop=3))
        for t in tank_names:
            self.combo_tanks.addItem(t)
        self.combo_tanks.resize(150, 32)
        self.combo_tanks.move(780, 120)

        self.tank_label = QLabel(self)
        self.tank_label.setText('Tank type:')
        self.tank_label.resize(150, 32)
        self.tank_label.move(700, 120)

        self.but_countries_for_tanks = QPushButton('Draw for tank', self)
        self.but_countries_for_tanks.clicked.connect(self.clickMethodTank)
        self.but_countries_for_tanks.resize(150, 32)
        self.but_countries_for_tanks.move(780, 160)

        # self.btn = QPushButton('Try me!', self)
        # self.btn.clicked.connect(self.onClick)
        # self.btn.resize(150, 32)
        # self.btn.move(500, 500)

    def onClick(self):
        self.SW = SecondWindow()
        self.SW.show()

    def changeTitle(self, state):

        if state == Qt.Checked:
            self.setWindowTitle('QCheckBox')
        else:
            self.setWindowTitle(' ')

    def clickMethodAllie(self):

        print('test: ' + self.country_name.text())
        print('test: ' + self.year_val.text())
        print('test: ' + self.combo.currentText())
        print('test: ' + self.core_val.text())

        if self.combo.currentText() == 'All Alliances':
            start_year = 0
            alliances = []
            if self.year_val.text():
                try:
                    start_year = int(self.year_val.text())
                except:
                    QMessageBox.about(self, 'Wrong input!',
                                      'Year number has to be an integer.')
                    return
            for res in session.query(Alliance.name_1, Alliance.name_2).filter(
                    Alliance.start_year >= start_year).all():
                alliances.append(res)
            G_allies = nx.Graph()
            G_allies.add_edges_from(alliances)
            G_allies = G_allies.to_undirected()

            if self.core_val.text():
                try:
                    G_allies = nx.k_core(G_allies, k=int(self.core_val.text()))
                except:
                    QMessageBox.about(self, 'Wrong input!',
                                      'Core size has to be an integer.')
            gd.draw_alliance(G_allies)

        elif self.combo.currentText() == 'All Tanks':
            seller_buyers = []

            for res in session.query(Tank.owner_name, Tank.seller_name).all():
                seller_buyers.append(res)
            G_sell_buy = nx.Graph()
            G_sell_buy.add_edges_from(seller_buyers)
            G_sell_buy = G_sell_buy.to_undirected()

            if self.core_val.text():
                G_sell_buy.remove_edges_from(nx.selfloop_edges(G_sell_buy))

                try:
                    G_sell_buy = nx.k_core(G_sell_buy,
                                           k=int(self.core_val.text()))
                except:
                    QMessageBox.about(self, 'Wrong input!',
                                      'Core size has to be an integer.')
            gd.draw_tanks(G_sell_buy)

    def clickMethodCountry(self):

        print('test: ' + self.country_name.text())
        print('test: ' + self.year_val.text())
        print('test: ' + self.combo.currentText())

        if self.country_name.text():
            try:
                if self.check_1.isChecked():
                    sql.get_tanks(self.country_name.text(), session)
                if self.check_2.isChecked():
                    sql.get_sum_of_tanks_from_allies(self.country_name.text(),
                                                     session)
                if self.check_3.isChecked():
                    sql.get_tank_sellers_tank_sum(self.country_name.text(),
                                                  session)
            except:
                QMessageBox.about(self, 'Wrong input!',
                                  'Try to change the country name.')

    def clickMethodTank(self):

        tank_name = self.combo_tanks.currentText()
        sql.get_countries_with_tank(tank_name)

    def onActivated(self, text):
        print(text)
        if text == 'All Tanks':
            self.year_val.setEnabled(False)
        else:
            self.year_val.setEnabled(True)
Beispiel #41
0
class Interface(QWidget):
    ports = []
    selectedPort = pyqtSignal(str)
    refresh = pyqtSignal()
    angle = pyqtSignal(int)

    def __init__(self, ports):
        super().__init__()
        self.ports = ports
        self.initUI()

    def initUI(self):
        self.combo = QComboBox(self)
        self.combo.move(10, 10)
        self.combo.activated[str].connect(self.onActivated)

        refresh = QPushButton("Refresh", self)
        refresh.move(10, 40)
        refresh.clicked.connect(self.refreshClicked)

        # sld = QSlider(Qt.Horizontal, self)
        # sld.setFocusPolicy(Qt.NoFocus)
        # sld.setGeometry(30, 40, 150, 30)

        sld = QDial(self)
        sld.setRange(0, 360)
        sld.move(10, 70)
        sld.valueChanged[int].connect(self.changeValue)

        self.motorAngle = QLabel("Angle: 000", self)
        self.motorAngle.move(120, 110)

        self.status = QLabel("Select a COM", self)
        self.status.move(10, 180)

        self.setGeometry(200, 200, 200, 200)
        self.setWindowTitle("Motor Control")

        self.combo.addItem("Connect/Refresh")
        self.show()
        self.addPorts()

        self.positionGraph = AnalogPosition()
        self.positionGraph.show()

    def isConnected(self, connected):
        if connected:
            self.status.setText("Connected")
        else:
            self.status.setText("Disconnected - Refresh and select a COM")

    def changeValue(self, value):
        print("Send: ", value)
        self.angle.emit(value)

    def refreshClicked(self):
        self.refresh.emit()

    def onActivated(self, text):
        self.selectedPort.emit(text)
        # ser = serial.Serial(text, 9600)
        # if not ser.isOpen():
        #     ser.open()
        # self.status.setText(str(ser.isOpen()))
        # self.status.adjustSize()

    def addPorts(self):
        # self.removeWidget(combo)
        # self.combo.deleteLater()
        # self.combo = QComboBox(self)
        self.combo.clear()
        for next in self.ports:
            self.combo.addItem(next)

    def setPorts(self, ports):
        self.ports = ports
        self.addPorts()

    def setAngle(self, angle):
        self.motorAngle.setText("Angle: " + str(angle))
        self.positionGraph.setAngle(angle)
class Ui_basic(QWidget):
    def __init__(self):
        super().__init__()
        self.model = None

    def initUI(self):
        self.resize(1200, 700)

        self.pic_list = [
            'maze7_1', 'maze7_2', 'maze7_3', 'maze10_1', 'maze10_2', 'maze10_3'
        ]
        self.timer = QBasicTimer()
        widget1 = QWidget(parent=self)
        widget1.setGeometry(QRect(30, 50, 800, 500))
        table_area = QGroupBox(parent=widget1)  #图形显示区域
        table_area.setGeometry(
            QRect(widget1.x(), widget1.y(), widget1.width(), widget1.height()))

        self.Plot = Draw_ui(width=3, height=3, dpi=100)
        gridlayout1 = QGridLayout(table_area)  # 继承容器groupBox
        gridlayout1.addWidget(self.Plot, 0, 1)

        pic_choose_label = QLabel(self)
        pic_choose_label.move(table_area.x() + table_area.width() + 30,
                              table_area.y() + 20)
        pic_choose_label.setText("选择迷宫:")
        self.pic_choose_combo = QComboBox(self)
        self.pic_choose_combo.move(
            pic_choose_label.geometry().x() +
            pic_choose_label.geometry().width() + 30,
            pic_choose_label.geometry().y())
        self.pic_choose_combo.resize(150,
                                     self.pic_choose_combo.geometry().height())
        self.pic_choose_combo.addItems(self.pic_list)
        self.pic_choose_combo.currentIndexChanged.connect(self.pic_change)
        self.pic_change()

        middle_x = (pic_choose_label.geometry().x() +
                    self.pic_choose_combo.geometry().x() +
                    self.pic_choose_combo.geometry().width()) / 2

        self.playing_index = -1
        self.problem_solving = False

        self.solve_problem_button = QPushButton(parent=self)
        self.solve_problem_button.setText("训练(可跳过训练)")
        self.solve_problem_button.move(
            middle_x - self.solve_problem_button.width() / 2,
            self.pic_choose_combo.y() + self.pic_choose_combo.height() + 100)
        self.solve_problem_button.pressed.connect(self.solve_button_pressed)

        self.solve_test = QLabel(parent=self)  # 解答过程中的信息显示
        self.solve_test.setText("正在训练。。。")
        self.solve_test.resize(400, self.solve_test.height())
        self.solve_test.setFont(QFont("Fixed", 7))
        self.solve_test.move(
            middle_x - self.solve_test.geometry().width() / 2,
            self.solve_problem_button.geometry().y() +
            self.solve_problem_button.geometry().height() + 20)
        self.solve_test.setHidden(True)

        speed_choose_label = QLabel(self)
        speed_choose_label.move(self.solve_test.x() + 20,
                                self.solve_test.geometry().y() + 40)
        speed_choose_label.setText("播放速度:")
        self.play_speed_combo = QComboBox(self)
        self.play_speed_combo.move(
            speed_choose_label.geometry().x() +
            speed_choose_label.geometry().width() + 30,
            speed_choose_label.geometry().y())
        self.play_speed_combo.addItems(["高速", "中速", "慢速"])

        play_button = QPushButton(self)
        play_button.setText("播放走迷宫过程")
        play_button.move(
            middle_x - play_button.geometry().width() / 2,
            self.play_speed_combo.geometry().y() +
            self.play_speed_combo.geometry().height() + 40)
        play_button.pressed.connect(self.play_button_pressed)

    def pic_change(self):
        self.timer.stop()
        current_text = self.pic_choose_combo.currentText()
        maze = Mazes[current_text]
        my_maze = Maze(maze_map=np.array(maze), period=2)
        self.model = QTableModel(my_maze)

        try:
            self.model.load_table('saved_qtable/' + current_text + '.npy')
        except:
            QMessageBox.information(self, "提示", "没找到Q表保存文件",
                                    QMessageBox.Ok | QMessageBox.Close,
                                    QMessageBox.Close)

        self.model.play_game((0, 0), 0)
        self.Plot.draw_root(self.model.my_maze, (0, 0), 1, 0, False)
        self.Plot.draw_qtable(qtable_model=self.model,
                              time_=self.model.my_maze.period -
                              1 if self.model.my_maze.period != 0 else 0,
                              fire_flag=True)

    def play_button_pressed(self):
        if self.model == None:
            QMessageBox.information(self, "提示", "请先选择迷宫",
                                    QMessageBox.Ok | QMessageBox.Close,
                                    QMessageBox.Close)
            return

        self.model.play_game((0, 0), 0)
        speed_text = self.play_speed_combo.currentText()
        self.playing_index = 0
        if speed_text == "高速":
            self.timer.start(150, self)
        elif speed_text == "中速":
            self.timer.start(500, self)
        else:
            self.timer.start(1500, self)

    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            period = self.model.my_maze.period
            if period != 0 and (self.playing_index % period) >= period / 2:
                fire_flag = True
            else:
                fire_flag = False

            self.Plot.draw_qtable(
                self.model, self.playing_index % period if period != 0 else 0,
                fire_flag)
            self.Plot.draw_root(self.model.my_maze, (0, 0), self.playing_index,
                                period, fire_flag)

            self.playing_index = self.playing_index + 1

            if self.playing_index >= len(self.model.my_maze.visited) + 2:
                self.playing_index = 0
                # print("up",self.playing_index)
        else:
            super(Ui_basic, self).timerEvent(event)

    def solve_button_pressed(self):
        if self.problem_solving:
            return
        if type(self.model) == type(None):
            QMessageBox.information(self, "提示", "请先选择迷宫",
                                    QMessageBox.Ok | QMessageBox.Close,
                                    QMessageBox.Close)
            return

        self.problem_solving = True
        self.playing_index = -1
        self.solve_test.setHidden(False)
        self.timer.stop()
        self.repaint()

        start_time = time.time()
        #path = "tangrams\\" + self.parent().pic_choose_combo.currentText() + ".png"
        self.model.train(output_line=self.solve_test, main_ui=self)
        end_time = time.time()

        QMessageBox.information(self, "提示",
                                "完成训练,用时:%.3f s" % (end_time - start_time),
                                QMessageBox.Ok | QMessageBox.Close,
                                QMessageBox.Close)

        self.Plot.draw_qtable(qtable_model=self.model,
                              time_=self.model.my_maze.period -
                              1 if self.model.my_maze.period != 0 else 0,
                              fire_flag=True)
        self.problem_solving = False
        self.solve_test.setHidden(True)
class App(QMainWindow):
    def __init__(self):
        super().__init__()
        self.fileNameInput = None
        self.fileNameLabel = None
        self.focalInpput = None
        self.focalLabel = None
        self.compStyle = None
        self.compLabel = None
        self.gridLayout = None
        # self.root = Tk()
        self.title = 'Panorama Image Stitching'
        self.left = 10
        self.top = 10
        self.width = 640
        self.height = 680
        self.selectImageBtn = None
        self.generateResultBtn = None
        self.numSelectLabel = None
        self.currentIndexLabel = None

        self.labelImage = None
        self.imageAreaWidgetContents = None
        self.prevImageBtn = None
        self.nextImageBtn = None

        self.currentIndex = 0
        self.imageFiles = None
        self.results = None
        self.initUI()

    def initUI(self):
        self.statusBar()
        self.numSelectLabel = QLabel(self)
        self.numSelectLabel.setText("Select 0 images")
        self.numSelectLabel.move(30, 40)

        self.selectImageBtn = QPushButton("Select", self)
        self.selectImageBtn.move(120, 40)
        self.selectImageBtn.setEnabled(True)
        self.selectImageBtn.clicked.connect(self.openFileNamesDialog)

        self.generateResultBtn = QPushButton("Generate", self)
        self.generateResultBtn.move(500, 10)
        self.generateResultBtn.setEnabled(False)
        self.generateResultBtn.clicked.connect(self.generateResult)

        # self.line = QFrame(self)
        # self.line.move(280, 60)
        # self.line.setFrameShape(QFrame.HLine)

        self.currentIndexLabel = QLabel(self)
        self.currentIndexLabel.setText("No Image Selected.")
        self.currentIndexLabel.move(280, 580)

        self.prevImageBtn = QPushButton("Prev Image", self)
        self.prevImageBtn.move(200, 620)
        self.prevImageBtn.setEnabled(False)
        self.prevImageBtn.clicked.connect(self.preImage)

        self.nextImageBtn = QPushButton("Next Image", self)
        self.nextImageBtn.move(350, 620)
        self.nextImageBtn.setEnabled(False)
        self.nextImageBtn.clicked.connect(self.nextImage)

        self.compLabel = QLabel(self)
        self.compLabel.setText("Compositing")
        self.compLabel.move(30, 10)

        self.compStyle = QComboBox(self)
        self.compStyle.addItem("Flat")
        self.compStyle.addItem("Cylindrical")
        self.compStyle.addItem("Spherical")
        self.compStyle.move(120, 10)
        self.compStyle.setEnabled(False)
        self.compStyle.activated[str].connect(self.chooseCompStyle)

        self.labelImage = QLabel(self)
        self.labelImage.move(300, 340)
        self.labelImage.setText("No Result")

        self.focalLabel = QLabel(self)
        self.focalLabel.setText("Focal Length")
        self.focalLabel.move(250, 10)

        self.focalInpput = QLineEdit(self)
        self.focalInpput.move(340, 10)
        self.focalInpput.setEnabled(False)
        self.focalInpput.setText("800")

        self.fileNameLabel = QLabel(self)
        self.fileNameLabel.setText("Save As")
        self.fileNameLabel.move(250, 40)

        self.fileNameInput = QLineEdit(self)
        self.fileNameInput.setText("new_img.jpg")
        self.fileNameInput.move(340, 40)
        self.fileNameInput.setEnabled(False)

        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.show()

    def openFileNamesDialog(self):
        # https://www.tutorialspoint.com/pyqt/pyqt_qfiledialog_widget.htm
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        files, _ = QFileDialog.getOpenFileNames(
            self,
            "QFileDialog.getOpenFileNames()",
            "",
            "Images (*.jpg *.jpeg *.png *.bmp)",
            options=options)
        if files:
            print(files)
            self.currentIndex = 0
            self.imageFiles = files
            self.numSelectLabel.setText("Select " + str(len(self.imageFiles)) +
                                        " images")
            self.currentIndexLabel.setText("Current Index " +
                                           str(self.currentIndex))
            self.showImages(self.imageFiles[0])
            self.generateResultBtn.setEnabled(True)
            self.nextImageBtn.setEnabled(True)
            self.prevImageBtn.setEnabled(True)
            if self.compStyle.currentText() != "Flat":
                self.focalInpput.setEnabled(True)
            else:
                self.focalInpput.setEnabled(False)
            self.fileNameInput.setEnabled(True)
            self.compStyle.setEnabled(True)

    def showImages(self, filename):
        self.labelImage.move(0, 100)
        self.labelImage.resize(640, 480)
        pixmap = QPixmap(filename)
        pixmapScaled = pixmap.scaled(640, 480, Qt.KeepAspectRatio)
        self.labelImage.setPixmap(pixmapScaled)

    def nextImage(self):
        self.currentIndex += 1
        if self.currentIndex > len(self.imageFiles) - 1:
            self.currentIndex = 0
        self.showImages(self.imageFiles[self.currentIndex])
        self.currentIndexLabel.setText("Current Index " +
                                       str(self.currentIndex))

    def preImage(self):
        self.currentIndex -= 1
        if self.currentIndex < 0:
            self.currentIndex = len(self.imageFiles) - 1

        self.showImages(self.imageFiles[self.currentIndex])
        self.currentIndexLabel.setText("Current Index " +
                                       str(self.currentIndex))

    def generateResult(self):
        # self.labelImage.move(300, 80)
        # self.labelImage.setText("Loading......")

        self.labelImage.move(300, 80)
        self.labelImage.setText("Loading......")
        QApplication.processEvents()
        self.stitchImage()
        #
        # callback()
        # # self.update(self)
        # self.root.after_idle(callback)

    def chooseCompStyle(self):
        if self.compStyle.currentText() != "Flat":
            self.focalInpput.setEnabled(True)
        else:
            self.focalInpput.setEnabled(False)

    def stitchImage(self):
        # nonlocal self
        start = timer()
        stitcher = Stitcher(self.imageFiles,
                            f=int(self.focalInpput.text()),
                            mode=self.compStyle.currentText())
        try:
            new_img = stitcher.stitch_all()
            end = timer()
            print("Total Time:", end - start)
            cv2.imwrite(self.fileNameInput.text(), new_img)
            self.showImages(self.fileNameInput.text())
        except Exception:
            print("!!!!!!!!!!!!!")
            self.labelImage.move(150, 80)
            self.labelImage.setText(
                "Failed to stitch the images, try other compositing method please."
            )
Beispiel #44
0
class CBR_API(QWidget):

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

    def initUI(self):

        logo_label = QLabel(self)
        logo_label.setPixmap(QPixmap('img/logo.png'))
        logo_label.move(0, 0)

        self.days()
        self.month()
        self.year()

        ok_button = QPushButton('OK', self)
        ok_button.resize(50, 23)
        ok_button.move(220, 198)

        ok_button.clicked.connect(self.make_request)

        self.load_result_image()

        self.setFixedSize(300, 400)
        self.setWindowTitle('История курса рубля')
        self.show()

    def days(self):
        self.days_combo = QComboBox(self)

        day_label = QLabel('День', self)
        day_label.move(20, 170)

        for day in range(1, 32):
            self.days_combo.addItem(f'{day}')

        self.days_combo.move(20, 200)


    def month(self):
        self.month_combo = QComboBox(self)

        month_label = QLabel('Месяц', self)
        month_label.move(80, 170)

        for month in range(1, 13):
            self.month_combo.addItem(f'{month}')

        self.month_combo.move(80, 200)

    def year(self):
        self.year_combo = QComboBox(self)

        year_label = QLabel('Год', self)
        year_label.move(140, 170)

        for year in range(2005, 2021):
            self.year_combo.addItem(f'{year}')

        self.year_combo.move(140, 200)

    def make_request(self):
        day_value = self.days_combo.currentText()
        month_value = self.month_combo.currentText()
        year_value = self.year_combo.currentText()

        result = self.get_result(day_value, month_value, year_value)

        self.dollar_value.setText(f"{result['dollar']} руб")
        self.dollar_value.adjustSize()

        self.euro_value.setText(f"{result['euro']} руб")
        self.euro_value.adjustSize()

    def get_result(self, day, month, year):
        
        result = {
            'dollar': 0,
            'euro': 0,
        }

        if int(day) < 10:
            day = f'0{day}'
        
        if int(month) < 10:
            month = f'0{month}'

        try:
            # request: 'http://www.cbr.ru/scripts/XML_daily.asp?date_req=ДД/ММ/ГГГ'
            get_xml = requests.get(f'http://www.cbr.ru/scripts/XML_daily.asp?date_req={day}/{month}/{year}')

            '''response: 
                <ValCurs Date="22.04.2017" name="Foreign Currency Market">
                <Valute ID="R01235">
                    <NumCode>840</NumCode>
                    <CharCode>USD</CharCode>
                    <Nominal>1</Nominal>
                    <Name>Доллар США</Name>
                    <Value>56,2307</Value>
                </Valute>
            
                <Valute ID="R01239">
                    <NumCode>978</NumCode>
                    <CharCode>EUR</CharCode>
                    <Nominal>1</Nominal>
                    <Name>Евро</Name>
                    <Value>60,3187</Value>
                </Valute>
            </ValCurs>'''

            structure = ET.fromstring(get_xml.content)

        except:
            return result

        try:
            dollar = structure.find("./*[@ID='R01235']/Value")
            result['dollar'] = dollar.text.replace(',', '.')
        except:
            result['dollar'] = 'x'

        try:
            euro = structure.find("./*[@ID='R01239']/Value")
            result['euro'] = euro.text.replace(',', '.')
        except:
            result['euro'] = 'x'

        return result

    def load_result_image(self):

        font = QFont()
        font.setFamily('Arial')
        font.setPointSize(18)

        dollar_label = QLabel(self)
        dollar_label.setPixmap(QPixmap('img/dollar.png'))
        dollar_label.move(60, 260)

        self.dollar_value = QLabel('0 руб', self)
        self.dollar_value.setFont(font)
        self.dollar_value.move(130, 263)

        euro_label = QLabel(self)
        euro_label.setPixmap(QPixmap('img/euro.png'))
        euro_label.move(50, 320)

        self.euro_value = QLabel('0 руб', self)
        self.euro_value.setFont(font)
        self.euro_value.move(130, 320)
Beispiel #45
0
class SettingsUI(QDialog):
    def __init__(self):
        super().__init__()

    def initUI(self, builders):
        rec = QApplication.desktop()
        rec = rec.screenGeometry()
        self.screenWidth, self.screenHeight = rec.width(), rec.height()

        if sys.platform == 'linux':
            font = QFont("Liberation Serif")
        elif sys.platform == 'darwin':
            font = QFont("Times")
        else:
            font = QFont("Calibri")

        self.ok = QPushButton('OK', self)
        self.ok.move(295 / 1920 * self.screenWidth,
                     225 / 1080 * self.screenHeight)
        self.ok.resize(100 / 1920 * self.screenWidth,
                       33 / 1080 * self.screenHeight)
        font.setPixelSize(22 / 1920 * self.screenWidth)
        self.ok.setFont(font)

        self.cancel = QPushButton('Cancel', self)
        self.cancel.move(20 / 1920 * self.screenWidth,
                         225 / 1080 * self.screenHeight)
        self.cancel.resize(100 / 1920 * self.screenWidth,
                           33 / 1080 * self.screenHeight)
        font.setPixelSize(22 / 1920 * self.screenWidth)
        self.cancel.setFont(font)

        self.lbl = QLabel("Build tool : ", self)
        font.setPixelSize(28 / 1920 * self.screenWidth)
        self.lbl.setFont(font)
        self.lbl.move(65 / 1920 * self.screenWidth,
                      20 / 1080 * self.screenHeight)
        self.lbl.font().setPixelSize(10)

        self.bldbox = QComboBox(self)
        self.bldbox.addItems(builders)
        self.bldbox.resize(140 / 1920 * self.screenWidth,
                           32 / 1080 * self.screenHeight)
        self.bldbox.move(195 / 1920 * self.screenWidth,
                         24 / 1080 * self.screenHeight)
        font.setPixelSize(22 / 1920 * self.screenWidth)
        self.bldbox.setFont(font)

        # cx_Freeze UI  ##############################################################################
        ##############################################################################################

        self.lbl2 = QLabel("Setup file : ", self)
        font.setPixelSize(26 / 1920 * self.screenWidth)
        self.lbl2.setFont(font)
        self.lbl2.move(10 / 1920 * self.screenWidth,
                       96 / 1080 * self.screenHeight)
        self.lbl2.hide()

        self.choosebtn = QPushButton('Choose', self)
        self.choosebtn.move(317 / 1920 * self.screenWidth,
                            98 / 1080 * self.screenHeight)
        self.choosebtn.resize(86 / 1920 * self.screenWidth,
                              32 / 1080 * self.screenHeight)
        font.setPixelSize(22 / 1920 * self.screenWidth)
        self.choosebtn.setFont(font)
        self.choosebtn.hide()

        self.createbtn = QPushButton("Create", self)
        self.createbtn.move(225 / 1920 * self.screenWidth,
                            98 / 1080 * self.screenHeight)
        self.createbtn.resize(86 / 1920 * self.screenWidth,
                              32 / 1080 * self.screenHeight)
        font.setPixelSize(22 / 1920 * self.screenWidth)
        self.createbtn.setFont(font)
        self.createbtn.hide()

        self.editbtn = QPushButton("Edit", self)
        self.editbtn.move(133 / 1920 * self.screenWidth,
                          98 / 1080 * self.screenHeight)
        self.editbtn.resize(86 / 1920 * self.screenWidth,
                            32 / 1080 * self.screenHeight)
        font.setPixelSize(22 / 1920 * self.screenWidth)
        self.editbtn.setFont(font)
        self.editbtn.hide()

        self.cxbldle = QLineEdit(self)
        self.cxbldle.move(10 / 1920 * self.screenWidth,
                          145 / 1080 * self.screenHeight)
        self.cxbldle.resize(395 / 1920 * self.screenWidth,
                            37 / 1080 * self.screenHeight)
        font.setPixelSize(23 / 1920 * self.screenWidth)
        self.cxbldle.setFont(font)
        self.cxbldle.setReadOnly(True)
        self.cxbldle.hide()

        ##############################################################################################
        ##############################################################################################

        # PyInstaller UI #############################################################################
        ##############################################################################################

        self.lbl3 = QLabel("Build options : ", self)
        font.setPixelSize(26 / 1920 * self.screenWidth)
        self.lbl3.setFont(font)
        self.lbl3.move(10 / 1920 * self.screenWidth,
                       95 / 1080 * self.screenHeight)
        self.lbl3.hide()

        self.instbldle = QLineEdit(self)
        self.instbldle.move(10 / 1920 * self.screenWidth,
                            145 / 1080 * self.screenHeight)
        self.instbldle.resize(395 / 1920 * self.screenWidth,
                              37 / 1080 * self.screenHeight)
        font.setPixelSize(23 / 1920 * self.screenWidth)
        self.instbldle.setFont(font)
        self.instbldle.hide()
        self.instbldle.setPlaceholderText(
            'For example: --noconsole, or leave empty')

        ##############################################################################################
        ##############################################################################################

    #Отобразить интерфейс для PyInstaller
    def showInstallerUI(self):
        self.lbl3.show()
        self.instbldle.show()

        self.lbl2.hide()
        self.choosebtn.hide()
        self.createbtn.hide()
        self.editbtn.hide()
        self.cxbldle.hide()

        self.ok.show()
        self.cancel.show()

    #Отобразить интерфейс для cx_Freeze
    def showFreezeUI(self):
        self.lbl3.hide()
        self.instbldle.hide()

        self.lbl2.show()
        self.choosebtn.show()
        self.createbtn.show()
        self.editbtn.show()
        self.cxbldle.show()

        self.ok.show()
        self.cancel.show()

    #Отобразить интерфейс для py2exe
    def showPy2ExeUi(self):
        self.lbl2.hide()
        self.choosebtn.hide()
        self.createbtn.hide()
        self.editbtn.hide()
        self.cxbldle.hide()

        self.lbl3.hide()
        self.instbldle.hide()

        self.ok.hide()
        self.cancel.hide()
Beispiel #46
0
class Main(QtWidgets.QMainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.initUI()

    def initUI(self):
        # Input
        self.input_line = QtWidgets.QLineEdit(self)
        self.input_line.setPlaceholderText('ERRONEOUS ADDRESS')
        self.input_line.move(5, 5)
        self.input_line.setAlignment(Qt.AlignRight)
        self.input_line.resize(400, 25)

        # Output
        self.output_line = QtWidgets.QLineEdit(self)
        self.output_line.setPlaceholderText('CORRECTED ADDRESS')
        self.output_line.move(5, 35)
        self.output_line.setReadOnly(True)
        self.output_line.setAlignment(Qt.AlignRight)
        self.output_line.resize(400, 25)

        self.combo = QComboBox(self)
        self.combo.addItem("en")
        self.combo.addItem("de")
        self.combo.addItem("fr")
        self.combo.addItem("es")
        self.combo.addItem("ru")
        self.combo.move(5, 65)


        # CORRECT button
        correct_button = QtWidgets.QPushButton("CORRECT", self)
        correct_button.move(305, 65)
        correct_button.resize(100, 30)
        correct_button.clicked.connect(self.Operator)

        # QUIT button
        quit_button = QtWidgets.QPushButton("QUIT", self)
        quit_button.clicked.connect(QCoreApplication.instance().quit)
        quit_button.move(200, 65)
        quit_button.resize(100, 30)

        # Window setting
        self.setGeometry(300, 300, 410, 120)
        self.setWindowTitle("ADDRESS CORRECTION")
        self.setFixedSize(410, 100)
        self.setWindowIcon(QtGui.QIcon(""))
        self.show()

    def Operator(self):
        self.output_line.setText(self.ad_complete(self.input_line.text()))

    def ad_format(self, adresse):
        # for all the german users, this function will replace all "Umlaute", i.e. ö,ä,ü and ß
        adresse = adresse.replace(' ', ',')
        adresse = adresse.replace('ü', 'ue')
        adresse = adresse.replace('ö', 'oe')
        adresse = adresse.replace('ä', 'ae')
        adresse = adresse.replace('ß', 'ss')
        return adresse

    def ad_complete(self, adresse):
        adresse = self.ad_format(adresse)

        # Insert addresses into url
        url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + adresse + "&language="+str(self.combo.currentText()) #de"
        r = urllib.request.urlopen(url)

        # Parse and read json file
        data = json.loads(r.read().decode(r.info().get_param('charset') or 'utf-8'))

        try:
            # extract formated address [additional informations e.g. geo coordinates ]
            formatierte_adresse = data['results'][0]['formatted_address']
        except:
            formatierte_adresse = 'Error'

        return formatierte_adresse
Beispiel #47
0
class CrossRoadTool(QWidget):
    def __init__(self):
        super().__init__()
        self.items_list = []
        self.road_list = {}
        common.list = common.list
        self.linkPropsWin = LinkProps()
        self.signalEditWin = SignalEdit()
        self.sectionWin = SectionEdit()
        self.readXML()
        self.initUI()
        # self.initTableDatas()

    def initUI(self):
        self.setGeometry(50, 50, 1500, 800)
        self.__paintBoard = CrossPaintBoard(self)
        self.__paintBoard.move(300, 50)
        # self.showMaximized()
        self.setWindowTitle("交通路口处理工具")
        self.initComboBox()
        self.initTableWidget()
        self.initButton()
        self.initQRadioButton()
        self.initRoadLine()

        self.show()

    # 初始化下拉选择框
    def initComboBox(self):
        self.comboLeftOne = QComboBox(self)
        self.comboLeftTwo = QComboBox(self)
        self.comboRightOne = QComboBox(self)
        self.comboRightTwo = QComboBox(self)
        self.comboTopOne = QComboBox(self)
        self.comboTopTwo = QComboBox(self)
        self.comboBottomOne = QComboBox(self)
        self.comboBottomTwo = QComboBox(self)

        self.comboLeftOne.setEditable(True)
        self.comboLeftTwo.setEditable(True)
        self.comboRightOne.setEditable(True)
        self.comboRightTwo.setEditable(True)
        self.comboTopOne.setEditable(True)
        self.comboTopTwo.setEditable(True)
        self.comboBottomOne.setEditable(True)
        self.comboBottomTwo.setEditable(True)

        self.comboLeftOne.addItems(self.items_list)
        self.comboLeftTwo.addItems(self.items_list)
        self.comboRightOne.addItems(self.items_list)
        self.comboRightTwo.addItems(self.items_list)
        self.comboTopOne.addItems(self.items_list)
        self.comboTopTwo.addItems(self.items_list)
        self.comboBottomOne.addItems(self.items_list)
        self.comboBottomTwo.addItems(self.items_list)

        # 增加自动补全
        self.completerLeftOne = QCompleter(self.items_list)
        self.completerLeftTwo = QCompleter(self.items_list)
        self.completerRightOne = QCompleter(self.items_list)
        self.completerRightTwo = QCompleter(self.items_list)
        self.completerTopOne = QCompleter(self.items_list)
        self.completerTopTwo = QCompleter(self.items_list)
        self.completerBottomOne = QCompleter(self.items_list)
        self.completerBottomTwo = QCompleter(self.items_list)

        self.comboLeftOne.setCompleter(self.completerLeftOne)
        self.comboLeftTwo.setCompleter(self.completerLeftTwo)
        self.comboRightOne.setCompleter(self.completerRightOne)
        self.comboRightTwo.setCompleter(self.completerRightTwo)
        self.comboTopOne.setCompleter(self.completerTopOne)
        self.comboTopTwo.setCompleter(self.completerTopTwo)
        self.comboBottomOne.setCompleter(self.completerBottomOne)
        self.comboBottomTwo.setCompleter(self.completerBottomTwo)

        # ComboBox 设置的位置
        self.comboLeftOne.move(200, 190)
        self.comboLeftTwo.move(200, 290)
        self.comboRightOne.move(730, 190)
        self.comboRightTwo.move(730, 290)
        self.comboTopOne.move(420, 20)
        self.comboTopTwo.move(520, 20)
        self.comboBottomOne.move(420, 500)
        self.comboBottomTwo.move(520, 500)

    def initButton(self):
        self.createButton = QPushButton(self)
        self.createButton.setText("生成")
        self.createButton.clicked.connect(self.createContent)
        self.createButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.createButton.move(900, 650)

        self.saveButton = QPushButton(self)
        self.saveButton.setText("保存")
        self.saveButton.setShortcut('Ctrl+S')  # shortcut key
        self.saveButton.clicked.connect(self.saveContextToXML)
        self.saveButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.saveButton.move(1000, 650)

        self.clearButton = QPushButton(self)
        self.clearButton.setText("清除")
        self.clearButton.clicked.connect(self.clearEvent)
        self.clearButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.clearButton.move(1100, 650)

        self.readProsBT = QPushButton(self)
        self.readProsBT.setText("读取列表")
        self.readProsBT.move(1200, 650)
        self.readProsBT.clicked.connect(self.readPropsListEvent)
        self.readProsBT.setCursor(QCursor(Qt.PointingHandCursor))

        self.editProsBT = QPushButton(self)
        self.editProsBT.setText("编辑属性")
        self.editProsBT.move(1300, 650)
        self.editProsBT.clicked.connect(self.openPropsWinEvent)
        self.editProsBT.setCursor(QCursor(Qt.PointingHandCursor))

        self.openSignalBT = QPushButton(self)
        self.openSignalBT.setText("信号灯编辑")
        self.openSignalBT.clicked.connect(self.openSignalEditEvent)
        self.openSignalBT.setCursor(QCursor(Qt.PointingHandCursor))
        self.openSignalBT.move(900, 700)

        self.sectionEditBT = QPushButton(self)
        self.sectionEditBT.setText("Section编辑")
        self.sectionEditBT.move(1000, 700)
        self.sectionEditBT.clicked.connect(self.openSectionWinEvent)
        self.sectionEditBT.setCursor(QCursor(Qt.PointingHandCursor))

    def initQRadioButton(self):
        self.rbCrossType = QRadioButton("十字型路口", self)
        self.rbTType = QRadioButton("T字型路口", self)
        self.rbStraightType = QRadioButton("直型路口", self)
        self.rbTurnType = QRadioButton("拐字型路口", self)
        self.rbStraightType.setChecked(True)  # 默认选中

        self.lbID = QLabel("ID:", self)
        self.inputID = QLineEdit(self)
        self.lbID.move(680, 605)
        self.inputID.move(700, 600)

        self.bg = QButtonGroup(self)
        self.bg.addButton(self.rbCrossType, 1)
        self.bg.addButton(self.rbTType, 2)
        self.bg.addButton(self.rbStraightType, 3)
        self.bg.addButton(self.rbTurnType, 4)
        self.bg.buttonClicked.connect(self.rbclicked)
        self.rbCrossType.move(500, 650)
        self.rbTType.move(600, 650)
        self.rbStraightType.move(700, 650)
        self.rbTurnType.move(800, 650)

    def rbclicked(self):
        if self.bg.checkedId() == 1:  # 十字路口
            print("十字路口...")
            self.comboLeftOne.setVisible(True)
            self.comboLeftTwo.setVisible(True)
            self.comboRightOne.setVisible(True)
            self.comboRightTwo.setVisible(True)
            self.comboTopOne.setVisible(True)
            self.comboTopTwo.setVisible(True)
            self.comboBottomOne.setVisible(True)
            self.comboBottomTwo.setVisible(True)
        elif self.bg.checkedId() == 2:  # 丁字路口
            print("丁字路口...")
            self.comboLeftOne.setVisible(True)
            self.comboLeftTwo.setVisible(True)
            self.comboRightOne.setVisible(True)
            self.comboRightTwo.setVisible(True)
            self.comboTopOne.setVisible(True)
            self.comboTopTwo.setVisible(True)
            self.comboBottomOne.setVisible(False)
            self.comboBottomTwo.setVisible(False)
        elif self.bg.checkedId() == 3:  # 直型路口
            self.comboLeftOne.setVisible(True)
            self.comboLeftTwo.setVisible(True)
            self.comboRightOne.setVisible(True)
            self.comboRightTwo.setVisible(True)
            self.comboTopOne.setVisible(False)
            self.comboTopTwo.setVisible(False)
            self.comboBottomOne.setVisible(False)
            self.comboBottomTwo.setVisible(False)
        elif self.bg.checkedId() == 4:  # 拐字型路口
            self.comboLeftOne.setVisible(False)
            self.comboLeftTwo.setVisible(False)
            self.comboRightOne.setVisible(True)
            self.comboRightTwo.setVisible(True)
            self.comboTopOne.setVisible(True)
            self.comboTopTwo.setVisible(True)
            self.comboBottomOne.setVisible(False)
            self.comboBottomTwo.setVisible(False)

    # Override
    def paintEvent(self, e):
        qp = QPainter()
        qp.begin(self)
        # self.drawLines(qp)
        qp.end()

    def drawLines(self, qp):
        pen = QPen(Qt.black, 2, Qt.SolidLine)

        qp.setPen(pen)
        # 左
        qp.drawLine(300, 200, 400, 200)
        qp.drawLine(300, 300, 400, 300)
        # 右
        qp.drawLine(600, 200, 700, 200)
        qp.drawLine(600, 300, 700, 300)
        # 上
        qp.drawLine(450, 150, 450, 50)
        qp.drawLine(550, 150, 550, 50)
        # 下
        qp.drawLine(450, 350, 450, 450)
        qp.drawLine(550, 350, 550, 450)

        # qp.drawArc(400, 200, 450, 350, 30 * 16, 120 * 16)

        path = QPainterPath()
        path.moveTo(400, 200)
        # 使用cubicTo() 方法生成,分别需要三个点:起始点,控制点和终止点

        # qp.setPen(Qt.red)
        # # self.area.setPen(QPen(Qt.black, 5, Qt.SolidLine))
        # self.update()

        # 直行
        qp.setPen(Qt.green)
        qp.drawLine(600, 200, 400, 200)  # 右1--左1
        qp.drawLine(400, 300, 600, 300)  # 左2--右2
        qp.drawLine(450, 150, 450, 350)  # 上1 -- 下1
        qp.drawLine(550, 350, 550, 150)  # 下2 -- 上2

        # 左行
        qp.setPen(Qt.blue)
        qp.drawLine(400, 300, 550, 150)  # 左2 -- 上2
        qp.drawLine(600, 200, 450, 350)  # 右1 -- 下1
        qp.drawLine(450, 150, 600, 300)  # 上1 -- 右1
        qp.drawLine(550, 350, 400, 200)  # 下2 -- 左1

        # 右行
        qp.setPen(Qt.red)
        qp.drawLine(400, 300, 450, 350)  # 左2 -- 下1
        qp.drawLine(600, 200, 550, 150)  # 右1 -- 上2
        qp.drawLine(450, 150, 400, 200)  # 上1 -- 左1
        qp.drawLine(550, 350, 600, 300)  # 下2 -- 右2

        # 贝塞尔曲线
        # qp.setPen(Qt.red)
        # path.cubicTo(400, 200, 450, 250, 450, 350)

        qp.drawPath(path)
        # pen.setStyle(Qt.DashLine)
        # qp.setPen(pen)
        # qp.drawLine(20, 80, 250, 80)

        # pen.setStyle(Qt.DashDotLine)
        # qp.setPen(pen)
        # qp.drawLine(20, 120, 250, 120)
        #
        # pen.setStyle(Qt.DotLine)
        # qp.setPen(pen)
        # qp.drawLine(20, 160, 250, 160)
        #
        # pen.setStyle(Qt.DashDotDotLine)
        # qp.setPen(pen)
        # qp.drawLine(20, 200, 250, 200)
        #
        # pen.setStyle(Qt.CustomDashLine)
        # pen.setDashPattern([1, 4, 5, 4])
        # qp.setPen(pen)
        # qp.drawLine(20, 240, 250, 240)

    def initTableWidget(self):
        common.tableWidget = QTableWidget(self)
        common.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
        common.tableWidget.setColumnCount(3)
        common.tableWidget.setRowCount(18)
        common.tableWidget.move(900, 100)
        common.tableWidget.setFixedHeight(500)
        common.tableWidget.setFixedWidth(500)
        common.tableWidget.setHorizontalHeaderLabels(["从ID路", "到ID路", "类型"])

    def initTableDatas(self):
        common.tableWidget.clearContents()
        for i in range(len(common.list)):
            common.tableWidget.setItem(i, 0, QTableWidgetItem(common.list[i].get("fromroad")))
            common.tableWidget.setItem(i, 1, QTableWidgetItem(common.list[i].get("toroad")))
            if common.list[i].get("type") == "st":
                common.tableWidget.setItem(i, 2, QTableWidgetItem("直行"))
            elif common.list[i].get("type") == "lt":
                common.tableWidget.setItem(i, 2, QTableWidgetItem("左行"))
            elif common.list[i].get("type") == "rt":
                common.tableWidget.setItem(i, 2, QTableWidgetItem("右行"))
            elif common.list[i].get("type") == "ut":
                common.tableWidget.setItem(i, 2, QTableWidgetItem("掉头"))

    def readXML(self):
        print("start read xml...")
        # 打开xml文档
        '''
        必须在解析的时候添加
        remove_blank_text=True
        这样的话 pretty_print=True 才会真正有效
        '''
        parser = etree.XMLParser(remove_blank_text=True)
        xml = etree.parse('yf_sample_data.xml', parser)
        self.root = xml.getroot()  # 获取根节点
        # self.removeNodes("junction")  # 清除所有junction节点
        itemlist = self.root.xpath('//OpenDriveData/road/@id')
        for id in itemlist:
            # id = item.getAttribute("id")
            if not id:
                print("id is null")
            else:
                self.items_list.append(id)
                # roadSections = self.root.xpath('//OpenDriveData/road[@id="' + id + '"]/lanes/section')
                #
                # self.road_list[id] = {"id": id, "roadNum": 6}
        self.items_list.sort()

    # 保存数据到XML
    def saveContextToXML(self):
        print("saveContextToXML start...")

        if len(common.list) == 0:
            QMessageBox.information(self, "温馨提示", "请先生成数据!", QMessageBox.Yes, QMessageBox.Yes)
            return
        print("junction id:" + self.inputID.text().strip())

        junctionID = self.inputID.text().strip()

        if junctionID == "":
            print("junction id is null")
            QMessageBox.information(self, "温馨提示", "ID不能为空,请输入!", QMessageBox.Yes, QMessageBox.Yes)
            return

        currentJunctionIds = self.root.xpath('//OpenDriveData/junction[@id="' + junctionID + '"]')
        if len(currentJunctionIds) > 0:
            print("当前的ID已经存在,请更换一个ID!")
            reply = QMessageBox.information(self, "温馨提示", "当前的ID已经存在,是否替换!", QMessageBox.Yes | QMessageBox.No,
                                            QMessageBox.No)
            if reply == QMessageBox.Yes:
                self.removeNodes("junction", junctionID)
            else:
                return

        # 用DOM对象创建元素子节点
        # junction = etree.SubElement(self.root, 'junction', attrib={'id': '222', "name": "333"})
        junction = etree.SubElement(self.root, 'junction', attrib={"id": junctionID})
        links = etree.SubElement(junction, "links")

        for i in range(len(common.list)):
            id = common.list[i].get("fromroad") + common.list[i].get("toroad")
            type = common.list[i].get("type")
            fromroad = common.list[i].get("fromroad")
            toroad = common.list[i].get("toroad")

            roadNums = self.getRoadNum(common.list[i])
            lansfrom = ""
            lansto = ""
            if type == "st":
                _fromRoadNum = roadNums["fromRoadNum"]
                _toRoadNum = roadNums["toRoadNum"]
                _roadNumMin = min(_fromRoadNum, _toRoadNum)
                if _roadNumMin <= 2:
                    lansfrom = "-1;-2"
                    lansto = "-1;-2"
                else:
                    for _indexNum in range(2, _roadNumMin):
                        lansfrom = lansfrom + "-" + str(_indexNum) + ";"
                        lansto = lansto + "-" + str(_indexNum) + ";"
                    lansfrom = lansfrom[0:-1]
                    lansto = lansto[0:-1]
            elif type == "lt":
                lansfrom = "-1"
                lansto = "-1"
            elif type == 'rt':
                lansfrom = "-" + str(roadNums["fromRoadNum"])
                lansto = "-" + str(roadNums["toRoadNum"])
            elif type == 'ut':
                lansfrom = "-1"
                lansto = "-1"

            # link = etree.SubElement(links, "link",
            #                         attrib={"type": type, "fromroad": fromroad, "toroad": toroad, "id": id,
            #                                 "name": "", "lansfrom": "-1", "lansto": "-1", "s": "0",
            #                                 "lansmark": "0,solid;solid", "hidepavement": ""
            #                                 })
            link = etree.SubElement(links, "link")
            # 使用set方法添加属性,属性值不排序,而etree.SubElement(links, "link", attrib={})设置,属性值导出时是有序的
            link.set("type", type)
            link.set("fromroad", fromroad)
            link.set("toroad", toroad)
            link.set("id", id)

            fromroadName = self.root.xpath('//OpenDriveData/road[@id="' + fromroad + '"]/@name')[0]
            toroadName = self.root.xpath('//OpenDriveData/road[@id="' + fromroad + '"]/@name')[0]
            _name = type + "_" + fromroadName + "_" + toroadName
            link.set("name", _name)
            link.set("lansfrom", lansfrom)
            link.set("lansto", lansto)
            link.set("s", "0")

            _lansmark = "0,"
            for k in range(0, len(lansfrom.split(";")) + 1):
                _lansmark = _lansmark + "solid;"
            _lansmark = _lansmark[0:-1]
            link.set("lansmark", _lansmark)

            link.set("hidepavement", "")

            # 判断是否编辑了属性
            if "lansfrom" in common.list[i]:
                link.set("lansfrom", common.list[i]["lansfrom"])
            if "lansto" in common.list[i]:
                link.set("lansto", common.list[i]["lansto"])
            if "lansmark" in common.list[i]:
                link.set("lansmark", common.list[i]["lansmark"])
            if "hidepavement" in common.list[i]:
                link.set("hidepavement", common.list[i]["hidepavement"])
            if "s" in common.list[i]:
                link.set("s", common.list[i]["s"])

            if "leftCurve" in common.list[i]:
                link.set("leftCurve", common.list[i]["leftCurve"])
            if "rightCurve" in common.list[i]:
                link.set("rightCurve", common.list[i]["rightCurve"])

            objects = etree.SubElement(link, "objects")
            signals = etree.SubElement(link, "signals")
        try:
            # 节点转为tree对象
            tree = etree.ElementTree(self.root)
            '''
            各个参数含义如下:
            1)第1个参数是xml的完整路径(包括文件名);
            2)pretty_print参数是否美化代码;
            3)xml_declaration参数是否写入xml声明,就是我们看到xml文档第1行文字;
            4)encoding参数很明显是保存的编码。
            '''
            tree.write('yf_sample_data.xml', pretty_print=True, xml_declaration=True, encoding='utf-8')
            print('写入xml OK!')
            QMessageBox.information(self, "温馨提示", "写入xml成功!", QMessageBox.Yes, QMessageBox.Yes)
            self.clearEvent()

        except Exception as err:
            print('错误信息:{0}'.format(err))
            QMessageBox.information(self, "温馨提示", "写入xml失败!", QMessageBox.Yes, QMessageBox.Yes)

    # 删除指定节点
    def removeNodes(self, nodeName, id=""):
        if id == "":
            junctionOlds = self.root.xpath("//OpenDriveData/" + nodeName)
        else:
            junctionOlds = self.root.xpath("//OpenDriveData/" + nodeName + "[@id='" + id + "']")
        for node in junctionOlds:
            self.root.remove(node)

    # 清除数据
    def clearEvent(self):
        print("clear ...")
        common.list = []
        common.tableWidget.clearContents()

        self.__paintBoard.clearBoard()
        self.initRoadLine()

    def getComboBoxIds(self):
        self.leftOneId = self.comboLeftOne.currentText()
        self.leftTwoId = self.comboLeftTwo.currentText()
        self.rightOneId = self.comboRightOne.currentText()
        self.rightTwoId = self.comboRightTwo.currentText()
        self.topOneId = self.comboTopOne.currentText()
        self.topTwoId = self.comboTopTwo.currentText()
        self.bottomOneId = self.comboBottomOne.currentText()
        self.bottomTwoId = self.comboBottomTwo.currentText()

    def generatedCrossData(self):
        #### 直行#####
        # 左2--右2
        common.list.append({"type": "st", "fromroad": self.leftTwoId, "toroad": self.rightTwoId})
        # 右1--左1
        common.list.append({"type": "st", "fromroad": self.rightOneId, "toroad": self.leftOneId})
        # 上1--下1
        common.list.append({"type": "st", "fromroad": self.topOneId, "toroad": self.bottomOneId})
        # 下2--上2
        common.list.append({"type": "st", "fromroad": self.bottomTwoId, "toroad": self.topTwoId})

        #### 左行#####
        # 左2--上2
        common.list.append({"type": "lt", "fromroad": self.leftTwoId, "toroad": self.topTwoId})
        # 右1--下1
        common.list.append({"type": "lt", "fromroad": self.rightOneId, "toroad": self.bottomOneId})
        # 上1--右2
        common.list.append({"type": "lt", "fromroad": self.topOneId, "toroad": self.rightTwoId})
        # 下2--左1
        common.list.append({"type": "lt", "fromroad": self.bottomTwoId, "toroad": self.leftOneId})

        #### 右行#####
        # 左2--下1
        common.list.append({"type": "rt", "fromroad": self.leftTwoId, "toroad": self.bottomOneId})
        # 右1--上2
        common.list.append({"type": "rt", "fromroad": self.rightOneId, "toroad": self.topTwoId})
        # 上1--左1
        common.list.append({"type": "rt", "fromroad": self.topOneId, "toroad": self.leftOneId})
        # 下2--右2
        common.list.append({"type": "rt", "fromroad": self.bottomTwoId, "toroad": self.rightTwoId})

        #### 掉头#####
        # 左2--左1
        common.list.append({"type": "ut", "fromroad": self.leftTwoId, "toroad": self.leftOneId})
        # 右1--右2
        common.list.append({"type": "ut", "fromroad": self.rightOneId, "toroad": self.rightTwoId})
        # 上1--上2
        common.list.append({"type": "ut", "fromroad": self.topOneId, "toroad": self.topTwoId})
        # 下2--下1
        common.list.append({"type": "ut", "fromroad": self.bottomTwoId, "toroad": self.bottomOneId})
        # 连线
        self.initCrossConnectLine()

    # T型路口(没有下边路)
    def generatedTData(self):
        #### 直行#####
        # 左2--右2
        common.list.append({"type": "st", "fromroad": self.leftTwoId, "toroad": self.rightTwoId})
        # 右1--左1
        common.list.append({"type": "st", "fromroad": self.rightOneId, "toroad": self.leftOneId})

        #### 左行#####
        # 左2--上2
        common.list.append({"type": "lt", "fromroad": self.leftTwoId, "toroad": self.topTwoId})
        # 上1--右2
        common.list.append({"type": "lt", "fromroad": self.topOneId, "toroad": self.rightTwoId})

        #### 右行#####
        # 右1--上2
        common.list.append({"type": "rt", "fromroad": self.rightOneId, "toroad": self.topTwoId})
        # 上1--左1
        common.list.append({"type": "rt", "fromroad": self.topOneId, "toroad": self.leftOneId})

        #### 掉头#####
        # 左2--左1
        common.list.append({"type": "ut", "fromroad": self.leftTwoId, "toroad": self.leftOneId})
        # 右1--右2
        common.list.append({"type": "ut", "fromroad": self.rightOneId, "toroad": self.rightTwoId})
        # 上1--上2
        common.list.append({"type": "ut", "fromroad": self.topOneId, "toroad": self.topTwoId})
        self.initTConnectLine()

    # 直行路口(只有左右路的直行和掉头)
    def generatedStraightData(self):
        #### 直行#####
        # 左2--右2
        common.list.append({"type": "st", "fromroad": self.leftTwoId, "toroad": self.rightTwoId})
        # 右1--左1
        common.list.append({"type": "st", "fromroad": self.rightOneId, "toroad": self.leftOneId})

        #### 掉头#####
        # 左2--左1
        common.list.append({"type": "ut", "fromroad": self.leftTwoId, "toroad": self.leftOneId})
        # 右1--右2
        common.list.append({"type": "ut", "fromroad": self.rightOneId, "toroad": self.rightTwoId})
        # 连线
        self.initCrossConnectLine()

    # 拐字型路口(只有右和上路)
    def generatedTurnData(self):
        #### 左行#####
        # 上1--右2
        common.list.append({"type": "lt", "fromroad": self.topOneId, "toroad": self.rightTwoId})

        #### 右行#####
        # 右1--上2
        common.list.append({"type": "rt", "fromroad": self.rightOneId, "toroad": self.topTwoId})

        #### 掉头#####
        # 右1--右2
        common.list.append({"type": "ut", "fromroad": self.rightOneId, "toroad": self.rightTwoId})
        # 上1--上2
        common.list.append({"type": "ut", "fromroad": self.topOneId, "toroad": self.topTwoId})
        # 连线
        self.initCrossConnectLine()

    # 生成数据
    def createContent(self):
        print("createContent...")
        common.list = []
        self.getComboBoxIds()
        if self.bg.checkedId() == 1:  # 十字路口
            self.generatedCrossData()
        elif self.bg.checkedId() == 2:  # 丁字路口
            self.generatedTData()
        elif self.bg.checkedId() == 3:  # 直行路口
            self.generatedStraightData()
        elif self.bg.checkedId() == 4:  # 拐字型路口
            self.generatedTurnData()
        # 初始化表格数据
        self.initTableDatas()

    def getUUID(self):
        uid = str(uuid.uuid4())
        suid = ''.join(uid.split('-'))
        return suid

    def initRoadLine(self):

        # self.__paintBoard.move(1400, 100)

        self.__paintBoard.setPen(QColor("black"), 8)
        # 左
        self.__paintBoard.drawLine(QPoint(0, 150), QPoint(100, 150))
        self.__paintBoard.drawLine(QPoint(0, 250), QPoint(100, 250))
        # 右
        self.__paintBoard.drawLine(QPoint(300, 150), QPoint(400, 150))
        self.__paintBoard.drawLine(QPoint(300, 250), QPoint(400, 250))
        # 上
        self.__paintBoard.drawLine(QPoint(150, 100), QPoint(150, 0))
        self.__paintBoard.drawLine(QPoint(250, 100), QPoint(250, 0))
        # 下
        self.__paintBoard.drawLine(QPoint(150, 300), QPoint(150, 400))
        self.__paintBoard.drawLine(QPoint(250, 300), QPoint(250, 400))

        # 设置道路放像
        self.__paintBoard.drawLine(QPoint(350, 150), QPoint(360, 140))
        self.__paintBoard.drawLine(QPoint(350, 150), QPoint(360, 160))

    def initCrossConnectLine(self):
        # 直行
        self.__paintBoard.setPen(QColor("green"), 4)
        self.__paintBoard.drawLine(QPoint(300, 150), QPoint(100, 150))  # 右1--左1
        self.__paintBoard.drawLine(QPoint(100, 250), QPoint(300, 250))  # 左2--右2
        self.__paintBoard.drawLine(QPoint(150, 100), QPoint(150, 300))  # 上1 -- 下1
        self.__paintBoard.drawLine(QPoint(250, 300), QPoint(250, 100))  # 下2 -- 上2

        # 左行
        self.__paintBoard.setPen(QColor("blue"), 4)
        self.__paintBoard.drawLine(QPoint(100, 250), QPoint(250, 100))  # 左2 -- 上2
        self.__paintBoard.drawLine(QPoint(300, 150), QPoint(150, 300))  # 右1 -- 下1
        self.__paintBoard.drawLine(QPoint(150, 100), QPoint(300, 250))  # 上1 -- 右1
        self.__paintBoard.drawLine(QPoint(250, 300), QPoint(100, 150))  # 下2 -- 左1

        # 右行
        self.__paintBoard.setPen(QColor("red"), 4)
        self.__paintBoard.drawLine(QPoint(100, 250), QPoint(150, 300))  # 左2 -- 下1
        self.__paintBoard.drawLine(QPoint(300, 150), QPoint(250, 100))  # 右1 -- 上2
        self.__paintBoard.drawLine(QPoint(150, 100), QPoint(100, 150))  # 上1 -- 左1
        self.__paintBoard.drawLine(QPoint(250, 300), QPoint(300, 250))  # 下2 -- 右2

        # 掉头
        self.__paintBoard.setPen(QColor("#9e9e9e"), 4)
        self.__paintBoard.drawLine(QPoint(100, 250), QPoint(100, 150))
        self.__paintBoard.drawLine(QPoint(300, 150), QPoint(300, 250))
        self.__paintBoard.drawLine(QPoint(150, 100), QPoint(250, 100))
        self.__paintBoard.drawLine(QPoint(250, 300), QPoint(150, 300))

    def initTConnectLine(self):
        # 直行
        self.__paintBoard.setPen(QColor("green"), 4)
        self.__paintBoard.drawLine(QPoint(300, 150), QPoint(100, 150))  # 右1--左1
        self.__paintBoard.drawLine(QPoint(100, 250), QPoint(300, 250))  # 左2--右2

        # 左行
        self.__paintBoard.setPen(QColor("blue"), 4)
        self.__paintBoard.drawLine(QPoint(100, 250), QPoint(250, 100))  # 左2 -- 上2
        self.__paintBoard.drawLine(QPoint(150, 100), QPoint(300, 250))  # 上1 -- 右1

        # 右行
        self.__paintBoard.setPen(QColor("red"), 4)
        self.__paintBoard.drawLine(QPoint(300, 150), QPoint(250, 100))  # 右1 -- 上2
        self.__paintBoard.drawLine(QPoint(150, 100), QPoint(100, 150))  # 上1 -- 左1

        # 掉头
        self.__paintBoard.setPen(QColor("#9e9e9e"), 4)
        self.__paintBoard.drawLine(QPoint(100, 250), QPoint(100, 150))
        self.__paintBoard.drawLine(QPoint(300, 150), QPoint(300, 250))
        self.__paintBoard.drawLine(QPoint(150, 100), QPoint(250, 100))

    # 获取车道数
    def getRoadNum(self, item):
        type = item.get("type")
        fromroad = item.get("fromroad")
        toroad = item.get("toroad")

        fromRoadSections = self.root.xpath('//OpenDriveData/road[@id="' + fromroad + '"]/lanes/section')
        fromRoadSection = fromRoadSections[-1]
        fromRoadNum = len(fromRoadSection.xpath("@rightlans")[0].split(";"))
        toRoadSections = self.root.xpath('//OpenDriveData/road[@id="' + toroad + '"]/lanes/section')
        toRoadSection = toRoadSections[0]
        toRoadNum = len(toRoadSection.xpath("@rightlans")[0].split(";"))
        return {"fromRoadNum": fromRoadNum, "toRoadNum": toRoadNum}

        # if type == 'st':
        #     fromRoadSections = self.root.xpath('//OpenDriveData/road[@id="' + fromroad + '"]/lanes/section')
        #     fromRoadSection = fromRoadSections[-1]
        #     fromRoadNum = len(fromRoadSection.xpath("@rightlans")[0].split(";"))
        #     toRoadSections = self.root.xpath('//OpenDriveData/road[@id="' + toroad + '"]/lanes/section')
        #     toRoadSection = toRoadSections[0]
        #     toRoadNum = len(toRoadSection.xpath("@rightlans")[0].split(";"))
        #     return {"fromRoadNum": fromRoadNum, "toRoadNum": toRoadNum}
        # elif type == 'lt':
        #     fromRoadSections = self.root.xpath('//OpenDriveData/road[@id="' + fromroad + '"]/lanes/section')
        #     fromRoadSection = fromRoadSections[-1]
        #     fromRoadNum = len(fromRoadSection.xpath("@rightlans")[0].split(";"))
        #     toRoadSections = self.root.xpath('//OpenDriveData/road[@id="' + toroad + '"]/lanes/section')
        #     toRoadSection = toRoadSections[0]
        #     toRoadNum = len(toRoadSection.xpath("@rightlans")[0].split(";"))
        #     return {"fromRoadNum": fromRoadNum, "toRoadNum": toRoadNum}
        # elif type == 'rt':
        #     fromRoadSections = self.root.xpath('//OpenDriveData/road[@id="' + fromroad + '"]/lanes/section')
        #     fromRoadSection = fromRoadSections[-1]
        #     fromRoadNum = len(fromRoadSection.xpath("@rightlans")[0].split(";"))
        #     toRoadSections = self.root.xpath('//OpenDriveData/road[@id="' + toroad + '"]/lanes/section')
        #     toRoadSection = toRoadSections[0]
        #     toRoadNum = len(toRoadSection.xpath("@rightlans")[0].split(";"))
        #     return {"fromRoadNum": fromRoadNum, "toRoadNum": toRoadNum}
        # elif type == 'ut':
        #     fromRoadSections = self.root.xpath('//OpenDriveData/road[@id="' + fromroad + '"]/lanes/section')
        #     fromRoadSection = fromRoadSections[-1]
        #     fromRoadNum = len(fromRoadSection.xpath("@rightlans")[0].split(";"))
        #     toRoadSections = self.root.xpath('//OpenDriveData/road[@id="' + toroad + '"]/lanes/section')
        #     toRoadSection = toRoadSections[0]
        #     toRoadNum = len(toRoadSection.xpath("@rightlans")[0].split(";"))
        #     return {"fromRoadNum": fromRoadNum, "toRoadNum": toRoadNum}

    def openPropsWinEvent(self):
        row = common.tableWidget.currentIndex().row()
        model = common.tableWidget.model()
        index = model.index(row, 0)  # 选中行第一列的内容
        fromroad = model.data(index)
        index = model.index(row, 1)
        toroad = model.data(index)
        if row == -1 or fromroad == None or toroad == None:
            QMessageBox.information(self, "温馨提示", "请选择一条正确记录!", QMessageBox.Yes, QMessageBox.Yes)
            return
        junctionID = self.inputID.text().strip()
        link = self.root.xpath(
            '//OpenDriveData/junction[@id="' + junctionID + '"]/links/link[@id="' + fromroad + toroad + '"]')
        if len(link) == 0:
            QMessageBox.information(self, "温馨提示", "你编辑的记录在文档中不存在,请先生成!", QMessageBox.Yes, QMessageBox.Yes)
            return

        # if len(common.list) == 0:
        #     QMessageBox.information(self, "温馨提示", "请先生成数据!", QMessageBox.Yes, QMessageBox.Yes)
        #     return
        if row == -1:
            print("你没有选择一行记录")
            QMessageBox.information(self, "温馨提示", "你选择你要编辑的记录!", QMessageBox.Yes, QMessageBox.Yes)
            return
        else:
            self.linkPropsWin.showWin(self.root, junctionID, fromroad, toroad)

    def readPropsListEvent(self):
        junctionID = self.inputID.text().strip()
        if junctionID == "":
            QMessageBox.information(self, "温馨提示", "ID不能为空,请输入!", QMessageBox.Yes, QMessageBox.Yes)
            return
        links = self.root.xpath('//OpenDriveData/junction[@id="' + junctionID + '"]/links/link')
        if len(links) == 0:
            QMessageBox.information(self, "温馨提示", "文档中没有这个ID的记录数据!", QMessageBox.Yes, QMessageBox.Yes)
            return
        _readRow = 0
        for readLink in links:
            readfromroad = readLink.xpath("@fromroad")
            readtoroad = readLink.xpath("@toroad")
            readtype = readLink.xpath("@type")
            readlinkid = readLink.xpath("@id")

            common.tableWidget.setItem(_readRow, 0, QTableWidgetItem(readfromroad[0]))
            common.tableWidget.setItem(_readRow, 1, QTableWidgetItem(readtoroad[0]))
            if readtype[0] == "st":
                common.tableWidget.setItem(_readRow, 2, QTableWidgetItem("直行"))
            elif readtype[0] == "lt":
                common.tableWidget.setItem(_readRow, 2, QTableWidgetItem("左行"))
            elif readtype[0] == "rt":
                common.tableWidget.setItem(_readRow, 2, QTableWidgetItem("右行"))
            elif readtype[0] == "ut":
                common.tableWidget.setItem(_readRow, 2, QTableWidgetItem("掉头"))
            _readRow = _readRow + 1

    def openSignalEditEvent(self):

        row = common.tableWidget.currentIndex().row()
        model = common.tableWidget.model()
        index = model.index(row, 0)  # 选中行第一列的内容
        fromroad = model.data(index)
        index = model.index(row, 1)
        toroad = model.data(index)
        if row == -1 or fromroad == None or toroad == None:
            QMessageBox.information(self, "温馨提示", "请选择一条正确记录!", QMessageBox.Yes, QMessageBox.Yes)
            return
        junctionID = self.inputID.text().strip()
        link = self.root.xpath(
            '//OpenDriveData/junction[@id="' + junctionID + '"]/links/link[@id="' + fromroad + toroad + '"]')
        if len(link) == 0:
            QMessageBox.information(self, "温馨提示", "你编辑的记录在文档中不存在,请先生成!", QMessageBox.Yes, QMessageBox.Yes)
            return

        # if len(common.list) == 0:
        #     QMessageBox.information(self, "温馨提示", "请先生成数据!", QMessageBox.Yes, QMessageBox.Yes)
        #     return
        if row == -1:
            print("你没有选择一行记录")
            QMessageBox.information(self, "温馨提示", "你选择你要编辑的记录!", QMessageBox.Yes, QMessageBox.Yes)
            return
        else:
            self.signalEditWin.showWin(junctionID, fromroad + toroad, fromroad, toroad, )
            # self.linkPropsWin.showWin(self.root, junctionID, fromroad, toroad)

    def openSectionWinEvent(self):
        self.sectionWin.showWin()
Beispiel #48
0
class Example(QWidget):
	def __init__(self):
		super().__init__() 
		self.ventana()
	def ventana(self):
		#Planteamiento de etiquetas
		self.inp= QLineEdit("Numero de datos", self)
		self.inp.move(5,5)
		self.x= QLineEdit(self)
		self.x.move(5,50)
		self.y= QLineEdit(self)
		self.y.move(160,50)
		lbl= QLabel("x", self)
		lbl.move(5, 30)
		lbl2= QLabel("y", self)
		lbl2.move(160, 30)
		self.lbl3= QLabel(self)
		self.lbl3.move(5,75)
		self.inp2=QLineEdit("Conocer X en",self)
		self.inp2.move(5,100)
		self.lbl4= QLabel("y=...", self)
		self.lbl4.move(160,100)
		self.com= QComboBox(self)
		self.com.move(160,5)
		but= QPushButton("Calcular", self)
		but.move(5,130)
		
		
		#Eventos
		self.com.activated[str].connect(self.onAc)
		self.inp.textChanged[str].connect(self.combo)
		self.x.textChanged[str].connect(self.lx)
		self.y.textChanged[str].connect(self.ly)
		self.inp.selectionChanged.connect(self.bor)
		self.x.selectionChanged.connect(self.bor2)
		self.y.selectionChanged.connect(self.bor3)
		self.inp2.selectionChanged.connect(self.bor4)
		but.clicked.connect(self.boton)

		#Ventana
		self.setGeometry(300, 300, 350, 160)
		self.setWindowTitle('Regresion Lineal')
		self.show()
#Metodos de los eventos
	def boton(self):
		sp=0
		ss=0
		ym= 0
		xm= 0
		b1=0
		b0=0
		te= int(self.inp.text())
		for c in range(te):
			ym+= yl[c]
			xm+= xl[c]
		c=0
		ym/=te
		xm/=te
		for c in range(te):
			sp+= (xl[c]-xm)*(yl[c]-ym)
			ss+= (xl[c]-xm)**2
		b1= sp/ss
		b0= ym-(b1*xm)
		if self.inp2.text() == '':
			self.inp2.setText("0")
		cp= float(self.inp2.text()) 		
		r= b0+(b1*cp)
		self.lbl4.setText("y="+str(r))
		self.lbl4.adjustSize()
		self.lbl3.setText("y="+str(b0)+"+("+str(b1)+"x)")
		self.lbl3.adjustSize()
	def bor(self):
		self.inp.clear()
	def bor2(self):
		self.x.clear()
	def bor3(self):
		self.y.clear()
	def bor4(self):
		self.inp2.clear()
	def combo(self, text):
		self.com.clear()
		if text =='':
			text='0'
		for c in range(int(text)):
			self.com.addItem(str(c+1))
			if len(xl)<= c:
				xl.append(0)
				yl.append(0)

	def lx(self, text):
		if text == "":
			text= "0"
		xl[(self.com.currentIndex())]= float(text)
	def ly(self, text):
		if text == "":
			text= "0"
		yl[(self.com.currentIndex())]= float(text)
	def onAc(self, text):
		
		if self.x.text()== " ":
			xl[int(text)-1]= 0
		if self.y.text()== " ":
			yl[int(text)-1]= 0
		self.x.setText(str(xl[int(text)-1]))
		self.y.setText(str(yl[int(text)-1]))
Beispiel #49
0
    def __init__(self):

        super().__init__()  #metodo construtor

        self.title = "TELA DE LOGIN"  #titulo
        self.top = 700  #topo - esquerda para direita
        self.left = 300  #esquerda-cima para baixo
        self.width = 530  #largura
        self.height = 500  #altura
        self.cor_fundo = 'background-color: #A9A9A9'  #cor DarkGray

        ##################################################################################
        ############logo

        #label
        label_logo = QLabel(self)
        label_logo.setText(" LOGIN - SAFIRA")
        label_logo.move(50, 5)  #x,y
        label_logo.setStyleSheet(
            'QLabel {font:bold; font-size:50px; color: #00008B}'
        )  #cor DarkBlue
        label_logo.resize(400, 55)

        #label
        label_trabalho = QLabel(self)
        label_trabalho.setText("CRIPTOMOEDA")
        label_trabalho.move(150, 60)  #x,y
        label_trabalho.setStyleSheet(
            'QLabel {font:bold; font-size:30px; color: #0000CD}'
        )  #cor MediumBlue
        label_trabalho.resize(250, 45)

        #################################################################################
        ###############senha

        #label
        label_ins_senha = QLabel(self)
        label_ins_senha.setText("SENHA:")
        label_ins_senha.move(60, 120)  #x,y
        label_ins_senha.setStyleSheet('QLabel { font: bold; font-size:15px}')
        label_ins_senha.resize(60, 20)

        #caixa de texto
        caixa_texto = QLineEdit(self)
        caixa_texto.move(60, 145)  #x,y
        caixa_texto.resize(180, 30)  #x,y
        caixa_texto.setStyleSheet(
            'QLineEdit{font-size:15px; background-color: #FFFFFF}'
        )  #cor branco

        #################################################################################
        ###############usuario

        #label
        label_usuario = QLabel(self)
        label_usuario.setText("USUÁRIO:")
        label_usuario.move(60, 190)  #x,y
        label_usuario.setStyleSheet('QLabel { font: bold; font-size:15px}')
        label_usuario.resize(70, 20)

        #combobox
        combo_usuario = QComboBox(self)
        combo_usuario.move(60, 215)  #x,y
        combo_usuario.setStyleSheet('QComboBox { font: bold; font-size:15px}')
        combo_usuario.resize(180, 30)

        #################################################################################
        ############### mostrar dados

        #label
        most_inf = QLabel(self)
        most_inf.setText("_dados_")
        most_inf.move(300, 145)  #x,y
        most_inf.setStyleSheet('QLabel { font: bold; font-size:20px}')
        most_inf.resize(150, 30)

        ############################################################################
        #@@@@@@@@@@@@@@@@ entrar

        #botao
        entrar_sist = QPushButton(self)
        entrar_sist.setText("ENTRAR")
        entrar_sist.move(60, 270)
        entrar_sist.resize(150, 40)
        entrar_sist.setStyleSheet('QPushButton { font: bold; font-size: 30px}')
        entrar_sist.clicked.connect(self.entrar_sist_click)

        ############################################################################
        ##################esqueceu senha.

        #botao
        esq_senha = QPushButton(self)
        esq_senha.setText("ESQUECEU SENHA")
        esq_senha.move(60, 350)
        esq_senha.resize(170, 25)
        esq_senha.setStyleSheet('QPushButton { font: bold; font-size: 17px}')
        esq_senha.clicked.connect(self.esq_senha_click)

        ############################################################################
        #@@@@@@@@@@@@@@@@ cadastrar usuario

        #botao
        cad_usu = QPushButton(self)
        cad_usu.setText("CADASTRAR USUÁRIO")
        cad_usu.move(240, 350)
        cad_usu.resize(200, 25)
        cad_usu.setStyleSheet('QPushButton { font: bold; font-size: 17px}')

        ############################################################################
        #@@@@@@@@@@@@@@@@ senha mestra

        #botao
        senha_mestra = QPushButton(self)
        senha_mestra.setText("SENHA MESTRA")
        senha_mestra.move(60, 400)
        senha_mestra.resize(200, 25)
        senha_mestra.setStyleSheet(
            'QPushButton { font: bold; font-size: 17px}')

        ############################################################################
        #@@@@@@@@@@@@@@@@ icone na barra de tarefa linux mint

        self.setWindowIcon(
            QtGui.QIcon("safira.jpg"))  # aparece na berra de tarefa

        self.InitWindow()
class VisualizationWindow(QWidget):

    def __init__(self, application, room, *args, **kwargs):
        '''
        Class defining main window and basic GUI widgets.
        :param application: parent application
        :param room: Room() instance, which is loaded and parsed input file
        '''
        super(VisualizationWindow, self).__init__(*args, **kwargs)

        # initializing error handler in case of exceptions
        self._error_handler = ErrorHandler()

        # assigning application as a class attribute just in case, e.g. for getting screen size
        self._application = application

        # assigning room as a class attribute for easier argument passing
        self.room = room

        # specifying window size
        self._width = 1280
        self._height = 720

        # setting window parameters such as size, position and title
        screen_center = self._application.desktop().screen().rect().center()
        self.setGeometry(screen_center.x() - self._width * .5,
                         screen_center.y() - self._height * .5,
                         self._width,
                         self._height)
        self.setWindowTitle('Ray Tracing Method 4-dimensional visualization')
        self.setFixedSize(self._width, self._height)

        # creating OpenGL widget area
        self._opengl_widget = OpenGLWidget(self)

        # creating source parameters label
        self._source_parameters_lbl = QLabel('Source parameters:', self)
        self._source_parameters_lbl.move(22, 20)

        # creating source coordinates labels and text fields
        self._source_x_lbl = QLabel('X:', self)
        self._source_x_lbl.move(22, 50)
        self._source_x_text = QLineEdit(self)
        self._source_x_text.setFixedWidth(57)
        self._source_x_text.move(40, 46)

        self._source_y_lbl = QLabel('Y:', self)
        self._source_y_lbl.move(112, 50)
        self._source_y_text = QLineEdit(self)
        self._source_y_text.setFixedWidth(57)
        self._source_y_text.move(130, 46)

        self._source_z_lbl = QLabel('Z:', self)
        self._source_z_lbl.move(202, 50)
        self._source_z_text = QLineEdit(self)
        self._source_z_text.setFixedWidth(57)
        self._source_z_text.move(220, 46)

        # creating source SPL label and text field
        self._source_spl_lbl = QLabel('SPL [dB]:', self)
        self._source_spl_lbl.move(22, 80)
        self._source_spl_text = QLineEdit(self)
        self._source_spl_text.setFixedWidth(190)
        self._source_spl_text.move(87, 76)

        # creating source frequency label and dropdown list
        self._source_freq_lbl = QLabel('Frequency [Hz]:', self)
        self._source_freq_lbl.move(22, 110)
        self._source_freq_dropdown = QComboBox(self)
        self._source_freq_dropdown.addItems(['125', '250', '500', '1000', '2000', '4000'])
        self._source_freq_dropdown.setFixedWidth(146)
        self._source_freq_dropdown.move(131, 106)

        # creating simulation button
        self._simulation_button = QPushButton('Start simulation', self)
        self._simulation_button.setFixedSize(257, 60)
        self._simulation_button.move(20, 160)
        self._simulation_button.clicked[bool].connect(self._start_simulation)

        self.show()

    def _start_simulation(self):
        '''
        Method disabling all Qt widgets and starting OpenGL animation.
        '''
        try:   # exception handling in case of wrong input values
            source_pos = (   # source position tuple
                float(self._source_x_text.text()),   # source position x
                float(self._source_z_text.text()),   # source position y
                float(self._source_y_text.text())    # source position z
            )
            source_spl = float(self._source_spl_text.text()),   # source sound pressure level
            source_spl = source_spl[0] if type(source_spl) == type(tuple()) else source_spl
            source_freq = int(self._source_freq_dropdown.currentText())   # source frequency
        except Exception as e:   # in case of exception
            self._error_handler.raise_dialog(str(e))   # raise dialog window with exception description
            return   # and return to prevent function from proceeding

        # disabling all widgets
        self._source_parameters_lbl.setDisabled(True)
        self._source_x_lbl.setDisabled(True)
        self._source_x_text.setDisabled(True)
        self._source_y_lbl.setDisabled(True)
        self._source_y_text.setDisabled(True)
        self._source_z_lbl.setDisabled(True)
        self._source_z_text.setDisabled(True)
        self._source_spl_lbl.setDisabled(True)
        self._source_spl_text.setDisabled(True)
        self._source_freq_lbl.setDisabled(True)
        self._source_freq_dropdown.setDisabled(True)
        self._simulation_button.setDisabled(True)

        # initializing OpenGL animation
        self._opengl_widget.initialize_animation(source_pos=source_pos, source_spl=source_spl, source_freq=source_freq)
Beispiel #51
0
class Main(QMainWindow):
    def __init__(self):
        super().__init__()
        self.api = None
        self.logged_in = False
        self.init_ui()

    def init_ui(self):
        self.statusBar().showMessage('')
        self.setFixedSize(1000, 700)
        self.setWindowTitle('Travian Bot v1.0')
        self.add_toolbar()
        self.build_main()
        self.build_buildings()
        self.build_resources()

        self.show()

    def build_resources(self):
        self.resources_widget = QWidget(self)
        self.resources_widget.hide()
        self.resources_widget.move(0, 60)
        self.resources_widget.resize(1000, 610)
        self.resources_widget.setAutoFillBackground(True)

        label = QLabel('Ресурсы', self.resources_widget)
        label.move(20, 10)

    def build_buildings(self):
        self.buildings_widget = QWidget(self)
        self.buildings_widget.hide()
        self.buildings_widget.move(0, 60)
        self.buildings_widget.resize(1000, 610)
        self.buildings_widget.setAutoFillBackground(True)

        label = QLabel('Центр деревни', self.buildings_widget)
        label.move(20, 10)

    def build_main(self):
        self.main_widget = QWidget(self)
        self.main_widget.hide()
        self.main_widget.move(0, 60)
        self.main_widget.resize(1000, 610)
        self.main_widget.setAutoFillBackground(True)

        servers_label = QLabel('Сервер', self.main_widget)
        servers_label.move(20, 10)

        self.server_combo = QComboBox(self.main_widget)
        self.server_combo.addItem('RU (tx3)', ['ru', 'tx3'])
        self.server_combo.resize(220, 25)
        self.server_combo.move(14, 30)

        self.login = QLineEdit(self.main_widget)
        self.login.setPlaceholderText('Логин')
        self.login.resize(220, 25)
        self.login.move(20, 60)

        self.passw = QLineEdit(self.main_widget)
        self.passw.setEchoMode(QLineEdit.PasswordEchoOnEdit)
        self.passw.setPlaceholderText('Пароль')
        self.passw.resize(220, 25)
        self.passw.move(20, 90)

        self.race_label = QLabel('Раса: -', self.main_widget)
        self.race_label.move(850, 10)
        self.race_label.setFixedWidth(140)
        # self.status_label = QLabel('Статус: -', self.main_widget)
        # self.status_label.move(850, 30)

        self.login_btn = QPushButton('ОК', self.main_widget)
        self.login_btn.resize(110, 40)
        self.login_btn.move(14, 120)
        self.login_btn.clicked.connect(self.log_in)

        self.logout_btn = QPushButton('Выйти', self.main_widget)
        self.logout_btn.resize(110, 40)
        self.logout_btn.move(14, 120)
        self.logout_btn.clicked.connect(self.log_out)
        self.logout_btn.hide()

    def add_toolbar(self):
        action_params = [
            ('Главная', 'img/a_main.png', self.main),
            ('Ресурсы', 'img/a_resources.png', self.resources),
            ('Центр деревни', 'img/a_buildings.png', self.buildings),
        ]
        tool_bar = QToolBar()
        tool_bar.setMovable(False)
        tool_bar.setIconSize(QSize(48, 48))

        for name, icon, action in action_params:
            _action = QAction(QIcon(icon), name, self)
            _action.triggered.connect(action)
            tool_bar.addAction(_action)

        tool_bar.addSeparator()

        self.village_list = QComboBox()
        self.village_list.setFixedSize(220, 25)
        self.village_list.currentIndexChanged.connect(self.set_current_village)
        tool_bar.addWidget(self.village_list)

        self.addToolBar(tool_bar)

    def set_current_village(self):
        self.api.set_village(self.village_list.currentData())

    def log_out(self):
        self.statusBar().showMessage('')
        try:
            self.api.logout()
            self.set_online_status()
            self.statusBar().showMessage('Успешно')
        except:
            self.statusBar().showMessage('Ошибка выхода с учетной записи!')

    def log_in(self):
        self.statusBar().showMessage('')
        domain, world = self.server_combo.currentData()
        login = self.login.text()
        passw = self.passw.text()

        self.api = TravianApi(login, passw, world, domain)

        try:
            self.api.login()
            self.set_online_status(STATUS_ONLINE)
            self.statusBar().showMessage('Успешно')
        except:
            self.set_online_status(STATUS_OFFLINE)
            self.statusBar().showMessage('Ошибка авторизации!')

    def set_online_status(self, status=STATUS_OFFLINE):
        self.logged_in = bool(status)

        if status == STATUS_OFFLINE:
            self.login.setDisabled(False)
            self.passw.setDisabled(False)
            self.server_combo.setDisabled(False)
            self.login_btn.show()
            self.logout_btn.hide()
            self.village_list.clear()
            self.set_race()
        else:
            self.login.setDisabled(True)
            self.passw.setDisabled(True)
            self.server_combo.setDisabled(True)
            self.login_btn.hide()
            self.logout_btn.show()
            self.get_villages()
            self.set_race()

    def set_race(self):
        if not self.logged_in:
            self.race_label.setText('Раса: -')
            return

        race = self.api.get_race()
        self.race_label.setText('Раса: {}'.format(race))

    def get_villages(self):
        self.village_list.clear()
        for v in self.api.list_villages():
            self.village_list.addItem('{} (ID: {})'.format(v.name, v.id), v.id)

    def main(self):
        self.buildings_widget.hide()
        self.resources_widget.hide()
        self.main_widget.show()

    def resources(self):
        self.main_widget.hide()
        self.buildings_widget.hide()
        self.resources_widget.show()

    def buildings(self):
        self.main_widget.hide()
        self.resources_widget.hide()
        self.buildings_widget.show()