Validates that this env contains an IRkernel kernel and returns info to start it


    Returns: tuple
        (ARGV, language, resource_dir)
964745
def validate_IRkernel(venv_dir):
    
    r_exe_name = find_exe(venv_dir, "R")
    if r_exe_name is None:
        return [], None, None

    # check if this is really an IRkernel **kernel**
    import subprocess
    ressources_dir = None
    try:
        print_resources = 'cat(as.character(system.file("kernelspec", package = "IRkernel")))'
        resources_dir_bytes = subprocess.check_output([r_exe_name, '--slave', '-e', print_resources])
        resources_dir = resources_dir_bytes.decode(errors='ignore')
    except:
        # not installed? -> not useable in any case...
        return [], None, None
    argv = [r_exe_name, "--slave", "-e", "IRkernel::main()", "--args", "{connection_file}"]
    if not os.path.exists(resources_dir.strip()):
        # Fallback to our own log, but don't get the nice js goodies...
        resources_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logos", "r")
    return argv, "r", resources_dir
1355346
def kernelspec_from_language(language):
    """"""
    try:
        for name in find_kernel_specs():
            kernel_specs = get_kernel_spec(name)
            if kernel_specs.language == language or (language == 'c++' and kernel_specs.language.startswith('C++')):
                return {'name': name, 'language': language, 'display_name': kernel_specs.display_name}
    except (KeyError, ValueError):
        pass
    return None
1015799
def _virtualenv_sys(venv_path):
    ""
    executable = os.path.join(venv_path, env_bin_dir, 'python')
    # Must use "executable" as the first argument rather than as the
    # keyword argument "executable" to get correct value from sys.path
    p = subprocess.Popen([executable,
        '-c', 'import sys;'
              'print (sys.version[:3]);'
              'print ("\\n".join(sys.path));'],
        env={},
        stdout=subprocess.PIPE)
    stdout, err = p.communicate()
    assert not p.returncode and stdout
    lines = stdout.decode('utf-8').splitlines()
    return lines[0], list(filter(bool, lines[1:]))
1237782
def kernel():
	
	print('================================')
	print('  WARNING: upgrading the kernel')
	print('================================')
	time.sleep(5)

	print('-[kernel]----------')
	cmd('rpi-update', True)
	print(' >> You MUST reboot to load the new kernel <<')
658821
def verify_environments():
    
    env_confs = discover(
        os.path.join(
            OPTIONS['base_dir'],
            '*.' + OPTIONS['in_ext'],
        )
    )
    success = True
    for conf in env_confs:
        env = Environment(name=conf['name'])
        current_comment = generate_hash_comment(env.infile)
        existing_comment = parse_hash_comment(env.outfile)
        if current_comment == existing_comment:
            logger.info("OK - %s was generated from %s.",
                        env.outfile, env.infile)
        else:
            logger.error("ERROR! %s was not regenerated after changes in %s.",
                         env.outfile, env.infile)
            logger.error("Expecting: %s", current_comment.strip())
            logger.error("Found:     %s", existing_comment.strip())
            success = False
    return success
