Exemple #1
0
 def __init__(self, source='', destination='', clear_destination=False):
     super(GCWii, self).__init__()
     self.export_in_progress = False
     app = QtWidgets.QApplication(sys.argv)
     self.MainWindow = QtWidgets.QMainWindow()
     self.max_treads = QThread.idealThreadCount()
     self.setupUi(self.MainWindow)
     self.msg = MessageBox()
     self.manager = GCWiiManager()
     self.default_box_artwork = str(os.path.join('images',
                                                 'blanc-case.png'))
     self.default_disc_artwork = str(
         os.path.join('images', 'blanc-disc.png'))
     self.source_directory = source
     self.source_game_collection = {}
     self.destination_directory = destination
     self.clear_destination = clear_destination
     self.destination_game_collection = {}
     self.box_artwork_path = os.path.join(os.getcwd(), 'images', 'cover3D')
     self.disc_artwork_path = os.path.join(os.getcwd(), 'images', 'disc')
     self.current_selection = {}
     self.games_to_export = {}
     self.setup_widgets()
     self.setup_actions()
     self.MainWindow.show()
     if self.source_directory:
         self.update_source_list()
     if self.destination_directory:
         self.update_destination_list()
     sys.exit(app.exec_())
Exemple #2
0
	def step(self):
		"""
		Execute the script line by line
		"""
		if not self.play_cmd:
			return False		
		
		line = self.get()
		self.warn_observers('step')
		if(line):
			if line[0]!='#':
				line = line.split('#')

				comment = ""
				if len(line) > 1:
					comment = line[1]
					
				line = line[0]
				if self.parse(line, comment):
					self.wait_exec()
				else:
					self.show_message("Stopped! Box returns error", 'error', self.line_number)
					self.warn_observers('stop')					
			else:
				self.show_message("#     " + line[1:])
				self.step()
		else:
			self.show_message("End.")
			m = MessageBox('info')
			m.mostrar('Process Finished', '')
			self.warn_observers('stop')
 def import_error(self,):
     message = MessageBox()
     message.about(self, 'Warning!', "Data were not loaded. \n Please, be sure that:\n "
                                             "1. Data have 1 or 2 columns.\n"
                                             "2. Data are longer than 100 points.\n"
                                             "3. Delimiter is correctly specified.\n"
                                             "4. Rows in data contain only numeric values\n")
Exemple #4
0
    def startCrack(self):

        if not self.FileChecker.isArchiveEmpty(
        ) and not self.FileChecker.isDictionaryEmpty():

            if self.FileChecker.isArchiveRAR():

                MessageBox.ShowError(
                    "Error",
                    "This is a RAR file(If you want to use this just uncomment code in Zip_Cracker.py file)"
                )
                #Uncomment this if you have linux :/
                #if not self.FileChecker.RequiresPassword():
                #    Cracker=RARCracker(self.FileChecker.getArchiveFilePath(),self.FileChecker.getDictionaryPath())
                #else:
                #    messagebox.showinfo("WAIT WHAT?","RAR archive doesn't have any password")
                #    return
            else:

                Cracker = ZIPCracker(self.FileChecker.getArchiveFilePath(),
                                     self.FileChecker.getDictionaryPath(),
                                     self.ProgressBar)
                self.ProgressBar.setMaxValue(Cracker.countPasswords())
                # I'm f*****g lazy to create a special class for two lines of code  :/
                self.thread = threading.Thread(target=Cracker.TryBruteForce())
                self.thread.start()
        else:
            MessageBox.ShowError("Error", "You didn't choose all options")
Exemple #5
0
 def import_error(self,):
     message = MessageBox()
     message.about(self, 'Warning!', "Data were not loaded. \n Please, be sure that:\n "
                                             "1. Data have 1 or 2 columns.\n"
                                             "2. Data are longer than 100 points.\n"
                                             "3. Delimiter is correctly specified.\n"
                                             "4. Rows in data contain only numeric values\n")
 def dot_pick_enable(self, ):  # if checked, user can choose peaks
     try:  # if figure and canvas is initiated
         if self.chbxDotPickEnable.isChecked():
             self.cid_click = self.canvas.mpl_connect('button_press_event', self.on_click)
             self.cid_motion = self.canvas.mpl_connect('motion_notify_event', self.on_motion)
         else:
             self.canvas.mpl_disconnect(self.cid_click)
             self.canvas.mpl_disconnect(self.cid_motion)
     except:
         message = MessageBox()
         message.about(self, 'Warning!', "File was not loaded! \n Please be sure that your file has \
             \n 1) 1 or 2 columns; \n 2) check headers, footers and delimeter \n and try again.")
Exemple #7
0
    def displayDialog(self, message):
        messageBox = MessageBox(style=MessageBox.ICON_WARNING)
        messageBox.setText("MakeHazard")
        messageBox.setMessage(message)
        messageBox.setButtonLabels(["Continue Merge", "Cancel Merge"])
        messageBox.setDefaultIndex(1)
        if (messageBox.open() == 0):
            self.continueCommand()
        else:
            self.cancelCommand()

        return
Exemple #8
0
 def dot_pick_enable(self, ):  # if checked, user can choose peaks
     try:  # if figure and canvas is initiated
         if self.chbxDotPickEnable.isChecked():
             self.cid_click = self.canvas.mpl_connect('button_press_event', self.on_click)
             self.cid_motion = self.canvas.mpl_connect('motion_notify_event', self.on_motion)
         else:
             self.canvas.mpl_disconnect(self.cid_click)
             self.canvas.mpl_disconnect(self.cid_motion)
     except:
         message = MessageBox()
         message.about(self, 'Warning!', "File was not loaded! \n Please be sure that your file has \
             \n 1) 1 or 2 columns; \n 2) check headers, footers and delimeter \n and try again.")
Exemple #9
0
    def createDialog(self):
        if not self.dialog:
            self.dialog = QDialog()
            self.dialog.setWindowIcon(QIcon("images/mail.png"))

            self.msg = MessageBox(self.dialog, self.connectionThread, self.jid,
                                  self.name)
            layout = QVBoxLayout(self.dialog)
            layout.addWidget(self.msg)
            self.dialog.setLayout(layout)
            self.dialog.setWindowTitle(
                self.dialog.tr("Chat with ") + self.name)
        self.dialog.show()
        self.dialog.raise_()
    def closeEvent(self, event):
        """Exchange default event to add a dialog"""
        if self.multiple_data_sets.empty:
            reply = MessageBox.question(self, 'Warning!',
                                        "Are you sure to quit?", QMessageBox.Yes, QMessageBox.No)
        else:
            reply = MessageBox.question(self, 'Warning!',
                                        "You have unsaved analysed data! \n Are you sure to quit?",
                                        QMessageBox.Yes, QMessageBox.No)

        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()
Exemple #11
0
 def get_add_res(self, issuccess: bool, userItem: UserItem):
     # 获取添加的结果,如果添加成功则为真,否则为False
     if issuccess is True:
         self.add_line_item(userItem)
         # 放到记录里
         if self.inDoOperate is False:
             self.operateStack.push(Operate(Operate.ADD, userItem))
             TipUi.show_tip('添加成功')
         else:
             self.inDoOperate = False
     else:
         MessageBox.error(self, u'添加项目', u'添加时发生错误,请重启程序再次尝试',
                          MessageBox.CLOSE)
         sys.exit()
