Exemple #1
0
def Download_data(Out_file='E:\\',
                  data_type='f',
                  Update_Frequency='hourly',
                  Version='rinex3',
                  Station='ebre',
                  Year='2017',
                  DOY='175'):
    year = Year2short(Year)
    try:
        if Update_Frequency == 'hourly':
            for Hour in range(0, 24):
                hour = Hour2alpha(Hour)
                if (Hour < 10):
                    Url = Url_or + '/' + Update_Frequency + '/' + Version + '/' + Year + '/' + DOY + '/' + '0' + str(
                        Hour)
                else:
                    Url = Url_or + '/' + Version + '/' + Year + '/' + DOY + '/' + str(
                        Hour)
                ftp = connect(ip)
                ftp.cwd(Url)
                # +'/'+Station+DOY+hour+'.'+year+'o'
                filename = Station + DOY + hour + '.' + year + data_type + '.Z'
                files = ftp.nlst()
                if not os.path.exists(
                        os.path.join(Out_file, filename)
                ) and filename in files:  # 这里的not应该不要吧  不在本地文件 同时存在ftp上 才下载
                    with open(os.path.join(Out_file, filename), 'wb') as f:
                        ftp.retrbinary('RETR ' + filename, f.write)
                ftp.quit()
                Url = ''
        elif Update_Frequency == 'daily':
            Url = ''
    except:
        gui.exceptionbox()
Exemple #2
0
def encrypt_file(filenames, params):
    logging.info(f'Encrypting files @ {str(filenames)}')
    encryption_password = easygui.passwordbox(
        msg='Enter encryption password', title='FileLocker').encode('utf-8')
    try:
        fern = kfp(encryption_password)
        logging.info('Generated key from password.')
        for file in filenames:
            to_enc = open(file, 'rb')
            enc_this = open(file + '.filelock', 'wb')

            block_count = 0
            while True:
                data = to_enc.read(1048576)
                if len(data) == 0:
                    break

                logging.debug(f'Read block {str(block_count)}')
                enc_this.write(base64.b64encode(fern.encrypt(data)) + b'\n')
                block_count += 1
            to_enc.close()
            enc_this.close()
            os.remove(file)
    except:
        easygui.exceptionbox()
Exemple #3
0
def fetchURL(link):
  # exception handling
  try:
      res = requests.get(link) # the response
      if "text/html" not in res.headers["content-type"]:
        raise Exception('WH')
  except requests.exceptions.ConnectionError:
    eg.exceptionbox()
    exceptionReport('CE')
    return
  except requests.exceptions.Timeout:
    eg.exceptionbox()
    exceptionReport('TE')
    return
  except requests.exceptions.URLRequired:
    eg.exceptionbox()
    exceptionReport('WU')
    return
  except requests.exceptions.RequestException:
    eg.exceptionbox()
    exceptionReport('RE')
    return
  except Exception as exp:
    eg.exceptionbox()
    exceptionReport(exp.args)
    return

  # the real work: fetch
  msg = 'Completed fetching from: ' + link
  title = 'Fetch: Complete'

  print msg
  eg.msgbox(msg, title)

  return res
Exemple #4
0
    def create_trial_list(self):
        '''Create lists of trials based on digital inputs and outputs and store
        to hdf5 store
        Can only be run after data extraction
        '''
        if not self.process_status['extract_data']:
            eg.exceptionbox('Must extract data before creating trial list',
                            'Data Not Extracted')
            return

        if self.rec_info.get('dig_in'):
            in_list = dio.h5io.create_trial_data_table(
                self.h5_file,
                self.dig_in_mapping,
                self.sampling_rate,
                'in')
            self.dig_in_trials = in_list
        else:
            print('No digital input data found')

        if self.rec_info.get('dig_out'):
            out_list = dio.h5io.create_trial_data_table(
                self.h5_file,
                self.dig_out_mapping,
                self.sampling_rate,
                'out')
            self.dig_out_trials = out_list
        else:
            print('No digital output data found')

        self.process_status['create_trial_list'] = True
        self.save()
Exemple #5
0
 def select_stream(self):
     selection = easygui.enterbox(msg='Select - use st for trace.stats:',
                                  default='225 < st.azi < 265.7')
     try:
         self.st_all = self.st_all_old.select(expr=selection)
     except:
         exceptionbox("Error while selecting!")
