示例#1
0
    def display_message(self, msg, title=None, is_error=False):
        """
        Display the specified message to the user.

        """

        # Ensure we record any reasons this method doesn't work.  Especially
        # since it's critical in displaying errors to users!
        try:

            # Attempt to identify the current application window.
            parent_window = None
            workbench = self.application.get_service('envisage.'
                'workbench.IWorkbench')
            if workbench is not None:
                parent_window = workbench.active_window.control

            # Display the requested message
            if is_error:
                error(parent_window, msg, title=title)
            else:
                information(parent_window, msg, title=title)

        except:
            logger.exception('Unable to display pop-up message')

        return
示例#2
0
    def _get_hsp_raw(self):
        fname = self.hsp_file
        if not fname:
            return

        try:
            pts = read_hsp(fname)

            n_pts = len(pts)
            if n_pts > KIT.DIG_POINTS:
                msg = ("The selected head shape contains {n_in} points, "
                       "which is more than the recommended maximum ({n_rec}). "
                       "The file will be automatically downsampled, which "
                       "might take a while. A better way to downsample is "
                       "using FastScan.")
                msg = msg.format(n_in=n_pts, n_rec=KIT.DIG_POINTS)
                information(None, msg, "Too Many Head Shape Points")
                pts = _decimate_points(pts, 5)

        except Exception as err:
            error(None, str(err), "Error Reading Head Shape")
            self.reset_traits(['hsp_file'])
            raise
        else:
            return pts
示例#3
0
def get_mne_root():
    """Get the MNE_ROOT directory

    Returns
    -------
    mne_root : None | str
        The MNE_ROOT path or None if the user cancels.

    Notes
    -----
    If MNE_ROOT can't be found, the user is prompted with a file dialog.
    If specified successfully, the resulting path is stored with
    mne.set_config().
    """
    mne_root = get_config('MNE_ROOT')
    problem = _mne_root_problem(mne_root)
    while problem:
        info = ("Please select the MNE_ROOT directory. This is the root "
                "directory of the MNE installation.")
        msg = '\n\n'.join((problem, info))
        information(None, msg, "Select the MNE_ROOT Directory")
        msg = "Please select the MNE_ROOT Directory"
        dlg = DirectoryDialog(message=msg, new_directory=False)
        if dlg.open() == OK:
            mne_root = dlg.path
            problem = _mne_root_problem(mne_root)
            if problem is None:
                set_config('MNE_ROOT', mne_root)
        else:
            return None

    return mne_root
示例#4
0
    def on_export(self):
        """
        Shows a dialog to export a file
        """

        information(
            None, "This will save exactly what you see on the screen "
            "to a file.", "Export")

        f = ""
        filetypes_groups = self.plot_pane.canvas.get_supported_filetypes_grouped(
        )
        filename_exts = []
        for name, ext in filetypes_groups.iteritems():
            if f:
                f += ";"
            f += FileDialog.create_wildcard(name,
                                            " ".join(["*." + e for e in ext
                                                      ]))  #@UndefinedVariable
            filename_exts.append(ext)

        dialog = FileDialog(parent=self.window.control,
                            action='save as',
                            wildcard=f)

        if dialog.open() == OK:
            filetypes = self.plot_pane.canvas.get_supported_filetypes().keys()
            if not filter(lambda ext: dialog.path.endswith(ext),
                          ["." + ext for ext in filetypes]):
                selected_exts = filename_exts[dialog.wildcard_index]
                ext = sorted(selected_exts, key=len)[0]
                dialog.path += "."
                dialog.path += ext

            self.plot_pane.export(dialog.path)
示例#5
0
def get_fs_home():
    """Get the FREESURFER_HOME directory

    Returns
    -------
    fs_home : None | str
        The FREESURFER_HOME path or None if the user cancels.

    Notes
    -----
    If FREESURFER_HOME can't be found, the user is prompted with a file dialog.
    If specified successfully, the resulting path is stored with
    mne.set_config().
    """
    fs_home = get_config('FREESURFER_HOME')
    problem = _fs_home_problem(fs_home)
    while problem:
        info = ("Please select the FREESURFER_HOME directory. This is the "
                "root directory of the freesurfer installation.")
        msg = '\n\n'.join((problem, info))
        information(None, msg, "Select the FREESURFER_HOME Directory")
        msg = "Please select the FREESURFER_HOME Directory"
        dlg = DirectoryDialog(message=msg, new_directory=False)
        if dlg.open() == OK:
            fs_home = dlg.path
            problem = _fs_home_problem(fs_home)
            if problem is None:
                set_config('FREESURFER_HOME', fs_home)
        else:
            return None

    return fs_home
示例#6
0
    def display_message(self, msg, title=None, is_error=False):
        """
        Display the specified message to the user.

        """

        # Ensure we record any reasons this method doesn't work.  Especially
        # since it's critical in displaying errors to users!
        try:

            # Attempt to identify the current application window.
            parent_window = None
            workbench = self.application.get_service('envisage.'
                                                     'workbench.IWorkbench')
            if workbench is not None:
                parent_window = workbench.active_window.control

            # Display the requested message
            if is_error:
                error(parent_window, msg, title=title)
            else:
                information(parent_window, msg, title=title)

        except:
            logger.exception('Unable to display pop-up message')

        return
示例#7
0
    def _get_hsp_raw(self):
        fname = self.hsp_file
        if not fname:
            return

        try:
            pts = _read_dig_points(fname)
            n_pts = len(pts)
            if n_pts > KIT.DIG_POINTS:
                msg = ("The selected head shape contains {n_in} points, "
                       "which is more than the recommended maximum ({n_rec}). "
                       "The file will be automatically downsampled, which "
                       "might take a while. A better way to downsample is "
                       "using FastScan.".
                       format(n_in=n_pts, n_rec=KIT.DIG_POINTS))
                if self.show_gui:
                    information(None, msg, "Too Many Head Shape Points")
                pts = _decimate_points(pts, 5)

        except Exception as err:
            if self.show_gui:
                error(None, str(err), "Error Reading Head Shape")
            self.reset_traits(['hsp_file'])
            raise
        else:
            return pts
示例#8
0
def get_fs_home():
    """Get the FREESURFER_HOME directory

    Returns
    -------
    fs_home : None | str
        The FREESURFER_HOME path or None if the user cancels.

    Notes
    -----
    If FREESURFER_HOME can't be found, the user is prompted with a file dialog.
    If specified successfully, the resulting path is stored with
    mne.set_config().
    """
    fs_home = get_config('FREESURFER_HOME')
    problem = _fs_home_problem(fs_home)
    while problem:
        info = ("Please select the FREESURFER_HOME directory. This is the "
                "root directory of the freesurfer installation.")
        msg = '\n\n'.join((problem, info))
        information(None, msg, "Select the FREESURFER_HOME Directory")
        msg = "Please select the FREESURFER_HOME Directory"
        dlg = DirectoryDialog(message=msg, new_directory=False)
        if dlg.open() == OK:
            fs_home = dlg.path
            problem = _fs_home_problem(fs_home)
            if problem is None:
                set_config('FREESURFER_HOME', fs_home)
        else:
            return None

    return fs_home
示例#9
0
def get_mne_root():
    """Get the MNE_ROOT directory

    Returns
    -------
    mne_root : None | str
        The MNE_ROOT path or None if the user cancels.

    Notes
    -----
    If MNE_ROOT can't be found, the user is prompted with a file dialog.
    If specified successfully, the resulting path is stored with
    mne.set_config().
    """
    mne_root = get_config('MNE_ROOT')
    problem = _mne_root_problem(mne_root)
    while problem:
        info = ("Please select the MNE_ROOT directory. This is the root "
                "directory of the MNE installation.")
        msg = '\n\n'.join((problem, info))
        information(None, msg, "Select the MNE_ROOT Directory")
        msg = "Please select the MNE_ROOT Directory"
        dlg = DirectoryDialog(message=msg, new_directory=False)
        if dlg.open() == OK:
            mne_root = dlg.path
            problem = _mne_root_problem(mne_root)
            if problem is None:
                set_config('MNE_ROOT', mne_root)
        else:
            return None

    return mne_root
