Create a package finder appropriate to this install command.
        This method is meant to be overridden by subclasses, not
        called directly.
976
def _build_package_finder(self, options, index_urls):
        
        return PackageFinder(find_links=options.find_links,
                             index_urls=index_urls,
                             use_mirrors=options.use_mirrors,
                             mirrors=options.mirrors)
766932
def install_packages(packages,
                     what_for='for a complete setup to work properly'):
    '''
    '''
    res = True
    non_installed_packages = _non_installed(packages)
    packages_str = '  '.join(non_installed_packages)
    if non_installed_packages:
        with quiet():
            dpkg = _has_dpkg()
        hint = '  (You may have to install them manually)'
        do_install = False
        go_on = True
        if dpkg:
            if _is_sudoer('Want to install dpkg packages'):
                do_install = True
            else:
                do_install is False  # cannot install anything
                info = yellow(' '.join([
                    'This deb packages are missing to be installed',
                    flo("{what_for}: "), ', '.join(non_installed_packages),
                ]))
                question = '  Continue anyway?'
                go_on = query_yes_no(info + hint + question, default='no')
        else:
            # dpkg == False, unable to determine if packages are installed
            do_install = False  # cannot install anything
            info = yellow(' '.join([
                flo('Required {what_for}: '),
                ', '.join(non_installed_packages),
            ]))
            go_on = query_yes_no(info + hint + '  Continue?', default='yes')
        if not go_on:
            sys.exit('Abort')
        if do_install:
            command = flo('sudo  apt-get install {packages_str}')
            res = run(command).return_code == 0
    return res
1191023
def installed?(package)
      fail LookupFailed, 'No supported package tool found.' if tool.nil?

      cmd = tools[tool]
      fail LookupFailed, "Package tool '#{cmd}' not found." if command?(cmd).nil?

      send tool, package
    end
798851
def setup_packages():
    '''
    
    '''

    # protect the user in case they run python setup.py not from root directory
    src_path = dirname(abspath(sys.argv[0]))
    old_path = os.getcwd()
    os.chdir(src_path)
    sys.path.insert(0, src_path)

    # create a list of the python extensions
    python_dirs = ["theory/python_bindings",
                   "mocks/python_bindings"]
    extensions = generate_extensions(python_dirs)

    # check requirement for extensions and set the compiler if specified
    # in command-line
    common_dict = requirements_check()

    # Some command options require headers/libs to be generated
    # so that the following dirs_patters supplies them.
    if install_required():
        from distutils.sysconfig import get_config_var
        if get_config_var('SHLIB_EXT') != '".so"' and version_info[0] == 2:
            msg = "The extensions all get the `.so` automatically. "\
                  "However, python expects the extension to be `{0}`"\
                  .format(get_config_var('SHLIB_EXT'))
            raise ValueError(msg)
        
        # global variable compiler is set if passed in
        # command-line
        extra_string = ''
        if compiler != '':
            extra_string = 'CC={0}'.format(compiler)

        command = "make libs {0}".format(extra_string)
        run_command(command)
        
    else:
        # not installing. Check if creating source distribution
        # in that case run distclean to delete auto-generated C
        # files
        if 'sdist' in sys.argv:
            command = "make distclean"
            run_command(command)
            

    # find all the data-files required.
    # Now the lib + associated header files have been generated
    # and put in lib/ and include/
    # This step must run after ``make install``
    dirs_patterns = {'theory/tests/data': ['*.ff', '*.txt',
                                              '*.txt.gz', '*.dat'],
                     'mocks/tests/data': ['*.ff', '*.txt',
                                             '*.txt.gz', '*.dat'],
                     'theory/tests': ['Mr19*', 'bins*', 'cmass*'],
                     'mocks/tests': ['Mr19*', 'bins*', 'angular_bins*'],
                     'include': ['count*.h'],
                     'lib': ['libcount*.a']
                     }
    data_files = []
    for d in dirs_patterns:
        patterns = dirs_patterns[d]
        f = recursive_glob(d, patterns)
        data_files.extend(f)

    # change them to be relative to package dir rather than root
    data_files = ["../{0}".format(d) for d in data_files]
    long_description = read_text_file('README.rst')
    min_np_major = int(common_dict['MIN_NUMPY_MAJOR'][0])
    min_np_minor = int(common_dict['MIN_NUMPY_MINOR'][0])

    # All book-keeping is done.
    # base_url = "https://github.com/manodeep/Corrfunc"
    classifiers = ['Development Status :: 4 - Beta',
                   'Intended Audience :: Developers',
                   'Intended Audience :: Science/Research',
                   'License :: OSI Approved :: MIT License',
                   'Natural Language :: English',
                   'Operating System :: POSIX',
                   'Programming Language :: C',
                   'Programming Language :: Python',
                   'Programming Language :: Python :: 2',
                   'Programming Language :: Python :: 2.7',
                   'Programming Language :: Python :: 3',
                   'Programming Language :: Python :: 3.4',
                   'Programming Language :: Python :: 3.5',
                   'Programming Language :: Python :: 3.6']
    metadata = dict(
            name=projectname,
            version=version,
            author='Manodeep Sinha',
            author_email='manodeep@gmail.com',
            maintainer='Manodeep Sinha',
            maintainer_email='manodeep@gmail.com',
            url=base_url,
            download_url='{0}/archive/{1}-{2}.tar.gz'.format(
                    base_url, projectname, version),
            description='Blazing fast correlation functions on the CPU',
            long_description=long_description,
            classifiers=classifiers,
            license='MIT',
            # Solaris might work, Windows will almost certainly not work
            platforms=["Linux", "Mac OSX", "Unix"],
            keywords=['correlation functions', 'simulations',
                      'surveys', 'galaxies'],
            provides=[projectname],
            packages=find_packages(),
            ext_package=projectname,
            ext_modules=extensions,
            package_data={'': data_files},
            include_package_data=True,
            setup_requires=['setuptools',
                            'numpy>={0}.{1}'.format(min_np_major,
                                                    min_np_minor)],
            install_requires=['numpy>={0}.{1}'.format(min_np_major,
                                                      min_np_minor),
                              'future',
                              'wurlitzer'],
            python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, <4',
            zip_safe=False,
            cmdclass={'build_ext': BuildExtSubclass})

    # Now the actual setup
    try:
        setup(**metadata)
    finally:
        del sys.path[0]
        os.chdir(old_path)

    return