def main():
    try:
        while True:
            # Directory input
            directory = easygui.diropenbox(
                "Select a folder to recursively search", program)
            if directory is None:
                if easygui.ccbox("No folder selected. Try again?", program):
                    continue
                else:
                    exit()
            print("Directory: ", directory)

            # Keyword input
            keyword = easygui.enterbox(
                "Enter the keyword to search for, case insensitive", program)
            if keyword is None:
                if easygui.ccbox("No keyword entered. Try again?", program):
                    continue
                else:
                    exit(0)

            print("Keyword: ", keyword)

            results = search(directory, keyword)

            print("Entries: ", len(results))
            print("Results: ", results)

            if results is None:
                if easygui.ccbox("No Results found. Try again?", program):
                    continue
                else:
                    exit(0)
            unc = pathlib.Path(directory).resolve()
            header = "To save press OK.\nResults: \n Directory: " + directory + "\n UNC: " + str(
                unc
            ) + "\n Keyword: " + keyword + "\n Number of Results: " + str(
                len(results))
            results_pretty = ""
            for line in results:
                results_pretty += line + "\n\n"
            if easygui.textbox(header, program, results_pretty):
                path = easygui.filesavebox("Save Results", program,
                                           program + "_" + keyword,
                                           results_pretty)
                if path is not None:
                    save_file(path, results)
                    exit(0)
                else:
                    exit(0)
            else:
                exit(0)

    except SystemExit:
        exit(0)
    except:
        easygui.exceptionbox(
            "Error occurred. Please contact the maintainer of this program.",
            program)
Exemple #7
0
def main():
    """
    Main function
    """
    try:
        filename = sys.argv[1]
    except:
        filename = easygui.fileopenbox()
    try:
        ole = olefile.OleFileIO(filename)
        listdir = ole.listdir()
        streams = []
        for direntry in listdir:
            #print direntry
            streams.append('/'.join(direntry))
        streams.append(ABOUT)
        streams.append(QUIT)
        stream = True
        while stream is not None:
            msg ="Select a stream, or press Esc to exit"
            title = "olebrowse"
            stream = easygui.choicebox(msg, title, streams)
            if stream is None or stream == QUIT:
                break
            if stream == ABOUT:
                about()
            else:
                browse_stream(ole, stream)
    except:
        easygui.exceptionbox()
Exemple #8
0
def decrypt_file(filenames, params):
    logging.info(f'Decrypting files @ {str(filenames)}')
    encryption_password = easygui.passwordbox(
        msg='Enter decryption password', title='FileLocker').encode('utf-8')
    try:
        fern = kfp(encryption_password)
        logging.info('Generated key from password.')
        for file in filenames:
            to_dec = open(file, 'rb')
            dec_this = open(file.split('.filelock')[0], 'wb')

            block_count = 0
            while True:
                dat = to_dec.readline()
                if len(dat) == 0:
                    break
                logging.debug(f'Read block {str(block_count)}')
                dec_this.write(fern.decrypt(base64.b64decode(dat)))
                block_count += 1

            to_dec.close()
            dec_this.close()
            os.remove(file)
    except:
        easygui.exceptionbox()
def execute_single_mysql_statement(dbcursor, statement, error_message):
    """Executes a single MySQL statement. If there is a problem, writes the given 
    message and the MySQL message to stderr and exits"""
    global DIALOG_COMMUNICATION
    global DRY_RUN

    if DRY_RUN:
        print_verbose(
            "If I were not running dry, I'd execute the following db statement: %s"
            % statement)
    else:
        if DIALOG_COMMUNICATION:
            try:
                dbcursor.execute(statement)
            except:
                g.exceptionbox(
                    "MySQL error in the statemet %s. See the MySQL message below."
                    % (statement), windowtitle)
                exit(1)
        else:
            try:
                print_debug("Executing the following db statement: %s" %
                            statement)
                dbcursor.execute(statement)
            except (mysql.connector.Error) as e:
                print_error_and_exit("MySQL error. %s \n  MySQL said: '%s'" %
                                     (error_message, str(e.args)))
    def handle_config(self, option=None, section=None, key=None, value=None):
        import configparser
        conf = configparser.ConfigParser()
        realpath = os.path.split(os.path.realpath(sys.argv[0]))[0]
        configini = realpath + r"\config.ini"

        try:
            conf.read(configini)
            if option == 'g':
                value = conf.get(section, key)
                return value
            elif option == 's':
                conf.set(section, key, value)
            elif option == "a":
                conf.add_section(section)
            elif option == "rs":
                conf.remove_section(section)
            elif option == "ro":
                conf.remove_option(section, key)

            with open(configini, 'w') as fw:
                conf.write(fw)
            return conf

        except:
            easygui.exceptionbox()
def google_popularity():
    try:
        pytrend = TrendReq()

        # Create payload and capture API tokens. Only needed for interest_over_time(), interest_by_region() & related_queries()
        cap_list = ['Compare search metrics', 'Trending searches']
        speak.Speak("Welcome to the Google search capabilities")

        google_response_ = easygui.choicebox(msg='Google search capabilities',
                                             title='Google Trends',
                                             choices=cap_list)
        print(google_response_)
        if google_response_ == 'Compare search metrics':

            Compare_two_keywords(pytrend)
        elif google_response_ == 'Trending searches':
            trending_searches_df = pytrend.trending_searches()
            trending_searches_df.to_csv(popdir + '\googleTrendingSearch' +
                                        str(datetime.datetime.now().date()) +
                                        '.csv')
            easygui.msgbox(
                msg='Saving latest google trending searches in this csv' +
                os.getcwd() + os.getcwd() + '\googleTrendingSearch' +
                str(datetime.datetime.now().date()) + '.csv')
