コード例 #1
1
ファイル: nybblergui.py プロジェクト: 602p/nybbler
def main():
	series=None
	while series==None:
		series=easygui.fileopenbox("Select a series file", title, './en_US_1.py', [["*.py", "*.nybser", "Series File"]])

	action=None
	while action==None:
		action=easygui.boolbox("Select an Action", title, ("Compress", "Decompress"))

	f_in=None
	while f_in==None:
		f_in=easygui.fileopenbox("Select an input file", title, '*')

	f_out=None
	while f_out==None:
		f_out=easygui.filesavebox("Select a output file", title, '*')

	if action: #Decompress
		os.system("python nybblecli.py -qs "+series+" -d "+f_in+" "+f_out)
	else: #Compress
		os.system("python nybblecli.py -qs "+series+" -c "+f_in+" "+f_out)

	repeat=None
	while repeat==None:
		repeat=easygui.boolbox("Again?", title, ("Yes", "No"))

	if repeat: main()
コード例 #2
0
def download_name(mode):
    name = eg.enterbox(msg='输入歌曲名称')
    url_name = parse.quote(name)
    url_name = url_name.replace('%20', '+')
    url_json1 = 'https://songsearch.kugou.com/song_search_v2?callback=jQuery11240770641348037286_1566198223730' \
                '&keyword={}&page=1&pagesize=30&userid=-1&clientver=&platform=WebFilter&tag=em&filter=2&iscorrection' \
                '=1&privilege_filter=0&_=1566198223734'.format(url_name)
    page1 = requests.get(url=url_json1, headers=headers).text
    song_json = json.loads(page1[41:-2])
    i = 0
    song_list = []
    song_dict = {}
    for song in song_json['data']['lists']:
        file_name = song['FileName'].replace('<em>', '').replace('</em>', '')
        song_dict[file_name] = i
        song_list.append(file_name)
        i += 1
    i = int(song_dict[eg.choicebox(msg='请在以上结果中选择你要下载的歌曲', choices=song_list)])
    # i=int(input('请在以上结果中选择你要下载的歌曲(填数字编号)\n'))-1
    lyrics_mode = eg.boolbox('是否下载歌词?', choices=['是', '否'])
    if mode == 1:  # 流畅
        lyrics(download_hash(song_json['data']['lists'][i]['FileHash'], True),
               lyrics_mode)
    elif mode == 2:  # 高品
        lyrics(
            download_hash(song_json['data']['lists'][i]['HQFileHash'], True),
            lyrics_mode)
    elif mode == 3:  # 超高
        lyrics(
            download_hash(song_json['data']['lists'][i]['SQFileHash'], True),
            lyrics_mode)
    elif mode == 4:  # 无损
        lyrics(
            download_hash(song_json['data']['lists'][i]['ResFileHash'], True),
            lyrics_mode)
コード例 #3
0
ファイル: tyc.py プロジェクト: li19876/pythongit
def run(cookie):
    encoding = getencoding("公司名列表.txt")
    with open("公司名列表.txt", "r", encoding=encoding) as fp:
        gslist = [i.strip() for i in fp]
    print(gslist)
    while len(gslist) > 0:
        try:
            gs = gslist.pop(0)
            start = time.time()
            res = parsed(keyword=gs, cookie=cookie)
            if isinstance(res, int):
                while True:
                    boo = e.boolbox("请到天眼查输入验证码,验证完成后点击yes!")
                    if boo:
                        break
            savefile(res)
            end = time.time()
            print("用时:", end - start)
        except:
            with open("公司名列表.txt", "w", encoding=encoding) as fp:
                for s in gslist:
                    fp.write(s + "\n")
        finally:
            with open("公司名列表.txt", "w", encoding=encoding) as fp:
                for s in gslist:
                    fp.write(s + "\n")
コード例 #4
0
    def guessnum2(self):
        secret = random.randint(1, 9)
        times = 3

        num = easygui.integerbox("来猜猜小公主我现在心里想的是1-9里哪一个数字::",
                                 title="猜数字",
                                 lowerbound=1,
                                 upperbound=9)
        if num == secret:
            easygui.msgbox("你是小公主我肚子里的蛔虫吗??!!")
        else:
            while num != secret:
                times -= 1
                if num > secret:
                    easygui.msgbox("大了", title="游戏结果")
                elif num < secret:
                    easygui.msgbox("小了", title="游戏结果")
                if times > 0:
                    easygui.msgbox("总共 3 次机会,你还剩下 %d 次机会哦" % times)
                    num = easygui.integerbox("重新输吧:",
                                             title="猜数字",
                                             lowerbound=1,
                                             upperbound=9)
                else:
                    easygui.msgbox("次数用光了")
                    break
            else:
                easygui.msgbox("终于猜对了呀,哼,真是的,居然不是一次就中,你根本不爱我!")
        exitgame = easygui.boolbox("游戏结束辣", choices=["退出游戏", "再玩一次"])
        if exitgame:
            sys.exit(0)
        else:
            self.guessnum2()
コード例 #5
0
    def guessnum1(self):
        secret = random.randint(1, 9)
        times = 3

        num = easygui.integerbox("来猜猜小公主我现在心里想的是哪一个数字:",
                                 title="猜数字",
                                 lowerbound=1,
                                 upperbound=9)
        while (num != secret) and (times > 0):
            times -= 1
            if num == secret:
                easygui.msgbox("你是小公主我肚子里的蛔虫吗??!!")
                break
            elif num > secret:
                easygui.msgbox("大了", title="游戏结果")
            elif num < secret:
                easygui.msgbox("小了", title="游戏结果")
            if times > 0:
                num = easygui.integerbox("重新输吧:",
                                         title="猜数字",
                                         lowerbound=1,
                                         upperbound=9)
            else:
                easygui.msgbox("次数用光了")
        exitgame = easygui.boolbox("游戏结束", choices=["退出游戏", "取消"])
        if exitgame:
            sys.exit(0)
        else:
            pass
コード例 #6
0
ファイル: main.py プロジェクト: NikitaShymberg/RandomSeater
def main(args):
    families_csv_path, rows_csv_path = get_csv_paths(args)

    # Read csv files
    families = read_csv(families_csv_path, Family)
    families.sort(key=lambda f: f.size, reverse=True)
    hall = Hall(rows_csv_path)

    print('Found the following families:')
    print(*families, '\n', sep='\n')
    print(hall)

    # Seating loop
    families_are_sitting = False
    try_num = 0
    while not families_are_sitting:
        try_num += 1
        try:
            if sit_families(families, hall):
                families_are_sitting = True
        except HallFullException as e:
            print(e)
            hall.reset()
            if try_num % NUM_TRIES_BEFORE_WARN == 0 and args.use_gui:
                to_continue = easygui.boolbox(
                    msg=f'I wasn\'t able to find a suitable seating '
                    f'arangement in {try_num} tries. This is either '
                    'because I was unluck and I need to try a couple '
                    'more times, or no possible seating arangements exist.'
                    '\n\n Would you like to continue trying?')
                if not to_continue:
                    quit()

    output_path = get_output_path(args)
    hall.to_csv(output_path)
コード例 #7
0
ファイル: leveleditor.py プロジェクト: mcdenhoed/redo
 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]
コード例 #8
0
ファイル: app2.py プロジェクト: oledan/properties
def decide_offer():
  #Display the property which the user owns and existing offer on the property via inner join
  #Selecting the property that has an offer that is owned by current customer
  myQ = "SELECT a.address, b.decision, b.amtsold from properties a inner join offers b on a.property_id=b.property_id where b.cust_id =" + current_user.user_id()
  myD = db.get_from_db(myQ)
  decision = myD[0][1] #Get the decision of property from offers table

  if (decision >= 1):
    eg.msgbox(msg="No current offers.")

  elif (decision == 0):
    query = "SELECT a.property_type, a.address, a.MINprice, b.bid, b.amtsold, a.property_id FROM properties a inner join offers b on a.user="******"Property Type: " + str(property_type) + "\n" + "Address: " + str(address) + "\n" + "Minimum Price: " + str(minprice) + "\n" + "Bid: " + str(bid) + "\n" + "Maximum Bid: " + str(amtsold) + "\n"

    text = "Accept or Reject Existing Offer?"
    choices = ["Accept", "Reject"]
    reply=eg.boolbox(msg, title=text, choices=choices) #Boolbox returns 1 if the first button is chosen. Otherwise returns 0.

    #If offer is accepted
    if (reply == 1):
      eg.msgbox(msg="Offer Accepted")
      acceptoffer = "UPDATE offers set decision=1 where cust_id=" + current_user.user_id()
      db.add_to_db(acceptoffer)
    #If offer is rejected
    if (reply == 0):
      eg.msgbox(msg="Offer Rejected")
      rejectoffer = "UPDATE offers set decision=3 where cust_id=" + current_user.user_id()
      db.add_to_db(rejectoffer)
コード例 #9
0
ファイル: views.py プロジェクト: victorSerrano98/Proyecto
def modificar(request):
    usuario = request.user
    if usuario.has_perm('modelo.change_cliente'):
        dni = request.GET['cedula']
        cliente = Cliente.objects.get(cedula=dni)
        formulario = FormularioCliente(request.POST, instance=cliente)
        if request.method == 'POST':
            if formulario.is_valid():
                datos = formulario.cleaned_data
                cliente.cedula = datos.get('cedula')
                cliente.nombres = datos.get('nombres')
                cliente.apellidos = datos.get('apellidos')
                cliente.genero = datos.get('genero')
                cliente.estadoCivil = datos.get('estadoCivil')
                cliente.estado = True
                cliente.correo = datos.get('correo')
                cliente.telefono = datos.get('telefono')
                cliente.celular = datos.get('celular')
                cliente.direccion = datos.get('direccion')
                if boolbox(msg='Caja booleana',
                           title='Control: boolbox',
                           choices=('Si(1)', 'No(0)')):
                    cliente.save()
                    messages.warning(request, 'Guardado Exitosamente')
                return redirect(principal)
        else:
            formulario = FormularioCliente(instance=cliente)

        context = {
            'mensaje': 'Editar Cliente: ' + dni,
            'f': formulario,
        }
        return render(request, 'cliente/crear_cliente.html', context)
    else:
        return render(request, 'login/buscar.html')
