コード例 #1
0
ファイル: room22.py プロジェクト: Forritarar-FS/Kastali
 def counter_Attack():
     global Damage
     global Enemy_damage
     counter_attack_Direction = randint(1,3)
     CA_Direction = ("Attack Left!", "Attack Middle!", "Attack Right!")
     if counter_attack_Direction == 1:
         vulnerable = "Left"
     elif counter_attack_Direction == 2:
         vulnerable = "Middle"
     else:
         vulnerable = "Right"
     start_time = time.time()
     Counter_Attack = eg.buttonbox("The monster is vulnerable to attack from the "+ vulnerable +"!", choices=CA_Direction, title=fyrirUtan.info)
     total_time =time.time() - start_time
     print (total_time)
     print (vulnerable)
     print (Counter_Attack)
     if Counter_Attack == "Attack Left!" and vulnerable == "Left":
         Enemy_Hit()
     elif Counter_Attack == "Attack Middle!" and vulnerable == "Middle":
         Enemy_Hit()
     elif Counter_Attack == "Attack Right!" and vulnerable == "Right":
         Enemy_Hit()
          
     else:
         eg.msgbox("You missed and the monster regained his strength!", title=fyrirUtan.info)
コード例 #2
0
def dbConnect(inputHost,inputUser,inputPasswd,inputDB):

#     Create connection information for MySQLdb module.
#     
#     @type inputHost: string
#     @param inputHost: MySQL host machine or ip.
#     
#     @type inputUser: string
#     @param inputUser: MySQL username
# 
#     @type inputPasswd: string
#     @param inputPasswd: MySQL password.
# 
#     @type inputPasswd: string
#     @param inputPasswd: MySQL database.
#     
#     @rtype:  MySQLdb connect
#     @return: Return MySQLdb connection information.

    try:
        db = MySQLdb.connect(host=inputHost, user=inputUser, passwd =inputPasswd, db = inputDB)
    except:
        eg.msgbox("You entered in the incorrect username or password.")
        raise SystemExit
    return db
コード例 #3
0
ファイル: code.py プロジェクト: tejastank/rfc2barcode
def run(rfc_list= ["1111","22222"], pdf_file="barcode.pdf"):
    try:
        os.remove(pdf_file)
    except:
        pass

    c = Canvas(pdf_file)
    c.setFontSize(size="7")
    print  " %s pag para %s rfcs " % (round(len(rfc_list)/114.0,0), len(rfc_list))
    for times in range(0,int(round(len(rfc_list)/114.0,0))):
        for i in range(0,6):
            for j in range(1,20):
                st = code128.Code128()
                if len(rfc_list) >0 :
                    rfc = rfc_list.pop()
                else:
                    c.save()
                    sys.exit()
                st.value = rfc
                pos_x = i*30*mm
                pos_y = j*15*mm
                #print pos_x/mm,pos_y/mm
                st.drawOn(c, x = pos_x, y = pos_y)
                c.drawString(pos_x+10*mm, pos_y+7*mm , rfc )
        c.showPage()
        c.setFontSize(size="7")

        try:
            f = open(pdf_file, "wb")
        except IOError:
            easygui.msgbox("El archivo pdf esta abierto, por lo que no se puede guardar", "Error")
            sys.exit(0)
        c.save()
コード例 #4
0
def gamemenu():
    resolution = [640, 480]
    mode = 0
    msg = "Welcome player! Choose an option:"
    buttons = ["Finger", "Tool"]
    picture = None  # gif file
    while True:  # endless loop
        title = "Menu"
        selection = easygui.buttonbox(msg, title, buttons, picture)

        if selection == "Finger":
            mode = 1
            print "mode interno %d" % (mode)
            easygui.msgbox(
                "Make a L with your thumb and index finger to hold the pool stick. Circle your finger CW or CCW to rotate the pool stick.  Swipe to hit the ball. Show 5 fingers to start"
            )
            break
        elif selection == "Tool":
            mode = 2
            print "mode interno %d" % (mode)
            easygui.msgbox(
                "Hold a pen or pencil to rotate the pool stick. Move the tool fast to hit or open your hand. Show 5 fingers to start"
            )
            break

    return mode  # returns how many times the screensaver was watched (if anybody ask)
コード例 #5
0
ファイル: blubclient.py プロジェクト: AnthyG/BlubClient
def checkInbox(threadName, delay, counter):
    while True:
        if ONline == True:
            #test = str(raw_input("test: "))
            #if test == "break":
            #    break
            sock = socket.socket(socket.AF_INET, # Internet
                                 socket.SOCK_DGRAM) # UDP
            sock.bind((S_IP, int(S_PORT)))
            data, addr = sock.recvfrom(int(S_BUFFERSIZE)) #buffer size in bytes
            now = datetime.datetime.now()
            if data != "CC":
                print "Server>> ", now, " ", str(addr) + data
                easygui.msgbox(str(addr) + data, now)
                #self.components.chathistory.text = self.components.chathistory.text + "\n\n" + str(now) + " " + UDP_SENDERIP + ": " +  data
                
            if data == "CC":
                print data, str(addr)
                #send "heartbeat" to connected client
                sock = socket.socket(socket.AF_INET, # Internet
                socket.SOCK_DGRAM) # UDP
                sock.sendto(S_IP+" You have Succesfully connected to: "+ S_IP, (addr))

        elif ONline == False:
            print "Server>> OFFLINE!"
            time.sleep(1)
コード例 #6
0
ファイル: Lab10.py プロジェクト: Jaren831/usafa
def exercise1():
    """Interact with the user and test the sum_odds and sum_evens functions."""
    # You _DO_NOT_ need to modify this code for Lab 10.
    n = easygui.integerbox("Enter n:", "Input", lowerbound=0, upperbound=2 ** 31)
    odd = sum_odds(n)
    even = sum_evens(n)
    easygui.msgbox("n = {}\nsum of odds = {}\nsum of evens = {}".format(n, odd, even))
コード例 #7
0
    def _get_run_id(self):
        msg = ''' 
Please choose one of the following methods for defining gene families.

OrthoMCL runs are useful for identifying orthologs (genes likely to share a function)

maxbit runs are useful for identifying broader
gene families. c_xxx in the following list means xxx was used as a cutoff. Higher 
cutoffs mean more stringent similarity to define a family of related genes.

Note that only the groups of organisms that contain your gene are listed here.
'''
        valid_choices = self.accumulated_data['run_to_cluster'].keys()

        if len(valid_choices) == 0:
            easygui.msgbox('The chosen gene is not found in any clustering results!')
            return True

        runid = easygui.choicebox(msg, 'Select a cluster run', valid_choices)

        # Canceling from here - just go back to the other menu
        if runid is None:
            return runid

        self.accumulated_data['runid'] = runid
        return runid
コード例 #8
0
def show_windows():
    while 1:
