Beispiel #1
1
def exercise4():
    """Display files with line numbers until the user clicks Cancel."""
    # TODO 4b: Write code to use the print_file function as described in the lab document.
    file_name = easygui.fileopenbox( default="./data/*.txt")
    while len(file_name) > 1:
        print_file( file_name )
        file_name = easygui.fileopenbox( default="./data/*.txt" )
Beispiel #2
1
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()
Beispiel #3
1
def exercise2():
    """Uses the specified function as described in the lab document."""
    # Get the first file name before testing the loop condition.
    filename = easygui.fileopenbox( default="./data/*.txt", title="Character Frequency - File Open" )
    # A valid filename (i.e., user did not click Cancel) is longer than one character.
    while len( filename ) > 1:
        # Read the contents of the file as a string.
        with open( filename ) as data_file:
            data = data_file.read()
        # Show a message box with the base file name and letter frequency.
        char = "e"
        easygui.msgbox( "Frequency of the character '{}' in {}: {:.2%}.".format(
            char, os.path.basename( filename ), character_frequency( char, data ) ), "Character Frequency - Result" )
        # Get another file name before testing the loop condition.
        filename = easygui.fileopenbox( default="./data/*.txt", title="Character Frequency - File Open" )
def main():
    
    def process_test(test):
        answer_match = string_find(regexes[1], test)
        if answer_match:
            answer_key = [x[1] for x in answer_match]
            test = string_replace(regexes[0], "A) True\nB) False\n", test)
            for regex in regexes[1:]:
                test = string_replace(regex, '', test)
            print test
            format_answers(answer_key)
            
    def string_find(pattern, string):
        return re.findall(pattern, string, flags=re.I | re.X)            

    def string_replace(pattern, string_old, string_new):
        return re.sub(pattern, string_old, string_new, flags=re.I | re.X)

    def format_answers(answers):
        print 'Answers:'
        number = 0
        for answer in answers:
            number += 1          
            answers = string_replace(regexes[3], "", str(number) + '.' + answer.replace(":", ""))
            print string.capwords(answers)
            
    msg = "This program will attempt to format a test file for use with Respondus, Do you want to continue?"
    title = "Respondus Format Utility version 1.5 Beta"
    if easygui.ccbox(msg, title):
        pass
    else:
        sys.exit(0)        
    try:
        sys.stdout = open(easygui.filesavebox(msg='Before we begin choose where to save your formatted test file?',
                                          default='formatted_test.txt'), 'w')      
    except TypeError:
        sys.exit(-1) 
    file_choice = easygui.indexbox(msg="Choose the file type of your test file (Note: Word is very experimental)",
                                   choices=("Plain text file (.txt)", "Word 2007, 2010 file (.docx)", "Quit"))
    if file_choice is 0:
        input_file = easygui.fileopenbox(msg='Where is the test file to format?')
        try:
            with open(input_file) as inputFileHandle:
                process_test(inputFileHandle.read().replace("\n", "\n\n"))
        except (TypeError, IOError):
            sys.stderr.write('Could not open %s\n' % input_file)
            sys.exit(-1)
    elif file_choice is 1:
        try:
            with zipfile.ZipFile(easygui.fileopenbox(msg='Where is the test file to format?')) as docx:                
                process_test(re.sub('<(.|\n)*?>', '\n', docx.read('word/document.xml')))                             
        except (TypeError, AttributeError, IOError):
            sys.stderr.write('Could not open %s\n' % zipfile)
            sys.exit(-1)  
    else:
        sys.exit(0)
    easygui.msgbox("Format complete!", ok_button="Close", image="tick_64.png")
    sys.stdout.flush()
    sys.stdout.close()
Beispiel #5
0
def exercise4():
    """Uses the specified function as described in the lab document."""
    # TODO 4: Write code to use the function as described in the lab document.
    filename = easygui.fileopenbox(default="./data/*.txt", title="TOr13 - File Open")
    while len(filename) > 1:
        rot13_filename = filename[:filename.rfind(".") ] + "_rot13.txt"
        with open(filename) as data_file, open(rot13_filename, "w") as rot13_file:
            rot13_file.write(rot13(data_file.read()))
        filename - easygui.fileopenbox(default= "./dara/*.txt", title = "ROT13 - File Open")
Beispiel #6
0
def parse_shazams():
        """Parses shazam history, and returns a list of track dictionaries"""

        import easygui
        file = easygui.fileopenbox(msg='Select your shazam histor html file', filetypes=['*.html'])
        # file = input("Enter the path to your shazam history html file: ")
        try:
            file = open(file, 'r')
            htmltree = file.read()
            soup = bs4.BeautifulSoup(htmltree, 'html.parser')
            table = soup.find('table')
            table_rows = table.findAll('tr')
            data = []
            for row in table_rows:
                track = {}
                try:
                    cols = row.find_all('td')
                    track["Title"] = cols[0].text.strip()
                    track["TrackID"] = ""
                    track["Artist"] = cols[1].text
                    if not (track in data):
                        data.append(track)
                    print(track)
                except Exception as ex:
                    print(ex)
            print('created list of track dicts')
            return data
        except:
            print('Could not read file. is it html?\n')
            parse_shazams()
Beispiel #7
0
def main():
    """
    Begins the program. Prompts user for image file and then passes this to get_exif function. Only file no directory.
    :return:
    """
    start = easygui.buttonbox(msg="Picture or Folder?", title="Welcome to Where's My Ex! Choose a Picture",
                              choices=["Upload Picture", "Cancel"])
    # if start == "Upload Directory":
    #     file_search = easygui.diropenbox()
    #     directory_list = os.listdir(file_search)
    #     for file in directory_list:
    #         if imghdr.what(file) == "gif" or "jpeg":
    #             get_exif(file)
    #         else:
    #             print("No image detected")
    #             sys.exit()
    if start == "Upload Picture":
        file = easygui.fileopenbox(default="./data/")
        if imghdr.what(file) == 'gif' or 'jpeg':
            get_exif(file)
        else:
            print("No image detected")
            sys.exit()
    elif start == "Cancel":
        sys.exit(0)  # Exit Program
Beispiel #8
0
def load_world(filename = None):
  """Loads a robot world from filename.
  Opens file-chooser if no filename is given."""
  global _scene, _world
  if _scene:
    raise RuntimeError("A robot world already exists!")
  if not filename:
    filename = _easygui.fileopenbox("Select a Robot world", 
                                    "Robot World", '*', [ "*.wld" ])
    if not filename: 
      raise RuntimeError("No world file selected.")
  txt = open(filename, 'rb').read()
  txt = _re.sub('\r\n', '\n', txt) # Windows
  txt = _re.sub('\r', '\n', txt)  # Mac
  _check_world(txt)
  wd = {}
  # extracts avenues, streets, walls and beepers
  try:
    exec txt in wd
    w = _World(wd['avenues'], wd['streets'], wd['walls'], wd['beepers'])
  except:
    raise ValueError("Error interpreting world file.")
  _world = w
  _scene = _g.Canvas()
  _scene.setWidth(50 * w.av)
  _scene.setHeight(50 * w.st)
  i = filename.rfind("/")
  if i >= 0: filename = filename[i+1:]
  _scene.setTitle("Robot World: " + filename)
  _world.create_layer()
  _scene.setAutoRefresh(False)
def Choice_Restore_Pilot():
    #Restore From File
    RestoreFile = easygui.fileopenbox("Select File To Restore From","Select File To Restore From",PilotApp.Settings['EpicorBackupDir'])
    usrpw = GetDSNPassword()
    rightnow = datetime.datetime.now()
    compname =  rightnow.strftime("%B")
    compname = compname[:3]
    compname = '--- TEST ' + compname + str(rightnow.day) + ' ---'
    compname = easygui.enterbox(msg='New Pilot Company Name?',default=compname)
    easygui.msgbox(msg='This will take some time, please wait until you see the main app dialog.')
    #Shutdown Pilot
    PilotApp.Shutdown()
    PilotApp.ShutdownDB()
    PilotApp.Restore(RestoreFile)
    PilotApp.StartupDB(5) #Number of retries
    #Connect to db
    PilotDB = EpicorDatabase(PilotApp.Settings['DSN'],usrpw[0], usrpw[1] );del usrpw
    #Update to Pilot Settings
    PilotDB.Sql("UPDATE pub.company set name = \'" + compname + "\'")
    PilotDB.Sql("UPDATE pub.SysAgent set AppServerURL = \'" + PilotApp.Settings['AppServerURL'] + "\'")
    PilotDB.Sql("UPDATE pub.SysAgent set MfgSysAppServerURL = \'" + PilotApp.Settings['MfgSysAppServerURL'] + "\'")
    PilotDB.Sql("UPDATE pub.SysAgent set FileRootDir = \'" + PilotApp.Settings['FileRootDir'] + "\'")
    #Remove Global Alerts / Task Scheduler
    PilotDB.Sql("UPDATE pub.glbalert set active=0 where active=1")
    PilotDB.Sql("UPDATE pub.chglogGA set SendEmail=0 where SendEmail=1")
    PilotDB.Sql("DELETE from pub.SysAgentTask")
    #Commit changes and close connection
    PilotDB.Commit()
    PilotDB.Close()
    PilotApp.Startup()
