text:
import distutils
import glob
import os
import sys
import textwrap
from os.path import curdir, join, pardir

import pytest

from pip._internal import pep425tags
from pip._internal.status_codes import ERROR
from pip._internal.utils.misc import rmtree
from tests.lib import (
    _create_svn_repo, _create_test_package, create_test_package_with_setup,
    need_bzr, need_mercurial, path_to_url, pyversion, pyversion_tuple,
    requirements_file,
)
from tests.lib.local_repos import local_checkout
from tests.lib.path import Path

def test_without_setuptools(script, data):
    script.pip("uninstall", "setuptools", "-y")
    result = script.run(
        "python", "-c",
        "import pip._internal; pip._internal.main(["
        "'install', "
        "'INITools==0.2', "
        "'-f', '%s', "
        "'--no-binary=:all:'])" % data.packages,
        expect_error=True,
    )
    assert (
        "Could not import setuptools which is required to install from a "
        "source distribution."
        in result.stderr
    )
    assert "Please install setuptools" in result.stderr

def test_with_setuptools_and_import_error(script, data):
    # Make sure we get an ImportError while importing setuptools
    setuptools_init_path = script.site_packages_path.join(
        "setuptools", "__init__.py")
    with open(setuptools_init_path, 'a') as f:
        f.write('\nraise ImportError("toto")')

    result = script.run(
        "python", "-c",
        "import pip._internal; pip._internal.main(["
        "'install', "
        "'INITools==0.2', "
        "'-f', '%s', "
        "'--no-binary=:all:'])" % data.packages,
        expect_error=True,
    )
    assert (
        "Could not import setuptools which is required to install from a "
        "source distribution."
        in result.stderr
    )
    assert "Traceback " in result.stderr
    assert "ImportError: toto" in result.stderr

@pytest.mark.network
def test_pip_second_command_line_interface_works(script, data):
    """
    Check if ``pip<PYVERSION>`` commands behaves equally
    """
    # On old versions of Python, urllib3/requests will raise a warning about
    # the lack of an SSLContext.
    kwargs = {}
    if pyversion_tuple < (2, 7, 9) or pyversion_tuple[:2] == (3, 3):
        kwargs['expect_stderr'] = True

    args = ['pip%s' % pyversion]
    args.extend(['install', 'INITools==0.2'])
    args.extend(['-f', data.packages])
    result = script.run(*args, **kwargs)
    egg_info_folder = (
        script.site_packages / 'INITools-0.2-py%s.egg-info' % pyversion
    )
    initools_folder = script.site_packages / 'initools'
    assert egg_info_folder in result.files_created, str(result)
    assert initools_folder in result.files_created, str(result)

def test_install_exit_status_code_when_no_requirements(script):
    """
    Test install exit status code when no requirements specified
    """
    result = script.pip('install', expect_error=True)
    assert "You must give at least one requirement to install" in result.stderr
    assert result.returncode == ERROR

def test_install_exit_status_code_when_blank_requirements_file(script):
    """
    Test install exit status code when blank requirements file specified
    """
    script.scratch_path.join("blank.txt").write("\n")
    script.pip('install', '-r', 'blank.txt')

@pytest.mark.network
def test_basic_install_from_pypi(script):
    """
    Test installing a package from PyPI.
    """
    result = script.pip('install', '-vvv', 'INITools==0.2')
    egg_info_folder = (
        script.site_packages / 'INITools-0.2-py%s.egg-info' % pyversion
    )
    initools_folder = script.site_packages / 'initools'
    assert egg_info_folder in result.files_created, str(result)
    assert initools_folder in result.files_created, str(result)

    # Should not display where it's looking for files
    assert "Looking in indexes: " not in result.stdout
    assert "Looking in links: " not in result.stdout

def test_basic_editable_install(script):
    """
    Test editable installation.
    """
    result = script.pip('install', '-e', 'INITools==0.2', expect_error=True)
    assert (
        "INITools==0.2 should either be a path to a local project or a VCS url"
        in result.stderr
    )
    assert not result.files_created
    assert not result.files_updated

@pytest.mark.svn
def test_basic_install_editable_from_svn(script):
    """
    Test checking out from svn.
    """
    checkout_path = _create_test_package(script)
    repo_url = _create_svn_repo(script, checkout_path)
    result = script.pip(
        'install',
        '-e', 'svn+' + repo_url + '#egg=version-pkg'
    )
    result.assert_installed('version-pkg', with_files=['.svn'])

def _test_install_editable_from_git(script, tmpdir):
    """Test cloning from Git."""
    pkg_path = _create_test_package(script, name='testpackage', vcs='git')
    args = ['install', '-e', 'git+%s#egg=testpackage' % path_to_url(pkg_path)]
    result = script.pip(*args, **{"expect_error": True})
    result.assert_installed('testpackage', with_files=['.git'])

def test_basic_install_editable_from_git(script, tmpdir):
    _test_install_editable_from_git(script, tmpdir)

@pytest.mark.network
def test_install_editable_from_git_autobuild_wheel(
        script, tmpdir, common_wheels):
    script.pip('install', 'wheel', '--no-index', '-f', common_wheels)
    _test_install_editable_from_git(script, tmpdir)

@pytest.mark.network
def test_install_editable_uninstalls_existing(data, script, tmpdir):
    """
    Test that installing an editable uninstalls a previously installed
    non-editable version.
    https://github.com/pypa/pip/issues/1548
    https://github.com/pypa/pip/pull/1552
    """
    to_install = data.packages.join("pip-test-package-0.1.tar.gz")
    result = script.pip_install_local(to_install)
    assert 'Successfully installed pip-test-package' in result.stdout
    result.assert_installed('piptestpackage', editable=False)

    result = script.pip(
        'install', '-e',
        '%s#egg=pip-test-package' %
        local_checkout(
            'git+https://github.com/pypa/pip-test-package.git',
            tmpdir.join("cache"),
        ),
    )
    result.assert_installed('pip-test-package', with_files=['.git'])
    assert 'Found existing installation: pip-test-package 0.1' in result.stdout
    assert 'Uninstalling pip-test-package-' in result.stdout
    assert 'Successfully uninstalled pip-test-package' in result.stdout

def test_install_editable_uninstalls_existing_from_path(script, data):
    """
    Test that installing an editable uninstalls a previously installed
    non-editable version from path
    """
    to_install = data.src.join('simplewheel-1.0')
    result = script.pip_install_local(to_install)
    assert 'Successfully installed simplewheel' in result.stdout
    simple_folder = script.site_packages / 'simple'
    result.assert_installed('simple', editable=False)
    assert simple_folder in result.files_created, str(result.stdout)

    result = script.pip(
        'install', '-e',
        to_install,
    )
    install_path = script.site_packages / 'simplewheel.egg-link'
    assert install_path in result.files_created, str(result)
    assert 'Found existing installation: simplewheel 1.0' in result.stdout
    assert 'Uninstalling simplewheel-' in result.stdout
    assert 'Successfully uninstalled simplewheel' in result.stdout
    assert simple_folder in result.files_deleted, str(result.stdout)

@need_mercurial
def test_basic_install_editable_from_hg(script, tmpdir):
    """Test cloning from Mercurial."""
    pkg_path = _create_test_package(script, name='testpackage', vcs='hg')
    args = ['install', '-e', 'hg+%s#egg=testpackage' % path_to_url(pkg_path)]
    result = script.pip(*args, **{"expect_error": True})
    result.assert_installed('testpackage', with_files=['.hg'])

@need_mercurial
def test_vcs_url_final_slash_normalization(script, tmpdir):
    """
    Test that presence or absence of final slash in VCS URL is normalized.
    """
    pkg_path = _create_test_package(script, name='testpackage', vcs='hg')
    args = ['install', '-e', 'hg+%s/#egg=testpackage' % path_to_url(pkg_path)]
    result = script.pip(*args, **{"expect_error": True})
    result.assert_installed('testpackage', with_files=['.hg'])

@need_bzr
def test_install_editable_from_bazaar(script, tmpdir):
    """Test checking out from Bazaar."""
    pkg_path = _create_test_package(script, name='testpackage', vcs='bazaar')
    args = ['install', '-e', 'bzr+%s/#egg=testpackage' % path_to_url(pkg_path)]
    result = script.pip(*args, **{"expect_error": True})
    result.assert_installed('testpackage', with_files=['.bzr'])

@pytest.mark.network
@need_bzr
def test_vcs_url_urlquote_normalization(script, tmpdir):
    """
    Test that urlquoted characters are normalized for repo URL comparison.
    """
    script.pip(
        'install', '-e',
        '%s/#egg=django-wikiapp' %
        local_checkout(
            'bzr+http://bazaar.launchpad.net/%7Edjango-wikiapp/django-wikiapp'
            '/release-0.1',
            tmpdir.join("cache"),
        ),
    )

def test_basic_install_from_local_directory(script, data):
    """
    Test installing from a local directory.
    """
    to_install = data.packages.join("FSPkg")
    result = script.pip('install', to_install, expect_error=False)
    fspkg_folder = script.site_packages / 'fspkg'
    egg_info_folder = (
        script.site_packages / 'FSPkg-0.1.dev0-py%s.egg-info' % pyversion
    )
    assert fspkg_folder in result.files_created, str(result.stdout)
    assert egg_info_folder in result.files_created, str(result)

def test_basic_install_relative_directory(script, data):
    """
    Test installing a requirement using a relative path.
    """
    egg_info_file = (
        script.site_packages / 'FSPkg-0.1.dev0-py%s.egg-info' % pyversion
    )
    egg_link_file = (
        script.site_packages / 'FSPkg.egg-link'
    )
    package_folder = script.site_packages / 'fspkg'

    # Compute relative install path to FSPkg from scratch path.
    full_rel_path = data.packages.join('FSPkg') - script.scratch_path
    full_rel_url = (
        'file:' + full_rel_path.replace(os.path.sep, '/') + '#egg=FSPkg'
    )
    embedded_rel_path = script.scratch_path.join(full_rel_path)

    # For each relative path, install as either editable or not using either
    # URLs with egg links or not.
    for req_path in (full_rel_path, full_rel_url, embedded_rel_path):
        # Regular install.
        result = script.pip('install', req_path,
                            cwd=script.scratch_path)
        assert egg_info_file in result.files_created, str(result)
        assert package_folder in result.files_created, str(result)
        script.pip('uninstall', '-y', 'fspkg')

        # Editable install.
        result = script.pip('install', '-e' + req_path,
                            cwd=script.scratch_path)
        assert egg_link_file in result.files_created, str(result)
        script.pip('uninstall', '-y', 'fspkg')

def test_install_quiet(script, data):
    """
    Test that install -q is actually quiet.
    """
    # Apparently if pip install -q is not actually quiet, then it breaks
    # everything. See:
    #   https://github.com/pypa/pip/issues/3418
    #   https://github.com/docker-library/python/issues/83
    to_install = data.packages.join("FSPkg")
    result = script.pip('install', '-qqq', to_install, expect_error=False)
    assert result.stdout == ""
    assert result.stderr == ""

def test_hashed_install_success(script, data, tmpdir):
    """
    Test that installing various sorts of requirements with correct hashes
    works.

    Test file URLs and index packages (which become HTTP URLs behind the
    scenes).

    """
    file_url = path_to_url(
        (data.packages / 'simple-1.0.tar.gz').abspath)
    with requirements_file(
            'simple2==1.0 --hash=sha256:9336af72ca661e6336eb87bc7de3e8844d853e'
            '3848c2b9bbd2e8bf01db88c2c7\n'
            '{simple} --hash=sha256:393043e672415891885c9a2a0929b1af95fb866d6c'
            'a016b42d2e6ce53619b653'.format(simple=file_url),
            tmpdir) as reqs_file:
        script.pip_install_local('-r', reqs_file.abspath, expect_error=False)