#            title = "Message from test1.py"
#            eg.msgbox("Hello, world!", title)
    
        msg ="Run with which classification model?"
        title = "Classification model"
        models = ["Multinomial Naive Bayes", "Support Vector Machines", "Maximum Entropy"]
        model_choice = str(eg.choicebox(msg, title, models))
    
        msg     = "Use saved preset values?"
        choices = ["Yes","No"]
        choice = eg.buttonbox(msg,choices=choices)
        if str(choice)=="Yes":
            model_preset_functions[model_choice]()
        else:
            model_select_functions[model_choice]()
    
        # note that we convert choice to string, in case
        # the user cancelled the choice, and we got None.
#            eg.msgbox("You chose: " + str(choice), "Survey Result")
        message = "Sentiments over time period something something"
        image = "temporal_sentiments.png"
        eg.msgbox(message, image=image)
        
        msg = "Do you want to continue?"
        title = "Please Confirm"
        if eg.ccbox(msg, title):     # show a Continue/Cancel dialog
            pass  # user chose Continue
        else:
            sys.exit(0)           # user chose Cancel
コード例 #9
0
ファイル: __init__.py プロジェクト: sajmansilla/filefix
    def dir_open(self):
        directorio = eg.diropenbox(msg="Abrir directorio:",
                                   title="Control: diropenbox",
                                   default='/home/antonio')

        eg.msgbox(directorio, "diropenbox", ok_button="Continuar")
        return directorio
コード例 #10
0
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()
コード例 #11
0
ファイル: chill.py プロジェクト: Nasty94/ProjektPythonChill
    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) 
コード例 #12
0
ファイル: room33.py プロジェクト: Forritarar-FS/Kastali
def spookyGhost():
	eg.msgbox('"Já, ókei, flott, hæ. Ég er draugur falskra leikmanna-valmöguleika. Ég er með prik sem þú mátt fá, viltu?"')
	if revolver in room.grunnur.items:
		eg.msgbox('"Óh, flott byssa."')
		choosing2()
	else:
		choosing2()
コード例 #13
0
ファイル: Lab08.py プロジェクト: Jaren831/usafa
def exercise3():
    """Use the screen and turtle defined below to solve the given exercise."""
    # Create the turtle screen and two turtles (leave this as the first line).
    screen, artist, writer = turtle_setup()

    # TODO 3b: In the space below, write code to use the draw_inner_square function, as described in the lab document.
    draw_square(artist, 200)
    draw_inner_square(artist, 200, 0.25)
    easygui.msgbox("Click ok")
    artist.clear()

    # TODO 3d: In the space below, write code to use the draw_inner_squares function, as described in the lab document.
    draw_square(artist, 200)
    draw_inner_square(artist, 200, 9)
    artist.penup()
    artist.setpos( -120, 0)
    artist.pendown()
    draw_square(artist, 100)
    draw_inner_square(artist, 100, 4)
    artist.penup()
    artist.setpos(-120, -300)
    artist.pendown()
    draw_square(artist, 280)
    draw_inner_square(artist, 280, 2)
    easygui.msgbox("Click Ok")
    artist.clear()

    # TODO 3f: In the space below, write code to use the draw_art function, as described in the lab document.
    draw_art(artist, WIDTH - MARGIN * 2)

    # Wait for the user to click before closing the window (leave this as the last line).
    screen.exitonclick()
コード例 #14
0
ファイル: main.py プロジェクト: AgentSpyname/MightyMountain
    def deductRocks(self, entry):
        # Remove the collectible
        entry.getIntoNodePath().getParent().removeNode()
        # Update the number of objects
        if self.score > 500:
            randomnum = random.randint(1,2)
            if randomnum == 1:
             self.score = self.score - 100 #Removes Score
            if randomnum == 2:
             self.score = self.score + 100 #Removes Score

        if self.score < 500:
            self.score = self.score - 100

        randomnum = random.randint(1,2)

        if randomnum == 1:
            result =buttonbox(msg='A kind wizard wishes to help you on your quest? Trust him?', title='Alert!', choices=("Yes", "No"))

            if result == "Yes":
                othernum = random.randint(1,100)
                othernum = othernum * self.score + self.numObjects #Y = MX + B

                if othernum > 1000:
                    msgbox("Good choice! Add 1,000 Points to your Score!")
                    self.score = self.score + 1000
                if othernum < 1000:
                    msgbox("The wizard tricked you!He stole 100 Points!")
                    self.score = self.score - 100

        printNumObj(self.score)
コード例 #15
0
    def monitorEntregas(self):

        time0 = time.time()
        print 'Sistema de Monitoramente de Encomendas Iniciado'
        dados = self.versaiuentrega()
        if(dados[0] is not None):
            if(dados[0] == 'continue'):
                pass
            else:
                self.alarme()
                eg.msgbox('''Sua Encomenda saiu para entrega
(data - hora): %s ''' % dados[0])
                return

        while(1):
            if((time.time() - time0) >= self.deltat * 60):
                time0 = time.time()
                dados = self.versaiuentrega()
                if(dados[0] is not None):
                    if(dados[0] == 'continue'):
                        pass
                    else:
                        self.alarme()
                        eg.msgbox('''Sua Encomenda saiu para entrega
(data - hora): %s ''' % dados[0])
                        return
コード例 #16
0
ファイル: master.py プロジェクト: ThomasDoylend/PyCraft3
def runQuit(world):
    pygame.quit()
    thread_run=False
    world.save()
    easygui.msgbox(title = "Saved",msg = "Your world, \""+world.saveName+",\" has been saved.")
    logdata("PyCraft was closed.")
    quit()
コード例 #17
0
def handle_users(current_users):
	for user in current_users:
		print "Loading images for %s" % user.name

		# Check for out of swipes
		if user.name == 'Tinder Team':
			easygui.msgbox("Swipe limit reached.\nThe app will close.\nWait an hour and try again.")
			handle_app_quit()

		# Do GUI operations for main image
		user_class = AppUserControl(user)
		stack_background = stack_user_images(user_class)
		if stack_background is None:
			continue

		user_class.stacked_photos = stack_background
		return_operation = handle_gui_operations(user_class, stack_background)

		# GUI operations loop
		while return_operation is not None:
			return_operation = control_functions_dict[return_operation](user_class)

			# We are moving onto the next user
			if user_class.move_to_next_user:
				break

		# If user closes the window with the X button
		if return_operation is None:
			handle_app_quit()

	return
コード例 #18
0
ファイル: add.py プロジェクト: aquinoacordero/GYM
 def onButtonConfirm(self, *args):
     """metodo que nos lleva ingresar en la base de datos"""
     print ("Confirmar")
     act=str(self.actividad)
     actN=len(self.actividad)
     nom=self.nombre.get_text()
     ape=self.apellido.get_text()
     dni_=self.dni.get_text()
     ti=self.tiempo.get_text()
     ti_=int(ti)
     #calcula la cuota en base a unos parametros
     if(ti_<3):
         valBa=25
     else:
         valBa=20
     if(actN<3):
         actBa=1.2
     else:
         actBa=2.8
     cuot=valBa*actBa
     cuot_=str(cuot)
     print(nom,ape,dni_,ti,cuot_,act)
     #Llama a la base de datos pasando los parametros a ingresar
     if dni_=="" or nom=="" or ape=="":
         easygui.msgbox("Faltan datos", title="ERROR")
     else:
         BD.BD().insertar(nom,ape,dni_,cuot_,ti,act)