#            print(trending_searches_df.head())

    except Exception as e:
        speak.Speak(
            'Sorry My mistake please provide your feedback regarding this error'
        )
        easygui.exceptionbox(str(e))
Exemple #12
0
def main():
    """
    Main function
    """
    try:
        filename = sys.argv[1]
    except:
        filename = easygui.fileopenbox()
    try:
        ole = olefile.OleFileIO(filename)
        listdir = ole.listdir()
        streams = []
        for direntry in listdir:
            #print direntry
            streams.append('/'.join(direntry))
        streams.append(ABOUT)
        streams.append(QUIT)
        stream = True
        while stream is not None:
            msg = "Select a stream, or press Esc to exit"
            title = "olebrowse"
            stream = easygui.choicebox(msg, title, streams)
            if stream is None or stream == QUIT:
                break
            if stream == ABOUT:
                about()
            else:
                browse_stream(ole, stream)
    except:
        easygui.exceptionbox()
Exemple #13
0
def encrypt_folder(filenames, params):
    logging.info(f'Encrypting folders @ {str(filenames)}')
    encryption_password = easygui.passwordbox(
        msg='Enter encryption password', title='FileLocker').encode('utf-8')
    try:
        fern = kfp(encryption_password)
        logging.info('Generated key from password.')
        for file in filenames:
            logging.info('Generating temporary archive.')
            shutil.make_archive(file, format='zip', root_dir=file)
            shutil.rmtree(file)
            to_enc = open(file.rstrip(os.sep) + '.zip', 'rb')
            enc_this = open(file.rstrip(os.sep) + '.dirlock', 'wb')

            block_count = 0
            while True:
                data = to_enc.read(1048576)
                if len(data) == 0:
                    break

                logging.debug(f'Read block {str(block_count)}')
                enc_this.write(base64.b64encode(fern.encrypt(data)) + b'\n')
                block_count += 1
            to_enc.close()
            enc_this.close()
            os.remove(file.rstrip(os.sep) + '.zip')
    except:
        easygui.exceptionbox()
def timesheet_with_graph():
    try:
        filepath = timesheet()

        df = pd.read_csv(filepath, encoding="ISO-8859-1")

        speak.Speak("Please enter filename to save:")
        file_name = easygui.textbox(msg='Please enter filename to save:',
                                    title='Time_sheet_with_graph').split()[0]

        if not os.path.exists(mail_dir):
            os.mkdir(mail_dir)
        os.chmod(mail_dir, 777)

        df.set_index(df['Title'], inplace=True)
        #    os.chmod(current_dir+'\\'+str(file_name)+'\\',777)
        fig, ax = plt.subplots()
        # the size of A4 paper
        fig.set_size_inches(10, 20)
        sns.barplot(df['Duration(Minutes)'], df.index, data=df)
        plt.savefig(mail_dir + '\\' + str(file_name) + '.png', format='png')
        #        print('file saved to '+mail_dir+'\\'+str(file_name)+'.png'))
        easygui.msgbox(msg='file saved to ' + str(mail_dir) + '\\' +
                       str(file_name) + '.png',
                       title='Timesheet with graph prepared')
        speak.Speak('file saved to directory' + str(file_name) +
                    'with the name time spending in meeting')
    except Exception as e:
        speak.Speak(
            'Sorry My mistake please provide your feedback regarding this error'
        )
        easygui.exceptionbox(str(e))
    def resTip(self, AttentionLink: str, task_name):
        """

        :param task_name: 任务类型:ssr ; v2ray
        :param AttentionLink: 订阅链接
        :return:
        """
        global hotOpt
        # 公示分发结果
        if AttentionLink.strip() != '':
            easygui.enterbox(msg=v_success, title=TITLE, default=AttentionLink)
            hotOpt += 1
        try:
            # 获取成功
            if 'http' in AttentionLink:
                # 自动复制
                pyperclip.copy(AttentionLink)
                # 将数据存入本地文件
                save_flow(AttentionLink, task_name)
            # 获取异常
            else:
                easygui.exceptionbox(msg=v_msg +
                                     '\n服务器维护中,请稍后再试;\n请勿频繁请求,您的操作权限可能已被冻结',
                                     title=TITLE)

        finally:
            # 返回主菜单
            self.Home()
 def ask_file(self):
     try:
         data_file = easygui.fileopenbox(
             "Open a file with 3 colums and delimeter ;")
         data = open(data_file, "r", encoding='UTF-8')
         raw_data = data.readlines()
         x_axis = []
         y_axis = []
         z_axis = []
         for list_of_strings in range(0, len(raw_data)):
             data_too_graph = raw_data[list_of_strings].split(";")
             x_axis.append(float(data_too_graph[0]))
             y_axis.append(float(data_too_graph[1]))
             z_axis.append(float(data_too_graph[2]))
         self.graphicsView.plot(z_axis,
                                pen=python_graph_plotter.mkPen('r',
                                                               width=1))
         self.graphicsView.plot(y_axis,
                                pen=python_graph_plotter.mkPen('y',
                                                               width=1))
         self.graphicsView.plot(x_axis,
                                pen=python_graph_plotter.mkPen('g',
                                                               width=1))
     except:
         easygui.exceptionbox()