def test_hashed_install_failure(script, tmpdir):
    """Test that wrong hashes stop installation.

    This makes sure prepare_files() is called in the course of installation
    and so has the opportunity to halt if hashes are wrong. Checks on various
    kinds of hashes are in test_req.py.

    """
    with requirements_file('simple2==1.0 --hash=sha256:9336af72ca661e6336eb87b'
                           'c7de3e8844d853e3848c2b9bbd2e8bf01db88c2c\n',
                           tmpdir) as reqs_file:
        result = script.pip_install_local('-r',
                                          reqs_file.abspath,
                                          expect_error=True)
    assert len(result.files_created) == 0

def test_install_from_local_directory_with_symlinks_to_directories(
        script, data):
    """
    Test installing from a local directory containing symlinks to directories.
    """
    to_install = data.packages.join("symlinks")
    result = script.pip('install', to_install, expect_error=False)
    pkg_folder = script.site_packages / 'symlinks'
    egg_info_folder = (
        script.site_packages / 'symlinks-0.1.dev0-py%s.egg-info' % pyversion
    )
    assert pkg_folder in result.files_created, str(result.stdout)
    assert egg_info_folder in result.files_created, str(result)

def test_install_from_local_directory_with_no_setup_py(script, data):
    """
    Test installing from a local directory with no 'setup.py'.
    """
    result = script.pip('install', data.root, expect_error=True)
    assert not result.files_created
    assert "is not installable. File 'setup.py' not found." in result.stderr

def test_editable_install_from_local_directory_with_no_setup_py(script, data):
    """
    Test installing from a local directory with no 'setup.py'.
    """
    result = script.pip('install', '-e', data.root, expect_error=True)
    assert not result.files_created
    assert "is not installable. File 'setup.py' not found." in result.stderr

@pytest.mark.skipif("sys.version_info >= (3,4)")
@pytest.mark.xfail
def test_install_argparse_shadowed(script):
    # When argparse is in the stdlib, we support installing it
    # even though that's pretty useless because older packages did need to
    # depend on it, and not having its metadata will cause pkg_resources
    # requirements checks to fail // trigger easy-install, both of which are
    # bad.
    # XXX: Note, this test hits the outside-environment check, not the
    # in-stdlib check, because our tests run in virtualenvs...
    result = script.pip('install', 'argparse>=1.4')
    assert "Not uninstalling argparse" in result.stdout

@pytest.mark.skipif("sys.version_info < (3,4)")
def test_upgrade_argparse_shadowed(script):
    # If argparse is installed - even if shadowed for imported - we support
    # upgrading it and properly remove the older versions files.
    script.pip('install', 'argparse==1.3')
    result = script.pip('install', 'argparse>=1.4')
    assert "Not uninstalling argparse" not in result.stdout

def test_install_curdir(script, data):
    """
    Test installing current directory ('.').
    """
    run_from = data.packages.join("FSPkg")
    # Python 2.4 Windows balks if this exists already
    egg_info = join(run_from, "FSPkg.egg-info")
    if os.path.isdir(egg_info):
        rmtree(egg_info)
    result = script.pip('install', curdir, cwd=run_from, expect_error=False)
    fspkg_folder = script.site_packages / 'fspkg'
    egg_info_folder = (
        script.site_packages / 'FSPkg-0.1.dev0-py%s.egg-info' % pyversion
    )
    assert fspkg_folder in result.files_created, str(result.stdout)
    assert egg_info_folder in result.files_created, str(result)

def test_install_pardir(script, data):
    """
    Test installing parent directory ('..').
    """
    run_from = data.packages.join("FSPkg", "fspkg")
    result = script.pip('install', pardir, cwd=run_from, expect_error=False)
    fspkg_folder = script.site_packages / 'fspkg'
    egg_info_folder = (
        script.site_packages / 'FSPkg-0.1.dev0-py%s.egg-info' % pyversion
    )
    assert fspkg_folder in result.files_created, str(result.stdout)
    assert egg_info_folder in result.files_created, str(result)

@pytest.mark.network
def test_install_global_option(script):
    """
    Test using global distutils options.
    (In particular those that disable the actual install action)
    """
    result = script.pip(
        'install', '--global-option=--version', "INITools==0.1",
        expect_stderr=True)
    assert '0.1\n' in result.stdout

def test_install_with_pax_header(script, data):
    """
    test installing from a tarball with pax header for python<2.6
    """
    script.pip('install', 'paxpkg.tar.bz2', cwd=data.packages)

def test_install_with_hacked_egg_info(script, data):
    """
    test installing a package which defines its own egg_info class
    """
    run_from = data.packages.join("HackedEggInfo")
    result = script.pip('install', '.', cwd=run_from)
    assert 'Successfully installed hackedegginfo-0.0.0\n' in result.stdout

@pytest.mark.network
def test_install_using_install_option_and_editable(script, tmpdir):
    """
    Test installing a tool using -e and --install-option
    """
    folder = 'script_folder'
    script.scratch_path.join(folder).mkdir()
    url = 'git+git://github.com/pypa/pip-test-package'
    result = script.pip(
        'install', '-e', '%s#egg=pip-test-package' %
        local_checkout(url, tmpdir.join("cache")),
        '--install-option=--script-dir=%s' % folder,
        expect_stderr=True)
    script_file = (
        script.venv / 'src' / 'pip-test-package' /
        folder / 'pip-test-package' + script.exe
    )
    assert script_file in result.files_created

@pytest.mark.network
@need_mercurial
def test_install_global_option_using_editable(script, tmpdir):
    """
    Test using global distutils options, but in an editable installation
    """
    url = 'hg+http://bitbucket.org/runeh/anyjson'
    result = script.pip(
        'install', '--global-option=--version', '-e',
        '%s@0.2.5#egg=anyjson' % local_checkout(url, tmpdir.join("cache")),
        expect_stderr=True)
    assert 'Successfully installed anyjson' in result.stdout

@pytest.mark.network
def test_install_package_with_same_name_in_curdir(script):
    """
    Test installing a package with the same name of a local folder
    """
    script.scratch_path.join("mock==0.6").mkdir()
    result = script.pip('install', 'mock==0.6')
    egg_folder = script.site_packages / 'mock-0.6.0-py%s.egg-info' % pyversion
    assert egg_folder in result.files_created, str(result)

mock100_setup_py = textwrap.dedent('''\
                        from setuptools import setup
                        setup(name='mock',
                              version='100.1')''')

def test_install_folder_using_dot_slash(script):
    """
    Test installing a folder using pip install ./foldername
    """
    script.scratch_path.join("mock").mkdir()
    pkg_path = script.scratch_path / 'mock'
    pkg_path.join("setup.py").write(mock100_setup_py)
    result = script.pip('install', './mock')
    egg_folder = script.site_packages / 'mock-100.1-py%s.egg-info' % pyversion
    assert egg_folder in result.files_created, str(result)

def test_install_folder_using_slash_in_the_end(script):
    r"""
    Test installing a folder using pip install foldername/ or foldername\
    """
    script.scratch_path.join("mock").mkdir()
    pkg_path = script.scratch_path / 'mock'
    pkg_path.join("setup.py").write(mock100_setup_py)
    result = script.pip('install', 'mock' + os.path.sep)
    egg_folder = script.site_packages / 'mock-100.1-py%s.egg-info' % pyversion
    assert egg_folder in result.files_created, str(result)

def test_install_folder_using_relative_path(script):
    """
    Test installing a folder using pip install folder1/folder2
    """
    script.scratch_path.join("initools").mkdir()
    script.scratch_path.join("initools", "mock").mkdir()
    pkg_path = script.scratch_path / 'initools' / 'mock'
    pkg_path.join("setup.py").write(mock100_setup_py)
    result = script.pip('install', Path('initools') / 'mock')
    egg_folder = script.site_packages / 'mock-100.1-py%s.egg-info' % pyversion
    assert egg_folder in result.files_created, str(result)

@pytest.mark.network
def test_install_package_which_contains_dev_in_name(script):
    """
    Test installing package from pypi which contains 'dev' in name
    """
    result = script.pip('install', 'django-devserver==0.0.4')
    devserver_folder = script.site_packages / 'devserver'
    egg_info_folder = (
        script.site_packages / 'django_devserver-0.0.4-py%s.egg-info' %
        pyversion
    )
    assert devserver_folder in result.files_created, str(result.stdout)
    assert egg_info_folder in result.files_created, str(result)

def test_install_package_with_target(script):
    """
    Test installing a package using pip install --target
    """
    target_dir = script.scratch_path / 'target'
    result = script.pip_install_local('-t', target_dir, "simple==1.0")
    assert Path('scratch') / 'target' / 'simple' in result.files_created, (
        str(result)
    )

    # Test repeated call without --upgrade, no files should have changed
    result = script.pip_install_local(
        '-t', target_dir, "simple==1.0", expect_stderr=True,
    )
    assert not Path('scratch') / 'target' / 'simple' in result.files_updated

    # Test upgrade call, check that new version is installed
    result = script.pip_install_local('--upgrade', '-t',
                                      target_dir, "simple==2.0")
    assert Path('scratch') / 'target' / 'simple' in result.files_updated, (
        str(result)
    )
    egg_folder = (
        Path('scratch') / 'target' / 'simple-2.0-py%s.egg-info' % pyversion)
    assert egg_folder in result.files_created, (
        str(result)
    )

    # Test install and upgrade of single-module package
    result = script.pip_install_local('-t', target_dir, 'singlemodule==0.0.0')
    singlemodule_py = Path('scratch') / 'target' / 'singlemodule.py'
    assert singlemodule_py in result.files_created, str(result)

    result = script.pip_install_local('-t', target_dir, 'singlemodule==0.0.1',
                                      '--upgrade')
    assert singlemodule_py in result.files_updated, str(result)

def test_install_package_with_root(script, data):
    """
    Test installing a package using pip install --root
    """
    root_dir = script.scratch_path / 'root'
    result = script.pip(
        'install', '--root', root_dir, '-f', data.find_links, '--no-index',
        'simple==1.0',
    )
    normal_install_path = (
        script.base_path / script.site_packages / 'simple-1.0-py%s.egg-info' %
        pyversion
    )
    # use distutils to change the root exactly how the --root option does it
    from distutils.util import change_root
    root_path = change_root(
        os.path.join(script.scratch, 'root'),
        normal_install_path
    )
    assert root_path in result.files_created, str(result)

    # Should show find-links location in output
    assert "Looking in indexes: " not in result.stdout
    assert "Looking in links: " in result.stdout

def test_install_package_with_prefix(script, data):
    """
    Test installing a package using pip install --prefix
    """
    prefix_path = script.scratch_path / 'prefix'
    result = script.pip(
        'install', '--prefix', prefix_path, '-f', data.find_links,
        '--no-binary', 'simple', '--no-index', 'simple==1.0',
    )

    rel_prefix_path = script.scratch / 'prefix'
    install_path = (
        distutils.sysconfig.get_python_lib(prefix=rel_prefix_path) /
        'simple-1.0-py{}.egg-info'.format(pyversion)
    )
    assert install_path in result.files_created, str(result)

def test_install_editable_with_prefix(script):
    # make a dummy project
    pkga_path = script.scratch_path / 'pkga'
    pkga_path.mkdir()
    pkga_path.join("setup.py").write(textwrap.dedent("""
        from setuptools import setup
        setup(name='pkga',
              version='0.1')
    """))

    if hasattr(sys, "pypy_version_info"):
        site_packages = os.path.join(
            'prefix', 'lib', 'python{}'.format(pyversion), 'site-packages')
    else:
        site_packages = distutils.sysconfig.get_python_lib(prefix='prefix')

    # make sure target path is in PYTHONPATH
    pythonpath = script.scratch_path / site_packages
    pythonpath.makedirs()
    script.environ["PYTHONPATH"] = pythonpath

    # install pkga package into the absolute prefix directory
    prefix_path = script.scratch_path / 'prefix'
    result = script.pip(
        'install', '--editable', pkga_path, '--prefix', prefix_path)

    # assert pkga is installed at correct location
    install_path = script.scratch / site_packages / 'pkga.egg-link'
    assert install_path in result.files_created, str(result)

