class NodeInfoDialog(tkSimpleDialog.Dialog):

    _label_var = None
    _theta_var = None

    def body(self, master):

        Label(master, text="Label:").grid(row=0, sticky=W)
        Label(master, text="Theta (deg):").grid(row=1, sticky=W)

        self._label_var = StringVar(master, value=NodeInfoDialog._label_var)
        self._theta_var = StringVar(master, value=NodeInfoDialog._theta_var)

        self.e1 = Entry(master, textvariable=self._label_var)
        self.e2 = Entry(master, textvariable=self._theta_var)

        self.e1.grid(row=0, column=1)
        self.e2.grid(row=1, column=1)
        return self.e1  # initial focus

    def validate(self):
        if not self.e2.get() == "":
            theta = float(self.e2.get())
            if theta < -360.0 or theta > 360.0:
                tkMessageBox.showerror(
                    "Invalid Theta value",
                    "Insert a value between -360° and 360°")
                self.e2.delete(0, 'end')
                return 0
            else:
                return 1
        else:
            return 1

    def apply(self):
        label = self.e1.get()
        theta = self.e2.get()

        self.result = label, theta

    @staticmethod
    def setLabelField(label):
        NodeInfoDialog._label_var = str(label)

    @staticmethod
    def setThetaField(theta):
        NodeInfoDialog._theta_var = str(theta)
示例#2
0
    def initUI(self):
        self.parent.title("Software Activation")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        if(self.needsActivated()):
            idEntry = Entry(self, width=36)
            idEntry.place(x=175, y=20)
            idEntry.delete(0, END)
            idEntry.insert(0, "Enter a product id")
            
            keyEntry = Entry(self, width=36)
            keyEntry.place(x=175, y=40)
            keyEntry.delete(0, END)
            keyEntry.insert(0, "Enter your license key")
            
            activateButton = Button(self, text="Activate",
                                    command=lambda:self.activate(
                                        idEntry.get(), keyEntry.get()))
            activateButton.place(x=250, y=65)
        else:
            label = Label(self, text="Product has already been activated")
            label.pack()
示例#3
0
class topFrame(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.setUI()

    def setUI(self):
        self.parent.title("ServoGui")
        self.pack(fill=BOTH, expand=1)
        self.comPort = StringVar(self)
        self.laststrm = StringVar(self)

        settingFrame = Frame(self, borderwidth=1, relief=RAISED)
        settingFrame.pack(fill=Y, side=LEFT)

        Label(settingFrame, width=50, text="Port Settings", bg="green", fg="black").pack(fill=X)

        ports = self.getComPorts()
        w = apply(OptionMenu, (settingFrame, self.comPort) + tuple(ports))
        w.pack(fill=X)

        BaudFrame = Frame(settingFrame)
        BaudFrame.pack(fill=X)
        Label(BaudFrame, text="Baud:").pack(side=LEFT)
        self.baud_entry = Entry(BaudFrame,
                                width=15,
                                validate="focusout",
                                validatecommand=self.baudValidate)
        self.baud_entry.pack(side=LEFT, expand = True)
        self.baud_entry.insert(0,"115200")

        Button(settingFrame, text="Open Port", command=self.openPort). pack(fill=X)
        Button(settingFrame, text="Close Port", command=self.closePort). pack(fill=X)

        StreamFrame = Frame(settingFrame)
        StreamFrame.pack()
        self.btnStartStream = Button(StreamFrame,
                                text="Start Stream",
                                command=self.startStream,
                                state=DISABLED)
        self.btnStopStream = Button(StreamFrame,
                                text="Stop Stream",
                                command=self.stopStream,
                                state=DISABLED)
        self.btnGetConfig = Button(StreamFrame,
                                text="Get Config",
                                command=self.getConfig,
                                state=DISABLED)
        self.btnStartStream.pack(side=LEFT)
        self.btnStopStream.pack(side=LEFT)
        self.btnGetConfig.pack(side=LEFT)
        self.queue = Queue.Queue()
        self.writequeue = Queue.Queue()

        Label(settingFrame, width=50, text="Drive Settings", bg="green", fg="black").pack(fill=X)
        DriveSettingsFrame = Frame(settingFrame, relief=SUNKEN)
        DriveSettingsFrame.pack(fill=X)

        driveSettingsFrames = []
        self.driveSettingsEntries = []
        for drivesetting in drivesettings:
            driveSettingsFrames.append(Frame(DriveSettingsFrame))
            driveSettingsFrames[-1].pack(fill=X)
            Label(driveSettingsFrames[-1], text=drivesetting).pack(side=LEFT)
            self.driveSettingsEntries.append(Entry(driveSettingsFrames[-1]))
            self.driveSettingsEntries[-1].pack(side=RIGHT)
        Button(DriveSettingsFrame, text="Send to drive", command=self.sendConfig).pack(fill=X)
        Button(DriveSettingsFrame, text="Save config in drive", command=self.saveConfig).pack(fill=X)

        Label(settingFrame, width=50, textvariable=self.laststrm, bg="green", fg="black").pack(fill=X)

        #MatplotLib stuff

        f = Figure(figsize=(5, 4), dpi=100)
        self.a = f.add_subplot(311)
        self.a.set_title("Requested and actual position")
        self.b = f.add_subplot(312)
        self.b.set_title("Error")
        self.c = f.add_subplot(313)
        self.c.set_title("Current meas ADC value")

        self.canvas = FigureCanvasTkAgg(f, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)

        toolbar = NavigationToolbar2TkAgg(self.canvas, self)
        toolbar.update()
        self.canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)

        self.hall=[]
        self.encoder_count=[]
        self.pos_error=[]
        self.requested_position=[]
        self.requested_delta=[]
        self.adc_value=[]
        self.pid_output=[]
        self.a.set_autoscaley_on(True)


        self.encoder_line, = self.a.plot([],[])
        self.error_line, = self.b.plot([],[])
        self.reqpos_line, = self.a.plot([],[])
        self.ADC_line, = self.c.plot([],[])
        self.updateCanvas()


    def baudValidate(self):
        sVal = self.baud_entry.get()
        try:
            iVal = int(sVal)
        except ValueError:
            print "Illegal baud value"
            self.baud_entry.delete(0, END)
            self.baud_entry.insert(0, "115200")
            return False
        return True

    def openPort(self):
        try:
            self.ser = serial.Serial(self.comPort.get(), int(self.baud_entry.get()), timeout=0)
        except serial.SerialException:
            print "unable to open"
            return
        self.btnStartStream['state'] = NORMAL
        self.btnStopStream['state'] = NORMAL
        self.btnGetConfig['state'] = NORMAL

        self.thread = SerialThread(self.queue, self.writequeue, self.ser)
        self.thread.daemon = True
        self.thread.start()
        self.process_serial()

    def closePort(self):
        self.thread.stop()
        self.thread.join()
        self.ser.closePort()

        self.btnStartStream['state'] = DISABLED
        self.btnStopStream['state'] = DISABLED
        self.btnGetConfig['state'] = DISABLED

    def process_serial(self):
        while self.queue.qsize():
            try:
                line = self.queue.get()
                self.handleLine(line)
            except Queue.Empty:
                pass
        self.after(100, self.process_serial)

    def startStream(self):
        self.writequeue.put(b"STREAM START \r")

    def stopStream(self):
        self.writequeue.put(b"STREAM DIE \r")
    def getConfig(self):
        self.writequeue.put(b"GET\r")
    def saveConfig(self):
        self.writequeue.put(b"SAVE \r")
    def sendConfig(self):
        for setting in drivesettings:
            dataToSend = b"SET "+setting+" "+self.driveSettingsEntries[drivesettings.index(setting)].get()+"\r"
            print dataToSend
            self.writequeue.put(dataToSend)
            time.sleep(0.2)


    def getComPorts(self):
        ports = serial.tools.list_ports.comports()
        portNames = []
        for port in ports:
            portNames.append(port[0])
        return portNames
    def handleLine(self,line):
        line = line.replace(" ", "")
        line = line.replace("/n", "")
        line = line.replace("/r", "")
        parts = line.split(":")
        if len(parts)>1:
            if parts[0] == "STR":
                self.handleStr(parts[1])
                return
            if parts[0] in drivesettings:
                self.driveSettingsEntries[drivesettings.index(parts[0])].delete(0, END)
                self.driveSettingsEntries[drivesettings.index(parts[0])].insert(0, parts[1])
    def handleStr(self,strm):
        #format of the stream line: STR:hall;count;requestedPosition;requestedDelta;error
        parts = strm.split(";")

        self.laststrm.set(strm)
        self.hall.append(int(parts[0]))
        if len(self.hall) > 5000:
            self.hall.pop(0)

        self.encoder_count.append(parts[1])
        if len(self.encoder_count) > 5000:
            self.encoder_count.pop(0)

        self.requested_position.append(parts[2])
        if len(self.requested_position) > 5000:
            self.requested_position.pop(0)

        self.requested_delta.append(parts[3])
        if len(self.requested_delta) > 5000:
            self.requested_delta.pop(0)

        self.pos_error.append(parts[4])
        if len(self.pos_error) > 5000:
            self.pos_error.pop(0)

        self.adc_value.append(parts[5])
        if len(self.adc_value) > 5000:
            self.adc_value.pop(0)

        self.pid_output.append(parts[5])
        if len(self.pid_output) > 5000:
            self.pid_output.pop(0)

    def updateCanvas(self):

        self.encoder_line.set_xdata(range(len(self.encoder_count)))
        self.encoder_line.set_ydata(self.encoder_count)
        self.error_line.set_xdata(range(len(self.pos_error)))
        self.error_line.set_ydata(self.pos_error)
        self.reqpos_line.set_xdata(range(len(self.requested_position)))
        self.reqpos_line.set_ydata(self.requested_position)
        self.ADC_line.set_xdata(range(len(self.adc_value)))
        self.ADC_line.set_ydata(self.adc_value)
        self.a.relim()
        self.a.autoscale_view()
        self.b.relim()
        self.b.autoscale_view()
        self.c.relim()
        self.c.autoscale_view()
        self.canvas.draw()
        self.after(100, self.updateCanvas)
示例#4
0
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        
        self.initUI()
        
        
    def initUI(self):
   
      
        self.parent.title("Append Data")
        self.pack(fill=BOTH, expand=True)
        labelfont20 = ('Roboto', 15, 'bold')
        labelfont10 = ('Roboto', 10, 'bold')
        labelfont8 = ('Roboto', 8, 'bold')
        
        frame0 = Frame(self)
        frame0.pack()
        
        lbl0 = Label(frame0, text="Hi Nakul")
        lbl0.config(font=labelfont20)    
        lbl0.pack( padx=5, pady=5)
        lbl00 = Label(frame0, text="Fill the data here")
        lbl00.config(font=labelfont10)
        lbl00.pack( padx=5, pady=5)
        
        ####################################
        frame1 = Frame(self)
        frame1.pack()
        frame1.place(x=50, y=100)        
        
        lbl1 = Label(frame1, text="Name", width=15)
        lbl1.pack(side=LEFT,padx=7, pady=5) 
             
        self.entry1 = Entry(frame1,width=20)
        self.entry1.pack(padx=5, expand=True)
    
        ####################################
        frame2 = Frame(self)
        frame2.pack()
        frame2.place(x=50, y=130)
        
        lbl2 = Label(frame2, text="F Name", width=15)
        lbl2.pack(side=LEFT, padx=7, pady=5)

        self.entry2 = Entry(frame2)
        self.entry2.pack(fill=X, padx=5, expand=True)
        
        ######################################
        frame3 = Frame(self)
        frame3.pack()
        frame3.place(x=50, y=160)
        
        lbl3 = Label(frame3, text="DOB(D/M/Y)", width=15)
        lbl3.pack(side=LEFT, padx=7, pady=5)        

        self.entry3 = Entry(frame3)
        self.entry3.pack(fill=X, padx=5, expand=True) 
        
        #######################################
        frame4 = Frame(self)
        frame4.pack()
        frame4.place(x=50, y=190)
        
        lbl4 = Label(frame4, text="Medium(H/E)", width=15)
        lbl4.pack(side=LEFT, padx=7, pady=5)        

        self.entry4 = Entry(frame4)
        self.entry4.pack(fill=X, padx=5, expand=True)
        
        ##########################################
        frame5 = Frame(self)
        frame5.pack()
        frame5.place(x=50, y=225)  
        MODES = [
            ("M", "Male"),
            ("F", "Female"),
            ]
        lbl5 = Label(frame5, text="Gender", width=15)
        lbl5.pack(side=LEFT, padx=7, pady=5)

        global v
        v = StringVar()
        v.set("Male") # initialize

        for text, mode in MODES:
            b = Radiobutton(frame5, text=text,variable=v, value=mode)
            b.pack(side=LEFT,padx=10)
        
        ############################################
        #####printing line
        lbl5a = Label(text="___________________________________________________")
        lbl5a.pack()
        lbl5a.place(x=45, y=255)  
        
        ############################################
        frame6 = Frame(self)
        frame6.pack()
        frame6.place(x=50, y=290)
        
        lbl6 = Label(frame6, text="Phone No:", width=15)
        lbl6.pack(side=LEFT, padx=7, pady=5)        

        self.entry6 = Entry(frame6)
        self.entry6.pack(fill=X, padx=5, expand=True)
        
        ################################################
        
        frame7 = Frame(self)
        frame7.pack()
        frame7.place(x=50, y=320)
        
        lbl7 = Label(frame7, text="Landline No:", width=15)
        lbl7.pack(side=LEFT, padx=7, pady=5)        

        self.entry7 = Entry(frame7)
        self.entry7.pack(fill=X, padx=5, expand=True)
        
        ###############################################
        frame8 = Frame(self)
        frame8.pack()
        frame8.place(x=50, y=350)
        
        lbl8 = Label(frame8, text="Email:", width=15)
        lbl8.pack(side=LEFT, padx=7, pady=5)        

        self.entry8 = Entry(frame8)
        self.entry8.pack(fill=X, padx=5, expand=True)
        
        #############################################
        frame9 = Frame(self)
        frame9.pack()
        frame9.place(x=50, y=380)
        
        lbl9 = Label(frame9, text="HomeTown:", width=15)
        lbl9.pack(side=LEFT, padx=7, pady=5)        

        self.entry9 = Entry(frame9)
        self.entry9.pack(fill=X, padx=5, expand=True)
        
        ###############################################
        frame10 = Frame(self)
        frame10.pack()
        frame10.place(x=60, y=415)
        
        lbl10 = Label(frame10, text="Address:")
        lbl10.pack( padx=5, pady=5)        

        self.entry10 = Text(frame10,height=5, width=28)
        self.entry10.pack(padx=5, expand=True)
        
        ##############################################
        
        #############################################
        
        frame11 = Frame(self)
        frame11.pack()
        frame11.place(x=350, y=100)
        
        lbl11x = Label(frame11,text="_______Class 10th Data_______")
        lbl11x.pack(padx=0, pady=0)
        
        lbl11 = Label(text="%",width=15)
        lbl11.pack(side=LEFT,padx=0, pady=0)
        lbl11.place(x=350, y=130)        

        self.entry11 = Entry(width=12)
        self.entry11.pack(padx=1, expand=True)
        self.entry11.place(x=420, y=130) 
        
        lbl11a = Label(text="Passing Year",width=15)
        lbl11a.pack(padx=0, pady=2)   
        lbl11a.place(x=350, y=160)   

        self.entry11a = Entry(width=12)
        self.entry11a.pack(padx=1, expand=True)
        self.entry11a.place(x=420, y=160) 
        
        lbl11b = Label(text="Board Name",width=15)
        lbl11b.pack(padx=0, pady=2)   
        lbl11b.place(x=350, y=190)   

        self.entry11b = Entry(width=12)
        self.entry11b.pack(padx=1, expand=True)
        self.entry11b.place(x=420, y=190)
        
        
        ####################################################
        frame12 = Frame(self)
        frame12.pack()
        frame12.place(x=510, y=100)
        
        lbl12x = Label(frame12,text="_______Class 12th Data_______")
        lbl12x.pack(padx=0, pady=0)
        
        lbl12 = Label(text="%",width=15)
        lbl12.pack(side=LEFT,padx=0, pady=0)
        lbl12.place(x=510, y=130)        

        self.entry12 = Entry(width=12)
        self.entry12.pack(padx=1, expand=True)
        self.entry12.place(x=580, y=130) 
        
        lbl12a = Label(text="Passing Year",width=15)
        lbl12a.pack(padx=0, pady=2)   
        lbl12a.place(x=510, y=160)   

        self.entry12a = Entry(width=12)
        self.entry12a.pack(padx=1, expand=True)
        self.entry12a.place(x=580, y=160) 
        
        lbl12b = Label(text="Board Name",width=15)
        lbl12b.pack(padx=0, pady=2)   
        lbl12b.place(x=510, y=190)   

        self.entry12b = Entry(width=12)
        self.entry12b.pack(padx=1, expand=True)
        self.entry12b.place(x=580, y=190)

        #####################################################
        frame13 = Frame(self)
        frame13.pack()
        frame13.place(x=670, y=100)
        
        lbl13x = Label(frame13,text="________B.Tech Data_________")
        lbl13x.pack(padx=0, pady=0)
        
        lbl13 = Label(text="%",width=15)
        lbl13.pack(side=LEFT,padx=0, pady=0)
        lbl13.place(x=670, y=130)        

        self.entry13 = Entry(width=12)
        self.entry13.pack(padx=1, expand=True)
        self.entry13.place(x=740, y=130) 
        
        lbl13a = Label(text="Passing Year",width=15)
        lbl13a.pack(padx=0, pady=2)   
        lbl13a.place(x=670, y=160)   

        self.entry13a = Entry(width=12)
        self.entry13a.pack(padx=1, expand=True)
        self.entry13a.place(x=740, y=160) 
        
        lbl13b = Label(text="College",width=15)
        lbl13b.pack(padx=0, pady=2)   
        lbl13b.place(x=670, y=190)   

        self.entry13b = Entry(width=12)
        self.entry13b.pack(padx=1, expand=True)
        self.entry13b.place(x=740, y=190)
        
        ####################################################
        
        frame14 = Frame(self)
        frame14.pack()
        frame14.place(x=380, y=255)
        
        lbl14 = Label(frame14, text="Any Other Info:")
        lbl14.pack( padx=5, pady=5)        

        self.entry14 = Text(frame14,height=5, width=28)
        self.entry14.pack(padx=5, expand=True)
             
         
        
        frame15 = Frame(self)
        frame15.pack()
        frame15.place(x=650, y=290)
        
        openButton = Button(frame15, text="Attatch Resume",width=15,command=self.openResume)
        openButton.pack(padx=5, pady=5)
        self.entry15 = Entry(frame15)
        self.entry15.pack(fill=X, padx=4, expand=True)
        #############################################################
        frame16 = Frame(self)
        frame16.pack()
        frame16.place(x=450, y=500)
        
        closeButton = Button(frame16, text="SUBMIT",width=35,command=self.getDatax)
        closeButton.pack(padx=5, pady=5)
        
        #######################################
        framexxx = Frame(self)
        framexxx.pack()
        framexxx.place(x=700, y=600)
        self.xxx = Label(framexxx,text="Recent Changes Will Appear Here")
        self.xxx.config(font=labelfont8) 
        self.xxx.pack()
        
        #######################################
        
        frame000 = Frame(self)
        frame000.pack()
        frame000.place(x=50, y=600)
        
        self.lbl000= Label(frame000, text="Beta/Sample2.0 | (c) Nakul Rathore")
        self.lbl000.config(font=labelfont8)    
        self.lbl000.pack( padx=5, pady=5)
        
        
           

    def openResume(self):
        ftypes = [('All files', '*')]
        dlg = tkFileDialog.Open(self, filetypes = ftypes,initialdir='C:/Users/')
        global x15
        fl = dlg.show()
        #file name
        x15 = fl
        temp1 = os.path.basename(fl)
        global temp2
        temp2 = os.path.splitext(temp1)[0]
        
        self.entry15.delete(0, 'end')
        self.entry15.insert(0,temp2)
        
      
        
        
        
        #####################
        
        
        
        
        
    def getDatax(self):
        x1 = self.entry1.get()
        x2 = self.entry2.get()
        x3 = self.entry3.get()
        x4 = self.entry4.get()
        
        x5 = v.get()
        
        x6 = int(self.entry6.get())
        x7 = int(self.entry7.get())
        x8 = self.entry8.get()
        x9 = self.entry9.get()
        
        x10 = self.entry10.get('1.0', 'end')
        
        x11 = int(self.entry11.get())
        x11a = int(self.entry11a.get())
        x11b = self.entry11b.get()
        
        x12 = int(self.entry12.get())
        x12a = int(self.entry12a.get())
        x12b = self.entry12b.get()
        
        x13 = int(self.entry13.get())
        x13a = int(self.entry13a.get())
        x13b = self.entry13b.get()
        
        x14 = self.entry14.get('1.0', 'end')
        
        
        
        
        
        list1=[x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x11a,x11b,x12,x12a,x12b,x13,x13a,x13b,x14,"=HYPERLINK("+"\""+x15+"\""+","+"\""+temp2+"\""+")"]
        
        
        wb = openpyxl.load_workbook('..\database\database.xlsx')
        ws = wb.active
        print(wb.get_sheet_names())
        max_row = ws.get_highest_row()
        #max_col = ws.get_highest_column()
        max_col = 21
        print max_row
        
        for i in xrange(1,max_col+1):
            #print list1[i]
            ws.cell(row = max_row+1, column = i).value = list1[i-1]
        ws.cell(row = max_row+1, column = max_col).font = Font(color="0000FF", underline='single')
        ws.cell(row = max_row+1, column = max_col).alignment = Alignment(horizontal='center')
        wb.save('..\database\database.xlsx')
        
        
        self.entry1.delete(0, 'end')
        self.entry2.delete(0, 'end')
        self.entry3.delete(0, 'end')
        self.entry4.delete(0, 'end')
        
        self.entry6.delete(0, 'end')
        self.entry7.delete(0, 'end')
        self.entry8.delete(0, 'end')
        self.entry9.delete(0, 'end')
        self.entry10.delete('1.0', '2.0')
        self.entry11.delete(0, 'end')
        self.entry11a.delete(0, 'end')
        self.entry11b.delete(0, 'end')
        self.entry12.delete(0, 'end')
        self.entry12a.delete(0, 'end')
        self.entry12b.delete(0, 'end')
        self.entry13.delete(0, 'end')
        self.entry13a.delete(0, 'end')
        self.entry13b.delete(0, 'end')
        
        self.entry14.delete('1.0', '2.0')
        
        
        self.xxx.config(text="Recent Changes Made For : "+x1)
示例#5
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.initUI()

    def initUI(self):

        self.parent.title("Review")
        self.pack(fill=BOTH, expand=True)
        labelfont20 = ('Roboto', 20, 'bold')
        labelfont12 = ('Roboto', 12, 'bold')

        frame0 = Frame(self)
        frame0.pack()

        lbl0 = Label(frame0, text="Hi USER")
        lbl0.config(font=labelfont20)
        lbl0.pack(padx=5, pady=5)
        lbl00 = Label(frame0, text="Fill the data here")
        lbl00.config(font=labelfont12)
        lbl00.pack(padx=5, pady=5)

        frame1 = Frame(self)
        frame1.pack()

        lbl1 = Label(frame1, text="Name", width=15)
        lbl1.pack(side=LEFT, padx=7, pady=5)

        self.entry1 = Entry(frame1, width=20)
        self.entry1.pack(padx=5, expand=True)

        frame2 = Frame(self)
        frame2.pack()

        lbl2 = Label(frame2, text="Branch", width=15)
        lbl2.pack(side=LEFT, padx=7, pady=5)

        self.entry2 = Entry(frame2)
        self.entry2.pack(fill=X, padx=5, expand=True)

        frame3 = Frame(self)
        frame3.pack()

        lbl3 = Label(frame3, text="Percent", width=15)
        lbl3.pack(side=LEFT, padx=7, pady=5)

        self.entry3 = Entry(frame3)
        self.entry3.pack(fill=X, padx=5, expand=True)

        frame4 = Frame(self)
        frame4.pack()

        lbl4 = Label(frame4, text="Placed(Yes/No)", width=15)
        lbl4.pack(side=LEFT, padx=7, pady=5)

        self.entry4 = Entry(frame4)
        self.entry4.pack(fill=X, padx=5, expand=True)

        frame5 = Frame(self)
        frame5.pack()

        lbl5 = Label(frame5, text="Resume_File", width=15)
        lbl5.pack(side=LEFT, padx=7, pady=5)

        self.entry5 = Entry(frame5)
        self.entry5.pack(fill=X, padx=5, expand=True)

        frame6 = Frame(self)
        frame6.pack()
        closeButton = Button(frame6,
                             text="SUBMIT",
                             width=15,
                             command=self.getDate)
        closeButton.pack(padx=5, pady=5)

        frame000 = Frame(self)
        frame000.pack()

        self.lbl000 = Label(frame000, text="Enter the data and click SUBMIT")
        self.lbl000.config(font=labelfont12)
        self.lbl000.pack(padx=5, pady=5)

    def getDate(self):
        x1 = self.entry1.get()
        x2 = self.entry2.get()
        x3 = self.entry3.get()
        x4 = self.entry4.get()
        x5 = self.entry5.get()

        list1 = [x1, x2, x3, x4, "=HYPERLINK(" + "\"" + x5 + "\"" + ")"]
        self.entry1.delete(0, 'end')
        self.entry2.delete(0, 'end')
        self.entry3.delete(0, 'end')
        self.entry4.delete(0, 'end')
        self.entry5.delete(0, 'end')
        self.lbl000.config(text="YO")

        with open("test.csv", "ab") as fp:
            wr = csv.writer(fp, dialect='excel')
            wr.writerow(list1)
        fp.close()