Exemple #17
0
 def clean_data(self):
     print('Begin to clean data...\n')
     file = self.cleansql
     ret = self.ConnDB.cmd(self.db, "mysql", file)
     if ret == 0:
         easygui.msgbox(msg="Import Over", image=self.img)
     else:
         easygui.exceptionbox("Clean Data Failed")
def out_flow(dataFlow, reFP=''):
    try:
        with open(SYS_LOCAL_aPATH, 'w', encoding='utf-8', newline='') as f:
            writer = csv.writer(f)
            for x in dataFlow:
                writer.writerow(x)
    except PermissionError:
        easygui.exceptionbox(
            '系统监测到您正在占用核心文件,请解除该文件的资源占用:{}'.format(SYS_LOCAL_aPATH))
Exemple #19
0
def secimekrani():
    try:
        yemek = easygui.choicebox(msg="Seçim yapın.", title="Seçim Ekranı", choices=obf.Meals.meals)
    except:
        easygui.exceptionbox()

    try:
        easygui.codebox(msg="Tarife göz atın.", title="Tarif Ekranı", text=obf.Recipes.recipes[str(yemek[:4])])
    except:
        easygui.exceptionbox()
Exemple #20
0
def out_flow(dataFlow, reFP=''):
    global SYS_LOCAL_aPATH
    SYS_LOCAL_aPATH = os.path.join(easygui.diropenbox('选择保存地址', TITLE), 'AirportURL.csv')
    try:
        with open(SYS_LOCAL_aPATH, 'w', encoding='utf-8', newline='') as f:
            writer = csv.writer(f)
            for x in dataFlow:
                writer.writerow(x)
    except PermissionError:
        easygui.exceptionbox('系统监测到您正在占用核心文件,请解除该文件的资源占用:{}'.format(SYS_LOCAL_aPATH))
Exemple #21
0
def main():
    try:
        filename = sys.argv[1]
    except:
        filename = easygui.fileopenbox()
    if filename:
        try:
            hexview_file(filename, msg='File: %s' % filename)
        except:
            easygui.exceptionbox(msg='Error:', title='ezhexviewer')
Exemple #22
0
def main():
    try:
        filename = sys.argv[1]
    except:
        filename = easygui.fileopenbox()
    if filename:
        try:
            hexview_file(filename, msg='File: %s' % filename)
        except:
            easygui.exceptionbox(msg='Error:', title='ezhexviewer')
Exemple #23
0
def getplanets():
    
    try:
        s=""
        for planet in app.v["planets"]:
            s += " "+str(planet.x())+"|"+str(planet.y())+"|"+planet.file+"|"+planet.name+"|"+str(planet.g)+"|"+str(planet.d)+"|"+planet.tmp
        
        return s
    except:
        easygui.exceptionbox()