768657
def check_env(env)
      ## The environment must be an true instance of Hash (no
      ## subclassing allowed) that includes CGI-like headers.
      ## The application is free to modify the environment.
      assert("env #{env.inspect} is not a Hash, but #{env.class}") {
        env.instance_of? Hash
      }

      ##
      ## The environment is required to include these variables
      ## (adopted from PEP333), except when they'd be empty, but see
      ## below.

      ## <tt>REQUEST_METHOD</tt>:: The HTTP request method, such as
      ##                           "GET" or "POST". This cannot ever
      ##                           be an empty string, and so is
      ##                           always required.

      ## <tt>SCRIPT_NAME</tt>:: The initial portion of the request
      ##                        URL's "path" that corresponds to the
      ##                        application object, so that the
      ##                        application knows its virtual
      ##                        "location". This may be an empty
      ##                        string, if the application corresponds
      ##                        to the "root" of the server.

      ## <tt>PATH_INFO</tt>:: The remainder of the request URL's
      ##                      "path", designating the virtual
      ##                      "location" of the request's target
      ##                      within the application. This may be an
      ##                      empty string, if the request URL targets
      ##                      the application root and does not have a
      ##                      trailing slash. This value may be
      ##                      percent-encoded when I originating from
      ##                      a URL.

      ## <tt>QUERY_STRING</tt>:: The portion of the request URL that
      ##                         follows the <tt>?</tt>, if any. May be
      ##                         empty, but is always required!

      ## <tt>SERVER_NAME</tt>, <tt>SERVER_PORT</tt>:: When combined with <tt>SCRIPT_NAME</tt> and <tt>PATH_INFO</tt>, these variables can be used to complete the URL. Note, however, that <tt>HTTP_HOST</tt>, if present, should be used in preference to <tt>SERVER_NAME</tt> for reconstructing the request URL.  <tt>SERVER_NAME</tt> and <tt>SERVER_PORT</tt> can never be empty strings, and so are always required.

      ## <tt>HTTP_</tt> Variables:: Variables corresponding to the
      ##                            client-supplied HTTP request
      ##                            headers (i.e., variables whose
      ##                            names begin with <tt>HTTP_</tt>). The
      ##                            presence or absence of these
      ##                            variables should correspond with
      ##                            the presence or absence of the
      ##                            appropriate HTTP header in the
      ##                            request.

      ## In addition to this, the Rack environment must include these
      ## Rack-specific variables:

      ## <tt>rack.version</tt>:: The Array [1,0], representing this version of Rack.
      ## <tt>rack.url_scheme</tt>:: +http+ or +https+, depending on the request URL.
      ## <tt>rack.input</tt>:: See below, the input stream.
      ## <tt>rack.errors</tt>:: See below, the error stream.
      ## <tt>rack.multithread</tt>:: true if the application object may be simultaneously invoked by another thread in the same process, false otherwise.
      ## <tt>rack.multiprocess</tt>:: true if an equivalent application object may be simultaneously invoked by another process, false otherwise.
      ## <tt>rack.run_once</tt>:: true if the server expects (but does not guarantee!) that the application will only be invoked this one time during the life of its containing process. Normally, this will only be true for a server based on CGI (or something similar).
      ##

      ## Additional environment specifications have approved to
      ## standardized middleware APIs.  None of these are required to
      ## be implemented by the server.

      ## <tt>rack.session</tt>:: A hash like interface for storing request session data.
      ##                         The store must implement:
      if session = env['rack.session']
        ##                         store(key, value)         (aliased as []=);
        assert("session #{session.inspect} must respond to store and []=") {
          session.respond_to?(:store) && session.respond_to?(:[]=)
        }

        ##                         fetch(key, default = nil) (aliased as []);
        assert("session #{session.inspect} must respond to fetch and []") {
          session.respond_to?(:fetch) && session.respond_to?(:[])
        }

        ##                         delete(key);
        assert("session #{session.inspect} must respond to delete") {
          session.respond_to?(:delete)
        }

        ##                         clear;
        assert("session #{session.inspect} must respond to clear") {
          session.respond_to?(:clear)
        }
      end

      ## The server or the application can store their own data in the
      ## environment, too.  The keys must contain at least one dot,
      ## and should be prefixed uniquely.  The prefix <tt>rack.</tt>
      ## is reserved for use with the Rack core distribution and other
      ## accepted specifications and must not be used otherwise.
      ##

      %w[REQUEST_METHOD SERVER_NAME SERVER_PORT
         QUERY_STRING
         rack.version rack.input rack.errors
         rack.multithread rack.multiprocess rack.run_once].each { |header|
        assert("env missing required key #{header}") { env.include? header }
      }

      ## The environment must not contain the keys
      ## <tt>HTTP_CONTENT_TYPE</tt> or <tt>HTTP_CONTENT_LENGTH</tt>
      ## (use the versions without <tt>HTTP_</tt>).
      %w[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH].each { |header|
        assert("env contains #{header}, must use #{header[5,-1]}") {
          not env.include? header
        }
      }

      ## The CGI keys (named without a period) must have String values.
      env.each { |key, value|
        next  if key.include? "."   # Skip extensions
        assert("env variable #{key} has non-string value #{value.inspect}") {
          value.instance_of? String
        }
      }

      ##
      ## There are the following restrictions:

      ## * <tt>rack.version</tt> must be an array of Integers.
      assert("rack.version must be an Array, was #{env["rack.version"].class}") {
        env["rack.version"].instance_of? Array
      }
      ## * <tt>rack.url_scheme</tt> must either be +http+ or +https+.
      assert("rack.url_scheme unknown: #{env["rack.url_scheme"].inspect}") {
        %w[http https].include? env["rack.url_scheme"]
      }

      ## * There must be a valid input stream in <tt>rack.input</tt>.
      check_input env["rack.input"]
      ## * There must be a valid error stream in <tt>rack.errors</tt>.
      check_error env["rack.errors"]

      ## * The <tt>REQUEST_METHOD</tt> must be a valid token.
      assert("REQUEST_METHOD unknown: #{env["REQUEST_METHOD"]}") {
        env["REQUEST_METHOD"] =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/
      }

      ## * The <tt>SCRIPT_NAME</tt>, if non-empty, must start with <tt>/</tt>
      assert("SCRIPT_NAME must start with /") {
        !env.include?("SCRIPT_NAME") ||
        env["SCRIPT_NAME"] == "" ||
        env["SCRIPT_NAME"] =~ /\A\//
      }
      ## * The <tt>PATH_INFO</tt>, if non-empty, must start with <tt>/</tt>
      assert("PATH_INFO must start with /") {
        !env.include?("PATH_INFO") ||
        env["PATH_INFO"] == "" ||
        env["PATH_INFO"] =~ /\A\//
      }
      ## * The <tt>CONTENT_LENGTH</tt>, if given, must consist of digits only.
      assert("Invalid CONTENT_LENGTH: #{env["CONTENT_LENGTH"]}") {
        !env.include?("CONTENT_LENGTH") || env["CONTENT_LENGTH"] =~ /\A\d+\z/
      }

      ## * One of <tt>SCRIPT_NAME</tt> or <tt>PATH_INFO</tt> must be
      ##   set.  <tt>PATH_INFO</tt> should be <tt>/</tt> if
      ##   <tt>SCRIPT_NAME</tt> is empty.
      assert("One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)") {
        env["SCRIPT_NAME"] || env["PATH_INFO"]
      }
      ##   <tt>SCRIPT_NAME</tt> never should be <tt>/</tt>, but instead be empty.
      assert("SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'") {
        env["SCRIPT_NAME"] != "/"
      }
    end