示例#6
0
class Metadator(Tk):
    def __init__(self):
        u"""
        Main window constructor
        Creates 1 frame and 2 labeled subframes
        """
        # first: the log
        # see: http://sametmax.com/ecrire-des-logs-en-python/
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.DEBUG)  # all errors will be get
        log_form = logging.Formatter('%(asctime)s || %(levelname)s || %(message)s')
        logfile = RotatingFileHandler('Metadator_LOG.log', 'a', 5000000, 1)
        logfile.setLevel(logging.DEBUG)
        logfile.setFormatter(log_form)
        self.logger.addHandler(logfile)
        self.logger.info('\n\t ======== Metadator ========')  # first messages
        self.logger.info('Starting the UI')

        # checking the path to GDAL in the path
        if "GDAL_DATA" not in env.keys():
            try:
                gdal.SetConfigOption(str('GDAL_DATA'),
                                     str(path.abspath(r'data/gdal')))
            except:
                print("Oups! Something has gone wrong...\
                      see: https://github.com/Guts/Metadator/issues/21")
        else:
            pass

        # basics settings
        Tk.__init__(self)           # constructor of parent graphic class
        self.title(u'Metadator {0}'.format(MetadatorVersion))
        self.style = Style()        # more friendly windows style
        if opersys == 'win32':
            self.logger.info('Op. system: {0}'.format(platform.platform()))
            self.iconbitmap('Metadator.ico')    # windows icon
            self.uzer = env.get(u'USERNAME')
        elif opersys == 'linux2':
            self.logger.info('Op. system: {0}'.format(platform.platform()))
            self.uzer = env.get(u'USER')
            icon = Image("photo", file=r'data/img/metadator.gif')
            self.call('wm', 'iconphoto', self._w, icon)
            self.minsize(580, 100)
            self.style.theme_use('clam')
        elif opersys == 'darwin':
            self.logger.info('Op. system: {0}'.format(platform.platform()))
            self.uzer = env.get(u'USER')
        else:
            self.logger.warning('Operating system not tested')
            self.logger.info('Op. system: {0}'.format(platform.platform()))
        self.resizable(width=False, height=False)
        self.focus_force()

        self.logger.info('GDAL version: {}'.format(gdal.__version__))

        # variables
        self.def_rep = ""       # folder to search for
        self.def_lang = 'FR'    # language to start
        self.def_doc = IntVar()     # to export into Word
        self.def_xls = IntVar()     # to export into Excel 2003
        self.def_xml = IntVar()     # to export into ISO 19139
        self.def_cat = IntVar()     # to merge all output Word files
        self.def_odt = IntVar()     # to export into OpenDocumentText
        self.def_dict = IntVar()    # to make a dictionnary of data
        self.def_kass = IntVar()    # to handle field name case sensitive
        self.def_stat = IntVar()    # to active/disable stats fields
        self.li_pro = []            # list for profiles in language selected
        self.li_shp = []            # list for shapefiles path
        self.li_tab = []            # list for MapInfo tables path
        self.num_folders = 0        # number of folders explored
        self.today = strftime("%Y-%m-%d")   # date of the day
        self.dico_layer = OD()      # dictionary about layer properties
        self.dico_profil = OD()     # dictionary from profile selected
        self.dico_fields = OD()     # dictionary for fields information
        self.dico_rekur = OD()      # dictionary of recurring attributes
        self.dico_err = OD()     # errors list
        self.dico_help = OD()                # dictionary of help texts
        li_lang = [lg for lg in listdir(r'locale')]   # available languages
        self.blabla = OD()      # texts dictionary

        # GUI fonts
        ft_tit = tkFont.Font(family="Times", size=10, weight=tkFont.BOLD)

        # fillfulling
        self.load_settings()
        self.load_texts(self.def_lang)
        self.li_profiles(self.def_lang)
        self.li_rekurs(self.def_lang)
        self.recup_help(self.def_lang)

        # Tabs
        self.nb = Notebook(self)
        self.tab_globals = Frame(self.nb)   # tab_id = 0
        self.tab_options = Frame(self.nb)   # tab_id = 1
        self.tab_attribs = Frame(self.nb)   # tab_id = 2
        self.nb.add(self.tab_globals,
                    text=self.blabla.get('gui_tab1'), padding=3)
        self.nb.add(self.tab_options,
                    text=self.blabla.get('gui_tab2'), padding=3)
        self.nb.add(self.tab_attribs,
                    text=self.blabla.get('gui_tab3'), padding=3)
        self.logger.info('UI created')

                ### Tab 1: global
        # Frames
        self.FrPath = Labelframe(self.tab_globals,
                                 name='main',
                                 text=self.blabla.get('tab1_fr1'))
        self.FrProg = Labelframe(self.tab_globals,
                                 name='progression',
                                 text=self.blabla.get('tab1_frprog'))
            ## Frame 1
        # target folder
        self.labtarg = Label(self.FrPath, text=self.blabla.get('tab1_path'))
        self.target = Entry(self.FrPath, width=25)
        self.browsetarg = Button(self.FrPath,       # browse button
                                 text=self.blabla.get('tab1_browse'),
                                 command=lambda: self.setpathtarg(),
                                 takefocus=True)
        self.browsetarg.focus_force()               # force the focus on
        self.profil = Label(self.FrPath, text=self.blabla.get('tab1_prof'))
        # profiles switcher
        self.ddl_profil = Combobox(self.FrPath, values=self.li_pro, width=5)
        self.ddl_profil.current(0)
        self.ddl_profil.bind("<<ComboboxSelected>>", self.select_profil)
        # widgets placement
        self.labtarg.grid(row=1, column=1, columnspan=1,
                          sticky=N + S + W + E, padx=2, pady=8)
        self.target.grid(row=1, column=2, columnspan=1,
                         sticky=N + S + W + E, padx=2, pady=8)
        self.browsetarg.grid(row=1, column=3,
                             sticky=N + S + W + E, padx=2, pady=8)
        self.profil.grid(row=2, column=1,
                         sticky=N + S + W + E, padx=2, pady=8)
        self.ddl_profil.grid(row=2, column=2, sticky=W + E + N + S,
                             columnspan=2, padx=2, pady=8)

        # tooltips
        InfoBulle(self.target, message=self.dico_help.get(30)[1])
        InfoBulle(self.browsetarg, message=self.dico_help.get(30)[1])
        InfoBulle(self.ddl_profil, message=self.dico_help.get(31)[1])

            ## Frame 2
        # variables
        self.status = StringVar(self.FrProg, '')
        # widgets
        self.prog_layers = Progressbar(self.FrProg, orient="horizontal")
        self.prog_fields = Progressbar(self.FrProg, orient="horizontal")
        # widgets placement
        Label(self.FrProg, textvariable=self.status,
                           foreground='DodgerBlue').pack(expand=1)
        self.prog_layers.pack(expand=1, fill=X)

        # Frames placement
        self.FrPath.pack(expand=1, fill='both')
        self.FrProg.pack(expand=1, fill='both')

                ### Tab 2: options
        # Export options
        caz_doc = Checkbutton(self.tab_options,
                              text=u'HTML / Word (.doc/.docx)',
                              variable=self.def_doc,
                              command=lambda: self.catalog_dependance())
        caz_xls = Checkbutton(self.tab_options,
                              text=u'Excel 2003 (.xls)',
                              variable=self.def_xls)
        caz_xml = Checkbutton(self.tab_options,
                              text=u'XML (ISO 19139)',
                              variable=self.def_xml)
        self.caz_cat = Checkbutton(self.tab_options,
                                   text=self.blabla.get('tab2_merge'),
                                   variable=self.def_cat)
        caz_odt = Checkbutton(self.tab_options,
                              text=u'Open Document Text (.odt)',
                              variable=self.def_odt)
        # widgets placement
        caz_doc.grid(row=1,
                     column=0,
                     sticky=N + S + W + E,
                     padx=2, pady=2)
        self.caz_cat.grid(row=2,
                          column=0,
                          sticky=N + S + W + E,
                          padx=2, pady=2)
        caz_xls.grid(row=1,
                     column=1,
                     sticky=N + S + W + E,
                     padx=2, pady=2)
        caz_xml.grid(row=2,
                     column=1,
                     sticky=N + S + W + E,
                     padx=2, pady=2)
        caz_odt.grid(row=3,
                     column=1,
                     sticky=N + S + W + E,
                     padx=2, pady=2)
        # disabling the widgets which work only on Windows OS
        if opersys != 'win32':
            self.logger.info('Disabling Windows reserved functions.')
            self.def_doc.set(0)
            self.def_cat.set(0)
            caz_doc.configure(state='disabled')
            self.caz_cat.configure(state='disabled')
        else:
            pass
        # make the catalog option depending on the Word option
        self.catalog_dependance()

        # tooltips
        InfoBulle(caz_doc,
                  message=self.dico_help.get(33)[1],
                  image=self.dico_help.get(33)[2])
        InfoBulle(caz_xls,
                  message=self.dico_help.get(34)[1],
                  image=self.dico_help.get(34)[2])
        InfoBulle(caz_xml,
                  message=self.dico_help.get(35)[1],
                  image=self.dico_help.get(35)[2])
        InfoBulle(caz_odt,
                  message=self.dico_help.get(36)[1],
                  image=self.dico_help.get(36)[2])
        InfoBulle(self.caz_cat,
                  message=self.dico_help.get(37)[1],
                  image=self.dico_help.get(37)[2])

                ### Tab 3: recurring attributes
        # Attribute selector
        self.lab_chps = Label(self.tab_attribs, text=self.blabla.get('tab3_sele'))
        self.ddl_attr = Combobox(self.tab_attribs, values=self.dico_rekur.keys())
        self.ddl_attr.bind("<<ComboboxSelected>>", self.edit_rekur)
        self.supr = Button(self.tab_attribs, text=self.blabla.get('tab3_supp'),
                           command=self.del_rekur)
        # frame
        self.FrRekur = Labelframe(self.tab_attribs,
                                  name='attributes',
                                  text=self.blabla.get('tab3_tit'))
        # attribute settings
        self.tab3_LBnom = Label(self.FrRekur,
                                text=self.blabla.get('tab3_nom'),
                                state=DISABLED)
        self.tab3_ENnom = Entry(self.FrRekur, state=DISABLED)
        self.tab3_LBdesc = Label(self.FrRekur,
                                 text=self.blabla.get('tab3_desc'),
                                 state=DISABLED)
        self.tab3_TXdesc = Text(self.FrRekur,
                                height=5, width=30,
                                wrap=WORD, state=DISABLED)
        self.tab3_CBcass = Checkbutton(self.FrRekur,
                                       text=self.blabla.get('tab3_cass'),
                                       variable=self.def_kass,
                                       state=DISABLED)
        self.tab3_CBstat = Checkbutton(self.FrRekur,
                                       text=self.blabla.get('tab3_stat'),
                                       variable=self.def_stat,
                                       state=DISABLED)
        # Validation button
        self.save = Button(self.FrRekur,
                           text=self.blabla.get('tab3_save'),
                           command=self.save_rekur,
                           state='disabled')

        # widgets placement
        self.lab_chps.grid(row=1, column=1, sticky=N + S + W,
                           padx=2, pady=2)
        self.ddl_attr.grid(row=1, column=2, sticky=N + S + W + E,
                           padx=2, pady=2)
        self.supr.grid(row=1, column=3, sticky=N + S + W + E,
                       padx=2, pady=2)
        self.tab3_LBnom.grid(row=1, column=0, columnspan=1,
                             sticky=N + S + W, padx=2, pady=2)
        self.tab3_ENnom.grid(row=1, column=1, columnspan=1,
                             sticky=N + S + W + E, padx=2, pady=2)
        self.tab3_LBdesc.grid(row=2, column=0, columnspan=1,
                              sticky=N + S + W + E, padx=2, pady=2)
        self.tab3_TXdesc.grid(row=2, column=1, columnspan=2,
                              sticky=N + S + W + E, padx=2, pady=2)
        self.tab3_CBcass.grid(row=3, column=0, columnspan=1,
                              sticky=N + S + W + E, padx=2, pady=2)
        self.tab3_CBstat.grid(row=3, column=1, columnspan=1,
                              sticky=N + S + W + E, padx=2, pady=2)
        self.save.grid(row=5, column=0, columnspan=4,
                       sticky=N + S + W + E, padx=2, pady=2)

        # Frame placement
        self.FrRekur.grid(row=2, column=1, columnspan=3,
                          sticky=N + S + W + E, padx=2, pady=2)

        # tooltips
        InfoBulle(self.lab_chps, message=self.dico_help.get(38)[1])
        InfoBulle(self.ddl_attr, message=self.dico_help.get(39)[1])
        InfoBulle(self.supr, message=self.dico_help.get(40)[1])
        InfoBulle(self.tab3_CBcass, message=self.dico_help.get(41)[1])
        InfoBulle(self.tab3_CBstat, message=self.dico_help.get(42)[1])

            ## Main frame
        # Hola
        self.welcome = Label(self,
                             text=self.blabla.get('hi') + self.uzer,
                             font=ft_tit,
                             foreground="red2")
        # Image
        self.icone = PhotoImage(master=self, file=r'data/img/metadator.gif')
        Label(self, image=self.icone).grid(row=2,
                                           column=0,
                                           padx=2,
                                           pady=2,
                                           sticky=N + S + W + E)
        # credits
        s = Style(self)
        s.configure('Kim.TButton', foreground='DodgerBlue',
                    borderwidth=0, relief="flat")
        Button(self,
               text='by Julien M. (2015)',
               style='Kim.TButton',
               command=lambda: open_new('https://github.com/Guts')).grid(row=3,
                                                                         padx=2,
                                                                         pady=2,
                                                                         sticky=W+E)
        # language switcher
        self.ddl_lang = Combobox(self, values=li_lang, width=5)
        self.ddl_lang.current(li_lang.index(self.def_lang))
        self.ddl_lang.bind("<<ComboboxSelected>>", self.change_lang)
        # Go go go button
        self.val = Button(self,
                          text=self.blabla.get('tab1_go'),
                          state='active',
                          command=lambda: self.process())
        # Cancel button
        self.can = Button(self,
                          text=self.blabla.get('gui_quit'),
                          command=self.destroy)
        # widgets placement
        self.welcome.grid(row=0, column=0, columnspan=1, sticky=N + S + W + E,
                          padx=2, pady=2)
        self.ddl_lang.grid(row=1, column=0, sticky=N, padx=2, pady=0)
        self.can.grid(row=4, column=0, sticky=N + S + W + E, padx=2, pady=2)
        self.val.grid(row=4, column=1, sticky=N + S + W + E, padx=2, pady=2)

        # tooltips
        InfoBulle(self.ddl_lang, message=self.dico_help.get(32)[1])

                ### Notebook placement
        self.nb.grid(row=0, rowspan=4, column=1, sticky=N + S + W + E)
        # keep updated list of profiles
        self.maj()

    def maj(self):
        """
        update the profiles dropdown list every second
        """
        try:
            self.li_profiles(self.ddl_lang.get())
            self.ddl_profil['values'] = self.li_pro
            self.after(1000, self.maj)
        except WindowsError:    # avoid an error occuring with browse button
            self.after(1000, self.maj)
            pass

    def alter_state(self, parent, new_state):
        """
        just a function to change easily  the state of  all children widgets
        of a parent class

        parent=Tkinter class with children (Frame, Labelframe, Tk, etc.)
        new_state=Tkinter keyword for widget state (ACTIVE, NORMAL, DISABLED)
        """
        for child in parent.winfo_children():
            child.configure(state=new_state)
        # end of function
        return parent, new_state

    def catalog_dependance(self):
        """ unselect the catalog option if the word option is unselected """
        if self.def_doc.get() == 0:
            self.def_cat.set(0)
            self.caz_cat.config(state='disabled')
        elif self.def_doc.get() == 1:
            self.caz_cat.config(state='normal')
        # end of function
        return

    def load_settings(self):
        u""" load settings from last execution """
        confile = 'options.ini'
        config = ConfigParser.RawConfigParser()
        config.read(confile)
        # basics
        self.def_lang = config.get('basics', 'def_codelang')
        self.def_rep = config.get('basics', 'def_rep')
        # export preferences
        self.def_doc.set(config.get('export_preferences', 'def_word'))
        self.def_cat.set(config.get('export_preferences', 'def_cat'))
        self.def_xls.set(config.get('export_preferences', 'def_xls'))
        self.def_xml.set(config.get('export_preferences', 'def_xml'))
        self.def_dict.set(config.get('export_preferences', 'def_dict'))
        self.def_odt.set(config.get('export_preferences', 'def_odt'))
        # log
        self.logger.info('Last options loaded')
        # End of function
        return config, self.def_rep, self.def_lang, self.def_doc

    def save_settings(self):
        u""" save options in order to make the next execution easier """
        confile = 'options.ini'
        config = ConfigParser.RawConfigParser()
        # add sections
        config.add_section('basics')
        config.add_section('export_preferences')
        # basics
        config.set('basics', 'def_codelang', self.ddl_lang.get())
        config.set('basics', 'def_rep', self.target.get())
        # export preferences
        config.set('export_preferences', 'def_word', self.def_doc.get())
        config.set('export_preferences', 'def_cat', self.def_cat.get())
        config.set('export_preferences', 'def_xls', self.def_xls.get())
        config.set('export_preferences', 'def_xml', self.def_xml.get())
        config.set('export_preferences', 'def_dict', self.def_dict.get())
        config.set('export_preferences', 'def_odt', self.def_odt.get())
        # Writing the configuration file
        with open(confile, 'wb') as configfile:
            config.write(configfile)
        # End of function
        return config

    def change_lang(self, event):
        u""" update the texts dictionary with the language selected """
        new_lang = event.widget.get()
        # change to the new language selected
        self.load_texts(new_lang)
        self.li_profiles(new_lang)
        self.li_rekurs(new_lang)
        self.ddl_profil.delete(0, END)
        self.ddl_profil.config(values=self.li_pro)
        self.ddl_profil.update()
        self.ddl_attr.config(values=self.dico_rekur.keys())
        self.recup_help(new_lang)
        # update widgets text
          # tab1
        self.nb.tab(0, text=self.blabla.get('gui_tab1'))
        self.welcome.config(text=self.blabla.get('hi') + self.uzer)
        self.can.config(text=self.blabla.get('gui_quit'))
        self.FrPath.config(text=self.blabla.get('tab1_fr1'))
        self.FrProg.config(text=self.blabla.get('tab1_frprog'))
        self.labtarg.config(text=self.blabla.get('tab1_path'))
        self.browsetarg.config(text=self.blabla.get('tab1_browse'))
        self.val.config(text=self.blabla.get('tab1_go'))
        self.profil.config(text=self.blabla.get('tab1_prof'))
          # tab2
        self.nb.tab(1, text=self.blabla.get('gui_tab2'))
        self.caz_cat.config(text=self.blabla.get('tab2_merge'))
          # tab3
        self.nb.tab(2, text=self.blabla.get('gui_tab3'))
        self.lab_chps.config(text=self.blabla.get('tab3_sele'))
        self.supr.config(text=self.blabla.get('tab3_supp'))
        self.FrRekur.config(text=self.blabla.get('tab3_tit'))
        self.tab3_LBnom.config(text=self.blabla.get('tab3_nom'))
        self.tab3_LBdesc.config(text=self.blabla.get('tab3_desc'))
        self.tab3_CBcass.config(text=self.blabla.get('tab3_cass'))
        self.tab3_CBstat.config(text=self.blabla.get('tab3_stat'))
        self.save.config(text=self.blabla.get('tab3_save'))

        # End of function
        return self.blabla

    def load_texts(self, lang='FR'):
        u"""
        Load texts according to the selected language
        """
        # clearing the text dictionary
        self.blabla.clear()
        # open xml cursor
        xml = ET.parse('locale/{0}/lang_{0}.xml'.format(lang))
        # Looping and gathering texts from the xml file
        for elem in xml.getroot().getiterator():
            self.blabla[elem.tag] = elem.text
        # updating the GUI
        self.update()
        # en of function
        return self.blabla

    def setpathtarg(self):
        """ ...browse and insert the path of target folder """
        foldername = askdirectory(parent=self,
                                  initialdir=self.def_rep,
                                  mustexist=True,
                                  title=self.blabla.get('gui_cible'))
        # check if a folder has been choosen
        if foldername:
            try:
                self.target.delete(0, END)
                self.target.insert(0, foldername)
            except:
                info(title=self.blabla.get('nofolder'),
                     message=self.blabla.get('nofolder'))
                return

        # count shapefiles and MapInfo files in a separated thread
        proc = threading.Thread(target=self.li_geofiles,
                                args=(foldername, ))
        proc.daemon = True
        proc.start()

        # end of function
        return foldername

    def li_geofiles(self, foldertarget):
        u""" List shapefiles and MapInfo files (.tab, not .mid/mif) contained
        in the folders structure """
        # reseting global variables
        self.li_shp = []
        self.li_tab = []
        self.browsetarg.config(state=DISABLED)
        # Looping in folders structure
        self.status.set(self.blabla.get('tab1_prog1'))
        self.prog_layers.start()
        for root, dirs, files in walk(unicode(foldertarget)):
            self.num_folders = self.num_folders + len(dirs)
            for f in files:
                """ looking for files with geographic data """
                try:
                    unicode(path.join(root, f))
                    full_path = path.join(root, f)
                except UnicodeDecodeError:
                    full_path = path.join(root, f.decode('latin1'))
                # Looping on files contained
                if path.splitext(full_path.lower())[1].lower() == '.shp'\
                   and (path.isfile('{0}.dbf'.format(full_path[:-4]))
                        or path.isfile('{0}.DBF'.format(full_path[:-4])))\
                   and (path.isfile('{0}.shx'.format(full_path[:-4]))
                        or path.isfile('{0}.SHX'.format(full_path[:-4]))):
                    """ listing compatible shapefiles """
                    # add complete path of shapefile
                    self.li_shp.append(full_path)
                elif path.splitext(full_path.lower())[1] == '.tab'\
                    and (path.isfile(full_path[:-4] + '.dat')
                         or path.isfile(full_path[:-4] + '.DAT'))\
                    and (path.isfile(full_path[:-4] + '.map')
                         or path.isfile(full_path[:-4] + '.MAP'))\
                    and (path.isfile(full_path[:-4] + '.id')
                         or path.isfile(full_path[:-4] + '.ID')):
                    """ listing MapInfo tables """
                    # add complete path of MapInfo file
                    self.li_tab.append(full_path)
        # stopping the progress bar
        self.prog_layers.stop()
        # Lists ordering and tupling
        self.li_shp.sort()
        self.li_shp = tuple(self.li_shp)
        self.li_tab.sort()
        self.li_tab = tuple(self.li_tab)
        # setting the label text and activing the buttons
        self.status.set(unicode(len(self.li_shp)) + u' shapefiles - '
                        + unicode(len(self.li_tab)) + u' tables (MapInfo) - '
                        + unicode(self.num_folders) + self.blabla.get('log_numfold'))
        self.browsetarg.config(state=ACTIVE)
        self.val.config(state=ACTIVE)
        # End of function
        return foldertarget, self.li_shp, self.li_tab

    def li_profiles(self, lang):
        u"""
        list profiles already existing
        """
        # reseting global variable
        self.li_pro = []
        # Looping in folders structure
        folder_profiles = path.join('locale/', lang + '/profiles/')
        self.li_pro = [lg[:-4] for lg in listdir(folder_profiles)]
        self.li_pro.append(self.blabla.get('tab1_new'))
        # End of function
        return folder_profiles, self.li_pro

    def li_rekurs(self, lang):
        u"""
        List recurring attributes that already exist in the selected language
        """
        # clearing the text dictionary
        self.dico_rekur.clear()
        champis = path.abspath(r'locale/{0}/champignons_{0}.xml'.format(lang))
        xml = ET.parse(champis)
        # Looping and gathering texts from the xml file
        for elem in xml.findall('champ'):
            rek_name = elem.find('intitule').text
            rek_desc = elem.find('description').text
            rek_kass = elem.find('case').text
            rek_stat = elem.find('stats').text
            self.dico_rekur[rek_name] = rek_desc, rek_kass, rek_stat
        self.dico_rekur[self.blabla.get('tab3_new')] = '', 0, 0
        # updating the GUI
        self.update()
        # End of function
        return self.dico_rekur

    def edit_rekur(self, event):
        u"""
        preparing the form to edit a recurring attribute
        """
        rekur = event.widget.get()
        # deactivate the selector
        self.ddl_attr.config(state=DISABLED)
        # activate the form
        self.alter_state(self.FrRekur, NORMAL)
        # change to the new language selected
        self.tab3_ENnom.insert(0, rekur)
        self.tab3_TXdesc.insert(1.0, self.dico_rekur.get(rekur)[0])
        self.def_kass.set(self.dico_rekur.get(rekur)[1])
        self.def_stat.set(self.dico_rekur.get(rekur)[2])
        # End of function
        return self.dico_rekur

    def save_rekur(self):
        u""" save the recurring attribute edited """
        # check if the attribute already exists
        if self.tab3_ENnom.get() in self.dico_rekur:
            if not askyesno(title=self.blabla.get('tab3_alert_exist1'),
                            message=self.blabla.get('tab3_alert_exist2')):
                return
            else:
                pass
        else:
            pass

        # save
        self.dico_rekur[self.tab3_ENnom.get()] = self.tab3_TXdesc.get(1.0, END).rstrip(),\
                                                 self.def_kass.get(),\
                                                 self.def_stat.get()
        # reset the form
        self.tab3_ENnom.delete(0, END)
        self.tab3_TXdesc.delete(1.0, END)
        self.def_kass.set(0)
        self.def_stat.set(0)
        # deactivate the form
        self.alter_state(self.FrRekur, DISABLED)
        # updating the dropdown list
        self.ddl_attr.config(state=NORMAL)
        self.ddl_attr.delete(0, END)
        self.ddl_attr['values'] = self.dico_rekur.keys()

        # End of function
        return self.dico_rekur

    def del_rekur(self):
        u""" delete the selected recurring attribute """
        # reactivate the selector
        self.ddl_attr.config(state=ACTIVE)
        self.dico_rekur.pop(self.ddl_attr.get())

        self.ddl_attr.delete(0, END)
        self.ddl_attr['values'] = self.dico_rekur.keys()
        # reset the form
        self.tab3_ENnom.delete(0, END)
        self.tab3_TXdesc.delete(1.0, END)
        self.def_kass.set(0)
        self.def_stat.set(0)
        # deactivate the form
        self.alter_state(self.FrRekur, DISABLED)

        # End of function
        return self.dico_rekur

    def saveas_rekurs(self, lang):
        u""" save the recurring fields into the file dedicated """
        rekur = ET.Element(u'champs')
        xml_path = r'locale/{0}/champignons_{0}.xml'.format(lang)
        self.dico_rekur.pop(self.blabla.get('tab3_new'))
        with open(xml_path, 'w') as champis:
            for elem in self.dico_rekur.keys():
                rek = ET.SubElement(rekur, u'champ')
                # name of recurring attribute
                rek_name = ET.SubElement(rek, u'intitule')
                rek_name.text = elem
                # description of recurring attribute
                rek_desc = ET.SubElement(rek, u'description')
                rek_desc.text = self.dico_rekur.get(elem)[0]
                # stats option of recurring attribute
                rek_stats = ET.SubElement(rek, u'stats')
                rek_stats.text = unicode(self.dico_rekur.get(elem)[1])
                # case sensitive option of recurring attribute
                rek_case = ET.SubElement(rek, u'case')
                rek_case.text = unicode(self.dico_rekur.get(elem)[2])

        # creating the xml tree
        out_rekurs = ET.ElementTree(rekur)
        # saving it
        out_rekurs.write(xml_path,
                         encoding='utf-8',
                         xml_declaration='version="1.0"',
                         method='xml')

        # End of function
        return self.dico_rekur

    def select_profil(self, event):
        """ when a profile is selected... """
        profsel = event.widget.get()
        # if user wants to use an existing profile or create a new one
        if profsel == self.blabla.get('tab1_new'):
            self.val.config(text=self.blabla.get('tab1_crprofil'))
        else:
            self.val.config(text=self.blabla.get('tab1_go'))

        # end of function
        return self.val

    def recup_profil(self, lang):
        """ get the information from the profile selected """
        # clearing the profile dictionary
        self.dico_profil.clear()
        # specific path to profile file
        path_profile = path.join('locale/{0}/profiles/{1}.xml'.format(lang,
                                                                      self.ddl_profil.get()))
        with open(path_profile, 'r') as profile:
            # open xml parser
            xml = ET.parse(profile)
            # basic informations
            self.dico_profil['description'] = xml.find('description').text
            self.dico_profil['sources'] = xml.find('sources').text
            self.dico_profil['url'] = xml.find('url').text
            self.dico_profil['url_label'] = xml.find('url_label').text
            self.dico_profil[u'diffusion'] = xml.find('diffusion').text
            # data language
            lang_data = xml.find(u'lang_data')
            self.dico_profil[u"lang_data"] = lang_data.find(u'name').text
            # metadata language
            lang_metad = xml.find(u'lang_metad')
            self.dico_profil[u"lang_md"] = lang_metad.find(u'name').text
            # diffusion constraints
            diff = xml.find(u'diffusion')
            self.dico_profil['diffusion'] = diff.find(u'name').text
            # update rythm
            rythm = xml.find(u'rythm')
            self.dico_profil['rythm'] = rythm.find(u'name').text
            # INSPIRE themes
            themes = xml.find('themesinspire')
            li_themesinspire = [theme.find('name').text for theme in themes.findall('theme')]
            self.dico_profil['themesinspire'] = li_themesinspire
            # custom keywords
            keywords = xml.find('keywords')
            li_keywords = [keyword.find('name').text for keyword in keywords.findall('keyword')]
            self.dico_profil['keywords'] = li_keywords
            # places keywords
            geokeywords = xml.find('geokeywords')
            li_geokeywords = [geokeyword.find('name').text for geokeyword in geokeywords.findall('geokeyword')]
            self.dico_profil['geokeywords'] = li_geokeywords
            # contacts
            contacts = xml.find(u'contacts')
            # point of contact
            cont = contacts.find(u'pointdecontact')
            self.dico_profil[u'cont_name'] = cont.find(u'name').text
            self.dico_profil[u'cont_orga'] = cont.find(u'org').text
            self.dico_profil[u'cont_mail'] = cont.find(u'mail').text
            self.dico_profil[u'cont_role'] = cont.find(u'role').text
            self.dico_profil[u'cont_func'] = cont.find(u'func')[0].text
            self.dico_profil[u'cont_street'] = cont.find(u'street').text
            self.dico_profil[u'cont_city'] = cont.find(u'city').text
            self.dico_profil[u'cont_cp'] = cont.find(u'cp').text
            self.dico_profil[u'cont_country'] = cont.find(u'country').text
            self.dico_profil[u'cont_phone'] = cont.find(u'tel').text
            # second contact (responsable, etc.)
            resp = contacts.find(u'second_contact')
            self.dico_profil[u'resp_name'] = resp.find(u'name').text
            self.dico_profil[u'resp_orga'] = resp.find(u'org').text
            self.dico_profil[u'resp_mail'] = resp.find(u'mail').text
            self.dico_profil[u'resp_role'] = resp.find(u'role').text
            self.dico_profil[u'resp_func'] = resp.find(u'func')[0].text
            self.dico_profil[u'resp_street'] = resp.find(u'street').text
            self.dico_profil[u'resp_city'] = resp.find(u'city').text
            self.dico_profil[u'resp_cp'] = resp.find(u'cp').text
            self.dico_profil[u'resp_country'] = resp.find(u'country').text
            self.dico_profil[u'resp_phone'] = resp.find(u'tel').text
        # End of function
        return self.dico_profil

    def recup_help(self, lang):
        """ get the help texts """
        # specific path to xml file
        path_help = 'locale/%s/help_%s.xml' % (lang, lang)
        # reading and parsing the xml
        with open(path_help, 'r') as source:
            xml = ET.parse(source)                  # xml cursor
            for tooltip in xml.findall('tooltip'):
                idu = tooltip.find('id').text
                ref = tooltip.find('ref').text
                txt = tooltip.find('txt').text
                img = tooltip.find('image').text
                doc = tooltip.find('doc').text
                # fillfulling the INSPIRE dictionary
                self.dico_help[int(idu)] = ref, txt, img, doc
        # End of function
        return self.dico_help

    def process(self):
        u""" launch the different processes """
        # display the main tab
        self.nb.select(0)
        # check option selected: process or create a new profile
        if self.ddl_profil.get() == self.blabla.get('tab1_new'):
            # launching the profile form
            self.logger.info('Creation of a new profile')
            tr_profile = threading.Thread(target=NewProfile,
                                          args=(self.blabla,
                                                self.ddl_lang.get(),
                                                self.dico_help,
                                                self.li_pro))
            tr_profile.daemon = True
            tr_profile.run()
            # NewProfile(self.blabla, self.ddl_lang.get(), self.li_pro)
            self.li_profiles(self.ddl_lang.get())   # updating the dropdow list
            self.ddl_profil['values'] = self.li_pro
            return
        # check if the target folder has been selected
        if self.target.get() == "":
            info(title=self.blabla.get('info_blanktarget1'),
                 message=self.blabla.get('info_blanktarget2'))
            return
        # check if a profile has been selected
        if self.ddl_profil.get() == "":
            info(title=self.blabla.get('info_blankprofile1'),
                 message=self.blabla.get('info_blankprofile2'))
            return
        # disabling others GUI parts
        self.tab_globals.focus_force()
        self.alter_state(self.FrPath, DISABLED)

        # check if there are some layers into the folder structure
        if len(self.li_shp) + len(self.li_tab) == 0:
            self.logger.warning("No geofiles found in the folder structure")
            self.status.set(self.blabla.get('log_nodata'))
            return
        # specific variables
        dest = path.join(self.target.get(), 'metadator')
        if not path.isdir(dest):    # test if folder already exists
            mkdir(dest, 0777)       # if not, we create it
        # getting profile informations
        self.recup_profil(self.ddl_lang.get())
        # saving options in a separated thread
        tr_options = threading.Thread(target=self.save_settings)
        tr_options.daemon = True
        tr_options.start()
        self.logger.info('Current options saved')
        # saving recurring fiels in a separated thread
        tr_rekurs = threading.Thread(target=self.saveas_rekurs,
                                     args=(self.ddl_lang.get(), ))
        tr_rekurs.daemon = True
        tr_rekurs.start()
        # configuring the progression bar
        self.prog_layers["maximum"] = len(self.li_shp) + len(self.li_tab)
        self.prog_layers["value"]
        # Processing the shapefiles
        self.logger.info('\tStart processing the files')
        for shp in self.li_shp:
            """ looping on shapefiles list """
            self.logger.info('Processing: %s' % path.basename(shp))
            self.status.set(path.basename(shp))
            # reset recipient data
            self.dico_layer.clear()
            self.dico_fields.clear()
            # getting separated process threads
            Read_SHP(shp,
                     self.dico_layer,
                     self.dico_fields,
                     'shape',
                     self.blabla)
            # checking layer error
            if self.dico_layer.get('error'):
                # increment the progress bar
                self.prog_layers["value"] = self.prog_layers["value"] + 1
                self.update()
                self.logger.warning('This shape has an issue: %s' % shp)
                continue
            # getting fields statistics only if needed
            if self.def_doc.get() == 1 or self.def_xls.get() == 1 or self.def_odt.get() == 1:
                StatsFields(shp, self.dico_fields, self.dico_rekur, self.blabla)
            # export according to options selected
            if self.def_doc.get() == 1:
                ExportToHTML(dest,
                             self.dico_layer,
                             self.dico_fields,
                             self.dico_profil,
                             self.dico_rekur,
                             self.blabla)
                html_path = path.join(dest,
                                      "{0}_MD.html".format(self.dico_layer['name'][:-4]))
                ExportToDocX(html_path, dest)
            if self.def_xls.get() == 1:
                ExportToXLS(dest,
                            self.dico_layer,
                            self.dico_fields,
                            self.dico_profil,
                            self.dico_rekur,
                            self.blabla)
            if self.def_xml.get() == 1:
                ExportToXML(dest,
                            self.dico_layer,
                            self.dico_profil,
                            '',
                            self.blabla,
                            1,
                            0)
            if self.def_odt.get() == 1:
                ExportToODT(dest,
                            self.dico_layer,
                            self.dico_fields,
                            self.dico_profil,
                            self.dico_rekur,
                            self.blabla)
            # increment the progress bar
            self.prog_layers["value"] = self.prog_layers["value"] + 1
            self.update()

        # Processing the MapInfo tables
        for tab in self.li_tab:
            """ looping on MapInfo tables list """
            self.logger.info('Processing: %s' % path.basename(tab))
            self.status.set(path.basename(tab))
            # reset recipient data
            self.dico_layer.clear()
            self.dico_fields.clear()
            # getting the informations
            Read_TAB(tab,
                     self.dico_layer,
                     self.dico_fields,
                     'table',
                     self.blabla)
            # checking layer error
            if self.dico_layer.get('error'):
                self.logger.warning('This MapInfo table has an issue: %s' % tab)
                # increment the progress bar
                self.prog_layers["value"] = self.prog_layers["value"] +1
                self.update()
                continue
            # getting fields statistics only if needed
            if self.def_doc.get() == 1 \
               or self.def_xls.get() == 1 \
               or self.def_odt.get() == 1:
                StatsFields(tab, self.dico_fields, self.dico_rekur, self.blabla)
            # export according to options selected
            if self.def_doc.get() == 1:
                ExportToHTML(dest,
                             self.dico_layer,
                             self.dico_fields,
                             self.dico_profil,
                             self.dico_rekur,
                             self.blabla)
                html_path = path.join(dest,
                                      "{0}_MD.html".format(self.dico_layer['name'][:-4]))
                ExportToDocX(html_path, dest)
            if self.def_xls.get() == 1:
                ExportToXLS(dest,
                            self.dico_layer,
                            self.dico_fields,
                            self.dico_profil,
                            self.dico_rekur,
                            self.blabla)
            if self.def_xml.get() == 1:
                ExportToXML(dest,
                            self.dico_layer,
                            self.dico_profil,
                            '',
                            self.blabla,
                            1,
                            0)
            if self.def_odt.get() == 1:
                ExportToODT(dest,
                            self.dico_layer,
                            self.dico_fields,
                            self.dico_profil,
                            self.dico_rekur,
                            self.blabla)
            # increment the progress bar
            self.prog_layers["value"] = self.prog_layers["value"] + 1
            self.update()

        # Word catalog export
        if self.def_doc.get() == 1 and self.def_cat.get() == 1:
            self.status.set(self.blabla.get('info_cat'))
            self.update()
            DocxMerger(dest, '00_Metadator_Catalog', 'metadator_')
        else:
            pass

        # final message
        # msg = self.blabla.get('info_end2') + self.blabla.get('info_end3')
        # info(title=self.blabla.get('info_end'), message=msg)
        # opening the destination folder
        self.open_dir_file(dest)
        # cleaning up
        logging.info('Hurray! It worked! All seem to have been fine!')
        self.destroy()
        # end of function
        return

    def open_dir_file(self, target):
        """
        Open a file or a directory in the explorer of the operating system
        http://sametmax.com/ouvrir-un-fichier-avec-le-bon-programme-en-python
        """
        # check if the file or the directory exists
        if not path.exists(target):
            raise IOError('No such file: {0}'.format(target))

        # check the read permission
        if not access(target, R_OK):
            raise IOError('Cannot access file: {0}'.format(target))

        # open the directory or the file according to the os
        if opersys == 'win32':  # Windows
            proc = startfile(target)

        elif opersys.startswith('linux'):  # Linux:
            proc = subprocess.Popen(['xdg-open', target],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)

        elif opersys == 'darwin':  # Mac:
            proc = subprocess.Popen(['open', '--', target],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)

        else:
            raise NotImplementedError(
                "Your `%s` isn't a supported operating system`." % opersys)

        # end of function
        return proc