def timesheet():
    try:
        OUTLOOK_FORMAT = '%m/%d/%Y %H:%M'
        outlook = Dispatch("Outlook.Application")
        ns = outlook.GetNamespace("MAPI")

        appointments = ns.GetDefaultFolder(9).Items

        # Restrict to items in the next 30 days (using Python 3.3 - might be slightly different for 2.7)
        begin = datetime.date.today()
        end = begin + datetime.timedelta(days=30)
        restriction = "[Start] > '" + begin.strftime(
            "%m/%d/%Y") + "' AND [End] < '" + end.strftime("%m/%d/%Y") + "'"
        #    restrictedItems = appointments.Restrict(restriction)

        #appointments.Sort("[Duration]")
        appointments.IncludeRecurrences = "True"

        # Iterate through restricted AppointmentItems and print them
        calcTableHeader = ['Title', 'Organizer', 'Start', 'Duration(Minutes)']
        calcTableBody = []

        #pdb.set_trace()
        for appointmentItem in appointments:
            row = []
            row.append(appointmentItem.Subject)
            row.append(appointmentItem.Organizer)
            row.append(appointmentItem.Start.Format(OUTLOOK_FORMAT))
            row.append(appointmentItem.Duration)
            calcTableBody.append(row)

        df = pd.DataFrame(calcTableBody, columns=calcTableHeader)
        dir_ = os.getcwd()
        speak.Speak("Please Enter the filename to save")

        file_name = easygui.textbox(msg='Please enter filename to save:',
                                    title='Time_sheet').split()[0]
        #    file_name = input("Please enter filename to save: ")
        #    resultsfile = open(dir_+'\\'+str(file_name)+'.csv','w',encoding="utf-8")
        #        if not os.path.exists(mail_dir+'\\'+str(file_name)):
        #            os.mkdir(mail_dir+'\\'+str(file_name))

        filepath = mail_dir + '\\' + str(file_name) + '.csv'
        df.to_csv(filepath)
        #    print('your Timesheet saved '+str(filepath))
        speak.Speak("your timesheet saved in the following path")

        easygui.msgbox(msg='your Timesheet saved ' + str(filepath),
                       title='Timesheet prepared')
        return filepath
    except Exception as e:
        speak.Speak(
            'Sorry My mistake please provide your feedback regarding this error'
        )
        easygui.exceptionbox(str(e))
def timesheet_with_graph_for_specificDay():
    try:
        filepath = timesheet()
        speak.Speak("Please Enter the date for which you want your analysis")

        date = easygui.textbox(msg='Enter the date (dd-mm-yyyy):',
                               title='Time sheet with graph')
        #    filepath='D:\karparthy\yy.csv'

        #    sns.set_style('whitegrid')
        current_dir = os.getcwd()
        filepath = r'' + filepath
        print(filepath)
        date = parse(date).date()
        df = pd.read_csv(filepath, encoding="ISO-8859-1")
        #    df.columns
        speak.Speak("Please Enter the filename to save")

        file_name = easygui.textbox(msg='Please enter filename to save:',
                                    title='Time_sheet_with_graph').split()[0]

        #    file_name=input('Enter name of the directory to save')

        if not os.path.exists(current_dir + '\\' + str(file_name)):
            os.mkdir(current_dir + '\\' + str(file_name))

        df['Start_date'] = pd.DatetimeIndex(df['Start']).date
        df.set_index(df['Title'], inplace=True)
        df = df[df['Start_date'] == date]
        #    os.chmod(current_dir+'\\'+str(file_name)+'\\',777)

        #    df['Start']=

        #    df=df[df['Start']==]
        fig, ax = plt.subplots()
        # the size of A4 paper
        fig.set_size_inches(10, 5)
        sns.barplot(df['Duration(Minutes)'], df.index, data=df)
        plt.savefig(current_dir + '\\' + str(file_name) + '\\' +
                    str('Time_spent_meeting') + '.png',
                    format='png')
        print('file saved to ' +
              str(current_dir + '\\' + str(file_name) + '\\' +
                  str('Time_spent_meeting') + '.png'))
        speak.Speak("File saved master")

        easygui.msgbox(msg='file saved to ' +
                       str(current_dir + '\\' + str(file_name) + '\\' +
                           str('Time_spent_meeting') + '.png'),
                       title='Timesheet with graph prepared')
    except Exception as e:
        speak.Speak(
            'Sorry My mistake please provide your feedback regarding this error'
        )
        easygui.exceptionbox(str(e))
def amazon_products():
    try:
        query_string = str(
            easygui.textbox(msg='Enter the product name ',
                            title='Getting Amazon products '))
        getSearchPage(query_string)
    except Exception as e:
        speak.Speak(
            'Sorry My mistake please provide your feedback regarding this error'
        )
        easygui.exceptionbox(msg=str(e), title='sorry for the inconvenince')
 def insertScore():
     try:
         fieldNames = ["Student ID:", "Course ID:", "Score:"]
         values = []
         values = easygui.multenterbox("Enter Info:", "Update Score",
                                       fieldNames)
         data = self.Fun.insertGrade(values[0], values[1],
                                     int(values[2]), sel)
         messagebox.showinfo(message="Successful!", title='Success')
     except:
         easygui.exceptionbox()
Exemple #28
0
def INIT_USER_AGENT():
    """
    将伪装请求头文件写入系统缓存,不执行该初始化步骤 fake-useragent库将发生致命错误
    :return:
    """
    import tempfile
    if 'fake_useragent_0.1.11.json' not in os.listdir(tempfile.gettempdir()):
        os.system('copy {} {}'.format(
            ROOT_DATABASE + '/fake_useragent_0.1.11.json',
            tempfile.gettempdir() + '/fake_useragent_0.1.11.json'))
        easygui.exceptionbox('>>> 环境初始化成功,请重启脚本', TITLE)
        sys.exit()
 def getDismiss(self):
     try:
         data = self.Fun.getTobeDismissed()
         result = "  id   name"
         if data:
             for each in data:
                 result += "\n" + "  ".join(each)
         else:
             result = "None"
         easygui.codebox(msg="Results:", title="Result", text=result)
     except:
         easygui.exceptionbox()
