Exemple #1
0
    def sort(self, column, order=Qt.AscendingOrder):
        """Overriding sort method"""
        if self.complex_intran is not None:
            if self.complex_intran.any(axis=0).iloc[column-1]:
                QMessageBox.critical(self.dialog, "Error",
                                     "TypeError error: no ordering "
                                     "relation is defined for complex numbers")
                return False
        try:
            ascending = order == Qt.AscendingOrder
            if column > 0:
                try:
                    self.df.sort_values(by=self.df.columns[column-1],
                                        ascending=ascending, inplace=True,
                                        kind='mergesort')
                except AttributeError:
                    # for pandas version < 0.17
                    self.df.sort(columns=self.df.columns[column-1],
                                 ascending=ascending, inplace=True,
                                 kind='mergesort')
                self.update_df_index()
            else:
                self.df.sort_index(inplace=True, ascending=ascending)
                self.update_df_index()
        except TypeError as e:
            QMessageBox.critical(self.dialog, "Error",
                                 "TypeError error: %s" % str(e))
            return False

        self.reset()
        return True
Exemple #2
0
 def _scatter_artist(self, axes, state, layer=None, layer_state=None):
     if len(self._layer_artist_container) == 0:
         QMessageBox.critical(self, "Error", "Can only add a scatter plot "
                              "overlay once an image is present",
                              buttons=QMessageBox.Ok)
         return None
     return ScatterLayerArtist(axes, state, layer=layer, layer_state=None)
Exemple #3
0
    def change_format(self):
        """
        Ask user for display format for floats and use it.

        This function also checks whether the format is valid and emits
        `sig_option_changed`.
        """
        format, valid = QInputDialog.getText(self, _('Format'),
                                             _("Float formatting"),
                                             QLineEdit.Normal,
                                             self.dataModel.get_format())
        if valid:
            format = str(format)
            try:
                format % 1.1
            except:
                msg = _("Format ({}) is incorrect").format(format)
                QMessageBox.critical(self, _("Error"), msg)
                return
            if not format.startswith('%'):
                msg = _("Format ({}) should start with '%'").format(format)
                QMessageBox.critical(self, _("Error"), msg)
                return
            self.dataModel.set_format(format)
            self.sig_option_changed.emit('dataframe_format', format)
Exemple #4
0
    def setData(self, index, value, role=Qt.EditRole, change_type=None):
        """Cell content change"""
        column = index.column()
        row = index.row()

        if change_type is not None:
            try:
                value = self.data(index, role=Qt.DisplayRole)
                val = from_qvariant(value, str)
                if change_type is bool:
                    val = bool_false_check(val)
                self.df.iloc[row, column - 1] = change_type(val)
            except ValueError:
                self.df.iloc[row, column - 1] = change_type('0')
        else:
            val = from_qvariant(value, str)
            current_value = self.get_value(row, column-1)
            if isinstance(current_value, bool):
                val = bool_false_check(val)
            supported_types = (bool,) + REAL_NUMBER_TYPES + COMPLEX_NUMBER_TYPES
            if (isinstance(current_value, supported_types) or 
                    is_text_string(current_value)):
                try:
                    self.df.iloc[row, column-1] = current_value.__class__(val)
                except ValueError as e:
                    QMessageBox.critical(self.dialog, "Error",
                                         "Value error: %s" % str(e))
                    return False
            else:
                QMessageBox.critical(self.dialog, "Error",
                                     "The type of the cell is not a supported "
                                     "type")
                return False
        self.max_min_col_update()
        return True
Exemple #5
0
 def start(self):
     filename = to_text_string(self.filecombo.currentText())
     
     self.process = QProcess(self)
     self.process.setProcessChannelMode(QProcess.SeparateChannels)
     self.process.setWorkingDirectory(osp.dirname(filename))
     self.process.readyReadStandardOutput.connect(self.read_output)
     self.process.readyReadStandardError.connect(
                                       lambda: self.read_output(error=True))
     self.process.finished.connect(lambda ec, es=QProcess.ExitStatus:
                                   self.finished(ec, es))
     self.stop_button.clicked.connect(self.process.kill)
     
     self.output = ''
     self.error_output = ''
     
     plver = PYLINT_VER
     if plver is not None:
         if plver.split('.')[0] == '0':
             p_args = ['-i', 'yes']
         else:
             # Option '-i' (alias for '--include-ids') was removed in pylint
             # 1.0
             p_args = ["--msg-template='{msg_id}:{line:3d},"\
                       "{column}: {obj}: {msg}"]
         p_args += [osp.basename(filename)]
     else:
         p_args = [osp.basename(filename)]
     self.process.start(PYLINT_PATH, p_args)
     
     running = self.process.waitForStarted()
     self.set_running_state(running)
     if not running:
         QMessageBox.critical(self, _("Error"),
                              _("Process failed to start"))
Exemple #6
0
    def open_project(self, path=None, restart_consoles=True,
                     save_previous_files=True):
        """Open the project located in `path`"""
        if path is None:
            basedir = get_home_dir()
            path = getexistingdirectory(parent=self,
                                        caption=_("Open project"),
                                        basedir=basedir)
            if not self.is_valid_project(path):
                if path:
                    QMessageBox.critical(self, _('Error'),
                                _("<b>%s</b> is not a Spyder project!") % path)
                return
            else:
                self.add_to_recent(path)

        # A project was not open before
        if self.current_active_project is None:
            if save_previous_files:
                self.editor.save_open_files()
            self.editor.set_option('last_working_dir', getcwd_or_home())
            self.show_explorer()
        else: # we are switching projects
            self.set_project_filenames(self.editor.get_open_filenames())

        self.current_active_project = EmptyProject(path)
        self.latest_project = EmptyProject(path)
        self.set_option('current_project_path', self.get_active_project_path())
        self.setup_menu_actions()
        self.sig_project_loaded.emit(path)
        self.pythonpath_changed.emit()
        if restart_consoles:
            self.restart_consoles()
Exemple #7
0
 def chdir(self, directory=None, browsing_history=False):
     """Set directory as working directory"""
     if directory is not None:
         directory = osp.abspath(to_text_string(directory))
     if browsing_history:
         directory = self.history[self.histindex]
     elif directory in self.history:
         self.histindex = self.history.index(directory)
     else:
         if self.histindex is None:
             self.history = []
         else:
             self.history = self.history[:self.histindex+1]
         if len(self.history) == 0 or \
            (self.history and self.history[-1] != directory):
             self.history.append(directory)
         self.histindex = len(self.history)-1
     directory = to_text_string(directory)
     if PY2:
         PermissionError = OSError
     try:
         os.chdir(directory)
         self.parent_widget.open_dir.emit(directory)
         self.refresh(new_path=directory, force_current=True)
     except PermissionError:
         QMessageBox.critical(self.parent_widget, "Error",
                              _("You don't have the right permissions to "
                                "open this directory"))
Exemple #8
0
 def _set_step(self, step):
     """Proceed to a given step"""
     new_tab = self.tab_widget.currentIndex() + step
     assert new_tab < self.tab_widget.count() and new_tab >= 0
     if new_tab == self.tab_widget.count()-1:
         try:
             self.table_widget.open_data(self._get_plain_text(),
                                     self.text_widget.get_col_sep(),
                                     self.text_widget.get_row_sep(),
                                     self.text_widget.trnsp_box.isChecked(),
                                     self.text_widget.get_skiprows(),
                                     self.text_widget.get_comments())
             self.done_btn.setEnabled(True)
             self.done_btn.setDefault(True)
             self.fwd_btn.setEnabled(False)
             self.back_btn.setEnabled(True)
         except (SyntaxError, AssertionError) as error:
             QMessageBox.critical(self, _("Import wizard"),
                         _("<b>Unable to proceed to next step</b>"
                           "<br><br>Please check your entries."
                           "<br><br>Error message:<br>%s") % str(error))
             return
     elif new_tab == 0:
         self.done_btn.setEnabled(False)
         self.fwd_btn.setEnabled(True)
         self.back_btn.setEnabled(False)
     self._focus_tab(new_tab)
Exemple #9
0
 def rename_file(self, fname):
     """Rename file"""
     path, valid = QInputDialog.getText(self, _('Rename'),
                           _('New name:'), QLineEdit.Normal,
                           osp.basename(fname))
     if valid:
         path = osp.join(osp.dirname(fname), to_text_string(path))
         if path == fname:
             return
         if osp.exists(path):
             if QMessageBox.warning(self, _("Rename"),
                      _("Do you really want to rename <b>%s</b> and "
                        "overwrite the existing file <b>%s</b>?"
                        ) % (osp.basename(fname), osp.basename(path)),
                      QMessageBox.Yes|QMessageBox.No) == QMessageBox.No:
                 return
         try:
             misc.rename_file(fname, path)
             self.parent_widget.renamed.emit(fname, path)
             return path
         except EnvironmentError as error:
             QMessageBox.critical(self, _("Rename"),
                         _("<b>Unable to rename file <i>%s</i></b>"
                           "<br><br>Error message:<br>%s"
                           ) % (osp.basename(fname), to_text_string(error)))
Exemple #10
0
 def delete_file(self, fname, multiple, yes_to_all):
     """Delete file"""
     if multiple:
         buttons = QMessageBox.Yes|QMessageBox.YesAll| \
                   QMessageBox.No|QMessageBox.Cancel
     else:
         buttons = QMessageBox.Yes|QMessageBox.No
     if yes_to_all is None:
         answer = QMessageBox.warning(self, _("Delete"),
                              _("Do you really want "
                                "to delete <b>%s</b>?"
                                ) % osp.basename(fname), buttons)
         if answer == QMessageBox.No:
             return yes_to_all
         elif answer == QMessageBox.Cancel:
             return False
         elif answer == QMessageBox.YesAll:
             yes_to_all = True
     try:
         if osp.isfile(fname):
             misc.remove_file(fname)
             self.parent_widget.removed.emit(fname)
         else:
             self.remove_tree(fname)
             self.parent_widget.removed_tree.emit(fname)
         return yes_to_all
     except EnvironmentError as error:
         action_str = _('delete')
         QMessageBox.critical(self, _("Project Explorer"),
                         _("<b>Unable to %s <i>%s</i></b>"
                           "<br><br>Error message:<br>%s"
                           ) % (action_str, fname, to_text_string(error)))
     return False
Exemple #11
0
 def create_new_folder(self, current_path, title, subtitle, is_package):
     """Create new folder"""
     if current_path is None:
         current_path = ''
     if osp.isfile(current_path):
         current_path = osp.dirname(current_path)
     name, valid = QInputDialog.getText(self, title, subtitle,
                                        QLineEdit.Normal, "")
     if valid:
         dirname = osp.join(current_path, to_text_string(name))
         try:
             os.mkdir(dirname)
         except EnvironmentError as error:
             QMessageBox.critical(self, title,
                                  _("<b>Unable "
                                    "to create folder <i>%s</i></b>"
                                    "<br><br>Error message:<br>%s"
                                    ) % (dirname, to_text_string(error)))
         finally:
             if is_package:
                 fname = osp.join(dirname, '__init__.py')
                 try:
                     with open(fname, 'wb') as f:
                         f.write(to_binary_string('#'))
                     return dirname
                 except EnvironmentError as error:
                     QMessageBox.critical(self, title,
                                          _("<b>Unable "
                                            "to create file <i>%s</i></b>"
                                            "<br><br>Error message:<br>%s"
                                            ) % (fname,
                                                 to_text_string(error)))
Exemple #12
0
    def save_data(self, filename=None):
        """Save data"""
        if filename is None:
            filename = self.filename
            if filename is None:
                filename = getcwd_or_home()
            filename, _selfilter = getsavefilename(self, _("Save data"),
                                                   filename,
                                                   iofunctions.save_filters)
            if filename:
                self.filename = filename
            else:
                return False
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        QApplication.processEvents()

        error_message = self.shellwidget.save_namespace(self.filename)
        self.shellwidget._kernel_reply = None

        QApplication.restoreOverrideCursor()
        QApplication.processEvents()
        if error_message is not None:
            if 'Some objects could not be saved:' in error_message:
                save_data_message = (
                    _('<b>Some objects could not be saved:</b>')
                    + '<br><br><code>{obj_list}</code>'.format(
                        obj_list=error_message.split(': ')[1]))
            else:
                save_data_message = _(
                    '<b>Unable to save current workspace</b>'
                    '<br><br>Error message:<br>') + error_message
            QMessageBox.critical(self, _("Save data"), save_data_message)
        self.save_button.setEnabled(self.filename is not None)