示例#7
0
class topFrame(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.setUI()

    def setUI(self):
        self.parent.title("ServoGui")
        self.pack(fill=BOTH, expand=1)
        self.comPort = StringVar(self)
        self.laststrm = StringVar(self)

        settingFrame = Frame(self, borderwidth=1, relief=RAISED)
        settingFrame.pack(fill=Y, side=LEFT)

        Label(settingFrame,
              width=50,
              text="Port Settings",
              bg="green",
              fg="black").pack(fill=X)

        ports = self.getComPorts()
        w = apply(OptionMenu, (settingFrame, self.comPort) + tuple(ports))
        w.pack(fill=X)

        BaudFrame = Frame(settingFrame)
        BaudFrame.pack(fill=X)
        Label(BaudFrame, text="Baud:").pack(side=LEFT)
        self.baud_entry = Entry(BaudFrame,
                                width=15,
                                validate="focusout",
                                validatecommand=self.baudValidate)
        self.baud_entry.pack(side=LEFT, expand=True)
        self.baud_entry.insert(0, "115200")

        Button(settingFrame, text="Open Port",
               command=self.openPort).pack(fill=X)
        Button(settingFrame, text="Close Port",
               command=self.closePort).pack(fill=X)

        StreamFrame = Frame(settingFrame)
        StreamFrame.pack()
        self.btnStartStream = Button(StreamFrame,
                                     text="Start Stream",
                                     command=self.startStream,
                                     state=DISABLED)
        self.btnStopStream = Button(StreamFrame,
                                    text="Stop Stream",
                                    command=self.stopStream,
                                    state=DISABLED)
        self.btnGetConfig = Button(StreamFrame,
                                   text="Get Config",
                                   command=self.getConfig,
                                   state=DISABLED)
        self.btnStartStream.pack(side=LEFT)
        self.btnStopStream.pack(side=LEFT)
        self.btnGetConfig.pack(side=LEFT)
        self.queue = Queue.Queue()
        self.writequeue = Queue.Queue()

        Label(settingFrame,
              width=50,
              text="Drive Settings",
              bg="green",
              fg="black").pack(fill=X)
        DriveSettingsFrame = Frame(settingFrame, relief=SUNKEN)
        DriveSettingsFrame.pack(fill=X)

        driveSettingsFrames = []
        self.driveSettingsEntries = []
        for drivesetting in drivesettings:
            driveSettingsFrames.append(Frame(DriveSettingsFrame))
            driveSettingsFrames[-1].pack(fill=X)
            Label(driveSettingsFrames[-1], text=drivesetting).pack(side=LEFT)
            self.driveSettingsEntries.append(Entry(driveSettingsFrames[-1]))
            self.driveSettingsEntries[-1].pack(side=RIGHT)
        Button(DriveSettingsFrame,
               text="Send to drive",
               command=self.sendConfig).pack(fill=X)
        Button(DriveSettingsFrame,
               text="Save config in drive",
               command=self.saveConfig).pack(fill=X)

        Label(settingFrame,
              width=50,
              textvariable=self.laststrm,
              bg="green",
              fg="black").pack(fill=X)

        #MatplotLib stuff

        f = Figure(figsize=(5, 4), dpi=100)
        self.a = f.add_subplot(311)
        self.a.set_title("Requested and actual position")
        self.b = f.add_subplot(312)
        self.b.set_title("Error")
        self.c = f.add_subplot(313)
        self.c.set_title("Current meas ADC value")

        self.canvas = FigureCanvasTkAgg(f, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)

        toolbar = NavigationToolbar2TkAgg(self.canvas, self)
        toolbar.update()
        self.canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)

        self.hall = []
        self.encoder_count = []
        self.pos_error = []
        self.requested_position = []
        self.requested_delta = []
        self.adc_value = []
        self.pid_output = []
        self.a.set_autoscaley_on(True)

        self.encoder_line, = self.a.plot([], [])
        self.error_line, = self.b.plot([], [])
        self.reqpos_line, = self.a.plot([], [])
        self.ADC_line, = self.c.plot([], [])
        self.updateCanvas()

    def baudValidate(self):
        sVal = self.baud_entry.get()
        try:
            iVal = int(sVal)
        except ValueError:
            print "Illegal baud value"
            self.baud_entry.delete(0, END)
            self.baud_entry.insert(0, "115200")
            return False
        return True

    def openPort(self):
        try:
            self.ser = serial.Serial(self.comPort.get(),
                                     int(self.baud_entry.get()),
                                     timeout=0)
        except serial.SerialException:
            print "unable to open"
            return
        self.btnStartStream['state'] = NORMAL
        self.btnStopStream['state'] = NORMAL
        self.btnGetConfig['state'] = NORMAL

        self.thread = SerialThread(self.queue, self.writequeue, self.ser)
        self.thread.daemon = True
        self.thread.start()
        self.process_serial()

    def closePort(self):
        self.thread.stop()
        self.thread.join()
        self.ser.closePort()

        self.btnStartStream['state'] = DISABLED
        self.btnStopStream['state'] = DISABLED
        self.btnGetConfig['state'] = DISABLED

    def process_serial(self):
        while self.queue.qsize():
            try:
                line = self.queue.get()
                self.handleLine(line)
            except Queue.Empty:
                pass
        self.after(100, self.process_serial)

    def startStream(self):
        self.writequeue.put(b"STREAM START \r")

    def stopStream(self):
        self.writequeue.put(b"STREAM DIE \r")

    def getConfig(self):
        self.writequeue.put(b"GET\r")

    def saveConfig(self):
        self.writequeue.put(b"SAVE \r")

    def sendConfig(self):
        for setting in drivesettings:
            dataToSend = b"SET " + setting + " " + self.driveSettingsEntries[
                drivesettings.index(setting)].get() + "\r"
            print dataToSend
            self.writequeue.put(dataToSend)
            time.sleep(0.2)

    def getComPorts(self):
        ports = serial.tools.list_ports.comports()
        portNames = []
        for port in ports:
            portNames.append(port[0])
        return portNames

    def handleLine(self, line):
        line = line.replace(" ", "")
        line = line.replace("/n", "")
        line = line.replace("/r", "")
        parts = line.split(":")
        if len(parts) > 1:
            if parts[0] == "STR":
                self.handleStr(parts[1])
                return
            if parts[0] in drivesettings:
                self.driveSettingsEntries[drivesettings.index(
                    parts[0])].delete(0, END)
                self.driveSettingsEntries[drivesettings.index(
                    parts[0])].insert(0, parts[1])

    def handleStr(self, strm):
        #format of the stream line: STR:hall;count;requestedPosition;requestedDelta;error
        parts = strm.split(";")

        self.laststrm.set(strm)
        self.hall.append(int(parts[0]))
        if len(self.hall) > 5000:
            self.hall.pop(0)

        self.encoder_count.append(parts[1])
        if len(self.encoder_count) > 5000:
            self.encoder_count.pop(0)

        self.requested_position.append(parts[2])
        if len(self.requested_position) > 5000:
            self.requested_position.pop(0)

        self.requested_delta.append(parts[3])
        if len(self.requested_delta) > 5000:
            self.requested_delta.pop(0)

        self.pos_error.append(parts[4])
        if len(self.pos_error) > 5000:
            self.pos_error.pop(0)

        self.adc_value.append(parts[5])
        if len(self.adc_value) > 5000:
            self.adc_value.pop(0)

        self.pid_output.append(parts[5])
        if len(self.pid_output) > 5000:
            self.pid_output.pop(0)

    def updateCanvas(self):

        self.encoder_line.set_xdata(range(len(self.encoder_count)))
        self.encoder_line.set_ydata(self.encoder_count)
        self.error_line.set_xdata(range(len(self.pos_error)))
        self.error_line.set_ydata(self.pos_error)
        self.reqpos_line.set_xdata(range(len(self.requested_position)))
        self.reqpos_line.set_ydata(self.requested_position)
        self.ADC_line.set_xdata(range(len(self.adc_value)))
        self.ADC_line.set_ydata(self.adc_value)
        self.a.relim()
        self.a.autoscale_view()
        self.b.relim()
        self.b.autoscale_view()
        self.c.relim()
        self.c.autoscale_view()
        self.canvas.draw()
        self.after(100, self.updateCanvas)
