Ejemplo n.º 1
0
class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        # This is always the same
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
Ejemplo n.º 2
0
class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        global ui
        super(ApplicationWindow, self).__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
Ejemplo n.º 3
0
class Browser(QtWidgets.QMainWindow):
    def __init__(self):
        super(Browser, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.url = self.make_true_url('http://127.0.0.1:5000')
        self.ui.webView.load(self.url)

        self.ui.reloadButton.clicked.connect(self.ui.webView.reload)
        self.ui.backButton.clicked.connect(self.ui.webView.back)
        self.ui.goButton.clicked.connect(self.go_to_page)
        self.ui.urlLine.setText(
            re.findall("('.+')", str(self.ui.webView.url()))[0][1:-1])

        self.ui.webView.urlChanged.connect(self.update_urlbar)
        self.ui.webView.titleChanged.connect(self.update_title)

    @staticmethod
    def make_true_url(url):
        return QUrl(url) if QUrl(url).scheme() else QUrl('http://' + url)

    def go_to_page(self):
        self.url = self.make_true_url(self.ui.urlLine.text())
        self.ui.webView.load(self.url)

    def update_urlbar(self):
        self.ui.urlLine.setText(
            re.findall("('.+')", str(self.ui.webView.url()))[0][1:-1])

    def update_title(self):
        title = self.ui.webView.page().title()
        self.setWindowTitle(f'{title} - MiniBrowser')
class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setFixedSize(WIDTH, HEIGHT)
        self.ui.submit_Btn.clicked.connect(self.run)

    def run(self):
        try:
            file_name = self.ui.file_path_textEdit.toPlainText()
            iterations = int(self.ui.iterations_textEdit.toPlainText())
            delimiter = self.ui.delimiter_textEdit.toPlainText()
            learning_rate = float(self.ui.learning_rate_textEdit.toPlainText())
            get_gradient_descent(file_name, learning_rate, delimiter,
                                 iterations)
        except Exception as ex:
            self.display_error(str(ex))

    def display_error(self, message):
        msg = QtGui.QMessageBox()
        msg.setIcon(QtGui.QMessageBox.Warning)
        msg.setWindowTitle("Error")
        msg.setInformativeText(message)
        msg.exec_()
Ejemplo n.º 5
0
class MainApp:
    def __init__(self):

        self.init_ui()

    def init_ui(self):
        self.app = QtWidgets.QApplication(sys.argv)
        self.MainWindow = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.MainWindow)

    def init_listeners(self):
        self.ui.pushButtonTSNE.clicked.connect(self.tsne)
        self.ui.pushButtonHist.clicked.connect(self.hist)

    def tsne(self):
        path = self.ui.lineEdit.text()
        print(path)
        self.ts = tsne(path)

    def hist(self):
        path = self.ui.lineEdit.text()
        self.pt = starts(path)

    def start(self):
        self.ui.setupUi(self.MainWindow)
        self.init_listeners()
        self.MainWindow.show()
        sys.exit(self.app.exec_())
Ejemplo n.º 6
0
def main():
    app = QApplication(sys.argv)
    main_window = QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(main_window)
    main_window.show()

    sys.exit(app.exec_())