Exemple #30
0
 def save_ppsd(self, file_=None):
     if self.ppsd == None:
         msgbox('No PPSD to save.')
         return
     if file_ == None:
         file_ = easygui.filesavebox(default=def_save_data,
                                    filetypes=['*.pickle', '*.*'])
     if file_ != None:
         try:
             self.ppsd.save(file_)
         except:
             exceptionbox("Error while writing file_!")
Exemple #31
0
 def save_ppsd(self, file_=None):
     if self.ppsd == None:
         msgbox('No PPSD to save.')
         return
     if file_ == None:
         file_ = easygui.filesavebox(default=def_save_data,
                                     filetypes=['*.pickle', '*.*'])
     if file_ != None:
         try:
             self.ppsd.save(file_)
         except:
             exceptionbox("Error while writing file_!")
def journal_downloading():
    try:
        #        import arxivpy
        #import easygui
        #from docx import Document
        #from docx.shared import Inches
        #import os

        topic = str(
            easygui.textbox(msg='Enter the topic you want the paper ?'))
        print(topic)
        max_ind = 10
        articles = query(search_query=topic,
                         start_index=0,
                         max_index=max_ind,
                         results_per_iteration=100,
                         wait_time=5.0,
                         sort_by='lastUpdatedDate')  # grab 200 articles

        print(articles)

        document = Document()
        #        directory=os.getcwd()
        #        directory=directory+'\Journals_abstract'
        if not os.path.exists(jourdir):
            os.mkdir(jourdir)

        document.add_heading(topic, 0)
        for dictionary in articles:
            document.add_heading(dictionary.get('title'), 0)
            p = document.add_paragraph(dictionary.get('abstract'))
            adding_break = p.add_run()
            adding_break.add_break()
            p.add_run(' main_author: ' +
                      str(dictionary.get('main_author'))).bold = True
            adding_break = p.add_run()
            adding_break.add_break()
            p.add_run(' published_date: ' +
                      str(dictionary.get('publish_date'))).bold = True
            adding_break = p.add_run()

            adding_break.add_break()
            p.add_run(' pdf_url: ' +
                      str(dictionary.get('pdf_url'))).italic = True
            adding_break = p.add_run()

            adding_break.add_break()
        document.save(jourdir + '\\' + str(topic) + '_abstract.docx')
    except Exception as e:
        speak.Speak(
            'Sorry My mistake please provide your feedback regarding this error'
        )
        easygui.exceptionbox(msg=str(e), title='sorry for the inconvenince')
Exemple #33
0
def ask_file():
    try:
        data_file = easygui.fileopenbox(
            "Open a file with 3 colums and delimeter ;")
        data = open(data_file, "r", encoding='UTF-8')
        os.chdir(easygui.diropenbox("Place to Savew Graphs"))
        raw_data = data.readlines()
        x_axis = []
        y_axis = []
        z_axis = []
        for list_of_strings in range(0, len(raw_data)):
            data_too_graph = raw_data[list_of_strings].split(";")
            x_axis.append(int(data_too_graph[0]))
            y_axis.append(int(data_too_graph[1]))
            z_axis.append(int(data_too_graph[2]))
        plot_system.rc('grid', linestyle="-", color='black')

        plot_system.plot(x_axis, linewidth=2, markersize=12, color='green')
        plot_system.savefig('x_axis_no_grid.png')
        clear_graph()
        plot_system.grid(True)
        plot_system.plot(x_axis, linewidth=2, markersize=12, color='green')
        plot_system.savefig('x_axis_grid.png')
        clear_graph()
        plot_system.plot(y_axis, linewidth=2, markersize=12, color='red')
        plot_system.savefig('y_axis_no_grid.png')
        clear_graph()
        plot_system.plot(y_axis, linewidth=2, markersize=12, color='red')
        plot_system.grid(True)
        plot_system.savefig('y_axis_grid.png')
        clear_graph()
        plot_system.plot(z_axis, linewidth=2, markersize=12, color='yellow')
        plot_system.savefig('z_axis_no_grid.png')
        clear_graph()
        plot_system.grid(True)
        plot_system.plot(z_axis, linewidth=2, markersize=12, color='yellow')
        plot_system.savefig('z_axis_grid.png')
        clear_graph()
        plot_system.plot(z_axis, linewidth=2, markersize=12, color='yellow')
        plot_system.plot(y_axis, linewidth=2, markersize=12, color='red')
        plot_system.plot(x_axis, linewidth=2, markersize=12, color='green')
        plot_system.savefig('all_togeter_no_grid.png')
        clear_graph()
        plot_system.grid(True)
        plot_system.plot(z_axis, linewidth=2, markersize=12, color='yellow')
        plot_system.plot(y_axis, linewidth=2, markersize=12, color='red')
        plot_system.plot(x_axis, linewidth=2, markersize=12, color='green')
        plot_system.savefig('all_togeter_grid.png')
        clear_graph()

    except:
        easygui.exceptionbox()
 def save_file(self):
     try:
         exporter = python_graph_plotter.exporters.ImageExporter(
             self.graphicsView.plotItem)
         # set export parameters if needed
         exporter.params.param('width').setValue(
             self.centralwidget.width(), blockSignal=exporter.widthChanged)
         exporter.params.param('height').setValue(
             self.centralwidget.height(),
             blockSignal=exporter.heightChanged)
         # save to file
         exporter.export(easygui.filesavebox("Save Graph"))
     except:
         easygui.exceptionbox()