Beispiel #10
0
def exercise3():
    """Display file information until the user clicks Cancel."""
    # TODO 3b: Re-write the code below to use the file_info function as described in the lab document.
    # Get the first file name before testing the loop condition.
    filename = easygui.fileopenbox( default="./data/*.txt" )

    # A valid filename (i.e., user did not click Cancel) is longer than one character.
    while len( filename ) > 1:
        # Get the base file name to use as the dialog title, then show the results.
        basename = os.path.basename( filename )

        # Show the entire string returned from the file_info function in the message box.
        easygui.msgbox( file_info( filename ), basename )

        # Get another file name before testing the loop condition.
        filename = easygui.fileopenbox( default="./data/*.txt" )
Beispiel #11
0
def get_file_name():        
    default='C:\dev\projects\ScriptsUtil\data\*.csv'
    msg='Seleccione archivo a procesar'
    title='Procesando archivos para EERR'
    filetypes=["*.csv",]
    file = fileopenbox(msg,title,default,filetypes)
    print(file)
Beispiel #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()
def generateSplicePattern():
    filename=easygui.fileopenbox(filetypes=['*.csv'])
    df=pd.read_csv(filename)

    grouped=df.groupby('sentID')
    #rezDf=pd.DataFrame({'fileA','fileB'})
    count=0
    for k, gp in grouped:
        curSubTable=grouped.get_group(k)
        #keep Context Test
        val1=curSubTable['filename'][(curSubTable['keepCont']==1)]
        #splice test
        val2=curSubTable['filename'][(curSubTable['splice']==1)]
        if count<1:
            res=pd.DataFrame({'fileA':val1.values,'fileB':val2.values})
        else:
            curRow=pd.DataFrame({'fileA':val1.values,'fileB':val2.values})
            res=res.append(curRow)
        count+=1

    res=res.reset_index(drop=True)
    ##Remove '.wav'
    res['fileA']=res['fileA'].apply(lambda x: re.sub(r'\.wav','',x))
    res['fileB']=res['fileB'].apply(lambda x: re.sub(r'\.wav','',x))
    #res['outputFilename']=res.fileB.str.cat('_spliced',sep='')
    res['fileR']=res['fileB'].apply(lambda x: re.sub(r'\.wav','',x)+'_spliced')
    return res
	def analyze(self,igroup):
		database=self.gettmpdata('database');
		spectra=database[0]['resultdatatablegroups'][igroup];
		spectranew=spectra.getemptyinstance();
		
		fullfilechosen=easygui.fileopenbox('Please choose a file external standard','Opeing a file...',"*");
		if fullfilechosen is not None:
			spectstandard=EMWSpectrum(fullfilechosen);
			spectstandard.import_();
			
			spectstandard['xunit'].setcurrentunit("cm_1");
			spectra.plot();
			spectstandard.plot();
			xmin=float(self['xminstr'].get());
			xmax=float(self['xmaxstr'].get());
				
			for k in spectra.keys():
				self.stdout(("k:",k));
				spect=spectra[k];
				spectnew=spect.copyxy();
				spectnew.renorm(spectstandard,xmin,xmax,self['gainorshift'].get());
				spectnew.log({"Operation":"renorm","spectstandard":fullfilechosen,"xmin":xmin,"xmax":xmax,"gainorshift":self['gainorshift'].get()});
				spectranew.insert(spectnew,k);
			
			spectra=database[0]['resultdatatablegroups'][igroup]=spectranew;
			spectranew.plot('o');
				#spectra=resultdatagrouped[0]['datagroups'][igroup]=spectranew;
				#spectranew.plot();
			
Beispiel #15
0
def main():

    filename = easygui.fileopenbox()
    filename = os.path.basename(filename)
    metricsReader = MetricsReader(os.path.dirname(os.getcwd()) +'/'+ (filename))
    metricsReader.fill_dictionary()
    print(metricsReader.metrics_lines[0])
Beispiel #16
0
def exercise3():
    """Display file information until the user clicks Cancel."""
    # TODO 3b: Write code to use the file_info function as described in the lab document.
    file = easygui.fileopenbox( default="./data/*.txt")
    with open( file ) as data_file:
        count_file = file_info(data_file.read())
    easygui.msgbox( "{}". format( count_file ))
Beispiel #17
0
def main():
    db_name = 'pymongo_GridFS_test'
    collection_name = 'fs'

    client = pymongo.MongoClient(host = 'localhost', port = 27017)
    db = client[db_name]
    db.drop_collection(collection_name)

    # GridFS put test
    file_to_put = easygui.fileopenbox(
        msg = 'Select the file you want to put into GridFS:')
    if file_to_put:
        file_id, md5_digest = put_test(client, db, collection_name, file_to_put)
        if file_id:
            easygui.msgbox(
                msg = '"put" successfully!\nMD5: {}'.format(md5_digest),
                title = 'Congratulations!')
        else:
            easygui.msgbox(
                msg = 'Failed to "put"!', title = 'Error!')
            return

    # GridFS get test
    name, ext = os.path.splitext(os.path.basename(file_to_put))
    file_to_save = easygui.filesavebox(
        msg = 'Where do you want to save this file:',
        default = name + '_get_from_GridFS' + ext)
    if file_to_save:
        if get_test(client, db, collection_name, file_id, file_to_save):
            easygui.msgbox(
                msg = '"get" successfully!', title = 'Congratulations!')
        else:
            easygui.msgbox(msg = 'Failed to "get"!', title = 'Error!')

    client.drop_database(db_name)
Beispiel #18
0
 def question1(self, msg, title):
     '''
     questions1: Select file from dropdown
     :return: string
     '''
     filetypes = "*.*"
     file = eg.fileopenbox(title, msg, filetypes=filetypes)
     return file
Beispiel #19
0
 def __init__(self):
     super().__init__()
     tessname = easygui.fileopenbox(msg="Tess File", title="Horizon Tess/QB Compare", default="*.xlsx")
     self.__tessWB = load_workbook(tessname, read_only=True)
     qbname = easygui.fileopenbox(msg="QB File", title="Horizon Tess/QB Compare", default="*.xlsx")
     self.__qbWB = load_workbook(qbname, read_only=True)
     self.tessWS = self.__tessWB[easygui.choicebox(msg="Which Sheet for Tessetura?",
                                                   title="Horizon Tess/QB Compare",
                                                   choices=self.__tessWB.get_sheet_names())]
     self.qbWS = self.__qbWB[easygui.choicebox(msg="Which Sheet for QB?",
                                               title="Horizon Tess/QB Compare",
                                               choices=self.__qbWB.get_sheet_names())]
     self.tessHead = []
     x = 1
     while x <= self.tessWS.max_column:
         cell = self.tessWS.cell(row=1, column=x)
         if cell.value is not None:
             self.tessHead.append([x, cell.value])
             print(cell.value)
         x += 1
     self.qbHead = []
     x = 1
     while x <= self.qbWS.max_column:
         cell = self.qbWS.cell(row=1, column=x)
         if cell.value is not None:
             self.qbHead.append([x, cell.value])
             print(cell.value)
         x += 1
     self.tessCust = ast.literal_eval(easygui.choicebox(msg="Customer ID in Tessetura?",
                                       title="Horizon Tess/QB Compare",
                                       choices=self.tessHead))
     self.qbCust = ast.literal_eval(easygui.choicebox(msg="Customer ID in QB?",
                                       title="Horizon Tess/QB Compare",
                                       choices=self.qbHead))
     self.tessDate = ast.literal_eval(easygui.choicebox(msg="Transaction Date in Tessetura?",
                                       title="Horizon Tess/QB Compare",
                                       choices=self.tessHead))
     self.qbDate = ast.literal_eval(easygui.choicebox(msg="Transaction Date in QB?",
                                       title="Horizon Tess/QB Compare",
                                       choices=self.qbHead))
     self.tessMoney = ast.literal_eval(easygui.choicebox(msg="Money Amount in Tessetura?",
                                       title="Horizon Tess/QB Compare",
                                       choices=self.tessHead))
     self.qbMoney = ast.literal_eval(easygui.choicebox(msg="Money Amount in QB?",
                                       title="Horizon Tess/QB Compare",
                                       choices=self.qbHead))
Beispiel #20
0
    def file_open(self):
        extension = ["*.py", "*.pyc"]
        archivo = eg.fileopenbox(msg="Abrir archivo",
                                 title="Control: fileopenbox",
                                 default='',
                                 filetypes=extension)

        eg.msgbox(archivo, "fileopenbox", ok_button="Continuar")
        return archivo
