Ejemplo n.º 1
0
class Mjolnir3(KRCCModule):
  def __init__(self, root):
    super().__init__()
    self.root = root
    self.exception = None

    self.list_string = StringVar()
    self.listbox = Listbox(root, listvariable=self.list_string,
                           font='TkFixedFont', width=300)

    self.load()

  def establish_connection_and_run(self):
    error = None
    dots = 0
    connection = None
    while not self.terminate:
      try:
        if connection is None:
          connection = krpc.connect(name=self.name)
        self.run_with_connection(connection)
        error = None
        dots = 0
      except Exception as e:
        if error != e.args[0]:
          error = e.args[0]
          print('\n')
          print(traceback.format_exc())
          sys.stdout.write('Retrying...\n')
        if dots > 80:
          dots = 0
          sys.stdout.write('\n')
        sys.stdout.write('.')
        dots += 1
        sys.stdout.flush()
        time.sleep(1)
    if connection is not None:
      connection.close()

  def run_with_connection(self, connection):
    logging.debug('KRPC connection established')
    strategy = PreLaunch(connection)
    while not self.terminate:
      strategy = strategy.update()
      self.list_string.set(tuple(strategy.display()))

  def run(self):
    try:
      self.establish_connection_and_run()
      self.listbox.destroy()
    except RuntimeError:
      # Should only happen when KeyboardInterrupt is thrown in the MainThread.
      pass

  @property
  def name(self):
    return 'Mjolnir 3'

  def load(self):
    self.listbox.pack(side=LEFT, fill=BOTH)
Ejemplo n.º 2
0
class Autocomplete(Entry):
    def __init__(self, *args, **kwargs):
        Entry.__init__(self, *args, **kwargs)
        self.var = self["textvariable"]
        if self.var == '':
            self.var = self["textvariable"] = tk.StringVar()
        self.lb_up = False
        self.bind("<space>", self.changed)

    def changed(self, args):
        if self.var.get() == '':
            self.lb.destroy()
            self.lb_up = False
        else:
            words = self.comparison()
            if words:
                if not self.lb_up:
                    self.lb = Listbox()
                    self.lb.place(x=self.winfo_x(),
                                  y=self.winfo_y() + self.winfo_height())
                    self.lb_up = True

                #self.lb.delete(0, 'end')
                for w in words:
                    self.lb.insert('end', w)
            else:
                if self.lb_up:
                    self.lb.destroy()
                    self.lb_up = False

    def comparison(self):
        pattern = self.var.get()
        return [sug for sug in suggestion.suggest(pattern)]
Ejemplo n.º 3
0
class LoadGame(Window):
    def __init__(self, program):
        super().__init__(program)
        self.frame = Frame(program.master, width=800, height=800)
        self.frame.pack(side='top', fill='both', expand=1)
        self.listbox = Listbox()
        self.save_names = []

    def dispose(self):
        self.listbox.pack_forget()
        self.frame.pack_forget()
        self.listbox.destroy()
        self.frame.destroy()
        self.listbox = None
        self.frame = None

    def show(self):
        for file_name, file_path in self.program.settings.list_saves():
            self.listbox.insert(END, file_name)
            self.save_names.append(file_name)
        self.listbox.pack()
        self.add_button('Back', self.back)
        self.add_button('Load', self.load)

    def load(self):
        selection = next(iter(map(int, self.listbox.curselection())))
        self.dispose()
        g = Game(self.program)
        g.load(self.save_names[selection])
        self.change(g)

    def back(self):
        self.dispose()
        self.change(LoginScreen(self.program))

    def add_button(self, text, command):
        button = Button(self.frame,
                        text=text,
                        width=100,
                        height=20,
                        command=command)
        button.pack()
Ejemplo n.º 4
0
class Tenacity2(KRCCModule):
  def __init__(self, root):
    super().__init__()
    self.arbitrary_list = [
        ('bla', random.uniform(0, 500)),
        ('blub', random.randint(1, 10)),
        ('hurrz', 'yolo'),
        'sploink',
    ]
    self.listbox = Listbox(root)
    self.canvas = Canvas(root)
    self.load()

  def __del__(self):
    self.canvas.destroy()
    self.listbox.destroy()

  def run(self):
    while not self.terminate:
      pass

  def name(self):
    return 'Tenacity 2'

  def load(self):
    for item in self.arbitrary_list:
      insert_item = 'error'
      if type(item) == type(''):
        insert_item = item
      elif type(item) == type(()):
        key = item[0]
        value = '%s' % item[1]
        if type(item[1]) == float:
          value = '%8.3f' % item[1]
        insert_item = '%s: %s' % (key, value)
      self.listbox.insert(END, insert_item)
    self.listbox.pack(side=LEFT, fill=Y)
    self.canvas.pack(side=RIGHT, fill=BOTH, expand=True)