Exemple #13
0
    def save_data(self, filename=None):
        """Save data"""
        if filename is None:
            filename = self.filename
            if filename is None:
                filename = getcwd_or_home()
            filename, _selfilter = getsavefilename(self, _("Save data"),
                                                   filename,
                                                   iofunctions.save_filters)
            if filename:
                self.filename = filename
            else:
                return False
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        QApplication.processEvents()

        error_message = self.shellwidget.save_namespace(self.filename)
        self.shellwidget._kernel_reply = None

        QApplication.restoreOverrideCursor()
        QApplication.processEvents()
        if error_message is not None:
            QMessageBox.critical(self, _("Save data"),
                            _("<b>Unable to save current workspace</b>"
                              "<br><br>Error message:<br>%s") % error_message)
        self.save_button.setEnabled(self.filename is not None)
Exemple #14
0
 def delete_project(self):
     """
     Delete the current project without deleting the files in the directory.
     """
     if self.current_active_project:
         self.switch_to_plugin()
         path = self.current_active_project.root_path
         buttons = QMessageBox.Yes | QMessageBox.No
         answer = QMessageBox.warning(
             self,
             _("Delete"),
             _("Do you really want to delete <b>{filename}</b>?<br><br>"
               "<b>Note:</b> This action will only delete the project. "
               "Its files are going to be preserved on disk."
               ).format(filename=osp.basename(path)),
             buttons)
         if answer == QMessageBox.Yes:
             try:
                 self.close_project()
                 shutil.rmtree(osp.join(path, '.spyproject'))
             except EnvironmentError as error:
                 QMessageBox.critical(
                     self,
                     _("Project Explorer"),
                     _("<b>Unable to delete <i>{varpath}</i></b>"
                       "<br><br>The error message was:<br>{error}"
                       ).format(varpath=path, error=to_text_string(error)))
 def save_data(self, filename=None):
     """Save data"""
     if filename is None:
         filename = self.filename
         if filename is None:
             filename = getcwd()
         filename, _selfilter = getsavefilename(self, _("Save data"),
                                                filename,
                                                iofunctions.save_filters)
         if filename:
             self.filename = filename
         else:
             return False
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     QApplication.processEvents()
     if self.is_internal_shell:
         wsfilter = self.get_internal_shell_filter('picklable',
                                                   check_all=True)
         namespace = wsfilter(self.shellwidget.interpreter.namespace).copy()
         error_message = iofunctions.save(namespace, filename)
     else:
         settings = self.get_view_settings()
         error_message = monitor_save_globals(self._get_sock(),
                                              settings, filename)
     QApplication.restoreOverrideCursor()
     QApplication.processEvents()
     if error_message is not None:
         QMessageBox.critical(self, _("Save data"),
                         _("<b>Unable to save current workspace</b>"
                           "<br><br>Error message:<br>%s") % error_message)
     self.save_button.setEnabled(self.filename is not None)
Exemple #16
0
 def finished(self, exit_code, exit_status):
     self.set_running_state(False)
     if not self.output:
         if self.error_output:
             QMessageBox.critical(self, _("Error"), self.error_output)
             print("pylint error:\n\n" + self.error_output, file=sys.stderr)
         return
     
     # Convention, Refactor, Warning, Error
     results = {'C:': [], 'R:': [], 'W:': [], 'E:': []}
     txt_module = '************* Module '
     
     module = '' # Should not be needed - just in case something goes wrong
     for line in self.output.splitlines():
         if line.startswith(txt_module):
             # New module
             module = line[len(txt_module):]
             continue
         # Supporting option include-ids: ('R3873:' instead of 'R:')
         if not re.match('^[CRWE]+([0-9]{4})?:', line):
             continue
         i1 = line.find(':')
         if i1 == -1:
             continue
         msg_id = line[:i1]
         i2 = line.find(':', i1+1)
         if i2 == -1:
             continue
         line_nb = line[i1+1:i2].strip()
         if not line_nb:
             continue
         line_nb = int(line_nb.split(',')[0])
         message = line[i2+1:]
         item = (module, line_nb, message, msg_id)
         results[line[0]+':'].append(item)
         
     # Rate
     rate = None
     txt_rate = 'Your code has been rated at '
     i_rate = self.output.find(txt_rate)
     if i_rate > 0:
         i_rate_end = self.output.find('/10', i_rate)
         if i_rate_end > 0:
             rate = self.output[i_rate+len(txt_rate):i_rate_end]
     
     # Previous run
     previous = ''
     if rate is not None:
         txt_prun = 'previous run: '
         i_prun = self.output.find(txt_prun, i_rate_end)
         if i_prun > 0:
             i_prun_end = self.output.find('/10', i_prun)
             previous = self.output[i_prun+len(txt_prun):i_prun_end]
         
     
     filename = to_text_string(self.filecombo.currentText())
     self.set_data(filename, (time.localtime(), rate, previous, results))
     self.output = self.error_output + self.output
     self.show_data(justanalyzed=True)
 def __init__(self, *args, **kwargs):
     super(VispyVolumeViewer, self).__init__(*args, **kwargs)
     if not OPENGL_INSTALLED:
         self.close()
         QMessageBox.critical(self, "Error",
                              "The PyOpenGL package is required for the "
                              "3D volume rendering viewer",
                              buttons=QMessageBox.Ok)
Exemple #18
0
def run_python_script_in_terminal(fname, wdir, args, interact,
                                  debug, python_args):
    """Run Python script in an external system terminal"""
    
    # If fname has spaces on it it can't be ran on Windows, so we have to
    # enclose it in quotes. Also wdir can come with / as os.sep, so we
    # need to take care of it
    if os.name == 'nt':
        fname = '"' + fname + '"'
        wdir = wdir.replace('/', '\\')
    
    p_args = ['python']
    p_args += get_python_args(fname, python_args, interact, debug, args)
    
    if os.name == 'nt':
        cmd = 'start cmd.exe /c "cd %s && ' % wdir + ' '.join(p_args) + '"'
        # Command line and cwd have to be converted to the filesystem
        # encoding before passing them to subprocess, but only for
        # Python 2.
        # See http://bugs.python.org/issue1759845#msg74142 and Issue 1856
        if PY2:
            cmd = encoding.to_fs_from_unicode(cmd)
            wdir = encoding.to_fs_from_unicode(wdir)
        try:
            run_shell_command(cmd, cwd=wdir)
        except WindowsError:
            from qtpy.QtWidgets import QMessageBox

            from spyderlib.config.base import _

            QMessageBox.critical(None, _('Run'),
                                 _("It was not possible to run this file in "
                                   "an external terminal"),
                                 QMessageBox.Ok)
    elif os.name == 'posix':
        cmd = 'gnome-terminal'
        if is_program_installed(cmd):
            run_program(cmd, ['--working-directory', wdir, '-x'] + p_args,
                        cwd=wdir)
            return
        cmd = 'konsole'
        if is_program_installed(cmd):
            run_program(cmd, ['--workdir', wdir, '-e'] + p_args,
                        cwd=wdir)
            return
        cmd = 'xfce4-terminal'
        if is_program_installed(cmd):
            run_program(cmd, ['--working-directory', wdir, '-x'] + p_args,
                        cwd=wdir)
            return
        cmd = 'xterm'
        if is_program_installed(cmd):
            run_program(cmd, ['-e'] + p_args + [wdir])
            return		
        # TODO: Add a fallback to OSX
    else:
        raise NotImplementedError
    def start(self, wdir=None, args=None, pythonpath=None):
        filename = to_text_string(self.filecombo.currentText())
        if wdir is None:
            wdir = self._last_wdir
            if wdir is None:
                wdir = osp.basename(filename)
        print(filename)
        if os.name == 'nt':
            # On Windows, one has to replace backslashes by slashes to avoid
            # confusion with escape characters (otherwise, for example, '\t'
            # will be interpreted as a tabulation):
            filename = osp.normpath(filename).replace(os.sep, '/')
        if args is None:
            args = self._last_args
            if args is None:
                args = []
        if pythonpath is None:
            pythonpath = self._last_pythonpath
        self._last_wdir = wdir
        self._last_args = args
        self._last_pythonpath = pythonpath

        self.datelabel.setText(_('Running tests, please wait...'))

        self.process = QProcess(self)
        self.process.setProcessChannelMode(QProcess.SeparateChannels)
        self.process.setWorkingDirectory(filename)
        self.process.readyReadStandardOutput.connect(self.read_output)
        self.process.readyReadStandardError.connect(
            lambda: self.read_output(error=True))
        self.process.finished.connect(self.finished)
        self.stop_button.clicked.connect(self.process.kill)

        if pythonpath is not None:
            env = [to_text_string(_pth)
                   for _pth in self.process.systemEnvironment()]
            baseshell.add_pathlist_to_PYTHONPATH(env, pythonpath)
            self.process.setEnvironment(env)

        self.output = ''
        self.error_output = ''

        executable = "py.test"
        p_args = ['--junit-xml', self.DATAPATH]

#        executable = "nosetests"
#        p_args = ['--with-xunit', "--xunit-file=%s" % self.DATAPATH]

        if args:
            p_args.extend(programs.shell_split(args))
        self.process.start(executable, p_args)

        running = self.process.waitForStarted()
        self.set_running_state(running)
        if not running:
            QMessageBox.critical(self, _("Error"),
                                 _("Process failed to start"))
Exemple #20
0
 def is_valid(self):
     wdir = to_text_string(self.wd_edit.text())
     if not self.fixed_dir_radio.isChecked() or osp.isdir(wdir):
         return True
     else:
         QMessageBox.critical(self, _("Run configuration"),
                              _("The following working directory is "
                                "not valid:<br><b>%s</b>") % wdir)
         return False
Exemple #21
0
 def convert_notebook(self, fname):
     """Convert an IPython notebook to a Python script in editor"""
     try: 
         script = nbexporter().from_filename(fname)[0]
     except Exception as e:
         QMessageBox.critical(self, _('Conversion error'), 
                              _("It was not possible to convert this "
                              "notebook. The error is:\n\n") + \
                              to_text_string(e))
         return
     self.parent_widget.sig_new_file.emit(script)
Exemple #22
0
    def start(self):

        if self.p_gui is None:
            self.p_gui = subprocess.Popen(['python', 'scnr2.py'])
            #self.p = subprocess.Popen(['python'],shell=True)
        else:
            if not self.p_gui.poll() is  None:
                self.p_gui = subprocess.Popen(['python', 'scnr2.py'])
                #self.p = subprocess.Popen(['python'], shell=True)
            else:
                QMessageBox.critical(self, 'Error', "Graphical User Interface seems to be already running.\nIf the Problem persists please restart the computer.", QMessageBox.Ok)
Exemple #23
0
 def _on_sphinx_thread_error_msg(self, error_msg):
     """ Display error message on Sphinx rich text failure"""
     self._sphinx_thread.wait()
     self.plain_text_action.setChecked(True)
     sphinx_ver = programs.get_module_version('sphinx')
     QMessageBox.critical(self,
                 _('Help'),
                 _("The following error occured when calling "
                   "<b>Sphinx %s</b>. <br>Incompatible Sphinx "
                   "version or doc string decoding failed."
                   "<br><br>Error message:<br>%s"
                   ) % (sphinx_ver, error_msg))
Exemple #24
0
    def create_process(self):
        self.shell.clear()

        self.process = QProcess(self)
        self.process.setProcessChannelMode(QProcess.MergedChannels)

        # PYTHONPATH (in case we use Python in this terminal, e.g. py2exe)
        env = [to_text_string(_path)
               for _path in self.process.systemEnvironment()]

        processEnvironment = QProcessEnvironment()
        for envItem in env:
            envName, separator, envValue = envItem.partition('=')
            processEnvironment.insert(envName, envValue)

        add_pathlist_to_PYTHONPATH(env, self.path)
        self.process.setProcessEnvironment(processEnvironment)                   

        
        # Working directory
        if self.wdir is not None:
            self.process.setWorkingDirectory(self.wdir)
            
        # Shell arguments
        if os.name == 'nt':
            p_args = ['/Q']
        else:
            p_args = ['-i']
            
        if self.arguments:
            p_args.extend( shell_split(self.arguments) )
        
        self.process.readyReadStandardOutput.connect(self.write_output)
        self.process.finished.connect(self.finished)
        self.kill_button.clicked.connect(self.process.kill)
        
        if os.name == 'nt':
            self.process.start('cmd.exe', p_args)
        else:
            # Using bash:
            self.process.start('bash', p_args)
            self.send_to_process('PS1="\\u@\\h:\\w> "\n')
            
        running = self.process.waitForStarted()
        self.set_running_state(running)
        if not running:
            QMessageBox.critical(self, _("Error"),
                                 _("Process failed to start"))
        else:
            self.shell.setFocus()
            self.started.emit()
            
        return self.process