Exemple #35
0
 def save_data(self, file=None): #@ReservedAssignment
     if self.st == None:
         msgbox('No stream to save.')
         return
     if file == None:
         file = easygui.filesavebox(msg='Please omit file ending.', default=def_save_data) #@ReservedAssignment
     if file != None:
         try:
             if self.ui.check_save.isChecked():
                 self.st.write(file, 'Q')
             else:
                 self.st.select(expr='st.mark==False').write(file, 'Q')
         except:
             exceptionbox("Error while writing file!")
Exemple #36
0
 def save_rf(self, file=None): #@ReservedAssignment
     if self.st3 == None:
         msgbox('No stream to save.')
         return
     if file == None:
         file = easygui.filesavebox(default=def_save_rf) #@ReservedAssignment
     if file != None:
         try:
             if self.ui.check_save.isChecked():
                 self.st3.write(file, 'Q')
             else:
                 self.st3.select(expr='st.mark==False').write(file, 'Q')
         except:
             exceptionbox("Error while saving file!")
 def getstu():
     mode = sel.get()
     value = key.get()
     try:
         data = self.Fun.getStuInfo(value, mode)
         if data:
             result = '   id     name   dept   gender birthday'
             for each in data:
                 result += "\n" + "  ".join(each)
         else:
             result = "None"
         easygui.codebox(msg="Results:", title="Result", text=result)
     except:
         easygui.exceptionbox()
Exemple #38
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)
Exemple #39
0
 def open_ppsd(self, file_=None):
     if file_ == None:
         file_ = easygui.fileopenbox(default=def_open,
                                    filetypes=['*.pickle', '*.*'])
     if file_ != None:
         try:
             with open(file_) as f:
                 self.ppsd = pickle.load(f)
         except:
             exceptionbox("Error while reading file!")
         else:
             self.ui.pbar.setValue(0)
             self.ui.button.setText('Add')
             self.ui.project.setEnabled(True)
             self.ui.station.setEnabled(True)
             self.ui.component.setEnabled(True)
             self.data = None
             self.daystream = None
             self.date = self.startdate
Exemple #40
0
 def open_data(self, file=None): #@ReservedAssignment
     if file == None:
         file = easygui.fileopenbox(default=def_open, filetypes=['*.QHD', '*.*']) #@ReservedAssignment
     if file != None:
         try:
             self.st_all = read(file)
         except:
             exceptionbox("Error while reading file!")
         if self.st_all[0].stats.event.get('id') == None:
             for tr in self.st_all:
                 tr.stats.event['id'] = str(tr.stats.event.eventno)
         self.handmarked = []
         self.handunmarked = []
         self.st_all.downsample2(self.ui.spin_downsample.value())
         self.st_all.trim2(-50, 300)
         self.st_all.sort(self.sort_after.split(','))
         self.st_all.check()
         self.st_all.setHI('mark', False)
         #self.slice_changed(self.ui.edit_slice.text())
         #self.update_raw()
         self.st_all_old = self.st_all
         self.update_rf()
# coding:utf-8

#    __author__ = 'Mark sinoberg'
#    __date__ = '2016/5/25'
#    __Desc__ = 这是一个很好用的对话框,当应用程序出现异常的时候,就可以通过这个来给与用户友好的界面提示

import easygui

try:
    int('Exception')
except:
    easygui.exceptionbox('int类型数据转换错误!请检查您的数据类型!')

