Example #1
0
 def quit(self, *data):
     try:
         self.save_history()
     finally:
         self.logger.debug('gtkshell session stopped at %s.' %
                                                         time.asctime())
         gtk.main_quit()
Example #2
0
 def on_quit_button__clicked(self, button):
     gtk.main_quit()
     self.retval = False
     # oneiric didn't need this, but it is required for
     # precise for reasons unknown
     # application.py as well
     raise SystemExit
Example #3
0
    def __init__(self):
        # Create a new window
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)

        self.window.set_title("Image'd Buttons!")

        # It's a good idea to do this for all windows.
        self.window.connect("destroy", lambda wid: gtk.main_quit())
        self.window.connect("delete_event", lambda a1, a2: gtk.main_quit())

        # Sets the border width of the window.
        self.window.set_border_width(10)

        # Create a new button
        button = gtk.Button()

        # Connect the "clicked" signal of the button to our callback
        button.connect("clicked", self.callback, "cool button")

        # This calls our box creating function
        box1 = xpm_label_box(self.window, "info.xpm", "cool button")

        # Pack and show all our widgets
        button.add(box1)

        box1.show()
        button.show()

        self.window.add(button)
        self.window.show()
Example #4
0
	def on_btnLaunchSave_clicked(self, savedialog):
		#Get pipeline info
		pipeline = self.builder.get_object("cmbPipeline").get_active_text()
		#For mothur, we require the file locations for the template, classifier seqs, and classifier taxa
		if (pipeline.lower() == "mothur"):
			classseqs = self.builder.get_object("txtMClassSeqs").get_text()
			classtaxa = self.builder.get_object("txtMClassTaxa").get_text()
			aligntemplate = self.builder.get_object("txtMAlign").get_text()
			if (classtaxa == "") | (classtaxa == None):
				error_dialogue("Classification Taxonomy file location must be provided.")
				return
			elif (classseqs == "") | (classseqs == None):
				error_dialogue("Classification Sequences file location must be provided.")
				return
			elif (aligntemplate == "") | (aligntemplate == None):
				error_dialogue("Alignment Template file location must be provided.")
				return
		chooser = gtk.FileChooserDialog(title="Save File",action=gtk.FILE_CHOOSER_ACTION_SAVE, \
			buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK))
		chooser.set_default_response(gtk.RESPONSE_OK)
		chooser.set_filter(self.builder.get_object("ftrAx"))
		chooser.set_do_overwrite_confirmation(True)
		response = chooser.run()
		if response == gtk.RESPONSE_OK:
			print chooser.get_filename(), 'selected'
			self.save_session(chooser.get_filename())
			chooser.destroy()
			print "File saved! Exiting..."
			gtk.main_quit()
		else:
			chooser.destroy()
Example #5
0
    def on_destroy(self, widget):
        """
        Called when the window closes.
        """

        # We kill gtk
        gtk.main_quit()
Example #6
0
 def quit_ui(self):
     try:
         gtk.main_quit()
     except RuntimeError:
         # main_quit throws a runtimeerror if it's called outside
         # of the gtk main loop.
         pass
Example #7
0
def main_quit(obj):
	"""main_quit function, it stops the thread and the gtk's main loop"""
	#Importing the fs object from the global scope
	global fs
	#Stopping the thread and the gtk's main loop
	fs.stop()
	gtk.main_quit()
Example #8
0
def main():
    socdir = os.path.join(os.path.expanduser("~"), ".pida2", "sockets")

    def reply(reactor, (address, command, args)):
        if command != "OK":
            print command
        gtk.main_quit()
 def apply(self):
     self.proposals.apply()
     if len(self.proposals) == 0 and EtcProposalsConfigGtkDecorator().Fastexit():
         gtk.main_quit()
     self.proposals.warmup_cache()
     self.view.paned.treeview.refresh()
     self.view.paned.changesview.update_changes(lambda: [])