class AutocompleteEntry(Entry):
    def __init__(self, lista, *args, **kwargs):

        Entry.__init__(self, *args, **kwargs)
        self.lista = lista
        self.var = self["textvariable"]
        if self.var == '':
            self.var = self["textvariable"] = StringVar()

        self.var.trace('w', self.changed)
        self.bind("<Right>", self.selection)
        self.bind("<Up>", self.up)
        self.bind("<Down>", self.down)

        self.lb_up = False

    def changed(self, name, index, mode):

        if self.var.get() == '':
            self.lb.destroy()
            self.lb_up = False
        else:
            words = self.comparison()
            if words:
                if not self.lb_up:
                    self.lb = Listbox()
                    self.lb.bind("<Double-Button-1>", self.selection)
                    self.lb.bind("<Right>", self.selection)
                    self.lb.place(x=self.winfo_x(),
                                  y=self.winfo_y() + self.winfo_height())
                    self.lb_up = True

                self.lb.delete(0, END)
                for w in words:
                    self.lb.insert(END, w)
            else:
                if self.lb_up:
                    self.lb.destroy()
                    self.lb_up = False

    def selection(self, event):

        if self.lb_up:
            self.var.set(self.lb.get(ACTIVE))
            self.lb.destroy()
            self.lb_up = False
            self.icursor(END)

    def up(self, event):

        if self.lb_up:
            if self.lb.curselection() == ():
                index = '0'
            else:
                index = self.lb.curselection()[0]
            if index != '0':
                self.lb.selection_clear(first=index)
                index = str(int(index) - 1)
                self.lb.selection_set(first=index)
                self.lb.activate(index)

    def down(self, event):

        if self.lb_up:
            if self.lb.curselection() == ():
                index = '0'
            else:
                index = self.lb.curselection()[0]
            if index != END:
                self.lb.selection_clear(first=index)
                index = str(int(index) + 1)
                self.lb.selection_set(first=index)
                self.lb.activate(index)

    def comparison(self):
        pattern = re.compile('.*' + self.var.get() + '.*')
        return [w for w in self.lista if re.match(pattern, w)]
Ejemplo n.º 6
0
class StreamFrame(Frame):
    def __init__(self, master):
        super(StreamFrame, self).__init__(master)
        self.root = master

        # check if user has saved the training sentiment analyzers
        pol_checkfile = os.path.exists('files/sa_polarity.pickle')
        subj_checkfile = os.path.exists('files/sa_subjectivity.pickle')

        if not (pol_checkfile
                and subj_checkfile):  # if we cant find the SA files
            # These frames will hold the widgets
            nofiles_frm = Frame(
                self
            )  # this for the the warning message and the back and exit buttons
            nofiles_frm.grid(row=3, column=0, pady=5)
            exit_frm = Frame(self)  # exit frame, contains back and exit button
            exit_frm.grid(row=4, column=0, pady=5)

            message = "SA files not found."
            read_write.log_message("[WARN] (frames.StreamFrame) : " + message)
            message += "\nClick Start Training first to train the NLTK classifiers."
            Label(nofiles_frm, text=message).grid(row=0,
                                                  column=0,
                                                  padx=10,
                                                  pady=5)

            self.mng_stream_btn = Button(
                nofiles_frm,
                text="Start Stream")  # ignore this, if there are no tweets

            # Build the widgets for nofiles_frm
            self.back_btn = Button(exit_frm, text="Back")
            self.back_btn.grid(row=1, column=1, ipadx=5, ipady=3, pady=15)
            self.exit_btn = Button(exit_frm,
                                   text="Exit",
                                   command=self.safe_exit)
            self.exit_btn.grid(row=1,
                               column=3,
                               ipadx=5,
                               ipady=3,
                               padx=15,
                               pady=10)
        else:
            # These frames will hold the widgets
            label_frm = Frame(self)  # this for the label and entry
            label_frm.grid(row=0,
                           column=2,
                           padx=10,
                           pady=10,
                           ipady=20,
                           ipadx=20)

            # Frame for keywords
            self.keywords_frm = Frame(
                self
            )  # this will be hidden until user wants to see previous keywords
            self.keywords_frm.grid(row=0, column=3, rowspan=3, pady=15)

            # Build the widgets for label_frm
            Label(label_frm, text="Keyword:").grid(row=0, column=0, padx=20)
            self.keyword_entry = Entry(label_frm, width=30)
            self.keyword_entry.grid(row=0, column=1, columnspan=3)

            # Build the widgets for button_frm
            self.mng_stream_btn = Button(
                label_frm,
                text="Start Stream")  # this will change from start to stop
            self.mng_stream_btn.grid(row=1,
                                     column=1,
                                     ipadx=5,
                                     ipady=3,
                                     pady=20)
            self.pause_stream_btn = Button(
                label_frm,
                text="Pause Stream")  # if user starts stream, show this button
            self.pause_stream_btn.grid(row=1,
                                       column=3,
                                       ipadx=5,
                                       ipady=3,
                                       padx=10,
                                       pady=20)
            self.pause_stream_btn.grid_remove()

            # Build the widgets for keywords_frm
            self.manage_keywords_btn = Button(
                self.keywords_frm, command=self.show_keywords,
                text=">>>")  # this will change into "<<<" when user clicks it
            self.manage_keywords_btn.grid(row=0,
                                          column=0,
                                          ipadx=5,
                                          ipady=3,
                                          padx=10)

            # Build the widgets for exit_frm
            self.back_btn = Button(label_frm, text="Back")
            self.back_btn.grid(row=2, column=1, ipadx=5, ipady=3, pady=15)
            self.exit_btn = Button(label_frm,
                                   text="Exit",
                                   command=self.safe_exit)
            self.exit_btn.grid(row=2,
                               column=3,
                               ipadx=5,
                               ipady=3,
                               padx=15,
                               pady=10)

    # this method creates a new list box and populates it with the data from keywords.json
    def show_keywords(self):
        # first re-configure the button to show the desired text and change the command into hiding method
        self.manage_keywords_btn.config(text="<<<", command=self.hide_keywords)

        self.previous_keywords = read_write.read_keywords(
        )  # get any previous keywords

        # if there are keywords and the list is not empty
        if len(self.previous_keywords) > 0:
            # build the list box
            self.keyword_lb = Listbox(self.keywords_frm, height=10)
            self.keyword_lb.grid(column=1,
                                 row=0,
                                 pady=10,
                                 padx=5,
                                 sticky=(N, S, E, W))
            # add a binding method
            self.keyword_lb.bind('<Double-1>', self.select_keyword)
            # and add the OK button. This happens here, because we don'w want a button without a list box
            self.select_keyword_btn = Button(self.keywords_frm,
                                             text="OK",
                                             command=self.select_keyword)
            self.select_keyword_btn.grid(row=3,
                                         column=1,
                                         ipady=3,
                                         ipadx=5,
                                         pady=10)

            # adding the keywords to the list box
            counter = 0
            for keyword in self.previous_keywords:
                self.keyword_lb.insert(counter, keyword)
                counter += 1

            # Colorize alternating lines of the listbox
            for i in range(0, len(self.previous_keywords), 2):
                self.keyword_lb.itemconfigure(i, background='#f0f0ff')

    # this method changes the button again and it is called to hide the list box
    def hide_keywords(self):
        self.manage_keywords_btn.config(text=">>>", command=self.show_keywords)
        try:
            # this may result to an error, because we can call hide_keywords before we initialize
            # the list box. This happening if no keywords are present in keywords.json
            self.keyword_lb.destroy()
            self.select_keyword_btn.destroy()
        except AttributeError:
            pass

    def select_keyword(self, *args):
        idxs = self.keyword_lb.curselection()
        if len(idxs) == 1:
            idx = int(idxs[0])
            name = self.previous_keywords[idx]
            self.keyword_entry.delete(0, "end")
            self.keyword_entry.insert(0, name)

    def safe_exit(self):
        x = messagebox.askyesno(title="Exit",
                                message="Are you sure you want to exit?",
                                icon="question")
        if x:
            stream_util.stream_controller.stop()
            read_write.log_message("[INFO]" + stream_util.LOG_NAME +
                                   "Exiting...")
            self.root.destroy()