示例#8
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.initUI()

    def initUI(self):

        self.parent.title("Append Data")
        self.pack(fill=BOTH, expand=True)
        labelfont20 = ('Roboto', 15, 'bold')
        labelfont10 = ('Roboto', 10, 'bold')
        labelfont8 = ('Roboto', 8, 'bold')

        frame0 = Frame(self)
        frame0.pack()

        lbl0 = Label(frame0, text="Hi Nakul")
        lbl0.config(font=labelfont20)
        lbl0.pack(padx=5, pady=5)
        lbl00 = Label(frame0, text="Fill the data here")
        lbl00.config(font=labelfont10)
        lbl00.pack(padx=5, pady=5)

        ####################################
        frame1 = Frame(self)
        frame1.pack()
        frame1.place(x=50, y=100)

        lbl1 = Label(frame1, text="Name", width=15)
        lbl1.pack(side=LEFT, padx=7, pady=5)

        self.entry1 = Entry(frame1, width=20)
        self.entry1.pack(padx=5, expand=True)

        ####################################
        frame2 = Frame(self)
        frame2.pack()
        frame2.place(x=50, y=130)

        lbl2 = Label(frame2, text="F Name", width=15)
        lbl2.pack(side=LEFT, padx=7, pady=5)

        self.entry2 = Entry(frame2)
        self.entry2.pack(fill=X, padx=5, expand=True)

        ######################################
        frame3 = Frame(self)
        frame3.pack()
        frame3.place(x=50, y=160)

        lbl3 = Label(frame3, text="DOB(D/M/Y)", width=15)
        lbl3.pack(side=LEFT, padx=7, pady=5)

        self.entry3 = Entry(frame3)
        self.entry3.pack(fill=X, padx=5, expand=True)

        #######################################
        frame4 = Frame(self)
        frame4.pack()
        frame4.place(x=50, y=190)

        lbl4 = Label(frame4, text="Medium(H/E)", width=15)
        lbl4.pack(side=LEFT, padx=7, pady=5)

        self.entry4 = Entry(frame4)
        self.entry4.pack(fill=X, padx=5, expand=True)

        ##########################################
        frame5 = Frame(self)
        frame5.pack()
        frame5.place(x=50, y=225)
        MODES = [
            ("M", "Male"),
            ("F", "Female"),
        ]
        lbl5 = Label(frame5, text="Gender", width=15)
        lbl5.pack(side=LEFT, padx=7, pady=5)

        global v
        v = StringVar()
        v.set("Male")  # initialize

        for text, mode in MODES:
            b = Radiobutton(frame5, text=text, variable=v, value=mode)
            b.pack(side=LEFT, padx=10)

        ############################################
        #####printing line
        lbl5a = Label(
            text="___________________________________________________")
        lbl5a.pack()
        lbl5a.place(x=45, y=255)

        ############################################
        frame6 = Frame(self)
        frame6.pack()
        frame6.place(x=50, y=290)

        lbl6 = Label(frame6, text="Phone No:", width=15)
        lbl6.pack(side=LEFT, padx=7, pady=5)

        self.entry6 = Entry(frame6)
        self.entry6.pack(fill=X, padx=5, expand=True)

        ################################################

        frame7 = Frame(self)
        frame7.pack()
        frame7.place(x=50, y=320)

        lbl7 = Label(frame7, text="Landline No:", width=15)
        lbl7.pack(side=LEFT, padx=7, pady=5)

        self.entry7 = Entry(frame7)
        self.entry7.pack(fill=X, padx=5, expand=True)

        ###############################################
        frame8 = Frame(self)
        frame8.pack()
        frame8.place(x=50, y=350)

        lbl8 = Label(frame8, text="Email:", width=15)
        lbl8.pack(side=LEFT, padx=7, pady=5)

        self.entry8 = Entry(frame8)
        self.entry8.pack(fill=X, padx=5, expand=True)

        #############################################
        frame9 = Frame(self)
        frame9.pack()
        frame9.place(x=50, y=380)

        lbl9 = Label(frame9, text="HomeTown:", width=15)
        lbl9.pack(side=LEFT, padx=7, pady=5)

        self.entry9 = Entry(frame9)
        self.entry9.pack(fill=X, padx=5, expand=True)

        ###############################################
        frame10 = Frame(self)
        frame10.pack()
        frame10.place(x=60, y=415)

        lbl10 = Label(frame10, text="Address:")
        lbl10.pack(padx=5, pady=5)

        self.entry10 = Text(frame10, height=5, width=28)
        self.entry10.pack(padx=5, expand=True)

        ##############################################

        #############################################

        frame11 = Frame(self)
        frame11.pack()
        frame11.place(x=350, y=100)

        lbl11x = Label(frame11, text="_______Class 10th Data_______")
        lbl11x.pack(padx=0, pady=0)

        lbl11 = Label(text="%", width=15)
        lbl11.pack(side=LEFT, padx=0, pady=0)
        lbl11.place(x=350, y=130)

        self.entry11 = Entry(width=12)
        self.entry11.pack(padx=1, expand=True)
        self.entry11.place(x=420, y=130)

        lbl11a = Label(text="Passing Year", width=15)
        lbl11a.pack(padx=0, pady=2)
        lbl11a.place(x=350, y=160)

        self.entry11a = Entry(width=12)
        self.entry11a.pack(padx=1, expand=True)
        self.entry11a.place(x=420, y=160)

        lbl11b = Label(text="Board Name", width=15)
        lbl11b.pack(padx=0, pady=2)
        lbl11b.place(x=350, y=190)

        self.entry11b = Entry(width=12)
        self.entry11b.pack(padx=1, expand=True)
        self.entry11b.place(x=420, y=190)

        ####################################################
        frame12 = Frame(self)
        frame12.pack()
        frame12.place(x=510, y=100)

        lbl12x = Label(frame12, text="_______Class 12th Data_______")
        lbl12x.pack(padx=0, pady=0)

        lbl12 = Label(text="%", width=15)
        lbl12.pack(side=LEFT, padx=0, pady=0)
        lbl12.place(x=510, y=130)

        self.entry12 = Entry(width=12)
        self.entry12.pack(padx=1, expand=True)
        self.entry12.place(x=580, y=130)

        lbl12a = Label(text="Passing Year", width=15)
        lbl12a.pack(padx=0, pady=2)
        lbl12a.place(x=510, y=160)

        self.entry12a = Entry(width=12)
        self.entry12a.pack(padx=1, expand=True)
        self.entry12a.place(x=580, y=160)

        lbl12b = Label(text="Board Name", width=15)
        lbl12b.pack(padx=0, pady=2)
        lbl12b.place(x=510, y=190)

        self.entry12b = Entry(width=12)
        self.entry12b.pack(padx=1, expand=True)
        self.entry12b.place(x=580, y=190)

        #####################################################
        frame13 = Frame(self)
        frame13.pack()
        frame13.place(x=670, y=100)

        lbl13x = Label(frame13, text="________B.Tech Data_________")
        lbl13x.pack(padx=0, pady=0)

        lbl13 = Label(text="%", width=15)
        lbl13.pack(side=LEFT, padx=0, pady=0)
        lbl13.place(x=670, y=130)

        self.entry13 = Entry(width=12)
        self.entry13.pack(padx=1, expand=True)
        self.entry13.place(x=740, y=130)

        lbl13a = Label(text="Passing Year", width=15)
        lbl13a.pack(padx=0, pady=2)
        lbl13a.place(x=670, y=160)

        self.entry13a = Entry(width=12)
        self.entry13a.pack(padx=1, expand=True)
        self.entry13a.place(x=740, y=160)

        lbl13b = Label(text="College", width=15)
        lbl13b.pack(padx=0, pady=2)
        lbl13b.place(x=670, y=190)

        self.entry13b = Entry(width=12)
        self.entry13b.pack(padx=1, expand=True)
        self.entry13b.place(x=740, y=190)

        ####################################################

        frame14 = Frame(self)
        frame14.pack()
        frame14.place(x=380, y=255)

        lbl14 = Label(frame14, text="Any Other Info:")
        lbl14.pack(padx=5, pady=5)

        self.entry14 = Text(frame14, height=5, width=28)
        self.entry14.pack(padx=5, expand=True)

        frame15 = Frame(self)
        frame15.pack()
        frame15.place(x=650, y=290)

        openButton = Button(frame15,
                            text="Attatch Resume",
                            width=15,
                            command=self.openResume)
        openButton.pack(padx=5, pady=5)
        self.entry15 = Entry(frame15)
        self.entry15.pack(fill=X, padx=4, expand=True)
        #############################################################
        frame16 = Frame(self)
        frame16.pack()
        frame16.place(x=450, y=500)

        closeButton = Button(frame16,
                             text="SUBMIT",
                             width=35,
                             command=self.getDatax)
        closeButton.pack(padx=5, pady=5)

        #######################################
        framexxx = Frame(self)
        framexxx.pack()
        framexxx.place(x=700, y=600)
        self.xxx = Label(framexxx, text="Recent Changes Will Appear Here")
        self.xxx.config(font=labelfont8)
        self.xxx.pack()

        #######################################

        frame000 = Frame(self)
        frame000.pack()
        frame000.place(x=50, y=600)

        self.lbl000 = Label(frame000,
                            text="Beta/Sample2.0 | (c) Nakul Rathore")
        self.lbl000.config(font=labelfont8)
        self.lbl000.pack(padx=5, pady=5)

    def openResume(self):
        ftypes = [('All files', '*')]
        dlg = tkFileDialog.Open(self, filetypes=ftypes, initialdir='C:/Users/')
        global x15
        fl = dlg.show()
        #file name
        x15 = fl
        temp1 = os.path.basename(fl)
        global temp2
        temp2 = os.path.splitext(temp1)[0]

        self.entry15.delete(0, 'end')
        self.entry15.insert(0, temp2)

        #####################

    def getDatax(self):
        x1 = self.entry1.get()
        x2 = self.entry2.get()
        x3 = self.entry3.get()
        x4 = self.entry4.get()

        x5 = v.get()

        x6 = int(self.entry6.get())
        x7 = int(self.entry7.get())
        x8 = self.entry8.get()
        x9 = self.entry9.get()

        x10 = self.entry10.get('1.0', 'end')

        x11 = int(self.entry11.get())
        x11a = int(self.entry11a.get())
        x11b = self.entry11b.get()

        x12 = int(self.entry12.get())
        x12a = int(self.entry12a.get())
        x12b = self.entry12b.get()

        x13 = int(self.entry13.get())
        x13a = int(self.entry13a.get())
        x13b = self.entry13b.get()

        x14 = self.entry14.get('1.0', 'end')

        list1 = [
            x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x11a, x11b, x12,
            x12a, x12b, x13, x13a, x13b, x14,
            "=HYPERLINK(" + "\"" + x15 + "\"" + "," + "\"" + temp2 + "\"" + ")"
        ]

        wb = openpyxl.load_workbook('..\database\database.xlsx')
        ws = wb.active
        print(wb.get_sheet_names())
        max_row = ws.get_highest_row()
        #max_col = ws.get_highest_column()
        max_col = 21
        print max_row

        for i in xrange(1, max_col + 1):
            #print list1[i]
            ws.cell(row=max_row + 1, column=i).value = list1[i - 1]
        ws.cell(row=max_row + 1,
                column=max_col).font = Font(color="0000FF", underline='single')
        ws.cell(row=max_row + 1,
                column=max_col).alignment = Alignment(horizontal='center')
        wb.save('..\database\database.xlsx')

        self.entry1.delete(0, 'end')
        self.entry2.delete(0, 'end')
        self.entry3.delete(0, 'end')
        self.entry4.delete(0, 'end')

        self.entry6.delete(0, 'end')
        self.entry7.delete(0, 'end')
        self.entry8.delete(0, 'end')
        self.entry9.delete(0, 'end')
        self.entry10.delete('1.0', '2.0')
        self.entry11.delete(0, 'end')
        self.entry11a.delete(0, 'end')
        self.entry11b.delete(0, 'end')
        self.entry12.delete(0, 'end')
        self.entry12a.delete(0, 'end')
        self.entry12b.delete(0, 'end')
        self.entry13.delete(0, 'end')
        self.entry13a.delete(0, 'end')
        self.entry13b.delete(0, 'end')

        self.entry14.delete('1.0', '2.0')

        self.xxx.config(text="Recent Changes Made For : " + x1)
class IniGenGui(Frame):

  def __init__(self, parent):
    Frame.__init__(self, parent)
    self.parent = parent
    self.initUIGlobals()

  def initUIGlobals(self):
   
    self.parent.title("Ini Generator")

    Style().configure("TButton", padding=(0, 0, 0, 0), font='serif 10')

    f1 = Frame(self)
    f1.grid(row=0, column=0, padx=10, sticky=N+S+E+W)

    f11 = LabelFrame(f1, text="Algorithms to Run")
    f11.grid(row=0, column=0)
    row = 0

    self.check_algs_value_list = []
    self.check_algs_map = {}
    for alg in algorithms:
      if alg == 'clean':
        continue
      check_alg_value = IntVar()
      check_alg = Checkbutton(f11, text=alg, variable=check_alg_value, justify=LEFT, width=25)
      check_alg.grid(row=row, column=0, sticky=W+E)
      self.check_algs_value_list.append(check_alg_value)
      self.check_algs_map[alg] = check_alg_value
      row += 1

    f111 = Frame(f11)
    f111.grid(row=row, column=0)

    button_checkall = Button(f111, text="All", command=self.checkall)
    button_checkall.grid(row=0, column=0, sticky=W+E)
    button_uncheckall = Button(f111, text="None", command=self.uncheckall)
    button_uncheckall.grid(row=0, column=1, sticky=W+E)

    row = 0

    f12 = Frame(f1)
    f12.grid(row=1, column=0, pady=20, sticky=S+W+E)

    f121 = LabelFrame(f12, text='Location of uPMU')
    f121.grid(row=0, column=0)

    self.radio_loc_string = StringVar()
    locations.append('Other Location')
    for loc in locations:
      radio_loc = Radiobutton(f121, text=loc, variable=self.radio_loc_string, value=loc, command=self.set_loc, justify=LEFT, width=25)
      radio_loc.grid(row=row, column=0, sticky=W+E)
      row += 1

    self.entry_otherloc = Entry(f121)

    f2 = Frame(self)
    f2.grid(row=0, column=1, padx=10, sticky=N+S+E+W)

    f21 = LabelFrame(f2, text='Name of uPMU (raw)')
    f21.grid(row=0)
    row = 0

    f211 = Frame(f21)
    f211.grid(row=row)
    row += 1

    self.entry_namesearch = Entry(f211)
    self.entry_namesearch.grid(row=0, column=0, sticky=E+W)

    button_namesearch = Button(f211, text="Search", command=self.namesearch)
    button_namesearch.grid(row=0, column=1, sticky=W+E)

    self.lstbx_namelist = Listbox(f21)
    self.lstbx_namelist.bind("<Double-Button-1>", self.namelist_select)
    self.lstbx_namelist.grid(row=row, sticky=W+E)
    row += 1

    f212 = Frame(f21)
    f212.grid(row=row)
    row += 1

    label_nameselected = Label(f212, text="Selected:")
    label_nameselected.grid(row=0, column=0)

    self.entry_nameselected = Entry(f212, state=DISABLED)
    self.entry_nameselected.grid(row=0, column=1, sticky=W+E)

    f22 = LabelFrame(f2, text="Name of uPMU (abbr)")
    f22.grid(row=1, sticky=W+E, pady=10)
    self.entry_name = Entry(f22, width=30)
    self.entry_name.grid(row=0, column=0, sticky=E+W)

    f23 = LabelFrame(f2, text="Name of Reference uPMU (clean)")
    f23.grid(row=2, pady=10)
    row = 0

    f231 = Frame(f23)
    f231.grid(row=row)
    row += 1

    self.entry_refnamesearch = Entry(f231)
    self.entry_refnamesearch.grid(row=0, column=0, sticky=E+W)

    button_refnamesearch = Button(f231, text="Search", command=self.refnamesearch)
    button_refnamesearch.grid(row=0, column=1, sticky=W+E)

    self.lstbx_refnamelist = Listbox(f23)
    self.lstbx_refnamelist.bind("<Double-Button-1>", self.refnamelist_select)
    self.lstbx_refnamelist.grid(row=row, sticky=W+E)
    row += 1

    f232 = Frame(f23)
    f232.grid(row=row)
    row += 1

    label_refnameselected = Label(f232, text="Selected:")
    label_refnameselected.grid(row=0, column=0)

    self.entry_refnameselected = Entry(f232, state=DISABLED)
    self.entry_refnameselected.grid(row=0, column=1, sticky=W+E)

    button_gen = Button(self, text="Generate Files", command=self.generate_files)
    button_gen.grid(row=1, column=0, columnspan=2, sticky=W+E)

    self.pack()

  def generate_files(self):
    algs = []
    for alg in self.check_algs_map:
      if self.check_algs_map[alg].get() == 1:
        algs.append(alg)

    if self.radio_loc_string.get() == "Other Location":
      location = self.entry_otherloc.get()
    else:
      location = self.radio_loc_string.get()

    name_raw = self.entry_nameselected.get()
    name = self.entry_name.get()
    ref_name = self.entry_refnameselected.get()

    uuid_map = self.get_uuid_map(name_raw)
    reference_uuid_map = self.get_ref_uuid_map(ref_name)

    IniGenAutomation(location, name_raw, name, uuid_map, ref_name, reference_uuid_map, algs)

  def namesearch(self):
    searchterm = self.entry_namesearch.get()
    searchphrase = '/upmu/%{0}%/%'.format(searchterm)
    search_results = self.search(searchterm, searchphrase)
    self.lstbx_namelist.delete(0, END)
    if len(search_results) == 0:
      tkMessageBox.showwarning('Search Error', 'No matches from search for \'{0}\''.format(searchterm))
    else:
      for result in search_results:
        self.lstbx_namelist.insert(END, result)
        
  def refnamesearch(self):
    searchterm = self.entry_refnamesearch.get()
    searchphrase = '/Clean/%{0}%/%'.format(searchterm)
    search_results = self.search(searchterm, searchphrase, ref=True)
    self.lstbx_refnamelist.delete(0, END)
    if len(search_results) == 0:
      tkMessageBox.showwarning('Search Error', 'No matches from search for \'{0}\''.format(searchterm))
    else:
      for result in search_results:
        self.lstbx_refnamelist.insert(END, result)
  
  def search(self, searchterm, searchphrase, ref=False):
    connection = _mysql.connect(host="128.32.37.231", port=3306, user="******",
                                passwd="moresecuredataftw", db='upmu')
    connection.query("SELECT * FROM uuidpathmap WHERE path LIKE '{0}'".format(searchphrase))
    results = connection.store_result()
    queried_data = {}
    result = results.fetch_row()
    while result != tuple():
      queried_data[result[0][0]] = result[0][1]
      result = results.fetch_row()
    search_results = set()
    for path in queried_data:
      dirs = path.split('/')
      if ref:
        if searchterm in '/'.join(dirs[2:-2]):
          search_results.add('/'.join(dirs[2:-2]))
      else:
        if searchterm in '/'.join(dirs[2:-1]):
          search_results.add('/'.join(dirs[2:-1]))
    return search_results

  def set_loc(self):
    if self.radio_loc_string.get() == "Other Location":
      self.entry_otherloc.grid(sticky=W+E)
    else:
      self.entry_otherloc.grid_forget()

  def checkall(self):
    for check in self.check_algs_value_list:
      check.set(1)
  
  def uncheckall(self):
    for check in self.check_algs_value_list:
      check.set(0)

  def namelist_select(self, event):
    selected_index = self.lstbx_namelist.curselection()
    selected = self.lstbx_namelist.get(selected_index)
    self.entry_nameselected.configure(state=NORMAL)
    self.entry_nameselected.delete(0, END)
    self.entry_nameselected.insert(0, selected)
    self.entry_nameselected.configure(state=DISABLED)

  def refnamelist_select(self, event):
    selected_index = self.lstbx_refnamelist.curselection()
    selected = self.lstbx_refnamelist.get(selected_index)
    self.entry_refnameselected.configure(state=NORMAL)
    self.entry_refnameselected.delete(0, END)
    self.entry_refnameselected.insert(0, selected)
    self.entry_refnameselected.configure(state=DISABLED)

  def get_uuid_map(self, name):
    uuid_map = {}
    connection = _mysql.connect(host="128.32.37.231", port=3306, user="******",
                                passwd="moresecuredataftw", db='upmu')
    connection.query("SELECT * FROM uuidpathmap WHERE path LIKE '/upmu/{0}/%'".format(name))
    results = connection.store_result()
    result = results.fetch_row()
    while result != tuple():
      path = result[0][0].split('/')
      uuid_map[path[-1]] = result[0][1]
      result = results.fetch_row()
    return uuid_map
    
  def get_ref_uuid_map(self, name):
    uuid_map = {}
    connection = _mysql.connect(host="128.32.37.231", port=3306, user="******",
                                passwd="moresecuredataftw", db='upmu')
    connection.query("SELECT * FROM uuidpathmap WHERE path LIKE '/Clean/{0}/%'".format(name))
    results = connection.store_result()
    result = results.fetch_row()
    while result != tuple():
      path = result[0][0].split('/')
      uuid_map[path[-2]] = result[0][1]
      result = results.fetch_row()
    return uuid_map
示例#10
0
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        
        self.initUI()
        
        
    def initUI(self):
        self.parent.title("Filter Data")
        self.pack(fill=BOTH, expand=True)
        labelfont20 = ('Roboto', 15, 'bold')
        labelfont10 = ('Roboto', 10, 'bold')
        labelfont8 = ('Roboto', 8, 'bold')
        
        frame0 = Frame(self)
        frame0.pack()
        
        lbl0 = Label(frame0, text="Hi Nakul")
        lbl0.config(font=labelfont20)    
        lbl0.pack( padx=5, pady=5)
        lbl00 = Label(frame0, text="Filter Data")
        lbl00.config(font=labelfont10)
        lbl00.pack( padx=5, pady=5)
        
        ####################################
        
        
        ##########################################
        
        
        ############################################
        #####printing line
        
        lbl5a = Label(text="__________________________________")
        lbl5a.pack()
        lbl5a.place(x=170, y=300)
        
        lbl5b = Label(text="__________________________________")
        lbl5b.pack()
        lbl5b.place(x=480, y=300)
        
        self.lbl5c = Label(text="Search Result Will Appear Here")
        self.lbl5c.pack()
        self.lbl5c.place(x=170, y=320)
        
        self.lbl5d = Label(text="File Name Will Appear Here")
        self.lbl5d.pack()
        self.lbl5d.place(x=480, y=320)
        
        ############################################
        
        
        #############################################
        
        ###############################################
        
        
        ##############################################
        
        #############################################
        
        frame11 = Frame(self)
        frame11.pack()
        frame11.place(x=200, y=100)
        
        lbl11x = Label(frame11,text="Class 10th %")
        lbl11x.pack(padx=0, pady=0)
        
               

        self.entry11 = Entry(width=12)
        self.entry11.pack(padx=1, expand=True)
        self.entry11.place(x=200, y=120) 
        
        
        
        
        ####################################################
        frame12 = Frame(self)
        frame12.pack()
        frame12.place(x=380, y=100)
        
        lbl12x = Label(frame12,text="Class 12th %")
        lbl12x.pack(padx=0, pady=0)
        
               

        self.entry12 = Entry(width=12)
        self.entry12.pack(padx=1, expand=True)
        self.entry12.place(x=380, y=120) 
        
        

        #####################################################
        frame13 = Frame(self)
        frame13.pack()
        frame13.place(x=550, y=100)
        
        lbl13x = Label(frame13,text="B.Tech %")
        lbl13x.pack(padx=0, pady=0)
        
               

        self.entry13 = Entry(width=12)
        self.entry13.pack(padx=1, expand=True)
        self.entry13.place(x=550, y=120) 
        
        
        
        ####################################################
        frame9 = Frame(self)
        frame9.pack()
        frame9.place(x=350, y=160)
        
        lbl9 = Label(frame9, text="HomeTown:")
        lbl9.pack()        

        self.entry9 = Entry(frame9)
        self.entry9.pack(fill=X, padx=5, expand=True)
        
        
             
         
        
        
        #############################################################
        frame16 = Frame(self)
        frame16.pack()
        frame16.place(x=190, y=250)
        closeButton = Button(frame16, text="Filter",width=20,command=self.getDatax2)
        closeButton.pack(padx=5, pady=5)
        
        #######################################
        frame17 = Frame(self)
        frame17.pack()
        frame17.place(x=500, y=250)
        closeButton = Button(frame17, text="Save & Open",width=20,command=self.getDatax3)
        closeButton.pack(padx=5, pady=5)
        
        #######################################
        
        frame000 = Frame(self)
        frame000.pack()
        frame000.place(x=50, y=600)
        
        self.lbl000= Label(frame000, text="Beta/Sample2.0 | (c) Nakul Rathore")
        self.lbl000.config(font=labelfont8)    
        self.lbl000.pack( padx=5, pady=5)
        
        
        
    def getDatax2(self):
        x1 = self.entry11.get()
        if x1 != "":
            x1 = int(x1)
        
        x2 = self.entry12.get()
        if x2 != "":
            x2 = int(x2)
        x3 = self.entry13.get()
        if x3 != "":
            x3 = int(x3)
        x4 = self.entry9.get()
        list1=[x1,x2,x3,x4]
        
        wb = openpyxl.load_workbook('..\database\database.xlsx')
        ws = wb.active
        print(wb.get_sheet_names())
        max_row = ws.get_highest_row()
        max_col = ws.get_highest_column()
        global temp
        global tempx
        temp = []
        tempx = []
        for i in xrange(2,max_row+1):
            temp.append(i)
        #print temp
        
        if isinstance(x1, int):
            for i in temp:
                if ws.cell(row = i, column = 11).value >= x1:
                    tempx.append(i)
            temp = tempx
            tempx = []
            print temp
            
        if isinstance(x2, int):
            for i in temp:
                if ws.cell(row = i, column = 14).value >= x2:
                    tempx.append(i)
            temp = tempx
            tempx = []
            print temp
        if isinstance(x3, int):
            for i in temp:
                if ws.cell(row = i, column = 17).value >= x3:
                    tempx.append(i)
            temp = tempx
            tempx = []
            print temp
            
        if isinstance(x3, str) and x3 != "":
            for i in temp:
                if ws.cell(row = i, column = 9).value == x4:
                    tempx.append(i)
            temp = tempx
            tempx = []
            print temp
        self.lbl5c.config(text=""+str(len(temp))+" result(s) found")
            
    def getDatax3(self):
        import datetime
        now = datetime.datetime.now()
        now = now.replace(microsecond=0,second = 0)
        now = now.strftime("%d_%B_%y,%I-%M_%p")
        now = now+".xlsx"
        
       
        
        
        if len(temp) != 0:
            wb1 = openpyxl.load_workbook('..\database\database.xlsx')
            ws1 = wb1.active
            wb2 = openpyxl.load_workbook('..\_frame\_frame.xlsx')
            ws2 = wb2.active
        
            for i in xrange(2,len(temp)+2):
                for j in xrange(1,22):
                    ws2.cell(row = i, column = j).value = ws1.cell(row = temp[i-2], column = j).value
        
        wb2.save('..\Result\\'+now)
        tempstart = '..\Result\\'+now
        self.lbl5d.config(text="File is :: "+"\""+now+"\"")
        os.system("start "+tempstart)
        
        self.entry11.delete(0, 'end')
        self.entry12.delete(0, 'end')
        self.entry13.delete(0, 'end')
        self.entry9.delete(0, 'end')
