Test whether the current python environment is the correct lore env.

    :return:  :any:`True` if the environment is launched
    :rtype: bool
559868
def launched():
    
    if not PREFIX:
        return False

    return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)
909132
def environment(**options):
    
    env = Environment(**options)
    env.globals.update({
        'static': staticfiles_storage.url,
        'url': reverse,
    })
    env.globals.update(context_processors.environment())
    return env
1017961
protected function isInCurrentEnv(string $currentEnv = '*', array $envList = []): bool
    {
        if (in_array('*', $envList, false)) {
            return true;
        }

        if (in_array($currentEnv, $envList, false)) {
            return true;
        }

        return false;
    }
801308
def validate():
    
    if not os.path.exists(os.path.join(ROOT, APP, '__init__.py')):
        message = ansi.error() + ' Python module not found.'
        if os.environ.get('LORE_APP') is None:
            message += ' $LORE_APP is not set. Should it be different than "%s"?' % APP
        else:
            message += ' $LORE_APP is set to "%s". Should it be different?' % APP
        sys.exit(message)

    if exists():
        return

    if len(sys.argv) > 1:
        command = sys.argv[1]
    else:
        command = 'lore'
    sys.exit(
        ansi.error() + ' %s is only available in lore '
                       'app directories (missing %s)' % (
            ansi.bold(command),
            ansi.underline(VERSION_PATH)
        )
    )
17190
def log_env_gte(desired):
    
    return LOGLEVELS.get(check_log_env()) >= LOGLEVELS.get(desired, LOGLEVELS[TEST])
1056620
def _is_env_per_bucket():
    '''
    
    '''

    buckets = _get_buckets()
    if isinstance(buckets, dict):
        return True
    elif isinstance(buckets, list):
        return False
    else:
        raise ValueError('Incorrect s3.buckets type given in config')
416214
def _check_virtualenv():
    
    from os import waitpid
    from subprocess import Popen, PIPE
    penvs = Popen("source /usr/local/bin/virtualenvwrapper.sh; workon",
                 shell=True, executable="/bin/bash", stdout=PIPE, stderr=PIPE)
    waitpid(penvs.pid, 0)
    envs = penvs.stdout.readlines()
    enverr = penvs.stderr.readlines()
    result = (settings.venv + '\n') in envs and len(enverr) == 0

    vms("Find virtualenv: {}".format(' '.join(envs).replace('\n', '')))
    vms("Find virtualenv | stderr: {}".format(' '.join(enverr)))
    
    if not result:
        info(envs)
        err("The virtualenv '{}' does not exist; can't use CI server.".format(settings.venv))
        if len(enverr) > 0:
            map(err, enverr)
    return result
123650
function checkEnv() {
        async.series([
            function(cb) {
                childProcess.exec(
                    'python -c "import django; print(django.get_version())"',
                    function(err, version) {
                        if (err || !/^1\.7/.test(version)) {
                            return cb(new Error(
                                'Django 1.7 environment is not working'
                            ));
                        }
                        cb();
                    });
            }
        ], function(err) {
            if (err) {
                console.error(chalk.red('\nFATAL: ' + err.message +
                    '\n'));
            }
        });
    }
798086
def check_chef_env(chef_env_name)
      return unless chef_env_name
      Chef::Environment.load(chef_env_name) if chef_env_name
    rescue Net::HTTPServerException => e
      raise unless e.to_s =~ /^404/
      ui.info 'Creating chef environment ' + chef_env_name
      chef_env = Chef::Environment.new
      chef_env.name(chef_env_name)
      chef_env.create
      chef_env
    end
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
420576
def is_virtual_environment(path):
    
    if not path.is_dir():
        return False
    for bindir_name in ('bin', 'Scripts'):
        for python in path.joinpath(bindir_name).glob('python*'):
            try:
                exeness = python.is_file() and os.access(str(python), os.X_OK)
            except OSError:
                exeness = False
            if exeness:
                return True
    return False
456138
def launch():
    
    if launched():
        check_version()
        os.chdir(ROOT)
        return

    if not os.path.exists(BIN_LORE):
        missing = ' %s virtualenv is missing.' % APP
        if '--launched' in sys.argv:
            sys.exit(ansi.error() + missing + ' Please check for errors during:\n $ lore install\n')
        else:
            print(ansi.warning() + missing)
            import lore.__main__
            lore.__main__.install(None, None)

    reboot('--env-launched')
705108
def virt_env(self):
        
        if self._virt_env is None:
            self._virt_env = self._create_virt_env()
        return self._virt_env
1076584
def cdk_module_matches_env(env_name, env_config, env_vars):
    """"""
    if env_config.get(env_name):
        current_env_config = env_config[env_name]
        if isinstance(current_env_config, type(True)) and current_env_config:
            return True
        if isinstance(current_env_config, six.string_types):
            (account_id, region) = current_env_config.split('/')
            if region == env_vars['AWS_DEFAULT_REGION']:
                boto_args = extract_boto_args_from_env(env_vars)
                sts_client = boto3.client(
                    'sts',
                    region_name=env_vars['AWS_DEFAULT_REGION'],
                    **boto_args
                )
                if sts_client.get_caller_identity()['Account'] == account_id:
                    return True
        if isinstance(current_env_config, dict):
            return True
    return False
1230345
def initialize_env(env_file=None, fail_silently=True, load_globally=True):
    
    data = {}
    data.update(os.environ)
    if env_file:
        data.update(read_file_values(env_file, fail_silently))
    
    if load_globally:
        os.environ.update(data)
    
    return Environment(env_dict=data)
1288536
def collect_environment(no_cache: bool = False) -> dict:
    
    global _env
    if _env is None or no_cache:
        _env = collect_environment_without_packages()
        _env["packages"] = collect_loaded_packages()
    return _env
242352
def env(var_name, default=False):
    
    try:
        value = os.environ[var_name]
        if str(value).strip().lower() in ['false', 'no', 'off' '0', 'none', 'null']:
            return None
        return value
    except:
        from traceback import format_exc
        msg = format_exc() + '\n' + "Unable to find the %s environment variable.\nUsing the value %s (the default) instead.\n" % (var_name, default)
        warnings.warn(msg)
        return default