Ejemplo n.º 7
0
class AutoCompleteEntry(Entry): # pylint: disable=too-many-ancestors
    """
    An entry widget with asdf.
    """
    def __init__(self, autocomplete_list, *args, **kwargs):
        self.autocomplete_list = autocomplete_list
        self.list_box_length = kwargs.pop('list_box_length', 8)
        self.matches_function = kwargs.pop('matches_function',
                                           self._default_match)

        # function to initate_string_var_no_textvariable
        self.textvariable = kwargs.get('textvariable', StringVar())
        self.list_box = None
        super().__init__(*args, **kwargs)
        self.config(textvariable=self.textvariable)
        self.focus()

        self.textvariable.trace('w', self._changed)

    @property
    def existing_list_box(self):
        """
        Check if this instance has its' listbox defined/open.
        """
        return self.__dict__.get('list_box', False)

    @staticmethod
    def _default_match(query, list_entry):
        """
        The default match function if none is given during instantiation.
        """
        pattern = re.compile(re.escape(query) + '.*', re.IGNORECASE)
        return re.match(pattern, list_entry)

    def _changed(self, name, index, mode):
        """
        Event handler for changes to entry.
        """
        print("in _changed")
        print(name, index, mode)

        if self.textvariable.get():  # not empty string
            words = self.__comparison()

            if not words:
                return self.__delete_existing_list_box()

            if not self.existing_list_box:
                self.list_box = Listbox(width=self["width"],
                                        height=self.list_box_length)
                # looks hacky
                self.list_box.place(
                    x=self.winfo_x(), y=self.winfo_y() + self.winfo_height())
                self.list_box.delete(0, END)
                for word in words:
                    self.list_box.insert(END, word)
        else:
            self.__delete_existing_list_box()

    def __delete_existing_list_box(self):
        """
        Deletes open listbox.
        """
        if self.existing_list_box:
            self.list_box.destroy()

    # hmmmm
    def __comparison(self):
        """
        Finds words similar to query. TODO
        """
        if len(self.get()) < 3:
            return []
        ans = [w for w in self.autocomplete_list if
               self.matches_function(self.textvariable.get(), w)]
        print(ans)
        return ans[:5]
Ejemplo n.º 8
0
class Mjolnir3(KRCCModule):
    def __init__(self, root):
        super().__init__()
        self.root = root
        self.exception = None

        self.list_string = StringVar()
        self.listbox = Listbox(root,
                               listvariable=self.list_string,
                               font='TkFixedFont',
                               width=300)

        self.load()

    def establish_connection_and_run(self):
        error = None
        dots = 0
        connection = None
        while not self.terminate:
            try:
                if connection is None:
                    connection = krpc.connect(name=self.name)
                self.run_with_connection(connection)
                error = None
                dots = 0
            except Exception as e:
                if error != e.args[0]:
                    error = e.args[0]
                    print('\n')
                    print(traceback.format_exc())
                    sys.stdout.write('Retrying...\n')
                if dots > 80:
                    dots = 0
                    sys.stdout.write('\n')
                sys.stdout.write('.')
                dots += 1
                sys.stdout.flush()
                time.sleep(1)
        if connection is not None:
            connection.close()

    def run_with_connection(self, connection):
        logging.debug('KRPC connection established')
        strategy = PreLaunch(connection)
        while not self.terminate:
            strategy = strategy.update()
            self.list_string.set(tuple(strategy.display()))

    def run(self):
        try:
            self.establish_connection_and_run()
            self.listbox.destroy()
        except RuntimeError:
            # Should only happen when KeyboardInterrupt is thrown in the MainThread.
            pass

    @property
    def name(self):
        return 'Mjolnir 3'

    def load(self):
        self.listbox.pack(side=LEFT, fill=BOTH)
