Connect an external kernel to the Variable Explorer and Help, if
        it is a Spyder kernel.
335688
def connect_external_kernel(self, shellwidget):
        
        sw = shellwidget
        kc = shellwidget.kernel_client
        if self.main.help is not None:
            self.main.help.set_shell(sw)
        if self.main.variableexplorer is not None:
            self.main.variableexplorer.add_shellwidget(sw)
            sw.set_namespace_view_settings()
            sw.refresh_namespacebrowser()
            kc.stopped_channels.connect(lambda :
                self.main.variableexplorer.remove_shellwidget(id(sw)))
43487
def set_cwd(self, dirname):
        """"""
        # Replace single for double backslashes on Windows
        if os.name == 'nt':
            dirname = dirname.replace(u"\\", u"\\\\")

        if not self.external_kernel:
            code = u"get_ipython().kernel.set_cwd(u'''{}''')".format(dirname)
            if self._reading:
                self.kernel_client.input(u'!' + code)
            else:
                self.silent_execute(code)
            self._cwd = dirname
1124860
def open_external(self, fnames=None):
        """"""
        if fnames is None:
            fnames = self.get_selected_filenames()
        for fname in fnames:
            self.open_outside_spyder([fname])
243691
def load_data(self, filename, ext):
        """"""
        from spyder_kernels.utils.iofuncs import iofunctions
        from spyder_kernels.utils.misc import fix_reference_name

        glbs = self._mglobals()

        load_func = iofunctions.load_funcs[ext]
        data, error_message = load_func(filename)

        if error_message:
            return error_message

        for key in list(data.keys()):
            new_key = fix_reference_name(key, blacklist=list(glbs.keys()))
            if new_key != key:
                data[new_key] = data.pop(key)

        try:
            glbs.update(data)
        except Exception as error:
            return str(error)

        return None
843331
async def set_kernel_options(cls, options: typing.Optional[str]):
        """"""
        await cls.set_config("kernel_opts", "" if options is None else options)
1119941
def start_new_kernel(startup_timeout=60, kernel_name='python', **kwargs):
    """"""
    logger.debug('Starting new kernel: "%s"' % kernel_name)
    km = KernelManager(kernel_name=kernel_name,
                       kernel_spec_manager=NbvalKernelspecManager())
    km.start_kernel(**kwargs)
    kc = km.client()
    kc.start_channels()
    try:
        kc.wait_for_ready(timeout=startup_timeout)
    except RuntimeError:
        logger.exception('Failure starting kernel "%s"', kernel_name)
        kc.stop_channels()
        km.shutdown_kernel()
        raise

    return km, kc
1100614
def create_kernel_manager_and_kernel_client(self, connection_file,
                                                stderr_handle,
                                                is_cython=False,
                                                is_pylab=False,
                                                is_sympy=False):
        """"""
        # Kernel spec
        kernel_spec = self.create_kernel_spec(is_cython=is_cython,
                                              is_pylab=is_pylab,
                                              is_sympy=is_sympy)

        # Kernel manager
        try:
            kernel_manager = QtKernelManager(connection_file=connection_file,
                                             config=None, autorestart=True)
        except Exception:
            error_msg = _("The error is:<br><br>"
                          "<tt>{}</tt>").format(traceback.format_exc())
            return (error_msg, None)
        kernel_manager._kernel_spec = kernel_spec

        kwargs = {}
        if os.name == 'nt':
            # avoid closing fds on win+Python 3.7
            # which prevents interrupts
            # jupyter_client > 5.2.3 will do this by default
            kwargs['close_fds'] = False
        # Catch any error generated when trying to start the kernel
        # See issue 7302
        try:
            kernel_manager.start_kernel(stderr=stderr_handle, **kwargs)
        except Exception:
            error_msg = _("The error is:<br><br>"
                          "<tt>{}</tt>").format(traceback.format_exc())
            return (error_msg, None)

        # Kernel client
        kernel_client = kernel_manager.client()

        # Increase time to detect if a kernel is alive
        # See Issue 3444
        kernel_client.hb_channel.time_to_dead = 18.0

        return kernel_manager, kernel_client