Exemple #25
0
 def vcs_command(self, fnames, action):
     """VCS action (commit, browse)"""
     try:
         for path in sorted(fnames):
             vcs.run_vcs_tool(path, action)
     except vcs.ActionToolNotFound as error:
         msg = _("For %s support, please install one of the<br/> "
                 "following tools:<br/><br/>  %s")\
                     % (error.vcsname, ', '.join(error.tools))
         QMessageBox.critical(self, _("Error"),
             _("""<b>Unable to find external program.</b><br><br>%s""")
                 % to_text_string(msg))
Exemple #26
0
 def is_valid(self):
     """Return True if all widget contents are valid"""
     for lineedit in self.lineedits:
         if lineedit in self.validate_data and lineedit.isEnabled():
             validator, invalid_msg = self.validate_data[lineedit]
             text = to_text_string(lineedit.text())
             if not validator(text):
                 QMessageBox.critical(self, self.get_name(),
                                  "%s:<br><b>%s</b>" % (invalid_msg, text),
                                  QMessageBox.Ok)
                 return False
     return True
Exemple #27
0
 def change_format(self):
     """Change display format"""
     format, valid = QInputDialog.getText(
         self, _("Format"), _("Float formatting"), QLineEdit.Normal, self.model.get_format()
     )
     if valid:
         format = str(format)
         try:
             format % 1.1
         except:
             QMessageBox.critical(self, _("Error"), _("Format (%s) is incorrect") % format)
             return
         self.model.set_format(format)
    def convert_data_units(self):
        """
        Calls CubeVizUnit.change_units to finalize
        conversions. Updates plots with new units.
        :return:
        """
        success = self.current_layout.change_units()
        if not success:
            info = QMessageBox.critical(self, "Error", "Conversion failed.")
            return

        new_unit = self.current_layout.new_unit
        self.current_unit.unit = new_unit
        self.current_unit.unit_string = str(new_unit)

        component_id = self.component_combo.currentData()
        component = component_id.parent.get_component(component_id)

        old_array = component._data.copy()
        old_array.flags.writeable = True

        wavelengths = self.controller.construct_3d_wavelengths(old_array)

        new_array = self.current_unit.convert_value(old_array, wave=wavelengths)

        component._data = new_array

        self.current_unit = self.controller.add_component_unit(component_id, new_unit)
        component.units = self.current_unit.unit_string
        msg = FluxUnitsUpdateMessage(self, self.current_unit, component_id)
        self._hub.broadcast(msg)
        self.close()
Exemple #29
0
    def add_data(self, data):
        """

        Parameters
        ----------
        data

        Returns
        -------

        """
        if not glue_data_has_spectral_axis(data):
            QMessageBox.critical(self, "Error", "Data is not a 1D spectrum",
                                 buttons=QMessageBox.Ok)
            return False
        return super(SpecvizDataViewer, self).add_data(data)
Exemple #30
0
    def add_subset(self, subset):
        """

        Parameters
        ----------
        subset

        Returns
        -------

        """
        if not glue_data_has_spectral_axis(subset):
            QMessageBox.critical(self, "Error", "Subset is not a 1D spectrum",
                                 buttons=QMessageBox.Ok)
            return False
        return super(SpecvizDataViewer, self).add_subset(subset)
Exemple #31
0
 def plot(self):
     if self.param_model is None:
         QMessageBox.critical(self, "Error plotting",
                              "Error, you don't have any data loaded")
     else:
         if self._CIchanged:
             self.on_CIvalues_editingFinished()
         fct = self.fct
         res = self.res
         model = self.param_model
         xdata = model.valuesX
         ydata = model.valuesY
         p0 = model.parm_values
         parm_names = model.parm_names
         eval_points = None
         fixed = tuple(find(array(model.fixed) > 0))
         if self.interpolate.isChecked():
             if self.autoScale.isChecked():
                 xmin = xdata.min()
                 xmax = xdata.max()
             else:
                 xmin = float(self.xMin.text())
                 xmax = float(self.xMax.text())
             eval_points = arange(xmin, xmax, (xmax - xmin) / 1024)
         CImethod = None
         CImethodName = user_text(self.CImethod.currentText())
         if CImethodName == u"Bootstrapping":
             CImethod = bootstrap.bootstrap_regression
         elif CImethodName == u"Residual resampling":
             CImethod = bootstrap.bootstrap_residuals
         outfile = self.output
         CI = ()
         result = None
         loc = str(self.legendLocation.currentText())
         fct_desc = "$%s$" % (fct.description, )
         try:
             cf_kwrds = dict(residuals=res.__call__,
                             p0=p0,
                             function=fct,
                             maxfev=10000,
                             fix_params=fixed,
                             Dfun=fct.Dfun,
                             Dres=res.Dfun,
                             col_deriv=True)
             if self.CI is not None:
                 CI = self.CI[1]
                 bs = bootstrap.bootstrap(CurveFitting,
                                          xdata,
                                          ydata,
                                          CI,
                                          shuffle_method=CImethod,
                                          shuffle_kwrds={
                                              "add_residual": res.invert,
                                              "fit": CurveFitting
                                          },
                                          extra_attrs=('popt', ),
                                          eval_points=eval_points,
                                          fit_kwrds=cf_kwrds)
                 result = plot_fit.fit_evaluation(bs.y_fit,
                                                  xdata,
                                                  ydata,
                                                  eval_points=eval_points,
                                                  xname=self.fieldX,
                                                  yname=self.fieldY,
                                                  fct_desc=fct_desc,
                                                  param_names=parm_names,
                                                  res_name=res.name,
                                                  CI=CI,
                                                  CIresults=bs)
             else:
                 fit = CurveFitting(xdata, ydata, **cf_kwrds)
                 fit.fit()
                 result = plot_fit.fit_evaluation(fit,
                                                  xdata,
                                                  ydata,
                                                  eval_points=eval_points,
                                                  xname=self.fieldX,
                                                  yname=self.fieldY,
                                                  fct_desc=fct_desc,
                                                  param_names=parm_names,
                                                  res_name=res.name)
         except Exception as ex:
             traceback.print_exc()
             QMessageBox.critical(
                 self, "Error during Parameters Estimation",
                 "{1} exception: {2}".format(type(ex).__name__, ex.message))
             return
         plot_fit.plot1d(result, loc=loc)
         if self.writeResult and outfile:
             #print("output to file '%s'" % (outfile,))
             plot_fit.write1d(outfile, result, res.description,
                              CImethodName)
Exemple #32
0
    def draw_contour(self, draw=True):
        self._delete_contour()

        if len(self.visible_layers()) == 0:
            return

        if self.is_contour_preview_active:
            settings = self.contour_preview_settings
        else:
            settings = self.contour_settings

        arr = self.get_contour_array()

        vmax = np.nanmax(arr)
        if settings.vmax is not None:
            vmax = settings.vmax

        vmin = np.nanmin(arr)
        if settings.vmin is not None:
            vmin = settings.vmin

        if settings.spacing is None:
            spacing = 1
            if vmax != vmin:
                spacing = (vmax - vmin) / CONTOUR_DEFAULT_NUMBER_OF_LEVELS
        else:
            spacing = settings.spacing

        levels = np.arange(vmin, vmax, spacing)
        levels = np.append(levels, vmax)

        if levels.size > CONTOUR_MAX_NUMBER_OF_LEVELS:
            message = "The current contour spacing is too small and " \
                      "results in too many levels. Contour spacing " \
                      "settings have been reset to auto."
            info = QMessageBox.critical(self, "Error", message)

            settings.spacing = None
            settings.data_spacing = spacing
            if settings.dialog is not None:
                settings.dialog.custom_spacing_checkBox.setChecked(False)
            spacing = (vmax - vmin) / CONTOUR_DEFAULT_NUMBER_OF_LEVELS
            levels = np.arange(vmin, vmax, spacing)
            levels = np.append(levels, vmax)

        self.contour = self.axes.contour(arr,
                                         levels=levels,
                                         **settings.options)

        if settings.add_contour_label:
            if abs(levels).max() > 1000 \
                    or 0.0 < abs(levels).min() < 0.001 \
                    or 0.0 < abs(levels).max() < 0.001:
                self.axes.clabel(self.contour,
                                 fmt='%.2E',
                                 fontsize=settings.font_size)
            else:
                self.axes.clabel(self.contour, fontsize=settings.font_size)

        settings.data_max = arr.max()
        settings.data_min = arr.min()
        settings.data_spacing = spacing
        if settings.dialog is not None:
            settings.update_dialog()
        if draw:
            self.axes.figure.canvas.draw()
Exemple #33
0
    def create_process(self):
        self.shell.clear()

        self.process = QProcess(self)
        if self.merge_output_channels:
            self.process.setProcessChannelMode(QProcess.MergedChannels)
        else:
            self.process.setProcessChannelMode(QProcess.SeparateChannels)
        self.shell.wait_for_ready_read.connect(
            lambda: self.process.waitForReadyRead(250))

        # Working directory
        if self.wdir is not None:
            self.process.setWorkingDirectory(self.wdir)

        #-------------------------Python specific------------------------------
        # Python arguments
        p_args = ['-u']
        if DEBUG >= 3:
            p_args += ['-v']
        p_args += get_python_args(self.fname, self.python_args,
                                  self.interact_action.isChecked(),
                                  self.debug_action.isChecked(),
                                  self.arguments)

        env = [
            to_text_string(_path)
            for _path in self.process.systemEnvironment()
        ]
        if self.pythonstartup:
            env.append('PYTHONSTARTUP=%s' % self.pythonstartup)

        #-------------------------Python specific-------------------------------
        # Post mortem debugging
        if self.post_mortem_action.isChecked():
            env.append('SPYDER_EXCEPTHOOK=True')

        # Set standard input/output encoding for Python consoles
        # (IPython handles it on its own)
        # See http://stackoverflow.com/q/26312400/438386, specifically
        # the comments of Martijn Pieters
        if not self.is_ipykernel:
            env.append('PYTHONIOENCODING=UTF-8')

        # Monitor
        if self.monitor_enabled:
            env.append('SPYDER_SHELL_ID=%s' % id(self))
            env.append('SPYDER_AR_TIMEOUT=%d' % self.autorefresh_timeout)
            env.append('SPYDER_AR_STATE=%r' % self.autorefresh_state)
            from spyder.widgets.externalshell import introspection
            introspection_server = introspection.start_introspection_server()
            introspection_server.register(self)
            notification_server = introspection.start_notification_server()
            self.notification_thread = notification_server.register(self)
            self.notification_thread.sig_pdb.connect(
                lambda fname, lineno: self.sig_pdb.emit(fname, lineno))
            self.notification_thread.new_ipython_kernel.connect(
                lambda args: self.create_ipython_client.emit(args))
            self.notification_thread.open_file.connect(
                lambda fname, lineno: self.open_file.emit(fname, lineno))
            if self.namespacebrowser is not None:
                self.configure_namespacebrowser()
            env.append('SPYDER_I_PORT=%d' % introspection_server.port)
            env.append('SPYDER_N_PORT=%d' % notification_server.port)

        # External modules options
        if not self.is_ipykernel:
            env.append('ETS_TOOLKIT=%s' % self.ets_backend)
        if self.mpl_backend is not None:
            backends = {0: 'Automatic', 1: 'None', 2: 'TkAgg'}
            env.append('SPY_MPL_BACKEND=%s' % backends[self.mpl_backend])
        if self.qt_api and not self.is_ipykernel:
            env.append('QT_API=%s' % self.qt_api)
        env.append('COLORIZE_SYS_STDERR=%s' % self.colorize_sys_stderr)
        #        # Socket-based alternative (see input hook in sitecustomize.py):
        #        if self.install_qt_inputhook:
        #            from PyQt4.QtNetwork import QLocalServer
        #            self.local_server = QLocalServer()
        #            self.local_server.listen(str(id(self)))

        # User Module Deleter
        if self.is_interpreter:
            env.append('UMR_ENABLED=%r' % self.umr_enabled)
            env.append('UMR_NAMELIST=%s' % ','.join(self.umr_namelist))
            env.append('UMR_VERBOSE=%r' % self.umr_verbose)
            env.append('MATPLOTLIB_ION=True')
        else:
            if self.interact:
                env.append('MATPLOTLIB_ION=True')
            else:
                env.append('MATPLOTLIB_ION=False')

        # IPython kernel
        env.append('IPYTHON_KERNEL=%r' % self.is_ipykernel)

        # External interpreter
        env.append('EXTERNAL_INTERPRETER=%r' % self.external_interpreter)

        # Add sitecustomize path to path list
        pathlist = []
        scpath = osp.dirname(osp.abspath(__file__))
        pathlist.append(scpath)

        # Adding Spyder path
        pathlist += self.path

        # Adding path list to PYTHONPATH environment variable
        add_pathlist_to_PYTHONPATH(env, pathlist)

        #-------------------------Python specific------------------------------

        self.process.readyReadStandardOutput.connect(self.write_output)
        self.process.readyReadStandardError.connect(self.write_error)
        self.process.finished.connect(
            lambda ec, es=QProcess.ExitStatus: self.finished(ec, es))
        self.sig_finished.connect(self.dialog_manager.close_all)
        self.terminate_button.clicked.connect(self.process.terminate)
        self.kill_button.clicked.connect(self.process.kill)

        #-------------------------Python specific------------------------------
        # Fixes for our Mac app:
        # 1. PYTHONPATH and PYTHONHOME are set while bootstrapping the app,
        #    but their values are messing sys.path for external interpreters
        #    (e.g. EPD) so we need to remove them from the environment.
        # 2. Set PYTHONPATH again but without grabbing entries defined in the
        #    environment (Fixes Issue 1321)
        # 3. Remove PYTHONOPTIMIZE from env so that we can have assert
        #    statements working with our interpreters (See Issue 1281)
        if running_in_mac_app():
            if MAC_APP_NAME not in self.pythonexecutable:
                env = [p for p in env if not (p.startswith('PYTHONPATH') or \
                                              p.startswith('PYTHONHOME'))] # 1.

                add_pathlist_to_PYTHONPATH(env, pathlist, drop_env=True)  # 2.
            env = [p for p in env if not p.startswith('PYTHONOPTIMIZE')]  # 3.

        processEnvironment = QProcessEnvironment()
        for envItem in env:
            envName, separator, envValue = envItem.partition('=')
            processEnvironment.insert(envName, envValue)
        self.process.setProcessEnvironment(processEnvironment)
        self.process.start(self.pythonexecutable, p_args)
        #-------------------------Python specific------------------------------

        running = self.process.waitForStarted(3000)
        self.set_running_state(running)
        if not running:
            if self.is_ipykernel:
                self.ipython_kernel_start_error.emit(
                    _("The kernel failed to start!! That's all we know... "
                      "Please close this console and open a new one."))
            else:
                QMessageBox.critical(self, _("Error"),
                                     _("A Python console failed to start!"))
        else:
            self.shell.setFocus()
            self.started.emit()
        return self.process