Ejemplo n.º 9
0
class AutocompleteEntry(Entry):

    def __init__(self, *args, **kwargs):
        Entry.__init__(self, width=100, *args, **kwargs)

        self.focus_set()
        self.pack()

        self.var = self["textvariable"]
        if self.var == '':
            self.var = self["textvariable"] = StringVar()

        self.var.trace('w', self.changed)
        self.bind("<Right>", self.selection)
        self.bind("<Up>", self.up)
        self.bind("<Down>", self.down)
        self.bind("<Return>", self.enter)
        self.lb_up = False
        self.lb = None

    def enter(self, event):
        print(event)

    def changed(self, name, index, mode):

        if self.var.get() == '':
            if self.lb:
                self.lb.destroy()
            self.lb_up = False
        else:
            words = self.comparison()
            if words:
                if not self.lb_up:
                    self.lb = Listbox(master=root, width=100)

                    self.lb.bind("<Double-Button-1>", self.selection)
                    self.lb.bind("<Right>", self.selection)
                    self.lb.place(x=self.winfo_x(), y=self.winfo_y()+self.winfo_height())
                    self.lb_up = True

                self.lb.delete(0, END)
                for w in words:
                    self.lb.insert(END,w)
            else:
                if self.lb_up:
                    self.lb.destroy()
                    self.lb_up = False

    def selection(self, _):

        if self.lb_up:
            self.var.set(self.lb.get(ACTIVE))
            self.lb.destroy()
            self.lb_up = False
            self.icursor(END)

    def up(self, _):

        if self.lb_up:
            if self.lb.curselection() == ():
                index = '0'
            else:
                index = self.lb.curselection()[0]
            if index != '0':
                self.lb.selection_clear(first=index)
                index = str(int(index)-1)
                self.lb.selection_set(first=index)
                self.lb.activate(index)

    def down(self, _):

        if self.lb_up:
            if self.lb.curselection() == ():
                index = '0'
            else:
                index = self.lb.curselection()[0]
            if index != END:
                self.lb.selection_clear(first=index)
                index = str(int(index)+1)
                self.lb.selection_set(first=index)
                self.lb.activate(index)

    def comparison(self):
        q = self.var.get()
        q = str(q.decode('utf8'))
        for hit in searcher.search(qp.parse(q), limit=50):
            if hit['author']:
                yield '%s. "%s"' % (hit['author'], hit['title'])
            else:
                yield hit['title']
Ejemplo n.º 10
0
class AutocompleteEntry(Entry):
    def __init__(self, autocompleteList, *args, **kwargs):

        # Listbox length
        if 'listboxLength' in kwargs:
            self.listboxLength = kwargs['listboxLength']
            del kwargs['listboxLength']
        else:
            self.listboxLength = 8

        # Custom matches function
        if 'matchesFunction' in kwargs:
            self.matchesFunction = kwargs['matchesFunction']
            del kwargs['matchesFunction']
        else:

            def matches(fieldValue, acListEntry):
                pattern = re.compile('.*' + re.escape(fieldValue) + '.*',
                                     re.IGNORECASE)
                return re.match(pattern, acListEntry)

            self.matchesFunction = matches

        Entry.__init__(self, *args, **kwargs)
        self.focus()

        self.autocompleteList = autocompleteList

        self.var = self["textvariable"]
        if self.var == '':
            self.var = self["textvariable"] = StringVar()

        self.var.trace('w', self.changed)
        self.bind("<Right>", self.selection)
        self.bind("<Up>", self.moveUp)
        self.bind("<Down>", self.moveDown)

        self.listboxUp = False

    def changed(self, name, index, mode):
        if self.var.get() == '':
            if self.listboxUp:
                self.listbox.destroy()
                self.listboxUp = False
        else:
            words = self.comparison()
            if words:
                if not self.listboxUp:
                    self.listbox = Listbox(width=self["width"],
                                           height=self.listboxLength)
                    self.listbox.bind("<Button-1>", self.selection)
                    self.listbox.bind("<Right>", self.selection)
                    self.listbox.place(x=self.winfo_x(),
                                       y=self.winfo_y() + self.winfo_height())
                    self.listboxUp = True

                self.listbox.delete(0, END)
                for w in words:
                    self.listbox.insert(END, w)
            else:
                if self.listboxUp:
                    self.listbox.destroy()
                    self.listboxUp = False

    def selection(self, event):
        if self.listboxUp:
            self.var.set(self.listbox.get(ACTIVE))
            self.listbox.destroy()
            self.listboxUp = False
            self.icursor(END)

    def moveUp(self, event):
        if self.listboxUp:
            if self.listbox.curselection() == ():
                index = '0'
            else:
                index = self.listbox.curselection()[0]

            if index != '0':
                self.listbox.selection_clear(first=index)
                index = str(int(index) - 1)

                self.listbox.see(index)  # Scroll!
                self.listbox.selection_set(first=index)
                self.listbox.activate(index)

    def moveDown(self, event):
        if self.listboxUp:
            if self.listbox.curselection() == ():
                index = '0'
            else:
                index = self.listbox.curselection()[0]

            if index != END:
                self.listbox.selection_clear(first=index)
                index = str(int(index) + 1)

                self.listbox.see(index)  # Scroll!
                self.listbox.selection_set(first=index)
                self.listbox.activate(index)

    def comparison(self):
        return [
            w for w in self.autocompleteList
            if self.matchesFunction(self.var.get(), w)
        ]