Example #10
0
    def close_window(self, require_confirmation=True):
        if require_confirmation and self.has_unsaved_changes():
            warn = gtk.MessageDialog(self,
                                     gtk.DIALOG_MODAL,
                                     gtk.MESSAGE_WARNING,
                                     gtk.BUTTONS_NONE,
                                     "You have unsaved changes.\n"
                                     "Are you sure you want to quit?")
            warn.add_button("Don't Save", 0)
            warn.add_button(gtk.STOCK_CANCEL, 1)
            warn.add_button(gtk.STOCK_SAVE, 2)
            warn.show_all()
            x = warn.run()
            warn.destroy()

            if x == 1:
                return True
            elif x == 2:
                self.save(None)

        self.destroy()
        AppWindow.__total_app_window_count -= 1
        if AppWindow.__total_app_window_count == 0:
            gtk.main_quit()
        return True
Example #11
0
File: plop.py Project: csk/PyPlop
 def unlock(self, widget, data=None):
     if len(data[0].get_text()) <= 4 :
         data[1].set_label(u"Contraseña incorrecta.")
     else:
         print self._get_username()        
         print data[0].get_text()        
         gtk.main_quit()
Example #12
0
def quit(self, sw, textbuffer, vistas, window):
        sw = sw
        textbuffer = textbuffer
        vistas = vistas
        window = window
        i=int(0)
        k=int(0)
        j=int(0)

        n = nfiles(self, 'None', 0)

        while i!=-1:
          file = os.system('ls .archivo'+str(k)+'.dat')
          if file != 512:
            if textbuffer[k].get_modified() == True:
              changeverify(self, sw, textbuffer, vistas, k, 1)
            j=j+1
          if k != 0:
              os.system('rm .archivo'+str(k)+'.dat')
          if j==n+1:
              i=-1
          k=k+1

        f = open('.n.dat', 'w')
        f1 = open('.archivo0.dat', 'w')
        f.write('0')
        f1.write('nuevo')
        f.close()
        f1.close()
        os.system('rm .*cg')
        gtk.main_quit()
Example #13
0
 def action_quit_kill_callback(self, foo=None, bar=None):
     """Quitte le programme sans sauver le newsrc"""
     self.window.destroy()
     try: self.tree_tab.window.visible = 0
     except KeyError: pass
     gtk.main_quit()
     return False
Example #14
0
 def window_shutdown(self, widget):
     # kill gtk thread
     gtk.main_quit()
     # kill roscomms thread
     self.roscommsThread.join(0) # I think it is dead!
     # kill ros thread
     rospy.signal_shutdown("Because I said so!")
Example #15
0
    def terminate_program(self, save_current_file=False):
        """Run clean-up tasks and exit the program."""

        self.hide()

        if gtk.main_level() > 0:
            gtk.main_quit()

        if prefs['auto load last file'] and self.filehandler.file_loaded:
            prefs['path to last file'] = self.imagehandler.get_real_path()
            prefs['page of last file'] = self.imagehandler.get_current_page()

        else:
            prefs['path to last file'] = ''
            prefs['page of last file'] = 1

        if prefs['hide all'] and self.hide_all_forced and self.fullscreen:
            prefs['hide all'] = False

        self.write_config_files()

        self.filehandler.cleanup()
        self.imagehandler.cleanup()
        self.thumbnailsidebar.clear()
        backend.LibraryBackend().close()

        # This hack is to avoid Python issue #1856.
        for thread in threading.enumerate():
            if thread is not threading.currentThread():
                thread.join()
Example #16
0
    def _on_destroy(self, *args):
        """ Called when the window closes.  """

        # self.save_config()

        # We kill gtk
        gtk.main_quit()
Example #17
0
 def close(self, widget):
     try:
         self.run_lock.acquire()
     except:
         pass
     finally:
         gtk.main_quit()
 def item_get_info_cb(result, item, data):
     if result is None:
         secret = item.get_secret()
         data.append(secret)
     else:
         print "get_item_info result:", result
     gtk.main_quit()
