Example #1
1
	def upload(filepath, caption, user, password, context):
		print "Filepath is "+filepath 
		insta = InstagramSession()
		print "InstagramSession started"
		if user == None and password == None:
			authfields = ["Username:"******"Password:"******"Authentication", "Please enter a username and password.", authfields)
			user = auth[0]
			USERNAME = auth[0]
			password = auth[1]
			PASSWORD = auth[1]
		if user == None:
			USERNAME = easygui.enterbox("Please enter a username:"******"Please enter a password:"******"Inside login"
			media_id = insta.upload_photo(filepath)
			print "media id"
			if media_id is not None:
				if caption == None:
					description = easygui.enterbox("Please enter a description of the image:")
				else:
					description = str(caption)
				insta.configure_photo(media_id, description)
				if context != "scheduled":
					main()
				else:
					pass
def anothertry(no1, no2, operation, tries):

    tries = tries + 1
    easygui.msgbox(title = "Math flash", msg = "Sorry that was wrong \n try again")
    if operation == "Addition":
        answer = no1 + no2
        answerusergot = easygui.enterbox(title = "Math flash",
                                         msg = "    "+ str(no1) +
                                         "\n+ " + str(no2))

    if operation == "Subtraction":
        answer = no1 - no2
        answerusergot = easygui.enterbox(title = "Math flash",
                                         msg = "    "+ str(no1) +
                                         "\n- " + str(no2))
    if operation == "Multiplication":
        answer = no1 * no2
        answerusergot = easygui.enterbox(title = "Math flash",
                                         msg = "    "+ str(no1) +
                                         "\nX " + str(no2))
    if operation == "Division":
        answer = no1 / no2
        answerusergot = easygui.enterbox(title = "Math flash",
                                         msg = "    "+ str(no1) +
                                         "\n/ " + str(no2))
    Right = CheckAnswer(answer, answerusergot)
    if not Right:
        
        if not tries == 3:
            anothertry(no1, no2, operation, tries)
    else:
        easygui.msgbox(title = "Math flash", msg = "Great that was right, but the first time you did it it was wrong so this problem is wrong")
def userOutput(outDir,defaultOutput='METAR-vis.html'):
    '''
    Asks the user what they want to call the map. This is an HTML document that
    will be saved to the directory they specified in the previous step.
    '''
    default = outDir+"/"+defaultOutput
    msg = "Set the name and location of output leaflet map.\n\nDefault: %s" % default
    title = "METAR-vis"
    output = eg.enterbox(msg=msg,title=title,default=default)
    
    # Error check the user input
    while 1: # Loop continuosly, until all values are acceptable
        if output == None:
            # User cancelled
            cancel()
        errmsg = ""
        
        # Check that the directory exists
        checkDir = '/'.join(output.split('/')[0:-1])
        if not os.path.isdir(checkDir):
            # The user has not specified an existing directory
            note = '%s is not an existing directory' % checkDir
            errmsg = msg + "\n\nERROR: " + note + "\n"
        
        # Check that the suggested output file is an HTML
        # If not, just silently overwrite it
        if output.split('.')[-1] != 'html':
            output = output.split('.')[0] + '.html'
        if errmsg == "":
            break
        else:
            output = eg.enterbox(msg=errmsg,title=title,default=default)
               
    return output
Example #4
0
def fetchData():

    url = easygui.enterbox(msg = 'Enter the URL + API KEY',title = 'URL+API KEY')


    pages = easygui.enterbox(msg = 'Enter the Max. pages to extract',title = 'MAX. PAGES TO EXTRACT')

    responses = []

    index = int(getIndex(url))

    for i in range(1, (int(pages)+1)):
        url = url[0:index] + str(i) + url[index+1:]
        response = requests.get(url,verify = False)
        response = json.loads(response.content)

        if i == 1 :
            result = response["results"]
            responses = responses + result
        else:
            result = response["results"]
            result.pop(0)
            responses = responses + result

    return responses
def userMetar():
    '''
    Seeks user input for a list of METAR stations to retrieve, returning a list
    of these stations (strings) only once they have been given without error.
    If the user chooses to cancel, the program closes.
    '''
    # Get the METAR station codes from the user
    msg = "Enter the METAR stations you are interested in collecting information for as a comma-separated list below."
    title = "METAR-vis"
    default = 'NZWN,NZAA,NZCH'
    metarValues = eg.enterbox(msg=msg,title=title,default=default)

    # Error check the user input
    while 1: # Loop continuosly, until all values are acceptable
        
        if metarValues is None:
            cancel()
        errmsg = ""
        
        # Check the validity of user-suppled METAR values
        metarstations = getMetarStations(metarValues)
        if metarstations[0] == False:
            note = ""
            # The metar stations were not listed correctly or at least one does not exist
            if metarstations[1] != '': # If there's an additional note
                note = '\n\n' + metarstations[1]
            errmsg = msg + errmsg + ('\n\nERROR: This must be comma-separated list of four-character and extant METAR identification codes. These must be alphanumeric. See http://weather.noaa.gov/pub/data/observations/metar/decoded/ for the list of possibilities.%s\n' % note)
        
        if errmsg == "": 
            break # no problems found
        else:
            # show the box again, with the errmsg as the message    
            metarValues = eg.enterbox(errmsg, title, default, metarValues)
            
    return metarstations
Example #6
0
def exercise1():
    """Uses the specified function as described in the lab document."""
    s = easygui.enterbox( "Enter a string (Cancel to quit):", "Three-Peat - Input", "This is a test." )
    while s is not None:
        three_peat(s)

        s = easygui.enterbox( "Enter a string (Cancel to quit):", "Three-Peat - Input" )
Example #7
0
 def handleMouseDown(self, coords):
     x,y = coords
     but = False
     SimpleUI.state['clicked'] = True
     for button in self.buttons:
         if (button.containsPoint(x, y)):
             button.do()
             SimpleUI.state['clicked'] = False
             but = True
             break
     for platform in self.gameRects:
         if platform.rect.collidepoint(x, y):
             self.selected = platform.rect
             if SimpleUI.state['mode'] is not 'prop': SimpleUI.state['mode'] = 'drag'
             else:
                 platform.setBy = eg.enterbox('ButtonGroup to that sets this platform')
                 print("set by"+platform.setBy+"yo")
                 if eg.boolbox("Platform visible by default?", "One more thing", ["Yes", "No"]):
                     platform.visibleDefault = True
                 else:
                     platform.visibleDefault = False
             but = True
             break    
     for gbutton in self.gameButtons:
         if gbutton.rect.collidepoint(x,y):
             self.selected = gbutton.rect
             if SimpleUI.state['mode'] is not 'prop': SimpleUI.state['mode'] = 'drag'
             else:
                 gbutton.sets = eg.enterbox('Object Group to set')
             but = True
     for recorder in self.gameRecorders:
         if recorder.rect.collidepoint(x,y):
             self.selected = recorder.rect
             SimpleUI.state['mode'] = 'drag'
             but = True
     if self.gamePlayer.rect.collidepoint(x,y):
         self.selected = self.gamePlayer.rect
         SimpleUI.state['mode'] = 'drag'
         but = True
     elif self.gameExit.rect.collidepoint(x,y):
         self.selected = self.gameExit.rect
         SimpleUI.state['mode'] = 'drag'
         but = True
     if not but:
         if SimpleUI.state['mode'] == 'rect':
             SimpleUI.LAST = [x,y]
         if SimpleUI.state['mode'] == 'player':
             self.gamePlayer.rect.center = (x,y)
         if SimpleUI.state['mode'] == 'recorder':
             temp = levelformat.Recorder(x,y)
             temp.rect.center = (x,y)
             self.gameRecorders.append(temp)
         if SimpleUI.state['mode'] == 'button':
             temp = levelformat.Button(x,y)
             temp.rect.center = (x,y)
             self.gameButtons.append(temp)
         if SimpleUI.state['mode'] == 'exit':
             self.gameExit.rect.center = (x,y)
         if SimpleUI.state['mode'] == 'move':
             SimpleUI.LAST = [x,y]
def mode3(): # density change
    target_x = int(easygui.enterbox('Input the target position','Initialise the question')) #m
    limit_d = float(easygui.enterbox('Allowable errors about the distance between target and landing point','CHOOSE ERROR')) #m
    d = target_x
    limit = limit_d
    c = dense_air(ini(), _dt = 0.1)
    while d > limit:       
        d = abs(c.shoot()[0] - target_x)
        print(c.shoot()[0])
        if d < limit: break
        final = []
        temp = []
        for angle in range(5,90,5):
            c = dense_air(ini(340,angle), _dt = 0.1)
            final.append(c.shoot()[0])
            temp.append(angle)
        i = final.index(max(final))
        angle = temp[i]
        print angle
        for v in range(100,target_x,1):
            c = dense_air(ini(v, angle), _dt = 0.1)
            d = abs(c.shoot()[0] - target_x)
            if d < limit: 
                c = dense_air(ini(v, angle), _dt = 0.1)
                out = c.shoot()
                c.show_trajectory(v, angle)
                show()
                out = 'Final Landing Point: '+str(out)
                easygui.msgbox(out, 'Target Position: '+str(target_x))
                break
    choosemode()
def InteractionAtBeganing(TitleText):
    TermsOfSevace = "Terms of Sevace \n \n  By Using this program you agree to not report an invalid bug, and to allow Boston Abrams and others,to use the data that you perduse, your email  adress and your name. "
    easygui.msgbox(msg = TermsOfSevace, title = TitleText +  " Terms of sevace", ok_button = "I Agree")            
    easygui.msgbox(msg = "I have chosen a code for you to break", title = TitleText +  " Intoduction", ok_button = "Next")
    easygui.msgbox(msg = "There is no way you can guess it", title = TitleText +  " Intoduction", ok_button = "Next")
    easygui.msgbox(msg = "But I will give you a try", title = TitleText +  " Intoduction", ok_button = "Next")
    Name = easygui.enterbox(msg = "Enter Your nic-name (what you want to be called by in the game)", title = TitleText)
    Email = easygui.enterbox(msg = "Enter your email address", title = Name + " " + TitleText + " Email Address.")
Example #10
0
def exercise6():
    """Uses the specified function as described in the lab document."""
    # TODO 6b: Write code to use the function as described in the lab document.
    s = easygui.enterbox( "Enter a string (Cancel to quit):", "Acronym - Input", "Three Letter Acronym" )  # TLA
    while s is not None:
        easygui.msgbox( acronym( s ), "Acronym - Result" )
        s = easygui.enterbox( "Enter a string (Cancel to quit):", "Acronym - Input",
                              "Integrity first, Service before self, Excellence in all we do." )  # IFSBSEA
Example #11
0
def exercise5():
    """Interact with the user and test the scorekeeper function."""
    # TODO 5b: Write code to use the scorekeeper function as described in the lab document.\

    player1 = easygui.enterbox("Name of Player 1?")
    player2 = easygui.enterbox("Name of Player 2?")
    winning_score = easygui.integerbox("Winning score for the game?", "Input", "10", 3, 2 ** 31)
    winner = scorekeeper(player1, player2, winning_score)
    easygui.msgbox("{} WINS!".format(winner), "Result")
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
Example #13
0
def exercise5():

    """Uses the specified function as described in the lab document."""
    # TODO 5b: Write code to use the function as described in the lab document.
    s = easygui.enterbox("Enter a string (Cancel to quit:", "ROT13 - Input", "Why did the chicken cross the road?")
    while s is not None:
        cipher_text = rot13(s)
        easygui.msgbox(cipher_text, "ROT13 - Encrypted")
        plain_text = rot13_v2(cipher_text)
        easygui.msgbox(plain_text, "ROT13 - Decrypted")
        s = easygui.enterbox("Enter a string (Cancel to quit:", "ROT13 - Input", "To get to the other side")
Example #14
0
def room_seven():
    global oldGame
    eg.msgbox("\nYou enter the room, door disappearing behind you.", title)
    room7 = eg.enterbox("Input: ").lower()
    if room7 == "examine room":
        eg.msgbox("\nYou see no doors - just an old man standing before you.", title)
        room_seven()
    elif room7 == "examine old man":
        eg.msgbox("\nHis face is covered, perhaps you could talk to him.", title)
        room_seven()
    elif room7 == "enter s":
        eg.msgbox("\nThe door had disappeared", title)
        room_seven()
    elif room7 == "room":
        eg.msgbox("\nThis is room seven.", title)
        room_seven()
    elif room7 == "talk to old man":
        old_man()
    elif room7 == "help":
        help()
        room_seven()
    elif room7 == "commands":
        commands()
        room_seven()
    elif room7 == "exit":
        exit()
    elif room7 == "i":
        eg.msgbox("\nYou currently have:", title)
        eg.msgbox(invent, title)
        room_seven()
    else:
        eg.msgbox("\nInput error, please use a valid command.", title)
        room_seven()
Example #15
0
def command():
    command_str = easygui.enterbox(title="W.I.L.L", msg="Please enter a command.")
    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()
    command_process(command_str)
    def _check_credentials(self):
        """
        GUI: show GUI for entering the credentials when there is no credentials.
        """
        if not self.connection_options:
            title = 'Enter Credentials'
            msg = textwrap.dedent('''\
            Please enter your Credentials for downloading.
            Or you can put it in "<CURRENT_DIR>/tc_credentials.json" file.

            e.g. {"clientId": "XXX", "accessToken": "XXX" ...}

            * Tips: [←][→] Move, [Enter] Select, [Esc] Cancel
            ''')
            ret = easygui.enterbox(msg, title)
            try:
                raw_credentials_dict = json.loads(ret)
                if 'credentials' in raw_credentials_dict:
                    self.connection_options = raw_credentials_dict
                elif 'clientId' in raw_credentials_dict:
                    self.connection_options = {'credentials': raw_credentials_dict}
                logger.debug('connection options: {}'.format(self.connection_options))
            except Exception as e:
                logger.debug(e)
                self.connection_options = {}
                logger.debug('Can not load connection options from user input.')
                title = 'Load Options Error'
                msg = textwrap.dedent('''\
                Can not load Credentials from user input.
                Run with no credentials.

                * Tips: [Enter] OK
                ''')
                easygui.msgbox(msg, title)
Example #17
0
def leftroom2():
	sense_of_direction = 0
	while sense_of_direction == 0:
		choices = eg.enterbox("You stand in a room with a dead monster.")
		if choices == "look" or choices == "look around" or choices == "examine room" or choices == "examine" or choices == "look monster" or choices == "look at monster" or choices == "examine monster":
			eg.msgbox("The monster lays on the ground, dead.")
			if "revolver" in room.grunnur.items:
				pass
			else:
				eg.msgbox("You see the barrel of what appears to be a revolver sticking out from underneath the monstrosity's body.")
		elif choices == "take gun" or choices == "take revolver" or choices == "gun" or choices == "pick up gun" or choices == "pick up revolver" or choices == "revolver":
			if "revolver" in room.grunnur.items:
				eg.msgbox("You've already taken the revolver.")
			else:
				room.grunnur.items.append("revolver")
				sense_of_direction = 1
				eg.msgbox("You pick up the revolver. Feels like nothing's restricting you from using it in other rooms!")
				eg.msgbox("Looks like there's nothing else to do in here, you go back to the previous room.")
				entry()
		elif choices == "go back" or choices == "back" or choices == "south":
			sense_of_direction = 1
			entry()
		elif choices == "leave":
			sense_of_direction = 1
			leaving()
		else:
			puzzled()
def Choice_Restore_Pilot():
    #Restore From File
    RestoreFile = easygui.fileopenbox("Select File To Restore From","Select File To Restore From",PilotApp.Settings['EpicorBackupDir'])
    usrpw = GetDSNPassword()
    rightnow = datetime.datetime.now()
    compname =  rightnow.strftime("%B")
    compname = compname[:3]
    compname = '--- TEST ' + compname + str(rightnow.day) + ' ---'
    compname = easygui.enterbox(msg='New Pilot Company Name?',default=compname)
    easygui.msgbox(msg='This will take some time, please wait until you see the main app dialog.')
    #Shutdown Pilot
    PilotApp.Shutdown()
    PilotApp.ShutdownDB()
    PilotApp.Restore(RestoreFile)
    PilotApp.StartupDB(5) #Number of retries
    #Connect to db
    PilotDB = EpicorDatabase(PilotApp.Settings['DSN'],usrpw[0], usrpw[1] );del usrpw
    #Update to Pilot Settings
    PilotDB.Sql("UPDATE pub.company set name = \'" + compname + "\'")
    PilotDB.Sql("UPDATE pub.SysAgent set AppServerURL = \'" + PilotApp.Settings['AppServerURL'] + "\'")
    PilotDB.Sql("UPDATE pub.SysAgent set MfgSysAppServerURL = \'" + PilotApp.Settings['MfgSysAppServerURL'] + "\'")
    PilotDB.Sql("UPDATE pub.SysAgent set FileRootDir = \'" + PilotApp.Settings['FileRootDir'] + "\'")
    #Remove Global Alerts / Task Scheduler
    PilotDB.Sql("UPDATE pub.glbalert set active=0 where active=1")
    PilotDB.Sql("UPDATE pub.chglogGA set SendEmail=0 where SendEmail=1")
    PilotDB.Sql("DELETE from pub.SysAgentTask")
    #Commit changes and close connection
    PilotDB.Commit()
    PilotDB.Close()
    PilotApp.Startup()
Example #19
0
	def new_schedule():
		filepath = get_file()
		timeenters = ["Days", "Hours", "Minutes", "Seconds"]
		stime = easygui.multenterbox("Scheduler", "Please specify a time", timeenters)
		days = stime[0]
		hours = stime[1]
		minutes= stime[2]
		seconds = stime[3]
		description = easygui.enterbox("Please enter a description of the image")
		days = int(days)*24
		hours = int(days)+int(hours)
		minutes = hours*60+int(minutes)
		seconds = minutes*60+int(seconds)
		isauth = os.path.isfile("auth.txt")
		if isauth == True:
			authfile = open("auth.txt").read().split('\n')
			print authfile
			username = authfile[0]
			password = authfile[1]
		else:
			accountfields = ["Username:"******"Password:"******"Authentication", "Please enter the required information.", accountfields)
			username = userpass[0]
			password = userpass[1]
		p = threading.Thread(target=wait, args=(seconds, filepath, description, username, password))
		processes.append(p)
		p.start()
#		processfile.close()
		main()
	def newdir(self):
		datadict=self.getcurrentdatadict();
		dirnew=DataObject();
		newdirname=easygui.enterbox("new dir name?","creating dir","newdir");
		if newdirname is not None:
			datadict[newdirname]=dirnew;
			self.updatecurrentframe();
Example #21
0
 def main():
     urlchoice = "Supply a url to turn into a pdf"
     filechoice = "Pick a single file to turn into a pdf"
     dirchoice = "Pick a directory, all .html or .htm files within will be converted to pdf"
     mainchoices = [urlchoice, filechoice, dirchoice]
     choice = easygui.choicebox(title="Options", msg="Please select an option", choices=mainchoices)
     if choice == urlchoice:
         filetype = "url"
         fileobject = easygui.enterbox("Please enter a url")
         try:
             if "http://" in fileobject or "https://" in fileobject:
                 html = urllib2.urlopen(fileobject).read()
                 convert(filetype, fileobject)
             else:
                 fileobject = "http://" + fileobject
                 html = urllib2.urlopen(fileobject).read()
                 convert(filetype, fileobject)
         except urllib2.HTTPError:
             easygui.msgbox("Invalid url")
             main()
     elif choice == filechoice:
         filetype = "file"
         fileobject = get_file(filetype)
         convert(filetype, fileobject)
     elif choice == dirchoice:
         filetype = "dir"
         fileobject = get_file(filetype)
         convert(filetype, fileobject)
Example #22
0
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
Example #23
0
def room_five():
    global keyCount
    eg.msgbox("\nYou enter the room.", title)
    room5 = eg.enterbox("Input: ", title).lower()
    if room5 == "examine room":
        if "Boot" in invent:
            eg.msgbox("\nYou see an exit in every direction.", title)
        else:
            eg.msgbox("\nYou see an exit in every direction, as well as a boot.", title)
            room_five()
    elif room5 == "enter n":
        eg.msgbox("\nLEAVING ROOM", title)
        room_eight()
    elif room5 == "enter e":
        eg.msgbox("\nLEAVING ROOM", title)
        room_six()
    elif room5 == "enter s":
        eg.msgbox("\nLEAVING ROOM", title)
        room_two()
    elif room5 == "enter w":
        eg.msgbox("\nLEAVING ROOM", title)
        room_four()
    elif room5 == "examine boot":
        if "Boot" in invent:
            eg.msgbox("\nInvalid command.", title)
            room_five()
        else:
            eg.msgbox("\nIt appears to be an old, leather boot.", title)
            room_five()
    elif room5 == "take boot":
        if "Key Four" in invent:
            eg.msgbox("\nInvalid command.", title)
            room_five()
        else:
            eg.msgbox("\nYou take the nasty boot and see something within.", title)
            eg.msgbox("You reach in and take a key from the boot.", title)
            invent.append("Key Four")
            invent.append("Boot")
            if "Empty" in invent:
                invent.remove("Empty")
            keyCount = keyCount + 1
            room_five()
    elif room5 == "room":
        eg.msgbox("This is room five.", title)
        room_five()
    elif room5 == "help":
        help()
        room_five()
    elif room5 == "commands":
        commands()
        room_five()
    elif room5 == "exit":
        exit()
    elif room5 == "i":
        eg.msgbox("\nYou currently have:", title)
        eg.msgbox(invent, title)
        room_five()
    else:
        eg.msgbox("\nInput error, please use a valid command.", title)
        room_five()
	def importnhmfl(self,pathstr,filename):
		success=0;
		#fullreffilechosen=os.path.join(pathstr,reffilename);
		answer=easygui.enterbox("Expname length","Loading NHMFL files","3");
		if answer is not None:
			lexpname=int(answer);
			expname=filename[0:lexpname];
			files=os.listdir(pathstr);
			i=0;
			for file in files:
				if not os.path.isdir(file):
					if file[0:lexpname]==expname:
						if i==0:
							spect=self.importnhmfl_nonui(pathstr,file);
							xunitobj=spect.get('xunit');
							xunitobj.uiset('string');
							#spect.set('xunit',xunitobj);
							spect0=spect.copyxy();
							i=i+1;
						else:
							spect=self.importnhmfl_nonui(pathstr,file,spect0);
						spect.convertx("cm_1");
						self['savabledata']['rawspectra'].insert(spect,file);
			success=1;
		return success;
Example #25
0
    def otsi():
        uudised=[]
        for pealkiri in pealkirjad:
            tekst = pealkiri.childNodes[0].data
            if tekst != "uudised.err.ee - online": 
                uudised.append(tekst)

        def otsija(otsitav, uudised):
            sobivad_uudised=[]
            for sona in uudised:
                if sona[:len(otsitav)]== otsitav:
                    sobivad_uudised.append(sona)

            return sobivad_uudised
       
        otsing = easygui.enterbox("Sisesta otsingu keyword")
        if otsing != None:
            sobivad_uudised=otsija(otsing, uudised)

            for uudised in sobivad_uudised:             
                if len(sobivad_uudised)==1:
                    easygui.msgbox (sobivad_uudised[0])
                else:
                    for j in sobivad_uudised:
                        easygui.msgbox (j) 
Example #26
0
    def hit_by_player(self):
        E_hits = pg.sprite.spritecollide(self, self.game.bullets, False)

        if E_hits:
            if self.hp > 0:
                self.hp -= BULLET_DAMAGE
                # Bullet.collide_with_figure(self.game.enemies)
            else:
                E_killed = pg.mixer.Sound(self.game.sound_folder + "/" + ENEMY_DEATH_SOUND)
                pg.mixer.Channel(1).play(E_killed)
                self.kill()
                # Bullet.collide_with_figure(self.game.enemies)
                self.game.player.enemy_kills += 1
                print("Enemy killed. Total: " + str(self.game.player.enemy_kills))
                # Game Win Sequence with Scoreboard Writing
                if (self.CountEnemy() - self.game.player.enemy_kills) == 0:
                    Time = datetime.datetime.now()

                    PlayerName = easygui.enterbox(
                        msg="Please enter your Name below: ",
                        title="Nameinput  for Scoreboard!",
                        strip=True, # will remove whitespace around whatever the user types in
                        default="Username")

                    FinalTime = Time - self.game.Time_start
                    with open("score.txt", "w") as f:
                        f.write(str(PlayerName + " : " + str(FinalTime) + " : " +  str(datetime.date.today())))

                    self.exec = True
                    text_1 = 'All Enemies killed!'
                    text_2 = 'You win!'
                    text = text_1 + ".." + text_2
                    self.game.a_area.event_display_text(text)
                    time.sleep(5)
                    self.game.quit()
Example #27
0
def getFile(world):
    b = easygui.buttonbox("","PyCraft: Select a World", ("Load World","New World","Quit"))
    if b == "Quit":
        logdata("The user quitted immediatly.")
        quit()
    if b == "New World":
        logdata("The user created a new world.")
        name = easygui.enterbox("Pick a name for your world: ")
        logdata("They named it '"+name+"'.")
        gens = os.listdir("generators/")
        for gen in range(len(gens)):
            gens[gen] = gens[gen][:-3]
        gen = easygui.choicebox("Select a world generator: ","",gens)
        logdata("They used the generator '"+gen+"'.")
        exec open("generators/"+gen+".py").read()
        generateRandomMap(world)
        
        world.saveName = name
    if b == "Load World":
        worlds = os.listdir("worlds/")
        world_name = easygui.choicebox("Select a world","Pycraft: Select a World", worlds)
        logdata("They loaded the world named '"+world_name+"'.")
        world_data = open("worlds/"+world_name,"r").read()
        logdata("It contains "+str(len(world_data.split("\n"))-1)+" blocks.")
        parseMap(world,world_data)
        world.saveName = world_name
Example #28
0
	def login(self, browser):
		"""
		利用配置文件和初始化信息进行模拟登陆
		:param:浏览器对象,已打开原始的登录页面
		:return:浏览器对象
		"""
		browser.get( self.config['BussinessStaffURL'] )
		browser.switch_to.frame( browser.find_element_by_tag_name("iframe") )
		userNameInput = browser.find_element_by_name("TPL_username")
		userNameInput.clear()
		userNameInput.send_keys( self.username+Keys.TAB+self.password+Keys.RETURN )
		browser.switch_to.default_content()
		loopKey = True
		while loopKey:
			try:
				WebDriverWait( browser, 4 ).until( EC.presence_of_element_located( ( By.CSS_SELECTOR, "ul>li>a>div>strong>span" ) ) )
				loopKey = False
			except Exception:
				browser.switch_to.frame( browser.find_element_by_tag_name("iframe") )
				passwordInput  = WebDriverWait(browser,10).until( EC.presence_of_element_located( (By.ID, "TPL_password_1") ) )
				passwordInput.clear()
				passwordInput.send_keys( self.password )
				checkCodeInput = WebDriverWait(browser,10).until( EC.presence_of_element_located( (By.ID,"J_CodeInput_i") ) )
				checkCode = enterbox("请输入验证码(不区分大小写)","验证码输入","", True)
				checkCodeInput.send_keys(checkCode+Keys.RETURN)
				browser.switch_to.default_content()
				loopKey = True

		return browser
 def getGeneId(self):
     gene_alias = easygui.enterbox("Please enter the locus tag or ITEP ID (sanitized or not) of the gene you wish to study.")
     if gene_alias is None:
         raise UserCancelError('User cancelled the operation.')
     self._setUpGeneInfo(gene_alias)
     self._setUpClusterInfo()
     return gene_alias
Example #30
0
def Update_User_Photo(database, frame):
    print(str(Path(get_file_path())))
    root_dir = Path(get_file_path())
    database = str(root_dir.joinpath(database))
    pic_dir = str(root_dir.joinpath('./pictures'))

    if not os.path.isdir(pic_dir):
        os.makedirs(pic_dir)

    try:
        Name = easygui.enterbox(msg="請輸入:\"姓名\"\n"\
            ,title='新增/更新臉部資料')
        if Name[0] == "\'":
            raise ValueError("輸入\'字元")
        if Name[0] == "":
            raise ValueError("輸入空字元")
    except:
        easygui.msgbox('錯誤,請再次輸入\"姓名\"')
        return
    
    conn = sqlite3.connect(database)
    c = conn.cursor()
    data_list = []
    for data in c.execute("SELECT\
        Unit_id, Unit_name, ID, Name, Title_name\
                FROM User_Profile Where Name = '{}'".format(Name)):
        # [[Unit_id, Unit_name, ID, Name, Title_name], ... ]
        data_list.append([data[0], data[1], data[2], data[3], data[4]])
    conn.commit()
    conn.close()
    # ID not found
    if len(data_list) == 0:
        easygui.msgbox('未找到符合身分。')
        # if(Insert_one_face_in_db(database, photo_path, user_profile)):
        #     easygui.msgbox('未找到符合身分。加入資料庫')
        # else:
        #     easygui.msgbox('臉部偵測錯誤,請重新檢測!')
    # Got the same name, find ID's last 5 words
    elif len(data_list) > 1:
        try:
            ID = easygui.enterbox(
                msg="與他人撞名\n請輸入:\"身分證後五碼\"\n", title='新增/更新臉部資料')
            if len(ID) != 5:
                easygui.msgbox('錯誤,請再次輸入\"身分證後五碼\"')
                return
        except:
            easygui.msgbox('錯誤,請再次輸入\"身分證後五碼\"')
            return

        # Find the same ID by last 5 words, and get the correct user_profile
        is_ID = False
        for tmp_Unit_id, tmp_Unit_name, tmp_ID, tmp_Name, tmp_Title_name in data_list:
            if five_last_ID(tmp_ID) == five_last_ID(ID):
                user_profile = [tmp_Unit_id, tmp_Unit_name,
                                tmp_ID, tmp_Name, tmp_Title_name]
                is_ID = True
                break
        if is_ID == False:
            easygui.msgbox('錯誤,無法找到此身分證後五碼的資料')
            return
        photo_path = save_photo(user_profile[2], pic_dir, frame)
        if(Update_one_face_in_db(database, photo_path, user_profile)):
            easygui.msgbox('更新成功!')
        else:
            easygui.msgbox('臉部偵測錯誤,請重新檢測!')
    # Normal case
    else:
        user_profile = data_list[0]
        photo_path = save_photo(user_profile[2], pic_dir, frame)
        if(Update_one_face_in_db(database, photo_path, user_profile)):
            easygui.msgbox('更新成功!')
        else:
            easygui.msgbox('臉部偵測錯誤,請重新檢測!')
def _record_name(patient):
    name = enterbox(ms["enter_info"], ms["patient_info"], patient.name)
    if name is None:
        raise LeftIncompleteException
    patient.name = name
Example #32
0
def on_press(key):
    global brightness, contrast, EV, saturation, zoom
    global speed, LEDintensity
    global arrowkey_mode, path, filename, recording_mode

### F1: keyboard shortcuts
    
    if key == Key.f1:
        shortcuts()

######## CAMERA
        
### Camera preview modes, video or photo         
   
    if key == Key.tab:
        if recording_mode == False:
            camera.resolution = (1920, 1080)
            camera.annotate_text = "Video mode"
            recording_mode = True
        elif recording_mode == True:
            if HighResolution == True:
                camera.resolution = (3280, 2464) # Pi camera v2 max resolution, 8MP
            else:
                camera.resolution = (1920, 1080) # reduced resolution, Full HD
            camera.annotate_text = "Photo mode"
            recording_mode = False

### Reset camera settings
    if key == KeyCode(char='0'):
        camera_reset()
        
### digital zoom
    
    if key == KeyCode(char='+'):
        if zoom > 0.2:
            zoom = zoom - 0.1
            camera.zoom = (0,0,zoom,zoom)
            annotate_text = "Digital zoom:" + str(round(1/zoom,2)) + "X"
            camera.annotate_text = annotate_text  

    if key == KeyCode(char='-'):
        if zoom < 1.0: 
            zoom = zoom + 0.1
            camera.zoom = (0,0,zoom,zoom)
            annotate_text = "Digital zoom:" + str(round(1/zoom,2)) + "X"
            camera.annotate_text = annotate_text
            
### start and stop camera preview
 
    if key == KeyCode(char='P'):
        camera.start_preview()
        
    if key == KeyCode(char='p'):
        camera.stop_preview()

### brightness
        
    if key == KeyCode(char='B'):
        if brightness !=100:
            brightness += 5
            camera.brightness = brightness
            annotate_text = "Brightness:" + str(brightness) + "%"
            camera.annotate_text = annotate_text
            
    if key == KeyCode(char='b'):
        if brightness !=0:
            brightness -= 5
            camera.brightness = brightness
            annotate_text = "Brightness:" + str(brightness) + "%"
            camera.annotate_text = annotate_text
            
### contrast
            
    if key == KeyCode(char='C'):
        if contrast !=100:
            contrast += 5
            camera.contrast = contrast
            annotate_text = "Contrast:" + str(contrast) + "%"
            camera.annotate_text = annotate_text
    if key == KeyCode(char='c'):
        if contrast !=-100:
            contrast -= 5
            camera.contrast = contrast
            annotate_text = "Contrast:" + str(contrast) + "%"
            camera.annotate_text = annotate_text
            
### EV compensation
            
    if key == KeyCode(char='V'):
        if EV !=25:
            EV += 1
            camera.exposure_compensation = EV
            annotate_text = "EV:" + str(EV)
            camera.annotate_text = annotate_text
    if key == KeyCode(char='v'):
        if EV !=-25:
            EV -= 1
            camera.exposure_compensation = EV
            annotate_text = "EV:" + str(EV)
            camera.annotate_text = annotate_text

### saturation
            
    if key == KeyCode(char='S'):
        if saturation !=100:
            saturation += 5
            camera.saturation = saturation
            annotate_text = "Saturation:" + str(saturation) + "%"
            camera.annotate_text = annotate_text
    if key == KeyCode(char='s'):
        if saturation !=-100:
            saturation -= 5
            camera.saturation = saturation
            annotate_text = "Saturation:" + str(saturation) + "%"
            camera.annotate_text = annotate_text

### ISO
            
    if key == KeyCode(char='i'):
        camera.preview_alpha=0
        ISO_choices = ["0","100","200","320","400","500","640","800"]
        ISO_selected = easygui.choicebox("Select ISO (default: 0 for auto)", "ISO", ISO_choices)
        if ISO_selected is not None:
            camera.iso = int(ISO_selected)
        camera.preview_alpha=255

### white balance
        
    if key == KeyCode(char='W'):
        camera.preview_alpha=0
        WB_choices = ["off","auto","sunlight","cloudy","shade","tungsten","fluorescent","flash","horizon"]
        WB_selected = easygui.choicebox("Select white balance mode (default: auto)", "White Balance", WB_choices)
        if WB_selected is not None:
            camera.awb_mode = WB_selected
        if WB_selected == "off":
            WB_gain = easygui.enterbox("White balance gain - typical values between 0.9 and 1.9", "White balance gain", "1.0")
            if WB_gain is not None:
                camera.awb_gains = float(WB_gain)
        camera.preview_alpha=255

### frame rate
        
    if key == KeyCode(char='r'):
        camera.preview_alpha=0
        Framerate_choices = ["30","20", "15","10","5","2","1", "0.5", "0.1", "manual"]
        Framerate_selected = easygui.choicebox("Select framerate","Framerate", Framerate_choices)
        if Framerate_selected == "manual":
            Framerate_selected = easygui.enterbox("Framerate", "Input", "")
        if Framerate_selected is not None:
            camera.framerate = float(Framerate_selected)
        camera.preview_alpha=255

### exposure time (shutter speed)
        
    if key == KeyCode(char='e'):
        camera.preview_alpha=0
        Exposure_choices = ["0","10","20","50","100","200", "500", "1000", "manual"]
        Exposure_selected = easygui.choicebox("Select exposure time in ms (default: 0, auto)\n\
Maximum exposure time is determined by the framerate","Exposure time (shutter speed)", Exposure_choices)
        if Exposure_selected == "manual":
            Exposure_selected = easygui.enterbox("Exposure time (ms)", "Input", "")
        if Exposure_selected is not None:
            camera.shutter_speed = int(Exposure_selected)*1000
        camera.preview_alpha=255

### exposure modes
            
    if key == KeyCode(char='E'):
        camera.preview_alpha=0
        ExposureMode_choices = ["off","auto","night","nightpreview","backlight","spotlight"]
        ExposureMode_selected = easygui.choicebox("Exposure mode", "Exposure mode", ExposureMode_choices)
        if ExposureMode_selected is not None:
            camera.exposure_mode = ExposureMode_selected
        camera.preview_alpha=255

### select folder and set filename prefix
    
    if key == KeyCode(char='F'):
        camera.preview_alpha=0
        path = easygui.diropenbox()
        camera.preview_alpha=255
    if key == KeyCode(char='f'):
        camera.preview_alpha=0
        filename = easygui.enterbox("Filename prefix", "Input", "")
        camera.preview_alpha=255
        
######## MOTORIZED STAGE

### Ctrl: change motor speed
    
    if key == Key.ctrl_l or key == Key.ctrl_r:
        if speed == slow:
            speed = medium
            camera.annotate_text = "Motor speed = medium"
        elif speed == medium:
            speed = fast
            camera.annotate_text = "Motor speed = fast"
        elif speed == fast:
            speed = slow
            camera.annotate_text = "Motor speed = slow"
            
### keyboard arrow keys, Alt key toggles between X-Y and Rotate-Tilt
### send Arduino a string to control the motors, e.g. "-100X," or "500Y,"
### the integer defines the direction and the speed of the motor, the letter selects the motor
            
    if key == Key.alt_l or key == Key.alt_r:
        if arrowkey_mode == True:
            arrowkey_mode = False
            camera.annotate_text = "X-Y"
        elif arrowkey_mode == False:
            arrowkey_mode = True
            camera.annotate_text = "Rotate-Tilt"

    if not KeyboardControl:
        return

    if key == Key.left:
        if arrowkey_mode == False:
            data = str(speed*-1) + "X,"
        else:
            data = str(speed*-1) + "R,"
        ser.write(data.encode())
            
    if key == Key.right:
        if arrowkey_mode == False:
            data = str(speed) + "X,"
        else:
            data = str(speed) + "R,"
        ser.write(data.encode())
      
    if key == Key.down:
        if arrowkey_mode == False:
            data = str(speed*-1) + "Y,"
        else:
            data = str(speed*-1) + "T,"
        ser.write(data.encode())
            
    if key == Key.up:
        if arrowkey_mode == False:
            data = str(speed) + "Y,"
        else:
            data = str(speed) + "T,"
        ser.write(data.encode())
        
### Z up and down, Page up and Page down
            
    if key == Key.page_up: 
        data = str(speed) + "Z,"
        ser.write(data.encode())
        
    if key == Key.page_down:
        data = str(speed*-1) + "Z,"
        ser.write(data.encode())

### Camera up and down, Home and End
        
    if key == Key.home: 
        data = str(speed) + "C,"
        ser.write(data.encode())
        
    if key == Key.end: 
        data = str(speed*-1) + "C,"
        ser.write(data.encode())
        
######## LED

### LED intensity, max. value in the data is set to 20 to make it compatible with the joystick
### PWM of the LED driver works in the opposite direction
### Intensity is controlled in 5% increments
        
    if key == KeyCode(char='L'):
        if LEDintensity !=20:
            LEDintensity += 1
            data = str(20-LEDintensity) + "L,"
            ser.write(data.encode())
            annotate_text = "LED intensity:" + str(LEDintensity*5) + "%"
            camera.annotate_text = annotate_text
    if key == KeyCode(char='l'):
        if LEDintensity !=0:
            LEDintensity -= 1
            data = str(20-LEDintensity) + "L,"
            ser.write(data.encode())
            annotate_text = "LED intensity:" + str(LEDintensity*5) + "%"
            camera.annotate_text = annotate_text
Example #33
0
def gui_input_gene():
    easygui.msgbox('  This is a (List-based Evolutionary Algorithm) program built by Yingkai Liu'
                   '\n                                enjoy!                                      '
                   '\n'
                   '\n                  should you find any problems, contact                     '
                   '\n                      [email protected]                              ',
                   'List-based Evolutionary Algorithm')

    number_of_gene_input = easygui.enterbox(
        msg='           Here you need to specify number of chromosome sites first.',
        title='-number_of_gene',
        default='5')

    number_of_gene = int(number_of_gene_input)
    gene_set_field_name = []
    for i in range(number_of_gene):
        gene_set_field_name.append("*****************" + str(i) + "th gene's high")
        gene_set_field_name.append("low")
        gene_set_field_name.append("number of interval")

    gene_set_input = easygui.multenterbox(
        msg='Here you need to specify the high,low,step of each parameter\n and of course, it starts from zero\n',
        title='LEA-gene_set[]',
        fields=gene_set_field_name,
        values = [5,0,5,5,0,5,5,0,5,5,0,5,5,0,5])
        #values=[str(7 * i - i + 6) for i in range(len(gene_set_field_name))])

    hi_of_each_gene = []
    lo_of_each_gene = []
    n_of_each_gene = []

    step_of_each_gene = []
    range_of_each_gene = []
    val_of_each_gene = []

    for i in range(number_of_gene):
        hi_of_each_gene.append(float(gene_set_input[3 * i + 0]))
        lo_of_each_gene.append(float(gene_set_input[3 * i + 1]))
        n_of_each_gene.append(int(gene_set_input[3 * i + 2]))

    for i in range(number_of_gene):
        # take the absolute of high - low
        step_of_each_gene.append(abs((hi_of_each_gene[i] - lo_of_each_gene[i]) / float(n_of_each_gene[i] - 1)))
        range_of_each_gene.append(abs(hi_of_each_gene[i] - lo_of_each_gene[i]))
        val_of_each_gene.append([])

    for m in range(number_of_gene):
        for k in range(n_of_each_gene[m]):
            val_of_each_gene[m].append(lo_of_each_gene[m] + k * step_of_each_gene[m])

    confirm_message = ''
    for i in range(number_of_gene):
        info = ['***the ', str(i), 'th Gene:',
                '\n                 High:: ', str(hi_of_each_gene[i]),
                '\n                  Low:: ', str(lo_of_each_gene[i]),
                '\n                Range:: ', str(range_of_each_gene[i]),
                '\n                    N:: ', str(n_of_each_gene[i]),
                '\n                 Step:: ', str(step_of_each_gene[i]),
                '\n                         **********Gene Set @ site ' + str(i) + '**********',
                '\n                        ', str(val_of_each_gene[i]),
                '\n']
        confirm_message += ''.join(info)

    easygui.textbox(msg='Here is the confirm message of your input:\n'
                        '\n'
                        'total site = ' + str(number_of_gene) + '\n',
                    title='NSGA-confirm_message',
                    text=confirm_message,
                    codebox=True)

    gene_set = val_of_each_gene
    gene_range = range_of_each_gene

    return gene_set, gene_range
Example #34
0
import easygui
import os
ynbox = easygui.ynbox('选择下载方式', 'bilibili下载', ('AV号下载', '链接下载'))
if ynbox == True:
    b = easygui.enterbox(msg='输入AV号',
                         title='bilibili下载',
                         strip=True,
                         image=None,
                         root=None)
    c = 'python -m you_get -d -l -o /home/mwx/视频/bilibili https://www.bilibili.com/video/' + b
    print(c)
    os.system(c)
elif ynbox == False:
    d = easygui.enterbox(msg='输入连接',
                         title='bilibili下载',
                         strip=True,
                         image=None,
                         root=None)
    g = float(len(d))
    if g > 45:
        e = d[0:d.rfind('?', 1)]
    elif g < 50:
        e = d
    f = 'python -m you_get -d -l -o E:\lenovo\py ' + e
    print(f)
    os.system(f)
Example #35
0
def compareText():  #主体判断与执行函数 (要做的:+文件与文件夹比对  +大量文件互相交叉比对12)
    mode = chooseMode()  #选择模式
    if mode == 0:
        sys.exit(0)  #点取消就退出程序
    elif mode == 1:  #文件比对
        choice = g.buttonbox(msg='请选择文件格式',
                             title='选择文件格式',
                             choices=('TXT', 'Word(仅支持docx格式)'),
                             image=None)
        if choice == 'TXT':
            SourceRoute1 = g.fileopenbox(
                msg="请选择需比对的第一份文件",
                filetypes=["*.txt"])  #找到比对源文件,输出路径到SourceRoute1
            Source1 = open(SourceRoute1, encoding='utf-8')  #打开比对源文件1
            try:
                SourceDocString1 = Source1.read(
                )  #将txt内容输出到字符串SourceDocString1
            finally:
                Source1.close()
            SourceRoute2 = g.fileopenbox(
                msg="请选择需比对的第二份文件",
                filetypes=["*.txt"])  #找到比对源文件,输出路径到SourceRoute2
            Source2 = open(SourceRoute2, encoding='utf-8')  #打开比对源文件2
            try:
                SourceDocString2 = Source2.read(
                )  #将txt内容输出到字符串SourceDocString2
            finally:
                Source2.close()
        elif choice == 'Word(仅支持docx格式)':
            SourceDocString1 = wordGet(1)
            SourceDocString2 = wordGet(2)
        start = time.process_time()  #计时
        print("正在进行比对")
        r = synonyms.compare(SourceDocString1,
                             SourceDocString2,
                             seg=True,
                             ignore=True)  #语句比对
        end = time.process_time()
        Sim = str(r)  #将r值number转换为string
        g.msgbox(msg="输入的语句相似度为" + Sim, title='比对结果', ok_button='返回')
    elif mode == 2:  #网络比对
        output_list = []
        output_list2 = []
        choice = g.buttonbox(msg='请选择文本源',
                             title='选择文本源',
                             choices=('输入文本', '文本文件'),
                             image=None)  #选择文本比对/文件比对
        if choice == '输入文本':
            sen1 = g.enterbox(msg='请输入需比对的语句',
                              title='输入语句',
                              strip=True,
                              image=None)
            start = time.process_time()  #计时
            output = webCompare(sen1)  #比对函数
            end = time.process_time()
            for key, value in output.items():  #创造输出的条件
                output_list.append(key)
                output_list2.append(value)
            g.msgbox(msg="相似度最高,为" + str(output_list[0]) + "的网络链接为:" +
                     output_list2[0] + "\n" + "相似度第二高,为" +
                     str(output_list[1]) + "的网络链接为:" + output_list2[1] + "\n" +
                     "相似度第三高,为" + str(output_list[2]) + "的网络链接为:" +
                     output_list2[2])
        elif choice == '文本文件':
            SourceRoute1 = g.fileopenbox(
                msg="请选择需比对的文本文件",
                filetypes=["*.txt"])  #找到比对源文件,输出路径到SourceRoute1
            Source1 = open(SourceRoute1, encoding='utf-8')  #打开比对源文件1
            try:
                SourceDocString1 = Source1.read(
                )  #将txt内容输出到字符串SourceDocString1
            finally:
                Source1.close()
            start = time.process_time()  #计时
            output = webCompare(SourceDocString1)
            end = time.process_time()
            for key, value in output.items():  #创造输出的条件
                output_list.append(key)
                output_list2.append(value)
            print(output)
            g.msgbox(msg="相似度最高,为" + str(output_list[0]) + "的网络链接为:" +
                     output_list2[0] + "\n" + "相似度第二高,为" +
                     str(output_list[1]) + "的网络链接为:" + output_list2[1] + "\n" +
                     "相似度第三高,为" + str(output_list[2]) + "的网络链接为:" +
                     output_list2[2])
    elif mode == 3:  #即时输入比对
        sen1 = g.enterbox(msg='请输入需比对的第一语句',
                          title='输入语句',
                          strip=True,
                          image=None)
        sen2 = g.enterbox(msg='请输入需比对的第二语句',
                          title='输入语句',
                          strip=True,
                          image=None)
        start = time.process_time()  #计时
        print("正在进行比对")
        r = synonyms.compare(sen1, sen2, seg=True, ignore=True)  #语句比对
        Sim = str(r)  #将r值number转换为string
        end = time.process_time()
        g.msgbox(msg="输入的语句相似度为" + Sim, title='比对结果', ok_button='返回')
    elif mode == 4:  #即时输入与文件比对
        SourceRoute1 = g.fileopenbox(msg="请选择需比对的第一份文件",
                                     filetypes=["*.txt"
                                                ])  #找到比对源文件,输出路径到SourceRoute1
        Source1 = open(SourceRoute1, encoding='utf-8')  #打开比对源文件1
        try:
            SourceDocString1 = Source1.read()  #将txt内容输出到字符串SourceDocString1
        finally:
            Source1.close()
        sen1 = g.enterbox(msg='请输入需比对的第一语句',
                          title='输入语句',
                          strip=True,
                          image=None)
        start = time.process_time()  #计时
        print("正在进行比对")
        r = synonyms.compare(sen1, SourceDocString1, seg=True,
                             ignore=True)  #语句比对
        Sim = str(r)  #将r值number转换为string
        end = time.process_time()
        g.msgbox(msg="输入的语句相似度为" + Sim, title='比对结果', ok_button='返回')
    elif mode == 5:  #文件+文件夹比对(Word(.docx) only)
        SourceDocString1 = wordGet(1)  #取文件
        Dir = g.diropenbox(msg="请选择需比对的文件目录", title="请选择需比对的文件目录")  #取文件夹
        FileDir = os.listdir(Dir)  #遍历文件
        filecontent = dict()  #建立内容字典
        reldict = dict()  #建立相似度字典
        key_list2 = []
        value_list2 = []
        output_list = []
        output_list2 = []
        output = dict()
        for file in FileDir:
            fildir = Dir + "\\" + file
            if os.path.splitext(file)[1] == '.docx':  #判断文件扩展名
                doc = docx.Document(fildir)
                content = ''
                for i in doc.paragraphs:  #遍历全部段落
                    contentstr = i.text
                    if len(contentstr) > 0:  #排除空段
                        content += contentstr  #content字符串保存内容
                filecontent[file] = content
            else:
                pass
        start = time.process_time()
        for filecon in filecontent.values():  #比对代码+反向查询+排序
            rel = synonyms.compare(filecon,
                                   SourceDocString1,
                                   seg=True,
                                   ignore=True)
            reldict[rel] = filecon  #创造子字典(相似度:比对内容)
        ressorted = sorted(reldict.items(), key=lambda x: x[0], reverse=True)
        for key, value in filecontent.items():  #创造主字典内反向查找的条件
            key_list2.append(key)
            value_list2.append(value)
        for m in ressorted[0:3]:  #beg:end=beg->(end-1)!!!!!注意数字含义!!
            key = m[1]  #查找:在results中取前三位的key值
            output[m[0]] = key_list2[value_list2.index(key)]
        for key, value in output.items():  #创造输出的条件
            output_list.append(key)
            output_list2.append(value)
        end = time.process_time()
        g.msgbox(msg="相似度最高,为" + str(output_list[0]) + "的文件为:" +
                 output_list2[0] + "\n" + "相似度第二高,为" + str(output_list[1]) +
                 "的文件为:" + output_list2[1] + "\n" + "相似度第三高,为" +
                 str(output_list[2]) + "的文件为:" + output_list2[2])
    elif mode == 6:  #文件夹交叉比对
        Dir = g.diropenbox(msg="请选择需比对的文件目录", title="请选择需比对的文件目录")  #取文件夹
        FileDir = os.listdir(Dir)  #遍历文件
        FullDir = []
        RelDict = {}
        output = {}
        output_list = []
        output_list2 = []
        for file in FileDir:  #完整路径list
            fildir = Dir + "\\" + file
            FullDir.append(fildir)
        start = time.process_time()
        for sourcefile in FullDir[0:len(FullDir) - 1]:  #对除最后一个以外的每一个文件进行操作
            srcdoc = docx.Document(sourcefile)
            srccontent = ''
            for i in srcdoc.paragraphs:  #遍历全部段落
                srccontentstr = i.text
                if len(srccontentstr) > 0:  #排除空段
                    srccontent += srccontentstr  #content字符串保存内容
            for targetfile in FullDir[FullDir.index(sourcefile) +
                                      1:]:  #对该文件与其之后的文件进行比对
                tgtdoc = docx.Document(targetfile)
                tgtcontent = ''
                for i in tgtdoc.paragraphs:  #遍历全部段落
                    tgtcontentstr = i.text
                    if len(tgtcontentstr) > 0:  #排除空段
                        tgtcontent += tgtcontentstr  #content字符串保存内容
                sim = synonyms.compare(srccontent,
                                       tgtcontent,
                                       seg=True,
                                       ignore=True)
                RelDict[sim] = os.path.basename(
                    targetfile) + "和" + os.path.basename(sourcefile)
        ressorted = sorted(RelDict.items(), key=lambda x: x[0], reverse=True)
        end = time.process_time()
        for m in ressorted[0:3]:  #beg:end=beg->(end-1)!!!!!注意数字含义!!
            output[m[0]] = m[1]
        for key, value in output.items():  #创造输出的条件
            output_list.append(key)
            output_list2.append(value)
        g.msgbox(msg="相似度最高,为" + str(output_list[0]) + "的文件为:" +
                 output_list2[0] + "\n" + "相似度第二高,为" + str(output_list[1]) +
                 "的文件为:" + output_list2[1] + "\n" + "相似度第三高,为" +
                 str(output_list[2]) + "的文件为:" + output_list2[2])
    print("本次运行用时%6.3f'秒" % (end - start), sep='')
Example #36
0
import easygui

easygui.msgbox("This program converts Fahrenheit to Celsius")
fahrenheit = float(easygui.enterbox("Type in  a temperature in Fahrenheit: "))
celsius = int((fahrenheit - 32) * 5.0 / 9)
easygui.msgbox("This is " + str(celsius) + " degrees Celsius")
Example #37
0
                    bb11[k] = item[k]
            bb1.append(bb11)
        blocks2.append(bb1)
    templates1.append(blocks2)

# my_file.write('tcm_template1.json', templates)
import requests
import easygui as eg
from requests.auth import HTTPBasicAuth

auth = HTTPBasicAuth('hpp_test', 'hpp.123456')
headers = {'Content-Type': 'application/json'}
print auth.username
rq_template = get_uuid()
template_name = '普适版%s' % format_time(frm='%m%d%H%M')
template_name = eg.enterbox('模板标题', default=template_name)
rq_data = {
    'template_name': template_name,
    # 'template_name': '普适版',
    'template': rq_template,
    'template_info': templates1[0]
}
rq_data = my_file.read('tcm_template_online.json')[0]
rq_data['template'] = rq_template
rq_data['template_name'] = template_name
my_file.write('%s.json' % rq_template, rq_data)
response = requests.request(
    'post',
    'http://192.168.105.4:8000/api/v2/detection/template/',
    auth=auth,
    headers=headers,
Example #38
0
 def searchfileface(self):
     defaultdir = easygui.enterbox(msg="请输入你想查找的文件目录:")
     target = easygui.enterbox(msg=("请输入你想要查找的文件名:"))
     choice = SearchFile().searchfile(defaultdir, target)
     resultbox = easygui.choicebox(
         msg="在{}路径下搜索到的符合条件的文档如下:".format(defaultdir), choices=choice)
Example #39
0
def Main():  # The space for the main function of the program.
    easygui.msgbox(
        "Welcome to Grade Letter Calculator. Get ready to enter your percentage from 0 to 100."
    )
    leave = False  # Sentinel variable for allowing user to exit the program.
    grade = ""  # The letter grade.
    ext = ""  # The + or -.
    perfect = False  # a 100% or an F gives makes this true.
    while (not leave):  # THis keeps the program running.
        gradePercent = float(easygui.enterbox(
            "Please enter the grade."))  # Asks the user for the grade.
        '''THis next part determines what the grade is by checking if the value is less than a certain number, 
        and until that is true, it just keeps on looking until it hits 100, the highest possible number for this 
        program to accept. '''
        if (gradePercent < 60):
            grade = "F"
            perfect = True
        elif (gradePercent <= 69):
            grade = "D"
        elif (gradePercent <= 79):
            grade = "C"
        elif (gradePercent <= 89):
            grade = "B"
        elif (gradePercent <= 99):
            grade = "A"
        elif (gradePercent == 100):
            grade = "A"
            perfect = True
            ext = "+"
        else:
            print "Please enter a valid grade."
            break

        if (
                grade != "F" and not perfect
        ):  # This checks if the grade isn't an F and it isn't perfect. The "grade !=
            # "F"" is just redundancy.
            if (gradePercent % 10 >= 7.50):
                ext = "+"
            elif (gradePercent % 10 <= 2.49):
                ext = "-"
            else:
                ext = ""
        '''This code does nothing. It was a previous attempt that works, but it doesn't actually run during the 
        program's cycle. '''
        # elif (gradePercent < 70 and gradePercent >= 60):
        #     if(gradePercent < 62.5):
        #         easygui.msgbox("The grade is a D-")
        #     elif(gradePercent >= 62.5 and gradePercent < 67.5):
        #         easygui.msgbox("The grade is a D.")
        #     else:
        #         easygui.msgbox("The grade is a D+.")
        # elif (gradePercent < 80 and gradePercent >= 70):
        #     if(gradePercent < 72.5):
        #         easygui.msgbox("The grade is a C-")
        #     elif(gradePercent >= 72.5 and gradePercent < 77.5):
        #         easygui.msgbox("The grade is a C.")
        #     else:
        #         easygui.msgbox("The grade is a C+.")
        # elif (gradePercent < 90 and gradePercent >= 80):
        #     if(gradePercent < 82.5):
        #         easygui.msgbox("The grade is a B-")
        #     elif(gradePercent >= 82.5 and gradePercent < 87.5):
        #         easygui.msgbox("The grade is a B.")
        #     else:
        #         easygui.msgbox("The grade is a B+.")
        # elif (gradePercent < 100 and gradePercent >= 90):
        #     if(gradePercent < 92.5):
        #         easygui.msgbox("The grade is a A-")
        #     elif(gradePercent >= 92.5 and gradePercent < 97.5):
        #         easygui.msgbox("The grade is a A.")
        #     else:
        #         easygui.msgbox("The grade is a A+.")

        easygui.msgbox("The grade is " + grade + ext +
                       ".")  # Outputs the letter grade with extension.
        leaver = easygui.buttonbox(
            "Do you want to leave? ",
            choices=["Yes", "No"])  #Asks the user if they wish to exit.
        if (leaver == "Yes"):  #The check.
            leave = True
        else:
            leave = False
Example #40
0
    ###########################################################################
    # test inputs -- these will have to be edited to be put in a config file later
    ###########################################################################
    results_folder = 'turing_data' #directory to store dataframes/excel files of results
    dicom_data_folder = 'dicom_sample' #path to folder containing all folders that have ct data in them (ie in results folders are 0001, 0002, etc)
    human_rts_filename = 'Manual_only.dcm'
    machine_rts_filename = 'DL_Ottawa93.dcm'   
    structure_choices = ['Prostate', 'Rectum', 'Bladder']
    smooth_human_contours = True

   
    ###########################################################################
    # Initialize user info, and data available based on that
    ###########################################################################
    users = ['dgranville', 'mmacpherson', 'dlarussa']
    user = easygui.enterbox('Enter your TOH username')
    while user not in users:
        user = easygui.enterbox('Username not found.\nEnter your TOH username')
    # read in previous user data if it exists, if not create fresh set of user data
    if user + '.p' in os.listdir(results_folder):
        user_data = pickle.load( open( results_folder + '\\' + user + ".p", "rb" ) )
    else:
        user_data = []
        
    ###########################################################################
    # Allow user to select structure to evaluate
    ###########################################################################
    structure_wanted_human = easygui.choicebox('Select the structure to evaluate:', 'Structure Options', structure_choices)
    structure_wanted_machine = structure_wanted_human.upper() + '_1'    
    
    # generate list of patient folder names
Example #41
0
    x = 1
    while i < count:
        keyword = linecache.getline(JDpath, i)
        if keyword.find(word) == -1:
            b = 1
        else:
            # 查询到了
            n = i
            print(2)
            while x < 2:
                keyword = linecache.getline(JDpath, n)
                if keyword.find("答案") == -1:
                    # 空值
                    b = 1
                else:
                    x = 2
                    Strtitle = keyword = linecache.getline(JDpath, i)
                    keyword = linecache.getline(JDpath, n)
                    g.msgbox(msg=keyword, title=Strtitle, ok_button="确定")
                    i = count
                    # 查询到了
                    search(g.enterbox(msg="请输入搜索内容", title="禁毒正则"), JDpath)
                n = n + 1
        i = i + 1
    print("查询结束")


if __name__ == "__main__":
    JDpath = g.enterbox(msg="请输入题库路径", title="哔哩哔哩:萌新杰少")
    search(g.enterbox(msg="请输入搜索内容", title="禁毒正则"), JDpath)
def vvid():
    msg = 'Введіть шлях до зображення'
    title = 'Введення шляху до зображення'
    fieldValues2 = easygui.enterbox(msg, title)
    path_string = fieldValues2
    return path_string
Example #43
0
import easygui
from easygui import msgbox, multenterbox

  = "3.jpg"
msg = "是否加入到人脸识别库中?"
choices = ["Yes","No"]
reply = easygui.buttonbox(msg, image=image, choices=choices)
if reply=="No":
    print("no")
else:
    print("yes")
    flavor = easygui.enterbox("请输入名字(必须是英文(拼音),不能有空格和特殊符号)") 
    easygui.msgbox ("您输入了: " + flavor)
    


Example #44
0
import easygui as ei
import pylab as py

A=[]
b=[]

msg= 'Informe o numero de linnhas e colunas da matriz'
title= 'Sistema Linear'
op= ('Linhas','Colunas')
coef= ei.multenterbox(msg,title,op)
if (coef[0]!=coef[1]):
    ei.msgbox('A Matriz nao e quadrada! Informe valores iguais para Linha e Coluna')
elif
    for i in range(coef[0]):
        for j in range(coef[1]):
            c =ei.enterbox(msg='Informe o valor para o termo A' + str(i) + str(j), title)
            aux=[]
            aux.append(c)
            aux = py.array(aux)
            A.append(aux)
            print (A)


#Jerdy Bartholomeus 0919350 RAC17-ICTVT1C 31-08-2017
#Opdracht 8

import easygui

#1
art_numm = int(easygui.enterbox("Voer hier de artikelnummer in"))
#2
art_naam = easygui.enterbox("Voer hier de naam van de artikel in")
#3
art_prijs = float(easygui.enterbox("Voer hier de prijs van de artikel in"))
#4
korting = float(15 / 100 * art_prijs)
art_prijs_kort = float(art_prijs - korting)

easygui.msgbox("Uw korting is " + str(korting))
easygui.msgbox("Artikelnummer: " + str(art_numm) + " " + art_naam +
               " kost normaal " + str(art_prijs) +
               " euro en nu met 15% korting nog maar " + str(art_prijs_kort) +
               " euro.")
Example #46
0
def bs():
    while True:
        appinfo = gui.buttonbox(
            msg="Application: Waterf0x",
            title="HUGEHARD System",
            choices=("Open", "Info", "Cancel"),
            image=
            "/Users/jacobduan/Desktop/WORK/MY_NAME_IS_HACK-BETA/Images/waterf0x.gif"
        )
        if appinfo == "Open":
            web = gui.enterbox(
                msg="Welcome to Waterf0X broswer, type the website here",
                title="HUGEHARD System -- Waterf0X")
            if web == "pylogin.com/has_been_locked":
                gui.textbox(
                    msg="The user has been locked",
                    text=
                    "The user has been locked might be you don't have a account or your account is not safe, or your account has been hacked"
                )
            if web == "10.10.10.14/23":
                gui.textbox(
                    msg="PROBLEM\nNo.8",
                    text=
                    "The account cannot be hack might because the account has protect by some encrypt system that we don't know, until this encrypt system's source code is open to us, the hack might be succed",
                    title="Waterf0X")
            if web == "tools.me":
                gui.textbox(
                    msg="tools.me\nCOPYRIGHT TOOLS.ME, TEMPLE MONKEY COMPANY",
                    text=
                    "Welcome to tools.me, there are a lot of free tools and fee-paying tools here",
                    title="HUGEHARD System -- Waterf0X")
                dl = gui.choicebox(
                    msg="Tools",
                    choices=[
                        "Waterf0X - Fast and simple broswer",
                        "Mail Box - Fast speed email tools",
                        "HTTP Catcher - Powerful HTTP catching tools"
                    ],
                    title="HUGEHARD System -- Waterf0X")
                if dl == "Waterf0X":
                    gui.msgbox(
                        msg=
                        "You already download this application in your computer",
                        title="HUGEHARD System -- Waterf0X")
                    continue
                else:
                    gui.msgbox(
                        msg=
                        "You already download this application in your computer",
                        title="HUGEHARD System -- Waterf0X")
                    continue
            else:
                chs = gui.buttonbox(msg="Can't found the server, continue?",
                                    choices=["continue searching", "exit"],
                                    title="HUGEHARD System -- Waterf0X")
                if chs == "continue searching":
                    continue
                if chs == "exit":
                    exit()
        if appinfo == "Info":
            gui.msgbox(
                msg=ve + "1.13" + "\n" + sp + "95.3M" + "\n" + de +
                "WATERF0X GRUOP",
                title="HUGEHARD System",
                image=
                "/Users/jacobduan/Desktop/WORK/MY_NAME_IS_HACK-BETA/Images/waterf0x.gif"
            )
Example #47
0
def six():
    result = gui.enterbox(breadtext, title)
    print(result)  # Returnere værdien der bliver skrevet
def _record_age(patient):
    age = enterbox(ms["enter_patient_age"], ms["patient_age"], patient.age)
    if age is None:
        raise LeftIncompleteException
    patient.age = age
import xlrd
from natsort import os_sorted
import re

excel_or_nah = easygui.indexbox(msg="select what you would like to do",
                                title="Yeast Classifier",
                                choices=('Compare Excel sheets',
                                         'Extract data from pictures',
                                         'lookup cell'))
if (excel_or_nah == 2):
    easygui.msgbox(
        title="Yeast Classifier",
        msg="Next select the folder for the images and the cell location")
    dir = easygui.diropenbox(title="Yeast Classifier")
    cell_loc = easygui.enterbox(title="Yeast Classifier",
                                msg="Enter cell location"
                                "\nExample U04-C07"
                                "\nMAKE SURE TO USE CAPITAL LETTERS")

    choose = easygui.indexbox(msg="Which mode would you like?",
                              title="Yeast Classifier",
                              choices=('384 format with cluster of 4',
                                       '384 format each cell different'))
    loc = (re.findall('\d+', cell_loc))
    row = (cell_loc[4])
    col = int(loc[1])
    plate = (int(loc[0]) - 1)  # list will be zero indexed so minus 1
    if (col > 12):
        print("Wrong value entered")
        exit(-2)
    imagePath = (list(paths.list_images(dir)))
    imagePath = os_sorted(imagePath)
Example #50
0
        choices=choices)

pklFile.close()
pklFile = file(saveLoc + "\\pklFileFLDROptIn.txt", 'w')
pickle.dump(FLDROptIn, pklFile)
pklFile.close()

#If 'Name Folder' Chosen:
if FLDROptIn == "Name Folder":
    #Folder name for MXD files.
    try:
        pklFile = file(saveLoc + "\\pklFileFLDR_MXD.txt", 'r')
        restoreValFLDR = pickle.load(pklFile)
        if setupOptIn == 'Setup':
            FLDR_MXD = eg.enterbox(
                "Enter the name of the folders containing your MXD files, ie: service_mxd",
                default=restoreValFLDR)
        else:
            FLDR_MXD = restoreValFLDR
    except:
        FLDR_MXD = eg.enterbox(
            "Enter the name of the folders containing your MXD files, ie: service_mxd"
        )

    pklFile.close()
    pklFile = file(saveLoc + "\\pklFileFLDR_MXD.txt", 'w')
    pickle.dump(FLDR_MXD, pklFile)
    pklFile.close()
else:
    pass
def askname(msg="please enter your name"):
    return easygui.enterbox(msg)  # python2.x: use "raw_input" instead "input"
Example #52
0
import easygui as g
import sys
import calendar
import datetime

while 1:

    s = g.enterbox("请输入目标时间(年月日,如20190706): ")
    d = g.enterbox("请输入开始时间(年月日,如20190706): ")

    a = str(s)
    b = str(d)

    year1 = int((a[0:4]))
    month1 = int(a[4:6])
    day1 = int(a[6:8])
    # print(year1,month1,day1)

    year2 = int((b[0:4]))
    month2 = int(b[4:6])
    day2 = int(b[6:8])
    #print(year2,month2,day2)

    cal = calendar.month(year1, month1)
    #print("本月日历为: ")
    #print(cal)

    l = g.msgbox("目标月月历为: " + cal)

    def days(data1, data2):
        date1 = datetime.date(year1, month1, day1)
#!/usr/bin/env python
__author__ = 'marcsantiago'

from PIL import Image

from easygui import buttonbox
from easygui import enterbox
from easygui import msgbox
from easygui import fileopenbox

answer = buttonbox("What would you like to do, encrypt a message or decrypt the image", choices=["Encrypt", "Decrypt"])

if answer == "Encrypt":
    plaintext = enterbox("Enter a message you would like to hide in an image")
    # creates a long vertical image 1 pixel wide
    im = Image.fromstring('L', (1, len(plaintext)), plaintext)
    filename = enterbox("Give your image a name")
    # check to see if the user added the extention manually
    if ".png" in filename:
        filename = filename.replace(".png", "")
    im.save(filename + ".png", format("PNG"))
elif answer == "Decrypt":
    image_file = fileopenbox("Please pick an image file that you would like to decrypt", filetypes=["*.png"])
    if ".png" not in image_file:
        image = image_file + ".png"
    my_image = Image.open(image_file)
    pix = my_image.getdata()
    temp = []
    # convert the ascii data back into characters and recontruct the string
    for i in list(pix):
        temp.append(i)
Example #54
0
IC0283 COMPUTATIONAL MODELLING
Universidad EAFIT
Departamento de Ingenieria Civil

Last updated January 2016
"""
import numpy as np
import preprocesor as pre
import postprocesor as pos
import assemutil as ass
from datetime import datetime
import matplotlib.pyplot as plt
import easygui

folder = easygui.diropenbox(title="Folder for the job") + "/"
name = easygui.enterbox("Enter the job name")
echo = easygui.buttonbox("Do you want to echo files?", choices=["Yes", "No"])

start_time = datetime.now()

#%%
#   MODEL ASSEMBLY
#
# Reads the model
nodes, mats, elements, loads = pre.readin(folder=folder)
if echo == "Yes":
    pre.echomod(nodes, mats, elements, loads, folder=folder)
# Retrieves problem parameters
ne, nn, nm, nl, COORD = pre.proini(nodes, mats, elements, loads)
# Counts equations and creates BCs array IBC
neq, IBC = ass.eqcounter(nn, nodes)
Example #55
0
# -*- coding: utf-8 -*-
# @Author: WuLC
# @Date:   2016-05-12 22:57:40
# @Last modified by:   WuLC
# @Last Modified time: 2016-05-12 23:32:02
# @Email: [email protected]

import sys
import easygui

reload(sys)
sys.setdefaultencoding('utf8')

forbidden = []
with open('filtered_words.txt') as f:
	forbidden = map(lambda x:x.strip().lower(), f.readlines())

while True:
	inp = easygui.enterbox('input sth,click "Cancle" to stop').strip()
	forbid = False
	for i in forbidden:
		if i in inp:
		    print 'forbidden',inp.replace(i, '**')
		    forbid = True
		    break
	if not forbid:
		print inp
Example #56
0
    def Activated(self):
        "Do something here"
        import numpy, scipy, FreeCADGui, easygui, Draft
        from SurveyTools import Tools
        from scipy.spatial import Delaunay
        import matplotlib.pyplot as plt

        #aconsegueix la seleccio de freecad

        sel = FreeCADGui.Selection.getSelection(
        )  #comprova si la seleccio es un grup
        if sel[0].InList[0].Tipus == "Punts":
            #grup_llista=[]
            #for i in range(len(sel)-1):
            #    grup_llista.append(sel[i].OutList)    #llista d'objectes del grup
            #print grup_llista
            #comprova que el primer objecte sigui un Punt (Survey)
            if sel[0][0].Tipus == "Punt":
                tri_grp = Tools.creaSuperficie(
                    easygui.enterbox('tria un nom de superficie'))

                llistaPunts_z = []
                llistaPunts = []
                #agrega els punts del grup a la llista
                for p in grup_llista:
                    llistaPunts_z.append([p.X, p.Y, p.Z])
                    llistaPunts.append([p.X, p.Y])
                    print(p.Label, p.Codi, p.X, p.Y, p.Z)
                points = numpy.array(llistaPunts)
                tri = Delaunay(points)
                pointsZ = numpy.array(llistaPunts_z)
                triZ = Delaunay(pointsZ)

                print llistaPunts, llistaPunts_z
                for t in points[tri.simplices]:
                    triangle = []
                    print 't', t
                    for p in t:
                        for pun in llistaPunts_z:
                            if pun[0] == p[0] and pun[1] == p[1]:

                                print 'for t in pointZ(tri.simplices)/forp in t', p
                                x, y, z = pun
                                triangle.append(FreeCAD.Vector(x, y, z))
                        print 'p', p
                    Draft.makeWire(triangle,
                                   closed=True,
                                   face=True,
                                   support=None)  # create the wire open

                    # create the wire open

                return

            else:
                easygui.msgbox('Necessites triar un grup de punts',
                               'Instruccions')

        else:
            easygui.msgbox('Necessites triar un grup de punts', 'Instruccions')

        return
import cv2
import numpy as np
import os
import dlib
from imutils import face_utils
from imutils.face_utils import FaceAligner
import easygui

detector = dlib.get_frontal_face_detector()
shape_predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
face_aligner = FaceAligner(shape_predictor, desiredFaceWidth=200)
video_capture = cv2.VideoCapture(0)
name = easygui.enterbox("Enter Name", "DataSet Generator")
path = 'images'
directory = os.path.join(path, name)
if not os.path.exists(directory):
    os.makedirs(directory, exist_ok='True')
msg = "How do you want to add new data?"
title = "DataSet Generator"
choices = ["Live Video", "Upload Photo"]
choice = easygui.choicebox(msg, title, choices)
t = choice
number_of_images = 0
MAX_NUMBER_OF_IMAGES = 10
count = 0
if t == "Live Video":
    while number_of_images < MAX_NUMBER_OF_IMAGES:
        ret, frame = video_capture.read()

        frame = cv2.flip(frame, 1)
Example #58
0
import easygui
import turtle


reply=easygui.buttonbox("Select shape",choices=['circle','triangle'])
t=turtle.Pen()
turtle.setup(width=550, height=400)

if reply=='circle':
    number=easygui.enterbox("Enter number of circle to draw")
    number=int(number)
    for i in range (number):
        if i%2==1:
            t.setheading(0)
            t.circle(20)
            t.up()
            t.forward(80)
            t.down()
        else:
            t.setheading(0) 
            t.circle(20)
            t.up()
            t.forward(40)
            t.down()
            
            
elif reply=='triangle':
    number=easygui.enterbox("Enter number of triangle to draw")
    number=int(number)
    for i in range (number):
        if i%2==1:
Example #59
0
password = "******"

easygui.msgbox("You need to type in a password to enter this program!")
choice = easygui.choicebox(
    "To learn about the password, you need to answer 30 simple multiplication questions. If you get all of them right in 60 seconds, you will get the password. Are you ready?",
    choices=["Sounds interesting and YES!", "Ahhh, get out of here!"])
if choice == "Sounds interesting and YES!":
    easygui.msgbox("Let's get started!")
    Time1 = timer()
    rights = 0
    wrongs = 0
    number = 0
    while number < 30:
        a = random.randint(1, 10)
        b = random.randint(1, 10)
        answer = int(easygui.enterbox(str(a) + " X " + str(b) + " = "))
        if answer == a * b:
            rights = rights + 1
        else:
            wrongs = wrongs + 1
        number = number + 1

    Time2 = timer()
    Time = round((Time2 - Time1), 2)

    if Time <= 60 and rights == 30:
        easygui.msgbox(
            "Nice! You got all 30 questions right in 60 seconds! The password is "
            + password + ".")
        TypeIn = easygui.enterbox("Please type in the password: ")
        if TypeIn == password:
def Create_project_true():
    enters = g.enterbox("Имя проекта","Создание проекта")
    if enters != "":
        if os.path.isdir(sys.argv[1]+enters):
            pass
        else:
            os.mkdir(sys.argv[1]+enters)
            os.mkdir(sys.argv[1]+enters+prefix+dir_virt)
            create_files_to(sys.argv[1]+enters+prefix+project_file,MAIN)
            create_files_to(sys.argv[1]+enters+prefix+test_file,MAIN)
            create_files_to(sys.argv[1]+enters+prefix+requipments_file)
            enters2 = g.enterbox("Заметка","README.md")
            create_files_to(sys.argv[1]+enters+prefix+help_file,enters2)
            create_files_to(sys.argv[1]+enters+prefix+gitignore_file,GIRIGNORE)
    else:
        if os.path.isdir(sys.argv[1]+dir_py_project):
            pass
        else:
            os.mkdir(sys.argv[1]+dir_py_project)
            os.mkdir(sys.argv[1]+dir_py_project+prefix+dir_virt)
            create_files_to(sys.argv[1]+dir_py_project+prefix+project_file,MAIN)
            create_files_to(sys.argv[1]+dir_py_project+prefix+test_file,MAIN)
            create_files_to(sys.argv[1]+dir_py_project+prefix+requipments_file)
            enters2 = g.enterbox("Заметка","README.md")
            create_files_to(sys.argv[1]+dir_py_project+prefix+help_file,enters2)
            create_files_to(sys.argv[1]+dir_py_project+prefix+gitignore_file,GIRIGNORE)