Exemple #34
0
    def getMenuAction(self,
                      menu,
                      title='notitle',
                      action_name='noaction',
                      shortcut="",
                      args=[],
                      kwargs={}):
        # ToDo: Clean this up, it is very hacky
        env = {
            'app': QApplication.instance(),
            'win': self,
            'action': actions,
        }

        if action_name is not None:

            if action_name.startswith('settings.'):
                setting_id = action_name[len('settings.'):]
                setting = getSetting(setting_id)

                if setting:
                    if setting.enum_options is not None:
                        submenu = QMenu(parent=self, title=title)

                        group = QActionGroup(self)
                        group.setExclusive(True)
                        group.triggered.connect(
                            lambda a: setting.setValue(a.data()))

                        def update(group, val):
                            for act in group.actions():
                                if act.data() == val:
                                    act.setChecked(True)
                                    break

                        for num, opt in enumerate(setting.enum_options):

                            menu_action = QAction(parent=self, text=opt)
                            menu_action.setCheckable(True)
                            if setting.value == num:
                                menu_action.setChecked(True)

                            menu_action.setData(num)
                            setting.notify(lambda v: update(group, v))

                            menu_action.setActionGroup(group)
                            submenu.addAction(menu_action)
                        menu.addMenu(submenu)

                    elif setting.value_type == bool:
                        # works for bool settings
                        menu_action = QAction(parent=self, text=title)
                        menu_action.setCheckable(True)
                        menu_action.triggered.connect(setting.setValue)
                        menu_action.setShortcut(shortcut)
                        setting.notify(menu_action.setChecked)
                        menu.addAction(menu_action)

                    return

            try:
                menu_action = QAction(parent=self, text=title)

                mod, action = action_name.split('.', 1)
                method = getattr(env.get(mod, self), action)
                if menu_action.isCheckable():
                    menu_action.triggered.connect(method)
                else:
                    menu_action.triggered.connect(
                        lambda checked: method(*args, **kwargs))

                menu_action.setShortcut(shortcut)
                menu.addAction(menu_action)
                return
            except:
                pass

            try:
                menu_action = QAction(parent=self, text=title)
                actions.bindWidget(menu_action, action_name)
                menu_action.setShortcut(shortcut)
                menu.addAction(menu_action)
                return
            except actions.InvalidAction:
                LOG.exception('Error binding menu action %s', action_name)

        menu_action = QAction(parent=self, text=title)
        msg = "The <b>{}</b> action specified for the " \
              "<b>{}</b> menu item could not be triggered. " \
              "Check the YAML config file for errors." \
              .format(action_name or '', title.replace('&', ''))
        menu_action.triggered.connect(
            lambda: QMessageBox.critical(self, "Menu Action Error!", msg))
        menu.addAction(menu_action)
Exemple #35
0
    def open_project(self, path=None, project=None, restart_consoles=True,
                     save_previous_files=True, workdir=None):
        """Open the project located in `path`."""
        self.unmaximize()
        if path is None:
            basedir = get_home_dir()
            path = getexistingdirectory(parent=self,
                                        caption=_("Open project"),
                                        basedir=basedir)
            path = encoding.to_unicode_from_fs(path)
            if not self.is_valid_project(path):
                if path:
                    QMessageBox.critical(
                        self,
                        _('Error'),
                        _("<b>%s</b> is not a Spyder project!") % path,
                    )
                return
        else:
            path = encoding.to_unicode_from_fs(path)
        if project is None:
            project_type_class = self._load_project_type_class(path)
            project = project_type_class(
                root_path=path,
                parent_plugin=project_type_class._PARENT_PLUGIN,
            )

        # A project was not open before
        if self.current_active_project is None:
            if save_previous_files and self.main.editor is not None:
                self.main.editor.save_open_files()

            if self.main.editor is not None:
                self.main.editor.set_option('last_working_dir',
                                            getcwd_or_home())

            if self.get_option('visible_if_project_open'):
                self.show_explorer()
        else:
            # We are switching projects
            if self.main.editor is not None:
                self.set_project_filenames(
                    self.main.editor.get_open_filenames())

            # TODO: Don't emit sig_project_closed when we support
            # multiple workspaces.
            self.sig_project_closed.emit(
                self.current_active_project.root_path)

        self.current_active_project = project
        self.latest_project = project
        self.add_to_recent(path)

        self.set_option('current_project_path', self.get_active_project_path())

        self.setup_menu_actions()
        if workdir and osp.isdir(workdir):
            self.sig_project_loaded.emit(workdir)
        else:
            self.sig_project_loaded.emit(path)
        self.sig_pythonpath_changed.emit()
        self.watcher.start(path)

        if restart_consoles:
            self.restart_consoles()

        open_successfully, message = project.open_project()
        if not open_successfully:
            QMessageBox.warning(self, "Project open", message)
Exemple #36
0
 def _export_error(self, message):
     QMessageBox.critical(self,
                          'Export Error', message,
                          QMessageBox.Close)
Exemple #37
0
    def dropEvent(self, event):
        """Reimplement Qt method"""
        event.ignore()
        action = event.dropAction()
        if action not in (Qt.MoveAction, Qt.CopyAction):
            return

        # QTreeView must not remove the source items even in MoveAction mode:
        # event.setDropAction(Qt.CopyAction)

        dst = self.get_filename(self.indexAt(event.pos()))
        yes_to_all, no_to_all = None, None
        src_list = [
            to_text_string(url.toString()) for url in event.mimeData().urls()
        ]
        if len(src_list) > 1:
            buttons = QMessageBox.Yes|QMessageBox.YesToAll| \
                      QMessageBox.No|QMessageBox.NoToAll|QMessageBox.Cancel
        else:
            buttons = QMessageBox.Yes | QMessageBox.No
        for src in src_list:
            if src == dst:
                continue
            dst_fname = osp.join(dst, osp.basename(src))
            if osp.exists(dst_fname):
                if yes_to_all is not None or no_to_all is not None:
                    if no_to_all:
                        continue
                elif osp.isfile(dst_fname):
                    answer = QMessageBox.warning(
                        self, _('Project explorer'),
                        _('File <b>%s</b> already exists.<br>'
                          'Do you want to overwrite it?') % dst_fname, buttons)
                    if answer == QMessageBox.No:
                        continue
                    elif answer == QMessageBox.Cancel:
                        break
                    elif answer == QMessageBox.YesToAll:
                        yes_to_all = True
                    elif answer == QMessageBox.NoToAll:
                        no_to_all = True
                        continue
                else:
                    QMessageBox.critical(
                        self, _('Project explorer'),
                        _('Folder <b>%s</b> already exists.') % dst_fname,
                        QMessageBox.Ok)
                    event.setDropAction(Qt.CopyAction)
                    return
            try:
                if action == Qt.CopyAction:
                    if osp.isfile(src):
                        shutil.copy(src, dst)
                    else:
                        shutil.copytree(src, dst)
                else:
                    if osp.isfile(src):
                        misc.move_file(src, dst)
                    else:
                        shutil.move(src, dst)
                    self.parent_widget.removed.emit(src)
            except EnvironmentError as error:
                if action == Qt.CopyAction:
                    action_str = _('copy')
                else:
                    action_str = _('move')
                QMessageBox.critical(
                    self, _("Project Explorer"),
                    _("<b>Unable to %s <i>%s</i></b>"
                      "<br><br>Error message:<br>%s") %
                    (action_str, src, to_text_string(error)))
Exemple #38
0
def run_python_script_in_terminal(fname,
                                  wdir,
                                  args,
                                  interact,
                                  debug,
                                  python_args,
                                  executable=None):
    """
    Run Python script in an external system terminal.

    :str wdir: working directory, may be empty.
    """
    if executable is None:
        executable = get_python_executable()

    # If fname or python_exe contains spaces, it can't be ran on Windows, so we
    # have to enclose them in quotes. Also wdir can come with / as os.sep, so
    # we need to take care of it.
    if os.name == 'nt':
        fname = '"' + fname + '"'
        wdir = wdir.replace('/', '\\')
        executable = '"' + executable + '"'

    p_args = [executable]
    p_args += get_python_args(fname, python_args, interact, debug, args)

    if os.name == 'nt':
        cmd = 'start cmd.exe /K "'
        if wdir:
            cmd += 'cd ' + wdir + ' && '
        cmd += ' '.join(p_args) + '"' + ' ^&^& exit'
        # Command line and cwd have to be converted to the filesystem
        # encoding before passing them to subprocess, but only for
        # Python 2.
        # See https://bugs.python.org/issue1759845#msg74142 and
        # spyder-ide/spyder#1856.
        if PY2:
            cmd = encoding.to_fs_from_unicode(cmd)
            wdir = encoding.to_fs_from_unicode(wdir)
        try:
            if wdir:
                run_shell_command(cmd, cwd=wdir)
            else:
                run_shell_command(cmd)
        except WindowsError:
            from qtpy.QtWidgets import QMessageBox
            from spyder.config.base import _
            QMessageBox.critical(
                None, _('Run'),
                _("It was not possible to run this file in "
                  "an external terminal"), QMessageBox.Ok)
    elif sys.platform.startswith('linux'):
        programs = [
            {
                'cmd': 'gnome-terminal',
                'wdir-option': '--working-directory',
                'execute-option': '-x'
            },
            {
                'cmd': 'konsole',
                'wdir-option': '--workdir',
                'execute-option': '-e'
            },
            {
                'cmd': 'xfce4-terminal',
                'wdir-option': '--working-directory',
                'execute-option': '-x'
            },
            {
                'cmd': 'xterm',
                'wdir-option': None,
                'execute-option': '-e'
            },
        ]
        for program in programs:
            if is_program_installed(program['cmd']):
                arglist = []
                if program['wdir-option'] and wdir:
                    arglist += [program['wdir-option'], wdir]
                arglist.append(program['execute-option'])
                arglist += p_args
                if wdir:
                    run_program(program['cmd'], arglist, cwd=wdir)
                else:
                    run_program(program['cmd'], arglist)
                return
    elif sys.platform == 'darwin':
        f = tempfile.NamedTemporaryFile('wt',
                                        prefix='run_spyder_',
                                        suffix='.sh',
                                        dir=get_temp_dir(),
                                        delete=False)
        if wdir:
            f.write('cd {}\n'.format(wdir))
        f.write(' '.join(p_args))
        f.close()
        os.chmod(f.name, 0o777)

        def run_terminal_thread():
            proc = run_shell_command('open -a Terminal.app ' + f.name)
            # Prevent race condition
            time.sleep(3)
            proc.wait()
            os.remove(f.name)

        thread = threading.Thread(target=run_terminal_thread)
        thread.start()
    else:
        raise NotImplementedError