797808
def _detect_notebook() -> bool:
    
    try:
        from IPython import get_ipython
        from ipykernel import zmqshell
    except ImportError:
        return False
    kernel = get_ipython()
    try:
        from spyder.utils.ipython.spyder_kernel import SpyderKernel

        if isinstance(kernel.kernel, SpyderKernel):
            return False
    except (ImportError, AttributeError):
        pass
    return isinstance(kernel, zmqshell.ZMQInteractiveShell)
1309416
def _ioctl(self, func, arg):
        """"""
        if self._fd is None:
            raise WatchdogError("Watchdog device is closed")
        if os.name != 'nt':
            import fcntl
            fcntl.ioctl(self._fd, func, arg, True)
1062276
def InternalPlatformSwitch(funcname, *args, **kwargs):
  """"""
  # pylint: disable=g-import-not-at-top
  clz = None
  if sys.platform.startswith('linux'):
    from pyu2f.hid import linux
    clz = linux.LinuxHidDevice
  elif sys.platform.startswith('win32'):
    from pyu2f.hid import windows
    clz = windows.WindowsHidDevice
  elif sys.platform.startswith('darwin'):
    from pyu2f.hid import macos
    clz = macos.MacOsHidDevice

  if not clz:
    raise Exception('Unsupported platform: ' + sys.platform)

  if funcname == '__init__':
    return clz(*args, **kwargs)
  return getattr(clz, funcname)(*args, **kwargs)
153092
private function _kernel()
    {
        if (CommonFunctions::executeProgram('oslevel', '', $ret1) && CommonFunctions::executeProgram('oslevel', '-s', $ret2)) {
            $this->sys->setKernel($ret1 . '   (' . $ret2 . ')');
        }
    }
1134837
def patch_spyder3(verbose=False):
    ''' '''
    try:
        # patch spyder/config/utils.py for file extension
        from spyder.config import utils
        src_file = utils.__file__
        spyder_dir = os.path.dirname(os.path.dirname(src_file))
        patch_file(src_file,
        '''
    (_("Cython/Pyrex files"), ('.pyx', '.pxd', '.pxi')),
    (_("C files"), ('.c', '.h')),''',
        '''
    (_("Cython/Pyrex files"), ('.pyx', '.pxd', '.pxi')),
    (_("SoS files"), ('.sos', )),
    (_("C files"), ('.c', '.h')),''',
            verbose=verbose)
        #
        # patch spyder/app/cli_options.py to add command line option --kernel
        patch_file(os.path.join(spyder_dir, 'app', 'cli_options.py'),
            '''help="String to show in the main window title")
    options, args = parser.parse_args()''',
            '''help="String to show in the main window title")
    parser.add_option('--kernel', help="Jupyter kernel to start.")
    options, args = parser.parse_args()''',
            verbose=verbose)
        #
        # patch spyder/utils/sourcecode.py,
        patch_file(os.path.join(spyder_dir, 'utils', 'sourcecode.py'),
                "'Python': ('py', 'pyw', 'python', 'ipy')",
                "'Python': ('py', 'pyw', 'python', 'ipy', 'sos')",
            verbose=verbose)
        patch_file(os.path.join(spyder_dir, 'utils', 'sourcecode.py'),
                '''CELL_LANGUAGES = {'Python': ('#%%', '# %%', '# <codecell>', '# In[')}''',
                '''CELL_LANGUAGES = {'Python': ('#%%', '# %%', '# <codecell>', '# In[', '%cell')}''',
            verbose=verbose)
        #
        # patch spyder/app/mainwindow.py
        patch_file(os.path.join(spyder_dir, 'app', 'mainwindow.py'),
            '''
    app.exec_()
''',
            r'''
    try:
        if options.kernel == 'sos':
            cfg_file = os.path.expanduser('~/.ipython/profile_default/ipython_config.py')
            has_cfg = os.path.isfile(cfg_file)
            if has_cfg and not os.path.isfile(cfg_file + '.sos_bak'):
                os.rename(cfg_file, cfg_file + '.sos_bak')
            with open(cfg_file, 'w') as cfg:
                cfg.write("c.IPKernelApp.kernel_class =  'sos_notebook.spyder_kernel.SoS_SpyderKernel'\n")
        app.exec_()
    finally:
        if options.kernel == 'sos':
            os.remove(cfg_file)
            if os.path.isfile(cfg_file + '.sos_bak'):
                os.rename(cfg_file + '.sos_bak', cfg_file)
''',
            verbose=verbose)
        #
        print('\nSpyder is successfully patched to accept .sos format and sos kernel.')
        print('Use ')
        print()
        print('    $ spyder --kernel sos')
        print()
        print('to start spyder with sos kernel')
    except Exception as e:
        sys.exit('Failed to patch spyder: {}'.format(e))