Ejemplo n.º 11
0
class AvionicsLogger(KRCCModule):
    def __init__(self, root):
        super().__init__()
        self.root = root
        self.exception = None

        self.list_string = StringVar()
        self.listbox = Listbox(root,
                               listvariable=self.list_string,
                               font='TkFixedFont',
                               width=30)

        self.write_cache = ''
        self.logfile = None
        self.enable_logging = BooleanVar()
        self.enable_logging_checkbox = Checkbutton(
            root,
            var=self.enable_logging,
            text='Enable logging',
            command=self.enable_logging_changed)

        self.logfile_label = Label(root, text='Logfile name:')
        self.logfile_name = StringVar()
        self.logfile_name_entry = Entry(root, textvar=self.logfile_name)

        self.load()

    def write(self, string):
        if self.enable_logging.get() and self.logfile is None:
            if self.logfile_name.get() == '':
                self.logfile_name.set('logs/{}.log'.format(time.time()))
            self.logfile = io.open(self.logfile_name.get(), 'a')
            self.logfile.write(self.write_cache)
            self.write_cache = ''
        self.logfile.write(string)

    def cache(self, string):
        self.write_cache += string

    def enable_logging_changed(self):
        if not self.enable_logging.get():
            self.logfile_name_entry.configure(state=NORMAL)
            if self.logfile is not None:
                self.logfile.close()
                self.logfile = None
                self.logfile_name.set('')
        else:
            self.logfile_name_entry.configure(state=DISABLED)

    def establish_connection_and_run(self):
        error = None
        dots = 0
        connection = None
        while not self.terminate:
            try:
                if connection is None:
                    connection = krpc.connect(name=self.name)
                self.run_with_connection(connection)
                error = None
                dots = 0
            except Exception as e:
                if error != e.args[0]:
                    error = e.args[0]
                    print('\n')
                    print(traceback.format_exc())
                    sys.stdout.write('Retrying')
                if dots > 80:
                    dots = 0
                    sys.stdout.write('\n')
                sys.stdout.write('.')
                dots += 1
                sys.stdout.flush()
                time.sleep(1)
        if connection is not None:
            connection.close()

    def run_with_connection(self, connection):
        logging.debug('KRPC connection established')
        vessel = connection.space_center.active_vessel
        ref = vessel.orbit.body.reference_frame
        flight = connection.add_stream(vessel.flight, ref)
        floats = [
            'mean_altitude',
            'atmosphere_density',
            'ballistic_coefficient',
            'drag_coefficient',
        ]
        vectors = [
            'velocity',
        ]
        colon_pos_float = max([len(v) for v in floats])
        colon_pos_vec = max([len(v) + 3 for v in vectors])
        self.listbox.configure(width=max(colon_pos_float, colon_pos_vec) + 11)

        # Write the log file header.
        self.cache('time\t' + '\t'.join(floats) + '\t')
        s = '{}\t' + '\t'.join('{{}}[{}]'.format(x) for x in [0, 1, 2])
        self.cache('\t'.join(
            s.format(*(v for _ in [0, 1, 2, 3])) for v in vectors))
        self.cache('\n')
        log_sample_interval = 0.01
        next_log_sample = time.time()
        while not self.terminate:
            values = [time.time()]
            strings = []
            for name in floats:
                value = flight().__getattribute__(name)
                values.append(value)
                padding = colon_pos_float - len(name) + 9
                format_string = '{{}}: {{:>{}.3f}}'.format(padding)
                strings.append(format_string.format(name, value))
            for name in vectors:
                value = flight().__getattribute__(name)
                magnitude = value[0]
                padding = colon_pos_float - len(name) + 9
                format_string = '{{}}: {{:>{}.3f}}'.format(padding)
                strings.append(format_string.format(name, magnitude))
                values.append(magnitude)
                padding = colon_pos_vec - len(name) + 2
                format_string = '{{}}[{{}}]: {{:>{}.3f}}'.format(padding)
                for i in [0, 1, 2]:
                    values.append(value[i])
                    strings.append(format_string.format(name, i, value[i]))
            if self.enable_logging.get() and time.time() > next_log_sample:
                self.write('\t'.join(['{}'.format(v) for v in values]) + '\n')
                next_log_sample = time.time() + log_sample_interval
            self.list_string.set(tuple(strings))

    def run(self):
        try:
            self.establish_connection_and_run()
            self.logfile_name_entry.destroy()
            self.logfile_label.destroy()
            self.enable_logging_checkbox.destroy()
            self.listbox.destroy()
        except RuntimeError:
            # Should only happen when KeyboardInterrupt is thrown in the MainThread.
            pass
        if self.logfile is not None:
            self.logfile.close()

    @property
    def name(self):
        return 'Avionics Logger'

    def load(self):
        self.listbox.pack(side=LEFT, fill=BOTH)
        self.logfile_label.pack(side=LEFT, anchor=NW)
        self.logfile_name_entry.pack(side=LEFT, anchor=NE, fill=X, expand=True)
        self.enable_logging_checkbox.pack(side=LEFT, anchor=NW)