示例#10
0
    def on_problem(self):

        information(
            None, "Your email client will now create a new message to the "
            "developer.  Debugging logs are attached.  Please fill "
            "out the template bug report and send -- thank you for "
            "reporting a bug!")

        log = self.application.application_log.getvalue()

        versions = [
            "{0} {1}".format(key, value)
            for key, value in self._get_package_versions().items()
        ]

        body = """
Thank you for your bug report!  Please fill out the following template.

PLATFORM (Mac, PC, Linux, other):

OPERATING SYSTEM (eg OSX 10.7, Windows 8.1):

SEVERITY (Critical? Major? Minor? Enhancement?):

DESCRIPTION:
  - What were you trying to do?
  - What happened?
  - What did you expect to happen?
  

PACKAGE VERSIONS: {0}

DEBUG LOG: {1}
""".format(versions, log)
示例#11
0
 def _subjects_dir_changed(self, old, new):
     if new and self.subjects == ['']:
         information(None, "The directory selected as subjects-directory "
                     "(%s) does not contain any valid MRI subjects. MRI "
                     "subjects need to contain head surface models which "
                     "can be created by running:\n\n    $ mne "
                     "make_scalp_surfaces" % self.subjects_dir,
                     "No Subjects Found")
示例#12
0
 def _subjects_dir_changed(self, old, new):
     if new and self.subjects == ['']:
         information(None, "The directory selected as subjects-directory "
                     "(%s) does not contain any valid MRI subjects. If "
                     "this is not expected make sure all MRI subjects have "
                     "head surface model files which "
                     "can be created by running:\n\n    $ mne "
                     "make_scalp_surfaces" % self.subjects_dir,
                     "No Subjects Found")
示例#13
0
 def close(self, info, is_ok):  # noqa: D102
     if info.object.kit2fiff_panel.queue.unfinished_tasks:
         msg = ("Can not close the window while saving is still in "
                "progress. Please wait until all files are processed.")
         title = "Saving Still in Progress"
         information(None, msg, title)
         return False
     else:
         return True
示例#14
0
 def close(self, info, is_ok):
     if info.object.kit2fiff_panel.queue.unfinished_tasks:
         msg = ("Can not close the window while saving is still in "
                "progress. Please wait until all files are processed.")
         title = "Saving Still in Progress"
         information(None, msg, title)
         return False
     else:
         return True
示例#15
0
 def _subjects_dir_changed(self, old, new):
     if new and self.subjects == ['']:
         information(
             None, "The directory selected as subjects-directory "
             "(%s) does not contain any valid MRI subjects. If "
             "this is not expected make sure all MRI subjects have "
             "head surface model files which "
             "can be created by running:\n\n    $ mne "
             "make_scalp_surfaces" % self.subjects_dir, "No Subjects Found")
 def close(self, info, is_ok):
     if info.object.queue.unfinished_tasks:
         information(
             None,
             "Can not close the window while saving is still "
             "in progress. Please wait until all MRIs are "
             "processed.",
             "Saving Still in Progress",
         )
         return False
     else:
         return True
示例#17
0
 def cite(self):
     from pyface.api import information
     import os
     try:
         basedir = os.path.dirname(os.path.realpath(__file__)) + '/'
     except NameError:  #__file__ not defined if this is main script
         basedir = ''
     fname = basedir + 'data/cite.txt'
     citations = open(fname, 'r').read()
     msg = u'You are encouraged to cite in your papers one (or all) of the following:\n\n\n' + \
             unicode(citations, 'utf-8').replace(u'\ufeff', '')
     information(None, msg, title = "Citing ffnet/ffnetui")
示例#18
0
    def _on_exit(self):
        """ Called when the exit action is invoked. """

        parent = self.control

        print(choose_one(parent, "Make a choice", ['one', 'two', 'three']))

        information(parent, 'Going...')
        warning(parent, 'Going......')
        error(parent, 'Gone!')

        if confirm(parent, 'Should I exit?') == YES:
            self.close()
示例#19
0
    def _on_exit(self):
        """ Called when the exit action is invoked. """

        parent = self.control

        print(choose_one(parent, "Make a choice", ["one", "two", "three"]))

        information(parent, "Going...")
        warning(parent, "Going......")
        error(parent, "Gone!")

        if confirm(parent, "Should I exit?") == YES:
            self.close()
示例#20
0
    def _on_exit(self):
        """ Called when the exit action is invoked. """

        parent = self.control

        print((choose_one(parent, "Make a choice", ['one', 'two', 'three'])))

        information(parent, 'Going...')
        warning(parent, 'Going......')
        error(parent, 'Gone!')

        if confirm(parent, 'Should I exit?') == YES:
            self.close()
示例#21
0
文件: dialog.py 项目: OspreyX/pyface
    def _on_exit(self):
        """ Called when the exit action is invoked. """

        parent = self.control

        information(parent, 'Going...')
        warning(parent, 'Going......')
        error(parent, 'Gone!')

        if confirm(parent, 'Should I exit?') == YES:
            self.close()

        return
示例#22
0
    def _on_exit(self):
        """ Called when the exit action is invoked. """

        parent = self.control

        information(parent, 'Going...')
        warning(parent, 'Going......')
        error(parent, 'Gone!')

        if confirm(parent, 'Should I exit?') == YES:
            self.close()

        return
示例#23
0
    def _save(self, project, parent_window, prompt_for_location=False):
        """
        Save the specified project.  If *prompt_for_location* is True,
        or the project has no known location, then the user is prompted to
        provide a location to save to.

        Returns True if the project was saved successfully, False if not.

        """

        location = project.location.strip()

        # If the project's existing location is valid, check if there are any
        # autosaved versions.
        autosave_loc = ""
        if location is not None and os.path.exists(location):
            autosave_loc = self._get_autosave_location(location)

        # Ask the user to provide a location if we were told to do so or
        # if the project has no existing location.
        if prompt_for_location or location is None or len(location) < 1:
            location = self._get_user_location(project, parent_window)
            # Rename any existing autosaved versions to the new project
            # location.
            if location is not None and len(location) > 0:
                self._clean_autosave_location(location)
                new_autosave_loc = self._get_autosave_location(location)
                if os.path.exists(autosave_loc):
                    shutil.move(autosave_loc, new_autosave_loc)

        # If we have a location to save to, try saving the project.
        if location is not None and len(location) > 0:
            try:
                project.save(location)
                saved = True
                msg = '"%s" saved to %s' % (project.name, project.location)
                information(parent_window, msg, "Project Saved")
                logger.debug(msg)

            except Exception as e:
                saved = False
                logger.exception("Error saving project [%s]", project)
                error(parent_window, str(e), title="Save Error")
        else:
            saved = False

        # If the save operation was successful, delete any autosaved files that
        # exist.
        if saved:
            self._clean_autosave_location(location)
        return saved
示例#24
0
    def _save(self, project, parent_window, prompt_for_location=False):
        """
        Save the specified project.  If *prompt_for_location* is True,
        or the project has no known location, then the user is prompted to
        provide a location to save to.

        Returns True if the project was saved successfully, False if not.

        """

        location = project.location.strip()

        # If the project's existing location is valid, check if there are any
        # autosaved versions.
        autosave_loc = ''
        if location is not None and os.path.exists(location):
            autosave_loc = self._get_autosave_location(location)

        # Ask the user to provide a location if we were told to do so or
        # if the project has no existing location.
        if prompt_for_location or location is None or len(location) < 1:
            location = self._get_user_location(project, parent_window)
            # Rename any existing autosaved versions to the new project
            # location.
            if location is not None and len(location) > 0:
                self._clean_autosave_location(location)
                new_autosave_loc = self._get_autosave_location(location)
                if os.path.exists(autosave_loc):
                    shutil.move(autosave_loc, new_autosave_loc)

        # If we have a location to save to, try saving the project.
        if location is not None and len(location) > 0:
            try:
                project.save(location)
                saved = True
                msg = '"%s" saved to %s' % (project.name, project.location)
                information(parent_window, msg, 'Project Saved')
                logger.debug(msg)

            except Exception as e:
                saved = False
                logger.exception('Error saving project [%s]', project)
                error(parent_window, str(e), title='Save Error')
        else:
            saved = False

        # If the save operation was successful, delete any autosaved files that
        # exist.
        if saved:
            self._clean_autosave_location(location)
        return saved