Exemple #39
0
def critical(parent, msg):
    QMessageBox.critical(parent, QCoreApplication.applicationName(), msg)
Exemple #40
0
    def import_data(self, filenames=None):
        """Import data from text file"""
        title = _("Import data")
        if filenames is None:
            if self.filename is None:
                basedir = getcwd()
            else:
                basedir = osp.dirname(self.filename)
            filenames, _selfilter = getopenfilenames(self, title, basedir,
                                                     iofunctions.load_filters)
            if not filenames:
                return
        elif is_text_string(filenames):
            filenames = [filenames]

        for filename in filenames:
            self.filename = to_text_string(filename)
            ext = osp.splitext(self.filename)[1].lower()

            if ext not in iofunctions.load_funcs:
                buttons = QMessageBox.Yes | QMessageBox.Cancel
                answer = QMessageBox.question(
                    self, title,
                    _("<b>Unsupported file extension '%s'</b><br><br>"
                      "Would you like to import it anyway "
                      "(by selecting a known file format)?") % ext, buttons)
                if answer == QMessageBox.Cancel:
                    return
                formats = list(iofunctions.load_extensions.keys())
                item, ok = QInputDialog.getItem(self, title,
                                                _('Open file as:'), formats, 0,
                                                False)
                if ok:
                    ext = iofunctions.load_extensions[to_text_string(item)]
                else:
                    return

            load_func = iofunctions.load_funcs[ext]

            # 'import_wizard' (self.setup_io)
            if is_text_string(load_func):
                # Import data with import wizard
                error_message = None
                try:
                    text, _encoding = encoding.read(self.filename)
                    base_name = osp.basename(self.filename)
                    editor = ImportWizard(
                        self,
                        text,
                        title=base_name,
                        varname=fix_reference_name(base_name))
                    if editor.exec_():
                        var_name, clip_data = editor.get_data()
                        self.set_value(var_name, clip_data)
                except Exception as error:
                    error_message = str(error)
            else:
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                QApplication.processEvents()
                if self.is_ipyclient:
                    error_message = self.shellwidget.load_data(
                        self.filename, ext)
                    self.shellwidget._kernel_reply = None
                else:
                    error_message = monitor_load_globals(
                        self._get_sock(), self.filename, ext)
                QApplication.restoreOverrideCursor()
                QApplication.processEvents()

            if error_message is not None:
                QMessageBox.critical(
                    self, title,
                    _("<b>Unable to load '%s'</b>"
                      "<br><br>Error message:<br>%s") %
                    (self.filename, error_message))
            self.refresh_table()
Exemple #41
0
def run_python_script_in_terminal(fname,
                                  wdir,
                                  args,
                                  interact,
                                  debug,
                                  python_args,
                                  executable=None):
    """
    Run Python script in an external system terminal.

    :str wdir: working directory, may be empty.
    """
    if executable is None:
        executable = get_python_executable()

    # If fname or python_exe contains spaces, it can't be ran on Windows, so we
    # have to enclose them in quotes. Also wdir can come with / as os.sep, so
    # we need to take care of it.
    if os.name == 'nt':
        fname = '"' + fname + '"'
        wdir = wdir.replace('/', '\\')
        executable = '"' + executable + '"'

    p_args = [executable]
    p_args += get_python_args(fname, python_args, interact, debug, args)

    if os.name == 'nt':
        cmd = 'start cmd.exe /c "cd %s && ' % wdir + ' '.join(p_args) + '"'
        # Command line and cwd have to be converted to the filesystem
        # encoding before passing them to subprocess, but only for
        # Python 2.
        # See http://bugs.python.org/issue1759845#msg74142 and Issue 1856
        if PY2:
            cmd = encoding.to_fs_from_unicode(cmd)
            wdir = encoding.to_fs_from_unicode(wdir)
        try:
            run_shell_command(cmd, cwd=wdir)
        except WindowsError:
            from qtpy.QtWidgets import QMessageBox
            from spyder.config.base import _
            QMessageBox.critical(
                None, _('Run'),
                _("It was not possible to run this file in "
                  "an external terminal"), QMessageBox.Ok)
    elif os.name == 'posix':
        programs = [
            {
                'cmd': 'gnome-terminal',
                'wdir-option': '--working-directory',
                'execute-option': '-x'
            },
            {
                'cmd': 'konsole',
                'wdir-option': '--workdir',
                'execute-option': '-e'
            },
            {
                'cmd': 'xfce4-terminal',
                'wdir-option': '--working-directory',
                'execute-option': '-x'
            },
            {
                'cmd': 'xterm',
                'wdir-option': None,
                'execute-option': '-e'
            },
        ]
        for program in programs:
            if is_program_installed(program['cmd']):
                arglist = []
                if program['wdir-option'] and wdir:
                    arglist += [program['wdir-option'], wdir]
                arglist.append(program['execute-option'])
                arglist += p_args
                if wdir:
                    run_program(program['cmd'], arglist, cwd=wdir)
                else:
                    run_program(program['cmd'], arglist)
                return
        # TODO: Add a fallback to OSX
    else:
        raise NotImplementedError
 def under_process(self):
     QMessageBox.critical(self, _('Under Progress'),
                          "This step is under process.")
Exemple #43
0
 def conversionButtonClicked(self):
     try:
         self._conversion()
     except Exception as ex:
         QMessageBox.critical(self, "Error Inputs", str(ex), QMessageBox.Ok)
         return
Exemple #44
0
    def createEditor(self, parent, option, index):
        """Overriding method createEditor"""
        if self.show_warning(index):
            answer = QMessageBox.warning(
                self.parent(), _("Warning"),
                _("Opening this variable can be slow\n\n"
                  "Do you want to continue anyway?"),
                QMessageBox.Yes | QMessageBox.No)
            if answer == QMessageBox.No:
                return None
        try:
            value = self.get_value(index)
            try:
                self.old_obj = value.copy()
            except AttributeError:
                self.old_obj = copy.deepcopy(value)
            if value is None:
                return None
        except Exception as msg:
            QMessageBox.critical(
                self.parent(), _("Error"),
                _("Spyder was unable to retrieve the value of "
                  "this variable from the console.<br><br>"
                  "The error message was:<br>"
                  "<i>%s</i>") % to_text_string(msg))
            return
        self.current_index = index

        key = index.model().get_key(index).obj_name
        readonly = (isinstance(value, (tuple, set)) or self.parent().readonly
                    or not is_known_type(value))

        # CollectionsEditor for a list, tuple, dict, etc.
        if isinstance(value, (list, set, tuple, dict)):
            from spyder.widgets.collectionseditor import CollectionsEditor
            editor = CollectionsEditor(parent=parent)
            editor.setup(value,
                         key,
                         icon=self.parent().windowIcon(),
                         readonly=readonly)
            self.create_dialog(
                editor,
                dict(model=index.model(),
                     editor=editor,
                     key=key,
                     readonly=readonly))
            return None
        # ArrayEditor for a Numpy array
        elif (isinstance(value, (ndarray, MaskedArray))
              and ndarray is not FakeObject):
            editor = ArrayEditor(parent=parent)
            if not editor.setup_and_check(value, title=key, readonly=readonly):
                return
            self.create_dialog(
                editor,
                dict(model=index.model(),
                     editor=editor,
                     key=key,
                     readonly=readonly))
            return None
        # ArrayEditor for an images
        elif (isinstance(value, Image) and ndarray is not FakeObject
              and Image is not FakeObject):
            arr = array(value)
            editor = ArrayEditor(parent=parent)
            if not editor.setup_and_check(arr, title=key, readonly=readonly):
                return
            conv_func = lambda arr: Image.fromarray(arr, mode=value.mode)
            self.create_dialog(
                editor,
                dict(model=index.model(),
                     editor=editor,
                     key=key,
                     readonly=readonly,
                     conv=conv_func))
            return None
        # DataFrameEditor for a pandas dataframe, series or index
        elif (isinstance(value, (DataFrame, Index, Series))
              and DataFrame is not FakeObject):
            editor = DataFrameEditor(parent=parent)
            if not editor.setup_and_check(value, title=key):
                return
            editor.dataModel.set_format(index.model().dataframe_format)
            editor.sig_option_changed.connect(self.change_option)
            self.create_dialog(
                editor,
                dict(model=index.model(),
                     editor=editor,
                     key=key,
                     readonly=readonly))
            return None
        # QDateEdit and QDateTimeEdit for a dates or datetime respectively
        elif isinstance(value, datetime.date):
            if readonly:
                return None
            else:
                if isinstance(value, datetime.datetime):
                    editor = QDateTimeEdit(value, parent=parent)
                else:
                    editor = QDateEdit(value, parent=parent)
                editor.setCalendarPopup(True)
                editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA))
                return editor
        # TextEditor for a long string
        elif is_text_string(value) and len(value) > 40:
            te = TextEditor(None, parent=parent)
            if te.setup_and_check(value):
                editor = TextEditor(value,
                                    key,
                                    readonly=readonly,
                                    parent=parent)
                self.create_dialog(
                    editor,
                    dict(model=index.model(),
                         editor=editor,
                         key=key,
                         readonly=readonly))
            return None
        # QLineEdit for an individual value (int, float, short string, etc)
        elif is_editable_type(value):
            if readonly:
                return None
            else:
                editor = QLineEdit(parent=parent)
                editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA))
                editor.setAlignment(Qt.AlignLeft)
                # This is making Spyder crash because the QLineEdit that it's
                # been modified is removed and a new one is created after
                # evaluation. So the object on which this method is trying to
                # act doesn't exist anymore.
                # editor.returnPressed.connect(self.commitAndCloseEditor)
                return editor
        # An arbitrary Python object.
        # Since we are already in the Object Explorer no editor is needed
        else:
            return None