コード例 #10
0
ファイル: views.py プロジェクト: victorSerrano98/Proyecto
def modificar(request):
    usuario = request.user
    if usuario.has_perm('modelo.change_cuenta'):
        dni = request.GET['numero']
        cuenta = Cuenta.objects.get(numero=dni)
        formulario = FormularioCuenta(request.POST, instance=cuenta)
        if request.method == 'POST':
            if formulario.is_valid():
                datos = formulario.cleaned_data
                cuenta.saldo = cuenta.saldo
                cuenta.cliente = datos.get('cliente')
                cuenta.tipo_Cuenta = datos.get('tipo_Cuenta')
                cuenta.save()
                messages.warning(request, 'Guardado Exitosamente')
                if boolbox(msg='Deser Modificar la cuenta: ' + dni,
                           title='Control: boolbox',
                           choices=('Si', 'No')):
                    cuenta.save()
                    messages.warning(request, 'Guardado Exitosamente')
                return redirect(principal)
        else:
            formulario = FormularioCuenta(instance=cuenta)

        context = {
            'title': "Modificar Cuenta: " + dni,
            'f': formulario,
        }
        return render(request, 'cliente/crear_cliente.html', context)
    else:
        messages.warning(request, 'No Permitido')
        return render(request, 'login/buscar.html')
コード例 #11
0
ファイル: interface.py プロジェクト: Trafire/fm_ecuador
def enter_mix_shipment():
    command = "scripts/enter_shipment_mix2.f2s"
    f2_system = "f2Canada"
    fields = ["date", "awb", "Shipment Code"]
    date, awb, shipment_code = get_info(fields)
    logistical_route = get_shipment()
    filename = easygui.fileopenbox(default='standings')
    invoice_num = easygui.enterbox("enter invoice num")
    f2_data = excel_to_dict.get_dict(filename)
    supplier = f2_data[0]["supplier"]

    commands = []
    commands.append((command, f2_system, date, awb, shipment_code,
                     logistical_route, supplier, invoice_num, f2_data))

    while easygui.boolbox("do you have additional invoices to enter?"):
        filename = easygui.fileopenbox(default='standings')
        invoice_num = easygui.enterbox("enter invoice num")
        f2_data = excel_to_dict.get_dict(filename)
        supplier = f2_data[0]["supplier"]
        commands.append((command, f2_system, date, awb, shipment_code,
                         logistical_route, supplier, invoice_num, f2_data))

    for c in commands:
        make_json.make_json(*c)
    print("enter_mix_shipment")
コード例 #12
0
def quit():
    judgment = easygui.boolbox("是否退出游戏?", "注意", ["确定退出", "算了,再玩会儿"])
    if judgment:
        pygame.quit()
        sys.exit()
    else:
        ...
コード例 #13
0
def welcome():
    f_content = ''

    b_ret = g.boolbox(msg='您是否要打开文本文件?', choices=('open', 'exit'))

    print(b_ret)
    if b_ret:
        f_path = get_file()
    print(f_path)
    if f_path is not '':
        f = open(f_path, 'r', encoding='utf-8')

        f_content = f.readlines()

        f.close()

        (file_dir, file_name) = os.path.split(f_path)

        new_content = g.textbox(title='显示文件内容',
                                msg='文件【%s】的内容如下:' % (file_name),
                                text=f_content)

        ret = content_compare(f_content, new_content)

        print(ret)

        if ret is not True:
            save_file(new_content, f_path)
コード例 #14
0
def download_list():
    with open('数据/歌单哈希值列表.txt', 'r') as f:
        song_hash_list = f.read().split()
    lyrics_mode = eg.boolbox(msg='是否需要一键下载全部歌词?', choices=['是', '否'])
    for i in song_hash_list:
        lyrics(download_hash(i, False), lyrics_mode)
        time.sleep(1)
コード例 #15
0
def warning():
    yujing = g.boolbox(msg='预警?',
                       title=' ',
                       choices=('修改预警值', '预警报告'),
                       image=None,
                       default_choice='Yes',
                       cancel_choice='No')
    if yujing == False:
        beijian = xlrd.open_workbook(workbook)
        table0 = beijian.sheet_by_name('data')
        nrows = table0.nrows
        mode = 0
        #历遍主数据,如果查到有一样的,mode取1,没查到取0,查到时记录行号i0
        list = []
        for i in range(nrows):
            #print (table.row_values(i)[0])
            if int(table0.row_values(i)[4]) < int(table0.row_values(i)[5]):

                list.append('\n' + table0.row_values(i)[0] + ' ' +
                            table0.row_values(i)[1] + ' 库位: ' +
                            table0.row_values(i)[2] + ' ' +
                            table0.row_values(i)[3] + '  库存:' +
                            str(int(table0.row_values(i)[4])) + ' 预警: ' +
                            str(int(table0.row_values(i)[5])) + ' ')

        S = ''
        for s in list:
            S = S + s + '\n'
        #print ('S is:',S)
        #g.msgbox(S,title='搜索结果')
        g.msgbox(S)

    else:
        wubian = g.enterbox("请输入精确物编:\n", title="盘点")
        beijian = xlrd.open_workbook(workbook)
        table0 = beijian.sheet_by_name('data')
        nrows = table0.nrows
        mode = 0
        #历遍主数据,如果查到有一样的,mode取1,没查到取0,查到时记录行号i0
        list = []
        for i in range(nrows):
            #print (table.row_values(i)[0])
            if wubian == table0.row_values(i)[0]:
                print(wubian)
                new_yujing = g.enterbox("请输入新预警值:\n",
                                        title=table0.row_values(i)[0],
                                        default=int(table0.row_values(i)[5]))
                if new_yujing == None:
                    menu()
                beijian1 = copy(beijian)

                beijian1.get_sheet('data').write(i, 5, int(new_yujing))
                try:
                    beijian1.save(workbook)
                    g.msgbox("修改成功")
                except:
                    g.msgbox("保存失败,有人已打开excel表 \n 请关闭beijian.xls,再试")

    menu()
コード例 #16
0
ファイル: cmdprox.py プロジェクト: peacedata0/proxmox-tools
def yn_choice(message, default='y', usegui=False):
    if usegui:
        return easygui.boolbox(message, __app__)
    else:
        choices = 'Y/n' if default.lower() in ('y', 'yes') else 'y/N'
        choice = input("%s (%s) " % (message, choices))
        values = ('y', 'yes', '') if default == 'y' else ('y', 'yes')
        return choice.strip().lower() in values
コード例 #17
0
ファイル: prox.py プロジェクト: FredHutch/IT
def yn_choice(message, default='y', usegui=False):
    if usegui:
        return easygui.boolbox(message, __app__)
    else:
        choices = 'Y/n' if default.lower() in ('y', 'yes') else 'y/N'
        choice = input("%s (%s) " % (message, choices))
        values = ('y', 'yes', '') if default == 'y' else ('y', 'yes')
        return choice.strip().lower() in values
コード例 #18
0
ファイル: queryMongo.py プロジェクト: CKRVV/SCSE19-0210
def askSelectOrType():
    msg = "Please choose to either do a selection or type the query.\nA selection will display available columns to query.\nA typed query supports logical operators."
    selectOrType = eg.boolbox(msg, title, [
        "Select", "Type"
    ])  #Prompts the user to choose Select or Type. A bool value is returned.
    if selectOrType is None:
        quit()
    return selectOrType
コード例 #19
0
	def analyze(self,igroup):
		# to get the sourcedata
		resultdatagrouped=self.gettmpdata('resultdatagrouped');
		
		spectra=resultdatagrouped[0]['datagroups'][igroup];
		spectranew=spectra.getemptyinstance();
		
		fig=XpyFigure();
#======================================================================
#         the real calculation
#======================================================================
		Tgroups=spectra.group(["Temperature"]);
		
		canceled=False;
		satisfied=False;
		pylab.hold(False);
		while not satisfied and not canceled:
			keys=Tgroups[0].keyssorted(["min(x)"]);
			j=0;
			for Tspectra in Tgroups:
				spect0=Tspectra[keys[0]];
				for i in range(1,len(keys)):
			#=======================================display:
					spect=Tspectra[keys[i]];
					spect0.plot('b');
					pylab.hold(True);pylab.grid(True);
					spect.plot('r');
					answer=easygui.boolbox("Choose the range for for merging","Individual merging",["OK","Cancel"]);
					if answer==1:
						A=pylab.axis();
						xmin=A[0];
						xmax=A[1];
				for Tspectra in Tgroups:
					spect0=Tspectra[keys[0]].copyxy();
					for i in range(1,len(keys)):
						spect=Tspectra[keys[i]];
						spect0.indmerge(spect,xmin,xmax);
						spect0.log({"Operation":"indmerge","xmin":xmin,"xmax":xmax});
					spectnew=spect0;
					
				spect0.plot('g');
			else:	
				canceled=True;
			if not canceled:
				answer=easygui.buttonbox("Satisfied?","Individual merging",["Yes","No","Cancel"]);
					#print "answer:",answer
				if answer=="Yes":
					satisfied=True;
				elif answer=="Cancel":
					canceled=True;
			if canceled:
				break;
					
		spectnew=spect0;	
		spectranew.insert(spectnew,keys[0]);
		spectra=resultdatagrouped[0]['datagroups'][igroup]=spectranew;
		#pylab.figure();
		spectranew.plot('o');
コード例 #20
0
ファイル: fetch.py プロジェクト: babhishek21/topcoder-tuts
def checkBackup(backupFilePath):
  if os.path.isfile(backupFilePath):
    print 'Found a backup. Continue with it? Or make new list?'
    msg = 'We found an old backup. Do you want to use it?\n(Otherwise a new list will be generated)'
    title = 'Backup found!'
    return eg.boolbox(msg, title, image=imgErr)
  else:
    print 'No backups found.'
    return False
コード例 #21
0
ファイル: main.py プロジェクト: willji0023/BioProject-2017
def gameover(self):
    keep_going = False
    while not keep_going:
        if easygui.boolbox("Restart?", " ", ["Heck yeah!", "How to Play??"]):
            keep_going = True
        else:
            easygui.msgbox(
                "To play, move left and right with the arrow keys. Press spacebar to become stationary, but eject a shield to block incoming acid rain, earning points each drop. Catch the mega-acid drop to earn even more points. Rain speed can possibly become stronger or weaker. You have 16 seconds. Good luck!"
            )
コード例 #22
0
 def on_closing(self):
     if not self.order.is_completed():
         if gui.boolbox(ms["on_close"], ms["exit"], [ms["yes"], ms["no"]]):
             self.workspace.restart()
             self.root.destroy()
             ngui.start()
     else:
         self.workspace.restart()
         self.root.destroy()
         ngui.start()
コード例 #23
0
def timer(minutes):
    time.sleep(minutes*60)
    winsound.Beep(frequency, duration)
    message = "Is it done"
    title = "Done?"
    while True:
        if boolbox(message, title, ["Yes", "No"]):
           return
        else:
            continue