示例#25
0
 def close(self, info, is_ok):  # noqa: D102
     if info.object.kit2fiff_panel.queue.unfinished_tasks:
         msg = ("Can not close the window while saving is still in "
                "progress. Please wait until all files are processed.")
         title = "Saving Still in Progress"
         information(None, msg, title)
         return False
     else:
         # store configuration, but don't prevent from closing on error
         try:
             info.object.save_config()
         except Exception as exc:
             warn("Error saving GUI configuration:\n%s" % (exc, ))
         return True
示例#26
0
 def close(self, info, is_ok):  # noqa: D102
     if info.object.kit2fiff_panel.queue.unfinished_tasks:
         msg = ("Can not close the window while saving is still in "
                "progress. Please wait until all files are processed.")
         title = "Saving Still in Progress"
         information(None, msg, title)
         return False
     else:
         # store configuration, but don't prevent from closing on error
         try:
             info.object.save_config()
         except Exception as exc:
             warn("Error saving GUI configuration:\n%s" % (exc,))
         return True
示例#27
0
 def on_export(self):
     """
     Shows a dialog to export a file
     """
     
     information(None, "This will save exactly what you see on the screen "
                       "to a file. Choose the file type via the file " 
                       "extension (ie .png, .pdf, .jpg)", "Export")
     
     dialog = FileDialog(parent = self.window.control,
                         action = 'save as')
     
     if dialog.open() == OK:
         self.view.export(dialog.path)
示例#28
0
    def error(self, excp):
        """Handles an error that occurs while setting the object's trait value.

        Parameters
        ----------
        excp : Exception
            The exception which occurred.
        """
        from pyface.api import information

        information(
            parent=self.get_control_widget(),
            title=self.description + " value error",
            message=str(excp),
            text_format='plain',
        )
示例#29
0
    def run(self, application):
        """
        Run this runnable.

        Overridden here to: (a) ensure the UI service monitors for the
        closing of the application, and (b) restore the last opened
        project.

        """

        # Ensure our UI service is listening for the application to close.
        # FIXME: This ugly hack (doing this here) is necessary only because
        # this plugin contributes to the workbench plugin and that means the
        # workbench insists on starting us first which means our UI service
        # can't directly reference the workbench service until after
        # everything has been started.
        ui_service = application.get_service(IPROJECT_UI)
        ui_service.listen_for_application_exit()

        # Load the project we were using when we last shutdown.
        model_service = application.get_service(IPROJECT_MODEL)
        location = model_service.preferences.get('project location',
                                                 default=None)
        if location and len(location) > 0:
            logger.info("Opening last project from location [%s]", location)

            try:
                project = model_service.factory.open(location)
            except:
                logger.exception('Error during opening of last project.')
                project = None

            if project is not None:
                model_service.project = project
            else:
                information(
                    self._get_parent_window(application),
                    'Unable to open last project from location:\t\n'
                    '\t%s\n' % (location) + '\n\n'
                    'The project may no longer exist.',
                    'Can Not Open Last Project',
                )

        else:
            logger.info('No previous project to open')

        return
示例#30
0
    def scanning_step(self):

        if self.icCamera.init_active:
            information(parent=None, title="please wait",
             message="The initialization of the camera is running. " + \
             "Please wait until the initialization is finished.")
            return False

        #self.icCryo.cryo_refresh=False
        self.finished=False
        self.x_koords=[]
        self.y_koords=[]
        self.spectra=[]
        self.used_centerwvl=[]
        self.used_grating=[]
        self.apd_counts=[]

        if self.x1>self.x2:
            self.x2,self.x1 = self.x1,self.x2

        if self.y1>self.y2:
            self.y1,self.y2=self.y2,self.y1

        if self.ivSpectro.exit_mirror=='front (CCD)': #ueberprueft ob spiegel umgeklappt bzw falls nicht klappt er ihn um
             self.ivSpectro.exit_mirror='side (APDs)'#self.ivSpectro.exit_mirror_value[1

        self.icCryo.waiting() #wartet bis cryo bereit

        #TODO das hier gehört nach cryo
        # [x,y] = self.icCryo.get_numeric_position()
        #x,y=self.icCryo.convert_output(self.icCryo.position())

        x_pos,y_pos = self.calc_snake_xy_pos()

        for i in range(len(x_pos)):
            if self.finished:
                break # abort condition
            self.icCryo.move(x_pos[i],y_pos[i])
            self.icCryo.waiting()
            # get actuall position, maybe x_pos[i] != x
            x,y=self.icCryo.pos()
            if self.threshold_counts < self.icVoltage.measure()/self.VoltPerCount: # vergleicht schwellenspannung mit aktueller
                self.take_spectrum(x,y)
            self.plot_map(x,y)

        self.finished = True
        print 'searching finish'
示例#31
0
    def run(self, application):
        """
        Run this runnable.

        Overridden here to: (a) ensure the UI service monitors for the
        closing of the application, and (b) restore the last opened
        project.

        """

        # Ensure our UI service is listening for the application to close.
        # FIXME: This ugly hack (doing this here) is necessary only because
        # this plugin contributes to the workbench plugin and that means the
        # workbench insists on starting us first which means our UI service
        # can't directly reference the workbench service until after
        # everything has been started.
        ui_service = application.get_service(IPROJECT_UI)
        ui_service.listen_for_application_exit()

        # Load the project we were using when we last shutdown.
        model_service = application.get_service(IPROJECT_MODEL)
        location = model_service.preferences.get('project location',
            default=None)
        if location and len(location) > 0:
            logger.info("Opening last project from location [%s]", location)

            try:
                project = model_service.factory.open(location)
            except:
                logger.exception('Error during opening of last project.')
                project = None

            if project is not None:
                model_service.project = project
            else:
                information(self._get_parent_window(application),
                    'Unable to open last project from location:\t\n'
                    '\t%s\n'  % (location) + '\n\n'
                    'The project may no longer exist.',
                    'Can Not Open Last Project',
                    )

        else:
            logger.info('No previous project to open')

        return
示例#32
0
def _get_root_home(cfg, name, check_fun):
    root = get_config(cfg)
    problem = check_fun(root)
    while problem:
        info = "Please select the %s directory. This is the root " "directory of the %s installation." % (cfg, name)
        msg = "\n\n".join((problem, info))
        information(None, msg, "Select the %s Directory" % cfg)
        msg = "Please select the %s Directory" % cfg
        dlg = DirectoryDialog(message=msg, new_directory=False)
        if dlg.open() == OK:
            root = dlg.path
            problem = check_fun(root)
            if problem is None:
                set_config(cfg, root)
        else:
            return None
    return root
示例#33
0
    def _test_stim_fired(self):
        try:
            events = self.model.get_event_info()
        except Exception as err:
            error(None, "Error reading events from SQD data file: %s (Check "
                  "the terminal output for details)" % str(err),
                  "Error Reading events from SQD file")
            raise err

        if len(events) == 0:
            information(None, "No events were found with the current "
                        "settings.", "No Events Found")
        else:
            lines = ["Events found (ID: n events):"]
            for id_ in sorted(events):
                lines.append("%3i: \t%i" % (id_, events[id_]))
            information(None, '\n'.join(lines), "Events in SQD File")