Exemple #12
0
    def closeEvent(self, event):
        """Exchange default event to add a dialog"""
        if self.multiple_data_sets.empty:
            reply = MessageBox.question(self, 'Warning!',
                                        "Are you sure to quit?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
        else:
            reply = MessageBox.question(self, 'Warning!',
                                        "You have unsaved analysed data! \n Are you sure to quit?",
                                        QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()
Exemple #13
0
    def gerarChaves(self):
        p = self.txtP.get()
        q = self.txtQ.get()

        try:
            result = self.controller.gerarChaves(p, q)
            if result == True:
                messageBox = MessageBox(
                    "Chaves Geradas Com Sucesso",
                    "Chave Pública Salva Em " + str(Path.home()), None)
        except ValueError as ve:
            messageBox = MessageBox("Erro ao Executar Cifragem", ve.args[0],
                                    None)
            print(ve.args)
Exemple #14
0
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self,parent,*args,**kwargs)
        self.parent = parent
        self.grandpa = self.parent
        self.parent.title("ANC AUTO PUNCHER")
        
        # The data dump is assigned to the root.
        # Root will be always referenced to as grandpa
        parent.ds = data_storage(self)
        
        # Determine the width and height of the main window
        self.w = self.parent.winfo_screenwidth() * 0.5
        self.h = self.parent.winfo_screenheight() * 0.5
        if (self.w < 750):
            self.w = 800
        # Set the window size
        self.parent.geometry(("%dx%d")%(self.w,self.h))
        
        self.parent.resizable(width=False, height=False)
        
        # Create a dictionary of main windows and populate
        self.main = {}
        for page in (PunchPage, RunPage, ProcessPage):
            self.main[page.__name__] = page(self,width = self.w/8*7, height = self.h/4*3)
            self.main[page.__name__].grid(row = 0, column = 1, sticky = "wens")
            self.main[page.__name__].grid_propagate(0)

        self.main["PunchPage"].tkraise()
        
        self.msgb = MessageBox(self,width = self.w, height = self.h/4, bg='lavender')
        self.navg = Navigation(self,controller=self,width = self.w/8, height = self.h/4*3, bg='white')

        # Layout all the main containers
        self.grid_rowconfigure(0, weight = 0)
        self.grid_rowconfigure(1, weight = 0)
        self.grid_columnconfigure(0, weight = 0)
        self.grid_columnconfigure(1, weight = 0)

        self.msgb.grid(row = 1, columnspan = 2, sticky = "wnse")
        self.navg.grid(row = 0, column = 0, sticky = "wnse")
         
        self.msgb.grid_propagate(0)
        self.navg.grid_propagate(0)

        self.msgb.insert_text("Welcome to ANC AUTO PUNCHER!")
        self.msgb.insert_text("\nSet inputs, choose an analysis from the drop down menu and get punching!")
        self.grid()

        self.grandpa.msgb = self.msgb
Exemple #15
0
	def wait_exec(self):
		"""
		Really wait for the time_ defined or by a click on the box
		"""
		sec_time = self.sec_time

		if sec_time < 0:
			self.show_message("Waiting a click")
			m = MessageBox('info')
			m.mostrar('Wait Box','Click to continue')
			self.next_step = timeout_add(50, self.step)

		else:
			self.show_message("Waiting ddd "+ str(sec_time) + " seconds")
			self.next_step = timeout_add(int(sec_time * 1000), self.step)
Exemple #16
0
def main():
    manager = Manager()
    upen = UnderlinePen('~')
    mbox = MessageBox('*')
    sbox = MessageBox('\\')
    manager.register("strong message", upen)
    manager.register("warning box", mbox)
    manager.register("slash box", sbox)

    p1 = manager.create("strong message")
    p1.use("Hello, world.")
    p2 = manager.create("warning box")
    p2.use("Hello, world.")
    p3 = manager.create("slash box")
    p3.use("Hello, world")
    def data_preprocessing(self, data_to_preprocess):
        try:
            # Detrend dataset
            if self.chbxDetrendData.isChecked():
                self.data_detrended = sig.detrend(data_to_preprocess)
            else:
                self.data_detrended = data_to_preprocess

            # Application of Savitzkyi-Golay filter for data smoothing
            sg_window_frame = self.BoxSGwindowFrame.value()
            sg_polynom_degree = self.BoxSGpolynomDegree.value()
            self.data_after_filter = sig.savgol_filter(self.data_detrended, sg_window_frame, sg_polynom_degree)
        except:
            message = MessageBox()
            message.about(self, 'Warning!',
                          "Not possible to detrend and/or smooth data! \n Please check your dataset and try again.")
Exemple #18
0
    def data_preprocessing(self, data_to_preprocess):
        try:
            # Detrend dataset
            if self.chbxDetrendData.isChecked():
                self.data_detrended = sig.detrend(data_to_preprocess)
            else:
                self.data_detrended = data_to_preprocess

            # Application of Savitzkyi-Golay filter for data smoothing
            sg_window_frame = self.BoxSGwindowFrame.value()
            sg_polynom_degree = self.BoxSGpolynomDegree.value()
            self.data_after_filter = sig.savgol_filter(self.data_detrended, sg_window_frame, sg_polynom_degree)
        except:
            message = MessageBox()
            message.about(self, 'Warning!',
                          "Not possible to detrend and/or smooth data! \n Please check your dataset and try again.")
Exemple #19
0
 def __init__(self):
     #Setup Debugging Variables for outside of Maya
     self.maya_enabled = True
     #Setup Paths
     self.get_maya_project_path()
     svnPath = self.mayaProjectPath + "svn"
     #Setup pysvn
     self.client = pysvn.Client(svnPath)
     self.client.callback_get_login = self.get_login
     self.client.callback_ssl_server_trust_prompt = self.ssl_server_trust_prompt
     #Setup Message Box
     pt.initializePumpThread()
     app = QtGui.QApplication(sys.argv)
     self.msgBox = MessageBox()
     #Testing Variables
     self.svnURL = "https://192.168.0.22:8443/svn/Dalek/trunk/"
	def add_ip(self):
		wdg = self.get_wdg("txtIP")
		ip = wdg.get_text()
		if is_valid_ip(ip):
			cb = self.get_wdg("cbIP")
			model = cb.get_model()
			model.append([ip])
			cb.set_model(model)
			cb.show()
			self.stbip.append(ip)
			if cb.get_active() == -1:
				cb.set_active(0)
		else:
			m = MessageBox('error')
			m.mostrar('Error', 'Invalid IP')
		wdg.set_text('')
Exemple #21
0
 def get_delete_res(self, issuccess: bool, ID: str):
     # 删除成功信号
     if issuccess is True:
         item = self.itemList.pop(ID)
         row = self.get_row_by_id(ID)
         if row != NOTLINE:
             self.ui.table.removeRow(row)
         # 在进行常规的删除操作
         if self.inDoOperate is False:
             self.operateStack.push(Operate(Operate.DELETE, item))
             TipUi.show_tip('删除成功')
         else:
             self.inDoOperate = False
     else:
         MessageBox.error(self, u'删除项目', u'删除时发生错误,请重启程序再次尝试',
                          MessageBox.CLOSE)
         sys.exit()
	def send(self, key, hold=None):
		"""
		Prepare, send and check return of a remote command to Remote class

		@param key string defines the remote button used
		@param hold enum (0,1,2) represents Button Press Down or UP
		@returns bool the request was successful and the return is valid
		"""
		if len(self.stbip) == 0:
			mb = MessageBox('error')
			mb.mostrar("Set an ip", "Please set an ip to send a command")
			return False

		for ip in self.stbip:
			wdg_retorno = self.get_wdg("txtRetorno")
			if(self.first_command):
				self.first_command = False
				
			if hold is None:
				hold = self.get_wdg("cbRemoteType").get_active()
			rem = Remote(ip)

			ret = rem.send(hold, key)
			msg = "ip: %s\n" % (ip)

			if ret is not None:
				if(rem.return_is_valid(ret, key, hold)):
					complete="Success!"
					tag = "success"
					
					self.show_message(msg + self.__make_rem_readable(ret) + "\n" + complete, tag)
				else:
					complete="Fail."
					tag = "error"
					self.stbip.remove(ip)
			else:
				complete = 'Fail.'
				tag = 'error'
				self.stbip.remove(ip)
				msg += "Timeout Connection\n"
				self.show_message(msg + complete, tag)


			
		
		return True if len(self.stbip) else False
 def cannyFilterBox(self):
     canny_text = QLabel("Sigma Canny", self)
     #sig = QLabel(str(self.sigma_canny), self)
     canny_btn = self.button(self.cannyFilter, "Canny")
     drog_btn = self.button(self.drogFilter, "Drog")
     #sigma_slider = self.slider(self.cannyFilter, self.sigma_canny, minimum=3,maximum=7)
     widget = [canny_text, canny_btn, drog_btn]
     result = MessageBox(widget, None)
     result.setDefaultButton(QMessageBox.Apply)
     result.setStandardButtons(QMessageBox.Apply | QMessageBox.Cancel)
     result.buttonClicked.connect(self.applyEdgeDetectionFilter)
     result.exec_()
Exemple #24
0
    def TryBruteForce(self):
        with open(self.wordlist,'r',errors='ignore',encoding='utf-8') as file:
            for word in file.readlines():
                if(self.isPasswordCorrect(word.strip())):
                    self.password=word.strip()
                    MessageBox.ShowInfo("Done",f"Password found! {self.password}")
                    return

                self.counter+=1
               	self.ProgressBar.updateValue(self.counter)
Exemple #25
0
 def get_edit_res(self, flag: bool, ID: str, header: str, value: str):
     if flag is True:
         self.itemList[ID][header] = value
         row = self.get_row_by_id(ID)
         column = {
             'name': 1,
             'account': 2,
             'password': 3,
             'email_or_phone': 4,
             'note': 5
         }[header]
         if column == 3:
             self.ui.table.item(row, column).setText(
                 op.decrypt_password(value, self.adminPassword))
         else:
             self.ui.table.item(row, column).setText(value)
     else:
         MessageBox.error(self, u'编辑项目', u'编辑时数据库发生错误,请重启程序再次尝试',
                          MessageBox.CLOSE)
         sys.exit()
Exemple #26
0
	def createDialog(self):
		if not self.dialog:
			self.dialog = QDialog()
			self.dialog.setWindowIcon(QIcon("images/mail.png"))

			self.msg = MessageBox(self.dialog, self.connectionThread, self.jid, self.name)
			layout = QVBoxLayout(self.dialog)
			layout.addWidget(self.msg)
			self.dialog.setLayout(layout)
			self.dialog.setWindowTitle(self.dialog.tr("Chat with ") + self.name)
		self.dialog.show()
		self.dialog.raise_()
Exemple #27
0
    def cifrar(self):
        try:
            self.controller.leTextoClaro()

            self.controller.cifrar()
            self.controller.decifrar()

            self.controller.salvarCifrado()
            self.controller.salvarDecifrado()

            messageBox = MessageBox(
                "Cifragem Executada com Sucesso",
                "Texto Cifrado e Decifrado Salvo em {}".format(
                    self.controller.cifra.getDiretorio()), self.reset)
        except ValueError as ve:
            messageBox = MessageBox("Erro ao Executar Cifragem", ve.args[0],
                                    None)
            print(ve.args)
        except FileNotFoundError as fnfe:
            messageBox = MessageBox("Erro ao Executar Cifragem",
                                    "Arquivo Não Encontrado", None)
            print(fnfe.args)
Exemple #28
0
 def remove_line(self):
     # 点击删除按钮,发送删除信号
     if self.ui.table.currentRow() != NOTLINE:
         ID = self.get_selected_id()
         # 如果设置项中删除前提示
         if self.setting.applyBeforeDel is True:
             msg = MessageBox.information(
                 self, '删除选项', '是否删除所选项?',
                 MessageBox.YES | MessageBox.CANCEL)
             if msg == MessageBox.YES:
                 # 发送删除信号,为删除项的ID
                 self.deleteItemSignal.emit(ID)
         else:
             self.deleteItemSignal.emit(ID)
	def sendSerial(self,command):
		"""
		Prepare and send a serial command to Serial class

		@param cmd string command
		"""
		wdg_retorno = self.get_wdg("txtRetorno")
		if(self.first_command):
			self.first_command=False
			buffer = gtk.TextBuffer()
			wdg_retorno.set_buffer(buffer)

		command = self.get_wdg("cbSerialCommand").get_active_text()
		for ip in self.stbip:
			ser = Serial(ip)
			cmds = serial_commands[command]['serial']

			if (serial_commands[command]['complemento'] == False):
				retorno = ser.process(cmds)
				msg = "ip: %s\n"%(ip)
				self.show_message(msg + self.__make_serial_readable(command, retorno) + "\n")
			else:
				mb = MessageBox('error')
				mb.mostrar('Not implemented yet')
 def blurFilterBox(self):
     arith_mean_btn = self.button(self.arithmeticMeanFilter, "Arithmetic mean Blur Filter")
     geomet_mean_btn = self.button(self.geometricMeanFilter, "Geometric mean Blur Filter")
     harmonic_mean_btn = self.button(self.harmonicMeanFilter, "Harmonic mean Blur Filter")
     median_filter_btn = self.button(self.medianFilter, "Median Blur Filter")
     widget = [arith_mean_btn, geomet_mean_btn, harmonic_mean_btn, median_filter_btn]
     result = MessageBox(widget, None)
     result.setStandardButtons(QMessageBox.Apply | QMessageBox.Cancel)
     result.buttonClicked.connect(self.applyBlurFilter)
     result.exec_()
Exemple #31
0
 def __init__(self):
     #Setup Debugging Variables for outside of Maya
     self.maya_enabled = True
     #Setup Paths
     self.get_maya_project_path()
     svnPath = self.mayaProjectPath + "svn"
     #Setup pysvn
     self.client = pysvn.Client(svnPath)
     self.client.callback_get_login = self.get_login
     self.client.callback_ssl_server_trust_prompt = self.ssl_server_trust_prompt
     #Setup Message Box
     pt.initializePumpThread()
     app = QtGui.QApplication(sys.argv)
     self.msgBox = MessageBox()
     #Testing Variables
     self.svnURL = "https://192.168.0.22:8443/svn/Dalek/trunk/"
    def save_data(self, ):
        try:
            file_name = QFileDialog.getSaveFileName(self, 'Save file')[0]
            writer = pd.ExcelWriter('{}.xlsx'.format(file_name))
            self.multiple_data_sets.to_excel(writer, index=True, sheet_name='Results')
            writer.sheets['Results'].set_zoom(80)
            writer.sheets['Results'].set_column('A:A', 5)
            writer.sheets['Results'].set_column('B:X', 23)
            writer.save()

            message = MessageBox()
            message.about(self, 'Data saved', "Data were saved!")
            self.multiple_data_sets = pd.DataFrame()
            self.BtnSaveFullDataset.setStyleSheet("background-color: #FAF6F2")
            self.BtnLoadFile.setStyleSheet("background-color: #7CF2BD")
        except Exception as e:
            message = MessageBox()
            message.about(self, 'Warning!', "Data were not exported to Excel! \n Please try again.")
            print(e)
    def colorBox(self):

        lumtext = QLabel("Luminance", self)
        sliderL = self.slider(self.luminanceFilter, self.lumPosition)
        contrtext = QLabel("Contrast", self)
        sliderC = self.slider(self.contrastFilter, self.contrPosition)
        sattext = QLabel("Saturation", self)
        sliderS = self.slider(self.saturationFilter, self.satPosition, maximum=255, minimum=-255)

        widget = [lumtext, sliderL, contrtext, sliderC, sattext, sliderS]
        result = MessageBox(widget, None)
        result.setStandardButtons(QMessageBox.Apply | QMessageBox.Cancel)
        result.buttonClicked.connect(self.applyColors)
        result.exec_()
    def transformsBox(self):
        trasText = QLabel("Translate", self)
        sliderTX = self.slider(self.translateX, self.trasPositionX)
        sliderTY = self.slider(self.translateY, self.trasPositionY)
        scalText = QLabel("Scaling", self)
        sliderS = self.slider(self.scaling, self.scalePosition, -360, 360)
        rotText = QLabel("Rotate", self)
        sliderR = self.slider(self.rotate, self.rotatePosition)

        widget = [trasText, sliderTX, sliderTY, scalText, sliderS, rotText, sliderR, self.transform_check]
        result = MessageBox(widget, None)
        result.setStandardButtons(QMessageBox.Apply | QMessageBox.Cancel)
        result.buttonClicked.connect(self.applyTransforms)
        result.exec_()
    def SRMBox(self):
        text = QLabel("Nearness", self)

        samples = QLineEdit()
        samples.setValidator(QIntValidator())
        samples.setMaxLength(4)
        samples.setAlignment(Qt.AlignCenter)
        samples.textChanged.connect(self.setNumberSamples)
        samples.setPlaceholderText("default: " + str(self.samplesSRM))
        srm_btn = self.button(self.statisticalRegionMerging, "Preview")

        widget = [text, samples, srm_btn]
        result = MessageBox(widget, None)
        result.setStandardButtons(QMessageBox.Apply | QMessageBox.Cancel)
        result.buttonClicked.connect(self.applySRM)
        result.exec_()
Exemple #36
0
    def closeEvent(self, event):
        # 如果设置没有保存
        if self.setting.autoLockTime != self.ui.sb_autoLockTime.value() or \
            self.setting.showToolTips != self.ui.cb_showToolTips.isChecked() or \
            self.setting.showLineIndex != self.ui.cb_showLineIndex.isChecked() or \
            self.setting.applyBeforeDel != self.ui.cb_deleteTips.isChecked() or \
            self.setting.autoBackup != self.ui.cb_autoBackup.isChecked() or \
            self.setting.useRegExpFilite != self.ui.cb_useRegExpSearch.isChecked() or \
            self.setting.singalClickSelect != self.ui.cb_mouseClickSelect.isChecked() or \
           self.setting.ctrlSelect != self.ui.cb_pushCtrl.isChecked():

            pbt = MessageBox.warning(
                self, '保存设置', '设置修改后尚未保存,\n关闭后将会丢失,是否保存?',
                MessageBox.YES | MessageBox.NO | MessageBox.CANCEL,
                MessageBox.YES)
            if pbt == MessageBox.YES:
                self.save_settings()
                event.accept()
            elif pbt == MessageBox.CANCEL:
                event.ignore()
            else:
                event.accept()
Exemple #37
0
    def save_data(self, ):
        try:
            file_name = QtGui.QFileDialog.getSaveFileName(self, 'Save file')
            writer = pd.ExcelWriter('{}.xlsx'.format(file_name))
            self.multiple_data_sets.to_excel(writer, index=True, sheet_name='Results')
            writer.sheets['Results'].set_zoom(80)
            writer.sheets['Results'].set_column('A:A', 5)
            writer.sheets['Results'].set_column('B:X', 23)
            writer.save()

            message = MessageBox()
            message.about(self, 'Data saved', "Data were saved!")
            self.multiple_data_sets = pd.DataFrame()
            self.BtnSaveFullDataset.setStyleSheet("background-color: #FAF6F2")
            self.BtnLoadFile.setStyleSheet("background-color: #7CF2BD")
        except:
            message = MessageBox()
            message.about(self, 'Warning!', "Data were not exported to Excel! \n Please try again.")
Exemple #38
0
class BuddyItem(QTreeWidgetItem):
    """
      BuddyItem implements the view of a Buddy from the Roster
    """

    dialog = None
    msg = None

    def __init__(self, parent, jid, con):
        QTreeWidgetItem.__init__(self, parent, [jid],
                                 QTreeWidgetItem.UserType + 1)

        # QTreeWidgetItem configuration
        self.setFlags(Qt.ItemIsDragEnabled
                      | Qt.ItemIsEnabled)  # we can move a contact
        self.parent = parent
        self.jid = jid
        self.name = jid
        self.setStatus(STATUS.unavailable)
        self.connectionThread = con

    def setStatus(self, status):
        self.status = status
        if self.status.index not in range(6):
            self.status = STATUS.unavailable
        settings = QSettings("Trunat", "PyTalk")
        settings.beginGroup("preferences")
        repStatus = settings.value("images_status",
                                   QVariant("images/status/")).toString()
        fileStatus = settings.value(
            str(self.status),
            QVariant(STATUS_IMAGE[self.status.index])).toString()
        settings.endGroup()
        self.setIcon(0, QIcon(repStatus + fileStatus))

    def setName(self, name):
        if name:
            self.name = name
            self.setText(0, name)

    def status(self):
        return status

    def isAway(self):
        return (self.status == STATUS.away or self.status == STATUS.xa)

    def isOffline(self):
        if self.status == STATUS.unavailable:
            return True
        else:
            return False

    def createDialog(self):
        if not self.dialog:
            self.dialog = QDialog()
            self.dialog.setWindowIcon(QIcon("images/mail.png"))

            self.msg = MessageBox(self.dialog, self.connectionThread, self.jid,
                                  self.name)
            layout = QVBoxLayout(self.dialog)
            layout.addWidget(self.msg)
            self.dialog.setLayout(layout)
            self.dialog.setWindowTitle(
                self.dialog.tr("Chat with ") + self.name)
        self.dialog.show()
        self.dialog.raise_()

    def receiveMessage(self, event):
        self.createDialog()
        self.msg.receiveMessage(event)

    def sendMessage(self):
        self.createDialog()

    def __str__(self):
        return u'%s' % self.name
Exemple #39
0
class MayaSVN:
    #Class Contructor
    def __init__(self):
        #Setup Debugging Variables for outside of Maya
        self.maya_enabled = True
        #Setup Paths
        self.get_maya_project_path()
        svnPath = self.mayaProjectPath + "svn"
        #Setup pysvn
        self.client = pysvn.Client(svnPath)
        self.client.callback_get_login = self.get_login
        self.client.callback_ssl_server_trust_prompt = self.ssl_server_trust_prompt
        #Setup Message Box
        pt.initializePumpThread()
        app = QtGui.QApplication(sys.argv)
        self.msgBox = MessageBox()
        #Testing Variables
        self.svnURL = "https://192.168.0.22:8443/svn/Dalek/trunk/"

    #Get Project Path from Maya
    def get_maya_project_path(self):
        if (self.maya_enabled):
            self.mayaProjectPath = "E:\\MayaSVN\\testProject\\"
            #self.mayaProjectPath =  cmds.workspace(q=True,rd=True)
        else:
            self.mayaProjectPath = "E:\\MayaSVN\\testProject\\"

    #SVN Callbacks
    def get_login(self, realm, username, may_save):
        #Open Dialog ask for username & pass
        username, password = self.login_dialog()
        dialogRet = True
        return dialogRet, username, password, True

    def ssl_server_trust_prompt(self, trust_dict):
        return True, 3, True

    #SVN Functions
    #Checkout project files from SVN
    def checkoutProject(self):
        #Open dialog for URL & Path
        url, path = self.checkout_dialog()
        #Perform SVN Checkout
        print "Started Checkout"
        self.client.checkout(url, path)
        print "Checkout Completed"
        self.msgBox.setMessage("SVN Checkout Completed")
        self.msgBox.showMessageBox()
        #Set Maya Project to path
        #

    #Perform an update of SVN Files
    def updateSVN(self):
        self.client.update(self.mayaProjectPath)
        print "SVN Update Completed"

    #Open file in Maya, SVN update & lock file
    def openFile(self, filename):
        #Update SVN before opening file
        filepath = self.mayaProjectPath + filename
        self.updateSVN()
        #Lock file on SVN so other users cant edit
        self.client.lock(filepath, 'Maya Opened By user')
        #Open File in Maya
        #
        print "File Opened"

    #Save file commit to svn & unlock
    def saveFile(self, filename, comment):
        #Save & Close File in Maya
        #

        #Update SVN before saving file
        filepath = self.mayaProjectPath + filename
        self.updateSVN()
        #Work out whether this file is already under version control
        statusList = self.client.status(filepath)
        if (statusList):
            if (statusList[0].is_versioned == False):
                #Add New File to SVN
                self.client.add(filepath)
                print "New File Added to Repository"
            else:
                #Unlock so others may edit
                self.client.unlock(filepath)
            #Submit updated file to SVN
            self.client.checkin(filepath, comment)
            print "Check In Complete"
        else:
            print "Invalid File"

    #Import a Maya project into SVN
    def importProject(self):
        #Update Project Path Variable
        self.get_maya_project_path()
        #Import all project files into SVN
        url, path = self.import_dialog()
        self.client.import_(self.mayaProjectPath,
                            url,
                            'New Project Commit',
                            recurse=True)
        print "Import Completed"

    #Dialogs
    #Dialog for login to SVN
    def login_dialog(self):
        global app
        if (self.maya_enabled):
            app = QtGui.QApplication(sys.argv)
            login = LoginDialog()
            login.show()
            time.sleep(0.02)
            app.exec_()
        return login.getLoginDetails()

    #Dialog for checkout from SVN - Asks for URL & Path
    def checkout_dialog(self):
        return self.svnURL, self.mayaProjectPath

    #Dialog for import into SVN - Asks for URL & Path
    def import_dialog(self):
        return self.svnURL, self.mayaProjectPath
Exemple #40
0
	def handlekeypress(self, keynum, rawcode):
		if keynum == KEY_TIVO and rawcode == MYKEY_PUSHRESUME:
			tivo = 0
			if self.submenu:
				tivo = self.submenu.getResult()
				self.submenu = None

			if tivo == -1:
				self.isactive = False
				self.app.send_key(KEY_TIVO, MYKEY_PUSHCOMPLETE)
				return

			tivoname = self.menu[tivo]
			tsn = self.tsns[tivo]
		
			if self.sep is None or self.sep == os.path.sep:
				relfile = os.path.sep + self.vf.getRelativePath(self.container)
			else:
				relfile = self.sep + self.vf.getRelativePath(self.container).translate(maketrans(os.path.sep, self.sep))
			
			params = urllib.urlencode({'Command': 'Push', 'Container': self.container,
						'File': relfile,
						'tsn': tsn})
			url = 'http://%s:%s/TivoConnect' % (self.ip, self.port)

			try:
				f = urllib.urlopen(url, params)
				html = f.read()
				
			except:
				MessageBox(self.app, "Push Error",
						"An unknown exception has occurred during HTML request - verify configuration",
						'bonk',
						[[[], MYKEY_PUSHCOMPLETE]])
			else:
				if html.lower().count('queue') != 0:
					if self.opts['savepushdata']:
						self.vf.setMetaItem("pushDate", strftime("%Y-%m-%dT%H:%M:%SZ", gmtime()))
						self.vf.setMetaItem("vPushTivo", tivoname)
						meta = self.vf.getMeta()
						try:
							fn = self.vf.getMetaFileName()
							metafile = open(fn, 'w')
							metadata.dump(metafile, meta)
							metafile.close()
						except:
							pass
					MessageBox(self.app, "Successfully Queued",
							"File has been successfully queued for push to " + tivoname,
							'alert',
							[[[], MYKEY_PUSHCOMPLETE]])
					
				else:
					MessageBox(self.app, "Push Error",
							"PyTivo responded with an unknown message (%s) push may still occur" % html,
							'alert',
							[[[], MYKEY_PUSHCOMPLETE]])

		elif self.submenu:
			self.submenu.handlekeypress(keynum, rawcode)

		else:
			self.app.sound('bonk')
class Vidmgr(Application):
	def handle_resolution(self):
		print "Vidmgr Entering Handle Resolution"
		for (hres, vres, x, y) in self.resolutions:
			print "   Checking resolution %d, %d" %(hres, vres)
			if (hres == 1280):
				print "  Found an HD resolution"
				return (hres, vres, x, y)
			
		print "NO HD resolutions found!!!"
		self.active = False
		self.sound('bonk')
		return self.resolutions[0]
	
	def startup(self):
		print "Vidmgr thread entering startup"
		self.vwInfo = None
		self.vcChanged = False
		config = Config.Config()
		self.opts = config.load()
		self.cp = config.getConfigParser()
					
		# get the tivo information out of the startup config file.  For each tivo, we need to know:
		# tivox.name - the user friendly name and
		# tivox.tsn - the TSN
		# these fields all go into a section named [tivos]		
		self.loadTivos(self.cp, self.opts['sorttivosbyname'])
		if len(self.tivos) == 0:
			raise ConfigError("No Tivos found - exiting")

		# get the pytivo information.  For each pytivo instance, we need the following:
		# pytivox.config - the location of the config file
		# pytivox.ip - the ip address
		#
		# also, if the pytivo port number is not specified in the pytivo config file, you must have
		# pytivox.port - the port number
		self.shares = []		
		self.loadShares(self.cp)
		if len(self.shares) == 0:
			raise ConfigError("No shares found - exiting")
		
	def cleanup(self):
		tc.save()
		if self.vcChanged:
			self.vc.save()
		
	def handle_active(self):
		print "Vidmgr thread activating"
		self.myimages = Images(self)
		self.myfonts = Fonts(self)
		self.tdcount = 0

		self.push = None
		self.msgbox = None
		self.rebuildingCache = False
		
		self.vc = VideoCache(self.opts, self.cp)
		
		self.root.set_resource(self.myimages.Background)
		self.TitleView = View(self, height=30, width=screenWidth, ypos=titleYPos)
		self.SubTitleView= View(self, height=20, width=screenWidth, ypos=subTitleYPos)
		
		self.ldm = ListDisplayManager(self, self.opts)
		self.ddm = DetailDisplayManager(self, self.opts, tc)
		self.vwInfo = InfoView(self, self.opts, self.myfonts.infofont)
		self.subMenu = SubMenu(self, self.opts)

		self.rootNode = self.vc.load()
		self.vcChanged = False

		self.start()

	def reStart(self):
		self.ldm.ReInit()
		self.start()
		
	def start(self):
		if self.rootNode == None:
			raise ConfigError("No video cache - exiting")

		self.TitleView.set_text(TITLE, font=self.myfonts.fnt30, colornum=0xffffff, flags=RSRC_VALIGN_BOTTOM)
		self.SubTitleView.set_text(self.rootNode.getFullTitle(), font=self.app.myfonts.fnt20, colornum=0xffffff, flags=RSRC_VALIGN_BOTTOM)

		self.currentNode, self.currentItem = self.ldm.Descend(self.rootNode)
		self.lopts = self.rootNode.getOpts()
		self.ddm.show(self.currentItem)
		
		if self.currentNode == None:
			print "Current node = NULL - exiting"
			self.active = False
			
	def handle_font_info(self, font):
		if self.vwInfo == None:
			print "Got handle font before vwInfo was instantiated ??"
		else:
			self.vwInfo.setinfogeometry(font)
			
	def handle_key_press(self, keynum, rawcode):
		if keynum == KEY_THUMBSDOWN:
			self.tdcount += 1
			if self.tdcount == 3:
				self.mb = MessageBox(self.app, "Rebuilding Cache...",
					"Please Wait",
					'alert',
					[[[KEY_TIVO], 0]])

				self.send_key(KEY_TIVO, MYKEY_REBUILDCACHE)
				self.rebuildingCache = True
				return

			self.sound('thumbsup')
			return
		else:
			self.tdcount = 0
			
		if keynum == KEY_TIVO and rawcode == MYKEY_REBUILDCACHE:
			self.rootNode = self.vc.build()
			self.vcChanged = True

			self.mb.close()
			self.reStart()
			return

		if self.msgbox:
			self.msgbox.handlekeypress(keynum, rawcode)
			
		elif self.vwInfo.isVisible:
			snd = 'updown'
			if keynum in [ KEY_LEFT, KEY_CLEAR, KEY_INFO ]:
				self.vwInfo.hide()
				
			elif keynum in [ KEY_DOWN, KEY_CHANNELDOWN ]:
				if not self.vwInfo.pagedown():
					snd = 'bonk'
					
			elif keynum in [ KEY_UP, KEY_CHANNELUP ]:
				if not self.vwInfo.pageup():
					snd = 'bonk'
					
			else:
				snd = 'bonk'
				
			self.sound(snd)

		elif self.push:
			if keynum == KEY_TIVO and rawcode == MYKEY_PUSHCOMPLETE:
				self.push = None
			else:
				self.push.handlekeypress(keynum, rawcode)
				
		elif self.currentItem == None and keynum not in [ KEY_LEFT, KEY_TIVO ]:
			self.sound('bonk')
				
		elif keynum == KEY_INFO:
			meta = self.currentItem.getMeta()
			if len(meta) == 0:
				snd = 'bonk'
			else:
				self.vwInfo.loadmetadata(meta)
				self.vwInfo.paint()
				self.vwInfo.show()
				snd = 'updown'
			self.sound(snd)
				
		elif self.ldm.isNavKey(keynum, rawcode):
			self.currentItem = self.ldm.Navigate(keynum, rawcode)
			self.ddm.show(self.currentItem)
			
		elif keynum == KEY_LEFT:
			self.currentNode, self.currentItem = self.ldm.Ascend()
			if self.currentNode == None:
				self.active = False
				return
			self.SubTitleView.set_text(self.currentNode.getFullTitle(),
						font=self.app.myfonts.fnt20,
						colornum=0xffffff, flags=RSRC_VALIGN_BOTTOM)
			self.ddm.show(self.currentItem)
			self.sound('updown')
			
		elif keynum in [KEY_RIGHT, KEY_SELECT]:
			if self.currentItem.getObjType() == TYPE_VIDFILE:
				self.push = Push(self, self.opts, self.currentItem)
			else:
				self.SubTitleView.set_text(self.currentItem.getFullTitle(),
								font=self.app.myfonts.fnt20,
								colornum=0xffffff, flags=RSRC_VALIGN_BOTTOM)
				self.lopts = self.currentItem.getOpts()
				self.currentNode, self.currentItem = self.ldm.Descend(self.currentItem)
			self.ddm.show(self.currentItem)
			self.sound('updown')
			
		elif keynum == KEY_CLEAR:
			if not self.deletable(self.currentItem):
				self.sound('bonk')
			else:
				MessageBox(self.app, "Delete Confirmation",
						"Press THUMBS-UP button to confirm deletion of " + 
						self.currentItem.formatDisplayText(self.lopts['dispopt']),
						'alert',
						[
						 [[KEY_THUMBSUP], MYKEY_DELETECONFIRM], 
						 [[], MYKEY_DELETECANCEL]
						])
				
		elif keynum == KEY_TIVO and rawcode == MYKEY_DELETECOMPLETE:
			pass # nothing to do here
		
		elif keynum == KEY_TIVO and rawcode == MYKEY_DELETECANCEL:
			m = MessageBox(self.app, "Delete Cancelled",
					"CANCELLED",
					'bonk',
					[[[KEY_TIVO], 0]])
			self.sleep(1)
			m.close()
		
		elif keynum == KEY_TIVO and rawcode == MYKEY_DELETECONFIRM:
			m = MessageBox(self.app, "Deleting...",
					"Please Wait",
					'updown',
					[[[KEY_TIVO], 0]])
			self.currentItem.delVideo()
			self.currentItem = self.ldm.Verify()
			self.ddm.show(self.currentItem)
			m.close()
			MessageBox(self.app, "Deleted",
					"Video/Metadata/Artwork Deleted - Press any key",
					'alert',
					[[[], MYKEY_DELETECOMPLETE]])
			self.vcChanged = True
		
		else:
			self.sound('bonk')

	def deletable(self, item):
		if item.getObjType() != TYPE_VIDFILE:
			return False
		
		if item.isDeletable():
			return True
		
		return False
		
	# load up tivo information from the config file
	def loadTivos(self, cfg, sortflag):
		def cmptivo (left, right):
			return cmp(left['name'], right['name'])
		
		tlist = []
		section = 'tivos'
		
		allchars = maketrans('', '')
		if cfg.has_section(section):
			i = 0
			while (True):
				i = i + 1
				namekey = 'tivo' + str(i) + '.name'
				tsnkey = 'tivo' + str(i) +  '.tsn'
				if cfg.has_option(section, namekey) and cfg.has_option(section, tsnkey):
					tlist.append({'name' : cfg.get(section, namekey),
									'tsn' : cfg.get(section, tsnkey).translate(allchars, '-')})
				else:
					break
				
		if sortflag:
			self.tivos = sorted(tlist, cmp=cmptivo)
		else:
			self.tivos = tlist[:]

	# load up pytivo and shares information from config and from pytivo config(s)
	def loadShares(self, cfg):
		self.shares = []
		
		s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		s.connect(('4.2.2.1', 123))
		defip = s.getsockname()[0]
	
		section = 'pytivos'
		if cfg.has_section(section):
			i = 0
			while (True):
				i = i + 1
				key = "pytivo" + str(i) + ".config"
				if not cfg.has_option(section, key): break
				cfgfile = cfg.get(section, key)
				
				sep = None
				sepkey = 'pytivo' + str(i) + '.sep'
				if cfg.has_option(section, sepkey): sep = cfg.get(section, sepkey)
				
				ip = defip
				key = "pytivo" + str(i) + ".ip"
				if cfg.has_option(section, key):
					ip = cfg.get(section, key)

				port = None				
				key = "pytivo" + str(i) + ".port"
				if cfg.has_option(section, key):
					port = cfg.get(section, key)
					
				key = "pytivo" + str(i) + ".skip"
				skip = []
				if cfg.has_option(section, key):
					sk = cfg.get(section, key).split(",")
					skip = [s.strip() for s in sk]
				
				self.loadPyTivoConfig(cfgfile, ip, port, sep, skip)
					

	# parse a pytivo config looking for shares				
	def loadPyTivoConfig(self, cf, ip, defport, sep, skip):
		pyconfig = ConfigParser.ConfigParser()
		if not pyconfig.read(cf):
			raise ConfigError("ERROR: pyTivo config file " + cf + " does not exist.")

		port = defport
		if pyconfig.has_option('Server', 'port') : port = pyconfig.get('Server', 'port')
		
		if port == None:
			raise ConfigError("Neither main config file nor pytivo config file " + cf + " has port number specified")
		
		for section in pyconfig.sections():
			if not section in skip:
				if (pyconfig.has_option(section, "type")
						and (pyconfig.get(section, "type") == "video" or pyconfig.get(section, "type") == "dvdvideo")
						and	pyconfig.has_option(section, 'path')):
					path = pyconfig.get(section, 'path')
					self.shares.append({'name' : section,
							'ip' : ip,
							'port' : port,
							'path' : path,
							'sep' : sep})
	def handle_key_press(self, keynum, rawcode):
		if keynum == KEY_THUMBSDOWN:
			self.tdcount += 1
			if self.tdcount == 3:
				self.mb = MessageBox(self.app, "Rebuilding Cache...",
					"Please Wait",
					'alert',
					[[[KEY_TIVO], 0]])

				self.send_key(KEY_TIVO, MYKEY_REBUILDCACHE)
				self.rebuildingCache = True
				return

			self.sound('thumbsup')
			return
		else:
			self.tdcount = 0
			
		if keynum == KEY_TIVO and rawcode == MYKEY_REBUILDCACHE:
			self.rootNode = self.vc.build()
			self.vcChanged = True

			self.mb.close()
			self.reStart()
			return

		if self.msgbox:
			self.msgbox.handlekeypress(keynum, rawcode)
			
		elif self.vwInfo.isVisible:
			snd = 'updown'
			if keynum in [ KEY_LEFT, KEY_CLEAR, KEY_INFO ]:
				self.vwInfo.hide()
				
			elif keynum in [ KEY_DOWN, KEY_CHANNELDOWN ]:
				if not self.vwInfo.pagedown():
					snd = 'bonk'
					
			elif keynum in [ KEY_UP, KEY_CHANNELUP ]:
				if not self.vwInfo.pageup():
					snd = 'bonk'
					
			else:
				snd = 'bonk'
				
			self.sound(snd)

		elif self.push:
			if keynum == KEY_TIVO and rawcode == MYKEY_PUSHCOMPLETE:
				self.push = None
			else:
				self.push.handlekeypress(keynum, rawcode)
				
		elif self.currentItem == None and keynum not in [ KEY_LEFT, KEY_TIVO ]:
			self.sound('bonk')
				
		elif keynum == KEY_INFO:
			meta = self.currentItem.getMeta()
			if len(meta) == 0:
				snd = 'bonk'
			else:
				self.vwInfo.loadmetadata(meta)
				self.vwInfo.paint()
				self.vwInfo.show()
				snd = 'updown'
			self.sound(snd)
				
		elif self.ldm.isNavKey(keynum, rawcode):
			self.currentItem = self.ldm.Navigate(keynum, rawcode)
			self.ddm.show(self.currentItem)
			
		elif keynum == KEY_LEFT:
			self.currentNode, self.currentItem = self.ldm.Ascend()
			if self.currentNode == None:
				self.active = False
				return
			self.SubTitleView.set_text(self.currentNode.getFullTitle(),
						font=self.app.myfonts.fnt20,
						colornum=0xffffff, flags=RSRC_VALIGN_BOTTOM)
			self.ddm.show(self.currentItem)
			self.sound('updown')
			
		elif keynum in [KEY_RIGHT, KEY_SELECT]:
			if self.currentItem.getObjType() == TYPE_VIDFILE:
				self.push = Push(self, self.opts, self.currentItem)
			else:
				self.SubTitleView.set_text(self.currentItem.getFullTitle(),
								font=self.app.myfonts.fnt20,
								colornum=0xffffff, flags=RSRC_VALIGN_BOTTOM)
				self.lopts = self.currentItem.getOpts()
				self.currentNode, self.currentItem = self.ldm.Descend(self.currentItem)
			self.ddm.show(self.currentItem)
			self.sound('updown')
			
		elif keynum == KEY_CLEAR:
			if not self.deletable(self.currentItem):
				self.sound('bonk')
			else:
				MessageBox(self.app, "Delete Confirmation",
						"Press THUMBS-UP button to confirm deletion of " + 
						self.currentItem.formatDisplayText(self.lopts['dispopt']),
						'alert',
						[
						 [[KEY_THUMBSUP], MYKEY_DELETECONFIRM], 
						 [[], MYKEY_DELETECANCEL]
						])
				
		elif keynum == KEY_TIVO and rawcode == MYKEY_DELETECOMPLETE:
			pass # nothing to do here
		
		elif keynum == KEY_TIVO and rawcode == MYKEY_DELETECANCEL:
			m = MessageBox(self.app, "Delete Cancelled",
					"CANCELLED",
					'bonk',
					[[[KEY_TIVO], 0]])
			self.sleep(1)
			m.close()
		
		elif keynum == KEY_TIVO and rawcode == MYKEY_DELETECONFIRM:
			m = MessageBox(self.app, "Deleting...",
					"Please Wait",
					'updown',
					[[[KEY_TIVO], 0]])
			self.currentItem.delVideo()
			self.currentItem = self.ldm.Verify()
			self.ddm.show(self.currentItem)
			m.close()
			MessageBox(self.app, "Deleted",
					"Video/Metadata/Artwork Deleted - Press any key",
					'alert',
					[[[], MYKEY_DELETECOMPLETE]])
			self.vcChanged = True
		
		else:
			self.sound('bonk')
Exemple #43
0
    def coordinates_analysis(self, ):
        """
        Main function
        """
        coord_x, coord_y = zip(*self.coordinates)
        leftpb_x, leftpb_y = zip(*self.left_peak_border)
        rightpb_x, rightpb_y= zip(*self.right_peak_border)

        # absolute amplitude % and MAX
        relative_amplitude = []
        ampl_max = max(self.amplitudes)
        relative_amplitude[:] = [(i / ampl_max) for i in self.amplitudes]

        # create temporal Pandas DataFrame for sorting and calculation:
        temp_dataset = list(
            zip(coord_x, self.amplitudes, relative_amplitude, leftpb_x, leftpb_y, rightpb_x, rightpb_y, self.area))
        df = pd.DataFrame(data=temp_dataset,
                          columns=['Peak Time',
                                   'Amplitude',
                                   'Relative Amplitude \n (F/Fmax)',
                                   'Peak Start Time',
                                   'Peak Start Ordinate',
                                   'Peak Stop Time',
                                   'Peak Stop Ordinate',
                                   'Area'])

        # Sort data in DataFrame according to the time of peak appearance
        df_sorted = df.sort_values(['Peak Time'], ascending=True)
        df_sorted.index = range(0, len(df_sorted))  # reset indexing

        # calculate periods
        periods = []
        for i in range(1, len(df_sorted['Peak Time'])):
            periods.append(df_sorted.at[i, 'Peak Time'] - df_sorted.at[i - 1, 'Peak Time'])
        periods.insert(0, np.nan)  # add placeholder because len(periods)=len(peaks)-1

        # calculate frequencies based on calculated periods
        frequencies = []
        frequencies[:] = [(1 / i) for i in periods]

        # Analise peak start - stop time (left and right peak borders)
        peak_full_time = []
        for i in range(0, len(df_sorted['Peak Time']), 1):
            peak_full_time.append(df_sorted.at[i, 'Peak Stop Time'] - df_sorted.at[i, 'Peak Start Time'])
        peak_up_time = []
        for i in range(0, len(df_sorted['Peak Time']), 1):
            peak_up_time.append(df_sorted.at[i, 'Peak Time'] - df_sorted.at[i, 'Peak Start Time'])
        peak_down_time = []
        for i in range(0, len(df_sorted['Peak Time']), 1):
            peak_down_time.append(df_sorted.at[i, 'Peak Stop Time'] - df_sorted.at[i, 'Peak Time'])

        # Compute area under the peak using the composite trapezoidal rule.
        peak_area = []
        for i in range(0, len(df_sorted['Peak Time']), 1):
            peak_area.append(np.trapz(df_sorted.at[i, 'Area']))

        # Analise the peak decay area
        half_decay_time = []
        half_decay_amplitude = []
        for i in range(0, len(df_sorted['Peak Time']), 1):
            half_decay_ampl = df_sorted.at[i, 'Amplitude'] / 2  # calculate the half of the amplitude
            peak_index = self.x.index(df_sorted.at[i, 'Peak Time'])  # find index of the peak time
            stop_idx = self.x.index(df_sorted.at[i, 'Peak Stop Time'])  # find index of the right peak border
            data_decay_region = self.data_after_filter[peak_index:stop_idx]  # determine the amplitude region where to search for halftime decay index
            time_decay_region = self.x[peak_index:stop_idx]
            half_decay_idx = (np.abs(data_decay_region - half_decay_ampl)).argmin()  # find the closet value in data_decay_region that corresponds to the half amplitude

            half_decay_amplitude.append(half_decay_ampl)
            half_decay_time.append(time_decay_region[half_decay_idx] - df_sorted.at[i, 'Peak Time'])

        # Compute amplitude normalised to the baseline
        normalised_amplitude = []
        sg_window_frame = self.BoxSGwindowFrame.value()
        sg_polynom_degree = self.BoxSGpolynomDegree.value()
        orig_data_filtered = sig.savgol_filter(self.y, sg_window_frame, sg_polynom_degree)
        for i in range(0, len(df_sorted['Peak Time']), 1):
            start_idx = self.x.index(df_sorted.at[i, 'Peak Start Time'])
            F0 = orig_data_filtered[start_idx]
            amplitude_normed_computation = df_sorted.at[i, 'Amplitude'] / F0
            normalised_amplitude.append(amplitude_normed_computation)

        # normalised amplitude %
        relative_normalised_amplitude = []
        maxATB = max(normalised_amplitude)
        relative_normalised_amplitude[:] = [(i / maxATB) for i in normalised_amplitude]

        # normalised amplitude MAX
        normalised_amplitude_max = list(range(0, len(df_sorted['Peak Time']) - 1))
        normalised_amplitude_max[:] = [np.nan for _ in normalised_amplitude_max]
        normalised_amplitude_max.insert(0, maxATB)

        # add file name as first column
        file_name = list(range(0, len(df_sorted['Peak Time']) - 1))
        file_name[:] = [np.nan for _ in file_name]
        file_name.insert(0, self.graph_name)

        # add maximum amplitude
        absolute_amplitude_max = list(range(0, len(df_sorted['Peak Time']) - 1))
        absolute_amplitude_max[:] = [np.nan for _ in absolute_amplitude_max]
        absolute_amplitude_max.insert(0, max(df_sorted['Amplitude']))

        # peak sorting
        big_peaks_number = [p for p in self.amplitudes if (p > ampl_max * 0.66)]
        medium_peaks_number = [p for p in self.amplitudes if (p > ampl_max * 0.33 and p <= ampl_max * 0.66)]
        small_peaks_number = [p for p in self.amplitudes if (p > 0 and p <= ampl_max * 0.33)]

        big_peaks_frequency = list(range(0, len(df_sorted['Peak Time']) - 1))
        big_peaks_frequency[:] = [np.nan for _ in big_peaks_frequency]
        big_peaks_frequency.insert(0, len(big_peaks_number) / (self.x[-1] - self.x[0]))

        medium_peaks_frequency = list(range(0, len(df_sorted['Peak Time']) - 1))
        medium_peaks_frequency[:] = [np.nan for _ in medium_peaks_frequency]
        medium_peaks_frequency.insert(0, len(medium_peaks_number) / (self.x[-1] - self.x[0]))

        small_peaks_frequency = list(range(0, len(df_sorted['Peak Time']) - 1))
        small_peaks_frequency[:] = [np.nan for _ in small_peaks_frequency]
        small_peaks_frequency.insert(0, len(small_peaks_number) / (self.x[-1] - self.x[0]))

        final_dataset = list(zip(file_name,
                                df_sorted['Peak Time'],
                                df_sorted['Amplitude'],
                                df_sorted['Relative Amplitude \n (F/Fmax)'],
                                absolute_amplitude_max,
                                normalised_amplitude,
                                relative_normalised_amplitude,
                                normalised_amplitude_max,
                                periods,
                                frequencies,
                                half_decay_time,
                                half_decay_amplitude,
                                df_sorted['Peak Start Time'],
                                df_sorted['Peak Start Ordinate'],
                                df_sorted['Peak Stop Time'],
                                df_sorted['Peak Stop Ordinate'],
                                peak_up_time,
                                peak_down_time,
                                peak_full_time,
                                peak_area,
                                big_peaks_frequency,
                                medium_peaks_frequency,
                                small_peaks_frequency))

        final_dataframe = pd.DataFrame(data=final_dataset,
                                       columns=['File name',
                                                'Peak time',
                                                'Absolute amplitude',
                                                'Absolute amplitude (%)',
                                                'Absolute amplitude MAX',
                                                'Normalised amplitude',
                                                'Normalised amplitude (%)',
                                                'Normalised amplitude MAX',
                                                'Period',
                                                'Frequency',
                                                'Half-decay time',
                                                'Half-decay amplitude',
                                                'Start time',
                                                'Start ordinate',
                                                'Stop time',
                                                'Stop ordinate',
                                                'Ascending time',
                                                'Decay time',
                                                'Full peak time',
                                                'AUC',
                                                'Big peaks, Hz',
                                                'Mid peaks, Hz',
                                                'Small peaks, Hz'])

        # specify data for export acording to the settings tab in GUI
        # and append current analysed dataset to existing ones
        try:
            columns_to_delete_for_export = []
            if not self.chbxFileName.isChecked(): columns_to_delete_for_export.append('File name')
            if not self.chbxPeakTime.isChecked(): columns_to_delete_for_export.append('Peak time')
            if not self.chbxAmplAbs.isChecked(): columns_to_delete_for_export.append('Absolute amplitude')
            if not self.chbxAmplAbsRel.isChecked(): columns_to_delete_for_export.append('Absolute amplitude (%)')
            if not self.chbxAmplAbsMax.isChecked(): columns_to_delete_for_export.append('Absolute amplitude MAX')
            if not self.chbxAmplNorm.isChecked(): columns_to_delete_for_export.append('Normalised amplitude')
            if not self.chbxAmplNormRel.isChecked(): columns_to_delete_for_export.append('Normalised amplitude (%)')
            if not self.chbxAmplNormMax.isChecked(): columns_to_delete_for_export.append('Normalised amplitude MAX')
            if not self.chbxPeriod.isChecked(): columns_to_delete_for_export.append('Period')
            if not self.chbxFreq.isChecked(): columns_to_delete_for_export.append('Frequency')
            if not self.chbxHalfDecayTime.isChecked(): columns_to_delete_for_export.append('Half-decay time')
            if not self.chbxHalfDecayAmpl.isChecked(): columns_to_delete_for_export.append('Half-decay amplitude')
            if not self.chbxLeftBorderTime.isChecked(): columns_to_delete_for_export.append('Start time')
            if not self.chbxLeftBorder.isChecked(): columns_to_delete_for_export.append('Start ordinate')
            if not self.chbxRightBorderTime.isChecked(): columns_to_delete_for_export.append('Stop time')
            if not self.chbxRightBorder.isChecked(): columns_to_delete_for_export.append('Stop ordinate')
            if not self.chbxTimeToPeak.isChecked(): columns_to_delete_for_export.append('Ascending time')
            if not self.chbxDecayTime.isChecked(): columns_to_delete_for_export.append('Decay time')
            if not self.chbxFullPeakTime.isChecked(): columns_to_delete_for_export.append('Full peak time')
            if not self.chbxAUC.isChecked(): columns_to_delete_for_export.append('AUC')
            if not self.chbxSmallPeaks.isChecked(): columns_to_delete_for_export.append('Big peaks, Hz')
            if not self.chbxMidPeaks.isChecked(): columns_to_delete_for_export.append('Mid peaks, Hz')
            if not self.chbxBigPeaks.isChecked(): columns_to_delete_for_export.append('Small peaks, Hz')
            final_dataframe.drop(columns_to_delete_for_export, axis=1, inplace=True)

            self.multiple_data_sets = self.multiple_data_sets.append(final_dataframe)

            if self.chbxSaveFig.isChecked():
                os.makedirs('_Figures', exist_ok=True)
                dpi = self.BoxDPI.value()
                plt.savefig(os.path.join('_Figures', 'Fig_{figName}.png'.format(figName=self.graph_name)), dpi=dpi)

            del df
            del df_sorted
            del final_dataframe

            dialog = MessageBox.question(self, '', "Current dataset was analysed \n and added to previous ones (if exist). \n Would you like to load next file? ",
                                         QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
            if dialog == QtGui.QMessageBox.Yes:
                self.load_file()
            else:
                self.rmmpl()
                self.BtnSaveFullDataset.setStyleSheet("background-color: #7CF2BD")
                self.BtnLoadFile.setStyleSheet("background-color: #7CF2BD")

        except:
            message = MessageBox()
            message.about(self, 'Warning!', "Data were not added to existing dataset. \n Plese be sure that you did not change the output settings.")
Exemple #44
0
class GCWii(Ui_MainWindow):
    def __init__(self, source='', destination='', clear_destination=False):
        super(GCWii, self).__init__()
        self.export_in_progress = False
        app = QtWidgets.QApplication(sys.argv)
        self.MainWindow = QtWidgets.QMainWindow()
        self.max_treads = QThread.idealThreadCount()
        self.setupUi(self.MainWindow)
        self.msg = MessageBox()
        self.manager = GCWiiManager()
        self.default_box_artwork = str(os.path.join('images',
                                                    'blanc-case.png'))
        self.default_disc_artwork = str(
            os.path.join('images', 'blanc-disc.png'))
        self.source_directory = source
        self.source_game_collection = {}
        self.destination_directory = destination
        self.clear_destination = clear_destination
        self.destination_game_collection = {}
        self.box_artwork_path = os.path.join(os.getcwd(), 'images', 'cover3D')
        self.disc_artwork_path = os.path.join(os.getcwd(), 'images', 'disc')
        self.current_selection = {}
        self.games_to_export = {}
        self.setup_widgets()
        self.setup_actions()
        self.MainWindow.show()
        if self.source_directory:
            self.update_source_list()
        if self.destination_directory:
            self.update_destination_list()
        sys.exit(app.exec_())

    def setup_widgets(self):
        self.source_btn.clicked.connect(lambda: self.update_source_list(True))
        self.destination_btn.clicked.connect(
            lambda: self.update_destination_list(True))
        self.export_btn.clicked.connect(self.export_all)
        self.listView_source.clicked.connect(
            lambda: self.update_art_work('source'))
        self.listView_destination.clicked.connect(
            lambda: self.update_art_work('destination'))
        self.listView_destination.addAction(self.action_reload_destination)
        self.listView_destination.addAction(
            self.action_select_folder_destination)
        self.listView_destination.addAction(
            self.action_delete_selected_in_destination)
        self.listView_destination.addAction(
            self.action_delete_all_items_in_destination)
        self.listView_source.addAction(self.action_reload_source)
        self.listView_source.addAction(self.action_select_folder_source)
        self.listView_source.addAction(self.action_export_selected)
        self.exit_btn.clicked.connect(self.quit)
        self.exportSelected_btn.clicked.connect(self.export_selection)
        self.cancel_btn.setEnabled(False)
        self.cancel_btn.clicked.connect(self.cancel_copy)
        self.label_box.setPixmap(QtGui.QPixmap(self.default_box_artwork))
        self.label_disc.setPixmap(QtGui.QPixmap(self.default_disc_artwork))
        self.progressBar_fileProgress.setVisible(False)
        self.progressBar_destination.setVisible(False)

    def setup_actions(self):
        # Source
        self.action_reload_source.triggered.connect(self.update_source_list)
        self.action_select_folder_source.triggered.connect(
            lambda: self.update_source_list(True))
        self.action_export_selected.triggered.connect(self.export_selection)

        # Destination
        self.action_reload_destination.triggered.connect(
            self.update_destination_list)
        self.action_select_folder_destination.triggered.connect(
            lambda: self.update_destination_list(True))
        self.action_delete_selected_in_destination.triggered.connect(
            self.delete_selected_in_destination)
        self.action_delete_all_items_in_destination.triggered.connect(
            self.delete_all_in_destination)

    def delete_all_in_destination(self):
        self.manager.delete_all_files_in_directory(self.destination_directory)
        self.update_destination_list()

    def delete_selected_in_destination(self):
        for item in self.listView_destination.selectedIndexes():
            title = item.data()
            game = self.manager.get_game_from_collection_by_title(
                title, self.destination_game_collection)
            if game:
                self.manager.delete_all_files_in_directory(game["path"])
        self.update_destination_list()

    def export_selection(self):
        """ Export games marked on the source list_name """
        results = dict()
        for index in self.listView_source.selectedIndexes():
            title = QModelIndex.data(index)
            for key in self.source_game_collection.keys():
                if self.source_game_collection[key]["title"] == title:
                    results[key] = self.source_game_collection[key]
        self.games_to_export = results
        self.export()

    def export_all(self):
        self.games_to_export = self.manager.get_collection_diff(
            self.source_game_collection, self.destination_game_collection)
        if not self.games_to_export:
            return self.msg.info("Nothing to export")
        self.export()

    def update_status_info(self, text=None):
        if not text:
            self.MainWindow.statusBar().clearMessage()
            return self.MainWindow.statusBar().setVisible(False)
        if not self.MainWindow.statusBar().isVisible():
            self.MainWindow.statusBar().setVisible(True)
        self.MainWindow.statusBar().showMessage(text)

    def update_global_progress_bar(self, value):
        self.progressBar_destination.setValue(value)

    def update_file_progress_bar(self, value):
        self.progressBar_fileProgress.setValue(value)

    def reset_progress_bars(self):
        self.progressBar_fileProgress.setValue(0)
        self.progressBar_destination.setValue(0)

    def hide_progress_bars(self):
        self.progressBar_fileProgress.setVisible(False)
        self.progressBar_destination.setVisible(False)

    def show_progress_bars(self):
        self.progressBar_fileProgress.setVisible(True)
        self.progressBar_destination.setVisible(True)

    def update_art_work(self, list_name):
        identifier = self.get_selection(list_name)
        box = self.default_box_artwork
        disc = self.default_disc_artwork
        if not identifier:
            return
        region = self.manager.get_game_region(identifier)
        try:
            if GameTDBclient.get_art_work(region, identifier, True, None):
                box = str(
                    os.path.join(self.box_artwork_path, region,
                                 identifier + ".png"))
            if GameTDBclient.get_art_work(region, identifier, None, True):
                disc = str(
                    os.path.join(self.disc_artwork_path, region,
                                 identifier + ".png"))
        except GameTDBclient.ErrorFetchingData:
            print("Unable to fetch artwork for game id: '{}' region: '{}'".
                  format(identifier, region))
        self.label_box.setPixmap(QtGui.QPixmap(box))
        self.label_disc.setPixmap(QtGui.QPixmap(disc))

    def get_selection(self, list_name):
        games_collection = dict()
        model = None
        if list_name == 'source':
            model = self.listView_source.currentIndex()
            games_collection = self.source_game_collection
        elif list_name == 'destination':
            model = self.listView_destination.currentIndex()
            games_collection = self.destination_game_collection
        title = QModelIndex.data(model)
        for identifier in games_collection:
            if games_collection[identifier]["title"] == title:
                return identifier

    def select_directory(self):
        return QtWidgets.QFileDialog.getExistingDirectory(self.MainWindow)

    def update_source_list(self, select=False):
        try:
            if select:
                directory = self.select_directory()
                if not directory:
                    return
                self.source_directory = directory
            if not self.source_directory:
                return
            list_of_found_files = self.manager.find_supported_files(
                self.source_directory)
            self.source_game_collection = self.manager.generate_game_collection(
                list_of_found_files)
            self.label_source.setText('Source: ' + self.source_directory)
            list_of_titles = self.manager.get_sorted_game_titles(
                self.source_game_collection)
            if not list_of_titles:
                return self.listView_source.setModel(
                    QStringListModel(['No Wii or GameCube game found']))
            self.listView_source.setModel(QStringListModel(list_of_titles))
            self.listView_source.selectionModel().selectionChanged.connect(
                lambda: self.update_art_work('source'))
            self.listView_source.setEditTriggers(
                QtWidgets.QAbstractItemView.NoEditTriggers)

        except PermissionError as err:
            details = f"Directory '{self.source_directory}' can not be read"
            self.msg.warning('Directory not readable', details, str(err))

    def update_destination_list(self, select=False):
        try:
            while select:
                directory = self.select_directory()
                if not directory:
                    return
                if not self.manager.test_directory_writeable(directory):
                    response = self.msg.question(
                        "Directory is not writeable.\nDo you want to select a different directory?"
                    )
                    if not response:
                        return
                    continue
                select = False
                self.destination_directory = directory
            if not self.destination_directory:
                return
            list_of_found_files = self.manager.find_supported_files(
                self.destination_directory)
            self.destination_game_collection = self.manager.generate_game_collection(
                list_of_found_files)
            self.label_destination.setText('Destination: ' +
                                           self.destination_directory)
            self.destination_directory = self.destination_directory
            list_of_titles = self.manager.get_sorted_game_titles(
                self.destination_game_collection)
            if not list_of_titles:
                return self.listView_destination.setModel(
                    QStringListModel(['No Wii or GameCube game found']))
            self.listView_destination.setModel(
                QStringListModel(list_of_titles))
            self.listView_destination.selectionModel(
            ).selectionChanged.connect(
                lambda: self.update_art_work('destination'))
            self.listView_source.setEditTriggers(
                QtWidgets.QAbstractItemView.NoEditTriggers)
        except PermissionError as err:
            details = f"Directory '{self.destination_directory}' can not be read"
            self.msg.warning('Directory not readable', details, str(err))

    def export(self):
        if not self.source_game_collection:
            return self.msg.info("Source list is empty")
        if not self.source_directory:
            return self.msg.info("Please select source folder")
        if not self.destination_directory:
            return self.msg.info("Please select destination folder")
        if self.destination_directory == self.source_directory:
            return self.msg.warning(
                "Source and destination should not be the same directory.")
        if not self.games_to_export:
            return self.msg.info(
                "Please select games from source or click \"Export All\"")
        print("\nProcessing")
        self.export_btn.setDisabled(True)
        self.exportSelected_btn.setDisabled(True)
        self.source_btn.setDisabled(True)
        self.destination_btn.setDisabled(True)
        self.cancel_btn.setEnabled(True)
        self.show_progress_bars()

        # Create a QThread object
        self.thread = QThread()

        # Create a worker object
        self.worker = CopyWorker(self.games_to_export,
                                 self.destination_directory)

        # Move worker to the thread
        self.worker.moveToThread(self.thread)

        # Connect signals and slots
        self.thread.started.connect(self.worker.run)
        self.worker.thread_file_progress.progress.connect(
            self.update_file_progress_bar)
        self.worker.progress.connect(self.update_global_progress_bar)
        self.worker.processing.connect(self.handle_worker_processing_update)
        self.worker.finished.connect(self.handle_worker_finished)
        self.worker.error.connect(self.msg.critical)

        self.thread.start()

    def handle_worker_processing_update(self, info=None):
        self.update_status_info(info)
        self.update_destination_list()

    def handle_worker_finished(self):
        print("\nFinished")
        self.update_destination_list()
        self.reset_progress_bars()
        self.hide_progress_bars()
        self.worker.quit()
        self.thread.quit()
        self.export_btn.setDisabled(False)
        self.exportSelected_btn.setDisabled(False)
        self.source_btn.setDisabled(False)
        self.destination_btn.setDisabled(False)
        self.cancel_btn.setEnabled(False)
        self.cancel_btn.setText("Cancel")

    def quit(self):
        if self.clear_destination:
            self.manager.delete_all_files_in_directory(
                self.destination_directory)
        sys.exit(0)

    def cancel_copy(self):
        try:
            self.worker.stop()
            self.thread.quit()
            self.cancel_btn.setText("Cancelling...")
            self.cancel_btn.setEnabled(False)
            print("\nCanceling")
        except AttributeError:
            self.msg.info("There is nothing to cancel. ")
    def coordinates_analysis(self, ):
        """
        Main function
        """
        coord_x, coord_y = zip(*self.coordinates)
        leftpb_x, leftpb_y = zip(*self.left_peak_border)
        rightpb_x, rightpb_y= zip(*self.right_peak_border)

        # absolute amplitude % and MAX
        relative_amplitude = []
        ampl_max = max(self.amplitudes)
        relative_amplitude[:] = [(i / ampl_max) for i in self.amplitudes]

        # create temporal Pandas DataFrame for sorting and calculation:
        temp_dataset = list(
            zip(coord_x, self.amplitudes, relative_amplitude, leftpb_x, leftpb_y, rightpb_x, rightpb_y, self.area))
        df = pd.DataFrame(data=temp_dataset,
                          columns=['Peak Time',
                                   'Amplitude',
                                   'Relative Amplitude \n (F/Fmax)',
                                   'Peak Start Time',
                                   'Peak Start Ordinate',
                                   'Peak Stop Time',
                                   'Peak Stop Ordinate',
                                   'Area'])

        # Sort data in DataFrame according to the time of peak appearance
        df_sorted = df.sort_values(['Peak Time'], ascending=True)
        df_sorted.index = range(0, len(df_sorted))  # reset indexing

        # calculate periods
        periods = []
        for i in range(1, len(df_sorted['Peak Time'])):
            periods.append(df_sorted.at[i, 'Peak Time'] - df_sorted.at[i - 1, 'Peak Time'])
        periods.insert(0, np.nan)  # add placeholder because len(periods)=len(peaks)-1

        # calculate frequencies based on calculated periods
        frequencies = []
        frequencies[:] = [(1 / i) for i in periods]

        # Analise peak start - stop time (left and right peak borders)
        peak_full_time = []
        for i in range(0, len(df_sorted['Peak Time']), 1):
            peak_full_time.append(df_sorted.at[i, 'Peak Stop Time'] - df_sorted.at[i, 'Peak Start Time'])
        peak_up_time = []
        for i in range(0, len(df_sorted['Peak Time']), 1):
            peak_up_time.append(df_sorted.at[i, 'Peak Time'] - df_sorted.at[i, 'Peak Start Time'])
        peak_down_time = []
        for i in range(0, len(df_sorted['Peak Time']), 1):
            peak_down_time.append(df_sorted.at[i, 'Peak Stop Time'] - df_sorted.at[i, 'Peak Time'])

        # Compute area under the peak using the composite trapezoidal rule.
        peak_area = []
        for i in range(0, len(df_sorted['Peak Time']), 1):
            peak_area.append(np.trapz(df_sorted.at[i, 'Area']))

        # Analise the peak decay area
        half_decay_time = []
        half_decay_amplitude = []
        for i in range(0, len(df_sorted['Peak Time']), 1):
            half_decay_ampl = df_sorted.at[i, 'Amplitude'] / 2  # calculate the half of the amplitude
            peak_index = self.x.index(df_sorted.at[i, 'Peak Time'])  # find index of the peak time
            stop_idx = self.x.index(df_sorted.at[i, 'Peak Stop Time'])  # find index of the right peak border
            data_decay_region = self.data_after_filter[peak_index:stop_idx]  # determine the amplitude region where to search for halftime decay index
            time_decay_region = self.x[peak_index:stop_idx]
            half_decay_idx = (np.abs(data_decay_region - half_decay_ampl)).argmin()  # find the closet value in data_decay_region that corresponds to the half amplitude

            half_decay_amplitude.append(half_decay_ampl)
            half_decay_time.append(time_decay_region[half_decay_idx] - df_sorted.at[i, 'Peak Time'])

        # Compute amplitude normalised to the baseline
        normalised_amplitude = []
        sg_window_frame = self.BoxSGwindowFrame.value()
        sg_polynom_degree = self.BoxSGpolynomDegree.value()
        orig_data_filtered = sig.savgol_filter(self.y, sg_window_frame, sg_polynom_degree)
        for i in range(0, len(df_sorted['Peak Time']), 1):
            start_idx = self.x.index(df_sorted.at[i, 'Peak Start Time'])
            F0 = orig_data_filtered[start_idx]
            amplitude_normed_computation = df_sorted.at[i, 'Amplitude'] / F0
            normalised_amplitude.append(amplitude_normed_computation)

        # normalised amplitude %
        relative_normalised_amplitude = []
        maxATB = max(normalised_amplitude)
        relative_normalised_amplitude[:] = [(i / maxATB) for i in normalised_amplitude]

        # normalised amplitude MAX
        normalised_amplitude_max = list(range(0, len(df_sorted['Peak Time']) - 1))
        normalised_amplitude_max[:] = [np.nan for _ in normalised_amplitude_max]
        normalised_amplitude_max.insert(0, maxATB)

        # add file name as first column
        file_name = list(range(0, len(df_sorted['Peak Time']) - 1))
        file_name[:] = [np.nan for _ in file_name]
        file_name.insert(0, self.graph_name)

        # add maximum amplitude
        absolute_amplitude_max = list(range(0, len(df_sorted['Peak Time']) - 1))
        absolute_amplitude_max[:] = [np.nan for _ in absolute_amplitude_max]
        absolute_amplitude_max.insert(0, max(df_sorted['Amplitude']))

        # peak sorting
        big_peaks_number = [p for p in self.amplitudes if (p > ampl_max * 0.66)]
        medium_peaks_number = [p for p in self.amplitudes if (p > ampl_max * 0.33 and p <= ampl_max * 0.66)]
        small_peaks_number = [p for p in self.amplitudes if (p > 0 and p <= ampl_max * 0.33)]

        big_peaks_frequency = list(range(0, len(df_sorted['Peak Time']) - 1))
        big_peaks_frequency[:] = [np.nan for _ in big_peaks_frequency]
        big_peaks_frequency.insert(0, len(big_peaks_number) / (self.x[-1] - self.x[0]))

        medium_peaks_frequency = list(range(0, len(df_sorted['Peak Time']) - 1))
        medium_peaks_frequency[:] = [np.nan for _ in medium_peaks_frequency]
        medium_peaks_frequency.insert(0, len(medium_peaks_number) / (self.x[-1] - self.x[0]))

        small_peaks_frequency = list(range(0, len(df_sorted['Peak Time']) - 1))
        small_peaks_frequency[:] = [np.nan for _ in small_peaks_frequency]
        small_peaks_frequency.insert(0, len(small_peaks_number) / (self.x[-1] - self.x[0]))

        final_dataset = list(zip(file_name,
                                df_sorted['Peak Time'],
                                df_sorted['Amplitude'],
                                df_sorted['Relative Amplitude \n (F/Fmax)'],
                                absolute_amplitude_max,
                                normalised_amplitude,
                                relative_normalised_amplitude,
                                normalised_amplitude_max,
                                periods,
                                frequencies,
                                half_decay_time,
                                half_decay_amplitude,
                                df_sorted['Peak Start Time'],
                                df_sorted['Peak Start Ordinate'],
                                df_sorted['Peak Stop Time'],
                                df_sorted['Peak Stop Ordinate'],
                                peak_up_time,
                                peak_down_time,
                                peak_full_time,
                                peak_area,
                                big_peaks_frequency,
                                medium_peaks_frequency,
                                small_peaks_frequency))

        final_dataframe = pd.DataFrame(data=final_dataset,
                                       columns=['File name',
                                                'Peak time',
                                                'Absolute amplitude',
                                                'Absolute amplitude (%)',
                                                'Absolute amplitude MAX',
                                                'Normalised amplitude',
                                                'Normalised amplitude (%)',
                                                'Normalised amplitude MAX',
                                                'Period',
                                                'Frequency',
                                                'Half-decay time',
                                                'Half-decay amplitude',
                                                'Start time',
                                                'Start ordinate',
                                                'Stop time',
                                                'Stop ordinate',
                                                'Ascending time',
                                                'Decay time',
                                                'Full peak time',
                                                'AUC',
                                                'Big peaks, Hz',
                                                'Mid peaks, Hz',
                                                'Small peaks, Hz'])

        # specify data for export acording to the settings tab in GUI
        # and append current analysed dataset to existing ones
        try:
            columns_to_delete_for_export = []
            if not self.chbxFileName.isChecked(): columns_to_delete_for_export.append('File name')
            if not self.chbxPeakTime.isChecked(): columns_to_delete_for_export.append('Peak time')
            if not self.chbxAmplAbs.isChecked(): columns_to_delete_for_export.append('Absolute amplitude')
            if not self.chbxAmplAbsRel.isChecked(): columns_to_delete_for_export.append('Absolute amplitude (%)')
            if not self.chbxAmplAbsMax.isChecked(): columns_to_delete_for_export.append('Absolute amplitude MAX')
            if not self.chbxAmplNorm.isChecked(): columns_to_delete_for_export.append('Normalised amplitude')
            if not self.chbxAmplNormRel.isChecked(): columns_to_delete_for_export.append('Normalised amplitude (%)')
            if not self.chbxAmplNormMax.isChecked(): columns_to_delete_for_export.append('Normalised amplitude MAX')
            if not self.chbxPeriod.isChecked(): columns_to_delete_for_export.append('Period')
            if not self.chbxFreq.isChecked(): columns_to_delete_for_export.append('Frequency')
            if not self.chbxHalfDecayTime.isChecked(): columns_to_delete_for_export.append('Half-decay time')
            if not self.chbxHalfDecayAmpl.isChecked(): columns_to_delete_for_export.append('Half-decay amplitude')
            if not self.chbxLeftBorderTime.isChecked(): columns_to_delete_for_export.append('Start time')
            if not self.chbxLeftBorder.isChecked(): columns_to_delete_for_export.append('Start ordinate')
            if not self.chbxRightBorderTime.isChecked(): columns_to_delete_for_export.append('Stop time')
            if not self.chbxRightBorder.isChecked(): columns_to_delete_for_export.append('Stop ordinate')
            if not self.chbxTimeToPeak.isChecked(): columns_to_delete_for_export.append('Ascending time')
            if not self.chbxDecayTime.isChecked(): columns_to_delete_for_export.append('Decay time')
            if not self.chbxFullPeakTime.isChecked(): columns_to_delete_for_export.append('Full peak time')
            if not self.chbxAUC.isChecked(): columns_to_delete_for_export.append('AUC')
            if not self.chbxSmallPeaks.isChecked(): columns_to_delete_for_export.append('Big peaks, Hz')
            if not self.chbxMidPeaks.isChecked(): columns_to_delete_for_export.append('Mid peaks, Hz')
            if not self.chbxBigPeaks.isChecked(): columns_to_delete_for_export.append('Small peaks, Hz')
            final_dataframe.drop(columns_to_delete_for_export, axis=1, inplace=True)

            self.multiple_data_sets = self.multiple_data_sets.append(final_dataframe)

            if self.chbxSaveFig.isChecked():
                os.makedirs('_Figures', exist_ok=True)
                dpi = self.BoxDPI.value()
                plt.savefig(os.path.join('_Figures', 'Fig_{figName}.png'.format(figName=self.graph_name)), dpi=dpi)

            del df
            del df_sorted
            del final_dataframe

            dialog = MessageBox.question(self, '', "Current dataset was analysed \n and added to previous ones (if exist). \n Would you like to load next file? ",
                                         QMessageBox.Yes, QMessageBox.No)
            if dialog == QMessageBox.Yes:
                self.load_file()
            else:
                self.rmmpl()
                self.BtnSaveFullDataset.setStyleSheet("background-color: #7CF2BD")
                self.BtnLoadFile.setStyleSheet("background-color: #7CF2BD")

        except:
            message = MessageBox()
            message.about(self, 'Warning!', "Data were not added to existing dataset. \n Plese be sure that you did not change the output settings.")
Exemple #46
0
    def displayDialog(self, message):
        from MessageBox import MessageBox
        messageBox = MessageBox(style=MessageBox.ICON_WARNING)
        messageBox.setText("MakeHazard")
        messageBox.setMessage(message)
        messageBox.setButtonLabels(["Continue Merge", "Cancel Merge"])
        messageBox.setDefaultIndex(1)
        if (messageBox.open() == 0):
            self.continueCommand()
        else:
            self.cancelCommand()

        return
Exemple #47
0
class MayaSVN:
    #Class Contructor
    def __init__(self):
        #Setup Debugging Variables for outside of Maya
        self.maya_enabled = True
        #Setup Paths
        self.get_maya_project_path()
        svnPath = self.mayaProjectPath + "svn"
        #Setup pysvn
        self.client = pysvn.Client(svnPath)
        self.client.callback_get_login = self.get_login
        self.client.callback_ssl_server_trust_prompt = self.ssl_server_trust_prompt
        #Setup Message Box
        pt.initializePumpThread()
        app = QtGui.QApplication(sys.argv)
        self.msgBox = MessageBox()
        #Testing Variables
        self.svnURL = "https://192.168.0.22:8443/svn/Dalek/trunk/"

    #Get Project Path from Maya
    def get_maya_project_path(self):
        if(self.maya_enabled):
            self.mayaProjectPath = "E:\\MayaSVN\\testProject\\"
            #self.mayaProjectPath =  cmds.workspace(q=True,rd=True)
        else:
            self.mayaProjectPath = "E:\\MayaSVN\\testProject\\"
    
    #SVN Callbacks
    def get_login( self,realm, username, may_save):
        #Open Dialog ask for username & pass
        username, password = self.login_dialog()
        dialogRet = True
        return dialogRet, username, password, True

    def ssl_server_trust_prompt( self,trust_dict ):
        return True, 3, True

    #SVN Functions
    #Checkout project files from SVN
    def checkoutProject(self):
        #Open dialog for URL & Path
        url, path = self.checkout_dialog()
        #Perform SVN Checkout
        print "Started Checkout"
        self.client.checkout(url,path)
        print "Checkout Completed"
        self.msgBox.setMessage("SVN Checkout Completed")
        self.msgBox.showMessageBox()
        #Set Maya Project to path
        #

    #Perform an update of SVN Files
    def updateSVN(self):
        self.client.update(self.mayaProjectPath)
        print "SVN Update Completed"

    #Open file in Maya, SVN update & lock file
    def openFile(self,filename):
        #Update SVN before opening file
        filepath = self.mayaProjectPath + filename
        self.updateSVN()
        #Lock file on SVN so other users cant edit
        self.client.lock(filepath,'Maya Opened By user')
        #Open File in Maya
        #
        print "File Opened"

    #Save file commit to svn & unlock
    def saveFile(self, filename,comment):
        #Save & Close File in Maya
        #
        
        #Update SVN before saving file
        filepath = self.mayaProjectPath + filename
        self.updateSVN()
        #Work out whether this file is already under version control
        statusList = self.client.status(filepath)
        if(statusList):
            if(statusList[0].is_versioned == False):
                #Add New File to SVN
                self.client.add(filepath)
                print "New File Added to Repository"
            else:
                #Unlock so others may edit
                self.client.unlock(filepath)
            #Submit updated file to SVN
            self.client.checkin(filepath,comment)
            print "Check In Complete"
        else:
            print "Invalid File"

    #Import a Maya project into SVN
    def importProject(self):
        #Update Project Path Variable
        self.get_maya_project_path()
        #Import all project files into SVN
        url, path = self.import_dialog()
        self.client.import_(self.mayaProjectPath,url,'New Project Commit',recurse=True)
        print "Import Completed"

    #Dialogs
    #Dialog for login to SVN
    def login_dialog(self):
        global app
        if(self.maya_enabled):
            app = QtGui.QApplication(sys.argv)
            login = LoginDialog()
            login.show()
            time.sleep(0.02)
            app.exec_()
        return login.getLoginDetails()

    #Dialog for checkout from SVN - Asks for URL & Path
    def checkout_dialog(self):
        return self.svnURL,self.mayaProjectPath

    #Dialog for import into SVN - Asks for URL & Path
    def import_dialog(self):
        return self.svnURL,self.mayaProjectPath
Exemple #48
0
class BuddyItem(QTreeWidgetItem):
	"""
	BuddyItem implements the view of a Buddy from the Roster
	"""

	dialog = None
	msg = None

	def __init__(self, parent, jid, con):
		QTreeWidgetItem.__init__(self, parent, [jid], QTreeWidgetItem.UserType+1)

		# QTreeWidgetItem configuration
		self.setFlags(Qt.ItemIsDragEnabled | Qt.ItemIsEnabled) # we can move a contact
		self.parent = parent
		self.jid = jid
		self.name = jid
		self.setStatus(STATUS.unavailable)
		self.connectionThread = con
	
	def setStatus(self, status):
		self.status = status
		if self.status not in range(6):
			self.status = STATUS.unavailable
		settings = QSettings("Trunat", "PyTalk")
		settings.beginGroup("preferences")
		repStatus = settings.value("images_status", QVariant("images/status/")).toString()
		fileStatus = settings.value(str(self.status), QVariant(STATUS_IMAGE[self.status])).toString()
		settings.endGroup()
		self.setIcon(0, QIcon(repStatus+fileStatus))

	def setName(self, name):
		if name:
			self.name = name
			self.setText(0, name)

	def DEAstatus(self):
		return status

	def isAway(self):
		return (self.status == STATUS.away or self.status == STATUS.xa)

	def isOffline(self):
		if self.status == STATUS.unavailable:
			return True
		else:
			return False

	def createDialog(self):
		if not self.dialog:
			self.dialog = QDialog()
			self.dialog.setWindowIcon(QIcon("images/mail.png"))

			self.msg = MessageBox(self.dialog, self.connectionThread, self.jid, self.name)
			layout = QVBoxLayout(self.dialog)
			layout.addWidget(self.msg)
			self.dialog.setLayout(layout)
			self.dialog.setWindowTitle(self.dialog.tr("Chat with ") + self.name)
		self.dialog.show()
		self.dialog.raise_()

	def receiveMessage(self, event):
		print "recieveMessage"
		self.createDialog()
		self.msg.receiveMessage(event)

	def sendMessage(self):
		print "sendMessage"
		self.createDialog()

	def __str__(self):
		return u'%s' % self.name
screen = pygame.display.set_mode((width, height), 0, 32)
clock = pygame.time.Clock()
screen.fill((255, 255, 255))
pygame.display.set_caption('UI Component Test')
collection = UIComponentCollection()
label = TextLabel('TextLabel1', screen, (50, 50), (0, 0), 'Hello world!', 'arial', 48)
label.SetHoveredColor((5, 230, 65))

collection.Append(label)

button = Button('Button1', screen, (250, 450))
button.SetClickCallback(CreateMessageBox)
collection.Append(button)

msgBox = MessageBox('DraggableMessageBox', screen, (random.randint(0, 349), random.randint(0, 349)), (350, 150))
msgBox.draggable = True
collection += msgBox

collection.Render()
pygame.display.update()

while True:
    
	for event in pygame.event.get():
		if event.type == QUIT:
			exit()
		cur_pos = pygame.mouse.get_pos()
		collection.Update(event)
	
	screen.fill((255, 255, 255))