コード例 #19
0
ファイル: olebrowse.py プロジェクト: decalage2/oletools
def browse_stream (ole, stream):
    """
    Browse a stream (hex view or save to file)
    """
    #print 'stream:', stream
    while True:
        msg ='Select an action for the stream "%s", or press Esc to exit' % repr(stream)
        actions = [
            'Hex view',
##                'Text view',
##                'Repr view',
            'Save stream to file',
            '~ Back to main menu',
            ]
        action = easygui.choicebox(msg, title='olebrowse', choices=actions)
        if action is None or 'Back' in action:
            break
        elif action.startswith('Hex'):
            data = ole.openstream(stream).getvalue()
            ezhexviewer.hexview_data(data, msg='Stream: %s' % stream, title='olebrowse')
##            elif action.startswith('Text'):
##                data = ole.openstream(stream).getvalue()
##                easygui.codebox(title='Text view - %s' % stream, text=data)
##            elif action.startswith('Repr'):
##                data = ole.openstream(stream).getvalue()
##                easygui.codebox(title='Repr view - %s' % stream, text=repr(data))
        elif action.startswith('Save'):
            data = ole.openstream(stream).getvalue()
            fname = easygui.filesavebox(default='stream.bin')
            if fname is not None:
                f = open(fname, 'wb')
                f.write(data)
                f.close()
                easygui.msgbox('stream saved to file %s' % fname)
コード例 #20
0
 def execute(self):
     constants.redundancy_.master = True
     if szn.execute(self.szene_to_read):
         pass            
         #easygui.msgbox("Szene ausgeführt", title="Execute")
     else:
         easygui.msgbox("Szene wurde NICHT ausgeführt", title="Execute")
コード例 #21
0
ファイル: basicclient.py プロジェクト: asharahmed/W.I.L.L
 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()
コード例 #22
0
ファイル: room14.py プロジェクト: Forritarar-FS/Kastali
def suicide():
	mysteryinv.remove("gun")
	eg.msgbox("You ready the gun, put it up to your head and shoot.")
	sleep(1)
	eg.msgbox("You get a weird feeling as your body disintegrates and re-forms itself elsewere...")
	sleep(0.3)
	do()
コード例 #23
0
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()
コード例 #24
0
ファイル: tc.py プロジェクト: babhishek21/topcoder-tuts
def listTut():
  print ('''
    +++++++++++++++++++++++++++++++++++
    ++++++  Available Tutorials   +++++
    +++++++++++++++++++++++++++++++++++
    ''')

  # check for empty list
  if len(tutList) == 0:
    title = 'No tutorials found.'
    msg = 'No tutorials found. Did you fetch?\nTry fetching afresh.'
    print msg
    eg.msgbox(msg, title, image=imgErr)
    return

  # do the thing
  dispList = []
  print 'ID         Title'
  for idx, tut in enumerate(tutList):
    dispList.append( ' '.join( (str(x).rjust(2), tut.getInfo().encode('ascii', 'ignore')) ) )
    print dispList[-1]

  title = 'Available Tutorials'
  msg = 'This is the list of available tutorials.\n(Note the ID for custom downloads)'
  text = '\n'.join(dispList)
  eg.textbox(msg, title, text)
コード例 #25
0
ファイル: FBETLv2.2.py プロジェクト: yvonne0921/project
def main():
    #創建專案資料夾
    createProject()
    start = str(datetime.datetime.now())    
   
    #取得粉絲團連結
    f = open(disk_path + '/fanpages.txt','r')
    while(True):
        fanpage_link = f.readline().strip('\r\n').strip('\n')
        if fanpage_link == '':            
            break
        else:
            #取得粉絲團ID
            fbid = getFBid(fanpage_link)

            #設定連結
            res_url = baseurl + fbid + '?fields=id,posts{full_picture,message,likes{name},created_time,link}'
            comm_url = baseurl + fbid + '?fields=posts{full_picture,comments}'    
            data = url_res(res_url)
            comm_data = url_res(comm_url)

            while(True):
                #抓取圖片、PO文、回覆和PO文連結
                if 'data' in data.keys():
                    picture(data,fbid)
                    message(data,fbid)
                    link(data,fbid)
                    comments(comm_data,fbid)
                else:
                    print "fail to load data, excute picture again"
                    log=open(disk_path+'error.log',"a")
                    log.write(datetime.datetime.now())
                    log.write('loading'+fbid+'is error.\r\n')
                    log.close()
                    

                #判斷comments是否還有下一頁,有的話抓取下一頁連接 
                while(nextfrompage(comm_data)):
                    comm_next_url = nexturl(comm_data)
                    comm_data = url_res_noposts(comm_next_url)
                    comments(comm_data,fbid)                        

                #判斷message是否還有下一頁,有的話抓取下一頁連接
                if(nextfrompage(data)):             
                    normal_next_url = nexturl(data)
                    data = url_res_noposts(normal_next_url)
                else:
                    break

            #休息5秒
            time.sleep(5)

            #完成下載後,更改資料夾檔名
            os.rename(disk_path + '/pic/' + fbid + '(working)',disk_path + '/pic/' + fbid)
            os.rename(disk_path + '/message/' + fbid + '(working)',disk_path + '/message/' + fbid)
            os.rename(disk_path + '/comments/' + fbid + '(working)',disk_path + '/comments/' + fbid)
            os.rename(disk_path + '/link/' + fbid + '(working)',disk_path + '/link/' + fbid)
    
    f.close()
    easygui.msgbox('Starting : ' + start + '\nEnding : ' + str(datetime.datetime.now()), title='作業結束')
コード例 #26
0
ファイル: GAGv1.0.py プロジェクト: pythongratis/GridsAndGrime
def allvisited():
    global actedcount
    global visitcount
    if visitcount == 10 and actedcount == 1:
        #Exited the while loop - all rooms visited, all actions performed
        easygui.msgbox(open("\\gridsandgrime\\game\\texts\\end.txt").read(),title)
        quit()
コード例 #27
0
ファイル: Lab11.py プロジェクト: Jaren831/usafa
def exercise3():
    """Display file information until the user clicks Cancel."""
    # TODO 3b: Write code to use the file_info function as described in the lab document.
    file = easygui.fileopenbox( default="./data/*.txt")
    with open( file ) as data_file:
        count_file = file_info(data_file.read())
    easygui.msgbox( "{}". format( count_file ))
コード例 #28
0
ファイル: room14.py プロジェクト: Forritarar-FS/Kastali
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()
コード例 #29
0
def edit_monsters(m1, m2):
    while True:  # loop until Cancel or having valid values
        # easygui.multenterbox(text, titles, fieldls, values)
        values = easygui.multenterbox(
            "Please edit carefully", "edit monster stats", (
                "Monster1: name (text)", "Monster1: attack (float)",
                "Monster1: defense (float)", "Monster1: hitpoints (integer)",
                "Monster2: name (text)", "Monster2: attack (float)",
                "Monster2: defense (float)", "Monster2: hitpoints (integer)"
            ), (
                m1.name, m1.attack, m1.defense, m1.hitpoints, m2.name,
                m2.attack, m2.defense, m2.hitpoints
            )
        )
        if values == None or None in values:
            easygui.msgbox("nothing changed: empty value or Cancel")
            break  # break out of the  edit loop
        else:
            try:
                m1 = goblin.Monster(
                    values[0], float(values[1]), float(values[2]),
                    int(values[3])
                )
                m2 = goblin.Monster(
                    values[4], float(values[5]), float(values[6]),
                    int(values[7])
                )
            except:
                easygui.msgbox("Invalid value. Please try again")
                continue  # repeat editing
            break  # no problems detected:
    return m1, m2  # return the changed monster instances