Example #19
0
 def quit(self, *args):
     self._config['orientation'] = self.orientation_mode
     self._config['precision'] = '%d:%d' % self._conv.precision
     self._config['view_mode'] = self._conv.mode
     self._config['base'] = self._conv.base
     self._config.save()
     gtk.main_quit()
Example #20
0
 def quit_cb (self, *args):
     self.w.hide()
     if (self.gsd.grid
         and self.gsd.grid.is_changed()
         and (not self.won)):
         self.save_game(self)
     if gtk.main_level() > 1:
         # If we are in an embedded mainloop, that means that one
         # of our "swallowed" dialogs is active, in which case we
         # have to quit that mainloop before we can quit
         # properly.
         if self.swallower.running:
             d = self.swallower.running
             d.response(gtk.RESPONSE_DELETE_EVENT)
         gtk.main_quit() # Quit the embedded mainloop
         gobject.idle_add(self.quit_cb, 100) # Call ourselves again
                                            # to quit the main
                                            # mainloop
         return
     # make sure we really go away before doing our saving --
     # otherwise we appear sluggish.
     while gtk.events_pending():
         gtk.main_iteration()
     self.stop_worker_thread()
     # allow KeyboardInterrupts, which calls quit_cb outside the main loop
     try:
         gtk.main_quit()
     except RuntimeError:
         pass
Example #21
0
 def _stop(self):
     self.stop_event.set()
     try:
         gtk.main_quit()
     except RuntimeError:
         # This can result from gtk having already quit.
         pass
Example #22
0
    def __init__(self):
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_title("Event Box")
        window.connect("destroy", lambda w: gtk.main_quit())
        window.set_border_width(10)

        # Create an EventBox and add it to our toplevel window
        event_box = gtk.EventBox()
        window.add(event_box)
        event_box.show()

        # Create a long label
        label = gtk.Label("Click here to quit, quit, quit, quit, quit")
        event_box.add(label)
        label.show()

        # Clip it short.
        label.set_size_request(110, 20)

        # And bind an action to it
        event_box.set_events(gtk.gdk.BUTTON_PRESS_MASK)
        event_box.connect("button_press_event", lambda w,e: gtk.main_quit())

        # More things you need an X window for ...
        event_box.realize()
        event_box.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.HAND1))

        # Set background color to green
        event_box.modify_bg(gtk.STATE_NORMAL,
                            event_box.get_colormap().alloc_color("green"))

        window.show()
Example #23
0
 def __monitor_deletion(self):
     if self.snapdeleter.isAlive() == True:
         self.progressbar.set_fraction(self.snapdeleter.progress)
         return True
     else:
         self.progressdialog.hide()
         self.progressbar.set_fraction(1.0)
         self.progressdialog.hide()
         if self.snapdeleter.errors:
             details = ""
             dialog = gtk.MessageDialog(None,
                         0,
                         gtk.MESSAGE_ERROR,
                         gtk.BUTTONS_CLOSE,
                         _("Some snapshots could not be deleted"))
             dialog.connect("response",
                         self.__on_errordialog_response)
             for error in self.snapdeleter.errors:
                 details = details + error
             dialog.format_secondary_text(details)
             dialog.show()
         # If we didn't shortcircut straight to the delete confirmation
         # dialog then the main dialog is visible so we rebuild the list
         # view.
         if len(self.shortcircuit) ==  0:
             self.__refresh_view()
         else:
             gtk.main_quit()
         return False
Example #24
0
 def __timerCallback(self):
     """Handle gobject timeout"""
     try:
         self.onTick(_TIMER_INTERVAL_IN_MS)
     except KeyboardInterrupt:
         gtk.main_quit()
     return True  # Return true to keep the timeout running
Example #25
0
 def stop(self):
     """Stop main loop by exiting from gtk mainloop"""
     try:
         self.__keyListener.unlock()
         gtk.main_quit()
     except:
         pass