def test_install_package_conflict_prefix_and_user(script, data):
    """
    Test installing a package using pip install --prefix --user errors out
    """
    prefix_path = script.scratch_path / 'prefix'
    result = script.pip(
        'install', '-f', data.find_links, '--no-index', '--user',
        '--prefix', prefix_path, 'simple==1.0',
        expect_error=True, quiet=True,
    )
    assert (
        "Can not combine '--user' and '--prefix'" in result.stderr
    )

# skip on win/py3 for now, see issue #782
@pytest.mark.skipif("sys.platform == 'win32' and sys.version_info >= (3,)")
def test_install_package_that_emits_unicode(script, data):
    """
    Install a package with a setup.py that emits UTF-8 output and then fails.

    Refs https://github.com/pypa/pip/issues/326
    """
    to_install = data.packages.join("BrokenEmitsUTF8")
    result = script.pip(
        'install', to_install, expect_error=True, expect_temp=True, quiet=True,
    )
    assert (
        'FakeError: this package designed to fail on install' in result.stdout
    )
    assert 'UnicodeDecodeError' not in result.stdout

def test_install_package_with_utf8_setup(script, data):
    """Install a package with a setup.py that declares a utf-8 encoding."""
    to_install = data.packages.join("SetupPyUTF8")
    script.pip('install', to_install)

def test_install_package_with_latin1_setup(script, data):
    """Install a package with a setup.py that declares a latin-1 encoding."""
    to_install = data.packages.join("SetupPyLatin1")
    script.pip('install', to_install)

def test_url_req_case_mismatch_no_index(script, data):
    """
    tar ball url requirements (with no egg fragment), that happen to have upper
    case project names, should be considered equal to later requirements that
    reference the project name using lower case.

    tests/data/packages contains Upper-1.0.tar.gz and Upper-2.0.tar.gz
    'requiresupper' has install_requires = ['upper']
    """
    Upper = '/'.join((data.find_links, 'Upper-1.0.tar.gz'))
    result = script.pip(
        'install', '--no-index', '-f', data.find_links, Upper, 'requiresupper'
    )

    # only Upper-1.0.tar.gz should get installed.
    egg_folder = script.site_packages / 'Upper-1.0-py%s.egg-info' % pyversion
    assert egg_folder in result.files_created, str(result)
    egg_folder = script.site_packages / 'Upper-2.0-py%s.egg-info' % pyversion
    assert egg_folder not in result.files_created, str(result)

def test_url_req_case_mismatch_file_index(script, data):
    """
    tar ball url requirements (with no egg fragment), that happen to have upper
    case project names, should be considered equal to later requirements that
    reference the project name using lower case.

    tests/data/packages3 contains Dinner-1.0.tar.gz and Dinner-2.0.tar.gz
    'requiredinner' has install_requires = ['dinner']

    This test is similar to test_url_req_case_mismatch_no_index; that test
    tests behaviour when using "--no-index -f", while this one does the same
    test when using "--index-url". Unfortunately this requires a different
    set of packages as it requires a prepared index.html file and
    subdirectory-per-package structure.
    """
    Dinner = '/'.join((data.find_links3, 'dinner', 'Dinner-1.0.tar.gz'))
    result = script.pip(
        'install', '--index-url', data.find_links3, Dinner, 'requiredinner'
    )

    # only Upper-1.0.tar.gz should get installed.
    egg_folder = script.site_packages / 'Dinner-1.0-py%s.egg-info' % pyversion
    assert egg_folder in result.files_created, str(result)
    egg_folder = script.site_packages / 'Dinner-2.0-py%s.egg-info' % pyversion
    assert egg_folder not in result.files_created, str(result)

def test_url_incorrect_case_no_index(script, data):
    """
    Same as test_url_req_case_mismatch_no_index, except testing for the case
    where the incorrect case is given in the name of the package to install
    rather than in a requirements file.
    """
    result = script.pip(
        'install', '--no-index', '-f', data.find_links, "upper",
    )

    # only Upper-2.0.tar.gz should get installed.
    egg_folder = script.site_packages / 'Upper-1.0-py%s.egg-info' % pyversion
    assert egg_folder not in result.files_created, str(result)
    egg_folder = script.site_packages / 'Upper-2.0-py%s.egg-info' % pyversion
    assert egg_folder in result.files_created, str(result)

def test_url_incorrect_case_file_index(script, data):
    """
    Same as test_url_req_case_mismatch_file_index, except testing for the case
    where the incorrect case is given in the name of the package to install
    rather than in a requirements file.
    """
    result = script.pip(
        'install', '--index-url', data.find_links3, "dinner",
        expect_stderr=True,
    )

    # only Upper-2.0.tar.gz should get installed.
    egg_folder = script.site_packages / 'Dinner-1.0-py%s.egg-info' % pyversion
    assert egg_folder not in result.files_created, str(result)
    egg_folder = script.site_packages / 'Dinner-2.0-py%s.egg-info' % pyversion
    assert egg_folder in result.files_created, str(result)

    # Should show index-url location in output
    assert "Looking in indexes: " in result.stdout
    assert "Looking in links: " not in result.stdout

@pytest.mark.network
def test_compiles_pyc(script):
    """
    Test installing with --compile on
    """
    del script.environ["PYTHONDONTWRITEBYTECODE"]
    script.pip("install", "--compile", "--no-binary=:all:", "INITools==0.2")

    # There are many locations for the __init__.pyc file so attempt to find
    #   any of them
    exists = [
        os.path.exists(script.site_packages_path / "initools/__init__.pyc"),
    ]

    exists += glob.glob(
        script.site_packages_path / "initools/__pycache__/__init__*.pyc"
    )

    assert any(exists)

@pytest.mark.network
def test_no_compiles_pyc(script):
    """
    Test installing from wheel with --compile on
    """
    del script.environ["PYTHONDONTWRITEBYTECODE"]
    script.pip("install", "--no-compile", "--no-binary=:all:", "INITools==0.2")

    # There are many locations for the __init__.pyc file so attempt to find
    #   any of them
    exists = [
        os.path.exists(script.site_packages_path / "initools/__init__.pyc"),
    ]

    exists += glob.glob(
        script.site_packages_path / "initools/__pycache__/__init__*.pyc"
    )

    assert not any(exists)

def test_install_upgrade_editable_depending_on_other_editable(script):
    script.scratch_path.join("pkga").mkdir()
    pkga_path = script.scratch_path / 'pkga'
    pkga_path.join("setup.py").write(textwrap.dedent("""
        from setuptools import setup
        setup(name='pkga',
              version='0.1')
    """))
    script.pip('install', '--editable', pkga_path)
    result = script.pip('list', '--format=freeze')
    assert "pkga==0.1" in result.stdout

    script.scratch_path.join("pkgb").mkdir()
    pkgb_path = script.scratch_path / 'pkgb'
    pkgb_path.join("setup.py").write(textwrap.dedent("""
        from setuptools import setup
        setup(name='pkgb',
              version='0.1',
              install_requires=['pkga'])
    """))
    script.pip('install', '--upgrade', '--editable', pkgb_path, '--no-index')
    result = script.pip('list', '--format=freeze')
    assert "pkgb==0.1" in result.stdout

def test_install_subprocess_output_handling(script, data):
    args = ['install', data.src.join('chattymodule')]

    # Regular install should not show output from the chatty setup.py
    result = script.pip(*args)
    assert 0 == result.stdout.count("HELLO FROM CHATTYMODULE")
    script.pip("uninstall", "-y", "chattymodule")

    # With --verbose we should show the output.
    # Only count examples with sys.argv[1] == egg_info, because we call
    # setup.py multiple times, which should not count as duplicate output.
    result = script.pip(*(args + ["--verbose"]))
    assert 1 == result.stdout.count("HELLO FROM CHATTYMODULE egg_info")
    script.pip("uninstall", "-y", "chattymodule")

    # If the install fails, then we *should* show the output... but only once,
    # even if --verbose is given.
    result = script.pip(*(args + ["--global-option=--fail"]),
                        expect_error=True)
    assert 1 == result.stdout.count("I DIE, I DIE")

    result = script.pip(*(args + ["--global-option=--fail", "--verbose"]),
                        expect_error=True)
    assert 1 == result.stdout.count("I DIE, I DIE")

def test_install_log(script, data, tmpdir):
    # test that verbose logs go to "--log" file
    f = tmpdir.join("log.txt")
    args = ['--log=%s' % f,
            'install', data.src.join('chattymodule')]
    result = script.pip(*args)
    assert 0 == result.stdout.count("HELLO FROM CHATTYMODULE")
    with open(f, 'r') as fp:
        # one from egg_info, one from install
        assert 2 == fp.read().count("HELLO FROM CHATTYMODULE")

def test_install_topological_sort(script, data):
    args = ['install', 'TopoRequires4', '--no-index', '-f', data.packages]
    res = str(script.pip(*args, expect_error=False))
    order1 = 'TopoRequires, TopoRequires2, TopoRequires3, TopoRequires4'
    order2 = 'TopoRequires, TopoRequires3, TopoRequires2, TopoRequires4'
    assert order1 in res or order2 in res, res

@pytest.mark.network
def test_install_wheel_broken(script, data, common_wheels):
    script.pip('install', 'wheel', '--no-index', '-f', common_wheels)
    res = script.pip(
        'install', '--no-index', '-f', data.find_links, '-f', common_wheels,
        'wheelbroken',
        expect_stderr=True)
    assert "Successfully installed wheelbroken-0.1" in str(res), str(res)

@pytest.mark.network
def test_cleanup_after_failed_wheel(script, data, common_wheels):
    script.pip('install', 'wheel', '--no-index', '-f', common_wheels)
    res = script.pip(
        'install', '--no-index', '-f', data.find_links, '-f', common_wheels,
        'wheelbrokenafter',
        expect_stderr=True)
    # One of the effects of not cleaning up is broken scripts:
    script_py = script.bin_path / "script.py"
    assert script_py.exists, script_py
    shebang = open(script_py, 'r').readline().strip()
    assert shebang != '#!python', shebang
    # OK, assert that we *said* we were cleaning up:
    assert "Running setup.py clean for wheelbrokenafter" in str(res), str(res)

@pytest.mark.network
def test_install_builds_wheels(script, data, common_wheels):
    # We need to use a subprocess to get the right value on Windows.
    res = script.run('python', '-c', (
        'from pip._internal.utils import appdirs; '
        'print(appdirs.user_cache_dir("pip"))'
    ))
    wheels_cache = os.path.join(res.stdout.rstrip('\n'), 'wheels')
    # NB This incidentally tests a local tree + tarball inputs
    # see test_install_editable_from_git_autobuild_wheel for editable
    # vcs coverage.
    script.pip('install', 'wheel', '--no-index', '-f', common_wheels)
    to_install = data.packages.join('requires_wheelbroken_upper')
    res = script.pip(
        'install', '--no-index', '-f', data.find_links, '-f', common_wheels,
        to_install, expect_stderr=True)
    expected = ("Successfully installed requires-wheelbroken-upper-0"
                " upper-2.0 wheelbroken-0.1")
    # Must have installed it all
    assert expected in str(res), str(res)
    wheels = []
    for top, dirs, files in os.walk(wheels_cache):
        wheels.extend(files)
    # and built wheels for upper and wheelbroken
    assert "Running setup.py bdist_wheel for upper" in str(res), str(res)
    assert "Running setup.py bdist_wheel for wheelb" in str(res), str(res)
    # Wheels are built for local directories, but not cached.
    assert "Running setup.py bdist_wheel for requir" in str(res), str(res)
    # wheelbroken has to run install
    # into the cache
    assert wheels != [], str(res)
    # and installed from the wheel
    assert "Running setup.py install for upper" not in str(res), str(res)
    # Wheels are built for local directories, but not cached.
    assert "Running setup.py install for requir" not in str(res), str(res)
    # wheelbroken has to run install
    assert "Running setup.py install for wheelb" in str(res), str(res)
    # We want to make sure we used the correct implementation tag
    assert wheels == [
        "Upper-2.0-{}-none-any.whl".format(pep425tags.implementation_tag),
    ]