コード例 #24
0
    def thread_process_finished(self):
        self.__update_log("\n---------\nProcessing finished")

        if self.errors:
            if easygui.boolbox("Error has occurred in the process\ncreate a log file?", title="Bilibili Video Changer"):
                with open("runtime_log.txt", "w") as log_file:
                    log_file.write(self.log)
                    log_file.close()
                easygui.msgbox("The runtime log has saved into file {}\\runtime_log.txt"
                               .format(os.path.dirname(__file__)))
コード例 #25
0
def admin_mode(msg, title):
    global guiset
    global done
    global endnow
    global kill
    admindone = False
    while not admindone:
        a = easygui.buttonbox(msg=msg, title=title, choices=['Users', 'Options', 'Exit'])
        if a == 'Options':
            dfile = open(savepath+"guiset.pkl", 'r')
            guiset = pickle.load(dfile)
            dfile.close()
            if guiset == True:
                currentguiset = 'on'
            elif guiset == False:
                currentguiset = 'off'
            a1 = choices('Please choose mode. EasyGui is currently %s.' %currentguiset, 'Mode', ['EasyGui ON', 'EasyGui OFF'])
            if a1 == 'EasyGui ON':
                guiset = True
            elif a1 == 'EasyGui OFF':
                guiset = False
            savegui = easygui.boolbox('Save EasyGui settings?', 'EasyGui Save')
            if savegui == 1:
                sfile = open(savepath+"guiset.pkl", 'w')
                pickle.dump(guiset, sfile)
                sfile.close()
            elif savegui == 0:
                pass
        elif a == 'Users':
            a1 = choices('Pick an option', 'User Menu', ['View Users', 'Create a User'])
            if a1 == 'View Users':
                password2 = easygui.passwordbox('Enter your admin password.', 'Password entry')
                if password2 == '171644':
                    userinfo1 = []
                    userinfo = ''
                    for i in range(user_num):
                        userfile = open(savepath+"users/%s.txt" % str(i+1), 'r')
                        userinfo1 = userinfo1 + userfile.readlines()
                        userinfo = userinfo + userinfo1[i+1]
                        userfile.close()
                    easygui.textbox('Here is information for all users.', 'User Info', userinfo)
                else:
                    easygui.msgbox('Your access to sensitive info has been denied.', 'ACCESS DENIED')
        elif a == 'Exit':
            exitchoice = choices('Choose your exit method', 'CHOOSE', ['Exit Admin', 'Exit Program', 'Back'])
            if exitchoice == 'Exit Admin':
                admindone = True
            elif exitchoice == 'Exit Program':
                admindone = True
                done = True
                endnow = True
                kill = True
            elif exitchoice == 'Back':
                pass
コード例 #26
0
def index_fasta(fasta_file):
    filePrefix = 'indexed_'
    fasta_filename = str(path_leaf(fasta_file))
    ##    if fasta_filename.split('_')[0]==filePrefix[:-1]:
    ##        fasta_filename=fasta_filename[len(filePrefix):]
    ##        existFile=True
    ##        print "new filename:", fasta_filename
    reIndex = False
    fas_input_path = ntpath.split(fasta_file)[0]
    if os.path.isfile(
            os.path.join(fas_input_path, (filePrefix + fasta_filename))):
        existFile = True
        indexYN = eg.boolbox(
            msg=
            '''%s file was already prepared for indexing, do you wish to rewrite the file?
        This might take a couple of minutes...''' % fasta_filename,
            title='File already indexed',
            choices=('Yes', 'No'))
        if indexYN:
            reIndex = True
        else:
            index_file = os.path.join(fas_input_path,
                                      (filePrefix + fasta_filename))
            reIndex = False
    else:
        ##        reIndex=True
        existFile = False
    if reIndex or not existFile:
        print 'Preparing file %s for indexing' % fasta_filename
        index_file = os.path.join(fas_input_path, filePrefix + fasta_filename)
        indexOutputHandler = open(index_file, 'w')
        myRe = r"(^>[^\r\s])+"
        mySub = r"\1"
        with open(fasta_file, "rU") as fileread:
            for line in fileread:

                Result = re.search(myRe, line)
                if Result:
                    #print Result.groups()
                    new_line = re.sub(myRe, mySub, line)
                else:
                    new_line = line
                #print new_line
                indexOutputHandler.write(new_line)
        indexOutputHandler.close()
    print 'Indexing file, please wait...'
    unigene_dict = SeqIO.index(index_file, "fasta")
    ##    for i,key in enumerate(unigene_dict.keys()):
    ##        if i<10:
    ##            print "Dict key:", key, "Dict Value:", unigene_dict[key]
    ##        else:
    ##            break
    return unigene_dict
コード例 #27
0
    def index(self):
        database = ''
        model = ''
        while 1:
            databasetype = (
                'xls',
                'xlsx',
            )
            modeltype = (
                'doc',
                'docx',
            )
            choose = g.buttonbox(msg='轻松Word',
                                 title='智能Word填写软件__ByNext',
                                 choices=('打开数据文件', '打开模板文件', '下一步', '退出'))
            if choose == '打开数据文件':
                database = self.choosedata()  #database 数据文件名称
                continue
            elif choose == '打开模板文件':
                model = self.choosemodel()  #mode 模板文件名称
                continue
            elif choose == '下一步':
                if database.endswith(databasetype) and model.endswith(
                        modeltype):
                    break
                elif not (database.endswith(databasetype)
                          or model.endswith(modeltype)):
                    c = g.boolbox(msg='数据和模板文件错误', choices=('Yes', 'No'))
                elif not database.endswith(databasetype):
                    c = g.boolbox(msg='数据文件错误', choices=('Yes', 'No'))
                elif not model.endswith(modeltype):
                    c = g.boolbox(msg='模板文件错误', choices=('Yes', 'No'))
                if c:
                    continue
                else:
                    return  ## 退出
            elif choose == '退出':
                return

        return database, model  # 放回2个值,分别是 数据文件名称、模板名称
コード例 #28
0
ファイル: Traverse.py プロジェクト: sc-dyer/G_FRAC
    def travClick(self, event):
        #When the plot is clicked, draw a vertical line where clicked and store that value as the new 0 for splitting the traverse
        #Will ask for confirmation before drawing and storing the location.
        #It can be changed as many times as desired
        self.splitLine.pop(0).remove()
        newZero = event.xdata
        self.travPlot.autoscale(False)
        self.splitLine = self.travPlot.plot([newZero, newZero], [-100, 100],
                                            color='black',
                                            linestyle='--')

        title = ""
        msg = "Split traverse at x = " + str(newZero) + "?"
        answer = easygui.boolbox(msg, title, ["Yes", "No"])
        #answer = input('Split traverse at x = ' + str(newZero) +'? (y/n)')
        if answer:
            msg = "Take the left or right side?"
            selLeft = easygui.boolbox(msg, title, ["Left", "Right"])
            self.selectedTrav = self.splitTrav(newZero, selLeft)
            plt.draw()
            print(
                "Done, you may now exit this plot or choose a different x location to split the traverse."
            )
コード例 #29
0
def levels():
    while True:
        eg.msgbox(msg='To win level 1, click the ok button!', \
                  title='1', ok_button='OK')
        if eg.boolbox(
                'To win level 2, click the button which says \
"kjbkbjgf".', '2', ['kjbkbjgf', 'kjdkbjgf']):
            print('gg')
            break
        else:
            print('how?')
            continue
    eg.msgbox(msg='now that you\'ve done the levels, \
you get free play mode!')
コード例 #30
0
def func_replace():
    if (inputtext.get() == ""):
        easygui.exceptionbox(msg="enter file name with its path",
                             title="WARNING")
        return

    e = easygui.enterbox(msg="enter value to be replaced",
                         title="replace text",
                         default="")
    e2 = easygui.enterbox(msg="replace previous value with",
                          title="replace with text",
                          default="")
    if (easygui.boolbox(msg="Are you  sure", title="confirm")):
        FileManupulation(inputtext.get()).replace_all(e, e2)
コード例 #31
0
 def makeword(self, name, title, lenth, info, filename, saveplace):
     w = win32com.client.Dispatch("Word.Application")
     w.Visible = True
     while 1:
         try:
             doc = w.Documents.Open(str(name))  # 载入模板
             break
         except:
             if g.boolbox(msg='模板文件错误,请重新选择!',
                          choices=('Yes', 'No,不选了,麻烦!')):
                 name = Func.index()[1]  # 重新调用index函数,重新选择
                 continue
             else:
                 return False
     w.Selection.Find.ClearFormatting()
     w.Selection.Find.Replacement.ClearFormatting()
     for i in range(1, lenth):
         OldStr = title[i]
         NewStr = info[i]
         w.Selection.Find.Execute(OldStr, False, False, False, False, False,
                                  True, 1, True, NewStr, 2)
     while 1:
         try:
             #if saveplace:
             doc.SaveAs(saveplace + info[filename] + '.doc')
             #else:
             #doc.SaveAs(saveplace+info[filename]+'.doc')
             break
         except:
             if g.boolbox(msg='文件名称含有特殊字符或其他错误,请重新选择文件名称',
                          choices=('Yes', 'No,不选了,麻烦!')):
                 filename = self.savename(title)
                 continue
             else:
                 break
     doc.Close()
     return True
コード例 #32
0
def download():
    # 选择模式
    mode_list = [
        '下载整个歌单', '根据歌曲名称下载', '根据哈希值下载', '导入文件批量下载', '转换utf-8为gbk', '更新cookies'
    ]
    mode = eg.choicebox(msg='请选择下载模式', title='选择模式', choices=mode_list)

    if mode == '下载整个歌单':
        url = easygui.enterbox('请输入分享歌单的链接(支持酷狗码和QQ空间分享)', '输入连接')
        if (type(eval(url)) == int):
            kugou_code(url)
        else:
            get_song_list(url)

        if eg.ynbox(msg='歌单获取完成,已保存在<歌单列表.txt>,是否一键下载?',
                    title='一键下载',
                    choices=['是', '否']):
            download_list()
    elif mode == '根据歌曲名称下载':
        quality_list = ['标准(大部分允许下载)', '高品(很少有允许下载)', '超高品(不允许)', '无损(不允许)']
        quality = eg.choicebox(choices=quality_list, msg='选择音质')
        quality_dict = {}
        num = 1
        for i in quality_list:
            quality_dict[i] = num
            num += 1
        download_name(quality_dict[quality])
    elif mode == '根据哈希值下载':
        lyrics(download_hash(eg.enterbox('请输入哈希值'), True),
               eg.boolbox('是否下载歌词?', choices=['是', '否']))
    elif mode == '导入文件批量下载':
        download_list()
    elif mode == '转换utf-8为gbk':
        utf8_to_gbk()
    elif mode == '更新cookies':
        with open('数据/cookies.txt', 'r') as f:
            cookies_old = f.read()
        cookies = eg.textbox(
            '输入cookies,可在浏览器酷狗音乐页面按f12寻找\n下面的是原来的cookies,请删除后更改', '更新cookies',
            cookies_old)
        if cookies:
            with open('数据/cookies.txt', 'w') as f:
                f.write(cookies)
    else_mode = eg.choicebox(msg='本次操作已完成,是否进行其他操作',
                             choices=['继续使用', '打开文件夹', '关闭程序'])
    if else_mode == '继续使用':  #循环调用
        download()
    elif else_mode == '打开文件夹':
        os.system("explorer 音乐\n")