Exemple #45
0
    def createEditor(self, parent, option, index, object_explorer=False):
        """Overriding method createEditor"""
        val_type = index.sibling(index.row(), 1).data()
        self.sig_open_editor.emit()
        if index.column() < 3:
            return None
        if self.show_warning(index):
            answer = QMessageBox.warning(
                self.parent(), _("Warning"),
                _("Opening this variable can be slow\n\n"
                  "Do you want to continue anyway?"),
                QMessageBox.Yes | QMessageBox.No)
            if answer == QMessageBox.No:
                return None
        try:
            value = self.get_value(index)
            if value is None:
                return None
        except ImportError as msg:
            self.sig_editor_shown.emit()
            module = str(msg).split("'")[1]
            if module in ['pandas', 'numpy']:
                if module == 'numpy':
                    val_type = 'array'
                else:
                    val_type = 'dataframe, series'
                message = _("Spyder is unable to show the {val_type} or object"
                            " you're trying to view because <tt>{module}</tt>"
                            " is not installed. ")
                if running_in_mac_app():
                    message += _("Please consider using the full version of "
                                 "the Spyder MacOS application.<br>")
                else:
                    message += _("Please install this package in your Spyder "
                                 "environment.<br>")
                QMessageBox.critical(
                    self.parent(), _("Error"),
                    message.format(val_type=val_type, module=module))
                return
            else:
                message = _("Spyder is unable to show the variable you're"
                            " trying to view because the module "
                            "<tt>{module}</tt> is not ")
                if running_in_mac_app():
                    message += _("supported in the Spyder MacOS "
                                 "application.<br>")
                else:
                    message += _("found in your Spyder environment. Please "
                                 "install this package in your Spyder "
                                 "environment.<br>")
                QMessageBox.critical(self.parent(), _("Error"),
                                     message.format(module=module))
                return
        except Exception as msg:
            QMessageBox.critical(
                self.parent(), _("Error"),
                _("Spyder was unable to retrieve the value of "
                  "this variable from the console.<br><br>"
                  "The error message was:<br>"
                  "%s") % to_text_string(msg))
            return

        key = index.model().get_key(index)
        readonly = (isinstance(value, (tuple, set)) or self.parent().readonly
                    or not is_known_type(value))
        # CollectionsEditor for a list, tuple, dict, etc.
        if isinstance(value, (list, set, tuple, dict)) and not object_explorer:
            from spyder.widgets.collectionseditor import CollectionsEditor
            editor = CollectionsEditor(parent=parent)
            editor.setup(value,
                         key,
                         icon=self.parent().windowIcon(),
                         readonly=readonly)
            self.create_dialog(
                editor,
                dict(model=index.model(),
                     editor=editor,
                     key=key,
                     readonly=readonly))
            return None
        # ArrayEditor for a Numpy array
        elif (isinstance(value, (ndarray, MaskedArray))
              and ndarray is not FakeObject and not object_explorer):
            editor = ArrayEditor(parent=parent)
            if not editor.setup_and_check(value, title=key, readonly=readonly):
                return
            self.create_dialog(
                editor,
                dict(model=index.model(),
                     editor=editor,
                     key=key,
                     readonly=readonly))
            return None
        # ArrayEditor for an images
        elif (isinstance(value, Image) and ndarray is not FakeObject
              and Image is not FakeObject and not object_explorer):
            arr = array(value)
            editor = ArrayEditor(parent=parent)
            if not editor.setup_and_check(arr, title=key, readonly=readonly):
                return
            conv_func = lambda arr: Image.fromarray(arr, mode=value.mode)
            self.create_dialog(
                editor,
                dict(model=index.model(),
                     editor=editor,
                     key=key,
                     readonly=readonly,
                     conv=conv_func))
            return None
        # DataFrameEditor for a pandas dataframe, series or index
        elif (isinstance(value, (DataFrame, Index, Series))
              and DataFrame is not FakeObject and not object_explorer):
            editor = DataFrameEditor(parent=parent)
            if not editor.setup_and_check(value, title=key):
                return
            editor.dataModel.set_format(index.model().dataframe_format)
            editor.sig_option_changed.connect(self.change_option)
            self.create_dialog(
                editor,
                dict(model=index.model(),
                     editor=editor,
                     key=key,
                     readonly=readonly))
            return None
        # QDateEdit and QDateTimeEdit for a dates or datetime respectively
        elif isinstance(value, datetime.date) and not object_explorer:
            if readonly:
                self.sig_editor_shown.emit()
                return None
            else:
                if isinstance(value, datetime.datetime):
                    editor = QDateTimeEdit(value, parent=parent)
                    # Needed to handle NaT values
                    # See spyder-ide/spyder#8329
                    try:
                        value.time()
                    except ValueError:
                        self.sig_editor_shown.emit()
                        return None
                else:
                    editor = QDateEdit(value, parent=parent)
                editor.setCalendarPopup(True)
                editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA))
                self.sig_editor_shown.emit()
                return editor
        # TextEditor for a long string
        elif is_text_string(value) and len(value) > 40 and not object_explorer:
            te = TextEditor(None, parent=parent)
            if te.setup_and_check(value):
                editor = TextEditor(value,
                                    key,
                                    readonly=readonly,
                                    parent=parent)
                self.create_dialog(
                    editor,
                    dict(model=index.model(),
                         editor=editor,
                         key=key,
                         readonly=readonly))
            return None
        # QLineEdit for an individual value (int, float, short string, etc)
        elif is_editable_type(value) and not object_explorer:
            if readonly:
                self.sig_editor_shown.emit()
                return None
            else:
                editor = QLineEdit(parent=parent)
                editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA))
                editor.setAlignment(Qt.AlignLeft)
                # This is making Spyder crash because the QLineEdit that it's
                # been modified is removed and a new one is created after
                # evaluation. So the object on which this method is trying to
                # act doesn't exist anymore.
                # editor.returnPressed.connect(self.commitAndCloseEditor)
                self.sig_editor_shown.emit()
                return editor
        # ObjectExplorer for an arbitrary Python object
        else:
            show_callable_attributes = index.model().show_callable_attributes
            show_special_attributes = index.model().show_special_attributes
            dataframe_format = index.model().dataframe_format

            if show_callable_attributes is None:
                show_callable_attributes = False
            if show_special_attributes is None:
                show_special_attributes = False

            from spyder.plugins.variableexplorer.widgets.objectexplorer \
                import ObjectExplorer
            editor = ObjectExplorer(
                value,
                name=key,
                parent=parent,
                show_callable_attributes=show_callable_attributes,
                show_special_attributes=show_special_attributes,
                dataframe_format=dataframe_format,
                readonly=readonly)
            editor.sig_option_changed.connect(self.change_option)
            self.create_dialog(
                editor,
                dict(model=index.model(),
                     editor=editor,
                     key=key,
                     readonly=readonly))
            return None
    def move_motor(self):
        """ Move motor to commanded position or by the specified
            number of steps. When an encoder target position is
            provided, a max number of retries can also be specified. """

        try:
            # clear stop flag
            self.stop_sent = False

            # check motor connection
            if not _driver.connected:
                msg = 'Driver nao conectado.'
                _QMessageBox.critical(self, 'Falha', msg, _QMessageBox.Ok)
                return False

            # whether to use encoder position or step as set point
            use_encoder = self.ui.rbt_encoder_position.isChecked()
            # encoder update enable status
            #            enc_update_enabled = (
            #                self.ui.chb_encoder_update_enable.isChecked()
            #            )
            enc_update_enabled = self.encoder_update_enabled

            # check display connection
            if use_encoder and not _display.connected:
                msg = ('Display nao conectado -'
                       ' posicao do encoder invalida.')
                _QMessageBox.critical(self, 'Falha', msg, _QMessageBox.Ok)
                return False
            # check encoder update
            if use_encoder and not enc_update_enabled:
                msg = ('Leitura do Encoder precisa estar habilitada '
                       'se um set point de posicao de encoder esta '
                       'sendo utilizado.')
                _QMessageBox.critical(self, 'Falha', msg, _QMessageBox.Ok)
                return False

            # make sure pneumatic actuator is off
            status = self.pneumatic_off()
            if status == False:
                msg = 'Falha ao tentar recuar atuador pneumatico.'
                _QMessageBox.critical(self, 'Falha', msg, _QMessageBox.Ok)
                return False

            # interval to wait after display read command
            wait_display = _utils.WAIT_DISPLAY
            # interval to wait after move
            wait = _utils.WAIT_MOTION

            # disable move and homing buttons
            self.ui.pbt_move_motor.setEnabled(False)
            self.ui.pbt_homing.setEnabled(False)
            # process gui events
            _QApplication.processEvents()

            # get retry count
            retry_count = int(self.ui.sb_retry_count.value())

            # get motor info
            driver_address = self.advanced_options.motor_driver_address
            motor_resolution = (self.advanced_options.motor_resolution)
            rotation_direction = (
                self.advanced_options.motor_rotation_direction)
            velocity = self.advanced_options.motor_velocity
            acceleration = self.advanced_options.motor_acceleration
            linear_conversion = self.advanced_options.linear_conversion_factor
            tolerance = self.advanced_options.position_tolerance
            move_timeout = self.advanced_options.move_timeout

            # timeout flag
            is_timeout = False

            # motion mode is 'preset' (not continuous)
            mode = 0

            # step set point
            steps = 0

            # only used for encoder set point mode
            target_position = 0
            diff = 0
            previous_encoder_index = 0

            # start time for timeout reference
            t_start = _time.time()

            # if steps are selected, just assign number
            if self.ui.rbt_nr_steps.isChecked():
                steps = int(self.ui.sb_commanded_nr_steps.value())
                curr_dir = rotation_direction
                if steps < 0:
                    if rotation_direction == '+':
                        curr_dir = '-'
                    else:
                        curr_dir = '+'
                # if steps selected, ignore retries
                retry_count = 0
            elif use_encoder:
                # wait until there is a valid encoder reading
                while (self.encoder_measurement_index == -1
                       and not self.stop_sent
                       and (_time.time() - t_start) < move_timeout):
                    _time.sleep(wait)
                    _QApplication.processEvents()
                # get target position
                target_position = float(
                    self.ui.sbd_commanded_encoder_position.value())
                previous_encoder_index = self.encoder_measurement_index
                diff = target_position - self.current_encoder_position
                steps = _math.floor(diff /
                                    (linear_conversion / motor_resolution))
                curr_dir = rotation_direction
                if steps < 0:
                    if rotation_direction == '+':
                        curr_dir = '-'
                    else:
                        curr_dir = '+'

            # update motor moving LED
            self.ui.la_motor_is_moving.setEnabled(True)

            # try to reach position at the first move
            if steps != 0 and not self.stop_sent:
                # configure motor
                if not _driver.config_motor(driver_address, mode, curr_dir,
                                            motor_resolution, velocity,
                                            acceleration, steps):
                    msg = 'Falha ao enviar configuracao para motor.'
                    _QMessageBox.critical(self, 'Falha', msg, _QMessageBox.Ok)
                else:
                    # start motor motion if commanded to
                    _driver.move_motor(driver_address)
                    # wait for command reception
                    _time.sleep(wait)
                    # process gui events
                    _QApplication.processEvents()

            # if necessary, retry position
            while retry_count > 0:
                # update counter
                retry_count = retry_count - 1
                # wait until motor is idle

                while ((not _driver.ready(driver_address, wait)
                        or previous_encoder_index
                        == self.encoder_measurement_index
                        or self.encoder_measurement_index == -1)
                       and not self.stop_sent
                       and (_time.time() - t_start) < move_timeout):
                    _time.sleep(wait)
                    _QApplication.processEvents()
                # break if stop was sent
                if self.stop_sent:
                    break
                if (_time.time() - t_start) >= move_timeout:
                    is_timeout = True
                    break
                # update diff
                previous_encoder_index = self.encoder_measurement_index
                diff = target_position - self.current_encoder_position
                # check if diff is small enough
                if abs(diff) <= abs(tolerance):
                    break
                # update number of steps
                steps = _math.floor(diff /
                                    (linear_conversion / motor_resolution))
                curr_dir = rotation_direction
                if steps < 0:
                    if rotation_direction == '+':
                        curr_dir = '-'
                    else:
                        curr_dir = '+'
                # configure motor
                if not _driver.config_motor(driver_address, mode, curr_dir,
                                            motor_resolution, velocity,
                                            acceleration, steps):
                    msg = 'Falha ao enviar configuracao para motor.'
                    _QMessageBox.critical(self, 'Falha', msg, _QMessageBox.Ok)
                else:
                    # start motor motion if commanded to
                    _driver.move_motor(driver_address)
                    # wait for command reception
                    _time.sleep(wait)
                    # process gui events
                    _QApplication.processEvents()

            # wait until motor is idle

            while (not _driver.ready(driver_address, wait)
                   and (_time.time() - t_start) < move_timeout):
                _time.sleep(wait)
                _QApplication.processEvents()

            if self.stop_sent:
                msg = 'Recebido comando de Pare.'
                _QMessageBox.critical(self, 'Falha', msg, _QMessageBox.Ok)

            if is_timeout:
                msg = 'Timeout de movimentacao esgotado.'
                _QMessageBox.critical(self, 'Falha', msg, _QMessageBox.Ok)

            # update motor moving LED
            self.ui.la_motor_is_moving.setEnabled(False)

            # re-enable move and homing buttons
            self.ui.pbt_move_motor.setEnabled(True)
            self.ui.pbt_homing.setEnabled(True)

            return True
        except Exception:
            # update motor moving LED
            self.ui.la_motor_is_moving.setEnabled(False)
            # re-enable move and homing buttons
            self.ui.pbt_move_motor.setEnabled(True)
            self.ui.pbt_homing.setEnabled(True)
            # print erro info to user
            _traceback.print_exc(file=_sys.stdout)
            msg = 'Falha ao tentar mover o motor.'
            _QMessageBox.critical(self, 'Falha', msg, _QMessageBox.Ok)
            return False
Exemple #47
0
 def wrap_message(parent):
     return QMessageBox.critical(parent, _('Kite error'), err_msg)