コード例 #30
0
    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)
コード例 #31
0
import random
import easygui as g

g.msgbox("嗨,欢迎进入第一个界面小游戏^-^")
secret = random.randint(1, 10)

msg = '不妨猜一下小甲鱼现在心里想的是那个人数字'
title = '数字小游戏'
guess = g.integerbox(msg, title, lowerbound=1, upperbound=10)

while True:
    if guess == secret:
        g.msgbox("卧槽,你是小甲鱼心里的蛔虫吗?!")
        g.msgbox("嘿嘿,猜中了也没有奖励!!")
        break
    else:
        if guess > secret:
            g.msgbox("哥,大了大了~~~")
        else:
            g.msgbox("嘿,小了小了~~~")
        guess = g.integerbox(msg, title, lowerbound=1, upperbound=10)

g.msgbox("游戏结束,不玩了^-^")
コード例 #32
0
(odpName, odpSuffix) = odpFile.split(".")

## Find or create list of .png or .jpg files

odpFileSubdirectory = odpFileDirectory + os.sep + odpName
# Create a subdirectory for generated files (if needed)
ensure_dir(odpFileSubdirectory)

scriptAndImagesCreated = False
if sys.platform.startswith("win") and odpSuffix.startswith("ppt"):
    # create .jpg files
    slideNotes = []
    try:
        Application = win32com.client.Dispatch("PowerPoint.Application")
    except:
        easygui.msgbox("PowerPoint not available.")
        sys.exit()
    Application.Visible = True
    Presentation = Application.Presentations.Open(odpFilePath)
    onSlide = 0
    for Slide in Presentation.Slides:
        imageName = "Slide" + str(onSlide) + ".jpg"
        onSlide += 1
        Slide.Export(odpFileSubdirectory + os.sep + imageName, "JPG", 800, 600)

        for Shape in Slide.NotesPage.Shapes:
            if Shape.HasTextFrame:
                if Shape.TextFrame.HasText:
                    text = Shape.TextFrame.TextRange.Text
                    if not text.isdigit():
                        slideNotes.append(text)
コード例 #33
0
def game():
    g.msgbox("即将进入石头剪刀布游戏", title="石头剪刀布", ok_button="START", image='皮卡丘.png')
    choice = g.buttonbox("做出你的选择",
                         choices=('石头', '剪刀', '布'),
                         image='石头剪刀布.png')
    i = random.randint(1, 3)
    if str(choice) == aDict[i]:
        g.msgbox("你们打成了平手", title="结果", ok_button="确认", image='握手.png')
    if str(choice) == '石头':
        if aDict[i] == '剪刀':
            g.msgbox("对方出了剪刀,你赢了", title="结果", ok_button="确认", image='剪刀.png')
        if aDict[i] == '布':
            g.msgbox("对方出了布,你输了", title="结果", ok_button="确认", image='布.png')
    if str(choice) == '剪刀':
        if aDict[i] == '布':
            g.msgbox("对方出了布,你赢了", title="结果", ok_button="确认", image='布.png')
        if aDict[i] == '石头':
            g.msgbox("对方出了石头,你输了", title="结果", ok_button="确认", image='石头.png')
    if str(choice) == '布':
        if aDict[i] == '石头':
            g.msgbox("对方出了石头,你赢了", title="结果", ok_button="确认", image='石头.png')
        if aDict[i] == '剪刀':
            g.msgbox("对方出了剪刀,你输了", title="结果", ok_button="确认", image='剪刀.png')
コード例 #34
0
def cashuzi():
    g.msgbox('欢迎进入第一个小游戏')
    secret=random.randint(1,10)
    guess=g.integerbox(msg='请输入1-10的数字',title='猜数字小游戏',lowerbound=1,upperbound=10)
    while True:
        if guess==secret:
            g.msgbox('你是小甲鱼肚子里的蛔虫吗')
            g.msgbox('猜对了也没有奖励哦')
            break
        else:
            if guess>secret:
                g.msgbox('大了大了')
            else:
                g.msgbox('小了小了')
            guess = g.integerbox(msg='请输入1-10的数字', title='猜数字小游戏', lowerbound=1, upperbound=10)
    g.msgbox('游戏结束不玩了哦')
コード例 #35
0
def main_():
    COMMANDS = [
        "hash an file", "hash files from a directory",
        "hash all files and folders in a directory", "check a checksum file",
        "help", "exit"
    ]
    command = gui.choicebox("Select command:", "HASHIT", COMMANDS)

    if command == COMMANDS[0]:
        filename = gui.fileopenbox("Choose a file to hash", "HASHIT")
        hashres = hashFile(filename, new(selecthash()), False)
        file = writetofile()

        gui.msgbox(hashres, "HASHIT")

    elif command == COMMANDS[1]:
        my_path = gui.diropenbox("select directory:", "HASHIT")
        files = [
            my_path + "/" + f for f in os.listdir(my_path)
            if os.path.isfile(os.path.join(my_path, f))
        ]
        files_to_hash = gui.multchoicebox("Select files to hash:", "HASHIT",
                                          files)
        hasher = selecthash()
        HASHED = []

        for fname in files_to_hash:
            HASHED.append(
                str(hashFile(fname, new(hasher), False)) + " " + fname)

        file = writetofile()

        if file:
            open(file, "w").write("\n".join(HASHED))
        else:
            gui.msgbox('\n\n'.join(HASHED))

    elif command == COMMANDS[2]:
        my_path = gui.diropenbox("select directory:", "HASHIT")
        files = walk(my_path)
        hasher = selecthash()
        HASHED = []

        for fname in files:
            HASHED.append(
                str(hashFile(fname, new(hasher), False)) + " " + fname)
        file = writetofile()

        if file:
            open(file, "w").write("\n".join(HASHED))
        else:
            gui.msgbox('\n\n'.join(HASHED))

    elif command == COMMANDS[3]:
        file = readfromfile()
        hasher = new(selecthash())
        DONE = []

        for c in check_(file, hasher,
                        open(file, "r").readline(), False, False, False):

            if isinstance(c, str):
                gui.exceptionbox(
                    "An Error has occured:\n\n        {}".format(c), "HASHIT")
            else:
                if not c["hash_check"]:
                    DONE.append("{}: FAILED".format(c["filename"]))
                else:
                    DONE.append("{}: OK".format(c["filename"]))

        gui.msgbox('\n'.join(DONE))

    elif command == COMMANDS[4]:
        showhelp()

    elif command == COMMANDS[5]:
        exit()