Beispiel #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')
def changeSettings():
	easygui.msgbox("Choose your favorite Media Player. This can be changed later", "Ashwin's Badass Simpsons Player")
	playerpath = easygui.fileopenbox(msg="Choose your favorite Media Player", \
									 title="Ashwin's Badass Random Simpsons Player")
	
	if not playerpath:
		sys.exit(0)

	save(playerpath, "UserSettings.SIMPSONS")
	easygui.msgbox("Your new settings have been changed", "Ashwin's Badass Random Simpsons Player")
 def chooseImageFunction(self):
     path = easygui.fileopenbox()
     if path != '.':
         print('imagePath', path)
         myPixmap = QtGui.QPixmap(path)
         #myScaledPixmap = myPixmap.scaled(self.labelImage.size(), QtCore.Qt.KeepAspectRatio)
         self.labelImage.setPixmap(myPixmap)
         #self.tab.setPixmap(myScaledPixmap)
         print('OTVORENA SLIKA')
         self.labelTest.setText(_translate("MainWindow", "opened image", None))
         self.tabMainTab.setStyleSheet('QTabBar::tab {background-color: green;}')       
Beispiel #24
0
    def get_metadata(self):

        def inp_metadata(meta_inp_path):
            mdata = {}

            # Dictionaries to connect string values in JPL metadata to SQL columns
            tags = {'TITLE': 'Name', 'CHEMICAL_NAME': 'chemical_name', 'SHORT_NAME': 's_name',
                    'Q(300.0)': 'Q_300_0', 'Q(225.0)': 'Q_225_0', 'Q(150.0)': 'Q_150_0',
                    'Q(75.00)': 'Q_75_00', 'Q(37.50)': 'Q_37_50', 'Q(18.75)': 'Q_18_75', 'Q(9.375)': 'Q_9_375',
                    'A': 'A', 'B': 'B', 'C': 'C', 'MU_A': 'MU_A',  'MU_B': 'MU_B', 'MU_C': 'MU_C',
                    'CONTRIBUTOR': 'Contributor', 'REF': 'REF'}

            for line in open(meta_inp_path, 'r').read().split('\n'):
                if not line:
                    continue
                if line[0] == '!':
                    continue

                id, value = line.split(':')
                try:
                    mdata[tags[id]] = value.strip()
                except KeyError:
                    if id == 'STATE_ID_IDX':
                        self.STATE_ID_IDX = value.strip()
                    elif id == 'STATE_ID_VAL':
                        self.STATE_ID_VAL = value.strip()
                    else:
                        continue

            mdata['Date'] = time.strftime('%b %Y', time.gmtime())
            return mdata

        metadata = {}

        # Dictionaries to connect string values in JPL metadata to SQL columns
        tags = {'Name:': 'Name', 'Q(300.0)=': 'Q_300_0', 'Q(225.0)=': 'Q_225_0', 'Q(150.0)=': 'Q_150_0',
                'Q(75.00)=': 'Q_75_00', 'Q(37.50)=': 'Q_37_50', 'Q(18.75)=': 'Q_18_75', 'Q(9.375)=': 'Q_9_375',
                'A=': 'A', 'B=': 'B', 'C=': 'C', '$\\mu_a$ =': 'MU_A',  '$\\mu_b$ =': 'MU_B', '$\\mu_c$ =': 'MU_C',
                'Contributor:': 'Contributor'}

        gui_order = ['Name', 'Contributor', 'Q(300.0)=', 'Q(225.0)=', 'Q(150.0)=', 'Q(75.00)=', 'Q(37.50)=', 'Q(18.75)=',
                     'Q(9.375)=', 'A', 'B', 'C', 'mu_A', '$\\mu_a$ =', '$\\mu_b$ =', '$\\mu_c$ =', 'Ref1']

        ent = eg.buttonbox(msg='Would you like to use a metadata input file or input it manually?',
                           choices=['Input file', 'Manual entry'])
        if ent == 'Input file':
            meta_path = eg.fileopenbox(msg='Choose a metadata input file.', title='Metadata input.')
            metadata = inp_metadata(meta_path)
        else:
            meta_temp = eg.multenterbox('Enter metadata', 'Metadata entry', gui_order)
            for i, entry in enumerate(gui_order):
                metadata[entry] = meta_temp[i]

        return metadata
Beispiel #25
0
def send_image():
        image = eg.fileopenbox(title="Pick an image to attach to your tweet")
        message = eg.enterbox(title="Send a tweet", msg="What message would you like to send?")
        try:
                length = len(message)
                if length < 140:
                        api.update_with_media(image, status=message)
                else:
                        eg.msgbox(msg="Your tweet is too long. It is "+str(length)+" characters long")
        except:
                sys.exit()
Beispiel #26
0
 def question2(self):
     '''
     questions2: select sNp files
     :return: list
     '''
     msg = "Please select ALL sNp files you wish to use"
     title = "Select sNp files"
     filetypes = "*.*"
     multiple = True
     files = eg.fileopenbox(msg, title, filetypes=filetypes, multiple=multiple)
     return files
Beispiel #27
0
def main():
    fileopen = easygui.fileopenbox(msg="Selecciona el archivo csv",
     filetypes = ["*.csv"])
    if fileopen is None:
        error("No se selecciono ningun archivo")
    pdf_file = easygui.filesavebox(msg = "Guardar archivo pdf con codigo de barras",
        default ="barcode.pdf", filetypes=["*.pdf"] )
    if pdf_file is None:
        error("No se guardo el archivo")
    genpdf(fileopen,pdf_file)
    easygui.msgbox("Archivo generado")
Beispiel #28
0
def obtain_midi_file():
    """
    Asks user to select MIDI and returns this file opened in binary mode for reading
    """
    file = egui.fileopenbox(msg='Choose MIDI file to convert',
                            title='MIDI file selection',
                            filetypes=[['*.mid', 'MID files']])
    if not file:
        return None
    file = open(file, mode='rb').read()
    return file
	def analyze(self,igroup):
		database=self.gettmpdata('database');
		spectra=database[0]['resultdatatablegroups'][igroup];
		spectranew=spectra.getemptyinstance();
		spectracorrected=spectranew.copy();
		spectra.plot();
		#print "spectranew type:",type(spectranew);
		
		rfilm=float(self['rfilm'].get());
#		wlfix=float(self['wlfix'].get());
		xmin=float(self['xminstr'].get());
		xmax=float(self['xmaxstr'].get());

		fullfilechosen=easygui.fileopenbox('Please choose a file (Ref for opus) to open','Opeing a file...',"*");
		if fullfilechosen is not None:
			extstandard=EMWSpectrum(fullfilechosen);
			extstandard.import_();
			extstandard['xunit'].setcurrentunit("cm_1");
			
			refchosen=easygui.choicebox("choose the reference","calculating ratio",spectra.keys());
			if refchosen is not None:
				spect0=spectra[refchosen];
				filmthickness={};
				for k in spectra.keys():
					self.stdout(k);
					spectnew=spectra[k].copyxy();
					# find out the film thichness first
					specttemp=spectnew.copyxy();
					specttemp.pick(xmin,xmax);
					fthickness=[];
					for x in specttemp['x']:
						yreal300K=extstandard(x);
						wavelength=1e7/x;
						rsample=yreal300K**0.5;
						yratio=spectnew(x)/spectra[refchosen](x);
						ft=m.findfilmthickness(yratio,wavelength,rfilm,rsample);
						fthickness.append(ft);
					filmthickness[k]=mean(fthickness);
					print "filmthickness"
					print fthickness;
					print filmthickness[k]
					# then get the real reflectance
					
					for i in range(len(spectnew['x'])):
						x=spectnew['x'][i];
						wavelength=1e7/x;
						yraw=spectnew(x)/spectra[refchosen](x)*extstandard(x);
						yreal=m.findrsample(yraw,wavelength,filmthickness[k],rfilm);
						spectnew['y'][i]=yreal;
						
					spectranew.insert(spectnew,k);
				XpyFigure();
				spectranew.plot('o');
				database[0]['resultdatatablegroups'][igroup]=spectranew;
Beispiel #30
0
 def load_file(self):
     """
     Callback for the 'Load Image' menu option.
     """
     import easygui
     tmp = easygui.fileopenbox(title = "Choose your file",default="*.npy")
     if tmp:
         try:
             self.file_name = tmp
             self.set_data(load(self.file_name))
         except:
             print 'Loading file failed'
Beispiel #31
0
import xlrd, xlsxwriter, os
import easygui as eg

#=================【第一项步骤】=======================

Path1 = eg.fileopenbox('Please select file', 'open', default='*.xlsx')
print(Path1)

#-(1):【read xlsx】
ticker_dict = {}