Exemple #48
0
    def start(self, wdir=None, args=None, pythonpath=None):
        """
        Start the profiling process.

        Parameters
        ----------
        wdir: str
            Working directory path string. Default is None.
        args: list
            Arguments to pass to the profiling process. Default is None.
        pythonpath: str
            Python path string. Default is None.
        """
        filename = to_text_string(self.filecombo.currentText())
        if wdir is None:
            wdir = self._last_wdir
            if wdir is None:
                wdir = osp.basename(filename)

        if args is None:
            args = self._last_args
            if args is None:
                args = []

        if pythonpath is None:
            pythonpath = self._last_pythonpath

        self._last_wdir = wdir
        self._last_args = args
        self._last_pythonpath = pythonpath

        self.datelabel.setText(_('Profiling, please wait...'))

        self.process = QProcess(self)
        self.process.setProcessChannelMode(QProcess.SeparateChannels)
        self.process.setWorkingDirectory(wdir)
        self.process.readyReadStandardOutput.connect(self._read_output)
        self.process.readyReadStandardError.connect(
            lambda: self._read_output(error=True))
        self.process.finished.connect(
            lambda ec, es=QProcess.ExitStatus: self._finished(ec, es))
        self.process.finished.connect(self.stop_spinner)

        if pythonpath is not None:
            env = [to_text_string(_pth)
                   for _pth in self.process.systemEnvironment()]
            add_pathlist_to_PYTHONPATH(env, pythonpath)
            processEnvironment = QProcessEnvironment()
            for envItem in env:
                envName, __, envValue = envItem.partition('=')
                processEnvironment.insert(envName, envValue)

            processEnvironment.insert("PYTHONIOENCODING", "utf8")
            self.process.setProcessEnvironment(processEnvironment)

        self.output = ''
        self.error_output = ''
        self.running = True
        self.start_spinner()

        p_args = ['-m', 'cProfile', '-o', self.DATAPATH]
        if os.name == 'nt':
            # On Windows, one has to replace backslashes by slashes to avoid
            # confusion with escape characters (otherwise, for example, '\t'
            # will be interpreted as a tabulation):
            p_args.append(osp.normpath(filename).replace(os.sep, '/'))
        else:
            p_args.append(filename)

        if args:
            p_args.extend(shell_split(args))

        executable = sys.executable
        if executable.endswith("spyder.exe"):
            # py2exe distribution
            executable = "python.exe"

        self.process.start(executable, p_args)
        running = self.process.waitForStarted()
        if not running:
            QMessageBox.critical(
                self,
                _("Error"),
                _("Process failed to start"),
            )
        self.update_actions()
    def save_files(self):
        """Save database record to file."""
        try:
            table_name = self.twg_database.get_current_table_name()
            if table_name is None:
                return

            object_class = self._table_object_dict[table_name]

            idns = self.twg_database.get_table_selected_ids(table_name)
            nr_idns = len(idns)
            if nr_idns == 0:
                return

            objs = []
            fns = []
            try:
                for i in range(nr_idns):
                    idn = idns[i]
                    obj = object_class(database_name=self.database_name,
                                       mongo=self.mongo,
                                       server=self.server)
                    obj.db_read(idn)
                    default_filename = obj.default_filename
                    objs.append(obj)
                    fns.append(default_filename)

            except Exception:
                _traceback.print_exc(file=_sys.stdout)
                msg = 'Falha ao tentar ler entradas no banco de dados.'
                _QMessageBox.critical(self, 'Falha', msg, _QMessageBox.Ok)
                return

            if nr_idns == 1:
                filename = _QFileDialog.getSaveFileName(
                    self,
                    caption='Save file',
                    directory=_os.path.join(self.directory, fns[0]),
                    filter="Text files (*.txt *.dat)")

                if isinstance(filename, tuple):
                    filename = filename[0]

                if len(filename) == 0:
                    return

                fns[0] = filename
            else:
                directory = _QFileDialog.getExistingDirectory(
                    self, caption='Save files', directory=self.directory)

                if isinstance(directory, tuple):
                    directory = directory[0]

                if len(directory) == 0:
                    return

                for i in range(len(fns)):
                    fns[i] = _os.path.join(directory, fns[i])

            try:
                for i in range(nr_idns):
                    obj = objs[i]
                    idn = idns[i]
                    filename = fns[i]
                    if (not filename.endswith('.txt')
                            and not filename.endswith('.dat')):
                        filename = filename + '.txt'
                    obj.save_file(filename)
            except Exception:
                _traceback.print_exc(file=_sys.stdout)
                msg = 'Falha ao tentar salvar arquivos.'
                _QMessageBox.critical(self, 'Falha', msg, _QMessageBox.Ok)
        except Exception:
            _traceback.print_exc(file=_sys.stdout)
Exemple #50
0
 def critical_message(self, title, message):
     """Expose a QMessageBox.critical dialog to be used from the plugin."""
     QMessageBox.critical(self, title, message)
Exemple #51
0
    def finished(self, exit_code, exit_status):
        self.set_running_state(False)
        if not self.output:
            if self.error_output:
                QMessageBox.critical(self, _("Error"), self.error_output)
                print("pylint error:\n\n" + self.error_output, file=sys.stderr)
            return

        # Convention, Refactor, Warning, Error
        results = {'C:': [], 'R:': [], 'W:': [], 'E:': []}
        txt_module = '************* Module '

        module = ''  # Should not be needed - just in case something goes wrong
        for line in self.output.splitlines():
            if line.startswith(txt_module):
                # New module
                module = line[len(txt_module):]
                continue
            # Supporting option include-ids: ('R3873:' instead of 'R:')
            if not re.match(r'^[CRWE]+([0-9]{4})?:', line):
                continue
            items = {}
            idx_0 = 0
            idx_1 = 0
            key_names = ["msg_id", "message_name", "line_nb", "message"]
            for key_idx, key_name in enumerate(key_names):
                if key_idx == len(key_names) - 1:
                    idx_1 = len(line)
                else:
                    idx_1 = line.find(":", idx_0)

                if idx_1 < 0:
                    break
                item = line[(idx_0):idx_1]

                if not item:
                    break

                if key_name == "line_nb":
                    item = int(item.split(',')[0])

                items[key_name] = item
                idx_0 = idx_1 + 1
            else:
                pylint_item = (module, items["line_nb"], items["message"],
                               items["msg_id"], items["message_name"])
                results[line[0] + ':'].append(pylint_item)

        # Rate
        rate = None
        txt_rate = 'Your code has been rated at '
        i_rate = self.output.find(txt_rate)
        if i_rate > 0:
            i_rate_end = self.output.find('/10', i_rate)
            if i_rate_end > 0:
                rate = self.output[i_rate + len(txt_rate):i_rate_end]

        # Previous run
        previous = ''
        if rate is not None:
            txt_prun = 'previous run: '
            i_prun = self.output.find(txt_prun, i_rate_end)
            if i_prun > 0:
                i_prun_end = self.output.find('/10', i_prun)
                previous = self.output[i_prun + len(txt_prun):i_prun_end]

        filename = str(self.filecombo.currentText())
        self.set_data(filename, (time.localtime(), rate, previous, results))
        self.output = self.error_output + self.output
        self.show_data(justanalyzed=True)
Exemple #52
0
    def _create_client_for_kernel(self, connection_file, hostname, sshkey,
                                  password):
        ipycon = self.main.ipyconsole

        # Verifying if the connection file exists
        try:
            cf_path = osp.dirname(connection_file)
            cf_filename = osp.basename(connection_file)
            # To change a possible empty string to None
            cf_path = cf_path if cf_path else None
            connection_file = find_connection_file(filename=cf_filename,
                                                   path=cf_path)
        except (IOError, UnboundLocalError):
            QMessageBox.critical(
                self, _('IPython'),
                _("Unable to connect to "
                  "<b>%s</b>") % connection_file)
            return

        # Getting the master id that corresponds to the client
        # (i.e. the i in i/A)
        master_id = None
        given_name = None
        external_kernel = False
        slave_ord = ord('A') - 1
        kernel_manager = None

        for cl in ipycon.get_clients():
            if connection_file in cl.connection_file:
                if cl.get_kernel() is not None:
                    kernel_manager = cl.get_kernel()
                connection_file = cl.connection_file
                if master_id is None:
                    master_id = cl.id_['int_id']
                given_name = cl.given_name
                new_slave_ord = ord(cl.id_['str_id'])
                if new_slave_ord > slave_ord:
                    slave_ord = new_slave_ord

        # If we couldn't find a client with the same connection file,
        # it means this is a new master client
        if master_id is None:
            ipycon.master_clients += 1
            master_id = to_text_string(ipycon.master_clients)
            external_kernel = True

        # Set full client name
        client_id = dict(int_id=master_id, str_id=chr(slave_ord + 1))

        # Creating the client
        show_elapsed_time = ipycon.get_option('show_elapsed_time')
        reset_warning = ipycon.get_option('show_reset_namespace_warning')
        ask_before_restart = ipycon.get_option('ask_before_restart')
        client = MxClientWidget(
            ipycon,
            id_=client_id,
            given_name=given_name,
            history_filename=get_conf_path('history.py'),
            config_options=ipycon.config_options(),
            additional_options=ipycon.additional_options(),
            interpreter_versions=ipycon.interpreter_versions(),
            connection_file=connection_file,
            menu_actions=self.menu_actions,
            hostname=hostname,
            external_kernel=external_kernel,
            slave=True,
            show_elapsed_time=show_elapsed_time,
            reset_warning=reset_warning,
            ask_before_restart=ask_before_restart,
            css_path=ipycon.css_path)

        # Change stderr_dir if requested
        if ipycon.test_dir is not None:
            client.stderr_dir = ipycon.test_dir

        # Create kernel client
        kernel_client = QtKernelClient(connection_file=connection_file)

        # This is needed for issue spyder-ide/spyder#9304.
        try:
            kernel_client.load_connection_file()
        except Exception as e:
            QMessageBox.critical(
                self, _('Connection error'),
                _("An error occurred while trying to load "
                  "the kernel connection file. The error "
                  "was:\n\n") + to_text_string(e))
            return

        if hostname is not None:
            try:
                connection_info = dict(ip=kernel_client.ip,
                                       shell_port=kernel_client.shell_port,
                                       iopub_port=kernel_client.iopub_port,
                                       stdin_port=kernel_client.stdin_port,
                                       hb_port=kernel_client.hb_port)
                newports = ipycon.tunnel_to_kernel(connection_info, hostname,
                                                   sshkey, password)
                (kernel_client.shell_port, kernel_client.iopub_port,
                 kernel_client.stdin_port, kernel_client.hb_port) = newports
            except Exception as e:
                QMessageBox.critical(
                    self, _('Connection error'),
                    _("Could not open ssh tunnel. The "
                      "error was:\n\n") + to_text_string(e))
                return

        # Assign kernel manager and client to shellwidget
        kernel_client.start_channels()
        shellwidget = client.shellwidget
        shellwidget.set_kernel_client_and_manager(kernel_client,
                                                  kernel_manager)
        shellwidget.sig_exception_occurred.connect(
            self.main.console.exception_occurred)
        if external_kernel:
            shellwidget.sig_is_spykernel.connect(self.connect_external_kernel)
            shellwidget.is_spyder_kernel()

        # Set elapsed time, if possible
        if not external_kernel:
            ipycon.set_elapsed_time(client)

        # Adding a new tab for the client
        ipycon.add_tab(client, name=client.get_name())

        # Register client
        ipycon.register_client(client)
Exemple #53
0
 def _error_promopt(self, error):
     QMessageBox.critical(self, "Error Input", str(error), QMessageBox.Ok)
     return False