1301215
def create_package(self):
        

        # Create the Lambda zip package (includes project and virtualenvironment)
        # Also define the path the handler file so it can be copied to the zip
        # root for Lambda.
        current_file = os.path.dirname(os.path.abspath(
            inspect.getfile(inspect.currentframe())))
        handler_file = os.sep.join(current_file.split(os.sep)[
                                   0:-2]) + os.sep + 'handler.py'
        exclude = self.zappa_settings[self.api_stage].get('exclude', []) + ['static', 'media']
        self.zip_path = self.zappa.create_lambda_zip(
                self.lambda_name,
                handler_file=handler_file,
                use_precompiled_packages=self.zappa_settings[self.api_stage].get('use_precompiled_packages', True),
                exclude=exclude
            )

        # Add this environment's Django settings to that zipfile
        with open(self.settings_file, 'r') as f:
            contents = f.read()
            all_contents = contents
            if not self.zappa_settings[self.api_stage].has_key('domain'):
                script_name = self.api_stage
            else:
                script_name = ''

            all_contents = all_contents + \
                '\n# Automatically added by Zappa:\nSCRIPT_NAME=\'/' + script_name + '\'\n'
            f.close()

        with open('zappa_settings.py', 'w') as f:
            f.write(all_contents)

        with zipfile.ZipFile(self.zip_path, 'a') as lambda_zip:
            lambda_zip.write('zappa_settings.py', 'zappa_settings.py')
            lambda_zip.close()

        os.unlink('zappa_settings.py')
557972
def install_jspackage(package_name, version, modulesdir):
    
    if not version:
        version = ''

    requirements = _resolve_dependencies(package_name, version)
    print('Packages going to be installed: {0}'.format(', '.join(
        '{0}->{1}'.format(*i) for i in requirements
    )))

    downloads = {}
    for dependency_name, _, version_info in requirements:
        try:
            downloads[dependency_name] = version_info['dist']['tarball']
        except KeyError:
            raise JSPackageInstallError('Unable to detect a supported download url for package',
                                        error_code=3)

    for dependency_name, download_url in downloads.items():
        tarball = BytesIO()
        print('Fetching {0}'.format(download_url), end='')
        with closing(urlopen(download_url)) as data:
            chunk = data.read(1024)
            while chunk:
                print('.', end='')
                tarball.write(chunk)
                chunk = data.read(1024)
        print('')

        tarball.seek(0)
        with closing(tarfile.open(fileobj=tarball)) as tb:
            dest = os.path.join(modulesdir, dependency_name)
            tmpdir = tempfile.mkdtemp()
            try:
                tb.extractall(tmpdir)
                shutil.rmtree(os.path.abspath(dest), ignore_errors=True)
                shutil.move(os.path.join(tmpdir, 'package'),
                            os.path.abspath(dest))
            finally:
                shutil.rmtree(tmpdir)

    print('Installing {0} in {1} Done!'.format(package_name, modulesdir))