コード例 #36
0
	#读取TXT中的数据,按行输出
	line = line[:-1]
	#删除换行符
	if vrf_module.match(line):
		sheet_vrf = newwb.get_sheet('vrf')
	else:
		break
	if vrf_rd
	sheet_vrf.wtite(a,b,line)

	a = a+1

'''

title = gui.msgbox(msg="已经完成配置文件读取,保存在output.xlsx!!!",
                   title="恭喜完成",
                   ok_button="好的",
                   image="finish.gif")
#msgbox(msg='(Your message goes here)', title=' ', ok_button='OK', image=None, root=None)
'''
#sheet.write(a,b,line)
#xlwt的行、列都是从0开始的


import easygui as g


if g.ccbox(msg = "是否继续输入实际接口物理状态?",choices = ("是的","不用了"),image = "haha2.gif"):
	g.msgbox(msg = "ok go on",image = "haha2.gif")
else:
	g.msgbox("ok qiut")
コード例 #37
0
#-*-coding:utf-8-*-

import random, easygui

secret = random.randint(1, 99)
guess = 0
tries = 0

easygui.msgbox('''哈哈...猜数字中文带窗口版本,来玩玩.从1到99.有6次机会.''')

while guess != secret and tries < 6:
    guess = easygui.integerbox('来,输入你觉得对的数字:')
    if not guess: break
    if guess < secret:
        easygui.msgbox(str(guess) + "你猜的数字小了,再来~")
    elif guess > secret:
        easygui.msgbox(str(guess) + "不,不,不...太大了")
    tries = tries + 1

if guess == secret:
    easygui.msgbox("恭喜你,猜对了,喜欢玩的话可以再运行一次,答案是不一样的哦~")
else:
    easygui.msgbox("噢,不好意思,6次机会已经用完了,再玩一次程序内部的数字将会改变,但你是可以无限次地运行我哦.")
コード例 #38
0
userlist = []
for item in folderlist:
    if len(os.path.splitext(item)[1]) == 0:
        userlist.append(item)

# Ask current user for their user name
UserName = easygui.choicebox(
    msg='Please select a user name, or click cancel to create a new user',
    choices=userlist)
if UserName is None:
    UserName = easygui.enterbox(
        msg=
        'Please enter a new username. This is used to identify where your data is stored.'
    )
    if UserName is None or UserName in userlist:
        easygui.msgbox(msg=str(UserName) + " is an invalid choice.")
        sys.exit()

# If folder does not have a folder, create it
if os.path.isdir("R:\\Autobots Roll Out\\%s" % UserName) == False:
    os.mkdir("R:\\Autobots Roll Out\\%s" % UserName)
    os.mkdir("R:\\Autobots Roll Out\\%s\\JSON_Files" % UserName)
    os.mkdir("R:\\Autobots Roll Out\\%s\\NewNexFiles" % UserName)
if not os.path.isdir("R:\\Autobots Roll Out\\" + UserName + '/Info_Files'):
    os.mkdir("R:\\Autobots Roll Out\\" + UserName + '/Info_Files')

# Determine which files have already been analyzed
os.chdir("R:\\Autobots Roll Out\\%s\\JSON_Files" %
         UserName)  # Change directory to folder containing all json files
Analyzedlist = os.listdir('./')  # Check for all folders in data folder
コード例 #39
0
import easygui

menu = ['create', 'show all', 'change', 'quit']

while 1:
    action = easygui.buttonbox(
        msg=
        "          ************ welcome to schedule management system ***************",
        title="schedule",
        choices=menu,
        default_choice=None,
        cancel_choice=None,
        callback=None,
        run=True)

    # 根据用户输入决定后续操作
    if action == 'create':
        tools.new_schedule()

    elif action == 'change':
        tools.search_schedule()

    elif action == 'show all':
        tools.show_schedule()

    elif action == "quit":
        easygui.msgbox("welcome to use schedule management system")
        break

    else:
        easygui.msgbox("please click again...")
コード例 #40
0
import pygame, easygui, sys
import constants
pygame.init()

try:
    centerFontObj = pygame.font.Font("resources/font.ttf", 32)
except pygame.error:
    easygui.msgbox("font.ttf doesn't exist.")
    pygame.quit()
    sys.exit()

fontObj = pygame.font.Font("resources/font.ttf", 16)


class centerText:
    def __init__(self, text):
        self.text = centerFontObj.render(text, True, constants.WHITE)
        self.rect = self.text.get_rect()
        self.rect.center = (constants.SCREEN_WIDTH / 2,
                            constants.SCREEN_HEIGHT / 2)

    def __str__(self):
        return self.text


class ScoreText:
    def __init__(self):
        self.text = fontObj.render("", True, constants.WHITE)
        self.rect = self.text.get_rect()
        self.rect.x = 0
        self.rect.y = 0
コード例 #41
0

def geturl(url):
    webpage = req.urlopen(url)
    data = webpage.read()
    data = data.decode('utf-8')
    return data


shuju = easygui.enterbox('请输入一个av或bv号')
if shuju[0] == 'b' or shuju[0] == 'B':
    info = 1
elif shuju[0] == 'a' or shuju[0] == 'A':
    info = 0
else:
    easygui.msgbox("数据错误!!!")
    exit()
curpath = os.path.dirname(os.path.realpath(__file__))
conf = configparser.RawConfigParser()
conf.read("config.ini")
ver = conf.get("ver", "version")
if info == 1:
    api = conf.get("api", "bvtoav").replace('%bv%', shuju).replace(
        '%nobvbv%', shuju[2:]).replace('%ver', ver)
else:
    api = conf.get("api", "avtobv").replace('%av%', shuju).replace(
        '%noavaid%', shuju[2:]).replace('%ver%', ver)
updata = conf.get("updata", "server").replace('%ver%', ver)
if geturl(updata) != 'SUCCESS':
    easygui.msgbox(geturl(updata))
    exit()
コード例 #42
0
ファイル: ezgui.py プロジェクト: efineberg19/Vehicle-Tracker
def main():
    easygui.msgbox(msg="Welcome to Vehicle Tracker!", title="Welcome!")
    run_app()
コード例 #43
0
            if start == '否':
                break


way = g.buttonbox(msg="Please choose the way to go in:",
                  choices=("register", "enter"))
if way == "enter":
    inputValues = g.multpasswordbox('please enter the password:', 'window',
                                    ["username", "password"])
    for a_user in users:
        if a_user["username"] == inputValues[0]:
            while (count < 5):
                if inputValues[0] == a_user["username"] and inputValues[
                        1] == a_user["password"]:
                    user = a_user
                    g.msgbox('Welcome to come back, ' + inputValues[0] + '.',
                             ok_button='Thank you!')
                    success()
                    break
                else:
                    count = count + 1
                    left_count = 5 - count
                    inputValues = g.multpasswordbox(
                        'The username or the password is wrong,you have ' +
                        str(left_count) +
                        ' time<s> left,please enter them again', 'window',
                        ["username", "password"])
            else:
                g.msgbox("Sorry,break.")
        else:
            g.msgbox('Your username is wrong,break.')
        break
