Esempio n. 1
0
	def openFile(self, widget, e):
		fileChooser = gtk.FileChooserDialog('Open a File', self.window,
				gtk.FILE_CHOOSER_ACTION_OPEN,
				(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
				gtk.STOCK_OPEN, gtk.RESPONSE_OK), None)
		fileFilter = gtk.FileFilter()
		fileFilter.set_name('Text Files')
		fileFilter.add_pattern('*.txt')
		fileFilter.add_pattern('*.csv')
		fileChooser.add_filter(fileFilter)
		response = fileChooser.run()
		if response != gtk.RESPONSE_OK:
			fileChooser.destroy()
			return
		fileName = fileChooser.get_filename()
		fileChooser.destroy()
		fileParser = FileParser()
		newListStore, headersType, tableHeaders, rowsNotes = fileParser.parseToTable(fileName)
		if newListStore == None:
			self.displayErrorPrompt('ERROR! Corrupted File', 'The file: \'' + fileName +
				'could not be loaded\nFile\'s data is malformed')
			return
		self.currentFile = fileName
		self.loadData(newListStore, headersType,
					tableHeaders, rowsNotes)
Esempio n. 2
0
 def grep(self, pattern, url, depth = -1):
     if depth is -1:
         depth = self.depth
     elif depth is 0 or not url or url in self.visited:
         return
     self.visited.append(url)
     f = FileParser(url)
     matches = f.search(pattern)
     if len(matches) > 0:
         print url + ':'
     for i in matches:
         print "    ", i
     if depth > 1:
         for i in f.outlinks():
             self.grep(pattern, i, depth - 1)
Esempio n. 3
0
    def new_file(self):
        self.master.filename = filedialog.askopenfilename(
            initialdir="./json",
            title="Select file",
            filetypes=(("json files", "*.json"), ("all files", "*.*")))

        self.parser = FileParser(self.master.filename)
        self.keylist = self.parser.findKeys()

        self.key_search['values'] = self.keylist
        self.key_extract['values'] = self.keylist

        self.key_search.current(0)
        self.key_extract.current(0)

        file = os.path.basename(self.master.filename)
        self.name.config(text="Current File: " + file)
Esempio n. 4
0
def main(args):
    if "filename" in args:
        parser = FileParser(args.filename)
    else:
        parser = NetParser(args.host, args.port)
    renderer = Renderer(args.pixels, args.mass, parser)
    window = Window(args.fps, renderer)
    window.mainloop()
Esempio n. 5
0
def serve(sock, filename):
    try:
        parser = FileParser(filename)
        sock.send("{}\n".format(parser.n))
        sock.send("{}\n".format(parser.L))
        sock.send("{}\n".format(parser.N))
        sock.send("{}\n".format(parser.N_p))
        for m in parser.masses:
            sock.send("{}\n".format(m))

        for _ in range(parser.N_p):
            msg = sock.recv(3)
            if msg != "g\r\n":
                print "msg = '{}'".format(msg)
                return
            for (x, y) in parser.next():
                sock.send("{} {} 0.0 0.0\n".format(x, y))
    except Exception:
        traceback.print_exc()
Esempio n. 6
0
    def test_max_value(self):
        parser = FileParser('./test-input.txt')
        max_register_value = parser.get_max_register_value()
        self.assertEqual(0, max_register_value)

        parser.run()
        max_register_value = parser.get_max_register_value()
        self.assertEqual(10, max_register_value)
Esempio n. 7
0
	def saveFile(self, widget, e):
		fileChooser = gtk.FileChooserDialog('Save File', self.window,
				gtk.FILE_CHOOSER_ACTION_SAVE,
				(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
				gtk.STOCK_SAVE, gtk.RESPONSE_OK), None)
		fileFilter = gtk.FileFilter()
		fileFilter.set_name('Text Files')
		fileFilter.add_pattern('*.txt')
		fileFilter.add_pattern('*.csv')
		fileChooser.add_filter(fileFilter)
		response = fileChooser.run()
		if response != gtk.RESPONSE_OK:
			fileChooser.destroy()
			return
		fileName = fileChooser.get_filename()
		fileChooser.destroy()
		fileParser = FileParser()
		rowNotes = []
		for nbuffer in self.notesBuffers:
			startIter = nbuffer.get_start_iter()
			endIter = nbuffer.get_end_iter()
			rowNotes.append(nbuffer.get_text(startIter, endIter))
		fileParser.parseToFile(fileName, self.liststore, self.tableHeaders, rowNotes)