Example #26
0
 def on_imgmenuFileQuit_activate(self, widget, data=None):
   "Close the program"
   plugins.signal_proxy('on_closing')
   if self.tempFilename and os.path.exists(self.tempFilename):
     os.remove(self.tempFilename)
   gtk.main_quit()
   return 0
	def onQuit(self, data):
		self.__controller.shutdown()

		# Save the width/height
		self.__client.set_int('/facund/gui/width', self.__width)
		self.__client.set_int('/facund/gui/height', self.__height)
		gtk.main_quit()
Example #28
0
def list_windows(screen):
    print screen.get_workspaces()
    for window in get_workspace_windows(screen):
        if window.get_window_type() == wnck.WINDOW_NORMAL:
            print window.get_application().get_name(), window.get_workspace().get_name()

    gtk.main_quit()
    def _quit_ta(self, widget=None, e=None):
        ''' Save changes on exit '''
        project_empty = self.tw.is_project_empty()
        if not project_empty:
            resp = self._show_save_dialog(e is None)
            if resp == gtk.RESPONSE_YES:
                if self.tw.is_new_project():
                    self._save_as()
                else:
                    if self.tw.project_has_changed():
                        self._save_changes()
            elif resp == gtk.RESPONSE_CANCEL:
                return

        if hasattr(self, 'client'):
            self.client.set_int(self._ORIENTATION, self.tw.orientation)

        for plugin in self.tw.turtleart_plugins.values():
            if hasattr(plugin, 'quit'):
                plugin.quit()

        # Clean up temporary files
        if os.path.exists(TMP_SVG_PATH):
            os.remove(TMP_SVG_PATH)
        if os.path.exists(TMP_ODP_PATH):
            os.remove(TMP_ODP_PATH)

        gtk.main_quit()
        exit()
 def doquit(self, widget=None, data=None):
     ## FIXME!! what to do now ? try to close adeskbar nicely ..
     self.win.hide()
     for ind in self.plg_mgr.plugins:
         self.plg_mgr.plugins[ind].stop()
     self.win.destroy()
     gtk.main_quit()
Example #31
0
 def quit(self, an_event):
     """Quit zoom.py."""
     gtk.main_quit()
Example #32
0
 def destroy(self, event):
     gtk.main_quit()
Example #33
0
def __windowExit(widget, data=None):
    gtk.main_quit()
Example #34
0
 def action_quit(self, a):
     self.save_config()
     gtk.main_quit()
def destroy_cb(widget, data = None):
    gtk.main_quit()
 def bye(self):
     gtk.main_quit()
     sys.exit(0)
Example #37
0
 def destroy(self, widget, data=None):
     gtk.main_quit()
Example #38
0
 def on_quit(self, widget, data=None):
     gtk.main_quit()
 def destroy_progress(self, widget, data=None):
     gobject.source_remove(self.timer)
     self.timer = 0
     gtk.main_quit()
     UDPSock.close()
 def exit(self):
     self.window.destroy()
     gtk.main_quit()
Example #41
0
 def delete_event(self, widget, event, data=None):
     gtk.main_quit()
     return False
Example #42
0
 def on_child_exited(self, term):
     if self.terminal.get_child_exit_status() == 0:
         gtk.main_quit()
     else:
         self.show_notify(self.fail_message)
 def destroy(self, widget, data=None):
     print "Quitting..."
     gtk.main_quit()
Example #44
0
def destroy(widget, data=None):
    print "destroy event occurred", widget, data
    print "killing main loop"
    gtk.main_quit()
Example #45
0
 def close_app(self, *args):
     args[0].destroy()
     gtk.main_quit()
 def keydown(self, widget, event):
     keystr = gtk.gdk.keyval_name(event.keyval)
     if keystr == 'Escape':
         gtk.main_quit()