示例#11
0
文件: gui.py 项目: saadraza128/CHEWD
class CHEWDDialog(ModelessDialog):
    name = "Energy Visualizer"
    buttons = ("Apply", "Close")
    help = ("Energy.html", CHEWD)
    title = "CHemical Energy Wise Decomposition"

    def fillInUI(self, parent):

        #parent.resizable(0, 0)
        frame4 = Frame(parent)
        frame4.grid(row=0, column=0, sticky="nsew")
        self.wat = IntVar()
        self.wat.set(1)
        self.waterswap = Checkbutton(frame4,
                                     text="Water Swap",
                                     command=self.optionws,
                                     variable=self.wat)
        self.waterswap.grid(row=0, column=0)
        self.lig = IntVar()
        self.lig.set(0)
        self.ligandswap = Checkbutton(frame4,
                                      text="Ligand Swap",
                                      command=self.optionls,
                                      variable=self.lig)
        self.ligandswap.grid(row=0, column=1)
        self.mm = IntVar()
        self.mm.set(0)
        self.mmpbsa = Checkbutton(frame4,
                                  text="MMPBSA",
                                  command=self.optionmm,
                                  variable=self.mm)
        self.mmpbsa.grid(row=0, column=2)

        frame1 = Frame(parent)
        frame1.grid(row=1, column=0, sticky="nsew")
        lbl1 = Label(frame1, text="Log file folder", width=12)
        lbl1.grid(row=0, column=0)
        self.entry1 = Entry(frame1)
        self.entry1.grid(row=0, column=1, columnspan=4, sticky=W + E)
        self.browserButton = Button(frame1,
                                    text="Browser",
                                    command=self.onOpen)
        self.browserButton.grid(row=0, column=5, sticky="e")

        lbl2 = Label(frame1, text="MMPBSA log file", width=12)
        lbl2.grid(row=1, column=0)
        self.entry2 = Entry(frame1, state=DISABLED)
        self.entry2.grid(row=1, column=1, columnspan=4, sticky=W + E)
        self.browserButtonMM = Button(frame1,
                                      text="Browser",
                                      command=self.onOpenMM,
                                      state=DISABLED)
        self.browserButtonMM.grid(row=1, column=5, sticky="e")

        lbl3 = Label(frame1, text="MMPBSA PDB file", width=12)
        lbl3.grid(row=2, column=0)
        self.entry3 = Entry(frame1, state=DISABLED)
        self.entry3.grid(row=2, column=1, columnspan=4, sticky=W + E)
        self.browserButtonPDB = Button(frame1,
                                       text="Browser",
                                       command=self.onOpenPDB,
                                       state=DISABLED)
        self.browserButtonPDB.grid(row=2, column=5, sticky="e")

        lbl4 = Label(frame1, text="Ligand Name", width=12)
        lbl4.grid(row=3, column=0)
        self.entry4 = Entry(frame1)
        self.entry4.grid(row=3, column=1)
        self.lblswap = Label(frame1,
                             text="Swap Ligand",
                             width=12,
                             state=DISABLED)
        self.lblswap.grid(row=3, column=2)
        self.swapentry = Entry(frame1, state=DISABLED)
        self.swapentry.grid(row=3, column=3)
        self.l1v = IntVar()
        self.l1v.set(1)
        self.lig1ck = Checkbutton(frame1,
                                  text="Ligand 1",
                                  command=self.changelig1,
                                  state=DISABLED,
                                  variable=self.l1v)
        self.lig1ck.grid(row=4, column=0)
        self.l2v = IntVar()
        self.l2v.set(0)
        self.lig2ck = Checkbutton(frame1,
                                  text="Ligand 2",
                                  command=self.changelig2,
                                  state=DISABLED,
                                  variable=self.l2v)
        self.lig2ck.grid(row=4, column=2)
        lbl5 = Label(frame1, text="Display Radius", width=12)
        lbl5.grid(row=5, column=0)
        self.entry5 = Entry(frame1)
        self.entry5.grid(row=5, column=1)
        self.entry5.insert(0, "5.0")
        self.sv = IntVar()
        self.sv.set(0)
        self.surface = Checkbutton(frame1,
                                   text="View Surface",
                                   command=self.viewsurface,
                                   variable=self.sv)
        self.surface.grid(row=5, column=2)
        self.vl = IntVar()
        self.vl.set(1)
        self.label = Checkbutton(frame1,
                                 text="View Label",
                                 command=self.viewlabel,
                                 variable=self.vl)
        self.label.grid(row=5, column=3)

        lbl6 = Label(frame1, text="Min Value", width=12)
        lbl6.grid(row=6, column=0)
        self.entry6 = Entry(frame1)
        self.entry6.grid(row=6, column=1)
        self.entry6.insert(0, "-5")
        lbl7 = Label(frame1, text="Max Value", width=12)
        lbl7.grid(row=6, column=2)
        self.entry7 = Entry(frame1)
        self.entry7.grid(row=6, column=3)
        self.entry7.insert(0, "+5")

        lbl8 = Label(frame1, text="Starting log file", width=12)
        lbl8.grid(row=7, column=0)
        self.entry8 = Entry(frame1)
        self.entry8.grid(row=7, column=1)
        self.entry8.insert(0, "400")
        lbl9 = Label(frame1, text="Ending log file", width=12)
        lbl9.grid(row=7, column=2)
        self.entry9 = Entry(frame1)
        self.entry9.grid(row=7, column=3)
        self.entry9.insert(0, "1000")

        frame2 = Frame(parent)
        frame2.grid(row=2, column=0, sticky="nsew")
        self.vsb = Scrollbar(frame2, orient="vertical", command=self.OnVsb)
        self.vsb.grid(row=1, column=3, sticky="ns")
        self.lb1 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb1.grid(row=1, column=0)
        self.lb2 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb2.grid(row=1, column=1)
        self.lb3 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb3.grid(row=1, column=2)

        self.b1 = Button(frame2,
                         text="Residue Number",
                         state=DISABLED,
                         command=lambda: self.sortdata(0))
        self.b1.grid(row=0, column=0, sticky=W + E)
        self.b2 = Button(frame2,
                         text="Residue Name",
                         state=DISABLED,
                         command=lambda: self.sortdata(1))
        self.b2.grid(row=0, column=1, sticky=W + E)
        self.b3 = Button(frame2,
                         text="Energy Value",
                         state=DISABLED,
                         command=lambda: self.sortdata(2))
        self.b3.grid(row=0, column=2, sticky=W + E)

        self.lb1.bind("<<ListboxSelect>>", self.OnSelect)
        self.lb1.bind("<MouseWheel>", self.OnMouseWheel)
        self.lb2.bind("<<ListboxSelect>>", self.OnSelect)
        self.lb2.bind("<MouseWheel>", self.OnMouseWheel)
        self.lb3.bind("<<ListboxSelect>>", self.OnSelect)
        self.lb3.bind("<MouseWheel>", self.OnMouseWheel)

        frame3 = Frame(parent)
        frame3.grid(row=3, column=0, sticky="nsew")

        self.previous = Button(frame3,
                               text="Previous Frame",
                               state=DISABLED,
                               command=self.prevframe)
        self.previous.grid(row=0, column=0, sticky=W + E)
        self.scale = Scale(frame3,
                           command=self.onScale,
                           state=DISABLED,
                           orient=HORIZONTAL,
                           length=320,
                           showvalue=0)
        self.scale.grid(row=0, column=1, sticky=W + E)
        self.next = Button(frame3,
                           text="Next Frame",
                           state=DISABLED,
                           command=self.nextframe)
        self.next.grid(row=0, column=2, sticky=W + E)

        self.var = IntVar()
        v = 000
        self.var.set(v)
        self.label = Label(frame3, text=0, textvariable=self.var)
        self.label.grid(row=0, column=3)

        ToolTip(lbl1, "Load the result directory of Sire Analysis")
        ToolTip(self.browserButton,
                "Load the result directory of Sire Analysis")
        ToolTip(lbl4, "Enter the name of the Ligand in your coordinate file")
        ToolTip(
            lbl5,
            "The radially distributed zone around ligand you want to be displayed"
        )
        ToolTip(
            lbl6,
            "Minimum scale value for the color distribution and it will be treated as blue"
        )
        ToolTip(
            lbl7,
            "Maximum scale value for the color distribution and it will be treated as red"
        )

    def viewlabel(self):
        if (load > 0):
            if (self.wat.get() == 1):
                CHEWD.togglelabelws(self.vl.get(), str(self.scale.get()),
                                    self.entry4.get(), self.entry5.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                CHEWD.togglelabells(self.vl.get(), str(self.scale.get()), vl,
                                    self.entry5.get(), hl)
            elif (self.mm.get() == 1):
                CHEWD.togglelabelws(self.vl.get(), "0", self.entry4.get(),
                                    self.entry5.get())

    def viewsurface(self):
        if (load > 0):
            CHEWD.togglesurface(self.sv.get())

    def optionws(self):
        if (self.wat.get() == 1):
            self.lig.set(0)
            self.mm.set(0)
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)
        else:
            self.wat.set(0)
            self.lig.set(1)
            self.mm.set(0)
            self.swapentry.config(state="normal")
            self.lig1ck.config(state="normal")
            self.lig2ck.config(state="normal")
            self.lblswap.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def optionls(self):
        if (self.lig.get() == 1):
            self.wat.set(0)
            self.mm.set(0)
            self.swapentry.config(state="normal")
            self.lig1ck.config(state="normal")
            self.lig2ck.config(state="normal")
            self.lblswap.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)
        else:
            self.lig.set(0)
            self.mm.set(0)
            self.wat.set(1)
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def optionmm(self):
        if (self.mm.get() == 1):
            self.lig.set(0)
            self.wat.set(0)
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry8.config(state=DISABLED)
            self.entry9.config(state=DISABLED)
            self.entry1.config(state=DISABLED)
            self.browserButton.config(state=DISABLED)
            self.entry2.config(state="normal")
            self.entry3.config(state="normal")
            self.browserButtonMM.config(state="normal")
            self.browserButtonPDB.config(state="normal")
        else:
            self.wat.set(1)
            self.lig.set(0)
            self.mm.set(0)
            self.entry8.config(state="normal")
            self.entry9.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def changelig1(self):
        if (self.l1v.get() == 1):
            self.l2v.set(0)
        else:
            self.l2v.set(1)
        if (load > 0):
            if (self.l1v.get() == 1):
                vl = self.entry4.get()
                hl = self.swapentry.get()
            if (self.l2v.get() == 1):
                vl = self.swapentry.get()
                hl = self.entry4.get()
            CHEWD.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                               self.entry7.get(), prevz, str(self.scale.get()),
                               hl, self.vl.get())

    def changelig2(self):
        if (self.l2v.get() == 1):
            self.l1v.set(0)
        else:
            self.l1v.set(1)
        if (load > 0):
            if (self.l1v.get() == 1):
                vl = self.entry4.get()
                hl = self.swapentry.get()
            if (self.l2v.get() == 1):
                vl = self.swapentry.get()
                hl = self.entry4.get()
            CHEWD.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                               self.entry7.get(), prevz, str(self.scale.get()),
                               hl, self.vl.get())

    def loadmmpbsaresults(self):
        fp = open(self.entry2.get(), "r")
        resv = list()
        for line in fp:
            t = line.split(',')
            t2 = t[0].split()
            if (len(t) == 20 and len(t2) == 2 and t2[0] != self.entry4.get()):
                resv.append([int(t2[1]), float(t[17]), t2[0]])
            matchObj = re.match(r'Sidechain Energy Decomposition:', line,
                                re.M | re.I)
            if matchObj:
                break
        self.lb1.delete(0, END)
        self.lb2.delete(0, END)
        self.lb3.delete(0, END)
        x = len(resv)
        for i in range(x):
            self.lb1.insert(END, resv[i][0])
            self.lb2.insert(END, resv[i][2])
            self.lb3.insert(END, resv[i][1])
        fp = open(tempfile.gettempdir() + "/temp.txt", "w")
        fc = open(tempfile.gettempdir() + "/clear.txt", "w")
        fp.write("attribute: sireEnergy\n")
        fp.write("recipient: residues\n")
        fc.write("attribute: sireEnergy\n")
        fc.write("recipient: residues\n")
        for i in range(x):
            fp.write("\t:" + str(resv[i][0]) + "\t" + str(resv[i][1]) + "\n")
            fc.write("\t:" + str(resv[i][0]) + "\t0.0\n")
        fp.close()
        fc.close()
        self.b1.config(state="normal")
        self.b2.config(state="normal")
        self.b3.config(state="normal")

    def changestate(self):
        x = list()
        tempx = list()
        if (self.wat.get() == 1):
            base = os.listdir(self.entry1.get())
        else:
            base = os.listdir(self.entry1.get() + "/")
        for a in base:
            if a.endswith(".log"):
                tempx.append(a)
        tempx.sort()
        tlen = len(tempx)
        ia = int(self.entry8.get()) - 1
        while (ia <= int(self.entry9.get()) and ia < tlen):
            x.append(tempx[ia])
            ia += 1
        resv = list()
        c = 0
        i = 0
        for fn in x:
            if (self.wat.get() == 1):
                fp = open(self.entry1.get() + "/" + fn, "r")
            else:
                fp = open(self.entry1.get() + "/" + fn, "r")
            if (c == 0):
                for line in fp:
                    t = line.split()
                    if (len(t) == 8):
                        if (t[0] == "Residue("):
                            resv.append([int(t[3]), float(t[5]), t[1]])
                    if (line == "PROTEIN BOX WATER FREE ENERGY COMPONENTS\n"):
                        c = c + 1
                        i = 0
                        break
            else:
                for line in fp:
                    t = line.split()
                    if (len(t) == 8):
                        if (t[0] == "Residue("):
                            resv[i][1] = resv[i][1] + float(t[5])
                            i = i + 1
                    if (line == "PROTEIN BOX WATER FREE ENERGY COMPONENTS\n"):
                        c = c + 1
                        i = 0
                        break
            fp.close()
        x = len(resv)
        self.lb1.delete(0, END)
        self.lb2.delete(0, END)
        self.lb3.delete(0, END)
        for i in range(x):
            resv[i][1] = resv[i][1] / c
        for i in range(x):
            self.lb1.insert(END, resv[i][0])
            self.lb2.insert(END, resv[i][2])
            self.lb3.insert(END, round(resv[i][1], 3))

        fp = open(tempfile.gettempdir() + "/temp.txt", "w")
        fc = open(tempfile.gettempdir() + "/clear.txt", "w")
        fp.write("attribute: sireEnergy\n")
        fp.write("recipient: residues\n")
        fc.write("attribute: sireEnergy\n")
        fc.write("recipient: residues\n")
        for i in range(x):
            fp.write("\t:" + str(resv[i][0]) + "\t" + str(resv[i][1]) + "\n")
            fc.write("\t:" + str(resv[i][0]) + "\t0.0\n")
        fp.close()
        fc.close()
        self.b1.config(state="normal")
        self.b2.config(state="normal")
        self.b3.config(state="normal")

    def prevframe(self):
        global prevz, load
        if (load > 0):
            self.scale.set(self.scale.get() - 1)

    def nextframe(self):
        global prevz, load
        if (load > 0):
            self.scale.set(self.scale.get() + 1)

    def onScale(self, val):
        global prevz, load
        if (load > 0):
            v = self.lig1pdb[int(float(val))][14:19]
            self.var.set(v)
            if (self.scale.get() == 0):
                self.previous.config(state=DISABLED)
            if (self.scale.get() == len(self.lig1pdb) - 2):
                self.next.config(state="normal")
            if (self.scale.get() == 1):
                self.previous.config(state="normal")
            if (self.scale.get() == len(self.lig1pdb) - 1):
                self.next.config(state=DISABLED)
            if (self.wat.get() == 1):
                CHEWD.wsupdateview(self.entry4.get(), self.entry5.get(),
                                   self.entry6.get(), self.entry7.get(), prevz,
                                   str(self.scale.get()), self.vl.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                CHEWD.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                                   self.entry7.get(), prevz,
                                   str(self.scale.get()), hl, self.vl.get())

    def OnSelect(self, val):
        global prev
        sender = val.widget
        idx = sender.curselection()
        dis = self.lb1.get(idx)
        if (self.wat.get() == 1):
            CHEWD.wslistdisplay(self.entry4.get(), self.entry5.get(), prev,
                                dis, str(self.scale.get()), self.vl.get())
        elif (self.lig.get() == 1):
            if (self.l1v.get() == 1):
                vl = self.entry4.get()
                hl = self.swapentry.get()
            if (self.l2v.get() == 1):
                vl = self.swapentry.get()
                hl = self.entry4.get()
            CHEWD.lslistdisplay(vl, self.entry5.get(), prev, dis,
                                str(self.scale.get()), hl, self.vl.get())
        elif (self.mm.get() == 1):
            CHEWD.mmlistdisplay(self.entry4.get(), self.entry5.get(), prev,
                                dis, "0", self.vl.get())
        prev = dis

    def sortdata(self, sc):
        global dr1, dr2, dr3
        tableData1 = self.lb1.get(0, END)
        tableData2 = self.lb2.get(0, END)
        tableData3 = self.lb3.get(0, END)

        data = list()
        nv = len(tableData1)
        for x in range(nv):
            data.append([tableData1[x], tableData2[x], tableData3[x]])

        if (sc == 0):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b1.cget('text')
            if dr1 == 1: self.b1.config(text='[+] ' + lab)
            else: self.b1.config(text='[-] ' + lab)
            data.sort(key=lambda s: (s[sc]), reverse=dr1 == 1)
            dr1 = dr1 * -1
        if (sc == 1):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b2.cget('text')
            if dr2 == 1: self.b2.config(text='[+] ' + lab)
            else: self.b2.config(text='[-] ' + lab)
            data.sort(key=lambda s: (s[sc]), reverse=dr2 == 1)
            dr2 = dr2 * -1
        if (sc == 2):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b3.cget('text')
            if dr3 == 1: self.b3.config(text='[+] ' + lab)
            else: self.b3.config(text='[-] ' + lab)
            data.sort(key=lambda s: (s[sc]), reverse=dr3 == 1)
            dr3 = dr3 * -1
        nv = len(data)
        self.lb1.delete(0, 'end')
        self.lb2.delete(0, 'end')
        self.lb3.delete(0, 'end')
        for x in range(nv):
            self.lb1.insert(END, data[x][0])
            self.lb2.insert(END, data[x][1])
            self.lb3.insert(END, data[x][2])

    def onOpen(self):
        global load
        fold = tkFileDialog.askdirectory()
        self.entry1.delete(0, 'end')
        self.entry1.insert(0, fold)
        load = 0

    def onOpenMM(self):
        global load
        fold = tkFileDialog.askopenfilename()
        self.entry2.delete(0, 'end')
        self.entry2.insert(0, fold)
        load = 0

    def onOpenPDB(self):
        global load
        fold = tkFileDialog.askopenfilename()
        self.entry3.delete(0, 'end')
        self.entry3.insert(0, fold)
        load = 0

    def OnVsb(self, *args):
        self.lb1.yview(*args)
        self.lb2.yview(*args)
        self.lb3.yview(*args)

    def OnMouseWheel(self, event):
        self.lb1.yview("scroll", event.delta, "units")
        self.lb2.yview("scroll", event.delta, "units")
        self.lb3.yview("scroll", event.delta, "units")
        return "break"

    def Apply(self):
        global load, prevz
        if (load == 0):

            if (self.wat.get() == 1 or self.lig.get() == 1):
                self.changestate()
                self.base = os.listdir(self.entry1.get())
                pdb1 = list()
                for a in self.base:
                    matchObj = re.match(r'bound_mobile_\d{6}_0\.\d{5}\.pdb', a,
                                        re.M | re.I)
                    if matchObj:
                        pdb1.append(a)
                self.lig1pdb = list()
                self.lig2pdb = list()
                #print x
                x = pdb1[1][22:27]

                for a in pdb1:

                    matchObj = re.match(r'bound_mobile_\d{6}_0\.' + x + '.pdb',
                                        a, re.M | re.I)
                    if matchObj:
                        self.lig1pdb.append(a)
                    else:
                        self.lig2pdb.append(a)
                self.lig1pdb.sort()
                self.lig2pdb.sort()
                self.scale.configure(from_=0, to=len(self.lig1pdb) - 1)
                self.scale.config(state="normal")

            elif (self.mm.get() == 1):
                self.loadmmpbsaresults()
                CHEWD.mmloadpdb(self.entry3.get())
                CHEWD.mmvisualizer("0", tempfile.gettempdir(),
                                   self.entry4.get(), self.entry5.get(),
                                   self.entry6.get(), self.entry7.get(),
                                   self.vl.get())

            if (self.wat.get() == 1):
                CHEWD.wsloadallpdb(self.lig1pdb, self.entry1.get())
                self.next.config(state="normal")
                v = self.lig1pdb[0][14:19]
                self.var.set(v)
                CHEWD.wsvisualizer(str(self.scale.get()),
                                   tempfile.gettempdir(), self.entry4.get(),
                                   self.entry5.get(), self.entry6.get(),
                                   self.entry7.get(), self.vl.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                CHEWD.wsloadallpdb(self.lig1pdb, self.entry1.get())
                self.next.config(state="normal")
                v = self.lig1pdb[0][14:19]
                self.var.set(v)
                CHEWD.lsvisualizer(str(self.scale.get()),
                                   tempfile.gettempdir(), vl,
                                   self.entry5.get(), self.entry6.get(),
                                   self.entry7.get(), hl, self.vl.get())
            load = 1

        else:

            if (self.wat.get() == 1):
                self.changestate()
                CHEWD.clear(tempfile.gettempdir())
                CHEWD.loadresults(tempfile.gettempdir())
                CHEWD.wsupdateview(self.entry4.get(), self.entry5.get(),
                                   self.entry6.get(), self.entry7.get(), prevz,
                                   str(self.scale.get()), self.vl.get())
            elif (self.lig.get() == 1):
                self.changestate()
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()

                CHEWD.clear(tempfile.gettempdir())
                CHEWD.loadresults(tempfile.gettempdir())
                CHEWD.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                                   self.entry7.get(), prevz,
                                   str(self.scale.get()), hl, self.vl.get())
            elif (self.mm.get() == 1):
                CHEWD.mmupdateview(self.entry4.get(), self.entry5.get(),
                                   self.entry6.get(), self.entry7.get(), prevz,
                                   "0", self.vl.get())
        prevz = self.entry5.get()
示例#12
0
class ListFrame(LabelFrame):
    """
    A Frame representing one of the search term lists
    (e.g. Hashtags, Excluded Users).

    Displays all the items in the list,
    and allows the user to add or remove items.
    Methods should not be called directly;
    instead they should be bound as event handlers.
    """
    def __init__(self, name, add_handler, remove_handler, master=None):
        """
        Creates a ListFrame with the given name as its title.

        add_handler and remove_handler are functions to be called
        when items are added or removed, and should relay the information
        back to the Searcher (or whatever object actually uses the list).
        """
        LabelFrame.__init__(self, master)
        self['text'] = name
        self.add_handler = add_handler
        self.remove_handler = remove_handler
        self.list = Listbox(self)
        self.list.grid(row=0, columnspan=2)
        # Tkinter does not automatically close the right-click menu for us,
        # so we must close it when the user clicks away from the menu.
        self.list.bind("<Button-1>", lambda event: self.context_menu.unpost())
        self.list.bind("<Button-3>", self.open_menu)
        self.context_menu = Menu(self, tearoff=0)
        self.context_menu.add_command(label="Remove", command=self.remove)
        self.input = Entry(self)
        self.input.bind("<Return>", lambda event: self.add())
        self.input.grid(row=1, columnspan=2)
        self.add_button = Button(self)
        self.add_button['text'] = "Add"
        self.add_button['command'] = self.add
        self.add_button.grid(row=2, column=0, sticky=W + E)
        self.remove_button = Button(self)
        self.remove_button['text'] = "Remove"
        self.remove_button['command'] = self.remove
        self.remove_button.grid(row=2, column=1, sticky=W + E)

    def add(self):
        """
        Add the item in the input line to the list.
        """
        self.list.insert(END, self.input.get())
        self.add_handler(self.input.get())
        self.input.delete(0, END)

    def remove(self):
        """
        Remove the active (highlighted) item from the list.
        """
        deleted = self.list.get(ACTIVE)
        self.list.delete(ACTIVE)
        self.remove_handler(deleted)

    def open_menu(self, event):
        """
        Opens a right-click menu for the selected item.
        Currently the menu only has an option for removing the item.
        """
        index = self.list.index("@" + str(event.x) + "," + str(event.y))
        if index < 0:
            return
        self.context_menu.post(event.x_root, event.y_root)
        self.list.activate(index)
        self.list.selection_clear(0, END)
        self.list.selection_set(ACTIVE)