コード例 #33
0
def main(open_path):
    """

    :param open_path:
    :return:
    """
    while True:
        answer = easygui.boolbox("Do you wish to train your model or find constants?",
                                 choices=["[T]rain", "[V]iew Constants"])
        if answer is None:
            return open_path
        elif answer:
            open_path = train_model(open_path)
        else:
            open_path = find_constants(open_path)
コード例 #34
0
ファイル: add_subtitles.py プロジェクト: AIstroemeria/test
def insertsub(*args):
    global flag
    if not flag:
        if g.boolbox('目标文件不存在,是否创建?', 'warning!'):
            os.mkdir(curchap.get())
            flag = 1
        else:
            return
    filepath = os.path.join(workpath, curchap.get())
    filepath = os.path.join(filepath, '%s.txt' % comboxlist1.get())
    with open(filepath, 'a') as f:
        tmp = textinsert.get(1.0, END)
        f.write(tmp.replace('\n', '') + '\n')
    textinsert.delete(1.0, END)
    change_curchap()
コード例 #35
0
	def setrange(self):
		igroup=self.gettmpdata('groupnum').get();
		database=self.gettmpdata('database');
		spectra=database[0]['resultdatatablegroups'][igroup];
		spectranew=spectra.getemptyinstance();
		spectra.plot();
		#print "spectranew type:",type(spectranew);
		
		answer=easygui.boolbox("Choose the range for group "+str(igroup),"picking spectra part",["OK","Cancel"]);
		if answer==1:
			A=pylab.axis();
			xmin=A[0];
			xmax=A[1];
			self['xminstr'].set(str(xmin));
			self['xmaxstr'].set(str(xmax));
コード例 #36
0
def instruction():
    a = "Welcome to Automated Mail Check!!\nLeave it to us to detect malicious mail and enjoy your mail worry free!!\n"
    b = "\n\nLicense Agreement Policy\n"
    c = "This software asks for your gmail username and password\n"
    d = "All passwords are stored locally and we are not responsible for any loss of data\n"
    e = "If you approve to this click Yes else click No\n"
    value = a + b + c + d + e
    if easygui.boolbox(msg=value,
                       title='License Agreement',
                       choices=('[<F1>]Yes', '[<F2>]No'),
                       image=None,
                       default_choice='[<F1>]Yes',
                       cancel_choice='[<F2>]No'):
        return
    else:
        exit(0)
コード例 #37
0
ファイル: views.py プロジェクト: victorSerrano98/Proyecto
def showDialog(request):
    usuario = request.user
    if usuario.has_perm('modelo.delete_cliente'):
        dni = request.GET['numero']
        cliente = Cuenta.objects.get(numero=dni)
        cliente.estado = False
        if boolbox(msg='¿Desea Eliminar la cuenta: ' + dni,
                   title='ELIMINAR',
                   choices=('Si', 'No')):
            cliente.save()
            messages.warning(request, 'Eliminado Exitosamente')
            return redirect(principal)
        else:
            return redirect(principal)
    else:
        return render(request, 'login/buscar.html')
コード例 #38
0
def index_fasta(fasta_file):
    filePrefix='indexed_'
    fasta_filename=str(path_leaf(fasta_file))
##    if fasta_filename.split('_')[0]==filePrefix[:-1]:
##        fasta_filename=fasta_filename[len(filePrefix):]
##        existFile=True
##        print "new filename:", fasta_filename
    reIndex=False
    fas_input_path=ntpath.split(fasta_file)[0]
    if os.path.isfile(os.path.join(fas_input_path,(filePrefix+fasta_filename))):
        existFile=True
        indexYN=eg.boolbox(msg='''%s file was already prepared for indexing, do you wish to rewrite the file?
        This might take a couple of minutes...''' % fasta_filename, title='File already indexed', choices=('Yes', 'No'))
        if indexYN:
            reIndex=True
        else:
            index_file=os.path.join(fas_input_path, (filePrefix+fasta_filename))
            reIndex=False
    else:
##        reIndex=True
        existFile=False
    if reIndex or not existFile:
        print 'Preparing file %s for indexing' % fasta_filename
        index_file=os.path.join(fas_input_path, filePrefix+fasta_filename)
        indexOutputHandler=open(index_file, 'w')
        myRe=r"(^>[^\r\s])+"
        mySub=r"\1"
        with open(fasta_file, "rU") as fileread:
            for line in fileread:

                Result=re.search(myRe,line)
                if Result:
                    #print Result.groups()
                    new_line=re.sub(myRe, mySub, line)
                else:
                    new_line=line
                #print new_line
                indexOutputHandler.write(new_line)
        indexOutputHandler.close()
    print 'Indexing file, please wait...'
    unigene_dict = SeqIO.index(index_file, "fasta")
##    for i,key in enumerate(unigene_dict.keys()):
##        if i<10:
##            print "Dict key:", key, "Dict Value:", unigene_dict[key]
##        else:
##            break
    return unigene_dict
コード例 #39
0
ファイル: gui.py プロジェクト: Sudoka/SWAG
def main():
  reply = eg.boolbox(msg='Hello, do you have a pre-computed classifier?', choices=('Yes', 'No'))
  if reply == 1:
    filename = eg.fileopenbox(msg='Please specificy cached classifier file ending in .clfr')
    model = utils.load_classifiers(filename)
    reply = eg.boolbox(msg='Now that we have specified our classifier, we must now specify data to be classified. Are you ready to proceed?', choices=('Yes', 'No'))
    if reply == 0:
      sys.exit()
    filename = eg.fileopenbox(msg='Please specify data to be classified.')
    D = utils.parse_data(filename)
    outfilename = ''.join(filename.split('.')[:-1]) + '.lbls'
    print 'Classifying data...'
    with open(outfilename, 'w') as f:
      for d in D:
        f.write(str(model.classify_vector(d)))
        f.write('\n')
    print 'Done!'

  else:
    filename = eg.fileopenbox(msg='Please specify training data for your classifier')
    D = utils.parse_data(filename)
    reply = eg.boolbox(msg='Would you like to engage in manual or automatic construction of your classifier?', choices=('Manual', 'Automatic'))
    #manual selection
    if reply == 1:
      algs = eg.multchoicebox(msg='Please choose at least one algorithm:', choices=('k-Nearest Neighbors', 'Support Vector Machine', 'Naive Bayes'))
      alg_params = {alg : 'auto' for alg in algs}
      #storage for set of classifiers
      C = []
      for alg in algs:
        reply = eg.boolbox(msg='Would you like to engage in manual or automatic parameter tuning for your ' + alg + ' algorithm?', choices=('Manual', 'Automatic'))
        if reply == 1:
          if alg[0] == 'k':
            params = eg.multenterbox(msg='Please select the following parameters for your ' + alg + ' algorithm:', fields=('k'), values=['1'])
            print 'Building ' + alg + ' classifier...'
            C.append(cl.kNN(D, k=int(params[0])))
            print 'Done!\n'
          if alg[0] == 'S':
            reply = eg.boolbox(msg='What type of kernel would you like to use for your Support Vector Machine?', choices=('Radial Basis Function', 'Linear'))
            if reply == 1:
              params = eg.multenterbox(msg='Please select the following parameters for your RBF Support Vector Machine:', fields=('margin', 'gamma'), values=['1.0', '1.0'])
              print 'Building ' + alg + ' classifier...'
              C.append(cl.SVM(D, kernel_type='RBF', margin=float(params[0]), gamma=float(params[1])))
              print 'Done!\n'
            else:
              params = eg.enterbox(msg='Please select the margin parameter for your Linear Support Vector Machine:', default='1.0')
              print 'Building ' + alg + ' classifier...'
              C.append(cl.SVM(D, kernel_type='Linear', margin=float(params[0])))
              print 'Done!\n'
          if alg[0] == 'N':
            params = eg.enterbox(msg='Please select the binning threshold parameter for your Naive Bayes algorithm:', default='.01')
            print 'Building ' + alg + ' classifier...'
            C.append(cl.NB(D))
            print 'Done!\n'
            
        else:
          if alg[0] == 'k':
            print 'Building ' + alg + ' classifier...'
            C.append(cl.kNN(D))
            print 'Done!\n'
          if alg[0] == 'S':
            print 'Building ' + alg + ' classifier...'
            C.append(cl.SVM(D))
            print 'Done!\n'
          if alg[0] == 'N':
            print 'Building ' + alg + ' classifier...'
            C.append(cl.NB(D))
            print 'Done!\n'

      model = mcl.AdaBoost(C)

    #automatic selection
    else:
      print 'Constructing classifiers...'
      model = mcl.AdaBoost([cl.kNN(D), cl.SVM(D), cl.NB(D)])
      print 'Done!\n'

    reply = eg.boolbox(msg='Now that we have specified our classifier, we must now specify data to be classified. Are you ready to proceed?', choices=('Yes', 'No'))
    if reply == 0:
      sys.exit()
    filename = eg.fileopenbox(msg='Please specify data to be classified.')
    D = utils.parse_data(filename)
    outfilename = ''.join(filename.split('.')[:-1])
    print 'Classifying data...'
    with open(outfilename + '.lbls', 'w') as f:
      for d in D:
        f.write(str(model.classify_vector(d)))
        f.write('\n')
    print 'Done!'
    #cache our classifier
    utils.store_classifiers(outfilename + '.clfr', model)
    #give user some information on classifiers used
    open(outfilename + '.info', 'w').write(model.get_info())