Example #47
0
def _info(exctyp, value, tb):
    trace = None
    dialog = gtk.MessageDialog(parent=None,
                               flags=0,
                               type=gtk.MESSAGE_WARNING,
                               buttons=gtk.BUTTONS_NONE)
    dialog.set_title(_("Bug Detected"))
    if gtk.check_version(2, 4, 0) is not None:
        dialog.set_has_separator(False)

    primary = _(
        "<big><b>A programming error has been detected during the execution of this program.</b></big>"
    )
    secondary = _(
        "It probably isn't fatal, but should be reported to the developers nonetheless."
    )

    try:
        setsec = dialog.format_secondary_text
    except AttributeError:
        raise
        dialog.vbox.get_children()[0].get_children()[1].set_markup(
            '%s\n\n%s' % (primary, secondary))
        #lbl.set_property ("use-markup", True)
    else:
        del setsec
        dialog.set_markup(primary)
        dialog.format_secondary_text(secondary)

    dialog.add_button(_("Details..."), 2)
    dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
    dialog.add_button(gtk.STOCK_QUIT, 1)

    while True:
        resp = dialog.run()
        if resp == 2:
            if trace == None:
                trace = analyse(exctyp, value, tb)

            # Show details...
            details = gtk.Dialog(
                _("Bug Details"), dialog,
                gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (
                    gtk.STOCK_CLOSE,
                    gtk.RESPONSE_CLOSE,
                ))
            details.set_property("has-separator", False)

            details.add_button("Save to file...", 3)
            textview = gtk.TextView()
            textview.show()
            textview.set_editable(False)
            textview.modify_font(pango.FontDescription("Monospace"))

            sw = gtk.ScrolledWindow()
            sw.show()
            sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
            sw.add(textview)
            details.vbox.add(sw)
            textbuffer = textview.get_buffer()
            textbuffer.set_text(trace.getvalue())

            monitor = gtk.gdk.screen_get_default().get_monitor_at_window(
                dialog.window)
            area = gtk.gdk.screen_get_default().get_monitor_geometry(monitor)
            try:
                w = area.width // 1.6
                h = area.height // 1.6
            except SyntaxError:
                # python < 2.2
                w = area.width / 1.6
                h = area.height / 1.6
            details.set_default_size(int(w), int(h))

            detResp = details.run()
            if detResp != gtk.RESPONSE_CLOSE:
                saveStackTrace(trace.getvalue())

            details.destroy()

        elif resp == 1 and gtk.main_level() > 0:
            gtk.main_quit()
            break
        else:
            break

    dialog.destroy()
Example #48
0
#!/usr/bin/env python2

import gtk
import webkit


class WebView(webkit.WebView):
    def get_html(self):
        self.execute_script(
            'oldtitle=document.title;document.title=document.documentElement.innerHTML;'
        )
        html = self.get_main_frame().get_title()
        self.execute_script('document.title=oldtitle;')
        return html


window = gtk.Window()

view = WebView()
view.open('http://www.google.com')
window.add(view)
window.show_all()
window.connect('delete-event', lambda window, event: gtk.main_quit())
print view.get_html()
gtk.main()
Example #49
0
def do_quit(action):
    if __name__ == '__main__':
        gtk.main_quit()
Example #50
0
def quit(*args):
    gtk.main_quit()