work_book = xlrd.open_workbook(Path1)  # (1)打开 文件
sheet_list = work_book.sheet_names()  # (2)读取 工作表 名(全部)
for each_sheet in sheet_list:  # (3)历遍 工作表 名
    sheet = work_book.sheet_by_name(each_sheet)  # (4)读取 工作表 内容
    item_Dict = {}
    num = 0
    for each_rows in range(5):  # (5)找出 两个目标列表
        count = 0
        num += 1
        value_list = sheet.row_values(each_rows)
        for each_value in value_list:
            each_value = str(each_value)
            if 'Acquiror Name' == each_value[each_value.
                                             find('A'):each_value.rfind('e') +
                                             1]:
                item_Dict['Acquiror Name'] = value_list.index(each_value)
                count += 1
            elif 'Target Name' == each_value[each_value.
                                             find('T'):each_value.rfind('e') +
                                             1]:
# 18.2 - Example App: PDF Page Rotator
# Review Exercise #1

import easygui as gui
from PyPDF2 import PdfFileReader, PdfFileWriter

# Ask suser to select a PDF file
open_title = "Select a PDF to rotate..."
file_type = "*.pdf"
input_path = gui.fileopenbox(title=open_title, default=file_type)

# If nothing was returned by gui.fileopenbox(), the user either
# hit cancel or closed the window so we should exit the program.
if input_path is None:
    exit()

# Ask the user by how many degrees each page should be rotated.
# If the user dosn't select anything, keep displaying the
# buttonbox() element until they do.
choices = ("90", "180", "270")
message = "Rotate the PDF clockwise by how many degrees?"
degrees = None
while degrees is None:
    degrees = gui.buttonbox(message, "Choose rotation...", choices)

# Convert the chosen number of degrees to an integer
degrees = int(degrees)

# Ask the user what they would like to call the new PDF and where
# it should be saved.
save_title = "Save the rotated PDF as..."
def button1():
    path = easygui.fileopenbox(default="HOME/Downloads/*.xlsx",
                               filetypes='*.xlsx')
    try:
        workbook = openpyxl.load_workbook(path)
    except Exception as e:
        try:
            workbook = openpyxl.load_workbook(path)
        except Exception as e:
            sg.popup_auto_close('не выбран файл!')
            sg.popup_ok(e)
            workbook = None
        return (workbook)
    #path = easygui.fileopenbox(default= '*.xlsx', filetypes= '*.xlsx')
    path2 = easygui.filesavebox(default="HOME/APPDATA/RPBeta/Egoryevsk.xlsx",
                                filetypes='*.xslx')
    #workbook = openpyxl.load_workbook(path)
    worksheet = workbook["Лист 1"]
    filetypes = ['*.xlsx', "Excel"]
    default = '*'
    worksheet.unmerge_cells('A1:P1')
    worksheet.unmerge_cells('A2:P2')
    worksheet.unmerge_cells('A3:P3')
    worksheet.unmerge_cells('A4:P4')
    worksheet.unmerge_cells('A5:P5')
    worksheet['D4'] = '= SUBTOTAL(9,D10:D119)'
    worksheet['E4'] = '= SUBTOTAL(9,E10:E119)'
    worksheet['G4'] = '= SUBTOTAL(9,G10:G119)'
    worksheet['F4'].number_format = FORMAT_PERCENTAGE_00
    worksheet['H4'].number_format = FORMAT_PERCENTAGE_00
    worksheet['F4'] = '= E4/D4'
    worksheet['H4'] = '= G4/D4'
    worksheet['A4'] = 'ИТОГИ'
    worksheet['G1'] = 'RNISka Reports 1.2.4'
    worksheet['G1'].font = Font(name='Tahoma',
                                size=9,
                                color="FF0000",
                                italic=True)
    worksheet.merge_cells('D4:D5')
    worksheet.merge_cells('E4:E5')
    worksheet.merge_cells('G4:G5')
    worksheet.merge_cells('F4:F5')
    worksheet.merge_cells('H4:H5')
    worksheet['D4'].alignment = Alignment(horizontal="center",
                                          vertical="center")
    worksheet['E4'].alignment = Alignment(horizontal="center",
                                          vertical="center")
    worksheet['G4'].alignment = Alignment(horizontal="center",
                                          vertical="center")
    worksheet['F4'].alignment = Alignment(horizontal="center",
                                          vertical="center")
    worksheet['H4'].alignment = Alignment(horizontal="center",
                                          vertical="center")
    worksheet.merge_cells('A4:C5')
    worksheet['A4'].alignment = Alignment(horizontal="left", vertical="center")
    worksheet['D4'].font = Font(bold=True, size=12)
    worksheet['E4'].font = Font(bold=True, size=12)
    worksheet['G4'].font = Font(bold=True, size=12)
    worksheet['F4'].font = Font(bold=True, size=12)
    worksheet['H4'].font = Font(bold=True, size=12)
    worksheet.delete_cols(9, 17)
    ws1 = worksheet.title = "Егорьевск"
    FullRange = "C6:" + get_column_letter(worksheet.max_column) \
    + str(worksheet.max_row)
    worksheet.auto_filter.ref = FullRange
    ws1 = worksheet.auto_filter.add_filter_column(0, ["167", "168", "169", "171", "172", "173", "174", "175", "176", \
                                                      "177", "178", "180", "181", "182", "183", "184", "185", "186",\
                                                      "187", "188", "189", "190", "193", "194", "678", "1853", "1855",\
                                                      "2102", "2600", "3252", "3253", "3254", "179*"])
    workbook.save(path2)
    sg.popup_ok('Файл готов!')
Beispiel #34
0
def oro_pipeline():
    imgs, darks, flats, bias = oro_fileloader()

    imgs_filtered, expt_filtered, t_filtered = filter_pipe(
        imgs,
        darks,
        flats,
        bias,
        filters=('Bessell V', 'Bessell B', 'Bessell R'))

    # Get reference frame for coordinate matchmaking
    fileselect = eg.fileopenbox(title='Select catalogue/reference image')
    file_data = get_oroimage(fileselect, show_info=False)
    ref_img = {}
    ref_img['img_data'] = file_data['img_data'].reshape(
        (len(file_data['img_data'][:,
                                   0]), len(file_data['img_data'][0, :]), 1))
    ref_img['img_filter'] = [file_data['img_filter']]
    ref_img['ra'] = file_data['ra']
    ref_img['dec'] = file_data['dec']
    ref_img['exp_time'] = [file_data['exp_time']]
    ref_img['time_utc'] = [file_data['time_utc']]
    ref_filtered = filter_pipe(ref_img,
                               darks,
                               flats,
                               filters=(ref_img['img_filter']),
                               bias=None)[0]
    ref_filtered = ref_filtered[ref_img['img_filter'][0]]

    imgs_V = imgs_filtered['Bessell V']
    expt_V = expt_filtered['Bessell V']
    time_utc_V = t_filtered['Bessell V']
    imgs_B = imgs_filtered['Bessell B']
    expt_B = expt_filtered['Bessell B']
    time_utc_B = t_filtered['Bessell B']
    imgs_R = imgs_filtered['Bessell R']
    expt_R = expt_filtered['Bessell R']
    time_utc_R = t_filtered['Bessell R']

    imgs_BVR = np.copy(imgs_B)
    imgs_BVR = np.append(imgs_BVR, imgs_V, axis=2)
    imgs_BVR = np.append(imgs_BVR, imgs_R, axis=2)
    # [[best_match_x, best_match_y], [ref_x, ref_y]] = matchmaker(imgs_BVR, ref_filtered)
    fname = 'NGC6791'
    for k in range(0, len(imgs_V[0, 0, :])):
        save_fitsfile(img_data=imgs_V[:, :, k],
                      fname=fname,
                      filt='Bessell_V',
                      time=time_utc_V[k],
                      expt=expt_V[k])
    for k in range(0, len(imgs_B[0, 0, :])):
        save_fitsfile(img_data=imgs_B[:, :, k],
                      fname=fname,
                      filt='Bessell_B',
                      time=time_utc_B[k],
                      expt=expt_B[k])
    for k in range(0, len(imgs_R[0, 0, :])):
        save_fitsfile(img_data=imgs_R[:, :, k],
                      fname=fname,
                      filt='Bessell_R',
                      time=time_utc_R[k],
                      expt=expt_R[k])
Beispiel #35
0
    exit()

ok = gui.msgbox(
    "Now select the .txt file " +
    "that contains the AWL Code from Step-7 that you want to load to the PIC.",
    "mikroPLC-Loader")

if ok == "OK":
    pass
else:
    exit()

####Looking for the Statement List File#####
extension = ["*.txt"]  #.txt files by default

code_filename = gui.fileopenbox(
    "", "Select the code file with the " + "statement list...", "", extension)
code_file = open(code_filename, "r")
code_file_text = code_file.readlines()
code_file.close()

modified_code = gui.codebox("Verify the AWL Code.",
                            "mikroPLC-Loader: " + code_filename,
                            code_file_text)

if modified_code == None:
    exit()