コード例 #40
0
def selSwiftFolderDownload(options,swifttenant):
    choice=''
    oldchoice=''
    container=''
    prefix=''
    level=0
    myoptions={'prefix': None}
    with SwiftService(options=options) as swift:
        
        while not choice.startswith('------------ DOWNLOAD FOLDER'):            
            visible_folders = []         
            if choice.startswith("------------ GO UP ONE LEVEL"):
                level-=1
                if not '/' in oldchoice:
                    choice = ''
                    container = ''
                    myoptions={'prefix': None}
                else:
                    choice=os.path.dirname(oldchoice.rstrip("/"))+'/'
                    if choice == '/':
                        choice=container
                        container=''
                                 
            if choice != '':
                level+=1
                if container == '':
                    container=choice
                    myoptions={'prefix': None, 'delimiter': '/'}
                else:
                    prefix=choice
                    myoptions={'prefix': prefix, 'delimiter': '/'}
                            
                visible_folders.append("------------ DOWNLOAD FOLDER '%s/%s' NOW-----------" % (container, prefix))
                visible_folders.append("------------ GO UP ONE LEVEL -----------")

            listing=swift.list(container=container, options=myoptions)
            
            for o in listing:
                for i in o['listing']:
                    cnt=0
                    if 'subdir' in i:
                        visible_folders.append(i['subdir'])
                        cnt+=1
                    elif not i['name'].startswith('.') and container=='':
                        visible_folders.append(i['name'])
                        cnt+=1
            if cnt == 0:
                if easygui.boolbox('Do you want to download /%s/%s now?' % (container,prefix), "Downloading stuff", ["    Yes    ","   No   "]):
                    return container, prefix
                else:
                    oldchoice=choice
                    choice="------------ GO UP ONE LEVEL"
                    continue
            msg="Please select a sub folder for download or download the current folder '%s/%s'" % (container,prefix)
            oldchoice=choice
            choice = easygui.choicebox(msg,"Select Folder/Container for data transfer",visible_folders)
            if not choice:
                return None, ""
        if level<=1:
            prefix=''
        elif level>1:
            prefix=oldchoice  
    return container, prefix
コード例 #41
0
def process(PA):
	global ActiveWindow, Shapes, Word, TRs_all, xl, Visio
	global RESULTS
	try:

		# ouvrir le fichier excel et faire les initialisations de coutume
		xl = CreateObject("Excel.application")
		xl.Visible = False
		xl.DisplayAlerts = False
		wb = xl.Workbooks.Open(PA)
		wb.Sheets("synoptique-bilan µmodules").Select()

		# dans la sheet visée, détecter tout les objets OLE (qui seront 
		# normalement tous des déssins visio)
		OLEObjects = wb.Sheets("synoptique-bilan µmodules").OLEObjects()

		# pour chaque déssin ...
		for OLEObject in OLEObjects:
			# l'ouvrir dans Visio
			OLEObject.Verb(2)
			# prendre la main sur la fenêtre visio ouverte
			Visio = GetActiveObject("Visio.Application")
			# Visio.Visible = False
			Visio.DisplayAlerts = False
			ActiveWindow =  Visio.ActiveWindow
			Page = ActiveWindow.Page
			Shapes = Page.Shapes

			msg = "Voulez confirmer le nombre de PBs après chaque sélection?\n" \
						+ "(si c'est plan assez complexe mieux vaut répondre par oui)"
			yn = ynbox(msg)

			# allons-y!
			# On extrait d'abord les infos d'entête
			for shape in Shapes:
				text = shape.Text
				if text.startswith('NRO'):
					bloc_NRO = text
				elif text.startswith('PT'):
					try:
						blocs_PT.append(shape)
					except:
						blocs_PT = [shape]
				elif text.startswith('PA'):
					PA_posx = get_XY(shape)[0]
			if get_XY(blocs_PT[0])[0] > get_XY(blocs_PT[1])[0]:
				FI_bloc = blocs_PT[0]
				PA_bloc = blocs_PT[1]
			else:
				PA_bloc = blocs_PT[1]
				FI_bloc = blocs_PT[0]
			PA_PT = PA_bloc.Text.rsplit('\n')[0].replace('PT: ', '')
			PMZ_PT = FI_bloc.Text.rsplit('\n')[0].replace('PT: ', '')
			CH = PA_bloc.Text.rsplit('\n')[2].replace('CH: ', '')
			NRO = extract('NRO/PMZ/PA', bloc_NRO, 'NRO')
			ADRESSE1 = ' '.join(PA_bloc.Text.rsplit('\n')[3:5])\
									.replace('Adresse: ', '')
			ADRESSE2 = ADRESSE1.rsplit('-')[0]

			TRs = {}
			empty_TRs = []
			# là ça va barder!
			for shape in Shapes:
				if shape.Text.startswith('TR'):
					if get_XY(shape)[0] > PA_posx:
						TR_TXT = str(shape.Text.encode()).replace("b'", '').replace("'", '')
						TR = TR_TXT.rsplit('FO')[0] \
							.replace('\\n', ' ') + 'FO'
						if not re.match(r'TR\s+\d{2}\s+\d{4}\s+\d+FO', TR):
							empty_TRs.append(shape.ID)
							continue
						if TR not in TRs:
							TRs[TR] = {
								'LONG': 0,
								'SHAPES': [shape.ID],
								'CH/IMB/AP': [],
								'PTs': [],
								'maxPT': 0
								}
						else:
							TRs[TR]['SHAPES'].append(shape.ID)
						try:
							TR_LONG = int(TR_TXT.rsplit('\\xe2\\x80\\x93 ')[1] \
															.replace('m', ''))
						except:
							TR_LONG = 0
						TRs[TR]['LONG'] = TRs[TR]['LONG'] + TR_LONG
			
			title1 = 'Sélectionnez les bloc'
			title2 = 'Confirmez la sélection'
			for TR in TRs:
				while True:
					SelectShapes(TRs[TR]['SHAPES'])
					if ccbox(TR, title1):
						CH_OR_IMB_OR_AP_all = []
						PTs = []
						msg = "Pour " + TR + "\nVous avez sélectionné:\n"
						selected_PBs = 0
						yn_yes = True
						for selected in ActiveWindow.Selection:
							try:
								TEXT = str(selected.Text)
								if not TEXT.startswith('PB'):
									continue
								selected_PBs = selected_PBs + 1
								PT = TEXT.rsplit('\n')[2]
								ADR = TEXT.rsplit('\n')[3]
								CH_OR_IMB_OR_AP = TEXT.rsplit('\n')[4]
								if (not CH_OR_IMB_OR_AP.startswith('AP ')
										and not CH_OR_IMB_OR_AP.startswith('Ch.')
										and not CH_OR_IMB_OR_AP.startswith('IMB')):
									SelectShapes([selected.ID])
									msgbox("T'as surement encore fais une connerie dans tes"
												+ "déssins, regarde ce bloc dans la ligne PT!\n"
												+ "Je devrais trouver Ch.XXXX ou AP XXXX"
												+ "ou IMB/XXXX/XXX mais j'ai trouvé\n"
												+ CH_OR_IMB_OR_AP + "\n"
												+ "Quand t'auras détécté l'erreur click sur OK")
									cont = boolbox("Dois-je continuer ou fermer?",
																"Que faire?",
																['Continuer?', 'Fermer?'])
									if not cont:
										exit(0)
									else:
										pass
								else:
									msg = msg + "- " + CH_OR_IMB_OR_AP + "\n"
									CH_OR_IMB_OR_AP_all.append([ADR, CH_OR_IMB_OR_AP])
									PTs.append(int(PT.replace('PT', '')))
							except:
								SelectShapes([selected.ID])
								msgbox("T'as surement encore fais une connerie dans tes"
									+ "déssins, regarde ce bloc dans la ligne PT!\n"
									+ "Quand t'auras détécté l'erreur click sur OK")
								cont = boolbox("Dois-je continuer ou fermer?",
																"Que faire?",
																['Continuer?', 'Fermer?'])
								if not cont:
									exit(0)
								else:
									msg = msg + "(RIEN!)"
									CH_OR_IMB_OR_AP_all = []
									PTs = []
									yn_yes = False
						if not selected_PBs:
							cont = boolbox("Tu n'as rien sélectionné! Tu confirmes"
															+ " que ce n'est pas une connerie?",
															"Sélection vide!",
															['Oui vas-y', 'Comme d\'hab! Une connerie'])
							if cont:
								break
							else:
								continue
						if yn and yn_yes:
							msg = msg + "(" + str(selected_PBs) + " sélectionnés)"
							conf = boolbox(msg, title2, ['Confirmer?', 'Refaire?'])
							if conf:
								TRs[TR]['CH/IMB/AP'] = CH_OR_IMB_OR_AP_all
								TRs[TR]['PTs'] = PTs
								break
							else:
								pass
						else:
							TRs[TR]['CH/IMB/AP'] = CH_OR_IMB_OR_AP_all
							TRs[TR]['PTs'] = PTs
							break
					else:
						exit(0)
				if len(TRs[TR]['PTs']):
					TRs[TR]['maxPT'] = 'DE_PT%06d' % max(TRs[TR]['PTs']) + '.doc'
				else:
					TRs[TR]['maxPT'] = 'je_ne_suis_pas_cense_exister.doc'
			if TRs == {}:
				msgbox("il n'y pas de TR valide sur ce déssin")
			TRs_all.append(TRs)
			Visio.Visible = False

		RESULTS[PA] = {
			'TRs_all': 	TRs_all,
			'NRO':			NRO,
			'PMZ_PT':		PMZ_PT,
			'PA_PT':		PA_PT,
			'CH':				CH,
			'ADRESSE1':	ADRESSE1,
			'ADRESSE2':	ADRESSE2,
			'DATE':			DATE
		}
		xl.Quit()
		return

	except:
		print(format_exc())
		codebox("t'as encore fais une connerie! Fais moi un screen de malheur!",
						"Erreur",
						format_exc())
		going()
コード例 #42
0
__models_folder__ = abtronics.__models_folder__
__model_name__ = 'model_DE_PTXXXXXX.doc'
__model_path__ = __models_folder__ + sep + __model_name__
__jobs_folder__ = abtronics.__jobs_folder__
__JOB_ID__ = abtronics.__JOB_ID__
__JOB_PATH__ = __jobs_folder__ + sep + __JOB_ID__ + sep
__DEs_PATH__ = __JOB_PATH__ + 'DEs' + sep
mkdir(__JOB_PATH__)
mkdir(__DEs_PATH__)


all_files = []
while True:
	all_files = all_files + fileopenbox("Séléctionnez les fiches PA à traiter", "Abtronics", filetypes= "*.xls", multiple=True)
	cont = boolbox("Séléctionner d'autres?", ['Oui', 'Non, c\'est tout'])
	if cont:
		pass
	else:
		break

for file in all_files:
	filename = ntpath.basename(file)
	copyFile(file, __JOB_PATH__ + filename)


__RG = {
	'NRO/PMZ/PA': r'NRO\s(?P<NRO>[A-Z]+)\s-\sPMZ\s(?P<PMZ>[0-9]+)\s-\sPA\s(?P<PA>[0-9]+)'
}