示例#34
0
def _get_root_home(cfg, name, check_fun):
    root = get_config(cfg)
    problem = check_fun(root)
    while problem:
        info = ("Please select the %s directory. This is the root "
                "directory of the %s installation." % (cfg, name))
        msg = '\n\n'.join((problem, info))
        information(None, msg, "Select the %s Directory" % cfg)
        msg = "Please select the %s Directory" % cfg
        dlg = DirectoryDialog(message=msg, new_directory=False)
        if dlg.open() == OK:
            root = dlg.path
            problem = check_fun(root)
            if problem is None:
                set_config(cfg, root, set_env=False)
        else:
            return None
    return root
示例#35
0
文件: run.py 项目: derekrazo/OpenBCI
    def close(self, info, isok):
        app = info.object  # convenience
        app.sensor.disconnect()
        file_name = os.path.join(ETSConfig.get_application_home(True),
                                 'sensor_output %s.csv' % str(datetime.datetime.now()).replace(':', '-'))
        # make sure directory exists.
        if not os.path.exists(ETSConfig.get_application_home(False)):
            os.makedirs(ETSConfig.get_application_home(False))
        arr = np.array(app.sensor.history)

        if not arr.size:
            return isok

        np.savetxt(file_name,
                   arr)
        msg = 'Output (size %s) saved to %s.' % (str(arr.shape), file_name)
        logging.info(msg)
        from pyface.api import information
        information(info.ui.control, msg, title='Array saved to disk.')
        return isok
示例#36
0
    def close(self, info, isok):
        app = info.object  # convenience
        app.sensor.disconnect()
        file_name = os.path.join(
            ETSConfig.get_application_home(True), 'sensor_output %s.csv' %
            str(datetime.datetime.now()).replace(':', '-'))
        # make sure directory exists.
        if not os.path.exists(ETSConfig.get_application_home(False)):
            os.makedirs(ETSConfig.get_application_home(False))
        arr = np.array(app.sensor.history)

        if not arr.size:
            return isok

        np.savetxt(file_name, arr)
        msg = 'Output (size %s) saved to %s.' % (str(arr.shape), file_name)
        logging.info(msg)
        from pyface.api import information
        information(info.ui.control, msg, title='Array saved to disk.')
        return isok
示例#37
0
    def on_problem(self):
        
        information(None, "Your email client will now create a new message to the "
                    "developer.  Debugging logs are attached.  Please fill "
                    "out the template bug report and send -- thank you for "
                    "reporting a bug!")
        
#         import tempfile
        log = guiutil.parent_log.getvalue()
        log += self.model.get_child_log()
# 
#         logfile = tempfile.NamedTemporaryFile(delete = False)
#         logfile.write(parent_log)
#         logfile.write(child_log)
#         logfile.close()
        
        versions = ["{0} {1}".format(key, value) for key, value in self._get_package_versions().iteritems()]

        body = """
Thank you for your bug report!  Please fill out the following template.

PLATFORM (Mac, PC, Linux, other):

OPERATING SYSTEM (eg OSX 10.7, Windows 8.1):

SEVERITY (Critical? Major? Minor? Enhancement?):

DESCRIPTION:
  - What were you trying to do?
  - What happened?
  - What did you expect to happen?
  

PACKAGE VERSIONS: {0}

DEBUG LOG: {1}
""".format(versions, log)

        mailto.mailto("*****@*****.**", 
                      subject = "Cytoflow bug report",
                      body = body)
    def run_python_script(self, path="", code=""):
        """ Run the content of the python file in-process.

        Parameters
        ----------
        path : str [OPTIONAL]
            Path to the script file. Cannot be empty if the code is empty.

        code : str [OPTIONAL]
            Content of the script file. Cannot be empty if the path is empty.
        """
        from kromatography.tools.python_script_runner import PythonScriptRunner

        if not code:
            if not path:
                msg = "Cannot run any script as neither a path nor code has" \
                      " been provided (path={}, code={}).".format(path, code)
                logger.exception(msg)
                raise ValueError(msg)

            code = open(path).read()

        script = PythonScriptRunner(code=code,
                                    task=self,
                                    app=self._app,
                                    path=path)
        try:
            output = script.run()
        except Exception as e:
            msg = "Failed to run the script {}: error as {}"
            msg = msg.format(path, e)
            logger.exception(msg)
            error(None, msg)
        else:
            msg = "Script {} ran successfully with the following output:\n\n{}"
            msg = msg.format(path, output)
            information(None, msg)

        logger.debug(msg)
示例#39
0
    def _send_fired(self):
        br = Browser()

        # Ignore robots.txt
        br.set_handle_robots(False)
        # Google demands a user-agent that isn't a robot
        br.addheaders = [('User-agent', 'Firefox')]

        # Retrieve the Google home page, saving the response
        resp = br.open("https://www.t-mobile.cz/.gang/login-url/portal?nexturl=https%3A%2F%2Fwww.t-mobile.cz%2Fweb%2Fcz%2Fosobni")

        br.select_form(nr=2)

        br.form['username'] = '******'
        br.form['password'] = self.password

        resp = br.submit()
        # print resp.get_data()

        resp = br.open("https://sms.client.tmo.cz/closed.jsp")
        br.select_form(nr=1)

        # print br.form
        # help(br.form)

        br.form['recipients'] = self.phone_number  # '736639077'#'737451193' #'605348558'
        br.form['text'] = self.message

        br.form.find_control("confirmation").get("1").selected = self.confirmation

        resp = br.submit()

        # logout
        resp = br.follow_link(url_regex='logout')

        br.close()

        information(None, 'SMS sent!')
示例#40
0
    def _get_user_location(self, project, parent_window):
        """
        Prompt the user for a new location for the specified project.

        Returns the chosen location or, if the user cancelled, an empty
        string.

        """

        # The dialog to use depends on whether we're prompting for a file or
        # a directory.
        if self.model_service.are_projects_files():
            dialog = FileDialog(
                parent=parent_window,
                title="Save Project As",
                default_path=project.location,
                action="save as",
            )
            title_type = "File"
        else:
            dialog = DirectoryDialog(
                parent=parent_window,
                message="Choose a Directory for the Project",
                default_path=project.location,
                action="open",
            )
            title_type = "Directory"

        # Prompt the user for a new location and then validate we're not
        # overwriting something without getting confirmation from the user.
        result = ""
        while dialog.open() == OK:
            location = dialog.path.strip()

            # If the chosen location doesn't exist yet, we're set.
            if not os.path.exists(location):
                logger.debug("Location [%s] does not exist yet.", location)
                result = location
                break

            # Otherwise, confirm with the user that they want to overwrite the
            # existing files or directories.  If they don't want to, then loop
            # back and prompt them for a new location.
            else:
                logger.debug(
                    "Location [%s] exists.  Prompting for overwrite "
                    "permission.",
                    location,
                )
                message = "Overwrite %s?" % location
                title = "Project %s Exists" % title_type
                action = confirm(parent_window, message, title)
                if action == YES:

                    # Only use the location if we successfully remove the
                    # existing files or directories at that location.
                    try:
                        self.model_service.clean_location(location)
                        result = location
                        break

                    # Otherwise, display the remove error to the user and give
                    # them another chance to pick another location
                    except Exception as e:
                        msg = str(e)
                        title = "Unable To Overwrite %s" % location
                        information(parent_window, msg, title)

        logger.debug("Returning user location [%s]", result)
        return result
示例#41
0
def save_data_file(sourceFile,
                   destination=None,
                   subdirectory=None,
                   user=None,
                   verbose=True):
    """ Function used to save (i.e copy) a data file into a directory of choice after an experimental session
        Parameters: sourceFile   - the path of the file that was generated by the experimental session and that resides
                                    in the local file system.
                    destination  - An optional destination path where to save the file. File name may be included
                                    or not at the end of the path.
                    subdirectory - An optional subdirectory, i.e folder, to add to the destination path. For example,
                                    if the destination path is a folder called "experiments", the subdirectory can be
                                    a child folder of "experiments", named after the experiment type ("behaviour"
                                    for instance).
                    user         - An optional parameter to indicate which user is conducting the experiments.
                                    If supplied, and if no destination is passed, a configuration file is looked
                                    up to retrieve the folder into which the user is usually copying data files.
                                    If no destination and no user is provided, a default directory is looked up
                                    in the configuration file as the default destination of the file to be copied.
                                    Either way, a save as dialog box will appear and the user will have final say.
    """

    # Validate file parameter passed. Also check to see if the path provided is lacking the default .h5 extension
    if not os.path.exists(sourceFile):
        if not os.path.exists(sourceFile + ".h5"):
            # Error message if the source file path could not be found in the system
            error(None,"Woah there!\n\n1. Couldn't find the file that you want to copy.\
                    \n2. Check to see if it exists in the file system and the path provided is correct"\
                    , "File Finding Police report")
            return
        else:
            # File exists but has an extension and one was not provided in the path given.
            # Add it to file path descriptor
            sourceFile += ".h5"