class Window(object):
    """"This class creates a GUI using the built in python libary tkinter"""

    def __init__(self, window):
        self.window = window

        self.check = False

        self.animateval = False

        titlel = Label(window, text="Evolutionary Spatial Games", height=3)
        titlel.grid(row=0, column=0, rowspan=2)

        self.cellularAutomata = Canvas(window, height=600, width=600, background="blue")
        self.cellularAutomata.grid(row=2, column=0, rowspan="20")

        l2 = Label(window, text="Payoff matrix:", width=16)
        l2.grid(row=3, column=1)

        l3 = Label(window, text="Cell size: ", width=16)
        l3.grid(row=6, column=1)

        l8 = Label(window, text="Moore Neighbourhood: ", width=22)
        l8.grid(row=7, column=1)

        l9 = Label(window, text="Von Nuemann Neighbourhood: ", width=26)
        l9.grid(row=8, column=1)

        l4 = Label(window, text="Initial Distribution: ", width=16)
        l4.grid(row=10, column=1)

        l9 = Label(window, text="Fixed boundary (A): ", width=26)
        l9.grid(row=11, column=1)

        l9 = Label(window, text="Reflective boundary:  ", width=26)
        l9.grid(row=12, column=1)

        l9 = Label(window, text="Periodic boundary: ", width=26)
        l9.grid(row=13, column=1)

        la = Label(window, text="Count (A|B|C): ", width=16)
        la.grid(row=16, column=1)

        l5 = Label(window, text="Iterations: ", width=16)
        l5.grid(row=17, column=1)

        b1 = Button(window, text="Draw", command=self.draw_command)
        b1.grid(row=19, column=1)

        self.b2 = Button(window, text="Start", command=self.begin_command)
        self.b2.grid(row=19, column=2)

        self.e1 = Scale(
            window, width=8, orient=HORIZONTAL, from_=2, to=3, label="Strategies"
        )
        self.e1.grid(row=0, column=1)

        self.e1.bind("<ButtonRelease-1>", self.change_entry)

        self.li = Label(window, text="B invades A: ", width=16)
        self.li.grid(row=14, column=1)

        self.ival = IntVar()
        self.iv = Checkbutton(window, variable=self.ival)
        self.iv.grid(row=14, column=2)

        self.ld = Label(window, text="Dynamic", width=16)
        self.ld.grid(row=15, column=1)

        self.dyval = IntVar()
        self.dyval.set(1)
        self.dy = Checkbutton(window, variable=self.dyval)
        self.dy.grid(row=15, column=2)

        self.e2 = IntVar()
        self.e2 = Entry(window, textvariable=self.e2, width=6)
        self.e2.grid(row=3, column=2)

        self.e3 = IntVar()
        self.e3 = Entry(window, textvariable=self.e3, width=6)
        self.e3.grid(row=3, column=3)

        self.e4 = IntVar()
        self.e4 = Entry(window, textvariable=self.e4, width=6)
        self.e4.grid(row=4, column=2)

        self.e5 = IntVar()
        self.e5 = Entry(window, textvariable=self.e5, width=6)
        self.e5.grid(row=4, column=3)

        self.cellsize = IntVar()
        self.cellsize.set(8)
        self.cellsize = Entry(window, textvariable=self.cellsize, width=6)
        self.cellsize.grid(row=6, column=2)

        self.p1 = DoubleVar()
        self.p1 = Entry(window, textvariable=self.p1, width=6)
        self.p1.grid(row=10, column=2)

        self.p2 = DoubleVar()
        self.p2 = Entry(window, textvariable=self.p2, width=6)
        self.p2.grid(row=10, column=3)

        self.neighbourE = IntVar()
        self.neighbourE.set(1)
        self.moore = Radiobutton(window, variable=self.neighbourE, value=1)
        self.moore.grid(row=7, column=2)

        self.nuemann = Radiobutton(window, variable=self.neighbourE, value=2)
        self.nuemann.grid(row=8, column=2)

        self.boundaryvar = IntVar()
        self.boundaryvar.set(2)
        self.fixed = Radiobutton(window, variable=self.boundaryvar, value=1)
        self.fixed.grid(row=11, column=2)

        self.reflective = Radiobutton(window, variable=self.boundaryvar, value=2)
        self.reflective.grid(row=12, column=2)

        self.periodic = Radiobutton(window, variable=self.boundaryvar, value=3)
        self.periodic.grid(row=13, column=2)

        self.a1 = Listbox(window, width=4, height=1)
        self.a1.grid(row=16, column=2)

        self.a2 = Listbox(window, width=4, height=1)
        self.a2.grid(row=16, column=3)

        self.i1 = Listbox(window, width=4, height=1)
        self.i1.grid(row=17, column=2)

    def draw_command(self):
        self.cellularAutomata.delete("all")
        self.count = 0
        self.i1.delete(0, END)
        self.i1.insert(END, self.count)
        try:
            self.b3.destroy()
            self.b2 = Button(window, text="Start", command=self.begin_command)
            self.b2.grid(row=19, column=2)
        except AttributeError:
            pass
        try:
            if self.e1.get() == 2:
                matrix = [
                    [self.e2.get(), self.e3.get()],
                    [self.e4.get(), self.e5.get()],
                ]
                self.SpatialGame = spatialGame(
                    600,
                    600,
                    self.cellsize.get(),
                    [self.p1.get(), self.p2.get()],
                    self.e1.get(),
                    matrix,
                    self.ival.get(),
                    self.neighbourE.get(),
                    self.boundaryvar.get(),
                    self.dyval.get(),
                )
            if self.e1.get() == 3:
                matrix = [
                    [self.e2.get(), self.e3.get(), self.e6.get()],
                    [self.e4.get(), self.e5.get(), self.e7.get()],
                    [self.e8.get(), self.e9.get(), self.e10.get()],
                ]
                self.SpatialGame = spatialGame(
                    600,
                    600,
                    self.cellsize.get(),
                    [self.p1.get(), self.p2.get(), self.p3.get()],
                    self.e1.get(),
                    matrix,
                    self.ival.get(),
                    self.neighbourE.get(),
                    self.boundaryvar.get(),
                    self.dyval.get(),
                )
            self.cells = self.SpatialGame.cells
            for x in range(0, self.SpatialGame.width):
                for y in range(0, self.SpatialGame.height):
                    if self.cells[x][y] == 2:
                        square_coords = (
                            x * self.SpatialGame.cell_size,
                            y * self.SpatialGame.cell_size,
                            x * self.SpatialGame.cell_size + self.SpatialGame.cell_size,
                            y * self.SpatialGame.cell_size + self.SpatialGame.cell_size,
                        )
                        self.cellularAutomata.create_rectangle(
                            square_coords, fill="red", outline="red"
                        )
                    if self.SpatialGame.cells[x][y] == 3:
                        square_coords = (
                            x * self.SpatialGame.cell_size,
                            y * self.SpatialGame.cell_size,
                            x * self.SpatialGame.cell_size + self.SpatialGame.cell_size,
                            y * self.SpatialGame.cell_size + self.SpatialGame.cell_size,
                        )
                        self.cellularAutomata.create_rectangle(
                            square_coords, fill="pink", outline="pink"
                        )
        except ValueError:
            self.cellularAutomata.create_text(
                300,
                300,
                fill="White",
                font="Times 20 bold",
                text="Your probability distribution must add to 1.",
            )

    def begin_command(self):
        self.animateval = True
        self.animate()

    def next(self):
        self.cellularAutomata.delete("all")
        self.SpatialGame.run_rules()
        self.cells = self.SpatialGame.cells
        self.count = self.count + 1
        self.i1.delete(0, END)
        self.i1.insert(END, self.count)
        self.b2.destroy()
        self.b3 = Button(window, text="Stop", command=self.stop_command)
        self.b3.grid(row=19, column=2)
        self.animateval = True
        for x in range(0, self.SpatialGame.width):
            for y in range(0, self.SpatialGame.height):
                if self.cells[x][y] == 2:
                    square_coords = (
                        x * self.SpatialGame.cell_size,
                        y * self.SpatialGame.cell_size,
                        x * self.SpatialGame.cell_size + self.SpatialGame.cell_size,
                        y * self.SpatialGame.cell_size + self.SpatialGame.cell_size,
                    )
                    self.cellularAutomata.create_rectangle(
                        square_coords, fill="red", outline="red"
                    )
                if self.cells[x][y] == 4:
                    square_coords = (
                        x * self.SpatialGame.cell_size,
                        y * self.SpatialGame.cell_size,
                        x * self.SpatialGame.cell_size + self.SpatialGame.cell_size,
                        y * self.SpatialGame.cell_size + self.SpatialGame.cell_size,
                    )
                    self.cellularAutomata.create_rectangle(
                        square_coords, fill="green", outline="green"
                    )
                if self.cells[x][y] == 5:
                    square_coords = (
                        x * self.SpatialGame.cell_size,
                        y * self.SpatialGame.cell_size,
                        x * self.SpatialGame.cell_size + self.SpatialGame.cell_size,
                        y * self.SpatialGame.cell_size + self.SpatialGame.cell_size,
                    )
                    self.cellularAutomata.create_rectangle(
                        square_coords, fill="yellow", outline="yellow"
                    )
                if self.cells[x][y] == 3:
                    square_coords = (
                        x * self.SpatialGame.cell_size,
                        y * self.SpatialGame.cell_size,
                        x * self.SpatialGame.cell_size + self.SpatialGame.cell_size,
                        y * self.SpatialGame.cell_size + self.SpatialGame.cell_size,
                    )
                    self.cellularAutomata.create_rectangle(
                        square_coords, fill="pink", outline="pink"
                    )
                if self.cells[x][y] == 6:
                    square_coords = (
                        x * self.SpatialGame.cell_size,
                        y * self.SpatialGame.cell_size,
                        x * self.SpatialGame.cell_size + self.SpatialGame.cell_size,
                        y * self.SpatialGame.cell_size + self.SpatialGame.cell_size,
                    )
                    self.cellularAutomata.create_rectangle(
                        square_coords, fill="purple", outline="purple"
                    )
        self.a1.delete(0, END)
        self.a1.insert(END, self.SpatialGame.stratA)
        self.a2.delete(0, END)
        self.a2.insert(END, self.SpatialGame.stratB)
        try:
            self.a3.delete(0, END)
            self.a3.insert(END, self.SpatialGame.stratC)
        except:
            pass

    def change_entry(self, event):
        if self.e1.get() == 3 and self.check == False:
            self.check = True
            self.e6 = IntVar()
            self.e6 = Entry(window, textvariable=self.e6, width=6)
            self.e6.grid(row=3, column=4)
            self.e7 = IntVar()
            self.e7 = Entry(window, textvariable=self.e7, width=6)
            self.e7.grid(row=4, column=4)
            self.e8 = IntVar()
            self.e8 = Entry(window, textvariable=self.e8, width=6)
            self.e8.grid(row=5, column=2)
            self.e9 = IntVar()
            self.e9 = Entry(window, textvariable=self.e9, width=6)
            self.e9.grid(row=5, column=3)
            self.e10 = IntVar()
            self.e10 = Entry(window, textvariable=self.e10, width=6)
            self.e10.grid(row=5, column=4)
            self.p3 = DoubleVar()
            self.p3 = Entry(window, textvariable=self.p3, width=6)
            self.p3.grid(row=10, column=4)
            self.li.destroy()
            self.iv.destroy()
            self.ival = IntVar()
            self.ival.set(0)
            self.a3 = Listbox(window, width=4, height=1)
            self.a3.grid(row=16, column=4)
        elif self.e1.get() == 2 and self.check == True:
            self.li = Label(window, text="B invades A: ", width=16)
            self.li.grid(row=14, column=1)
            self.ival = IntVar()
            self.iv = Checkbutton(window, variable=self.ival)
            self.iv.grid(row=14, column=2)
            self.check = False
            self.e6.destroy()
            self.e7.destroy()
            self.e8.destroy()
            self.e9.destroy()
            self.e10.destroy()
            self.p3.destroy()
            self.a3.destroy()

    def stop_command(self):
        self.animateval = False
        self.b3.destroy()
        self.b2 = Button(window, text="Start", command=self.begin_command)
        self.b2.grid(row=19, column=2)

    def animate(self):
        while self.animateval == True:
            self.next()
            self.window.update()
            time.sleep(0.5)