@pytest.mark.network
def test_install_no_binary_disables_building_wheels(
        script, data, common_wheels):
    script.pip('install', 'wheel', '--no-index', '-f', common_wheels)
    to_install = data.packages.join('requires_wheelbroken_upper')
    res = script.pip(
        'install', '--no-index', '--no-binary=upper', '-f', data.find_links,
        '-f', common_wheels,
        to_install, expect_stderr=True)
    expected = ("Successfully installed requires-wheelbroken-upper-0"
                " upper-2.0 wheelbroken-0.1")
    # Must have installed it all
    assert expected in str(res), str(res)
    # and built wheels for wheelbroken only
    assert "Running setup.py bdist_wheel for wheelb" in str(res), str(res)
    # Wheels are built for local directories, but not cached across runs
    assert "Running setup.py bdist_wheel for requir" in str(res), str(res)
    # Don't build wheel for upper which was blacklisted
    assert "Running setup.py bdist_wheel for upper" not in str(res), str(res)
    # Wheels are built for local directories, but not cached across runs
    assert "Running setup.py install for requir" not in str(res), str(res)
    # And these two fell back to sdist based installed.
    assert "Running setup.py install for wheelb" in str(res), str(res)
    assert "Running setup.py install for upper" in str(res), str(res)

@pytest.mark.network
def test_install_no_binary_disables_cached_wheels(script, data, common_wheels):
    script.pip('install', 'wheel', '--no-index', '-f', common_wheels)
    # Seed the cache
    script.pip(
        'install', '--no-index', '-f', data.find_links, '-f', common_wheels,
        'upper')
    script.pip('uninstall', 'upper', '-y')
    res = script.pip(
        'install', '--no-index', '--no-binary=:all:', '-f', data.find_links,
        'upper', expect_stderr=True)
    assert "Successfully installed upper-2.0" in str(res), str(res)
    # No wheel building for upper, which was blacklisted
    assert "Running setup.py bdist_wheel for upper" not in str(res), str(res)
    # Must have used source, not a cached wheel to install upper.
    assert "Running setup.py install for upper" in str(res), str(res)

def test_install_editable_with_wrong_egg_name(script):
    script.scratch_path.join("pkga").mkdir()
    pkga_path = script.scratch_path / 'pkga'
    pkga_path.join("setup.py").write(textwrap.dedent("""
        from setuptools import setup
        setup(name='pkga',
              version='0.1')
    """))
    result = script.pip(
        'install', '--editable', 'file://%s#egg=pkgb' % pkga_path,
        expect_error=True)
    assert ("egg_info for package pkgb produced metadata "
            "for project name pkga. Fix your #egg=pkgb "
            "fragments.") in result.stderr
    assert "Successfully installed pkga" in str(result), str(result)

def test_install_tar_xz(script, data):
    try:
        import lzma  # noqa
    except ImportError:
        pytest.skip("No lzma support")
    res = script.pip('install', data.packages / 'singlemodule-0.0.1.tar.xz')
    assert "Successfully installed singlemodule-0.0.1" in res.stdout, res

def test_install_tar_lzma(script, data):
    try:
        import lzma  # noqa
    except ImportError:
        pytest.skip("No lzma support")
    res = script.pip('install', data.packages / 'singlemodule-0.0.1.tar.lzma')
    assert "Successfully installed singlemodule-0.0.1" in res.stdout, res

def test_double_install(script):
    """
    Test double install passing with two same version requirements
    """
    result = script.pip('install', 'pip', 'pip',
                        use_module=True,
                        expect_error=False)
    msg = "Double requirement given: pip (already in pip, name='pip')"
    assert msg not in result.stderr

def test_double_install_fail(script):
    """
    Test double install failing with two different version requirements
    """
    result = script.pip('install', 'pip==*', 'pip==7.1.2', expect_error=True)
    msg = ("Double requirement given: pip==7.1.2 (already in pip==*, "
           "name='pip')")
    assert msg in result.stderr

def test_install_incompatible_python_requires(script, common_wheels):
    script.scratch_path.join("pkga").mkdir()
    pkga_path = script.scratch_path / 'pkga'
    pkga_path.join("setup.py").write(textwrap.dedent("""
        from setuptools import setup
        setup(name='pkga',
              python_requires='<1.0',
              version='0.1')
    """))
    script.pip(
        'install', 'setuptools>24.2',  # This should not be needed
        '--no-index', '-f', common_wheels,
    )
    result = script.pip('install', pkga_path, expect_error=True)
    assert ("pkga requires Python '<1.0' "
            "but the running Python is ") in result.stderr, str(result)

def test_install_incompatible_python_requires_editable(script, common_wheels):
    script.scratch_path.join("pkga").mkdir()
    pkga_path = script.scratch_path / 'pkga'
    pkga_path.join("setup.py").write(textwrap.dedent("""
        from setuptools import setup
        setup(name='pkga',
              python_requires='<1.0',
              version='0.1')
    """))
    script.pip(
        'install', 'setuptools>24.2',  # This should not be needed
        '--no-index', '-f', common_wheels,
    )
    result = script.pip(
        'install', '--editable=%s' % pkga_path, expect_error=True)
    assert ("pkga requires Python '<1.0' "
            "but the running Python is ") in result.stderr, str(result)

@pytest.mark.network
def test_install_incompatible_python_requires_wheel(script, common_wheels):
    script.scratch_path.join("pkga").mkdir()
    pkga_path = script.scratch_path / 'pkga'
    pkga_path.join("setup.py").write(textwrap.dedent("""
        from setuptools import setup
        setup(name='pkga',
              python_requires='<1.0',
              version='0.1')
    """))
    script.pip(
        'install', 'setuptools>24.2',  # This should not be needed
        '--no-index', '-f', common_wheels,
    )
    script.pip('install', 'wheel', '--no-index', '-f', common_wheels)
    script.run(
        'python', 'setup.py', 'bdist_wheel', '--universal', cwd=pkga_path)
    result = script.pip('install', './pkga/dist/pkga-0.1-py2.py3-none-any.whl',
                        expect_error=True)
    assert ("pkga requires Python '<1.0' "
            "but the running Python is ") in result.stderr

def test_install_compatible_python_requires(script, common_wheels):
    script.scratch_path.join("pkga").mkdir()
    pkga_path = script.scratch_path / 'pkga'
    pkga_path.join("setup.py").write(textwrap.dedent("""
        from setuptools import setup
        setup(name='pkga',
              python_requires='>1.0',
              version='0.1')
    """))
    script.pip(
        'install', 'setuptools>24.2',  # This should not be needed
        '--no-index', '-f', common_wheels,
    )
    res = script.pip('install', pkga_path, expect_error=True)
    assert "Successfully installed pkga-0.1" in res.stdout, res

@pytest.mark.network
def test_install_pep508_with_url(script):
    res = script.pip(
        'install', '--no-index',
        'packaging@https://files.pythonhosted.org/packages/2f/2b/'
        'c681de3e1dbcd469537aefb15186b800209aa1f299d933d23b48d85c9d56/'
        'packaging-15.3-py2.py3-none-any.whl#sha256='
        'ce1a869fe039fbf7e217df36c4653d1dbe657778b2d41709593a0003584405f4'
    )
    assert "Successfully installed packaging-15.3" in str(res), str(res)

@pytest.mark.network
def test_install_pep508_with_url_in_install_requires(script):
    pkga_path = create_test_package_with_setup(
        script, name='pkga', version='1.0',
        install_requires=[
            'packaging@https://files.pythonhosted.org/packages/2f/2b/'
            'c681de3e1dbcd469537aefb15186b800209aa1f299d933d23b48d85c9d56/'
            'packaging-15.3-py2.py3-none-any.whl#sha256='
            'ce1a869fe039fbf7e217df36c4653d1dbe657778b2d41709593a0003584405f4'
        ],
    )
    res = script.pip('install', pkga_path, expect_error=True)
    assert "Direct url requirement " in res.stderr, str(res)
    assert "are not allowed for dependencies" in res.stderr, str(res)

def test_installing_scripts_outside_path_prints_warning(script):
    result = script.pip_install_local(
        "--prefix", script.scratch_path, "script_wheel1", expect_error=True
    )
    assert "Successfully installed script-wheel1" in result.stdout, str(result)
    assert "--no-warn-script-location" in result.stderr

def test_installing_scripts_outside_path_can_suppress_warning(script):
    result = script.pip_install_local(
        "--prefix", script.scratch_path, "--no-warn-script-location",
        "script_wheel1"
    )
    assert "Successfully installed script-wheel1" in result.stdout, str(result)
    assert "--no-warn-script-location" not in result.stderr

def test_installing_scripts_on_path_does_not_print_warning(script):
    result = script.pip_install_local("script_wheel1")
    assert "Successfully installed script-wheel1" in result.stdout, str(result)
    assert "--no-warn-script-location" not in result.stderr

def test_installed_files_recorded_in_deterministic_order(script, data):
    """
    Ensure that we record the files installed by a package in a deterministic
    order, to make installs reproducible.
    """
    to_install = data.packages.join("FSPkg")
    result = script.pip('install', to_install, expect_error=False)
    fspkg_folder = script.site_packages / 'fspkg'
    egg_info = 'FSPkg-0.1.dev0-py%s.egg-info' % pyversion
    installed_files_path = (
        script.site_packages / egg_info / 'installed-files.txt'
    )
    assert fspkg_folder in result.files_created, str(result.stdout)
    assert installed_files_path in result.files_created, str(result)

    installed_files_path = result.files_created[installed_files_path].full
    installed_files_lines = [
        p for p in Path(installed_files_path).read_text().split('\n') if p
    ]
    assert installed_files_lines == sorted(installed_files_lines)

def test_install_conflict_results_in_warning(script, data):
    pkgA_path = create_test_package_with_setup(
        script,
        name='pkgA', version='1.0', install_requires=['pkgb == 1.0'],
    )
    pkgB_path = create_test_package_with_setup(
        script,
        name='pkgB', version='2.0',
    )

    # Install pkgA without its dependency
    result1 = script.pip('install', '--no-index', pkgA_path, '--no-deps')
    assert "Successfully installed pkgA-1.0" in result1.stdout, str(result1)

    # Then install an incorrect version of the dependency
    result2 = script.pip(
        'install', '--no-index', pkgB_path,
        expect_stderr=True,
    )
    assert "pkga 1.0 has requirement pkgb==1.0" in result2.stderr, str(result2)
    assert "Successfully installed pkgB-2.0" in result2.stdout, str(result2)