コード例 #44
0
            else:

                search = browser.find_element_by_xpath(
                    '//input[@role="combobox"]')

                for i in range(0, 5):
                    search.send_keys(Keys.PAGE_DOWN)

                    small_wait()

                for i in range(0, 5):
                    search.send_keys(Keys.PAGE_UP)

                    small_wait()

                names, designations, links = get_data()

                count = finalizing_data(names, designations, links, count)

    remove_duplicates()

    finalize_image(Companies)

    total_employees()

    employees_companies()

    company_logos()

    easygui.msgbox("Data has been scraped successfully")
コード例 #45
0
def main(open_gui=None):
    # The skipinitialspace option eliminates leading
    # spaces and reduces blank cells to '' while the clean_spaces
    # function gets rid of trailing spaces.
    try:
        if open_gui == None:
            start_dir = '~/'
            if isdir(expanduser("~/Desktop")):
                start_dir = '~/Desktop/'
            msg = 'Please select the .csv file to be converted to .ics'
            open_gui = easygui.fileopenbox(msg=msg,
                                           title="",
                                           default=expanduser(start_dir),
                                           filetypes=["*.csv"])

        reader_builder = list(
            csv.DictReader(open(open_gui, 'Ub'), skipinitialspace=True))

    # For testing comment 4 lines above (2 x if / else) and use this:
    #        reader_builder = list(csv.DictReader(open('path_to_tester.csv', 'rb'), skipinitialspace = True))

    except:
        easygui.msgbox(
            'Looks like there was an error opening the file, didn\'t even make it to the conversion part. Sorry!'
        )
        sys.exit(1)

    # Filter out events with empty subjects, a required element
    # for a calendar event.
    # Code found here: http://bit.ly/Z4Pg4h
    reader_builder[:] = [d for d in reader_builder if d.get('Subject') != '']

    headers = reader_builder[0].keys()
    logger.debug('reader_builder[0].keys(): {}'.format(headers))
    check_headers(headers)

    reader = clean_spaces(reader_builder)

    # Start calendar file
    cal = Calendar()
    cal.add('prodid', 'n8henrie.com')
    cal.add('version', '2.0')

    # Write the clean list of dictionaries to events.
    rownum = 0
    try:
        for row in reader:
            event = Event()
            event.add('summary', row['Subject'])

            try:
                check_dates_and_times(start_date=row.get('Start Date'),
                                      start_time=row.get('Start Time'),
                                      end_date=row.get('End Date'),
                                      end_time=row.get('End Time'),
                                      all_day=row.get('All Day Event'),
                                      subject=row.get('Subject'))
            except DateTimeError as e:
                sys.exit(e)

        # If marked as an "all day event," ignore times.
        # If start and end date are the same
        # or if end date is blank default to a single 24-hour event.
            if row.get('All Day Event') != None and row['All Day Event'].lower(
            ) == 'true':

                # All-day events will not be marked as 'busy'
                event.add('transp', 'TRANSPARENT')

                event.add(
                    'dtstart',
                    datetime.strptime(row['Start Date'], '%m/%d/%Y').date())

                if row.get('End Date') in ['', None]:
                    event.add(
                        'dtend',
                        (datetime.strptime(row['Start Date'], '%m/%d/%Y') +
                         timedelta(days=1)).date())
                else:
                    event.add('dtend',
                              (datetime.strptime(row['End Date'], '%m/%d/%Y') +
                               timedelta(days=1)).date())

            # Continue processing events not marked as "all day" events.
            else:

                # Events with times should be 'busy' by default
                event.add('transp', 'OPAQUE')

                # Get rid of spaces
                # Note: Must have both start and end times if not all_day, already checked
                row['Start Time'] = row['Start Time'].replace(' ', '')
                row['End Time'] = row['End Time'].replace(' ', '')

                # Allow either 24 hour time or 12 hour + am/pm
                if row['Start Time'][-2:].lower() in ['am', 'pm']:
                    event.add(
                        'dtstart',
                        datetime.strptime(
                            row['Start Date'] + row['Start Time'],
                            '%m/%d/%Y%I:%M%p'))
                else:
                    event.add(
                        'dtstart',
                        datetime.strptime(
                            row['Start Date'] + row['Start Time'],
                            '%m/%d/%Y%H:%M'))

                # Allow blank end dates (assume same day)
                if row.get('End Date') in ['', None]:
                    row['End Date'] = row['Start Date']

                if row['End Time'][-2:].lower() in ['am', 'pm']:
                    event.add(
                        'dtend',
                        datetime.strptime(row['End Date'] + row['End Time'],
                                          '%m/%d/%Y%I:%M%p'))
                else:
                    event.add(
                        'dtend',
                        datetime.strptime(row['End Date'] + row['End Time'],
                                          '%m/%d/%Y%H:%M'))

            if row.get('Description'):
                event.add('description', row['Description'])
            if row.get('Location'):
                event.add('location', row['Location'])

            event.add('dtstamp',
                      datetime.replace(datetime.now(), tzinfo=LocalTimezone()))
            event['uid'] = str(randint(1, 10**30)) + datetime.now().strftime(
                '%Y%m%dT%H%M%S') + '___n8henrie.com'

            cal.add_component(event)
            rownum += 1

    except Exception, e:
        if rownum > 0:
            easygui.msgbox(
                'I had a problem with an event. I think I might have gotten through about {0} events and had trouble with an event with subject: {1}. Sorry!'
                .format(rownum, row['Subject']))
            logger.exception(e)
        elif rownum == 0:
            easygui.msgbox(
                'Looks like I didn\'t even get through the first event. Sorry!'
            )
            logger.exception(e)
        else:
            easygui.msgbox(
                'Somehow it looks like I processed negative events... that shouldn\'t have happened. Sorry!'
            )
            logger.exception(e)
        sys.exit(2)
コード例 #46
0
def guess_the_number():
    easygui.msgbox("你好,我是一个智能机器人!我有一个秘密,它是一个1至100的整数。我会给你5次机会,快来猜吧(还有小提示哦)!",
                   ok_button="开始游戏")
    while (1):
        secret = random.randint(0, 100)
        tries = 0
        user['playtimes'] = user['playtimes'] + 1
        while tries < 5:
            tries = tries + 1
            guess = easygui.integerbox("请输入你猜的数:",
                                       lowerbound=1,
                                       upperbound=100)
            if guess > secret:
                easygui.msgbox("这个数比" + str(guess) + "要小哦!")
            elif guess < secret:
                easygui.msgbox("这个数比" + str(guess) + "要大哦!")
            elif guess == secret:
                easygui.msgbox(
                    "你       猜       对       了\n你       猜       对       了\n你       猜       对       了\n你       猜       对       了"
                ),
                user['wintimes'] = user['wintimes'] + 1
                easygui.msgbox("用户" + str(user['username']) + "   游戏次数:" +
                               str(user['playtimes']) + "  获胜次数:" +
                               str(user['wintimes']),
                               ok_button="Let's go!!!")
                break
        else:
            easygui.msgbox("您的机会已用完,下次加油!   揭晓答案:" + str(secret))
            easygui.msgbox("用户" + str(user['username']) + "   游戏次数:" +
                           str(user['playtimes']) + "  获胜次数:" +
                           str(user['wintimes']),
                           ok_button="Let's go!!!")
            start = easygui.buttonbox("是否要再来一局?: ", choices=['是', '否'])
            if start == '否':
                save = json.dumps(user)
                fd = open("class.json", mode='w')
                fd.write(save)
                fd.close()
                break
