class FInput: """ Class created to manipulate files for output """ def __init__(self, master, label=""): self.label = Label(master, text=label) self.entry = Entry(master) self.button = Button(master, text="Open", command=self.getLoadName) self.options = {} def __call__(self): return self.entry.get() def set(self, value): self.entry.delete(0, END) self.entry.insert(0, value) def setOptions(self, options): """ Getting the options """ self.options = options def getLoadName(self): """ The method that takes the filename """ filename = tkFileDialog.askopenfilename(**self.options) self.entry.delete(0, END) self.entry.insert(0, filename) def enable(self): self.label.config(state=NORMAL) self.entry.config(state=NORMAL) self.button.config(state=NORMAL) def disable(self): self.label.config(state=DISABLED) self.entry.config(state=DISABLED) self.button.config(state=DISABLED)
class encoderface(LabelFrame): def __init__(self, x): LabelFrame.__init__(self, x) # self.default_font = tkFont.nametofont("TkDefaultFont") # self.default_font.configure(family="Helvetica",size=12) self.config(relief=GROOVE) self.config(borderwidth=2, padx=5, pady=5) self.config(text = "Encoder") self.config(labelanchor = "n") self.INSTRUCTION = StringVar() self.INSTRUCTION.set("Instruction") self.machinecode = StringVar() self.machinecode.set("") self.codeEntry = Entry(self, textvariable=self.INSTRUCTION) #self.codeEntry.configure(font=("Helvetica", 12), width=40) self.codeEntry.configure(width=40) self.codeButton = Button(self, text="Compile") self.VHPL = Label(self, text="VHPL") self.codeButton.grid(row=0, column=0, rowspan=4, sticky="wens") self.VHPL.grid(row=0, column=1, sticky="wens") self.VHPL.config(relief=GROOVE, borderwidth=2) self.codeEntry.grid(row=1, column=1, sticky="wens") self.codeEntry.config(fg="green", bg="black") self.pack()
def makeentry(parent, caption, cur, row, column=0, ro=False, **options): Label(parent, text=caption).grid(row=row, column=column) entry = Entry(parent, **options) entry.insert(0, '%s' % cur) if ro: entry.config(state='readonly') entry.grid(row=row, column=column + 1) return entry
class UsernameOverlay(Overlay): def __init__(self, *args, **kwargs): Overlay.__init__(self, *args, **kwargs) self.label = "" self.field = "" self.button = "" self.user = "" self.logger = JPYLogger(self) self.config( background="gold", cursor="arrow" ) self.renderLabel() self.renderField() self.renderButton() def renderLabel(self): self.label = Label(self) self.label.config( text="CHANGE PLAYERNAME", font=Fonts.MONEY_BIG, background="gold" ) self.label.pack() def renderField(self): self.field = Entry(self) self.field.config( relief="solid", bd=2, highlightcolor="black", font=Fonts.USER_LABEL_NAME_BIG ) self.field.pack() def renderButton(self): Label(self, text='\n', background="gold").pack() self.button = Button(self) self.button.config( text="OK", relief="solid", background="black", foreground="gold", font=Fonts.MONEY_MEDIUM, command=self.save ) self.button.pack() def save(self): self.logger.prompt("User " + str(self.user.id) + " changed name from '" + self.user.name.get() + "' to '" + self.field.get() + "'") self.user.name.set(self.field.get()) self.hide(self) self.root.root.inputController.blockBuzzer = False def insert(self, user): self.field.delete(0, END) self.field.insert(0, user.name.get())
class Entry_Widget_Set_C(object): def __init__(self, rootFrame, color, name, relief, side=side, padx=padx, pady=pady, width=width): self.labelFrame = Frame(rootFrame, width=150, height=0, bg=color, borderwidth=3, relief=relief) self.labelFrame.pack(padx=padx, pady=pady, side=side) self.label = Label(self.labelFrame, anchor=NW, text=name, bg=color, font=("Helvetica", 7)) self.label.pack(padx=0, pady=0) self.variable = StringVar() if callback: self.variable.trace( "w", lambda name, index, mode, sv=self.variable: callback(sv)) self.entree = Entry(self.labelFrame, textvariable=self.variable, width=width) self.entree.pack(side=side, padx=5, pady=4) self.entree.config(state=DISABLED) def __del__(self): try: del self.entree, self.variable, self.labelFrame except: pass
def __init__(self): root = Tk() root.title('count days') root.resizable(False, False) center_window(root, 200, 200) label_start = Label(root, text="start date:") label_start.pack() entry_start = Entry(root) entry_start.pack() self.contends_start = StringVar() entry_start.config(textvariable=self.contends_start) self.contends_start.set('2014-07-07') label_end = Label(root, text="end date:") label_end.pack() entry_end = Entry(root) entry_end.pack() self.contends_end = StringVar() self.contends_end.set(now_date) entry_end.config(textvariable=self.contends_end) label_tot = Label(root, text="total days:") label_tot.pack() entry_tot = Entry(root) entry_tot.pack() self.contends_tot = StringVar() entry_tot.config(textvariable=self.contends_tot, state='disabled', highlightbackground='red') my_button(root, "count days:", "clik to count", self.count_days)
class App(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.data = '' self.grid() self.label = Label(self, text='not ready', fg='red') self.label.grid() self.img = ImageTk.PhotoImage(file='a.bmp') #Label(self, image=self.img).grid(side='top') Label(self, image=self.img).grid() self.content = StringVar() self.entry = Entry(self) self.entry.grid() self.entry.config(textvariable=self.content) self.entry.bind('<Key-Return>', self.post) def post(self, event): self.data = self.content.get() self.label['text']='ready' self.label['fg'] = 'green' self.quit() def getdata(self): return self.data
def init_dialog(self, master): self.master = master master.title("Joint positions") self.entries = [] for i in range(0, self.num_joints): new_label = Label(master, text="Joint " + str(i)) new_label.grid(row=i, column=0) callback_with_arg = partial(self.inc, -1, i) minus_button = Button(master, text="-", command=callback_with_arg) minus_button.grid(row=i, column=1) new_entry = Entry(master) new_entry.insert(0, "0.0") new_entry.config(width=5) new_entry.grid(row=i, column=2) self.entries.append(new_entry) callback_with_arg = partial(self.inc, 1, i) minus_button = Button(master, text="+", command=callback_with_arg) minus_button.grid(row=i, column=3) self.publish_button = Button(master, text="Send", command=self.send) self.publish_button.grid(row=self.num_joints, column=0)
def init_dialog(self, master): self.master = master master.title("Joint positions") self.entries = [] for i in range(0,self.num_joints): new_label = Label(master, text="Joint " + str(i)) new_label.grid(row=i, column=0) callback_with_arg = partial(self.inc, -1, i) minus_button = Button(master, text="-", command=callback_with_arg) minus_button.grid(row=i, column=1) new_entry = Entry(master) new_entry.insert(0,"0.0") new_entry.config(width=5) new_entry.grid(row=i, column=2) self.entries.append(new_entry) callback_with_arg = partial(self.inc, 1, i) minus_button = Button(master, text="+", command=callback_with_arg) minus_button.grid(row=i, column=3) self.publish_button = Button(master, text="Send", command=self.send) self.publish_button.grid(row=self.num_joints, column=0)
class PanelInformation(Frame): def __init__(self,parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.frame = Frame(self.parent, relief=RAISED,borderwidth=1) self.xL = StringVar() self.xLE = StringVar() self.positionXL = Label(self.frame, textvariable=self.xL) self.positionXL.grid(row=0,column=0) self.positionXE = Entry(self.frame, textvariable=self.xLE) self.positionXE.grid(row=0,column=1) self.xLE.set(0) self.yL = StringVar() self.yLE = StringVar() self.positionYL = Label(self.frame, textvariable=self.yL) self.positionYL.grid(row=1,column=0) self.positionYE = Entry(self.frame, textvariable=self.yLE) self.positionYE.grid(row=1,column=1) self.yLE.set(0) self.thetaL = StringVar() self.thetaLE = StringVar() self.positionThetaL = Label(self.frame, textvariable=self.thetaL) self.positionThetaL.grid(row=2,column=0) self.positionThetaE = Entry(self.frame, textvariable=self.thetaLE) self.positionThetaE.grid(row=2,column=1) self.thetaLE.set(0) def getInfo(self): return (self.positionXE.get(),self.positionYE.get(),self.positionThetaE.get()) def setInfo(self,x,y,theta): self.xLE.set(x) self.yLE.set(y) self.thetaLE.set(theta) def getFrame(self): return self.frame def setDisableEntry(self): self.positionXE.config(state=DISABLED) self.positionYE.config(state=DISABLED) self.positionThetaE.config(state=DISABLED) def setLabelXLabel(self,text): self.xL.set(text) def setLabelYLabel(self,text): self.yL.set(text) def setLabelThetaLabel(self,text): self.thetaL.set(text)
class _Hatch_GUI(object): """ create a Hatch object from hatch_supt and to then create a skeleton python project. """ def __init__(self, master): self.initComplete = 0 self.master = master self.x, self.y, self.w, self.h = -1, -1, -1, -1 # bind master to <Configure> in order to handle any resizing, etc. # postpone self.master.bind("<Configure>", self.Master_Configure) self.master.bind('<Enter>', self.bindConfigure) self.master.title("PyHatch GUI") self.master.resizable(0, 0) # Linux may not respect this dialogframe = Frame(master, width=810, height=630) dialogframe.pack() self.Shortdesc_Labelframe = LabelFrame( dialogframe, text="Short Description (1-liner)", height="90", width="718") self.Shortdesc_Labelframe.place(x=60, y=127) helv20 = tkFont.Font(family='Helvetica', size=20, weight='bold') self.Buildproject_Button = Button(dialogframe, text="Build Project", width="15", font=helv20) self.Buildproject_Button.place(x=492, y=10, width=263, height=68) self.Buildproject_Button.bind("<ButtonRelease-1>", self.Buildproject_Button_Click) self.Selectdir_Button = Button(dialogframe, text="<Select Directory>", width="15") self.Selectdir_Button.place(x=72, y=585, width=672, height=31) self.Selectdir_Button.bind("<ButtonRelease-1>", self.Selectdir_Button_Click) self.Author_Entry = Entry(dialogframe, width="15") self.Author_Entry.place(x=228, y=424, width=187, height=21) self.Author_Entry_StringVar = StringVar() self.Author_Entry.configure(textvariable=self.Author_Entry_StringVar) self.Author_Entry_StringVar.set("John Doe") self.Classname_Entry = Entry(dialogframe, width="15") self.Classname_Entry.place(x=192, y=73, width=165, height=21) self.Classname_Entry_StringVar = StringVar() self.Classname_Entry.configure( textvariable=self.Classname_Entry_StringVar) self.Classname_Entry_StringVar.set("MyClass") self.Copyright_Entry = Entry(dialogframe, width="15") self.Copyright_Entry.place(x=228, y=478, width=461, height=21) self.Copyright_Entry_StringVar = StringVar() self.Copyright_Entry.configure( textvariable=self.Copyright_Entry_StringVar) self.Copyright_Entry_StringVar.set("Copyright (c) 2013 John Doe") self.Email_Entry = Entry(dialogframe, relief="sunken", width="15") self.Email_Entry.place(x=228, y=505, width=458, height=21) self.Email_Entry_StringVar = StringVar() self.Email_Entry.configure(textvariable=self.Email_Entry_StringVar) self.Email_Entry_StringVar.set("*****@*****.**") self.GithubUserName_Entry = Entry(dialogframe, relief="sunken", width="15") self.GithubUserName_Entry.place(x=228, y=539, width=458, height=21) self.GithubUserName_Entry_StringVar = StringVar() self.GithubUserName_Entry.configure( textvariable=self.GithubUserName_Entry_StringVar) self.GithubUserName_Entry_StringVar.set("github_user_name") self.Funcname_Entry = Entry(dialogframe, width="15") self.Funcname_Entry.place(x=192, y=100, width=157, height=21) self.Funcname_Entry_StringVar = StringVar() self.Funcname_Entry.configure( textvariable=self.Funcname_Entry_StringVar) self.Funcname_Entry_StringVar.set("my_function") # License values should be correct format LICENSE_OPTIONS = tuple(sorted(CLASSIFIER_D.keys())) self.License_Entry_StringVar = StringVar() self.License_Entry = OptionMenu(dialogframe, self.License_Entry_StringVar, *LICENSE_OPTIONS) self.License_Entry.place(x=552, y=424, width=184, height=21) self.License_Entry_StringVar.set(LICENSE_OPTIONS[0]) self.Mainpyname_Entry = Entry(dialogframe, width="15") self.Mainpyname_Entry.place(x=168, y=37, width=196, height=21) self.Mainpyname_Entry_StringVar = StringVar() self.Mainpyname_Entry.configure( textvariable=self.Mainpyname_Entry_StringVar) self.Mainpyname_Entry_StringVar.set("main.py") self.Projname_Entry = Entry(dialogframe, width="15") self.Projname_Entry.place(x=168, y=10, width=194, height=21) self.Projname_Entry_StringVar = StringVar() self.Projname_Entry.configure( textvariable=self.Projname_Entry_StringVar) self.Projname_Entry_StringVar.set("MyProject") self.Shortdesc_Entry = Entry(dialogframe, width="15") self.Shortdesc_Entry.place(x=72, y=150, width=688, height=48) self.Shortdesc_Entry_StringVar = StringVar() self.Shortdesc_Entry.configure( textvariable=self.Shortdesc_Entry_StringVar) self.Shortdesc_Entry_StringVar.set("My project does this") # Status must be correct format self.Status_Entry_StringVar = StringVar() self.Status_Entry = OptionMenu(dialogframe, self.Status_Entry_StringVar, *DEV_STATUS_OPTIONS) self.Status_Entry.place(x=228, y=451, width=183, height=21) self.Status_Entry_StringVar.set(DEV_STATUS_OPTIONS[0]) self.Version_Entry = Entry(dialogframe, width="15") self.Version_Entry.place(x=552, y=451, width=184, height=21) self.Version_Entry_StringVar = StringVar() self.Version_Entry.configure(textvariable=self.Version_Entry_StringVar) self.Version_Entry_StringVar.set("0.1.1") self.Author_Label = Label(dialogframe, text="Author", width="15") self.Author_Label.place(x=96, y=424, width=112, height=22) self.Classname_Label = Label(dialogframe, text="Class Name", width="15") self.Classname_Label.place(x=60, y=73, width=112, height=22) self.Copyright_Label = Label(dialogframe, text="Copyright", width="15") self.Copyright_Label.place(x=96, y=478, width=113, height=23) self.Email_Label = Label(dialogframe, text="Email", width="15") self.Email_Label.place(x=96, y=505, width=113, height=23) self.GithubUserName_Label = Label(dialogframe, text="GithubUserName", width="15") self.GithubUserName_Label.place(x=96, y=539, width=113, height=23) self.Funcname_Label = Label(dialogframe, text="Function Name", width="15") self.Funcname_Label.place(x=60, y=100, width=112, height=22) self.License_Label = Label(dialogframe, text="License", width="15") self.License_Label.place(x=432, y=424, width=113, height=23) self.Longdesc_Label = Label(dialogframe, text="Paragraph Description", width="15") self.Longdesc_Label.place(x=216, y=220, width=376, height=22) self.Mainpyname_Label = Label(dialogframe, text="Main Python File", width="15") self.Mainpyname_Label.place(x=48, y=37, width=112, height=22) self.Projname_Label = Label(dialogframe, text="Project Name", width="15") self.Projname_Label.place(x=48, y=10, width=112, height=22) self.Selectdir_Label = Label( dialogframe, text="Select the Directory Below Which to Place Your Project", width="15") self.Selectdir_Label.place(x=156, y=567, width=536, height=24) self.Status_Label = Label(dialogframe, text="Status", width="15") self.Status_Label.place(x=96, y=451, width=114, height=24) self.Version_Label = Label(dialogframe, text="Version", width="15") self.Version_Label.place(x=432, y=451, width=113, height=23) self.Isclass_Radiobutton = Radiobutton(dialogframe, text="Class Project", value="Class Project", width="15", anchor=W) self.Isclass_Radiobutton.place(x=320, y=73, width=135, height=27) self.RadioGroup1_StringVar = StringVar() self.RadioGroup1_StringVar.set("Class Project") self.RadioGroup1_StringVar_traceName = \ self.RadioGroup1_StringVar.trace_variable("w", self.RadioGroup1_StringVar_Callback) self.Isclass_Radiobutton.configure(variable=self.RadioGroup1_StringVar) self.Isfunction_Radiobutton = Radiobutton(dialogframe, text="Function Project", value="Function Project", width="15", anchor=W) self.Isfunction_Radiobutton.place(x=320, y=100, width=135, height=27) self.Isfunction_Radiobutton.configure( variable=self.RadioGroup1_StringVar) lbframe = Frame(dialogframe) self.Text_1_frame = lbframe scrollbar = Scrollbar(lbframe, orient=VERTICAL) self.Text_1 = Text(lbframe, width="40", height="6", yscrollcommand=scrollbar.set) scrollbar.config(command=self.Text_1.yview) scrollbar.pack(side=RIGHT, fill=Y) self.Text_1.pack(side=LEFT, fill=BOTH, expand=1) self.Text_1_frame.place(x=72, y=250, width=665, height=160) # >>>>>>insert any user code below this comment for section "top_of_init" self.dirname = '<Select Directory>' self.Funcname_Entry.config(state=DISABLED) h = Hatch(projName='MyProject', mainDefinesClass='N') if h.author: self.Author_Entry_StringVar.set(h.author) if h.proj_license: self.License_Entry_StringVar.set(h.proj_license) if h.proj_copyright: self.Copyright_Entry_StringVar.set(h.proj_copyright) if h.email: self.Email_Entry_StringVar.set(h.email) if h.github_user_name: self.GithubUserName_Entry_StringVar.set(h.github_user_name) del h def build_result_dict(self): """Takes user inputs from GUI and builds a dictionary of results""" # pylint: disable=W0201 self.result = {} # return a dictionary of results self.result["author"] = self.Author_Entry_StringVar.get() self.result["status"] = self.Status_Entry_StringVar.get() self.result["proj_license"] = self.License_Entry_StringVar.get() self.result["version"] = self.Version_Entry_StringVar.get() self.result["proj_copyright"] = self.Copyright_Entry_StringVar.get() self.result["email"] = self.Email_Entry_StringVar.get() self.result[ "github_user_name"] = self.GithubUserName_Entry_StringVar.get() self.result["main_py_name"] = self.Mainpyname_Entry_StringVar.get() self.result["proj_name"] = self.Projname_Entry_StringVar.get() self.result["class_name"] = self.Classname_Entry_StringVar.get() self.result["func_name"] = self.Funcname_Entry_StringVar.get() self.result["short_desc"] = self.Shortdesc_Entry_StringVar.get() self.result["para_desc"] = self.Text_1.get(1.0, END) self.result["parent_dir"] = self.dirname if self.RadioGroup1_StringVar.get() == "Class Project": self.result["is_class_project"] = 'Y' else: self.result["is_class_project"] = 'N' def Buildproject_Button_Click(self, event): """When clicked, this method gathers all the user inputs and builds the project skeleton in the directory specified. """ # tkinter requires arguments, but I don't use them # pylint: disable=W0613 # >>>>>>insert any user code below this comment for section "compID=29" # replace, delete, or comment-out the following #print "executed method Buildproject_Button_Click" if not os.path.isdir(self.dirname): ShowError( title='Need Parent Directory', message= 'You need to choose a directory in which to place your project.' ) else: self.build_result_dict() # builds self.result dict r = self.result h = Hatch(projName=r["proj_name"], mainDefinesClass=r["is_class_project"], mainPyFileName=r["main_py_name"], mainClassName=r["class_name"], mainFunctionName=r["func_name"], author=r["author"], proj_copyright=r["proj_copyright"], proj_license=r["proj_license"], version=r["version"], email=r["email"], status=r["status"], github_user_name=r["github_user_name"], simpleDesc=r["short_desc"], longDesc=r["para_desc"]) call_result = h.save_project_below_this_dir(self.dirname) if call_result == 'Success': if AskYesNo(title='Exit Dialog', message='Do you want to leave this GUI?'): self.master.destroy() else: ShowWarning( title='Project Build Error', message='Project did NOT build properly.\n'+\ 'Warning Message = (%s)'%call_result) # return a string containing directory name def AskDirectory(self, title='Choose Directory', initialdir="."): """Simply wraps the tkinter function of the "same" name.""" dirname = tkFileDialog.askdirectory(parent=self.master, initialdir=initialdir, title=title) return dirname # <-- string def Selectdir_Button_Click(self, event): # I don't care what the exception is, if there's a problem, bail # Also, I want to redefine the dirname attribute here # pylint: disable=W0702, W0201 # tkinter requires arguments, but I don't use them # pylint: disable=W0613 """Selects the directory in which to build project.""" dirname = self.AskDirectory(title='Choose Directory For Nose Tests', initialdir='.') if dirname: try: dirname = os.path.abspath(dirname) except: self.dirname = '<Select Directory>' return # let Alarm force dir selection self.dirname = dirname self.Selectdir_Button.config(text=self.dirname) def RadioGroup1_StringVar_Callback(self, varName, index, mode): # tkinter requires arguments, but I don't use them # pylint: disable=W0613 """Responds to changes in RadioGroup1_StringVar.""" if self.RadioGroup1_StringVar.get() == "Class Project": self.Funcname_Entry.config(state=DISABLED) self.Classname_Entry.config(state=NORMAL) else: self.Classname_Entry.config(state=DISABLED) self.Funcname_Entry.config(state=NORMAL) # tk_happy generated code. DO NOT EDIT THE FOLLOWING. section "Master_Configure" def bindConfigure(self, event): """bindConfigure and Master_Configure help stabilize GUI""" # tkinter requires arguments, but I don't use them # pylint: disable=W0613 if not self.initComplete: self.master.bind("<Configure>", self.Master_Configure) self.initComplete = 1 def Master_Configure(self, event): """bindConfigure and Master_Configure help stabilize GUI""" # >>>>>>insert any user code below this comment for section "Master_Configure" # replace, delete, or comment-out the following if event.widget != self.master: if self.w != -1: return x = int(self.master.winfo_x()) y = int(self.master.winfo_y()) w = int(self.master.winfo_width()) h = int(self.master.winfo_height()) if (self.x, self.y, self.w, self.h) == (-1, -1, -1, -1): self.x, self.y, self.w, self.h = x, y, w, h if self.w != w or self.h != h: print "Master reconfigured... make resize adjustments" self.w = w self.h = h
class ChemicalEditor: """Gets the contaminant properties.""" def __init__(self, master, system, chemical, chemicals, database, editflag): """Constructor method. Defines the parameters to be obtained in this window.""" self.master = master self.fonttype = system.fonttype self.version = system.version self.superfont = get_superfont(self.fonttype) #superscript font self.frame = Frame(master.frame) self.tframe = Frame(master.tframe) self.bframe = Frame(master.bframe) self.system = system self.database = database self.top = None #flag for existence of toplevel# self.tkfont = tkFont.Font(font=system.fonttype) self.soluableflag = chemical.soluable self.editflag = editflag self.cancelflag = 0 self.chemicals = chemicals self.diffunit = system.diffunit self.diffunits = system.diffunits if self.soluableflag == 1: self.database = database self.chemical = chemical self.name = StringVar(value='') self.formula = StringVar(value='') self.MW = DoubleVar(value=0) self.temp = DoubleVar(value=0) self.Dw = DoubleVar(value=0) self.Ref = StringVar(value='') self.Koc = DoubleVar(value=0) self.Kdoc = DoubleVar(value=0) self.Kf = DoubleVar(value=0) self.N = DoubleVar(value=0) if editflag == 1: #Detemine whether the chemical is added or edited self.name.set(self.chemical.name) self.formula.set(self.chemical.formula) self.MW.set(self.chemical.MW) self.temp.set(self.chemical.temp) self.Dw.set(self.chemical.Dw) self.Koc.set(self.chemical.Koc) self.Kdoc.set(self.chemical.Kdoc) self.Ref.set(self.chemical.Ref) self.Kf.set(self.chemical.Kf) self.N.set(self.chemical.N) else: self.name = StringVar(value=' ') self.formula = StringVar(value=' ') self.MW = DoubleVar(value=100) self.temp = DoubleVar(value=0) self.Dw = DoubleVar(value=0) self.Koc = DoubleVar(value=0) self.Kdoc = DoubleVar(value=0) self.Kf = DoubleVar(value=0) self.N = DoubleVar(value=0) if editflag == 1: #Detemine whether the chemical is added or edited self.name.set(chemical.name) def make_widgets(self): """Make the widgets for the window.""" self.bgcolor = self.frame.cget('bg') self.instructions = Label( self.tframe, text= ' Please provide the following chemical properties: ' ) self.blankcolumn = Label(self.frame, text=' ', width=2) self.namecolumn = Label(self.frame, text=' ', width=20) self.MWcolumn = Label(self.frame, text=' ', width=12) self.tempcolumn = Label(self.frame, text=' ', width=10) self.Dwcolumn = Label(self.frame, text=' ', width=18) self.Koccolumn = Label(self.frame, text=' ', width=18) self.Kdoccolumn = Label(self.frame, text=' ', width=18) self.Refcolumn = Label(self.frame, text=' ', width=20) self.Rightcolumn = Label(self.frame, text=' ', width=2) self.namelabel = Label(self.frame, text='Chemical name') self.MWlabel = Label(self.frame, text='Molecular\n weight') self.templabel = Label(self.frame, text='Temperature') self.Dwlabel = Label(self.frame, text='Molecular diffusivity\n in water') self.Koclabel = Label(self.frame, text='Organic carbon\n partition coefficient') self.Kdoclabel = Label( self.frame, text='Dissolved organic carbon\n partition coefficient') self.Reflabel = Label(self.frame, text='Reference') self.tempunits = Label(self.frame, text=unichr(176) + 'C') self.Dwunits = Label(self.frame, text=self.diffunit) self.Kocunits = Label(self.frame, text='log(L/kg)') self.Kdocunits = Label(self.frame, text='log(L/kg)') self.importbutton = Button(self.frame, text='From Database', width=20, command=self.importchemical) self.okbutton = Button(self.frame, text='OK', width=20, command=self.OK) self.cancelbutton = Button(self.frame, text='Cancel', width=20, command=self.Cancel) self.blank1 = Label(self.frame, text=' ') self.blank2 = Label(self.frame, text=' ') #show the widgets on the grid self.instructions.grid(row=0, column=0, columnspan=6, padx=8, sticky='W') self.blankcolumn.grid(row=1, column=0, sticky='WE', padx=1, pady=1) self.namecolumn.grid(row=1, column=1, sticky='WE', padx=1, pady=1) self.MWcolumn.grid(row=1, column=2, sticky='WE', padx=1, pady=1) self.tempcolumn.grid(row=1, column=3, sticky='WE', padx=1, pady=1) self.Dwcolumn.grid(row=1, column=4, sticky='WE', padx=1, pady=1) self.Koccolumn.grid(row=1, column=5, sticky='WE', padx=1, pady=1) self.Kdoccolumn.grid(row=1, column=6, sticky='WE', padx=1, pady=1) self.Refcolumn.grid(row=1, column=7, sticky='WE', padx=1, pady=1) self.Rightcolumn.grid(row=1, column=8, sticky='WE', padx=1, pady=1) self.namelabel.grid(row=2, column=1, sticky='WE', padx=1, pady=1) self.MWlabel.grid(row=2, column=2, sticky='WE', padx=1, pady=1) self.templabel.grid(row=2, column=3, sticky='WE', padx=1, pady=1) self.Dwlabel.grid(row=2, column=4, sticky='WE', padx=1, pady=1) self.Koclabel.grid(row=2, column=5, sticky='WE', padx=1, pady=1) self.Kdoclabel.grid(row=2, column=6, sticky='WE', padx=1, pady=1) self.Reflabel.grid(row=2, column=7, sticky='WE', padx=1, pady=1) self.tempunits.grid(row=3, column=3, sticky='WE', padx=1, pady=1) self.Dwunits.grid(row=3, column=4, sticky='WE', padx=1, pady=1) self.Kocunits.grid(row=3, column=5, sticky='WE', padx=1, pady=1) self.Kdocunits.grid(row=3, column=6, sticky='WE', padx=1, pady=1) if self.soluableflag == 1: if self.editflag == 0: self.namewidget = Entry(self.frame, width=18, justify='center', textvariable=self.name) self.tempwidget = Entry(self.frame, width=10, justify='center', textvariable=self.temp) else: self.namewidget = Label(self.frame, width=18, justify='center', textvariable=self.name) self.tempwidget = Label(self.frame, width=10, justify='center', textvariable=self.temp) self.Dwwidget = Entry(self.frame, width=16, justify='center', textvariable=self.Dw) self.MWwidget = Entry(self.frame, width=10, justify='center', textvariable=self.MW) self.Kocwidget = Entry(self.frame, width=16, justify='center', textvariable=self.Koc) self.Kdocwidget = Entry(self.frame, width=16, justify='center', textvariable=self.Kdoc) self.Refwidget = Entry(self.frame, width=18, justify='center', textvariable=self.Ref) self.namewidget.grid(row=4, column=1, padx=2, pady=1) self.MWwidget.grid(row=4, column=2, padx=2, pady=1) self.tempwidget.grid(row=4, column=3, padx=2, pady=1) self.Dwwidget.grid(row=4, column=4, padx=2, pady=1) self.Kocwidget.grid(row=4, column=5, padx=2, pady=1) self.Kdocwidget.grid(row=4, column=6, padx=2, pady=1) self.Refwidget.grid(row=4, column=7, padx=2, pady=1) else: self.namewidget = Entry(self.frame, width=18, justify='center', textvariable=self.name) self.Dwwidget = Label(self.frame, width=16, justify='center', text='Not applicable') self.Kocwidget = Label(self.frame, width=16, justify='center', text='Not applicable') self.Kdocwidget = Label(self.frame, width=16, justify='center', text='Not applicable') self.namewidget.grid(row=4, column=1, padx=2, pady=1) self.Dwwidget.grid(row=4, column=3, padx=2, pady=1) self.Kocwidget.grid(row=4, column=4, padx=2, pady=1) self.Kdocwidget.grid(row=4, column=5, padx=2, pady=1) self.blank1.grid(row=5) if self.editflag == 0: self.importbutton.grid(row=6, columnspan=11) self.okbutton.grid(row=7, columnspan=11) self.cancelbutton.grid(row=8, columnspan=11) self.blank2.grid(row=9) self.okbutton.bind('<Return>', self.OK) self.focusbutton = self.okbutton if int((self.tkfont.measure(self.Ref.get()) + 10) * 1.1424219345 / 8) + 1 > 18: self.Refwidget.config( width=int((self.tkfont.measure(self.Ref.get()) + 10) * 1.1424219345 / 8) + 3) if int((self.tkfont.measure(self.name.get()) + 10) * 1.1424219345 / 8) + 1 > 18: self.namewidget.config( width=int((self.tkfont.measure(self.name.get()) + 10) * 1.1424219345 / 8) + 3) self.master.geometry() self.master.center() def importchemical(self): if self.top is None: self.top = CapSimWindow(master=self.master, buttons=2) self.top.make_window( ChemicalImporter(self.top, self.system, self.database)) self.top.tk.mainloop() if self.top.window.cancelflag == 0: self.updatechemical(self.top.window) if self.top is not None: self.top.destroy() self.top = None elif self.top is not None: tkmb.showerror( title=self.system.version, message= 'Please close the existing parameter input window first.') self.top.tk.focus() def updatechemical(self, window): self.name.set(window.name.get()) self.formula.set(window.formula.get()) self.MW.set(window.MW.get()) self.temp.set(window.temp.get()) self.Koc.set(window.Koc.get()) self.Kdoc.set(window.Kdoc.get()) self.Ref.set(window.Ref.get()) self.Kf.set(window.Kf.get()) self.N.set(window.N.get()) if self.diffunit == self.diffunits[0]: self.Dw.set(window.Dw.get()) elif self.diffunit == self.diffunits[1]: Dw = window.Dw.get() * 86400 * 365 if Dw > 1: self.Dw.set(round(Dw, 2)) else: i = 2 while Dw / 100 < 0.1**i: i = i + 1 self.Dw.set(round(Dw, i)) self.frame.update() if int((self.tkfont.measure(self.Ref.get()) + 10) * 1.1424219345 / 8) + 1 > 20: self.Refwidget.config( width=int((self.tkfont.measure(self.Ref.get()) + 10) * 1.1424219345 / 8) + 3) if int((self.tkfont.measure(self.name.get()) + 10) * 1.1424219345 / 8) + 1 > 20: self.namewidget.config( width=int((self.tkfont.measure(self.name.get()) + 10) * 1.1424219345 / 8) + 3) self.master.geometry() self.master.center() def OK(self, event=None): """Finish and move on. Checks that the number chemicals are less than the total number of chemicals in database.""" if self.editflag == 0: check = [(chemical.name == self.name.get()) for chemical in self.chemicals[0:-1]] else: check = [0] if self.master.window.top is not None: self.master.open_toplevel() elif sum(check) >= 1: self.chemicals_error() elif self.name.get() == '' or self.name.get().count(' ') == len( self.name.get()): self.name_error() elif self.Dw.get() == 0: self.Dw_error() else: self.master.tk.quit() def chemicals_error(self): tkmb.showerror(title=self.version, message='This chemical has already been selected!') self.focusbutton = self.okbutton self.master.tk.lift() def name_error(self): tkmb.showerror(title=self.version, message='Please input the name for the chemical!') self.focusbutton = self.okbutton self.master.tk.lift() def Dw_error(self): tkmb.showerror( title=self.version, message= 'The diffusivity of the chemical can not be zero, please correct!') self.focusbutton = self.okbutton self.master.tk.lift() def Cancel(self): try: self.name.set(self.chemical.name) self.MW.set(self.chemical.MW.get()) self.formula.set(self.chemical.formula.get()) self.temp.set(self.chemical.temp.get()) self.Dw.set(self.chemical.Dw.get()) self.Koc.set(self.chemical.Koc.get()) self.Kdoc.set(self.chemical.Kdoc.get()) self.Ref.set(self.chemical.Ref.get()) self.Kf.set(self.chemical.Kf.get()) self.N.set(self.chemical.N.get()) except: self.cancelflag = 1 if self.master.window.top is not None: self.master.open_toplevel() else: self.master.tk.quit()
def __init__(self): root = Tk() root.title('speaker identification') root.resizable(False, False) center_window(root, 300, 250) separator = Frame(root, height=4, bd=2, relief=SUNKEN) separator.pack(fill=X, padx=5, pady=5) lable_title = Label(root, text="说话人识别".decode('gbk').encode('utf-8')) lable_title.pack() separator = Frame(root, height=2, bd=1, relief=SUNKEN) separator.pack(fill=X, padx=5, pady=5) frm = Frame(root) frm_left = Frame(frm) # label details label = Label(frm_left) label['text'] = "Record a wave" label.pack() # label details button = Button(frm_left) button['text'] = "clik to record" button['command'] = self.record_wave button.pack() # # record_wave_path=Entry(frm_left) # record_wave_path.pack() frm_left.pack(side=LEFT) frm_right = Frame(frm) self.my_button(frm_right, "choose a wav", "click and find", self.choose_file) # choose_wave_path=Entry(frm_right) # choose_wave_path.pack() frm_right.pack(side=LEFT) frm.pack() separator = Frame(root, height=2, bd=1, relief=SUNKEN) separator.pack(fill=X, padx=5, pady=5) frm_path = Frame(root) labe_path = Label(frm_path) labe_path['text'] = 'file path:' labe_path.pack(side=LEFT) wave_path = Entry(frm_path, state='disabled') wave_path.pack(side=RIGHT) # show your wav file path self.contents_wave_path = StringVar() # self.contents_wave_path.set("path show out") wave_path.config(textvariable=self.contents_wave_path) frm_path.pack() separator = Frame(root, height=2, bd=1, relief=SUNKEN) separator.pack(fill=X, padx=5, pady=5) # 开始检测 frm_start = Frame(root) self.my_button(frm_start, "start", "clik to start", self.start_identification) frm_start.pack() separator = Frame(root, height=2, bd=1, relief=SUNKEN) separator.pack(fill=X, padx=5, pady=5) # 显示结果输出 frm_result = Frame(root) result_label = Label(frm_result, text='识别结果:'.decode('gbk').encode('utf-8')) result_label.pack(side=LEFT) result_entry = Entry(frm_result, state='disabled', highlightbackground='red') result_entry.pack(side=RIGHT) # show result contends self.contents_result_entry = StringVar() self.contents_result_entry.set(" ".decode('gbk').encode('utf-8')) result_entry.config(textvariable=self.contents_result_entry) frm_result.pack() separator = Frame(root, height=2, bd=1, relief=SUNKEN) separator.pack(fill=X, padx=5, pady=5)
class pump_ui(object): def __init__(self): master = Tk() master.style = ttk.Style() master.style.theme_use("default") master.config(bg=background_colour) master.resizable( 0, 0 ) # Disable resizing the UI to prevent having to make widget placing dynamic master.winfo_toplevel().title(frame_title) master.iconbitmap("bitcoin.ico") # Create pumper assistant to store data on the current BTC and alt holdings. self.pumper = pumper() self.create_title(master) self.create_api_info(master, previous_row=0) self.create_auto_sell(master, previous_row=3) self.create_stop_loss(master, previous_row=4) self.create_order_type(master, previous_row=6) self.create_fee_type(master, previous_row=7) self.create_btc_balance_picker(master, previous_row=8) self.create_alt_ticker(master, previous_row=10) self.create_pump_and_sell_buttons(master, previous_row=11) self.create_current_profit(master, previous_row=12) self.create_output_box(master, rightmost_column=1) # Can hardcode API key and Secret #self.api_key_entry.delete(0,END) #self.api_key_entry.insert(0,"KEY") #self.api_key_entry.config(state=DISABLED) #self.api_secret_entry.delete(0, END) #self.api_secret_entry.insert(0, "SECRET") #self.api_secret_entry.config(state=DISABLED) # Display the UI, this can only be called once per program. # Nothing in the main Python script will be run after creating the UI because of this. master.mainloop() def create_title(self, master, previous_row=-1, previous_column=-1): empty = Label(master, text=frame_title) empty.grid(row=previous_row + 1, column=previous_column + 2, columnspan=1) empty.config(bg=background_colour, fg=label_font_colour) def create_api_info(self, master, previous_row=-1, previous_column=-1): api_key_lbl = Label(master, text="API Key:") api_key_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=1, sticky=E, padx=(3, 0)) api_key_lbl.config(bg=background_colour, fg=label_font_colour) self.api_key_entry = Entry(master, highlightthickness=0, bd=0, width=21, show="*") self.api_key_entry.config(borderwidth=2, relief=default_relief) self.api_key_entry.grid(row=previous_row + 1, column=previous_column + 2) api_secret_lbl = Label(master, text="API Secret:") api_secret_lbl.grid(row=previous_row + 2, column=previous_column + 1, columnspan=1, sticky=E, padx=(3, 0)) api_secret_lbl.config(bg=background_colour, fg=label_font_colour) self.api_secret_entry = Entry(master, highlightthickness=0, bd=0, width=21, show="*") self.api_secret_entry.config(borderwidth=2, relief=default_relief) self.api_secret_entry.grid(row=previous_row + 2, column=previous_column + 2) self.api_connect_btn = Button(master, text="Connect To Binance", command=self.on_connect_api) self.api_connect_btn.grid(row=previous_row + 3, column=previous_column + 2, columnspan=1, sticky=W + E, padx=10, pady=(0, 3)) self.api_connect_btn.config(highlightbackground=background_colour) def create_auto_sell(self, master, previous_row=-1, previous_column=-1): auto_sell_lbl = Label(master, text="Auto Sell (%):") auto_sell_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=1, sticky=E, padx=(3, 0)) auto_sell_lbl.config(bg=background_colour, fg=label_font_colour) self.auto_sell_spinbox = Spinbox(master, from_=1.0, to=300.0, increment=1.0, highlightbackground=background_colour) self.auto_sell_spinbox.config(borderwidth=2, relief=default_relief) self.auto_sell_spinbox.grid(row=previous_row + 1, column=previous_column + 2) self.auto_sell_spinbox.delete(0, "end") self.auto_sell_spinbox.insert(0, 50) def create_stop_loss(self, master, previous_row=-1, previous_column=-1): stop_loss_lbl = Label(master, text="Stop Loss (%):") stop_loss_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=1, sticky=E, padx=(3, 0)) stop_loss_lbl.config(bg=background_colour, fg=label_font_colour) self.stop_loss_spinbox = Spinbox(master, from_=-100.0, to=-10.0, increment=1.0, highlightbackground=background_colour) self.stop_loss_spinbox.config(borderwidth=2, relief=default_relief) self.stop_loss_spinbox.grid(row=previous_row + 1, column=previous_column + 2) self.stop_loss_spinbox.delete(0, "end") self.stop_loss_spinbox.insert(0, -10) def create_btc_balance_picker(self, master, previous_row=-1, previous_column=-1): self.btc_balance_str = StringVar() btc_balance_lbl = Label(master, textvar=self.btc_balance_str) btc_balance_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=2, sticky=W + E, padx=(3, 0)) btc_balance_lbl.config(bg=background_colour, fg=label_font_colour) self.set_available_btc_balance(Decimal(0)) btc_to_use_label = Label(master, text="BTC to spend:", bg=background_colour, fg=label_font_colour) btc_to_use_label.grid(row=previous_row + 2, column=previous_column + 1, sticky=E, padx=(3, 0)) self.btc_to_use_spinbox = Spinbox( master, from_=minimum_trade, to=minimum_trade, increment=btc_to_use_increment, highlightbackground=background_colour) self.btc_to_use_spinbox.config(borderwidth=2, relief=default_relief) self.btc_to_use_spinbox.grid(row=previous_row + 2, column=previous_column + 2) def create_order_type(self, master, previous_row=-1, previous_column=-1): order_type_lbl = Label(master, text="Entry Type:") order_type_lbl.grid(row=previous_row + 1, column=previous_column + 1, sticky=E, padx=(3, 0)) order_type_lbl.config(bg=background_colour, fg=label_font_colour) self.is_entry_market = True def change_order_type(*args): self.is_entry_market = (self.order_type.get() == "Market Buy \/") self.order_type = StringVar() self.order_type.trace( "w", change_order_type ) # Reduces how much work is done when the pump starts choices = {"Market Buy \/", "Limit Buy \/"} self.entry_type_option_menu = OptionMenu(master, self.order_type, *choices) self.entry_type_option_menu.grid(row=previous_row + 1, column=previous_column + 2, sticky=W + E, padx=8) self.entry_type_option_menu.config(highlightthickness=0) self.entry_type_option_menu.configure(indicatoron=0) self.order_type.set("Market Buy \/") def create_fee_type(self, master, previous_row=-1, previous_column=-1): fee_type_lbl = Label(master, text="Fee Type:") fee_type_lbl.grid(row=previous_row + 1, column=previous_column + 1, sticky=E, padx=(3, 0)) fee_type_lbl.config(bg=background_colour, fg=label_font_colour) self.is_using_bnb = True def change_fee_type(*args): self.is_using_bnb = ( self.order_type.get() == "Binance Coin (BNB) \/") self.fee_type = StringVar() self.fee_type.trace( "w", change_fee_type ) # Reduces how much work is done when the pump starts choices = {"Binance Coin (BNB) \/", "0.1% Of All Trades \/"} self.fee_type_option_menu = OptionMenu(master, self.fee_type, *choices) self.fee_type_option_menu.grid(row=previous_row + 1, column=previous_column + 2, sticky=W + E, padx=8) self.fee_type_option_menu.config(highlightthickness=0) self.fee_type_option_menu.configure(indicatoron=0) self.fee_type.set("Binance Coin (BNB) \/") def create_pump_and_sell_buttons(self, master, previous_row=-1, previous_column=-1): # Manual sell button can only be activated after initiating a pump. self.manual_sell_btn = Button(master, text="Sell", state=DISABLED, command=self.on_manual_sell) self.manual_sell_btn.grid(row=previous_row + 1, column=previous_column + 1, sticky=W + E, padx=(3, 0)) self.manual_sell_btn.config(highlightbackground=background_colour) self.pump_btn = Button(master, text="Pump", command=self.on_pump) self.pump_btn.grid(row=previous_row + 1, column=previous_column + 2, sticky=W + E, padx=8) self.pump_btn.config(highlightbackground=background_colour, state=DISABLED) def create_alt_ticker(self, master, previous_row=-1, previous_column=-1): ticker_lbl = Label(master, text="Ticker To Pump:") ticker_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=1, sticky=E, padx=(3, 0), pady=(0, 8)) ticker_lbl.config(bg=background_colour, fg=label_font_colour) self.ticker_entry = Entry(master, highlightthickness=0, bd=0, width=21) self.ticker_entry.config(borderwidth=2, relief=default_relief) self.ticker_entry.grid(row=previous_row + 1, column=previous_column + 2, pady=8) self.ticker_entry.bind('<Return>', self.on_pump_shortcut) def create_current_profit(self, master, previous_row=-1, previous_column=-1): self.current_profit_str = StringVar() current_profit_lbl = Label(master, textvar=self.current_profit_str) current_profit_lbl.grid(row=previous_row + 1, column=previous_column + 1, columnspan=2, sticky=W + E, padx=3, pady=(0, 3)) current_profit_lbl.config(bg=background_colour, fg=label_font_colour) self.current_profit_str.set("Current Profit: 0%") def create_output_box(self, master, rightmost_column): self.pump_output = StringVar() console_lbl = Label(master, textvar=self.pump_output, borderwidth=2, relief=default_relief, anchor=N) console_lbl.grid(row=0, column=rightmost_column + 1, columnspan=1, rowspan=14, padx=(10, 0), pady=0) console_lbl.config(width=50, height=22, bg="black", font=Font(family="Courier", size=9), fg="white") self.lines = 0 def disable_pre_pump_options(self): # Change the buttons that can be clicked to prevent the user # from trying to pump multiple coins with one bot. self.manual_sell_btn.config(state=NORMAL) self.pump_btn.config(state=DISABLED) self.btc_to_use_spinbox.config(state=DISABLED) self.ticker_entry.config(state=DISABLED) self.auto_sell_spinbox.config(state=DISABLED) self.stop_loss_spinbox.config(state=DISABLED) self.api_key_entry.config( state=DISABLED) # Comment out if hardcoding key self.api_secret_entry.config( state=DISABLED) # Comment out if hardcoding secret self.api_connect_btn.config(state=DISABLED) self.entry_type_option_menu.config(state=DISABLED) self.fee_type_option_menu.config(state=DISABLED) def enable_pump_options(self): # Change the buttons that can be clicked to prevent the user # from trying to pump multiple coins with one bot. self.manual_sell_btn.config(state=DISABLED) self.pump_btn.config(state=NORMAL) self.btc_to_use_spinbox.config(state=NORMAL) self.ticker_entry.config(state=NORMAL) self.auto_sell_spinbox.config(state=NORMAL) self.stop_loss_spinbox.config(state=NORMAL) self.api_key_entry.config( state=NORMAL) # Comment out if hardcoding key self.api_secret_entry.config( state=NORMAL) # Comment out if hardcoding secret self.api_connect_btn.config(state=NORMAL) self.entry_type_option_menu.config(state=NORMAL) self.fee_type_option_menu.config(state=NORMAL) def set_available_btc_balance(self, btc_balance): self.pumper.btc_balance = btc_balance self.btc_balance_str.set("Available Balance: " + readable_btc_balance(btc_balance)) def set_current_profit(self, current_profit): self.current_profit_str.set( "Current Profit: " + '{0:.3f}'.format(round(current_profit * Decimal(100), 3)) + "%") def write_to_console(self, line): self.lines += 1 if self.lines > max_lines_in_console: i = self.pump_output.get().index('\n') self.pump_output.set(self.pump_output.get()[i + 1:] + "\n" + line) elif self.lines == 1: self.pump_output.set(line) else: self.pump_output.set(self.pump_output.get() + "\n" + line) #### Button Behaviour #### def on_pump(self): try: api = self.api btc_to_use = Decimal(self.btc_to_use_spinbox.get()) except InvalidOperation: # The BTC to spend box is empty. self.write_to_console("Stop!") self.write_to_console("BTC to spend cannot be empty.") return except AttributeError: # There is no API object. self.write_to_console( "You need to connect to Binance before pumping.") return if btc_to_use >= minimum_trade: if btc_to_use <= self.pumper.btc_balance: target_profit_percentage = Decimal( float(self.auto_sell_spinbox.get()) / 100.0) # Validate auto-sell and stop loss if target_profit_percentage <= Decimal(0): self.write_to_console("Auto sell has to be positive.") return if Decimal(self.stop_loss_spinbox.get()) >= Decimal(0): self.write_to_console("Stop loss has to be negative.") return ticker = self.ticker_entry.get().upper() # Empty strings are False in Python if ticker: full_ticker = api.full_ticker_for(ticker) try: alt = self.api.get_ticker(symbol=full_ticker) except BinanceAPIException, e: logging.debug(str(e)) self.write_to_console("Invalid ticker.") return alt_value = Decimal(alt["askPrice"]) # Used in console output decimal_points = minimum_decimals_in_quantity.get( full_ticker, 0) self.pumper.decimal_points_in_alt = decimal_points self.pumper.set_up(btc_to_use, target_profit_percentage, alt_value, ticker) if self.is_entry_market: self.pumper.alt_holdings = api.market_buy( self.pumper.btc_to_use, full_ticker, self.is_using_bnb) self.write_to_console( "Bought " + readable_alt_balance( decimal_points, pumper=self.pumper) + " with " + readable_btc_balance(btc_to_use) + ".") else: highest_bid = Decimal(alt["bidPrice"]) if alt_value - highest_bid <= Decimal(0.00000001): to_bid = highest_bid else: # Bid between the highest bid and the lowest ask for the best odds of being filled. to_bid = (alt_value - highest_bid) / 2 + highest_bid to_bid = Decimal( floor(to_bid * Decimal(100000000.0)) ) / Decimal(100000000.0) self.pumper.starting_alt_value = to_bid expected = api.limit_buy( btc_to_alt(btc_to_use, alt_value), pumper, full_ticker, to_bid, self.is_using_bnb) self.write_to_console("Buying " + readable_alt_balance( decimal_points, alt_amount=expected, ticker=ticker ) + " for " + readable_btc_balance(btc_to_use) + ".") self.write_to_console( "This is a limit order, it may not get filled.") self.disable_pre_pump_options() self.set_stop_loss() self.start_monitoring_orderbook(full_ticker) else: # The user is trying to trade with more than they actually have. self.write_to_console("You did not enter a ticker.") else: # The user is trying to trade with more than they actually have. self.write_to_console("Stop!") self.write_to_console( "You are trying to spend more BTC than you have.") else:
class DPSinterface: """ DSPinterface is a Tk graphical interface to drive a DPS power supplier. """ def __init__(self, root): """ Create a DSP interface instance. :param root: is the Tk() interface where the DPS will be drawedstring with the prot name i.e. /dev/ttyUSB0 or COM5 for Windows :returns: a new instance of DPS graphical interface """ self.root = root root.title("DPS power supplier interface") root.protocol("WM_DELETE_WINDOW", self.wnwcmdclose) self.dps = None self.poller = None self.waver = None self.strtme = time() self.dpsfwave = None self.maxoutv = 5 self.maxoutc = 5 menubar = Menu(root) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Exit", command=self.wnwcmdclose) menubar.add_cascade(label="File", menu=filemenu) scopemenu = Menu(menubar, tearoff=0) scopemenu.add_command(label="Load sampled points...", command=self.mnucmdloadsmppts) scopemenu.add_command(label="Save sampled points as...", command=self.mnucmdsavesmppts) menubar.add_cascade(label="Scope", menu=scopemenu) wavemenu = Menu(menubar, tearoff=0) wavemenu.add_command(label="New wave", command=self.mnucmdnewwve) wavemenu.add_command(label="Load wave...", command=self.mnucmdloadwve) wavemenu.add_command(label="Edit wave...", command=self.mnucmdedtwve) wavemenu.add_command(label="Save wave as...", command=self.mnucmdsavewve) menubar.add_cascade(label="Wave", menu=wavemenu) memmenu = Menu(menubar, tearoff=0) memmenu.add_command(label="Edit memories...", command=self.mnucmdedtmem) menubar.add_cascade(label="Memory", menu=memmenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="Help...", command=self.mnucmdhelp) helpmenu.add_command(label="About...", command=self.mnucmdabout) menubar.add_cascade(label="Help", menu=helpmenu) root.config(menu=menubar) row = 0 col = 0 rowspan = 1 colspan = 1 insertlabelrow(root, row, col, ("Serial: ", None, "Addr,Baud: "), E) col += colspan self.svardpsport = StringVar() self.svardpsport.set('/dev/ttyUSB0') self.entryserport = Entry(root, textvariable=self.svardpsport, width=ENTRYWIDTH, justify='right') self.entryserport.grid(row=row, column=col, sticky=W) col += colspan col += colspan self.svardpsaddbrt = StringVar() self.svardpsaddbrt.set('1, 9600') self.entrydpsadd = Entry(root, textvariable=self.svardpsaddbrt, width=ENTRYWIDTH, justify='right') self.entrydpsadd.grid(row=row, column=col, sticky=W) col += colspan colspan = 2 self.ivarconctd = IntVar() self.ivarconctd.set(0) Checkbutton(root, variable=self.ivarconctd, text='Connect', command=self.butcmdconnect).grid(row=row, column=col, columnspan=colspan, sticky=E + W) row += rowspan col = 0 colspan = 1 Separator(root, orient='horizontal').grid(row=row, columnspan=8, sticky=E + W, pady=8) row += rowspan rowspan = 1 colspan = 2 col = 0 self.ivarbrghtnes = IntVar() s = Scale(root, label='Brightness', variable=self.ivarbrghtnes, from_=0, to=5, resolution=1, orient="horizontal") s.bind("<ButtonRelease-1>", self.sclbndbrghtnss) s.grid(row=row, column=col, columnspan=colspan, sticky=E + W) col += colspan colspan = 1 Label(root, text="Model: ").grid(row=row, column=col, sticky=E) col += colspan self.ivarmodel = IntVar() Entry(root, textvariable=self.ivarmodel, state="readonly", width=ENTRYWIDTH, justify='right').grid(row=row, column=col, sticky=W) col += colspan colspan = 2 self.ivarsetmem = IntVar() s = Scale(root, label='Mem Recall', variable=self.ivarsetmem, from_=1, to=9, resolution=1, orient="horizontal") s.bind("<ButtonRelease-1>", self.sclbndmemory) s.grid(row=row, column=col, columnspan=colspan, sticky=E + W) row += rowspan colspan = 1 col = 0 insertlabelrow( root, row, col, (("Vinp [V]: ", VCOL), None, "Out Mode: ", None, "Protection: "), E) self.dvarvinp = DoubleVar() self.svarwrmde = StringVar() self.setworkmode(0) self.svarprot = StringVar() self.setprotection(0) insertentryrow( root, row, col, (None, self.dvarvinp, None, self.svarwrmde, None, self.svarprot), 'right', W, 'readonly') colspan = 1 row += rowspan col = 0 insertlabelrow(root, row, col, (("Vmax [V]: ", VCOL), None, ("Cmax [A]: ", CCOL), None, ("Pmax [W]: ", PCOL)), E) self.dvarvmaxm0 = DoubleVar() self.dvarcmaxm0 = DoubleVar() self.dvarpmaxm0 = DoubleVar() entries = insertentryrow(root, row, col, (None, self.dvarvmaxm0, None, self.dvarcmaxm0, None, self.dvarpmaxm0), 'right', W) for e, f in zip(entries, (self.entbndvmax, self.entbndcmax, self.entbndpmax)): e.bind('<FocusOut>', f) e.bind('<Return>', f) row += rowspan col = 0 insertlabelrow(root, row, col, (("Vout [V]: ", VCOL), None, ("Cout [A]: ", CCOL), None, ("Pout [W]: ", PCOL)), E) self.dvarvout = DoubleVar() self.dvarcout = DoubleVar() self.dvarpout = DoubleVar() insertentryrow( root, row, col, (None, self.dvarvout, None, self.dvarcout, None, self.dvarpout), 'right', W, 'readonly') row += rowspan col = 0 self.scope = Scope(root, [], row, col) row += 9 col = 4 Label(root, text="Rte[s/Sa]: ").grid(row=row, column=col, sticky=E) col += colspan self.dvarsecsmp = DoubleVar() self.dvarsecsmp.set(self.scope.sampletime()) e = Entry(root, textvariable=self.dvarsecsmp, width=ENTRYWIDTH, justify='right').grid(row=row, column=col, sticky=W) row += rowspan col = 0 colspan = 2 self.ivaracquire = IntVar() self.ivaracquire.set(0) Checkbutton(root, variable=self.ivaracquire, text='Run Acquisition', command=self.butcmdacquire).grid(row=row, column=col, columnspan=2, sticky=E + W) col += colspan self.ivarkeylock = IntVar() self.ivarkeylock.set(0) Checkbutton(root, variable=self.ivarkeylock, text="Key Lock", command=self.butcmdkeylock).grid(row=row, column=col, sticky=E + W, columnspan=colspan) col += colspan self.ivaroutenab = IntVar() self.ivaroutenab.set(0) Checkbutton(root, variable=self.ivaroutenab, text="Output Enable", command=self.butcmdoutenable).grid(row=row, column=col, sticky=E + W, columnspan=colspan) row += rowspan col = 0 rowspan = 1 colspan = 3 self.dvarvscale = DoubleVar() self.voltscale = Scale(root, label='Vset [V]', foreground=VCOL, variable=self.dvarvscale, from_=0, to=self.maxoutv, resolution=1, orient="horizontal") #, label='Vset[V]' self.voltscale.bind("<ButtonRelease-1>", self.sclbndvolt) self.voltscale.grid(row=row, column=col, columnspan=colspan, sticky=E + W) col += colspan self.dvarcscale = DoubleVar() self.curntscale = Scale(root, label='Cset[A]', foreground=CCOL, variable=self.dvarcscale, from_=0, to=self.maxoutc, resolution=1, orient="horizontal") #,label='Cset[A]' self.curntscale.bind("<ButtonRelease-1>", self.sclbndcrnt) self.curntscale.grid(row=row, column=col, columnspan=colspan, sticky=E + W) row += rowspan col = 0 self.dvarvscalef = DoubleVar() sc = Scale(root, foreground=VCOL, variable=self.dvarvscalef, from_=0, to=0.99, resolution=0.01, orient="horizontal") sc.bind("<ButtonRelease-1>", self.sclbndvolt) sc.grid(row=row, column=col, columnspan=colspan, sticky=E + W) col += colspan self.dvarcscalef = DoubleVar() sc = Scale(root, foreground=CCOL, variable=self.dvarcscalef, from_=0, to=0.99, resolution=0.01, orient="horizontal") sc.bind("<ButtonRelease-1>", self.sclbndcrnt) sc.grid(row=row, column=col, columnspan=colspan, sticky=E + W) row += rowspan col = 0 colspan = 1 Separator(root, orient='horizontal').grid(row=row, columnspan=6, sticky=E + W, pady=8) row += rowspan colspan = 1 col = 0 Label(root, text="Waveform: ").grid(row=row, column=col, sticky=E) col += colspan colspan = 2 self.svarwave = StringVar() Entry(root, textvariable=self.svarwave, width=ENTRYWIDTH, justify='right', state='readonly').grid(row=row, column=col, columnspan=colspan, sticky=E + W) col += colspan colspan = 1 self.ivarplaywv = IntVar() self.ivarplaywv.set(0) Checkbutton(root, variable=self.ivarplaywv, text='Play', command=self.butcmdplaywave).grid(row=row, column=col, sticky=E + W) col += colspan self.ivarpausewv = IntVar() self.ivarpausewv.set(0) Checkbutton(root, variable=self.ivarpausewv, text='Pause', command=self.butcmdpausewave).grid(row=row, column=col, sticky=E + W) col += colspan self.ivarloopwv = IntVar() self.ivarloopwv.set(0) Checkbutton(root, variable=self.ivarloopwv, text='Loop').grid(row=row, column=col, sticky=E + W) self.scope.update() self.scope.redraw() def sclbndvolt(self, event): """ Voltage scale bind command to set the voltage on the DSP. :param event: the event describing what changed """ if self.isconnected(): self.dps.set(['vset'], [self.getvscale()]) def sclbndcrnt(self, event): """ Current scale bind command to set the current on the DSP. :param event: the event describing what changed """ if self.isconnected(): self.dps.set(['cset'], [self.getcscale()]) def sclbndmemory(self, event): """ Memory-set bind command to set the memory on the DSP. :param event: the event describing what changed """ if self.isconnected(): m = self.ivarsetmem.get() self.dps.set(['mset'], [m]) self.updatefields(True) def sclbndbrghtnss(self, event): """ Brightness bind command to set the brightness on the DSP. :param event: the event describing what changed """ if self.isconnected(): b = self.ivarbrghtnes.get() self.dps.set(['brght'], [b]) def mnucmdnewwve(self): """ New wave menu command to initialize a new wave. """ self.dpsfwave = Dpsfile() self.svarwave.set('unnamed') def mnucmdloadwve(self): """ Load wave menu command to load a wave file. """ fname = tkFileDialog.askopenfilename(initialdir=".", title="Select wave file to load", filetypes=(("dps files", "*.dps"), ("all files", "*.*"))) if fname: self.svarwave.set(os.path.basename(fname)) self.dpsfwave = Dpsfile() self.dpsfwave.load(fname) def mnucmdedtwve(self): """ Edit wave menu command to open the edit wave window. """ if self.dpsfwave is not None: Wveinterface(self.root, self.dpsfwave.getpoints()) else: tkMessageBox.showinfo('No wave loaded', 'Load or create a new wave file to modify') def mnucmdsavewve(self): """ Save wave menu command to save the current wave in memory. """ if self.dpsfwave is not None: fname = tkFileDialog.asksaveasfilename( initialdir=".", title="Select wave file to save", filetypes=(("dps files", "*.dps"), ("all files", "*.*"))) if fname: self.dpsfwave.save(fname) self.svarwave.set(os.path.basename(fname)) else: tkMessageBox.showinfo('No wave in memory', 'Load or create a wave file to modify') def mnucmdloadsmppts(self): """ Load sampled points menu command to load in the graphical view sampled before. """ fname = tkFileDialog.askopenfilename(initialdir=".", title="Select data file to load", filetypes=(("dps files", "*.dps"), ("all files", "*.*"))) if fname: self.scope.load(fname) def mnucmdsavesmppts(self): """ Save sampled points menu command to save the last points sampled showed in the graphical view. """ fname = tkFileDialog.asksaveasfilename( initialdir=".", title="Select data file to save", filetypes=(("dps files", "*.dps"), ("all files", "*.*"))) if fname: self.scope.save(fname) def mnucmdedtmem(self): """ Memory menu command to edit the values of preset memories on DSP. """ if self.isconnected(): Meminterface(self.root, self.dps, self.updatefields) def mnucmdabout(self): """ About menu command to show the window with program information. """ Txtinterface( self.root, 'About', """DPS interface is designed by Simone Pernice That project was born as a textual driver to interface any DPS device. After the driver I made also a graphical interface to manage DPS devices. This project was born because I was not able to find any Linux application to manage DPS devices via USB. For question email to me: [email protected] Version {} relesed on {} First release on 3rd February 2019 Turin Italy DPS interface is under licence {} If you like this program please make a donation with PayPal to [email protected]""" .format(__version__, __date__, __license__)) def mnucmdhelp(self): """ Help menu command to show basic help on usage. """ Txtinterface( self.root, 'Help', """This is an interface to remote controll a power supplier of DPS series. The white fields can be edited, the gray are read only. To connect to DPS power supplier first link it to the PC through an USB cable. The data required to connect is on the first row of the graphical interface. Write the serial address on the first field (COMxx for Windows or /dev/ttyUSBx for Linux). Address and baudrate do not require update because they are the default for DPS power supplier. Turn on DPS with up key pressed to change those values. Press 'Connect' check button and if the device is present it is linked. Press again the same check button to disconnect the DPS. Once the link to DPS is in place all the data on the interface are updated and on the DPS the keylock is set. The second block of graphical interface contains all data about DPS. The brightness set which can be changed through the scale regulation. The model number. The memory from which recall the preset parameters. The input voltage, the output mode cv (constant voltage) or cc (constant current). The protection mode: none (no protection triggered), ovp (over voltage protection), ocp (over current protection), opp (over power protection). The maximum voltage, current and power to provide before triggering the self protection. The next row contains output voltage, current and power in textual form. A time diagram of the DPS output voltage, current and power is avaiable. It is possible to play with the mouse on that screen: - wheel press to fit in the screen all the enabled drawings - wheel to zoom in time - shift+wheel to zoom on Y for the highlighted curves - ctrl+wheel to change the enabled curves - left button drag to move the highlighted curve The same mouse functions are available in the fields below the diagram: - voltage per division, current per division and watt per division - zero position for voltage, current and power - check button to view voltage, current and power - time: second per divisions and zero position for time The sample time is used for the acquisition. DPS is quite slot, the minimum read time is around 1 second. The suggested rate is to have a sample for displayed pixel. The next buttons are: - Run acquisition: starts a thread that read the DPS status, update the interface fields as well as the time diagram. The acquisition points can be saved and loaded to be showed lated with menu commands on DPS scope load/save. They can be also edited through the wave edit window and played. - Key lock: set or reset the DPS key lock. It should be on in order to have faster communication. If key lock is on less fields of DPS are read since user can change them only through the PC interface. - Output enable to enable the DPS output Eventually there are the voltage and current scale. Thery are split in two: - the first is for coarse (1 unit/step) adjustment the unit of voltage/current - the second is for fine (0.01 unit/step) adjustament of voltage/current On the last block of interface there is a waveform field showing the wave loaded. Wave is a set of required output voltage and current at give timings. It is possible play and pause it through the respective commands of the interface. If loop is set when the wave play is completed it restarts. The acquisition may slow the wave player, use low acquisition sample time to avoid delays.""") def butcmdconnect(self): """ Connect check button command to connect to the DSP. It reads: serial port address, DPS address and serial speed from other interface fields. If it is capable to link to the DPS: - the maximum voltage and current are read and scale maximums set accordingly - the DPS current data are read and set accordingly in the interface - the localDPS interface is locked so that the user cannot change them but has to go through the graphical interface if the DPS is locked the polling is faster because less data needs to be read from DPS - the input fields are disabled """ if self.ivarconctd.get(): try: flds = self.svardpsaddbrt.get().split(',') if len(flds) > 0: ch = int(flds[0]) else: ch = 1 if len(flds) > 1: br = int(flds[1]) else: br = 9600 self.dps = DPSdriver(self.svardpsport.get(), ch, br) except Exception as e: tkMessageBox.showerror('Error', 'Cannot connect: ' + str(e)) self.ivarconctd.set(0) self.dps = None return m = self.dps.get(['model']) m = m[0] self.ivarmodel.set(m) to = m / 100 self.voltscale.config(to=to) self.maxoutv = to to = m % 100 self.curntscale.config(to=to) self.maxoutv = to self.scope.resetpoints() self.ivarkeylock.set(1) self.butcmdkeylock() self.updatefields(True) self.entryserport.config(state='readonly') self.entrydpsadd.config(state='readonly') else: # Stop polling self.ivaracquire.set(0) if self.poller: self.poller.wake() time.sleep(1.) # Wait to be sure the thread exits # Stop waveform generation self.ivarplaywv.set(0) if self.waver: self.waver.wake() time.sleep(1.) # Wait to be sure the thread exits self.dps = None self.entryserport.config(state=NORMAL) self.entrydpsadd.config(state=NORMAL) def butcmdacquire(self): """ Acquire check button command to manage the acquisition thread to read the DSP data. If the button is not selected the thread is lunched. If the button is selected the thread is stopped. """ if self.ivaracquire.get(): if not self.isconnected(): self.ivaracquire.set(0) return self.scope.resetpoints() self.strtme = time() self.poller = Poller(self.ivaracquire, self.dvarsecsmp, self.updatefields) else: self.poller.wake() def butcmdkeylock(self): """ Key lock button command to enable or disable the key lock on DPS remote interface. """ if self.isconnected(): self.dps.set(['lock'], [self.ivarkeylock.get()]) else: self.ivarkeylock.set(0) def butcmdoutenable(self): """ DPS output button command to enable or disable the DPS output power. """ if self.isconnected(): self.dps.set(['onoff'], [self.ivaroutenab.get()]) else: self.ivaroutenab.set(0) def butcmdplaywave(self): """ Wave generator check button command to manage the wave generation thread to make a waveform on the DSP. If the button is not selected the thread is lunched. If the button is selected the thread is stopped. """ if self.ivarplaywv.get(): if not self.isconnected(): self.ivarplaywv.set(0) return if not self.dpsfwave: tkMessageBox.showinfo('No wave in memory', 'Load or create a wave file to modify') self.ivarplaywv.set(0) return if not self.ivaroutenab.get(): self.ivaroutenab.set(1) self.butcmdoutenable() self.waver = Waver(self.setvcdps, self.ivarplaywv, self.ivarpausewv, self.ivarloopwv, self.dpsfwave.getpoints()) else: self.waver.wake() def butcmdpausewave(self): """ Wave generator pause check button command to temporary pause the wave generations. """ self.waver.wake() def wnwcmdclose(self): """ DPS main window close. Before exiting the supplier is disconnected the external supplier. """ if self.ivarconctd.get(): self.ivarconctd.set(0) self.butcmdconnect() self.root.destroy() def entbndvmax(self, event): """ Maximum voltage entry bind to set the protection maximum ouput voltage of the DSP. :param event: the event describing what changed """ if self.isconnected(): if self.dvarvmaxm0.get() > self.maxoutv * PROTEXCEED: self.dvarvmaxm0.set(self.maxoutv * PROTEXCEED) elif self.dvarvmaxm0.get() < 0.: self.dvarvmaxm0.set(0.) self.dps.set(['m0ovp'], [self.dvarvmaxm0.get()]) def entbndcmax(self, event): """ Maximum current entry bind to set the protection maximum output curret of the DSP. :param event: the event describing what changed """ if self.isconnected(): if self.dvarcmaxm0.get() > self.maxoutc * PROTEXCEED: self.dvarcmaxm0.set(self.maxoutc * PROTEXCEED) elif self.dvarcmaxm0.get() < 0.: self.dvarcmaxm0.set(0.) self.dps.set(['m0ocp'], [self.dvarcmaxm0.get()]) def entbndpmax(self, event): """ Maximum power entry bind to set the protection maximum output power of the DSP. :param event: the event describing what changed """ if self.isconnected(): if self.dvarpmaxm0.get( ) > self.maxoutv * self.maxoutc * PROTEXCEED * PROTEXCEED: self.dvarpmaxm0.set(self.maxoutv * self.maxoutc * PROTEXCEED * PROTEXCEED) elif self.dvarpmaxm0.get() < 0.: self.dvarcmaxm0.set(0.) self.dps.set(['m0opp'], [self.dvarpmaxm0.get()]) def setvcdps(self, v, c): """ Set the DPS output voltage and current moving their scales accordingly. :param v: the required voltage, if negative it is not changed :param c: the required current, if negative it is not changed """ if v >= 0: if c >= 0: self.setvscale(v) self.setcscale(c) self.dps.set(['vset', 'cset'], [v, c]) else: self.setvscale(v) self.dps.set(['vset'], [v]) elif c >= 0: self.setcscale(c) self.dps.set(['cset'], [c]) def isconnected(self): """ Check if the DPS is connected, if not display a message. :returns: True if connected, False if not """ if self.dps is None: tkMessageBox.showinfo('Not connected', 'Enstablish a connection before') return False return True def setvscale(self, v): """ Set the voltage scale, nothing is changed on the DPS. :param v: the voltage to set """ if v > self.maxoutv: v = self.maxoutv elif v < 0: v = 0 self.dvarvscale.set(int(v)) self.dvarvscalef.set(round(v - int(v), 2)) def getvscale(self): """ Get the voltage scale set value. :returns: the voltage set """ return self.dvarvscale.get() + self.dvarvscalef.get() def setcscale(self, c): """ Set the current scale, nothing is changed on the DPS. :param c: the current to set """ if c > self.maxoutc: c = self.maxoutc elif c < 0: c = 0 self.dvarcscale.set(int(c)) self.dvarcscalef.set(round(c - int(c), 2)) def getcscale(self): """ Get the current scale set value. :returns: the current set """ return self.dvarcscale.get() + self.dvarcscalef.get() def updatefields(self, forcereadall=False): """ Reads data stored in DPS and updates the interface fields accordingly. In order to be as fast as possible, if keylock is enabled, reads only the fields that can change without uses access. If keylock is disabled all the fields are read because user may have changed something from the interface. :param forcereadall: if True read and update all the DPS fields regardless of the keylock status :returns: the point read. A point is made by (time, voltage, current, power) """ if not forcereadall and self.ivarkeylock.get( ): # If user keep locked fewer data are read, otherwise all data = self.dps.get( ['vout', 'cout', 'pout', 'vinp', 'lock', 'prot', 'cvcc']) self.dvarvout.set(data[0]) self.dvarcout.set(data[1]) self.dvarpout.set(data[2]) self.dvarvinp.set(data[3]) self.ivarkeylock.set(data[4]) self.setprotection(data[5]) self.setworkmode(data[6]) vcp = data[0:3] else: # All data is read data = self.dps.get([ 'vset', 'cset', 'vout', 'cout', 'pout', 'vinp', 'lock', 'prot', 'cvcc', 'onoff', 'brght', 'mset', 'm0ovp', 'm0ocp', 'm0opp' ]) self.setvscale(data[0]) self.setcscale(data[1]) self.dvarvout.set(data[2]) self.dvarcout.set(data[3]) self.dvarpout.set(data[4]) self.dvarvinp.set(data[5]) self.ivarkeylock.set(data[6]) self.setprotection(data[7]) self.setworkmode(data[8]) self.ivaroutenab.set(data[9]) self.ivarbrghtnes.set(data[10]) self.ivarsetmem.set(data[11]) self.dvarvmaxm0.set(data[12]) self.dvarcmaxm0.set(data[13]) self.dvarpmaxm0.set(data[14]) vcp = data[2:5] vcp.insert(TPOS, time() - self.strtme) self.scope.addpoint(vcp) return vcp def setprotection(self, p): """ Set the protection field with an user readable string explaining the DPS protection status. :param p: the protection statu returned by the DPS """ self.svarprot.set({0: 'none', 1: 'ovp', 2: 'ocp', 3: 'opp'}[p]) def setworkmode(self, wm): """ Set the workmode field with an user readable string explaining the DPS work mode. :param wm: the working mode returned by the DPS """ self.svarwrmde.set({0: 'cv', 1: 'cc'}[wm])
class Clustering: def selectAll(self, event): event.widget.delete(0, END) # Class initialize and function definition def __init__(self, master): # In-class variables self.window = master self.filename = "" self.hasPre = False self.rawData = "" self.nClust = -1 self.nRuns = -1 self.master = master master.title("K Means Clustering") # Buttons, Entries & Labels setup self.label = Label(master, text="") self.label.pack() self.entry = Entry(master, state='disabled') self.entry.pack() self.browseBtn = Button(master, text="Browse", command=self.browseFile) vcmd = master.register(self.validate) self.clustersNum = Entry(master, validate="key", validatecommand=(vcmd, '%P')) self.clusterNumLabel = Label(master, text="Num of clusters k") self.clustersNum.bind('<Button-1>', self.selectAll) self.clustersNum.bind('<FocusIn>', self.selectAll) self.clustersNum.pack() self.clustersRun = Entry(master, validate="key", validatecommand=(vcmd, '%P')) self.clustersRunLabel = Label(master, text="Num of runs") self.clustersRun.bind('<Button-1>', self.selectAll) self.clustersRun.bind('<FocusIn>', self.selectAll) self.clustersRun.pack() self.preProcessBtn = Button(master, text="Pre-Process", command=lambda: self.preprocessing()) self.clusterBtn = Button(master, text="Cluster", command=lambda: self.clustering()) # LAYOUT self.label.grid(row=0, column=0, sticky=W) self.label.grid(row=1, column=0, sticky=W) self.label.grid(row=2, column=0, sticky=W) self.label.grid(row=3, column=0, sticky=W) self.label.grid(row=14, column=0, sticky=W) self.label.grid(row=15, column=0, sticky=W) self.entry.grid(row=4, column=11, columnspan=5, sticky=W + E) self.browseBtn.grid(row=4, column=2, columnspan=3, sticky=W + E) self.clustersNum.grid(row=7, column=9, columnspan=3, sticky=W + E) self.clusterNumLabel.grid(row=7, column=2, columnspan=3, sticky=W) self.clustersRun.grid(row=10, column=9, columnspan=3, sticky=W + E) self.clustersRunLabel.grid(row=10, column=2, columnspan=3, sticky=W) self.preProcessBtn.grid(row=13, column=2, columnspan=3) self.clusterBtn.grid(row=13, column=11, columnspan=3) # Browse file function - saves filename to self.filename def browseFile(self): Tk().withdraw() self.filename = askopenfilename() self.entry.config(state='normal') self.entry.delete(0, END) self.entry.insert(0, self.filename) self.entry.config(state='disabled') # Validate function - checks that the entries will get only numbers def validate(self, new_text): if not new_text: self.entered_number = 0 return True try: self.entered_number = int(new_text) return True except ValueError: return False # Preprocessing the data using StandardScaler def preprocessing(self): if not self.filename: tkMessageBox.showerror("K Means Clustering", "Please choose file before..") else: donePre, self.complete_ready_data = cleanData.clean(self.filename) if not donePre: tkMessageBox.showerror("K Means Clustering", "Could not preprocess selected file") else: self.hasPre = True tkMessageBox.showinfo("K Means Clustering", "Preprocessing completed successfully!") # Clustering the data using KMeans clustering def clustering(self): self.nClust = self.clustersNum.get() self.nRuns = self.clustersRun.get() if not self.hasPre: tkMessageBox.showerror("K Means Clustering", "Please preprocess data before..") elif self.nClust == "" or self.nClust <= 0: tkMessageBox.showerror("K Means Clustering", "Please fill positive number of clusters") elif self.nRuns == "" or self.nRuns <= 0: tkMessageBox.showerror("K Means Clustering", "Please fill positive number of runs") else: #run the KMeans model doneCluster, self.complete_ready_data = clusterData.cluster( self.complete_ready_data, self.nClust, self.nRuns) if not doneCluster: tkMessageBox.showerror("K Means Clustering", "Clustering problems") else: # Generate scatter plot & show on GUI fig = Figure(figsize=(6, 6), dpi=70) a = fig.add_subplot(111) a.scatter(x=self.complete_ready_data["Generosity"], y=self.complete_ready_data["Social support"], c=self.complete_ready_data['Clustering']) a.set_title( "Scatter plot for Generosity and Social support by cluster" ) a.set_xlabel('Generosity', fontsize=12) a.set_ylabel('Social support', fontsize=12) canvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg( fig, master=self.window) canvas.get_tk_widget().grid(row=17, column=18) canvas.draw() # Generate second plot - Horopleth map & save to disk & show on GUI self.complete_ready_data.reset_index(inplace=True) # scl = [[0.0, 'rgb(242,240,247)'], [0.2, 'rgb(218,218,235)'], [0.4, 'rgb(188,189,220)'], \ # [0.6, 'rgb(158,154,200)'], [0.8, 'rgb(117,107,177)'], [1.0, 'rgb(84,39,143)']] scl = [[0.0, 'rgb(242,240,247)'], [0.4, 'rgb(188,189,220)'], [0.8, 'rgb(117,107,177)']] data = [ dict( type='choropleth', colorscale=scl, autocolorscale=False, locations=self.complete_ready_data['country'], z=self.complete_ready_data['Clustering'].astype(float), locationmode='country names', text=self.complete_ready_data['country'], marker=dict( line=dict(color='rgb(255,255,255)', width=2)), colorbar=dict(title="Cluster", dtick=1)) ] layout = dict( title='Cluster by country on world map', geo=dict(scope='world', projection=dict(type='Mercator'), showlakes=True, lakecolor='rgb(255, 255, 255)'), ) fig2 = dict(data=data, layout=layout) py.plot(fig2, filename='d3-cloropleth-map', auto_open=False) py.image.save_as(fig2, filename="world.png") im = Image.open('world.png') im = im.resize((520, 420), Image.ANTIALIAS) im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE) im.save('world.gif') photo = PhotoImage(file='world.gif') photo.zoom(2) self.worldImg = Label(master=self.window, image=photo) self.worldImg.image = photo self.worldImg.grid(row=17, column=19) if tkMessageBox.askokcancel( "K Means Clustering", "Clustering completed successfully!"): root.destroy() sys.exit()
class You2XBMC(): """ XBMC Object""" def __init__(self): #Initialize GUI self.address=None self.video = None self.ipAddress = None self.home = expanduser("~") self.config_widgets() #Configure Window and Widgets # Test if file exists, and if it does read the ip address if not isfile(self.home+"/"+"xbmcIP.txt"): print "No File :(" self.ipAddress = False elif isfile(self.home+"/"+"xbmcIP.txt"): print "File Exists :)" self.ipAddress = open(self.home+"/"+"xbmcIP.txt", "r").read().splitlines()[0] print self.ipAddress if self.ipAddress != False: self.ipEntry.insert(0, self.ipAddress) #Pack and Mainloop self.grid_everything() self.mainloop() def set_video(self): # Create a thread that sets the video x = Thread(target=self.set_video_callback) x.start() def set_video_callback(self): # This function creates a new file if a file doesn't exist with the ip address of the xbmc # it also sends the video to the JSON server if self.ipAddress == False: self.ipAddress = self.ipEntry.get() xbmcIP = open(self.home+"/"+"xbmcIP.txt", "w") xbmcIP.write(str(self.ipAddress)) xbmcIP.close() # Send video to XBMC self.ipAddress = ("http://"+self.ipEntry.get()+"/jsonrpc") xbmc = XBMC(self.ipAddress) address = self.addressEntry.get() video = pafy.new(address) video = video.getbest() print xbmc.Player.Open(item={"file": video.url}) def get_clipboard(self): # Get a video address fom clipboard string = self.window.clipboard_get() self.addressEntry.delete(0,END) self.addressEntry.insert(0, string) self.set_video() def config_widgets(self): # Create window and widgets self.window = Tk() self.window.title("Send youtube video to XBMC") self.window.resizable(0,0) self.addressEntry = Entry() self.addressEntry.config(width=50) self.addressEntry.config(justify=CENTER) self.addressLabel = Label(text="Insert youtube video address: ") self.ipEntry = Entry() self.ipEntry.config(justify=CENTER) self.ipLabel = Label(text="Ip address of XBMC machine: ") self.sendButton = Button(self.window, text="Play on XBMC", command=self.set_video) self.sendButton.config(width=30) self.clipboardButton = Button(text="Click to get from clipboard", command=self.get_clipboard) def grid_everything(self): # Grid everything up self.addressLabel.grid(row=0, column=0,pady=5, padx=20) self.addressEntry.grid(row=0, column=1, pady=10) self.sendButton.grid(row=3, column=1, pady=5) self.clipboardButton.grid(row=0, column=2, padx=3) self.ipEntry.grid(row=2, column=1, pady=10) self.ipLabel.grid(row=2, column=0,pady=5, padx=20) def mainloop(self): mainloop()
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("IAF CALC 0.01") self.pack(fill=BOTH, expand=1) self.configure(background="white") frameTOP = Frame(self) frameTOP.config(bg="white") frameTOP.pack(side=TOP) frameFILES = Frame(frameTOP) frameFILES.pack(side=LEFT, padx=10) # --- BUTTON FOR FILE 1 --- # frameF1 = LabelFrame(frameFILES, text="Eyes open file:", relief=FLAT, borderwidth=1, background="white") frameF1.pack(fill=X, expand=1) self.nameF1 = Entry(frameF1, width=50) self.nameF1.config(bg="lightgray") self.nameF1.pack(side=LEFT) self.nameF1.delete(0, END) self.nameF1.insert(0, "") self.buttonLoadFile1 = Button(frameF1, text="...", command=self.askOpenFile1) self.buttonLoadFile1.pack(side=LEFT, padx=5, pady=5) # ----------------------- # # --- BUTTON FOR FILE 2 --- # frameF2 = LabelFrame(frameFILES, text="Eyes closed file:", relief=FLAT, borderwidth=1, background="white") frameF2.pack(fill=X, expand=1) self.nameF2 = Entry(frameF2, width=50) self.nameF2.config(bg="lightgray") self.nameF2.pack(side=LEFT) self.nameF2.delete(0, END) self.nameF2.insert(0, "") self.buttonLoadFile2 = Button(frameF2, text="...", command=self.askOpenFile2) self.buttonLoadFile2.pack(side=LEFT, padx=5, pady=5) # ----------------------- # # --- BUTTON FOR FILE OUTPUT --- # frameO = LabelFrame(frameFILES, text="Output directory:", relief=FLAT, borderwidth=1, background="white") frameO.pack(fill=X, expand=1) self.nameO = Entry(frameO, width=50) self.nameO.config(bg="lightgray") self.nameO.pack(side=LEFT) self.nameO.delete(0, END) self.nameO.insert(0, "") self.buttonSelectOutput = Button(frameO, text="...", command=self.askOutputDirectory) self.buttonSelectOutput.pack(side=LEFT, padx=5, pady=5) # -------------------------------# # self.pack() # self.pack(fill=Y, expand=1) # ---------- PSD PARAMETER SELECTION ---------- # framePARAM = Frame(frameTOP) framePARAM.config(bg="white") framePARAM.pack(side=LEFT, fill=X) frame = LabelFrame(framePARAM, text="PSD Parameters", relief=RIDGE, borderwidth=1, background="white") frame.pack(fill=BOTH, expand=1, side=TOP) wFs = Label(frame, text="Fs:", bg="white") wFs.pack(side=LEFT) self.inputFs = Entry(frame, width=5) self.inputFs.pack(side=LEFT, padx=5) self.inputFs.delete(0, END) self.inputFs.insert(0, "500") wWS = Label(frame, text="Window size:", bg="white") wWS.pack(side=LEFT) self.inputWinSize = Entry(frame, width=5) self.inputWinSize.pack(side=LEFT, padx=5) self.inputWinSize.delete(0, END) self.inputWinSize.insert(0, "1024") wOL = Label(frame, text="Overlap:", bg="white") wOL.pack(side=LEFT) self.inputOverlap = Entry(frame, width=5) self.inputOverlap.pack(side=LEFT, padx=5) self.inputOverlap.delete(0, END) self.inputOverlap.insert(0, "512") wWT = Label(frame, text="Window function:", bg="white") wWT.pack(side=LEFT) variable = StringVar(frame) variable.set("Hamming") # default value self.inputWinType = OptionMenu(frame, variable, "Hamming", "Bartlett", "Blackman", "Hanning", "None") self.inputWinType.config(bg="white", width=10) self.inputWinType.pack(side=LEFT) buttonRun = Button(frame, text="GO!", command=self.goTime) buttonRun.pack(side=RIGHT) # Channel selector frameCh = LabelFrame(framePARAM, text="Channels", relief=RIDGE, borderwidth=1, background="white") frameCh.pack(fill=BOTH, expand=1, side=TOP) self.EOch1 = IntVar() self.inputEOch1 = Checkbutton(frameCh, text="1", variable=self.EOch1, bg="white") self.inputEOch1.pack(side=LEFT) self.EOch2 = IntVar() self.inputEOch2 = Checkbutton(frameCh, text="2", variable=self.EOch2, bg="white") self.inputEOch2.pack(side=LEFT) self.EOch3 = IntVar() self.inputEOch3 = Checkbutton(frameCh, text="3", variable=self.EOch3, bg="white") self.inputEOch3.pack(side=LEFT) self.EOch4 = IntVar() self.inputEOch4 = Checkbutton(frameCh, text="4", variable=self.EOch4, bg="white") self.inputEOch4.pack(side=LEFT) self.EOch5 = IntVar() self.inputEOch5 = Checkbutton(frameCh, text="5", variable=self.EOch5, bg="white") self.inputEOch5.pack(side=LEFT) self.EOch6 = IntVar() self.inputEOch6 = Checkbutton(frameCh, text="6", variable=self.EOch6, bg="white") self.inputEOch6.pack(side=LEFT) self.EOch7 = IntVar() self.inputEOch7 = Checkbutton(frameCh, text="7", variable=self.EOch7, bg="white") self.inputEOch7.pack(side=LEFT) self.EOch8 = IntVar() self.inputEOch8 = Checkbutton(frameCh, text="8", variable=self.EOch8, bg="white") self.inputEOch8.pack(side=LEFT) # IAF Calculation parameters frameIAF = LabelFrame(framePARAM, text="IAF Search Limits", relief=RIDGE, borderwidth=1, background="white") frameIAF.pack(fill=BOTH, expand=1, side=TOP) labelLowBound = Label(frameIAF, text="Lower limit (Hz):", bg="white") labelLowBound.pack(side=LEFT) self.inputLowBound = Entry(frameIAF, width=5) self.inputLowBound.pack(side=LEFT, padx=5) self.inputLowBound.delete(0, END) self.inputLowBound.insert(0, "7") labelUpBound = Label(frameIAF, text="Upper limit (Hz):", bg="white") labelUpBound.pack(side=LEFT) self.inputUpBound = Entry(frameIAF, width=5) self.inputUpBound.pack(side=LEFT, padx=5) self.inputUpBound.delete(0, END) self.inputUpBound.insert(0, "14") self.GaussVar = IntVar() self.inputGauss = Checkbutton(frameIAF, text="Gauss", variable=self.GaussVar, bg="white") self.inputGauss.pack(side=LEFT) buttonRun = Button(frameIAF, text="IAF!", command=self.calculateIAF) buttonRun.pack(side=RIGHT) self.pack() # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # END OF TOP FRAME # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # my variables self.chSelect = 0 self.chOther = 0 self.P1 = ndarray(1) self.f1 = ndarray(1) self.P2 = ndarray(1) self.f2 = ndarray(1) self.filename1 = "..." self.filename2 = "..." self.IAF = 10 self.doGauss = True # FIGURE STUFF !!! self.Pmax = 0 self.Pmin = 0 self.Dmax = 0 self.Dmin = 0 frameBOTTOM = Frame(self) frameBOTTOM.config(bg="white") frameBOTTOM.pack(side=BOTTOM, pady=10) frameFig = LabelFrame(frameBOTTOM, text="Spectrum", relief=RIDGE, borderwidth=1, background="white") frameFig.pack(fill=X, expand=1, side=LEFT, padx=10) self.fig1 = matplotlib.figure.Figure(figsize=(7, 3), dpi=100) # ,frameon=False) self.fig1.set_facecolor("white") self.fig = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(self.fig1, master=frameFig) self.a1 = self.fig1.add_subplot(121) self.a2 = self.fig1.add_subplot(122) self.fig.show() self.fig.get_tk_widget().pack(side=BOTTOM) frameConfig = LabelFrame( frameBOTTOM, text="Filter configuration", relief=RAISED, borderwidth=1, background="white" ) frameConfig.pack(fill=BOTH, expand=1, side=RIGHT, padx=10) frameIAF = LabelFrame(frameConfig, text="Individual Alpha Frequency (IAF)") frameIAF.config(bg="white") frameIAF.pack(expand=1, side=TOP, padx=10) self.inputIAF = Entry(frameIAF, width=5) self.inputIAF.pack(side=LEFT, padx=5) self.inputIAF.delete(0, END) self.inputIAF.insert(0, "0") self.buttonWriteDefault = Button(frameIAF, text="Update Filters", command=self.updateFilters) self.buttonWriteDefault.pack(side=LEFT, padx=5, pady=5) frameFilters = LabelFrame(frameConfig, text="Filters", relief=RAISED, borderwidth=1, background="white") frameFilters.pack(fill=X, expand=1, side=TOP) # THETA FRAME frameTheta = LabelFrame(frameFilters, text="Theta", relief=RAISED, borderwidth=1, background="white") frameTheta.pack(expand=1, side=TOP, pady=5, padx=5) self.inputThetaLow = Entry(frameTheta, width=8) self.inputThetaLow.pack(side=LEFT, padx=5, pady=5) self.inputThetaLow.delete(0, END) self.inputThetaLow.insert(0, "0") self.inputThetaHigh = Entry(frameTheta, width=8) self.inputThetaHigh.pack(side=LEFT, padx=5, pady=5) self.inputThetaHigh.delete(0, END) self.inputThetaHigh.insert(0, "0") # BETA FRAME frameBeta = LabelFrame(frameFilters, text="Beta", relief=RAISED, borderwidth=1, background="white") frameBeta.pack(expand=1, side=TOP, pady=5, padx=5) self.inputBetaLow = Entry(frameBeta, width=8) self.inputBetaLow.pack(side=LEFT, padx=5, pady=5) self.inputBetaLow.delete(0, END) self.inputBetaLow.insert(0, "0") self.inputBetaHigh = Entry(frameBeta, width=8) self.inputBetaHigh.pack(side=LEFT, padx=5, pady=5) self.inputBetaHigh.delete(0, END) self.inputBetaHigh.insert(0, "0") # SMR FRAME frameSMR = LabelFrame(frameFilters, text="SMR", relief=RAISED, borderwidth=1, background="white") frameSMR.pack(expand=1, side=TOP, pady=5, padx=5) self.inputSMRLow = Entry(frameSMR, width=8) self.inputSMRLow.pack(side=LEFT, padx=5, pady=5) self.inputSMRLow.delete(0, END) self.inputSMRLow.insert(0, "0") self.inputSMRHigh = Entry(frameSMR, width=8) self.inputSMRHigh.pack(side=LEFT, padx=5, pady=5) self.inputSMRHigh.delete(0, END) self.inputSMRHigh.insert(0, "0") frameButtons = LabelFrame(frameConfig, text="Commands", relief=RAISED, borderwidth=1, background="white") frameButtons.pack(expand=1, side=BOTTOM) self.buttonWriteConfig = Button(frameButtons, text="Write Filters", command=self.writeFilters) self.buttonWriteConfig.pack(side=LEFT, padx=5, pady=5) self.buttonWriteDefault = Button(frameButtons, text="Reset to Defaults", command=self.resetIAFtoDefault) self.buttonWriteDefault.pack(side=LEFT, padx=5, pady=5) # self.buttonVisualize = Button(frameButtons, text="VIS",command=self.resetIAFtoDefault) # self.buttonVisualize.pack(side=LEFT,padx=5,pady=5) self.buttonPrintFig = Button(frameButtons, text="Print Figure", command=self.printFigureToFile) self.buttonPrintFig.pack(side=LEFT, padx=5, pady=5) def getChannelList(self): # Initialize self.chSelect = asarray([]) self.chOther = asarray([]) if self.EOch1.get(): self.chSelect = append(self.chSelect, 0) else: self.chOther = append(self.chOther, 0) if self.EOch2.get(): self.chSelect = append(self.chSelect, 1) else: self.chOther = append(self.chOther, 1) if self.EOch3.get(): self.chSelect = append(self.chSelect, 2) else: self.chOther = append(self.chOther, 2) if self.EOch4.get(): self.chSelect = append(self.chSelect, 3) else: self.chOther = append(self.chOther, 3) if self.EOch5.get(): self.chSelect = append(self.chSelect, 4) else: self.chOther = append(self.chOther, 4) if self.EOch6.get(): self.chSelect = append(self.chSelect, 5) else: self.chOther = append(self.chOther, 5) if self.EOch7.get(): self.chSelect = append(self.chSelect, 6) else: self.chOther = append(self.chOther, 6) if self.EOch8.get(): self.chSelect = append(self.chSelect, 7) else: self.chOther = append(self.chOther, 7) def updateFilters(self): # SET THETA self.inputThetaLow.delete(0, END) self.inputThetaLow.insert(0, "%.2f" % (float(self.inputIAF.get()) * 0.4)) self.inputThetaHigh.delete(0, END) self.inputThetaHigh.insert(0, "%.2f" % (float(self.inputIAF.get()) * 0.6)) # SET BETA self.inputBetaLow.delete(0, END) self.inputBetaLow.insert(0, "%.2f" % (float(self.inputIAF.get()) * 1.2)) self.inputBetaHigh.delete(0, END) self.inputBetaHigh.insert(0, 25) # SET SMR self.inputSMRLow.delete(0, END) self.inputSMRLow.insert(0, "%.2f" % (float(self.inputIAF.get()) * 1.2)) self.inputSMRHigh.delete(0, END) self.inputSMRHigh.insert(0, "%.2f" % (float(self.inputIAF.get()) * 1.5)) def resetIAFtoDefault(self): self.inputIAF.delete(0, END) self.inputIAF.insert(0, "10") self.updateFilters() def calculateIAF(self): self.getChannelList() print "LOLOL calculating IAF" m1 = 20 * log10(mean(self.P1[self.chSelect.astype(int), :], axis=0)) m2 = 20 * log10(mean(self.P2[self.chSelect.astype(int), :], axis=0)) d = m2 - m1 if self.GaussVar.get(): # print d.shape # print gauss_signal.shape d_gauss = d[bitwise_and(self.f1 > int(self.inputLowBound.get()), self.f1 < int(self.inputUpBound.get()))] gauss_signal = signal.gaussian(d_gauss.shape[0], 1) d_gauss = d_gauss * gauss_signal d[bitwise_and(self.f1 > int(self.inputLowBound.get()), self.f1 < int(self.inputUpBound.get()))] = d_gauss self.a2 = plotIAF(self.f1, d, "purple", self.a2, "IAF") # Get dat IAF val d_search = d[bitwise_and(self.f1 > int(self.inputLowBound.get()), self.f1 < int(self.inputUpBound.get()))] f_search = self.f1[bitwise_and(self.f1 > int(self.inputLowBound.get()), self.f1 < int(self.inputUpBound.get()))] f_idx = argmax(d_search) print f_search[f_idx] self.inputIAF.delete(0, END) self.inputIAF.insert(0, "%.2f" % (f_search[f_idx])) # Autoscale self.Dmin = amin(d_search) - 2 self.Dmax = amax(d_search) + 2 self.a2.set_ylim(self.Dmin, self.Dmax) # little modifier to differentiate the peak # IAF position self.a2.vlines(f_search[f_idx], self.Dmin, self.Dmax, color="Cyan") # Search limits self.a2.vlines(int(self.inputLowBound.get()), self.Dmin, self.Dmax, linestyles=":", linewidth=0.25) self.a2.vlines(int(self.inputUpBound.get()), self.Dmin, self.Dmax, linestyles=":", linewidth=0.25) self.fig.show() # Set filter configs def goTime(self): print "ITS GO TIME!" print self.filename1 print self.filename2 self.getChannelList() print self.chSelect print self.chOther self.f1, self.P1 = computeSpectrum( self.filename1, int(self.inputFs.get()), int(self.inputWinSize.get()), int(self.inputOverlap.get()) ) self.f2, self.P2 = computeSpectrum( self.filename2, int(self.inputFs.get()), int(self.inputWinSize.get()), int(self.inputOverlap.get()) ) # Plotting time self.a1.cla() self.a1 = plotSpectrum(self.f1, self.P1, "blue", self.a1, "Power spectrum", self.chSelect, self.chOther) self.a1 = plotSpectrum(self.f2, self.P2, "red", self.a1, "Power spectrum", self.chSelect, self.chOther) # Trying to autoscale P1_ROI = 20 * log10(self.P1[:, bitwise_and(self.f1 > 1, self.f1 < 20)]) P2_ROI = 20 * log10(self.P2[:, bitwise_and(self.f2 > 1, self.f2 < 20)]) self.Pmax = amax([amax(P1_ROI), amax(P2_ROI)]) self.Pmin = amin([(amin(P1_ROI)), amin(P2_ROI)]) self.a1.set_ylim(self.Pmin, self.Pmax) # Autoscale success :> self.fig.show() def writeFilters(self): f_theta = open(self.nameO.get() + "/theta.f", "w") f_theta.write( "<OpenViBE-SettingsOverride>\n\t<SettingValue>Butterworth</SettingValue>\n\t<SettingValue>Band pass</SettingValue>\n\t<SettingValue>4</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>0.5</SettingValue>\n</OpenViBE-SettingsOverride>".format( float(self.inputThetaLow.get()), float(self.inputThetaHigh.get()) ) ) f_theta.close() f_beta = open(self.nameO.get() + "/beta.f", "w") f_beta.write( "<OpenViBE-SettingsOverride>\n\t<SettingValue>Butterworth</SettingValue>\n\t<SettingValue>Band pass</SettingValue>\n\t<SettingValue>4</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>0.5</SettingValue>\n</OpenViBE-SettingsOverride>".format( float(self.inputBetaLow.get()), float(self.inputBetaHigh.get()) ) ) f_beta.close() f_smr = open(self.nameO.get() + "/smr.f", "w") f_smr.write( "<OpenViBE-SettingsOverride>\n\t<SettingValue>Butterworth</SettingValue>\n\t<SettingValue>Band pass</SettingValue>\n\t<SettingValue>4</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>0.5</SettingValue>\n</OpenViBE-SettingsOverride>".format( float(self.inputSMRLow.get()), float(self.inputSMRHigh.get()) ) ) f_smr.close() def printFigureToFile(self): self.fig1.savefig(self.nameO.get() + "/IAF_spectrum.png") def askOpenFile1(self): ftypes = [("asdadfh", "*.txt"), ("All files", "*")] dlg = tkFileDialog.Open(self, filetypes=ftypes) self.filename1 = dlg.show() self.nameF1.delete(0, END) self.nameF1.insert(0, self.filename1) def askOpenFile2(self): ftypes = [("asdadfh", "*.txt"), ("All files", "*")] dlg = tkFileDialog.Open(self, filetypes=ftypes) self.filename2 = dlg.show() self.nameF2.delete(0, END) self.nameF2.insert(0, self.filename2) def askOutputDirectory(self): dlg = tkFileDialog.askdirectory() # self.outputdir = dlg.show() self.outputdir = dlg self.nameO.delete(0, END) self.nameO.insert(0, self.outputdir)
#Throw in the labels, textboxes, needed in the billing form lblBillNo = Label(root, text="Bill No") lblBillNoValue = Label(root, text="Fetch from DB") lblSno = Label(root, text="S.No.") lblItemName = Label(root, text="Item Name and Description") lblQty = Label(root, text="Qty") lblRate = Label(root, text="Rate", width=3) lblCGST = Label(root, text="CGST%") lblSGST = Label(root, text="SGST%") lblBasicAmount = Label(root, text="Basic Amount") #Billing form entry box creation ROW1 txtBillRow1_1 = Entry(root, width=5) txtBillRow1_1.insert(0, " 1.") txtBillRow1_1.config(state='readonly') txtBillRow1_2 = Entry(root, width=50) txtBillRow1_3 = Entry(root, width=5) txtBillRow1_4 = Entry(root, width=5) txtBillRow1_5 = Entry(root, width=5) txtBillRow1_6 = Entry(root, width=5) txtBillRow1_7 = Entry(root) txtBillRow1_8 = Entry(root) #Billing form entry box creation ROW2 txtBillRow2_1 = Entry(root, width=5) txtBillRow2_1.insert(0, " 2.") txtBillRow2_1.config(state='readonly') txtBillRow2_2 = Entry(root, width=50) txtBillRow2_3 = Entry(root, width=5) txtBillRow2_4 = Entry(root, width=5)
class Example(Frame): ''' Constructor for creating a frame ''' def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() ''' Browse the filename to be added to to Openstack Swift ''' def browsefile(self): self.filename = askopenfilename() self.nm = self.filename.split("/") self.fnm = self.nm[len(self.nm)-1] self.e2.configure(state="normal") self.e2.update() self.e2.delete(0, 'end') self.e2.insert("end", self.fnm) self.e2.configure(state="disabled") self.e2.update() ''' Add Data - To Openstack Swift Check For De-Duplication of Data - Display the Data When found duplicate data Check For Already Added File - same file - Display the content of already Added file ''' def addData(self): file_ext=self.fnm.split('.') result = requests.get('http://localhost:8983/solr/techproducts/select?q='+ str(self.fnm)+'&wt=json&fl=id') op = result.json() flag = False if op['response']['numFound'] == 0: un_id = random.randint(1, 1000) if file_ext[1] == 'txt': listdocs = requests.get('http://localhost:8983/solr/techproducts/select?q=*.'+ file_ext[1] +'&wt=json') listdict = listdocs.json() f = open(self.fnm,"r") lines = f.readlines() alllines = "" for j in range(0, len(lines)): alllines += lines[j] for i in range(0, len(listdict['response']['docs'])): if alllines.strip() == (listdict['response']['docs'][i]['content'][0]).strip(): name = str(listdict['response']['docs'][i]['resourcename']).split("/") self.e3.delete('1.0', END) self.e3.insert(END,"Cannot Add Duplicate Data. There is already a file with same contents\n File name : "+ str(name[len(name)-1]) + "\n") self.e3.insert(END,"Here are the contents\n") self.e3.insert(END,str(listdict['response']['docs'][i]['content'][0]).strip()) flag = True if file_ext[1] == 'pdf': listdocs = requests.get('http://localhost:8983/solr/techproducts/select?q=*.'+ file_ext[1] +'&wt=json') listdict = listdocs.json() with open(self.fnm) as f: doc = slate.PDF(f) alllines = "" for i in range(0, len(doc)): alllines += doc[i] remove = string.punctuation + string.whitespace alllines = alllines.translate(None, remove) for i in range(0, len(listdict['response']['docs'])): alldocs = (listdict['response']['docs'][i]['content'][0]).encode("utf-8") alldocs = alldocs.translate(None, remove) res = (alllines == alldocs) if alllines == alldocs: name = str(listdict['response']['docs'][i]['resourcename']).split("/") self.e3.delete('1.0', END) self.e3.insert(END,"Cannot Add Duplicate Data. There is already a file with same contents\n File name : "+ str(name[len(name)-1]) + "\n") self.e3.insert(END,"Here are the contents\n") self.e3.insert(END,str(listdict['response']['docs'][i]['content'][0]).strip()) flag = True if file_ext[1] == 'docx': listdocs = requests.get('http://localhost:8983/solr/techproducts/select?q=*.'+ file_ext[1] +'&wt=json') listdict = listdocs.json() document = docx.Document(self.fnm) alllines = "" for para in document.paragraphs: dl = para.text.encode("utf-8") alllines += dl remove = string.punctuation + string.whitespace alllines = alllines.translate(None, remove) for i in range(0, len(listdict['response']['docs'])): alldocs = (listdict['response']['docs'][i]['content'][0]).encode("utf-8") alldocs = alldocs.translate(None, remove) res = (alllines == alldocs) if alllines == alldocs: name = str(listdict['response']['docs'][i]['resourcename']).split("/") self.e3.delete('1.0', END) self.e3.insert(END,"Cannot Add Duplicate Data. There is already a file with same contents\n File name : "+ str(name[len(name)-1]) + "\n") self.e3.insert(END,"Here are the contents\n") self.e3.insert(END,str(listdict['response']['docs'][i]['content'][0]).strip()) flag = True if flag == False: os.system('cp '+ str(self.fnm) + " /opt/solr/example/exampledocs/") os.system("/opt/solr/bin/post -c techproducts /opt/solr/example/exampledocs/" + str(self.fnm) + " -params \"literal.id=" + str(un_id) + "\"") self.e3.delete('1.0', END) self.e3.insert(END,"Indexing Done for the Upload .....\n") container = subprocess.check_output(["swift","list","-v","--os-username","admin","--os-password","ea12f4366a2a4253","--os-auth-url","http://localhost:5000/v2.0","--os-tenant-name","admin"]) container = container.split("\n") os_name = os.environ['OS_USERNAME'] os_password = os.environ['OS_PASSWORD'] os_auth_url = os.environ['OS_AUTH_URL'] os_tenant_name = os.environ['OS_TENANT_NAME'] response = os.system("swift upload -c -v --os-username "+ str(os_name) + " --os-password "+ str(os_password) + " --os-auth-url " + str(os_auth_url) + " --os-tenant-name "+ str(os_tenant_name) + " "+ str(container[0]) + " "+ str(self.fnm)) if response == 0: self.e3.insert(END,"File Uploaded Successfully to Openstack Swift\n") if op['response']['numFound'] > 0: answer = requests.get('http://localhost:8983/solr/techproducts/select?q='+ str(self.fnm)+'&wt=json&fl=content') details = answer.json() content_dict = details['response']['docs'][0]['content'] self.e3.delete('1.0', END) self.e3.insert(END,"Cannot Add Data Again\n") self.e3.insert(END,"Data Already Added to Openstack Swift:\nHere are the contents\n") self.e3.insert(END,content_dict[0]) ''' Search The Openstack Swift Data with Search Query given by the user ''' def searchData(self): query = self.e1.get() qresult = requests.get('http://localhost:8983/solr/techproducts/browse?q='+ str(query)+'&wt=json') qop = qresult.json() if qop['response']['numFound'] == 0: self.e3.delete('1.0', END) self.e3.insert(END,"Sorry !! No Details found for the search query") if qop['response']['numFound'] > 0: length = len(qop['response']['docs']) self.e3.delete('1.0', END) for i in range(0, length): sname = str(qop['response']['docs'][i]['resourcename']).split("/") self.e3.insert(END,"Filename : " + str(sname[len(sname)-1]) + "\n") self.e3.insert(END,qop['response']['docs'][i]['content'][0]) self.e3.insert(END,"Search Result Found "+ str(length) + " \n") ''' Clear The Text Area ''' def clearText(self): self.e1.delete(0, 'end') self.e2.configure(state="normal") self.e2.update() self.e2.delete(0, 'end') self.e2.configure(state="disabled") self.e2.update() self.e3.delete('1.0', END) ''' GUI : Add Canvas Add Buttons : Quit, Clear, Search, Browse, Add Add Text Area : Search, Add, Output ''' def initUI(self): self.parent.title("Openstack Search") self.config(bg = '#F0F0F0') self.pack(fill = BOTH, expand = 1) #create canvas self.canvas1 = Canvas(self, relief = FLAT, background = "#D2D2D2", width = 1000, height = 500) self.canvas1.pack(side = TOP, anchor = NW, padx = 10, pady = 10) self.e1 = Entry(self.canvas1) self.e1.config(width=20) self.e2 = Entry(self.canvas1) self.e2.config(width=20) self.e2.config(state="disabled") self.e1_window = self.canvas1.create_window(210,70,window = self.e1) self.e2_window = self.canvas1.create_window(210,120,window = self.e2) self.e3 = Text(self.canvas1,height=18) self.e3.grid(column=1,row=5, columnspan=5, rowspan=1, sticky='W') scrb=Scrollbar(self.canvas1,orient=VERTICAL,command=self.e3.yview) self.e3.configure(yscrollcommand=scrb.set) self.e3_window = self.canvas1.create_window(450,350,window = self.e3) self.button1 = Button(self, text = "Quit", command = self.quit, anchor = W) self.button1.configure(width = 10, activebackground = "#33B5E5", relief = FLAT) self.button1_window = self.canvas1.create_window(10, 10, anchor=NW, window=self.button1) self.button2 = Button(self, text = "Search", anchor = W) self.button2.configure(command=self.searchData) self.button2.configure(width = 10, activebackground = "#33B5F5", relief = FLAT) self.button2_window = self.canvas1.create_window(10, 60, anchor=NW, window=self.button2) self.button3 = Button(self, text = "Browse", command = self.browsefile, anchor = W) self.button3.configure(width = 10, activebackground = "#33B5D5", relief = FLAT) self.button3_window = self.canvas1.create_window(10, 110, anchor=NW, window=self.button3) self.button3 = Button(self, text = "Add", command = self.addData, anchor = W) self.button3.configure(width = 10, activebackground = "#33B5D5", relief = FLAT) self.button3_window = self.canvas1.create_window(10, 160, anchor=NW, window=self.button3) self.button4 = Button(self, text = "Clear", command = self.clearText, anchor = W) self.button4.configure(width = 10, activebackground = "#33B5D5", relief = FLAT) self.button4_window = self.canvas1.create_window(200, 10, anchor=NW, window=self.button4)
class UIFrame(Frame): def __init__(self, min_port_number, parent): Frame.__init__(self, parent, background='white') self.parent = parent self.min_port_number = min_port_number self._setup_ui() def _setup_ui(self): self.parent.title('p2paste') self.style = Style() self.style.theme_use('default') self.pack(fill=BOTH, expand=True) '''Fixed top-frame with connection controls''' frame_top = Frame(self) frame_top.pack(fill=X, side=TOP) label_nick = Label(frame_top, text="nickname:") label_nick.pack(side=LEFT, padx=2, pady=2) self.entry_nick = Entry(frame_top) self.entry_nick.pack(side=LEFT, padx=2) label_ip = Label(frame_top, text="ip:port") label_ip.pack(side=LEFT, padx=2, pady=2) self.entry_ip = Entry(frame_top) self.entry_ip.pack(side=LEFT, padx=2) self.button_connect = Button(frame_top, text="connect") self.button_connect.pack(side=LEFT, padx=2) self.button_disconnect = Button(frame_top, text="disconnect") self.button_disconnect.pack(side=LEFT, padx=2) label_port = Label(frame_top, text="port:") label_port.pack(side=LEFT, padx=2, pady=2) self.entry_port = Entry(frame_top, width=10) self.entry_port.pack(side=LEFT, padx=2, pady=2) self.button_host = Button(frame_top, text="host") self.button_host.pack(side=LEFT, padx=2, pady=2) self.button_close_server = Button(frame_top, text="close server") self.button_close_server.pack(side=LEFT, padx=2) '''Bottom frame with a PanedWindow, the main screen part''' frame_bottom = Frame(self) frame_bottom.pack(fill=BOTH, expand=True, side=TOP) pw_main = PanedWindow(frame_bottom) pw_main.pack(fill=BOTH, expand=True) '''Left part of screen, contains paste-text, chat-text and chat-entry''' frame_left = Frame(pw_main) pw_main.add(frame_left) '''Left-Bottom chat entry Frame with input controls''' frame_chat_entry = Frame(frame_left) frame_chat_entry.pack(fill=X, expand=True, side=BOTTOM) self.entry_chat = Entry(frame_chat_entry) self.entry_chat.pack(fill=X, expand=True, side=LEFT, padx=2, pady=2) self.button_send_message = Button(frame_chat_entry, text="send") self.button_send_message.pack(side=LEFT, padx=2, pady=2) self.button_copy_chat = Button(frame_chat_entry, text="copy") self.button_copy_chat.pack(side=LEFT, padx=2, pady=2) '''Paste and chat box on the left side wrapped in a PanedWindow for resizability''' pw_center = PanedWindow(frame_left, orient=VERTICAL) pw_center.pack(fill=BOTH, expand=True, side=TOP) '''Pastebox container''' frame_paste = Frame(pw_center) '''Input controls for Pastebox''' frame_paste_controls = Frame(frame_paste) frame_paste_controls.pack(fill=X, side=BOTTOM) label_has_paste = Label(frame_paste_controls, text="paste permission:") label_has_paste.pack(side=LEFT, padx=2, pady=2) self.entry_has_paste = Entry(frame_paste_controls, width=8, state=DISABLED) self.entry_has_paste.pack(side=LEFT, padx=2, pady=2) self.button_request_paste = Button(frame_paste_controls, text="request") self.button_request_paste.pack(side=LEFT, padx=2, pady=2) self.button_clear_pastebox = Button(frame_paste_controls, text="clear") self.button_clear_pastebox.pack(side=LEFT, padx=2, pady=2) self.button_selectall_pastebox = Button(frame_paste_controls, text="select all") self.button_selectall_pastebox.pack(side=LEFT, padx=2, pady=2) self.button_copy_pastebox = Button(frame_paste_controls, text="copy") self.button_copy_pastebox.pack(side=LEFT, padx=2, pady=2) self.button_paste_pastebox = Button(frame_paste_controls, text="paste") self.button_paste_pastebox.pack(side=LEFT, padx=2, pady=2) self.button_send_pastebox = Button(frame_paste_controls, text="send") self.button_send_pastebox.pack(side=LEFT, padx=2, pady=2) '''Pastebox with scrollbars''' sbx_text_paste = Scrollbar(frame_paste, orient=HORIZONTAL) sbx_text_paste.pack(side=BOTTOM, fill=X, padx=2) sby_text_paste = Scrollbar(frame_paste) sby_text_paste.pack(side=RIGHT, fill=Y, pady=2) self.text_paste = Text( frame_paste, wrap=NONE, xscrollcommand=sbx_text_paste.set, yscrollcommand=sby_text_paste.set ) self.text_paste.pack(fill=BOTH, expand=True, padx=2, pady=2) sbx_text_paste.config(command=self.text_paste.xview) sby_text_paste.config(command=self.text_paste.yview) pw_center.add(frame_paste) self.pastebox_disabled() '''Chatbox container''' frame_chat = Frame(pw_center) sby_text_chat = Scrollbar(frame_chat) sby_text_chat.pack(side=RIGHT, fill=Y, pady=2) self.text_chat = Text( frame_chat, wrap=WORD, state=DISABLED, yscrollcommand=sby_text_chat.set) self.text_chat.pack(fill=BOTH, expand=True, padx=2, pady=2) sby_text_chat.config(command=self.text_chat.yview) pw_center.add(frame_chat) '''Chat list on the right side''' frame_chatlist = Frame(pw_main) sby_chatlist = Scrollbar(frame_chatlist) sby_chatlist.pack(side=RIGHT, fill=Y, pady=2) self.listbox_clients = Listbox(frame_chatlist, yscrollcommand=sby_chatlist.set) self.listbox_clients.pack(fill=BOTH, expand=True, padx=2, pady=2) sby_chatlist.config(command=self.listbox_clients.yview) pw_main.add(frame_chatlist) def _message_to_chatbox(self, message): self.text_chat.config(state=NORMAL) self.text_chat.insert(END, '{0}\n'.format(message)) self.text_chat.yview(END) self.text_chat.config(state=DISABLED) def log_error(self, message): message = '^ERROR: {0}'.format(message) self._message_to_chatbox(message) def log_info(self, message): message = '^INFO: {0}'.format(message) self._message_to_chatbox(message) def _validate_port(self, port): try: port = int(port) if not port > self.min_port_number: raise ValueError return port except ValueError: raise InvalidPortNumber def _validate_ip(self, ip): try: parts = ip.split('.') if not len(parts) == 4: raise ValueError if not all(0 <= int(item) <= 255 for item in parts): raise ValueError return ip except ValueError: raise InvalidIPAddress def _validate_nickname(self, nickname): try: if not re.match(r'^[A-Za-z0-9\._-]{3,}$', nickname): raise ValueError return nickname except ValueError: raise InvalidNickName('Nickname contains invalid characters or is less than 3 characters in length.') def get_connect_address(self): try: address_string = self.entry_ip.get() ip, port = address_string.split(':') ip = self._validate_ip(ip) port = self._validate_port(port) return (ip, port) except InvalidIPAddress: error_message = 'Invalid ip address entered.' except InvalidPortNumber: error_message = 'Invalid port number entered.' except ValueError: error_message = 'Invalid address entered.' raise InvalidAddress(error_message) def get_nickname(self): nickname = self.entry_nick.get() return self._validate_nickname(nickname) def get_host_port(self): port_entered = self.entry_port.get() return self._validate_port(port_entered) def get_chat_message(self): message = self.entry_chat.get() self.entry_chat.delete(0, END) return message def add_chat_message(self, sender, message): self._message_to_chatbox('{0}: {1}'.format(sender, message)) def clear_client_list(self): self.listbox_clients.delete(0, END) def set_client_list(self, sender, client_list): self.clear_client_list() for nickname in client_list: self.listbox_clients.insert(END, nickname) def get_paste_data(self): return self.text_paste.get(1.0, END) def set_paste_data(self, sender, paste_data): self.text_paste.config(state=NORMAL) self.text_paste.delete(1.0, END) self.text_paste.insert(END, paste_data) self.text_paste.config(state=DISABLED) self.clear_paste_notification() def clear_pastebox(self, event): self.text_paste.delete(1.0, END) def selectall_pastebox(self, event): self.text_paste.tag_add('sel', 1.0, END) def _copy_from(self, text_element): text_element.config(state=NORMAL) try: text = text_element.selection_get() except TclError: return self.clipboard_clear() self.clipboard_append(text) text_element.config(state=DISABLED) def copy_chat(self, event): self._copy_from(self.text_chat) def copy_pastebox(self, event): self._copy_from(self.text_paste) def paste_pastebox(self, event): clipboard_data = self.clipboard_get() self.text_paste.insert(INSERT, clipboard_data) def _pastebox_permission(self, state): self.button_clear_pastebox.config(state=state) self.button_paste_pastebox.config(state=state) self.button_send_pastebox.config(state=state) self.text_paste.config(state=state) request_state = NORMAL if state == DISABLED else DISABLED self.button_request_paste.config(state=request_state) def pastebox_enabled(self, *args): self._pastebox_permission(NORMAL) def pastebox_disabled(self): self._pastebox_permission(DISABLED) def clear_paste_notification(self): self.entry_has_paste.config(state=NORMAL) self.entry_has_paste.delete(0, END) self.entry_has_paste.config(state=DISABLED) def set_paste_notification(self, sender, nickname): message = 'Paste permission granted to: {0}'.format(nickname) self.log_info(message) self.entry_has_paste.config(state=NORMAL) self.entry_has_paste.delete(0, END) self.entry_has_paste.insert(END, nickname) self.entry_has_paste.config(state=DISABLED)
class MainWindow: # c'tor def __init__(self, master): self.master = master master.title("Naive Bayes Classifier") creators_lbl = Label(master, text="Alon Galperin\nMatan Yeshurun", font="David", fg="Blue") #browse_button = Button(master, text="Browse", command=lambda: self.loadDataFromPath(browse_textbox.get()),height=1,width=10) browse_button = Button(master, text="Browse", command=lambda: self.getDirPath(), height=1, width=10) self.browse_value = StringVar() self.browse_textbox = Entry(master, width=55, exportselection=0, textvariable=self.browse_value) browse_lbl = Label(master, text="Directory Path: ") build_button = Button(master, text="Build", command=lambda: self.build(), height=1, width=20) classify_button = Button(master, text="Classify", command=lambda: self.classfy(), height=1, width=20) discretization_lbl = Label(master, text="Discretization Bins:") self.discretization_textbox = Entry(master, width=25) creators_lbl.place(x=220, y=20) browse_button.place(x=500, y=95) self.browse_textbox.place(x=150, y=100) browse_lbl.place(x=40, y=100) self.discretization_textbox.place(x=150, y=150) discretization_lbl.place(x=40, y=150) build_button.place(x=200, y=200) classify_button.place(x=200, y=250) master.minsize(width=600, height=400) master.maxsize(width=600, height=400) def update(self, param): if param is 'Browse': tkMessageBox.showinfo("message Box", "Browse") else: if param is 'build': tkMessageBox.showinfo("message Box", "build") def loadDataFromPath(self, value): if os.path.exists(value): tkMessageBox.showinfo("message Box-path exists", value) x = tkFileDialog.askdirectory(**self.dir_opt) else: tkMessageBox.showinfo("Path not exists", "Path not exists: " + value) def getDirPath(self): self.folderPath = tkFileDialog.askdirectory() #tkMessageBox.showinfo("",folderPath) self.browse_value.set = self.folderPath self.browse_textbox.config(state='normal') self.browse_textbox.delete(0, 'end') self.browse_textbox.insert(0, self.folderPath) self.browse_textbox.config(state='readonly') self.structure_path = self.folderPath + "/Structure.txt" self.train_path = self.folderPath + "/train.csv" self.test_path = self.folderPath + "/test.csv" if (not os.path.exists(self.structure_path)): tkMessageBox.showinfo( "Alert", "Structure file does not exists in the given path\nPlease select another folder of insert structure file into selected folder and pick again\nMissing 'Structure.text in: " + self.structure_path) if (not os.path.exists(self.train_path)): tkMessageBox.showinfo( "Alert", "train file does not exists in the given path\nPlease select another folder of insert structure file into selected folder and pick again\nMissing 'train.csv in: " + self.train_path) if (not os.path.exists(self.test_path)): tkMessageBox.showinfo( "Alert", "Structure file does not exists in the given path\nPlease select another folder of insert structure file into selected folder and pick again\nMissing 'test.csv in: " + self.test_path) if (not os.path.exists(self.structure_path) or not os.path.exists(self.train_path) or not os.path.exists(self.test_path)): self.getDirPath() else: tkMessageBox.showinfo("Alert", "All files are in the right place!") def build(self): self.bins_amount = int(self.discretization_textbox.get()) print("number of bins: " + str(self.bins_amount)) print("starting building model") #check bins value if (self.validBinValue(self.bins_amount)): #get Structure.text data self.structure = Structure.Structure(self.structure_path) self.structure.prepere_structure() self.train = Train.Train(self.train_path, self.structure.get_structure(), self.bins_amount) if (self.train.check_bin_max() <= int( self.discretization_textbox.get())): tkMessageBox.showinfo("Alert", "Invalid discretization bins value") return self.train.clean_train() self.classifier = Classifier.Classifier(self.train, self.structure, self.bins_amount, self.folderPath) self.classifier.build_model() tkMessageBox.showinfo( "Naive Bayes Classifier", "Building classifier using train-set is done!") def classfy(self): #create new test print("starting classifying model") test = Test.Test(self.test_path, self.structure.get_structure(), self.classifier, self.bins_amount) test.clean_test() test.classify_test() tkMessageBox.showinfo( "Done", "Classification is Done!\n results in output file") def validBinValue(self, bins): try: x = int(bins) if (x > 1): return True else: tkMessageBox.showinfo("Alert", "Invalid discretization bins value") return False except: tkMessageBox.showinfo("Alert", "Invalid discretization bins value") return False
class ArduinoSetup: def __init__(self, master, args): self.master = master self.master.minsize(width=360, height=600) self.master.title(PROJECT_TEXT) # GUI PROPS self.padXOut = 5 self.padYOut = 3 self.padXIn = 5 self.padYIn = 3 self.frameRelief = GROOVE self.frameBorder = 2 self.infoFG = "teal" self.selectBG = "teal" self.textBG = "white" self.errorBG = "red" self.vAction = StringVar() if args.verify: self.vAction.set("--verify") elif args.upload: self.vAction.set("--upload") else: self.vAction.set("") self.verify = args.verify self.upload = args.upload self.vPath = StringVar() self.vPath.set(args.arduino) self.vBoard = StringVar() self.vBoard.set(args.board) self.vPort = StringVar() self.vPort.set(args.port) self.vFile = StringVar() self.vFile.set(args.file) # GUI WIDGETS self.errorPath = True self.errorBoard = True self.errorPort = True self.errorFile = True self.enablePath = True self.enableBoard = True self.enablePort = True self.enableFile = True if self.vPath.get() != "": self.enablePath = False if self.vBoard.get() != "": self.enableBoard = False if self.vPort.get() != "": self.enablePort = False if self.vFile.get() != "": self.enableFile = False if self.enablePath: optArdu = {} optArdu["defaultextension"] = ".exe" optArdu["filetypes"] = [("exe files", ".exe"), ("all files", ".*")] # options['initialdir'] = 'C:\\' optArdu["initialfile"] = "arduino.exe" optArdu["parent"] = master optArdu["title"] = "Open arduino.exe" if system() == WINDOWS: pathexample = """Example: C:/Program Files/Arduino/arduino.exe""" else: pathexample = """Location of arduino executable""" self.vcmdPath = master.register(self.validatePath) self.framePath = LabelFrame(master, text="Arduino.exe path:", bd=self.frameBorder, relief=self.frameRelief) self.entryPath = Entry( self.framePath, bg=self.textBG, validate="all", validatecommand=(self.vcmdPath, "%P"), textvar=self.vPath, selectbackground=self.selectBG, ) self.entryPath.pack(fill=X, padx=self.padXIn, pady=self.padYIn) self.buttonPath = Button( self.framePath, text="Find arduino...", command=lambda: self.openPath(optArdu, self.vPath) ) self.buttonPath.pack(fill=X, padx=self.padXIn, pady=self.padYIn) self.labelPathInfo = Label(self.framePath, fg=self.infoFG, text=pathexample) self.labelPathInfo.pack(fill=X) self.framePath.pack(fill=X, padx=self.padXOut, pady=self.padYOut) if self.enableBoard: self.vcmdBoard = master.register(self.validateBoard) self.frameBoard = LabelFrame(master, text="Board:", bd=self.frameBorder, relief=self.frameRelief) self.entryBoard = Entry( self.frameBoard, bg=self.textBG, validate="all", validatecommand=(self.vcmdBoard, "%P"), textvar=self.vBoard, selectbackground=self.selectBG, ) self.entryBoard.pack(fill=X, padx=self.padXIn, pady=self.padYIn) self.labelBoardInfo = Label(self.frameBoard, fg=self.infoFG, text="""package:arch:board[:parameters]""") self.labelBoardInfo.pack(fill=X, padx=self.padXIn, pady=self.padYIn) self.textBoardExample = Text(self.frameBoard, fg=self.infoFG, width=50, height=6) self.textBoardExample.insert( END, """Packages: arduino, sparkfun, ... Arch: avr, sam, ... Boards: uno, mega, promicro, ... Parameters: cpu=CPU, ... Example: arduino:avr:nano:cpu=atmega168 SparkFun:avr:promicro:cpu=8MHzatmega32U4""", ) self.textBoardExample.config(state=DISABLED) self.textBoardExample.pack(fill=X, padx=self.padXIn, pady=self.padYIn) self.frameBoard.pack(fill=X, padx=self.padXOut, pady=self.padYOut) if self.enablePort: self.framePort = LabelFrame(master, text="Port:", bd=self.frameBorder, relief=self.frameRelief) if system() == WINDOWS: self.ports = serial_ports() # only for testing # self.ports.append(("COM", "Device 123")) self.frameListbox = Frame(self.framePort) scrollbar = Scrollbar(self.frameListbox) scrollbar.pack(side=RIGHT, fill=Y) self.listboxPort = Listbox( self.frameListbox, height=2, bg=self.textBG, selectbackground=self.selectBG, yscrollcommand=scrollbar.set, ) scrollbar.config(command=self.listboxPort.yview) self.listboxPort.insert(END, *self.ports) self.listboxPort.pack(fill=BOTH, expand=1) self.listboxPort.bind("<<ListboxSelect>>", self.portSelected) self.frameListbox.pack(fill=BOTH, expand=1, padx=self.padXIn, pady=self.padYIn) self.labelPortInfo = Label(self.framePort, fg=self.infoFG, text="port | port name | device name") self.labelPortInfo.pack(side=BOTTOM, fill=X, padx=self.padXIn, pady=self.padYIn) else: self.vcmdPort = master.register(self.validatePort) self.entryPort = Entry( self.framePort, bg=self.textBG, validate="all", validatecommand=(self.vcmdPort, "%P"), textvar=self.vPort, selectbackground=self.selectBG, ) self.entryPort.pack(fill=X, padx=self.padXIn, pady=self.padYIn) self.labelPortInfo = Label(self.framePort, fg=self.infoFG, text="""Example: /dev/ttyUSB0""") self.labelPortInfo.pack(side=BOTTOM, fill=X, padx=self.padXIn, pady=self.padYIn) self.framePort.pack(fill=BOTH, expand=1, padx=self.padXOut, pady=self.padYOut) if self.enableFile: optFile = {} optFile["defaultextension"] = ".ino" optFile["filetypes"] = [("arduino source files", ".ino"), ("all files", ".*")] # options['initialdir'] = 'C:\\' optFile["initialfile"] = "" optFile["parent"] = master optFile["title"] = "Open arduino source code" self.vcmdFile = master.register(self.validateFile) self.frameFile = LabelFrame(master, text="Source code path:", bd=self.frameBorder, relief=self.frameRelief) self.entryFile = Entry( self.frameFile, bg=self.textBG, validate="all", validatecommand=(self.vcmdFile, "%P"), textvar=self.vFile, selectbackground=self.selectBG, ) self.entryFile.pack(fill=X, padx=self.padXIn, pady=self.padYIn) self.buttonFile = Button( self.frameFile, text="Find source code...", command=lambda: self.openPath(optFile, self.vFile) ) self.buttonFile.pack(fill=X, padx=self.padXIn, pady=self.padYIn) self.labelFileInfo = Label( self.frameFile, fg=self.infoFG, text="""Source code to compile (file extension .ino)""" ) self.labelFileInfo.pack(fill=X) self.frameFile.pack(fill=X, padx=self.padXOut, pady=self.padYOut) # BOTTOM side items (reversed order) self.frameAbout = Frame(master, cursor="heart") self.labelAbout = Label(self.frameAbout, text=COPYRIGHT_TEXT, fg=self.infoFG) self.labelAbout.pack(side=LEFT) self.buttonAbout = Button( self.frameAbout, text="About app...", fg=self.infoFG, command=self.openAboutBox, borderwidth=1 ) self.buttonAbout.pack(side=RIGHT) self.frameAbout.pack(side=BOTTOM, fill=X, padx=self.padXOut, pady=self.padYOut) if self.vAction.get() != "": self.buttonContinue = Button(master, text="Continue", command=self.doContinue) self.buttonContinue.pack(fill=X, padx=self.padXOut, pady=self.padYOut) else: if self.verify is False: self.buttonVerify = Button(master, text="Verify", command=self.doVerify) self.buttonVerify.pack(side=BOTTOM, fill=X, padx=self.padXOut, pady=self.padYOut) if self.upload is False: self.buttonUpload = Button(master, text="Upload", command=self.doUpload) self.buttonUpload.pack(side=BOTTOM, fill=X, padx=self.padXOut, pady=self.padYOut) def openAboutBox(self): dialog = AboutDialog(self.master) def portSelected(self, P): self.errorPort = False self.listboxPort.config(bg=self.textBG) try: porti = map(int, self.listboxPort.curselection())[0] self.vPort.set(self.ports[porti][0]) except (IndexError): self.errorPort = True self.listboxPort.config(bg=self.errorBG) # only for linux def validatePort(self, P): if self.vPort.get() == "" and P == "": self.errorPort = True self.entryPort.config(bg=self.errorBG) return False else: self.errorPort = False self.entryPort.config(bg=self.textBG) return True def validatePath(self, P): if self.vPath.get() == "" and P == "": self.errorPath = True self.entryPath.config(bg=self.errorBG) return False else: self.errorPath = False self.entryPath.config(bg=self.textBG) return True def validateBoard(self, P): if self.vBoard.get() == "" and P == "": self.errorBoard = True self.entryBoard.config(bg=self.errorBG) return False else: self.errorBoard = False self.entryBoard.config(bg=self.textBG) return True def validateFile(self, P): if self.vFile.get() == "" and P == "": self.errorFile = True self.entryFile.config(bg=self.errorBG) return False else: self.errorFile = False self.entryFile.config(bg=self.textBG) return True def openPath(self, opt, sv): sv.set(tkFileDialog.askopenfilename(**opt)) def doVerify(self): self.vAction.set("--verify") self.doContinue() def doUpload(self): self.vAction.set("--upload") self.doContinue() def doContinue(self): if self.enablePath: self.validatePath(self.vPath.get()) else: self.errorPath = False if self.enableBoard: self.validateBoard(self.vBoard.get()) else: self.errorBoard = False if self.enableFile: self.validateFile(self.vFile.get()) else: self.errorFile = False if self.enablePort and system() != WINDOWS: print self.vPort.get() self.validatePort(self.vPort.get()) else: self.errorPort = False self.doAction() def doAction(self): result = 3 if self.errorPath or self.errorBoard or self.errorPort or self.errorFile: print "something missing" return command = '"' command += self.vPath.get() command += '" ' + self.vAction.get() command += " --board " + self.vBoard.get() command += " --port " + self.vPort.get() command += " --verbose" command += ' "' + self.vFile.get() command += '"' print "command:", command print "Please wait ..." sys.stdout.flush() self.master.destroy() p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = p.communicate() print output result = p.returncode
class MacroEdit(Toplevel): def __init__(self, root, prtr, settings, log, fn, text, *arg): Toplevel.__init__(self, root, *arg) self.title("Macro Editor") self.fn = fn self.app = root self.settings = settings self.printer = prtr self.log = log self.macroList = self.settings.getMacroList() self.macroEntry = None if fn == None: title = "New macro" self.macroTitle = None self.newMacro = True else: self.newMacro = False self.macroTitle = title = os.path.basename(fn) for m in self.macroList: if self.macroTitle == m[MNAME]: self.macroEntry = m break self.f = LabelFrame(self, text=title) self.entry = Text(self.f, width=80, height=24, relief=RIDGE, bd=2) self.entry.grid(row=1, column=1) self.f.grid(row=1, column=1, columnspan=6) self.bSave = Button(self, text="Save", width=20, command=self.doSave) self.bSave.grid(row=2, column=1) self.bExit = Button(self, text="Exit", width=20, command=self.doExit) self.bExit.grid(row=2, column=2) self.cbvAddButton = IntVar() self.cbAddButton = Checkbutton(self, text="Add Button", variable=self.cbvAddButton, command=self.doAddButton) self.cbAddButton.grid(row=2, column=3) self.buttonText = Entry(self, width=12) self.buttonText.grid(row=2, column=4) l = Label(self, text="Column:", justify=RIGHT) l.grid(row=2, column=5, sticky=E) self.spCol = Spinbox(self, values=[1,2,3], width=12, justify=RIGHT) self.spCol.grid(row=2, column=6) l = Label(self, text="Row:", justify=RIGHT) l.grid(row=3, column=5, sticky=E) self.spRow = Spinbox(self, values=[1,2,3,4,5,6,7,8,9,10], width=12, justify=RIGHT) self.spRow.grid(row=3, column=6) if self.macroEntry != None: self.cbvAddButton.set(1) self.spRow.delete(0, END) self.spRow.insert(0, self.macroEntry[MROW]) self.spCol.delete(0, END) self.spCol.insert(0, self.macroEntry[MCOL]) self.buttonText.delete(0, END) self.buttonText.insert(0, self.macroEntry[MTEXT]) self.initialButtonInfo = [1, self.macroEntry[MCOL], self.macroEntry[MROW], self.macroEntry[MTEXT]] else: self.cbvAddButton.set(0) self.spRow.delete(0, END) self.spRow.insert(0, 1) self.spCol.delete(0, END) self.spCol.insert(0, 1) self.buttonText.delete(0, END) self.initialButtonInfo = [0, 1, 1, ""] self.doAddButton() self.startText = text self.entry.delete("1.0", END) self.entry.insert(END, self.startText) self.entry.edit_modified(False) self.grab_set() self.app.wait_window(self) def doAddButton(self): if self.cbvAddButton.get() == 1: self.buttonText.config(state=NORMAL) self.spRow.config(state=NORMAL) self.spCol.config(state=NORMAL) else: self.buttonText.config(state=DISABLED) self.spRow.config(state=DISABLED) self.spCol.config(state=DISABLED) def buttonInfoChanged(self): if self.cbvAddButton.get() != self.initialButtonInfo[0]: return True if self.initialButtonInfo[1] != int(self.spCol.get()): return True if self.initialButtonInfo[2] != int(self.spRow.get()): return True return self.initialButtonInfo[3] != self.buttonText.get() def doSave(self): if self.cbvAddButton.get() == 1 and self.buttonInfoChanged(): c = int(self.spCol.get()) r = int(self.spRow.get()) for m in self.macroList: if c == m[MCOL] and r == m[MROW]: if self.newMacro or self.macroTitle != m[MNAME]: showerror("Duplicate Location", "That position is already in use by another macro", parent=self) return buttonInfo = [c, r, self.buttonText.get()] else: buttonInfo = None if self.entry.edit_modified() or self.buttonInfoChanged(): l = self.entry.get("1.0", END).rstrip() if self.app.macroEditSave(self.fn, l, buttonInfo, self): self.entry.edit_modified(False) self.initialButtonInfo[0] = self.cbvAddButton.get() self.initialButtonInfo[1] = int(self.spCol.get()) self.initialButtonInfo[2] = int(self.spRow.get()) self.initialButtonInfo[3] = self.buttonText.get() def doExit(self): if self.entry.edit_modified() or self.buttonInfoChanged(): if not tkMessageBox.askyesno("Exit?", "Are you sure you want to exit and lose changes?", parent=self): return self.app.macroEditExit(self.fn) self.destroy()
class IviGui: def __init__(self, master): self.master = master master.title("U2001A power measurement") # Label and Entry for inputting relative/attenuator value self.atten = Label(master, text="Relative (dB):") self.atten.grid(row=1, column=1) self.entry = Entry(master) self.entry.insert(0, '0') self.entry.grid(row=1, column=2) # Main display label. Shows relative measurement with dot during updates self.label = Label(master, text=" \n-NaN dBm", font=("Arial", 32), height=3, width=20) self.label.grid(row=2, column=1, columnspan=2) # Smaller secondary display to show real measurement by device self.label2 = Label(master, text=" \n-NaN dBm", font=("Arial", 16)) self.label2.grid(row=3, column=1, columnspan=2) print usbtmc.list_resources() # List USBTMC resources to connect to. self.instr = usbtmc.Instrument( 'USB::10893::11032::INSTR' ) # Your device to connect to. Pick from the list. self.instr.timeout = 60 * 1000 # Some devices are slow, some configurations are slow, timeout in ms. print self.instr.ask( "*IDN?" ) # Print out what device itself thinks its name is for validation. # Keysight U2001A trigger setup - free running trigger self.instr.write("INIT[1]:CONT 1") self.instr.write("TRIG[1]:SOUR IMM") # Init the variables self.measurement = -100 self.original_background = self.entry.cget("background") # Start first measurement self.update() # This method polls the device and updates display. Polling can take long time. def update(self): self.measurement = self.instr.ask("MEAS?") #print "%.2f" % float(self.measurement) # Debug printout to check the connection. self.update_number(True) self.label.after(100, self.remove_dot) # 100 ms after getting a measurement from the device, remove the dot above the measurement. # This provided clear indication to user about when the data was updated. def remove_dot(self): self.update_number(False) self.label.after(100, self.update) # Deal with getting the relative number from the Entry and updating all the displays. def update_number(self, dot=False): try: relative_value = float(self.entry.get()) self.entry.config(background=self.original_background) if dot: self.label.config(text=".\n%.2f dBm" % (float(self.measurement) - relative_value)) else: self.label.config(text=" \n%.2f dBm" % (float(self.measurement) - relative_value)) # If the relative box shows gibberish, just display the measurement. except ValueError: self.entry.config(background="#A44") if dot: self.label.config(text=".\n%.2f dBm" % float(self.measurement)) else: self.label.config(text=" \n%.2f dBm" % float(self.measurement)) self.label2.config(text="%.2f dBm" % float(self.measurement))
def make_entry(self,master,field,field_spec,values,bar): # print 'make entry',self.field_index,field,field_spec if field_spec['shape']=='tab': self.current_tab = Tab(master, field_spec['name']) bar.add(self.current_tab,field_spec['text']) self.tab_row=1 return None elif field_spec['shape']=='sep': Label(self.current_tab,text='', anchor=W).grid(row=self.tab_row,column=0,sticky=W) self.tab_row+=1 return None else: # print 'replace param in make entry',field # print 'content', field, self.field_content[field] # is it in the field content dictionary if not field in self.field_content: self.mon.log(self,"Value for field not found in opened file: " + field) return None else: if field_spec['must']=='yes': bg='pink' else: bg='white' # write the label Label(self.current_tab,text=field_spec['text'], anchor=W).grid(row=self.tab_row,column=0,sticky=W) # make the editable field if field_spec['shape']in ('entry','colour','browse','font'): obj=Entry(self.current_tab,bg=bg,width=40,font='arial 11') obj.insert(END,self.field_content[field]) elif field_spec['shape']=='text': obj=ScrolledText(self.current_tab,bg=bg,height=8,width=40,font='arial 11') obj.insert(END,self.field_content[field]) elif field_spec['shape']=='spinbox': obj=Spinbox(self.current_tab,bg=bg,values=values,wrap=True) obj.insert(END,self.field_content[field]) elif field_spec['shape']=='option-menu': self.option_val = StringVar(self.current_tab) self.option_val.set(self.field_content[field]) obj = apply(OptionMenu, [self.current_tab, self.option_val] + values) self.entries.append(self.option_val) else: self.mon.log(self,"Uknown shape for: " + field) return None if field_spec['read-only']=='yes': obj.config(state="readonly",bg='dark grey') obj.grid(row=self.tab_row,column=1,sticky=W) # display buttons where required if field_spec['shape']=='browse': but=Button(self.current_tab,width=1,height=1,bg='dark grey',command=(lambda o=obj: self.browse(o))) but.grid(row=self.tab_row,column=2,sticky=W) elif field_spec['shape']=='colour': but=Button(self.current_tab,width=1,height=1,bg='dark grey',command=(lambda o=obj: self.pick_colour(o))) but.grid(row=self.tab_row,column=2,sticky=W) elif field_spec['shape']=='font': but=Button(self.current_tab,width=1,height=1,bg='dark grey',command=(lambda o=obj: self.pick_font(o))) but.grid(row=self.tab_row,column=2,sticky=W) self.tab_row+=1 return obj
class Input: """ (TO DO) """ #================================================================ def __init__(self, master, t1="x", t2="", name=""): """ (TO DO) """ if name == "": self.label1 = Label(master, text=t1) self.label2 = Label(master, text=t2) self.tBox = Entry(master) else: self.label1 = Label(master, text=t1, name=("lb1_" + name)) self.label2 = Label(master, text=t2, name=("lb2_" + name)) self.tBox = Entry(master, name=("tbox_" + name)) #================================================================ def __call__(self, cFactor=1.): """ (TO DO) """ return self.get(cFactor) #=============================================================== def get(self, cFactor=1.): """ (TO DO) """ tmp = float(self.tBox.get()) return tmp * cFactor #================================================================ def set(self, value): """ (TO DO) """ self.tBox.delete(0, END) self.tBox.insert(0, value) #================================================================ def enable(self): """ (TO DO) """ self.label1.config(state=NORMAL) self.label2.config(state=NORMAL) self.tBox.config(state=NORMAL) #================================================================ def disable(self): """ (TO DO) """ self.label1.config(state=DISABLED) self.label2.config(state=DISABLED) self.tBox.config(state=DISABLED)
def create(self, S={}): root = self.root # #BackgroundFile = Image(file='/home/dmitrey/tmp_i/Backgd01.jpg') # bgfile = '/home/dmitrey/tmp_i/Backgd01.gif' # #bgfile = '/home/dmitrey/IP.png' # BackgroundFile = PhotoImage(file=bgfile) # #RootFrame.create_image(0, 0, image=BackgroundFile) RootFrame = Canvas(root)#, image=BackgroundFile) # RootFrame.create_image(0, 0, image=BackgroundFile) # RootFrame.image = BackgroundFile RootFrame.pack() self.NameEntriesList, self.LB_EntriesList, self.UB_EntriesList, self.TolEntriesList, self.ValueEntriesList = [], [], [], [], [] self.calculated_points = S.get('calculated_points', []) # Title #root.wm_title(' FuncDesigner ' + fdversion + ' Manager') C = Canvas(root) """ Buttons """ Frame(RootFrame).pack(ipady=4) #Label(root, text=' FuncDesigner ' + fdversion + ' ').pack() # Upper Frame UpperFrame = Frame(RootFrame) ProjectNameFrame = Frame(UpperFrame)#, relief = 'ridge', bd=2) Label(ProjectNameFrame, text = 'Project name:').pack(side = 'left') ProjectNameEntry = Entry(ProjectNameFrame) ProjectNameEntry.pack(side = 'left') self.ProjectNameEntry = ProjectNameEntry ProjectNameFrame.pack(side = 'left') GoalSelectFrame = Frame(UpperFrame, relief = 'ridge', bd=2) GoalSelectText = StringVar(value = 'Goal:') Label(GoalSelectFrame, textvariable = GoalSelectText).pack(side = 'left') goal = StringVar() r1 = Radiobutton(GoalSelectFrame, text = 'Minimum', value = 'min', variable=goal) r1.pack(side = 'left') r2 = Radiobutton(GoalSelectFrame, text = 'Maximum', value = 'max', variable=goal) r2.pack(side = 'left') goal.set('min') GoalSelectFrame.pack(side = 'left', padx = 10) self.goal = goal ObjectiveToleranceFrame = Frame(UpperFrame, relief = 'ridge', bd=2) ObjectiveToleranceFrame.pack(side='left') Label(ObjectiveToleranceFrame, text='Objective function tolerance:').pack(side = 'left') ObjTolEntry = Entry(ObjectiveToleranceFrame) ObjTolEntry.pack(side='left') self.ObjTolEntry = ObjTolEntry UpperFrame.pack(side = 'top', expand=True, fill = 'x') # Variables Frame varsRoot = Frame(RootFrame) # Lower frame LowerFrame = Frame(varsRoot) LowerFrame.pack(side = 'bottom', expand=True, fill = 'x') from webbrowser import open_new_tab About = Button(LowerFrame, text = 'About', command = lambda: open_new_tab('http://openopt.org/MultiFactorAnalysis')) About.pack(side='left') SaveButton = Button(LowerFrame, text = 'Save', command = self.save) SaveButton.pack(side='left', padx = 15) SaveAsButton = Button(LowerFrame, text = 'Save As ...', command = self.save) SaveAsButton.pack(side='left') Write_xls_Button = Button(LowerFrame, text = 'Write xls report', command = self.write_xls_report) Write_xls_Button.pack(side='left', padx = 15) # PlotButton = Button(LowerFrame, text = 'Plot', command = lambda: Plot(C, self.prob)) # PlotButton.pack(side='left') ExperimentNumber = IntVar() ExperimentNumber.set(1) self.ExperimentNumber = ExperimentNumber ObjVal = StringVar() ObjEntry = Entry(LowerFrame, textvariable = ObjVal) self.ObjEntry = ObjEntry NN = StringVar(LowerFrame) NN_Label = Label(LowerFrame, textvariable = NN) names, lbs, ubs, tols, currValues = \ Frame(varsRoot), Frame(varsRoot), Frame(varsRoot), Frame(varsRoot), Frame(varsRoot) Label(names, text=' Variable Name ').pack(side = 'top') Label(lbs, text=' Lower Bound ').pack(side = 'top') Label(ubs, text=' Upper Bound ').pack(side = 'top') Label(tols, text=' Tolerance ').pack(side = 'top') ValsColumnName = StringVar() ValsColumnName.set(' Initial Point ') Label(currValues, textvariable=ValsColumnName).pack(side = 'top') self.ValsColumnName = ValsColumnName # Commands Frame CommandsRoot = Frame(RootFrame) CommandsRoot.pack(side = 'right', expand = False, fill='y') AddVar = Button(CommandsRoot, text = 'Add Variable', command = \ lambda: self.addVar(names, lbs, ubs, tols, currValues)) AddVar.pack(side = 'top', fill='x') Next = Button(CommandsRoot, text = 'Next', command = lambda: ExperimentNumber.set(ExperimentNumber.get()+1)) #Next.pack(side='bottom', fill='x') names.pack(side = 'left', ipady=5) lbs.pack(side = 'left', ipady=5) ubs.pack(side = 'left', ipady=5) tols.pack(side = 'left', ipady=5) currValues.pack(side = 'left', ipady=5) #currValues.pack_forget() varsRoot.pack() Start = Button(CommandsRoot, text = 'Start', \ command = lambda: (Start.destroy(), \ Next.pack(side='bottom', fill='x'), #C.pack(side = 'bottom', expand=True, fill='both'), r1.config(state=DISABLED), r2.config(state=DISABLED), ObjTolEntry.config(state=DISABLED), ObjEntry.pack(side='right', ipady=4), NN_Label.pack(side='right'), \ self.startOptimization(root, varsRoot, AddVar, currValues, ValsColumnName, ObjEntry, ExperimentNumber, Next, NN, goal.get(), float(ObjTolEntry.get()), C))) Start.pack(side = 'bottom', fill='x') self.Start = Start if len(S) != 0: for i in range(len(S['names'])): tmp = S['values'][i] if self.x0 is None else self.x0.split(' ')[i] self.addVar(names, lbs, ubs, tols, currValues, S['names'][i], S['lbs'][i], S['ubs'][i], S['tols'][i], tmp) else: self.addVar(names, lbs, ubs, tols, currValues)
def create(self, S={}): root = self.root # #BackgroundFile = Image(file='/home/dmitrey/tmp_i/Backgd01.jpg') # bgfile = '/home/dmitrey/tmp_i/Backgd01.gif' # #bgfile = '/home/dmitrey/IP.png' # BackgroundFile = PhotoImage(file=bgfile) # #RootFrame.create_image(0, 0, image=BackgroundFile) RootFrame = Canvas(root) #, image=BackgroundFile) # RootFrame.create_image(0, 0, image=BackgroundFile) # RootFrame.image = BackgroundFile RootFrame.pack() self.NameEntriesList, self.LB_EntriesList, self.UB_EntriesList, self.TolEntriesList, self.ValueEntriesList = [], [], [], [], [] self.calculated_points = S.get('calculated_points', []) # Title #root.wm_title(' FuncDesigner ' + fdversion + ' Manager') C = Canvas(root) """ Buttons """ Frame(RootFrame).pack(ipady=4) #Label(root, text=' FuncDesigner ' + fdversion + ' ').pack() # Upper Frame UpperFrame = Frame(RootFrame) ProjectNameFrame = Frame(UpperFrame) #, relief = 'ridge', bd=2) Label(ProjectNameFrame, text='Project name:').pack(side='left') ProjectNameEntry = Entry(ProjectNameFrame) ProjectNameEntry.pack(side='left') self.ProjectNameEntry = ProjectNameEntry ProjectNameFrame.pack(side='left') GoalSelectFrame = Frame(UpperFrame, relief='ridge', bd=2) GoalSelectText = StringVar(value='Goal:') Label(GoalSelectFrame, textvariable=GoalSelectText).pack(side='left') goal = StringVar() r1 = Radiobutton(GoalSelectFrame, text='Minimum', value='min', variable=goal) r1.pack(side='left') r2 = Radiobutton(GoalSelectFrame, text='Maximum', value='max', variable=goal) r2.pack(side='left') goal.set('min') GoalSelectFrame.pack(side='left', padx=10) self.goal = goal ObjectiveToleranceFrame = Frame(UpperFrame, relief='ridge', bd=2) ObjectiveToleranceFrame.pack(side='left') Label(ObjectiveToleranceFrame, text='Objective function tolerance:').pack(side='left') ObjTolEntry = Entry(ObjectiveToleranceFrame) ObjTolEntry.pack(side='left') self.ObjTolEntry = ObjTolEntry UpperFrame.pack(side='top', expand=True, fill='x') # Variables Frame varsRoot = Frame(RootFrame) # Lower frame LowerFrame = Frame(varsRoot) LowerFrame.pack(side='bottom', expand=True, fill='x') from webbrowser import open_new_tab About = Button(LowerFrame, text='About', command=lambda: open_new_tab( 'http://openopt.org/MultiFactorAnalysis')) About.pack(side='left') SaveButton = Button(LowerFrame, text='Save', command=self.save) SaveButton.pack(side='left', padx=15) SaveAsButton = Button(LowerFrame, text='Save As ...', command=self.save) SaveAsButton.pack(side='left') Write_xls_Button = Button(LowerFrame, text='Write xls report', command=self.write_xls_report) Write_xls_Button.pack(side='left', padx=15) # PlotButton = Button(LowerFrame, text = 'Plot', command = lambda: Plot(C, self.prob)) # PlotButton.pack(side='left') ExperimentNumber = IntVar() ExperimentNumber.set(1) self.ExperimentNumber = ExperimentNumber ObjVal = StringVar() ObjEntry = Entry(LowerFrame, textvariable=ObjVal) self.ObjEntry = ObjEntry NN = StringVar(LowerFrame) NN_Label = Label(LowerFrame, textvariable=NN) names, lbs, ubs, tols, currValues = \ Frame(varsRoot), Frame(varsRoot), Frame(varsRoot), Frame(varsRoot), Frame(varsRoot) Label(names, text=' Variable Name ').pack(side='top') Label(lbs, text=' Lower Bound ').pack(side='top') Label(ubs, text=' Upper Bound ').pack(side='top') Label(tols, text=' Tolerance ').pack(side='top') ValsColumnName = StringVar() ValsColumnName.set(' Initial Point ') Label(currValues, textvariable=ValsColumnName).pack(side='top') self.ValsColumnName = ValsColumnName # Commands Frame CommandsRoot = Frame(RootFrame) CommandsRoot.pack(side='right', expand=False, fill='y') AddVar = Button(CommandsRoot, text = 'Add Variable', command = \ lambda: self.addVar(names, lbs, ubs, tols, currValues)) AddVar.pack(side='top', fill='x') Next = Button( CommandsRoot, text='Next', command=lambda: ExperimentNumber.set(ExperimentNumber.get() + 1)) #Next.pack(side='bottom', fill='x') names.pack(side='left', ipady=5) lbs.pack(side='left', ipady=5) ubs.pack(side='left', ipady=5) tols.pack(side='left', ipady=5) currValues.pack(side='left', ipady=5) #currValues.pack_forget() varsRoot.pack() Start = Button(CommandsRoot, text = 'Start', \ command = lambda: (Start.destroy(), \ Next.pack(side='bottom', fill='x'), #C.pack(side = 'bottom', expand=True, fill='both'), r1.config(state=DISABLED), r2.config(state=DISABLED), ObjTolEntry.config(state=DISABLED), ObjEntry.pack(side='right', ipady=4), NN_Label.pack(side='right'), \ self.startOptimization(root, varsRoot, AddVar, currValues, ValsColumnName, ObjEntry, ExperimentNumber, Next, NN, goal.get(), float(ObjTolEntry.get()), C))) Start.pack(side='bottom', fill='x') self.Start = Start if len(S) != 0: for i in range(len(S['names'])): tmp = S['values'][i] if self.x0 is None else self.x0.split( ' ')[i] self.addVar(names, lbs, ubs, tols, currValues, S['names'][i], S['lbs'][i], S['ubs'][i], S['tols'][i], tmp) else: self.addVar(names, lbs, ubs, tols, currValues)
class FootprintsUI(object): def __init__(self, master): self.config = Config() self.master = master self.master.resizable(width=FALSE, height=FALSE) self.master.title('NIRspec Observation Visualization Tool') self.background = ImageTk.PhotoImage( file=os.path.join(PKG_DATA_DIR, "back-08.png")) w = self.background.width() h = self.background.height() # position coordinates of root 'upper left corner' x = 0 y = 0 # make the root window the size of the image self.master.geometry("%dx%d+%d+%d" % (w, h, x, y)) # root has no image argument, so use a label as a panel self.panel1 = Label(self.master, image=self.background) # panel1.pack(side='top', fill='both', expand='Yes') self.panel1.place(x=0, y=0) # panel1.image = image1 # assigning values to colors self.colmsaVar = StringVar() self.colmsaVar.set(self.config['color_msa']) self.colshortVar = StringVar() self.colshortVar.set(self.config['color_short']) self.collongVar = StringVar() self.collongVar.set(self.config['color_long']) self.readfitsimageVar = StringVar() self.readfitsimageVar.set(self.config['readfitsimage']) # print(readfitsimageVar) self.labplotsources = Label(self.master, text=" Catalog on ?") self.labplotsources.place(relx=0.44, rely=0.26, anchor="w") self.plotsourcesVar = StringVar() self.plotsourcesVar.set(self.config['plot_src']) self.pt = OptionMenu(self.master, self.plotsourcesVar, 'Yes', 'No') self.pt.place(relx=0.29, rely=0.26, anchor="w") self.labplotmsa = Label(self.master, text="MSA footprint on ?") self.labplotmsa.place(relx=0.65, rely=0.38, anchor="w") self.plotmsaVar = StringVar() self.plotmsaVar.set(self.config['plot_msa']) self.pt = OptionMenu(self.master, self.plotmsaVar, 'Yes', 'No') self.pt.place(relx=0.35, rely=0.38, anchor="w") self.colmsaVar = StringVar() self.colmsaVar.set(self.config['color_msa']) self.colmsa = OptionMenu(self.master, self.colmsaVar, 'Red', 'Cyan', 'Blue', 'Yellow', 'Green') self.colmsa.config(width=9) self.colmsa.place(relx=0.49, rely=0.38, anchor="w") self.labramsa = Label(self.master, text="RA center of MSA") self.labramsa.place(relx=0.65, rely=0.42, anchor="w") self.ramsaVar = StringVar() self.ramsaVar.set(self.config['ra_nirspec']) self.ramsa = Entry(self.master, textvariable=self.ramsaVar) self.ramsa.place(relx=0.35, rely=0.42, anchor="w") self.ramsa_ttp = CreateToolTip( self.ramsa, 'Enter RA value.\nxxx.xxxx (degrees)\nhh mm ss.sss') self.labdecmsa = Label(self.master, text="DEC center of MSA") self.labdecmsa.place(relx=0.65, rely=0.46, anchor="w") self.decmsaVar = StringVar() self.decmsaVar.set(self.config['dec_nirspec']) self.decmsa = Entry(self.master, textvariable=self.decmsaVar) self.decmsa.place(relx=0.35, rely=0.46, anchor="w") self.decmsa_ttp = CreateToolTip( self.decmsa, 'Enter DEC value.\nxxx.xxxx (degrees)\nhh mm ss.sss') self.labthmsa = Label(self.master, text="MSA aperture PA") self.labthmsa.place(relx=0.65, rely=0.50, anchor="w") self.thmsaVar = StringVar() self.thmsaVar.set(self.config['theta_nirspec']) self.thmsa = Entry(self.master, textvariable=self.thmsaVar) self.thmsa.place(relx=0.35, rely=0.50, anchor="w") self.thmsa_ttp = CreateToolTip( self.thmsa, 'Enter MSA Aperture PA value in degrees') self.labplotshort = Label(self.master, text="Short channel on ?") self.labplotshort.place(relx=0.65, rely=0.61, anchor="w") self.plotshortVar = StringVar() self.plotshortVar.set(self.config['plot_short']) self.pt = OptionMenu(self.master, self.plotshortVar, 'Yes', 'No') self.pt.config(width=8) self.pt.place(relx=0.35, rely=0.61, anchor="w") self.labplotlong = Label(self.master, text="Long channel on ?") self.labplotlong.place(relx=0.65, rely=0.65, anchor="w") self.plotlongVar = StringVar() self.plotlongVar.set(self.config['plot_long']) self.pt = OptionMenu(self.master, self.plotlongVar, 'Yes', 'No') self.pt.config(width=8) self.pt.place(relx=0.35, rely=0.65, anchor="w") self.labranrcm = Label(self.master, text="RA center of NIRCam") self.labranrcm.place(relx=0.65, rely=0.69, anchor="w") self.ranrcmVar = StringVar() self.ranrcmVar.set(self.config['ra_nircam']) self.ranrcm = Entry(self.master, textvariable=self.ranrcmVar) self.ranrcm.place(relx=0.35, rely=0.69, anchor="w") self.ranrcm_ttp = CreateToolTip( self.ranrcm, 'Enter RA value.\nxxx.xxxx (degrees)\nhh mm ss.sss') self.labdecnrcm = Label(self.master, text="DEC center of NIRCam") self.labdecnrcm.place(relx=0.65, rely=0.73, anchor="w") self.decnrcmVar = StringVar() self.decnrcmVar.set(self.config['dec_nircam']) self.decnrcm = Entry(self.master, textvariable=self.decnrcmVar) self.decnrcm.place(relx=0.35, rely=0.73, anchor="w") self.decnrcm_ttp = CreateToolTip( self.decnrcm, 'Enter DEC value.\nxxx.xxxx (degrees)\nhh mm ss.sss') self.labthnrcm = Label(self.master, text="NIRCam aperture PA") self.labthnrcm.place(relx=0.65, rely=0.77, anchor="w") self.thnrcmVar = StringVar() self.thnrcmVar.set(self.config['theta_nircam']) self.thnrcm = Entry(self.master, textvariable=self.thnrcmVar) self.thnrcm.place(relx=0.35, rely=0.77, anchor="w") self.thnrcm_ttp = CreateToolTip( self.thnrcm, 'Enter NIRCam Aperture PA value in degrees') self.labdither = Label(self.master, text="NIRCam dither pattern") self.labdither.place(relx=0.02, rely=0.81, anchor="w") self.ditherVar = StringVar() self.ditherVar.set(self.config['dither']) self.pt = OptionMenu(self.master, self.ditherVar, 'None', 'FULL3', 'FULL3TIGHT', 'FULL6', '8NIRSPEC') self.pt.place(relx=0.35, rely=0.81, anchor="w") self.labmosaic = Label(self.master, text="NIRCam mosaic") self.labmosaic.place(relx=0.02, rely=0.87, anchor="w") self.mosaicVar = StringVar() self.mosaicVar.set(self.config['mosaic']) self.pt = OptionMenu(self.master, self.mosaicVar, 'No', 'Yes') self.pt.place(relx=0.35, rely=0.87, anchor="w") self.laboffhor = Label(self.master, text="Offset") self.laboffhor.place(relx=0.50, rely=0.85, anchor="w") self.offhorVar = StringVar() self.offhorVar.set(self.config['off_h']) self.offhor = Entry(self.master, textvariable=self.offhorVar) self.offhor.place(relx=0.65, rely=0.85, anchor="w") self.offhor_ttp = CreateToolTip(self.offhor, 'Enter NIRCam offset in arcsec') self.laboffver = Label(self.master, text="Offset") self.laboffver.place(relx=0.50, rely=0.89, anchor="w") self.offverVar = StringVar() self.offverVar.set(self.config['off_v']) self.offver = Entry(self.master, textvariable=self.offverVar) self.offver.place(relx=0.65, rely=0.89, anchor="w") self.offver_ttp = CreateToolTip(self.offver, 'Enter NIRCam offset in arcsec') self.ptVar = StringVar() self.ptVar.set('footprints') self.b5 = Button(self.master, text=" Select File ", command=self.readfitsfilename) self.b5.place(relx=0.43, rely=0.12, anchor="w") self.fileVar = StringVar() self.fileVar.set(self.config['fits_name']) self.filevalue = Entry(self.master, textvariable=self.fileVar, width=40, justify='left') self.filevalue.place(relx=0.02, rely=0.15, anchor="w") self.b6 = Button(self.master, text=" Select File ", command=self.readcataloguename) self.b6.place(relx=0.43, rely=0.295, anchor="w") self.catVar = StringVar() self.catVar.set(self.config['cat_name']) self.catvalue = Entry(self.master, textvariable=self.catVar, width=28, justify='left') self.catvalue.place(relx=0.02, rely=0.295, anchor="w") self.b7 = Button(self.master, text="View Timeline", command=self.maketimeline) self.b7.place(relx=0.6, rely=0.96, anchor="w") self.b3 = Button(self.master, text=" Quit ", command=self.quit) self.b3.place(relx=0.2, rely=0.96, anchor="w") self.b4 = Button(self.master, text=" Display ", command=self.makefootprints) self.b4.place(relx=0.8, rely=0.96, anchor="w") self.outdirVar = StringVar() self.outdirVar.set(self.config['out_dir']) self.outdirvalue = Entry(self.master, textvariable=self.outdirVar, width=40, justify='left') self.outdirvalue.place(relx=0.02, rely=0.219, anchor="w") #self.laboutdir = Label(self.master, text="Output directory") #self.laboutdir.place(relx=0.02, rely=0.25, anchor="w") self.colshortVar = StringVar() self.colshortVar.set(self.config['color_short']) self.colshort = OptionMenu(self.master, self.colshortVar, 'Green', 'Cyan', 'Blue', 'Yellow', 'Red') self.colshort.config(width=9) self.colshort.place(relx=0.49, rely=0.61, anchor="w") self.collongVar = StringVar() self.collongVar.set(self.config['color_long']) self.collong = OptionMenu(self.master, self.collongVar, 'Blue', 'Cyan', 'Green', 'Yellow', 'Red') self.collong.config(width=9) self.collong.place(relx=0.49, rely=0.65, anchor="w") self.labcmap = Label(self.master, text="Colour Map") self.labcmap.place(relx=0.65, rely=0.18, anchor="w") self.ds9cmapVar = StringVar() self.ds9cmapVar.set(self.config['cmap']) self.ds9cmap = OptionMenu(self.master, self.ds9cmapVar, 'grey', 'red', 'green', 'blue', 'heat') self.ds9cmap.place(relx=0.80, rely=0.18, anchor="w") self.ds9cmap.config(width=10) self.labscale = Label(self.master, text="Scale") self.labscale.place(relx=0.65, rely=0.21, anchor="w") self.ds9scaleVar = StringVar() self.ds9scaleVar.set(self.config['scale']) self.ds9scale = OptionMenu(self.master, self.ds9scaleVar, 'log', 'linear', 'power', 'sqrt', 'zscale', 'minmax') self.ds9scale.place(relx=0.80, rely=0.21, anchor="w") self.ds9scale.config(width=10) self.ds9limmin = Label(self.master, text="Low") self.ds9limmin.place(relx=0.65, rely=0.24, anchor="w") self.ds9limminVar = StringVar() self.ds9limminVar.set(self.config['lim_min']) self.ds9limmin = Entry(self.master, textvariable=self.ds9limminVar) self.ds9limmin.place(relx=0.80, rely=0.24, anchor="w") self.ds9limmin.config(width=10) self.ds9limmax = Label(self.master, text="High") self.ds9limmax.place(relx=0.65, rely=0.27, anchor="w") self.ds9limmaxVar = StringVar() self.ds9limmaxVar.set(self.config['lim_max']) self.ds9limmax = Entry(self.master, textvariable=self.ds9limmaxVar) self.ds9limmax.place(relx=0.80, rely=0.27, anchor="w") self.ds9limmax.config(width=10) def quit(self): self.config['fits_name'] = self.fileVar.get() self.config['cat_name'] = self.catVar.get() self.config['plot_long'] = self.plotlongVar.get() self.config['plot_short'] = self.plotshortVar.get() self.config['plot_msa'] = self.plotmsaVar.get() self.config['plot_src'] = self.plotsourcesVar.get() self.config['ra_nircam'] = self.ranrcmVar.get() self.config['dec_nircam'] = self.decnrcmVar.get() self.config['theta_nircam'] = float(self.thnrcmVar.get()) self.config['dither'] = self.ditherVar.get() self.config['ra_nirspec'] = self.ramsaVar.get() self.config['dec_nirspec'] = self.decmsaVar.get() self.config['theta_nirspec'] = float(self.thmsaVar.get()) self.config['mosaic'] = self.mosaicVar.get() self.config['off_h'] = float(self.offhorVar.get()) self.config['off_v'] = float(self.offverVar.get()) self.config['color_msa'] = self.colmsaVar.get() self.config['color_short'] = self.colshortVar.get() self.config['color_long'] = self.collongVar.get() self.config['cmap'] = self.ds9cmapVar.get() self.config['lim_min'] = float(self.ds9limminVar.get()) self.config['lim_max'] = float(self.ds9limmaxVar.get()) self.config['scale'] = self.ds9scaleVar.get() self.config.commit() self.master.quit() def makefootprints(self): if self.ptVar.get() == 'footprints': #print(self.catVar.get()) footprints(self.fileVar.get(), self.catVar.get(), self.plotlongVar.get(), self.plotshortVar.get(), self.plotmsaVar.get(), self.plotsourcesVar.get(), self.ranrcmVar.get(), self.decnrcmVar.get(), float(self.thnrcmVar.get()), self.ditherVar.get(), self.ramsaVar.get(), self.decmsaVar.get(), float(self.thmsaVar.get()), self.mosaicVar.get(), self.offhorVar.get(), self.offverVar.get(), self.colmsaVar.get(), self.colshortVar.get(), self.collongVar.get(), self.ds9cmapVar.get(), self.ds9limminVar.get(), self.ds9limmaxVar.get(), self.ds9scaleVar.get(), self.outdirVar.get()) #self.readfitsimageVar.get()) def readcataloguename(self): Tk().withdraw( ) # we don't want a full GUI, so keep the root window from appearing # show an "Open" dialog box and return the path to the selected file filename = askopenfilename(initialdir=os.path.abspath(os.curdir), title='Select RADEC file', filetypes=(('RADEC files', '*.radec'), ('all files', '*.*'))) #print(filename) self.catVar.set(filename) catvalue = Entry(self.master, textvariable=self.catVar, width=28, justify='right') catvalue.place(relx=0.02, rely=0.295, anchor="w") def readfitsfilename(self): #readfitsimage =True # set variable to read new image Tk().withdraw( ) # we don't want a full GUI, so keep the root window from appearing # show an "Open" dialog box and return the path to the selected file filename = askopenfilename(initialdir=os.path.abspath(os.curdir), title='Select FITS file', filetypes=(('FITS files', '*.fits'), ('all files', '*.*'))) #print(filename) self.fileVar.set(filename) filevalue = Entry(self.master, textvariable=self.fileVar, width=40, justify='right') filevalue.place(relx=0.02, rely=0.15, anchor="w") def maketimeline(self): #print(self.ramsaVar.get()) plottimeline(self.ramsaVar.get(), self.decmsaVar.get(), float(self.thmsaVar.get()), self.outdirVar.get())
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("IAF CALC 0.01") self.pack(fill=BOTH, expand=1) self.configure(background='white') frameTOP = Frame(self) frameTOP.config(bg="white") frameTOP.pack(side=TOP) frameFILES = Frame(frameTOP) frameFILES.pack(side=LEFT, padx=10) # --- BUTTON FOR FILE 1 --- # frameF1 = LabelFrame(frameFILES, text="Eyes open file:", relief=FLAT, borderwidth=1, background="white") frameF1.pack(fill=X, expand=1) self.nameF1 = Entry(frameF1, width=50) self.nameF1.config(bg="lightgray") self.nameF1.pack(side=LEFT) self.nameF1.delete(0, END) self.nameF1.insert(0, "") self.buttonLoadFile1 = Button(frameF1, text="...", command=self.askOpenFile1) self.buttonLoadFile1.pack(side=LEFT, padx=5, pady=5) # ----------------------- # # --- BUTTON FOR FILE 2 --- # frameF2 = LabelFrame(frameFILES, text="Eyes closed file:", relief=FLAT, borderwidth=1, background="white") frameF2.pack(fill=X, expand=1) self.nameF2 = Entry(frameF2, width=50) self.nameF2.config(bg="lightgray") self.nameF2.pack(side=LEFT) self.nameF2.delete(0, END) self.nameF2.insert(0, "") self.buttonLoadFile2 = Button(frameF2, text="...", command=self.askOpenFile2) self.buttonLoadFile2.pack(side=LEFT, padx=5, pady=5) # ----------------------- # # --- BUTTON FOR FILE OUTPUT --- # frameO = LabelFrame(frameFILES, text="Output directory:", relief=FLAT, borderwidth=1, background="white") frameO.pack(fill=X, expand=1) self.nameO = Entry(frameO, width=50) self.nameO.config(bg="lightgray") self.nameO.pack(side=LEFT) self.nameO.delete(0, END) self.nameO.insert(0, "") self.buttonSelectOutput = Button(frameO, text="...", command=self.askOutputDirectory) self.buttonSelectOutput.pack(side=LEFT, padx=5, pady=5) # -------------------------------# # self.pack() # self.pack(fill=Y, expand=1) # ---------- PSD PARAMETER SELECTION ---------- # framePARAM = Frame(frameTOP) framePARAM.config(bg="white") framePARAM.pack(side=LEFT, fill=X) frame = LabelFrame(framePARAM, text="PSD Parameters", relief=RIDGE, borderwidth=1, background="white") frame.pack(fill=BOTH, expand=1, side=TOP) wFs = Label(frame, text="Fs:", bg="white") wFs.pack(side=LEFT) self.inputFs = Entry(frame, width=5) self.inputFs.pack(side=LEFT, padx=5) self.inputFs.delete(0, END) self.inputFs.insert(0, "500") wWS = Label(frame, text="Window size:", bg="white") wWS.pack(side=LEFT) self.inputWinSize = Entry(frame, width=5) self.inputWinSize.pack(side=LEFT, padx=5) self.inputWinSize.delete(0, END) self.inputWinSize.insert(0, "1024") wOL = Label(frame, text="Overlap:", bg="white") wOL.pack(side=LEFT) self.inputOverlap = Entry(frame, width=5) self.inputOverlap.pack(side=LEFT, padx=5) self.inputOverlap.delete(0, END) self.inputOverlap.insert(0, "512") wWT = Label(frame, text="Window function:", bg="white") wWT.pack(side=LEFT) variable = StringVar(frame) variable.set("Hamming") # default value self.inputWinType = OptionMenu(frame, variable, "Hamming", "Bartlett", "Blackman", "Hanning", "None") self.inputWinType.config(bg="white", width=10) self.inputWinType.pack(side=LEFT) buttonRun = Button(frame, text="GO!", command=self.goTime) buttonRun.pack(side=RIGHT) # Channel selector frameCh = LabelFrame(framePARAM, text="Channels", relief=RIDGE, borderwidth=1, background="white") frameCh.pack(fill=BOTH, expand=1, side=TOP) self.EOch1 = IntVar() self.inputEOch1 = Checkbutton(frameCh, text="1", variable=self.EOch1, bg="white") self.inputEOch1.pack(side=LEFT) self.EOch2 = IntVar() self.inputEOch2 = Checkbutton(frameCh, text="2", variable=self.EOch2, bg="white") self.inputEOch2.pack(side=LEFT) self.EOch3 = IntVar() self.inputEOch3 = Checkbutton(frameCh, text="3", variable=self.EOch3, bg="white") self.inputEOch3.pack(side=LEFT) self.EOch4 = IntVar() self.inputEOch4 = Checkbutton(frameCh, text="4", variable=self.EOch4, bg="white") self.inputEOch4.pack(side=LEFT) self.EOch5 = IntVar() self.inputEOch5 = Checkbutton(frameCh, text="5", variable=self.EOch5, bg="white") self.inputEOch5.pack(side=LEFT) self.EOch6 = IntVar() self.inputEOch6 = Checkbutton(frameCh, text="6", variable=self.EOch6, bg="white") self.inputEOch6.pack(side=LEFT) self.EOch7 = IntVar() self.inputEOch7 = Checkbutton(frameCh, text="7", variable=self.EOch7, bg="white") self.inputEOch7.pack(side=LEFT) self.EOch8 = IntVar() self.inputEOch8 = Checkbutton(frameCh, text="8", variable=self.EOch8, bg="white") self.inputEOch8.pack(side=LEFT) # IAF Calculation parameters frameIAF = LabelFrame(framePARAM, text="IAF Search Limits", relief=RIDGE, borderwidth=1, background="white") frameIAF.pack(fill=BOTH, expand=1, side=TOP) labelLowBound = Label(frameIAF, text="Lower limit (Hz):", bg="white") labelLowBound.pack(side=LEFT) self.inputLowBound = Entry(frameIAF, width=5) self.inputLowBound.pack(side=LEFT, padx=5) self.inputLowBound.delete(0, END) self.inputLowBound.insert(0, "7") labelUpBound = Label(frameIAF, text="Upper limit (Hz):", bg="white") labelUpBound.pack(side=LEFT) self.inputUpBound = Entry(frameIAF, width=5) self.inputUpBound.pack(side=LEFT, padx=5) self.inputUpBound.delete(0, END) self.inputUpBound.insert(0, "14") self.GaussVar = IntVar() self.inputGauss = Checkbutton(frameIAF, text="Gauss", variable=self.GaussVar, bg="white") self.inputGauss.pack(side=LEFT) buttonRun = Button(frameIAF, text="IAF!", command=self.calculateIAF) buttonRun.pack(side=RIGHT) self.pack() # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # END OF TOP FRAME # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # my variables self.chSelect = 0 self.chOther = 0 self.P1 = ndarray(1) self.f1 = ndarray(1) self.P2 = ndarray(1) self.f2 = ndarray(1) self.filename1 = "..." self.filename2 = "..." self.IAF = 10 self.doGauss = True # FIGURE STUFF !!! self.Pmax = 0 self.Pmin = 0 self.Dmax = 0 self.Dmin = 0 frameBOTTOM = Frame(self) frameBOTTOM.config(bg="white") frameBOTTOM.pack(side=BOTTOM, pady=10) frameFig = LabelFrame(frameBOTTOM, text="Spectrum", relief=RIDGE, borderwidth=1, background="white") frameFig.pack(fill=X, expand=1, side=LEFT, padx=10) self.fig1 = matplotlib.figure.Figure(figsize=(7, 3), dpi=100) #,frameon=False) self.fig1.set_facecolor('white') self.fig = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg( self.fig1, master=frameFig) self.a1 = self.fig1.add_subplot(121) self.a2 = self.fig1.add_subplot(122) self.fig.show() self.fig.get_tk_widget().pack(side=BOTTOM) frameConfig = LabelFrame(frameBOTTOM, text="Filter configuration", relief=RAISED, borderwidth=1, background="white") frameConfig.pack(fill=BOTH, expand=1, side=RIGHT, padx=10) frameIAF = LabelFrame(frameConfig, text="Individual Alpha Frequency (IAF)") frameIAF.config(bg="white") frameIAF.pack(expand=1, side=TOP, padx=10) self.inputIAF = Entry(frameIAF, width=5) self.inputIAF.pack(side=LEFT, padx=5) self.inputIAF.delete(0, END) self.inputIAF.insert(0, "0") self.buttonWriteDefault = Button(frameIAF, text="Update Filters", command=self.updateFilters) self.buttonWriteDefault.pack(side=LEFT, padx=5, pady=5) frameFilters = LabelFrame(frameConfig, text="Filters", relief=RAISED, borderwidth=1, background="white") frameFilters.pack(fill=X, expand=1, side=TOP) # THETA FRAME frameTheta = LabelFrame(frameFilters, text="Theta", relief=RAISED, borderwidth=1, background="white") frameTheta.pack(expand=1, side=TOP, pady=5, padx=5) self.inputThetaLow = Entry(frameTheta, width=8) self.inputThetaLow.pack(side=LEFT, padx=5, pady=5) self.inputThetaLow.delete(0, END) self.inputThetaLow.insert(0, "0") self.inputThetaHigh = Entry(frameTheta, width=8) self.inputThetaHigh.pack(side=LEFT, padx=5, pady=5) self.inputThetaHigh.delete(0, END) self.inputThetaHigh.insert(0, "0") # BETA FRAME frameBeta = LabelFrame(frameFilters, text="Beta", relief=RAISED, borderwidth=1, background="white") frameBeta.pack(expand=1, side=TOP, pady=5, padx=5) self.inputBetaLow = Entry(frameBeta, width=8) self.inputBetaLow.pack(side=LEFT, padx=5, pady=5) self.inputBetaLow.delete(0, END) self.inputBetaLow.insert(0, "0") self.inputBetaHigh = Entry(frameBeta, width=8) self.inputBetaHigh.pack(side=LEFT, padx=5, pady=5) self.inputBetaHigh.delete(0, END) self.inputBetaHigh.insert(0, "0") # SMR FRAME frameSMR = LabelFrame(frameFilters, text="SMR", relief=RAISED, borderwidth=1, background="white") frameSMR.pack(expand=1, side=TOP, pady=5, padx=5) self.inputSMRLow = Entry(frameSMR, width=8) self.inputSMRLow.pack(side=LEFT, padx=5, pady=5) self.inputSMRLow.delete(0, END) self.inputSMRLow.insert(0, "0") self.inputSMRHigh = Entry(frameSMR, width=8) self.inputSMRHigh.pack(side=LEFT, padx=5, pady=5) self.inputSMRHigh.delete(0, END) self.inputSMRHigh.insert(0, "0") frameButtons = LabelFrame(frameConfig, text="Commands", relief=RAISED, borderwidth=1, background="white") frameButtons.pack(expand=1, side=BOTTOM) self.buttonWriteConfig = Button(frameButtons, text="Write Filters", command=self.writeFilters) self.buttonWriteConfig.pack(side=LEFT, padx=5, pady=5) self.buttonWriteDefault = Button(frameButtons, text="Reset to Defaults", command=self.resetIAFtoDefault) self.buttonWriteDefault.pack(side=LEFT, padx=5, pady=5) # self.buttonVisualize = Button(frameButtons, text="VIS",command=self.resetIAFtoDefault) # self.buttonVisualize.pack(side=LEFT,padx=5,pady=5) self.buttonPrintFig = Button(frameButtons, text="Print Figure", command=self.printFigureToFile) self.buttonPrintFig.pack(side=LEFT, padx=5, pady=5) def getChannelList(self): # Initialize self.chSelect = asarray([]) self.chOther = asarray([]) if self.EOch1.get(): self.chSelect = append(self.chSelect, 0) else: self.chOther = append(self.chOther, 0) if self.EOch2.get(): self.chSelect = append(self.chSelect, 1) else: self.chOther = append(self.chOther, 1) if self.EOch3.get(): self.chSelect = append(self.chSelect, 2) else: self.chOther = append(self.chOther, 2) if self.EOch4.get(): self.chSelect = append(self.chSelect, 3) else: self.chOther = append(self.chOther, 3) if self.EOch5.get(): self.chSelect = append(self.chSelect, 4) else: self.chOther = append(self.chOther, 4) if self.EOch6.get(): self.chSelect = append(self.chSelect, 5) else: self.chOther = append(self.chOther, 5) if self.EOch7.get(): self.chSelect = append(self.chSelect, 6) else: self.chOther = append(self.chOther, 6) if self.EOch8.get(): self.chSelect = append(self.chSelect, 7) else: self.chOther = append(self.chOther, 7) def updateFilters(self): # SET THETA self.inputThetaLow.delete(0, END) self.inputThetaLow.insert(0, "%.2f" % (float(self.inputIAF.get()) * 0.4)) self.inputThetaHigh.delete(0, END) self.inputThetaHigh.insert(0, "%.2f" % (float(self.inputIAF.get()) * 0.6)) # SET BETA self.inputBetaLow.delete(0, END) self.inputBetaLow.insert(0, "%.2f" % (float(self.inputIAF.get()) * 1.2)) self.inputBetaHigh.delete(0, END) self.inputBetaHigh.insert(0, 25) # SET SMR self.inputSMRLow.delete(0, END) self.inputSMRLow.insert(0, "%.2f" % (float(self.inputIAF.get()) * 1.2)) self.inputSMRHigh.delete(0, END) self.inputSMRHigh.insert(0, "%.2f" % (float(self.inputIAF.get()) * 1.5)) def resetIAFtoDefault(self): self.inputIAF.delete(0, END) self.inputIAF.insert(0, "10") self.updateFilters() def calculateIAF(self): self.getChannelList() print "LOLOL calculating IAF" m1 = 20 * log10(mean(self.P1[self.chSelect.astype(int), :], axis=0)) m2 = 20 * log10(mean(self.P2[self.chSelect.astype(int), :], axis=0)) d = m2 - m1 if self.GaussVar.get(): # print d.shape # print gauss_signal.shape d_gauss = d[bitwise_and(self.f1 > int(self.inputLowBound.get()), self.f1 < int(self.inputUpBound.get()))] gauss_signal = signal.gaussian(d_gauss.shape[0], 1) d_gauss = d_gauss * gauss_signal d[bitwise_and(self.f1 > int(self.inputLowBound.get()), self.f1 < int(self.inputUpBound.get()))] = d_gauss self.a2 = plotIAF(self.f1, d, "purple", self.a2, "IAF") # Get dat IAF val d_search = d[bitwise_and(self.f1 > int(self.inputLowBound.get()), self.f1 < int(self.inputUpBound.get()))] f_search = self.f1[bitwise_and(self.f1 > int(self.inputLowBound.get()), self.f1 < int(self.inputUpBound.get()))] f_idx = argmax(d_search) print f_search[f_idx] self.inputIAF.delete(0, END) self.inputIAF.insert(0, "%.2f" % (f_search[f_idx])) # Autoscale self.Dmin = amin(d_search) - 2 self.Dmax = amax(d_search) + 2 self.a2.set_ylim( self.Dmin, self.Dmax) # little modifier to differentiate the peak # IAF position self.a2.vlines(f_search[f_idx], self.Dmin, self.Dmax, color="Cyan") # Search limits self.a2.vlines(int(self.inputLowBound.get()), self.Dmin, self.Dmax, linestyles=":", linewidth=0.25) self.a2.vlines(int(self.inputUpBound.get()), self.Dmin, self.Dmax, linestyles=":", linewidth=0.25) self.fig.show() # Set filter configs def goTime(self): print "ITS GO TIME!" print self.filename1 print self.filename2 self.getChannelList() print self.chSelect print self.chOther self.f1, self.P1 = computeSpectrum(self.filename1, int(self.inputFs.get()), int(self.inputWinSize.get()), int(self.inputOverlap.get())) self.f2, self.P2 = computeSpectrum(self.filename2, int(self.inputFs.get()), int(self.inputWinSize.get()), int(self.inputOverlap.get())) # Plotting time self.a1.cla() self.a1 = plotSpectrum(self.f1, self.P1, "blue", self.a1, "Power spectrum", self.chSelect, self.chOther) self.a1 = plotSpectrum(self.f2, self.P2, "red", self.a1, "Power spectrum", self.chSelect, self.chOther) # Trying to autoscale P1_ROI = 20 * log10(self.P1[:, bitwise_and(self.f1 > 1, self.f1 < 20)]) P2_ROI = 20 * log10(self.P2[:, bitwise_and(self.f2 > 1, self.f2 < 20)]) self.Pmax = amax([amax(P1_ROI), amax(P2_ROI)]) self.Pmin = amin([(amin(P1_ROI)), amin(P2_ROI)]) self.a1.set_ylim(self.Pmin, self.Pmax) # Autoscale success :> self.fig.show() def writeFilters(self): f_theta = open(self.nameO.get() + "/theta.f", "w") f_theta.write( "<OpenViBE-SettingsOverride>\n\t<SettingValue>Butterworth</SettingValue>\n\t<SettingValue>Band pass</SettingValue>\n\t<SettingValue>4</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>0.5</SettingValue>\n</OpenViBE-SettingsOverride>" .format(float(self.inputThetaLow.get()), float(self.inputThetaHigh.get()))) f_theta.close() f_beta = open(self.nameO.get() + "/beta.f", "w") f_beta.write( "<OpenViBE-SettingsOverride>\n\t<SettingValue>Butterworth</SettingValue>\n\t<SettingValue>Band pass</SettingValue>\n\t<SettingValue>4</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>0.5</SettingValue>\n</OpenViBE-SettingsOverride>" .format(float(self.inputBetaLow.get()), float(self.inputBetaHigh.get()))) f_beta.close() f_smr = open(self.nameO.get() + "/smr.f", "w") f_smr.write( "<OpenViBE-SettingsOverride>\n\t<SettingValue>Butterworth</SettingValue>\n\t<SettingValue>Band pass</SettingValue>\n\t<SettingValue>4</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>{:.2f}</SettingValue>\n\t<SettingValue>0.5</SettingValue>\n</OpenViBE-SettingsOverride>" .format(float(self.inputSMRLow.get()), float(self.inputSMRHigh.get()))) f_smr.close() def printFigureToFile(self): self.fig1.savefig(self.nameO.get() + "/IAF_spectrum.png") def askOpenFile1(self): ftypes = [('asdadfh', '*.txt'), ('All files', '*')] dlg = tkFileDialog.Open(self, filetypes=ftypes) self.filename1 = dlg.show() self.nameF1.delete(0, END) self.nameF1.insert(0, self.filename1) def askOpenFile2(self): ftypes = [('asdadfh', '*.txt'), ('All files', '*')] dlg = tkFileDialog.Open(self, filetypes=ftypes) self.filename2 = dlg.show() self.nameF2.delete(0, END) self.nameF2.insert(0, self.filename2) def askOutputDirectory(self): dlg = tkFileDialog.askdirectory() #self.outputdir = dlg.show() self.outputdir = dlg self.nameO.delete(0, END) self.nameO.insert(0, self.outputdir)
def showOne(self): Ventana2 = Toplevel(self.master) try: Ventana2.configure(height=210, width=428, bg="#FFFFFF") Ventana2.resizable(1, 1) Ventana2.title("Buscar") frameAux = Frame(Ventana2, height=210, width=428, bg="#4a4a4a") frameAux.place(x=0, y=0) if sys.platform.startswith('win32'): r = "image\\BuscarBosch.png" ruta = "image\\Back.png" ruta2 = "image\\SearchOne.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): r = "image/BuscarBosch.png" ruta = "image/Back.png" ruta2 = "image/SearchOne.png" l = Image.open(r) re = ImageTk.PhotoImage(l) labelFont = Label(frameAux, image=re, borderwidth=0) labelFont.image = re labelFont.place(x=0, y=0) labelText1 = Label(frameAux, height=1, width=24, bg="#4a4a4a", text="Serie", fg="#FFFFFF", anchor=W) labelText1.config(font=("Tahoma", 11)) labelText1.place(x=15, y=25) labelText11 = Label(frameAux, height=1, width=24, bg="#4a4a4a", fg="#FFFFFF", anchor=W) labelText11.config(font=("Tahoma", 11)) labelText11.place(x=210, y=25) labelText2 = Label(frameAux, height=1, width=24, bg="#696969", text="Gravedad", fg="#FFFFFF", anchor=W) labelText2.config(font=("Tahoma", 11)) labelText2.place(x=15, y=50) labelText22 = Label(frameAux, height=1, width=24, bg="#696969", fg="#FFFFFF", anchor=W) labelText22.config(font=("Tahoma", 11)) labelText22.place(x=210, y=50) labelText3 = Label(frameAux, height=1, width=24, bg="#4a4a4a", text="Fecha", fg="#FFFFFF", anchor=W) labelText3.config(font=("Tahoma", 11)) labelText3.place(x=15, y=75) labelText33 = Label(frameAux, height=1, width=24, bg="#4a4a4a", fg="#FFFFFF", anchor=W) labelText33.config(font=("Tahoma", 11)) labelText33.place(x=210, y=75) labell = Label(frameAux, height=1, width=25, bg="#4a4a4a", text="Ingresa el numero de serie", fg="#FFFFFF", anchor=W) #labell.place(x=15,y=135) labell.config(font=("Tahoma", 11)) listbox3 = Entry(frameAux, width=24, justify=RIGHT, bg="#696969", fg="#FFFFFF", borderwidth=0) listbox3.place(x=210, y=125) listbox3.config(font=("Tahoma", 11)) load = Image.open(ruta) render = ImageTk.PhotoImage(load) backbutton = Button( frameAux, image=render, bg="#8d8e8c", borderwidth=0, activebackground="#696969", command=lambda: self.Switch(self.master, Ventana2)) backbutton.image = render backbutton.place(x=245, y=155) load2 = Image.open(ruta2) render2 = ImageTk.PhotoImage(load2) searchButton = Button( frameAux, image=render2, bg="#8d8e8c", borderwidth=0, activebackground="#c4c4c4", command=lambda: self.load1(listbox3, labelText11, labelText22, labelText33)) searchButton.image = render2 searchButton.place(x=324, y=155) except Exception as e: print(e) Ventana2.destroy() self.Error("Se produjo un error al cargar")
class OSCEditor(tkSimpleDialog.Dialog): def __init__(self, parent, options_file, req_unit_type, title=None, ): self.options_file=options_file self.req_unit_type=req_unit_type # init the super class tkSimpleDialog.Dialog.__init__(self, parent, title) def body(self, master): self.result=False config=ConfigParser.ConfigParser() config.read(self.options_file) if self.req_unit_type=='remote': Label(master, text="").grid(row=10, sticky=W) Label(master, text="Pi Presents Data Home:").grid(row=11, sticky=W) self.e_home = Entry(master,width=80) self.e_home.grid(row=12) self.e_home.insert(0,config.get('paths','home',0)) Label(master, text="").grid(row=20, sticky=W) Label(master, text="Offset for Current Profiles:").grid(row=21, sticky=W) self.e_offset = Entry(master,width=80) self.e_offset.grid(row=22) self.e_offset.insert(0,config.get('paths','offset',0)) Label(master, text="").grid(row=25, sticky=W) Label(master, text="Type of this Unit:").grid(row=26, sticky=W) self.e_type = Entry(master,width=80) self.e_type.grid(row=27) self.e_type.insert(0,self.req_unit_type) self.e_type.config(state="readonly",bg='dark grey') Label(master, text="").grid(row=30, sticky=W) Label(master, text="Name of This Unit:").grid(row=31, sticky=W) self.e_remote_name = Entry(master,width=80) self.e_remote_name.grid(row=32) self.e_remote_name.insert(0,config.get('this-unit','name',0)) Label(master, text="").grid(row=40, sticky=W) Label(master, text="IP of This Unit:").grid(row=41, sticky=W) self.e_remote_ip = Entry(master,width=80) self.e_remote_ip.grid(row=42) self.e_remote_ip.insert(0,config.get('this-unit','ip',0)) Label(master, text="").grid(row=50, sticky=W) Label(master, text="Listening Port of This Unit:").grid(row=51, sticky=W) self.e_remote_port = Entry(master,width=80) self.e_remote_port.grid(row=52) self.e_remote_port.insert(0,config.get('this-unit','port',0)) if self.req_unit_type in ('master','remote','master+slave'): Label(master, text="").grid(row=60, sticky=W) Label(master, text="Controlled Units (not used):").grid(row=61, sticky=W) self.e_controlled_units = Entry(master,width=80) self.e_controlled_units.grid(row=62) self.e_controlled_units.insert(0,config.get('this-unit','controlled-units',0)) Label(master, text="").grid(row=70, sticky=W) Label(master, text="Name of Controlled Unit:").grid(row=71, sticky=W) self.e_pipresents_unit = Entry(master,width=80) self.e_pipresents_unit.grid(row=72) self.e_pipresents_unit.insert(0,config.get('controlled-unit-1','controlled-unit-name',0)) Label(master, text="").grid(row=80, sticky=W) Label(master, text="IP of Controlled Unit:").grid(row=81, sticky=W) self.e_pipresents_ip = Entry(master,width=80) self.e_pipresents_ip.grid(row=82) self.e_pipresents_ip.insert(0,config.get('controlled-unit-1','controlled-unit-ip',0)) Label(master, text="").grid(row=90, sticky=W) Label(master, text="Listening Port of Controlled Unit:").grid(row=91, sticky=W) self.e_pipresents_port = Entry(master,width=80) self.e_pipresents_port.grid(row=92) self.e_pipresents_port.insert(0,config.get('controlled-unit-1','controlled-unit-port',0)) if self.req_unit_type in('slave','master+slave'): Label(master, text="").grid(row=100, sticky=W) Label(master, text="Controlled By Unit:").grid(row=101, sticky=W) self.e_controlled_by_unit = Entry(master,width=80) self.e_controlled_by_unit.grid(row=102) self.e_controlled_by_unit.insert(0,config.get('this-unit','controlled-by-name',0)) Label(master, text="").grid(row=110, sticky=W) Label(master, text="IP of Controlled By Unit:").grid(row=111, sticky=W) self.e_controlled_by_ip = Entry(master,width=80) self.e_controlled_by_ip.grid(row=112) self.e_controlled_by_ip.insert(0,config.get('this-unit','controlled-by-ip',0)) Label(master, text="").grid(row=120, sticky=W) Label(master, text="Listening Port of Controlled By Unit:").grid(row=121, sticky=W) self.e_controlled_by_port = Entry(master,width=80) self.e_controlled_by_port.grid(row=122) self.e_controlled_by_port.insert(0,config.get('this-unit','controlled-by-port',0)) return None # no initial focus def validate(self): if self.req_unit_type == 'remote': if self.e_home.get().strip() != '': if os.path.exists(self.e_home.get()) is False: tkMessageBox.showwarning("Pi Presents Remote","Data Home not found") return 0 if self.e_offset.get().strip() != '': if os.path.exists(self.e_home.get()+os.sep+'pp_profiles'+self.e_offset.get()) is False: tkMessageBox.showwarning("Pi Presents Remote","Current Profles directory not found") return 0 return 1 def apply(self): self.save_options() self.result=True def save_options(self): """ save the output of the options edit dialog to file""" config=ConfigParser.ConfigParser() config.add_section('paths') if self.req_unit_type == 'remote': config.set('paths','home',self.e_home.get()) config.set('paths','offset',self.e_offset.get()) else: config.set('paths','home','') config.set('paths','offset','') config.add_section('this-unit') config.set('this-unit','name',self.e_remote_name.get()) config.set('this-unit','ip',self.e_remote_ip.get()) config.set('this-unit','port',self.e_remote_port.get()) config.set('this-unit','type',self.req_unit_type) config.add_section('controlled-unit-1') if self.req_unit_type in ('master','remote','master+slave'): config.set('this-unit','controlled-units',self.e_controlled_units.get()) config.set('controlled-unit-1','controlled-unit-name',self.e_pipresents_unit.get()) config.set('controlled-unit-1','controlled-unit-ip',self.e_pipresents_ip.get()) config.set('controlled-unit-1','controlled-unit-port',self.e_pipresents_port.get()) else: config.set('this-unit','controlled-units','') config.set('controlled-unit-1','controlled-unit-name','') config.set('controlled-unit-1','controlled-unit-ip','') config.set('controlled-unit-1','controlled-unit-port','') if self.req_unit_type in ('slave','master+slave'): config.set('this-unit','controlled-by-name',self.e_controlled_by_unit.get()) config.set('this-unit','controlled-by-ip',self.e_controlled_by_ip.get()) config.set('this-unit','controlled-by-port',self.e_controlled_by_port.get()) else: config.set('this-unit','controlled-by-name','') config.set('this-unit','controlled-by-ip','') config.set('this-unit','controlled-by-port','') with open(self.options_file, 'wb') as optionsfile: config.write(optionsfile)
class img: def __init__(self): self.cropList = [] self.origList = [] self.origIndex = -1 self.cropIndex = 0 self.imageModified = False # self.mode = imageType.original self.mode = mode.orig self.index = -1 self.numOrig = 0 self.pt0 = 0, 0 self.pt1 = 0, 0 self.pts = [] self.imgW = imgW self.imgH = imgH self.orienVals = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] self.shapeVals = [ "circle", "semicircle", "quarter_circle", "triangle", "square", "rectangle", "trapezoid", "pentagon", "hexagon", "heptagon", "octagon", "star", "cross" ] self.colorVals = [ "white", "black", "gray", "red", "blue", "green", "yellow", "purple", "brown", "orange" ] # null obj self.currImgObj = img_obj(self, nullImg) self.import_images() #Set up GUI self.window = tk.Tk() #Makes main window self.setup_GUI() def import_images(self): for filename in glob.glob('SampleImages/*.jpg'): img = cv2.imread(filename) img = cv2.resize(img, (imgW, imgH)) image_obj = img_obj(self, img) self.origList.append(image_obj) self.numOrig = self.numOrig + 1 print "image imported", filename if self.numOrig > 0 and self.origIndex < 0: self.origIndex = 0 self.update_curr_img_obj() def import_images_alt(self): # ******************************************************* # # uncomment this line to clear the list of images on open # # ******************************************************* # self.origList = [] path = tkFileDialog.askdirectory() if os.path.exists(path): path += '/*.jpg' for filename in glob.glob(path): img = cv2.imread(filename) img = cv2.resize(img, (imgW, imgH)) image_obj = img_obj(self, img) self.origList.append(image_obj) self.numOrig = self.numOrig + 1 print "image imported", filename if self.numOrig > 0 and self.origIndex < 0: self.origIndex = 0 self.update_curr_img_obj() else: print "path does not exist, opening default dir" self.import_images() def setup_GUI(self): self.window.wm_title("Image Manipulation Genie (IMG)") self.window.config(background="#FFFFFF") #Graphics window self.imageFrame = tk.Frame(self.window, width=imgW, height=imgH) self.imageFrame.grid(row=0, column=0, padx=10, pady=2) self.lmain = tk.Label(self.imageFrame) self.lmain.grid(row=0, column=0) self.image_loop() # display image function # bind the following three to the main loop self.window.bind_all( '<KeyPress>', lambda event: key_press(event, self, self.currImgObj)) self.window.bind_all( '<ButtonPress-1>', lambda event: mouse_press(event, self, self.currImgObj)) self.window.bind_all( '<ButtonRelease-1>', lambda event: mouse_release(event, self, self.currImgObj)) # run the main loop of tkinter self.window.mainloop() #Starts GUI def image_loop(self): self.show_image() #self.lmain.after(100, lambda: self.lmain.focus_force()) self.lmain.after(250, self.image_loop) def show_image(self): self.update_curr_img_obj() liveImage = self.currImgObj.get_image_live() cv2image = cv2.cvtColor(liveImage, cv2.COLOR_BGR2RGBA) tempImage = Image.fromarray(cv2image) imgtk = ImageTk.PhotoImage(image=tempImage) self.lmain.imgtk = imgtk self.lmain.configure(image=imgtk) def setup_mode(self): if self.mode == mode.orig: self.sliderFrame.grid_forget() self.window.geometry("") else: #Slider window (slider controls stage position) self.sliderFrame = tk.Frame(self.window, width=800, height=400) self.sliderFrame.grid(row=1, column=0, padx=10, pady=2) self.sliderFrame.config(background="#FFFFFF") Label(self.sliderFrame, text="Type".rjust(20), font=(fontType, fontLabelSize)).grid(row=1, column=1) Label(self.sliderFrame, text="Latitude".rjust(20), font=(fontType, fontLabelSize)).grid(row=2, column=1) Label(self.sliderFrame, text="Longitude".rjust(20), font=(fontType, fontLabelSize)).grid(row=3, column=1) Label(self.sliderFrame, text="Orientation".rjust(20), font=(fontType, fontLabelSize)).grid(row=4, column=1) Label(self.sliderFrame, text="Shape".rjust(20), font=(fontType, fontLabelSize)).grid(row=5, column=1) Label(self.sliderFrame, text="Background Color".rjust(20), font=(fontType, fontLabelSize)).grid(row=6, column=1) Label(self.sliderFrame, text="Alphanumeric".rjust(20), font=(fontType, fontLabelSize)).grid(row=7, column=1) Label(self.sliderFrame, text="Alphanumeric Color".rjust(20), font=(fontType, fontLabelSize)).grid(row=8, column=1) Label(self.sliderFrame, text="Description".rjust(20), font=(fontType, fontLabelSize)).grid(row=9, column=1) self.orientationValue = tk.StringVar(self.sliderFrame) self.orientationValue.set("N") self.shapeValue = tk.StringVar(self.sliderFrame) self.shapeValue.set("circle") self.bkColorValue = tk.StringVar(self.sliderFrame) self.bkColorValue.set("white") self.alphaColorValue = tk.StringVar(self.sliderFrame) self.alphaColorValue.set("white") self.entryType = Entry(self.sliderFrame) self.entryLat = Entry(self.sliderFrame) self.entryLong = Entry(self.sliderFrame) self.optionOrien = tk.OptionMenu(self.sliderFrame, self.orientationValue, *self.orienVals) self.optionShape = tk.OptionMenu(self.sliderFrame, self.shapeValue, *self.shapeVals) self.optionBkColor = tk.OptionMenu(self.sliderFrame, self.bkColorValue, *self.colorVals) self.entryAlpha = Entry(self.sliderFrame) self.optionAlphaColor = tk.OptionMenu(self.sliderFrame, self.alphaColorValue, *self.colorVals) self.entryDesc = Entry(self.sliderFrame) self.entryRF = Button(self.sliderFrame, text="Return Focus", command=self.return_focus) self.entryType.grid(row=1, column=2) self.entryLat.grid(row=2, column=2) self.entryLong.grid(row=3, column=2) self.optionOrien.grid(row=4, column=2) self.optionShape.grid(row=5, column=2) self.optionBkColor.grid(row=6, column=2) self.entryAlpha.grid(row=7, column=2) self.optionAlphaColor.grid(row=8, column=2) self.entryDesc.grid(row=9, column=2) self.entryRF.grid(row=10, column=2) self.entryType.config(font=(fontType, fontEntrySize)) self.entryLat.config(font=(fontType, fontEntrySize)) self.entryLong.config(font=(fontType, fontEntrySize)) self.optionOrien.config(font=(fontType, fontEntrySize)) self.optionShape.config(font=(fontType, fontEntrySize)) self.optionBkColor.config(font=(fontType, fontEntrySize)) self.entryAlpha.config(font=(fontType, fontEntrySize)) self.optionAlphaColor.config(font=(fontType, fontEntrySize)) self.entryDesc.config(font=(fontType, fontEntrySize)) self.entryRF.config(font=(fontType, fontEntrySize)) def return_focus(self): self.currImgObj.get_entry_data() self.window.focus_force() print "focus returned." def update_curr_img_obj(self): if len(self.origList) and self.mode == mode.orig: self.currImgObj = (self.origList[self.origIndex]) elif len(self.cropList) and self.mode == mode.cropped: self.currImgObj = (self.cropList[self.cropIndex]) else: # null obj self.currImgObj = img_obj(self, nullImg) return self.currImgObj
def initUIElements(self): _onEdit = lambda i,j,k: self.onEdit() _onType = lambda i,j,k: self.onType() for k,v in self.fields.items(): _data = self.fields[k][0] _UIClass = self.fields[k][1] _context = self.fields[k][2] _toString = lambda x: x methods = [m for m in dir(self.data) \ if m.lower() == k.lower()+"tostring"] if methods: _toString = self.data.__getattribute__(methods[0]) if _UIClass == Entry: _var = StringVar(self.parent) _var.set(_toString(_data)) _var.trace("w",_onEdit) _label = Label(self,text=self.parseName(k)+":") _entry = Entry(self,textvariable=_var) _entry.config(width=10) self.fields[k] = (_data,_entry,_label,_var) elif _UIClass == ColorOption: self.fields[k] = (_data,_UIClass,None,None) elif _UIClass == OptionMenu and not self.differs: _var = StringVar(self.parent) _names = [c.name for c in _context] _var.set(_data.name) _var.trace("w",_onEdit) _label = Label(self,text=self.parseName(k)+":") _menu = OptionMenu(self,_var,*_names) _menu.configure(width=5) self.fields[k] = (_data,_menu,_label,_var) elif _UIClass == OptionMenu and self.differs: if k == "Type": _var = StringVar(self.parent) _names = _data _var.set(_names[0]) _var.trace("w",_onType) _label = Label(self,text=self.parseName(k)+":") _menu = OptionMenu(self,_var,*_names) _menu.configure(width=5) self.fields[k] = (_data,_menu,_label,_var) elif k == "Choose": _var = StringVar(self.parent) _names = [dI.name for dI in _data.values()[0]] if not _names: _names.append("") _var.set(_names[0]) _label = Label(self,text=self.parseName(k)+":") _menu = OptionMenu(self,_var,*_names) _menu.configure(width=5) self.fields[k] = (_data,_menu,_label,_var) elif _UIClass == FileFrame: _menu = FileFrame(self,self.active,_data) self.fields[k] = (_data,_menu,None,None) elif _UIClass == MapFrame and not self.active: _mapping = _data _mapFrame = MapFrame(self,_data,True,self.data) self.fields[k] = (_data,_mapFrame,None,None) elif _UIClass == ItemList and not self.active: _itemList = ItemList(self,_data,_context,True) self.fields[k] = (_data,_itemList,None,None) if not self.active: if is_mac(): self.apply = ttk.Button(self,text=unichr(10004),command=self.onApply, width=1) else: self.apply = Button(self,text=unichr(10004),command=self.onApply) self.createToolTip(self.apply,"Apply") self.delete = Button(self,text="x",command=self.onDelete) self.createToolTip(self.delete,"Delete") else: self.add = Button(self,text="Add",command=self.onAdd) self.createToolTip(self.add,"Add "+self.data.__class__.__name__) if self.multiple and not self.differs: _data = self.data self.typeDict = {} for dI in _data.values(): if "type" in dir(dI): _type = dI.type else: _type = dI.__class__.__name__ self.typeDict[_type] = dI.__class__.__name__ _var = StringVar(self.parent) _var.set(self.typeDict.keys()[0]) _var.trace("w",_onType) _label = Label(self,text="Type: ") _menu = OptionMenu(self,_var,*self.typeDict.keys()) _menu.configure(width=12) self.fields["type"] = (_data,_menu,_label,_var) elif self.multiple and self.differs: pass else: pass
class OSCEditor(tkSimpleDialog.Dialog): def __init__( self, parent, options_file, req_unit_type, title=None, ): self.options_file = options_file self.req_unit_type = req_unit_type # init the super class tkSimpleDialog.Dialog.__init__(self, parent, title) def body(self, master): self.result = False config = ConfigParser.ConfigParser() config.read(self.options_file) if self.req_unit_type == 'remote': Label(master, text="").grid(row=10, sticky=W) Label(master, text="Pi Presents Data Home:").grid(row=11, sticky=W) self.e_home = Entry(master, width=80) self.e_home.grid(row=12) self.e_home.insert(0, config.get('paths', 'home', 0)) Label(master, text="").grid(row=20, sticky=W) Label(master, text="Offset for Current Profiles:").grid(row=21, sticky=W) self.e_offset = Entry(master, width=80) self.e_offset.grid(row=22) self.e_offset.insert(0, config.get('paths', 'offset', 0)) Label(master, text="").grid(row=25, sticky=W) Label(master, text="Type of this Unit:").grid(row=26, sticky=W) self.e_type = Entry(master, width=80) self.e_type.grid(row=27) self.e_type.insert(0, self.req_unit_type) self.e_type.config(state="readonly", bg='dark grey') Label(master, text="").grid(row=30, sticky=W) Label(master, text="Name of This Unit:").grid(row=31, sticky=W) self.e_remote_name = Entry(master, width=80) self.e_remote_name.grid(row=32) self.e_remote_name.insert(0, config.get('this-unit', 'name', 0)) Label(master, text="").grid(row=40, sticky=W) Label(master, text="IP of This Unit:").grid(row=41, sticky=W) self.e_remote_ip = Entry(master, width=80) self.e_remote_ip.grid(row=42) self.e_remote_ip.insert(0, config.get('this-unit', 'ip', 0)) Label(master, text="").grid(row=50, sticky=W) Label(master, text="Listening Port of This Unit:").grid(row=51, sticky=W) self.e_remote_port = Entry(master, width=80) self.e_remote_port.grid(row=52) self.e_remote_port.insert(0, config.get('this-unit', 'port', 0)) if self.req_unit_type in ('master', 'remote', 'master+slave'): Label(master, text="").grid(row=60, sticky=W) Label(master, text="Controlled Units (not used):").grid(row=61, sticky=W) self.e_controlled_units = Entry(master, width=80) self.e_controlled_units.grid(row=62) self.e_controlled_units.insert( 0, config.get('this-unit', 'controlled-units', 0)) Label(master, text="").grid(row=70, sticky=W) Label(master, text="Name of Controlled Unit:").grid(row=71, sticky=W) self.e_pipresents_unit = Entry(master, width=80) self.e_pipresents_unit.grid(row=72) self.e_pipresents_unit.insert( 0, config.get('controlled-unit-1', 'controlled-unit-name', 0)) Label(master, text="").grid(row=80, sticky=W) Label(master, text="IP of Controlled Unit:").grid(row=81, sticky=W) self.e_pipresents_ip = Entry(master, width=80) self.e_pipresents_ip.grid(row=82) self.e_pipresents_ip.insert( 0, config.get('controlled-unit-1', 'controlled-unit-ip', 0)) Label(master, text="").grid(row=90, sticky=W) Label(master, text="Listening Port of Controlled Unit:").grid(row=91, sticky=W) self.e_pipresents_port = Entry(master, width=80) self.e_pipresents_port.grid(row=92) self.e_pipresents_port.insert( 0, config.get('controlled-unit-1', 'controlled-unit-port', 0)) if self.req_unit_type in ('slave', 'master+slave'): Label(master, text="").grid(row=100, sticky=W) Label(master, text="Controlled By Unit:").grid(row=101, sticky=W) self.e_controlled_by_unit = Entry(master, width=80) self.e_controlled_by_unit.grid(row=102) self.e_controlled_by_unit.insert( 0, config.get('this-unit', 'controlled-by-name', 0)) Label(master, text="").grid(row=110, sticky=W) Label(master, text="IP of Controlled By Unit:").grid(row=111, sticky=W) self.e_controlled_by_ip = Entry(master, width=80) self.e_controlled_by_ip.grid(row=112) self.e_controlled_by_ip.insert( 0, config.get('this-unit', 'controlled-by-ip', 0)) Label(master, text="").grid(row=120, sticky=W) Label(master, text="Listening Port of Controlled By Unit:").grid(row=121, sticky=W) self.e_controlled_by_port = Entry(master, width=80) self.e_controlled_by_port.grid(row=122) self.e_controlled_by_port.insert( 0, config.get('this-unit', 'controlled-by-port', 0)) return None # no initial focus def validate(self): if self.req_unit_type == 'remote': if self.e_home.get().strip() != '': if os.path.exists(self.e_home.get()) is False: tkMessageBox.showwarning("Pi Presents Remote", "Data Home not found") return 0 if self.e_offset.get().strip() != '': if os.path.exists(self.e_home.get() + os.sep + 'pp_profiles' + self.e_offset.get()) is False: tkMessageBox.showwarning( "Pi Presents Remote", "Current Profles directory not found") return 0 return 1 def apply(self): self.save_options() self.result = True def save_options(self): """ save the output of the options edit dialog to file""" config = ConfigParser.ConfigParser() config.add_section('paths') if self.req_unit_type == 'remote': config.set('paths', 'home', self.e_home.get()) config.set('paths', 'offset', self.e_offset.get()) else: config.set('paths', 'home', '') config.set('paths', 'offset', '') config.add_section('this-unit') config.set('this-unit', 'name', self.e_remote_name.get()) config.set('this-unit', 'ip', self.e_remote_ip.get()) config.set('this-unit', 'port', self.e_remote_port.get()) config.set('this-unit', 'type', self.req_unit_type) config.add_section('controlled-unit-1') if self.req_unit_type in ('master', 'remote', 'master+slave'): config.set('this-unit', 'controlled-units', self.e_controlled_units.get()) config.set('controlled-unit-1', 'controlled-unit-name', self.e_pipresents_unit.get()) config.set('controlled-unit-1', 'controlled-unit-ip', self.e_pipresents_ip.get()) config.set('controlled-unit-1', 'controlled-unit-port', self.e_pipresents_port.get()) else: config.set('this-unit', 'controlled-units', '') config.set('controlled-unit-1', 'controlled-unit-name', '') config.set('controlled-unit-1', 'controlled-unit-ip', '') config.set('controlled-unit-1', 'controlled-unit-port', '') if self.req_unit_type in ('slave', 'master+slave'): config.set('this-unit', 'controlled-by-name', self.e_controlled_by_unit.get()) config.set('this-unit', 'controlled-by-ip', self.e_controlled_by_ip.get()) config.set('this-unit', 'controlled-by-port', self.e_controlled_by_port.get()) else: config.set('this-unit', 'controlled-by-name', '') config.set('this-unit', 'controlled-by-ip', '') config.set('this-unit', 'controlled-by-port', '') with open(self.options_file, 'wb') as optionsfile: config.write(optionsfile)
class Participant(object): """ Creates the input frame and stores the information regarding the participant """ def __init__(self, parent, *args, **kwargs): """ Initialize the input frame and call to inititialize the user interface """ # Set the Tk as the parent self.parent = parent # Initialize the user interface self.initUI() def initUI(self): """ Initializes the user interface Setting up the entry widgets for: - Experiment_ID - Participant Name - Session Day - Pupil Size - Practice - Stereo """ # Set the title self.parent.title(EXP_NAME) # Create the label for Experiment_ID and set location label_id = Label(text='Participant ID:') label_id.place(x=20, y=20) # Check the DATA_DIR directory for previous participants # and choose the next Experiment_ID in line self.folders = listdir(DATA_DIR) # Initiate Tkinter's StringVar self.value_id = StringVar() # Set the default value self.value_id.set('001') # Going in reverse order of the participants' directories in # DATA_DIR, find the last participant's Experiment_ID and opt # for the next one in line for folder in reversed(self.folders): try: # Check if the value of the first 3 digits of the # directory name is greater than the default value if int(folder[:3]) >= int(self.value_id.get()): # Get the next Experiment_ID in integer form and # convert to string format num = str(int(folder[:3]) + 1) # Actions to perform in case scenarios for each # of the possibilites of num_length num_length = {3: num, 2: '0%s' % num, 1: '00%s' % num} # Set the value accordingly to the StringVar, # replacing the default self.value_id.set(num_length[len(num)]) # In case there are other folders in DATA_DIR, for which # the first 3 characters are not digits, we must cater # for when an exception is thrown up except ValueError: pass # Create the entry widget for Experiment_ID with the preset # value and state disabled self.input_id = Entry(self.parent, width=5, state=DISABLED, textvariable=self.value_id) self.input_id.place(x=150, y=20) # Create the label for Participant Name and set location label_name = Label(text='Participant Name:') label_name.place(x=20, y=50) # Initiate Tkinter's StringVar self.value_name = StringVar() # Set the default value self.value_name.set('') # Create the entry for Participant Name and set location self.input_name = Entry(self.parent, width=35, textvariable=self.value_name) self.input_name.place(x=150, y=50) self.input_name.focus() # Create the label for Session Day and set location label_day = Label(text='Session Day:') label_day.place(x=20, y=80) # Create value holder for Session Day as IntVar and set default # value to 1 self.value_day = IntVar() self.value_day.set(1) # Create the radiobuttons as required for day in range(1, TOTAL_SESSIONS + 1): input_day = Radiobutton(self.parent, text=str(day), variable=self.value_day, value=day) # Anchor them to the West (W) input_day.pack(anchor=W) # Choose location for the radiobuttons input_day.place(x=150, y=(50 + (day * 25))) # Create the label for Pupil Size and set location label_pupilsize = Label(text='Pupil Size:') label_pupilsize.place(x=20, y=140) self.value_pupilsize = StringVar() self.value_pupilsize.set('') # Create the MaxLengthEntry for Pupil Size and set location # The maximum length is set to 3 characters and a float must be # provided self.input_pupilsize = MaxLengthEntry(self.parent, width=5, maxlength=3, required_type=float) self.input_pupilsize.config(textvariable=self.value_pupilsize) self.input_pupilsize.place(x=150, y=140) # Create value folder for Practice as IntVar self.value_practice = IntVar() # Create the checkbutton for Practice and set location input_practice = Checkbutton(self.parent, text='Practice', variable=self.value_practice, onvalue=1, offvalue=0) input_practice.place(x=150, y=170) # Create value holder for Stereo as IntVar self.value_stereo = IntVar() # Create the checkbutton for Stereo and set location input_stereo = Checkbutton(self.parent, text='Stereo', variable=self.value_stereo, onvalue=1, offvalue=0) input_stereo.place(x=150, y=200) # Create the label for Previous Subjects and set location label_previous = Label(text='Previous Subjects:') label_previous.place(x=20, y=250) # Create the Listboc containing all the previous participants self.input_previous = Listbox(self.parent, width=35, height=10) for identifier in self.folders: self.input_previous.insert(END, identifier) self.input_previous.place(x=150, y=250) self.input_previous.bind('<<ListboxSelect>>', self.__select_previous) # Create the submit button, give command upon pressing and set # location submit = Button(text='Submit', width=47, command=self.gather_input) submit.pack(padx=8, pady=8) submit.place(x=20, y=425) def __select_previous(self, event): """ Handle scenario where user selects one of the previous participants """ # Collect from previous subjects, if it was chosen self.previous = self.input_previous.curselection() if self.previous: self.previous = self.folders[int(self.previous[0])] with open(join(DATA_DIR, self.previous, 'data.json')) as f: data = load(f) # Set the value for participant ID self.value_id.set(data['ID']) # Set the value for name and disable the user from making # any more changes self.value_name.set(data['Name']) self.input_name.config(state=DISABLED) # Set the value for pupilsize and disable the user from # making any more changes self.value_pupilsize.set(data['Pupil Size']) self.input_pupilsize.config(state=DISABLED) def gather_input(self): """ Gather the input from the Tkinter window and store it as class variables of the Participant class This module will also create a folder for the participant if it does not exist already in DATA_DIR NOTE: DATA_DIR is set in settings.py """ # Collect all the values input and convert to their appropriate # types self.subject_id = self.input_id.get() self.name = self.input_name.get().title() self.day = int(self.value_day.get()) try: self.pupilsize = float(self.input_pupilsize.get()) except ValueError: pass self.practice = bool(self.value_practice.get()) self.stereo = bool(self.value_stereo.get()) # Destroy the Tkinter window self.parent.destroy() # Put together the directory name and path self.subject_dir = '%s_%s' % (self.subject_id, self.name.replace(' ', '')) self.subject_dir = join(DATA_DIR, self.subject_dir) # If the directory for the participant does not exist, create it if not exists(self.subject_dir): makedirs(self.subject_dir)
class ANC350_controller: '''A class for custon gui to control ANC350 version 2''' def __init__(self): self.root = Tk() # create interface instance self.root.title('ANC350 Controller') # change title self.root.geometry('500x300') # define window size self.p = Positioner( ) # create a positioner instance to send commands to ANC350v2 self.pos = [ self.p.getPosition(0), self.p.getPosition(1), self.p.getPosition(2) ] # a position list # create text boxes to show position self.Xpos_ent = Entry(self.root, font="Helvetica 16 bold", justify="center", width=9) self.Ypos_ent = Entry(self.root, font="Helvetica 16 bold", justify="center", width=9) self.Zpos_ent = Entry(self.root, font="Helvetica 16 bold", justify="center", width=9) # create step size boxes self.Xstepsize_ent = Entry(self.root, font="Helvetica 16 bold", justify="center", width=3) self.Ystepsize_ent = Entry(self.root, font="Helvetica 16 bold", justify="center", width=3) self.Zstepsize_ent = Entry(self.root, font="Helvetica 16 bold", justify="center", width=3) self.Xstepsize_ent.insert(0, 1) # define defualt values self.Ystepsize_ent.insert(0, 1) # define defualt values self.Zstepsize_ent.insert(0, 1) # define defualt values # create status bar self.status_ent = Entry(self.root, font="Helvetica 14 bold", justify="center", width=20, readonlybackground="black") if self.p.numconnected: self.status_ent.insert(0, str(self.p.posinf.id) + " Connected") self.status_ent.config({"fg": "green", "state": "readonly"}) else: self.status_ent.insert(0, "Disconnected") self.status_ent.config({"fg": "red", "state": "readonly"}) # create labels self.Xpos_lbl = Label(self.root, text=u"X (\u03BCm)", font="Helvetica 14", justify="center") self.Ypos_lbl = Label(self.root, text=u"Y (\u03BCm)", font="Helvetica 14", justify="center") self.Zpos_lbl = Label(self.root, text=u"Z (\u03BCm)", font="Helvetica 14", justify="center") self.step_lbl = Label(self.root, text=u" Step (\u03BCm):", font="Helvetica 12", justify="center") # create buttons self.read_btn = Button(self.root, text="read", command=lambda: self.read(), font="Helvetica 16", justify="center") self.Xplus_btn = Button(self.root, text="X+", command=lambda: self.move(0, 1), font="Helvetica 16", justify="center") self.Xminus_btn = Button(self.root, text="X-", command=lambda: self.move(0, -1), font="Helvetica 16", justify="center") self.Yplus_btn = Button(self.root, text="Y+", command=lambda: self.move(1, 1), font="Helvetica 16", justify="center") self.Yminus_btn = Button(self.root, text="Y-", command=lambda: self.move(1, -1), font="Helvetica 16", justify="center") self.Zplus_btn = Button(self.root, text="Z+", command=lambda: self.move(2, 1), font="Helvetica 16", justify="center") self.Zminus_btn = Button(self.root, text="Z-", command=lambda: self.move(2, -1), font="Helvetica 16", justify="center") # place widgets on grid self.status_ent.grid(column=1, row=0, columnspan=3) self.Xpos_lbl.grid(column=1, row=1) self.Ypos_lbl.grid(column=2, row=1) self.Zpos_lbl.grid(column=3, row=1) self.Xpos_ent.grid(column=1, row=2) self.Ypos_ent.grid(column=2, row=2) self.Zpos_ent.grid(column=3, row=2) self.step_lbl.grid(column=0, row=3) self.Xstepsize_ent.grid(column=1, row=3) self.Ystepsize_ent.grid(column=2, row=3) self.Zstepsize_ent.grid(column=3, row=3) self.read_btn.grid(column=2, row=4) self.Yplus_btn.grid(column=1, row=5) self.Xplus_btn.grid(column=2, row=6) self.Xminus_btn.grid(column=0, row=6) self.Yminus_btn.grid(column=1, row=7) self.Zplus_btn.grid(column=3, row=5) self.Zminus_btn.grid(column=3, row=7) # key binding self.root.bind("<Next>", lambda event: self.move(0, 1)) # move +X key self.root.bind("<Delete>", lambda event: self.move(0, -1)) # move -X key self.root.bind("<Home>", lambda event: self.move(1, 1)) # move +Y key self.root.bind("<End>", lambda event: self.move(1, -1)) # move -Y key self.root.bind("<F2>", lambda event: self.move(2, 1)) # move +Z key self.root.bind("<F1>", lambda event: self.move(2, -1)) # move -Z key self.root.bind( "<Escape>", lambda event: self.root.focus()) # focus on main window key self.root.bind("<Return>", lambda event: self.read()) # read key def __enter__(self): '''Excecutes when entering a "with" statement, returns self''' return self def __exit__(self, exc_type, exc_val, exc_tb): '''Excecutes at the end of a "with" statement, closes connection to device''' self.p.setOutput(0, 0) # deactivate axis 0 self.p.setOutput(1, 0) # deactivate axis 1 self.p.setOutput(2, 0) # deactivate axis 2 self.p.close() def update_pos_boxes(self): '''Updates values in the position boxes based on the current values stored in "self.pos" list''' self.Xpos_ent.delete(0, "end") self.Ypos_ent.delete(0, "end") self.Zpos_ent.delete(0, "end") self.Xpos_ent.insert(0, self.pos[0] / 1e3) self.Ypos_ent.insert(0, self.pos[1] / 1e3) self.Zpos_ent.insert(0, self.pos[2] / 1e3) def read(self): '''Reads the positions of the 3 axes and updates the position boxes''' self.pos[0] = self.p.getPosition(0) self.pos[1] = self.p.getPosition(1) self.pos[2] = self.p.getPosition(2) self.update_pos_boxes() def move(self, axis, direct): '''Moves axis "axis" (0,1,2) in direction "direct" by length "stepsize" in nm''' # activate axis and get step size if axis == 0: self.p.setOutput(axis, 1) # activate axis self.p.setOutput(1, 0) # deactivate axis self.p.setOutput(2, 0) # deactivate axis stepsize = int(float(self.Xstepsize_ent.get()) * 1e3) # step size in nm elif axis == 1: self.p.setOutput(axis, 1) # activate axis self.p.setOutput(0, 0) # deactivate axis self.p.setOutput(2, 0) # deactivate axis stepsize = int(float(self.Ystepsize_ent.get()) * 1e3) # step size in nm elif axis == 2: self.p.setOutput(axis, 1) # activate axis self.p.setOutput(0, 0) # deactivate axis self.p.setOutput(1, 0) # deactivate axis stepsize = int(float(self.Zstepsize_ent.get()) * 1e3) # step size in nm # if there is no position value stored, get one if not self.pos[axis]: self.pos[axis] = self.p.getPosition(axis) # modify position based on the step taken if direct > 0: self.pos[axis] += stepsize else: self.pos[axis] -= stepsize self.p.moveAbsolute( axis, self.pos[axis]) # move absolute position to new value self.update_pos_boxes() # update new value in the position boxes
class VideoGUI(): def __init__(self): self.ENTRY_WITDH = 20 self.button_width = 6 self.default_dir = './' self.gui() def emptyIt(self): self.link_contend.set('') return 0 def chooseFile(self): self.fname = tkFileDialog.askopenfilename(title=u"Choose File", initialdir=(os.path.expanduser(self.default_dir))) self.link_contend.set(self.fname) return self.fname def startFFmpeg(self): self.result_link_contend.set('convert done!') input_path = self.link_contend.get() output_type = self.outType.get() output_path = input_path.split('.')[0] + '.' + output_type if output_type == 'wav': cmd = 'ffmpeg -i ' + input_path + ' -y ' + output_path elif output_type == 'mp4': cmd = 'ffmpeg -i ' + input_path + ' ' + output_path else: cmd = 'ffmpeg' os.system(cmd) self.result_link_contend.set(output_path) self.link_contend.set('convert done!') return 0 def gui(self): self.root = Tk() self.root.title('video converter') self.entry_link = Entry(self.root, width=self.ENTRY_WITDH, state='disabled') self.entry_link.grid(row=0, column=0, columnspan=2) self.link_contend = StringVar() self.entry_link.config(textvariable=self.link_contend) self.link_contend.set('plz choose:') self.choose_button = Button(self.root, text='choose', width=self.button_width, command=self.chooseFile) self.choose_button.grid(row=1, column=0, columnspan=1) self.clear_button = Button(self.root, text='empty', width=self.button_width, command=self.emptyIt) self.clear_button.grid(row=1, column=1, columnspan=1) self.outType = StringVar() self.typeChosen = Combobox(self.root, width=self.ENTRY_WITDH, textvariable=self.outType) self.typeChosen['values'] = ('wav', 'mp4', 'flv', 'mp3', 'gif') self.typeChosen.current(3) self.typeChosen.grid(row=2, column=0, columnspan=2) self.startButton = Button(self.root, text='Start Convert', width=self.button_width * 2, command=self.startFFmpeg) self.startButton.grid(row=3, column=0, columnspan=2) self.result_link = Entry(self.root, width=self.ENTRY_WITDH, state='disabled') self.result_link.grid(row=4, column=0, columnspan=2) self.result_link_contend = StringVar() self.result_link.config(textvariable=self.result_link_contend) self.result_link_contend.set('plz hold on:') mainloop()
class EktaproGUI(Tk): """ Constructs the main program window and interfaces with the EktaproController and the TimerController to access the slide projectors. """ def __init__(self): self.controller = EktaproController() self.controller.initDevices() Tk.__init__(self) self.protocol("WM_DELETE_WINDOW", self.onQuit) self.wm_title("EktaproGUI") self.bind("<Prior>", self.priorPressed) self.bind("<Next>", self.nextPressed) self.brightness = 0 self.slide = 1 self.timerController = TimerController(self.controller, self) self.controlPanel = Frame(self) self.manualPanel = Frame(self) self.projektorList = Listbox(self, selectmode=SINGLE) for i in range(len(self.controller.devices)): self.projektorList.insert(END, "[" + str(i) + "] " + str(self.controller.devices[i])) if self.projektorList.size >= 1: self.projektorList.selection_set(0) self.projektorList.bind("<ButtonRelease>", self.projektorSelectionChanged) self.projektorList.config(width=50) self.initButton = Button(self.controlPanel, text="init", command=self.initButtonPressed) self.nextButton = Button(self.controlPanel, text="next slide", command=self.nextSlidePressed) self.nextButton.config(state=DISABLED) self.prevButton = Button(self.controlPanel, text="previous slide", command=self.prevSlidePressed) self.prevButton.config(state=DISABLED) self.startButton = Button(self.controlPanel, text="start timer", command=self.startTimer) self.startButton.config(state=DISABLED) self.pauseButton = Button(self.controlPanel, text="pause", command=self.pauseTimer) self.stopButton = Button(self.controlPanel, text="stop", command=self.stopTimer) self.stopButton.config(state=DISABLED) self.timerLabel = Label(self.controlPanel, text="delay:") self.timerInput = Entry(self.controlPanel, width=3) self.timerInput.insert(0, "5") self.timerInput.config(state=DISABLED) self.timerInput.bind("<KeyPress-Return>", self.inputValuesChanged) self.timerInput.bind("<ButtonRelease>", self.updateGUI) self.fadeLabel = Label(self.controlPanel, text="fade:") self.fadeInput = Entry(self.controlPanel, width=3) self.fadeInput.insert(0, "1") self.fadeInput.config(state=DISABLED) self.fadeInput.bind("<KeyPress-Return>", self.inputValuesChanged) self.fadeInput.bind("<ButtonRelease>", self.updateGUI) self.standbyButton = Button(self.controlPanel, text="standby", command=self.toggleStandby) self.standbyButton.config(state=DISABLED) self.syncButton = Button(self.controlPanel, text="sync", command=self.sync) self.syncButton.config(state=DISABLED) self.reconnectButton = Button(self.controlPanel, text="reconnect", command=self.reconnect) self.cycle = IntVar() self.cycleButton = Checkbutton( self.controlPanel, text="use all projectors", variable=self.cycle, command=self.cycleToggled ) self.brightnessScale = Scale(self.manualPanel, from_=0, to=100, resolution=1, label="brightness") self.brightnessScale.set(self.brightness) self.brightnessScale.bind("<ButtonRelease>", self.brightnessChanged) self.brightnessScale.config(state=DISABLED) self.brightnessScale.config(orient=HORIZONTAL) self.brightnessScale.config(length=400) self.gotoSlideScale = Scale(self.manualPanel, from_=0, to=self.controller.maxTray, label="goto slide") self.gotoSlideScale.set(1) self.gotoSlideScale.bind("<ButtonRelease>", self.gotoSlideChanged) self.gotoSlideScale.config(state=DISABLED) self.gotoSlideScale.config(orient=HORIZONTAL) self.gotoSlideScale.config(length=400) self.controlPanel.pack(side=BOTTOM, anchor=W, fill=X) self.projektorList.pack(side=LEFT, fill=BOTH) self.manualPanel.pack(side=RIGHT, expand=1, fill=BOTH) self.initButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.prevButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.nextButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.cycleButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.startButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.pauseButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.stopButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.timerLabel.pack(side=LEFT, anchor=N, padx=4, pady=4) self.timerInput.pack(side=LEFT, anchor=N, padx=4, pady=4) self.fadeLabel.pack(side=LEFT, anchor=N, padx=4, pady=4) self.fadeInput.pack(side=LEFT, anchor=N, padx=4, pady=4) self.syncButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.standbyButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.reconnectButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.brightnessScale.pack(side=TOP, anchor=W, expand=1, fill=X) self.gotoSlideScale.pack(side=TOP, anchor=W, expand=1, fill=X) self.menubar = Menu(self) self.toolsmenu = Menu(self.menubar) self.helpmenu = Menu(self.menubar) self.filemenu = Menu(self.menubar) self.toolsmenu.add_command(label="Interpret HEX Sequence", command=self.interpretHEXDialog) self.helpmenu.add_command( label="About EktaproGUI", command=lambda: tkMessageBox.showinfo("About EktaproGUI", "EktaproGUI 1.0 (C)opyright Julian Hoch 2010"), ) self.filemenu.add_command(label="Exit", command=self.onQuit) self.menubar.add_cascade(label="File", menu=self.filemenu) self.menubar.add_cascade(label="Tools", menu=self.toolsmenu) self.menubar.add_cascade(label="Help", menu=self.helpmenu) self.configure(menu=self.menubar) def initButtonPressed(self): self.controller.resetDevices() self.updateGUI() self.brightnessScale.config(state=NORMAL) self.gotoSlideScale.config(state=NORMAL) self.nextButton.config(state=NORMAL) self.prevButton.config(state=NORMAL) self.startButton.config(state=NORMAL) self.timerInput.config(state=NORMAL) self.fadeInput.config(state=NORMAL) self.syncButton.config(state=NORMAL) self.standbyButton.config(state=NORMAL) def inputValuesChanged(self, event): try: fadeDelay = int(self.fadeInput.get()) slideshowDelay = int(self.timerInput.get()) if fadeDelay in range(0, 60): self.timerController.fadeDelay = fadeDelay if slideshowDelay in range(1, 60): self.timerController.slideshowDelay = slideshowDelay except Exception: pass self.updateGUI() def sync(self): self.controller.syncDevices() self.updateGUI() def reconnect(self): self.controller.cleanUp() self.controller.initDevices() self.updateGUI() self.projektorList.delete(0, END) for i in range(len(self.controller.devices)): self.projektorList.insert(END, "[" + str(i) + "] " + str(self.controller.devices[i])) if self.projektorList.size >= 1: self.projektorList.selection_set(0) def projektorSelectionChanged(self, event): items = map(int, self.projektorList.curselection()) if self.controller.setActiveDevice(items): self.updateGUI() def updateGUI(self, event=None): if self.controller.activeDevice == None: return self.brightness = self.controller.activeDevice.brightness self.brightnessScale.set(self.brightness) self.slide = self.controller.activeDevice.slide self.gotoSlideScale.set(self.slide) for i in range(self.projektorList.size()): if i == self.controller.activeIndex: self.projektorList.selection_set(i) else: self.projektorList.selection_clear(i) def brightnessChanged(self, event): newBrightness = self.brightnessScale.get() if not self.brightness == newBrightness and not self.controller.activeDevice == None: self.controller.activeDevice.setBrightness(newBrightness) self.brightness = self.brightnessScale.get() def gotoSlideChanged(self, event): if self.controller.activeDevice is None: return newSlide = self.gotoSlideScale.get() if not self.slide == newSlide: self.controller.activeDevice.gotoSlide(newSlide) self.slide = newSlide def nextSlidePressed(self): if self.controller.activeDevice is None: return self.timerController.fadePaused = False self.timerController.nextSlide() self.updateGUI() def prevSlidePressed(self): if self.controller.activeDevice is None: return self.timerController.fadePaused = False self.timerController.previousSlide() self.updateGUI() def startTimer(self): self.stopButton.config(state=NORMAL) self.startButton.config(state=DISABLED) self.timerController.startSlideshow() def pauseTimer(self): if self.timerController.fadePaused or self.timerController.slideshowPaused: self.pauseButton.config(text="pause") self.timerController.resume() self.updateGUI() else: self.pauseButton.config(text="resume") self.timerController.pause() self.updateGUI() def stopTimer(self): self.pauseButton.config(text="pause") self.stopButton.config(state=DISABLED) self.startButton.config(state=NORMAL) self.timerController.stopSlideshow() self.updateGUI() def cycleToggled(self): self.timerController.cycle = True if self.cycle.get() == 1 else False def interpretHEXDialog(self): interpretDialog = InterpretHEXDialog(self) # @UnusedVariable def toggleStandby(self): if self.pauseButton.config()["text"][4] == "pause" and self.pauseButton.config()["state"][4] == "normal": self.pauseTimer() self.controller.toggleStandby() def nextPressed(self, event): if self.startButton.config()["state"][4] == "disabled": self.pauseTimer() else: self.nextSlidePressed() def priorPressed(self, event): if self.startButton.config()["state"][4] == "disabled": self.toggleStandby() else: self.prevSlidePressed() def onQuit(self): self.controller.cleanUp() self.destroy()
class EktaproGUI(Tk): """ Constructs the main program window and interfaces with the EktaproController and the TimerController to access the slide projectors. """ def __init__(self): self.controller = EktaproController() self.controller.initDevices() Tk.__init__(self) self.protocol('WM_DELETE_WINDOW', self.onQuit) self.wm_title("EktaproGUI") self.bind("<Prior>", self.priorPressed) self.bind("<Next>", self.nextPressed) self.brightness = 0 self.slide = 1 self.timerController = TimerController(self.controller, self) self.controlPanel = Frame(self) self.manualPanel = Frame(self) self.projektorList = Listbox(self, selectmode=SINGLE) for i in range(len(self.controller.devices)): self.projektorList.insert(END, \ "[" + str(i) + "] " + str(self.controller.devices[i])) if self.projektorList.size >= 1: self.projektorList.selection_set(0) self.projektorList.bind("<ButtonRelease>", \ self.projektorSelectionChanged) self.projektorList.config(width=50) self.initButton = Button(self.controlPanel, \ text="init", \ command=self.initButtonPressed) self.nextButton = Button(self.controlPanel, \ text="next slide", \ command=self.nextSlidePressed) self.nextButton.config(state=DISABLED) self.prevButton = Button(self.controlPanel, \ text="previous slide", \ command=self.prevSlidePressed) self.prevButton.config(state=DISABLED) self.startButton = Button(self.controlPanel, \ text="start timer", \ command=self.startTimer) self.startButton.config(state=DISABLED) self.pauseButton = Button(self.controlPanel, \ text="pause", \ command=self.pauseTimer) self.stopButton = Button(self.controlPanel, \ text="stop", \ command=self.stopTimer) self.stopButton.config(state=DISABLED) self.timerLabel = Label(self.controlPanel, \ text="delay:") self.timerInput = Entry(self.controlPanel, \ width=3) self.timerInput.insert(0, "5") self.timerInput.config(state=DISABLED) self.timerInput.bind("<KeyPress-Return>", self.inputValuesChanged) self.timerInput.bind("<ButtonRelease>", self.updateGUI) self.fadeLabel = Label(self.controlPanel, \ text="fade:") self.fadeInput = Entry(self.controlPanel, \ width=3) self.fadeInput.insert(0, "1") self.fadeInput.config(state=DISABLED) self.fadeInput.bind("<KeyPress-Return>", self.inputValuesChanged) self.fadeInput.bind("<ButtonRelease>", self.updateGUI) self.standbyButton = Button(self.controlPanel, \ text="standby", \ command=self.toggleStandby) self.standbyButton.config(state=DISABLED) self.syncButton = Button(self.controlPanel, \ text="sync", \ command=self.sync) self.syncButton.config(state=DISABLED) self.reconnectButton = Button(self.controlPanel, \ text="reconnect", \ command=self.reconnect) self.cycle = IntVar() self.cycleButton = Checkbutton(self.controlPanel, \ text="use all projectors", \ variable=self.cycle, \ command=self.cycleToggled) self.brightnessScale = Scale(self.manualPanel, from_=0, to=100, resolution=1, \ label="brightness") self.brightnessScale.set(self.brightness) self.brightnessScale.bind("<ButtonRelease>", self.brightnessChanged) self.brightnessScale.config(state=DISABLED) self.brightnessScale.config(orient=HORIZONTAL) self.brightnessScale.config(length=400) self.gotoSlideScale = Scale(self.manualPanel, \ from_=0, to=self.controller.maxTray, \ label="goto slide") self.gotoSlideScale.set(1) self.gotoSlideScale.bind("<ButtonRelease>", self.gotoSlideChanged) self.gotoSlideScale.config(state=DISABLED) self.gotoSlideScale.config(orient=HORIZONTAL) self.gotoSlideScale.config(length=400) self.controlPanel.pack(side=BOTTOM, anchor=W, fill=X) self.projektorList.pack(side=LEFT, fill=BOTH) self.manualPanel.pack(side=RIGHT, expand=1, fill=BOTH) self.initButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.prevButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.nextButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.cycleButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.startButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.pauseButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.stopButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.timerLabel.pack(side=LEFT, anchor=N, padx=4, pady=4) self.timerInput.pack(side=LEFT, anchor=N, padx=4, pady=4) self.fadeLabel.pack(side=LEFT, anchor=N, padx=4, pady=4) self.fadeInput.pack(side=LEFT, anchor=N, padx=4, pady=4) self.syncButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.standbyButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.reconnectButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.brightnessScale.pack(side=TOP, anchor=W, expand=1, fill=X) self.gotoSlideScale.pack(side=TOP, anchor=W , expand=1, fill=X) self.menubar = Menu(self) self.toolsmenu = Menu(self.menubar) self.helpmenu = Menu(self.menubar) self.filemenu = Menu(self.menubar) self.toolsmenu.add_command(label="Interpret HEX Sequence", \ command=self.interpretHEXDialog) self.helpmenu.add_command(label="About EktaproGUI", \ command=lambda:tkMessageBox.showinfo("About EktaproGUI", \ "EktaproGUI 1.0 (C)opyright Julian Hoch 2010")) self.filemenu.add_command(label="Exit", command=self.onQuit) self.menubar.add_cascade(label="File", menu=self.filemenu) self.menubar.add_cascade(label="Tools", menu=self.toolsmenu) self.menubar.add_cascade(label="Help", menu=self.helpmenu) self.configure(menu=self.menubar) def initButtonPressed(self): self.controller.resetDevices() self.updateGUI() self.brightnessScale.config(state=NORMAL) self.gotoSlideScale.config(state=NORMAL) self.nextButton.config(state=NORMAL) self.prevButton.config(state=NORMAL) self.startButton.config(state=NORMAL) self.timerInput.config(state=NORMAL) self.fadeInput.config(state=NORMAL) self.syncButton.config(state=NORMAL) self.standbyButton.config(state=NORMAL) def inputValuesChanged(self, event): try: fadeDelay = int(self.fadeInput.get()) slideshowDelay = int(self.timerInput.get()) if fadeDelay in range(0, 60): self.timerController.fadeDelay = fadeDelay if slideshowDelay in range(1, 60): self.timerController.slideshowDelay = slideshowDelay except Exception: pass self.updateGUI() def sync(self): self.controller.syncDevices() self.updateGUI() def reconnect(self): self.controller.cleanUp() self.controller.initDevices() self.updateGUI() self.projektorList.delete(0, END) for i in range(len(self.controller.devices)): self.projektorList.insert(END, \ "[" + str(i) + "] " + str(self.controller.devices[i])) if self.projektorList.size >= 1: self.projektorList.selection_set(0) def projektorSelectionChanged(self, event): items = map(int, self.projektorList.curselection()) if self.controller.setActiveDevice(items): self.updateGUI() def updateGUI(self, event=None): if self.controller.activeDevice == None: return self.brightness = self.controller.activeDevice.brightness self.brightnessScale.set(self.brightness) self.slide = self.controller.activeDevice.slide self.gotoSlideScale.set(self.slide) for i in range(self.projektorList.size()): if i == self.controller.activeIndex: self.projektorList.selection_set(i) else: self.projektorList.selection_clear(i) def brightnessChanged(self, event): newBrightness = self.brightnessScale.get() if not self.brightness == newBrightness \ and not self.controller.activeDevice == None: self.controller.activeDevice.setBrightness(newBrightness) self.brightness = self.brightnessScale.get() def gotoSlideChanged(self, event): if self.controller.activeDevice is None: return newSlide = self.gotoSlideScale.get() if not self.slide == newSlide: self.controller.activeDevice.gotoSlide(newSlide) self.slide = newSlide def nextSlidePressed(self): if self.controller.activeDevice is None: return self.timerController.fadePaused = False self.timerController.nextSlide() self.updateGUI() def prevSlidePressed(self): if self.controller.activeDevice is None: return self.timerController.fadePaused = False self.timerController.previousSlide() self.updateGUI() def startTimer(self): self.stopButton.config(state=NORMAL) self.startButton.config(state=DISABLED) self.timerController.startSlideshow() def pauseTimer(self): if self.timerController.fadePaused or self.timerController.slideshowPaused: self.pauseButton.config(text="pause") self.timerController.resume() self.updateGUI() else: self.pauseButton.config(text="resume") self.timerController.pause() self.updateGUI() def stopTimer(self): self.pauseButton.config(text="pause") self.stopButton.config(state=DISABLED) self.startButton.config(state=NORMAL) self.timerController.stopSlideshow() self.updateGUI() def cycleToggled(self): self.timerController.cycle = True if self.cycle.get() == 1 else False def interpretHEXDialog(self): interpretDialog = InterpretHEXDialog(self) #@UnusedVariable def toggleStandby(self): if self.pauseButton.config()["text"][4] == "pause" \ and self.pauseButton.config()["state"][4] == "normal": self.pauseTimer() self.controller.toggleStandby() def nextPressed(self, event): if self.startButton.config()["state"][4] == "disabled": self.pauseTimer() else: self.nextSlidePressed() def priorPressed(self, event): if self.startButton.config()["state"][4] == "disabled": self.toggleStandby() else: self.prevSlidePressed() def onQuit(self): self.controller.cleanUp() self.destroy()
class App(object): def __init__(self, master): frame = Frame(master) frame.pack(fill=BOTH, expand=True) url_lab = Label(frame, text='URL:', fg='green', font=('Courier New', 16)) url_lab.grid(row=0, column=0, sticky=N + E) self.url_text = Text(frame, width=60, height=3, font=('Courier New', 12)) self.url_text.grid(row=0, column=1) f5_lab = Label(frame, text='F5 Big-Ip:', fg='blue', font=('Courier New', 14)) f5_lab.grid(row=1, column=0, sticky=N) self.f5bigip = StringVar() self.f5bigipEntry = Entry(frame, textvariable=self.f5bigip) self.f5bigipEntry.config(font=('Courier New', 12)) self.f5bigipEntry.config(width=60) self.f5bigipEntry.grid(row=1, column=1) self.testbtn = Button(frame, text='检测', font=('Courier New', 12)) self.testbtn.config(width=25) self.testbtn.config(bg='LightSkyBlue') self.testbtn.grid(row=2, column=1, sticky=W) self.decodebtn = Button(frame, text='解码F5 Big-Ip 值', font=('Courier New', 12)) self.decodebtn.config(width=25) self.decodebtn.config(bg='LightSkyBlue') self.decodebtn.grid(row=2, column=1, sticky=E) self.result_lab = Label(frame, text='执行结果:', fg='blue', font=('Courier New', 14)) self.result_lab.grid(row=3, column=0, sticky=N + E) scroll = Scrollbar(frame) scroll.grid(row=3, column=1, sticky=E + N + S) self.response = Text(frame, width=58, height=18, font=('Courier New', 12)) self.response.grid(row=3, column=1, sticky=W + S) self.response.config(yscrollcommand=scroll.set) scroll.config(command=self.response.yview) self.msg = StringVar() self.msg_lab = Label(frame, textvariable=self.msg, fg='blue', font=('Courier New', 12)) self.msg_lab.grid(row=4, column=0, columnspan=2, sticky=N + S + W + E) self.testbtn.bind('<Button-1>', self.check) self.decodebtn.bind('<Button-1>', self.decode_bigip2) self.url = '' self.pattern = re.compile('^(?:http|https)://(?:\w+\.)+.+') self.headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" } def check(self, event): self.msg.set('') self.url = self.url_text.get(1.0, END).strip() chek_url = self.pattern.match(self.url) # print chek_url.group() if not chek_url: # print ('123') self.msg.set('请输入正确的(GET)URL!') else: try: self.msg.set('') self.f5bigip.set('') self.response.delete(1.0, END) response = get(self.url, headers=self.headers) headers = response.headers set_cookie = headers.get('Set-cookie', None) headers = '\n'.join( [':'.join(item) for item in response.headers.iteritems()]) # print headers if set_cookie: bigip_value = self.getBigIPvalue(set_cookie) if bigip_value: self.f5bigip.set(bigip_value) self.msg_lab.config(fg='red') host = self.decode_bigip(bigip_value) self.msg.set( 'F5 BIG-IP Cookie Remote Information Disclosure\n' '存在信息泄露漏洞!\n' '内网地址:' + host) else: self.msg_lab.config(fg='blue') self.msg.set('不存在信息泄露漏洞!') else: self.msg_lab.config(fg='blue') self.msg.set('不存在信息泄露漏洞!') self.response.delete(1.0, END) self.response.insert(END, headers + '\n\n' + response.text) except: self.msg_lab.config(fg='red') self.msg.set('网络资源请求失败,请确保已经接入互联网和网址的有效性!') def getBigIPvalue(self, set_cookie): if set_cookie: lst = set_cookie.split(';') lst = [item.split('=') for item in lst] # print lst for key, value in lst: if re.search('BIGipServer.*?', key): return value return '' def decode_bigip(self, bigip_value): if bigip_value: if re.match('\d+\.\d+\.\d+', bigip_value): host, port, end = bigip_value.split('.') host = [ord(i) for i in struct.pack("<I", int(host))] port = [ord(e) for e in struct.pack("<H", int(port))] host = '.'.join([str(i) for i in host]) port = '0x%02X%02X' % (port[0], port[1]) # print port port = str(int(port, 16)) return ':'.join([host, port]) else: showerror( 'Decode F5 Bigip Error', 'Bigip value is Not a valid value !\n (xxx.xxx.xx)(x代表数字) ' ) return '' return '' def decode_bigip2(self, event): bigip_value = self.f5bigip.get().strip() result = self.decode_bigip(bigip_value) if result: showinfo("Decode F5 Bigip ", "%s : %s" % (bigip_value, result)) else: showerror( 'Decode F5 Bigip Error', 'Bigip value is Not a valid value !\n (xxx.xxx.xx)(x代表数字) ')
class Participant(object): """ Creates the input frame and stores the information regarding the participant """ def __init__(self, parent, *args, **kwargs): """ Initialize the input frame and call to inititialize the user interface """ # Set the Tk as the parent self.parent = parent # Initialize the user interface self.initUI() def initUI(self): """ Initializes the user interface Setting up the entry widgets for: - Experiment_ID - Participant Name - Session Day - Pupil Size - Practice - Stereo """ # Set the title self.parent.title(EXP_NAME) # Create the label for Experiment_ID and set location label_id = Label(text='Participant ID:') label_id.place(x=20, y=20) # Check the DATA_DIR directory for previous participants # and choose the next Experiment_ID in line self.folders = listdir(DATA_DIR) # Initiate Tkinter's StringVar self.value_id = StringVar() # Set the default value self.value_id.set('001') # Going in reverse order of the participants' directories in # DATA_DIR, find the last participant's Experiment_ID and opt # for the next one in line for folder in reversed(self.folders): try: # Check if the value of the first 3 digits of the # directory name is greater than the default value if int(folder[:3]) >= int(self.value_id.get()): # Get the next Experiment_ID in integer form and # convert to string format num = str(int(folder[:3]) + 1) # Actions to perform in case scenarios for each # of the possibilites of num_length num_length = { 3: num, 2: '0%s' % num, 1: '00%s' % num } # Set the value accordingly to the StringVar, # replacing the default self.value_id.set(num_length[len(num)]) # In case there are other folders in DATA_DIR, for which # the first 3 characters are not digits, we must cater # for when an exception is thrown up except ValueError: pass # Create the entry widget for Experiment_ID with the preset # value and state disabled self.input_id = Entry(self.parent, width=5, state=DISABLED, textvariable=self.value_id) self.input_id.place(x=150, y=20) # Create the label for Participant Name and set location label_name = Label(text='Participant Name:') label_name.place(x=20, y=50) # Initiate Tkinter's StringVar self.value_name = StringVar() # Set the default value self.value_name.set('') # Create the entry for Participant Name and set location self.input_name = Entry(self.parent, width=35, textvariable=self.value_name) self.input_name.place(x=150, y=50) self.input_name.focus() # Create the label for Session Day and set location label_day = Label(text='Session Day:') label_day.place(x=20, y=80) # Create value holder for Session Day as IntVar and set default # value to 1 self.value_day = IntVar() self.value_day.set(1) # Create the radiobuttons as required for day in range(1, TOTAL_SESSIONS + 1): input_day = Radiobutton(self.parent, text=str(day), variable=self.value_day, value=day) # Anchor them to the West (W) input_day.pack(anchor=W) # Choose location for the radiobuttons input_day.place(x=150, y=(50 + (day * 25))) # Create the label for Pupil Size and set location label_pupilsize = Label(text='Pupil Size:') label_pupilsize.place(x=20, y=140) self.value_pupilsize = StringVar() self.value_pupilsize.set('') # Create the MaxLengthEntry for Pupil Size and set location # The maximum length is set to 3 characters and a float must be # provided self.input_pupilsize = MaxLengthEntry(self.parent, width=5, maxlength=3, required_type=float) self.input_pupilsize.config(textvariable=self.value_pupilsize) self.input_pupilsize.place(x=150, y=140) # Create value folder for Practice as IntVar self.value_practice = IntVar() # Create the checkbutton for Practice and set location input_practice = Checkbutton(self.parent, text='Practice', variable=self.value_practice, onvalue=1, offvalue=0) input_practice.place(x=150, y=170) # Create value holder for Stereo as IntVar self.value_stereo = IntVar() # Create the checkbutton for Stereo and set location input_stereo = Checkbutton(self.parent, text='Stereo', variable=self.value_stereo, onvalue=1, offvalue=0) input_stereo.place(x=150, y=200) # Create the label for Previous Subjects and set location label_previous = Label(text='Previous Subjects:') label_previous.place(x=20, y=250) # Create the Listboc containing all the previous participants self.input_previous = Listbox(self.parent, width=35, height=10) for identifier in self.folders: self.input_previous.insert(END, identifier) self.input_previous.place(x=150, y=250) self.input_previous.bind('<<ListboxSelect>>', self.__select_previous) # Create the submit button, give command upon pressing and set # location submit = Button(text='Submit', width=47, command=self.gather_input) submit.pack(padx=8, pady=8) submit.place(x=20, y=425) def __select_previous(self, event): """ Handle scenario where user selects one of the previous participants """ # Collect from previous subjects, if it was chosen self.previous = self.input_previous.curselection() if self.previous: self.previous = self.folders[int(self.previous[0])] with open(join(DATA_DIR, self.previous, 'data.json')) as f: data = load(f) # Set the value for participant ID self.value_id.set(data['ID']) # Set the value for name and disable the user from making # any more changes self.value_name.set(data['Name']) self.input_name.config(state=DISABLED) # Set the value for pupilsize and disable the user from # making any more changes self.value_pupilsize.set(data['Pupil Size']) self.input_pupilsize.config(state=DISABLED) def gather_input(self): """ Gather the input from the Tkinter window and store it as class variables of the Participant class This module will also create a folder for the participant if it does not exist already in DATA_DIR NOTE: DATA_DIR is set in settings.py """ # Collect all the values input and convert to their appropriate # types self.subject_id = self.input_id.get() self.name = self.input_name.get().title() self.day = int(self.value_day.get()) try: self.pupilsize = float(self.input_pupilsize.get()) except ValueError: pass self.practice = bool(self.value_practice.get()) self.stereo = bool(self.value_stereo.get()) # Destroy the Tkinter window self.parent.destroy() # Put together the directory name and path self.subject_dir = '%s_%s' % (self.subject_id, self.name.replace(' ', '')) self.subject_dir = join(DATA_DIR, self.subject_dir) # If the directory for the participant does not exist, create it if not exists(self.subject_dir): makedirs(self.subject_dir)
class GUI: def __init__(self, master): self.master = master master.title("Naive Bayes Classifier") #set up vars for gui logic self.browse_text = StringVar() self.val_bins = master.register(self.validate_bins) self.isBin = False self.isBrowse = False self.isTest = '' self.isBrowse = '' self.isTrain = '' #buttons self.button_browse = Button(master, text='Browse', command=lambda: self.DisplayDir()) self.button_build = Button(master, text="Build", command=lambda: self.build()) self.button_classify = Button(master, text="Classify", command=lambda: self.classify()) #labels self.label_directory_path = Label(master, text="Directory Path") self.label_bins = Label(master, text="Discretization Bins") self.label_error = Label(master, text="", fg='red') #entries self.entry_browse = Entry(master, width=50) self.entry_bins = Entry(master, width=50, validatecommand=(self.val_bins, "%P", "%d"), validate='key') # LAYOUT self.button_browse.grid(row=1, column=4) self.entry_browse.grid(row=1, column=2, columnspan=2) self.label_directory_path.grid(row=1, column=1) self.label_bins.grid(row=2, column=1) self.entry_bins.grid(row=2, column=2) self.button_build.grid(row=3, column=1) self.button_classify.grid(row=3, column=2) self.label_error.grid(row=4, column=2) self.master.minsize(width=700, height=200) #control buttons self.button_build['state'] = 'disabled' self.button_classify['state'] = 'disabled' # #Logic self.modelBuilder = '' # build the model self.modelTrainer = ModelTrainer.ModelTrainer( ) # use the train file and clean it self.modelTest = ModelTest.ModelTest() self.modelClassifier = '' #classification def validate_bins(self, v, d): try: value = int(v) if value > 1: if self.isBrowse: self.button_build['state'] = 'normal' return True else: self.isBin = False tkMessageBox.showinfo("Alert Message", "Invalid number") return False except: if d == '0' and v == '': self.entry_bins.delete(1, 'end') if len(self.entry_bins.get()) == 1: self.button_build['state'] = 'disabled' self.button_classify['state'] = 'disabled' self.isBin = False return True tkMessageBox.showinfo("Alert Message", "Invalid number") return False def build(self): self.label_error.config(text="Begin building") self.modelBuilder = ModelBuilder.ModelBuilder(self.isStructure) self.modelTrainer = ModelTrainer.ModelTrainer(self.isTrain, self.modelBuilder, self.entry_bins.get()) self.modelTrainer.readFile() maxbins = self.modelTrainer.getMaxbins() if maxbins < int(self.entry_bins.get()): tkMessageBox.showinfo("Alert Message", "Invalid number of bins") elif os.stat(self.isTest).st_size == 0 or os.stat( self.isTrain).st_size == 0 or os.stat( self.isStructure).st_size == 0: tkMessageBox.showinfo("Alert Message", "One of the files is empty") else: self.modelTrainer.fillMissingValues() self.modelTrainer.discretization() tkMessageBox.showinfo( "Alert Message", "Building classifier using train-set is done!") self.button_classify['state'] = 'normal' self.label_error.config(text='') def classify(self): self.modelTest.setdata(self.isTest, self.modelBuilder, self.entry_bins.get()) self.modelTest.cleanData() self.modelClassifier = ModelClassifier.ModelClassifier( self.entry_browse.get(), self.modelTrainer.getData(), self.modelTest.getData(), self.modelBuilder, self.entry_bins.get()) self.modelClassifier.buildNaiveDictionary() self.modelClassifier.classify() self.modelClassifier.writeOutput() tkMessageBox.showinfo( "Alert Message", "Done classifying. output is ready in : {}".format( self.entry_browse.get())) def DisplayDir(self): feedback = askdirectory() self.browse_text.set(feedback) self.entry_browse.config(state='normal') self.entry_browse.delete(0, 'end') self.entry_browse.insert(0, self.browse_text.get()) self.entry_browse.config(state='readonly') self.isTest = os.path.join(self.browse_text.get(), "test.csv") self.isTrain = os.path.join(self.browse_text.get(), "train.csv") self.isStructure = os.path.join(self.browse_text.get(), "Structure.txt") self.texterror = "" if (os.path.exists(self.isTest) and os.path.exists(self.isTrain) and os.path.exists(self.isStructure)): if self.isBin: self.button_build['state'] = 'normal' self.button_classify['state'] = 'normal' self.label_error.config(text='folder content is valid !') else: self.texterror = "please fill bin text field" self.isBrowse = True else: if (not os.path.exists(self.isTrain) # and not os.path.exists(self.isStructure) and not os.path.exists(self.isTest)): self.texterror = "train.csv , structure.txt and test.csv were not found" elif (not os.path.exists(self.isTrain)): self.texterror = "train.csv was not found" elif (not os.path.exists(self.isStructure)): self.texterror = "Structure.txt was not found" elif (not os.path.exists(self.isTest)): self.texterror = "test.csv was not found" self.isBrowse = False self.label_error.config(text=self.texterror)