code_file = open(code_filename, "w")
code_file.write(modified_code)
code_file.close()
    nsamples = 2**17 / avg

    if not options.dir == "":
        datapath = options.dir
        # print "\nListing directory:", datapath
        datafiles = sorted(glob.glob(datapath + "/*.tdd"))
        # print "Found "+str(len(datafiles))+" \"tdd\" files.\n"
        if len(datafiles) > 0:
            fname = datafiles[0]
        else:
            print "No tdd files found in directory: " + datapath + "\nExiting..."
            exit(0)

    else:
        fname = easygui.fileopenbox(
            title="Choose a tdd file",
            default="/data/data_2/2018-11-LOW-BRIDGING/",
            filetypes="tdd")
        if fname is not None:
            datapath = fname[:fname.rfind("/")]
            print "\nListing directory:", datapath
            datafiles = sorted(glob.glob(datapath + "/*.tdd"))
            print "Found " + str(len(datafiles)) + " \"tdd\" files.\n"
        else:
            print "\nExiting!\n"
            exit(0)

    resolutions = 2**np.array(range(16)) * (800000.0 / 2**17)
    rbw = int(closest(resolutions, options.resolution))
    avg = 2**rbw
    nsamples = 2**17 / avg
    RBW = (avg * (400000.0 / 65536.0))
Beispiel #37
0
    def __init__(self, mandrel_name=None):

        import trimesh
        import matplotlib.pyplot as plt
        from trimesh.path.simplify import resample_spline
        import numpy as np

        if mandrel_name is None:
            import easygui
            path = easygui.fileopenbox()

        self.mandrel_name = mandrel_name

        path = mandrel_name + '.stl'

        mesh = trimesh.load(path)

        self.mesh = mesh

        mesh = mesh.process()

        sliced_mesh = mesh.section(plane_origin=[0, 0, 0],
                                   plane_normal=[0, 1, 0])

        sliced_mesh2_d = sliced_mesh.to_planar()[0]

        HTM = sliced_mesh.to_planar()[1]

        line = []
        nb_line = len(sliced_mesh2_d.entities)
        for i in range(nb_line):
            line.append(sliced_mesh2_d.entities[i].points)
        # [5] Affichage des lignes
        plt.figure()
        for i in range(nb_line):
            plt.plot(sliced_mesh2_d.vertices[line[i][:], 0],
                     sliced_mesh2_d.vertices[line[i][:], 1],
                     label=i,
                     marker='+')
        plt.legend()
        plt.show(block=True)

        groupe1 = input(
            'Numeros du 1er groupe de lignes separés par une virgule sans espace,'
            ' +/- selon le sens de parcours :')
        groupe2 = input(
            'Numeros du 2nd groupe de lignes separés par une virgule sans espace,'
            ' +/- selon le sens de parcours :')
        groupe1 = groupe1.split(',')
        groupe1 = [int(i) for i in groupe1]
        groupe2 = groupe2.split(',')
        groupe2 = [int(i) for i in groupe2]

        # [6] Reconstruction des 2 groupes de lignes
        if groupe1[0] >= 0:
            line1 = line[groupe1[0]][:]
        else:
            line1 = line[-groupe1[0]][::-1]
        if len(groupe1) > 1:
            for i in range(1, len(groupe1)):
                if groupe1[i] >= 0:
                    line1 = np.hstack((line1, line[groupe1[i]][:]))
                else:
                    line1 = np.hstack((line1, line[-groupe1[i]][::-1]))

        if groupe2[0] >= 0:
            line2 = line[groupe2[0]][:]
        else:
            line2 = line[-groupe2[0]][::-1]
        if len(groupe2) > 1:
            for i in range(1, len(groupe2)):
                if groupe2[i] >= 0:
                    line2 = np.hstack((line2, line[groupe2[i]][:]))
                else:
                    line2 = np.hstack((line2, line[-groupe2[i]][::-1]))

        # [7] Suppression des elements doublés et interpolation
        line1 = [ii for n, ii in enumerate(line1) if ii not in line1[:n]]
        line2 = [ii for n, ii in enumerate(line2) if ii not in line2[:n]]
        line1 = np.array((sliced_mesh2_d.vertices[line1[:], 0],
                          sliced_mesh2_d.vertices[line1[:], 1])).transpose()
        line1 = resample_spline(line1, count=1000, degree=1)
        line2 = np.array((sliced_mesh2_d.vertices[line2[:], 0],
                          sliced_mesh2_d.vertices[line2[:], 1])).transpose()
        line2 = resample_spline(line2, count=1000, degree=1)

        # [8] Création de la ligne des centres
        coord = []
        for i in range(line1.shape[0]):
            coord.append((line1[i] + line2[i]) / 2)
        coord = np.asarray(coord)

        # [9] Affichage dans un graphique
        plt.figure()
        plt.plot(line1[:, 0], line1[:, 1], label='1')
        plt.plot(line2[:, 0], line2[:, -1], label='2')
        plt.legend()
        plt.plot(coord[:, 0], coord[:, 1], label='Ligne des centres')
        # [10] Passage en 3D
        liste_centroid = np.dot(
            HTM,
            np.hstack((coord, np.zeros(coord.shape[0]).reshape(
                (coord.shape[0], 1)), np.ones(coord.shape[0]).reshape(
                    (coord.shape[0], 1)))).transpose()).transpose()
        # [11] Inversion du sens de parcours de la ligne des centres
        if np.linalg.norm(liste_centroid[0, 0:3]) > np.linalg.norm(
                liste_centroid[-1, 0:3]):
            liste_centroid = liste_centroid[::-1, 0:3]

        self.coordinates = liste_centroid
def ApplyMask(threshold):
    # Apply the mask to each color channel in the image:
    extracted_sharkB = cv2.bitwise_or(threshold, Enchanced_B)
    extracted_sharkG = cv2.bitwise_or(threshold, Enchanced_G)
    extracted_sharkR = cv2.bitwise_or(threshold, Enchanced_R)

    merged = cv2.merge((extracted_sharkB, extracted_sharkG, extracted_sharkR))

    return merged


# Repeat until the user chooses to exit:
while (1):
    gui.msgbox(opening_message + instructions, "Hello!")

    F = gui.fileopenbox()
    I = cv2.imread(F)

    YUV = cv2.cvtColor(I, cv2.COLOR_BGR2YUV)
    Y, U, V = cv2.split(YUV)

    # Using the Contrast Limited Adaptive Histogram Equalization class to enhance the contrast
    # Create the CLAHE object and set the clip limit and tile grid size:
    CLAHE = cv2.createCLAHE(clipLimit=4.5, tileGridSize=(3, 3))

    # This improves definition in the image:
    Enhanced_Y = CLAHE.apply(Y)

    # This is used to remove the background:
    Enhanced_U = CLAHE.apply(U)
Beispiel #39
0
    cv2.imshow(
        'fmap',
        cv2.resize(img_foc,
                   (600, int((600 / float(img_foc.shape[1]) *
                              img_foc.shape[0])))))  #.astype(dtype=np.uint8))
    cv2.waitKey(1)
    cv2.imshow(
        'underover',
        cv2.resize(img_uo,
                   (600, int((600 / float(img_uo.shape[1]) *
                              img_uo.shape[0])))))  #.astype(dtype=np.uint8))
    cv2.waitKey(1)

    cv2.imwrite(
        r'c:\Users\PocUser\Documents\DATA\TEMP' + 'foc_' +
        os.path.split(photo_file)[1], img_foc)
    cv2.imwrite(
        r'c:\Users\PocUser\Documents\DATA\TEMP' + 'uo_' +
        os.path.split(photo_file)[1], img_uo)


if __name__ == '__main__':
    msg = 'Do you want to continue?'
    title = 'Please Confirm'
    photo_file = os.path.join(IMAGE_DIR, 'nice_30.jpg')
    #main(photo_file)
    while easygui.ccbox(msg, title):  # show a Continue/Cancel dialog
        photo_file = easygui.fileopenbox(default=photo_file)
        cv2.destroyAllWindows()  # Ok, destroy the window
        main(photo_file)
    sys.exit(0)
sys.path.append(r"C:\PhD\Python\Python-Dust-Codes\FP Overplot")
sys.path.append(r"C:\PhD\Python\Python-Dust-Codes\General-Use")

from orbitdata_loading_functions import orb_vector, orb_obs
from FP_plot_functions import ra2xpix, dec2ypix, setaxisup, plotpixel
from conversion_routines import pos2radec, fixwraps, find_largest_nonzero_block 
from io_methods import correct_for_imagetype

#%%**********************
#FIRST CELL - GET DATA IN
#************************

if True:
    #choosing comet data to use
    inputfilefolder = "C:\PhD\Comet_data\Input_files\*pt1.txt"
    inputfile = easygui.fileopenbox(default = inputfilefolder)
    
    #reading main comet parameters
    with open(inputfile, "r") as c:
        cdata = c.readlines()
        comname = cdata[30][12:]
        comdenom = cdata[31][13:-2]
        orbitdir = cdata[25][23:-2]
        timedir = cdata[28][26:-2]
        pysav = cdata[27][24:-2]
        horiztag = cdata[40][10:]
    
    obsloc = 'Earth'    
    #import the orbit data
    comobs = orb_obs(comdenom, obsloc, pysav, orbitdir, horiztag)