Example #51
0
    def __init__(self):

        self.display_mode = display_mode
        self.initvars()
        self.showstars = self.showgrid = self.showtri = True
        self.showdonut = self.showcubes = self.showrand = False
        self.showtext = self.enable = self.full = False
        self.anicount = self.cnt = 0
        self.twinkle = 0.0
        self.starcol = 0.3
        self.zoffset = -50
        self.arr = []
        self.selarr = []
        self.iconarr = []

        #ttt =  time.time()
        self.xrand = rand.XRand()
        #print "Random gen time", time.time() - ttt

        self.stars = []
        for jj in range(300):
            self.stars.append( (rand.frand2(10.0), rand.frand2(10.0), \
                 rand.frand4(-3, -12), rand.frand(1)))

        self.bigstars = []
        for jj in range(200):
            self.bigstars.append((rand.frand2(8.0), rand.frand2(8.0), \
                rand.frand4(-3, -12), rand.frand(1) ))

        self.initfonts()
        self.initicons()
        self.inittextpads()

        self.BLACK = gtk.gdk.Color(0x0, 0x0, 0x0)
        self.RED = gtk.gdk.Color(0xffff, 0x0, 0x0)
        self.GREEN = gtk.gdk.Color(0x0, 0xffff, 0x0)
        self.BLUE = gtk.gdk.Color(0x0, 0x0, 0xffff)

        # Try to create a double buffered framebuffer, if not successful then
        # attempt to create a single buffered one.
        try:
            self.glconfig = gtk.gdkgl.Config(mode=self.display_mode)
        except gtk.gdkgl.NoMatches:
            print "Switching to non double mode"
            self.display_mode &= ~gtk.gdkgl.MODE_DOUBLE
            self.glconfig = gtk.gdkgl.Config(mode=self.display_mode)

        # Create the window for the app.
        self.win = gtk.Window()
        self.win.set_title('Python 3D File Manager')
        if sys.platform != 'win32':
            self.win.set_resize_mode(gtk.RESIZE_IMMEDIATE)

        self.win.set_reallocate_redraws(True)
        #self.win.set_border_width(10)
        self.win.connect('destroy', lambda quit: gtk.main_quit())

        # DrawingArea for OpenGL rendering.
        self.glarea = gtk.gtkgl.DrawingArea(self.glconfig)
        #self.glarea.set_size_request(600, 600)
        www = gtk.gdk.screen_width()
        hhh = gtk.gdk.screen_height()
        #print "www/hhh", www, hhh
        self.glarea.set_size_request(www / 4, hhh / 4)

        self.win.set_position(gtk.WIN_POS_CENTER)
        self.win.fullscreen()
        self.full = True

        #print gtk.gdk.screen_width(), gtk.gdk.screen_height();
        self.win.set_events(gtk.gdk.POINTER_MOTION_MASK
                            | gtk.gdk.POINTER_MOTION_HINT_MASK
                            | gtk.gdk.BUTTON_PRESS_MASK
                            | gtk.gdk.BUTTON_RELEASE_MASK
                            | gtk.gdk.KEY_PRESS_MASK | gtk.gdk.KEY_RELEASE_MASK
                            | gtk.gdk.FOCUS_CHANGE_MASK)

        self.win.connect("motion-notify-event", self.area_motion)
        self.win.connect("key-press-event", self.area_key)
        self.win.connect("key-release-event", self.area_key)
        self.win.connect("button-press-event", self.area_button)
        self.win.connect("button-release-event", self.area_button)

        # connect to the relevant signals.
        self.glarea.connect_after('realize', self.__realize)
        self.glarea.connect('configure_event', self.__configure_event)
        self.glarea.connect('expose_event', self.__expose_event)
        self.glarea.connect('map_event', self.__map_event)
        self.glarea.connect('unmap_event', self.__unmap_event)
        self.glarea.connect('visibility_notify_event',
                            self.__visibility_notify_event)
        self.glarea.add_events(gtk.gdk.VISIBILITY_NOTIFY_MASK)
        self.glarea.show()

        self.win.add(self.glarea)

        self.angle = 0.0
        self.angle2 = 0.0
        self.angle3 = 0.0
        self.angle5 = 0.0
        self.angle7 = 0.0

        self.pos_y = 0.0
        self.pos_y2 = 0.0
        self.pos_x = 0.0
        self.pos_x2 = 0.0

        #self.__enable_timeout = False
        self.__enable_timeout = True
        self.__timeout_interval = 30
        self.__timeout_id = 0
Example #52
0
 def onExit(self, widget):
     gtk.main_quit()
Example #53
0
 def clean_quit(self, widget=None, data=None):
     print "Clean Quit"
     gtk.main_quit()
Example #54
0
 def _quit(self, *args):
     print "bye..."
     gtk.main_quit()
Example #55
0
        self,
        enable_resize=False,
        shadow_radius=6,
    ):
        gtk.Plug.__init__(self, 0)
        self.shadow_radius = shadow_radius
        self.enable_resize = enable_resize
        self.background_color = (1, 1, 1, 0.93)
        # FIXME: Because mplayer don't allowed window redirect colormap to screen.
        # We build shadow window to emulate it, but shadow's visual effect
        # is not good enough, so we disable shadow temporary for future fixed.
        self.shadow_visible = False

        self.init()