Esempio n. 8
0
    def _read_file(self, file, data_size):
        """[summary]

        Arguments:
            file {[type]}

        """
        parser = FileParser(self.seq_len, file)
        d_size = len(parser.tours)
        if d_size < data_size:
            self.data_size = d_size
        points_list = np.array(parser.coords[: self.data_size])
        solutions = np.array(parser.tours[: self.data_size])
        return {"Points_List": points_list, "Solutions": solutions}
Esempio n. 9
0
    def get_parser(self, url: str):
        # first try supported hosts
        host = urlparse(url).netloc
        if host == Anime1Parser.host:
            return Anime1Parser()

        # finally try file parser by parsing file extention
        file_ext_match = re.match(r'.*\.(\w+$)', url)
        if file_ext_match and file_ext_match.group(
                1) in FileParser.support_extensions:
            return FileParser()

        # nothing we can do...
        raise Exception("url not support: %s" % url)
Esempio n. 10
0
def main():

    ip_file = None
    myargs = getopts(argv)
    if "-f" in myargs:
        ip_file = myargs["-f"]
    else:
        print "Usage: python mission_assign.py -f <input file>"
        exit()

    op_file = ip_file.split(".")[0] + "_output.txt"

    # create parser object
    parser = FileParser(filepath=ip_file)

    # flatten the uas indices into instances, taking into account uas count per uas
    parser.create_uas_index_to_instance_map()
    # setup mission map where each entry is a mission id - compatible uas list map.
    missions = parser.get_domain_for_missions()
    # setup pilot map where each entry is a pilot name - compatible uas list map.
    pilots, pilots_pref = parser.get_domain_for_pilots()
    uas_max = parser.get_uas_instance_count()
    uas_names = parser.get_uas_names()

    # create the solver object
    solver = Solver(pilot_map=pilots,
                    mission_map=missions,
                    uas_max=uas_max,
                    pilot_prefs={})

    # build the domain variables
    solver.build_variables()
    # build the constraints
    solver.build_constraints()

    # start the timer for 90 seconds
    t = threading.Timer(90.0, timeout)
    t.start()
    # solve the 'problem'
    solution = solver.get_solution()
    # solution was found, timer can be stopped
    t.cancel()

    if solution:

        # pretty print logic follows
        print "Solution found! Writing to file..." + op_file
        pretty_map = {}
        for key, value in solution.iteritems():
            if type(key) == int:
                if value in pretty_map:
                    pretty_map[value]["mission"].append(key)
                else:
                    pretty_map[value] = {
                        "mission": [key],
                        "pilot": None,
                        "uas":
                        uas_names[parser.get_uas_index_from_instance(value)],
                        "fav": None
                    }

        sorted_pretty_list = [None] * len(missions)

        for key, value in solution.iteritems():
            if type(key) != int:
                pretty_map[value]["pilot"] = key
                pretty_map[value][
                    "fav"] = "Yes" if value in pilots_pref[key] else "No"

        for uas, value in pretty_map.iteritems():
            missions = value["mission"]
            for mission in missions:
                sorted_pretty_list[mission] = str("M" + str(mission + 1) +
                                                  " " + value["pilot"] + " " +
                                                  value["uas"] + " " +
                                                  value["fav"])

        with open(op_file, 'w') as f:
            for assignment in sorted_pretty_list:
                f.write(assignment + "\n")
                print assignment
    else:
        print "No solution found!"
        with open(op_file, 'w') as f:
            f.write("No solution found!" + "\n")