213001
def detach_kernel_driver(self, interface):
        
        """
        self._ctx.managed_open()
        self._ctx.backend.detach_kernel_driver(
            self._ctx.handle,
            interface)
777925
def env(self):
        """"""
        # Add our PYTHONPATH to the kernel
        pathlist = CONF.get('main', 'spyder_pythonpath', default=[])

        default_interpreter = CONF.get('main_interpreter', 'default')
        pypath = add_pathlist_to_PYTHONPATH([], pathlist, ipyconsole=True,
                                            drop_env=False)

        # Environment variables that we need to pass to our sitecustomize
        umr_namelist = CONF.get('main_interpreter', 'umr/namelist')

        if PY2:
            original_list = umr_namelist[:]
            for umr_n in umr_namelist:
                try:
                    umr_n.encode('utf-8')
                except UnicodeDecodeError:
                    umr_namelist.remove(umr_n)
            if original_list != umr_namelist:
                CONF.set('main_interpreter', 'umr/namelist', umr_namelist)

        env_vars = {
            'SPY_EXTERNAL_INTERPRETER': not default_interpreter,
            'SPY_UMR_ENABLED': CONF.get('main_interpreter', 'umr/enabled'),
            'SPY_UMR_VERBOSE': CONF.get('main_interpreter', 'umr/verbose'),
            'SPY_UMR_NAMELIST': ','.join(umr_namelist),
            'SPY_RUN_LINES_O': CONF.get('ipython_console', 'startup/run_lines'),
            'SPY_PYLAB_O': CONF.get('ipython_console', 'pylab'),
            'SPY_BACKEND_O': CONF.get('ipython_console', 'pylab/backend'),
            'SPY_AUTOLOAD_PYLAB_O': CONF.get('ipython_console',
                                             'pylab/autoload'),
            'SPY_FORMAT_O': CONF.get('ipython_console',
                                     'pylab/inline/figure_format'),
            'SPY_BBOX_INCHES_O': CONF.get('ipython_console',
                                          'pylab/inline/bbox_inches'),
            'SPY_RESOLUTION_O': CONF.get('ipython_console',
                                         'pylab/inline/resolution'),
            'SPY_WIDTH_O': CONF.get('ipython_console', 'pylab/inline/width'),
            'SPY_HEIGHT_O': CONF.get('ipython_console', 'pylab/inline/height'),
            'SPY_USE_FILE_O': CONF.get('ipython_console',
                                       'startup/use_run_file'),
            'SPY_RUN_FILE_O': CONF.get('ipython_console', 'startup/run_file'),
            'SPY_AUTOCALL_O': CONF.get('ipython_console', 'autocall'),
            'SPY_GREEDY_O': CONF.get('ipython_console', 'greedy_completer'),
            'SPY_JEDI_O': CONF.get('ipython_console', 'jedi_completer'),
            'SPY_SYMPY_O': CONF.get('ipython_console', 'symbolic_math'),
            'SPY_TESTING': running_under_pytest() or SAFE_MODE,
            'SPY_HIDE_CMD': CONF.get('ipython_console', 'hide_cmd_windows')
        }

        if self.is_pylab is True:
            env_vars['SPY_AUTOLOAD_PYLAB_O'] = True
            env_vars['SPY_SYMPY_O'] = False
            env_vars['SPY_RUN_CYTHON'] = False
        if self.is_sympy is True:
            env_vars['SPY_AUTOLOAD_PYLAB_O'] = False
            env_vars['SPY_SYMPY_O'] = True
            env_vars['SPY_RUN_CYTHON'] = False
        if self.is_cython is True:
            env_vars['SPY_AUTOLOAD_PYLAB_O'] = False
            env_vars['SPY_SYMPY_O'] = False
            env_vars['SPY_RUN_CYTHON'] = True

        # Add our PYTHONPATH to env_vars
        env_vars.update(pypath)

        # Making all env_vars strings
        for key,var in iteritems(env_vars):
            if PY2:
                # Try to convert vars first to utf-8.
                try:
                    unicode_var = to_text_string(var)
                except UnicodeDecodeError:
                    # If that fails, try to use the file system
                    # encoding because one of our vars is our
                    # PYTHONPATH, and that contains file system
                    # directories
                    try:
                        unicode_var = to_unicode_from_fs(var)
                    except:
                        # If that also fails, make the var empty
                        # to be able to start Spyder.
                        # See https://stackoverflow.com/q/44506900/438386
                        # for details.
                        unicode_var = ''
                env_vars[key] = to_binary_string(unicode_var,
                                                 encoding='utf-8')
            else:
                env_vars[key] = to_text_string(var)
        return env_vars
371122
def check_spyder_kernels():
    """"""
    try:
        import spyder_kernels
        required_ver = '1.0.0'
        actual_ver = spyder_kernels.__version__
        if LooseVersion(actual_ver) < LooseVersion(required_ver):
            show_warning("Please check Spyder installation requirements:\n"
                         "spyder-kernels >= 1.0 is required (found %s)."
                         % actual_ver)
    except ImportError:
        show_warning("Failed to import spyder-kernels.\n"
                     "Please check Spyder installation requirements:\n\n"
                     "spyder-kernels >= 1.0 is required")
361144
def postActivate_(self):
        
        self.tmpfile = os.path.join(constant.tmpdir,"valkka-"+str(os.getpid())) # e.g. "/tmp/valkka-10968" 
        self.analyzer = ExternalDetector(
            executable = self.executable,
            image_dimensions = self.image_dimensions,
            tmpfile = self.tmpfile
            )
877506
def install_kernel_spec(self, app, dir_name, display_name,
                            settings_module, ipython_arguments):
        
        ksm = app.kernel_spec_manager
        try_spec_names = ['python3' if six.PY3 else 'python2', 'python']
        if isinstance(try_spec_names, six.string_types):
            try_spec_names = [try_spec_names]
        ks = None
        for spec_name in try_spec_names:
            try:
                ks = ksm.get_kernel_spec(spec_name)
                break
            except Exception:
                continue
        if not ks:
            self.parser.error("No notebook (Python) kernel specs found")

        ks.display_name = display_name
        ks.env["CORRAL_SETTINGS_MODULE"] = settings_module
        ks.argv.extend(ipython_arguments)

        in_corral_dir, in_corral = os.path.split(os.path.realpath(sys.argv[0]))

        pythonpath = ks.env.get(
            'PYTHONPATH', os.environ.get('PYTHONPATH', ''))
        pythonpath = pythonpath.split(':')
        if in_corral_dir not in pythonpath:
            pythonpath.append(in_corral_dir)
        ks.env['PYTHONPATH'] = ':'.join(filter(None, pythonpath))

        kernel_dir = os.path.join(ksm.user_kernel_dir, conf.PACKAGE)
        if not os.path.exists(kernel_dir):
            os.makedirs(kernel_dir)
            shutil.copy(res.fullpath("logo-64x64.png"), kernel_dir)
        with open(os.path.join(kernel_dir, 'kernel.json'), 'w') as f:
            f.write(ks.to_json())