def todo_(): #reply = easygui.enterbox(msg = "TO-DO", title = "TO-DO", default = '', strip = True) #print reply #f = open ("../../data/TODO.txt", "w") #f.write (reply + "\n") #f.close ynreply = easygui.ynbox(msg = 'Do you want to choose from TODO template?', title = 'Please Answer', choices = ('Yes', 'No'), image = None) if ynreply == 1: default = todo_template() else: default = "Enter TODO Text" ynreply = easygui.ynbox(msg='Do you want to reset the TODO file?', title='Please Answer', choices=('Yes', 'No'), image=None) rw = '' if ynreply == 1: rw = "w" else: rw = "a" #fieldNames = ["TO-DO"] #fieldValues = [] # we start with blanks for the values while True: #fieldValues = easygui.enterbox(msg,fieldNames[0], fieldNames) reply = easygui.enterbox("Enter TO-DO", "Smart Clock v1.0", default, strip = True) if reply: f = open ("../../data/TODO.txt", rw) f.write (reply + "\n") f.close ynreply = easygui.ynbox(msg = 'Sure To Save?', title = 'Please Answer', choices = ('Yes', 'No'), image = None) if ynreply == 1: break else: break
def setPowerMangement(): msg = "Would you like to set startup and shutdown times?" title = "Configure Power Management" pmYesNo = eg.ynbox(msg, title) if pmYesNo == 0: return times = [] msg = "What time do you want the computers to turn on?" title = "Startup Time" while 1: try: startup_time = eg.enterbox(msg, title) if startup_time != None: startup_time = dparser.parse(startup_time) startup_time = startup_time.strftime('%H:%M:%S') times.append(startup_time) break except ValueError: eg.msgbox("Wrong Time Format.", "Error") continue if startup_time == None: no_startup_time = eg.ynbox("Skip setting a startup time?") if no_startup_time == 1: times.append("no_startup") break else: continue msg = "What time do you want the computers to turn off?" title = "Shutdown Time" while 1: try: shutdown_time = eg.enterbox(msg, title) if shutdown_time != None: shutdown_time = dparser.parse(shutdown_time) shutdown_time = shutdown_time.strftime('%H:%M:%S') times.append(shutdown_time) break except ValueError: eg.msgbox("Wrong Time Format.", "Error") continue if startup_time == None: no_shutdown_time = eg.ynbox("Skip setting a shutdown time?") if no_shutdown_time == 1: times.append("no_shutdown") break else: continue return times
def quit_prompt(student_list): """Asks if the user wants to quit or not. If yes, saves the student_list as a CSV file. """ if eg.ynbox("Cikmak istediginize emin misiniz?", choices=('Evet', 'Hayir')): csv_file = eg.filesavebox(title='Tabloyu kaydet',filetypes=['*.csv']) #Adds .csv extension if user did not already. if csv_file: if csv_file[-4:] != '.csv': csv_file += '.csv' with open(csv_file, 'wb') as f: writer = csv.writer(f, delimiter=';') writer.writerow(['AD', 'SOYAD', 'UNIVERSITE', 'OSYM PUANI', 'YILI', 'CBUTF TABAN PUANI', 'NOT ORTALAMASI', 'SINIF', 'EGITIM', 'DISIPLIN CEZASI', 'TELEFON', 'UYGUNLUK', 'PUAN']) student_list = sort_students(student_list) for student in student_list: writer.writerow(student.export_for_csv()) sys.exit(0) else: choice = eg.buttonbox(msg='Kaydetmeden cikmak istediginize emin misiniz?', title='Kaydetmeden cikis',choices=('Evet','Hayir')) if choice: sys.exit(0)
def command_process(command_str): if command_str: answer = will.main(command_str) answer_json = json.loads(answer) answer_text = answer_json["text"] answer_type = answer_json["return_type"] answer_action = answer_json["return_action"] if answer_type == "answer": easygui.msgbox(title="W.I.L.L", msg=answer_text) command() else: def enter_response(): response_text = easygui.enterbox(title="W.I.L.L", msg=answer_text) if response_text: response = {} response.update({"response_args":response_text,"response_type":answer_type, "return_action":answer_action}) for key in answer_json.keys(): if not response[key]: response.update({key:answer_json[key]}) new_answer = will.main(response) command_process(new_answer) else: if easygui.ynbox(title="W.I.L.L", msg="Would you like to exit?"): sys.exit() else: enter_response() enter_response() else: if easygui.ynbox(title="W.I.L.L",msg="Would you like to exit?"): sys.exit() else: command()
def downchoiceFunc(): if "torch" in fyrirUtan.items: knifedoorhole = eg.buttonbox("You see a Knife, a door and a hole in the ground.", choices=DownChoice, title=fyrirUtan.info) if knifedoorhole == "Pick up knife": eg.msgbox("You put the knife into your pocket", title=fyrirUtan.info) fyrirUtan.items.append("knife") del DownChoice[0] downchoiceFunc() elif knifedoorhole == "Open door": Basement.BDoor(22) elif knifedoorhole == "Go towards the hole": eg.msgbox("You walk to the hole and look down it.", title=fyrirUtan.info) time.sleep(0.5) eg.msgbox("You see light at the bottom. Looks safe enough to jump.", title=fyrirUtan.info) if eg.ynbox("Jump in the hole?", title=fyrirUtan.info) == 1: Basement.fall() else: eg.msgbox("You decide not to jump", title=fyrirUtan.info) downchoiceFunc() elif knifedoorhole == "Go back": eg.msgbox("You whent back up.", title=fyrirUtan.info) mainRoom() else: eg.msgbox("It sure is dar...", title=fyrirUtan.info) eg.msgbox("SHIT!", title=fyrirUtan.info) eg.msgbox("You fell into a hole.", title=fyrirUtan.info) time.sleep(0.75) Basement.fall()
def pre_sort(): msg = 'Would you like to predetermine specific file extensions?' title = 'File Sorter v1.0' if easygui.ynbox(msg, title): promptExtAndDest() else: pass
def do_after_download(self): """ Do something after downloading finished. """ files_string = "\n" for f in self.downloaded_file_list: logger.debug("Download to {}".format(f)) files_string = "{}[{}]\n".format(files_string, f) title = "Download" msg = textwrap.dedent( """\ Finished. {} Would you like to continue traversing? * Tips: [←][→] Move, [Enter] Select, [Esc] No """.format( files_string ) ) user_choice = easygui.ynbox(msg, title) if not user_choice: exit(0) else: self._reset_arguments()
def close_chromium(use_gui): if not use_gui: if input("Enter an character to close chromium: ")[:-1]: system("taskkill /F /IM chrome.exe > NUL") else: if easygui.ynbox("Do you want to close chromium?"): system("taskkill /F /IM chrome.exe > NUL")
def onclick(event): #Define pop up for when graph is clicked msg = "Do you want to choose x=%f"%(event.xdata) title = "Please Confirm" if eg.ynbox(msg, title, choices=('Yes', 'No'), image=None): # show a Continue/Cancel dialog print 'x=%f'%(event.xdata) print 'The difference is: ' + str( np.sin(event.xdata) - np.exp(-event.xdata/5)) pyplot.close() # user chose Continue
def Down(): def downchoiceFunc(): if "torch" in fyrirUtan.items: knifedoorhole = eg.buttonbox("You see a Knife, a door and a hole in the ground.", choices=DownChoice, title=fyrirUtan.info) if knifedoorhole == "Pick up knife": eg.msgbox("You put the knife into your pocket", title=fyrirUtan.info) fyrirUtan.items.append("knife") del DownChoice[0] downchoiceFunc() elif knifedoorhole == "Open door": Basement.BDoor(22) elif knifedoorhole == "Go towards the hole": eg.msgbox("You walk to the hole and look down it.", title=fyrirUtan.info) time.sleep(0.5) eg.msgbox("You see light at the bottom. Looks safe enough to jump.", title=fyrirUtan.info) if eg.ynbox("Jump in the hole?", title=fyrirUtan.info) == 1: Basement.fall() else: eg.msgbox("You decide not to jump", title=fyrirUtan.info) downchoiceFunc() elif knifedoorhole == "Go back": eg.msgbox("You whent back up.", title=fyrirUtan.info) mainRoom() else: eg.msgbox("It sure is dar...", title=fyrirUtan.info) eg.msgbox("SHIT!", title=fyrirUtan.info) eg.msgbox("You fell into a hole.", title=fyrirUtan.info) time.sleep(0.75) Basement.fall() eg.msgbox("You walk down the stairs and open the door.", title=fyrirUtan.info) eg.msgbox("You walk into a dark room. There is a lit torch on the wall.", title=fyrirUtan.info) print (fyrirUtan.items) if "torch" not in fyrirUtan.items: if eg.ynbox("Do you want to take the torch?", title=fyrirUtan.info) == 1: eg.msgbox("You take it up", title=fyrirUtan.info) fyrirUtan.items.append("torch") if eg.ynbox("Do you want to go deeper?", title=fyrirUtan.info) == 1: eg.msgbox("You go in deeper", title=fyrirUtan.info) downchoiceFunc() else: eg.msgbox("You go back up.", title=fyrirUtan.info) mainRoom() else: eg.msgbox("It sure is dark in here.", title=fyrirUtan.info) else: pass
def show_data(): data = open("cal_data.txt", "r") easygui.textbox("Here is the data recorded so far:", "Get the data!", data) print(data) if easygui.ynbox("Do you want to enter more information?", "Get the data!"): input_data() else: pass
def select_options(symbol_dic): """ Set a few options for the plots""" options = 0 # candle_chart = eg.ynbox(msg = 'Plot candle chart?', title = 'option 1') while options == 0: title = 'Please enter some information' msg = 'Note: the format for the date is dd/mm/yyyy. By default the end date is today, the start date, one month before' fieldNames = ['start_date','end_date','stock_symbol or company name'] fieldValues = eg.multenterbox(msg,title,fieldNames) if not fieldValues[1]: end = datetime.date.today() else: try: end = datetime.datetime(int(fieldValues[1][-4:]),int(fieldValues[1][-7:-5]),int(fieldValues[1][:2])) except: eg.msgbox('please use the correct format for the date, day / month / year') options = 0 continue if not fieldValues[0]: start = datetime.date.today()-datetime.timedelta(365/12) else: try: start = datetime.date(int(fieldValues[0][-4:]),int(fieldValues[0][-7:-5]),int(fieldValues[0][:2])) except: eg.msgbox('please use the correct format for the date, day / month / year') options = 0 continue if start > end: eg.msgbox('The start date should be before the end date, noob') options = 0 continue options = 1 """ Check the correctness of the entries""" if fieldValues[2] not in symbol_dic: fieldValues[2] = fieldValues[2].lower() idx = 0 for name in symbol_dic.values(): if fieldValues[2] in name: question = eg.ynbox('are you talking about %s?' %(name)) if question == 1: fieldValues[2] = symbol_dic.keys()[idx] break else: idx += 1 continue idx += 1 if idx == len(symbol_dic): eg.msgbox('the company is not in the database or the symbol is incorrect') options = 0 continue return start, end, fieldValues[2] #, candle_chart
def choose(): temp = easygui.ynbox("请选择要查找的宝箱类型!", "宝箱类型选择", choices=("[<F1>]物品宝箱", "[<F2>]可交互宝箱"), image=None, default_choice='[<F1>]物品宝箱', cancel_choice='[<F2>]可交互宝箱') if temp: mainsearch() else: mainsearch1()
def newevent(self, event): # Quit if needed if event.type == pygame.QUIT: common.running = False # Also, resize the screen elif event.type == pygame.VIDEORESIZE: # set width and height, then resize window common.width = event.w common.height = event.h common.screen = pygame.display.set_mode((common.width, common.height), RESIZABLE) self.render() # For now, quit launcher elif event.type == pygame.MOUSEBUTTONDOWN: mx, my = event.pos if event.button == 1: if self.loggedin: # select world if mx <= self.l.x+self.l.w: self.l.event(event) elif my >= self.l.y+3 and my <= self.l.y+53 and mx >= self.l.x+self.l.w+(common.width-400)-150 and mx <= self.l.x+self.l.w+(common.width-400): common.levelname = self.l.list[self.l.selecteditem] common.inlauncher = False elif my >= self.l.y+63 and my <= self.l.y+113 and mx >= self.l.x+self.l.w+(common.width-400)-150 and mx <= self.l.x+self.l.w+(common.width-400): # new world name = genmap.makeMap() if name: # self.l.list = [d for d in os.listdir(os.path.join(common.rootdir, "saves"))] common.levelname = name common.inlauncher = False elif my >= self.l.y+123 and my <= self.l.y+173 and mx >= self.l.x+self.l.w+(common.width-400)-150 and mx <= self.l.x+self.l.w+(common.width-400): if easygui.ynbox("Really Delete World?", "", ("Yes", "No")): shutil.rmtree(os.path.join(common.rootdir, "saves", self.l.list[self.l.selecteditem])) self.l.list = [d for d in os.listdir(os.path.join(common.rootdir, "saves"))] else: self.loggedin = True elif not self.loggedin: if event.button == 4: self.voffset += 20 if self.voffset >= 0: self.voffset = 0 elif event.button == 5: self.voffset -= 20 if self.voffset <= -self.vmaxheight: self.voffset = 0
def do(): Enter = eg.ynbox(msg='There is a deep dark hole in the ground. Should you jump into it?', title='22') if Enter == 1: eg.msgbox("You jump in the hole.", ok_button="Continue") sleep(2) eg.msgbox("You are falling...", ok_button="Continue") sleep(2) eg.msgbox("It takes you 5 seconds to fall to your death.", ok_button="Shit") exit() #F*****G TERMINATE THE PROGRAM HERE LATER HLYNUR. print("it no work") else: eg.msgbox("Good thing you are sane.", ok_button="Continue") eg.msgbox("You continue on to the room.", ok_button="Continue")
def change_city_gui(): ynreply = easygui.ynbox(msg='Do you want to Choose From the Listof Cities?', title='Choose', choices=('Yes', 'No'), image=None) if ynreply == 1: default = city_list() else: default = "Kanpur" reply = easygui.enterbox ("Change City", "Smart Clock v1.0", default, strip = True) if reply: f = open ("../../data/current_city.dat", "w") f.write (reply) f.close return
def gui_download_artifacts(self, task_name, task_id): """ GUI: select artifacts for downloading. @param task_name: the task name. @param task_id: the TaskId. """ choice_artifact_list = self.gui_select_artifacts(task_name, task_id) if choice_artifact_list: # if there is no target dir, then show gui for user self._check_target_dir() if self.dest_dir: self.downloaded_file_list = [] # after user select the dir, download artifacts for item in choice_artifact_list: logger.debug("Download: {}".format(item)) try: local_file = self.artifact_downloader.download_latest_artifact(task_id, item, self.dest_dir) self.downloaded_file_list.append(local_file) except Exception as e: logger.error(e) title = "Download Failed" msg = textwrap.dedent( """\ Can not download: [{}] Exception: {} * Tips: [Enter] OK """ ).format(item, e) easygui.msgbox(msg, title) self.do_after_download() else: # if user cancel the selection of dir, stop download. title = "Cancel" msg = textwrap.dedent( """\ Cancel. Would you like to continue traversing? * Tips: [←][→] Move, [Enter] Select, [Esc] No """ ) user_choice = easygui.ynbox(msg, title) if not user_choice: exit(0) else: self._reset_arguments()
def enter_response(): response_text = easygui.enterbox(title="W.I.L.L", msg=answer_text) if response_text: response = {} response.update({"response_args":response_text,"response_type":answer_type, "return_action":answer_action}) for key in answer_json.keys(): if not response[key]: response.update({key:answer_json[key]}) new_answer = will.main(response) command_process(new_answer) else: if easygui.ynbox(title="W.I.L.L", msg="Would you like to exit?"): sys.exit() else: enter_response()
def gui_input(): try: import easygui as gui while True: msg = 'Enter when your system should shut down' Lines = ['month', 'day', 'hour', 'minute'] userinput = gui.multenterbox(msg, "Alex little helper v1.3", Lines) for i, val in enumerate(userinput): if len(val) == 1: userinput[i] = '0' + userinput[i] if gui.ynbox('Do you want me to shut down\non the %s.%s. around %s:%s?' % tuple(userinput)): return userinput except: return None
def settings_ui(self): settingschoices=[ "Day view duration", "Week view duration", "Weather Duration", "Time & Date duration", "Change Last line of time screen" ] sc=easygui.choicebox(msg="Please make a selection", title="Wall Program", choices=settingschoices) if sc==settingschoices[0]: scn="dayview" elif sc==settingschoices[1]: scn="weekview" elif sc==settingschoices[2]: scn="weather" elif sc==settingschoices[3]: scn="timescreen" elif sc==settingschoices[4]: newline=easygui.enterbox("What should it say?") tf=open('html/timescreen.html') f=tf.read() current=f.split('id="lastline">')[1].split("<")[0] newf=f.replace(current,newline) tf.close() finalfile=open('html/timescreen.html','w') finalfile.write(newf) finalfile.close() sys.exit() elif sc==None: sys.exit() else: print "Unrecognized choice {0}".format(sc) sys.exit() svaluecurrent=self.get_setting(scn) if easygui.ynbox("Current duration for {0} is {1}. Would you like to change it?".format(sc,svaluecurrent)): def get_new_val(): try: newsval=easygui.enterbox("What should the duration be (in seconds)?") newsval=int(newsval) self.make_setting(scn,newsval) easygui.msgbox("Done") except TypeError: easygui.msgbox("Must be a valid integer") get_new_val() get_new_val() else: sys.exit()
def calculate_more(self): file_load_list = [] file_save_list = [] if self.ui.edit_slice.text() != ':' and easygui.ynbox(msg="Maybe you want to change the slice setting to ':'?"): self.ui.edit_slice.setText(':') while True: file_load = easygui.fileopenbox(default='/home/richter/Data/Parkfield/receiver/M5.5_events/*.QHD', filetypes=['*.QHD', '*.*']) if file_load == None: break file_save = easygui.filesavebox(msg='Please omit file ending.', default='/home/richter/Data/Parkfield/receiver/*') if file_save == None: break file_load_list.append(file_load) file_save_list.append(file_save) for i in range(len(file_load_list)): self.open_data(file_load_list[i]) self.save_rf(file_save_list[i])
def do_after_download(self): """ Do something after downloading finished. """ for f in self.downloaded_file_list: logger.debug('Download {}'.format(f)) title = 'Download' msg = textwrap.dedent('''\ Finished. Would you like to continue traversing? * Tips: [←][→] Move, [Enter] Select, [Esc] No ''') user_choice = easygui.ynbox(msg, title) if not user_choice: exit(0)
def cast_main(leader, sentence, *args, **kwargs): log.info("In cast") def cast(chromecast): #cast = pychromecast.get_chromecast(friendly_name=chromecast) #cast.wait() if leader == "netflix" or sentence.split(" ")[1] == "netflix" or "netflix" in args["ents"].keys().lower(): log.info("Sentence is {0}".format(sentence)) full_sentence = (leader, sentence) full_text = ' '.join(full_sentence) netflix(full_text, args) known_chromecasts = config.load_config("chromecasts") log.info("Known chromecasts are {0}".format(str(known_chromecasts))) chromecasts_available = pychromecast.get_chromecasts_as_dict().keys() chromecast_name = None for chromecast in chromecasts_available: if isinstance(known_chromecasts, list): if chromecast in known_chromecasts: chromecast_name = chromecast elif isinstance(known_chromecasts, str): if chromecast == known_chromecasts: chromecast_name = chromecast else: return "Error: unrecognized chromecast conifg {0}".format(str(known_chromecasts)) if chromecast_name: cast(chromecast_name) else: chromecast_choice = easygui.buttonbox(title="Chromecasts Found", msg="Please choose a chromecast", choices=chromecasts_available) if chromecast_choice: if easygui.ynbox("Would you like to save this chromecast in your W.I.L.L config?"): config.add_config({"known_chromecasts":[chromecast_choice]}) cast(chromecast_choice) else: return "Error: No chromecast chosen" # cast.wait() # print(cast.device) # # print(cast.status) # # mc = cast.media_controller # mc.play_media('http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4', 'video/mp4') # print(mc.status) # # mc.pause() # time.sleep(5) # mc.play()
def path_selector(self): if self.mode != 1: configs = configObj.read_config() count = 1 path_list = [] for i in configs: tup = '' if not os.path.isfile(i[1]): tup = '(broken link)' path_list.append('%d.%s%s' % (count, i[0], tup)) count += 1 if len(path_list): self.path = easygui.choicebox(title="YoDa by Yogi", msg="You have set following download managers", choices=path_list) if not self.path: easygui.msgbox(title='YoDa by Yogi', msg="You haven't selected any Download Manger") exit(0) if 'broken' in self.path: broken_choice = ['Continue to url only mode', 'Exit'] broken_op = easygui.buttonbox(title='YoDa by Yogi', msg=('Your path to the download manager doesn' + '\'t seem to be working'), choices=broken_choice) if broken_op == broken_choice[0]: self.mode = 1 else: exit(0) if self.path: index = int(self.path.split('.')[0])-1 self.path = configs[index][1] self.cmd = configs[index][2] else: stal_op = easygui.ynbox(title='YoDa by Yogi', msg=('You haven\'t configured any download manager' + '. Continue to URL only mode?'), choices=['Continue', 'Exit']) if stal_op: self.mode = 1 else: exit(0) if self.mode == 2: qual = self.name[1] self.name = self.name[0] self.getter({qual: self.download_address}) else: self.link_input() else: self.link_input()
def getdata(inputtype, easyguiargs): '''Use easygui methods to get data and check if the user wants to exit if they hit cancel''' print inputtype print easyguiargs if inputtype != "enterbox" and inputtype != "msgbox" and inputtype != "ynbox": print easyguiargs print easyguiargs[0] print easyguiargs[1] answer = getattr(easygui, inputtype)(easyguiargs[0], "Create a plugin", easyguiargs[1]) else: answer = getattr(easygui, inputtype)(easyguiargs) if answer != None: return answer else: if easygui.ynbox("Would you like to exit?"): sys.exit() else: getdata(inputtype, easyguiargs)
def Choice_Backup_Live(): rightnow = datetime.datetime.now() defaultfilename = rightnow.strftime("%B") defaultfilename = defaultfilename[:3] if easygui.ynbox('Online Backup?') == 1: ynonline = "online" else: ynonline = "" easygui.msgbox(msg='After selecting Source, Destination & Online please wait, this can take a while and you will see no progress bar.') PilotApp.Backup( easygui.fileopenbox( 'Select database to backup', default=PilotApp.Settings['EpicorDBDir']+'\\'), easygui.filesavebox( 'Filename to backup to', default=PilotApp.Settings['EpicorDBDir']+'\\'+ defaultfilename + 'live' + str(rightnow.day ) ), ynonline)
def dodo(): eg.msgbox("Warning this room is incomplete! Check back soon for updates and fixes!") if dead == False: print("its true") elif dead == True: eg.msgbox("You feel darkness. You feel as you should not enter") print("Its false") else: pass enterQ = eg.ynbox("Do you want to enter?") if enterQ == 1: eg.msgbox("You continue on to the room.", ok_button="Continue", title=fyrirUtan.info) eg.msgbox("You open a large door.", ok_button="Continue", title=fyrirUtan.info) eg.msgbox("(Door opening sounds)", ok_button="Continue", title=fyrirUtan.info) mainRoom() else: eg.msgbox("Fine Then", ok_button="Continue", title=fyrirUtan.info) leave()
def main(): base_address = easygui.enterbox(title='Distance Calculator', msg='Main Address: ') other_addresses = get_file_data() if other_addresses: if easygui.ynbox('Do you want to log data? '): logfile = open('..\\logs\\dist_log.txt', 'at') logfile.write('From: {}\n'.format(base_address)) total_distance = get_total_distance(base_address, other_addresses, logfile) logfile.write('Total: {}\n\n'.format(total_distance)) logfile.close() else: total_distance = get_total_distance(base_address, other_addresses) if total_distance: msg = '{} miles'.format(total_distance) easygui.msgbox(msg) else: easygui.msgbox('Error finding distance') else: easygui.msgbox('Error with Address File')
def enter_settings(self): s1 = "What is your local time zone? (i.e. Australia/Perth.) Used to determine the UTC/GMT time for file naming purposes." self.timezone_name = easygui.choicebox(s1, "Choose local time zone", pytz.common_timezones) s2 = "Enable debug mode? (Displays very detailed program execution information on screen.)" a = easygui.buttonbox(s2,"Debug mode?",("Normal mode (recommended)","Debug mode (experts only)")) self.debug_mode = True if a.lower().startswith("debug") else False s3 = "Save emails older than X days: (default 60 days; 0 for all emails regardless of age.)" self.days_old = easygui.integerbox(s3,"Email age?",default=60, lowerbound=0, upperbound=99999999) self.dest_dir = easygui.diropenbox("Pick a folder to save the email .msg files to.", "Choose backup destination", "%HOMEPATH%") b = easygui.ynbox("Apply 'Saved as MSG' tag to emails that are saved?", title="Mark emails as saved?", choices=("Yes (recommended)","No (experts only)")) self.mark_as_saved = bool(b)
def get_symbol(self): """ Get the symbol associated with the company's or index name. Careful: If not in interactive mode, using company's name in class initialization is not recommended, or it has to be exactly matching the name in the dictionary. """ idx = 0 for company_name in SYMBOL_DIC.values(): if self._name.lower() == company_name[0]: # <-- check for exact match first self._symbol = SYMBOL_DIC.keys()[idx] break elif self._name.lower() in company_name[0] and self._interactive == True: # <-- if partial match and interactive mode, ask the user question = eg.ynbox('are you talking about %s?' %(company_name[0])) if question == 1: self._symbol = SYMBOL_DIC.keys()[idx] break idx += 1 if self._symbol == 'unknown': # <-- after checking all entries of the dictionary print('The provided company name does not match any symbol') del self sys.exit() return self._symbol
def ask_firmware_update(self, old_version, new_version): return easygui.ynbox( 'New system firmware is available, update now?\n' + str(old_version) + ' -> ' + str(new_version) + '\n', self.title, ('Yes', 'No'))
#print ("Vaheguru Jee Kaa Khalsa Vaheguru Jee Kee Fateh") #print ("gv-downloader") #input("The downloader will now ask you to select the playlist.m3u file you have downloaded for which tracks you would like to download. Please press enter to continue...") path = g.fileopenbox() file = open(path, "r") contents = file.read() print(" ") print(("Reading file ") + (os.path.basename(file.name))) if (os.path.basename(file.name)) != "playlist.m3u": oui_2 = g.ynbox( ("You selected the file ") + (os.path.basename(file.name)) + ("\n") + ("Are you sure this is the file you meant to select? If yes, the downloader will continue. If no, you will be prompted to select a file again." ), "GV Downloader") #print (("You selected the file ") + (os.path.basename(file.name))) #oui = input ("Are you sure this is the file you meant to select? If yes, the downloader will continue. If no, you will be prompted to select a file again. ") if oui_2 == ("True"): pass elif oui_2 == ("False"): path = easygui.fileopenbox() file = open(path, "r") contents = file.read() #if oui in yes_list: # pass #elif oui in no_list:
errors=errors+"WARNING:Total current is not balanced. You will need to attach an electrode to pin #3 to absorb "+str(totalCurrent)+" mA of excess current\n" if totalCurrent < 0: errors=errors+"WARNING:Total current is not balanced. You will need to attach an electrode to pin #13 to absorb "+str(abs(totalCurrent))+" mA of excess current\n" errorAbort=False if len(errors) > 0: if fatalError: errorAbort=True eg.msgbox(title="Critical protocol errors detected",msg="This protocol cannot be used because of errors. All errors and warnings are listed below.\n"+errors) continueRun=eg.buttonbox(title="Protocol issues detected", msg="At least one warning or safety issue was detected in this protocol. Do you want to continue?\n All issues are listed below.\n"+errors, choices=["Yes", "No"]) if "No" in continueRun: errorAbort=True if not errorAbort: print("Load protocl") outcomeSummary=protosplit[1].replace("NPHYS","Neurophysiological measurements").replace("/1"," before session").replace("/2"," after session").replace("/3"," before and after session") summary="DURATION:"+protodict.get("duration")+" minutes\nSHAM PROBABILITY:"+protodict.get("sham")+"%\nRAMPING DURATION:"+protodict.get("rampdur")+" seconds"+"\nFREQUENCY:"+protodict.get("frequency")+"\nPOWER LEVELS:\n"+eList+"OUTCOME MEASURES:\n"+outcomeSummary+"\n\nDo you want to run this protocol?" runproto=eg.ynbox(title="Protocol summary",msg=summary) if runproto: presession=[] postsession=[] prename="" postname="" hasData=False preData=[] postData=[] if randint(0,100) <= int(protodict.get("sham")): sham=True else: sham=False for item in protosplit[1].split("\n"): if "/1" in item or "/3" in item and "NPHYS" not in item: presession.append(item[:item.find("/")])
mexp.append(eatmillet) mdom.append(1 - np.mean(millet_df.mprop)) mdens.append((np.mean(millet_df.mpatch))/1000.) p1.set_data(yr, hpop) p2.set_data(yr, dpop) p3.set_data(yr, mpop) p4.set_data(yr, dkil) p5.set_data(yr, mexp) p6.set_data(yr, mdom) p7.set_data(yr, mdens) plt.draw() ###### ###### Simulation has ended, pop up a gui box to ask if/where to save files. msg = "Simulation finished. Do you want to save any stats or graphics?" title = "Simulation Finished." if eg.ynbox(msg, title): # show a Yes/No dialog choices = eg.multchoicebox("Which output files would you like to create?", "Data Output", ("General Stats","Millet Patches Stats","Plot")) else: # user chose No sys.exit(0) if "General Stats" in choices: gsf = eg.filesavebox("Choose a file to save the general stats to", "Save General Stats", default='%s%sSimulation_general_stats.csv' % (os.getcwd(), os.sep), filetypes=["*.csv", "Comma separated ASCII text files"]) mstatsout = pd.DataFrame(data=np.array([yr, hpop, hkcald, dpop, dkil, mpop, mexp, mdom, mdens]).T, columns = ["Year","Total Human Population","Human Kcal Deficit","Total Deer Population","Number of Deer Eaten","Total Millet Population (*10^3)","Number of Millet Patches Exploited","Proportion of Domestic-Type Millet","Average Millet Patch Density (*10^3)"]) # put the main stats data in a pandas data frame for easy formatting if gsf is '': # did the user press cancel, or not enter a file name? If so, then pass, otherwise, write the file. pass else: mstatsout.to_csv(gsf, float_format='%.5f') else: pass if "Millet Patches Stats" in choices: msf1 = eg.filesavebox("Choose a file to save the millet patches density stats to", "Save Millet Patch Stats", default='%s%sSimulation_millet_patch_density_stats.csv' % (os.getcwd(), os.sep), filetypes=["*.csv"]) if msf1 is '':
def writetofile(): yn = gui.ynbox("Write to file? (Recommended)") if yn: return gui.filesavebox("Save to:", "HASHIT") else: return False
def execute_main(self): t1 = threading.Thread(target=self.thread1) t2 = threading.Thread(target=self.thread2) t1.start() t2.start() t1.join() t2.join() db_object = DatabaseUtility(self.v_task_type, self.lo) if db_object.connection(): self.lo.log_to_file('INFO', 'Successful Connection') else: self.lo.log_to_file('ERROR', 'DB Server is not active') return v_start_time = time.time() self.lo.log_to_file("INFO", "Login in to DC4 Prod") login_obj = Login(self.v_task_type, self.v_driver, self.v_input_wb, self.lo) selenium_operation_obj = SeleniumOperations(self.v_task_type, self.v_driver, self.lo) report_file_obj = ReportFileUtility(self.v_task_type) input_sheet = self.v_input_wb.get_sheet_by_name('Input') input_sheet_row_count = input_sheet.max_row excel_operation_obj = ExcelOperations(self.v_task_type, input_sheet) Web_Fulfillment_Utility_obj = Web_Fulfillment_Utility( self.v_task_type, self.v_driver, self.v_input_wb, self.lo, self.v_username, db_object, self.v_driver_mv) # login_obj.login("Salesforce") self.v_driver.execute_script( "window.open('http://dc4ui.p01.pro:7777/dc4custmanager/faces/home.jsp', 'new_window')" ) # self.v_driver.execute_script( # "window.open('https://atlassian.spscommerce.com/browse/FICS-163692', 'new_window')") self.v_driver.switch_to.window(self.v_driver.window_handles[-1]) report_file_object = ReportFileUtility(self.v_task_type) time.sleep(2) login_obj.login("DC4 Prod") input_row = input_sheet_row_count + 1 FICS_Number = excel_operation_obj.get_value(input_row, 1) flag = 1 count = 0 v_start_time = time.time() while (flag): v_start_time1 = time.time() v_salesforce_id = easygui.enterbox('Please enter salesforce ID') self.v_driver.switch_to.window(self.v_driver.window_handles[0]) time.sleep(2) #self.v_driver.get('https://atlassian.spscommerce.com/browse/'+FICS_Number) #v_supplier_name, v_email_address, v_phone_number, v_retailer_name, v_billing_address, v_vendor_number, v_retailer_web_company_uid, v_account_number, v_retailer_dc4_company_uid, v_contact_name, v_salesforce_id = Web_Fulfillment_Utility_obj.get_info_from_JIRA() v_supplier_name, v_email_address, v_phone_number, v_retailer_name, v_billing_address, v_vendor_number, v_retailer_web_company_uid, v_account_number, v_retailer_dc4_company_uid, v_contact_name, client_uid, retailer_uid = Web_Fulfillment_Utility_obj.get_info_from_salesforce( v_salesforce_id) print(v_salesforce_id + "\n" + v_supplier_name + "\n" + v_email_address + "\n" + v_phone_number + "\n" + v_retailer_name + "\n" + v_vendor_number + "\n" + v_retailer_web_company_uid + "\n" + v_account_number + "\n" + v_retailer_dc4_company_uid + "\n" + v_contact_name) print(v_billing_address) self.v_driver.switch_to.window(self.v_driver.window_handles[-1]) time.sleep(2) #Web_Fulfillment_Utility_obj.get_data_for_library(v_salesforce_id, v_supplier_name, v_retailer_name, v_retailer_dc4_company_uid, FICS_Number) Web_Fulfillment_Utility_obj.run_setup_tool( v_salesforce_id, v_supplier_name, v_email_address, v_phone_number, v_retailer_name, v_billing_address, v_vendor_number, v_retailer_web_company_uid, v_account_number, v_retailer_dc4_company_uid, v_contact_name, client_uid, retailer_uid) print(input_row) count = count + 1 excel_operation_obj.set_value(input_row, 1, count) FICS_Number = excel_operation_obj.get_value(input_row, 1) v_end_time1 = time.time() excel_operation_obj.set_value( input_row, 2, math.floor(v_end_time1 - v_start_time1)) excel_operation_obj.set_value(input_row, 3, datetime.date.today()) print( '----------------------------------------------\n\nExecution Time: ' + str(math.floor(v_end_time1 - v_start_time1)) + ' count: ' + str(count) + '\n\n-------------------------') time.sleep(2) input_row = input_row + 1 self.v_input_wb.save(AppConstants.INPUT_FILE_PATH) flag = easygui.ynbox('Do you want to run one more setup?') v_end_time = time.time() report_file_object.update_sheet(self.v_username, count, math.floor(v_end_time - v_start_time), str(datetime.date.today()))
order by wojewodztwo; """ kursor.execute(pytanie) # wyłuskać nazwy kolumn z odpowiedzi do listy naglowek naglowek = [] for i in range(len(kursor.description)): naglowek.append( kursor.description[i][0] ) odpowiedz = kursor.fetchall() kursor.close() polaczenie.close() if easygui.ynbox('Odpowiedź otrzymano. Czy pokazać wyniki?', 'Zapytanie do bazy'): tekst = naglowek[0] + '\t' + naglowek[1] + '\t' + naglowek[2] + '\n' for wpis in odpowiedz: tekst += wpis[0]+'\t'+str(wpis[1])+'\t'+str(wpis[2])+'\n' easygui.textbox('Treść zapytania:\n' + pytanie, 'Wyniki', tekst) del(tekst) nazwapliku = easygui.filesavebox(None, 'Gdzie zapisać wyniki?', 'dane/*.txt') if nazwapliku: plik = open(nazwapliku, 'w') plik.write('# ' + naglowek[0] + '\t' + naglowek[1] + '\t' + naglowek[2] + '\n') for wpis in odpowiedz: plik.write(wpis[0].encode('utf-8')+'\t'+str(wpis[1])+'\t'+str(wpis[2])+'\n') plik.close()
from random import randint import easygui question = easygui.ynbox(msg="Are you sure you want to continue?") # q2 = easygui.multpasswordbox() q3 = easygui.passwordbox() q4 = easygui.choicebox(msg="Maak je keuze.", title="ABC", choices=("A", "B", "C")) q5 = easygui.codebox(msg="Uitkomst.", title="RES", text=(q4)) q6 = easygui.diropenbox() # print ("test") print(q4)
import easygui, random greeting_words = """Hello There. My name is Pirate Roberts, and I have a number puzzle. Would you want to play a puzzle game? """ title_ynbox = "NUMBER PUZZLE" if easygui.ynbox(greeting_words, title_ynbox): easygui.msgbox("OK, Let's play.\nIt's a secret number from 1 to 99.\nYou have 6 tries.") else: easygui.msgbox("Bye.") sys.exit(0) secret_number = random.randint(1,99) try_times = 0 guess_number = easygui.integerbox(msg="Let's begin. Please guess a integer number: ", lowerbound=0, upperbound=99) #print("Hello! My name is Pirate Roberts, and I have a number puzzle.") #print("Would you want to play a puzzle game? OK, You have 6 tries.") while try_times <= 6: if guess_number < secret_number: easygui.integerbox(msg="Too low. Please try again. Give me another number: ", lowerbound=0, upperbound=99) elif guess_number > secret_number: easygui.integerbox(msg="Too high. Please try again. Give me another number: ", lowerbound=0, upperbound=99) try_times = try_times + 1 if guess_number == secret_number: easygui.msgbox(f"You are correct. The number is {secret_number}. ") else: easygui.msgbox(f"No more guess. Wish you have a better luck!\nThe secret number is {secret_number}")
font = ImageFont.truetype("/usr/share/fonts/dejavu/DejaVuSans.ttf", 90) db = MySQLdb.connect("localhost", "loki", "******", "coe") cursor = db.cursor() sql = "SELECT * FROM stud" cursor.execute(sql) results = cursor.fetchall() c = 0 for row in results: name, email, coll = row img = Image.open('Sample Certificate Image.jpg') draw = ImageDraw.Draw(img) draw.text((1650 - 10 * len(name), 830), name, (0, 0, 0), font=font) if coll[-1] == 'y': draw.text((700, 1100), coll, (0, 0, 0), font=font) else: draw.text((1300, 1100), coll, (0, 0, 0), font=font) draw = ImageDraw.Draw(img) img.save(name + ".png") img.show() c += 1 if (easygui.ynbox('Email the certificate ?', 'Confirm Certificate', ('Yes', 'No'))): SendMail(name + ".png", email, name) print str(c) + ") Sent to " + name else: print str(c) + ") Not Sent to " + name db.close()
def pepEncoder(peptides = [], cT = 1, saved = '', ftype = '', aminopath = path1 + '/PDBFILES' , useNormal = False, csv = True, picture = True): asked = False max_length = 0 max_width = 0 j = 0 if len(peptides) == 0: ftype = eg.buttonbox('Type in a single sequence, or read from csv file?', choices = ('Sequence','Csv file')) if ftype.lower() == 'sequence': ftype = 's' peptides = [list(eg.enterbox('Sequence: ').upper())] elif ftype.lower() == 'csv file': ftype = 'c' filename = '' filenamelist = list(eg.fileopenbox(msg = 'Csv file location:')) for i in filenamelist: if i != '\\': filename = filename + i else: filename = filename +'/' peptides = np.loadtxt(filename, dtype = 'str') else: con = eg.ynbox('Please give a valid response, \n Continue? ') if con: pepEncoder() else: sys.exit('exit') savedlist = list(eg.diropenbox(msg = 'Where did you want this to be saved?')) cT = int(eg.buttonbox('Is this with 1 character amino acids, or 3?', choices = ('1','3'))) for i in savedlist: if i != '\\': saved = saved + i else: saved = saved +'/' useNormal = eg.ynbox('Did you want to nomralize the ecoding?') savetype = eg.buttonbox('Save it as a picture, csv, or both?', choices = ('Picture', 'Csv file', 'Both')) if savetype == 'Picture': csv = False if savetype == 'Csv file': picture = False if saved == '': saved = path1 + '/peptides' if not os.path.exists(saved): os.makedirs(saved) peplen = len(peptides) times = [] counting = False for i in peptides: j = j + 1 if saved != '': os.chdir(saved) if os.path.isfile('peptide'+str(j) +'.csv') and not asked: rewrite = eg.ynbox(msg = "Rewrite current peptides?") asked = True if os.path.isfile('peptide'+str(j) +'.csv') and not rewrite: matrix = np.genfromtxt('peptide'+str(j) +'.csv', delimiter=',') max_length = max(max_length, matrix.shape[0]) max_width = max(max_width, matrix.shape[1]) else: begin = time.time() if ftype == 'c': sequence = i.upper().split(',') else: sequence = i if aminopath != '': os.chdir(aminopath) matrix = gAA.generatePep(sequence, charType= cT) max_length = max(max_length, matrix.shape[0]) max_width = max(max_width, matrix.shape[1]) if saved != '': os.chdir(saved) gAA.printSequence(matrix, 'peptide'+str(j), makecsv = csv, makepicture = picture) end = time.time() times.append((end-begin)/3600) if peplen > 50: if counting or len(times) != 0: counting = True str_format = "{0:." + str(5) + "f}" print ("Encoding: ","ETA: ", str(round((sum(times)/len(times)*(peplen-j)), 4)), "(hours)", str_format.format(100 * (j / float(peplen))),"percent complete ", end = '\r') else: str_format = "{0:." + str(5) + "f}" print ("Encoding: ","ETA: "," ??? " , "(hours)", str_format.format(100 * (j / float(peplen))),"percent complete ", end = '\r') print ('') counting = False j = 0 times = [] end = 0 for filename in os.listdir(saved): if filename.endswith(".csv"): begin = time.clock() j = j + 1 matrix = np.genfromtxt(filename, delimiter=',') if useNormal: if aminopath != '': os.chdir(aminopath) matrix = normalizeData(matrix) if saved != '': os.chdir(saved) filename = filename.replace(".csv", "") m = np.zeros((max_length, max_width)) m[0:matrix.shape[0], 0:matrix.shape[1]] = matrix gAA.printSequence(m, filename, makecsv = csv, makepicture = picture) end = time.clock() times.append((end-begin)/3600) if peplen > 50: if counting or len(times) != 0: counting = True str_format = "{0:." + str(5) + "f}" print ("Reformating: ","ETA: ", str(round((sum(times)/len(times)*(peplen-j)), 4)), "(hours)", str_format.format(100 * (j / float(peplen))),"percent complete ", end = '\r') else: str_format = "{0:." + str(5) + "f}" print ("Reformating: ","ETA: "," ??? " , "(hours)", str_format.format(100 * (j / float(peplen))),"percent complete ", end = '\r') print ('Sucessfully genorated ', str(peplen), ' peptides.') for i in reversed(range(10)): print ('Closing in: ', str(i+1), end = '\r') time.sleep(1) return #app = Flask(__name__) #@app.route('/') ##def home(): ## return render_template('calc.html') # #def index(): # print(pepEncoder()) # return # #if __name__ == "__main__": # app.run()
if np.abs(on_times[j] - on_times[j + 1]) > 30: end.append(on_times[j]) start.append(on_times[j + 1]) try: end.append( on_times[-1] ) # append the last trial which will be missed by this method except: pass # Continue without appending anything if this port wasn't on at all start_points.append(np.array(start)) end_points.append(np.array(end)) # Show the user the number of trials on each digital input channel, and ask them to confirm check = easygui.ynbox( msg='Digital input channels: ' + str(dig_in_pathname) + '\n' + 'No. of trials: ' + str([len(ends) for ends in end_points]), title= 'Check and confirm the number of trials detected on digital input channels' ) # Go ahead only if the user approves by saying yes if check: pass else: print("Well, if you don't agree, blech_clust can't do much!") sys.exit() # Ask the user which digital input channels should be used for getting spike train data, and convert the channel numbers into integers for pulling stuff out of change_points dig_in_channels = easygui.multchoicebox( msg= 'Which digital input channels should be used to produce spike train data trial-wise?', choices=([path for path in dig_in_pathname])) dig_in_channel_nums = []
def flip(): output1 = easygui.ynbox( ' ', 'Flip', (' Vertical ', ' Horizontal ')) return output1
return '{}_{}.{}'.format(device, timestamp(date, time), extension) camera = PiCamera() basefolder = "./capture" easygui.msgbox("Welcome to Muday Lab Root Snap Program") while True: prompt = 'What is the unique name (or number) of this seedling box?\n Note: A name is required to uniquely identify the seedling box' device = easygui.enterbox(prompt, title="Specify Device name", default=DEVICE) if device is None: if not easygui.ynbox("Do you want to continue?"): easygui.msgbox("Program cancelled. Exiting") sys.exit(0) else: DEVICE = device break while True: prompt = "Enter Resolution 1=1024x768, 2=2592,1944, or custom resolution separated by commas, ENTER to quit: " resolution = easygui.enterbox(prompt, title="Specify Resolution") #resolution = input(prompt) if resolution is None or resolution == "": print("Exiting") sys.exit(0)
np.abs(np.gradient(np.mean(behaviour_frames[:, grad_mask], axis=1))), 20) signal_mean = np.mean(roi_gradient_signal) signal_std = np.std(roi_gradient_signal) answer = True while answer: SIGMA = easygui.enterbox('Enter value for SIGMA:') threshold = signal_mean + np.float64(SIGMA) * signal_std plt.figure() plt.plot(roi_gradient_signal) plt.axhline(threshold) plt.show() answer = easygui.ynbox('Retry?', 'Title', ('Yes', 'No')) # load brain data l_mouse_processed_file = direc.file(exp_folder=EXP, fname="left green 0.01-12.0Hz", subfolder="Derivatives") l_mouse_frames = vp.extract_RAW_frames(l_mouse_processed_file, 256, 256, dtype='float32', num_channels=1) ## equate video lengths assert np.abs(l_mouse_frames.shape[0] - roi_gradient_signal.shape[0]) < 10 while l_mouse_frames.shape[0] != roi_gradient_signal.shape[0]:
import easygui import turtle import math import time import datetime l = easygui.ynbox('', 'Codemao', ('是', '否')) k = False f = 0 Pn = turtle.Pen() Pen = turtle.Pen() Pn.penup() Pen.penup() Pn.goto((-300), 0) Pen.goto((-175), 75) Pen.hideturtle() Pn.shape('turtle') if not l: Pen.write('Turtle', font=('Arial', 108, 'italic')) while True: if k: t = datetime.time.microsecond f1 = ((f % 4) / 2) f3 = ((f % 4) % 2) F = f1**0.5 if f3 == 1 else (f1 + 2)**0.5 Pn.forward(1 + F) f += 1 if k: m = datetime.time.microsecond n = m - t if l: #print(f, " ", f1, " ", f3, " ", str(F)[:5],end=" ")
def run(self, use_updated=False): try: usr_choice = easygui.ynbox('是否执行v2ray云彩姬一键安装脚本?', install_title) if usr_choice: # 首次安装 if use_updated is False: PrepareEnv() for x in range(3): self.open_dir = easygui.diropenbox( '请选择安装路径', install_title, default=LOCAL_DIR_DATABASE) # 退出-放弃更新 if self.open_dir is None: return False # 选择限制 if os.listdir(self.open_dir): easygui.msgbox('当前目录下存在其他文件,请选择独立的文件夹!', TITLE) else: # 记录用户选择的下载目录,便于软件更新时的项目文件拉取 with open(LOCAL_PATH_DATABASE_YAML, 'w', encoding='utf-8') as f: proj = USER_YAML proj['path'] = self.open_dir yaml.dump(proj, f) break # 给头铁的孩子一点教育 else: easygui.msgbox('操作有误,请重试!', TITLE) return False # 软件更新 else: try: self.kill_main() # fixme:将updated模块移植到系统路径,通过外部操作控制软件更新; # TODO: 将self.open_dir赋值为软件所在路径 with open(LOCAL_PATH_DATABASE_YAML, 'r', encoding='utf-8') as f: data = yaml.load(f, Loader=yaml.FullLoader) print(data['path']) # self.open_dir = easygui.diropenbox() self.open_dir = data['path'] except Exception as e: print(e) # 下载线程 os.startfile(self.open_dir) print(f"install path >> {self.open_dir}") with ThreadPoolExecutor(max_workers=1) as t: t.submit(self.download) # t.submit(easygui.msgbox, '正在拉取项目文件,请等待下载', install_title) easygui.msgbox('下载完成', install_title) # 解压线程 with ThreadPoolExecutor(max_workers=2) as t: t.submit(UnZipManager, self.open_fp) t.submit(easygui.msgbox, '正在解压核心组件,请等待解压', title=install_title) easygui.msgbox('解压完成', install_title) # 自启动 target_file = self.open_fp.replace( '.zip', '') + f'_v{get_server_version()[0]}' try: os.startfile(os.path.join(target_file, v2raycs_name)) except OSError: pass finally: for filename in os.listdir(self.open_dir): if '.zip' in filename: try: os.remove(os.path.join(self.open_dir, filename)) except OSError: pass elif os.path.basename(target_file).split( '_')[-1] != filename.split('_')[-1]: if os.path.basename(target_file).split( '_')[0] in filename: try: shutil.rmtree( os.path.join(self.open_dir, filename)) os.rmdir( os.path.join(self.open_dir, filename)) except OSError: pass except Exception as e: easygui.exceptionbox(f'{e}') # over finally: easygui.msgbox('感谢使用', install_title)
pen.write("Player A: {} Player B : {}".format(score_a, score_b), align="center", font=("Courier", 24, "normal")) #paddle and ball collision if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle_b.ycor() + 50 and ball.ycor() > paddle_b.ycor() - 50): ball.setx(340) ball.dx *= -1 winsound.PlaySound("bounce.wav", winsound.SND_ASYNC) if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < paddle_a.ycor() + 50 and ball.ycor() > paddle_a.ycor() - 50): ball.setx(-340) ball.dx *= -1 winsound.PlaySound("bounce.wav", winsound.SND_ASYNC) if max(score_b, score_a) >= 10: yn = easygui.ynbox('Game over', 'Continue?', ('Yes', 'No')) if yn == 'Yes': score_b = score_a = 0 pen.clear() pen.write("Player A: {} Player B : {}".format(score_a, score_b), align="center", font=("Courier", 24, "normal")) window.update() # need to fix the yes catagory else: break
valores = valores.split(',') # if valores is not list: # x = valores # valores = [] # valores.append(x) easygui.msgbox("COMEÇAR?") time.sleep(5) for i in valores: kb.write(i) kb.send('enter') time.sleep(5) kb.send('f8') time.sleep(1) kb.send('tab') for i in range(10): kb.send('right') kb.send('enter') # easygui.msgbox("Continuar?") if easygui.ynbox() == True: kb.send('ctrl+s') time.sleep(3) else: toaster.show_toast("", "Finalizado - break", duration=2) break toaster.show_toast("", "Finalizado", duration=2)
filedir = easygui.diropenbox() os.chdir(filedir) FilesAnalyzed = '' Redo = True # If no json files exist, redo everything DelOld = True # If files have been worked on but not saved, delete old unitsJosh if len(Analyzedlist) > 0: # If there are any json files in the analyzed folder for n in range(len(Analyzedlist)): if n == 0: # If the first file FilesAnalyzed = str(Analyzedlist[n][:-5]) else: 6 if reanalyze == 1: DelOld = easygui.ynbox( msg= 'Do you want to delete old cells in the files you have already done? The files are: \n\n' + FilesAnalyzed) # Ask the user if they want to delete old cells if DelOld == False: # If they do not... Redo = easygui.ynbox( msg= 'Do you want to add new cells to the files you have already done?' ) # Ask if they want to add any cells elif reanalyze == 0: DelOld = False Redo = False # Look for the hdf5 file in the directory file_list = os.listdir('./') hdf5_name = '' first = True # Indicating first file
if fnamm != None: with open(fnamm, 'w') as fll: stt = json.dumps({'effects': ppe}) fll.write(stt) if option == 'Load': fnamm = easygui.fileopenbox(default="presets/", filetypes=['*.ivp', '*.*']) if fnamm != None: try: with open(fnamm, 'r') as fll: stt = json.loads(fll.read()) ppe = ppe + stt['effects'] except: easygui.msgbox("Invalid IVP File.", "Error") elif guiEvents[17]['pressed']: # Combine Scene sure = easygui.ynbox("Are You Sure?", "Combine Scene") if sure: trs = [] for m in scene: for tri in m['shape']: pos = m["position"] # Gets position of mesh scl = m["scale"] # Gets scale of mesh rot = m["rotation"] # Gets rotation of mesh point1 = translateVector( scaleVector(rotateVector(tri[0], rot), scl), pos ) # Rotates, scales, and translates each vector according to the position and scale of the mesh point2 = translateVector( scaleVector(rotateVector(tri[1], rot), scl), pos) point3 = translateVector( scaleVector(rotateVector(tri[2], rot), scl), pos)
def createProtocol(preselected_channels=False, preselected_powers=None): electrodes=[] powers=[] outcomes=[] anodeChoice=eg.multchoicebox(title="Select electrodes", msg="Select the locations that you want to recieve stimulation. You can set them as anodes or cathodes in the next step.", choices=['F4','C4','O2','C3','F3','O1']) if anodeChoice: for item in anodeChoice: electrodes.append(stimModes[item]) choices=anodeChoice choices.append("Ramp up/down duration (set to 0 for no ramping)") choices.append("Stimulation duration (minutes)") choices.append("Sham probability(set to 0 for no sham trials") choices.append("Frequency (set to 0 for dc stimulation)") powers=eg.multenterbox("Enter the power that should be used for each electrode. Positive values represent anodal stimulation, and negative values represent cathodal stimulation. You can also set the duration, ramping parameters, and sham probability of the protocol","Stimulation parameters",choices) if powers: exMode=eg.ynbox(title="Outcome measures",msg="Do you want to add outcome measures to this protocol?") if exMode: outcomes=[] selected="" keepPrompting=True while keepPrompting: keepPrompting=False prompt=eg.buttonbox(title="Select outcome measures",msg="Current outcome measures:\n"+selected,choices=["Add","Done"]) if prompt: keepPrompting=True if "Add" in prompt: name=eg.enterbox(title="Outcome measure name",msg="Enter the name for this outcome measure. Enter NPHYS to use automatically collected neurophsyiological measurements") if name: details=eg.buttonbox(title="Logging options",msg="How do you want to collect data on this measure?",choices=['Before stimulation only','After stimulation only','Both before and after stimulation']) name=name.replace("/","") selected=selected+name+ " "+details.lower()+"\n" if 'Before stimulation only' in details: name=name+"/1" elif 'After stimulation only' in details: name=name+"/2" else: name=name+"/3" outcomes.append(name) else: keepPrompting=False pwrite=eg.filesavebox(title="Where do you want to save this protocol?",msg="Where do you want to save this protocol?") if pwrite: outFile=open(pwrite,'w') outstring="" outstring=outstring+("phaselength:60\n") outstring=outstring+("duration:"+powers[len(powers)-3]+"\n") outstring=outstring+("rampdur:"+powers[len(powers)-4]+"\n") outstring=outstring+("sham:"+powers[len(powers)-2]+"\n") outstring=outstring+("frequency:"+powers[len(powers)-1]+"\n") outstring=outstring+("****\n") for item in outcomes: outstring=outstring+(item+"\n") outstring=outstring+("****\n") for item in range(0,len(choices)): outstring=outstring+(choices[item]+":"+powers[item]+"\n") outFile.write(outstring) outFile.flush() outFile.close()
from bbstxt import output as out import bbstxt from time import sleep import easygui as eg def pause(**opt): if "m" in opt: sleep(0.25 * opt["m"]) else: sleep(0.25) print("Waiting for user to configure . . .") use_defaults = eg.ynbox("Would you like to use the default configuration?", "Use defaults?") if use_defaults: bbstxt.baud = 9600 alias = "guest" user_code = "" else: bbstxt.baud = eg.integerbox("Enter baud rate (Default: 9600)", "Configure (1/3): Baud", 9600, 1, 120000000) alias = eg.enterbox("Enter your alias (Default: guest)", "Configure (2/3): Alias", "guest") user_code = eg.passwordbox("Enter your user-code (Default: [None])", "Configure (3/3): User-Code") print("Connecting to basic.fkbbs.net (800-135-9521) . . .") sleep(3) print("SUCCESS!")
if mode == 'Quick Simul': engine = Engine(read_params("default")) controller = Controller(engine) view = View(controller) controller.set_view(view) controller.run() if mode is None: exit() if mode == 'Live': nbr_bodies = easygui.integerbox("Choose bodies amount", lowerbound=1, upperbound=10000) theta = easygui.integerbox("Choose 10 theta", lowerbound=0, upperbound=10) / 10.0 write_to_file = easygui.ynbox('Do You want to save simulation ?', 'N Body Simulator', ('Yes', 'No')) if write_to_file: loop = True while loop: file_name = "simulation/" + easygui.enterbox("Choose file name") if file_name[11:] in os.listdir('simulation/'): loop = not easygui.ynbox( "This file already exists. Do you want to overwrite file ?" ) else: loop = False section_name = file_name[11:] else: file_name = None section_name = "Section easygui"
block = int(round(barLength * progress)) text = "\rPercent: [{0}] {1}% ".format( "#" * block + "-" * (barLength - block), int(progress * 100)) sys.stdout.write(text) sys.stdout.flush() dirname1 = easygui.diropenbox(msg=None, title="Please select the target directory", default=None) total_con = len(fnmatch.filter(os.listdir(dirname1), '*.las')) D1 = str(total_con) msg = str(total_con) + " files do you want to continue?" title = "Please Confirm" if easygui.ynbox(msg, title, ('Yes', 'No')): # show a Continue/Cancel dialog pass # user chose Continue else: # user chose Cancel else: exit(0) file_Dir1 = os.path.basename(dirname1) ci = 0 cls() eR = 0 f = open(dirname1 + "\Stat-Duplication.txt", "w") for filename in os.listdir(dirname1): if filename.endswith(".las"): ci += 1
def ask_to_play(): return easygui.ynbox("Do you want to play a game?", "Country Guesser", ("Yes", "No"))
def get_Del_config3(): global fileclass fileclass = easygui.ynbox('您要以以下哪种方式输入?', '文件管理', ('文件类型', '文件扩展名')) if fileclass == None: easygui.msgbox('您还未选择', '文件管理--提示', '重试') get_Del_config3()
def get_clear_config2(): global keep_dir keep_dir = easygui.ynbox('是否保留(不拆开)文件夹中包含的子文件夹?', '文件管理', ('保留', '不保留')) if keep_dir == None: easygui.msgbox('您还未选择', '文件管理--提示', '重试') get_clear_config2()
filename = gui.fileopenbox(msg='Pick your word list', title='File selection') logging.info('Your word list is %s' % filename) # Get save location savepath = gui.diropenbox(title='Choose save location') logging.info('Save files in %s' % savepath) # Choose base file name prefix = gui.enterbox( msg= 'Choose a prefix for your file names. This setting can be overridden in advanced settings to name files for their contents.', default='MagneticPoetry') logging.info('Saving files as %s with numerical suffixes' % prefix) # Use advanced settings? advancedSettings = gui.ynbox(msg='Use advanced settings?') logging.info('Advanced settings: %s' % advancedSettings) # If Advanced Settings are used, pop up box to ask for font size and colors if advancedSettings == True: # Set text size textSize = gui.integerbox(msg='Set font size', default=75, lowerbound=10, upperbound=300) logging.info('Setting text size to %s' % textSize) # Set colors textColor = gui.enterbox( msg='Choose your text color using standard named HTML colors', strip=True, default='black')