Ejemplo n.º 7
0
class MainWin(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWin, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.let_rice_val.setText("800")
        self.ui.let_rice_per_sushi.setText("160")

        self.show_msg = QtWidgets.QMessageBox()
        self.ui.pbn_calc.clicked.connect(self.calc_sushi_vals)
        self.ui.pbn_reset.clicked.connect(self.reset_vals)

    def calc_sushi_vals(self):

        res = self.check_input(self.ui.let_rice_val.text())

        if res == -1:
            return
        res = self.check_input(self.ui.let_rice_per_sushi.text())

        if res == -1:
            return
        rice = float(self.ui.let_rice_val.text())
        rice_per_sushi = float(self.ui.let_rice_per_sushi.text())

        acid_calc = str(round(rice * 11 / 100))
        shugar_calc = str(round(rice * 9 / 100))
        salt_calc = str(round(rice * 1 / 100))
        water_calc = str(round(rice * 111 / 100))

        total_sushi_calc = str(round(
            (rice + int(water_calc)) / rice_per_sushi))
        self.ui.let_acid_val.setText(acid_calc)
        self.ui.let_shugar_val.setText(shugar_calc)
        self.ui.let_salt_val.setText(salt_calc)
        self.ui.let_water_val.setText(water_calc)
        self.ui.let_total_sushu_cnt.setText(total_sushi_calc)

    def check_input(self, string):
        ciphers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        if len(string) == 0:
            self.show_msg.critical(None, "Ошибка ввода", "Пустое поле ввода")
            return -1
        for i, char in enumerate(string):
            if char not in ciphers:
                self.show_msg.critical(None, "Ошибка ввода",
                                       "В поле ввода находится не число!")
                return -1

    def reset_vals(self):
        self.ui.let_rice_val.setText("800")
        self.ui.let_rice_per_sushi.setText("160")
        self.ui.let_salt_val.clear()
        self.ui.let_shugar_val.clear()
        self.ui.let_water_val.clear()
        self.ui.let_acid_val.clear()
        self.ui.let_total_sushu_cnt.clear()
Ejemplo n.º 8
0
Archivo: main1.py Proyecto: aisyluG/LR3
class Window(QMainWindow):
    semaphore = QSemaphore()
    input_sended = pyqtSignal()
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.input = None
        # self.thr = Thread().
        self.timer = QTimer()
        self.reader_Thread = QThread()
        self.reader = ConsoleReader(self.semaphore, self.timer)
        self.reader.moveToThread(self.reader_Thread)

        self.writer_Thread = QThread()
        self.writer = ConsoleWriter(self.semaphore)
        self.writer.moveToThread(self.writer_Thread)

        self.ui.startBt.clicked.connect(self.startProcess)
        self.writer.process_created.connect(self.pp)
        # self.writer.process_created.connect(self.reader.set_pipe)
        self.reader.readed.connect(self.addToConsole)
        self.ui.sendBt.clicked.connect(self.addInput)
        # self.timer.timeout.connect(self.ii)
        # self.timer.timeout.connect(self.timer.stop)

        self.reader_Thread.start()
        self.writer_Thread.start()


    def ii(self):
        print('stopped')
        # self.reader_Thread.terminate()
        self.reader.thread().wait()

    def pp(self, process):
        self.reader.set_pipe(process)

    def addToConsole(self, output):
        self.ui.outputText.append(output)

    def startProcess(self):
        path = self.ui.comandLine.text()
        if '\\' in path:
            path = path.replace('\\', '/')
            # print(path)
        self.writer.createProcess(path)
        self.reader.run()

    def addInput(self):
        input = self.ui.inputText.text()
        self.writer.write(input)
        self.ui.outputText.append('>'+input)
Ejemplo n.º 9
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Exit QAction
        exit_action = QAction("Exit", self)
        exit_action.setShortcut(QKeySequence.Quit)
        exit_action.triggered.connect(self.close)

        self.ui.menuFile.addAction(exit_action)

        # Window dimensions
        geometry = qApp.desktop().availableGeometry(self)
        self.setFixedSize(geometry.width() * 0.8, geometry.height() * 0.7)
Ejemplo n.º 10
0
class Main(QtGui.QMainWindow):
	def __init__(self):
		QtGui.QMainWindow.__init__(self)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		self.ui.startwifi.clicked.connect(self.startwifi_clicked)
		self.ui.stopwifi.clicked.connect(self.stopwifi_clicked)
		self.ui.exitapp.clicked.connect(self.exitapp_clicked)

		self.ui.actionAbout.triggered.connect(self.actionAbout_triggered)
		self.ui.popAboutDailog = aboutDialog()

		self.ui.stopwifi.setEnabled(False)

	def startwifi_clicked(self):
		ssid = str(self.ui.wifiname.text())
		password = str(self.ui.wifipassword.text())

		if ssid == '' or password == '':
			self.ui.status.setText("Invalid Name & Password")
		else:
			os.system('netsh wlan set hostednetwork mode=allow ssid='+ssid+' key='+password+'')
			os.system('netsh wlan start hostednetwork')
			self.ui.status.setText("Hotspot Started")
			self.ui.startwifi.setEnabled(False)
			self.ui.stopwifi.setEnabled(True)


	def stopwifi_clicked(self):
		self.ui.startwifi.setEnabled(True)
		self.ui.stopwifi.setEnabled(False)
		os.system('netsh wlan stop hostednetwork')
		self.ui.status.setText("Hotspot Stopped")

	def exitapp_clicked(self):
		self.close()

	def actionAbout_triggered(self):
		self.ui.popAboutDailog.show()
Ejemplo n.º 11
0
class Window(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        highlight = syntax.PythonHighlighter(self.ui.editor.document())
        self.ui.editor.document().setDefaultFont(QFont("Monospace", 10, QFont.Normal))

        self.connect(self.ui.actionRun, SIGNAL("triggered()"), self.on_run_program)

    def load(self, fd):
        self.ui.editor.setPlainText(fd.read())

    def currentText(self):
        return self.ui.editor.toPlainText()

    def on_run_program(self):
        out = StringIO()
        runner = PythonRunner(out)
        runner.execute(str(self.currentText()))
        out.seek(0)
        self.ui.console.insertPlainText(out.read())
Ejemplo n.º 12
0
class DojoShare(QtWidgets.QMainWindow):
    def __init__(self):
        super(DojoShare, self).__init__()
        netList = get_interfaces_addresses()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.comboBox.addItems(netList)
        self.ui.pushButton.clicked.connect(self.buttonClicked)
        self.server_thread = Thread(target=self.start_server)

    def start_server(self):
        flask_app.run(debug=False, port=80, host=self.ui.comboBox.currentText())
        
    def buttonClicked(self):
        self.server_thread.start()
        self.ui.pushButton.setText("Sarvar started")
        self.ui.pushButton.setEnabled(False)
        self.ui.comboBox.setEnabled(False)
        self.ui.label_2.setText("<a href='http://"+self.ui.comboBox.currentText()+"'>http://"+self.ui.comboBox.currentText()+"</a>")
        self.ui.label_2.setOpenExternalLinks(True)
        
    def closeEvent(self, closedEvent):
        self.server_thread._stop()
Ejemplo n.º 13
0
class ShipHolderApplication(QMainWindow):
    def __init__(self, parent=None):
        super (ShipHolderApplication,self).__init__(parent)
        self.createWidgets()
        self.connectActions()
        #item to print
        self.printNo = 0
        
        #Stock bibitem a ecrire dans le fichier
        self.towrite = []
        self.lastfile = ""
        
    def createWidgets(self):
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
    def connectActions(self):
        self.ui.pushButton.connect(self.ui.pushButton,SIGNAL('clicked()'), self.Searching)
        self.ui.pushButton_2.connect(self.ui.pushButton_2,SIGNAL('clicked()'),app,SLOT('quit()'))
        self.ui.pushButton_3.connect(self.ui.pushButton_3,SIGNAL('clicked()'),app,SLOT('quit()'))
        self.ui.pushButton_4.connect(self.ui.pushButton_4,SIGNAL('clicked()'),app,SLOT('quit()'))
        self.ui.pushButton_5.connect(self.ui.pushButton_5,SIGNAL('clicked()'),app,SLOT('quit()'))

    def Searching(self):
        title = str(self.ui.lineEdit.text())
        author = str(self.ui.lineEdit_2.text())
        print author
        #print str(MyString)
        self.printNo = 0
        mySearch = TheSearch()
        mySearch.ToSearch(title.encode("utf-8"),author.encode("utf-8"))
        self.toprint = mySearch.DoSearch()

        #self.labelVariable.set(self.toprint[0].EntryToString())
        #print self.toprint[0].EntryToString())
        self.totalnumber = len(self.toprint)
Ejemplo n.º 14
0
class interface_window(QtWidgets.QMainWindow):
    def __init__(self):
        super(interface_window, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #self.ui.pushButton.clicked.connect(self.flashSplash)
        self.ui.pushButton.released.connect(self.ProcessorParsing)
        #self.ui.pushButton_4.clicked.connect(self.flashSplash)
        self.ui.pushButton_4.released.connect(self.VideocardParsing)
        #self.ui.pushButton_3.clicked.connect(self.flashSplash)
        self.ui.pushButton_3.released.connect(self.Ram_DIMMParsing)
        self.ui.ViewModeBtn.clicked.connect(self.View)
        self.list_get_requests = [
            "https://www.dns-shop.ru/catalog/17a89aab16404e77/videokarty/",
            "https://www.dns-shop.ru/catalog/17a899cd16404e77/processory/",
            "https://www.dns-shop.ru/catalog/17a89a3916404e77/operativnaya-pamyat-dimm/"
        ]
        self.ViewMode_ = None
        self.data_about_proc = list()
        self.data_about_gp = list()
        self.data_about_ram = list()
        dir = os.path.abspath(os.curdir)
        #self.splash = QtWidgets.QSplashScreen(QtGui.QPixmap(dir[:-6] + 'resource/icons8-loading-bar-100.png'))

    def ProcessorParsing(self):
        #self._toggle_buttons_(False)
        self.thread = QtCore.QThread()
        self.worker = getData()
        self.worker.request = self.list_get_requests[1]
        self.worker.moveToThread(self.thread)
        self.thread.started.connect(self.worker.run_parsing_proc)
        self.worker.finished.connect(self.thread.quit)
        self.worker.finished.connect(self.worker.deleteLater)
        self.worker.finished.connect(
            lambda: self.ui.pushButton.setEnabled(True))
        self.thread.finished.connect(self.thread.deleteLater)
        self.thread.start()
        self.ui.pushButton.setEnabled(False)
        #QtCore.QTimer.singleShot(5000, self.splash.close)

    def VideocardParsing(self):
        #self._toggle_buttons_(False)
        self.thread_2 = QtCore.QThread()
        self.worker_2 = getData()
        self.worker_2.request = self.list_get_requests[0]
        self.worker_2.moveToThread(self.thread_2)
        self.thread_2.started.connect(self.worker_2.run_parsing_gpu)
        self.worker_2.finished_1.connect(self.thread_2.quit)
        self.worker_2.finished_1.connect(self.worker_2.deleteLater)
        self.worker_2.finished_1.connect(
            lambda: self.ui.pushButton_4.setEnabled(True))
        self.thread_2.finished.connect(self.thread_2.deleteLater)
        self.thread_2.start()
        self.ui.pushButton_4.setEnabled(False)
        #QtCore.QTimer.singleShot(5000, self.splash.close)

    def Ram_DIMMParsing(self):
        #self._toggle_buttons_(False)
        self.thread_3 = QtCore.QThread()
        self.worker_3 = getData()
        self.worker_3.request = self.list_get_requests[2]
        self.worker_3.moveToThread(self.thread_3)
        self.thread_3.started.connect(self.worker_3.run_parsing_ram)
        self.worker_3.finished_2.connect(self.thread_3.quit)
        self.worker_3.finished_2.connect(self.worker_3.deleteLater)
        self.worker_3.finished_2.connect(
            lambda: self.ui.pushButton_3.setEnabled(True))
        self.thread_3.finished.connect(self.thread_3.deleteLater)
        self.thread_3.start()
        self.ui.pushButton_3.setEnabled(False)
        #QtCore.QTimer.singleShot(5000, self.splash.close)

    def flashSplash(self):
        self.splash.show()

    def View(self):
        self.ViewMode_ = None
        if not self.ViewMode_:
            self.ViewMode_ = ViewMode()
        self.ViewMode_.show()
class ApplicationWindow(QMainWindow):
    def __init__(self):
        super(ApplicationWindow, self).__init__()

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

        self.udm = None

        self.ui.base_data_btn.clicked.connect(self.on_base_btn_clicked)
        self.ui.user_data_btn.clicked.connect(self.on_user_btn_clicked)
        self.ui.item_data_btn.clicked.connect(self.on_item_btn_clicked)
        self.ui.load_data_btn.clicked.connect(self.on_load_data)
        self.ui.process_btn.clicked.connect(self.on_process)
        self.ui.save_btn.clicked.connect(self.on_save_matrix)
        self.ui.load_matrix_btn.clicked.connect(self.on_load_matrix)
        self.ui.run_dbscan_btn.clicked.connect(self.on_run_dbscan)

        self.ui.filtering_methods_cb.addItems([
            "Colabortive filtering", "Semantic filtering",
            "Weighted Hybrid filtering",
            "Semantic Colabrative Hybrid filtering"
        ])

    def on_base_btn_clicked(self):
        self.ui.base_data_path.setText(
            QFileDialog.getOpenFileName(self, "Base Dataset File",
                                        "/home/imad", "base (*.base)")[0])
        print('[input file]', self.ui.base_data_path.text())

    def on_item_btn_clicked(self):
        self.ui.item_data_path.setText(
            QFileDialog.getOpenFileName(self, "item File", "/home/imad",
                                        "item (*.item)")[0])
        print('[input file]', self.ui.item_data_path.text())

    def on_user_btn_clicked(self):
        self.ui.user_data_path.setText(
            QFileDialog.getOpenFileName(self, "Base Dataset File",
                                        "/home/imad", "user (*.user)")[0])
        print('[input file]', self.ui.user_data_path.text())

    def on_load_data(self):
        print('[load data] started')
        self.ui.status_label.setText('Loading data...')
        self.usage_matrix, self.movie_matrix = load_data(
            self.ui.base_data_path.text(), self.ui.user_data_path.text(),
            self.ui.item_data_path.text())
        print('[load data] finished')
        self.ui.status_label.setText('Done')

    def on_process(self):
        self.ui.status_label.setText('Processing...')
        print('[processing]', self.ui.filtering_methods_cb.currentText())
        self.udm = self.filter()
        self.ui.status_label.setText('Done')
        print('[Done]', self.ui.filtering_methods_cb.currentText())
        print(self.udm)

    def filter(self):
        if self.ui.filtering_methods_cb.currentIndex() == 0:
            return colaboratif_distance(self.usage_matrix)
        elif self.ui.filtering_methods_cb.currentIndex() == 1:
            return semantic_distance(self.usage_matrix, self.movie_matrix)
        elif self.ui.filtering_methods_cb.currentIndex() == 2:
            return None
        elif self.ui.filtering_methods_cb.currentIndex() == 3:
            return None

    def on_save_matrix(self):
        if self.udm is None:
            self.ui.status_label.setText(
                "<font color='red'>Matrix isn't ready to save</font>")
            return None
        filename = QFileDialog.getSaveFileName(self, 'Save Matrix')
        print(filename)
        if filename is not None: save_dist_matrix(filename[0], self.udm)

    def on_load_matrix(self):
        self.ui.matrix_file_path.setText(
            QFileDialog.getOpenFileName(self, "CSV distance matrix",
                                        "/home/imad", "csv (*.csv)")[0])
        print('[input file]', self.ui.matrix_file_path.text())

    def on_run_dbscan(self):
        if self.ui.matrix_file_path.text() == '':
            self.ui.status_label.setText(
                "<font color='red'>No data specified</font>")
            return None
        self.ui.status_label.setText("Loading data...")
        self.udm = load_dist_matrix(self.ui.matrix_file_path.text())
        self.ui.status_label.setText("Running dbscan for :{}...".format(
            self.ui.matrix_file_path.text()))
        dbs = dbscan.dbscan(self.udm,
                            float(self.ui.eps_edit.text()),
                            int(self.ui.min_points_edit.text()),
                            data_type="distance_matrix")
        dbs.process()

        self.ui.status_label.setText("Done.")
        print(dbs.get_clusters)
Ejemplo n.º 16
0
Archivo: CC02.py Proyecto: rouxinol/Lab
class StartQT4(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        
        #connect to run button
        
        QtCore.QObject.connect(self.ui.runButton, QtCore.SIGNAL(("clicked()")), self.handleCalculate)
        QtCore.QObject.connect(self.ui.plotBtn,   QtCore.SIGNAL(("clicked()")), self.plotData)
      #  QtCore.QObject.connect(self.ui.plotBtn,   QtCore.SIGNAL(("clicked()")), self.handleCalculate)
       
       
#    def plotData(self):
#        x, y = rand(2, 30)
#        self.ui.plotWidget.canvas.ax.plot(x, y, 'o')
#        self.ui.plotWidget.canvas.draw()
 
    def plotData(self):
        self.handleCalculate()
        w   = float(str(self.ui.wEdit.text()))
        s   = float(str(self.ui.sEdit.text()))
        t   = float(str(self.ui.tEdit.text()))
        h   = float(str(self.ui.hEdit.text()))
        l   = float(str(self.ui.lEdit.text()))
        e   = float(str(self.ui.eEdit.text()))
        rho = float(str(self.ui.rhoEdit.text()))
        tc  =  float(str(self.ui.tcEdit.text()))
        ck  = float(str(self.ui.ccEdit.text()))
        Tg  = float(str(self.ui.tgEdit.text()))
        ck = []
        Ql = []
        for n in range(0,len(Ccap)):
           # print 'n = ', n
           # print 'Ccap = ', Ccap[n]
            
            ck.append(Ccap[n])
           # print 'ck=  ', ck[n] eeff,l0,Lk,Ll,Cl,f0,alfa, z0,L,C,R,F0,Qi,Rstar,Cstar,fstar,Qext,
            
            Qload = cal(w,s,t,h,l,e,rho,tc,ck[n],Tg)[17] 
            Ql.append(Qload)
            
        savetxt('Ql.txt',Ql)
            #print 'end'
        
        self.ui.plotWidget.canvas.ax.plot(ck, Ql, marker='o', linestyle='-', color='r')
#            axes[0].plot(ng_vec, energies[:,n])
            #self.ui.plotWidget.canvas.ax.set_ylim(-10, ymax[0])
        self.ui.plotWidget.canvas.ax.set_yscale('log')
        self.ui.plotWidget.canvas.ax.set_xscale('log')
        self.ui.plotWidget.canvas.ax.set_xlabel(r'$C_c$', fontsize=12)
        self.ui.plotWidget.canvas.ax.set_ylabel(r'$Q_l$', fontsize=12)
            
            #self.ui.plotWidget.canvas.ax.plot(x, y, 'o')
       #     self.ui.plotWidget.canvas.draw()
        self.ui.plotWidget.canvas.draw()

### TEst
# #       def newWindow(self):
#        self.myOtherWindow = Plot_Widget()
#        self.myOtherWindow.show()
#        #app = QApplication(sys.argv)
#        #plot = Plot_Widget()#data2plot,  varDict = totaldict)
#        #plot.show()
#         #sys.exit(app.exec_()) 
### TEST


            
    def handleCalculate(self):
        w   = float(str(self.ui.wEdit.text()))
        s   = float(str(self.ui.sEdit.text()))
        t   = float(str(self.ui.tEdit.text()))
        h   = float(str(self.ui.hEdit.text()))
        l   = float(str(self.ui.lEdit.text()))
        e   = float(str(self.ui.eEdit.text()))
        rho = float(str(self.ui.rhoEdit.text()))
        tc  =  float(str(self.ui.tcEdit.text()))
        ck  = float(str(self.ui.ccEdit.text()))
        Tg  = float(str(self.ui.tgEdit.text()))
        #print ck
        
        
        
        
        eeff,l0,Lk,Ll,Cl,f0,alfa, z0,L,C,R,F0,Qi,Rstar,Cstar,fstar,Qext,Qload = cal(w,s,t,h,l,e,rho,tc,ck,Tg)
        #print ans
        self.ui.eeffLabel.setText( str("%.3f" % (eeff)))
        self.ui.lambdaLabel.setText( str("%.3E" % (l0)))
        self.ui.kineticLabel.setText('%.3E H/m' % (Lk)) 
        self.ui.alfaLabel.setText( str("%.3E" % (alfa)))
        
        self.ui.fEdit.setText(str("%.3E" % (f0)))
        self.ui.llEdit.setText(str("%.3E" % ((Ll))))
        self.ui.clEdit.setText(str("%.3E" % ((Cl))))
        self.ui.z0Edit.setText(str("%.2f" % ((z0))))
        
        self.ui.LEdit.setText(str("%.2E" % ((L))))
        self.ui.CEdit.setText(str("%.2E" % ((C))))
        self.ui.REdit.setText(str("%.2E" % ((R))))
        self.ui.f0Edit.setText(str("%.2E" % ((F0))))
        self.ui.qiEdit.setText(str("%.2f" % ((Qi/1e3))))
        self.ui.qeEdit.setText(str("%.2f" % ((Qext/1e3))))
        self.ui.qlEdit.setText(str("%.2f" % ((Qload/1e3))))
        self.ui.frEdit.setText(str("%.3E" % ((fstar))))
Ejemplo n.º 17
0
class Main(QtGui.QMainWindow):
    
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self.connect(self.ui.btnZapis, SIGNAL("clicked()"), self.btnZapis_Clicked)
        self.connect(self.ui.btnSmazat, SIGNAL("clicked()"), self.btnSmazat_Clicked)
        self.connect(self.ui.btnPrepocitat, SIGNAL("clicked()"), self.btnPrepocitat_Clicked)
        #self.connect(self.ui.tblVypis, SIGNAL(""), self.tableWidget_Pressed)
        
        # Define classes of widgets
        self.mysql = Mysql()
        self.vypis = Vypis(self.ui.tblVypis)        
        self.matplot = MatPlot(self.ui.matplot)
        
        # Do start functions
        self.starting()
        
    def starting(self):
        # Write out data to table widget
        self.vypis.writeOutData()
        
        # Plot the cashflow
        x = self.vypis.get_allCash()
        self.matplot.plot(x)
        
        # Populate database
#         data = self.vypis.get_csvData()
#         self.mysql.populate(data)
           
        
    def reload(func):
        def magic(self):
            func(self)
            self.matplotCashflow2()
        return magic
            
    #@reload
    def btnSmazat_Clicked(self):
        row = self.ui.tblVypis.currentRow()
        self.ui.tblVypis.removeRow(row)
        # is needed to recount all items
        self.vypis.recount()
       
    def btnPrepocitat_Clicked(self):
        self.vypis.recount()
    
    def countCsvFile(self):
        with open('cashflow.csv', 'r') as f:
            rowCount = 0
            for lastrow in csv.reader(f):
                rowCount += 1
            return rowCount
        
    def get_lastRow(self):
        with open('cashflow.csv', 'r') as f:
            lastrow = None
            self.rowCount = 0
            for lastrow in csv.reader(f):
                self.rowCount += 1
                pass
            return lastrow
             
    def btnZapis_Clicked(self):
        with open('cashflow.csv', 'a') as f:
            writer = csv.writer(f, delimiter=';', lineterminator='\n')
            
            date = time.strftime("%d:%m",time.gmtime(CZ_TIME))
            hour = time.strftime("%H:%M",time.gmtime(CZ_TIME))
            # current money
            money = int(self.get_lastRow()[0].split(";")[-2])
            predmet = self.ui.txtPredmet.text()
            pohyb = int(self.ui.spinBoxPohyb.text())
            writer.writerow([CZ_TIME, date, hour, predmet, pohyb, money + pohyb, None])
        self.vypis.writeOutData()
Ejemplo n.º 18
0
class Main_Window(QtWidgets.QMainWindow):
    #Variables
    next_question_pushed = False
    game_instance = Game()
    grid_row = 0
    grid_column = 0
    timer_thread = Thread()
    timer_thread.start()
    time_left = 0
    current_image_selection = Path('img\default.jpeg')
    question_manager_widget = None
    edit_question = None

    def __init__(self):
        super(Main_Window, self).__init__()
        frameGm = self.frameGeometry(
        )  # Center the windows on the current screen
        screen = QtWidgets.QApplication.desktop().screenNumber(
            QtWidgets.QApplication.desktop().cursor().pos())
        centerPoint = QtWidgets.QApplication.desktop().screenGeometry(
            screen).center()
        frameGm.moveCenter(centerPoint)
        grid_radio_buttons = QtWidgets.QButtonGroup()
        self.question_manager_widget = QuestionManagerWidget()  #start instance

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setStyleSheet(open('style.css').read())
        self.ui.stackedWidget.setCurrentIndex(0)
        self.showMaximized()

        # Load Logo
        logo_pixmap = QtGui.QPixmap('logo.png')
        self.ui.label_logo.setPixmap(
            logo_pixmap.scaled(1000, 900, QtCore.Qt.KeepAspectRatio))
        self.ui.label_19.setPixmap(
            logo_pixmap.scaled(700, 500, QtCore.Qt.KeepAspectRatio))
        self.ui.label.setPixmap(
            logo_pixmap.scaled(700, 500, QtCore.Qt.KeepAspectRatio))

        # ======================================================================= #
        #                                  Buttons                                #
        # ======================================================================= #

        # Start Page Elements
        self.ui.pushButton.clicked.connect(self.LoginPage)
        self.ui.pushButton_2.clicked.connect(self.RegisterPage)
        self.ui.pushButton_28.clicked.connect(self.quitBtn)

        # Login Page Elements
        self.ui.pushButton_3.clicked.connect(self.passoff_login)
        self.ui.lineEdit_2.returnPressed.connect(self.ui.pushButton_3.click)
        self.ui.pushButton_4.clicked.connect(self.StartPage)
        self.ui.lineEdit_2.setEchoMode(QtWidgets.QLineEdit.Password)

        # Register Page Elements
        self.ui.pushButton_8.clicked.connect(self.passoff_register)
        self.ui.pushButton_7.clicked.connect(self.StartPage)
        self.ui.lineEdit_5.returnPressed.connect(self.ui.pushButton_8.click)
        self.ui.lineEdit_4.setEchoMode(QtWidgets.QLineEdit.Password)
        self.ui.lineEdit_5.setEchoMode(QtWidgets.QLineEdit.Password)

        # Admin Main Memnu elements
        self.ui.pushButton_5.clicked.connect(self.QuestionManagerPage)
        self.ui.pushButton_6.clicked.connect(self.passoff_stats)
        self.ui.pushButton_11.clicked.connect(self.quitBtn)

        # Player Main Menu Elements
        self.ui.pushButton_12.clicked.connect(self.GamePage)
        self.ui.pushButton_13.clicked.connect(self.passoff_records)
        self.ui.pushButton_14.clicked.connect(self.passoff_leaderboards)
        self.ui.pushButton_15.clicked.connect(self.QuestionManagerPage)
        self.ui.pushButton_16.clicked.connect(self.quitBtn)

        # Game Interface Elements
        self.ui.pushButton_10.clicked.connect(self.quitGame)
        self.ui.pushButton_9.clicked.connect(self.next_question_button)
        self.ui.lineEdit_6.returnPressed.connect(self.ui.pushButton_9.click)
        self.ui.lcdNumber.display(30)

        # Score Page Elements
        self.ui.pushButton_17.clicked.connect(self.PlayerMainMenu)

        # Records Buttons
        self.ui.pushButton_18.clicked.connect(self.return_menu_records)

        # Leaderboard Elements
        self.ui.pushButton_19.clicked.connect(self.PlayerMainMenu)

        # Question Manager Buttons
        self.ui.pushButton_20.clicked.connect(self.return_menu_question)
        self.ui.pushButton_21.clicked.connect(self.AddQuestionPage)

        # Add a Question Menu Elements
        self.ui.pushButton_22.clicked.connect(self.cancelQuestion)
        self.ui.lineEdit_8.setMaxLength(80)
        self.grid_radio_buttons = QtWidgets.QButtonGroup()
        self.ui.pushButton_23.clicked.connect(self.scrape_from_url)
        self.ui.pushButton_25.clicked.connect(
            lambda: self.add_question_from_manager())
        self.ui.open_image_button.clicked.connect(self.add_image)
        self.ui.lcdNumber.display(30)

        # User Statistics Elements
        self.ui.pushButton_27.clicked.connect(self.AdminMainMenu)

    def return_menu_records(self):
        if self.user_obj.user_type == 1:  # If admin
            self.passoff_stats()
        else:
            self.PlayerMainMenu()

    def return_menu_question(self):
        if self.user_obj.user_type == 1:
            self.AdminMainMenu()
        else:
            self.PlayerMainMenu()

    # Passover control flow login to main menu
    def passoff_login(page):
        error = login_page.handle_login(page)
        if error != None: show_error(page, error)

    # Passover control flow from register to login
    def passoff_register(page):
        error = register_page.handle_register(page)
        if error != None: show_error(page, error)

    # Passover control from player menu to records
    def passoff_records(page):
        player_records.goto_records(page)

    # Passover control from player menu to records
    def passoff_leaderboards(page):
        player_lead.goto_leaderboards(page)

    # Passover control from admin menu to statistics
    def passoff_stats(page):
        admin_stats.goto_stats(page)

    # Passover control from admin statistics to players individual statistics
    def passoff_see_more(page, records):
        admin_stats.goto_see_more(page, records)

    def start_timer(self):
        self.timer_thread = Thread(target=self._countdown)
        self.timer_thread.daemon = True
        self.timer_thread.running = True
        self.timer_thread.start()

    def _countdown(self):
        TIME = 30  #seconds
        count = TIME
        running_thread = currentThread()
        while getattr(running_thread, "running", True) and count >= 0:
            self.ui.lcdNumber.display(count)
            self.time_left = count
            time.sleep(1)
            count = count - 1
            if count == 0:
                self.ui.lineEdit_6.setText('0')
                self.ui.lineEdit_6.setReadOnly(True)

    def stop_timer(self):
        self.timer_thread.running = False
        self.timer_thread.join()

    def next_question_button(self):
        if self.next_question_pushed == False:  #if pushing submit button for first time
            if self.display_score():  #if price is correctly formatted
                self.next_question_pushed = True
                self.ui.lineEdit_6.setReadOnly(True)
                self.ui.pushButton_9.setText('NEXT')
            else:
                #QtWidgets.QMessageBox.about(self, 'Error','Invalid price formatting.')
                show_error(self, 'Invalid price formatting.')
        else:
            self.ui.lineEdit_6.setReadOnly(False)
            self.ui.lineEdit_6.setText('')
            self.ui.pushButton_9.setText('SUBMIT')
            if self.game_instance.next_question(
            ) is False:  #if the last question has been reached, show score page
                self.next_question_pushed = False
                self.ScorePage()
            else:
                self.load_current_question()
                self.next_question_pushed = False

    def display_score(self):
        user_price = str(self.ui.lineEdit_6.text())
        price_int = 0
        if re.match(
                '^[+-]?[0-9]{1,3}(?:(,[0-9]{3})*|([0-9]{3})*)(?:\.[0-9]{2})?$',
                user_price):  #regex for price formatting
            if not '.' in user_price:
                price_int = int(
                    re.sub('[^0-9]', '', user_price)
                ) * 100  #if no cents indicated, make sure correct int format
            else:
                price_int = int(re.sub('[^0-9]', '',
                                       user_price))  #if cents used
        else:
            return False
        current_score = self.game_instance.calculate_score(
            price_int, 30 - self.time_left)
        self.stop_timer()
        msg = 'Your guess is ' + current_score.get_label(
        ) + '!\n\n Your score is ' + str(
            current_score.get_score()) + ' points!'
        score_prompt = QtWidgets.QMessageBox.information(
            self, 'Score', msg, QtWidgets.QMessageBox.Ok)
        if score_prompt == QtWidgets.QMessageBox.Ok:
            pass

        # score_window = Score_Window(current_score.get_score(), current_score.get_label(), self)
        # score_window.setStyleSheet("background-color: #212121")
        # score_window.show()
        return True

    def loginBtn(self):
        self.ui.lineEdit.text()
        self.ui.lineEdit_2.text()

    def quitBtn(self):
        self.close()

    # ========================================================================= #
    #                         Page Navigation Functions                         #
    # ========================================================================= #

    # Moves to start page
    def StartPage(self):
        self.ui.stackedWidget.setCurrentIndex(0)

    # Moves to login page
    def LoginPage(self):
        self.ui.stackedWidget.setCurrentIndex(1)

    # Moves to registration page
    def RegisterPage(self):
        self.ui.stackedWidget.setCurrentIndex(2)

    # Moves to a player's main menu
    def PlayerMainMenu(self):
        self.stop_timer()
        self.ui.stackedWidget.setCurrentIndex(3)

    # Moves to an admin's main menu
    def AdminMainMenu(self):
        self.ui.stackedWidget.setCurrentIndex(4)

    # Moves to game page
    def GamePage(self):
        self.ui.lineEdit_6.setReadOnly(False)
        self.ui.lineEdit_6.setText('')
        self.ui.stackedWidget.setCurrentIndex(5)
        self.ui.pushButton_9.setText('SUBMIT')
        if not self.game_instance.next_question(
        ):  #loads new questions if no new questions found
            self.game_instance.load_questions()
        self.ui.label_2.setFont(QtGui.QFont('SansSerif', 25))  #product title
        self.ui.label_3.setFont(QtGui.QFont('SansSerif', 10))  #question number
        self.load_current_question()
        self.start_time = time.time()

    def LeaderboardPage(self):
        self.ui.stackedWidget.setCurrentIndex(9)

    # Moves to question manager
    def QuestionManagerPage(self):
        self.current_image_selection = Path('img\default.jpeg')
        self.ui.stackedWidget.setCurrentIndex(9)
        self._reset_question_manager()

    # Moves to add question menu
    def AddQuestionPage(self):
        self.ui.stackedWidget.setCurrentIndex(10)

    # Exits current game and moves to Player Menu from Game interface
    def quitGame(self):
        quit_prompt = QtWidgets.QMessageBox.question(
            self, 'Quit Game', 'Current score will be discarded',
            QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
        if quit_prompt == QtWidgets.QMessageBox.Ok:
            self.PlayerMainMenu()
            self.stop_timer()
            self.game_instance.calculate_score(0, 0)
            self.next_question_pushed = False

        if quit_prompt == QtWidgets.QMessageBox.Cancel:
            pass

    def load_current_question(self):
        self.ui.label_3.setText(f'Q#: {self.game_instance.current_question}')
        self.ui.label_2.setText(self.game_instance.get_question().getName())
        self.ui.textBrowser.setText(
            self.game_instance.get_question().getDescription())
        product_pixmap = QtGui.QPixmap(
            self.game_instance.get_question().getImagePath())
        self.ui.label_product_image.setPixmap(
            product_pixmap.scaled(self.ui.label_product_image.size(),
                                  QtCore.Qt.KeepAspectRatio))
        self.ui.textBrowser.setMinimumWidth(400)
        self.start_timer()

    # Moves to score page
    # After game is over, moves to final score page.
    def ScorePage(self):
        self.ui.stackedWidget.setCurrentIndex(6)
        self.game_instance.write_game(self.user_obj.username,
                                      self.start_time)  #writes game log to DB
        self.ui.label_11.setText(str(self.game_instance.get_final_score()))

    def scrape_from_url(self):
        # print ('Attempting scrape')
        url = self.ui.lineEdit_7.text()
        if is_Amazon_URL(url) == False:
            show_error(self, 'Invalid URL')
            return
        soup = open_url(url)
        title = scrape_title(soup)
        self.grid_column = 0
        self.grid_row = 0
        self.ui.lineEdit_8.setText(title)
        self.ui.lineEdit_9.setText(str(scrape_price(soup)))
        self.ui.plainTextEdit.setPlainText(str(scrape_desc(soup)))
        scraped_images = scrape_Image_URLs(soup)
        # print(scraped_images)
        imagepaths = download_images(title[:8], scraped_images)

        for path in imagepaths:
            self.add_image_to_grid(path)

    #adds an image to currently free grid space, using a Path to the image
    def add_image_to_grid(self, path, checked=False):
        image = QtGui.QPixmap(os.fspath(path))
        image_box = QtWidgets.QVBoxLayout()
        image_label = QtWidgets.QLabel()
        image_label.setPixmap(
            image.scaled(image_label.size() / 2, QtCore.Qt.KeepAspectRatio))
        # image_label.setScaledContents(True)
        image_box.addWidget(image_label)
        radio_button = QtWidgets.QRadioButton()
        radio_button.toggled.connect(lambda: self.set_current_img(path))
        self.grid_radio_buttons.addButton(radio_button)
        image_box.addWidget(radio_button, 0, QtCore.Qt.AlignCenter)
        self.ui.gridLayout_3.addLayout(image_box, self.grid_row,
                                       self.grid_column)

        if checked:
            radio_button.setChecked(True)

        if self.grid_column is 0:
            if self.grid_row == 0:
                radio_button.setChecked(True)
            self.grid_column = 1
        else:
            self.grid_column = 0
            self.grid_row += 1

    # Opens image from file dialog
    def add_question_from_manager(self):
        name = str(self.ui.lineEdit_8.text())
        user_price = str(self.ui.lineEdit_9.text())
        description = str(self.ui.plainTextEdit.toPlainText())
        price = 0
        if re.match(
                '^[+-]?[0-9]{1,3}(?:(,[0-9]{3})*|([0-9]{3})*)(?:\.[0-9]{2})?$',
                user_price):  #regex for price formatting
            if not '.' in user_price:
                price = int(
                    re.sub('[^0-9]', '', user_price)
                ) * 100  #if no cents indicated, make sure correct int format
            else:
                price = int(re.sub('[^0-9]', '', user_price))  #if cents used
        else:
            return False

        path = self.current_image_selection
        question = Question(name, price, description)
        if question:
            new_path = question.img_path  #not using getter because it returns default if the file is not currently there
            im = Image.open(path)
            im = im.convert('RGB')
            im.save(new_path, 'JPEG')  #converts to jpeg for compression
            if os.path.isdir("./temp"):
                for file in Path('temp').iterdir():
                    os.remove(file)
        if self.edit_question:
            self.edit_question.setName(name)
            self.edit_question.setPrice(user_price)
            self.edit_question.setDescription(user_price)
            new_path = self.edit_question.generateImagePath()
            self.edit_question.updateQuestion()
            self.edit_question.removeQuestion(self.edit_question.getID())
        else:
            question = Question(name, price, description)
            new_path = question.img_path
            question.removeQuestion(question.getID())

        im = Image.open(path)
        im = im.convert('RGB')
        im.save(new_path, 'JPEG')  #converts to jpeg for compression
        # shutil.copy(str(path), new_path)
        for file in Path('temp').iterdir():
            os.remove(file)

        self.ui.lineEdit_8.setText('')
        self.ui.lineEdit_9.setText('')
        self.ui.plainTextEdit.setPlainText('')
        self.ui.lineEdit_7.setText('')
        self.grid_column = 0
        self.grid_row = 0
        self.clear_grid()
        self.current_image_selection = Path('img\default.jpeg')
        self.edit_question = None
        self.QuestionManagerPage()

    def clear_grid(self):
        while self.ui.gridLayout_3.count():
            parent = self.ui.gridLayout_3.takeAt(0)
            while parent.count():
                child = parent.takeAt(0)
                if child.widget():
                    child.widget().deleteLater()

    def populate_question_manager(self):
        self.ui.scrollArea_3.setAutoFillBackground(False)
        self.question_manager_widget = QuestionManagerWidget()
        for qid in Question.get_question_ids():
            self._add_question_to_manager(Question.createQuestion(qid))

        # self.ui.scrollArea_3.setFixedHeight(self.question_manager_widget.height())
        self.ui.scrollArea_3.setWidget(self.question_manager_widget)
        self.ui.scrollArea_3.setAutoFillBackground(False)
        pal = QPalette()
        pal.setColor(QtGui.QPalette.Background, QtCore.Qt.darkGray)
        self.ui.scrollArea_3.setPalette(pal)  #TODO this isnt working

    def _add_question_to_manager(self, question):
        buttons = self.question_manager_widget.add_question_widget(question)
        buttons[0].clicked.connect(lambda: self._open_question_edit(question))
        buttons[1].clicked.connect(lambda: self.deleteQuestion(question))

    def _delete_question_from_manager(self, question):
        Question.removeQuestion(question.getID())
        self._reset_question_manager()
        return

    def _open_question_edit(self, question):
        self.ui.lineEdit_7.setText('')
        self.ui.lineEdit_8.setText(question.getName())
        self.ui.lineEdit_9.setText(f'{(question.getPrice()/100):.2f}')
        self.ui.plainTextEdit.setPlainText(question.getDescription())
        self.add_image_to_grid(question.getImagePath(), True)
        self.edit_question = question
        self.AddQuestionPage()
        return

    def _reset_question_manager(self):
        self.question_manager_widget.deleteLater()
        self.populate_question_manager()

    # Empties Add Question menu fields and moves to Question Manager page
    def cancelQuestion(self):
        back_prompt = QtWidgets.QMessageBox.question(
            self, 'Go Back', 'Current data will be discarded',
            QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
        if back_prompt == QtWidgets.QMessageBox.Ok:
            self.QuestionManagerPage()
            self.ui.lineEdit_7.setText('')
            self.ui.lineEdit_8.setText('')
            self.ui.lineEdit_9.setText('')
            self.ui.plainTextEdit.setPlainText('')
            self.clear_grid()
            self.edit_question = None
        if back_prompt == QtWidgets.QMessageBox.Cancel:
            pass

    def deleteQuestion(self, question):
        back_prompt = QtWidgets.QMessageBox.question(
            self, 'Delete', 'Question will be permanently erased',
            QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
        if back_prompt == QtWidgets.QMessageBox.Ok:
            self._delete_question_from_manager(question)
        if back_prompt == QtWidgets.QMessageBox.Cancel:
            pass

    def set_current_img(self, path):
        self.current_image_selection = path

    def add_image(self):
        file_dialog = QtWidgets.QFileDialog(self)
        file_dialog.setFileMode(QtWidgets.QFileDialog.ExistingFiles)
        path = file_dialog.getOpenFileName(self, 'Add Image', '',
                                           "Images (*.jpg, *.png)")[0]
        self.add_image_to_grid(path, True)
Ejemplo n.º 19
0
class UIController(QtGui.QMainWindow):
    def __init__(self, parent=None):
        #Loads of BORING UI setup code!!
        QtGui.QMainWindow.__init__(self, parent)
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.loadSettings()
        self.initPD()
        self.initFTD()
        self.ui.listView.setModel(self.peer_container)
        self.peerSelection=self.ui.listView.selectionModel()
        self.ui.tableView.setModel(self.proxy)
        self.fileSelection=self.ui.tableView.selectionModel()
        self.dloadMgr=model.DownloadWidgetManager(self.ui.tableWidget)
        self.tableHeaderResize()
        self.initConnection()    

    def listCtxtMenu(self, point):
        if not self.peerSelection.hasSelection():
            return
        menu=QtGui.QMenu(parent=self.ui.listView)
        menu.addAction(self.ui.actionExplore)
        menu.addAction(self.ui.actionBlacklistPeer)
        menu.addAction(self.ui.actionDeleteIP)
        menu.exec_(self.ui.listView.mapToGlobal(point))

    def fileCtxtMenu(self, point):
        if not self.fileSelection.hasSelection():
            return
        menu=QtGui.QMenu(parent=self.ui.tableView)
        menu.addAction(self.ui.actionDownload)
        menu.addAction(self.ui.actionDownloadAs)
        menu.exec_(self.ui.tableView.mapToGlobal(point))
    
    def initConnection(self):
        self.ui.actionDiscover.triggered.connect(self.setDiscover)
        self.ui.actionAddIP.triggered.connect(self.manAddIP)
        self.ui.actionClearBlacklist.triggered.connect(self.resetBan)
        self.ui.actionBlacklistPeer.triggered.connect(self.blacklistPeer)
        self.ui.actionExplore.triggered.connect(self.explorePeer)
        self.peer_container.updated.connect(self.updateHT)
        self.ui.listView.customContextMenuRequested.connect(self.listCtxtMenu)
        self.ui.tableView.customContextMenuRequested.connect(self.fileCtxtMenu)
        self.ui.radioButton.toggled.connect(self.filterIP)
        self.ui.radioButton_2.toggled.connect(self.filterIP)
        self.ui.lineEdit.textChanged.connect(self.proxy.setFilterFixedString)
        self.peerSelection.selectionChanged.connect(self.filterIP)
        self.ui.tableView.doubleClicked.connect(self.downloadAction)
        self.ui.actionDownload.triggered.connect(self.downloadAction)
        self.ui.actionDownloadAs.triggered.connect(self.downloadAsAction)
        self.ui.actionDeleteIP.triggered.connect(self.deletePeer)

    def resetBan(self):
        QtGui.QMessageBox.information(self, 'Blacklist Cleared', 'List of blacklisted peers has been reset')
        self.peer_container.clearBlacklist()

    def filterIP(self):
        if not self.ui.radioButton.isChecked():
            addr=self.getSelectedPeer()
            self.file_model.selectIP(addr)
        else:
            self.file_model.selectIP(None)

    def initPD(self):
        self.busy_peers=[]
        self.peer_container=model.PeerContainer()
        mcast_addr=(self.settings['MULTICAST_IP'], int(self.settings['MULTICAST_PORT']))
        self.pd=PDModule(mcast_addr, self.settings['NAME'], self.peer_container)

    def initFTD(self):
        self.finxr=indexer.FileIndexer(self.settings['INDEXER_PATH'])
        self.dfct=daemon.IFFactory(self.finxr)
        reactor.listenTCP(int(self.settings['DAEMON_PORT']),self.dfct)
        self.file_model=model.FileIndexModel()
        self.proxy = model.TxtMapSortProxyModel(self, model.FILE_LIST_MAP)
        self.proxy.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.proxy.setSourceModel(self.file_model)


    def manAddIP(self):
        ipaddr, ok = QtGui.QInputDialog.getText(self, 'Manual IP Entry', 'IP address')
        if ok:
            ipaddr=str(ipaddr)
            if not is_valid_ip(ipaddr):
                QtGui.QMessageBox.warning(self, 'Input Error', 'Invalid IP address')
                return
            rc=self.peer_container.addAddr(ipaddr)
            if rc == 1:
                QtGui.QMessageBox.information(self, 'Address Exception', 'IP is already present')
            elif rc == 2:
                QtGui.QMessageBox.warning(self, 'Address Exception', 'IP is blacklisted')

    def loadSettings(self):
        re_cd, self.settings=load_settings_from_file(SETTINGS_FILE)
        if re_cd:
            self.firstRun()
        save_settings_to_file(self.settings, SETTINGS_FILE)

    def deletePeer(self):
        addr=self.getSelectedPeer()
        self.peer_container.removeAddr(addr)

    def isValidConfig(self):
        return is_name(self.settings['NAME']) and is_dir_path(self.settings['INDEXER_PATH'])

    def downloadAction(self):
        name, addr, fHash=self.getSelectedFile()
        option=QtGui.QMessageBox.question(self, 'Download file', 'Confirm download {0}'\
            .format(name), QtGui.QMessageBox.No | QtGui.QMessageBox.Yes)
        if option == QtGui.QMessageBox.Yes:
            sv_fObj=self.quickSaveFile(name)
            if sv_fObj:
                self.downloadFile(name, addr, fHash, sv_fObj)

    def downloadFile(self, name, addr, fHash, fObj):
        d=Deferred()
        fFact=probe.FTFactory(fHash, fObj, d)
        d.addCallback(self.makeDL, name)
        d.addErrback(self.logError, addr)
        reactor.connectTCP(addr, 17395, probe.FTFactory(fHash, fObj, d))

    def makeDL(self, FTProt, name):
        idx=self.dloadMgr.addFTProtocol(name, FTProt)
        FTProt.def_obj.addCallback(self.removeDL, idx)
        FTProt.def_obj.addErrback(self.removeDL, idx)

    def removeDL(self, arg, idFT):
        logging.info(arg)
        self.dloadMgr.doneFT(idFT)

    def downloadAsAction(self):
        name, addr, fHash=self.getSelectedFile()
        sv_fObj=self.saveFilePrompt(name)
        if sv_fObj:
            self.downloadFile(name, addr, fHash, sv_fObj)

    def saveFilePrompt(self, name):
        savePath=str(QtGui.QFileDialog.getSaveFileName(self, 'Choose a destination file', \
            os.path.join(self.finxr.path, 'tmp.'+name.split('.')[-1])))
        if savePath:
            return open(savePath, 'wb')
        return None

    def quickSaveFile(self, saveName):
        try:
            sv_fObj=None
            sv_fObj=self.finxr.saveFile(saveName)
        except:
            option=QtGui.QMessageBox.warning(self, 'File overwrite', 'File exits. Overwrite?', \
                QtGui.QMessageBox.Yes | QtGui.QMessageBox.Abort | QtGui.QMessageBox.Save)
            if option == QtGui.QMessageBox.Yes:
                return self.finxr.saveFile(saveName, True)
            elif option == QtGui.QMessageBox.Save:
                return self.saveFilePrompt(saveName)
        return sv_fObj

    def firstRun(self):
        self.settings=DEFAULT_SETTINGS
        frDialog=QtGui.QDialog(parent=self)
        frDialog.ui=first_run.Ui_Dialog()
        frDialog.ui.setupUi(frDialog)
        frDialog.ui.lineEdit.setText(self.settings['NAME'])
        def folderHandler():
            shareFolder=str(QtGui.QFileDialog.getExistingDirectory(frDialog, \
                'Choose a directory to share'))
            frDialog.ui.lineEdit_2.setText(shareFolder)
            self.settings['INDEXER_PATH']=shareFolder
        frDialog.ui.pushButton.clicked.connect(folderHandler)
        frDialog.exec_()
        self.settings['NAME']=str(frDialog.ui.lineEdit.text())
        if not self.isValidConfig():
            QtGui.QMessageBox.critical(self,'Settings Error','Invalid Configuration')
            logging.critical('Invalid Config')
            exit_reactor(1)

    def updateHT(self):
        active_peers=self.peer_container.getAddrList()
        explored_peers=self.file_model.getAddrList()
        for item in explored_peers:
            if not item in active_peers:
                self.file_model.delIndex(item)
        for item in active_peers:
            if not item in explored_peers:
                self.discoverPeer(item)

    def gotHT(self, fileHT, addr):
        self.busy_peers.remove(addr)
        self.file_model.updateIndex(addr, fileHT)

    def discoverPeer(self, addr):
        if addr in self.busy_peers:
            return
        d=Deferred()
        d.addCallback(self.gotHT, addr)
        d.addErrback(self.logError, addr)
        self.busy_peers.append(addr)
        reactor.connectTCP(addr, 17395, probe.FHFactory(d))
    
    def logError(self, reason, addr, role):
        if addr in self.busy_peers:
            self.busy_peers.remove(addr)
        logging.error('Error in role {2} connecting to {0} : {1}'\
            .format(addr, str(reason), str(role)))

    def setDiscover(self):
        self.pd.setEnable(self.ui.actionDiscover.isChecked())

    def getSelectedPeer(self):
        if not self.peerSelection.hasSelection():
            return ''
        sIdx=self.peerSelection.selectedRows()[0]
        return str(self.peer_container.itemFromIndex(sIdx).text())

    def getSelectedFile(self):
        if not self.fileSelection.hasSelection():
            return None
        return [str(self.file_model.itemFromIndex(self.proxy.mapToSource(\
                self.fileSelection.selectedRows(column=idx)[0])).text()) for idx in [0,2,3]]

    def explorePeer(self):
        addr=self.getSelectedPeer()
        self.discoverPeer(addr)

    def blacklistPeer(self):
        addr=self.getSelectedPeer()
        self.peer_container.blacklistAddr(addr)

    def tableHeaderResize(self):
        header_crtl=self.ui.tableView.horizontalHeader()
        header_crtl.setResizeMode(0, QtGui.QHeaderView.Stretch)
        header_crtl.setResizeMode(1, QtGui.QHeaderView.ResizeToContents)
        header_crtl.setResizeMode(2, QtGui.QHeaderView.ResizeToContents)
        header_crtl=self.ui.tableWidget.horizontalHeader()
        header_crtl.setResizeMode(0, QtGui.QHeaderView.Stretch)
        header_crtl.setResizeMode(1, QtGui.QHeaderView.ResizeToContents)
        header_crtl.setResizeMode(2, QtGui.QHeaderView.ResizeToContents)
Ejemplo n.º 20
0
class AppWindow(QMainWindow):
    # member variables
    data = []
    paddingIndex = 0
    vector = [int, int] * 1000
    isTrackEnabled = False
    paddingDict = {}
    # load hash meta file
    metadata = mpu.io.read("hash_meta.json")

    def __init__(self):
        # python version calls
        if (sys.version_info > (3, 0)):
            super().__init__()
        else:
            super(AppWindow, self).__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setFixedSize(910, 720)
        self.setMouseTracking(False)
        self.setWindowIcon(QtGui.QIcon("res/icon.png"))
        self.init_Connections()
        self.init_Interface()

        self.hashSelectionChanged()

        self.show()

    def init_Connections(self):
        self.ui.hashButton.clicked.connect(self.hashButton_Clicked)
        self.ui.loadFileButton.clicked.connect(self.loadFileButton_Clicked)
        self.ui.randomKeyButton.clicked.connect(self.randomKeyButton_Clicked)
        self.ui.progressSlider.valueChanged.connect(
            self.progressSlider_Changed)
        self.ui.exportButton.clicked.connect(self.exportButton_Clicked)
        self.ui.launchVisualiserButton.clicked.connect(self.launchVisualTab)
        self.ui.hashCombo.currentIndexChanged.connect(
            self.hashSelectionChanged)
        self.ui.actionConverter_Tool.triggered.connect(
            self.launchConversionTool)
        self.ui.actionKill_Children.triggered.connect(self.killChildPs)

    def init_Interface(self):
        # css
        with open("res/darkorange.stylesheet.css", "r") as f:
            qstr = f.read()
            self.setStyleSheet(qstr)

        self.ui.launchVisualiserError.hide()
        self.ui.padding_LeftArrow.setEnabled(False)
        self.ui.tabWidget.setCurrentIndex(1)

        # disable all the tab control
        self.ui.sineTable.setTabKeyNavigation(False)
        self.ui.exportButton.setEnabled(False)

    def eventFilter(self, source, event):
        # event filter for a mouse movement over the mouse capture region
        # for random key gen
        if event.type() == QtCore.QEvent.MouseMove:
            if (event.buttons() == QtCore.Qt.NoButton and self.isTrackEnabled
                    and source == self.ui.mouseCaptureRegion):
                pos = event.pos()
                self.cursorMoved(pos.x(), pos.y())

        if event.type() == QtCore.QEvent.MouseButtonPress:
            if (event.buttons() == QtCore.Qt.LeftButton
                    and source == self.ui.padding_LeftArrow
                    and self.ui.padding_LeftArrow.isEnabled()):
                self.paddingArrow_Clicked(0)

        if event.type() == QtCore.QEvent.MouseButtonPress:
            if (event.buttons() == QtCore.Qt.LeftButton
                    and source == self.ui.padding_RightArrow
                    and self.ui.padding_RightArrow.isEnabled()):
                self.paddingArrow_Clicked(1)

        return QMainWindow.eventFilter(self, source, event)

    def keyPressEvent(self, qKeyEvent):
        if qKeyEvent.key() == QtCore.Qt.Key_Return:
            self.hashButton_Clicked()

    def getSelectedHash(self):
        if self.ui.hashCombo.currentIndex() == 0:
            return "md5"
        else:
            return "sha1"

    def hashButton_Clicked(self):
        #read in the text and send the ascii encoded byte array to the md5 function
        msg = str(self.ui.hashInput.text())
        # msg = bytes(msg, encoding="utf-8")

        if self.getSelectedHash() == "md5":
            # md5 selected
            m = MD5()
        elif self.getSelectedHash() == "sha1":
            # sha1 selected
            m = SHA1()

        self.runHash(msg, m)

    def loadFileButton_Clicked(self):
        filen = QFileDialog.getOpenFileName(self, "Open File", "/home")

        if self.getSelectedHash() == "md5":
            h = MD5()
        else:
            h = SHA1()
        # check if a file was chosen and note qdialog exited
        if filen[1] != '':
            self.runHash(filen[0], h, load_file=True)

    def exportButton_Clicked(self):
        if not self.data:
            return
        # write json of current header
        now = datetime.datetime.now()
        val = "%s_%s_%s_%s_%s.json" % (now.year, now.day, now.hour, now.minute,
                                       now.second)

        newData = {}
        newData["Hash Function"] = self.getSelectedHash()
        newData["Message"] = self.data[0]["Message"]
        newData["Result"] = self.ui.outputText.text()
        mpu.io.write(val, newData)

    def launchVisualTab(self):
        # if the current system is not windows....
        if os.name != 'nt':
            self.ui.launchVisualiserError.show()
            return

        # empty data - hash has not been ran yet
        if not self.data:
            return

        # get the current index of the scrollbar
        # export the import data to curr_loop.json
        # while the process is running, "pause this program"
        filen = "curr_loop.json"

        # visualiser needs:
        # A B C D
        # M T S
        current = self.data[self.ui.progressSlider.value()]

        visualdata = current["VisualData"]

        if os.path.isfile(filen):
            os.remove(filen)
        mpu.io.write(filen, visualdata)

        openFile(
            "wpf_visual\Visualiser\Visualiser\\bin\Release\Visualiser.exe",
            self.getSelectedHash())

    def killChildPs(self):
        ps = psutil.Process()
        children = ps.children(recursive=True)

        for c in children:
            c.kill()

    def launchConversionTool(self):
        #os.system("python dialog.py")
        subprocess.Popen(r"python dialog.py")

    def runHash(self, input, hash, load_file=False):
        # re-enable button. prevents wrong data crash
        self.ui.launchVisualiserButton.setEnabled(True)
        self.ui.exportButton.setEnabled(True)
        QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)

        # first reset the ui
        # feed a string and run it through the hash and
        # update the user interface

        # clear the data struct
        self.data.clear()

        if load_file:
            _bytes = libs.HashLib.loadFromFile(input)
        else:
            _bytes = bytes(input, encoding="utf-8")

        h = hash.Hash(_bytes)

        self.ui.outputText.setText(h.upper())

        self.data = mpu.io.read("loop.json")

        self.paddingDict = self.data[0]

        # self.ui.blockText.clear()
        # self.ui.blockText.setText(self.data[0]["Block"])

        self.ui.progressSlider.setMaximum(len(self.data) - 1)
        self.ui.progressSlider.setEnabled(True)
        self.ui.progressSlider.setValue(1)
        self.progressSlider_Changed()
        self.updatePaddingRegion()
        QApplication.restoreOverrideCursor()

    def randomKeyButton_Clicked(self):
        self.isTrackEnabled = False
        self.vector.clear()
        self.isTrackEnabled = True
        self.ui.mouseCaptureRegion.setTitle(
            "Move your mouse in the region beleow to generate a random key")

    def progressSlider_Changed(self):
        current = self.data[self.ui.progressSlider.value()]

        buffers = current["Loop"]["Buffers"]
        word = current["Loop"]["Word"]
        f = current["Loop"]["f"]
        g = current["Loop"]["g"]
        id = current["Loop"]["Id"]

        # update the ui
        self.ui.aBufferVal.setText(str(hex(buffers[0])))
        self.ui.bBufferVal.setText(str(hex(buffers[1])))
        self.ui.cBufferVal.setText(str(hex(buffers[2])))
        self.ui.dBufferVal.setText(str(hex(buffers[3])))
        self.ui.fBufferVal.setText(str(f))
        self.ui.gBufferVal.setText(str(g))
        self.ui.workingWordText.setText(str(word).upper())
        self.ui.loopCountLabel.setText('Loop Count: ' + str(id))

        if len(buffers) == 5:
            self.ui.eBufferVal.setText(str(hex(buffers[4])))

    def hashSelectionChanged(self):
        if self.getSelectedHash() == "md5":
            # md5 chosen
            # update constants area
            self.updateConstantRegion(self.metadata["MD5"])

        elif self.getSelectedHash() == "sha1":
            # sha1 chosen
            self.updateConstantRegion(self.metadata["SHA1"])

        self.ui.launchVisualiserButton.setEnabled(False)

    def updateConstantRegion(self, data):
        # load sine table from data if valid
        if "Sine Table" in data:
            self.ui.sineTable.setVisible(True)
            self.ui.sineTable.setRowCount(len(data["Sine Table"]))
            self.ui.sineTable.setColumnCount(2)

            header = self.ui.sineTable.horizontalHeader()
            header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
            header.setSectionResizeMode(1, QHeaderView.ResizeToContents)

            for i in range(16):
                # row from the json file
                row = data["Sine Table"][str(i)]
                split = row.split(',')
                self.ui.sineTable.setItem(i, 0,
                                          QTableWidgetItem(str(i).upper()))
                self.ui.sineTable.setItem(i, 1, QTableWidgetItem(split[0]))

                self.ui.sineTable.setItem(i + 1, 0,
                                          QTableWidgetItem(str(i + 1).upper()))
                self.ui.sineTable.setItem(i + 1, 1, QTableWidgetItem(split[1]))

                self.ui.sineTable.setItem(i + 2, 0,
                                          QTableWidgetItem(str(i + 2).upper()))
                self.ui.sineTable.setItem(i + 2, 1, QTableWidgetItem(split[2]))

                self.ui.sineTable.setItem(i + 3, 0,
                                          QTableWidgetItem(str(i + 3).upper()))
                self.ui.sineTable.setItem(i + 3, 1, QTableWidgetItem(split[3]))
        elif "Constants" in data:
            consts = data["Constants"]
            self.ui.sineTable.setVisible(True)
            self.ui.sineTable.setRowCount(len(consts))
            self.ui.sineTable.setColumnCount(2)

            header = self.ui.sineTable.horizontalHeader()
            header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
            header.setSectionResizeMode(1, QHeaderView.ResizeToContents)

            for i in range(len(consts)):
                self.ui.sineTable.setItem(i, 0, QTableWidgetItem(str(i + 1)))
                self.ui.sineTable.setItem(
                    i, 1, QTableWidgetItem(str(consts[str(i)])))
        else:
            self.ui.sineTable.setVisible(False)

        # populate register data
        registers = data["Registers"]
        self.ui.regAText.setText(registers["A"])
        self.ui.regBText.setText(registers["B"])
        self.ui.regCText.setText(registers["C"])
        self.ui.regDText.setText(registers["D"])

        # block size etc
        self.ui.digestSizeLabel_2.setText(data["Digest"])
        self.ui.digestSizeLabel_3.setText(data["Block"])
        self.ui.digestSizeLabel_4.setText(data["Rounds"])

        if "E" in registers:
            #self.ui.blockText.setGeometry(QtCore.QRect(10, 140, 211, 101))
            self.ui.label_21.setVisible(True)
            self.ui.regEText.setVisible(True)
            self.ui.regEText.setText(registers["E"])
            self.ui.label_15.setVisible(True)
            self.ui.eBufferVal.setVisible(True)
        else:
            #self.ui.blockText.setGeometry(QtCore.QRect(10, 120, 211, 121))
            self.ui.label_21.setVisible(False)
            self.ui.regEText.setVisible(False)
            self.ui.label_15.setVisible(False)
            self.ui.eBufferVal.setVisible(False)

    def updatePaddingRegion(self):
        # called upon hash and arrow click
        # depending on index, write the correct key-value to text box
        if self.paddingIndex == 0:
            self.ui.padding_BlockText.setText(self.paddingDict["RawBytes"])
        elif self.paddingIndex == 1:
            self.ui.padding_BlockText.setText(self.paddingDict["RawBytes1"])
        elif self.paddingIndex == 2:
            self.ui.padding_BlockText.setText(self.paddingDict["RawBytes0"])
        elif self.paddingIndex == 3:
            self.ui.padding_BlockText.setText(self.paddingDict["Block"])

    def paddingArrow_Clicked(self, source):
        if not self.data:
            return
        # delta the counter
        self.paddingIndex = self.paddingIndex + 1 if source == 1 else self.paddingIndex - 1
        # disable/enable buttons based on current index
        if self.paddingIndex == 0:
            self.ui.padding_LeftArrow.setEnabled(False)
        elif self.paddingIndex == 3:
            self.ui.padding_RightArrow.setEnabled(False)
        else:
            self.ui.padding_LeftArrow.setEnabled(True)
            self.ui.padding_RightArrow.setEnabled(True)

        # source is 0 or 1 dependingg on button clicked
        labelVals = [
            "Binary of Input", "Append a \"1\" byte",
            "Append \"0\" bytes so that length in bits is congruent to 448 modulo 512",
            "Append 64 bit representation of original message length"
        ]

        self.ui.paddingStatusLabel.setText(labelVals[self.paddingIndex])
        self.updatePaddingRegion()

    def cursorMoved(self, x, y):
        if len(self.vector) == 1000:
            self.isTrackEnabled = False
            self.mouse_vector_acquired()
            return

        self.vector.append([x, y])
        self.ui.progressBar.setValue(len(self.vector) / 10)

    def mouse_vector_acquired(self):
        # called when 1000 mouse points have been collected
        # will change the input hash to a string the sum of all points

        _sum = sum(self.vector)
        now = datetime.datetime.now()
        val = _sum * sin(now.day + now.hour + now.second)

        self.runHash(str(val), MD5())
        # reset the ui
        self.ui.mouseCaptureRegion.setTitle("")
        self.isTrackEnabled = False

    def __del__(self):
        ps = psutil.Process()
        children = ps.children(recursive=True)

        for c in children:
            c.kill()
Ejemplo n.º 21
0
class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        # Iniciar main window
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Temp's
        self.tempRuby = ""
        self.tempFR = ""

        # Undo
        self.undoRuby = [""]
        self.undoRubyIndex = 0
        self.undoFR = [""]
        self.undoFRIndex = 0

        # Velocitats
        self.velRuby = 0
        self.velFR = 0
        self.velEmerald = ""

        # Hide
        self.vHideRuby = "visible"
        self.vHideFR = "visible"
        self.vLastIsHideRuby = "0"
        self.vLastIsHideFR = "0"

        #conectem coses Ruby
        self.connect(self.ui.BotoUp, QtCore.SIGNAL('clicked()'), self.UpRuby)
        self.connect(self.ui.BotoDown, QtCore.SIGNAL('clicked()'),
                     self.DownRuby)
        self.connect(self.ui.BotoRight, QtCore.SIGNAL('clicked()'),
                     self.RightRuby)
        self.connect(self.ui.BotoLeft, QtCore.SIGNAL('clicked()'),
                     self.LeftRuby)
        self.connect(self.ui.Botomirar, QtCore.SIGNAL('clicked()'),
                     self.faceRuby)
        self.connect(self.ui.Botoslow, QtCore.SIGNAL('clicked()'),
                     self.slowRuby)
        self.connect(self.ui.Botowalk, QtCore.SIGNAL('clicked()'),
                     self.walkRuby)
        self.connect(self.ui.Botorun, QtCore.SIGNAL('clicked()'), self.runRuby)
        self.connect(self.ui.Botojump, QtCore.SIGNAL('clicked()'),
                     self.jumpRuby)

        self.connect(self.ui.bSt1Ruby, QtCore.SIGNAL('clicked()'),
                     self.st1Ruby)
        self.connect(self.ui.bSt2Ruby, QtCore.SIGNAL('clicked()'),
                     self.st2Ruby)
        self.connect(self.ui.bSt3Ruby, QtCore.SIGNAL('clicked()'),
                     self.st3Ruby)
        self.connect(self.ui.bSt4Ruby, QtCore.SIGNAL('clicked()'),
                     self.st4Ruby)
        self.connect(self.ui.bHideRuby, QtCore.SIGNAL('clicked()'),
                     self.hideRuby)

        self.connect(self.ui.ClearRuby, QtCore.SIGNAL('clicked()'), self.RubyC)
        self.connect(self.ui.backspaceRuby, QtCore.SIGNAL('clicked()'),
                     self.GomaRuby)
        self.connect(self.ui.bAlertRuby, QtCore.SIGNAL('clicked()'),
                     self.alertRuby)
        self.connect(self.ui.bQRuby, QtCore.SIGNAL('clicked()'), self.qRuby)
        self.connect(self.ui.bLoveRuby, QtCore.SIGNAL('clicked()'),
                     self.loveRuby)
        self.connect(self.ui.bEndRuby, QtCore.SIGNAL('clicked()'),
                     self.endRuby)

        #conectem coses FR
        self.connect(self.ui.BotoUpFR, QtCore.SIGNAL('clicked()'), self.UpFR)
        self.connect(self.ui.BotoDownFR, QtCore.SIGNAL('clicked()'),
                     self.DownFR)
        self.connect(self.ui.BotoRightFR, QtCore.SIGNAL('clicked()'),
                     self.RightFR)
        self.connect(self.ui.BotoLeftFR, QtCore.SIGNAL('clicked()'),
                     self.LeftFR)
        self.connect(self.ui.BotomirarFR, QtCore.SIGNAL('clicked()'),
                     self.faceFR)
        self.connect(self.ui.BotoxslowFR, QtCore.SIGNAL('clicked()'),
                     self.xslowFR)
        self.connect(self.ui.BotoslowFR, QtCore.SIGNAL('clicked()'),
                     self.slowFR)
        self.connect(self.ui.BotowalkFR, QtCore.SIGNAL('clicked()'),
                     self.walkFR)
        self.connect(self.ui.BotorunFR, QtCore.SIGNAL('clicked()'), self.runFR)
        self.connect(self.ui.BotojumpFR, QtCore.SIGNAL('clicked()'),
                     self.jumpFR)

        self.connect(self.ui.bSt1FR, QtCore.SIGNAL('clicked()'), self.st1FR)
        self.connect(self.ui.bSt2FR, QtCore.SIGNAL('clicked()'), self.st2FR)
        self.connect(self.ui.bSt3FR, QtCore.SIGNAL('clicked()'), self.st3FR)
        self.connect(self.ui.bHideFR, QtCore.SIGNAL('clicked()'), self.hideFR)

        self.connect(self.ui.ClearFR, QtCore.SIGNAL('clicked()'), self.FRC)
        self.connect(self.ui.backspaceFR, QtCore.SIGNAL('clicked()'),
                     self.GomaFR)
        self.connect(self.ui.bAlertFR, QtCore.SIGNAL('clicked()'),
                     self.alertFR)
        self.connect(self.ui.bAlert2FR, QtCore.SIGNAL('clicked()'),
                     self.alert2FR)
        self.connect(self.ui.bQFR, QtCore.SIGNAL('clicked()'), self.qFR)
        self.connect(self.ui.bXFR, QtCore.SIGNAL('clicked()'), self.xFR)
        self.connect(self.ui.bHappyFR, QtCore.SIGNAL('clicked()'),
                     self.happyFR)
        self.connect(self.ui.bEndFR, QtCore.SIGNAL('clicked()'), self.endFR)

        #menu
        self.connect(self.ui.actionAbout, QtCore.SIGNAL('triggered()'),
                     self.aboutmsg)
        self.connect(self.ui.actionRubyList, QtCore.SIGNAL('triggered()'),
                     self.RList)
        self.connect(self.ui.actionFRList, QtCore.SIGNAL('triggered()'),
                     self.FRList)
        self.windowlist123 = None
        self.connect(self.ui.actionUndo, QtCore.SIGNAL('triggered()'),
                     self.undo)
        self.connect(self.ui.actionRedo, QtCore.SIGNAL('triggered()'),
                     self.redo)

#-------------Up----------------
#-------------Ruby----------------

    def UpRuby(self):
        self.tempRuby += get_mov("Ruby", self.velRuby, 1)
        self.update()

#-------------Down----------------
#-------------Ruby----------------

    def DownRuby(self):
        self.tempRuby += get_mov("Ruby", self.velRuby, 0)
        self.update()

#-------------Right----------------
#-------------Ruby----------------

    def RightRuby(self):
        self.tempRuby += get_mov("Ruby", self.velRuby, 3)
        self.update()

#-------------Left----------------
#-------------Ruby----------------

    def LeftRuby(self):
        self.tempRuby += get_mov("Ruby", self.velRuby, 2)
        self.update()

#-------------Up----------------
#-------------FR----------------

    def UpFR(self):
        self.tempFR += get_mov("FR", self.velFR, 1)
        self.update()

#-------------Down----------------
#-------------FR----------------

    def DownFR(self):
        self.tempFR += get_mov("FR", self.velFR, 0)
        self.update()

#-------------Right----------------
#-------------FR----------------

    def RightFR(self):
        self.tempFR += get_mov("FR", self.velFR, 3)
        self.update()

#-------------Left----------------
#-------------FR----------------

    def LeftFR(self):
        self.tempFR += get_mov("FR", self.velFR, 2)
        self.update()

#-------------Update----------------
# Update gui and undo system

    def update(self):
        self.ui.textFR.setPlainText(self.tempFR)
        self.vLastIsHideFR = "0"
        self.redoFR1 = self.tempFR
        self.ui.textRuby.setPlainText(self.tempRuby)
        self.vLastIsHideRuby = "0"
        self.redoRuby1 = self.tempRuby

        if self.undoRuby[self.undoRubyIndex] != self.tempRuby:
            self.undoRubyIndex += 1
        if len(self.undoRuby) == self.undoRubyIndex:
            self.undoRuby.append(self.tempRuby)
        else:
            self.undoRuby[self.undoRubyIndex] = self.tempRuby
        if self.undoFR[self.undoFRIndex] != self.tempFR:
            self.undoFRIndex += 1
        if len(self.undoFR) == self.undoFRIndex:
            self.undoFR.append(self.tempFR)
        else:
            self.undoFR[self.undoFRIndex] = self.tempFR
        self.scroll_down()

    def scroll_down(self):
        bar = self.ui.textRuby.verticalScrollBar()
        bar.setValue(bar.maximum())

#-------------Velocities----------------
#-------------Ruby----------------

    def faceRuby(self):
        self.velRuby = 0  # "face"

    def slowRuby(self):
        self.velRuby = 1  # "slow"

    def walkRuby(self):
        self.velRuby = 2  # "walk"

    def runRuby(self):
        self.velRuby = 13  # "run"

    def jumpRuby(self):
        self.velRuby = 17  # "jump"

    def st1Ruby(self):
        self.velRuby = 6  # "st1"

    def st2Ruby(self):
        self.velRuby = 7  # "st2"

    def st3Ruby(self):
        self.velRuby = 8  # "st3"

    def st4Ruby(self):
        self.velRuby = 9  # "st4"

#-------------FR----------------

    def faceFR(self):
        self.velFR = 0  # "face"

    def xslowFR(self):
        self.velFR = 1  # "xslow"

    def slowFR(self):
        self.velFR = 2  # "slow"

    def walkFR(self):
        self.velFR = 3  # "walk"

    def runFR(self):
        self.velFR = 5  # "run"

    def jumpFR(self):
        self.velFR = 16  # "jump"

    def st1FR(self):
        self.velFR = 6  # "st1"

    def st2FR(self):
        self.velFR = 7  # "st2"

    def st3FR(self):
        self.velFR = 8  # "st3"

#-------------Hide----------------
#-------------Ruby----------------

    def hideRuby(self):
        if self.vHideRuby == "visible":
            self.vHideRuby = "invisible"
            self.tempRuby += "#raw 0x54 'hide\n"
            self.ui.textRuby.setPlainText(self.tempRuby)
        else:
            self.vHideRuby = "visible"
            self.tempRuby += "#raw 0x55 'show\n"
            self.ui.textRuby.setPlainText(self.tempRuby)
        self.vLastIsHideRuby = "1"
        self.scroll_down()

#-------------FR----------------

    def hideFR(self):
        if self.vHideFR == "visible":
            self.vHideFR = "invisible"
            self.tempFR += "#raw 0x60 'hide\n"
            self.ui.textFR.setPlainText(self.tempFR)
        else:
            self.vHideFR = "visible"
            self.tempFR += "#raw 0x61 'show\n"
            self.ui.textFR.setPlainText(self.tempFR)
        self.vLastIsHideFR = "1"
        self.scroll_down()

#-------------Clear----------------
#-------------Ruby----------------

    def RubyC(self):
        self.tempRuby = ""
        self.update()
        if self.vHideRuby == "visible":
            self.vHideRuby = "invisible"
            self.ui.bHideRuby.setChecked(1)
        if self.vHideRuby == "invisible":
            self.vHideRuby = "visible"
            self.ui.bHideRuby.setChecked(0)

#-------------FR----------------

    def FRC(self):
        self.tempFR = ""
        self.update()
        if self.vHideFR == "visible":
            self.vHideFR = "invisible"
            self.ui.bHideFR.setChecked(1)
        if self.vHideFR == "invisible":
            self.vHideFR = "visible"
            self.ui.bHideFR.setChecked(0)

#-------------Goma----------------
#-------------Ruby----------------

    def GomaRuby(self):
        self.passalinia = "\n"
        self.abc = \
        "qwertyuiopasdfghjklzxcvbnm, QWERTYUIOPASDFGHJKLZXCVBNM1234567890'#-"
        self.tempRuby = self.tempRuby.rstrip(self.passalinia)
        self.tempRuby = self.tempRuby.rstrip(self.abc)
        self.update()
        if self.vLastIsHideRuby == "1":
            if self.vHideRuby == "visible":
                self.vHideRuby = "invisible"
                self.ui.bHideRuby.setChecked(1)
            elif self.vHideRuby == "invisible":
                self.vHideRuby = "visible"
                self.ui.bHideRuby.setChecked(0)

#-------------FR----------------

    def GomaFR(self):
        self.passalinia = "\n"
        self.abc = \
        "qwertyuiopasdfghjklzxcvbnm, QWERTYUIOPASDFGHJKLZXCVBNM1234567890'#-"
        self.tempFR = self.tempFR.rstrip(self.passalinia)
        self.tempFR = self.tempFR.rstrip(self.abc)
        self.update()
        if self.vLastIsHideFR == "1":
            if self.vHideFR == "visible":
                self.vHideFR = "invisible"
                self.ui.bHideFR.setChecked(1)
            elif self.vHideFR == "invisible":
                self.vHideFR = "visible"
                self.ui.bHideFR.setChecked(0)

#-------------Icons----------------
#-------------alertRuby----------------

    def alertRuby(self):
        self.tempRuby += get_mov("Ruby", 23, 0)  # "#raw 0x56 '!\n"
        self.update()

#-------------?Ruby----------------

    def qRuby(self):
        self.tempRuby += get_mov("Ruby", 23, 1)  # "#raw 0x57 '?\n"
        self.update()

#-------------loveRuby----------------

    def loveRuby(self):
        self.tempRuby += get_mov("Ruby", 23, 2)  # "#raw 0x58 '<3\n"
        self.update()

#-------------alertFR----------------

    def alertFR(self):
        self.tempFR += get_mov("FR", 19, 0)  # "#raw 0x62 '!\n"
        self.update()

#-------------alert2FR----------------

    def alert2FR(self):
        self.tempFR += get_mov("FR", 19, 3)  # "#raw 0x65 '!!\n"
        self.update()

#-------------?FR----------------

    def qFR(self):
        self.tempFR += get_mov("FR", 19, 1)  # "#raw 0x63 '?\n"
        self.update()

#-------------xFR----------------

    def xFR(self):
        self.tempFR += get_mov("FR", 19, 2)  # "#raw 0x64 'X\n"
        self.update()

#-------------happyFR----------------

    def happyFR(self):
        self.tempFR += get_mov("FR", 19, 4)  # "#raw 0x66 '^^\n"
        self.update()

#-------------FE-FR----------------

    def endFR(self):
        self.tempFR += "#raw 0xFE 'End\n"
        self.update()

#-------------FE-Ruby----------------

    def endRuby(self):
        self.tempRuby += "#raw 0xFE 'End\n"
        self.update()

#-------------Menu----------------
#-------------Help----------------
#-------------About----------------

    def aboutmsg(self):
        QtGui.QMessageBox.about(
            self, "About applymovement-gen", u"Applymovement-gen v2.0.0 \
                                \nCopyright © Jaume Delclos (cosarara97)")

#-------------Tools----------------
#-------------Ruby List----------------

    def RList(self):
        self.ollist = llista()
        self.ollist.show()
        fileName = "./ruby.txt"
        filer = open(fileName).read()
        self.ollist.wlist.textBrowser.setPlainText(filer)

#-------------FR List----------------

    def FRList(self):
        self.ollist = llista()
        self.ollist.show()
        fileName = "./FR.txt"
        filer = open(fileName).read()
        self.ollist.wlist.textBrowser.setPlainText(filer)

#----------------Edit----------------

    def undo(self):
        if self.undoRubyIndex != 0:
            self.undoRubyIndex -= 1
            self.tempRuby = self.undoRuby[self.undoRubyIndex]
            self.ui.textRuby.setPlainText(self.tempRuby)
        if self.undoFRIndex != 0:
            self.undoFRIndex -= 1
            self.tempFR = self.undoFR[self.undoFRIndex]
            self.ui.textFR.setPlainText(self.tempFR)
        self.scroll_down()

    def redo(self):
        if self.undoRubyIndex != len(self.undoRuby) - 1:
            self.undoRubyIndex += 1
            self.tempRuby = self.undoRuby[self.undoRubyIndex]
            self.ui.textRuby.setPlainText(self.tempRuby)
        if self.undoFRIndex != len(self.undoFR) - 1:
            self.undoFRIndex += 1
            self.tempFR = self.undoFR[self.undoFRIndex]
            self.ui.textFR.setPlainText(self.tempFR)
        self.scroll_down()
Ejemplo n.º 22
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        # 初始化界面
        self.ui.setupUi(self)
        self.__actionBlinding__()
        self.__beBeautiful__()
        self.udpIp = '192.168.1.3'
        self.udpPort = '5000'
        self.udpInterface = UdpApplication()

    def __actionBlinding__(self):
        self.ui.openFile.clicked.connect(self.fileOpenAck)
        self.ui.pushButtonTest.clicked.connect(self.pushButtonTestAck)
        self.ui.actionUDP.triggered.connect(self.udpManuCreate)

    def __beBeautiful__(self):
        self.ui.openFile.setFont('楷体')
        self.ui.openFile.setIcon(QIcon('./ico/2.png'))
        self.ui.menubar.setFont('黑体')
        self.ui.actionUDP.setIcon(QIcon('./ico/1.png'))

    def fileOpenAck(self):
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setViewMode(QFileDialog.Detail)
        if dialog.exec_():  # 选择完毕
            fileNames = dialog.selectedFiles()
            self.ui.fileDir.setText(fileNames[0])
            try:
                filedHead = open(
                    fileNames[0],
                    'rb',
                )
            except:
                self.tipErrorFileOpen()
                return
            self.fileMesgSize = os.path.getsize(fileNames[0])
            self.fileMesg = filedHead.read()
            filedHead.close()
            self.udpSendFile()

    def pushButtonTestAck(self):
        self.thread2 = threading.Thread(target=self.test)
        self.thread2.start()

    def test(self):
        while True:
            self.udpSendFile()
            time.sleep(20)

    def OpenInitFile(self):
        fileName = 'config.txt'

    def udpManuCreate(self):
        dialog = QDialog()
        dialog.setWindowTitle('UDP CONFIG')
        dialog.setWindowModality(Qt.ApplicationModal)
        dialog.setWindowIcon(QIcon('./ico/1.png'))
        vtLayout = QVBoxLayout()
        layout1 = QGridLayout()
        groupBox1 = QGroupBox('目标主机')
        groupBox2 = QGroupBox('数据接收窗口(文本模式)')
        groupBox3 = QGroupBox('数据发送窗口(文本模式)')

        groupBox1.setFont('黑体')
        groupBox2.setFont('黑体')
        groupBox3.setFont('黑体')
        label1 = QLabel('UDP IP')
        label2 = QLabel('UDP 端口号')
        textEditIP = QLineEdit()
        textEditIP.setPlaceholderText('输入UDP IP')
        textEditIP.setText(self.udpIp)
        textEditPort = QLineEdit()
        textEditPort.setPlaceholderText('输入UDP 端口号')
        textEditPort.setText(self.udpPort)
        layout1.addWidget(label1, 0, 0, 1, 1)
        layout1.addWidget(textEditIP, 0, 1, 1, 2)
        layout1.addWidget(label2, 0, 4, 1, 1)
        layout1.addWidget(textEditPort, 0, 5, 1, 2)
        groupBox1.setLayout(layout1)

        self.ui.textEditRx = QTextEdit()
        self.ui.pushButtonSocketCrcRx = QPushButton('接收清空')
        self.ui.pushButtonSocketSaveRx = QPushButton('保存数据')
        self.ui.pushButtonSocketCrcRx.setFont('楷体')
        self.ui.pushButtonSocketSaveRx.setFont('楷体')
        self.ui.textEditRx.setTextColor('red')
        layout2 = QGridLayout()
        layout2.addWidget(self.ui.textEditRx, 0, 0, 5, 6)
        layout2.addWidget(self.ui.pushButtonSocketCrcRx, 0, 7, 1, 1)
        layout2.addWidget(self.ui.pushButtonSocketSaveRx, 4, 7, 1, 1)
        groupBox2.setLayout(layout2)

        self.ui.textEditTx = QTextEdit()
        self.ui.pushButtonSocketSend = QPushButton('发送数据')
        self.ui.pushButtonSocketCrcSend = QPushButton('发送清空')
        self.ui.pushButtonSocketSend.setFont('楷体')
        self.ui.pushButtonSocketCrcSend.setFont('楷体')
        layout3 = QGridLayout()
        layout3.addWidget(self.ui.textEditTx, 0, 0, 5, 6)
        layout3.addWidget(self.ui.pushButtonSocketSend, 0, 7, 1, 1)
        layout3.addWidget(self.ui.pushButtonSocketCrcSend, 4, 7, 1, 1)
        groupBox3.setLayout(layout3)

        vtLayout.addWidget(groupBox1)
        vtLayout.addWidget(groupBox2)
        vtLayout.addWidget(groupBox3)

        vtLayout.setStretch(0, 1)
        vtLayout.setStretch(1, 6)
        vtLayout.setStretch(2, 2)
        dialog.setLayout(vtLayout)
        dialog.resize(1024, 600)
        # 绑定信号槽
        self.ui.pushButtonSocketSend.clicked.connect(
            lambda: self.pushButtonSocketSendSlot(self.ui.textEditTx.
                                                  toPlainText()))
        self.ui.pushButtonSocketCrcSend.clicked.connect(
            lambda: self.ui.textEditTx.setPlainText(''))
        self.ui.pushButtonSocketCrcRx.clicked.connect(
            lambda: self.ui.textEditRx.setPlainText(''))
        self.ui.pushButtonSocketSaveRx.clicked.connect(self.saveUdpRxdata)
        textEditIP.editingFinished.connect(
            lambda: self.setUdpIp(textEditIP.text()))
        textEditPort.editingFinished.connect(
            lambda: self.setUdpPort(textEditPort.text()))

        # 创建了UDP就可以开启接收线程
        self.thread1 = threading.Thread(target=self.monitorUdpRx)
        self.thread1.start()

        if dialog.exec_():
            pass

    def monitorUdpRx(self):
        while True:
            timeNow = time.strftime('%H:%M:%S', time.localtime(time.time()))
            recvIpPort, recvMesg = self.udpInterface.socketGetRcvData(
                self.udpInterface.udpSocket)
            res = '(' + timeNow + ' IP:' + recvIpPort[0] + ' Port:' + str(
                recvIpPort[1]) + '):' + recvMesg
            self.ui.textEditRx.append(res)

    def saveUdpRxdata(self):
        # 先判断目录是否存在
        dir = os.path.exists('./user')
        if dir == False:
            b = os.getcwd()
            os.makedirs(b + '\\user')
        # 写入数据到文件 不存在会新建 存在会直接覆盖
        filePoint = open('./user/Rx.txt', 'w+')
        msg = self.ui.textEditRx.toPlainText()
        filePoint.write(msg)
        # 写入完毕后弹出提示窗口
        dialog = QDialog()
        dialog.setFixedSize(200, 40)
        dialog.setWindowTitle('Tips')
        dialog.setWindowIcon(QIcon('./ico/1.png'))
        tip = '文件已保存至./user/Rx.txt'
        text = QLabel(tip)
        text.setFont('黑体')
        layout = QVBoxLayout()
        layout.addWidget(text)
        dialog.setLayout(layout)
        if dialog.exec_():
            pass

    def pushButtonSocketSendSlot(self, string):
        send = bytes(string, encoding='utf-8')
        self.udpInterface.socketSendString(send, self.udpIp, self.udpPort)

    def setUdpIp(self, string):  #设置UDP 目标IP地址
        self.udpIp = string

    def setUdpPort(self, string):  #设置UDP 目标端口号
        self.udpPort = string

    def udpSendFile(self):  #UDP发送文件
        self.udpInterface.socketCreate()
        try:
            times = int(self.fileMesgSize / 1024)
            res = self.fileMesgSize % 1024
            head = b'B10000000001'
            levelUp = b'B1000011000100060004\x5a\xa5\x80\x00'
            reboot = b'B1000011000100040004\x55\xaa\x5a\xa5'
            if (times != 0):
                for i in range(0, times):
                    vp_addr = bytes(str(hex(int('8000', 16) + 512 * i)).rjust(
                        4, '0'),
                                    encoding='utf-8')
                    vp_len = b'0400'
                    sand = head + vp_addr[2:] + vp_len + \
                        self.fileMesg[i*1024:(i+1)*1024]
                    self.udpInterface.socketSendString(sand, self.udpIp,
                                                       self.udpPort)
            if (res != 0):
                vp_addr = bytes(str(hex(int('8000', 16) + 512 * times)).rjust(
                    4, '0'),
                                encoding='utf-8')
                vp_len = bytes((str(hex(res))[2:]).rjust(4, '0'),
                               encoding='utf-8')
                sand = head + vp_addr[2:] + vp_len + \
                    self.fileMesg[times * 1024: times * 1024 + res]
                self.udpInterface.socketSendString(sand, self.udpIp,
                                                   self.udpPort)
                self.udpInterface.socketSendString(levelUp, self.udpIp,
                                                   self.udpPort)
                self.udpInterface.socketSendString(reboot, self.udpIp,
                                                   self.udpPort)
        except:
            self.tipErrorSocketSend()

    def tipErrorFileOpen(self):
        dialog = QDialog()
        dialog.setFixedSize(120, 40)
        text = QLabel('文件打开失败')
        text.setFont('黑体')
        layout = QVBoxLayout()
        layout.addWidget(text)
        dialog.setLayout(layout)
        if dialog.exec_():
            pass

    def tipErrorSocketSend(self):
        dialog = QDialog()
        dialog.setFixedSize(120, 40)
        text = QLabel('UDP连接失败')
        text.setFont('黑体')
        layout = QVBoxLayout()
        layout.addWidget(text)
        dialog.setLayout(layout)
        if dialog.exec_():
            pass
Ejemplo n.º 23
0
Archivo: main.py Proyecto: aisyluG/LVM
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.canvas = DrawWidget(self.ui.frame)
        self.ui.canvas.setGeometry(
            QRect(2, 2,
                  self.ui.frame.width() - 165,
                  self.ui.frame.height() - 6))
        palet = QPalette()
        palet.setColor(QPalette.Window, QColor('#ffffff'))
        palet.setColor(QPalette.Button, QColor('#ffffff'))
        self.ui.canvas.setPalette(palet)
        self.ui.canvas.setAutoFillBackground(True)

        ds = DangerousState()
        self.dangStates = [ds]
        self.ui.canvas.setState(ds)
        self.ui.listWidget.addItem('dangerous state 1')
        self.ui.listWidget.setCurrentRow(0)

        # кнопки
        self.ui.andBt.setStyleSheet('background-color: #f0f0f0;')
        self.ui.orBt.setStyleSheet('background-color: #f0f0f0;')
        self.ui.cursorBt.setStyleSheet('background-color: blue;')
        self.ui.stateBt.setStyleSheet('background-color: #f0f0f0;')
        self.ui.iniStateBt.setStyleSheet('background-color: #f0f0f0;')
        self.ui.dangStateBt.setStyleSheet('background-color: #f0f0f0;')
        self.ui.connectBt.setStyleSheet(('background-color: #f0f0f0;'))
        self.ui.cleanBt.setStyleSheet(('background-color: #f0f0f0;'))
        self.ui.delBt.setStyleSheet(('background-color: #f0f0f0;'))
        self.ui.addDSbt.setStyleSheet(('background-color: #f0f0f0;'))
        self.ui.saveBt.setStyleSheet(('background-color: #f0f0f0;'))
        self.ui.openBt.setStyleSheet(('background-color: #f0f0f0;'))

        # обработчики событий
        self.ui.andBt.clicked.connect(self.change_paintMode)
        self.ui.orBt.clicked.connect(self.change_paintMode)
        self.ui.stateBt.clicked.connect(self.change_paintMode)
        self.ui.cursorBt.clicked.connect(self.change_paintMode)
        self.ui.dangStateBt.clicked.connect(self.change_paintMode)
        self.ui.iniStateBt.clicked.connect(self.change_paintMode)
        self.ui.connectBt.clicked.connect(self.change_paintMode)
        self.ui.canvas.selectedChanged.connect(self.probabEnter)
        self.ui.computeDEPbt.clicked.connect(self.computing)
        self.ui.cleanBt.clicked.connect(self.cleancanvas)
        self.ui.addDSbt.clicked.connect(self.addNewDstate)
        self.ui.listWidget.currentItemChanged.connect(self.stateChanged)
        self.ui.canvas.dang_stateRenamed.connect(self.renameState)
        self.ui.delBt.clicked.connect(self.delCurrent)
        self.ui.openBt.clicked.connect(self.open)
        self.ui.saveBt.clicked.connect(self.save)

        self.selectedState = None

    def renameState(self, text):
        index = self.ui.listWidget.currentIndex()
        self.ui.listWidget.item(index.row()).setText(text)

    def delCurrent(self):
        self.ui.canvas.delCurrent()

    def stateChanged(self):
        index = self.ui.listWidget.currentIndex()
        self.ui.canvas.setState(self.dangStates[index.row()])
        self.ui.canvas.update()

    def addNewDstate(self):
        c = self.ui.listWidget.count()
        self.ui.listWidget.addItem(f'dangerous state {c + 1}')
        # try:
        #     self.ui.listWidget.setCurrentRow(c)
        # except Exception:
        #     print(Exception.mro())
        item = DangerousState()
        self.dangStates.append(item)
        self.ui.canvas.setState(item)
        self.ui.canvas.update()
        self.ui.listWidget.setCurrentRow(c)

    def change_paintMode(self):
        name = self.sender().objectName()
        self.ui.andBt.setStyleSheet('background-color: #f0f0f0;')
        self.ui.orBt.setStyleSheet('background-color: #f0f0f0;')
        self.ui.cursorBt.setStyleSheet('background-color: #f0f0f0;')
        self.ui.stateBt.setStyleSheet('background-color: #f0f0f0;')
        self.ui.dangStateBt.setStyleSheet('background-color: #f0f0f0;')
        self.ui.iniStateBt.setStyleSheet('background-color: #f0f0f0;')
        icon = QIcon()
        icon.addPixmap(
            QPixmap(
                "D:/ucheba/4 курс/теория_принятия_решений/LVM/connect.bmp"),
            QIcon.Normal, QIcon.Off)
        self.ui.connectBt.setIcon(icon)
        self.ui.connectBt.setStyleSheet(('background-color: #f0f0f0;'))
        if name == 'andBt':
            self.ui.canvas.setMode('and')
            self.ui.andBt.setStyleSheet('background-color: blue;')
        elif name == 'orBt':
            self.ui.canvas.setMode('or')
            self.ui.orBt.setStyleSheet('background-color: blue;')
        elif name == 'stateBt':
            self.ui.canvas.setMode('state')
            self.ui.stateBt.setStyleSheet('background-color: blue;')
        elif name == 'dangStateBt':
            self.ui.canvas.setMode('dang')
            self.ui.dangStateBt.setStyleSheet('background-color: blue;')
        elif name == 'iniStateBt':
            self.ui.canvas.setMode('ini')
            self.ui.iniStateBt.setStyleSheet('background-color: blue;')
        elif name == 'cursorBt':
            self.ui.canvas.setMode('cursor')
            self.ui.cursorBt.setStyleSheet('background-color: blue;')
        elif name == 'connectBt':
            self.ui.canvas.setMode('connect')
            icon = QIcon()
            icon.addPixmap(
                QPixmap(
                    "D:/ucheba/4 курс/теория_принятия_решений/LVM/connect_active.bmp"
                ), QIcon.Normal, QIcon.Off)
            self.ui.connectBt.setIcon(icon)
            self.ui.connectBt.setStyleSheet('background-color: blue;')

    def probabEnter(self, figure):
        self.selectedState = figure
        if figure is not None and figure.isClass(figures.IniStateFigure):
            self.ui.probLabel.setText(figure.get_name())

    def keyReleaseEvent(self, a0: QKeyEvent):
        if a0.key() == Qt.Key_Return:
            c = self.ui.dsCostBt.value()
            self.ui.canvas.dang_state.dang_state.setCost(c)
            if self.selectedState is not None and self.selectedState.isClass(
                    figures.IniStateFigure):
                p = self.ui.doubleSpinBox.value()
                self.selectedState.setProbability(p)
                self.ui.probLabel.setText('Вероятность')
                self.selectedState = None
                self.ui.canvas.update()

    def computing(self):
        text = self.ui.canvas.computeConditionFunc()
        self.ui.textEdit.setHtml(text)

    def cleancanvas(self):
        self.selectedState = None
        self.ui.canvas.clean()

    def open(self):
        filename, _ = QFileDialog.getOpenFileName(
            self, 'Загрузка данных об опасном состоянии', '/danger_state.txt',
            'Текстовый документ (*.txt)')
        if _ == 'Текстовый документ (*.txt)':
            self.ui.canvas.load(filename)

    def save(self):
        filename, _ = QFileDialog.getSaveFileName(
            self, 'Сохранение данных об опасном состоянии',
            '/danger_state.txt', 'Текстовый документ (*.txt)')
        if _ == 'Текстовый документ (*.txt)':
            self.ui.canvas.save(filename)
Ejemplo n.º 24
0
class MapWatchWindow(QtWidgets.QMainWindow):

    def __init__(self, parent=None):
        super().__init__(parent)
        # General Settings
        self.version = '0.3'
        self.appTitle = 'Map Watch (v'+self.version+')'
        self.setWindowIcon(QtGui.QIcon(r'images\\icon.ico'))
        self.firstClose = 1
        self.zana_mods = [ # TODO: maybe load from outside source? settings.ini?
            ['None', 'Free', 0, 0, ''],
            ['Item Quantity', 'Free', 1, 0, '+1% Quantity Per Master Level'],
            ['Rampage', '4x Chaos Orbs', 2, 0, 'Slaying enemies quickly grants Rampage bonuses'],
            ['Bloodlines', '4x Chaos Orb', 2, 15, 'Magic Monster Packs each have a Bloodline Mod'],
            ['Anarchy', '8x Chaos Orb', 3, 16, 'Area is inhabited by 4 additional Rogue Exiles'],
            ['Invasion', '8x Chaos Orb', 3, 16, 'Area is inhabited by 3 additional Invasion Bosses'],
            ['Domination', '10x Chaos Orb', 4, 0, 'Area Contains 5 Extra Shrines'],
            ['Onslaught', '8x Chaos Orb', 4, 30, '40% Increased Monster Cast & Attack Speed'],
            ['Torment', '8x Chaos Orb', 5, 12, 'Area spawns 3 extra Tormented Spirits (Stacks with any that naturally spawned)'],
            ['Beyond', '12x Chaos Orb', 5, 8, 'Slaying enemies close together can attract monsters from Beyond this realm'],
            ['Ambush', '12x Chaos Orb', 6, 0, 'Area contains 4 extra Strongboxes'],
            ['Nemesis', '1x Exalted Orb', 7, 0, 'One Rare Per Pack, Rare Monsters Each Have A Nemesis Mod'],
            ['Tempest', '3x Exalted Orb', 8, 16, 'Powerful Tempests can affect both Monsters and You'],
            ['Warbands', '3x Exalted Orb', 8, 16, 'Area is inhabited by 2 additional Warbands']
        ]
        #Windows hwnd
        self._handle = None
        self.window = None
        # System Tray Icon
        self.sysTrayIcon = QtWidgets.QSystemTrayIcon()
        self.sysTrayIcon.setIcon(QtGui.QIcon(r'images\\icon.ico'))
        self.sysTrayIcon.show()
        self.sysTrayIcon.activated.connect(self.restore)
        # System Tray Context Menu
        menu = QtWidgets.QMenu(parent)
        icon = QtGui.QIcon(r'images\\icon.ico')
        restoreAction = QtWidgets.QAction(icon, '&Show Map Watch', self)
        restoreAction.triggered.connect(self.popup)
        menu.addAction(restoreAction)
        icon = QtGui.QIcon('')
        exitAction = QtWidgets.QAction(icon, '&Exit', self)
        exitAction.triggered.connect(self.closeApplication)
        menu.addAction(exitAction)
        self.sysTrayIcon.setContextMenu(menu)
        # This will do the Map Watching in a different thread
        self.thread = MapWatcher()
        self.thread.runLoop()
        self.thread.trigger.connect(self.newMapFound)  # Triggered when new map found
        # Configure UI
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setFixedSize(471, 413)
        self.setWindowTitle(self.appTitle)
        self.ui_confirm = ConfirmDialog(self)
        self.ui_prefs = Preferences(self)
        self.setPrefs()
        self.addZanaMods()
        if not int(self.settings['AlwaysOnTop']):
            self.setWindowFlags(Qt.CustomizeWindowHint|Qt.WindowCloseButtonHint|Qt.X11BypassWindowManagerHint)
        else:
            self.setWindowFlags(Qt.CustomizeWindowHint|Qt.WindowCloseButtonHint|Qt.WindowStaysOnTopHint|Qt.X11BypassWindowManagerHint)  
        # Button Actions
        self.ui.ms_add_map.clicked.connect(self.addMap)
        self.ui.ms_remove_map.clicked.connect(self.removeMap)
        self.ui.mr_clear_map.clicked.connect(self.clearMap)
        self.ui.mr_run_map.clicked.connect(self.runMap)
        self.ui.mr_add_zana_mod.currentIndexChanged.connect(self.changeZanaMod)
        self.ui.mr_add_bonus_iq.valueChanged.connect(self.changeBonusIQ)
        # Menu Actions
        self.ui.menu_create_new_db.triggered.connect(lambda: self.setDBFile(True))
        self.ui.menu_load_db.triggered.connect(self.setDBFile)
        self.ui.menu_open_stats.triggered.connect(self.openStatFile)
        self.ui.menu_exit_app.triggered.connect(self.closeApplication)
        self.ui.menu_ms_add_map.triggered.connect(self.addMap)
        self.ui.menu_ms_add_unlinked_map.triggered.connect(lambda: self.addMap(True))
        self.ui.menu_ms_remove_map.triggered.connect(self.removeMap)
        self.ui.menu_mr_clear_map.triggered.connect(self.clearMap)
        self.ui.menu_mr_run_map.triggered.connect(self.runMap)
        self.ui.menu_preferences.triggered.connect(self.getPrefs)
        self.ui.menu_about.triggered.connect(self.about)
        # Keyboard Shortcuts
        self.hotkey_add = QtWidgets.QShortcut(QtGui.QKeySequence("A"), self, self.addMap)
        self.hotkey_addu = QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+U"), self, lambda: self.addMap(True))
        QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+D"), self, self.removeMap)
        QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+X"), self, self.clearMap)
        QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+R"), self, self.runMap)
        QtWidgets.QShortcut(QtGui.QKeySequence("Z"), self, lambda: self.giveFocus('ZanaMod'))
        QtWidgets.QShortcut(QtGui.QKeySequence("Q"), self, lambda: self.giveFocus('BonusIQ'))
        QtWidgets.QShortcut(QtGui.QKeySequence("F1"), self, lambda: self.setDBFile(True))
        QtWidgets.QShortcut(QtGui.QKeySequence("F2"), self, self.setDBFile)
        QtWidgets.QShortcut(QtGui.QKeySequence("F3"), self, self.openStatFile)
        QtWidgets.QShortcut(QtGui.QKeySequence("F4"), self, self.getPrefs)
        QtWidgets.QShortcut(QtGui.QKeySequence("F5"), self, self.about)
        QtWidgets.QShortcut(QtGui.QKeySequence("F12"), self, self.closeApplication)
        self.button_access = [False, False, False, False]
        # Setup Map Database
        self.map_data = None
        self.mapDB = MapDatabase(self)
        if int(self.settings['LoadLastOpenedDB']):
            if os.path.exists(self.settings['LastOpenedDB']):
                self.mapDB.setDBFile(self.settings['LastOpenedDB'])
                self.mapDB.setupDB('Checking DB Structure', True)
            else:
                self.mapDB.setupDB(self.settings['LastOpenedDB'])
        else:
            self.buttonAccess(self.button_access)
        self.updateWindowTitle()

    def _window_enum_callback(self, hwnd, wildcard):
        '''Pass to win32gui.EnumWindows() to check all the opened windows'''
        if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) != None:
            self._handle = hwnd
            print('hwnd: '+str(self._handle))
        #print(str(win32gui.GetWindowText(hwnd)))

    def restore(self, action):
        if action == self.sysTrayIcon.DoubleClick:
            self.popup()

    def popup(self):
        self.showNormal()
        #self.show()
        self.activateWindow()
        if self._handle:
            #win32gui.ShowWindow(self._handle, win32con.SW_RESTORE)
            win32gui.BringWindowToTop(self._handle)
            if int(self.settings['AlwaysOnTop']):
                win32gui.SetWindowPos(self._handle, win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_SHOWWINDOW + win32con.SWP_NOMOVE + win32con.SWP_NOSIZE)
            else:
                win32gui.SetWindowPos(self._handle, win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_SHOWWINDOW + win32con.SWP_NOMOVE + win32con.SWP_NOSIZE)
            self.window.SetFocus() #STEAL FOCUS! HAHA, f**k you Microsoft

    def giveFocus(self, widget):
        if widget is 'ZanaMod':
            self.ui.mr_add_zana_mod.setFocus(Qt.ShortcutFocusReason)
        elif widget is 'BonusIQ':
            self.ui.mr_add_bonus_iq.setFocus(Qt.ShortcutFocusReason)

    def newMapFound(self, map_data):
        self.popup()
        self.map_data = map_data
        self.button_access = [True, True, True, True]
        if self.thread.map_type is MapType.Fragment:
            self.button_access[Button.Add] = False
            self.hotkey_add.setEnabled(False)
            self.hotkey_addu.setEnabled(False)
        else:
            self.hotkey_add.setEnabled(True)
            self.hotkey_addu.setEnabled(True)
        self.buttonAccess(self.button_access)
        self.updateUiMapSelected()

    def updateUiMapSelected(self):
        print('UI Updated')
        # Clear those items that may not be updated with new map
        self.ui.ms_iq.setText('0%')
        self.ui.ms_ir.setText('0%')
        self.ui.ms_pack_size.setText('0%')
        self.ui.ms_mods.setText('None')
        # Get each piece of map info and update UI lables, etc
        if Map.TimeAdded in self.map_data:
            h = '%H'
            ms = ''
            p = ''
            if int(self.settings['ClockHour12']):
                h = '%I'
                p = ' %p'
            if int(self.settings['ShowMilliseconds']):
                ms = '.%f'
            time_added = datetime.datetime.fromtimestamp(self.map_data[Map.TimeAdded]).strftime(h+':%M:%S'+ms+p)
            self.ui.ms_time_stamp.setText(time_added)
        if Map.Name in self.map_data:
            self.ui.ms_name.setText(self.map_data[Map.Name])
        if Map.Tier in self.map_data:
            level = int(self.map_data[Map.Tier]) + 67
            self.ui.ms_tier.setText(self.map_data[Map.Tier] + '  (' + str(level) + ')')
        if Map.IQ in self.map_data:
            self.ui.ms_iq.setText(self.map_data[Map.IQ]+'%')
        if Map.IR in self.map_data:
            self.ui.ms_ir.setText(self.map_data[Map.IR]+'%')
        if Map.PackSize in self.map_data:
            self.ui.ms_pack_size.setText(self.map_data[Map.PackSize]+'%')
        if Map.Rarity in self.map_data:
            rarity = self.map_data[Map.Rarity]
            self.ui.ms_rarity.setText(rarity)
            if rarity == 'Rare':
                self.ui.ms_name.setStyleSheet("color: rgb(170, 170, 0);")
            elif rarity == 'Magic':
                self.ui.ms_name.setStyleSheet("color: rgb(0, 85, 255);")
            elif rarity == 'Unique':
                self.ui.ms_name.setStyleSheet("color: rgb(170, 85, 0);")
            else:
                self.ui.ms_name.setStyleSheet("color: rgb(0, 0, 0);")
        if Map.Mod1 in self.map_data:
            all_mods = self.map_data[Map.Mod1]
            self.ui.ms_mods.setText(all_mods)
        if Map.Mod2 in self.map_data:
            all_mods = all_mods + '\r\n' + self.map_data[Map.Mod2]
            self.ui.ms_mods.setText(all_mods)
        if Map.Mod3 in self.map_data:
            all_mods = all_mods + '\r\n' + self.map_data[Map.Mod3]
            self.ui.ms_mods.setText(all_mods)
        if Map.Mod4 in self.map_data:
            all_mods = all_mods + '\r\n' + self.map_data[Map.Mod4]
            self.ui.ms_mods.setText(all_mods)
        if Map.Mod5 in self.map_data:
            all_mods = all_mods + '\r\n' + self.map_data[Map.Mod5]
            self.ui.ms_mods.setText(all_mods)
        if Map.Mod6 in self.map_data:
            all_mods = all_mods + '\r\n' + self.map_data[Map.Mod6]
            self.ui.ms_mods.setText(all_mods)
        if Map.Mod7 in self.map_data:
            all_mods = all_mods + '\r\n' + self.map_data[Map.Mod7]
            self.ui.ms_mods.setText(all_mods)
        if Map.Mod8 in self.map_data:
            all_mods = all_mods + '\r\n' + self.map_data[Map.Mod8]
            self.ui.ms_mods.setText(all_mods)
        if Map.Mod9 in self.map_data:
            all_mods = all_mods + '\r\n' + self.map_data[Map.Mod9]
            self.ui.ms_mods.setText(all_mods)

    def updateUiMapRunning(self, clear=False):
        print('UI Updated')
        if clear:
            self.ui.mr_name.setText('None')
            self.ui.mr_tier.setText('0')
            self.ui.mr_iq.setText('0%')
            self.ui.mr_bonus_iq.setText('')
            self.ui.mr_ir.setText('0%')
            self.ui.mr_pack_size.setText('0%')
            self.ui.mr_rarity.setText('')
            self.ui.mr_mods.setText('')
            self.ui.mr_name.setStyleSheet("color: rgb(0, 0, 0);")
        else:
            self.ui.mr_name.setText(self.ui.ms_name.text())
            self.ui.mr_tier.setText(self.ui.ms_tier.text())
            self.ui.mr_iq.setText(self.ui.ms_iq.text())
            self.ui.mr_ir.setText(self.ui.ms_ir.text())
            self.ui.mr_pack_size.setText(self.ui.ms_pack_size.text())
            self.ui.mr_rarity.setText(self.ui.ms_rarity.text())
            self.ui.mr_mods.setText(self.ui.ms_mods.toPlainText())
            self.map_mod_text = self.ui.ms_mods.toHtml() # orginal copy for bonus IQ add/remove
            rarity = self.ui.ms_rarity.text()
            if rarity == 'Rare':
                self.ui.mr_name.setStyleSheet("color: rgb(170, 170, 0);")
            elif rarity == 'Magic':
                self.ui.mr_name.setStyleSheet("color: rgb(0, 85, 255);")
            elif rarity == 'Unique':
                self.ui.mr_name.setStyleSheet("color: rgb(170, 85, 0);")
            else:
                self.ui.mr_name.setStyleSheet("color: rgb(0, 0, 0);")

    def updateUiMapRunningBonuses(self):
        print('UI Updated')
        if Map.BonusIQ in self.mapDB.map_running and self.mapDB.map_running[Map.BonusIQ] != 0:
            self.ui.mr_bonus_iq.setText('+'+str(self.mapDB.map_running[Map.BonusIQ])+'%')
        else:
            self.ui.mr_bonus_iq.setText('')
        if Map.Mod9 in self.mapDB.map_running:
            if self.mapDB.map_running[Map.Mod9] and self.map_mod_text:
                all_mods = self.map_mod_text + '\r\n<br><b>' +self.mapDB.map_running[Map.Mod9]+ '</b>'
                self.ui.mr_mods.setText(all_mods)
            else:
                self.ui.mr_mods.setText(self.map_mod_text)

    def removeMap(self):
        print('Removing Last Map')
        self.ui_confirm.boxType('confirm')
        del_map = None
        if self.ui_confirm.exec_('Remove Map?', 'Are you sure you want to delete the last map saved to database?'):
            del_map = self.mapDB.deleteLastMap(Maps.Dropped)
            self.updateWindowTitle()
        if del_map:
            self.sysTrayIcon.showMessage(
                'Last Map Removed',
                del_map+' was removed from the database.',
                1, 1000)

    def addMap(self, unlinked=False):
        print('Adding to Map Drops')
        add_map = self.mapDB.addMap(self.map_data, unlinked)
        if add_map:
            self.minimizeToSysTray()
            self.updateWindowTitle()
            self.sysTrayIcon.showMessage(
                'Map Added',
                add_map+' was added to the database.',
                1, 1000)

    def clearMap(self):
        if self.mapDB.map_running:
            self.ui_confirm.boxType('confirm')
            if self.ui_confirm.exec_('Map Cleared?', 'Is the current running map cleared?  No more map drops will be linked to this map.'):
                self.mapDB.clearMap()
                self.updateUiMapRunning(True)
                return True
            else:
                return False
        else:
            return True

    def runMap(self):
        print('Running Selected Map')
        if self.mapDB.runMap(self.map_data):
            self.updateUiMapRunning()
            self.resetBonuses()

    def setDBFile(self, new=False):
        if self.clearMap():
            abs_path = os.path.abspath(os.path.dirname('__file__'))
            if new:
                file_name = QFileDialog.getSaveFileName(self, 'Create New Database File', abs_path+'/data', 'SQLite Files (*.sqlite)')
                if file_name[0]:
                    self.mapDB.setupDB(file_name[0])
            else:
                file_name = QFileDialog.getOpenFileName(self, 'Load Database File', abs_path+'/data', 'SQLite Files (*.sqlite)')
            # Update settings
            if file_name[0]:
                self.mapDB.setDBFile(file_name[0])
                if not new:
                    self.mapDB.setupDB('Checking DB Structure', True)
                self.updateWindowTitle()
                self.buttonAccess([True, True, True, True])
                self.settings['LastOpenedDB'] = file_name[0]
                writeSettings(self.settings)

    def addZanaMods(self):
        print('Adding Zana Mods to Combo Box')
        self.ui.mr_add_zana_mod.clear()
        for i, zana_mod in enumerate(self.zana_mods):
            self.ui.mr_add_zana_mod.addItem(zana_mod[ZanaMod.Name] + ' (' + zana_mod[ZanaMod.Cost] + ')')
            if int(self.settings['ZanaDefaultModIndex']) == i:
                self.ui.mr_add_zana_mod.setCurrentIndex(i)
            if int(self.settings['ZanaLevel']) < zana_mod[ZanaMod.Level]:
                break # Stop adding mod options if Zana level is to low to run them

    def changeZanaLevel(self):
        self.zana_mods[1][ZanaMod.IQ] = int(self.settings['ZanaLevel'])
        self.addZanaMods()

    def changeZanaMod(self):
        print('New Zana Mod Selected')
        if self.mapDB.map_running:
            self.mapDB.map_running[Map.BonusIQ] = self.calcBonusIQ()
            zana_mod_str = self.zana_mods[self.ui.mr_add_zana_mod.currentIndex()][ZanaMod.Desc]
            self.mapDB.map_running[Map.Mod9] = zana_mod_str
            self.updateUiMapRunningBonuses()
            self.ui.mr_mods.moveCursor(QtGui.QTextCursor.End)

    def changeBonusIQ(self):
        print('Bonus IQ Changed')
        if self.mapDB.map_running:
            self.mapDB.map_running[Map.BonusIQ] = self.calcBonusIQ()
            self.updateUiMapRunningBonuses()

    def calcBonusIQ(self):
        zana_iq = self.zana_mods[self.ui.mr_add_zana_mod.currentIndex()][ZanaMod.IQ]
        bonus_iq = self.ui.mr_add_bonus_iq.property('value') + zana_iq
        return bonus_iq

    def resetBonuses(self):
        self.ui.mr_add_zana_mod.setCurrentIndex(-1) # force change event
        self.ui.mr_add_zana_mod.setCurrentIndex(int(self.settings['ZanaDefaultModIndex']))
        self.ui.mr_add_bonus_iq.setProperty('value', 0)

    def openStatFile(self):
        stat_file = self.settings['SelectedStatisticsFile']
        webbrowser.open('file://' + stat_file)

    def getPrefs(self):
        if self.ui_prefs.exec_():
            self.setPrefs()

    def setPrefs(self):
        self.settings = readSettings()
        self.popup()
        self.thread.setMapCheckInterval(float(self.settings['MapCheckInterval']))
        self.changeZanaLevel()
        hour12 = self.settings['ClockHour12']
        milliseconds = self.settings['ShowMilliseconds']
        hour12 = False if hour12 == '0' else True
        milliseconds = False if milliseconds == '0' else True
        settings = {'hour12': hour12, 'milliseconds': milliseconds}
        writeSettingsJS(settings)
        print("Preferences Updated")

    def about(self):
        self.ui_confirm.boxType('about')
        self.ui_confirm.exec_('About', 'Map Watch\nVersion '+self.version+'\n\nCreated by\[email protected]\nIGN: Grahf_Azura')

    def updateWindowTitle(self):
        if self.mapDB.db_file:
            map_count = self.mapDB.countMapsAdded()
            self.setWindowTitle(self.appTitle + ' ---> ' + str(map_count) + ' map drops in database (' + os.path.basename(self.mapDB.db_file) + ')')
        else:
            self.setWindowTitle(self.appTitle + ' ---> Map Database Not Loaded')

    def buttonAccess(self, button):
        self.ui.ms_add_map.setEnabled(button[Button.Add])
        self.ui.ms_remove_map.setEnabled(button[Button.Remove])
        self.ui.mr_clear_map.setEnabled(button[Button.Clear])
        self.ui.mr_run_map.setEnabled(button[Button.Run])
        self.ui.menu_ms_add_map.setEnabled(button[Button.Add])
        self.ui.menu_ms_add_unlinked_map.setEnabled(button[Button.Add])
        self.ui.menu_ms_remove_map.setEnabled(button[Button.Remove])
        self.ui.menu_mr_clear_map.setEnabled(button[Button.Clear])
        self.ui.menu_mr_run_map.setEnabled(button[Button.Run])

    def error(self, err_msg, errors=None):
        err_msg += '\n'
        if errors is not None:
            for err in errors:
                err_msg += '\n'+str(err)
                #print(err)
        self.ui_confirm.boxType('error')
        self.ui_confirm.exec_('Error', err_msg)

    def closeApplication(self):
        print('Map Watch Closing')
        self.mapDB.clearMap() # In-case user forgot to clear thier map before closing app
        self.sysTrayIcon.hide()
        sys.exit()

    def closeEvent(self, event):
        # Changes the close button (X) behavior to minimize instead
        event.ignore()
        if self.firstClose:
            self.sysTrayIcon.showMessage(
                'Minimized To System Tray',
                'Map Watch will still continue to run in the background. Right click and select exit to shut down application.',
                1, 1000)
            self.firstClose = 0
        self.minimizeToSysTray()
        #self.closeApplication()

    def minimizeToSysTray(self):
        self.showMinimized()
        self.hide()
Ejemplo n.º 25
0
class MainWindow(QMainWindow, Ui_MainWindow):

    # Create settings for the software
    settings = QSettings('GGGG', 'Game Genie Good Guy')
    settings.setFallbacksEnabled(False)
    version = '1.0.0'

    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        # Load the ui
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # Set the MainWindow Title
        self.setWindowTitle('Game Genie Good Guy - ' + self.version)
        # When the software are closed on console the software are closed
        signal.signal(signal.SIGINT, signal.SIG_DFL)
        self.ui.system.addItem("Game Boy/Gear/Master System")
        self.ui.system.addItem("Genesis/Mega Drive (no SMD roms)")
        self.ui.system.addItem("Nintendo")
        self.ui.system.addItem("Super Nintendo")
        self.ui.browse.clicked.connect(self.browse)
        self.ui.patch.clicked.connect(self.generateRom)
        self.ui.ips.clicked.connect(self.generateIPS)
        self.ui.log.setReadOnly(True)
        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self.printLog)
        if self.settings.value("rom"):
            self.ui.rom.setText(self.settings.value("rom"))
        if self.settings.value("system"):
            self.ui.system.setCurrentIndex(int(self.settings.value("system")))
        # Show the form
        self.show()

    def browse(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(
            self,
            "QFileDialog.getOpenFileName()",
            "",
            "All Files (*);;",
            options=options)
        self.ui.rom.setText(str(fileName))
        self.settings.setValue("rom", str(fileName))

    def printLog(self):
        self.ui.log.clear()
        result = self.process.readAllStandardOutput().data().decode()
        self.ui.log.appendPlainText(result)

    def generateRom(self):
        self.rom = str(self.ui.rom.text())
        name, ext = os.path.splitext(self.rom)
        self.newrom = "{name}-{uid}{ext}".format(name=name, uid='new', ext=ext)
        system = int(self.ui.system.currentIndex()) + 1
        codes = str(self.ui.codes.toPlainText())
        self.settings.setValue("system", system - 1)
        system = str(system)
        if self.rom != '':
            self.process.start('./GGGG "' + codes + '" ' + system + ' "' +
                               self.rom + '" "' + self.newrom + '"')
            self.process.waitForFinished()
            self.process.close()

    # Based on https://github.com/fbeaudet/ips.py/blob/master/ips.py
    def generateIPS(self):
        self.generateRom()
        FILE_LIMIT = 0x1000000  #16MB
        PATCH_ASCII = bytes((0x50, 0x41, 0x54, 0x43, 0x48))
        EOF_ASCII = bytes((0x45, 0x4f, 0x46))
        name, ext = os.path.splitext(self.rom)
        ipsfile = "{name}{uid}{ext}".format(name=name, uid='', ext='.ips')
        original = open(self.rom, 'rb').read()
        modified = open(self.newrom, 'rb').read()
        patch = open(ipsfile, 'wb')
        recording = False
        record = bytearray()
        size = bytearray(2)

        if len(modified) > FILE_LIMIT:
            self.ui.log.appendPlainText(
                "\nModified file is too large for IPS format. Max: 16MB.")

        patch.write(PATCH_ASCII)
        for a in range(len(modified)):
            if not recording:
                if len(original) <= a or modified[a] != original[a]:
                    recording = True
                    record = bytearray()
                    offset = bytearray(3)

                    if a == EOF_ASCII:
                        record.append(modified[a - 1])

                    record.append(modified[a])
                    for x in range(3):
                        offset[x] = (a >> (16 - x * 8)) % 256

                    patch.write(offset)

                    if a == len(modified) - 1:
                        recording = False
                        patch.write(b'\x00\x01')
                        patch.write(record)
            else:
                if len(original) <= a or modified[a] != original[a]:
                    record.append(modified[a])

                    if a == len(modified) - 1:
                        recording = False
                        for x in range(2):
                            size[x] = len(record) >> (8 - x * 8)

                        patch.write(size)
                        patch.write(record)
                else:
                    recording = False
                    for x in range(2):
                        size[x] = len(record) >> (8 - x * 8)

                    patch.write(size)
                    patch.write(record)

        patch.write(EOF_ASCII)
        patch.close()
        self.ui.log.appendPlainText("\nIPS file generated")
Ejemplo n.º 26
0
class Cache(object):
    def __init__(self):
        self.cache_window = QtGui.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.cache_window)
        self.cache_window.show()
Ejemplo n.º 27
0
class WindowOperator(QtWidgets.QMainWindow):
    def __init__(self):
        super(WindowOperator, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.path_img_lineedit.setReadOnly(True)
        self.ui.predict_button.clicked.connect(self.predict_images)
        self.ui.file_path_button.clicked.connect(self.get_file_path)
        self.ui.model_box.currentIndexChanged.connect(self.get_model_path)
        self.ui.path_model_lable.setText('')
        self.ui.predict_button.setEnabled(False)

        self.images_path = ''
        self.model_path = config.lenet

    def get_file_path(self):
        """
        Get path to image or images
        :return:
        """
        self.images_path = QtWidgets.QFileDialog.getOpenFileNames(
            self, 'Select imgs', 'С:', "Images(*.png *.jpg *.jpeg)")[0]
        if not self.images_path:
            QMessageBox.critical(self, "Error path to image or images",
                                 "Please select path.")
            self.ui.predict_button.setEnabled(False)
            self.ui.path_model_lable.setText('')
        else:
            if self.model_path:
                self.ui.predict_button.setEnabled(True)

        temp_str = ''.join(self.images_path)
        self.ui.path_img_lineedit.setText(temp_str)

    def get_model_path(self):
        """
        Get model path, input path to label
        :return:
        """
        if self.ui.model_box.currentText() == 'LeNet':
            self.model_path = config.lenet
            self.ui.predict_button.setEnabled(True)
            self.ui.path_model_lable.setText('')
        if self.ui.model_box.currentText() == 'AlexNet':
            self.model_path = config.alexnet
            self.ui.predict_button.setEnabled(True)
            self.ui.path_model_lable.setText('')
        if self.ui.model_box.currentText() == 'VGG16':
            self.model_path = config.vgg16
            self.ui.predict_button.setEnabled(True)
            self.ui.path_model_lable.setText('')
        if self.ui.model_box.currentText() == 'VGG19':
            self.model_path = config.vgg19
            self.ui.predict_button.setEnabled(True)
            self.ui.path_model_lable.setText('')
        if self.ui.model_box.currentText() == 'Xception':
            self.model_path = config.xception
            self.ui.predict_button.setEnabled(True)
            self.ui.path_model_lable.setText('')

        if self.ui.model_box.currentIndex() == 5:
            self.model_path = QtWidgets.QFileDialog.getOpenFileNames(
                self, 'Select model', 'D:/MAGA_DIP/DiplomProject',
                "Model (*.hdf5)")[0]
            path_model_label_text = 'Select model: ' + ''.join(self.model_path)
            self.ui.path_model_lable.setText(path_model_label_text)
        if not self.model_path:
            QMessageBox.critical(self, "Error path to model",
                                 "Please select path to model.")
            self.ui.predict_button.setEnabled(False)
            self.ui.path_model_lable.setText('')
        else:
            if not self.images_path:
                self.ui.predict_button.setEnabled(False)

    def predict_images(self):
        """
        Predict classes for images
        :return:
        """
        predict.predict(self.model_path, self.images_path)
Ejemplo n.º 28
0
Archivo: main.py Proyecto: aisyluG/LR2
class Window(QMainWindow):
    # семафор для работы потока
    sem = QSemaphore()

    sem_forBuffer = QSemaphore()
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # буфер для отправленных, но еще не обработанных сообщений
        self.buffer = queue.Queue()
        # потоки для обработки информации
        self.sentThread = QThread()
        self.sentObj = Producer(self.sem, self.buffer)
        self.sentObj.moveToThread(self.sentThread)

        self.n = 1
        self.getThreadsPool = [QThread()]
        self.getObjs = [Consumer(self.sem, self.sem_forBuffer, 1, self.buffer)]
        self.getObjs[0].moveToThread(self.getThreadsPool[0])



        self.ui.sendBt.clicked.connect(self.sentObj.run)
        self.ui.sendBt.clicked.connect(self.check)
        self.sentObj.message_sented.connect(self.getObjs[0].run)
        self.sentObj.message_sented.connect(self.addSendedMessage)
        self.getObjs[0].message_getted.connect(self.addGettedMessage)
        self.ui.okBt.clicked.connect(self.change_threadNumber)


        self.sem_forBuffer.release()
        self.sentThread.start()
        self.getThreadsPool[0].start()

    def check(self):
        print('check', self.sem_forBuffer.available())

    def change_threadNumber(self):
        n_new = self.ui.threadNumberSBox.value()
        if self.n < n_new:
            print(list(range(self.n, n_new)))
            for i in range(self.n, n_new):
                self.getThreadsPool.append(QThread())
                self.getObjs.append(Consumer(self.sem, self.sem_forBuffer, i+1, self.buffer))
                self.getObjs[i].moveToThread(self.getThreadsPool[i])
                self.sentObj.message_sented.connect(self.getObjs[i].run)
                self.getObjs[i].message_getted.connect(self.addGettedMessage)
                self.getThreadsPool[i].start()
        elif self.n > n_new:
            for i in range(n_new, self.n):
                self.getThreadsPool[i].terminate()
                self.getThreadsPool[i].wait()
            self.getThreadsPool = self.getThreadsPool[:n_new]
            self.getObjs = self.getObjs[:n_new]
        self.n = n_new


    def addSendedMessage(self, message):
        self.ui.sendedText.append(message)
        # print('1')

    def addGettedMessage(self, message):
        print('add', self.sem_forBuffer.available())
        self.sem_forBuffer.acquire(1)
        self.ui.gettedText.append(message)
        self.sem_forBuffer.release(1)
Ejemplo n.º 29
0
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from window import Ui_MainWindow

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

window.show()
sys.exit(app.exec_())
Ejemplo n.º 30
0
from PyQt5 import QtWidgets

from window import Ui_MainWindow as ExamWindow


file = open('abbr.csv')
reader = csv.reader(file)
data_table = [row for row in reader]
file.close()
print('Read', len(data_table), 'abbreviations.')


app = QtWidgets.QApplication(sys.argv)
main_window = QtWidgets.QMainWindow()
ui = ExamWindow()
ui.setupUi(main_window)
ui.menubar.hide()

data_row_picked = None
count = 0


def pick_abbr():
    if count > 0:
        ui.lineEdit.returnPressed.disconnect()
    index = random.randint(0, len(data_table) - 1)
    global data_row_picked
    data_row_picked = data_table[index]
    ui.abbr.setText(data_row_picked[0])
    ui.lineEdit.clear()
    ui.lineEdit.returnPressed.connect(submit)
class Editor(QtGui.QMainWindow, QtGui.QWidget):
    def __init__(self, app):

        super(Editor, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pushButton.clicked.connect(self.launch)
        self.ui.pushButton_2.clicked.connect(self.makeInput)

        self.ui.pushButton_2.setVisible(False)

        self.outputdim = np.zeros(4)

        # Variables UI
        self.show()
        self.app = app

    def launch(self):

        inputdim = [
            self.ui.spinBox.value(),
            self.ui.spinBox_2.value(),
            self.ui.spinBox_3.value()
        ]
        stride = [self.ui.spinBox_4.value(), self.ui.spinBox_5.value()]
        weight = [
            self.ui.spinBox_6.value(),
            self.ui.spinBox_7.value(),
            self.ui.spinBox_8.value(),
            self.ui.spinBox_9.value()
        ]

        print("*" * 50)
        print("Layer of input : " + str(inputdim))

        if (self.ui.radioButton.isChecked()):
            pad = 1  # SAME
        else:
            pad = 0  # VALID

        if ((inputdim[0] - weight[0] + pad) % stride[0] != 0):
            print("Error dimension 1")
        self.outputdim[0] = (inputdim[0] - weight[0] + pad) / stride[0] + 1

        if ((inputdim[1] - weight[1] + pad) % stride[1] != 0):
            print("Error dimension 2")
        self.outputdim[1] = (inputdim[1] - weight[1] + pad) / stride[1] + 1

        if (inputdim[2] != weight[2]):
            print("Error dimension 3")
        self.outputdim[2] = weight[3]

        self.ui.Result.setText("[" + str(int(self.outputdim[0])) + ", " +
                               str(int(self.outputdim[1])) + ", " +
                               str(int(self.outputdim[2])) + "]")

        self.ui.pushButton_2.setVisible(True)

    def makeInput(self):

        self.ui.spinBox.setValue(self.outputdim[0])
        self.ui.spinBox_2.setValue(self.outputdim[1])
        self.ui.spinBox_3.setValue(self.outputdim[2])

        self.ui.pushButton_2.setVisible(False)
Ejemplo n.º 32
0
class UIController(QtGui.QMainWindow):
    def __init__(self, parent=None):
        #Loads of BORING UI setup code!!
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.loadSettings()
        self.initPD()
        self.initFTD()
        self.ui.listView.setModel(self.peer_container)
        self.peerSelection = self.ui.listView.selectionModel()
        self.ui.tableView.setModel(self.proxy)
        self.fileSelection = self.ui.tableView.selectionModel()
        self.dloadMgr = model.DownloadWidgetManager(self.ui.tableWidget)
        self.tableHeaderResize()
        self.initConnection()

    def listCtxtMenu(self, point):
        if not self.peerSelection.hasSelection():
            return
        menu = QtGui.QMenu(parent=self.ui.listView)
        menu.addAction(self.ui.actionExplore)
        menu.addAction(self.ui.actionBlacklistPeer)
        menu.addAction(self.ui.actionDeleteIP)
        menu.exec_(self.ui.listView.mapToGlobal(point))

    def fileCtxtMenu(self, point):
        if not self.fileSelection.hasSelection():
            return
        menu = QtGui.QMenu(parent=self.ui.tableView)
        menu.addAction(self.ui.actionDownload)
        menu.addAction(self.ui.actionDownloadAs)
        menu.exec_(self.ui.tableView.mapToGlobal(point))

    def initConnection(self):
        self.ui.actionDiscover.triggered.connect(self.setDiscover)
        self.ui.actionAddIP.triggered.connect(self.manAddIP)
        self.ui.actionClearBlacklist.triggered.connect(self.resetBan)
        self.ui.actionBlacklistPeer.triggered.connect(self.blacklistPeer)
        self.ui.actionExplore.triggered.connect(self.explorePeer)
        self.peer_container.updated.connect(self.updateHT)
        self.ui.listView.customContextMenuRequested.connect(self.listCtxtMenu)
        self.ui.tableView.customContextMenuRequested.connect(self.fileCtxtMenu)
        self.ui.radioButton.toggled.connect(self.filterIP)
        self.ui.radioButton_2.toggled.connect(self.filterIP)
        self.ui.lineEdit.textChanged.connect(self.proxy.setFilterFixedString)
        self.peerSelection.selectionChanged.connect(self.filterIP)
        self.ui.tableView.doubleClicked.connect(self.downloadAction)
        self.ui.actionDownload.triggered.connect(self.downloadAction)
        self.ui.actionDownloadAs.triggered.connect(self.downloadAsAction)
        self.ui.actionDeleteIP.triggered.connect(self.deletePeer)

    def resetBan(self):
        QtGui.QMessageBox.information(
            self, 'Blacklist Cleared',
            'List of blacklisted peers has been reset')
        self.peer_container.clearBlacklist()

    def filterIP(self):
        if not self.ui.radioButton.isChecked():
            addr = self.getSelectedPeer()
            self.file_model.selectIP(addr)
        else:
            self.file_model.selectIP(None)

    def initPD(self):
        self.busy_peers = []
        self.peer_container = model.PeerContainer()
        mcast_addr = (self.settings['MULTICAST_IP'],
                      int(self.settings['MULTICAST_PORT']))
        self.pd = PDModule(mcast_addr, self.settings['NAME'],
                           self.peer_container)

    def initFTD(self):
        self.finxr = indexer.FileIndexer(self.settings['INDEXER_PATH'])
        self.dfct = daemon.IFFactory(self.finxr)
        reactor.listenTCP(int(self.settings['DAEMON_PORT']), self.dfct)
        self.file_model = model.FileIndexModel()
        self.proxy = model.TxtMapSortProxyModel(self, model.FILE_LIST_MAP)
        self.proxy.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.proxy.setSourceModel(self.file_model)

    def manAddIP(self):
        ipaddr, ok = QtGui.QInputDialog.getText(self, 'Manual IP Entry',
                                                'IP address')
        if ok:
            ipaddr = str(ipaddr)
            if not is_valid_ip(ipaddr):
                QtGui.QMessageBox.warning(self, 'Input Error',
                                          'Invalid IP address')
                return
            rc = self.peer_container.addAddr(ipaddr)
            if rc == 1:
                QtGui.QMessageBox.information(self, 'Address Exception',
                                              'IP is already present')
            elif rc == 2:
                QtGui.QMessageBox.warning(self, 'Address Exception',
                                          'IP is blacklisted')

    def loadSettings(self):
        re_cd, self.settings = load_settings_from_file(SETTINGS_FILE)
        if re_cd:
            self.firstRun()
        save_settings_to_file(self.settings, SETTINGS_FILE)

    def deletePeer(self):
        addr = self.getSelectedPeer()
        self.peer_container.removeAddr(addr)

    def isValidConfig(self):
        return is_name(self.settings['NAME']) and is_dir_path(
            self.settings['INDEXER_PATH'])

    def downloadAction(self):
        name, addr, fHash = self.getSelectedFile()
        option=QtGui.QMessageBox.question(self, 'Download file', 'Confirm download {0}'\
            .format(name), QtGui.QMessageBox.No | QtGui.QMessageBox.Yes)
        if option == QtGui.QMessageBox.Yes:
            sv_fObj = self.quickSaveFile(name)
            if sv_fObj:
                self.downloadFile(name, addr, fHash, sv_fObj)

    def downloadFile(self, name, addr, fHash, fObj):
        d = Deferred()
        fFact = probe.FTFactory(fHash, fObj, d)
        d.addCallback(self.makeDL, name)
        d.addErrback(self.logError, addr)
        reactor.connectTCP(addr, 17395, probe.FTFactory(fHash, fObj, d))

    def makeDL(self, FTProt, name):
        idx = self.dloadMgr.addFTProtocol(name, FTProt)
        FTProt.def_obj.addCallback(self.removeDL, idx)
        FTProt.def_obj.addErrback(self.removeDL, idx)

    def removeDL(self, arg, idFT):
        logging.info(arg)
        self.dloadMgr.doneFT(idFT)

    def downloadAsAction(self):
        name, addr, fHash = self.getSelectedFile()
        sv_fObj = self.saveFilePrompt(name)
        if sv_fObj:
            self.downloadFile(name, addr, fHash, sv_fObj)

    def saveFilePrompt(self, name):
        savePath=str(QtGui.QFileDialog.getSaveFileName(self, 'Choose a destination file', \
            os.path.join(self.finxr.path, 'tmp.'+name.split('.')[-1])))
        if savePath:
            return open(savePath, 'wb')
        return None

    def quickSaveFile(self, saveName):
        try:
            sv_fObj = None
            sv_fObj = self.finxr.saveFile(saveName)
        except:
            option=QtGui.QMessageBox.warning(self, 'File overwrite', 'File exits. Overwrite?', \
                QtGui.QMessageBox.Yes | QtGui.QMessageBox.Abort | QtGui.QMessageBox.Save)
            if option == QtGui.QMessageBox.Yes:
                return self.finxr.saveFile(saveName, True)
            elif option == QtGui.QMessageBox.Save:
                return self.saveFilePrompt(saveName)
        return sv_fObj

    def firstRun(self):
        self.settings = DEFAULT_SETTINGS
        frDialog = QtGui.QDialog(parent=self)
        frDialog.ui = first_run.Ui_Dialog()
        frDialog.ui.setupUi(frDialog)
        frDialog.ui.lineEdit.setText(self.settings['NAME'])

        def folderHandler():
            shareFolder=str(QtGui.QFileDialog.getExistingDirectory(frDialog, \
                'Choose a directory to share'))
            frDialog.ui.lineEdit_2.setText(shareFolder)
            self.settings['INDEXER_PATH'] = shareFolder

        frDialog.ui.pushButton.clicked.connect(folderHandler)
        frDialog.exec_()
        self.settings['NAME'] = str(frDialog.ui.lineEdit.text())
        if not self.isValidConfig():
            QtGui.QMessageBox.critical(self, 'Settings Error',
                                       'Invalid Configuration')
            logging.critical('Invalid Config')
            exit_reactor(1)

    def updateHT(self):
        active_peers = self.peer_container.getAddrList()
        explored_peers = self.file_model.getAddrList()
        for item in explored_peers:
            if not item in active_peers:
                self.file_model.delIndex(item)
        for item in active_peers:
            if not item in explored_peers:
                self.discoverPeer(item)

    def gotHT(self, fileHT, addr):
        self.busy_peers.remove(addr)
        self.file_model.updateIndex(addr, fileHT)

    def discoverPeer(self, addr):
        if addr in self.busy_peers:
            return
        d = Deferred()
        d.addCallback(self.gotHT, addr)
        d.addErrback(self.logError, addr)
        self.busy_peers.append(addr)
        reactor.connectTCP(addr, 17395, probe.FHFactory(d))

    def logError(self, reason, addr, role):
        if addr in self.busy_peers:
            self.busy_peers.remove(addr)
        logging.error('Error in role {2} connecting to {0} : {1}'\
            .format(addr, str(reason), str(role)))

    def setDiscover(self):
        self.pd.setEnable(self.ui.actionDiscover.isChecked())

    def getSelectedPeer(self):
        if not self.peerSelection.hasSelection():
            return ''
        sIdx = self.peerSelection.selectedRows()[0]
        return str(self.peer_container.itemFromIndex(sIdx).text())

    def getSelectedFile(self):
        if not self.fileSelection.hasSelection():
            return None
        return [str(self.file_model.itemFromIndex(self.proxy.mapToSource(\
                self.fileSelection.selectedRows(column=idx)[0])).text()) for idx in [0,2,3]]

    def explorePeer(self):
        addr = self.getSelectedPeer()
        self.discoverPeer(addr)

    def blacklistPeer(self):
        addr = self.getSelectedPeer()
        self.peer_container.blacklistAddr(addr)

    def tableHeaderResize(self):
        header_crtl = self.ui.tableView.horizontalHeader()
        header_crtl.setResizeMode(0, QtGui.QHeaderView.Stretch)
        header_crtl.setResizeMode(1, QtGui.QHeaderView.ResizeToContents)
        header_crtl.setResizeMode(2, QtGui.QHeaderView.ResizeToContents)
        header_crtl = self.ui.tableWidget.horizontalHeader()
        header_crtl.setResizeMode(0, QtGui.QHeaderView.Stretch)
        header_crtl.setResizeMode(1, QtGui.QHeaderView.ResizeToContents)
        header_crtl.setResizeMode(2, QtGui.QHeaderView.ResizeToContents)
Ejemplo n.º 33
0

def copy_to_clipboard():
    global timer
    if timer is None:
        timer = QTimer()
        timer.timeout.connect(timeout)
    timer.start(1000)
    ui.lbl_copied.setVisible(True)
    cp = QtWidgets.QApplication.clipboard()
    cp.clear(mode=cp.Clipboard)
    cp.setText(ui.lbl_passwd.text(), mode=cp.Clipboard)


def timeout():
    ui.lbl_copied.setVisible(False)
    timer.stop()


# PP
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
ui.lbl_copied.setVisible(False)
ui.btn_generate.clicked.connect(generate)
ui.btn_copy.clicked.connect(copy_to_clipboard)
timer = None
generate()
MainWindow.show()
sys.exit(app.exec_())
Ejemplo n.º 34
0
class Formulario(QMainWindow):

    #Constructor de la clase
    def __init__(self):
        #Inicio el objeto QMainwindow
        QMainWindow.__init__(self)
        self.formulario = Ui_MainWindow()
        self.formulario.setupUi(self)

        self.iniciarVariables()
        self.vaciarLog()

        self.reporte = Reporte()

        #seteamos los eventos        
        self.formulario.btnSimulacion.clicked.connect(self.simular)
        self.formulario.btnGraficoDePuntos.clicked.connect(self.armarGraficoPuntos)
        self.formulario.btnGraficoDeBarras.clicked.connect(self.armarGraficoBarras)
        self.formulario.btnReporte.clicked.connect(self.armarReporte)



    def armarReporte(self):
        file = open("log.txt", "r")
        self.reporte.setearTexto( file.read() )
        self.reporte.show()


    def iniciarVariables(self):
        self.formulario.lineEditExp.setValue(1)
        self.formulario.lineEditDias.setValue(20)
        self.formulario.lineEditIncrementoM4.setValue(50)
        self.formulario.lineEditIncrementoM6.setValue(30)
        self.formulario.lineEditVelOperM4.setValue(5)
        self.formulario.lineEditVelOperM6.setValue(10)
        self.formulario.lineEditDiasProd.setValue(10)
        self.formulario.lineEditCantidadM4.setValue(30)
        self.formulario.lineEditCantidadM6.setValue(25)



    def calcularPorcentajes(self, solicitudesAtendidas, solicitudesSinAtender):
        total = solicitudesAtendidas + solicitudesSinAtender
        porcAtendidas = ( solicitudesAtendidas * 100 ) / total
        porcSinAtender = ( solicitudesSinAtender * 100) / total
        return porcAtendidas, porcSinAtender
    
    def vaciarLog(self):
        open("log.txt", "w").close()

    def grabarLog(self,cantEjecuciones,var,promSolicitudesAtendidas, promSolicitudesSinAtender,totalSolicitudes,diferencia):
        text_file = open("log.txt", "a")

        text = """
--- Reporte de simulación N° {} ---
        Parámetros utilizados:
        Meses: {}
        Días: {}
        Días de producción: {}
        Producción fija mensual M4: {}
        Producción fija mensual M6: {}
        Velocidad de atención M4 (min.): {}
        Velocidad de atención M6 (min.): {}
        Cantidad de pedidos M4: {}
        Cantidad de pedidos M6: {}
        ---
        Total de solicitudes: {}
        Promedio de solicitudes atendidas x mes: {}
        Promedio de solicitudes sin atender x mes: {}
        Diferencia observada: {:.2f} %        
        """.format(cantEjecuciones,
        	var.MES,
        	var.DIAS,
        	var.cantDiasProduccion,
        	var.incrementoStockM4, var.incrementoStockM6,        	
        	var.velOperM4, var.velOperM6,
        	var.cantidadM4,var.cantidadM6,
        	totalSolicitudes,
        	promSolicitudesAtendidas, promSolicitudesSinAtender,
        	diferencia)

        text_file.write(text)
        text_file.close()

    def simular(self):
        
        promSolicitudesAtendidas, promSolicitudesSinAtender, var , totalSolicitudes= self.procesar()        
        porcAtendidas, porcSinAtender = self.calcularPorcentajes(promSolicitudesAtendidas, promSolicitudesSinAtender)        
        listaPorcAtendidas.append(porcAtendidas)                      
        cantEjecuciones = len(listaPorcAtendidas)
        diferencia=0
        print('---------------------------------------------------------------')
        print('Promedio Solicitudes atendidas: {} ({:.2f}%) '.format(str(promSolicitudesAtendidas), porcAtendidas))
        print('Promedio Solicitudes NO atendidas: {} ({:.2f}%)'.format(str(promSolicitudesSinAtender), porcSinAtender ))        

        if cantEjecuciones > 1:
            print('Ejecuciones:' + str(cantEjecuciones))
            diferencia = listaPorcAtendidas[cantEjecuciones -1] - listaPorcAtendidas[cantEjecuciones -2]
            print('Diferencia: {:.2f}%'.format(diferencia))

            self.formulario.lineEditDiferencia.setText('{:.2f}%'.format(diferencia))            
            if diferencia > 0:                
                self.formulario.lineEditDiferencia.setStyleSheet('QLineEdit { background-color: #7CFC00}')
            else:
                self.formulario.lineEditDiferencia.setStyleSheet('QLineEdit { background-color: #B22222}')


        self.grabarLog(cantEjecuciones,var,promSolicitudesAtendidas, promSolicitudesSinAtender,totalSolicitudes,diferencia)
        self.armarGrafico(cantEjecuciones,porcAtendidas,porcSinAtender)


        
    def armarGrafico(self,nroEjecucion, porcAtendidas, porcSinAtender):

        labels = ['Prom. Solicitudes atendidas', 'Prom. Solicitudes NO atendidas']
        porcAtendidasI=int(porcAtendidas)
        porcSinAtenderI = int(porcSinAtender)
        sizes = [porcAtendidasI, porcSinAtenderI]        
        colors = ['yellowgreen', 'lightcoral']
        explode = (0.1, 0)
        plt.figure()
        plt.pie(sizes, explode=explode, colors=colors, autopct='%.2f%%', shadow=True, startangle=90)
        plt.legend(labels, loc="best")
        plt.axis('equal')
        plt.tight_layout()
        plt.gcf().canvas.set_window_title('Ejecucion nro {0}'.format(nroEjecucion))        
        plt.show()

    def armarGraficoPuntos(self):
        plt.figure()
        plt.ylabel('Porcentaje Solicitudes Atendidas')
        plt.xlabel('Ejecucion Nro')
        plt.gcf().canvas.set_window_title('Solicitudes atendidas en cada ejecucion')        

        cantEjec= len(listaPorcAtendidas) + 1
        indiceEjec = np.arange(1,cantEjec) 

        plt.axis([0, cantEjec + 2, 0, 100])
        plt.plot(indiceEjec, listaPorcAtendidas,'ro')        
        plt.show()



    def armarGraficoBarras(self):

        labels = np.arange(1, len(listaPorcAtendidas) + 1) 
        index = np.arange(len(listaPorcAtendidas))        
        bar_width = 0.35
        opacity = 0.4
        error_config = {'ecolor': '0.3'}
        fig, ax = plt.subplots()

        rects= ax.bar(index, listaPorcAtendidas, bar_width,
                alpha=opacity, color='b',
                yerr=index, error_kw=error_config,
                label='Solicitudes atendidas')
        
        ax.set_xlabel('Ejecuciones')
        ax.set_ylabel('Porcentaje')
        ax.set_title('Solicitudes atendidas en cada ejecucion')
        ax.set_xticks(index)
        ax.set_xticklabels(labels)                
        ax.legend()

        i=0 
        for x in listaPorcAtendidas:
            ax.text(i - 0.15, x - 5, '{:.2f}%'.format(x), fontsize=10)
            i +=1

        fig.tight_layout()
        plt.show()


    def generarPedidos(self,pedidos,var):
        cantPedidosM4 = np.random.poisson(var.cantidadM4)
        cantPedidosM6 = np.random.poisson(var.cantidadM6)

        #Armo una lista con elemntos M4 y M6
        for _ in range(cantPedidosM4):
            pedidos.append('M4')
        for _ in range(cantPedidosM6):    
            pedidos.append('M6')

        #Desordeno lista para no atender siempre las M4 primero
        np.random.shuffle(pedidos)    
 
    def procesarPedido(self,dia,item,var,noAtendidos):
        tiempoEspera = 0
        if (item == 'M4'):                
            if (var.stockM4 > 0):
                var.stockM4 -= 1
                #Esperar tiempo de Operador. se resta al tiempo disponible                    
                tiempoEspera = np.random.exponential(scale=var.velOperM4)         
                var.mesasConstruidasM4[dia] += 1 
                var.solicitudesAtendidas += 1
            else:
                noAtendidos.append(item)    

        if (item == 'M6'):                
            if (var.stockM6 > 0):
                var.stockM6 -= 1
                #Esperar tiempo de Operador. se resta al tiempo disponible                    
                tiempoEspera = np.random.exponential(scale=var.velOperM6)                                
                var.mesasConstruidasM6[dia] += 1 
                var.solicitudesAtendidas += 1
            else:
                noAtendidos.append(item)  

        var.minutosRestantes -= tiempoEspera

    
    def obtenerParametros(self):
        variable = Variable()
        variable.MES = int(self.formulario.lineEditExp.text())
        variable.DIAS = int(self.formulario.lineEditDias.text())
        variable.incrementoStockM4 = int(self.formulario.lineEditIncrementoM4.text())
        variable.incrementoStockM6 = int(self.formulario.lineEditIncrementoM6.text())
        variable.velOperM4 = int(self.formulario.lineEditVelOperM4.text())
        variable.velOperM6 = int(self.formulario.lineEditVelOperM6.text())
        variable.cantDiasProduccion = int(self.formulario.lineEditDiasProd.text())
        variable.cantidadM4 = int(self.formulario.lineEditCantidadM4.text())
        variable.cantidadM6 = int(self.formulario.lineEditCantidadM6.text())

        return variable

        
    def procesar(self):
        pedidos = []                    
        noAtendidos = []                

        var = self.obtenerParametros()  

        for mes in range(var.MES):            
            var.solicitudesAtendidas=0            

            for dia in range(var.DIAS):
                noAtendidos = []                
                var.minutosRestantes = var.minutosXdia
                var.mesasConstruidasM4.append(0)
                var.mesasConstruidasM6.append(0)

                #Incremento el stock los promeros N dia de cada mes
                if (dia < var.cantDiasProduccion):
                    var.stockM4 += var.incrementoStockM4
                    var.stockM6 += var.incrementoStockM6

                self.generarPedidos(pedidos,var)

                #Recorro la lista de solicitudes
                for item in pedidos:   
                    if (var.minutosRestantes > 0):
                        self.procesarPedido(dia,item,var,noAtendidos)
                    else:
                        noAtendidos.append(item)    

                pedidos = noAtendidos
                
            var.solicitudesSinAtender= len(pedidos)
            var.solicitudesAtendidasXMes.append(var.solicitudesAtendidas)
            var.solicitudesSinAtenderXMes.append(var.solicitudesSinAtender)

        promedioSolicitudesAtendidas = int(np.mean(var.solicitudesAtendidasXMes))
        promedioSolicitudesSinAtender = int(np.mean(var.solicitudesSinAtenderXMes))
        totalSolicitudes = int(np.sum(var.solicitudesAtendidasXMes)) + int(np.sum(var.solicitudesSinAtenderXMes))

        return promedioSolicitudesAtendidas, promedioSolicitudesSinAtender, var, totalSolicitudes
Ejemplo n.º 35
0
class mywindow(QtWidgets.QMainWindow):
    update_window_signal = pyqtSignal()

    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #Threads
        self.threadclass = ThreadClass()
        self.threadclass.start()
        self.threadclass.sig1.connect(self.graphUpdate)
        #self.connect(self.threadclass, QtCore.SIGNAL("elVal"), self.graphUpdate)
        #Signals:::
        self.ui.pushButton_start.clicked.connect(
            self.Button_Start_Clicked
        )  # connecting the clicked signal with btnClicked slot
        self.ui.Button_In.clicked.connect(self.Button_In_Clicked)
        self.ui.Button_Out.clicked.connect(self.Button_Out_Clicked)
        self.ui.dial_FS.valueChanged.connect(self.dial_FS_moved)
        self.ui.lineEdit_FS.returnPressed.connect(self.lineEdit_FS_change)
        self.ui.Button_getParams.clicked.connect(self.Button_getParams_Clicked)
        self.ui.Button_cmd.clicked.connect(self.Button_cmd_Clicked)
        self.ui.lineEdit_gCommand.returnPressed.connect(
            self.Button_cmd_Clicked)
        self.ui.Button_ParamSend.clicked.connect(self.Button_ParamSend_Clicked)
        self.ui.spinBox_maxTravel.valueChanged.connect(
            self.spinBox_maxTravel_clicked)
        self.ui.spinBox_position.valueChanged.connect(
            self.spinBox_position_clicked)
        self.ui.hSlider.valueChanged.connect(self.hSlider_clicked)
        self.ui.pushButton_go.clicked.connect(self.pushButton_go_clicked)
        self.ui.Button_holdRes.clicked.connect(self.Button_holdRes_Clicked)
        self.ui.Button_home.clicked.connect(self.Button_home_Clicked)

        self.ui.spinBox_maxFS.valueChanged.connect(self.settingChanges)

        self.update_window_signal.connect(self.update_window_routine)
        #self.ui.tableView_Params.itemChanged.connect(self.tableSignal)
        ### Default values
        self.ui.comboBox_temp_ports.setEnabled(False)
        self.ui.comboBox_stepper_ports.setEnabled(False)
        self.ui.Button_cmd.setEnabled(False)
        self.ui.Button_getParams.setEnabled(False)
        self.ui.Button_ParamSend.setEnabled(False)
        self.ui.dial_FS.setValue(200)
        self.ui.lineEdit_FS.setText(str(self.ui.dial_FS.value()))
        self.ui.hSlider.setMaximum(self.ui.spinBox_maxTravel.value() / 10)
        self.ui.spinBox_position.setMaximum(self.ui.spinBox_maxTravel.value())

        #private variables
        self.temp_counter = 0
        self.temp_old = temp_0
        self.block_soak = 0
        self.block_peak = 0

    def graphUpdate(self, val):
        #print("Output temp is ", val)
        mins = self.temp_counter / 60

        self.ui.graphicsView.plot([mins, (self.temp_counter + 1) / 60],
                                  [self.temp_old, val],
                                  pen='w')
        self.temp_old = val

        if val >= 130:
            if self.block_soak == 0:
                self.block_soak = 1
                #self.ui.graphicsView.plot([mins,mins+.5],[140,140], pen='r')
                #self.ui.graphicsView.plot([mins,mins+.5],[150,150], pen='r')
                self.ui.graphicsView.plot([mins + .5, mins + 1.5], [140, 140],
                                          pen='g')
                self.ui.graphicsView.plot([mins + .5, mins + 1.5], [150, 150],
                                          pen='g')
                self.ui.graphicsView.plot([mins + 1.5, mins + 2], [140, 140],
                                          pen='y')
                self.ui.graphicsView.plot([mins + 1.5, mins + 2], [150, 150],
                                          pen='y')

                self.ui.graphicsView.plot([mins, mins + .5], [130, 130],
                                          pen='r')
                self.ui.graphicsView.plot([mins, mins + .5], [170, 170],
                                          pen='r')
                self.ui.graphicsView.plot([mins + .5, mins + 1.5], [130, 130],
                                          pen='y')
                self.ui.graphicsView.plot([mins + .5, mins + 1.5], [170, 170],
                                          pen='y')
                self.ui.graphicsView.plot([mins + 1.5, mins + 2], [130, 130],
                                          pen='y')
                self.ui.graphicsView.plot([mins + 1.5, mins + 2], [170, 170],
                                          pen='y')
        if val >= 183:
            if self.block_peak == 0:
                self.block_peak = 1
                self.ui.graphicsView.plot([mins + .75, mins + .75], [183, 230],
                                          pen='g')
                self.ui.graphicsView.plot([mins + 1, mins + 1], [183, 230],
                                          pen='g')
                self.ui.graphicsView.plot([mins + .5, mins + .5], [183, 230],
                                          pen='y')
                self.ui.graphicsView.plot(
                    [mins + (100 / 60), mins + (100 / 60)], [183, 230],
                    pen='y')

        self.temp_counter += 1
        self.update_window_routine()

    def update_window_call(self):
        self.update_window_signal.emit()

    def update_window_routine(self):
        self.repaint()
        QApplication.processEvents()

    def settingChanges(self):
        ### maxFS ###
        newValue = self.ui.spinBox_maxFS.value()
        set_Setting("maxFS", newValue)
        self.ui.dial_FS.setValue(newValue)

    def pushButton_go_clicked(self):
        global pushButton_go_pushed
        pushButton_go_pushed = 1

    def hSlider_clicked(self):
        self.ui.spinBox_position.setValue(self.ui.hSlider.value() * 10)

    def spinBox_position_clicked(self):
        self.ui.hSlider.setValue(self.ui.spinBox_position.value() / 10)

    def spinBox_maxTravel_clicked(self):
        self.ui.hSlider.setMaximum(self.ui.spinBox_maxTravel.value() / 10)

    def Button_ParamSend_Clicked(self):
        global Button_ParamSend_pressed
        Button_ParamSend_pressed = 1

    def Button_cmd_Clicked(self):
        global sendCmd_pressed
        sendCmd_pressed = 1

    def Button_getParams_Clicked(self):
        global getParams_pressed
        getParams_pressed = 1
        self.ui.textEdit_Params.clear()
        #print("Get Params clicked")

    """def position(self, posvalue):
        count = 0
        while count < posvalue:
            count += 5
            #self.ui.progressBar.setValue(posvalue)
            time.sleep(1)"""

    #QApplication.processEvents()
    def dial_FS_moved(self):
        self.ui.lineEdit_FS.setText(str(self.ui.dial_FS.value()))

    def lineEdit_FS_change(self):
        self.ui.dial_FS.setValue(int(self.ui.lineEdit_FS.text()))
        self.ui.lineEdit_FS.selectAll()

    def Button_Start_Clicked(self):
        global Button_Start_pressed
        Button_Start_pressed = 1

    def Button_In_Clicked(self):
        global Button_In_pressed
        Button_In_pressed = 1  #dummy command.
        #print("Button pressed")

    def Button_Out_Clicked(self):
        #print("Button pressed")
        global Button_Out_pressed
        Button_Out_pressed = 1

    def Button_holdRes_Clicked(self):
        global Button_holdRes_Pressed
        if self.ui.Button_holdRes.isChecked():
            Button_holdRes_Pressed = 1
            print("hold Button pressed")
        else:
            Button_holdRes_Pressed = 0
            print("hold Button released")

    def Button_home_Clicked(self):
        global command_transfer
        command_transfer = "$H\n"
        print("Homing")

    def closeEvent(self, event):
        global close_everything
        close_everything = 1
        event.accept()  # let the window close
Ejemplo n.º 36
0
Archivo: main.py Proyecto: aisyluG/tpr1
class Window(QtWidgets.QMainWindow):
    report = ''
    optimum = []
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.yield_model = TableModel()
        self.ui.yield_table.setModel(self.yield_model)
        self.ui.yield_table.resizeColumnsToContents()

        self.probability_model = TableModel(1)
        self.ui.probabilitys_table.setModel(self.probability_model)
        self.ui.probabilitys_table.resizeColumnsToContents()
        # palette = self.ui.probabilitys_table.horizontalHeader().palette()
        # palette.setColor(QtGui.QPalette.Normal, QtGui.QPalette.Window, QtCore.Qt.red)
        # self.ui.probabilitys_table.setStyleSheet('QHeaderView {background-color: yellow;}')

        self.ui.changeNumbers_bt.clicked.connect(self.changeMatricesSize)
        self.ui.calcBt.clicked.connect(self.calculateOptimum)

        #
        saveAction = QtWidgets.QAction('Сохранить', self)
        saveAction.setShortcut('Ctrl+S')
        saveAction.triggered.connect(self.save)
        self.ui.menubar.addAction(saveAction)

    def changeMatricesSize(self):
        states = int(self.ui.states_spinB.text())
        strategys = int(self.ui.strategys_spinB.text())
        stages = int(self.ui.stages_spinB.text())
        self.yield_model.resize(strategys, states)
        self.probability_model.resize(strategys, states)
        self.ui.yield_table.resizeColumnsToContents()
        self.ui.probabilitys_table.resizeColumnsToContents()

    def calculateOptimum(self):
        if self.probability_model.get_size() == (int(self.ui.strategys_spinB.text()), int(self.ui.states_spinB.text())):
            res, self.optimum = algorithm(states=int(self.ui.states_spinB.text()), strategys=int(self.ui.strategys_spinB.text()),
                      n=int(self.ui.stages_spinB.text()), probabilitys=self.probability_model.get_data(),
                      yields=self.yield_model.get_data())
            self.ui.textEdit.setHtml(str(res))
            self.report = res
            # self.ui.widget.draw(QtGui.QPainter(), self.optimum
            self.ui.tabWidget.clear()
            palette = QtGui.QPalette()
            brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
            brush.setStyle(QtCore.Qt.SolidPattern)
            palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
            brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
            brush.setStyle(QtCore.Qt.SolidPattern)
            palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
            brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
            brush.setStyle(QtCore.Qt.SolidPattern)
            palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
            brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
            brush.setStyle(QtCore.Qt.SolidPattern)
            palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
            brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
            brush.setStyle(QtCore.Qt.SolidPattern)
            palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
            brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
            brush.setStyle(QtCore.Qt.SolidPattern)
            palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
            for i in range(int(self.ui.stages_spinB.text())):
                try:
                    tab = QtWidgets.QWidget()
                    tab.setObjectName(f"tab{i}")
                    widget = drawWidget(tab)
                    widget.setGeometry(QtCore.QRect(0, 0, 401, 391))
                    widget.setAutoFillBackground(True)
                    widget.setObjectName(f"widget{i}")
                    widget.setPalette(palette)
                    self.ui.tabWidget.addTab(tab, f"Этап {i + 1}")
                    widget.paint(self.optimum[i], self.probability_model.get_data())
                    widget.repaint()
                except Exception:
                    print(Exception.mro())
        else:
            self.ui.statusbar.showMessage('Проверте правильность введенных данных.')

    def save(self):
        try:
            filename, _ = QtWidgets.QFileDialog.getSaveFileName(self, 'Сохранить', '/report.html',
                                                                'Результаты алгоритма (*.html)')
            if _ == 'Результаты алгоритма (*.html)':
                with open(filename, 'w') as file:
                    file.write(f'Время {datetime.now()}<br>')
                    file.write('<h3>Исходные данные:</h3>')
                    file.write('<p style="margin-left: 50px;"><b>Матрицы переходных вероятностей:</b></p>')
                    file.write(self.probability_model.get_table_to_save())
                    file.write('<p style="margin-left: 50px;"><b>Матрицы доходностей:</b></p>')
                    file.write(self.yield_model.get_table_to_save())
                    file.write(self.report)
        except Exception:
            print('Error!')
Ejemplo n.º 37
0
class QDCWindow(QtGui.QMainWindow):

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

		# UI created by QT Designer 
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)

		# default value = 5 m
		self.launchAlt = 5 

		#Set up option parsing to get connection string
		import argparse  
		parser = argparse.ArgumentParser(description='Tracks GPS position of your computer (Linux only). Connects to SITL on local PC by default.')
		parser.add_argument('--connect', help="vehicle connection target.")
		args = parser.parse_args()

		self.connection_string = args.connect
		self.sitl = None

		#Start SITL if no connection string specified
		if not self.connection_string:
			import dronekit_sitl
			self.sitl = dronekit_sitl.start_default()
			self.connection_string = self.sitl.connection_string()

		# Connect to the Vehicle
		print 'Connecting to vehicle on: %s' % self.connection_string
		self.vehicle = connect(self.connection_string, wait_ready=True)

		# Display Flight Mode
		self.updateFlightModeGUI(self.vehicle.mode)
		self.addObserverAndInit(
			'mode'
			,lambda vehicle,name,mode: self.updateFlightModeGUI(mode) ) 

		# Display Location Info
		self.updateLocationGUI(self.vehicle.location)
		self.addObserverAndInit(
			'location'
			,lambda vehicle, name, location: self.updateLocationGUI(location) )


	def send_ned_velocity(self, velocity_x, velocity_y, velocity_z, duration):
		msg = self.vehicle.message_factory.set_position_target_local_ned_encode(
			0,       # time_boot_ms (not used)
			0, 0,    # target system, target component
			mavutil.mavlink.MAV_FRAME_LOCAL_NED, # frame
			0b0000111111000111, # type_mask (only speeds enabled)
			0, 0, 0, # x, y, z positions (not used)
			velocity_x, velocity_y, velocity_z, # x, y, z velocity in m/s
			0, 0, 0, # x, y, z acceleration (not supported yet, ignored in GCS_Mavlink)
			0, 0)    # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink) 

		#send command to vehicle on 1 Hz cycle
		for x in range(0,duration):
			self.vehicle.send_mavlink(msg)
			time.sleep(1)

	# set yaw from 0 to 359 / 0-north, 90-east, 180-south, 270-west
	def condition_yaw(heading, relative=False):
		if relative:
			is_relative = 1 #yaw relative to direction of travel
		else:
			is_relative = 0 #yaw is an absolute angle
		# create the CONDITION_YAW command using command_long_encode()
		msg = vehicle.message_factory.command_long_encode(
			0, 0,    # target system, target component
			mavutil.mavlink.MAV_CMD_CONDITION_YAW, #command
			0, #confirmation
			heading,    # param 1, yaw in degrees
			0,          # param 2, yaw speed deg/s
			1,          # param 3, direction -1 ccw, 1 cw
			is_relative, # param 4, relative offset 1, absolute angle 0
			0, 0, 0)    # param 5 ~ 7 not used
		# send command to vehicle
		vehicle.send_mavlink(msg)
 	
	def updateLocationGUI(self, location):
		self.ui.lblLongValue.setText(str(location.global_frame.lon))
		self.ui.lblLatValue.setText(str(location.global_frame.lat))
		self.ui.lblAltValue.setText(str(location.global_relative_frame.alt))
	
	def updateFlightModeGUI(self, value):
		index,mode = str(value).split(':')
		self.ui.lblFlightModeValue.setText(mode)
		
	def addObserverAndInit(self, name, cb):
		"""We go ahead and call our observer once at startup to get an initial value"""
		self.vehicle.add_attribute_listener(name, cb)


	def vehicle_validation(self, function):
		if self.vehicle.mode == "GUIDED":
			function()

	def west_click(self):
		@self.vehicle_validation
		def wrapped():
			self.send_ned_velocity(0,-1,0,1)
			self.send_ned_velocity(0,0,0,1)

	def east_click(self):
		@self.vehicle_validation
		def wrapped():
			self.send_ned_velocity(0,1,0,1)
			self.send_ned_velocity(0,0,0,1)

	def north_click(self):
		@self.vehicle_validation
		def wrapped():
			self.send_ned_velocity(1,0,0,1)
			self.send_ned_velocity(0,0,0,1)

	def south_click(self):
		@self.vehicle_validation
		def wrapped():
			self.send_ned_velocity(-1,0,0,1)
   			self.send_ned_velocity(0,0,0,1)

	def rtl_click(self):
		@self.vehicle_validation
		def wrapped():
			self.vehicle.mode = VehicleMode("RTL")

	def up_click(self):
		@self.vehicle_validation
		def wrapped():
			alt = self.vehicle.location.global_relative_frame.alt
			if  alt < 20:
				self.send_ned_velocity(0,0,-0.5,1)
	 	  		self.send_ned_velocity(0,0,0,1)

	def down_click(self):
		@self.vehicle_validation
		def wrapped():
			alt = self.vehicle.location.global_relative_frame.alt
			if alt > 3:
				self.send_ned_velocity(0,0,0.5,1)
	 	  		self.send_ned_velocity(0,0,0,1)

	def launch_click(self):
		"""
		Arms vehicle and fly to self.alt
		"""
		print "Basic pre-arm checks"
		# Don't let the user try to arm until autopilot is ready
		while not self.vehicle.is_armable:
			print " Waiting for vehicle to initialise..."
			time.sleep(1)

		print "Arming motors"
		# Copter should arm in GUIDED mode
		self.vehicle.mode = VehicleMode("GUIDED")
		self.vehicle.armed = True

		while not self.vehicle.armed:      
			print " Waiting for arming..."
			time.sleep(1)

		print "Taking off!"
		self.vehicle.simple_takeoff(self.launchAlt) # Take off to target altitude

		# Wait until the vehicle reaches a safe height before processing the goto (otherwise the command 
		#  after Vehicle.simple_takeoff will execute immediately).
		while True:
			print " Altitude: ", self.vehicle.location.global_relative_frame.alt      
			if self.vehicle.location.global_relative_frame.alt>=self.launchAlt*0.95: #Trigger just below target alt.
				print "Reached target altitude"
				break
			time.sleep(1)
Ejemplo n.º 38
0
class Window(QMainWindow):
    semaphore_start_reading = QSemaphore()
    input_sended = pyqtSignal()

    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.sem_for_timer = QSemaphore()

        self.reader_Thread = QThread()
        self.reader = ConsoleReader(self.sem_for_timer,
                                    self.semaphore_start_reading)
        self.reader.moveToThread(self.reader_Thread)

        # self.timerThread = QThread()
        # self.timer = Timer(self.sem_for_timer, self.reader_Thread)
        # self.timer.moveToThread(self.timerThread)

        self.writer_Thread = QThread()
        self.writer = ConsoleWriter(self.semaphore_start_reading)
        self.writer.moveToThread(self.writer_Thread)

        self.thr_read = Thread(target=self.ff)
        self.thr_write = Thread(target=self.ww)
        # self.thr_timer = Thread(target=self.gg)

        self.ui.startBt.clicked.connect(self.startProcess)
        # self.writer.process_created.connect(self.pp)
        # self.writer.process_created.connect(self.reader.set_pipe)
        self.ui.sendBt.clicked.connect(self.addInput)
        self.writer.value_entered.connect(self.semaphore_start_reading.release)
        self.reader.readed.connect(self.addToConsole)
        # self.timer.timeout.connect(self.newThread)

        self.writer_Thread.start()
        # self.timerThread.start()
        self.reader_Thread.start()

    # def newThread(self):
    #     self.reader_Thread = QThread()
    #     self.reader = ConsoleReader(self.sem_for_timer, self.semaphore_start_reading)
    #     self.reader.moveToThread(self.reader_Thread)
    #
    #     self.reader.set_pipe(self.writer.proc)
    #     self.reader.readed.connect(self.addToConsole)
    #     self.timer.set_readerThread(self.reader_Thread)
    #
    #     self.reader_Thread.start()
    #     print('new thread')
    #     self.semaphore_start_reading.release()
    #     self.thr_read.run()
    #     self.thr_timer.run()

    def addToConsole(self, output):
        self.ui.outputText.append(output)

    def startProcess(self):
        path = self.ui.comandLine.text()
        self.path = path.replace('\\', '/')
        # print(path)
        # self.writer.createProcess(path)
        self.thr_write.start()
        self.thr_read.start()
        # self.thr_timer.start()

    def addInput(self):
        print('x')
        input = self.ui.inputText.text()
        print('y')
        self.ui.outputText.append('>' + input)
        self.writer.write(input)

    def ff(self):
        # self.sem = QSemaphore()
        # self.timerThread = QThread()
        # self.timer = Timer(self.sem)
        # self.timer.moveToThread(self.timerThread)
        # # self.timer.timeout.connect(self.ii)

        # self.timerThread.start()

        # reader_Thread = QThread()
        # self.reader = ConsoleReader(self.semaphore)
        # self.reader.moveToThread(reader_Thread)
        #
        # self.reader.readed.connect(self.addToConsole)

        # reader_Thread.start()

        # self.semaphore.acquire()
        # self.reader.set_pipe(self.writer.proc)
        # self.timer.start()
        print('start read')
        self.reader.run()

    def ww(self):
        print('start process')
        print(self.path)
        self.writer.createProcess(self.path)
        self.reader.set_pipe(self.writer.proc)
Ejemplo n.º 39
0
class Readdialog(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        global dir2, dir3, dir1
        dir1 = "/home/slotlocker/random/"
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.listWidget.setMaximumWidth(80)
        self.ui.listWidget.setMaximumHeight(200)
        self.ui.listWidget.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
        self.setWindowTitle("Browse/Edit Diary")
        
        dir_list = os.listdir(dir1)
        self.ui.listWidget.addItems(dir_list)
        self.ui.listWidget.clicked.connect(self.step2)
    def step2(self):
        selected_item = self.ui.listWidget.selectedItems()
        dir_selected = selected_item[0].text()
        global dir2
        dir2 = dir1 + dir_selected + "/"
        global column2
        column2 = QtGui.QListWidget()
        column2.setAlternatingRowColors(True)
        column2.setMaximumWidth(80)
        column2.setMaximumHeight(200)
        column2.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
        self.ui.gridLayout.addWidget(column2,0,1)
        dir_list = os.listdir(dir2)
        column2.addItems(dir_list)
        column2.clicked.connect(self.step3)
    def step3(self):
        selected_item = column2.selectedItems()
        dir_selected = selected_item[0].text()
        global dir3
        dir3 = dir2 + dir_selected + "/"
        global column3
        column3 = QtGui.QListWidget()
        column3.setAlternatingRowColors(True)
        column3.setMaximumWidth(80)
        column3.setMaximumHeight(200)
        column3.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
        self.ui.gridLayout.addWidget(column3,0,2)
        dir_list = os.listdir(dir3)
        column3.addItems(dir_list)
        column3.clicked.connect(self.step4)
    def step4(self):
        global textarea1, textarea2
        textarea1 = QtGui.QTextEdit()
        textarea2 = QtGui.QTextEdit()
        self.ui.gridLayout.addWidget(textarea1,0,3)
        textarea1.setMinimumWidth(300)
        textarea1.setMinimumHeight(200)
        textarea1.setMaximumHeight(200)
        self.ui.gridLayout.setColumnStretch(3,100)
        self.ui.gridLayout.addWidget(textarea2,1,0,1,4)
        textarea2.setMinimumHeight(320)
        selected_item = column3.selectedItems()
        global file_selected
        file_selected = selected_item[0].text()
        file_path = dir3 + file_selected + "/diary.html"
        file_pointer = open(file_path, 'r')
        file_contents = file_pointer.read()
        textarea2.setText(file_contents)
        file_pointer.close()
        textarea2.setAcceptRichText(True)
        textarea2.setReadOnly(True)
        global title_file
        title_file = dir3 + file_selected + "/title.txt"
        file_pointer = open(title_file, "r")
        title = file_pointer.read()
        file_pointer.close()

        textarea1.setText(title)
        

        
        global button1
        button1 = QtGui.QPushButton("Edit")
        self.ui.gridLayout.addWidget(button1, 2,2)
        button1.setSizePolicy(QtGui.QSizePolicy.Fixed,QtGui.QSizePolicy.Fixed)
        global button2
        button2 = QtGui.QPushButton("Save")
        self.ui.gridLayout.addWidget(button2, 2,3)
        button2.setSizePolicy(QtGui.QSizePolicy.Fixed,QtGui.QSizePolicy.Fixed)
        button2.setEnabled(False)
        button1.pressed.connect(self.edit)

    def edit(self):
            button1.setEnabled(False)
            textarea2.setReadOnly(False)
            textarea2.setAcceptRichText(True)
            button2.setEnabled(True)

            button2.pressed.connect(self.save_exit)

    def save_exit(self):
        file_path = dir3+ file_selected + "/" + "diary.html"
        file_pointer = open(file_path,"w")
        file_contents = textarea2.toHtml()
        file_pointer.write(file_contents)
        file_pointer.close()
        button1.setEnabled(True)
        button2.setEnabled(False)
Ejemplo n.º 40
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        # 初始化界面
        self.ui.setupUi(self)
        self.__actionBlinding__()
        self.udpIp = '192.168.1.3'
        self.udpPort = '5000'

    def __actionBlinding__(self):
        self.ui.openFile.clicked.connect(self.fileOpenAck)
        self.ui.actionUDP.triggered.connect(self.udpManuCreate)

    def fileOpenAck(self):
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setViewMode(QFileDialog.Detail)
        if dialog.exec_():  # 选择完毕
            fileNames = dialog.selectedFiles()
            self.ui.fileDir.setText(fileNames[0])
            try:
                filedHead = open(
                    fileNames[0],
                    'rb',
                )
            except:
                self.tipErrorFileOpen()
                return
            self.fileMesgSize = os.path.getsize(fileNames[0])
            print(self.fileMesgSize)
            self.fileMesg = filedHead.read()
            filedHead.close()
            self.udpSendFile()

    def udpManuCreate(self):
        dialog = QDialog()
        dialog.setWindowTitle('UDP CONFIG')
        dialog.setWindowModality(Qt.ApplicationModal)
        dialog.setWindowIcon(QIcon('./ico/1.png'))
        vtLayout = QVBoxLayout()
        layout1 = QGridLayout()
        groupBox1 = QGroupBox('Socket状态')
        groupBox3 = QGroupBox('数据发送窗口(文本模式)')

        groupBox1.setFont('黑体')
        groupBox3.setFont('黑体')
        label1 = QLabel('UDP IP')
        label2 = QLabel('UDP 端口号')
        textEditIP = QLineEdit()
        textEditIP.setPlaceholderText('输入UDP IP')
        textEditIP.setText(self.udpIp)
        textEditPort = QLineEdit()
        textEditPort.setPlaceholderText('输入UDP 端口号')
        textEditPort.setText(self.udpPort)
        layout1.addWidget(label1, 0, 0, 1, 1)
        layout1.addWidget(textEditIP, 0, 1, 1, 2)
        layout1.addWidget(label2, 0, 4, 1, 1)
        layout1.addWidget(textEditPort, 0, 5, 1, 2)
        groupBox1.setLayout(layout1)

        self.ui.textEditTx = QTextEdit()
        self.ui.pushButtonSocketSend = QPushButton('发送数据')
        self.ui.pushButtonSocketCrcSend = QPushButton('发送清空')
        self.ui.pushButtonSocketCrcRX = QPushButton('统计清空')
        self.ui.pushButtonSocketSend.setFont('楷体')
        self.ui.pushButtonSocketCrcSend.setFont('楷体')
        self.ui.pushButtonSocketCrcRX.setFont('楷体')
        layout2 = QGridLayout()
        layout2.addWidget(self.ui.textEditTx, 0, 0, 5, 6)
        layout2.addWidget(self.ui.pushButtonSocketSend, 0, 7, 1, 1)
        layout2.addWidget(self.ui.pushButtonSocketCrcSend, 2, 7, 1, 1)
        layout2.addWidget(self.ui.pushButtonSocketCrcRX, 4, 7, 1, 1)
        groupBox3.setLayout(layout2)

        vtLayout.addWidget(groupBox1)
        vtLayout.addWidget(groupBox3)

        vtLayout.setStretch(0, 1)
        vtLayout.setStretch(1, 3)
        dialog.setLayout(vtLayout)
        textEditIP.editingFinished.connect(
            lambda: self.setUdpIp(textEditIP.text()))
        textEditPort.editingFinished.connect(
            lambda: self.setUdpPort(textEditPort.text()))
        if dialog.exec_():
            pass

    def setUdpIp(self, string):
        self.udpIp = string

    def setUdpPort(self, string):
        self.udpPort = string

    def udpSendFile(self):
        ip_port = ('192.168.1.2', 6000)
        udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        udp_socket.bind(ip_port)
        try:
            times = int(self.fileMesgSize / 1024)
            res = self.fileMesgSize % 1024
            head = b'B10000000001'
            if (times != 0):
                for i in range(0, times):
                    vp_addr = bytes(str(hex(int('5000', 16) + 512 * i)).rjust(
                        4, '0'),
                                    encoding='utf-8')
                    vp_len = b'0400'
                    sand = head + vp_addr[2:] + vp_len + \
                        self.fileMesg[i*1024:(i+1)*1024]
                    udp_socket.sendto(sand, (self.udpIp, int(self.udpPort)))
                    time.sleep(0.005)
            if (res != 0):
                vp_addr = bytes(str(hex(int('5000', 16) + 512 * times)).rjust(
                    4, '0'),
                                encoding='utf-8')
                vp_len = bytes((str(hex(res))[2:]).rjust(4, '0'),
                               encoding='utf-8')
                sand = head + vp_addr[2:] + vp_len + \
                    self.fileMesg[times * 1024: times * 1024 + res]
                udp_socket.sendto(sand, (self.udpIp, int(self.udpPort)))
        except:
            self.tipErrorSocketSend()
        udp_socket.close()

    def tipErrorFileOpen(self):
        dialog = QDialog()
        dialog.setFixedSize(120, 40)
        text = QLabel('文件打开失败')
        text.setFont('黑体')
        layout = QVBoxLayout()
        layout.addWidget(text)
        dialog.setLayout(layout)
        if dialog.exec_():
            pass

    def tipErrorSocketSend(self):
        dialog = QDialog()
        dialog.setFixedSize(120, 40)
        text = QLabel('UDP连接失败')
        text.setFont('黑体')
        layout = QVBoxLayout()
        layout.addWidget(text)
        dialog.setLayout(layout)
        if dialog.exec_():
            pass
Ejemplo n.º 41
0
Archivo: main.py Proyecto: miodeq/swd
class Main(QtGui.QMainWindow):
	def DEBUG(self):
		self.recast_data()
		#self.print_data()
		#self.refresh_data()
		#self.edit_types()
	def remove_row(self,i):
		self.zb.usun_obserwacja(i)
		self.populate_from_set()
	def remove_col(self,i):
		self.zb.usun_zmienna(int(i))
		self.populate_from_set()
	
	def print_data(self):
		cols = self.ui.treeWidget.columnCount()
		rows = self.ui.treeWidget.topLevelItemCount()
		zb = Zbior()
		root = self.ui.treeWidget.invisibleRootItem()
		child_count = root.childCount()
		lista = []
		for i in range(child_count):
				item = root.child(i)
				lista.append([u'%s'%(item.text(i)) for i in range(cols)])
		for i in lista:
				print i
		#for i in range(cols):
				#print self.ui.treeWidget.
		#print cols,rows

	def recast_data(self):
		for i in range(len(self.zb.typy)):
				self.zb.rzutuj(self.zb.typy[i],i)
		

	def get_translated(self,string):
		return QtGui.QApplication.translate("MainWindow", string, None, QtGui.QApplication.UnicodeUTF8)
	def populate_from_set(self):
		zb = self.zb
		if(not zb):
				print "Zbior not set"
		self.clear_tree()
		for i in zb.kolumny:
				self.add_column(i)
		for i in zb.lista:
				self.add_row(i)
		text = ",".join([self.TypToS[str(x)] for x in zb.typy])
		self.ui.typesLineEdit.setText(text)
		col_num = len(zb.kolumny)
		text = self.get_translated('')
		for i in range(col_num-1):
			text+=self.get_translated(zb.kolumny[i]+',')
		text+=self.get_translated(str(zb.kolumny[col_num-1]))
		
		#text = self.get_translated(',').join([self.get_translated(str(x)) for x in zb.kolumny])
		#text = ",".join(zb.kolumny)
		self.ui.namesLineEdit.setText(text)

	def set_zbior(self,zb):
		self.zb = zb;

	def clear_tree(self):
		#self.ui.treeWidget = QtGui.QTreeWidget(self.ui.centralwidget)
		self.ui.treeWidget.clear()
		self.ui.treeWidget.setColumnCount(0)

	def edit_types(self):
		types = [self.SToTyp[str(x).strip()] for x in self.ui.typesLineEdit.text().split(',')]
		if(len(types) != len(self.zb.typy)):
				print "can't cast! different size of types"
		else:
				self.zb.typy = types
				for i in range(len(types)):
					self.zb.rzutuj(types[i],i)
				#for i in range(len(types)):
					#self.zb.rzutuj(types[i],i)
				self.populate_from_set()

	def edit_names(self):
		names = [unicode(x).strip() for x in self.ui.namesLineEdit.text().split(',')]
		if(len(names) != len(self.zb.kolumny)):
				print "can't cast! different size of types"
		else:
				self.zb.kolumny = names
				self.populate_from_set()


	#def add_row(self):
		#add_row(None)
		
	def add_row(self,row_data):
		item = QtGui.QTreeWidgetItem(self.ui.treeWidget)
		if(row_data):
				for i in xrange(len(row_data)):
					text = QtGui.QApplication.translate("MainWindow", str(row_data[i]), None, QtGui.QApplication.UnicodeUTF8)
					item.setText(i,text)
		item.setFlags(QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEditable|QtCore.Qt.ItemIsDragEnabled|QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsEnabled)

	def add_empty_column(self):
		text, ok = QtGui.QInputDialog.getText(self, 'Nowa kolumna', 'Podaj nazwe')
		if ok:
				self.add_column(str(text))
	def remove_column_dialog(self):
		text, ok = QtGui.QInputDialog.getText(self, 'Usun kolumne', 'Podaj numer kolumny')
		if ok:
				self.remove_col(int(text))
	def remove_row_dialog(self):
		text, ok = QtGui.QInputDialog.getText(self, 'Usun wiersz', 'Podaj numer wiersza')
		if ok:
				self.remove_row(int(text))
	def add_column(self,nazwa):
		idx = self.ui.treeWidget.columnCount()
		self.ui.treeWidget.headerItem().setText(idx, QtGui.QApplication.translate("MainWindow", nazwa, None, QtGui.QApplication.UnicodeUTF8))
	def save_data(self):
		fname = QtGui.QFileDialog.getSaveFileName(self,'Zapisz plik','.')
		if(not fname):
				return
		separ, ok = QtGui.QInputDialog.getText(self, 'Separator', 'Podaj separator (\\t dla tabulatora)')
		if not ok:
				return
		kol, ok = QtGui.QInputDialog.getText(self, 'Nazwy kolumn', 'Zapisac nazwy kolumn ? [T/N]')
		if not ok:
				return
		if(str(kol).upper()=="T"):
			  kol=True
		else:
			  kol=False
		typy, ok = QtGui.QInputDialog.getText(self, 'Nazwy typow', 'Zapisac nazwy typów ? [T/N]')
		if not ok:
				return
		if(separ=='\\t'):separ='\t'
		if(str(typy).upper()=="T"):
			  typy=True
		else:
			  typy=False
		self.zb.zapisz(fname,separ,kol,typy)
		#pass
	def load_data(self):
		zb = Zbior()
		fname = QtGui.QFileDialog.getOpenFileName(self,'Otworz plik','.')
		if(not fname):
				return
		sep, ok = QtGui.QInputDialog.getText(self, 'Separator', 'Podaj separator (\\t dla tabulatora)')
		if not ok:
				return
		ile, ok = QtGui.QInputDialog.getText(self, 'Pomijanie wierszy', 'Ile wierszy pominac ?')
		if not ok:
				return
		kolumny, ok = QtGui.QInputDialog.getText(self, 'Nazwy kolumn', 'Czu 0 wiersz to nazwy kolumn [T/N] ?')
		if not ok:
				return
		typy, ok = QtGui.QInputDialog.getText(self, 'Nazwy typow', 'Czu 1 wiersz to nazwy typu [T/N] ?')
		if not ok:
				return
		if(sep=='\\t'):sep='\t'
		if(str(kolumny).upper()=='T'):
				kolumny = True
		else:
				kolumny = False
				
		if(str(typy).upper()=='T'):
				typy = True
		else:
				typy = False

		zb.wczytaj(fname,sep,int(ile),kolumny,typy)
		self.zb = zb
		self.populate_from_set()
		if(typy==True):
				print "recasting"
				self.recast_data()
	def dyskretyzacjaPRD(self):
		kol, ok = QtGui.QInputDialog.getText(self, 'Kolumna', 'Podaj indeks kolumny:')
		if not ok:
				return
		n, ok = QtGui.QInputDialog.getText(self, 'N', 'Podaj N:')
		if not ok:
				return
		self.zb.dyskretyzuj(int(kol),int(n))
		self.populate_from_set()
	def dyskretyzacjaNK(self):
		kol, ok = QtGui.QInputDialog.getText(self, 'Kolumna', 'Podaj indeks kolumny:')
		if not ok:
				return
		n, ok = QtGui.QInputDialog.getText(self, 'N', 'Podaj N:')
		if not ok:
				return
		self.zb.dyskretyzuj2(int(kol),int(n))
		self.populate_from_set()
	def standaryzacja(self):
		kol, ok = QtGui.QInputDialog.getText(self, 'Kolumna', 'Podaj indeks kolumny:')
		if not ok:
				return
		self.zb.standaryzuj(int(kol))
		self.populate_from_set()
	def odstajace3x(self):
		kol, ok = QtGui.QInputDialog.getText(self, 'Kolumna', 'Podaj indeks kolumny:')
		if not ok:
				return
		self.zb.odchylenie_trzykrotne(int(kol))
		self.populate_from_set()
	def odstajaceProcent(self):
		mi, ok = QtGui.QInputDialog.getText(self, 'Minimum np 0.05', 'Podaj minimum:')
		if not ok:
				return
		mx, ok = QtGui.QInputDialog.getText(self, 'Maksimum np 0.95', 'Podaj maksimum:')
		if not ok:
				return
		kol, ok = QtGui.QInputDialog.getText(self, 'Kolumna', 'Podaj indeks kolumny:')
		if not ok:
				return
		self.zb.odstajace_procentowo(float(mi),float(mx),int(kol))
		self.populate_from_set()
	def normalizacja(self):
		mi, ok = QtGui.QInputDialog.getText(self, 'Minimum np 0.0', 'Podaj minimum:')
		if not ok:
				return
		mx, ok = QtGui.QInputDialog.getText(self, 'Maksimum np 50.0', 'Podaj maksimum:')
		if not ok:
				return
		kol, ok = QtGui.QInputDialog.getText(self, 'Kolumna', 'Podaj indeks kolumny:')
		if not ok:
				return
		self.zb.normalizuj(float(mi),float(mx),int(kol))
		self.populate_from_set()

	def make_col_list(self,col):
		return [self.zb.lista[i][col] for i in range(len(self.zb.lista))]

	def Wykres2D(self):
		import numpy_demo
		i, ok = QtGui.QInputDialog.getText(self, 'Wektor X', 'Podaj kolumne:')
		if not ok:
				return
		j, ok = QtGui.QInputDialog.getText(self, 'Wektor Y', 'Podaj kolumne:')
		if not ok:
				return
		color, ok = QtGui.QInputDialog.getText(self, 'Kolor', 'Podaj kolumne koloru:')
		if not ok:
				return
		i = int(i)
		j = int(j)
		color = int(color)
		l1 = self.make_col_list(i)
		l2 = self.make_col_list(j)
		l3 = self.make_col_list(color)
		numpy_demo.wykres(l1,l2,l3,self.zb.kolumny[i],self.zb.kolumny[j])
	def Wykres3D(self):
		import numpy_demo
		i, ok = QtGui.QInputDialog.getText(self, 'Wektor X', 'Podaj kolumne:')
		if not ok:
				return
		j, ok = QtGui.QInputDialog.getText(self, 'Wektor Y', 'Podaj kolumne:')
		if not ok:
				return
		k, ok = QtGui.QInputDialog.getText(self, 'Wektor Z', 'Podaj kolumne:')
		if not ok:
				return
		color, ok = QtGui.QInputDialog.getText(self, 'Kolor', 'Podaj kolumne koloru:')
		if not ok:
				return
		i = int(i)
		j = int(j)
		k = int(k)
		color = int(color)
		l1 = self.make_col_list(i)
		l2 = self.make_col_list(j)
		l3 = self.make_col_list(k)
		l4 = self.make_col_list(color)
		numpy_demo.wykres3D(l1,l2,l3,l4,[self.zb.kolumny[i],self.zb.kolumny[j],self.zb.kolumny[k]])
	def SprawdzKlasyfikacje(self, metryka):
		indeksy, ok = QtGui.QInputDialog.getText(self, 'Podaj wektory', 'Podaj kolumny oddzielone przecinkiem np. 4,6,7:')
		if not ok:
				return
		
		klasa, ok = QtGui.QInputDialog.getText(self, 'Klasa Decyzyjna', 'Podaj kolumne klasy decyzyjnej:')
		if not ok:
				return

		k, ok = QtGui.QInputDialog.getText(self, 'Sasiedzi', 'Podaj k:')
		if not ok:
				return
		indeksy = [int(i) for i in indeksy.split(',')]
		#metryka = self.zb.metrykaEuklidesowa
		ocena = self.zb.ocenaKlasyfikacji(int(k),metryka,int(klasa), indeksy)
		reply = QtGui.QMessageBox.question(self, 'Podsumowanie',
            "%d z %d Sklasyfikowanych poprawnie (%.2f %%)"%(ocena[0],ocena[1],float(ocena[0])*100./ocena[1]), 
            QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
	def PopupMessage(self,m1,m2):
		QtGui.QMessageBox.question(self, m1, m2, QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
		
	def SprawdzEuklidesowa(self):
		self.SprawdzKlasyfikacje(self.zb.metrykaEuklidesowa)
		
	def SprawdzMiejska(self):
		self.SprawdzKlasyfikacje(self.zb.metrykaMiejska)
		
	def SprawdzMahalanobisa(self):
		self.SprawdzKlasyfikacje(self.zb.metrykaMahalanobisa)

	def KlasyfikujEuklidesowa(self):
		self.SklasyfikujObiekt(self.zb.metrykaEuklidesowa)
		
	def KlasyfikujMiejska(self):
		self.SklasyfikujObiekt(self.zb.metrykaMiejska)
		
	def KlasyfikujMahalanobisa(self):
		self.SklasyfikujObiekt(self.zb.metrykaMahalanobisa)

	def SklasyfikujObiekt(self, metryka):
		item_index = self.ui.treeWidget.indexFromItem(self.ui.treeWidget.currentItem()).row()
		if item_index == -1:
			self.PopupMessage("Niepoprawne zaznaczenie", "Prosze najpierw zaznaczyc obiekt z listy.")
		indeksy, ok = QtGui.QInputDialog.getText(self, 'Podaj wektory', 'Podaj kolumny oddzielone przecinkiem np. 4,6,7:')
		if not ok:
				return
		
		klasa, ok = QtGui.QInputDialog.getText(self, 'Klasa Decyzyjna', 'Podaj kolumne klasy decyzyjnej:')
		if not ok:
				return

		k, ok = QtGui.QInputDialog.getText(self, 'Sasiedzi', 'Podaj k:')
		if not ok:
				return
		indeksy = [int(i) for i in indeksy.split(',')]

		wynik =  self.zb.klasyfikuj(self.zb.lista[item_index],indeksy, int(klasa), metryka, int(k))
		zapisac, ok = QtGui.QInputDialog.getText(self, 'Zaktualizowac wynik na liscie ?', 'Uzyskano wynik:%s\nCzy chcesz zapisac wynik do obiektu ?[T/N]'%(wynik))
		if not ok:
				return
		if str(zapisac).upper()=="T":
			self.zb.lista[item_index][int(klasa)] = wynik
			self.populate_from_set()

	def Metoda_K_Srednich(self):
		N = None
		k, ok = QtGui.QInputDialog.getText(self, 'K klas', 'Podaj k:')
		if not ok:
			return

		klasa, ok = QtGui.QInputDialog.getText(self, 'Klasa decyzyjna', 'Podaj indeks klasy decyzyjnej:')
		if not ok:
			return

		indeksy, ok = QtGui.QInputDialog.getText(self, 'Indeksy Zmiennych', 'Podaj indeksy kolumn oddzielone ",":')
		if not ok:
			return

		indeksy = [int(i) for i in indeksy.split(',')]

		N, ok = QtGui.QInputDialog.getText(self, 'Ilosc iteracji', 'Podaj ilosc iteracji, lub -1 jesli chcesz iterowac az nie bedzie zmian:')
		if not ok:
			return

		N = int(N)

		wynik = self.zb.licz_k_srednich(int(k), self.zb.metrykaEuklidesowa, int(klasa), indeksy, (N if N>0 else None))

		if wynik['result'] == 'OK':
			self.PopupMessage("Podsumowanie klasyfikacji", "Sklasyfikowano %.2f%% osobnikow poprawnie" %(wynik['val']*100))
		else:
			self.PopupMessage("Nie mozna podsumowac klasyfikacji", "Nie mozna bylo podsumowac klasyfikacji, k <> faktycznej ilosci klas")
		self.populate_from_set()

	def Metoda_K_Srednich_search(self):

		indeksy, ok = QtGui.QInputDialog.getText(self, 'Indeksy Zmiennych', 'Podaj indeksy kolumn oddzielone ",":')
		if not ok:
			return

		klasa, ok = QtGui.QInputDialog.getText(self, 'Klasa decyzyjna', 'Podaj indeks klasy decyzyjnej:')
		if not ok:
			return

		indeksy = [int(i) for i in indeksy.split(',')]
		klasa = int(klasa)

		wynik = self.zb.znajdz_k_srednich(self.zb.metrykaEuklidesowa,klasa, indeksy)
		self.populate_from_set()
		self.PopupMessage("Podsumowanie szukania K", "Optymalne K: %d, Suma odchylen: %.3f" %(wynik[1],wynik[0]))

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

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

		self.ui.actionAdd_Row.triggered.connect(self.add_row)
		self.ui.actionAdd_Col.triggered.connect(self.add_empty_column)
		self.ui.actionDelete_Col.triggered.connect(self.remove_column_dialog)
		self.ui.actionDelete_Row.triggered.connect(self.remove_row_dialog)

		self.ui.actionClear.triggered.connect(self.clear_tree)
		self.ui.actionPopulate_from_set.triggered.connect(self.populate_from_set)
		self.ui.actionDEBUG.triggered.connect(self.DEBUG)
		self.ui.typesPushButton.clicked.connect(self.edit_types)
		self.ui.namesPushButton.clicked.connect(self.edit_names)
		self.ui.actionSave.triggered.connect(self.save_data)
		self.ui.actionLoad.triggered.connect(self.load_data)

		#zadanie1
		self.ui.actionDyskretyzacjaPRD.triggered.connect(self.dyskretyzacjaPRD)
		self.ui.actionDyskretyzacjaNK.triggered.connect(self.dyskretyzacjaNK)
		self.ui.actionStandaryzacja.triggered.connect(self.standaryzacja)
		self.ui.actionOdstajace3x.triggered.connect(self.odstajace3x)
		self.ui.actionOdstajaceProcent.triggered.connect(self.odstajaceProcent)
		self.ui.actionNormalizacja.triggered.connect(self.normalizacja)
		self.ui.actionWykres2D.triggered.connect(self.Wykres2D)
		self.ui.actionWykres3D.triggered.connect(self.Wykres3D)
		#self.ui.actionSprawdzOcene.triggered.connect(self.SprawdzOceneKlasyfikacji)
		#self.ui.actionSklasyfikujObiekt.triggered.connect(self.SklasyfikujObiekt)
		self.ui.actionMetryk_Euklidesow.triggered.connect(self.SprawdzEuklidesowa)
		self.ui.actionMetryk_Miejsk.triggered.connect(self.SprawdzMiejska)
		self.ui.actionMetryk_Mahalanobisa.triggered.connect(self.SprawdzMahalanobisa)
		self.ui.actionMetryk_Euklidesow_2.triggered.connect(self.KlasyfikujEuklidesowa)
		self.ui.actionMetryk_Miejsk_2.triggered.connect(self.KlasyfikujMiejska)
		self.ui.actionMetryk_Mahalanobisa_2.triggered.connect(self.KlasyfikujMahalanobisa)
		self.ui.actionMetoda_K_Srednich.triggered.connect(self.Metoda_K_Srednich)
		self.ui.actionMetoda_K_Srednich_optymalne_K.triggered.connect(self.Metoda_K_Srednich_search)

		self.TypToS = TypToS
		self.SToTyp = SToTyp
Ejemplo n.º 42
0
class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self.ui.btnInputCellFile.clicked.connect(self.btnInputCellFile_Clicked)
        self.ui.btnInputNeighborFile.clicked.connect(self.btnInputNeighborFile_Clicked)
        self.ui.btnGenerateCellFile.clicked.connect(self.btnGenerateCellFile_Clicked)
        self.ui.actionCellDatabaseFileFormat.triggered.connect(self.actionCellDatabaseFileFormat_Clicked)
        self.ui.actionNeighborFileFormat.triggered.connect(self.actionNeighborFileFormat_Clicked)
        self.ui.actionAbout.triggered.connect(self.actionAbout_Clicked)
        
    def btnInputCellFile_Clicked(self):
        self.ui.txtInputCellFile.setText(QtGui.QFileDialog.getOpenFileName(filter='CSV (*.csv);;All files (*.*)'))
              
    def btnInputNeighborFile_Clicked(self):
        self.ui.txtInputNeighborFile.setText(QtGui.QFileDialog.getOpenFileName(filter='CSV (*.csv);;All files (*.*)'))
            
    def actionCellDatabaseFileFormat_Clicked(self):
        QtGui.QMessageBox.information(None, 'Cell Database file Format', "CELL,CI,LAT,LON,ANT_DIRECTION,ANT_BEAM_WIDTH,ARFCN,BSIC,MCC,MNC,LAC")
        
    def actionNeighborFileFormat_Clicked(self):
        QtGui.QMessageBox.information(None, 'Neighbor file Format', "cell,neighbor")
        
    def actionAbout_Clicked(self):
        QtGui.QMessageBox.information(None, 'About', "Source code for this software can be found at:\nhttps://github.com/imtiaznizami/PyTemsCellFileGenerator")
        
    def btnGenerateCellFile_Clicked(self):
        fn_cel = self.ui.txtInputCellFile.text()
        fn_nbr = self.ui.txtInputNeighborFile.text()
        
        # check if file / folder names are valid
        if not os.path.isfile(fn_cel):
            QtGui.QMessageBox.information(None, 'Warning', "Cell file name is invalid. Aborting execution.")
            return
            
        if not os.path.isfile(fn_nbr):
            QtGui.QMessageBox.information(None, 'Warning', "Neighbor file name is invalid. Aborting execution.")
            return

        # read neighbor file into a dictionary
        # key: cell id
        # value: list of neighbors 
        dict_nbr = {}
        
        with open(fn_nbr, 'rt') as csvfile:
            reader_nbr = csv.reader(csvfile, delimiter=',', quotechar='"')
            for row in reader_nbr:
                if len(row) > 1:
                    if row[0] not in dict_nbr:
                        dict_nbr[row[0]] = []
                    
                    dict_nbr[ row[0].strip() ].append( row[1].strip() )   
        
        # read cell file and write to file like string
        output = io.StringIO()
        writer = csv.writer(output, delimiter = '\t', lineterminator='\n')
        writer.writerow(["2 TEMS_-_Cell_names"])
        lst_header = []
        flag = 1
        
        with open(fn_cel, 'rt') as f:
            reader = csv.DictReader(f) # read rows into a dictionary format
            for row in reader: # read a row as {column1: value1, column2: value2,...}                
                lst = list(row.values())
                for (k,v) in row.items(): # go over each column name and value  
                    if flag:
                        lst_header.append(k)                  
                    if k == 'CI':
                        if v in dict_nbr:
                            lst = lst + dict_nbr[v][:32]
                               
                if flag:
                    for n in range(1, 33):
                        lst_header.append("CI_N_%s" % (n,))
                    writer.writerow( lst_header )
                    flag = 0
                
                writer.writerow( lst )
        
        # write output file
        fn_out = QtGui.QFileDialog.getSaveFileName(filter='CEL (*.cel);;All files (*.*)')
        if not os.path.isdir(os.path.dirname(fn_out)):
            QtGui.QMessageBox.information(None, 'Warning', "Output file directory is invalid. Aborting execution.")
            return
        
        file_out = open(fn_out, "w")
        file_out.write(output.getvalue())
        file_out.close()