Esempio n. 11
0
class ParserGUI:

    # Initialize the class by creating a window with various widgets.
    def __init__(self, master):
        self.master = master
        master.title("JSON Parser")

        # Create a Frame for the window that holds all the other widgets used below
        mainframe = ttk.Frame(master, padding="5 5 12 12")
        mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
        master.columnconfigure(0, weight=1)
        master.rowconfigure(0, weight=1)

        # Creates an empty list that will eventually hold all the keys found in the JSON File.
        # Then create a Button that will load a JSON file to parse.
        self.keylist = list()
        file_button = ttk.Button(mainframe,
                                 text="Load New File",
                                 command=self.new_file)
        file_button.grid(column=3, row=3, sticky=(E))

        # A Label widget that will display the name of the file currently being parsed
        self.name = ttk.Label(mainframe)
        self.name.grid(column=5, row=3)
        self.name.config(text="No File has Been Loaded")

        # A Label and Combobox widget that displays the key the user would like to search for
        ttk.Label(mainframe, text="Key to search:  ").grid(column=0,
                                                           row=0,
                                                           sticky=(N, W))
        keysearch = StringVar()
        self.key_search = ttk.Combobox(mainframe, textvariable=keysearch)
        self.key_search['values'] = self.keylist
        self.key_search.grid(column=1, row=0)

        # A Label and Combobox widget that displays the key the user would like returned to them
        ttk.Label(mainframe, text="Key to extract:  ").grid(column=0,
                                                            row=1,
                                                            sticky=(N, W))
        keyextract = StringVar()
        self.key_extract = ttk.Combobox(mainframe, textvariable=keyextract)
        self.key_extract['values'] = self.keylist
        self.key_extract.grid(column=1, row=1)

        # An optional Label and Entry widget that allows the user to input a string that matches with the key they are searching with.
        user_input = ttk.Label(mainframe, text="Content to look for: ")
        user_input.grid(column=0, row=2)
        self.user_string = StringVar()
        string_input = ttk.Entry(mainframe, textvariable=self.user_string)
        string_input.grid(column=1, row=2)

        # A Button that will start the parsing process
        search_button = ttk.Button(mainframe, text="Search", command=self.find)
        search_button.grid(column=0, row=3, sticky=(W))

        # A Text widget that will display the parsed information
        self.results = tk.Text(master, height=10, width=200)
        self.results.grid(column=0, row=4, sticky=(N, S, E, W))

        # A Scrollbar widget created to easily move across the text box
        yscroll = ttk.Scrollbar(master, command=self.results.yview)
        yscroll.grid(column=1, row=4, sticky=(N, S, E, W))
        self.results['yscrollcommand'] = yscroll.set

    # Calls the 'parse' method in FileParser and gives it the search, extract, and uinput parameters
    def find(self):
        search = self.key_search.get()
        extract = self.key_extract.get()
        uinput = self.user_string.get()

        self.content = self.parser.parse(search, extract, uinput)

        self.results.delete(1.0, tk.END)  # Clears the current text box

        # If there was no content found in the file return a specified message
        # Otherwise return the matching data
        if not self.content:
            self.results.insert(tk.END, "No Matchng Results Found.")
        else:
            for x in self.content:
                self.results.insert(tk.END, x + '\n')

    # Has the user select a file to parse, and sends the name of the file to FileParser
    # Also resets the Comboboxes to the first key found in the JSON File
    # We also set the name label initialized above to the file name found here
    def new_file(self):
        self.master.filename = filedialog.askopenfilename(
            initialdir="./json",
            title="Select file",
            filetypes=(("json files", "*.json"), ("all files", "*.*")))

        self.parser = FileParser(self.master.filename)
        self.keylist = self.parser.findKeys()

        self.key_search['values'] = self.keylist
        self.key_extract['values'] = self.keylist

        self.key_search.current(0)
        self.key_extract.current(0)

        file = os.path.basename(self.master.filename)
        self.name.config(text="Current File: " + file)