Download virtualenv package from pypi and return response that can be
    read and written to file

    :param str version: version to download or latest version if None
    :param str dldir: directory to download into or None for cwd
500801
def download_virtualenv(version, dldir=None):
    '''
    
    '''
    dl_url = PYPI_DL_URL.format(VER=version)
    filename = basename(dl_url)
    if dldir:
        dl_path = join(dldir, filename)
    else:
        dl_path = filename
    data = urlopen(PYPI_DL_URL.format(VER=version))
    with open(dl_path, 'wb') as fh:
        fh.write(data.read())
    return dl_path
451600
def get_glibc_version():
    
    # TODO: Look into a nicer way to get the version
    try:
        out = subprocess.Popen(['ldd', '--version'],
                               stdout=subprocess.PIPE).communicate()[0]
    except OSError:
        return
    match = re.search('([0-9]+)\.([0-9]+)\.?[0-9]*', out)
    try:
        return map(int, match.groups())
    except AttributeError:
        return
1019149
def cublasGetVersion(handle):
    
    
    version = ctypes.c_int()
    status = _libcublas.cublasGetVersion_v2(handle, ctypes.byref(version))
    cublasCheckStatus(status)
    return version.value
1034818
def read_version():
    """"""
    finder = VersionFinder()
    finder.visit(ast.parse(local_file('curdling', 'version.py')))
    return finder.version
174700
def pypi_module_version_is_available(module, version):
    ""
    # returns True/False (or None if failed to execute the check)

    # using a hack that when passing "module==" w/ no version number to pip
    # it "fails" and returns all the available versions in stderr
    try:
        cmd = f"pip install {module}=="
        result = subprocess.run(cmd.split(), shell=False, check=False,
                                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    except Exception as e:
        print(f"Error: {e}")
        return None
    else:
        if result.returncode == 1 and result.stderr:
            output = result.stderr.decode('utf-8')
            return True if version in output else False
        else:
            print(f"Some error in {cmd}")
            return None
825407
def create_handler_venv(self):
        
        import subprocess

        # We will need the currenv venv to pull Zappa from
        current_venv = self.get_current_venv()

        # Make a new folder for the handler packages
        ve_path = os.path.join(os.getcwd(), 'handler_venv')

        if os.sys.platform == 'win32':
            current_site_packages_dir = os.path.join(current_venv, 'Lib', 'site-packages')
            venv_site_packages_dir = os.path.join(ve_path, 'Lib', 'site-packages')
        else:
            current_site_packages_dir = os.path.join(current_venv, 'lib', get_venv_from_python_version(), 'site-packages')
            venv_site_packages_dir = os.path.join(ve_path, 'lib', get_venv_from_python_version(), 'site-packages')

        if not os.path.isdir(venv_site_packages_dir):
            os.makedirs(venv_site_packages_dir)

        # Copy zappa* to the new virtualenv
        zappa_things = [z for z in os.listdir(current_site_packages_dir) if z.lower()[:5] == 'zappa']
        for z in zappa_things:
            copytree(os.path.join(current_site_packages_dir, z), os.path.join(venv_site_packages_dir, z))

        # Use pip to download zappa's dependencies. Copying from current venv causes issues with things like PyYAML that installs as yaml
        zappa_deps = self.get_deps_list('zappa')
        pkg_list = ['{0!s}=={1!s}'.format(dep, version) for dep, version in zappa_deps]

        # Need to manually add setuptools
        pkg_list.append('setuptools')
        command = ["pip", "install", "--quiet", "--target", venv_site_packages_dir] + pkg_list

        # This is the recommended method for installing packages if you don't
        # to depend on `setuptools`
        # https://github.com/pypa/pip/issues/5240#issuecomment-381662679
        pip_process = subprocess.Popen(command, stdout=subprocess.PIPE)
        # Using communicate() to avoid deadlocks
        pip_process.communicate()
        pip_return_code = pip_process.returncode

        if pip_return_code:
          raise EnvironmentError("Pypi lookup failed")

        return ve_path
845398
def get_version(name, dirs=None, config=None):
    
    if dirs:
        p = _get_program_file(dirs)
    else:
        p = tz.get_in(["resources", "program_versions"], config)
    if p:
        with open(p) as in_handle:
            for line in in_handle:
                prog, version = line.rstrip().split(",")
                if prog == name and version:
                    return version
        raise KeyError("Version information not found for %s in %s" % (name, p))
572517
def get_version():
    
    if not os.path.exists(VERSION_FILE):
        raise VersionNotFound(VERSION_FILE + " does not exist")
    fp = open(VERSION_FILE, "r")
    vline = None
    for x in fp.readlines():
        x = x.rstrip()
        if not x:
            continue
        if not x.startswith("__version__"):
            continue

        vline = x.split('=')[1]
        break
    if not vline:
        raise VersionNotFound("version file present but has no contents")

    return vline.strip().rstrip().replace("'", '')
858194
def download_file(filename: str):
    

    project = cd.project.get_internal_project()
    source_directory = project.source_directory if project else None

    if not filename or not project or not source_directory:
        return '', 204

    path = os.path.realpath(os.path.join(
        source_directory,
        '..',
        '__cauldron_downloads',
        filename
    ))

    if not os.path.exists(path):
        return '', 204

    return flask.send_file(path, mimetype=mimetypes.guess_type(path)[0])
704607
def download_cli(directory, master_token=None, member=None, access_token=None,
                 source=None, project_data=False, max_size='128m',
                 verbose=False, debug=False, memberlist=None,
                 excludelist=None, id_filename=False):
    
    return download(directory, master_token, member, access_token, source,
                    project_data, max_size, verbose, debug, memberlist,
                    excludelist, id_filename)
948217
def get_version():
    
    contents = read(os.path.join(PATH_BASE, 'srptools', '__init__.py'))
    version = re.search('VERSION = \(([^)]+)\)', contents)
    version = version.group(1).replace(', ', '.').strip()
    return version
255937
def download_source(version):
        
        local_filename = 'v{}.zip'.format(Spark.svm_version_path(version))
        Spark.download(Spark.spark_versions()['v{}'.format(version)], local_filename)
330999
def package_version():
    """"""
    version_path = os.path.join(os.path.dirname(__file__), 'version.py')

    version = read_version(version_path)
    write_version(version_path, version)

    return version
1041124
def get_pypi_version():
    
    try:
        response = requests.get(PYPI_URL, timeout=HALF_SECOND_TIMEOUT)
        response.raise_for_status()
        data = response.json()
        version_str = data["info"]["version"]
        return _parse_version_str(version_str)
    except requests.exceptions.ConnectionError:
        raise VersionException(UNABLE_TO_ACCESS_PYPI + " Failed to connect.")
    except requests.exceptions.Timeout:
        raise VersionException(UNABLE_TO_ACCESS_PYPI + " Timeout")
330241
def _check_pypi_version(self):
        
        try:
            check_version()
        except VersionException as err:
            print(str(err), file=sys.stderr)
            time.sleep(TWO_SECONDS)
409658
def load_version(fname: str) -> str:
    
    if not os.path.exists(fname):
        logger.warning("No version file found. Defaulting to 1.0.3")
        return "1.0.3"
    with open(fname) as inp:
        return inp.read().strip()
230826
def version(self):
        '''
        
        '''
        url = "http://{master_addr}:{master_port}/dir/status".format(
            master_addr=self.master_addr,
            master_port=self.master_port)
        data = self.conn.get_data(url)
        response_data = json.loads(data)
        return response_data.get("Version")