"""
コード例 #43
0
ファイル: NewUserNotify.py プロジェクト: FredHutch/IT
def setup():
    
    msg = ("Welcome to the new employee notification tool.\n"
           "The tool allows you to send customized automated emails "
           "that contain information about all ActiveDirectory users "
           "created within the last 24h.\n"
           "You will be asked several questions and config filters. "
           "Searches may take a few seconds to complete.\n"
           )
    msg2 = ("\nPlease create a new filter or load an existing filter "
            "which you can then modify."
            )
    cfgs = os.listdir(cfgdir)
    if len(cfgs)==0:
        msg2 = ''
        easygui.msgbox(msg,__app__)
        pick='New Config'
    else:        
        pick = easygui.buttonbox(msg+msg2, __app__, ['New Config','Load Existing',
                                                     'Cancel'])
    if pick == 'Cancel':
        return False
    
    if pick != 'New Config':
        config = easygui.choicebox("Select an existing config:",__app__,cfgs)
        if not config:
            return False
        cfg = Settings(os.path.join(cfgdir,config))
        cfg.restore
    else:
        config=''
        while config == '':
            config = easygui.enterbox('Saving this filter. Please enter a name for this notification.', __app__)
            if not config:
                sys.exit()
        config=config.replace(' ','_')
        if not config.endswith('.txt'):
            config=config+'.txt'            
        cfg = Settings(os.path.join(cfgdir,config))
        cfg.store()    # persist the settings
        
        msg = ("Please select employee information you would like to filter.\n"
               "For example if you want to know about new staff in specific departments "
               "please pick 'Departments'. If you want to know about new users "
               "reporting to specific managers please pick 'Managers'. "
               "If you'd like to check for new users in specific Divisions and optionally "
               "filter by certain job titles please pick 'Divisions/Jobtitles'"
               )
        choi = [ "Departments", "Managers", "Divisions/Jobtitles" ]
        choival = [ "department", "manager", "division" ]

        pick = easygui.buttonbox(msg, __app__, choi)
        if not pick:
            return False
        idx = choi.index(pick)
        
        cfg.filter1=getUserAttrList (choival[idx])
        cfg.filter1_attr=choival[idx]

    cfg.filter1=easygui.multchoicebox(msg,"Select values from %s" % pick,cfg.filter1)
    if cfg.filter1_attr == 'division':
        alist=getUserAttrList ('title')
        filter2_attr='title'
        filter2=easygui.multchoicebox(msg,"Select values from 'Jobtitile'",alist)
    else:
        cfg.filter2_attr=''
        cfg.filter2=''

    msg = ("Please enter one or multiple email addresses (separated by comma) "
           "to which you want to send a notification when new users arrive"
           )
    cfg.to = easygui.enterbox(msg, __app__,cfg.to)


    msg = ("Please enter the email body you want to use for your notification "
           "email. A list of new users will be added below this text."
           )
    cfg.mailbody = easygui.textbox(msg, __app__, cfg.mailbody, codebox=False)

    msg = ("Optional: Please enter the command line of a script including full path "
           "and command options. This script will be executed when new users arrive.\n"
           "(Please leave this line empty to not execute anything.)"
           )
    cfg.run = easygui.enterbox(msg, __app__,cfg.run)
    
    cfg.store()    # persist the settings

    
    testdate=''
    out=''
    while True:
        if easygui.boolbox('Do you want to test this configuration (again) ?', __app__, ('Yes', 'No')):
            msg = ("If you want to test this config, please enter the creation date "
                         "(format: YYYYMMDD) you would like to test."
                        )
            testdate = easygui.enterbox(msg, __app__,testdate)
            if not testdate:
                break
            if testdate != '':
                exe=getMyFile()
                try:
                    out=subprocess.check_output(
                        '"%s" --debug --search-date %s %s' % (exe,testdate,config),
                        stderr=subprocess.STDOUT,
                        shell=True)
                except :
                    print "likely subproces CalledProcessError.output "
                easygui.codebox('Please see debugging output below:', __app__, out)
        else:
            break

    cmdline = '%s %s' % (getMyFile(),config)
    easygui.codebox('Please activate this command via cron:' , __app__,cmdline)
コード例 #44
0
#Syntax to pass to the mid2cnc script: params = '-outfile ./mytest.gcode'
# os.system ('python -i mid2cnc.py ' + params)

import os
import easygui as eg
params = '' #initializing variable

machinelist = ('ultimaker', 'cupcake', 'thingomatic', 'shapercube', 'custom')
machine = eg.choicebox(msg='Machine type', title='Pick machine', choices=machinelist)
print machine

params = params + '-machine ' + machine

infile = eg.fileopenbox(msg='Choose the midi file ', title=' Grab the file you want to convert', default=os.path.expanduser("~")+"//My Documents/", filetypes = "*.mid") # the "default=os.path.expanduser("~")" gets your home forlder so you don't have top start browsing from some obscure python install folder
print infile
params = params + ' -infile ' + infile

outfile = eg.filesavebox(msg='Choose the output file ', title=' Pick where you want the gcode to arrive', default=os.path.expanduser("~")+"//My Documents//Output.gcode", filetypes = "*.gcode")
print outfile
params = params + " -outfile " + outfile

verbose = eg.boolbox(msg='Do you want the verbose to be activated (for debug)', title=' Verbose Y/N ', choices=('No', 'Yes'), image=None) # returns true if the first is chosen
if verbose == 0:
	 params = params + " -verbose"
print params


#TODO:
# Enforce .gcode at the end of outfile
# handle cases where nothing is entered
# Also why is filesavebox appearing in the background ?
コード例 #45
0
ファイル: __init__.py プロジェクト: orf/pypaper
 def showOption(self, name, default):
     return easygui.boolbox(name)
コード例 #46
0
	def analyze(self,igroup):
		# to get the sourcedata
		database=self.gettmpdata('database');
		spectra=database[0]['resultdatatablegroups'][igroup];
		spectranew=spectra.getemptyinstance();
#======================================================================
#         the real calculation
#======================================================================
		gainorshift=self['gainorshift'].get();
		
		keys=spectra.keyssorted(["min(x)"]);
		nameofintstandard=self['nameofintstandard'].get();
		if keys.count(nameofintstandard)==0:
			nameofintstandard=keys[0];
			self['nameofintstandard'].set(keys[0]);

		canceled=False;
		spect0=spectra[keys[0]].copyxy();
		gainfactors={};
		gainfactors[keys[0]]=1;

		for i in range(1,len(keys)):
			#print "i:",i
			spect=spectra[keys[i]].copyxy();
			spect0start=spect0.copyxy();
			spectstart=spect.copyxy();
			satisfied=False;
			while not satisfied and not canceled:
				spect0=spect0start.copyxy();
				spect=spectstart.copyxy();
				
				pylab.hold(False);
				spect0.plot('b');
				pylab.hold(True);pylab.grid(True);
				spect.plot('r');
				
				#print "spect0:",spect0['y'];
				#print "spect:",spect['y'];
				
				x,y1,y2=spect0.getcommonxy(spect);
				dx=(max(x)-min(x))/4;
				maxy=max(max(y1),max(y2));
				miny=min(min(y1),min(y2));
				dy=(maxy-miny)/4;
				#print x;
				#print y1;
				#print y2;
				A0=(min(x)-dx,max(x)+dx,miny-dy,maxy+dy)
				if (A0[0]-A0[1] )*(A0[2]-A0[3])!=0:
					#print "A0:",A0,(A0[0]-A0[1] )*(A0[2]-A0[3])
					pylab.axis(A0);
				answer=easygui.boolbox("Choose the range for for merging","Individual merging",["OK","Cancel"]);
				if answer==1:
					A=pylab.axis();
					xmin=A[0];
					xmax=A[1];
					gainfactors[keys[i]]=spect0.indmerge(spect,xmin,xmax,gainorshift);
					spect0.plot('g');
					if (A0[0]-A0[1] )*(A0[2]-A0[3])!=0:
						pylab.axis(A0);
				else:
					canceled=True;
				if not canceled	:
					answer=easygui.buttonbox("Satisfied?","Individual merging",["Yes","No","Cancel"]);
					#print "answer:",answer
					if answer=="Yes":
						satisfied=True;
					elif answer=="Cancel":
						canceled=True;
			if canceled:
				break;
			
		if not canceled:
			index=keys.index(nameofintstandard);
			print "index,gain:",index,gainfactors
			print "gainorshift:",gainorshift
			print "nameofintstandard",nameofintstandard
			if gainorshift==0:
				spect0['y']=spect0['y']/gainfactors[keys[index]];
			elif gainorshift==1:
				spect0['y']=spect0['y']-gainfactors[keys[index]];
			spect0.log({"operation":"Fr_SpectIndMerge","standard":nameofintstandard});
			spectnew=spect0;
			spectranew.insert(spectnew,keys[0]+'merged');
			spectra=database[0]['resultdatatablegroups'][igroup]=spectranew;
			spectnew.plot('o');
コード例 #47
0
# File input
if User_input.upper() == 'CSV':
    csv_input_file=eg.fileopenbox(msg='Please select csv input file', title='CSV input file', filetypes =["*.csv", "CSV files"], default="%s\\*.csv" % path_cwd)
    csv_input_path=ntpath.split(csv_input_file)[0]
    with open(csv_input_file, 'rb') as fileread:
        inputreader = csv.reader(fileread)
        for row in inputreader:
            Items_input.append(row[0])
    fileread.close()

# Use manual input data instead of file
else:
    Items_User_input = User_input.split(',')
    for z in Items_User_input:
        Items_input.append(z.strip())
    annotYN=eg.boolbox(msg='Do you want to search keyword in annotation file?', title='Search annotation? ', choices=('Yes', 'No'))
    if annotYN:
        annot_file=eg.fileopenbox(msg='Please select csv annotation file', title='CSV annotation file', filetypes =["*.csv", "CSV files"], default="%s\\*.csv" % path_cwd)

# prepare fasta reference file
unigene_file=eg.fileopenbox(msg='Please select fasta reference file', title='FASTA ref file', filetypes =["*.fas", "*.fa", "*.fasta", "*.pep", "*.txt", "FASTA files"], default="%s/*.fas" % path_cwd)
Fasta_output=eg.filesavebox(msg='Save fasta output file as', title='Output fasta file', default="%s/output.fas" % path_cwd, filetypes =["*.fas", "*.fa", "*.fasta", "*.pep", "*.txt", "FASTA files"])
fasta_dict=index_fasta(unigene_file)
print len(fasta_dict)

#
# Headers for output table


# Go through all entries in Item_list
found_list=[]
コード例 #48
0
ファイル: Easyguidemo.py プロジェクト: Jaren831/usafa
def main():
    """Main program to demonstrate the easygui module."""

    # The most basic message box displays a message with an OK button.
    easygui.msgbox( "Your software installation is complete.\n\n" +
                    "This and the following dialogs are a\ndemonstration of the easygui module.\n\n" +
                    "Your responses to each dialog are\nprinted in the console window.\n\n" +
                    "You may find this module useful\nthroughout the semester." )

    # A default Yes/No box asks "Shall I continue?", shows Yes and No buttons,
    # and returns True if Yes is clicked, False if No is clicked.
    response = easygui.ynbox()
    print( type( response ), response )

    # The message/question and dialog title can be specified.
    response = easygui.ynbox( msg="Is your squad the best at USAFA?", title="Best Squad?" )
    print( type( response ), response )

    # The more generic Bool box allows different text in the Yes/No buttons.
    response = easygui.boolbox( msg="Is your squad the best at USAFA?", title="Best Squad?",
                                choices=[ "Hooah!", "Form 10" ] )

    # This is how you might use the response from a Yes/No or Bool box.
    # Note the variable 'response' is already True or False, so there is no
    # need to compare it to anything (i.e., response == True is not necessary).
    if response:
        # The message box displays a message and a button to close the box.
        easygui.msgbox( msg="Of course my squad is best!", title="Best Squad", ok_button="Hooah!" )
    else:
        # If not specified, the button says "OK", as you would expect.
        easygui.msgbox( msg="My squad improves every day.", title="Best Squad" )

    # A button box allows more than two choices.
    response = easygui.buttonbox( msg="Who is your favorite turtle?", title="Select",
                                  choices=[ "Leonardo", "Michelangelo", "Raphael", "Donatello" ] )
    print( type( response ), response )

    # The enter box returns a string and allows specification of the default value.
    response = easygui.enterbox( msg="Enter your favorite baseball team:",
                                 title="Go Cubs!", default="Chicago Cubs" )
    print( type( response ), response )

    # The integer box returns an int and allows specification of lower and upper bounds.
    response = easygui.integerbox( msg="What is the answer?", title="Input",
                                   default="42", lowerbound=0, upperbound=100 )
    print( type( response ), response )

    # The file open box is a standard file chooser dialog and returns the file name as a string.
    filename = easygui.fileopenbox( msg="Open file...", filetypes=[ "*.txt", "*.py" ] )
    print( type( filename ), filename )

    # Here is a simple way to read the entire contents of a file into a single string.
    with open( filename, "r" ) as data_file:
        data = data_file.read()

    # A code box displays editable text in a monospaced font and does not wrap lines;
    # (not shown here, but a textbox would use a proportional font and wrap lines).
    edited_data = easygui.codebox( msg=filename, title="Code Box", text=data )

    # The text in the code box is returned as a single string when the window is closed.
    if data == edited_data:
        easygui.msgbox( msg="No changes made to text." )
    else:
        # The file save box asks to confirm before overwriting an existing file.
        filename = easygui.filesavebox( msg="Save file...", filetypes=[ "*.txt", "*.py" ] )
        # The file name will be None if the user clicks Cancel.
        if filename is not None:
            # Here is a simple way to write the entire contents of a string to a file.
            # Note: If the filename already exists, it will be completely overwritten!!
            with open( filename, "w" ) as data_file:
                data_file.write( edited_data )
コード例 #49
0
ファイル: popup.py プロジェクト: light-saber/quick-shutdown
#!/usr/bin/env python
#A simple script that checks the uptime and if it is greater than 15 hours, gives you an option to shut down the computer
#Trying out python scripts, thats all

#Created by light-saber
#Date: 2014.06.27

import os
import easygui
import math
from datetime import timedelta

with open('/proc/uptime', 'r') as f:
    uptime_seconds = float(f.readline().split()[0])
uptimes = uptime_seconds/3600
uptime=math.floor(uptimes)
if uptime > 15:
        message = "The computer is up and running for "+ str(uptime) +" hours"
        title = "Warning"
        if easygui.boolbox(message, title, ["Shutdown","Cancel"]):
                os.system("shutdown -h 10")
        else:
                pass
else:
        pass
コード例 #50
0
def process(PA):
	global ActiveWindow, Shapes, Word, TRs_all, xl, Visio
	global RESULTS
	# Bien gérer les erreurs
	try:

		# ouvrir le fichier excel et faire les initialisations de coutume
		xl = CreateObject("Excel.application")
		xl.Visible = False
		xl.DisplayAlerts = False
		PA_wb = xl.Workbooks.Open(PA)
		PA_wb.Sheets("synoptique-bilan µmodules").Select()

		# dans la sheet visée, détecter tout les objets OLE (qui seront 
		# normalement tous des déssins visio)
		OLEObjects = PA_wb.Sheets("synoptique-bilan µmodules").OLEObjects()

		# pour chaque déssin ...
		for OLEObject in OLEObjects:
			# l'ouvrir dans Visio
			OLEObject.Verb(2)
			# prendre la main sur la fenêtre visio ouverte
			Visio = GetActiveObject("Visio.Application")
			# Visio.Visible = False
			Visio.DisplayAlerts = False
			ActiveWindow =  Visio.ActiveWindow
			Page = ActiveWindow.Page
			Shapes = Page.Shapes
			# Ceci est pour les déssins plutôt compliqués, après chaque sélection des PB, le script
			# les affichera et demandra de confirmer si c'est bon ou non
			msg = "Voulez confirmer le nombre de PBs après chaque sélection?\n" \
						+ "(si c'est plan assez complexe mieux vaut répondre par oui)"
			yn = ynbox(msg)
			# allons-y!
			# On extrait d'abord les infos d'entête
			for shape in Shapes:
				text = shape.Text
				if text.startswith('NRO'):
					bloc_NRO = text
				elif text.startswith('PT'):
					# certaines shapes buguent je ne sais pas pourquoi, elles n'ont pas d'utilité
					try:
						blocs_PT.append(shape)
					except:
						blocs_PT = [shape]
				elif text.startswith('PA'):
					bloc_PA = text
					# On extrait la position x du PA pour prendre toutes les TR qui sont à droite
					PA_posx = get_XY(shape)[0]
			# Les deux blocs FI et PA tout deux commencent par PT, celui de PA est plus à gauche
			# on les différenciera par leur position
			if get_XY(blocs_PT[0])[0] < get_XY(blocs_PT[1])[0]:
				FI_bloc = blocs_PT[0]
				PA_bloc = blocs_PT[1]
			else:
				FI_bloc = blocs_PT[1]
				PA_bloc = blocs_PT[0]

			PA_PT = PA_bloc.Text.rsplit('\n')[0].replace('PT: ', '')
			PMZ_PT = FI_bloc.Text.rsplit('\n')[0].replace('PT: ', '')
			CH = PA_bloc.Text.rsplit('\n')[2].replace('CH: ', '')
			NRO = extract('NRO/PMZ/PA', bloc_NRO, 'NRO')
			ADRESSE1 = ' '.join(PA_bloc.Text.rsplit('\n')[3:5])\
									.replace('Adresse: ', '')
			ADRESSE2 = ADRESSE1.rsplit('-')[0]

			# Les TRs du déssin courant
			TRs = {}

			# là ça va barder!
			for shape in Shapes:
				if shape.Text.startswith('TR'):
					# Seulement ceux qui sont plus à droite de PA
					if get_XY(shape)[0] > PA_posx:
						# Le text est un peu bizarre, il est vraiment en texte mais paraît être un
						# bytes! On doit le nettoyer
						TR_TXT = str(shape.Text.encode()).replace("b'", '').replace("'", '')
						# Extraire ne TR
						TR = TR_TXT.rsplit('FO')[0] \
							.replace('\\n', ' ') + 'FO'
						# Si ce n'est pas un TR valide, passer
						if not re.match(r'TR\s+\d{2}\s+\d{4}\s+\d+FO', TR):
							continue
						# Si ce TR n'a pas encore été enregistré dans la liste TRs, l'enregistrer
						## Initialiser la longueur à 0
						## Mettre le shape courant dans la liste "shapes"
						## Initialiser une liste vide pour les CH ou IMB ou AP qui vont avec
						## Initialiser une liste vide pour les PTs qui vont avec (pour le nommage)
						## Et initialiser une variable "0" pour le PT qui est maximum (pour le nommage)
						if TR not in TRs:
							TRs[TR] = {
								'LONG': 0,
								'SHAPES': [shape.ID],
								'CH/IMB/AP': [],
								'PTs': [],
								'maxPT': 0
								}
						# Sinon si le TR est déjà dans TRs, ajouter le shape courant à "SHAPES"
						else:
							TRs[TR]['SHAPES'].append(shape.ID)
						# Essayer d'extraire la longueur du TR courant
						try:
							TR_LONG = int(TR_TXT.rsplit('\\xe2\\x80\\x93 ')[1] \
															.replace('m', ''))
						except:
							TR_LONG = 0
						# Et incrémenter la longueur du TR global corréspondant à cette ligne
						TRs[TR]['LONG'] = TRs[TR]['LONG'] + TR_LONG
			
			# Message pour que l'utilisateur sélectionner les blocs PB pour chaque TR
			title1 = 'Sélectionnez les bloc'
			title2 = 'Confirmez la sélection'
			# Pour chaque TR dans TRs
			for TR in TRs:
				# Python n'a pas de "REDO", on hack avec un "WHILE"
				while True:
					# Sélectionner toutes les shapes de cette ligne de TR
					SelectShapes(TRs[TR]['SHAPES'])
					# Demander lui de sélectionner, quand il confirme continuer...
					if ccbox(TR, title1):
						# Une liste vide pour tout les PB dans ce TR
						CH_OR_IMB_OR_AP_all = []
						# Une liste vide pour tout les PTs dans ce TR
						PTs = []
						# Une liste vide pour tout les PBs dans ce TR
						PBs = []
						# Un message au cas où l'utilisateur aurait choisit une confirmation
						msg = "Pour " + TR + "\nVous avez sélectionné:\n"
						# Le nombre de PBs sélectionnées (pour affichage dans la confirmation)
						selected_PBs = 0
						# Au cas où il n'y aurait pas de PB valide, pas la peine de mettre une 
						# fenêtre de confirmation, supposer tout de même qu'il y'en a ...
						yn_yes = True
						# Pour chaque fenêtre sélectionnée
						for selected in ActiveWindow.Selection:
							# (certains shapes n'aiment pas qu'on appelle leur .Text!!!!)
							try:
								TEXT = str(selected.Text)
								# Prendre seulement les blocs qui commencent par "PB"
								if not TEXT.startswith('PB'):
									continue
								# Incrémenter le nombre de PBs trouvés par +1
								selected_PBs = selected_PBs + 1
								# Enregister le PB, PT, l'adresse, et le text qui peut être un:
								## Ch.XXXXX
								## IMB/XXXXX/XXXX
								## AP XXXX
								PB = TEXT.rsplit('\n')[0].rstrip()
								PT = TEXT.rsplit('\n')[2]
								ADR = TEXT.rsplit('\n')[3]
								CH_OR_IMB_OR_AP = TEXT.rsplit('\n')[4]
								# Si l'un de ces lignes ne se trouve pas à la bonne place
								if (not CH_OR_IMB_OR_AP.startswith('AP ')
									and not CH_OR_IMB_OR_AP.startswith('Ch.')
									and not CH_OR_IMB_OR_AP.startswith('IMB')):
									# Resélectionner les sélectionnés (pfff sert à rien ça!)
									SelectShapes([selected.ID])
									# Et dire qu'il y a un truc qui cloche!
									msgbox("T'as surement encore fais une connerie dans tes"
												+ "déssins, regarde ce bloc dans la ligne PT!\n"
												+ "Je devrais trouver Ch.XXXX ou AP XXXX"
												+ "ou IMB/XXXX/XXX mais j'ai trouvé\n"
												+ CH_OR_IMB_OR_AP + "\n"
												+ "Quand t'auras détécté l'erreur click sur OK")
									# Continuer ou quitter!
									cont = boolbox("Dois-je continuer ou fermer?",
																"Que faire?",
																['Continuer?', 'Fermer?'])
									if not cont:
										exit(0)
									else:
										pass
								else:
									# Sinon, préparer le message de confirmation
									msg = msg + "- " + CH_OR_IMB_OR_AP + "\n"
									# Et ajouter le CH/IMB/AP à la liste
									CH_OR_IMB_OR_AP_all.append([ADR, CH_OR_IMB_OR_AP])
									# Ajouter le PT de ce bloc à la liste PTs
									PTs.append(int(PT.replace('PT', '')))
									# Ajouter le PB de ce bloc à la liste PBs
									PBs.append(PB)
							except:
								# Si quelque chose cloche, trouver une porte de sortie!!:
								SelectShapes([selected.ID])
								msgbox("T'as surement encore fais une connerie dans tes"
										+ "déssins, regarde ce bloc dans la ligne PT!\n"
										+ "Quand t'auras détécté l'erreur click sur OK")
								cont = boolbox("Dois-je continuer ou fermer?",
												"Que faire?",
												['Continuer?', 'Fermer?'])
								# Vraiment je ne sais pas à quoi sert ce que j'ai écrit dans les 
								# 8 prochaines lignes!!!!
								if not cont:
									exit(0)
								else:
									msg = msg + "(RIEN!)"
									CH_OR_IMB_OR_AP_all = []
									PTs = []
									PBs = []
									yn_yes = False
						# S'il n'a rien sélectionné
						if not selected_PBs:
							cont = boolbox("Tu n'as rien sélectionné! Tu confirmes"
											+ " que ce n'est pas une connerie?",
											"Sélection vide!",
											['Oui vas-y', 'Comme d\'hab! Une connerie'])
							# Soit on quitte!
							if cont:
								break
							# Soit c'est délibéré et on continue
							else:
								continue

						# Si l'utilisateur avait demandé une confirmation, la montrer
						# (S'il y a eu une erreur, yn_yes est False, et pas la peine de montrer la
						# confirmation)
						if yn and yn_yes:
							msg = msg + "(" + str(selected_PBs) + " sélectionnés)"
							conf = boolbox(msg, title2, ['Confirmer?', 'Refaire?'])
							if conf:
								# Si c'est confirmé, stocher ces données pour le shape
								TRs[TR]['CH/IMB/AP'] = CH_OR_IMB_OR_AP_all
								TRs[TR]['PTs'] = PTs
								TRs[TR]['PBs'] = PBs
								break
							else:
								pass
						# Sinon s'il n'avait pas demandé de confirmation, stocker ces données
						# directement pour le shape
						else:
							TRs[TR]['CH/IMB/AP'] = CH_OR_IMB_OR_AP_all
							TRs[TR]['PTs'] = PTs
							TRs[TR]['PBs'] = PBs
							break
					# En cas d'erreur sortir :-(
					else:
						exit(0)
				# Il doit y avoir au moins un PT pour créer un fichier doc et xls avec le max des TRs
				if len(TRs[TR]['PTs']):
					TRs[TR]['DE_filename'] = 'DE_PT%06d' % max(TRs[TR]['PTs']) + '.doc'
					TRs[TR]['AR_filename'] = 'AR_PT%06d' % max(TRs[TR]['PTs']) + '.xls'
				# Les fichiers avec ce nom ne devront jamais voir le jour!
				else:
					TRs[TR]['DE_filename'] = 'je_ne_suis_pas_cense_exister.doc'
					TRs[TR]['AR_filename'] = 'je_ne_suis_pas_cense_exister.xls'
					# Un cas très particulier m'a forcé à ajourer la ligne suivant!
					TRs[TR]['PBs'] = []

			# Si je n'ai trouvé aucun TR, montrer un message
			if TRs == {}:
				msgbox("il n'y pas de TR valide sur ce déssin")
			# Ajouter ces TRs à TR_all
			TRs_all.append(TRs)
			# Cacher le déssin Visio
			Visio.Visible = False

		# Demander qui est le client
		xl.Visible = True
		msg = "Quel est le client pour cette fiche PA?"
		choices = ["Circet","Engie"]
		client = buttonbox(msg, choices=choices)

		# Résultat globaux pour cette fiche PA
		RESULTS[PA] = {
			'PA_REF':		bloc_PA,
			'client':		client,
			'TRs_all': 		TRs_all,
			'NRO':			NRO,
			'PMZ_PT':		PMZ_PT,
			'PA_PT':		PA_PT,
			'CH':			CH,
			'ADRESSE1':		ADRESSE1,
			'ADRESSE2':		ADRESSE2,
			'DATE':			DATE
		}

		# Quitter excel et passer à la prochaine fiche PA
		xl.Quit()
		return

	except:
		# En cas d'erreur innatendue!
		print(format_exc())
		codebox("t'as encore fais une connerie! Fais moi un screen de malheur!",
				"Erreur",
				format_exc())
		going()
コード例 #51
0
ファイル: FinalProj.py プロジェクト: akashbulbule/tic-tac-toe
def main():	
	global total
	n = raw_input("Enter the value of n:")  #enter the order of tic-tac-toe
	n = int(n)
	pygame.init() #set the gui for tic-tac-toe
	tictactoe = pygame.display.set_mode(((width+margin)*(n)+margin,(height+margin)*(n)+margin)) #screen size
	pygame.display.set_caption("Tic-Tac-Toe")  #caption of the display
	tictactoe.fill((0,0,0))  #background filled black
	font = pygame.font.Font(None, 100)  
	gameboard(n,tictactoe) #set the tiles for the game
	choice = easygui.boolbox("Do you want to play first?", title="New Game", choices=('Yes','No'))
	k = np.array([['-' for i in range(n)] for j in range(n)])  #initialize board configuration
	if choice==0: #if choice is 0 then max's turn else min's turn
		mov='X'
	else:
		mov='O'
	while True:
		if mov=='X':
			total=0
			f = minmax1(k,mov,-float('inf'),float('inf'),4,0,n) 
			k = f[1] #play the max move
			movcord = f[2] 
			print "the total nodes expanded by computer's present move:",total
			tictactoe.blit(font.render(mov, 1, (0,0,255)),((width+margin)*movcord[1]+margin,(height+margin)*movcord[0]+margin-5)) #display the move on the game screen
			pygame.display.update() #update the display screen
			mov = nextmov[mov] #change the move to O's move

		for event in pygame.event.get():
			if event.type == QUIT:
				pygame.quit()
				return
			if event.type == pygame.MOUSEBUTTONDOWN: #detect the mouse button click by the user
				pos = pygame.mouse.get_pos()      #get the positions in pixels and convert to row,column coordinates
				r = (pos[0]-margin)/(width+margin)
				c = (pos[1]-margin)/(height+margin)
				o,p = np.where(k=='-')
				mv=[]
				for i in range(len(o)):
					mv+=[(o[i],p[i])]
				if (c,r) in mv:
					k[c][r]='O'
					tictactoe.blit(font.render(mov, 1, (255,0,0)),((width+margin)*r+margin-2,(height+margin)*c+margin-6)) #display user's move on screen
					pygame.display.update() #update the display
					mov = nextmov[mov]  #change the move to X's move
		j = evaluate1(k,0,'X',n)  #evaluate if the game is over or not
		win=0
		lost=0
		draw=0
		if j[1]:
			if j[0]>0: #computer(max's) win condition
				win = easygui.boolbox("Computer wins!!Do you want to restart the game?",title="Game Over",choices=('Yes','No'))
			elif j[0]<0:# player wins (min's) win condition
				lost = easygui.boolbox("You win!!Do you want to restart the game?",title = "Game Over",choices = ('Yes','No'))
			else:  #draw condition
				draw = easygui.boolbox("The game is a draw!!Do you want to restart the game?",title = "Game Over",choices = ('Yes','No'))
			if win or lost or draw: #if either of the above prompt to restart the game and reset the board configuration
				tictactoe.fill((0,0,0))
				gameboard(n,tictactoe)
				choice = easygui.boolbox("Do you want to play first?", title="New Game", choices=('Yes','No'))
				k = np.array([['-' for i in range(n)] for j in range(n)])
				if choice==0:
					mov='X'
				else:
					mov='O'
			else:
				pygame.quit()
				return				
コード例 #52
0
ファイル: cannon.py プロジェクト: yufan163/ThePythonGameBook
    wind = r.choice((-1, 1)) * round(r.random(), 4)
    e.msgbox("wind is : {}".format(wind))
    #print("wind is : {}".format(wind))
    #heading = float(input("please enter angle (e.g. 45.0)"))
    #speed = float(input("please enter speed (e.g. 10.0)"))
    heading = float(
        e.enterbox(
            "please enter angle (e.g. 45.0)",
            default="45.0"
        )
    )
    speed = float(e.enterbox("please enter speed (e.g. 10.0)", default="10.0"))

    t.setheading(180 - heading)

    dx = math.cos(t.heading() * math.pi / 180) * speed
    dy = math.sin(t.heading() * math.pi / 180) * speed
    #for step in range(200):
    y = ground
    while y >= ground:
        x = t.xcor()
        y = t.ycor()
        dy -= 0.1
        x += dx
        y += dy
        t.goto(x, y)

    play = e.boolbox("play again?")

t.exitonclick()