Ejemplo n.º 13
0
class Editor(ttk.Notebook):
    COR_FUNDO = '#282a36'
    COR_FRENTE = '#ffffdd'

    def __init__(self, parent):
        self.parent = parent
        ttk.Notebook.__init__(self, master=self.parent)
        self.pack(expand=True, fill='both')
        self.bind('<Button><3>', self.criaMenuFlutuante)
        self.fonte = font.Font(family='Consolas',
                               size=12,
                               weight='normal',
                               slant='roman')
        self.criaAbas()
        self.rolagemHorizontal()

    # // cria o menu flutuante com o widget listbox...

    def criaMenuFlutuante(self, e):
        opcoes = [
            f'Fechar aba atual {" "*14} Ctrl+W',
            f'Selecionar todo o texto{" "*3} Ctrl+A', f'colar{" "*35} Ctrl+V',
            f'copiar{" "*33} Ctrl+C', f'recortar{" "*30} Ctrl+X'
        ]
        self.menuFlutuante = Listbox(self,
                                     width=30,
                                     height=5,
                                     bg=self.COR_FUNDO,
                                     fg=self.COR_FRENTE)
        for x in range(len(opcoes)):
            self.menuFlutuante.insert(x, opcoes[x])
        self.menuFlutuante.place(x=e.x, y=e.y)
        self.menuFlutuante.bind('<Leave>', self.fechaMenuFlutuante)
        self.menuFlutuante.bind('<<ListboxSelect>>', self.menuFlutuanteSelecao)

    # identifica o elemento clicado no menu flutuante
    # e age de acordo com a selecao

    def menuFlutuanteSelecao(self, e=None):
        item = self.menuFlutuante.curselection()[0]
        print(item)
        if item == 0:
            aba = self.index('current')
            self.forget(aba)
        elif item == 1:
            self.selecionarTudo()
        elif item == 2:
            self.colar()
        elif item == 3:
            self.copiar()

    def copiar(self, e=None):
        self.texto.tag_delete('sels')
        texto = self.texto.get(1.0, 'end-1c')
        self.clipboard_clear()
        self.clipboard_append(texto)

    def colar(self):
        self.texto.insert('insert', self.clipboard_get())
        self.texto.tag_delete('sels')

    def recortar(self):
        texto = self.texto.get('1.0', 'end-1c')
        self.texto.delete('1.0', 'end')
        self.clipboard_append(texto)
        self.texto.tag_delete('sels')

    # fecha o menu flutuante quando mouse sai...

    def fechaMenuFlutuante(self, e):
        self.menuFlutuante.destroy()

    # cria as novas abas ao clica no menu ou ctrl+n...

    def criaAbas(self):
        self.frame = Frame(self, bg=self.COR_FUNDO)
        self.contaLinha = Text(self.frame,
                               width=5,
                               bd=0,
                               relief='flat',
                               font=self.fonte,
                               bg=self.COR_FUNDO,
                               fg=self.COR_FRENTE)
        self.contaLinha.bind('<MouseWheel>', self.naoRolar)
        self.frame.pack(fill='both', expand=True)
        self.contaLinha.pack(side='left', anchor='w', fill='y')
        self.texto = Text(self.frame,
                          bd=0,
                          relief='flat',
                          font=self.fonte,
                          bg=self.COR_FUNDO,
                          fg=self.COR_FRENTE,
                          insertbackground='#fff',
                          wrap='none')
        self.texto.focus_force()
        self.add(self.frame, text='aba')
        self.texto.pack(fill='both', side='left', expand=True)
        self.texto.bind('<KeyPress>', self.insereLinhas)
        self.texto.bind('<Tab>', self.espacosTab)
        self.texto.bind('<MouseWheel>', self.detectaRolagem)
        self.texto.bind('<Button><3>', self.criaMenuFlutuante)
        self.texto.bind('<Control_L><w>', self.fechaAba)

    # fecha aba atual com ctrl+w

    def fechaAba(self, e=None):
        aba = self.index('current')
        self.forget(aba)

    def selecionarTudo(self):
        self.texto.tag_add('sels', '1.0', 'end-1c')
        self.texto.tag_config('sels', background='blue')
        self.texto.mark_set('insert', '1.0')
        self.texto.see('insert')
        return 'break'

    # insere as linhas na lateral esquerda...

    def insereLinhas(self, e):
        self.tecla = e.char
        self.autoPar()
        if self.tecla in ['\'', '\"', '(', '{', '[']:
            return 'break'
        self.linhaAtual = float(self.texto.index('end-1c'))
        self.contaLinha.insert(self.linhaAtual + 1,
                               str(int(self.linhaAtual)) + '\n')
        self.deletaLinhas()
        self.texto.tag_delete('sels')

    # deleta as linhas sobresalentes....

    def deletaLinhas(self):
        self.contaLinha.delete(float(self.texto.index('end')), 'insert')
        self.contaLinha.see(float(self.texto.index('insert')) - 1)

    # transforma os TAB´s em 4 espaços...

    def espacosTab(self, e):
        self.texto.insert(self.texto.index('end-1c'), f'{" "*4}')
        return 'break'

    # autocompleta pares de delimitadores

    def autoPar(self):
        tam = self.texto.index('end-1c')
        i = tam.index('.')
        tam = tam[i + 1:]
        pares = ['\'', '\"', '(', '{', '[']
        fechaPares = ['\'', '\"', ')', '}', ']']
        if self.tecla in pares:
            par = pares.index(self.tecla)
        else:
            return
        if len(tam) == 1:
            indice = '%.1f' % (float(self.texto.index('insert')))
        elif len(tam) == 2:
            indice = '%.2f' % (float(self.texto.index('insert')))
        elif len(tam) == 3:
            indice = '%.3f' % (float(self.texto.index('insert')))
        self.texto.mark_set('insert', indice)
        print(indice)
        self.texto.insert(indice, pares[par] + fechaPares[par])

    # detecta a rolagem da area de texto e indica
    # a mesma para o contador de linhas para rolar junto

    def detectaRolagem(self, e):
        self.contaLinha.yview_scroll(int(-1 * (e.delta / 120)), 'units')
        print(int(-1 * (e.delta)))

    # detecta se o comprimento da linha ja atingiu o maximo da lagura da
    # tela e rola automaticamente na horizontal

    def rolagemHorizontal(self):
        self.rolagem = Scrollbar(self.texto, orient='horizontal')
        self.rolagem.pack(side='bottom', fill='x')
        self.rolagem.configure(command=self.texto.xview)
        self.texto.configure(xscrollcommand=self.rolagem.set)

    # impede a rolagem do contador de linhas ao receber um
    # evento de entrada e rolagem do mouse

    def naoRolar(self, e):
        return 'break'