示例#13
0
 def initUI(self):
     self.parent.title("One Time Pad Generator")
     self.style = Style()
     self.style.theme_use("default")
     self.grid()
     
     #string
     text_to_encrypt = Entry(self)
     text_to_encrypt.grid(row=0, column=0)
     text_to_encrypt.delete(0, Tkinter.END)
     text_to_encrypt.insert(0, "text you want to encrypt or decrypt")
     
     #pad
     encrypt_pad = Entry(self)
     encrypt_pad.grid(row=0, column=1)
     encrypt_pad.delete(0, Tkinter.END)
     encrypt_pad.insert(0, "padOutput")
     
     #start
     start_encrypt = Entry(self)
     start_encrypt.grid(row=0, column=2)
     start_encrypt.delete(0, Tkinter.END)
     start_encrypt.insert(0, 0)
     
     
     
     
     #encrypt button
     encodeButton = Button(self, text="Encrypt",
         command=lambda: self.encrypt(text_to_encrypt.get(), encrypt_pad.get(), start_encrypt.get()))
     encodeButton.grid(row=1, column=0)
     #decrypt button
     encodeButton = Button(self, text="Decrypt",
         command=lambda: self.decrypt(str(text_to_encrypt.get()), encrypt_pad.get(), start_encrypt.get()))
     encodeButton.grid(row=1, column=2)
     
   
     #generate pad
     padgen = Entry(self)
     padgen.grid(row=2, column=0)
     padgen.delete(0, Tkinter.END)
     padgen.insert(0, 0)
     
     #gen key button
     genkey = Button(self, text="Generate Key",
                     command=lambda: Cryptography.outputPad(Cryptography.GenerateKey(int(padgen.get())), encrypt_pad.get()))
     genkey.grid(row=2, column=1)
     
     #encrypted text
    
     self.T = Tkinter.Text(self)
     S = Scrollbar(self.T)
     S.grid(column=2);
     S.config(command=self.T.yview)
     self.T.config(yscrollcommand=S.set)
     self.T.insert(Tkinter.END,self.encrypted[0])
     self.T.grid(row=5, column=0, sticky="nsew", rowspan = 10, columnspan = 3)
     
    
     #input email
     e = Entry(self)
     e.grid(row = 3, column = 0)
     e.delete(0, Tkinter.END)
     e.insert(0, "Send encrypted message via email")
     #send email
     email = Button(self, text="Send Email",command=lambda:self.sendmail(e.get()))
     email.grid(row=3, column=1)
示例#14
0
class ElementalCodingGUI(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.elemental_coding = ElementalCoding()
        self.huffman_coding = HuffmanCoding()
        self.dictionary_coding = DictionaryCoding()
        self.init_ui()
        self.current_encoding = 5

    def init_ui(self):
        self.parent.title("Information Theory")
        Style().configure("TButton", padding=(0, 5, 0, 5), font='Verdana 10')

        self.columnconfigure(0, pad=3)
        self.columnconfigure(1, pad=3)
        self.columnconfigure(2, pad=3)
        self.columnconfigure(3, pad=3)
        self.columnconfigure(4, pad=3)

        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3)
        self.rowconfigure(2, pad=3)
        self.rowconfigure(3, pad=3)
        self.rowconfigure(4, pad=3)
        self.rowconfigure(5, pad=3)

        string_to_search_label = Label(self, text="Search a string: ")
        string_to_search_label.grid(row=0, column=0, rowspan=2)
        self.string_to_search_textfield = Entry(self)
        self.string_to_search_textfield.grid(row=0, column=1, rowspan=2, columnspan=2, sticky=W)
        self.string_to_search_textfield.bind('<Return>', self.get_string_from_textfield)
        self.compression_ratio_text = StringVar()
        self.compression_ratio_text.set('Compression Ratio: ')
        compression_ratio_label = Label(self, textvariable=self.compression_ratio_text).grid(row=0, column=2,
                                                                                             columnspan=4)

        Separator(self, orient=HORIZONTAL).grid(row=1)
        string_to_encode_label = Label(self, text="Encode a string: ")
        string_to_encode_label.grid(row=2, column=0, rowspan=2)
        self.string_to_encode_textfield = Entry(self)
        self.string_to_encode_textfield.grid(row=2, column=1, rowspan=2, columnspan=2, sticky=W)
        self.string_to_encode_textfield.bind('<Return>', self.get_string_from_textfield_to_encode)

        Separator(self, orient=HORIZONTAL).grid(row=3)
        self.area = Text(self)
        self.area.grid(row=4, column=0, columnspan=3, rowspan=1, padx=5, sticky=E + W)
        self.area.config(width=10, height=15)
        self.possible_options_text = StringVar()
        self.possible_options_text.set("Possible Options: ")
        self.possible_options_label = Label(self, textvariable=self.possible_options_text).grid(row=4, column=3,
                                                                                                sticky=N)

        huffman_coding_button = Button(self, text="Huffman",
                                       command=self.huffman_coding_callback).grid(row=5, column=0)
        arithmetic_coding_button = Button(self, text="Arithmetic Coding",
                                          command=self.arithmetic_coding_callback).grid(row=5, column=1)
        dictionary_coding_button = Button(self, text="Dictionary",
                                          command=self.dictionary_coding_callback).grid(row=5, column=2)
        elias_coding_button = Button(self, text="Elias",
                                     command=self.elias_coding_callback).grid(row=5, column=3)
        our_coding_button = Button(self, text="Elemental Coding",
                                   command=self.elemental_coding_callback).grid(row=5, column=4)
        self.pack()
        self.elemental_coding_callback()

    def get_string_from_textfield_to_encode(self, event):
        text_to_encode = self.string_to_encode_textfield.get()
        if text_to_encode == '':
            text_to_encode = 'a'
        if self.current_encoding == 1:
            self.huffman_coding.encode(text_to_encode)
            self.set_text_in_text_area(output)
            compression_ratio = self.huffman_coding.compression_ratio
            self.compression_ratio_text.set('Compression Ratio: ' + str(compression_ratio))
        if self.current_encoding == 2:
            pass
        if self.current_encoding == 3:
            pass
        if self.current_encoding == 4:
            pass
        if self.current_encoding == 5:
            self.elemental_coding.getElementList()
            self.elemental_coding.codeElemental(text_to_encode)
            self.elemental_coding.encodeText()
            output = self.elemental_coding.printCodedText()
            compression_ratio = self.elemental_coding.get_compression_ratio()
            self.compression_ratio_text.set('Compression Ratio: ' + str(compression_ratio))
            #self.set_text_in_text_area(output)

    def get_string_from_textfield(self, event):
        text_to_encode = self.string_to_sitemearch_textfield.get()
        possible_options = self.elemental_coding.lookForString(text_to_encode)
        self.possible_options_text.set('Possible Options: ' + possible_options)
        self.string_to_search_textfield.delete(END)

    def huffman_coding_callback(self):
        self.current_encoding = 1
        output = self.huffman_coding.encode_default_file()
        self.set_text_in_text_area(output)
        compression_ratio = self.huffman_coding.compression_ratio
        self.compression_ratio_text.set('Compression Ratio: ' + str(compression_ratio))
        print "HUFMAAN!"

    def arithmetic_coding_callback(self):
        self.current_encoding = 2
        text_to_encode = self.string_to_encode_textfield.get()
        if text_to_encode == '':
            text_to_encode = ' '
        for char in text_to_encode:
            if char not in arithmetic_intervals:
                can_encode = False
            else:
                can_encode = True
        if can_encode:
            codificacion = interval_coding(text_to_encode, arithmetic_intervals)
            self.compression_ratio_text.set(str(codificacion[2]))
        else:
            self.compression_ratio_text.set("Error: no en intervalos\n"
                                            "Si desea comprobar este metodo,"
                                            "introduce un string en el cuadro\n"
                                            "\"Encode text\"")

        print "Arithmetic!"

    def dictionary_coding_callback(self):
        self.current_encoding = 3
        contents = get_file_contents(os.getcwd() + '/pagina.txt')
        compress_text = self.dictionary_coding.compress(contents)
        compression_ratio = len(compress_text) / float(len(contents))
        self.compression_ratio_text.set('Compression Ratio: ' + str(compression_ratio) )
        compress_text = [str(item) for item in compress_text]
        self.set_text_in_text_area(''.join(compress_text))
        print "Dictionary!"

    def elias_coding_callback(self):
        self.current_encoding = 4
        text_to_encode = self.string_to_encode_textfield.get()
        if text_to_encode == '':
            text_to_encode = ' '
        for char in text_to_encode:
            if char not in elias_intervals:
                can_encode = False
            else:
                can_encode = True
        if can_encode:
            codificacion = interval_coding(text_to_encode, elias_intervals)
            self.compression_ratio_text.set(str(codificacion[2]) + "%")
        else:
            self.compression_ratio_text.set("Error: no en intervalos\n"
                                            "Si desea comprobar este metodo,"
                                            "introduce un string en el cuadro\n"
                                            "\"Encode text\"")


    def set_text_in_text_area(self, output):
        self.area.config(state=NORMAL)
        self.area.delete("1.0", END)
        self.area.insert(INSERT, output)
        self.area.config(state=DISABLED)

    def elemental_coding_callback(self):
        self.current_encoding = 5
        self.elemental_coding.getElementList()
        self.elemental_coding.processFile('pagina.txt')
        self.elemental_coding.encodeText()
        output = self.elemental_coding.printCodedText()
        self.set_text_in_text_area(output)
        compression_ratio = self.elemental_coding.get_compression_ratio()
        self.compression_ratio_text.set('Compression Ratio: ' + str(compression_ratio))
        print "Our Coding!"