1314166
def package_install(name, **kwargs):
    '''
    
    '''
    cmd = DETAILS['url']+'package/install/'+name
    if kwargs.get('version', False):
        cmd += '/'+kwargs['version']
    else:
        cmd += '/1.0'
    r = salt.utils.http.query(cmd, decode_type='json', decode=True)
    return r['dict']
838106
function createConfIndex() {
        requireConf.baseUrl = requireConf.baseUrl.replace( /\/$/, '' ) + '/';
        var descSorter = createDescSorter();

        // createPathsIndex
        pathsIndex = kv2List( requireConf.paths );
        pathsIndex.sort( descSorter );

        // createMappingIdIndex
        mappingIdIndex = kv2List( requireConf.map );
        mappingIdIndex.sort( descSorter );
        each(
            mappingIdIndex,
            function ( item ) {
                var key = item.k;
                item.v = kv2List( item.v );
                item.v.sort( descSorter );
                item.reg = key === '*'
                    ? /^/
                    : createPrefixRegexp( key );
            }
        );

        // createPackagesIndex
        packagesIndex = [];
        each(
            requireConf.packages,
            function ( packageConf ) {
                var pkg = packageConf;
                if ( typeof packageConf === 'string' ) {
                    pkg = {
                        name: packageConf.split('/')[ 0 ],
                        location: packageConf,
                        main: 'main'
                    };
                }

                pkg.location = pkg.location || pkg.name;
                pkg.main = (pkg.main || 'main').replace(/\.js$/i, '');
                packagesIndex.push( pkg );
            }
        );
        packagesIndex.sort( createDescSorter( 'name' ) );

        // createUrlArgsIndex
        urlArgsIndex = kv2List( requireConf.urlArgs );
        urlArgsIndex.sort( descSorter );
    }
120558
def packageDescriptor(self, dir=os.getcwd(), args=[]):
		
		
		# Verify that an Unreal project or plugin exists in the specified directory
		descriptor = self.getDescriptor(dir)
		
		# Perform the packaging step
		if self.isProject(descriptor):
			self.packageProject(dir, args[0] if len(args) > 0 else 'Shipping', args[1:])
		else:
			self.packagePlugin(dir, args)
144804
def finder(package):
    
    if package in _finder_cache:
        result = _finder_cache[package]
    else:
        if package not in sys.modules:
            __import__(package)
        module = sys.modules[package]
        path = getattr(module, '__path__', None)
        if path is None:
            raise DistlibException('You cannot get a finder for a module, '
                                   'only for a package')
        loader = getattr(module, '__loader__', None)
        finder_maker = _finder_registry.get(type(loader))
        if finder_maker is None:
            raise DistlibException('Unable to locate finder for %r' % package)
        result = finder_maker(module)
        _finder_cache[package] = result
    return result
89228
def install_packages(self):
        
        installs, upgraded = [], []
        for inst in (self.dep_install + self.install):
            package = (self.tmp_path + inst).split()
            pkg_ver = "{0}-{1}".format(split_package(inst)[0],
                                       split_package(inst)[1])
            self.checksums(inst)
            if GetFromInstalled(split_package(inst)[0]).name():
                print("[ {0}upgrading{1} ] --> {2}".format(
                    self.meta.color["YELLOW"], self.meta.color["ENDC"], inst))
                upgraded.append(pkg_ver)
                if "--reinstall" in self.flag:
                    PackageManager(package).upgrade("--reinstall")
                else:
                    PackageManager(package).upgrade("--install-new")
            else:
                print("[ {0}installing{1} ] --> {2}".format(
                    self.meta.color["GREEN"], self.meta.color["ENDC"], inst))
                installs.append(pkg_ver)
                PackageManager(package).upgrade("--install-new")
        return [installs, upgraded]