248244
def stdlib(self):
        
        if self.module == 'pkg_resources' or self.module.startswith('pkg_resources.'):
            return False
        elif self.filename.startswith(SITE_PACKAGES_PATHS):
            # if it's in site-packages then its definitely not stdlib
            return False
        elif self.filename.startswith(SYS_PREFIX_PATHS):
            return True
        else:
            return False
1185815
def _validate_args(env, args):
    """"""

    if all([args['cpu'], args['flavor']]):
        raise exceptions.ArgumentError(
            '[-c | --cpu] not allowed with [-f | --flavor]')

    if all([args['memory'], args['flavor']]):
        raise exceptions.ArgumentError(
            '[-m | --memory] not allowed with [-f | --flavor]')

    if all([args['dedicated'], args['flavor']]):
        raise exceptions.ArgumentError(
            '[-d | --dedicated] not allowed with [-f | --flavor]')

    if all([args['host_id'], args['flavor']]):
        raise exceptions.ArgumentError(
            '[-h | --host-id] not allowed with [-f | --flavor]')

    if all([args['userdata'], args['userfile']]):
        raise exceptions.ArgumentError(
            '[-u | --userdata] not allowed with [-F | --userfile]')

    image_args = [args['os'], args['image']]
    if all(image_args):
        raise exceptions.ArgumentError(
            '[-o | --os] not allowed with [--image]')

    while not any([args['os'], args['image']]):
        args['os'] = env.input("Operating System Code", default="", show_default=False)
        if not args['os']:
            args['image'] = env.input("Image", default="", show_default=False)