#             information(None, "the filename of source provided lacked the \".h5\" extension.\
#                         \n\nA file with the extension was found and presumed to be the source meant"\
#                         ,"Path Police report")

# Get file extension
    fileExtension = os.path.splitext(sourceFile)[-1]
    # Get the destination file name from the path provided
    destinationFile = os.path.split(sourceFile)[-1]
    destinationFolder = ""

    # If file has no extension, add the default .h5 extension to destination file name
    if fileExtension == "":
        warning(None, "The file you are trying to save has no extension\n\nAdding \".h5\" to the name of destination file"\
                 , ".h5 Extension Police")
        destinationFile = file + ".h5"
    # The file provided has different extension. Display a warning but do nothing.
    elif fileExtension != ".h5":
        warning(None, "Your file to be copied does not have an \".h5\" extension\n\nNo action taken."\
                , "h5 Extension Police")

    # Display confirmation dialog for copying the file
    dlg = ConfirmationDialog(
        title="You there!",
        yes_label="Yes Please!",
        no_label="Nah...",
        message=
        "Would you like to copy the data file generated after the session?\
                 \n\nIf you say Nah... and change your mind, you'll have to copy it manually later"
    )

    # Open the dialog GUI
    dlg.open()

    # User provided a destination path
    if destination:
        # Check to see if destination is a file name with an extension.
        destinationExtension = os.path.splitext(destination)[-1]
        if destinationExtension:
            # Is it .h5? If not, warn but don't override.
            if destinationExtension != ".h5":
                warning(None, "Your destination filename does not have an \".h5\" extension\n\nNo action taken."\
                        , "h5 Extension Police")
            destinationFolder, destinationFile = os.path.split(destination)
        # Assume destination is directory since there is no extension.
        else:
            destinationFolder = destination
    # Look up a default destination from the config file since no <destination> parameter was provided.
    else:
        configFile = os.environ.get("Voyeur_config")
        config = ConfigObj(configFile)

        # A user specific folder was provided.
        if user:
            destinationFolder = config['server']['folder']['data']['user']
        # Use default data folder as read from the config file.
        else:
            destinationFolder = config['server']['folder']['data']['default']

    # User provided a subdirectory, i.e subfolder, into which to place the file.
    if subdirectory:
        # The subdirectory provided has common path with the directory provided. Display warning but do nothing.
        if os.path.commonprefix((destination, subdirectory)):
            warning(None, "Friendly warning!\n<subdirectory> parameter provided has a common path with the <destination>\
                     path parameter\n\n1. No action taken.\n2. Check your final destination path to make sure it is what you want"\
                     , "Path Police report")
        destinationFolder = os.path.join(destinationFolder, subdirectory)

    # Path of the destination of file to be copied.
    destinationPath = os.path.join(destinationFolder, destinationFile)

    if dlg.return_code == YES:
        # A file with same name exists.
        if os.path.isfile(destinationPath):
            warning(
                None,
                "A file with given path already exists!\n\n1. No action taken\
                        \n2. Make sure to either rename file or choose different folder",
                "Path Police report")
        # Provided folder does not exist. Make one and inform the user.
        elif not os.path.isdir(destinationFolder):
            information(None, "Making a new folder to put the file into...",
                        "Information Transparency report")
            # TODO: What if this results in an exception? Catch and do something?
            # TODO: Keep track of made directories so we may delete them later
            os.makedirs(os.path.abspath(destinationFolder))
        # The save as dialog box.
        # TODO: change wildcard to current extension wildcard
        dialog = FileDialog(action="save as", title = "Select directory into which the data file will be copied",\
                             wildcard = "*.*", default_directory = destinationFolder, default_filename = destinationFile)  #*.h5|||
    elif dlg.return_code == NO and verbose:
        information(None, "No file was copied.\n\nIf you change your mind, you will have to transfer the data file manually."\
                    , "Information Transparency report")
        return

    dialog.open()

    # User clicked Save and successful input received.
    if dialog.return_code == OK:
        # The actual copying of the file. TODO: See if the copy2 function throws an exception
        copy2(sourceFile, dialog.path)
    # The user clicked Cancel.
    elif dialog.return_code == CANCEL:
        information(None, "No file was copied.\n\nIf you change your mind, you will have to transfer the data file manually."\
            , "Information Transparency report")

    #TODO: update the Voyeur config file after asking user

    return dialog.path
示例#42
0
class BlockApplicationViewHandler(Controller):
    """ Defines methods for handling menu actions in the BlockApplication.

        fixme: This is very much a temporary solution to test saving and
               loading of blocks.  Don't put much work in here because we
               will be using Envisage for the real deal...
    """
    def _on_import_data_file(self, info):
        """ Loading data files to import data for data contexts.

            File formats supported are ASCII, LAS, CSV, pickled files.
            ASCII files can be tab- or whitespace- delimited.
            If geo cannot be imported, only the pickled files can be
            used.
        """

        try:
            import geo
            wildcard = 'All files (*.*)|*.*|' + \
                       'ASCII files (*.asc)|*.asc|' + \
                       'Text files (*.txt)|*.txt|' + \
                       'CSV files (*.csv)|*.csv|' + \
                       'LAS files (*.las)|*.las|' + \
                       'Pickled files (*.pickle)|*.pickle|'+ \
                       'Segy files (*.segy)|*.segy'
        except ImportError:
            wildcard = 'Pickled files (*.pickle)|*.pickle'

        app = info.object
        file_dialog = FileDialog(
            action='open',
            default_directory=app.data_directory,
            wildcard=wildcard,
        )
        file_dialog.open()

        data_context, filename = None, file_dialog.path
        if file_dialog.path != '':
            filesplit = os.path.splitext(filename)
            if filesplit[1] != '':
                configurable_import = ConfigurableImportUI(filename=filename,
                                                           wildcard=wildcard)
                ui = configurable_import.edit_traits(kind='livemodal')
                if ui.result and isinstance(configurable_import.context,
                                            DataContext):
                    data_context = configurable_import.context
                    app.load_context(data_context,
                                     mode=configurable_import.save_choice_)

                    filename = configurable_import.filename

        if isinstance(data_context, DataContext):
            logger.debug('Loading data from %s' % filename)
        else:
            logger.error('Unidentified file format for data import: %s' %
                         filename)
        return

    def _on_reset(self, info):
        info.object.reset()
        pyface.information(parent=info.ui.control, message='Project cleaned')

    #------------------------------------------------------------------------
    # Script loading/saving
    #------------------------------------------------------------------------

    def _on_open(self, info):
        """ Menu action to load a script from file.  """
        file_dialog = FileDialog(action='open',
                                 default_directory=info.object.file_directory,
                                 wildcard='All files (*.*)|*.*')
        file_dialog.open()

        if file_dialog.path != '':
            info.object.load_code_from_file(file_dialog.path)

        return

    def _on_save(self, info):
        """ Save script to file """
        self._on_save_as(info)
        return

    def _on_save_as(self, info):
        """ Menu action to save script to file of different name """
        file_dialog = FileDialog(action='save as',
                                 default_path=info.object.file_directory,
                                 wildcard='All files (*.*)|*.*')
        file_dialog.open()

        if file_dialog.path != '':
            info.object.save_code_to_file(file_dialog.path)
            msg = 'Saving script at ', file_dialog.path
            logger.debug(msg)
        return

    def _on_export_as_function(self, info):
        """ Menu action to save function to file of different name 
        
        In this case the execution model and the local context are both
        included in the definition of a new function where free_variables
        take their default_value from the context.
        """
        file_dialog = FileDialog(action='save as',
                                 default_path=info.object.file_directory,
                                 wildcard='All files (*.*)|*.*')
        file_dialog.open()

        if file_dialog.path != '':
            info.object.export_as_function(file_dialog.path)
            msg = 'Saving script at ', file_dialog.path
            logger.debug(msg)
        return

    def _on_export_as_script(self, info):
        """ Menu action to save script to file of different name 
        
        In this case the execution model and the local context are both
        merged in a script in the form of assignments.
        """
        file_dialog = FileDialog(action='save as',
                                 default_path=info.object.file_directory,
                                 wildcard='All files (*.*)|*.*')
        file_dialog.open()

        if file_dialog.path != '':
            info.object.export_as_script(file_dialog.path)
            msg = 'Saving script at ', file_dialog.path
            logger.debug(msg)
        return

    #    def _on_run_custom_ui(self, info):
    #        """ Run a custom UI on top of the context.
    #        """
    #        wildcard = FileDialog.WILDCARD_PY.rstrip('|')
    #        file_dialog = FileDialog(action='open',
    #                                 default_directory=info.object.file_directory,
    #                                 wildcard=wildcard)
    #        file_dialog.open()
    #
    #        if file_dialog.path != '':
    #            info.object.run_custom_ui(file_dialog.path, live=False)
    #        return

    #------------------------------------------------------------------------
    # Project persistence
    #------------------------------------------------------------------------

    def _get_current_project_dir(self, project):
        """ Returns a best guess of where the "current" directory is, based on
        the project_save_path of the current project.  Can be used for loading
        and saving projects.
        """
        if os.path.exists(project.project_save_path):
            dir_path = os.path.split(project.project_save_path)
            project_dir = dir_path[0]
        else:
            project_dir = ETSConfig.user_data
        return project_dir

    def _save_project_graphically(self, parent, project, dirname):
        """ Saves the given project to a name **dirname**.  Gives the user
        graphical feedback.
        """
        # FIXME: pop up a progress bar
        try:
            project.save(dirname)
        except Exception, e:
            pyface.error(parent=parent,
                         message='Error while saving project:\n%s' % str(e))
            raise
        pyface.information(parent=parent,
                           message='Project saved to %s' % dirname)