def test_install_conflict_warning_can_be_suppressed(script, data):
    pkgA_path = create_test_package_with_setup(
        script,
        name='pkgA', version='1.0', install_requires=['pkgb == 1.0'],
    )
    pkgB_path = create_test_package_with_setup(
        script,
        name='pkgB', version='2.0',
    )

    # Install pkgA without its dependency
    result1 = script.pip('install', '--no-index', pkgA_path, '--no-deps')
    assert "Successfully installed pkgA-1.0" in result1.stdout, str(result1)

    # Then install an incorrect version of the dependency; suppressing warning
    result2 = script.pip(
        'install', '--no-index', pkgB_path, '--no-warn-conflicts'
    )
    assert "Successfully installed pkgB-2.0" in result2.stdout, str(result2)


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>CompartmentalSystems.bins.density_algorithm — CompartmentalSystems 1 documentation</title>
    <link rel="stylesheet" href="../../../_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../../../genindex.html" />
    <link rel="search" title="Search" href="../../../search.html" />

  <link rel="stylesheet" href="../../../_static/custom.css" type="text/css" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

Source code for CompartmentalSystems.bins.density_algorithm

# vim: set ff=unix expandtab ts=4 sw=4:
#from testinfrastructure.helpers import pp,pe
import numpy as np
import matplotlib
#matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as manimation
from mpl_toolkits.mplot3d import Axes3D

##def loss(age_dist_plain,eta_plain ):
##    return(age_dist_plain*eta_plain)

[docs]def losses(old_rectangles,death_rates,time):
    internal_death_rates= {k:v for k,v in death_rates.items() if isinstance(k,tuple)}
    losses=dict()
    for key,death_rate in internal_death_rates.items():
    #for pool_number,r in enumerate(old_rectangles):
        sending_pool=key[0]
        receiving_pool=key[1]
        r=old_rectangles[sending_pool]
        losses[key]=r*death_rate(r,time)
    return(losses)

[docs]def gains(pool_number,internal_losses):
    #sum over all pool ages
    #(first index=SystemAge,second_index PoolAge)
    #find pipelines leading to me

    this_pool_gains={k:v for k,v in internal_losses.items() if k[1]==pool_number}
    return(sum([np.sum(v,1) for v in this_pool_gains.values()]))

#def age_distributions(initial_plains,external_inputs,external_death_rates,internal_death_rates,start,end):
#    tss=initial_plains[0].tss
#    # infer the number of pools from the number of start distributions
#    number_of_pools=len(initial_plains)
#
#    # start the list with an element for the first time step
#    mpp=[initial_plains]
#
#    old_rectangles=initial_plains
#
#    times= np.arange(start+tss,end+tss,tss)
#    for t in times:
#        new_rectangles=advance_rectangles(old_rectangles,t-tss,external_inputs,death_rates)
#        mpp.append(new_rectangles)
#        old_rectangles=new_rectangles
#    return(mpp)

#def advance_rectangles(old_rectangles,time,external_inputs,death_rates):
#    new_rectangles=[]
#    #extract the deathrates out of the system
#    internal_death_rates= {k:v for k,v in death_rates.items() if isinstance(k,tuple)}
#    internal_losses=losses(old_rectangles,death_rates,time)
#    outward_death_rates= {k:v for k,v in death_rates.items() if not(isinstance(k,tuple))}
#
#    for pool_number,r in enumerate(old_rectangles):
#        x,y=r.shape
#        #first remove the outflow for all external deathrates defined for this pool
#        this_pool_outward_death_rates={k:v for k,v in outward_death_rates.items() if k==pool_number}
#
#        internal_input_to_first_pool=np.zeros(x) #fixme: faked since we know that we have no contributions from other pools
#        #accumulate losses through different output channels
#        l=np.zeros(r.shape)
#        for dr in this_pool_outward_death_rates.values():
#            #create the eta field of appropriate size
#            eta_rect=dr(r,time)
#            l+=loss(r,eta_rect)
#
#        x,y=r.shape
#        n=np.ndarray((x+1,y+1),dtype=default_data_type())
#        n[1:,1:]=r-l
#        #print("n[0,0]",n[0,0])
#        #print("n=",n[0,:])
#        #print("inp=",external_inputs[pool_number](y+1,time))
#        n[0,:]=external_inputs[pool_number](y+1,time)
#        n[1:,0]=internal_input_to_first_pool
#
#        new_rectangles.append(n)
#    return(new_rectangles)

CompartmentalSystems

Navigation

CompartmentalSystems.smooth_reservoir_model

CompartmentalSystems.smooth_model_run

CompartmentalSystems.start_distributions

Related Topics

Documentation overview

Module code

Quick search

    <form class="search" action="../../../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" />
      <input type="submit" value="Go" />
    </form>

      ©2020, Holger Metzler, Markus Müller.

      |
      Powered by Sphinx 3.2.1
      & Alabaster 0.7.12

redpajama_set_name: RedPajamaGithub


text:
typedef void (^TXTouchedButtonBlock)(NSInteger tag);

@interface UIButton (TXBlock)
-(void)tx_addActionHandler:(TXTouchedButtonBlock)touchHandler;
@end


text:
GRANT SELECT ON TABLE osm_aeroways TO "user";
GRANT SELECT ON TABLE osm_amenities TO "user";
GRANT SELECT ON TABLE osm_amenity_areas TO "user";
GRANT SELECT ON TABLE osm_areas_for_labels TO "user";
GRANT SELECT ON TABLE osm_barrierpoints TO "user";
GRANT SELECT ON TABLE osm_barrierways TO "user";
GRANT SELECT ON TABLE osm_buildings TO "user";
GRANT SELECT ON TABLE osm_housenumbers TO "user";
GRANT SELECT ON TABLE osm_housenumbers_interpolated TO "user";
GRANT SELECT ON TABLE osm_landusages TO "user";
GRANT SELECT ON TABLE osm_landusages_gen0 TO "user";
GRANT SELECT ON TABLE osm_landusages_gen1 TO "user";
GRANT SELECT ON TABLE osm_places TO "user";
GRANT SELECT ON TABLE osm_powerlines TO "user";
GRANT SELECT ON TABLE osm_powerpoles TO "user";
GRANT SELECT ON TABLE osm_roads_for_labels_int_ref TO "user";
GRANT SELECT ON TABLE osm_roads_for_labels_name TO "user";
GRANT SELECT ON TABLE osm_roads_for_labels_ref TO "user";
GRANT SELECT ON TABLE osm_roads_n_railways TO "user";
GRANT SELECT ON TABLE osm_roads_n_railways_gen0 TO "user";
GRANT SELECT ON TABLE osm_roads_n_railways_gen1 TO "user";
GRANT SELECT ON TABLE osm_transport_areas TO "user";
GRANT SELECT ON TABLE osm_transport_points TO "user";
GRANT SELECT ON TABLE osm_waterareas TO "user";
GRANT SELECT ON TABLE osm_waterareas_gen0 TO "user";
GRANT SELECT ON TABLE osm_waterareas_gen1 TO "user";
GRANT SELECT ON TABLE osm_waterways TO "user";
GRANT SELECT ON TABLE osm_waterways_for_labels TO "user";
GRANT SELECT ON TABLE osm_waterways_gen0 TO "user";
GRANT SELECT ON TABLE osm_waterways_gen1 TO "user";
GRANT SELECT ON TABLE osm_windturbines TO "user";


text:
<ion-header>
    <ion-navbar core-back-button>
        <ion-title>{{ 'addon.messages.contacts' | translate }}</ion-title>
        <ion-buttons end>
            <button ion-button icon-only (click)="gotoSearch()" [attr.aria-label]="'addon.messages.search' | translate">
                <ion-icon name="search"></ion-icon>
            </button>
            <!-- Add an empty context menu so discussion page can add items in split view, otherwise the menu disappears in some cases. -->
            <core-context-menu></core-context-menu>
        </ion-buttons>
    </ion-navbar>
</ion-header>
<core-split-view>
    <ion-content>
        <core-tabs>
            <core-tab [title]="'addon.messages.contacts' | translate" (ionSelect)="selectUser('contacts')">
                <ng-template>
                    <addon-messages-confirmed-contacts (onUserSelected)="selectUser('contacts', $event.userId, $event.onInit)"></addon-messages-confirmed-contacts>
                </ng-template>
            </core-tab>
            <core-tab [title]="'addon.messages.requests' | translate" [badge]="contactRequestsCount" (ionSelect)="selectUser('requests')">
                 <ng-template>
                    <addon-messages-contact-requests (onUserSelected)="selectUser('requests', $event.userId, $event.onInit)"></addon-messages-contact-requests>
                </ng-template>
            </core-tab>
        </core-tabs>
    </ion-content>
</core-split-view>


text:
using DotSpatial.Symbology;

namespace DotSpatial.Controls
{
    /// <summary>
    /// IGeoImageLayer
    /// </summary>
    public interface IMapImageLayer : IImageLayer, IMapLayer
    {
    }
}


text:
FBCHFA ;WOIFO/SAB-FILE ADJUSTMENTS FOR CH/CNH PAYMENT ;9/9/2003
 ;;3.5;FEE BASIS;**61**;JAN 30, 1995
 Q