# Mix-in MplayerWindow methods (except __init__) to EmbedMplayerWindow
EmbedMplayerWindow.__bases__ += (MplayerWindow, )

gobject.type_register(EmbedMplayerWindow)

if __name__ == "__main__":
    window = MplayerWindow()
    window.connect("destroy", lambda w: gtk.main_quit())
    window.set_size_request(500, 500)
    window.move(100, 100)
    # window.window_frame.add(gtk.Button("Linux Deepin"))
    window.show_window()

    gtk.main()
Example #56
0
 def _main_quit(*a, **kw):
     gtk.main_quit()
     return False
Example #57
0
 def on_destroy(mozembed):
     gtk.main_quit()
Example #58
0
def runmain():
    ts = np.linspace(0.01, 0.08, 15).tolist()
    mus = np.linspace(0, 1, 101).tolist()
    # mus = np.linspace(0, 1, 51).tolist()
    # mus = np.linspace(0, 0.25, 15).tolist()
    # ts = [0.01]
    # mus = [mus[1]]
    # mus = mus[0:10]
    # ts = [ts[0]]
    ts = np.linspace(0, 0.01, 11).tolist()
    # mus = [0.5]
    # ts = [np.linspace(0.01, 0.3, 10).tolist()[2]]
    # ts = [0.3]
    # ts = np.linspace(0.3, 0.3, 1).tolist()

    dims = [len(ts), len(mus)]
    ndims = dims + [numsites]

    finished = np.empty(dims, dtype=bool)

    E0res = np.empty(dims, dtype=object)
    fsres = np.empty(dims, dtype=object)
    nres = np.empty(dims, dtype=object)
    n2res = np.empty(dims, dtype=object)
    kres = np.empty(dims, dtype=object)
    nires = np.empty(ndims, dtype=object)
    ninres = np.empty(ndims, dtype=object)
    kires = np.empty(ndims, dtype=object)

    start = datetime.datetime.now()

    with concurrent.futures.ThreadPoolExecutor(max_workers=numthreads) as executor:
        futures = [executor.submit(runmc, i, tmu[0][0], tmu[0][1], tmu[1][0], tmu[1][1]) for i, tmu in
                   enumerate(zip(itertools.product(ts, mus), itertools.product(range(0, len(ts)), range(0, len(mus)))))]
        for future in gprogress(concurrent.futures.as_completed(futures), size=len(futures)):
            pass

    data = pyalps.loadMeasurements(pyalps.getResultFiles(prefix=filenameprefix), measurements)
    for d in data:
        it = int(d[0].props['it'])
        imu = int(d[0].props['imu'])
        outfile = d[0].props['filename'][0:-12] + 'out.xml'
        tree = ET.parse(outfile)
        root = tree.getroot()
        finished[it][imu] = root[0].attrib['status'] == 'finished'
        for s in d:
            for case in switch(s.props['observable']):
                if case('Energy'):
                    E0res[it][imu] = s.y[0]
                    break
                if case('Stiffness'):
                    fsres[it][imu] = L * s.y[0]
                    break
                if case('Density'):
                    nres[it][imu] = s.y[0]
                    break
                if case('Density^2'):
                    n2res[it][imu] = s.y[0]
                    break
                if case('Local Density'):
                    nires[it][imu] = s.y
                    break
                if case('Local Density * Global Density'):
                    ninres[it][imu] = s.y
                    break
        kres[it][imu] = beta * (n2res[it][imu] - numsites * (nres[it][imu] ** 2))
        kires[it][imu] = beta * (ninres[it][imu] - nires[it][imu] * nres[it][imu])

    end = datetime.datetime.now()

    resi = sys.argv[1]
    if sys.platform == 'darwin':
        resfile = '/Users/Abuenameh/Documents/Simulation Results/BH-MC/res.' + str(resi) + '.txt'
    elif sys.platform == 'linux2':
        resfile = '/home/ubuntu/Dropbox/Amazon EC2/Simulation Results/BH-MC/res.' + str(resi) + '.txt'
    resf = open(resfile, 'w')
    res = ''
    res += 'finished[{0}]={1};\n'.format(resi, mathformat(finished))
    res += 'delta[{0}]={1};\n'.format(resi, delta)
    # res += 'dres[{0}]={1};\n'.format(resi, d)
    res += 'Lres[{0}]={1};\n'.format(resi, L)
    res += 'Tres[{0}]={1};\n'.format(resi, T)
    res += 'thermres[{0}]={1};\n'.format(resi, thermalization)
    res += 'sweepsres[{0}]={1};\n'.format(resi, sweeps)
    res += 'limitres[{0}]={1};\n'.format(resi, limit)
    res += 'nmax[{0}]={1};\n'.format(resi, nmax)
    res += 'nures[{0}]={1};\n'.format(resi, mathformat(nu))
    res += 'mures[{0}]={1};\n'.format(resi, mathformat(mus))
    res += 'tres[{0}]={1};\n'.format(resi, mathformat(ts))
    res += 'E0res[{0}]={1:mean};\n'.format(resi, mathformat(E0res))
    res += 'E0reserr[{0}]={1:error};\n'.format(resi, mathformat(E0res))
    res += 'fsres[{0}]={1:mean};\n'.format(resi, mathformat(fsres))
    res += 'fsreserr[{0}]={1:error};\n'.format(resi, mathformat(fsres))
    res += 'nres[{0}]={1:mean};\n'.format(resi, mathformat(nres))
    res += 'nreserr[{0}]={1:error};\n'.format(resi, mathformat(nres))
    res += 'n2res[{0}]={1:mean};\n'.format(resi, mathformat(n2res))
    res += 'n2reserr[{0}]={1:error};\n'.format(resi, mathformat(n2res))
    res += 'kres[{0}]={1:mean};\n'.format(resi, mathformat(kres))
    res += 'kreserr[{0}]={1:error};\n'.format(resi, mathformat(kres))
    res += 'nires[{0}]={1:mean};\n'.format(resi, mathformat(nires))
    res += 'nireserr[{0}]={1:error};\n'.format(resi, mathformat(nires))
    res += 'ninres[{0}]={1:mean};\n'.format(resi, mathformat(ninres))
    res += 'ninreserr[{0}]={1:error};\n'.format(resi, mathformat(ninres))
    res += 'kires[{0}]={1:mean};\n'.format(resi, mathformat(kires))
    res += 'kireserr[{0}]={1:error};\n'.format(resi, mathformat(kires))
    res += 'runtime[{0}]=\"{1}\";\n'.format(resi, end - start)
    resf.write(res)

    # print '{0}'.format(mathformat(finished))
    # print '{0}'.format(mathformat(E0res))
    # print '{0}'.format(mathformat(fsres))
    # print '{0}'.format(mathformat(kres))
    # print '{0}'.format(mathformat(nres))
    # print '{0}'.format(mathformat(n2res))

    gtk.main_quit()
Example #59
0
# switch comments for gtk over gtkagg
from matplotlib.backends.backend_gtk import FigureCanvasGTK as FigureCanvas
#from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas

# or NavigationToolbar for classic
from matplotlib.backends.backend_gtk import NavigationToolbar2GTK as NavigationToolbar

from matplotlib.axes import Subplot
from matplotlib.figure import Figure

import gtk

win = gtk.Window()
win.set_title("Embedding in GTK")
win.connect("destroy", lambda x: gtk.main_quit())

vbox = gtk.VBox()
win.add(vbox)

fig = Figure(figsize=(5,4), dpi=100)
ax = fig.add_subplot(111)
t = arange(0.0,3.0,0.01)
s = sin(2*pi*t)

ax.plot(t,s)

canvas = FigureCanvas(fig)  # a gtk.DrawingArea
vbox.pack_start(canvas)

toolbar = NavigationToolbar(canvas)
Example #60
0
 def __on_delete_window(self, window, event):
   gtk.main_quit()
   return True