示例#43
0
 def _on_reset(self, info):
     info.object.reset()
     pyface.information(parent=info.ui.control, message='Project cleaned')
示例#44
0
 def _scan_sample_step_fired(self):
     if self.ivSpectro.measurement_process or self.ivSpectro.acquisition_process:
         information(parent=None,title='please wait', message='Measurement at the spectrometer is running please finish this first.')
     else:
         thread.start_new_thread(self.scanning_step,())
示例#45
0
文件: instrui.py 项目: pmrup/labtools
 def _io_button_fired(self):
     information(None, 'IO parameters not defined for this device.')
示例#46
0
 def ensure_init(self):
     if self.icCamera.init_active:
         information(parent=None, title="please wait", message="The initialization of the camera is running. Please wait until the initialization is finished.")
         while self.icCamera.init_active:
             sleep(.5)
示例#47
0
 def test_open_dialog(self):
     self.gui.invoke_after(100, self.gui.stop_event_loop)
     information(None, build_bug_report_content())
示例#48
0
    def open_bug_report(self):
        from kromatography.utils.app_utils import build_bug_report_content

        information(None,
                    build_bug_report_content(self),
                    title="Report a bug / Send feedback")
示例#49
0
文件: instrui.py 项目: pmrup/labtools
 def _settings_button_fired(self):
     information(None, 'Settings not defined for this device.')
示例#50
0
def assert_env_set(mne_root=True, fs_home=False):
    """Make sure that environment variables are correctly set

    Parameters
    ----------
    mne_root : bool
        Make sure the MNE_ROOT environment variable is set correctly, and the
        mne bin directory is in the PATH.
    fs_home : bool
        Make sure the FREESURFER_HOME environment variable is set correctly.

    Returns
    -------
    success : bool
        Whether the requested environment variables are successfully set or
        not.

    Notes
    -----
    Environment variables are added to ``os.environ`` to make sure that bash
    tools can find them.
    """
    if fs_home:
        fs_home = os.environ.get('FREESURFER_HOME', None)
        test_dir = os.path.join('%s', 'subjects', 'fsaverage')
        while (fs_home is None) or not os.path.exists(test_dir % fs_home):
            msg = ("Please select the FREESURFER_HOME directory. This is the "
                   "root directory of the freesurfer installation. In order "
                   "to avoid this prompt in the future, set the "
                   "FREESURFER_HOME environment variable. "
                   "In Python, this can be done with:\n"
                   ">>> os.environ['FREESURFER_HOME'] = path")
            information(None, msg, "Select FREESURFER_HOME Directory")
            msg = "Please select the FREESURFER_HOME Directory"
            dlg = DirectoryDialog(message=msg, new_directory=False)
            if dlg.open() == OK:
                fs_home = dlg.path
            else:
                return False
        os.environ['FREESURFER_HOME'] = fs_home

    if mne_root:
        mne_root = get_config('MNE_ROOT')
        test_dir = os.path.join('%s', 'share', 'mne', 'mne_analyze')
        while (mne_root is None) or not os.path.exists(test_dir % mne_root):
            msg = ("Please select the MNE_ROOT directory. This is the root "
                   "directory of the MNE installation. In order to "
                   "avoid this prompt in the future, set the MNE_ROOT "
                   "environment variable. "
                   "In Python, this can be done with:\n"
                   ">>> os.environ['MNE_ROOT'] = path")
            information(None, msg, "Select MNE_ROOT Directory")
            msg = "Please select the MNE_ROOT Directory"
            dlg = DirectoryDialog(message=msg, new_directory=False)
            if dlg.open() == OK:
                mne_root = dlg.path
            else:
                return False
        os.environ['MNE_ROOT'] = mne_root

        # add mne bin directory to PATH
        mne_bin = os.path.realpath(os.path.join(mne_root, 'bin'))
        if mne_bin not in map(_expand_path, os.environ['PATH'].split(':')):
            os.environ['PATH'] += ':' + mne_bin

    return True
    def _export_plot_data_to_file(self, plot_list, data_path, **kwargs):
        """ Export the plots' PlotData to a file.

        Supported formats include zipped .csv, multi-tab .xlsx and multi-key
        HDF5.

        Parameters
        ----------
        plot_list : list
            List of PlotDescriptor instances, containing the plot whose data
            need to be exported.

        data_path : str
            Path to the data file to be generated.
        """
        data_format = self.data_format

        if not splitext(data_path)[1]:
            data_path += data_format

        if isfile(data_path):
            msg = "Target data path specified already exists: {}. It will be" \
                  " overwritten.".format(data_path)
            logger.warning(msg)

        data_dir = dirname(data_path)

        if data_format == ".xlsx":
            writer = pd.ExcelWriter(data_path)
        elif data_format == ".h5":
            writer = pd.HDFStore(data_path)

        try:
            if data_format == ".csv":
                data_path = join(
                    data_dir,
                    string2filename(DEFAULT_DATASET_NAME) + ".csv")
                self._export_data_source_to_file(target=data_path)
            elif data_format == ".xlsx":
                writer = pd.ExcelWriter(data_path)
                self._export_data_source_to_file(target=writer,
                                                 key=DEFAULT_DATASET_NAME)
            else:
                self._export_data_source_to_file(target=writer,
                                                 key=DEFAULT_DATASET_NAME)

            created_csv_files = [data_path]
            for i, desc in enumerate(plot_list):
                df_dict = plot_data2dataframes(desc)
                for name, df in df_dict.items():
                    key = "plot_{}_{}".format(i, name)
                    if data_format == ".csv":
                        target_fpath = join(data_dir,
                                            string2filename(key) + ".csv")
                        df.to_csv(target_fpath)
                        created_csv_files.append(target_fpath)
                    elif data_format == ".xlsx":
                        df.to_excel(writer, sheet_name=key, **kwargs)
                    elif data_format == ".h5":
                        df.to_hdf(data_path, key=key, **kwargs)
                    else:
                        msg = "Data format {} not implemented. Please report" \
                              " this issue.".format(data_format)
                        logger.exception(msg)
                        raise NotImplementedError(msg)
        finally:
            if data_format in [".xlsx", ".h5"]:
                writer.close()

        if data_format == ".csv" and len(created_csv_files) > 1:
            # zip up all csv files:
            data_path = join(data_dir, self.data_filename + ".zip")
            with ZipFile(data_path, "w") as f:
                for f_path in created_csv_files:
                    f.write(f_path, basename(f_path))

            for f_path in created_csv_files:
                os.remove(f_path)

        if self.interactive:
            msg = "Plot data is stored in: {}".format(data_path)
            information(None, msg)