# 会弹出一个界面,内容信息可以自己定义,如上面。下面的内容就是追踪到的出错信息
# Traceback (most recent call last):
#   File "E:/Code/Python/MyTestSet/easygui_/exceptionbox.py", line 10, in <module>
#     int('Exception')
# ValueError: invalid literal for int() with base 10: 'Exception'
        g.msgbox('you choose the game1 is the best one!')
    if str(goodgame) == 'game2':
        g.msgbox('you choose the game2 is the best one!')
    if str(goodgame) == 'game3':
        g.msgbox('you choose the game3 is the best one!')

    index1 = g.indexbox('indexboxtest','indexibox',('yes','no'))
    if index1 == 0:
        g.msgbox('indexbox choose yes')
    if index1 == 1:
        g.msgbox('indexbox choose no')
        

    a = g.multchoicebox('multchoicebox test','multchoicebox',['game1','game2','game3','game4'])
    if a == None:
        print(a)
        a = ['meiyou']
        print(type(a))
    try:
        b = list(g.multchoicebox('multchoicebox test','multchoicebox',a))
    except:
        g.exceptionbox()
    
    
    if g.ccbox('continue the game?','please choose'):
        pass
    else:
        sys.exit(0)

input('please input any key to continue:')
import easygui as eg
import os

campos = [' Url de la página:',' Nombre Archivo:']
entrada = []
entrada = eg.multenterbox(msg='Convertir página web en archivo PDF', title='www.toString.es', fields=campos, values=())
final = ''

if entrada != None:
	try:
		for c, e in zip(campos,entrada):
			os.system("wkhtmltopdf -s Letter " + e[0] + " " + e[1])
			final = final + c + ' ' + e + '\n'
				
		eg.msgbox(final, 'multenterbox', ok_button='Salir')
	except:

		eg.exceptionbox("No es posible convertir a PDF", "Error")

Exemple #44
0
SIZE_THRESHOLD i
SYNC_DELTA i 
SHARE_HIDDEN b
PORT i"""

if __name__ == '__main__':
    import sys
    base_dir = op.dirname(op.abspath(__file__))
    sys.path.insert(0,base_dir) 

    import easygui as eg
    configdb = shelve.open(config_file,'c')
    try:
        set_config(configdb)
    except:
        eg.exceptionbox()
    finally:
        configdb.close()
else:
    db = shelve.open(config_file,'r')
    for line in NAMES.splitlines():
          res = line.strip().split(" ")
          res =[ r.strip() for r in res if r.strip() != "" ]  
          if len(res) == 2:
            name,type_ = res
          else:
            name = line.strip()
            type_ = None
     
          if name not in db:
            raise Exception("The config file is incomplete,\n\
Exemple #45
0
  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()

# --------------------------------------------------------------------
Exemple #46
0
 def select_stream(self):
     selection = easygui.enterbox(msg='Select - use st for trace.stats:', default='225 < st.azi < 265.7')
     try:
         self.st_all = self.st_all_old.select(expr=selection)
     except:
         exceptionbox("Error while selecting!")
tracks = eg.codebox(msg="Paste track list:", title="Album Splitter", text="")

#More formats can be added
if format == "<start time> - <title>":
    with open("tracks.txt", 'w') as t:
        t.write(tracks)
if format == "<start time> <title>":    
    tracks = tracks.split('\n')
    regex = re.compile("(\d*\s\-\s)*(?P<start>\S+)\s*(?P<title>.+)")
    for i in range(len(tracks)):
        if tracks[i] != "":
            m = regex.match(tracks[i])
            tStart = m.group('start').strip()
            tTitle = m.group('title').strip()
            tracks[i] = tStart + " - " + tTitle
    with open("tracks.txt", "w") as t:
        t.write("\n".join(tracks))

try:
    cmd = "python split.py " + link
    print(cmd)
    out = os.system(cmd) #I couldn't get this to work any other way, unfortunately.
    #print(out)
    #subprocess.call(("python split.py " + link))
    #out_str = subprocess.check_output(cmd, shell=True)
    #subprocess.Popen(cmd, shell=True)

except:
    eg.exceptionbox(msg="Album Splitter has crashed", title="Album Splitter") #This doesn't actually do anything due to the way the splitter program is currently launched.
            #TODO: Handle cancel
             
            msg = "Choose Resdiual Output Filename"
            title = "Resdiual Output"
            eg.msgbox(msg, title)
            msg = ""
            default_filename = "residuals"
            resid_directory = eg.filesavebox(msg, title, default=default_filename, filetypes=['*.csv'])
            #TODO: Handle cancel

            """
            Regression Loop
            """

            fr.fast_regression(regressors_path,predictors_path,resid_directory, plots_directory)

            eg.msgbox("Regressions Complete \n Residuals written to " + 
                        resid_directory + ".csv\n Plots written to " + plots_directory)
        except:
            #catch-all for exceptions
            message =   """An error has occured. Please double check the following: \n
                            There should be no trailing empty cells in the regresor or predictor .csv files \n
                            There can be no repeated column names in theses files\n
                            There can be no spaces or special charagers in the column names of these files \n
                            Row labels must be the same for bothe the regressor and predictor .csv files\n\n
                            Please see the Help file for more formatting information"""
            eg.exceptionbox(message, "Error")

        sys.exit(0)