コード例 #47
0
ファイル: cs1robots.py プロジェクト: lordpeara/hubo
    r = Robot("yellow")
    r.set_trace("blue")
    while True:
        try:
            e = _scene.wait()
            d = e.getDescription()
            if d == "canvas close":
                break
            if d == "keyboard":
                k = e.getKey()
                if k == "q":
                    _scene.close()
                    break
                elif k == " ":
                    try:
                        r.move()
                    except:
                        _easygui.msgbox("OUCH!")
                elif k == "t":
                    r.turn_left()
                elif k == "w":
                    load_world()
                elif k == "p":
                    r.pick_beeper()
                elif k == "d":
                    r.drop_beeper()
        except:
            _easygui.exceptionbox()

# --------------------------------------------------------------------
コード例 #48
0
def check_dates_and_times(start_date=None,
                          start_time=None,
                          end_date=None,
                          end_time=None,
                          all_day=None,
                          subject=None):
    '''Checks the dates and times to make sure everything is kosher.'''

    logger.debug('Date checker started.')

    # Gots to have a start date, no matter what.
    if start_date in ['', None]:
        logger.error('Missing a start date')
        easygui.msgbox(
            '''You're missing a start date. All events need start dates! '''
            '''The Subject for the event was: {}'''.format(subject))
        raise DateTimeError('Missing a start date')
        return False

    for date in [start_date, end_date]:
        if date not in ['', None]:
            try:
                datetime.strptime(date, '%m/%d/%Y')
            except:
                easygui.msgbox(
                    '''Problematic date found: {}\n'''
                    '''Make sure all dates are MM/DD/YYYY and try again.'''.
                    format(date))
                logger.error(
                    'Problem with date formatting. Date: {}'.format(date))
                raise DateTimeError('Something isn\'t right with the dates.')
                return False

    for time in [start_time, end_time]:
        if time not in ['', None]:
            try:
                time = time.replace(' ', '')
                if time[-2:].lower() in ['am', 'pm']:
                    datetime.strptime(time, '%I:%M%p')
                else:
                    datetime.strptime(time, '%H:%M')
            except:
                easygui.msgbox(
                    '''Problematic time found: {}\n'''
                    '''Make sure all times are HH:MM (either 24h or with am / pm) and try again.'''
                    .format(date))
                logger.error(
                    'Problem with time formatting. Time: {}'.format(time))
                raise DateTimeError('Something isn\'t right with the times.')
                return False

    if all_day == None or all_day.lower() != 'true':
        if not (start_time and end_time):
            easygui.msgbox(
                '''Missing a required time field in a non-all_day event on date: {}.\n'''
                '''Remember, if it's not an all_day event, you must have both start and end times!'''
                .format(date))
            logger.error(
                'Missing a required time field in a non-all_day event on date: {}.'
                .format(start_date))
            raise DateTimeError(
                'Missing a required time field in a non-all_day event.')
            return False

    logger.debug('Date checker ended.')
    return True
コード例 #49
0
# 图形用户界面GUI

# EasyGUI 官网:http://easygui.sourceforge.net
# 官方教学文档: - easygui-docs-0.96\tutorial\index.html
# 小甲鱼翻译改变的教学文档(1749426502登录查看):http://bbs.fishc.com/thread-46069-1-1.html

# 导包的三种方式:
# import mypackage          # 最普通的方式
# from mypackage import *   # 导入包中的所有函数,应用时不需要写较长的包名,但是可能会和其他包或者本地方法重名
# import mypackage as m     # 推荐导包方式,导入时将包名重命名

import easygui as g

g.msgbox('message')
コード例 #50
0
                                    filetypes=['*.ics']), 'wb')
        else:
            f = open(
                easygui.filesavebox(msg='Save .ics File',
                                    title='',
                                    default=expanduser('~/') + 'calendar.ics',
                                    filetypes=['*.ics']), 'wb')

    # For testing comment 4 lines above (2 x if / else) and use this:
    #    f = open('path_to_tester.csvcalendar.ics', 'wb')

        f.write(cal.to_ical())
        f.close()

    except Exception, e:
        easygui.msgbox(
            'Looks like the conversion went okay, but there was some kind of error writing the file. Sorry!'
        )
        logger.exception(e)
        sys.exit(3)


if __name__ == "__main__":
    try:
        if len(sys.argv) > 1:
            main(open_gui=sys.argv[1])
        else:
            main()
    except (HeadersError, DateTimeError) as e:
        sys.exit(e)
コード例 #51
0
while True:
    title = g.enterbox(msg="需要录制的软件名称,全屏录制请输入'然然'", title="小川来录屏")
    if title:
        if title == "然然":
            p = ImageGrab.grab()  #获得当前屏幕
            k = np.zeros((200, 200), np.uint8)
            a, b = p.size  #获得当前屏幕的大小
        else:
            try:
                hwnd = win32gui.FindWindow(None, title)
                rect = win32gui.GetWindowRect(hwnd)
                a = rect[2] - rect[0]
                b = rect[3] - rect[1]
                k = np.zeros((200, 200), np.uint8)
            except:
                g.msgbox(msg="没这个软件,别逗我")
                continue
        FileName = g.enterbox(msg="保存的文件名称", title="小川来录屏")
        while (not FileName):
            FileName = g.enterbox(msg="保存的文件名称", title="小川来录屏")
        fourcc = cv2.VideoWriter_fourcc(*'XVID')  #编码格式
        #输出文件帧率为16,可以自己设置
        video = cv2.VideoWriter(FileName + ".avi", fourcc, 16, (a, b))
        while True:
            im = ImageGrab.grab(rect)
            imm = cv2.cvtColor(np.array(im),
                               cv2.COLOR_RGB2BGR)  #转为opencv的BGR格式
            video.write(imm)
            cv2.imshow('imm', k)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
コード例 #52
0
ファイル: ice cream 2.py プロジェクト: lzan1/Hello_World
import easygui

flavor = easygui.choicebox("What is your favourite ice cream flavour?",
                           choices=['Vanilla', 'Chocolate', 'Strawberry'])
easygui.msgbox("You picked " + flavor)
コード例 #53
0
    except Exception:
        eg.msgbox("Error loading data file:"+filename)
    return elecOut
    
    
lastPacket={}
runDisplayThread=True
print("Brainkit 1.0 by Nathan Whitmore")
try:
    print("Checking for critical updates...")
    versionID=urllib2.urlopen("http://montageexplorer.appspot.com/brainkitversion").read()
    splitup=versionID.split("\n")
    if float(splitup[1]) > 1.0:
        print(splitup[2])
        eg.msgbox(splitup[2])
except Exception:
    print("Could not connect to server")