示例#15
0
class IniGenGui(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUIGlobals()

    def initUIGlobals(self):

        self.parent.title("Ini Generator")

        Style().configure("TButton", padding=(0, 0, 0, 0), font='serif 10')

        f1 = Frame(self)
        f1.grid(row=0, column=0, padx=10, sticky=N + S + E + W)

        f11 = LabelFrame(f1, text="Algorithms to Run")
        f11.grid(row=0, column=0)
        row = 0

        self.check_algs_value_list = []
        self.check_algs_map = {}
        for alg in algorithms:
            if alg == 'clean':
                continue
            check_alg_value = IntVar()
            check_alg = Checkbutton(f11,
                                    text=alg,
                                    variable=check_alg_value,
                                    justify=LEFT,
                                    width=25)
            check_alg.grid(row=row, column=0, sticky=W + E)
            self.check_algs_value_list.append(check_alg_value)
            self.check_algs_map[alg] = check_alg_value
            row += 1

        f111 = Frame(f11)
        f111.grid(row=row, column=0)

        button_checkall = Button(f111, text="All", command=self.checkall)
        button_checkall.grid(row=0, column=0, sticky=W + E)
        button_uncheckall = Button(f111, text="None", command=self.uncheckall)
        button_uncheckall.grid(row=0, column=1, sticky=W + E)

        row = 0

        f12 = Frame(f1)
        f12.grid(row=1, column=0, pady=20, sticky=S + W + E)

        f121 = LabelFrame(f12, text='Location of uPMU')
        f121.grid(row=0, column=0)

        self.radio_loc_string = StringVar()
        locations.append('Other Location')
        for loc in locations:
            radio_loc = Radiobutton(f121,
                                    text=loc,
                                    variable=self.radio_loc_string,
                                    value=loc,
                                    command=self.set_loc,
                                    justify=LEFT,
                                    width=25)
            radio_loc.grid(row=row, column=0, sticky=W + E)
            row += 1

        self.entry_otherloc = Entry(f121)

        f2 = Frame(self)
        f2.grid(row=0, column=1, padx=10, sticky=N + S + E + W)

        f21 = LabelFrame(f2, text='Name of uPMU (raw)')
        f21.grid(row=0)
        row = 0

        f211 = Frame(f21)
        f211.grid(row=row)
        row += 1

        self.entry_namesearch = Entry(f211)
        self.entry_namesearch.grid(row=0, column=0, sticky=E + W)

        button_namesearch = Button(f211,
                                   text="Search",
                                   command=self.namesearch)
        button_namesearch.grid(row=0, column=1, sticky=W + E)

        self.lstbx_namelist = Listbox(f21)
        self.lstbx_namelist.bind("<Double-Button-1>", self.namelist_select)
        self.lstbx_namelist.grid(row=row, sticky=W + E)
        row += 1

        f212 = Frame(f21)
        f212.grid(row=row)
        row += 1

        label_nameselected = Label(f212, text="Selected:")
        label_nameselected.grid(row=0, column=0)

        self.entry_nameselected = Entry(f212, state=DISABLED)
        self.entry_nameselected.grid(row=0, column=1, sticky=W + E)

        f22 = LabelFrame(f2, text="Name of uPMU (abbr)")
        f22.grid(row=1, sticky=W + E, pady=10)
        self.entry_name = Entry(f22, width=30)
        self.entry_name.grid(row=0, column=0, sticky=E + W)

        f23 = LabelFrame(f2, text="Name of Reference uPMU (clean)")
        f23.grid(row=2, pady=10)
        row = 0

        f231 = Frame(f23)
        f231.grid(row=row)
        row += 1

        self.entry_refnamesearch = Entry(f231)
        self.entry_refnamesearch.grid(row=0, column=0, sticky=E + W)

        button_refnamesearch = Button(f231,
                                      text="Search",
                                      command=self.refnamesearch)
        button_refnamesearch.grid(row=0, column=1, sticky=W + E)

        self.lstbx_refnamelist = Listbox(f23)
        self.lstbx_refnamelist.bind("<Double-Button-1>",
                                    self.refnamelist_select)
        self.lstbx_refnamelist.grid(row=row, sticky=W + E)
        row += 1

        f232 = Frame(f23)
        f232.grid(row=row)
        row += 1

        label_refnameselected = Label(f232, text="Selected:")
        label_refnameselected.grid(row=0, column=0)

        self.entry_refnameselected = Entry(f232, state=DISABLED)
        self.entry_refnameselected.grid(row=0, column=1, sticky=W + E)

        button_gen = Button(self,
                            text="Generate Files",
                            command=self.generate_files)
        button_gen.grid(row=1, column=0, columnspan=2, sticky=W + E)

        self.pack()

    def generate_files(self):
        algs = []
        for alg in self.check_algs_map:
            if self.check_algs_map[alg].get() == 1:
                algs.append(alg)

        if self.radio_loc_string.get() == "Other Location":
            location = self.entry_otherloc.get()
        else:
            location = self.radio_loc_string.get()

        name_raw = self.entry_nameselected.get()
        name = self.entry_name.get()
        ref_name = self.entry_refnameselected.get()

        uuid_map = self.get_uuid_map(name_raw)
        reference_uuid_map = self.get_ref_uuid_map(ref_name)

        IniGenAutomation(location, name_raw, name, uuid_map, ref_name,
                         reference_uuid_map, algs)

    def namesearch(self):
        searchterm = self.entry_namesearch.get()
        if searchterm.contains("/"):
            loc = searchterm.split('/')
            searchphrase = '/upmu/%{0}%/%{1}%/%'.format(loc[0], loc[1])
        else:
            searchphrase = '/upmu/%{0}%/%'.format(searchterm)
        search_results = self.search(searchterm, searchphrase)
        self.lstbx_namelist.delete(0, END)
        if len(search_results) == 0:
            tkMessageBox.showwarning(
                'Search Error',
                'No matches from search for \'{0}\''.format(searchterm))
        else:
            for result in search_results:
                self.lstbx_namelist.insert(END, result)

    def refnamesearch(self):
        searchterm = self.entry_refnamesearch.get()
        searchphrase = '/Clean/%{0}%/%'.format(searchterm)
        search_results = self.search(searchterm, searchphrase)
        self.lstbx_refnamelist.delete(0, END)
        if len(search_results) == 0:
            tkMessageBox.showwarning(
                'Search Error',
                'No matches from search for \'{0}\''.format(searchterm))
        else:
            for result in search_results:
                self.lstbx_refnamelist.insert(END, result)

    def search(self, searchterm, searchphrase):
        connection = _mysql.connect(host="128.32.37.231",
                                    port=3306,
                                    user="******",
                                    passwd="moresecuredataftw",
                                    db='upmu')
        connection.query(
            "SELECT * FROM uuidpathmap WHERE path LIKE '{0}'".format(
                searchphrase))
        results = connection.store_result()
        queried_data = {}
        result = results.fetch_row()
        while result != tuple():
            queried_data[result[0][0]] = result[0][1]
            result = results.fetch_row()
        search_results = set()
        for path in queried_data:
            dirs = path.split('/')
            if searchterm in dirs[2]:
                search_results.add(dirs[2])
        return search_results

    def set_loc(self):
        if self.radio_loc_string.get() == "Other Location":
            self.entry_otherloc.grid(sticky=W + E)
        else:
            self.entry_otherloc.grid_forget()

    def checkall(self):
        for check in self.check_algs_value_list:
            check.set(1)

    def uncheckall(self):
        for check in self.check_algs_value_list:
            check.set(0)

    def namelist_select(self, event):
        selected_index = self.lstbx_namelist.curselection()
        selected = self.lstbx_namelist.get(selected_index)
        self.entry_nameselected.configure(state=NORMAL)
        self.entry_nameselected.delete(0, END)
        self.entry_nameselected.insert(0, selected)
        self.entry_nameselected.configure(state=DISABLED)

    def refnamelist_select(self, event):
        selected_index = self.lstbx_refnamelist.curselection()
        selected = self.lstbx_refnamelist.get(selected_index)
        self.entry_refnameselected.configure(state=NORMAL)
        self.entry_refnameselected.delete(0, END)
        self.entry_refnameselected.insert(0, selected)
        self.entry_refnameselected.configure(state=DISABLED)

    def get_uuid_map(self, name):
        uuid_map = {}
        connection = _mysql.connect(host="128.32.37.231",
                                    port=3306,
                                    user="******",
                                    passwd="moresecuredataftw",
                                    db='upmu')
        connection.query(
            "SELECT * FROM uuidpathmap WHERE path LIKE '/upmu/{0}/%'".format(
                name))
        results = connection.store_result()
        result = results.fetch_row()
        while result != tuple():
            path = result[0][0].split('/')
            uuid_map[path[-1]] = result[0][1]
            result = results.fetch_row()
        return uuid_map

    def get_ref_uuid_map(self, name):
        uuid_map = {}
        connection = _mysql.connect(host="128.32.37.231",
                                    port=3306,
                                    user="******",
                                    passwd="moresecuredataftw",
                                    db='upmu')
        connection.query(
            "SELECT * FROM uuidpathmap WHERE path LIKE '/Clean/{0}/%'".format(
                name))
        results = connection.store_result()
        result = results.fetch_row()
        while result != tuple():
            path = result[0][0].split('/')
            uuid_map[path[-2]] = result[0][1]
            result = results.fetch_row()
        return uuid_map
示例#16
0
class CHEWD(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()
        self.selection = ""
        self.pdb = ""

    def initUI(self):
        self.parent.title("CHemical Energy Wise Decomposition")
        frame4 = Frame(self.parent)
        frame4.grid(row=0, column=0, sticky="nsew")
        self.wat = IntVar()
        self.wat.set(1)
        self.waterswap = Checkbutton(frame4,
                                     text="Water Swap",
                                     command=self.optionws,
                                     variable=self.wat)
        self.waterswap.grid(row=0, column=0)
        self.lig = IntVar()
        self.lig.set(0)
        self.ligandswap = Checkbutton(frame4,
                                      text="Ligand Swap",
                                      command=self.optionls,
                                      variable=self.lig)
        self.ligandswap.grid(row=0, column=1)
        self.mm = IntVar()
        self.mm.set(0)
        self.mmpbsa = Checkbutton(frame4,
                                  text="MMPBSA",
                                  command=self.optionmm,
                                  variable=self.mm)
        self.mmpbsa.grid(row=0, column=2)

        frame1 = Frame(self.parent)
        frame1.grid(row=1, column=0, sticky="nsew")
        lbl1 = Label(frame1, text="Log file folder", width=12)
        lbl1.grid(row=0, column=0)
        self.entry1 = Entry(frame1)
        self.entry1.grid(row=0, column=1, columnspan=4, sticky=W + E)
        self.browserButton = Button(frame1,
                                    text="Browser",
                                    command=self.onOpen)
        self.browserButton.grid(row=0, column=5, sticky="e")

        lbl2 = Label(frame1, text="MMPBSA log file", width=12)
        lbl2.grid(row=1, column=0)
        self.entry2 = Entry(frame1, state=DISABLED)
        self.entry2.grid(row=1, column=1, columnspan=4, sticky=W + E)
        self.browserButtonMM = Button(frame1,
                                      text="Browser",
                                      command=self.onOpenMM,
                                      state=DISABLED)
        self.browserButtonMM.grid(row=1, column=5, sticky="e")

        lbl3 = Label(frame1, text="MMPBSA PDB file", width=12)
        lbl3.grid(row=2, column=0)
        self.entry3 = Entry(frame1, state=DISABLED)
        self.entry3.grid(row=2, column=1, columnspan=4, sticky=W + E)
        self.browserButtonPDB = Button(frame1,
                                       text="Browser",
                                       command=self.onOpenPDB,
                                       state=DISABLED)
        self.browserButtonPDB.grid(row=2, column=5, sticky="e")

        lbl4 = Label(frame1, text="Ligand Name", width=12)
        lbl4.grid(row=3, column=0)
        self.entry4 = Entry(frame1)
        self.entry4.grid(row=3, column=1)
        self.lblswap = Label(frame1,
                             text="Swap Ligand",
                             width=12,
                             state=DISABLED)
        self.lblswap.grid(row=3, column=2)
        self.swapentry = Entry(frame1, state=DISABLED)
        self.swapentry.grid(row=3, column=3)
        self.l1v = IntVar()
        self.l1v.set(1)
        self.lig1ck = Checkbutton(frame1,
                                  text="Ligand 1",
                                  command=self.changelig1,
                                  state=DISABLED,
                                  variable=self.l1v)
        self.lig1ck.grid(row=4, column=0)
        self.l2v = IntVar()
        self.l2v.set(0)
        self.lig2ck = Checkbutton(frame1,
                                  text="Ligand 2",
                                  command=self.changelig2,
                                  state=DISABLED,
                                  variable=self.l2v)
        self.lig2ck.grid(row=4, column=2)
        lbl5 = Label(frame1, text="Display Radius", width=12)
        lbl5.grid(row=5, column=0)
        self.entry5 = Entry(frame1)
        self.entry5.grid(row=5, column=1)
        self.entry5.insert(0, "5.0")
        self.sv = IntVar()
        self.sv.set(0)
        self.surface = Checkbutton(frame1,
                                   text="View Surface",
                                   command=self.viewsurface,
                                   variable=self.sv)
        self.surface.grid(row=5, column=2)
        self.vl = IntVar()
        self.vl.set(1)
        self.label = Checkbutton(frame1,
                                 text="View Label",
                                 command=self.viewlabel,
                                 variable=self.vl)
        self.label.grid(row=5, column=3)

        lbl6 = Label(frame1, text="Min Value", width=12)
        lbl6.grid(row=6, column=0)
        self.entry6 = Entry(frame1)
        self.entry6.grid(row=6, column=1)
        self.entry6.insert(0, "-5")
        lbl7 = Label(frame1, text="Max Value", width=12)
        lbl7.grid(row=6, column=2)
        self.entry7 = Entry(frame1)
        self.entry7.grid(row=6, column=3)
        self.entry7.insert(0, "+5")

        lbl8 = Label(frame1, text="Starting log file", width=12)
        lbl8.grid(row=7, column=0)
        self.entry8 = Entry(frame1)
        self.entry8.grid(row=7, column=1)
        self.entry8.insert(0, "400")
        lbl9 = Label(frame1, text="Ending log file", width=12)
        lbl9.grid(row=7, column=2)
        self.entry9 = Entry(frame1)
        self.entry9.grid(row=7, column=3)
        self.entry9.insert(0, "1000")

        frame2 = Frame(self.parent)
        frame2.grid(row=2, column=0, sticky="nsew")
        self.vsb = Scrollbar(frame2, orient="vertical", command=self.OnVsb)
        self.vsb.grid(row=1, column=3, sticky="ns")
        self.lb1 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb1.grid(row=1, column=0)
        self.lb2 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb2.grid(row=1, column=1)
        self.lb3 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb3.grid(row=1, column=2)

        self.b1 = Button(frame2,
                         text="Residue Number",
                         state=DISABLED,
                         command=lambda: self.sortdata(0))
        self.b1.grid(row=0, column=0, sticky=W + E)
        self.b2 = Button(frame2,
                         text="Residue Name",
                         state=DISABLED,
                         command=lambda: self.sortdata(1))
        self.b2.grid(row=0, column=1, sticky=W + E)
        self.b3 = Button(frame2,
                         text="Energy Value",
                         state=DISABLED,
                         command=lambda: self.sortdata(2))
        self.b3.grid(row=0, column=2, sticky=W + E)

        OS = platform.system()
        if (OS == "Linux"):
            self.lb1.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb1.bind("<4>", self.OnMouseWheel)
            self.lb1.bind("<5>", self.OnMouseWheel)
            self.lb2.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb2.bind("<4>", self.OnMouseWheel)
            self.lb2.bind("<5>", self.OnMouseWheel)
            self.lb3.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb3.bind("<4>", self.OnMouseWheel)
            self.lb3.bind("<5>", self.OnMouseWheel)
        else:
            self.lb1.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb1.bind("<MouseWheel>", self.OnMouseWheel)
            self.lb2.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb2.bind("<MouseWheel>", self.OnMouseWheel)
            self.lb3.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb3.bind("<MouseWheel>", self.OnMouseWheel)

        frame3 = Frame(self.parent)
        frame3.grid(row=3, column=0, sticky="nsew")

        self.previous = Button(frame3,
                               text="Previous Frame",
                               state=DISABLED,
                               command=self.prevframe)
        self.previous.grid(row=0, column=0, sticky=W + E)
        self.scale = Scale(frame3,
                           command=self.onScale,
                           state=DISABLED,
                           orient=HORIZONTAL,
                           length=320,
                           showvalue=0)
        self.scale.grid(row=0, column=1, sticky=W + E)
        self.next = Button(frame3,
                           text="Next Frame",
                           state=DISABLED,
                           command=self.nextframe)
        self.next.grid(row=0, column=2, sticky=W + E)

        self.var = IntVar()
        v = 000
        self.var.set(v)
        self.label = Label(frame3, text=0, textvariable=self.var)
        self.label.grid(row=0, column=3)
        self.ApplyButton = Button(frame3, text="Apply", command=self.Apply)
        self.ApplyButton.grid(row=1, column=3, sticky="e")

        ToolTip(lbl1, "Load the result directory of Sire Analysis")
        ToolTip(self.browserButton,
                "Load the result directory of Sire Analysis")
        ToolTip(lbl4, "Enter the name of the Ligand in your coordinate file")
        ToolTip(
            lbl5,
            "The radially distributed zone around ligand you want to be displayed"
        )
        ToolTip(
            lbl6,
            "Minimum scale value for the color distribution and it will be treated as blue"
        )
        ToolTip(
            lbl7,
            "Maximum scale value for the color distribution and it will be treated as red"
        )

    def wsvisualizer(self, index, lig, zone, min, max, label):
        cmd.hide("all")
        x = cmd.get_names("all")
        cmd.show("cartoon", "bo. " + x[index])
        cmd.show("sticks", x[index] + " and r. " + lig)
        cmd.color("white", x[index] + " and pol.")
        fp = open(tempfile.gettempdir() + "/temp.txt", "r")
        #tt=0
        stored.bfact = []
        for line in fp:
            stored.bfact.append(line)
            #print(stored.bfact[tt]+"\t"+line+"\t"+str(tt))
            #tt=tt+1
        #print(tt)
        fp.close()
        cmd.alter(x[index], "b=stored.bfact.pop(0)")
        cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max)
        cmd.ramp_new("ramp_obj",
                     x[index],
                     range=[min, 0, max],
                     color="[blue, white, red ]")
        cmd.util.cbaw(x[index] + " and r. " + lig)
        cmd.show(
            "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) ")
        self.togglelabelws(label, index, lig, zone)

    def lsvisualizer(self, index, lig, zone, min, max, hlig, label):
        cmd.hide("all")
        x = cmd.get_names("all")
        cmd.show("cartoon", "bo. " + x[index])
        cmd.show("sticks", x[index] + " and r. " + lig)
        cmd.color("white", x[index] + " and pol.")
        fp = open(tempfile.gettempdir() + "/temp.txt", "r")
        stored.bfact = []
        for line in fp:
            stored.bfact.append(line)
        fp.close()
        cmd.alter(x[index], "b=stored.bfact.pop(0)")
        cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max)
        cmd.ramp_new("ramp_obj",
                     x[index],
                     range=[min, 0, max],
                     color="[blue, white, red ]")
        cmd.util.cbaw(x[index] + " and r. " + lig)
        cmd.show(
            "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) ")
        cmd.hide("licorice", x[index] + " and r. " + hlig)
        self.togglelabells(label, index, lig, zone, hlig)

    def wsupdateview(self, lig, zone, min, max, prev, index, label):
        cmd.hide("all")
        x = cmd.get_names("all")
        cmd.label(
            "( " + x[index] + " and (r. " + lig + " a. " + prev +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) " + " and name CA", "\" \"")
        cmd.show("cartoon", "bo. " + x[index])
        cmd.show("sticks", x[index] + " and r. " + lig)
        cmd.color("white", x[index] + " and pol.")
        fp = open(tempfile.gettempdir() + "/temp.txt", "r")
        #tt=0
        stored.bfact = []
        for line in fp:
            stored.bfact.append(line)
            #print(stored.bfact[tt]+"\t"+line+"\t"+str(tt))
            #tt=tt+1
        #print(tt)
        fp.close()
        cmd.alter(x[index], "b=stored.bfact.pop(0)")
        cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max)
        cmd.ramp_new("ramp_obj",
                     x[index],
                     range=[min, 0, max],
                     color="[blue, white, red ]")
        cmd.util.cbaw(x[index] + " and r. " + lig)
        cmd.show(
            "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) ")
        self.togglelabelws(label, index, lig, zone)

    def lsupdateview(self, lig, zone, min, max, prev, index, hlig, label):
        cmd.hide("all")
        x = cmd.get_names("all")
        cmd.label(
            "( " + x[index] + " and (r. " + lig + " a. " + prev +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) " + " and name CA", "\" \"")
        cmd.show("cartoon", "bo. " + x[index])
        cmd.show("sticks", x[index] + " and r. " + lig)
        cmd.color("white", x[index] + " and pol.")
        fp = open(tempfile.gettempdir() + "/temp.txt", "r")

        stored.bfact = []
        for line in fp:
            stored.bfact.append(line)

        fp.close()
        cmd.alter(x[index], "b=stored.bfact.pop(0)")
        cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max)
        cmd.ramp_new("ramp_obj",
                     x[index],
                     range=[min, 0, max],
                     color="[blue, white, red ]")
        cmd.util.cbaw(x[index] + " and r. " + lig)
        cmd.show(
            "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) ")
        cmd.hide("licorice", x[index] + " and r. " + hlig)
        self.togglelabells(label, index, lig, zone, hlig)

    def wsloadallpdb(self, pdblist, path):
        for x in pdblist:
            cmd.load(path + "/" + x)
            #print(path +"/"+ x)
        cmd.hide("all")

    def mmloadpdb(self, path):
        cmd.load(path)

    def togglesurface(self, sur):
        x = cmd.get_names("all")
        if (sur):
            cmd.show("surf", x[int(self.scale.get())])
            cmd.set("transparency", "0.7")
        else:
            cmd.hide("surf", x[int(self.scale.get())])

    def wslistdisplay(self, prev, cur, index):
        x = cmd.get_names("all")
        cmd.hide("sticks", x[index] + " and i. " + prev)
        cmd.label(x[index] + " and i. " + prev + " and name CA", "\" \"")
        cmd.show("sticks", x[index] + " and i. " + cur)
        cmd.label(x[index] + " and i. " + cur + " and name CA",
                  "\"%s %s\"%(resn,resi)")

    def togglelabelws(self, label, index, lig, zone):
        global prevz
        x = cmd.get_names("all")
        if (label):
            cmd.label(
                "( " + x[index] + " and (r. " + lig + " a. " + zone +
                ") ) and (not (" + x[index] +
                " and (r. SWT or r. BWT or r. SWP))) " + " and name CA",
                "\"%s %s\"%(resn,resi)")
            prevz = self.entry5.get()
        else:
            cmd.label(
                "( " + x[index] + " and (r. " + lig + " a. " + prevz +
                ") ) and (not (" + x[index] +
                " and (r. SWT or r. BWT or r. SWP))) " + " and name CA",
                "\" \"")

    def togglelabells(self, label, index, lig, zone, hlig):
        global prevz
        x = cmd.get_names("all")
        if (label):
            cmd.label(
                "( " + x[index] + " and (r. " + lig + " a. " + zone +
                ") ) and (not (" + x[index] +
                " and (r. SWT or r. BWT or r. SWP))) " + " and name CA",
                "\"%s %s\"%(resn,resi)")
            cmd.label(x[index] + " and r. " + hlig + " and name CA", "\" \"")
            prevz = self.entry5.get()
        else:
            cmd.label(
                "( " + x[index] + " and (r. " + lig + " a. " + prevz +
                ") ) and (not (" + x[index] +
                " and (r. SWT or r. BWT or r. SWP))) " + " and name CA",
                "\" \"")

    def viewlabel(self):
        if (load > 0):
            if (self.wat.get() == 1):
                self.togglelabelws(self.vl.get(), int(self.scale.get()),
                                   self.entry4.get(), self.entry5.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                self.togglelabells(self.vl.get(), int(self.scale.get()), vl,
                                   self.entry5.get(), hl)
            elif (self.mm.get() == 1):
                self.togglelabelws(self.vl.get(), 0, self.entry4.get(),
                                   self.entry5.get())

    def viewsurface(self):  ##
        if (load > 0):
            self.togglesurface(self.sv.get())

    def optionws(self):
        if (self.wat.get() == 1):
            self.lig.set(0)
            self.mm.set(0)
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)
        else:
            self.wat.set(0)
            self.lig.set(1)
            self.mm.set(0)
            self.swapentry.config(state="normal")
            self.lig1ck.config(state="normal")
            self.lig2ck.config(state="normal")
            self.lblswap.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def optionls(self):
        if (self.lig.get() == 1):
            self.wat.set(0)
            self.mm.set(0)
            self.swapentry.config(state="normal")
            self.lig1ck.config(state="normal")
            self.lig2ck.config(state="normal")
            self.lblswap.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)
        else:
            self.lig.set(0)
            self.mm.set(0)
            self.wat.set(1)
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def optionmm(self):
        if (self.mm.get() == 1):
            self.lig.set(0)
            self.wat.set(0)
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry8.config(state=DISABLED)
            self.entry9.config(state=DISABLED)
            self.entry1.config(state=DISABLED)
            self.browserButton.config(state=DISABLED)
            self.entry2.config(state="normal")
            self.entry3.config(state="normal")
            self.browserButtonMM.config(state="normal")
            self.browserButtonPDB.config(state="normal")
        else:
            self.wat.set(1)
            self.lig.set(0)
            self.mm.set(0)
            self.entry8.config(state="normal")
            self.entry9.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def changelig1(self):  ##
        if (self.l1v.get() == 1):
            self.l2v.set(0)
        else:
            self.l2v.set(1)
        if (load > 0):
            if (self.l1v.get() == 1):
                vl = self.entry4.get()
                hl = self.swapentry.get()
            if (self.l2v.get() == 1):
                vl = self.swapentry.get()
                hl = self.entry4.get()
            self.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                              self.entry7.get(), prevz, int(self.scale.get()),
                              hl, self.vl.get())

    def changelig2(self):  ##
        if (self.l2v.get() == 1):
            self.l1v.set(0)
        else:
            self.l1v.set(1)
        if (load > 0):
            if (self.l1v.get() == 1):
                vl = self.entry4.get()
                hl = self.swapentry.get()
            if (self.l2v.get() == 1):
                vl = self.swapentry.get()
                hl = self.entry4.get()
            self.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                              self.entry7.get(), prevz, int(self.scale.get()),
                              hl, self.vl.get())

    def loadmmpbsaresults(self):
        fp = open(self.entry3.get(), "r")
        e = 0
        atomcount = 0
        resnew = 0
        rescount = 0
        resnum = list()
        residuename = list()
        resv = list()
        atomnum = list()
        atomnums = list()
        score = list()
        r = ""
        rn = ""
        for line in fp:
            if e == 2:
                atomnum.append(atomnums)
                break
            t = line.split()
            if line.find('TER') != -1:
                e = e + 1
            if line.find('ATOM') != -1:
                if (resnew == 0):
                    r = t[4]
                    rn = t[3]
                    resnew = 1
                    resnum.append(r)
                    residuename.append(rn)
                    score.append(0)
                elif (r != t[4]):
                    r = t[4]
                    rn = t[3]
                    atomnum.append(atomnums)
                    resnum.append(r)
                    residuename.append(rn)
                    score.append(0)
                    atomnums = list()
                atomnums.append(atomcount)
                atomcount = atomcount + 1
        fp.close()
        ll = len(score)
        print(ll)
        resv = list()
        fp = open(self.entry2.get(), "r")
        for line in fp:
            t = line.split(',')
            t2 = t[0].split()
            if (len(t) == 20 and len(t2) == 2 and t2[0] != "LIG"):
                for xx in range(ll):
                    if (int(resnum[xx]) == int(t2[1])):
                        #print(str(ll)+"\t"+str(len(t)))
                        score[xx] = float(t[17])
            matchObj = re.match(r'Sidechain Energy Decomposition:', line,
                                re.M | re.I)
            if matchObj:
                break
        fp.close()
        x = len(score)
        data = list()
        for i in range(x):
            data.append([resnum[i], score[i], residuename[i], atomnum[i]])
        data.sort(key=lambda s: (int(s[0])))
        scores = list()
        for i in range(len(data)):
            for j in range(len(data[i][3])):
                scores.append("{0:.3f}".format(data[i][1]))
        fp = open(tempfile.gettempdir() + "/temp.txt", "w")
        xs = len(scores)
        for i in range(xs):
            fp.write(str(scores[i]) + "\n")
        fp.close()
        self.lb1.delete(0, END)
        self.lb2.delete(0, END)
        self.lb3.delete(0, END)

        for i in range(x):
            self.lb1.insert(END, data[i][0])
            self.lb2.insert(END, data[i][2])
            self.lb3.insert(END, round(data[i][1], 3))

        self.b1.config(state="normal")
        self.b2.config(state="normal")
        self.b3.config(state="normal")

    def changestate(self):  ##
        fp = open(self.entry1.get() + "/bound_mobile_000100_0.00500.pdb")
        lend = 0
        if (self.wat.get() == 1):
            lend = 2
        elif (self.lig.get() == 1):
            lend = 4
        e = 0
        atomcount = 0
        resnew = 0
        rescount = 0
        resnum = list()
        residuename = list()
        resv = list()
        atomnum = list()
        atomnums = list()
        score = list()
        r = ""
        rn = ""
        for line in fp:
            if e == lend:
                atomnum.append(atomnums)
                break
            t = line.split()
            if line.find('TER') != -1:
                e = e + 1
            if line.find('ATOM') != -1:
                if (resnew == 0):
                    r = t[4]
                    rn = t[3]
                    resnew = 1
                    resnum.append(r)
                    residuename.append(rn)
                    score.append(0)
                elif (r != t[4]):
                    r = t[4]
                    rn = t[3]
                    atomnum.append(atomnums)
                    resnum.append(r)
                    residuename.append(rn)
                    score.append(0)
                    atomnums = list()
                atomnums.append(atomcount)
                atomcount = atomcount + 1
        fp.close()
        x = list()
        tempx = list()
        ll = len(score)
        base = os.listdir(self.entry1.get())
        for a in base:
            if a.endswith(".log"):
                tempx.append(a)
        tempx.sort()
        tlen = len(tempx)
        ia = int(self.entry8.get())
        while (ia <= int(self.entry9.get()) and ia < tlen):
            x.append(tempx[ia])
            ia += 1
        c = 0
        i = 0
        for fn in x:
            fp = open(self.entry1.get() + "/" + fn, "r")
            if (c == 0):
                for line in fp:
                    t = line.split()
                    if (len(t) == 8):
                        if (t[0] == "Residue("):
                            for xx in range(ll):
                                if (int(resnum[xx]) == int(t[3])):
                                    score[xx] = float(t[5])
                    if (line == "PROTEIN BOX WATER FREE ENERGY COMPONENTS\n"):
                        c = c + 1
                        i = 0
                        break
            else:
                for line in fp:
                    t = line.split()
                    if (len(t) == 8):
                        if (t[0] == "Residue("):
                            for xx in range(ll):
                                if (int(t[3]) == int(resnum[xx])):
                                    score[xx] = score[xx] + float(t[5])
                                i = i + 1
                    if (line == "PROTEIN BOX WATER FREE ENERGY COMPONENTS\n"):
                        c = c + 1
                        i = 0
                        break
            fp.close()
        x = len(score)
        data = list()
        for i in range(x):
            data.append([resnum[i], score[i], residuename[i], atomnum[i]])
        data.sort(key=lambda s: (int(s[0])))
        for i in range(x):
            data[i][1] = data[i][1] / c
        scores = list()
        for i in range(len(data)):
            for j in range(len(data[i][3])):
                scores.append("{0:.3f}".format(data[i][1]))
        self.lb1.delete(0, END)
        self.lb2.delete(0, END)
        self.lb3.delete(0, END)

        for i in range(x):
            self.lb1.insert(END, data[i][0])
            self.lb2.insert(END, data[i][2])
            self.lb3.insert(END, round(data[i][1], 3))

        fp = open(tempfile.gettempdir() + "/temp.txt", "w")
        lx = len(scores)
        for i in range(lx):
            fp.write(str(scores[i]) + "\n")
        fp.close()
        self.b1.config(state="normal")
        self.b2.config(state="normal")
        self.b3.config(state="normal")

    def prevframe(self):
        global prevz, load
        if (load > 0):
            self.scale.set(self.scale.get() - 1)

    def nextframe(self):
        global prevz, load
        if (load > 0):
            self.scale.set(self.scale.get() + 1)

    def onScale(self, val):
        global prevz, load
        if (load > 0):
            v = self.lig1pdb[int(float(val))][14:19]
            self.var.set(v)
            if (self.scale.get() == 0):
                self.previous.config(state=DISABLED)
            if (self.scale.get() == len(self.lig1pdb) - 2):
                self.next.config(state="normal")
            if (self.scale.get() == 1):
                self.previous.config(state="normal")
            if (self.scale.get() == len(self.lig1pdb) - 1):
                self.next.config(state=DISABLED)
            if (self.wat.get() == 1):
                self.wsupdateview(self.entry4.get(), self.entry5.get(),
                                  self.entry6.get(), self.entry7.get(), prevz,
                                  int(self.scale.get()), self.vl.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                self.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                                  self.entry7.get(), prevz,
                                  int(self.scale.get()), hl, self.vl.get())

    def OnSelect(self, val):
        global prev
        sender = val.widget
        idx = sender.curselection()
        if (idx != ()):
            dis = self.lb1.get(idx)
            if (self.wat.get() == 1 or self.lig.get() == 1):
                self.wslistdisplay(prev, dis, int(self.scale.get()))
            elif (self.mm.get() == 1):
                self.wslistdisplay(prev, dis, 0)
            prev = dis

    def sortdata(self, sc):
        global dr1, dr2, dr3
        tableData1 = self.lb1.get(0, END)
        tableData2 = self.lb2.get(0, END)
        tableData3 = self.lb3.get(0, END)

        data = list()
        nv = len(tableData1)
        for x in range(nv):
            data.append([tableData1[x], tableData2[x], tableData3[x]])

        if (sc == 0):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b1.cget('text')
            if dr1 == 1: self.b1.config(text='[+] ' + lab)
            else: self.b1.config(text='[-] ' + lab)
            data.sort(key=lambda s: (int(s[sc])), reverse=dr1 == 1)
            dr1 = dr1 * -1
        if (sc == 1):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b2.cget('text')
            if dr2 == 1: self.b2.config(text='[+] ' + lab)
            else: self.b2.config(text='[-] ' + lab)
            data.sort(key=lambda s: (s[sc]), reverse=dr2 == 1)
            dr2 = dr2 * -1
        if (sc == 2):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b3.cget('text')
            if dr3 == 1: self.b3.config(text='[+] ' + lab)
            else: self.b3.config(text='[-] ' + lab)
            data.sort(key=lambda s: (float(s[sc])), reverse=dr3 == 1)
            dr3 = dr3 * -1
        nv = len(data)
        self.lb1.delete(0, 'end')
        self.lb2.delete(0, 'end')
        self.lb3.delete(0, 'end')
        for x in range(nv):
            self.lb1.insert(END, data[x][0])
            self.lb2.insert(END, data[x][1])
            self.lb3.insert(END, data[x][2])

    def onOpen(self):
        global load
        fold = tkFileDialog.askdirectory()
        self.entry1.delete(0, 'end')
        self.entry1.insert(0, fold)
        load = 0

    def onOpenMM(self):
        global load
        fold = tkFileDialog.askopenfilename()
        self.entry2.delete(0, 'end')
        self.entry2.insert(0, fold)
        load = 0

    def onOpenPDB(self):
        global load
        fold = tkFileDialog.askopenfilename()
        self.entry3.delete(0, 'end')
        self.entry3.insert(0, fold)
        load = 0

    def OnVsb(self, *args):
        self.lb1.yview(*args)
        self.lb2.yview(*args)
        self.lb3.yview(*args)

    def OnMouseWheel(self, event):
        self.lb1.yview("scroll", event.delta, "units")
        self.lb2.yview("scroll", event.delta, "units")
        self.lb3.yview("scroll", event.delta, "units")
        return "break"

    def Apply(self):
        global load, prevz
        if (load == 0):

            if (self.wat.get() == 1 or self.lig.get() == 1):
                self.changestate()
                self.base = os.listdir(self.entry1.get())
                pdb1 = list()
                for a in self.base:
                    matchObj = re.match(r'bound_mobile_\d{6}_0\.\d{5}\.pdb', a,
                                        re.M | re.I)
                    if matchObj:
                        pdb1.append(a)
                self.lig1pdb = list()
                self.lig2pdb = list()
                x = pdb1[1][22:27]

                for a in pdb1:

                    matchObj = re.match(r'bound_mobile_\d{6}_0\.' + x + '.pdb',
                                        a, re.M | re.I)
                    if matchObj:
                        self.lig1pdb.append(a)
                    else:
                        self.lig2pdb.append(a)
                self.lig1pdb.sort()
                self.lig2pdb.sort()
                self.scale.configure(from_=0, to=len(self.lig1pdb) - 1)
                self.scale.config(state="normal")

            elif (self.mm.get() == 1):
                self.loadmmpbsaresults()
                self.mmloadpdb(self.entry3.get())
                self.wsvisualizer(0, self.entry4.get(), self.entry5.get(),
                                  self.entry6.get(), self.entry7.get(),
                                  self.vl.get())

            if (self.wat.get() == 1):
                self.wsloadallpdb(self.lig1pdb, self.entry1.get())
                self.next.config(state="normal")
                v = self.lig1pdb[0][14:19]
                self.var.set(v)
                self.wsvisualizer(int(self.scale.get()), self.entry4.get(),
                                  self.entry5.get(), self.entry6.get(),
                                  self.entry7.get(), self.vl.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                self.wsloadallpdb(self.lig1pdb, self.entry1.get())
                self.next.config(state="normal")
                v = self.lig1pdb[0][14:19]
                self.var.set(v)
                self.lsvisualizer(int(self.scale.get()), vl, self.entry5.get(),
                                  self.entry6.get(), self.entry7.get(), hl,
                                  self.vl.get())
            load = 1

        else:  #old code "else:"

            if (self.wat.get() == 1):
                self.wsupdateview(self.entry4.get(), self.entry5.get(),
                                  self.entry6.get(), self.entry7.get(), prevz,
                                  int(self.scale.get()), self.vl.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()

                self.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                                  self.entry7.get(), prevz,
                                  int(self.scale.get()), hl, self.vl.get())
            elif (self.mm.get() == 1):
                self.wsupdateview(self.entry4.get(), self.entry5.get(),
                                  self.entry6.get(), self.entry7.get(), prevz,
                                  0, self.vl.get())
        prevz = self.entry5.get()
示例#17
0
class MainFrame(Frame):

    TOP_FRAME_BACKGROUND_COLOR = 'gray75'

    w_ = 500
    h_ = 400

    a_ = 5.
    b_ = 5.

    pad_l = 10

    def __init__(self, parent):
        Frame.__init__(self, parent, background='white')

        self.parent_ = parent

        # this is the main frame we are working on
        self.img_frame = Frame(self, background='navy')
        self.entry1 = None
        self.entry2 = None
        self.cb = None

        #
        self.init_ui()
        self.centering()

        # broken TV app))
        # while True:
        self.state = 0
        self.init_random_image()
        # time.sleep(0.05)

    def centering(self):
        pos_x = (self.parent_.winfo_screenwidth() - self.w_) / 2
        pos_y = (self.parent_.winfo_screenheight() - self.h_) / 2

        self.parent_.geometry('{}x{}+{}+{}'.format(self.w_, self.h_, pos_x, pos_y))

    def init_ui(self):
        self.parent_.title('Rough surface generator')
        self.pack(fill=BOTH, expand=True)

        # top panel with controls
        frame_top = Frame(self, background=self.TOP_FRAME_BACKGROUND_COLOR)
        frame_top.pack(fill=X)

        self.cb = Combobox(frame_top, values=('Gaussian', 'Laplace'))
        self.cb.current(0)
        self.cb.pack(side=LEFT, padx=5, expand=True)

        l1 = Label(frame_top, text=r'Cx', background=self.TOP_FRAME_BACKGROUND_COLOR, width=4)
        l1.pack(side=LEFT, padx=5, expand=True)

        self.entry1 = Entry(frame_top,
                            validate='key',
                            validatecommand=(self.register(self.on_validate),
                                             '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W'),
                            width=10)
        self.entry1.pack(side=LEFT, padx=5, expand=True)
        self.entry1.insert(0, str(self.a_))

        l1 = Label(frame_top, text=r'Cy', width=4, background=self.TOP_FRAME_BACKGROUND_COLOR)
        l1.pack(side=LEFT, padx=5)

        self.entry2 = Entry(frame_top,
                            validate='key',
                            validatecommand=(self.register(self.on_validate),
                                             '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W'),
                            width=10)
        self.entry2.pack(side=LEFT, padx=5, expand=True)
        self.entry2.insert(0, str(self.b_))

        but1 = Button(frame_top, text='RUN', command=self.button_action)
        but1.pack(side=RIGHT, padx=5, pady=5)

        # central panel. It will have a label with an image. Image may have a random noise state, or
        # transformed image state
        self.img_frame.pack(fill=BOTH, expand=True)
        img_label = Label(self.img_frame, background=None)
        img_label.pack(expand=True, fill=BOTH, padx=5, pady=5)

    def on_validate(self, d, i, P, s, S, v, V, W):
        """
        :param d: type of action: 1 - insert, 0 - delete, -1 - other
        :param i: index of char string to be inserted/deleted, or -1
        :param P: value of the entry if the edit is allowed
        :param s: value of entry prior to editing
        :param S: the text string being inserted or deleted, if any
        :param v: the type of validation that is currently set
        :param V: the type of validation that triggered the callback
                    (key, focusin, focusout, forced)
        :param W: the tk name of the widget
        :return: True/False -> Valid / Invalid

        Found it here:
            https://stackoverflow.com/questions/4140437/interactively-validating-entry-widget-content-in-tkinter
        Very good answer!
        """

        if d == '1':
            if W == str(self.entry1):
                try:
                    float(s + S)
                    return True
                except ValueError:
                    self.entry1.delete(0, 'end')
                    self.entry1.insert(0, s)

                    print("Not a number, entry 1")
                    return False
            if W == str(self.entry2):
                try:
                    float(s + S)
                    return True
                except ValueError:
                    self.entry2.delete(0, 'end')
                    self.entry2.insert(0, s)

                    print("Not a number, entry 2")
                    return False
        return True

    def init_random_image(self):
        """
            Create a rough surface image from a random noise
        """
        self.update()

        # set a colormap
        c_map = cm.get_cmap('bwr')

        # width and height of the image
        w_ = self.img_frame.winfo_width()-self.pad_l
        h_ = self.img_frame.winfo_height()-self.pad_l

        # generate random noise
        random_map = np.random.random((h_, w_))

        # generate a meshgrid for the filter
        xv, yv = np.meshgrid(np.linspace(-int(w_ / 2.), int(w_ / 2.), w_),
                             np.linspace(-int(h_ / 2.), int(h_ / 2.), h_))

        # define correlation length and width
        if len(self.entry1.get()) > 0:
            clx = float(self.entry1.get())
        else:
            return

        if len(self.entry2.get()) > 0:
            cly = float(self.entry2.get())
        else:
            return

        #
        if self.cb.get().startswith('G'):
            # Gaussian filter
            filter_ = np.exp(-np.power(xv, 2) / clx - np.power(yv, 2) / cly)
        else:
            # Laplace filter
            filter_ = np.exp(-np.abs(xv) / clx - np.abs(yv) / cly)

        # this is a resulting map
        random_map = np.fft.ifft2(np.multiply(np.fft.fft2(random_map), np.fft.fft2(filter_)))
        random_map = np.real(random_map)

        # normalize to [0, 1]
        random_map -= np.min(random_map)
        random_map /= np.max(random_map)

        # create PhotoImage object to add on the panel
        img = ImageTk.PhotoImage(
            Image.fromarray(
                # image really likes unsigned ints))
                np.uint8(
                    # convert to colormap you like
                    c_map(
                        # give a random image to color map with values between 0 and 1
                        # np.random.random(
                        #     (self.img_frame.winfo_height()-self.pad_l, self.img_frame.winfo_width()-self.pad_l)
                        # )
                        random_map
                    )*255
                )
            )
        )

        # Gray colormap
        # img = ImageTk.PhotoImage(
        #     Image.fromarray(np.random.random_integers(0, 255,
        #                                   (self.img_frame.winfo_height()-self.pad_l,
        #                                    self.img_frame.winfo_width()-self.pad_l)).astype(np.int8)
        #                     ).convert('L')
        # )

        keys = self.img_frame.children.keys()
        for key in keys:
            self.img_frame.children[key].configure(image=img)
            self.img_frame.children[key].image = img

    def button_action(self):
        """
        """
        self.init_random_image()
示例#18
0
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        
        self.initUI()
        
        
    def initUI(self):
      
        self.parent.title("Review")
        self.pack(fill=BOTH, expand=True)
        labelfont20 = ('Roboto', 20, 'bold')
        labelfont12 = ('Roboto', 12, 'bold')
        
        frame0 = Frame(self)
        frame0.pack()
        
        lbl0 = Label(frame0, text="Hi USER")
        lbl0.config(font=labelfont20)    
        lbl0.pack( padx=5, pady=5)
        lbl00 = Label(frame0, text="Search here")
        lbl00.config(font=labelfont12)
        lbl00.pack( padx=5, pady=5)
        
        
        frame1 = Frame(self)
        frame1.pack()
        
        lbl1 = Label(frame1, text="min %", width=9)
        lbl1.pack(side=LEFT, padx=7, pady=5)           
       
        self.entry1 = Entry(frame1,width=20)
        self.entry1.pack(padx=5, expand=True)
        
        
        
        
        
        frame6 = Frame(self)
        frame6.pack()
        closeButton = Button(frame6, text="Get Names",width=12,command=self.getDate)
        closeButton.pack(padx=5, pady=5)
        
        frame7 = Frame(self)
        frame7.pack()
        closeButton1 = Button(frame7, text="Open in excel",width=15,command=self.openDate)
        closeButton1.pack(padx=5, pady=5)
        
        
        
        frame000 = Frame(self)
        frame000.pack()
        self.lbl000= Label(frame000, text=" ")
        self.lbl000.config(font=labelfont12)    
        self.lbl000.pack( padx=5, pady=5)
        
        frame00a = Frame(self)
        frame00a.pack()
        self.lbl00a= Label(frame000, text=" ")
        self.lbl00a.pack( padx=5, pady=5)
        
        
        
        
    def getDate(self):
        x1 = self.entry1.get()
        nx = ""
        
        
        self.entry1.delete(0, 'end')
        
        self.lbl000.config(text="Names Are:")
        

        
        
        #read csv, and split on "," the line
        csv_file = csv.reader(open('test.csv', "rb"), delimiter=",")
        #loop through csv list
        for row in csv_file:
            if row[2] >= x1:
                nx+=str(row[0]+", ")
                with open("output5.csv", "ab") as fp:
                    wr = csv.writer(fp, dialect='excel')
                    wr.writerow(row)
                fp.close()
        self.lbl00a.config(text=nx)
        
    def openDate(self):
        os.system("start "+'output5.csv')
示例#19
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.initUI()

    def initUI(self):

        self.parent.title("Review")
        self.pack(fill=BOTH, expand=True)
        labelfont20 = ('Roboto', 20, 'bold')
        labelfont12 = ('Roboto', 12, 'bold')

        frame0 = Frame(self)
        frame0.pack()

        lbl0 = Label(frame0, text="Hi USER")
        lbl0.config(font=labelfont20)
        lbl0.pack(padx=5, pady=5)
        lbl00 = Label(frame0, text="Search here")
        lbl00.config(font=labelfont12)
        lbl00.pack(padx=5, pady=5)

        frame1 = Frame(self)
        frame1.pack()

        lbl1 = Label(frame1, text="min %", width=9)
        lbl1.pack(side=LEFT, padx=7, pady=5)

        self.entry1 = Entry(frame1, width=20)
        self.entry1.pack(padx=5, expand=True)

        frame6 = Frame(self)
        frame6.pack()
        closeButton = Button(frame6,
                             text="Get Names",
                             width=12,
                             command=self.getDate)
        closeButton.pack(padx=5, pady=5)

        frame7 = Frame(self)
        frame7.pack()
        closeButton1 = Button(frame7,
                              text="Open in excel",
                              width=15,
                              command=self.openDate)
        closeButton1.pack(padx=5, pady=5)

        frame000 = Frame(self)
        frame000.pack()
        self.lbl000 = Label(frame000, text=" ")
        self.lbl000.config(font=labelfont12)
        self.lbl000.pack(padx=5, pady=5)

        frame00a = Frame(self)
        frame00a.pack()
        self.lbl00a = Label(frame000, text=" ")
        self.lbl00a.pack(padx=5, pady=5)

    def getDate(self):
        x1 = self.entry1.get()
        nx = ""

        self.entry1.delete(0, 'end')

        self.lbl000.config(text="Names Are:")

        #read csv, and split on "," the line
        csv_file = csv.reader(open('test.csv', "rb"), delimiter=",")
        #loop through csv list
        for row in csv_file:
            if row[2] >= x1:
                nx += str(row[0] + ", ")
                with open("output5.csv", "ab") as fp:
                    wr = csv.writer(fp, dialect='excel')
                    wr.writerow(row)
                fp.close()
        self.lbl00a.config(text=nx)

    def openDate(self):
        os.system("start " + 'output5.csv')
示例#20
0
文件: tkgui.py 项目: Horace89/epyks
class MainForm(Frame):
    """
    If method is handling some GUI shit, its written in camelCase style
    """
    def __init__(self, parent, caller_instance):
        Frame.__init__(self, parent)
        self.caller_instance = caller_instance
        self.running_on = "%s:%s" % (get_local_addr(),
                                     getattr(self.caller_instance, 'port',
                                             None) or "8888")
        self.parent = parent
        caller_instance.messangers.append(self)
        self.initUI()

    def initUI(self):
        self.__centerWindow()
        self.parent.title("epyks %s" % self.running_on)
        #
        # Addr textbox
        #
        addr_validate = (self.parent.register(self.addrValidation), '%S', '%d')
        self.EntryAddress = Entry(self,
                                  validate='key',
                                  validatecommand=addr_validate,
                                  width=17)
        self.EntryAddress.grid(row=0,
                               column=0,
                               padx=10,
                               pady=5,
                               columnspan=2,
                               sticky=W)
        self.EntryAddress.delete(0, END)
        self.EntryAddress.insert(0, "192.168.0.102:8889")
        #
        # Call button
        #
        self.ButtonCall = Button(self,
                                 text="Call",
                                 command=self.onButtonCallClick)
        self.ButtonCall.grid(row=0, column=1, pady=5)
        #
        #   Callmode status canvas
        #
        self.CanvasCallmode = Canvas(self,
                                     width=20,
                                     height=20,
                                     bg="light grey")
        self.CanvasCallmode.create_oval(1,
                                        1,
                                        20,
                                        20,
                                        fill="red",
                                        outline="light grey")
        self.CanvasCallmode.grid(row=1,
                                 column=0,
                                 pady=0,
                                 padx=10,
                                 sticky=W,
                                 columnspan=2)
        #
        #   Callmode status label
        #
        self.LabelCallmode = Label(self, text="Not connected")
        self.LabelCallmode.grid(row=1, column=0, padx=35)
        #
        #   End call button
        #
        self.ButtonEndCall = Button(self,
                                    text="End call",
                                    command=self.onButtonEndCallClick)
        self.ButtonEndCall.grid(row=1, column=1)

        #
        #   Message listbox
        #
        self.MessagesListBox = Listbox(self)
        self.MessagesListBox.grid(row=2,
                                  column=0,
                                  columnspan=2,
                                  padx=2,
                                  pady=2,
                                  sticky="EW")
        #
        # Message entry
        #
        self.EntryMessage = Entry(self)
        self.EntryMessage.grid(row=3, column=0, padx=2)
        #
        # Send message
        #
        self.ButtonSendMessage = Button(self,
                                        text="Send",
                                        command=self.onButtonSendMessageClick)
        self.ButtonSendMessage.grid(row=3, column=1)

        # Testing

        # Pack all
        self.pack(fill=BOTH, expand=1)

    def onGetAnswerMessageBox(self, interlocutor):
        return tkMessageBox.askyesno(
            title="Incoming call",
            message="A call from {}, wanna answer?".format(interlocutor))

    def addrValidation(self, string, action):
        print string
        if action != 1:
            # 0 - delete, 1 - insert, -1 - focus in/out
            return True
        print "addrValidation: %s" % string
        if len(string) > 1:
            return full_ipv4_check(fulladdr=string)
        return string in ACCEPTABLE_CHARS

    def onTextBoxChange(self, *args, **kwargs):
        print 'lol ' + str(args) + str(kwargs)

    def onButtonCallClick(self):
        address = (self.EntryAddress.get())
        if not full_ipv4_check(fulladdr=address):
            tkMessageBox.showerror(message="Incorrect address")
        ip, port = address.split(':')
        self.caller_instance.call((ip, int(port)))

    def onButtonSendMessageClick(self):
        message = self.EntryMessage.get()
        self.MessagesListBox.insert(
            END, "{author}> {message}".format(author="self", message=message))
        ip, port = self.EntryAddress.get().split(':')
        self.caller_instance.send(message=message, address=(ip, int(port)))

    def onButtonEndCallClick(self):
        self.caller_instance.hang_up()

    def onMessageRecieved(self, author, message):
        """
        :param author: Address of author, tuple (ip, port)
        :param message: Content
        """
        author = ''.join([author[0], ':', str(author[1])])
        self.MessagesListBox.insert(
            END, "{author}> {message}".format(author=author, message=message))

    def checkStatus(self):
        status = self.caller_instance.status
        if status.startswith('On'):
            self.CanvasCallmode.create_oval(1,
                                            1,
                                            20,
                                            20,
                                            fill="green",
                                            outline="light grey")
            self.EntryAddress.delete(0, END)
            self.EntryAddress.insert(
                0, "{}:{}".format(self.caller_instance.interlocutor[0],
                                  self.caller_instance.interlocutor[1]))
            self.EntryAddress.configure(state='readonly')

        elif status.startswith('Not'):
            self.CanvasCallmode.create_oval(1,
                                            1,
                                            20,
                                            20,
                                            fill="red",
                                            outline="light grey")
            self.EntryAddress.configure(state='')
        else:
            self.CanvasCallmode.create_oval(1,
                                            1,
                                            20,
                                            20,
                                            fill="yellow",
                                            outline="light grey")
            self.EntryAddress.configure(state='readonly')
        self.LabelCallmode['text'] = status
        self.parent.after(ms=100, func=self.checkStatus)

    def __centerWindow(self):
        w = 260
        h = 270
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - w) / 2
        y = (sh - h) / 2
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
示例#21
0
class SelectPaths(MyFrame):
    def __init__(self, topframe=None):

        MyFrame.__init__(self, topframe=topframe)

        style = Style()
        style.theme_use('clam')

        self.patient_foler_path = ""
        self.patients = []
        self.set_title('Brain segmentation GUI')
        self.add_ui_components()

    def add_ui_components(self):

        # Creating the frames.
        self.sub_frame1 = Frame(self)
        self.sub_frame1.grid(column=0, row=0)

        sub_frame2 = Frame(self)
        sub_frame2.grid(column=0, row=1)

        sub_frame3 = Frame(self)
        sub_frame3.grid(column=0, row=2)

        sub_frame21 = Frame(sub_frame2)
        sub_frame21.grid(column=0, row=0)

        sub_frame22 = Frame(sub_frame2)
        sub_frame22.grid(padx=20, column=1, row=0)

        sub_frame221 = Frame(sub_frame22)
        sub_frame221.grid(row=1, column=0)

        # Creating the top-menu buttons.
        self.visualise_button = Button(self.sub_frame1,
                                       text="Visualise",
                                       command=self.start_visualisation)
        self.visualise_button.grid(row=0, column=1)

        self.help_button = Button(self.sub_frame1,
                                  text="Help",
                                  command=self.open_help)
        self.help_button.grid(row=0, column=2)

        # Creating the select modality path.
        self.modality_label = Label(sub_frame21,
                                    text="Path to patient folders",
                                    relief=FLAT)
        self.modality_label.grid(row=1, column=1)
        self.modality_path_entry = Entry(sub_frame21)
        self.modality_path_entry.grid(row=2, column=1)
        #self.modality_path_entry.set(self.patient_folder_path)

        self.modality_path_button = Button(
            sub_frame21,
            text="Choose",
            command=self.choose_directory_and_import)
        self.modality_path_button.grid(row=2, column=2)

        # Creating the patients listbox.
        self.label_patients = Label(sub_frame22, text="Patients")
        self.label_patients.grid(row=0, column=0)

        self.listbox_patients = Listbox(sub_frame221,
                                        selectmode='multiple',
                                        width=50,
                                        height=10)

        self.listbox_patients.pack(side=LEFT, fill=Y)
        #self.listbox_patients.grid(row=1, column=0)
        self.listbox_patients.bind("<Button-1>", self.listbox_changed)

        self.scrollbar = Scrollbar(sub_frame221)
        self.scrollbar.pack(side=RIGHT, fill=Y)

        # attach listbox to scrollbar
        self.listbox_patients.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.listbox_patients.yview)
        # Creating the status console.
        self.status_text = Text(sub_frame3, height=5)
        self.status_text.grid(column=0, row=0)
        self.status_text.tag_configure('title',
                                       justify='center',
                                       font="Arial 10 bold")
        self.status_text.tag_configure('entry', justify='left', font="Arial 9")
        self.status_text.insert(END, 'Status Console', 'title')
        self.status_text_entry_number = 1
        self.status_text.configure(state='disabled')