FILEADJ(FBIENS,FBADJ) ; File Adjustments
 ;
 ; Input
 ;   FBIENS -  required, internal entry numbers for file 162.5
 ;             in standard format as specified for FileMan DBS calls
 ;   FBADJ   - required, array passed by reference
 ;             array of adjustments to file
 ;             array does not have to contain any data or be defined
 ;             format
 ;               FBADJ(#)=FBADJR^FBADJG^FBADJA
 ;             where
 ;               # = sequentially assigned number starting with 1
 ;               FBADJR = adjustment reason (internal value file 162.91)
 ;               FBADJG = adjustment group (internal value file 162.92)
 ;               FBADJA = adjustment amount (dollar value)
 ; Output
 ;   Data in File 162.5 will be modified
 ;
 N FB,FBFDA,FBHIGH,FBI,FBMSR,FBSC,FBSIENS,FBTAS
 ;
 ; delete adjustment reasons currently on file
 D GETS^DIQ(162.5,FBIENS,"58*","","FB")
 K FBFDA
 S FBSIENS="" F  S FBSIENS=$O(FB(162.558,FBSIENS)) Q:FBSIENS=""  D
 . S FBFDA(162.558,FBSIENS,.01)="@"
 I $D(FBFDA) D FILE^DIE("","FBFDA")
 ;
 ; delete suspend data currently on file
 K FBFDA
 S FBFDA(162.5,FBIENS,9)="@"
 S FBFDA(162.5,FBIENS,10)="@"
 I $D(FBFDA) D FILE^DIE("","FBFDA")
 ;
 ; delete description of suspension currently on file
 D WP^DIE(162.5,FBIENS,18,,"@")
 ;
 ; compute total amount suspended and determine most significant reason
 ; loop thru reasons
 S (FBTAS,FBI,FBHIGH)=0,FBMSR=""
 F  S FBI=$O(FBADJ(FBI)) Q:'FBI  D
 . N FBADJA
 . ; get adjustment amount for reason
 . S FBADJA=$P(FBADJ(FBI),U,3)
 . ; add amount to total
 . S FBTAS=FBTAS+FBADJA
 . ; check if reason has largest absolute $ impact
 . I $FN(FBADJA,"-")>$G(FBHIGH) S FBMSR=FBI,FBHIGH=$FN(FBADJA,"-")
 ;
 I +FBTAS=0 Q  ; quit since total amount suspended is 0
 ;
 ; file adjustments from input array
 K FBFDA
 S FBI=0 F  S FBI=$O(FBADJ(FBI)) Q:'FBI  D
 . S FBFDA(162.558,"+"_FBI_","_FBIENS,.01)=$P(FBADJ(FBI),U)
 . S FBFDA(162.558,"+"_FBI_","_FBIENS,1)=$P(FBADJ(FBI),U,2)
 . S FBFDA(162.558,"+"_FBI_","_FBIENS,2)=+$P(FBADJ(FBI),U,3)
 I $D(FBFDA) D UPDATE^DIE("","FBFDA")
 ;
 ; file derived suspend data
 K FBFDA
 S FBFDA(162.5,FBIENS,9)=FBTAS
 I FBMSR,$P(FBADJ(FBMSR),U) S FBSC=$$GET1^DIQ(161.91,$P(FBADJ(FBMSR),U),3)
 I '$G(FBSC) S FBSC=4
 S FBFDA(162.5,FBIENS,10)=FBSC
 I $D(FBFDA) D FILE^DIE("","FBFDA")
 ;
 ; if suspend code = 4 (other) then file description of suspension
 I FBSC=4,FBMSR,$P(FBADJ(FBMSR),U) D WP^DIE(162.5,FBIENS,18,,"^FB(161.91,"_$P(FBADJ(FBMSR),U)_",4)")
 D MSG^DIALOG()
 ;
 Q
 ;
LOADADJ(FBIENS,FBADJ) ; Load Adjustments
 ; Input
 ;   FBIENS -  required, internal entry numbers for subfile 162.5
 ;             in standard format as specified for FileMan DBS calls
 ;   FBADJ   - required, array passed by reference
 ;             array to load adjustments into
 ; Output
 ;   FBADJ   - the FBADJ input array passed by reference will be modified
 ;             format
 ;               FBADJ(#)=FBADJR^FBADJG^FBADJA
 ;             where
 ;               # = sequentially assigned number starting with 1
 ;               FBADJR = adjustment reason (internal value file 162.91)
 ;               FBADJG = adjustment group (internal value file 162.92)
 ;               FBADJA = adjustment amount (dollar value)
 ;             if no adjustments are on file then the array will be
 ;               undefined
 N FB,FBC,FBI,FBSIENS
 ;
 K FBADJ
 ;
 S FBC=0
 D GETS^DIQ(162.5,FBIENS,"58*","I","FB")
 D MSG^DIALOG()
 S FBSIENS="" F  S FBSIENS=$O(FB(162.558,FBSIENS)) Q:FBSIENS=""  D
 . S FBC=FBC+1
 . S FBADJ(FBC)=FB(162.558,FBSIENS,.01,"I")
 . S FBADJ(FBC)=FBADJ(FBC)_U_FB(162.558,FBSIENS,1,"I")
 . S FBADJ(FBC)=FBADJ(FBC)_U_FB(162.558,FBSIENS,2,"I")
 ;
 Q
 ;
ADJLRA(FBIENS) ; Adjustment Reason^Amount List Extrinsic Function
 ; Input
 ;   FBIENS -  required, internal entry number for file 162.5
 ;             in standard format as specified for FileMan DBS calls
 ; Result
 ;   string containing sorted list (by external code) of reason^amounts
 ;   format
 ;      FBADJE 1, FBADJE 2^FBADJA 1,FBADJA2
 ;   where
 ;      FBADJE = adjustment reason code (external value)
 ;      FBADJA = adjustment amount
 N FBRET,FBADJ,FBADJL,FBADJLA,FBADJLR
 D LOADADJ^FBCHFA(FBIENS,.FBADJ)
 S FBADJL=$$ADJL^FBUTL2(.FBADJ)
 S FBADJLR=$$ADJLR^FBUTL2(FBADJL)
 S FBADJLA=$$ADJLA^FBUTL2(FBADJL)
 S FBRET=FBADJLR_U_FBADJLA
 Q FBRET
 ;
 ;FBCHFA


text:
'use strict';

exports.__esModule = true;
exports.storeShape = exports.subscriptionShape = undefined;

var _react = require('react');

var subscriptionShape = exports.subscriptionShape = _react.PropTypes.shape({
  trySubscribe: _react.PropTypes.func.isRequired,
  tryUnsubscribe: _react.PropTypes.func.isRequired,
  notifyNestedSubs: _react.PropTypes.func.isRequired,
  isSubscribed: _react.PropTypes.func.isRequired
});

var storeShape = exports.storeShape = _react.PropTypes.shape({
  subscribe: _react.PropTypes.func.isRequired,
  dispatch: _react.PropTypes.func.isRequired,
  getState: _react.PropTypes.func.isRequired
});


text:
Why?
----
The internet's got a lot of forms used to get data from users. Sometimes it's helpful to ensure that the data being submitted is legitimate.

[POP.co](http://pop.co), a product of [.CO](http://go.co), required a useful validation helper for mobile number entry since we were leveraging text messages to handle user validation.

PhoneCheckJS is the result of wanting to refactor and abstract away the main functionality that was initially implemented on [POP's](http://pop.co) homepage to collect user telephone numbers from multiple countries.

How?
----
To use PhoneCheckJS, you will need to have at least two elements in your markup:
* Country Field/List (<input> or <select>)
* Phone Number Field (<input>)

Note:
* The PhoneCheck and its underlying libphonenumber library (specified in Dependencies) rely on two-letter country codes to validate input.
* Users need to enter their number in its full international format.

After including the following depencies (inlcuded in the /js) and PhoneCheckJS:

```
<script type="text/javascript" src="js/libphonenumber.min.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/phonecheck.js"></script>
```

All you need to do is call the PhoneCheck constructor, passing in two jQuery objects, the first representing the phone number field to validate and country code field:

```
<script type="text/javascript">
	new PhoneCheck($('input'), $('select'));
</script>
```

Loading your webpage with this default code will insert the selected country's country code digit(s) in the number input field. Eg, for the US '+ 1 ' will be in the field. Selecting the United Kingdom (UK) will overwrite the current input to be '+ 44 '.

PhoneCheck validates the input as the user types a character.

* Valid input will result in a 'pc-valid'class being added to the input element.
* Invalid input will result in a 'pc-invalid' class being added to the input element.
* By default, with no input (ie, only the country code - if applicable), neither class will be present.

You may use either class ('pc-valid' or 'pc-invalid') to check the validity of the input in the element and/or style the field appropriately.

Disclaimer
----
PhoneCheckJS does not have 100% support for every country listed in the demo country selector. For countries that the libphonenumber library does not support, PhoneCheckJS will default to allowing any numeric entry as valid to reduce the occurrence of false negatives.

Dependencies
----
PhoneCheckJS has two depencies:
* [jQuery](http://jquery.com)
* [libphonenumber (by Google)](https://code.google.com/p/libphonenumber/)

Culprit (Creator)
----
This (hopefully) helpful package was put together by [@mrdazm](http://twitter.com/mrdazm) under MIT license.

Follow [@thePOPguys](http://twitter.com/thePOPguys) and [@dotco](http://twitter.com/dotco)!

© 2013 Domain Marketing Ventures


text:
package dnstap

import (
	"log"
	"net"
	"os"
)

type FrameStreamSockInput struct {
	wait     chan bool
	listener net.Listener
}

func NewFrameStreamSockInput(listener net.Listener) (input *FrameStreamSockInput) {
	input = new(FrameStreamSockInput)
	input.listener = listener
	return
}

func NewFrameStreamSockInputFromPath(socketPath string) (input *FrameStreamSockInput, err error) {
	os.Remove(socketPath)
	listener, err := net.Listen("unix", socketPath)
	if err != nil {
		return
	}
	return NewFrameStreamSockInput(listener), nil
}

func (input *FrameStreamSockInput) ReadInto(output chan []byte) {
	for {
		conn, err := input.listener.Accept()
		if err != nil {
			log.Printf("net.Listener.Accept() failed: %s\n", err)
			continue
		}
		i, err := NewFrameStreamInput(conn, true)
		if err != nil {
			log.Printf("dnstap.NewFrameStreamInput() failed: %s\n", err)
			continue
		}
		log.Printf("dnstap.FrameStreamSockInput: accepted a socket connection\n")
		go i.ReadInto(output)
	}
}

func (input *FrameStreamSockInput) Wait() {
	select {}
}


text:
/**
 * @file addMethodPropertyCoffeeMachine.js
 * @author Vladimir Deminenko
 * @date 20.08.2017
 */

'use strict';

/**
 * https://learn.javascript.ru/task/add-method-property-coffeemachine
 * @constructor CoffeeMachine
 * @param   {number}    power   мощность кофеварки
 * @method              run()   запускает кофеварку
 * @method              stop()  останавливает кофеварку
 */
function CoffeeMachine(power) {
    const WATER_HEAT_CAPACITY = 4200;

    let getBoilTime = () => this.waterAmount * WATER_HEAT_CAPACITY * 80 / power;
    let onReady = () => alert('Кофе готов!');
    let timerId = null;

    this.waterAmount = 0;

    this.stop = function () {
        if (timerId) {
            clearTimeout(timerId);
        }
    };

    this.run = function () {
        timerId = setTimeout(onReady, getBoilTime());
    };
}


text:
package de.memorian.ps4trophaen.models;

import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.Spannable;

/**
 * Model for a trophy.
 *
 *
 * @since 11.10.2014
 */
public class Trophy implements Parcelable, Comparable<Trophy> {

    private Type type;
    private String title;
    private String text;
    private String guide;
    private boolean secret;
    private Spannable formattedGuide;
    private String base64Icon;
    private Priority priority;

    public Trophy() {
        priority = Priority.NORMAL;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(type.name());
        dest.writeString(title);
        dest.writeString(text);
        dest.writeString(guide);
    }

    public static final Parcelable.Creator<Trophy> CREATOR
            = new Parcelable.Creator<Trophy>() {
        public Trophy createFromParcel(Parcel in) {
            return new Trophy(in);
        }

        public Trophy[] newArray(int size) {
            return new Trophy[size];
        }
    };

    private Trophy(Parcel in) {
        setType(Type.valueOf(in.readString()));
        setTitle(in.readString());
        setText(in.readString());
        setGuide(in.readString());
    }

    public String getBase64Icon() {
        return base64Icon;
    }

    public void setBase64Icon(String base64Icon) {
        this.base64Icon = base64Icon;
    }

    public Priority getPriority() {
        return priority;
    }

    public void setPriority(Priority priority) {
        this.priority = priority;
    }

    public void setFormattedGuide(Spannable spannable) {
        formattedGuide = spannable;
    }

    public Spannable getFormattedGuide(Context context) {
        return formattedGuide;
    }

    public boolean isSecret() {
        return secret;
    }

    public void setSecret(boolean secret) {
        this.secret = secret;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getGuide() {
        return guide;
    }

    public void setGuide(String guide) {
        this.guide = guide;
    }

    public Type getType() {

        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    @Override
    public int compareTo(Trophy other) {
        Priority otherPriority = other.getPriority();
        if (getPriority() == Priority.IMPORTANT && otherPriority != Priority.IMPORTANT) {
            return -1;
        }
        if (getPriority() == Priority.NORMAL) {
            if (otherPriority == Priority.IMPORTANT) {
                return 1;
            }
            if (otherPriority == Priority.UNIMPORTANT) {
                return -1;
            }
        }
        if (getPriority() == Priority.UNIMPORTANT && otherPriority != Priority.UNIMPORTANT) {
            return 1;
        }

        Type otherType = other.getType();
        if (getType() == Type.BRONZE) {
            if (otherType == Type.SILVER || otherType == Type.GOLD || otherType == Type.PLATIN) {
                return -1;
            } else return getTitle().compareTo(other.getTitle());
        }

        if (getType() == Type.SILVER) {
            if (otherType == Type.GOLD || otherType == Type.PLATIN) {
                return -1;
            } else if (otherType == Type.BRONZE) {
                return 1;
            } else return getTitle().compareTo(other.getTitle());
        }

        if (getType() == Type.GOLD) {
            if (otherType == Type.PLATIN) {
                return -1;
            } else if (otherType == Type.BRONZE || otherType == Type.SILVER) {
                return 1;
            } else return getTitle().compareTo(other.getTitle());
        }

        if (getType() == Type.PLATIN) {
            if (otherType == Type.PLATIN) {
                return getTitle().compareTo(other.getTitle());
            } else return 1;
        }

        return 0;
    }

    public enum Type {
        BRONZE, SILVER, GOLD, PLATIN;
    }

    public enum Priority {
        NORMAL, IMPORTANT, UNIMPORTANT;
    }
}


text:
try {
  new new Proxy(Function(), { get:String.fromCharCode })
  assert(false);
} catch (e) {
  assert(e instanceof TypeError);
}


text:
#include "PluginTest.h"

#include <string.h>

using namespace std;

class ToStringAndValueOfObject : public PluginTest {
public:
    ToStringAndValueOfObject(NPP npp, const string& identifier)
        : PluginTest(npp, identifier)
    {
    }

private:
    class ScriptableObject : public Object<ScriptableObject> {
    public:
        bool hasMethod(NPIdentifier methodName)
        {
            return identifierIs(methodName, "toString")
                || identifierIs(methodName, "valueOf");
        }

        bool invoke(NPIdentifier methodName, const NPVariant*, uint32_t, NPVariant* result)
        {
            if (identifierIs(methodName, "toString")) {
                // Return classname as string.
                char* className = static_cast<char*>(pluginTest()->NPN_MemAlloc(11));
                strcpy(className, "TestObject");
                STRINGZ_TO_NPVARIANT(className, *result);
                return true;
            }
            if (identifierIs(methodName, "valueOf")) {
                // Return some number.
                DOUBLE_TO_NPVARIANT(123456789, *result);
                return true;
            }
            return false;
        }

    private:
        ToStringAndValueOfObject* pluginTest() const { return static_cast<ToStringAndValueOfObject*>(Object<ScriptableObject>::pluginTest()); }
    };

    virtual NPError NPP_GetValue(NPPVariable variable, void* value)
    {
        if (variable != NPPVpluginScriptableNPObject)
            return NPERR_GENERIC_ERROR;

        *(NPObject**)value = ScriptableObject::create(this);

        return NPERR_NO_ERROR;
    }
};

static PluginTest::Register<ToStringAndValueOfObject> ToStringAndValueOfObject("to-string-and-value-of-object");


text:
:mod:`dircache` --- Cached directory listings
=============================================

.. module:: dircache
   :synopsis: Return directory listing, with cache mechanism.
   :deprecated:

.. deprecated:: 2.6
   The :mod:`dircache` module has been removed in Python 3.0.

.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>

The :mod:`dircache` module defines a function for reading directory listing
using a cache, and cache invalidation using the *mtime* of the directory.
Additionally, it defines a function to annotate directories by appending a
slash.

The :mod:`dircache` module defines the following functions:

.. function:: reset()

   Resets the directory cache.

.. function:: listdir(path)

   Return a directory listing of *path*, as gotten from :func:`os.listdir`. Note
   that unless *path* changes, further call to :func:`listdir` will not re-read the
   directory structure.

   Note that the list returned should be regarded as read-only. (Perhaps a future
   version should change it to return a tuple?)

.. function:: opendir(path)

   Same as :func:`listdir`. Defined for backwards compatibility.

.. function:: annotate(head, list)

   Assume *list* is a list of paths relative to *head*, and append, in place, a
   ``'/'`` to each path which points to a directory.

::

   >>> import dircache
   >>> a = dircache.listdir('/')
   >>> a = a[:] # Copy the return value so we can change 'a'
   >>> a
   ['bin', 'boot', 'cdrom', 'dev', 'etc', 'floppy', 'home', 'initrd', 'lib', 'lost+
   found', 'mnt', 'proc', 'root', 'sbin', 'tmp', 'usr', 'var', 'vmlinuz']
   >>> dircache.annotate('/', a)
   >>> a
   ['bin/', 'boot/', 'cdrom/', 'dev/', 'etc/', 'floppy/', 'home/', 'initrd/', 'lib/
   ', 'lost+found/', 'mnt/', 'proc/', 'root/', 'sbin/', 'tmp/', 'usr/', 'var/', 'vm
   linuz']


text:
$:.unshift("#{File.dirname(__FILE__)}/../../plugin_test_helper/lib")
require 'rubygems'
require 'plugin_test_helper'

# Run the migrations
ActiveRecord::Migrator.migrate("#{Rails.root}/db/migrate")

# Mixin the factory helper
require File.expand_path("#{File.dirname(__FILE__)}/factory")
class Test::Unit::TestCase #:nodoc:
  include Factory
end


text:
package org.springframework.boot.actuate.endpoint.web;

import java.util.Collection;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * {@link ServletContextInitializer} to register {@link ExposableServletEndpoint servlet
 * endpoints}.
 *
 * @author Phillip Webb
 * @author Madhura Bhave
 * @since 2.0.0
 */
public class ServletEndpointRegistrar implements ServletContextInitializer {

	private static final Log logger = LogFactory.getLog(ServletEndpointRegistrar.class);

	private final String basePath;

	private final Collection<ExposableServletEndpoint> servletEndpoints;

	public ServletEndpointRegistrar(String basePath,
			Collection<ExposableServletEndpoint> servletEndpoints) {
		Assert.notNull(servletEndpoints, "ServletEndpoints must not be null");
		this.basePath = cleanBasePath(basePath);
		this.servletEndpoints = servletEndpoints;
	}

	private static String cleanBasePath(String basePath) {
		if (StringUtils.hasText(basePath) && basePath.endsWith("/")) {
			return basePath.substring(0, basePath.length() - 1);
		}
		return (basePath != null) ? basePath : "";
	}

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		this.servletEndpoints
				.forEach((servletEndpoint) -> register(servletContext, servletEndpoint));
	}

	private void register(ServletContext servletContext,
			ExposableServletEndpoint endpoint) {
		String name = endpoint.getEndpointId().toLowerCaseString() + "-actuator-endpoint";
		String path = this.basePath + "/" + endpoint.getRootPath();
		String urlMapping = path.endsWith("/") ? path + "*" : path + "/*";
		EndpointServlet endpointServlet = endpoint.getEndpointServlet();
		Dynamic registration = servletContext.addServlet(name,
				endpointServlet.getServlet());
		registration.addMapping(urlMapping);
		registration.setInitParameters(endpointServlet.getInitParameters());
		logger.info("Registered '" + path + "' to " + name);
	}

}


text:
The JS API has been updated and now consists of two modules ,"estimote.beacons" and "estimote.nearables", with support for Estimote Beacons and Estimote Stickers. "EstimoteBeacons" is kept for backwards compatibility, and points to "estimote.beacons".

See file [changelog.md](changelog.md) for a list of all updates.

## JavaScript API documentation

In addition to this document [JSDoc generated documentation](http://evomedia.evothings.com/jsdoc/phonegap-estimotebeacons/) is available. This is based on the documentation comments in file
[EstimoteBeacons.js](plugin/src/js/EstimoteBeacons.js)

## Basic usage

Beacon ranging example:

    estimote.beacons.startRangingBeaconsInRegion(
        {}, // Empty region matches all beacons.
        function(result) {
            console.log('*** Beacons ranged ***')
            estimote.beacons.printObject(result) },
        function(errorMessage) {
            console.log('Ranging error: ' + errorMessage) })

Stickers ranging example:

	estimote.nearables.startRangingForType(
		estimote.nearables.NearableTypeAll,
		function(nearables) {
            console.log('*** Stickers ranged ***')
            estimote.beacons.printObject(nearables) },
        function(errorMessage) {
            console.log('Ranging error: ' + errorMessage) })

## Overview of the JavaScript API

The plugin currently supports:

* Monitoring beacons (iOS and Android)
* Ranging for beacons (iOS and Android)
* Scanning for beacons using CoreBluetooth (iOS)
* Requesting authorization for ranging/monitoring beacons on iOS
* Ranging for nearables (Estimote Stickers) (iOS)
* Monitoring for nearables (Estimote Stickers) (iOS)
* Monitoring for nearable triggers (Estimote Stickers) (iOS)
* Using Secure Beacons (iOS)
* Calling ESTConfig methods (iOS)
* Using an iPhone as a Virtual Beacon (iOS)

Scanning is similar to ranging but uses a different underlying implementation than ranging does.

## Estimote Beacons API

### Start and stop monitoring beacons (iOS and Android)

    estimote.beacons.startMonitoringForRegion(
       region,
        successCallback,
        errorCallback)

    estimote.beacons.stopMonitoringForRegion(
        region,
        successCallback,
        errorCallback)

Example:

    function onMonitoringSuccess(regionState) {
        console.log('State is ' + regionState.state)
    }

    estimote.beacons.startMonitoringForRegion(
       region,
        onMonitoringSuccess,
        onError)

### Start and stop ranging beacons (iOS and Android)

    estimote.beacons.startRangingBeaconsInRegion(
        region,
        successCallback,
        errorCallback)

    estimote.beacons.stopRangingBeaconsInRegion(
        region,
        successCallback,
        errorCallback)

Example:

    function onRangingSuccess(beaconInfo) {
        console.log('Number of beacons ranged ' + beaconInfo.beacons.length)
    }

    estimote.beacons.startRangingBeaconsInRegion(
        {},
        onRangingSuccess,
        onError)

### Start and stop scanning beacons (iOS only)

    estimote.beacons.startEstimoteBeaconsDiscoveryForRegion(
        region,
        successCallback,
        errorCallback)

    estimote.beacons.stopEstimoteBeaconDiscovery(
        region,
        successCallback,
		errorCallback)

Example:

    function onDiscoverySuccess(beaconInfo) {
        console.log('Number of beacons discovered ' + beaconInfo.beacons.length)
    }

    estimote.beacons.startEstimoteBeaconsDiscoveryForRegion(
        {},
        onDiscoverySuccess,
        onError)

### Authorization (iOS 8 and above)

On iOS 8 your app should ask for permission to use location services (required for monitoring and ranging on iOS 8 - on Android and iOS 7 this function does nothing):

    estimote.beacons.requestAlwaysAuthorization(
        successCallback,
        errorCallback)

Note that this is not needed for the Nearables API (Estimote Stickers).

### How to access beacon data

When you use ranging or scanning, you have access to a variety of beacon properties. Different properties are available depending on whether ranging or scanning is used. (Note that during monitoring you don't get data for individual beacons, rather you get data about regions entered and exited.)

### Beacon properties available on iOS

Properties available both during ranging and scanning:

* major - major value of the beacon
* minor - minor value of the beacon
* color - one of estimote.beacons.BeaconColorUnknown, estimote.beacons.BeaconColorMint, estimote.beacons.BeaconColorIce, estimote.beacons.BeaconColorBlueberry, estimote.beacons.BeaconColorWhite, estimote.beacons.BeaconColorTransparent
* rssi - number representing the Received Signal Strength Indication

Beacon properties available only when ranging:

* proximityUUID - UUID of the beacon
* distance - estimated distance from the beacon in meters
* proximity - one of estimote.beacons.ProximityUnknown, estimote.beacons.ProximityImmediate, estimote.beacons.ProximityNear, estimote.beacons.ProximityFar

Beacon properties available only when scanning:

* macAddress
* measuredPower

The full set of properties available on iOS are documented in the Estimote iOS SDK:
http://estimote.github.io/iOS-SDK/Classes/ESTBeacon.html

### Beacon properties available on Android

Beacon properties available when ranging:

* proximityUUID - UUID of the beacon
* major - major value of the beacon
* minor - minor value of the beacon
* rssi - number representing the Received Signal Strength Indication
* name - the name advertised by the beacon
* macAddress
* measuredPower

The properties available on Android are documented in the [Estimote Android SDK](http://estimote.github.io/Android-SDK/JavaDocs/index.html?com/estimote/sdk/Beacon.html)

### Beacon code example

Using the above data you can do all sorts of things, identify which beacons are close, how far they are, if they are close, and so on. Here is an example of how to access the beacon distance property:

    var region = { identifier: 'MyRegion' }

    estimote.beacons.startRangingBeaconsInRegion(
        region,
        onBeaconsRanged,
        onError)

    function onBeaconsRanged(beaconInfo)
    {
        // Sort beacons by distance.
        beaconInfo.beacons.sort(function(beacon1, beacon2) {
            return beacon1.distance > beacon2.distance })

        // Log distance for the closest beacon.
        var beacon = beaconInfo.beacons[0]
        console.log('Closest beacon is ' + beacon.distance + 'm away')
    }

    function onError(error)
    {
        console.log('Start ranging error: ' + error)
    }

### Secure Beacons (iOS)

You can use Estimote Secure Beacons from JavaScript.

Two steps are needed. First set the App ID and App Token. Second set the 'secure' property of the region you are using for monitoring/ranging to true.

Here is an example:

	// Step 1: Set App ID and App Token.
	estimote.beacons.setupAppIDAndAppToken('MyAppID', 'MyAppToken')

	// Step 2: Specify secure field in region object.
    var region = { identifier: 'MyRegion', secure: true }
    estimote.beacons.startRangingBeaconsInRegion(
        region,
        onBeaconsRanged,
        onError)

Read more about Secure Beacons in this article: https://community.estimote.com/hc/en-us/articles/204233603-How-security-feature-works

### Virtual Beacons (iOS)

A virtual beacon is an iOS device acting as an Estimote Beacon.

Here is how you turn your iPhone into a Beacon using the JavaScript API.

Function startAdvertisingAsBeacon starts advertising as a beacon:

    estimote.beacons.startAdvertisingAsBeacon(
        UUIDString
        majorValue,
        minorValue,
        regionName,
        successCallback,
        errorCallback)

Example that starts advertising:

    estimote.beacons.startAdvertisingAsBeacon(
        'B9407F30-F5F8-466E-AFF9-25556B57FE6D', // UUID
        1, // Major
        1, // Minor
        'MyRegion', // Region name (not visible?)
        function(result) {
            console.log('Beacon started') },
        function(errorMessage) {
            console.log('Error starting beacon: ' + errorMessage) })

Now you can run an Estimote Beacon scanning app on another device and your iPhone should be detected. Remember to use the same UUID when ranging/monitoring as the one used in the call to startAdvertisingAsBeacon.

Function stopAdvertisingAsBeacon stops advertising:

    estimote.beacons.stopAdvertisingAsBeacon(
        successCallback,
        errorCallback)

Here is an example:

    estimote.beacons.stopAdvertisingAsBeacon(
        function(result) {
            console.log('Beacon stopped') },
        function(errorMessage) {
            console.log('Error stopping beacon: ' + errorMessage) })

## Nearables API for iOS (Estimote Stickers)

### Start and stop ranging nearables (iOS only)

You can range for nearables by type:

    estimote.nearables.startRangingForType(
		estimote.nearables.NearableTypeAll,
        successCallback,
        errorCallback)

    estimote.nearables.stopRangingForType(
		estimote.nearables.NearableTypeAll,
        successCallback,
    	errorCallback)

Example successCallback function used when ranging for type (note that the callback gets an array of nearables):

    function successCallback(nearables) {
        console.log('Number of ranged nearables: ' + nearables.length) }

Or you can range for a specific beacon using the unique nearable identifier:

    estimote.nearables.startRangingForIdentifier(
		identifier,
        successCallback,
        errorCallback)

    estimote.nearables.stopRangingForIdentifier(
		identifier,
        successCallback,
    	errorCallback)

Example successCallback function used when ranging for identifier (note that the callback gets a single nearable):

    function successCallback(nearable) {
        console.log('Ranged nearable: ' + nearable.nameForType) }

Stop all ongoing nearable ranging:

    estimote.nearables.stopRanging()

### Nearable properties available when ranging

* type: number
* nameForType: string
* color: number
* nameForColor: string
* identifier: string
* hardwareVersion: string
* firmwareVersion: string
* rssi: number
* zone: number
* idleBatteryVoltage: number
* stressBatteryVoltage: number
* currentMotionStateDuration: number
* previousMotionStateDuration: number
* isMoving: bool
* orientation: number
* xAcceleration: number
* yAcceleration: number
* zAcceleration: number
* temperature: number
* power: number
* firmwareState: number

### Start and stop monitoring nearables (iOS only)

You can monitor for nearables by type:

    estimote.nearables.startMonitoringForType(
		estimote.nearables.NearableTypeDog,
        successCallback,
        errorCallback)

    estimote.nearables.stopMonitoringForType(
		estimote.nearables.NearableTypeDog,
        successCallback,
    	errorCallback)

Example successCallback function used when monitoring for type:

    function successCallback(state) {
        console.log('Type: ' + state.type + ' state: ' + state.state) }

Or you can monitor by the unique nearable identifier:

    estimote.nearables.startMonitoringForIdentifier(
		identifier,
        successCallback,
        errorCallback)

    estimote.nearables.stopMonitoringForIdentifier(
		identifier,
        successCallback,
    	errorCallback)

Example successCallback function used when monitoring for identifier:

    function successCallback(state) {
        console.log('Identifier: ' + state.identifier + ' state: ' + state.state) }

Stop all ongoing nearable monitoring:

    estimote.nearables.stopRanging()

### Using triggers with nearables (iOS only)

The Estimote trigger engine can be used to monitor for nearables using rules. In general, you use one rule for each nearable you wish to monitor. A trigger can contain one or more rules.

Each rule has en update function that is called by the trigger engine. The update function gets a nearable as a parameter and can inspect the properties of the nearable to determine if the rule holds true or not. The rule function should then call into the trigger engine and pass true or false to make the engine update the state for the trigger.

The actual trigger monitoring callback function is called when the trigger as a whole changes its state. The state is true if all rules hold, and false otherwise. The trigger callback is only called when the compound trigger state is changed. Update functions for individual rules are called continuously.

Here is a code example to give a taste of this style of coding. The trigger we monitor for tells us if our dos is moving or is still (assuming we have attached a Dog Sticker to our dog ;)

    // Called when trigger changes state.
    function onTriggerChangedState(trigger) {
        if (trigger.state)
            console.log('Dog is moving')
        else
            console.log('Dog is still')
    }

    // Called is case of error.
    function onTriggerError(errorMessage) {
        console.log('Trigger error: ' + errorMessage)
    }

    // Trigger rule.
    dogIsMovingRule = estimote.triggers.createRuleForNearable(
        estimote.nearables.NearableTypeDog,
        estimote.triggers.rules.nearableIsMoving())

    // Trigger.
    trigger = estimote.triggers.createTrigger('DogTrigger', [dogIsMovingRule])

    // Start monitoring for trigger.
    estimote.triggers.startMonitoringForTrigger(
        trigger,
        onTriggerChangedState,
        onTriggerError)

And here is how to stop monitoring a trigger:

    estimote.triggers.stopMonitoringForTrigger(trigger)


text:
package org.spoofax.interpreter.library.ssl;

import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.core.InterpreterException;
import org.spoofax.interpreter.library.AbstractPrimitive;
import org.spoofax.interpreter.stratego.Strategy;
import org.spoofax.interpreter.terms.IStrategoInt;
import org.spoofax.interpreter.terms.IStrategoReal;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.terms.util.TermUtils;

public class SSL_real_to_string_precision extends AbstractPrimitive {

    protected SSL_real_to_string_precision() {
        super("SSL_real_to_string_precision", 0, 2);
    }

    @Override
    public boolean call(IContext env, Strategy[] sargs, IStrategoTerm[] targs) throws InterpreterException {

        if(!(TermUtils.isReal(targs[0])))
            return false;
        if(!(TermUtils.isInt(targs[1])))
            return false;

        IStrategoReal a = (IStrategoReal) targs[0];
        IStrategoInt b = (IStrategoInt) targs[1];
        String s = String.format("%." + b.intValue() + "f", a.realValue());
        env.setCurrent(env.getFactory().makeString(s));
        return true;
    }
}


text:
<?php  namespace EntityMapper;

use Illuminate\Container\Container;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\ConnectionResolverInterface as Resolver;

class Repository {

    protected static $app;

    /**
     * @var mixed
     */
    protected $entity;

    /**
     * @var EntityMapper
     */
    protected $mapper;

    /**
     * Database connection
     * @var string
     */
    protected $connection;

    /**
     * The connection resolver instance.
     *
     * @var \Illuminate\Database\ConnectionResolverInterface
     */
    protected static $resolver;

    public function all($columns = ['*'])
    {
        return $this->query()->get($columns);
    }

    public function find($id, $columns = ['*'])
    {
        if( is_array($id) )
        {
            return $this->query()->findMany($id, $columns);
        }

        return $this->query()->find($id, $columns);
    }

    public function findOrFail($id, $columns = ['*'])
    {
        if ( ! is_null($entity = $this->query()->find($id, $columns)) ) return $entity;

        throw new EntityNotFoundException(get_class($entity));
    }

    /*
     * public function create(array $data) {} - Factory??
     * public function firstByAttributess($attributes) {}
     * */

    public function save($entity)
    {
        return $this->query()->save($entity);
    }

    public function delete($entity) {}
    public function touch($entity) {}

    /**
     * Set Entity class/class table
     * @param mixed $entityClassName
     */
    public function setEntity($entityClassName)
    {
        $this->entity = $entityClassName;
    }

    /**
     * Set mapper for this class
     * @param EntityMapper $mapper
     */
    public function setMapper(EntityMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    /**
     * Get the EntityMapper instance
     * @return EntityMapper
     */
    public function getMapper()
    {
        return $this->mapper;
    }

    /**
     * Get new Query Builder to build
     * entities for Select operations
     * @return Builder
     */
    public function query()
    {
        return new Builder( $this->newBaseQueryBuilder(), $this->entity, $this->mapper );
    }

    /**
     * Get a new query builder instance for the connection.
     * Used in the EntityMapper\Builder
     * @return \Illuminate\Database\Query\Builder
     */
    protected function newBaseQueryBuilder()
    {
        $conn = $this->getConnection();

        $grammar = $conn->getQueryGrammar();

        return new QueryBuilder($conn, $grammar, $conn->getPostProcessor());
    }

    // Date Logic?

    public function on($connection = null)
    {

    }

    public function getConnection()
    {
        return static::resolveConnection($this->connection);
    }

    public function getConnectionName()
    {
        return $this->connection;
    }

    public function setConnection($name)
    {
        $this->connection = $name;
    }

    public static function setConnectionResolver(Resolver $resolver)
    {
        static::$resolver = $resolver;
    }

    public static function getConnectionResolver()
    {
        return static::$resolver;
    }

    public static function resolveConnection($connection = null)
    {
        return static::$resolver->connection($connection);
    }

    /**
     * Set application container
     * used to create repository and dependencies
     * @param Container $app
     */
    public static function setApp(Container $app)
    {
        static::$app = $app;
    }

    /**
     * Get application container
     * @return mixed
     */
    public static function getApp()
    {
        return static::$app;
    }

    /**
     * Get the repository as specified by the Entity class
     * @param mixed $entityClassName Fully Qualified Class Name
     * @return Repository
     */
    public static function getRepository($entityClassName)
    {
        $app = static::getApp();

        $entityMapper = $app->make('EntityMapper\EntityMapper');

        // Set repository and its dependencies
        $repositoryClassName = $entityMapper->repository($entityClassName);
        $repository = ($repositoryClassName === 'base') ? new static : $app->make($repositoryClassName);
        $repository->setEntity($entityClassName);
        $repository->setMapper($entityMapper);

        return $repository;
    }

    /**
     * Handle dynamic method calls into the method.
     * Pass them to a new query Builder object
     * @param  string  $method
     * @param  array   $parameters
     * @return mixed
     */
    public function __call($method, $parameters)
    {
        $query = $this->query();

        return call_user_func_array(array($query, $method), $parameters);
    }
}