Beispiel #41
0
    layers = model.getLayerNames()  #Modelin içindeki layerlerin alınması
    layers = [layers[i[0] - 1] for i in model.getUnconnectedOutLayers()
              ]  #Layerlerin içinden çıktı verecek layerlerin alınması

    text = "Hangisini kullanmak istersiniz?"
    title = "Kullanım tercihi"
    choices = ["Resim", "Video", "Kamera", "Model seçimine geri dön"]
    rvkchoice = easygui.choicebox(
        text, title, choices)  #Resim, video, kamera seçim ekranının yapılması

    if rvkchoice == choices[
            0]:  #rvkchoice ile choice seçimine göre hangisinin seçileceğinin belirlenmesi
        easygui.msgbox(msg="Lütfen resim seçiniz..",
                       title="Bilgi",
                       ok_button="Tamam")
        path = easygui.fileopenbox(title="Resim seçiniz.",
                                   filetypes=["*.jpeg", "*.jpg", "*.png"])
        if not path:  #path(dosya) seçimediğinde yapılacak işlem
            ynbox = easygui.ynbox("Devam etmek istiyor musunuz?", "",
                                  ("Evet", "Hayır"))
            if ynbox == True:
                print("Devam ediliyor...")
                continue
            else:
                print("Kapatılıyor...")
                break

        resim = cv2.imread(
            path
        )  #path(dosyadan) alınan verinin okunup resim değerine eşitlenmesi
        width, height = 1080, 720  #resize için resimin en ve boyunun belirlenmesi
        resize = (width, height)
Beispiel #42
0
import plotly.express as px
import easygui
import datetime
import fnmatch

data = os.path.join("data")
filepath = os.path.dirname(data)


def to_usd(my_price):
    return f"${my_price:,.2f}"


# User prompted to select file with error handling
while True:
    filename = easygui.fileopenbox(msg="Please Select a File",
                                   default="data/*")
    if fnmatch.fnmatch(filename, '*.csv'):
        break
    else:
        easygui.exceptionbox(
            msg="Oops, unable to open file. Please try again.", title="OOPS!")

df = pd.read_csv(filename)

#month
m = df["date"].min()
monthinteger = int(m[5:7])
month = datetime.date(1900, monthinteger, 1).strftime('%B')

# year
y = df["date"].min()
def main():
    GRIDCONTS = 'GridDump'
    RowsNumConts = 'RowsNum'
    ColsNumConts = 'ColsNum'
    HeadsFileConts = 'HeadsFile'
    InputFileConts = 'InputFile'
    OutNameConts = 'OutName'
    RowsNum = 0
    ColsNum = 0
    ControlFileLoc = ""
    Stations = dict()
    RunsOptions = dict()
    HeadsDict = dict()
    tempOutName = ""

    cmdLine = checkExec_env()
    if cmdLine:
        print('Runnable with multiple processors')
    else:
        print('Unable to run with multiple processors')
    platform = (None, 'mp')[cmdLine]

    #platform='sp'
    #platform= 'mp'
    arg1 = sys.argv[1:]

    if len(arg1) < 2:
        #
        #   GUI to select ControlFile if not provided on command line
        #
        title = "Make Hydrographs and Duraction Curves"
        namMsg = "Please locate and select a ControlFile"
        reply = None
        while True:
            if len(arg1) < 2:
                ftypes = [
                    "*.dat", ["*.txt", "*.log", "Non Standard Namefiles"]
                ]
                reply = ez.fileopenbox(msg=namMsg,
                                       title=title,
                                       default='*',
                                       filetypes=ftypes)
            else:
                break
            if reply:
                break
        if reply:
            arg1[0] = reply
        print ("{} has been selected as the ControlFile."\
               .format(arg1[0]))
# print(arg1,len(arg1))
    if len(arg1) == 1:
        (path, namfile) = os.path.split(arg1[0])
        if path == '':
            print("""Explicit path missing from {}
                Using default path for testing""".format(namfile))
            path = 'H:\\'
    else:
        print("""Unable to process ControlFile data without file location
        details.
        """)
        exit()

    if len(arg1) > 0:
        ControlFileLoc = arg1[0]
    else:
        print('EasyGui failed to identify control file.  Using defaults')
        ControlFileLoc = r'\\ad.sfwmd.gov\dfsroot\data\wsd\MOD\kr\pmg\controlHyroDur.dat'

    ControlFile = open(ControlFileLoc, 'r')
    for line in ControlFile:
        if not line in ['\n', '\r\n']:
            values = line.split()
        if values[0].strip() == GRIDCONTS:
            tempGDfile = open(values[1], 'r')
            tempString = tempGDfile.read()
            TempDump = tempString.split()
        if values[0].strip() == RowsNumConts:
            RowsNum = values[1]
        if values[0].strip() == ColsNumConts:
            print(values[1])
            ColsNum = values[1]
        if values[0].strip() == InputFileConts:
            InputFile = open(values[1], 'r')
        if values[0].strip() == HeadsFileConts:
            print(values[1])
            HeadsDict[values[1]] = values[2]
            options = [values[3], values[4], values[5]]
            RunsOptions[values[1]] = options
        if values[0].strip() == OutNameConts:
            tempOutName = values[1]

    GridDump = [float(g) for g in TempDump]
    Grid = np.reshape(GridDump, (int(RowsNum), int(ColsNum)))
    #rid = np.reshape(GridDump,(292,408))
    for line in InputFile:
        values = line.split()
        if values[0].upper() != 'STATION':
            Station = values[0]
            Row = int(values[1])
            Col = int(values[2])
            topo = Grid[Row - 1, Col - 1]
            Stations[Station] = topo

#         print(Station, Row, Col, topo, Stations[Station])
    headsbyRun = dict()
    for Run, File in HeadsDict.items():
        HeadsFile = open(File, 'r')
        pdData = pd.read_csv(HeadsFile)
        headsbyRun[Run] = pdData

    AllrPool = []

    AllrPool.append(
        compileFigs(platform, headsbyRun, Stations, RunsOptions, tempOutName))

    if platform == 'mp':
        for rPool in reversed(AllrPool):
            for rp in rPool:
                rp.wait()
        print("Figure Creation process completed")

    print('Done')
Beispiel #44
0
def upload_file():
    filepath = easygui.fileopenbox()
    f = Filter(view_mode=False, save_mode=True)
    f.execute(filepath=filepath)
Beispiel #45
0
        return epsg
    elif zone == '9':
        epsg = 26909
        return epsg
    elif zone == '8':
        epsg = 26908
        return epsg
    elif zone == '7':
        epsg = 26907
        return epsg
    elif zone == '6':
        epsg = 26906
        return epsg
    elif zone == '5':
        epsg = 26905
        return epsg
    elif zone == '4':
        epsg = 26904
        return epsg


###>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.MAIN.>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>###

if __name__ == '__main__':
    eoFileList = easygui.fileopenbox(msg="Select HydroFusion *.dat Files",
                                     title="EO Selection",
                                     default='*',
                                     filetypes=".dat",
                                     multiple=True)
    eos2shp(eoFileList)
Beispiel #46
0
def readSWC(swcFName):
    """
    Read the data of all points in the swc file.
    :return:
    """

    swcPointData = []
    with open(swcFName, 'r') as fle:
        line = fle.readline()
        while not line == '':

            if not line[0] == '#':
                entries = line.split(' ')
                swcPointData.append([float(x) for x in entries[2:7]])

            line = fle.readline()
    return swcPointData

def getAverage(pts, origin = [0, 0, 0], normalize=True):

    av = np.mean(np.asarray(pts) -  np.asarray(origin), axis=0)

    if normalize:
        return av / np.linalg.norm(av)