示例#52
0
    def launch_experiment(self, info, selected):
        '''
        Runs specified experiment type.  On successful completion of an
        experiment, marks the animal as processed and saves the last paradigm
        used.  If the experiment is launched but not run, changes to the
        paradigm will not be saved.
        '''

        filename = selected._store_filename
        pathname = selected._store_pathname

        cohort_folder = filename[:-4]
        if not os.path.exists(cohort_folder):
            os.makedirs(cohort_folder)
        
        with tables.openFile(filename, 'a', rootUEP=pathname) as fh:
            # We need to call prepare_experiment prior to loading a saved
            # paradigm.  prepare_experiment adds the roving parameters as traits
            # on the TrialSetting object.  If a paradigm is loaded before the
            # traits are added, wonky things may happen.
            paradigm_name = get_experiment(self.args.type).node_name
            animal_folder = '{}_{}'.format(selected.identifier.upper(),
                                           selected.sex.upper())
            paradigm_folder = os.path.join(cohort_folder, animal_folder,
                                           paradigm_name)
            log.debug('paradigm folder %s', paradigm_folder)

            if not os.path.exists(paradigm_folder):
                os.makedirs(paradigm_folder)

            globpattern = os.path.join(paradigm_folder, 'session_*.hd5')
            log.debug('globbing for files in the paradigm folder using %s',
                      globpattern)
            session_files = sorted(glob(globpattern))
            if len(session_files):
                last_session_file = session_files[-1]
                log.debug('found last session file %s', last_session_file)
                last_session_id = int(last_session_file[-8:-4]) + 1
            else:
                # There are no prior sessions
                last_session_id = 0

            session_name = 'session_{:04d}'.format(last_session_id)
            log.debug('session name %s', session_name)
            file_name = os.path.join(paradigm_folder, session_name + '.hd5')

            relative_file_name = os.path.join(os.path.basename(cohort_folder),
                                              animal_folder, paradigm_name,
                                              session_name)

            # Calling abspath converts all / to the proper \ format.  Typically
            # it does not matter if the path separator uses / or \; however,
            # PyTables has some code that fails if we use the / separator when
            # creating a hardlink.
            file_name = os.path.abspath(file_name)
            log.debug('session file %s', file_name)

            with tables.openFile(file_name, 'a') as fh_data:
                node = fh_data.root
                model, controller = prepare_experiment(self.args, node,
                                                       create_child=False)
                model.animal = selected

                # Node that will contain the hard links to the actual experiment
                # file
                link_node = get_or_append_node(fh.root, 'experiments')
                link_name = paradigm_name + '_' + session_name
                link_target = relative_file_name + ':' + node._v_pathname
                link_target = str(link_target)
                log.debug('creating external link to %s', link_target)
                fh.createExternalLink(link_node, link_name, link_target)

                # Try to load settings from the last time the subject was run.
                # If we cannot load the settings for whatever reason, notify the
                # user and fall back to the default settings.
                paradigm_node = get_or_append_node(link_node, 'last_paradigm')
                paradigm_hash = paradigm_name + '_' + '_'.join(self.args.rove)

                # Attempt to load the last used paradigm
                paradigm = None
                try:
                    paradigm = paradigm_node._v_attrs[paradigm_hash]
                except KeyError as e:
                    log.exception(e)
                    mesg = 'No prior paradigm found'
                    log.debug(mesg)
                    information(info.ui.control, mesg)
                except pickle.UnpicklingError as e:
                    log.exception(e)
                    mesg = 'Prior settings found, but unable to load'
                    log.debug(mesg)
                    information(info.ui.control, mesg)

                try:
                    if paradigm is not None:
                        log.debug('Using paradigm from last time this animal was run')
                        model.paradigm = paradigm
                    elif self.last_paradigm is not None:
                        log.debug('Animal does not have any prior paradigm.')
                        model.paradigm = self.last_paradigm
                        mesg = 'Using paradigm from previous animal'
                        information(info.ui.control, mesg)
                        log.debug(mesg)
                except TraitError:
                    log.debug('Prior paradigm is not compatible with experiment')
        
                try:
                    model.edit_traits(parent=info.ui.control, kind='livemodal',
                                      handler=controller)

                    # One very nice feature of PyTables is that it will
                    # automatically pickle classes into strings that can be
                    # stored as node attributes.
                    paradigm_node._v_attrs[paradigm_hash] = model.paradigm
                    self.last_paradigm = model.paradigm
                    selected.processed = True
                    log.debug('Saved paradigm for animal to the datafile')
                except AttributeError, e: 
                    log.exception(e)
                except SystemError, e:
                    from textwrap import dedent
                    mesg = """\
                    Could not launch experiment.  This likely means that you
                    forgot to turn on a piece of equipment.  Please check and
                    ensure that the RX6, RZ5 and PA5 are turned on.  If you
                    still get this error message, please try power-cycling the
                    rack.  If this still does not fix the error, power-cycle the
                    computer as well.  
                    
                    Please remember that you need to give the equipment rack a
                    minute to boot up once you turn it back on before attempting
                    to launch an experiment.
                    """
                    error(info.ui.control, str(e) + '\n\n' + dedent(mesg))
 def _on_reset(self,info):
     info.object.reset()
     pyface.information(parent=info.ui.control, message='Project cleaned')
示例#54
0
    def _get_user_location(self, project, parent_window):
        """
        Prompt the user for a new location for the specified project.

        Returns the chosen location or, if the user cancelled, an empty
        string.

        """

        # The dialog to use depends on whether we're prompting for a file or
        # a directory.
        if self.model_service.are_projects_files():
            dialog = FileDialog(parent = parent_window,
                title = 'Save Project As',
                default_path = project.location,
                action = 'save as',
                )
            title_type = 'File'
        else:
            dialog = DirectoryDialog(parent = parent_window,
                message = 'Choose a Directory for the Project',
                default_path = project.location,
                action = 'open'
                )
            title_type = 'Directory'

        # Prompt the user for a new location and then validate we're not
        # overwriting something without getting confirmation from the user.
        result = ""
        while(dialog.open() == OK):
            location = dialog.path.strip()

            # If the chosen location doesn't exist yet, we're set.
            if not os.path.exists(location):
                logger.debug('Location [%s] does not exist yet.', location)
                result = location
                break

            # Otherwise, confirm with the user that they want to overwrite the
            # existing files or directories.  If they don't want to, then loop
            # back and prompt them for a new location.
            else:
                logger.debug('Location [%s] exists.  Prompting for overwrite '
                    'permission.', location)
                message = 'Overwrite %s?' % location
                title = 'Project %s Exists' % title_type
                action = confirm(parent_window, message, title)
                if action == YES:

                    # Only use the location if we successfully remove the
                    # existing files or directories at that location.
                    try:
                        self.model_service.clean_location(location)
                        result = location
                        break

                    # Otherwise, display the remove error to the user and give
                    # them another chance to pick another location
                    except Exception as e:
                        msg = str(e)
                        title = 'Unable To Overwrite %s' % location
                        information(parent_window, msg, title)

        logger.debug('Returning user location [%s]', result)
        return result