575456
def check_output(args, env=None, sp=subprocess):
    """"""
    log.debug('calling %s with env %s', args, env)
    output = sp.check_output(args=args, env=env)
    log.debug('output: %r', output)
    return output
9467
def isatty_from_env(cls, env):
    
    def str_int_bool(i):
      return i.isdigit() and bool(int(i))  # Environment variable values should always be strings.

    return tuple(
      str_int_bool(env.get(cls.TTY_ENV_TMPL.format(fd_id), '0')) for fd_id in STDIO_DESCRIPTORS
    )
300331
private function _kernel()
    {
        $result = "";
        if (CommonFunctions::executeProgram($uname="uptrack-uname", '-r', $strBuf, false) || // show effective kernel if ksplice uptrack is installed
            CommonFunctions::executeProgram($uname="uname", '-r', $strBuf, PSI_DEBUG)) {
            $result = $strBuf;
            if (CommonFunctions::executeProgram($uname, '-v', $strBuf, PSI_DEBUG)) {
                if (preg_match('/SMP/', $strBuf)) {
                    $result .= ' (SMP)';
                }
            }
            if (CommonFunctions::executeProgram($uname, '-m', $strBuf, PSI_DEBUG)) {
                $result .= ' '.$strBuf;
            }
        } elseif (CommonFunctions::rfts('/proc/version', $strBuf, 1) &&  preg_match('/version\s+(\S+)/', $strBuf, $ar_buf)) {
            $result = $ar_buf[1];
            if (preg_match('/SMP/', $strBuf)) {
                $result .= ' (SMP)';
            }
        }
        if ($result != "") {
            if (CommonFunctions::rfts('/proc/self/cgroup', $strBuf2, 0, 4096, false)) {
                if (preg_match('/:\/lxc\//m', $strBuf2)) {
                    $result .= ' [lxc]';
                } elseif (preg_match('/:\/docker\//m', $strBuf2)) {
                    $result .= ' [docker]';
                } elseif (preg_match('/:\/system\.slice\/docker\-/m', $strBuf2)) {
                    $result .= ' [docker]';
                }
            }
            if (CommonFunctions::rfts('/proc/version', $strBuf2, 1, 4096, false)
                && preg_match('/^Linux version [\d\.-]+-Microsoft/', $strBuf2)) {
                    $result .= ' [lxss]';
            }
            $this->sys->setKernel($result);
        }
    }
258028
def get_all_specs(self):
        
        # This is new in 4.1 -> https://github.com/jupyter/jupyter_client/pull/93
        specs = self.get_all_kernel_specs_for_envs()
        specs.update(super(EnvironmentKernelSpecManager, self).get_all_specs())
        return specs
382747
def kernel_initrds(self):
        

        kernels = []
        initrds = []
        name_values = [(k, v) for k, v in self.data.get('configs', [])]
        for value in self.data.get('title', []) + self.data.get('menuentry', []):
            name_values.extend(value)

        for name, value in name_values:
            if name.startswith('module'):
                if 'vmlinuz' in value:
                    kernels.append(_parse_kernel_initrds_value(value))
                elif 'initrd' in value or 'initramfs' in value:
                    initrds.append(_parse_kernel_initrds_value(value))
            elif (name.startswith(('kernel', 'linux'))):
                if 'ipxe.lkrn' in value:
                    # Machine PXE boots the kernel, assume all is ok
                    return {}
                elif 'xen.gz' not in value:
                    kernels.append(_parse_kernel_initrds_value(value))
            elif name.startswith('initrd') or name.startswith('initrd16'):
                initrds.append(_parse_kernel_initrds_value(value))

        return {GRUB_KERNELS: kernels, GRUB_INITRDS: initrds}