while True:
    choices=["(1) Create protocol manually","(2) Create protocol from experiment","(3) Run protocol","(4) Record data","(5) Run stimulator self tests"]
    userChoice=eg.choicebox("Welcome to BrainKit. Select an option to continue",title="BrainKit 1.0",choices=choices)
    if "1" in userChoice:
        createProtocol()
    if "2" in userChoice: #create protocol from experiment
        eFileName=eg.fileopenbox(title="Select the experiment file that you want to open")
        filepath=""
        splitup=eFileName.split("\\")
        for item in range(0,len(splitup)-1):
            filepath=filepath+splitup[item]+"\\"
        os.chdir(filepath) #set working directory so that we can load the data files
        eFile=open(eFileName,'r')
コード例 #54
0
    if keys[pygame.K_RIGHT] and (ship.get_x() < 700):
        ship.move_right(main_window)

    if keys[pygame.K_UP] and (ship.get_y() > 500):
        ship.move_up(main_window)

    if keys[pygame.K_DOWN] and (ship.get_y() < 570):
        ship.move_down(main_window)

    for i in range(50):
        inv[i].draw(main_window)
        inv[i].move_in_x(main_window, control_x)
        inv[i].move_in_y(main_window, control_y)

    if inv[0].get_x() < 100:
        control_x *= -1
        control_y = 40
    elif inv[49].get_x() > 700:
        control_x *= -1
        control_y = 40
    else:
        control_y = 0

    if inv[49].get_y() > 500:
        eg.msgbox(msg="Game Over", title="Game Over", ok_button="Aceptar")
        running_game = False

    ship.draw(main_window)
    pygame.display.update()

pygame.quit()
コード例 #55
0
import easygui as g
import sys

while 1:
    g.msgbox('Hello, world!')

    title = 'The most easy game in the world.'
    msg = 'What do you want now?'
    choices = ['Food', 'sleeping', 'Doing sport']

    choice = g.choicebox(msg, title, choices)
    g.msgbox('Your choice is :' + str(choice), 'result')

    msg = 'Do you want to restart the game?'
    title = 'Please make the choice.'
    if g.ccbox(msg, title):
        pass
    else:
        sys.exit(0)
コード例 #56
0
def getPhysData(filename, winLength,thresh,mode): #get neurophys measures from a file
    thefilter=firwin(251, 0.05, pass_zero=False,nyq=nyquist)
    closedset=[]
    openset=[]
    elecOut=[]
    try:
        print(filename)
        print(os.getcwd())
        theFile=open(filename,'r')
        fileLines=theFile.readlines()
        theFile.close()
        
        #step one:prprocessing and timing error correction
        lines=preprocess(fileLines)
        #step two:filter
        ave1=0
        ave2=0
        ave3=0
        ave4=0
        ave5=0
        ave6=0
        samples=0
        sticky=0;
        #raw_input()
        el1=[]
        el2=[]
        el3=[]
        el4=[]
        el5=[]
        el6=[]
        for line in lines:
            splitup=line.split("\t")
            average=(float(splitup[0])+float(splitup[1])+float(splitup[2])+float(splitup[3])+float(splitup[4])+float(splitup[5]))/6
            el1.append(float(splitup[0])-average)
            el2.append(float(splitup[1])-average)
            el3.append(float(splitup[2])-average)
            el4.append(float(splitup[3])-average)
            el5.append(float(splitup[4])-average)
            el6.append(float(splitup[5])-average)
        el1=lfilter(thefilter,1.0,el1).tolist()
        el2=lfilter(thefilter,1.0,el2).tolist()
        el3=lfilter(thefilter,1.0,el3).tolist()
        el4=lfilter(thefilter,1.0,el4).tolist()
        el5=lfilter(thefilter,1.0,el5).tolist()
        el6=lfilter(thefilter,1.0,el6).tolist()
        #step 3:epoch and reject bad epochs
        epochHolder=[]
        linenum=0
        numtaken=0
        while len(el1) > 0:
           # print(str(len(el1)))
            epoch=[]
            keepRunning=True
            while len(epoch) <  (winLength*10) and keepRunning:
                try:
                    line=lines[numtaken]
                    if  numtaken >=260:
                        epoch.append([el1.pop(0), el2.pop(0), el3.pop(0), el4.pop(0), el5.pop(0), el6.pop(0), int(line.split("\t")[6])])
                    else:
                        foo=([el1.pop(0), el2.pop(0), el3.pop(0), el4.pop(0), el5.pop(0), el6.pop(0), int(line.split("\t")[6])])
                    numtaken=numtaken+1
                except IndexError:
                    keepRunning=False
            keepEpoch=True
            for thing in epoch:
                startType=epoch[0][6]
                if (thing[6] != startType):
                    keepEpoch=False
            if keepEpoch or True:
                    epochHolder.append(epoch)
  
        #for epoch in epochHolder[5:]:
        print("*****")
        for epochnum in range(1,len(epochHolder)):
            epoch=epochHolder[epochnum];
            #raw_input()
            lastEpoch=epochHolder[epochnum-1];
            badEpoch=False
            for electrode in [0,1,2,3,4,5]:
                thistrode=[]
                for timepoint in lastEpoch:
                    thistrode.append(timepoint[electrode])
                ave=averageArray(thistrode)
                
                newtrode=[]
                for timepoint in epoch:
                    thistrode=timepoint[electrode]
                    if abs(thistrode-ave) > thresh:
                        badEpoch=True                
            #print(str(len(epoch[1])))
            if  not badEpoch:
                    closedset.append(epoch)
        for electrode in [0,1,2,3,4,5]:
                closedout=0
                closedlog=[]
                openout=0;
                conout=0
                
                for epoch in closedset:
                    ts=[]
                    for point in epoch:
                        ts.append(point[electrode])
                    ave=averageArray(ts)
                    newts=[]
                    
                    for point in ts:
                        newts.append(point-ave)
                    ts=newts
                    if "sessions" in mode:
                        closedout=closedout+qmean(ts)
                    else:
                        closedlog.append(qmean(ts))
                if "sessions" in mode:
                    closedout=closedout/len(closedset)
                    elecOut.append(closedout)
                else:
                    elecOut.append(closedlog)
                    

    except Exception:
        eg.msgbox("Error loading data file:"+filename)
    return elecOut
コード例 #57
0
# -*- coding: utf-8 -*-
"""
Created on Thu Mar  8 21:25:01 2018

@author: asus
"""

import easygui
name = easygui.enterbox("What's your name?")
addr = easygui.enterbox("Where are you from?")
code = easygui.enterbox("What is your postal code or zip code?")
whole_addr = name + "\n" + addr + "\n" + code
easygui.msgbox(whole_addr, "Here is your address:")
コード例 #58
0
ファイル: jsonGui.py プロジェクト: vothin/code
 def msgBox(self):
     g.msgbox(self.msg1, self.title, ok_button = "30¥")
コード例 #59
0
 def ready(self, place):
     return g.msgbox(msg='生成的文件将保存在' + str(place) + '文件中,现在开始吗',
                     title='Are you ready??!!',
                     ok_button='Ready Go...!!!')
コード例 #60
0
def gAs():
    ip = enterbox('请输入要查询地理位置的IP地址:\n目前仅支持IPv4!', '通过IP地址查询地理位置')
    if ip == None:
        return ip
    rt = getAdd(ip)
    return msgbox(rt, "通过IP地址查询地理位置", '好的')