示例#55
0
    def on_problem(self):

        log = str(self._get_package_versions()) + "\n" + self.application.application_log.getvalue()
        
        msg = "The best way to report a problem is send an application log to " \
              "the developers.  You can do so by either sending us an email " \
              "with the log in it, or saving the log to a file and filing a " \
              "new issue on GitHub at " \
              "https://github.com/bpteague/cytoflow/issues/new" 
        
        dialog = ConfirmationDialog(message = msg,
                                    informative = "Which would you like to do?",
                                    yes_label = "Send an email...",
                                    no_label = "Save to a file...")
                
        if dialog.open() == NO:
            dialog = DefaultFileDialog(parent = self.window.control,
                                       action = 'save as', 
                                       default_suffix = "log",
                                       wildcard = (FileDialog.create_wildcard("Log files", "*.log") + ';' + #@UndefinedVariable  
                                                   FileDialog.create_wildcard("All files", "*")))                    #@UndefinedVariable  
            
            if dialog.open() == OK:
                with open(dialog.path, 'w') as f:
                    f.write(log)
                  
                webbrowser.open_new_tab("https://github.com/bpteague/cytoflow/issues/new")
                  
            return
        
        information(None, "I'll now try to open your email client and create a "
                    "new message to the developer.  Debugging logs are "
                    "attached.  Please fill out the template bug report and " 
                    "send -- thank you for reporting a bug!")

        log = self.application.application_log.getvalue()
        
        versions = ["{0} {1}".format(key, value) for key, value in self._get_package_versions().items()]

        body = """
Thank you for your bug report!  Please fill out the following template.

PLATFORM (Mac, PC, Linux, other):

OPERATING SYSTEM (eg OSX 10.7, Windows 8.1):

SEVERITY (Critical? Major? Minor? Enhancement?):

DESCRIPTION:
  - What were you trying to do?
  - What happened?
  - What did you expect to happen?
  
PACKAGE VERSIONS: {0}

DEBUG LOG: {1}
""".format(versions, log)

        mailto("*****@*****.**", 
               subject = "Cytoflow bug report",
               body = body)
示例#56
0
def save_data_file(sourceFile, destination = None, subdirectory = None, user = None, verbose = True):
    """ Function used to save (i.e copy) a data file into a directory of choice after an experimental session
        Parameters: sourceFile   - the path of the file that was generated by the experimental session and that resides
                                    in the local file system.
                    destination  - An optional destination path where to save the file. File name may be included
                                    or not at the end of the path.
                    subdirectory - An optional subdirectory, i.e folder, to add to the destination path. For example,
                                    if the destination path is a folder called "experiments", the subdirectory can be
                                    a child folder of "experiments", named after the experiment type ("behaviour"
                                    for instance).
                    user         - An optional parameter to indicate which user is conducting the experiments.
                                    If supplied, and if no destination is passed, a configuration file is looked
                                    up to retrieve the folder into which the user is usually copying data files.
                                    If no destination and no user is provided, a default directory is looked up
                                    in the configuration file as the default destination of the file to be copied.
                                    Either way, a save as dialog box will appear and the user will have final say.
    """

    # Validate file parameter passed. Also check to see if the path provided is lacking the default .h5 extension
    if not os.path.exists(sourceFile):
        if not os.path.exists(sourceFile+".h5"):
            # Error message if the source file path could not be found in the system
            error(None,"Woah there!\n\n1. Couldn't find the file that you want to copy.\
                    \n2. Check to see if it exists in the file system and the path provided is correct"\
                    , "File Finding Police report")
            return
        else:
            # File exists but has an extension and one was not provided in the path given.
            # Add it to file path descriptor
            sourceFile += ".h5"
#             information(None, "the filename of source provided lacked the \".h5\" extension.\
#                         \n\nA file with the extension was found and presumed to be the source meant"\
#                         ,"Path Police report")

    # Get file extension
    fileExtension = os.path.splitext(sourceFile)[-1]
    # Get the destination file name from the path provided
    destinationFile = os.path.split(sourceFile)[-1]
    destinationFolder = ""

    # If file has no extension, add the default .h5 extension to destination file name
    if fileExtension == "":
        warning(None, "The file you are trying to save has no extension\n\nAdding \".h5\" to the name of destination file"\
                 , ".h5 Extension Police")
        destinationFile = file + ".h5"
    # The file provided has different extension. Display a warning but do nothing.
    elif fileExtension != ".h5":
        warning(None, "Your file to be copied does not have an \".h5\" extension\n\nNo action taken."\
                , "h5 Extension Police")

    # Display confirmation dialog for copying the file
    dlg = ConfirmationDialog(title = "You there!", yes_label = "Yes Please!",
                 no_label = "Nah...", message = "Would you like to copy the data file generated after the session?\
                 \n\nIf you say Nah... and change your mind, you'll have to copy it manually later")

    # Open the dialog GUI
    dlg.open()

    # User provided a destination path
    if destination:
        # Check to see if destination is a file name with an extension.
        destinationExtension = os.path.splitext(destination)[-1]
        if destinationExtension:
            # Is it .h5? If not, warn but don't override.
            if destinationExtension != ".h5":
                warning(None, "Your destination filename does not have an \".h5\" extension\n\nNo action taken."\
                        , "h5 Extension Police")
            destinationFolder, destinationFile = os.path.split(destination)
        # Assume destination is directory since there is no extension.
        else:
            destinationFolder = destination
    # Look up a default destination from the config file since no <destination> parameter was provided.
    else:
        configFile = os.environ.get("Voyeur_config")
        config = ConfigObj(configFile)

        # A user specific folder was provided.
        if user:
            destinationFolder = config['server']['folder']['data']['user']
        # Use default data folder as read from the config file.
        else:
            destinationFolder = config['server']['folder']['data']['default']

    # User provided a subdirectory, i.e subfolder, into which to place the file.
    if subdirectory:
        # The subdirectory provided has common path with the directory provided. Display warning but do nothing.
        if os.path.commonprefix((destination,subdirectory)):
            warning(None, "Friendly warning!\n<subdirectory> parameter provided has a common path with the <destination>\
                     path parameter\n\n1. No action taken.\n2. Check your final destination path to make sure it is what you want"\
                     , "Path Police report")
        destinationFolder = os.path.join(destinationFolder,subdirectory)

    # Path of the destination of file to be copied.
    destinationPath = os.path.join(destinationFolder,destinationFile)

    if dlg.return_code == YES:
        # A file with same name exists.
        if os.path.isfile(destinationPath):
            warning(None, "A file with given path already exists!\n\n1. No action taken\
                        \n2. Make sure to either rename file or choose different folder", "Path Police report")
        # Provided folder does not exist. Make one and inform the user.
        elif not os.path.isdir(destinationFolder):
            information(None, "Making a new folder to put the file into...", "Information Transparency report")
            # TODO: What if this results in an exception? Catch and do something?
            # TODO: Keep track of made directories so we may delete them later
            os.makedirs(os.path.abspath(destinationFolder))
        # The save as dialog box.
        # TODO: change wildcard to current extension wildcard
        dialog = FileDialog(action="save as", title = "Select directory into which the data file will be copied",\
                             wildcard = "*.*", default_directory = destinationFolder, default_filename = destinationFile)  #*.h5|||
    elif dlg.return_code == NO and verbose:
        information(None, "No file was copied.\n\nIf you change your mind, you will have to transfer the data file manually."\
                    , "Information Transparency report")
        return

    dialog.open()

    # User clicked Save and successful input received.
    if dialog.return_code == OK:
        # The actual copying of the file. TODO: See if the copy2 function throws an exception
        copy2(sourceFile, dialog.path)
    # The user clicked Cancel.
    elif dialog.return_code == CANCEL:
        information(None, "No file was copied.\n\nIf you change your mind, you will have to transfer the data file manually."\
            , "Information Transparency report")

    #TODO: update the Voyeur config file after asking user

    return dialog.path