799845
public function checkKernel()
    {
        $content = file_get_contents($this->kernelURL);

        $out = JSON::decode($content, true);

        if ($this->compaireSecondary($out->version, $this->kernel->version)
         && ($out->sha != $this->kernel->sha)) {
            return $out;
        } else {
            return false;
        }
    }
1356540
def get_kernel_spec(self, kernel_name):
        
        try:
            return super(EnvironmentKernelSpecManager,
                         self).get_kernel_spec(kernel_name)
        except (NoSuchKernel, FileNotFoundError):
            venv_kernel_name = kernel_name.lower()
            specs = self.get_all_kernel_specs_for_envs()
            if venv_kernel_name in specs:
                return specs[venv_kernel_name]
            else:
                raise NoSuchKernel(kernel_name)
955129
def validate_kernel_string(self, kernel):
        
        if kernel:
            if '/' not in kernel:
                raise ValueError('Kernel must be specified in the form of '
                                 '\'{username}/{kernel-slug}\'')

            split = kernel.split('/')
            if not split[0] or not split[1]:
                raise ValueError('Kernel must be specified in the form of '
                                 '\'{username}/{kernel-slug}\'')

            if len(split[1]) < 5:
                raise ValueError(
                    'Kernel slug must be at least five characters')
258511
def _verify_python3_env():
    """"""
    if PY2:
        return
    try:
        import locale
        fs_enc = codecs.lookup(locale.getpreferredencoding()).name
    except Exception:
        fs_enc = 'ascii'
    if fs_enc != 'ascii':
        return

    extra = ''
    if os.name == 'posix':
        import subprocess
        try:
            rv = subprocess.Popen(['locale', '-a'], stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE).communicate()[0]
        except OSError:
            rv = b''
        good_locales = set()
        has_c_utf8 = False

        # Make sure we're operating on text here.
        if isinstance(rv, bytes):
            rv = rv.decode('ascii', 'replace')

        for line in rv.splitlines():
            locale = line.strip()
            if locale.lower().endswith(('.utf-8', '.utf8')):
                good_locales.add(locale)
                if locale.lower() in ('c.utf8', 'c.utf-8'):
                    has_c_utf8 = True

        extra += '\n\n'
        if not good_locales:
            extra += (
                'Additional information: on this system no suitable UTF-8\n'
                'locales were discovered.  This most likely requires resolving\n'
                'by reconfiguring the locale system.'
            )
        elif has_c_utf8:
            extra += (
                'This system supports the C.UTF-8 locale which is recommended.\n'
                'You might be able to resolve your issue by exporting the\n'
                'following environment variables:\n\n'
                '    export LC_ALL=C.UTF-8\n'
                '    export LANG=C.UTF-8'
            )
        else:
            extra += (
                'This system lists a couple of UTF-8 supporting locales that\n'
                'you can pick from.  The following suitable locales were\n'
                'discovered: %s'
            ) % ', '.join(sorted(good_locales))

        bad_locale = None
        for locale in os.environ.get('LC_ALL'), os.environ.get('LANG'):
            if locale and locale.lower().endswith(('.utf-8', '.utf8')):
                bad_locale = locale
            if locale is not None:
                break
        if bad_locale is not None:
            extra += (
                '\n\nClick discovered that you exported a UTF-8 locale\n'
                'but the locale system could not pick up from it because\n'
                'it does not exist.  The exported locale is "%s" but it\n'
                'is not supported'
            ) % bad_locale

    raise RuntimeError(
        'Click will abort further execution because Python 3 was'
        ' configured to use ASCII as encoding for the environment.'
        ' Consult https://click.palletsprojects.com/en/7.x/python3/ for'
        ' mitigation steps.' + extra
    )