Exemple #54
0
    def contextMenuEvent(self, event):
        action = self.contextMenu.exec_(self.mapToGlobal(event.pos()))

        if action == self.action_update_formulas:
            index = self.currentIndex()
            if index.isValid():
                item = index.internalPointer()
                if isinstance(item, SpaceItem):
                    pass
                else:
                    if index.parent().isValid():
                        item = index.parent().internalPointer()
                    else:
                        return

                self.shell.update_codelist(item.itemData['fullname'])

        elif action == self.action_update_properties:
            index = self.currentIndex()
            if index.isValid():
                item = self.currentIndex().internalPointer()
                if not isinstance(item, ViewItem):
                    self.shell.update_mxproperty(item.itemData['fullname'])

        elif action == self.action_import_names:
            index = self.currentIndex()
            if index.isValid():
                item = self.currentIndex().internalPointer()

                if isinstance(item, SpaceItem):
                    has_children = True
                elif isinstance(item, CellsItem) or isinstance(item, RefItem):
                    has_children = False
                else:
                    return
            else:
                return

            if has_children:
                dialog = ImportNamesDialog(self)
                dialog.exec()

                if self.reply['accepted']:
                    import_selected = self.reply['import_selected']
                    import_children = self.reply['import_children']
                    replace_existing = self.reply['replace_existing']
                    self.reply = None
                else:
                    self.reply = None
                    return
            else:
                import_selected = True
                import_children = False
                replace_existing = True

            self.shell.import_names(item.itemData['fullname'],
                                    import_selected,
                                    import_children,
                                    replace_existing
                                    )

        elif action == self.action_analyze_selected:
            index = self.currentIndex()
            if index.isValid():
                item = self.currentIndex().internalPointer()
                if isinstance(item, CellsItem):
                    self.shell.mxanalyzer.update_object(item.itemData)

        elif action == self.action_new_model:
            dialog = NewModelDialog(self)
            dialog.exec()

            if self.reply['accepted']:
                name = self.reply['name']
                define_var = self.reply['define_var']
                if define_var:
                    varname = self.reply['varname']
                else:
                    varname = ''
                self.reply = None
                self.shell.new_model(name, define_var, varname)
            else:
                self.reply = None

        elif action == self.action_new_space:
            if self.model():
                parentList = self.model().rootItem.getSpaceContainerList()
            else:
                parentList = []

            # Find current item
            index = self.currentIndex()
            if index.isValid():
                name = index.internalPointer().itemData['fullname']
                try:
                    currIndex = parentList.index(name)
                except ValueError:
                    currIndex = 0
            else:
                currIndex = 0

            if self.model():
                model = self.model().rootItem.itemData['name']
            else:
                model = ''

            dialog = NewSpaceDialog(self, parentList, currIndex)
            dialog.exec()

            if self.reply['accepted']:
                name = self.reply['name']
                parent = self.reply['parent']
                bases = self.reply['bases']
                define_var = self.reply['define_var']
                if define_var:
                    varname = self.reply['varname']
                else:
                    varname = ''
                self.reply = None
                self.shell.new_space(
                    model, parent, name, bases, define_var, varname)
            else:
                self.reply = None

        elif action == self.action_new_cells:
            if self.model():
                parentList = self.model().rootItem.getChildSpaceList()
            else:
                parentList = []

            # Find current item
            index = self.currentIndex()
            if index.isValid():
                name = index.internalPointer().itemData['namedid']
                try:
                    currIndex = parentList.index(name)
                except ValueError:
                    currIndex = 0
            else:
                currIndex = 0

            if self.model():
                model = self.model().rootItem.itemData['name']
            else:
                model = ''

            dialog = NewCellsDialog(self, parentList, currIndex)
            dialog.exec()

            if self.reply['accepted']:
                name = self.reply['name']
                parent = self.reply['parent']
                formula = self.reply['formula']
                define_var = self.reply['define_var']
                if define_var:
                    varname = self.reply['varname']
                else:
                    varname = ''
                self.reply = None
                self.shell.new_cells(
                    model, parent, name, formula, define_var, varname)
            else:
                self.reply = None

        elif action == self.action_read_model:
            dialog = ReadModelDialog(self, modelpath=self.mx_widget.last_modelpath)
            dialog.exec()

            if self.reply['accepted']:
                modelpath = self.reply['directory']
                name = self.reply['name']
                define_var = self.reply['define_var']
                if define_var:
                    varname = self.reply['varname']
                else:
                    varname = ''
                self.reply = None
                self.shell.read_model(modelpath, name, define_var, varname)
                self.mx_widget.last_modelpath = modelpath
            else:
                self.reply = None

        elif action == self.action_write_model:
            model = self.container.current_widget().model_selector.get_selected_model()
            if not model:
                QMessageBox.critical(self, "Error", "No model exits.")
                return

            dialog = WriteModelDialog(self, modelpath=self.mx_widget.last_modelpath)
            dialog.exec()

            if self.reply['accepted']:
                modelpath = self.reply['directory'] + "/" + self.reply['name']
                backup = self.reply['backup']
                zipmodel = self.reply['zipmodel']
                self.reply = None
                self.shell.write_model(model, modelpath, backup, zipmodel)
                self.mx_widget.last_modelpath = modelpath
            else:
                self.reply = None

        elif action == self.action_delete_model:
            model = self.container.current_widget().model_selector.get_selected_model()
            if model:
                answer = QMessageBox.question(
                    self, _("Delete Model"),
                    _("Do you want to delete %s?" % model),
                    QMessageBox.Yes | QMessageBox.No)
                if answer == QMessageBox.Yes:
                    self.shell.del_model(model)
                else:
                    return
            else:
                QMessageBox.critical(self, "Error", "No model exits.")
        elif action == self.action_delete_selected:
            index = self.currentIndex()
            if index.isValid():
                item = index.internalPointer()
                if isinstance(item, ViewItem) or isinstance(item, ItemSpaceItem):
                    pass
                else:
                    if index.parent().isValid():
                        parent = index.parent().internalPointer().fullname
                    else:
                        parent = self.container.current_widget().model_selector.get_selected_model()
                    assert parent

                    answer = QMessageBox.question(
                        self, _("Delete Selected"),
                        _("Do you want to delete %s?" % item.name),
                        QMessageBox.Yes | QMessageBox.No)

                    if answer == QMessageBox.Yes:
                        self.shell.del_object(parent, item.name)

                        QMessageBox.information(
                            self, "Notice",
                            "'%s' is deleted from '%s'" % (item.name, parent))
Exemple #55
0
    def start(self, wdir=None, args=None, pythonpath=None):
        filename = to_text_string(self.filecombo.currentText())
        if wdir is None:
            wdir = self._last_wdir
            if wdir is None:
                wdir = osp.basename(filename)
        if args is None:
            args = self._last_args
            if args is None:
                args = []
        if pythonpath is None:
            pythonpath = self._last_pythonpath
        self._last_wdir = wdir
        self._last_args = args
        self._last_pythonpath = pythonpath

        self.datelabel.setText(_('Profiling, please wait...'))

        self.process = QProcess(self)
        self.process.setProcessChannelMode(QProcess.SeparateChannels)
        self.process.setWorkingDirectory(wdir)
        self.process.readyReadStandardOutput.connect(self.read_output)
        self.process.readyReadStandardError.connect(
            lambda: self.read_output(error=True))
        self.process.finished.connect(self.finished)
        self.stop_button.clicked.connect(self.process.kill)

        if pythonpath is not None:
            env = [
                to_text_string(_pth)
                for _pth in self.process.systemEnvironment()
            ]
            add_pathlist_to_PYTHONPATH(env, pythonpath)
            processEnvironment = QProcessEnvironment()
            for envItem in env:
                envName, separator, envValue = envItem.partition('=')
                processEnvironment.insert(envName, envValue)
            self.process.setProcessEnvironment(processEnvironment)

        self.output = ''
        self.error_output = ''

        if os.name == 'nt':
            # On Windows, one has to replace backslashes by slashes to avoid
            # confusion with escape characters (otherwise, for example, '\t'
            # will be interpreted as a tabulation):
            filename = osp.normpath(filename).replace(os.sep, '/')
            p_args = [
                '-lvb', '-o', '"' + self.DATAPATH + '"', '"' + filename + '"'
            ]
            if args:
                p_args.extend(programs.shell_split(args))
            executable = '"' + programs.find_program('kernprof') + '"'
            executable += ' ' + ' '.join(p_args)
            executable = executable.replace(os.sep, '/')
            self.process.start(executable)
        else:
            p_args = ['-lvb', '-o', self.DATAPATH, filename]
            if args:
                p_args.extend(programs.shell_split(args))
            executable = 'kernprof'
            self.process.start(executable, p_args)

        running = self.process.waitForStarted()
        self.set_running_state(running)
        if not running:
            QMessageBox.critical(self, _("Error"),
                                 _("Process failed to start"))
Exemple #56
0
def int_conversion_error(text, parent=None):
    QMessageBox.critical(
        parent, 'Conversion Error',
        'The input "{0}" could not be converted to an integer number.'.format(
            text))
    def homing(self):
        """ Move motor to limit switch at the beginning of range.
            If the motor direction is reversed, than the positive
            limit switch is used as home switch. """
        # clear stop flag
        self.stop_sent = False

        # check motor connection
        if not _driver.connected:
            msg = 'Driver nao conectado.'
            _QMessageBox.critical(self, 'Falha', msg, _QMessageBox.Ok)
            return False

        # disable move and homing buttons
        self.ui.pbt_move_motor.setEnabled(False)
        self.ui.pbt_homing.setEnabled(False)

        try:
            # interval to wat after move
            wait = 0.1

            # motor info
            driver_address = self.advanced_options.motor_driver_address
            resolution = self.advanced_options.motor_resolution
            rotation_direction = self.advanced_options.motor_rotation_direction
            velocity = self.advanced_options.motor_velocity
            acceleration = self.advanced_options.motor_acceleration
            move_timeout = self.advanced_options.move_timeout

            # mode = preset (not continuous)
            mode = 0
            steps = int(int(resolution) * 2)

            # register move start
            t_start = _time.time()

            # move start flag
            move_started = False

            # move towards the negative or positive limit switch
            if not self.stop_sent:
                if rotation_direction == '+':
                    if not _driver.move_to_negative_limit(
                            driver_address, velocity, acceleration, wait):
                        msg = ('Falha ao tentar enviar comando '
                               'para driver.')
                        _QMessageBox.critical(self, 'Falha', msg,
                                              _QMessageBox.Ok)
                    else:
                        move_started = True
                else:
                    if not _driver.move_to_positive_limit(
                            driver_address, velocity, acceleration, wait):
                        msg = ('Falha ao tentar enviar comando '
                               'para driver.')
                        _QMessageBox.critical(self, 'Falha', msg,
                                              _QMessageBox.Ok)
                    else:
                        move_started = True

            # wait motor stop
            if move_started:
                _time.sleep(wait)
                t_curr = _time.time()
                while (not _driver.ready(driver_address) and not self.stop_sent
                       and not (t_curr - t_start) > move_timeout):
                    t_curr = _time.time()
                    _time.sleep(wait)
                    _QApplication.processEvents()

                if (t_curr - t_start) > move_timeout:
                    self.stop_motor()
                    msg = 'Timeout durante Homing - parando motor.'
                    _QMessageBox.critical(self, 'Falha', msg, _QMessageBox.Ok)

        except Exception:
            _traceback.print_exc(file=_sys.stdout)
            msg = 'Homing falhou.'
            _QMessageBox.critical(self, 'Falha', msg, _QMessageBox.Ok)

        # re-enable move and homing buttons
        self.ui.pbt_move_motor.setEnabled(True)
        self.ui.pbt_homing.setEnabled(True)

        return
Exemple #58
0
    def add_data_for_testing(self, data):
        """
        Processes data message from the central communication hub.

        Parameters
        ----------
        data : :class:`glue.core.data.Data`
            Data object.
        """

        # Check whether the data is suitable for the MOSViz viewer - basically
        # we expect a table of 1D columns with at least three string and four
        # floating-point columns.
        if data.ndim != 1:
            QMessageBox.critical(self,
                                 "Error", "MOSViz viewer can only be used "
                                 "for data with 1-dimensional components",
                                 buttons=QMessageBox.Ok)
            return False

        components = [data.get_component(cid) for cid in data.main_components]
        categorical = [c for c in components if c.categorical]
        if len(categorical) < 3:
            QMessageBox.critical(
                self,
                "Error", "MOSViz viewer expected at least "
                "three string components/columns, representing "
                "the filenames of the 1D and 2D spectra and "
                "cutouts",
                buttons=QMessageBox.Ok)
            return False

        # We can relax the following requirement if we make the slit parameters
        # optional
        numerical = [c for c in components if c.numeric]
        if len(numerical) < 4:
            QMessageBox.critical(
                self,
                "Error", "MOSViz viewer expected at least "
                "four numerical components/columns, representing "
                "the slit position, length, and position angle",
                buttons=QMessageBox.Ok)
            return False

        # Block of code to bypass the loader_selection gui
        #########################################################
        if 'loaders' not in data.meta:
            data.meta['loaders'] = {}

        # Deimos data
        data.meta['loaders']['spectrum1d'] = "DEIMOS 1D Spectrum"
        data.meta['loaders']['spectrum2d'] = "DEIMOS 2D Spectrum"
        data.meta['loaders']['cutout'] = "ACS Cutout Image"

        if 'special_columns' not in data.meta:
            data.meta['special_columns'] = {}

        data.meta['special_columns']['spectrum1d'] = 'spectrum1d'
        data.meta['special_columns']['spectrum2d'] = 'spectrum2d'
        data.meta['special_columns']['source_id'] = 'id'
        data.meta['special_columns']['cutout'] = 'cutout'
        data.meta['special_columns']['slit_ra'] = 'ra'
        data.meta['special_columns']['slit_dec'] = 'dec'
        data.meta['special_columns']['slit_width'] = 'slit_width'
        data.meta['special_columns']['slit_length'] = 'slit_length'

        data.meta['loaders_confirmed'] = True
        #########################################################

        self._primary_data = data
        self._layer_view.data = data
        self._unpack_selection(data)
        return True
Exemple #59
0
 def error(self, message):
     """An error occured, closing the dialog box"""
     QMessageBox.critical(self, _("Array editor"), message)
     self.setAttribute(Qt.WA_DeleteOnClose)
     self.reject()
Exemple #60
0
 def print_error(self, exception):
     """Print error message"""
     message = "Smoothing Failed!\n\n" + str(exception)
     info = QMessageBox.critical(self, "Error", message)
     self.clean_up()