swcFile = fileopenbox(msg='SWC file with three point soma', filetypes=['*.swc'])
pts = readSWC(swcFile)
ptsAverage = getAverage([x[:3] for x in pts])
print(ptsAverage)
"""

from asammdf import MDF
import easygui
import pandas as pd
import glob, os
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import binned_statistic_2d 



datFiles = easygui.fileopenbox(msg='Select dat files', default='*.dat', multiple = True)
#get the folderpath of dat file
folderPath = os.path.dirname(datFiles[0])

def Averaging_df(x,y):
    RPM = [3200,3000,2800,2600,2400,2200,2000,1800,1600,1400,1200]
    # RPM = [3150,2950,2750,2550,2350,2150,1950,1750,1550,1350,1150]
    mean_ = []
    for i in RPM:
        df_i = x[(x['cps_n_engine'] > i-50) & (x['cps_n_engine'] < i+50)]
        a = df_i[y].mean()
        mean_.append(a)
    mean_dict = {'Engine speed (RPM)':RPM,y:mean_}
    df_mean_ = pd.DataFrame(mean_dict)
    df_mean_.set_index(df_mean_['Engine speed (RPM)'])
    # print(df_mean_)
sys.path.append(r"C:\PhD\Python\Python-Dust-Codes\FP Overplot")
sys.path.append(r"C:\PhD\Python\Python-Dust-Codes\General-Use")

from orbitdata_loading_functions import orb_vector, orb_obs
from FP_plot_functions import ra2xpix, dec2ypix, setaxisup, plotpixel
from conversion_routines import pos2radec, fixwraps, find_largest_nonzero_block
from io_methods import correct_for_imagetype, get_obs_loc, get_hih_low
from io_methods import get_stereo_instrument, get_soho_instrument

#%%**********************
#FIRST CELL - GET DATA IN
#************************
#choosing comet data to use
inputfilefolder = "C:\PhD\Comet_data\Input_files\*pt1.txt"
inputfile = easygui.fileopenbox(default=inputfilefolder)

#reading main comet parameters
with open(inputfile, "r") as c:
    cdata = c.readlines()
    comname = cdata[30][12:]
    comdenom = cdata[31][13:-2]
    imagedir = cdata[24][18:-2]
    orbitdir = cdata[25][23:-2]
    timedir = cdata[28][26:-2]
    pysav = cdata[27][24:-2]
    horiztag = cdata[40][10:]
    obslocstr = cdata[34][19:]
#choose observer locations
[obsloc, imagedir] = get_obs_loc(obslocstr, imagedir)
if "Stereo" in obsloc: [inst, imagedir] = get_stereo_instrument(imagedir)
def main():
    # choose file using easygui, output file
    INPUTFILE = easygui.fileopenbox("Input .txt file with Eprime data")
    OUTPUTFILE = easygui.enterbox("Enter output filename")
    print(INPUTFILE)
    if INPUTFILE == None or OUTPUTFILE == None:
        print("Must select file location and destination")
        return 1


# part 1 reading from textfile with weird utf encoding

    read_file = open(INPUTFILE, "r", encoding="utf-16-le")
    write_file = open("write_file.txt", "w")

    trials = read_file.read().split("\n")
    # creates a separate .txt file to to simplify transfer to excel file
    for i in range(1, len(trials)):
        trials[i] = trials[i].lstrip()
        if trials[i] == "Level: 3":
            for j in range(i, len(trials)):
                trials[j] = trials[j].lstrip()
                if trials[j].startswith(
                        "StimulusContent:") or trials[j].startswith(
                            "CorrectResponse:") or trials[j].startswith(
                                "RT:") or trials[j].startswith("ACC:"):
                    write_file.write(trials[j])
                    write_file.write("\n")
                elif trials[j] == "*** LogFrame End ***":
                    write_file.write("\n \n")
                elif trials[j] == "Level: 2":
                    break
            break
    write_file.close()

    # part 2 writing to excel

    write_file = open("write_file.txt", "r")
    wb = Workbook()
    sheet1 = wb.add_sheet("Sheet 1")

    boldFont = xlwt.easyxf('font: name Arial, bold on, height 200;')
    regFont = xlwt.easyxf('font: name Arial, bold off, height 200;')

    # collumn titles
    sheet1.write(0, 0, "VapingPull", boldFont)
    sheet1.write(0, 2, "VapingPush", boldFont)
    sheet1.write(0, 4, "NeutralPull", boldFont)
    sheet1.write(0, 6, "NeutralPush", boldFont)

    for i in range(8):
        sheet1.write(1, i, "RT" if i % 2 == 0 else "ACC", boldFont)
    trials = write_file.read().split()

    # number of elements in each new array
    n = 8

    # separates each chunk of the write file by making
    # sub arrays of size n, has to be adjusted if the
    # .txt format changes
    trials = [
        trials[i * n:(i + 1) * n] for i in range((len(trials) + n - 1) // n)
    ]

    col = 0
    row = 0
    bottomRow = [2, 2, 2, 2]
    # writing the error and reaction time to excel file
    for trial in trials:
        if trial[trial.index("StimulusContent:") + 1] == "regular":
            col += 4
        if trial[trial.index("CorrectResponse:") + 1] == "Push":
            col += 2
        rowInt = int(col / 2)

        # trial[x] part must be changed if the order
        # that error/rt/stimulusContent/correctResponse appear
        # in the .txt file change
        # ['ErrorCount:', '1', 'StimulusContent:', 'Neutral', 'CorrectResponse:', 'Pull', 'RT:', '828']
        # could optimize to recognize each class, not just array index
        sheet1.write(bottomRow[rowInt], col,
                     int(trial[trial.index("RT:") + 1]), regFont)
        sheet1.write(bottomRow[rowInt], col + 1,
                     int(trial[trial.index("ACC:") + 1]), regFont)

        bottomRow[rowInt] += 1
        col = 0
        row += 1

    wb.save(OUTPUTFILE + ".xls")

    write_file.close()
    read_file.close()
░░███╔═╝███████║╚█████╗░██║░░░░░███████║╚██╗░██╔╝╚█████╗░█████═╝░██║╚█████╗░
██╔══╝░░██╔══██║░╚═══██╗██║░░░░░██╔══██║░╚████╔╝░░╚═══██╗██╔═██╗░██║░╚═══██╗
███████╗██║░░██║██████╔╝███████╗██║░░██║░░╚██╔╝░░██████╔╝██║░╚██╗██║██████╔╝
╚══════╝╚═╝░░╚═╝╚═════╝░╚══════╝╚═╝░░╚═╝░░░╚═╝░░░╚═════╝░╚═╝░░╚═╝╚═╝╚═════╝░

"""

import datetime
import sys
import easygui
from tkinter import filedialog


row_data = ["Raw Radio Data Channel 1","Channel 2",
"Channel 3","Channel 4","throttle","battery_voltage"
,"ESC 1","ESC 2","ESC 3","ESC 4","Gyro Data","Temp","PID Data"]
path = easygui.fileopenbox()
input_raw_data = open(path,"r",encoding='UTF-8').readlines()
for string_in_file in range(0,len(input_raw_data)):
	for row_eliment in range(0,len(row_data)):
		input_raw_data[string_in_file].replace(row_data[row_eliment],"")
		input_raw_data[string_in_file].replace(" ","")
		input_raw_data[string_in_file].replace(":",",")
directory = filedialog.asksaveasfilename()
output_file=open(directory,"a",encoding='UTF-8')
for string_in_array in range(0,len(input_raw_data)):
    output_file.write(input_raw_data[string_in_array])
    output_file.write("\n")
output_file.flush()   
output_file.close() 
def upload():
    ImagePath = easygui.fileopenbox()
    cartoonify(ImagePath)
Beispiel #52
0
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import easygui
font1 = ImageFont.truetype(
    "/usr/share/fonts/truetype/freefont/FreeSansBold.ttf", 65)

#overlap = 100
overlap = int(input('overlap = '))
name1 = easygui.fileopenbox()
name2 = easygui.fileopenbox()
img1 = Image.open(name1)
img2 = Image.open(name2)
width1, height1 = img1.size
width2, height2 = img2.size
if height1 == height2:
    toImage = Image.new('RGBA', (width1 + width2 - overlap, height1))
    draw = ImageDraw.Draw(toImage)
    toImage.paste(img2, (width1 - overlap, 0))
    toImage.paste(img1, (0, 0))
    toImage.save('merged_hori.png')
else:
    print('heights not equal!')
Beispiel #53
0
def fileChoose():
    path=easygui.fileopenbox()
    filePath=(conventPDF(path))
    return filePath
    src_array = np.array([A_point, B_point, C_point, D_point],
                         dtype=np.float32)
    dst_array = np.array([[0, 0], [0, img.shape[0]], [img.shape[1], 0],
                          [img.shape[1], img.shape[0]]],
                         dtype=np.float32)
    perspective_matrix = getPerspectiveTransform(src=src_array, dst=dst_array)
    img = warpPerspective(src=bk_img,
                          M=perspective_matrix,
                          dsize=(img.shape[1], img.shape[0]),
                          flags=INTER_LANCZOS4)
    global have_not_trans
    have_not_trans = False


# 创建图像与窗口并将窗口与回调函数绑定
filename = easygui.fileopenbox('选择需要处理的图片', '选择图片')
# filename = 'D:\\document\\aff_correction\\20160908221841999.jpg'
img = imread(filename)
have_not_trans = True
bk_img = deepcopy(img)
namedWindow('image')
setMouseCallback('image', draw_circle)
point_list = []
while (1):
    imshow('image', img)
    keycode = waitKeyEx(20)
    if getWindowProperty('image', WND_PROP_AUTOSIZE) < 1:  # 使用关闭按钮关闭窗口
        break
    if keycode == -1: continue  #显示
    elif keycode & 0xFF == 27:  #esc
        break
Beispiel #55
0
def open_file():
    input_file = easygui.fileopenbox(filetypes=["*.docx"])
    return input_file