951044
def package_install(name, **kwargs):
    '''
    
    '''
    DETAILS = _load_state()
    if kwargs.get('version', False):
        version = kwargs['version']
    else:
        version = '1.0'
    DETAILS['packages'][name] = version
    _save_state(DETAILS)
    return {name: version}
106885
def create(self, name=None, prefix=None, pkgs=None, channels=None):
        """"""
        logger.debug(str((prefix, pkgs, channels)))

        # TODO: Fix temporal hack
        if (not pkgs or (not isinstance(pkgs, (list, tuple)) and
                         not is_text_string(pkgs))):
            raise TypeError('must specify a list of one or more packages to '
                            'install into new environment')

        cmd_list = ['create', '--yes', '--json', '--mkdir']
        if name:
            ref = name
            search = [os.path.join(d, name) for d in
                      self.info().communicate()[0]['envs_dirs']]
            cmd_list.extend(['--name', name])
        elif prefix:
            ref = prefix
            search = [prefix]
            cmd_list.extend(['--prefix', prefix])
        else:
            raise TypeError('must specify either an environment name or a '
                            'path for new environment')

        if any(os.path.exists(prefix) for prefix in search):
            raise CondaEnvExistsError('Conda environment {0} already '
                                      'exists'.format(ref))

        # TODO: Fix temporal hack
        if isinstance(pkgs, (list, tuple)):
            cmd_list.extend(pkgs)
        elif is_text_string(pkgs):
            cmd_list.extend(['--file', pkgs])

        # TODO: Check if correct
        if channels:
            cmd_list.extend(['--override-channels'])

            for channel in channels:
                cmd_list.extend(['--channel'])
                cmd_list.extend([channel])

        return self._call_and_parse(cmd_list)
670271
def install():
    
    # check installed package
    print("Compare to '%s' ..." % _DST)
    need_install_flag = check_need_install()
    if not need_install_flag:
        print("\tpackage is up-to-date, no need to install.")
        return
    print("Difference been found, start installing ...")

    # remove __pycache__ folder and *.pyc file
    print("Remove *.pyc file ...")
    pyc_folder_list = list()
    for root, _, basename_list in os.walk(_ROOT):
        if os.path.basename(root) == "__pycache__":
            pyc_folder_list.append(root)

    for folder in pyc_folder_list:
        shutil.rmtree(folder)
    print("\tall *.pyc file has been removed.")

    # install this package to all python version
    print("Uninstall %s from %s ..." % (_PACKAGE_NAME, _DST))
    try:
        shutil.rmtree(_DST)
        print("\tSuccessfully uninstall %s" % _PACKAGE_NAME)
    except Exception as e:
        print("\t%s" % e)

    print("Install %s to %s ..." % (_PACKAGE_NAME, _DST))
    shutil.copytree(_ROOT, _DST)
    print("\tComplete!")
161897
def ensure_source_package_dir(nb_path, pkg_name):
    """"""

    pkg_path = join(dirname(nb_path), pkg_name)

    makedirs(join(pkg_path,'notebooks'),exist_ok=True)
    makedirs(join(pkg_path, 'docs'), exist_ok=True)

    return pkg_path
1347918
def find(self, package, **kwargs):
        
        if not exists(package):
            return None
        name, path = None, None
        enforce_init = kwargs.pop('enforce_init', True)
        if isdir(package):
            if isfile(join(package, '__init__.py')) or not enforce_init:
                name, path = basename(package), package
        elif isfile(package) and package.endswith('.py'):
            name, path = splitext(basename(package))[0], package
        if name and path:
            return PackageSpec(name, path)
        return None
163026
def find_package(name: str) -> Tuple[Optional[Path], Path]:
    
    module = name.split(".")[0]
    loader = pkgutil.get_loader(module)
    if name == "__main__" or loader is None:
        package_path = Path.cwd()
    else:
        if hasattr(loader, 'get_filename'):
            filename = loader.get_filename(module)  # type: ignore
        else:
            __import__(name)
            filename = sys.modules[name].__file__
        package_path = Path(filename).resolve().parent
        if hasattr(loader, 'is_package'):
            is_package = loader.is_package(module)  # type: ignore
            if is_package:
                package_path = Path(package_path).resolve().parent
    sys_prefix = Path(sys.prefix).resolve()
    try:
        package_path.relative_to(sys_prefix)
    except ValueError:
        return None, package_path
    else:
        return sys_prefix, package_path