# ***** EVENTS - START********************************

    def start_visualisation(self):
        """ Launch visualisation module. 
        Linked to self.visualise_button (Button). """

        patient_path = os.path.join(self.patient_folder_path,
                                    'processed_' + self.patients[0])

        segmentation_path = os.path.join(
            patient_path, SEGM_PREFIX + '_' + self.patients[0] + '.nii.gz')

        supervoxel_path = os.path.join(
            patient_path,
            SUPERVOXEL_PREFIX + '_' + self.patients[0] + '.nii.gz')

        # check if the supervoxels and the segmentation exist
        if not os.path.exists(supervoxel_path):
            supervoxel_path = None
        if not os.path.exists(segmentation_path):
            segmentation_path = None

        mod_paths = []
        for mod in MODALITY_PREFIXES:
            mod_paths.append(\
                    os.path.join(patient_path,
                                 mod+'_'+self.patients[0]+'.nii.gz'))

        vis = vv.VisualVolumes(image_paths=mod_paths,
                               segm_path=segmentation_path,
                               supervoxel_id_path=supervoxel_path,
                               topframe=self.master)
        vis.tkraise()

    def listbox_changed(self, event):
        """ Add a patient upon selection in the listbox. 
        Linked to self.listbox_patients (Listbox). """

        indices = list(self.listbox_patients.curselection())
        selected_idx = self.listbox_patients.nearest(event.y)

        if selected_idx == -1:
            return

        # remove or add a patient index
        if selected_idx not in indices:
            indices.append(selected_idx)
        else:
            indices.remove(selected_idx)

        # set self.patients based on the new patient indices and enable visualisation if only one is selected.
        self.patients = []
        for idx in indices:
            self.patients.append(self.listbox_patients.get(idx).split(' ')[0])
        if len(self.patients) == 1:
            self.visualise_button['state'] = 'enabled'
        else:
            self.visualise_button['state'] = 'disabled'

    def choose_directory_and_import(self):
        """ Allow the user to select an import path. 
	    Linked to self.modality_path_button (Button), 
	    and sets self.modality_path_entry (Entry). """

        initialdir = DATA_PATH
        msg = 'Select directory containing patients'
        path = askdirectory(title=msg, initialdir=initialdir)
        # update the text box.
        self.modality_path_entry.delete(0, END)
        self.modality_path_entry.insert(0, str(path))

        # Adding the modality paths after the folder is selected.
        self.patient_folder_path = self.modality_path_entry.get()
        if os.path.exists(self.patient_folder_path):

            patients_validation = os.listdir(self.patient_folder_path)

            # Checking if the patient has the right modalities and importing the patient.
            for i, patient in enumerate(patients_validation):

                # Checking if the patient was already processed.
                if patient.startswith('processed_') or os.path.exists(
                        os.path.join(self.patient_folder_path,
                                     'processed_' + patient)):
                    print("The files of the patient " + patient +
                          " are already copied")
                    continue

                # If everything is fine, then it continues to makign folders and copying files
                # Copying the files into the new folder.
                valid = self._convert_and_copy_files(patient)
                if not valid:
                    patients_validation[i] = None

            # We make a list of patients with only ids for the listbox.
            valid_patients = [p for p in patients_validation if p is not None]
            self.list_existing_patients(valid_patients)

    def _convert_and_copy_files(self, patient):
        """ Check if all valid files exist for this patient and return
        True if so. """

        # Getting the list of modalities for every patient.
        patient_path = os.path.join(self.patient_folder_path, patient)
        modalities = os.listdir(patient_path)

        # Look for paths
        valid_paths = {}
        prefices = [SEGM_PREFIX, SUPERVOXEL_PREFIX] + MODALITY_PREFIXES
        for prefix in prefices:
            candidates = [modality \
                          for modality in modalities \
                          if modality.startswith(prefix+'.')]
            if len(candidates) != 1:
                err = '%s file not identified. Look for ambiguities in %s.' \
                        % (prefix, patient_path)
                print(err)
                return False
            modality = candidates[0]

            if not any([
                    modality.endswith(ext)
                    for ext in ['.mha', '.nii', '.nii.gz']
            ]):
                err = "Image format not recognized: %s. In %s" \
                            % (modality, patient_path)
                print(err)
                return False

            valid_paths[prefix] = modality

        # Creating a processed patient folder.
        os.mkdir(os.path.join(self.patient_folder_path,
                              'processed_' + patient))
        for prefix, basename in valid_paths.iteritems():
            shutil.copyfile(
                os.path.join(self.patient_folder_path, patient, basename),
                os.path.join(self.patient_folder_path, 'processed_' + patient,
                             prefix + '_' + patient + '.nii.gz'))
        return True

    def open_help(self):

        self.help_window = help_window.HelpWindow()
        self.help_window.tkraise()


# ***** EVENTS - END***************************

    def list_existing_patients(self, patients=None):
        print("Importing existing patients")
        # We make a list of patients with only ids for the listbox.

        if patients is None:
            patients = os.listdir(self.patient_folder_path)
        self.patients = []
        for patient in patients:
            if not patient.startswith('processed_'):
                self.patients.append(patient)
        self.patients.sort()
        self.populate_patient_listbox(self.patients)

        if self.listbox_patients.size() > 0:
            self.listbox_patients.selection_set(0)

        self.status_text.configure(state='normal')
        self.status_text.insert(
            END, '\n' + str(self.status_text_entry_number) +
            '- Patients are imported.', 'entry')
        self.status_text_entry_number += 1
        self.status_text.insert(
            END, '\n' + str(self.status_text_entry_number) +
            '- Please select a patient to proceed', 'entry')
        self.status_text_entry_number += 1
        self.status_text.configure(state='disabled')

    def populate_patient_listbox(self, patients):

        self.listbox_patients.delete(0, END)
        for patient in patients:
            patient_path = os.path.join(self.patient_folder_path,
                                        'processed_' + patient)

            #check if a given patient has a label
            if os.path.exists(
                    os.path.join(
                        patient_path, 'corrected_' + SEGM_PREFIX + '_' +
                        patient + '.nii.gz')):
                patient = patient + ' - segmentation corrected'
            self.listbox_patients.insert(END, patient)
示例#22
0
class ListFrame(LabelFrame):
    """
    A Frame representing one of the search term lists
    (e.g. Hashtags, Excluded Users).

    Displays all the items in the list,
    and allows the user to add or remove items.
    Methods should not be called directly;
    instead they should be bound as event handlers.
    """

    def __init__(self, name, add_handler, remove_handler, master=None):
        """
        Creates a ListFrame with the given name as its title.

        add_handler and remove_handler are functions to be called
        when items are added or removed, and should relay the information
        back to the Searcher (or whatever object actually uses the list).
        """
        LabelFrame.__init__(self, master)
        self['text'] = name
        self.add_handler = add_handler
        self.remove_handler = remove_handler
        self.list = Listbox(self)
        self.list.grid(row=0, columnspan=2)
        # Tkinter does not automatically close the right-click menu for us,
        # so we must close it when the user clicks away from the menu.
        self.list.bind("<Button-1>", lambda event: self.context_menu.unpost())
        self.list.bind("<Button-3>", self.open_menu)
        self.context_menu = Menu(self, tearoff=0)
        self.context_menu.add_command(label="Remove", command=self.remove)
        self.input = Entry(self)
        self.input.bind("<Return>", lambda event: self.add())
        self.input.grid(row=1, columnspan=2)
        self.add_button = Button(self)
        self.add_button['text'] = "Add"
        self.add_button['command'] = self.add
        self.add_button.grid(row=2, column=0, sticky=W+E)
        self.remove_button = Button(self)
        self.remove_button['text'] = "Remove"
        self.remove_button['command'] = self.remove
        self.remove_button.grid(row=2, column=1, sticky=W+E)

    def add(self):
        """
        Add the item in the input line to the list.
        """
        self.list.insert(END, self.input.get())
        self.add_handler(self.input.get())
        self.input.delete(0, END)

    def remove(self):
        """
        Remove the active (highlighted) item from the list.
        """
        deleted = self.list.get(ACTIVE)
        self.list.delete(ACTIVE)
        self.remove_handler(deleted)

    def open_menu(self, event):
        """
        Opens a right-click menu for the selected item.
        Currently the menu only has an option for removing the item.
        """
        index = self.list.index("@" + str(event.x) + "," + str(event.y))
        if index < 0:
            return
        self.context_menu.post(event.x_root, event.y_root)
        self.list.activate(index)
        self.list.selection_clear(0, END)
        self.list.selection_set(ACTIVE)