Beispiel #56
0
import numpy as np
import cv2
import pytesseract
import os
import easygui

os.system('cls')

while True:
    fname = easygui.fileopenbox()
    print 'Opened ' + fname
    img = cv2.imread(fname, 0)

    cv2.imshow('image', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    #preprocessing
    strel = np.ones((9, 9), np.uint8)
    bw = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                               cv2.THRESH_BINARY_INV, 25,
                               2)  # adaptive threshold plus complement
    bw = cv2.morphologyEx(bw, cv2.MORPH_OPEN, strel)  #morph open

    strel = np.ones((5, 5), np.uint8)
    bwD = cv2.dilate(bw, strel, iterations=3)  #morph dilation

    vProj = cv2.reduce(
        bwD, 0, cv2.REDUCE_SUM, dtype=cv2.CV_32S
    )  #get vertical projection / sum of all rows reduced to one row
    vProj[vProj > 0] = 255  #converts to pseudo 'logical'
Beispiel #57
0
def oro_fileloader():
    fileselect = eg.fileopenbox(title='Select images, darks and flats',
                                multiple=True)
    imgs = {
        'img_filter': [],
        'time_utc': [],
        'ra': [],
        'dec': [],
        'exp_time': []
    }
    darks = {'time_utc': [], 'exp_time': []}
    flats = {'img_filter': [], 'time_utc': [], 'exp_time': []}
    bias = None
    for file in fileselect:
        file_data = get_oroimage(file, show_info=False)
        if file_data['img_type'] == 'Light Frame':
            if 'img_data' in imgs.keys():
                imgs['img_data'] = np.append(imgs['img_data'],
                                             file_data['img_data'][:, :,
                                                                   np.newaxis],
                                             axis=2)
            else:
                imgs['img_data'] = file_data['img_data']
                imgs['img_data'] = imgs['img_data'].reshape(
                    (len(imgs['img_data'][:,
                                          0]), len(imgs['img_data'][0, :]), 1))
            imgs['img_filter'].append(file_data['img_filter'])
            imgs['time_utc'].append(file_data['time_utc'])
            imgs['ra'].append(file_data['ra'])
            imgs['dec'].append(file_data['dec'])
            imgs['exp_time'].append(file_data['exp_time'])
        elif file_data['img_type'] == 'Dark Frame':
            if 'img_data' in darks.keys():
                darks['img_data'] = np.append(
                    darks['img_data'],
                    file_data['img_data'][:, :, np.newaxis],
                    axis=2)
            else:
                darks['img_data'] = file_data['img_data']
                darks['img_data'] = darks['img_data'].reshape(
                    (len(darks['img_data'][:, 0]),
                     len(darks['img_data'][0, :]), 1))
            darks['time_utc'].append(file_data['time_utc'])
            darks['exp_time'].append(file_data['exp_time'])
        elif file_data['img_type'] == 'Flat Field':
            if 'img_data' in flats.keys():
                flats['img_data'] = np.append(
                    flats['img_data'],
                    file_data['img_data'][:, :, np.newaxis],
                    axis=2)
            else:
                flats['img_data'] = file_data['img_data']
                flats['img_data'] = flats['img_data'].reshape(
                    (len(flats['img_data'][:, 0]),
                     len(flats['img_data'][0, :]), 1))
            flats['img_filter'].append(file_data['img_filter'])
            flats['time_utc'].append(file_data['time_utc'])
            flats['exp_time'].append(file_data['exp_time'])
        else:
            print(file_data['img_type'])
            print('Unknown filetype')
    return imgs, darks, flats, bias
def button3():
    path = easygui.fileopenbox(default="HOME/Downloads/*.xlsx",
                               filetypes='*.xlsx')
    try:
        workbook = openpyxl.load_workbook(path)
    except Exception as e:
        try:
            workbook = openpyxl.load_workbook(path)
        except Exception as e:
            sg.popup_auto_close('не выбран файл!')
            sg.popup_ok(e)
            workbook = None
        return (workbook)


#   path = easygui.fileopenbox(default= '*.xlsx', filetypes= '*.xlsx')
    path2 = easygui.filesavebox(default="HOME/APPDATA/RPBeta/Shatoora.xlsx",
                                filetypes='*.xslx')
    #   workbook = openpyxl.load_workbook(path)
    worksheet = workbook["Лист 1"]
    filetypes = ['*.xlsx', "Excel"]
    default = '*'
    worksheet = workbook["Лист 1"]
    worksheet.unmerge_cells('A1:P1')
    worksheet.unmerge_cells('A2:P2')
    worksheet.unmerge_cells('A3:P3')
    worksheet.unmerge_cells('A4:P4')
    worksheet.unmerge_cells('A5:P5')
    worksheet['D4'] = '= SUBTOTAL(9,D8:D127)'
    worksheet['E4'] = '= SUBTOTAL(9,E8:E127)'
    worksheet['G4'] = '= SUBTOTAL(9,G8:G127)'
    worksheet['F4'].number_format = FORMAT_PERCENTAGE_00
    worksheet['H4'].number_format = FORMAT_PERCENTAGE_00
    worksheet['F4'] = '= E4/D4'
    worksheet['H4'] = '= G4/D4'
    worksheet['A4'] = 'ИТОГИ'
    worksheet['G1'] = 'RNISka Reports 1.2.4'
    worksheet['G1'].font = Font(name='Tahoma',
                                size=9,
                                color="FF0000",
                                italic=True)
    worksheet.merge_cells('D4:D5')
    worksheet.merge_cells('E4:E5')
    worksheet.merge_cells('G4:G5')
    worksheet.merge_cells('F4:F5')
    worksheet.merge_cells('H4:H5')
    worksheet['D4'].alignment = Alignment(horizontal="center",
                                          vertical="center")
    worksheet['E4'].alignment = Alignment(horizontal="center",
                                          vertical="center")
    worksheet['G4'].alignment = Alignment(horizontal="center",
                                          vertical="center")
    worksheet['F4'].alignment = Alignment(horizontal="center",
                                          vertical="center")
    worksheet['H4'].alignment = Alignment(horizontal="center",
                                          vertical="center")
    worksheet.merge_cells('A4:C5')
    worksheet['A4'].alignment = Alignment(horizontal="left", vertical="center")
    worksheet['D4'].font = Font(bold=True, size=12)
    worksheet['E4'].font = Font(bold=True, size=12)
    worksheet['G4'].font = Font(bold=True, size=12)
    worksheet['F4'].font = Font(bold=True, size=12)
    worksheet['H4'].font = Font(bold=True, size=12)
    worksheet.delete_cols(9, 17)
    ws1 = worksheet.title = "Шатура"
    FullRange = "C6:" + get_column_letter(worksheet.max_column) \
    + str(worksheet.max_row)
    worksheet.auto_filter.ref = FullRange
    ws1 = worksheet.auto_filter.add_filter_column(0, ["1513", "1172", "1993", "1514", "1515", "1516", "1988", "1519", \
                                                      "1697", "3234", "2082", "1517", "1518", "1521", "1543", "1522", \
                                                      "2491", "1523", "1524", "1525", "1544", "2609", "1546", "1547", \
                                                      "1526", "1527", "1528", "1529", "1530", "1548", "1531", "1532", \
                                                      "1550", "2565", "1549", "1545", "1991", "1896", "1534", "1538", \
                                                      "1539", "1811", "1540", "1541", "1812", "1542", "1759"])
    workbook.save(path2)
    sg.popup_ok('Файл готов!')
Beispiel #59
0
	help="face detection model to use: either `hog` or `cnn`")
args = vars(ap.parse_args())
'''


# load the known faces and embeddings
print("[INFO] loading encodings...")

data = pickle.loads(open(encoding_file_name, "rb").read())
# print('data',data)

# load the input image and convert it from BGR to RGB


print("[INFO] Select input image ...")
input_file=fileopenbox(msg='Select an image file...',title='Face Detection')
image = cv2.imread(input_file)
rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# detect the (x, y)-coordinates of the bounding boxes corresponding
# to each face in the input image, then compute the facial embeddings
# for each face

print("[INFO] recognizing faces...")

t1= datetime.now()#测试起始时间
# print('t1=',t1)
boxes = face_recognition.face_locations(rgb, model=default_model)

t2 = datetime.now()#测试结束时间
# print('t2=',t2)
from itertools import count
from networkx.drawing.nx_agraph import graphviz_layout
import os
import nltk
import easygui
import sys
nltk.download('punkt')

#files = os.listdir()
#print('\n\n')
#for i in files:
#    print(i)

filename = easygui.fileopenbox(msg=None,
                               title='Abrir arquivo do livro',
                               default='*',
                               filetypes=None,
                               multiple=False)

f = open(filename, 'r')

string = f.read()

tokens = nltk.word_tokenize(string)

dicname = easygui.fileopenbox(msg=None,
                              title='Abrir arquivo do dicionario',
                              default='*',
                              filetypes=None,
                              multiple=False)