text:
""" This module offers highlevel functions to get package metadata
    like the METADATA file, the name, or a list of dependencies.

    Usage examples:

       # Getting package name from pip reference:
       from pytonforandroid.pythonpackage import get_package_name
       print(get_package_name("pillow"))
       # Outputs: "Pillow" (note the spelling!)

       # Getting package dependencies:
       from pytonforandroid.pythonpackage import get_package_dependencies
       print(get_package_dependencies("pep517"))
       # Outputs: "['pytoml']"

       # Get package name from arbitrary package source:
       from pytonforandroid.pythonpackage import get_package_name
       print(get_package_name("/some/local/project/folder/"))
       # Outputs package name

    NOTE:

    Yes, this module doesn't fit well into python-for-android, but this
    functionality isn't available ANYWHERE ELSE, and upstream (pip, ...)
    currently has no interest in taking this over, so it has no other place
    to go.
    (Unless someone reading this puts it into yet another packaging lib)

    Reference discussion/upstream inclusion attempt:

    https://github.com/pypa/packaging-problems/issues/247

"""

import functools
import os
import shutil
import subprocess
import sys
import tarfile
import tempfile
import textwrap
import time
import zipfile
from io import open  # needed for python 2
from urllib.parse import unquote as urlunquote
from urllib.parse import urlparse

import toml
from pep517.envbuild import BuildEnvironment
from pep517.wrappers import Pep517HookCaller

def transform_dep_for_pip(dependency):
    if dependency.find("@") > 0 and (
            dependency.find("@") < dependency.find("://") or
            "://" not in dependency
            ):
        # WORKAROUND FOR UPSTREAM BUG:
        # https://github.com/pypa/pip/issues/6097
        # (Please REMOVE workaround once that is fixed & released upstream!)
        #
        # Basically, setup_requires() can contain a format pip won't install
        # from a requirements.txt (PEP 508 URLs).
        # To avoid this, translate to an #egg= reference:
        if dependency.endswith("#"):
            dependency = dependency[:-1]
        url = (dependency.partition("@")[2].strip().partition("#egg")[0] +
               "#egg=" +
               dependency.partition("@")[0].strip()
              )
        return url
    return dependency

def extract_metainfo_files_from_package(
        package,
        output_folder,
        debug=False
        ):
    """ Extracts metdata files from the given package to the given folder,
        which may be referenced in any way that is permitted in
        a requirements.txt file or install_requires=[] listing.

        Current supported metadata files that will be extracted:

        - pytoml.yml  (only if package wasn't obtained as wheel)
        - METADATA
    """

    if package is None:
        raise ValueError("package cannot be None")

    if not os.path.exists(output_folder) or os.path.isfile(output_folder):
        raise ValueError("output folder needs to be existing folder")

    if debug:
        print("extract_metainfo_files_from_package: extracting for " +
              "package: " + str(package))

    # A temp folder for making a package copy in case it's a local folder,
    # because extracting metadata might modify files
    # (creating sdists/wheels...)
    temp_folder = tempfile.mkdtemp(prefix="pythonpackage-package-copy-")
    try:
        # Package is indeed a folder! Get a temp copy to work on:
        if is_filesystem_path(package):
            shutil.copytree(
                parse_as_folder_reference(package),
                os.path.join(temp_folder, "package"),
                ignore=shutil.ignore_patterns(".tox")
            )
            package = os.path.join(temp_folder, "package")

        # Because PEP517 can be noisy and contextlib.redirect_* fails to
        # contain it, we will run the actual analysis in a separate process:
        try:
            subprocess.check_output([
                sys.executable,
                "-c",
                "import importlib\n"
                "import json\n"
                "import os\n"
                "import sys\n"
                "sys.path = [os.path.dirname(sys.argv[3])] + sys.path\n"
                "m = importlib.import_module(\n"
                "    os.path.basename(sys.argv[3]).partition('.')[0]\n"
                ")\n"
                "m._extract_metainfo_files_from_package_unsafe("
                "    sys.argv[1],"
                "    sys.argv[2],"
                ")",
                package, output_folder, os.path.abspath(__file__)],
                stderr=subprocess.STDOUT,  # make sure stderr is muted.
                cwd=os.path.join(os.path.dirname(__file__), "..")
            )
        except subprocess.CalledProcessError as e:
            output = e.output.decode("utf-8", "replace")
            if debug:
                print("Got error obtaining meta info.")
                print("Detail output:")
                print(output)
                print("End of Detail output.")
            raise ValueError(
                "failed to obtain meta info - "
                "is '{}' a valid package? "
                "Detailed output:\n{}".format(package, output)
                )
    finally:
        shutil.rmtree(temp_folder)

def _get_system_python_executable():
    """ Returns the path the system-wide python binary.
        (In case we're running in a virtualenv or venv)
    """
    # This function is required by get_package_as_folder() to work
    # inside a virtualenv, since venv creation will fail with
    # the virtualenv's local python binary.
    # (venv/virtualenv incompatibility)

    # Abort if not in virtualenv or venv:
    if not hasattr(sys, "real_prefix") and (
            not hasattr(sys, "base_prefix") or
            os.path.normpath(sys.base_prefix) ==
            os.path.normpath(sys.prefix)):
        return sys.executable

    # Extract prefix we need to look in:
    if hasattr(sys, "real_prefix"):
        search_prefix = sys.real_prefix  # virtualenv
    else:
        search_prefix = sys.base_prefix  # venv

    def python_binary_from_folder(path):
        def binary_is_usable(python_bin):
            """ Helper function to see if a given binary name refers
                to a usable python interpreter binary
            """

            # Abort if path isn't present at all or a directory:
            if not os.path.exists(
                os.path.join(path, python_bin)
            ) or os.path.isdir(os.path.join(path, python_bin)):
                return
            # We should check file not found anyway trying to run it,
            # since it might be a dead symlink:
            try:
                filenotfounderror = FileNotFoundError
            except NameError:  # Python 2
                filenotfounderror = OSError
            try:
                # Run it and see if version output works with no error:
                subprocess.check_output([
                    os.path.join(path, python_bin), "--version"
                ], stderr=subprocess.STDOUT)
                return True
            except (subprocess.CalledProcessError, filenotfounderror):
                return False

        python_name = "python" + sys.version
        while (not binary_is_usable(python_name) and
               python_name.find(".") > 0):
            # Try less specific binary name:
            python_name = python_name.rpartition(".")[0]
        if binary_is_usable(python_name):
            return os.path.join(path, python_name)
        return None

    # Return from sys.real_prefix if present:
    result = python_binary_from_folder(search_prefix)
    if result is not None:
        return result

    # Check out all paths in $PATH:
    bad_candidates = []
    good_candidates = []
    ever_had_nonvenv_path = False
    ever_had_path_starting_with_prefix = False
    for p in os.environ.get("PATH", "").split(":"):
        # Skip if not possibly the real system python:
        if not os.path.normpath(p).startswith(
                os.path.normpath(search_prefix)
                ):
            continue

        ever_had_path_starting_with_prefix = True

        # First folders might be virtualenv/venv we want to avoid:
        if not ever_had_nonvenv_path:
            sep = os.path.sep
            if (
                ("system32" not in p.lower() and
                 "usr" not in p and
                 not p.startswith("/opt/python")) or
                {"home", ".tox"}.intersection(set(p.split(sep))) or
                "users" in p.lower()
            ):
                # Doesn't look like bog-standard system path.
                if (p.endswith(os.path.sep + "bin") or
                        p.endswith(os.path.sep + "bin" + os.path.sep)):
                    # Also ends in "bin" -> likely virtualenv/venv.
                    # Add as unfavorable / end of candidates:
                    bad_candidates.append(p)
                    continue
            ever_had_nonvenv_path = True

        good_candidates.append(p)

    # If we have a bad env with PATH not containing any reference to our
    # real python (travis, why would you do that to me?) then just guess
    # based from the search prefix location itself:
    if not ever_had_path_starting_with_prefix:
        # ... and yes we're scanning all the folders for that, it's dumb
        # but i'm not aware of a better way: (@JonasT)
        for root, dirs, files in os.walk(search_prefix, topdown=True):
            for name in dirs:
                bad_candidates.append(os.path.join(root, name))

    # Sort candidates by length (to prefer shorter ones):
    def candidate_cmp(a, b):
        return len(a) - len(b)
    good_candidates = sorted(
        good_candidates, key=functools.cmp_to_key(candidate_cmp)
    )
    bad_candidates = sorted(
        bad_candidates, key=functools.cmp_to_key(candidate_cmp)
    )

    # See if we can now actually find the system python:
    for p in good_candidates + bad_candidates:
        result = python_binary_from_folder(p)
        if result is not None:
            return result

    raise RuntimeError(
        "failed to locate system python in: {}"
        " - checked candidates were: {}, {}"
        .format(sys.real_prefix, good_candidates, bad_candidates)
    )

def get_package_as_folder(dependency):
    """ This function downloads the given package / dependency and extracts
        the raw contents into a folder.

        Afterwards, it returns a tuple with the type of distribution obtained,
        and the temporary folder it extracted to. It is the caller's
        responsibility to delete the returned temp folder after use.

        Examples of returned values:

        ("source", "/tmp/pythonpackage-venv-e84toiwjw")
        ("wheel", "/tmp/pythonpackage-venv-85u78uj")

        What the distribution type will be depends on what pip decides to
        download.
    """

    venv_parent = tempfile.mkdtemp(
        prefix="pythonpackage-venv-"
    )
    try:
        # Create a venv to install into:
        try:
            if int(sys.version.partition(".")[0]) < 3:
                # Python 2.x has no venv.
                subprocess.check_output([
                    sys.executable,  # no venv conflict possible,
                                     # -> no need to use system python
                    "-m", "virtualenv",
                    "--python=" + _get_system_python_executable(),
                    os.path.join(venv_parent, 'venv')
                ], cwd=venv_parent)
            else:
                # On modern Python 3, use venv.
                subprocess.check_output([
                    _get_system_python_executable(), "-m", "venv",
                    os.path.join(venv_parent, 'venv')
                ], cwd=venv_parent)
        except subprocess.CalledProcessError as e:
            output = e.output.decode('utf-8', 'replace')
            raise ValueError(
                'venv creation unexpectedly ' +
                'failed. error output: ' + str(output)
            )
        venv_path = os.path.join(venv_parent, "venv")

        # Update pip and wheel in venv for latest feature support:
        try:
            filenotfounderror = FileNotFoundError
        except NameError:  # Python 2.
            filenotfounderror = OSError
        try:
            subprocess.check_output([
                os.path.join(venv_path, "bin", "pip"),
                "install", "-U", "pip", "wheel",
            ])
        except filenotfounderror:
            raise RuntimeError(
                "venv appears to be missing pip. "
                "did we fail to use a proper system python??\n"
                "system python path detected: {}\n"
                "os.environ['PATH']: {}".format(
                    _get_system_python_executable(),
                    os.environ.get("PATH", "")
                )
            )

        # Create download subfolder:
        os.mkdir(os.path.join(venv_path, "download"))

        # Write a requirements.txt with our package and download:
        with open(os.path.join(venv_path, "requirements.txt"),
                  "w", encoding="utf-8"
                 ) as f:
            def to_unicode(s):  # Needed for Python 2.
                try:
                    return s.decode("utf-8")
                except AttributeError:
                    return s
            f.write(to_unicode(transform_dep_for_pip(dependency)))
        try:
            subprocess.check_output(
                [
                    os.path.join(venv_path, "bin", "pip"),
                    "download", "--no-deps", "-r", "../requirements.txt",
                    "-d", os.path.join(venv_path, "download")
                ],
                stderr=subprocess.STDOUT,
                cwd=os.path.join(venv_path, "download")
            )
        except subprocess.CalledProcessError as e:
            raise RuntimeError("package download failed: " + str(e.output))

        if len(os.listdir(os.path.join(venv_path, "download"))) == 0:
            # No download. This can happen if the dependency has a condition
            # which prohibits install in our environment.
            # (the "package ; ... conditional ... " type of condition)
            return (None, None)

        # Get the result and make sure it's an extracted directory:
        result_folder_or_file = os.path.join(
            venv_path, "download",
            os.listdir(os.path.join(venv_path, "download"))[0]
        )
        dl_type = "source"
        if not os.path.isdir(result_folder_or_file):
            # Must be an archive.
            if result_folder_or_file.endswith((".zip", ".whl")):
                if result_folder_or_file.endswith(".whl"):
                    dl_type = "wheel"
                with zipfile.ZipFile(result_folder_or_file) as f:
                    f.extractall(os.path.join(venv_path,
                                              "download", "extracted"
                                             ))
                    result_folder_or_file = os.path.join(
                        venv_path, "download", "extracted"
                    )
            elif result_folder_or_file.find(".tar.") > 0:
                # Probably a tarball.
                with tarfile.open(result_folder_or_file) as f:
                    f.extractall(os.path.join(venv_path,
                                              "download", "extracted"
                                             ))
                    result_folder_or_file = os.path.join(
                        venv_path, "download", "extracted"
                    )
            else:
                raise RuntimeError(
                    "unknown archive or download " +
                    "type: " + str(result_folder_or_file)
                )

        # If the result is hidden away in an additional subfolder,
        # descend into it:
        while os.path.isdir(result_folder_or_file) and \
                len(os.listdir(result_folder_or_file)) == 1 and \
                os.path.isdir(os.path.join(
                    result_folder_or_file,
                    os.listdir(result_folder_or_file)[0]
                )):
            result_folder_or_file = os.path.join(
                result_folder_or_file,
                os.listdir(result_folder_or_file)[0]
            )

        # Copy result to new dedicated folder so we can throw away
        # our entire virtualenv nonsense after returning:
        result_path = tempfile.mkdtemp()
        shutil.rmtree(result_path)
        shutil.copytree(result_folder_or_file, result_path)
        return (dl_type, result_path)
    finally:
        shutil.rmtree(venv_parent)

def _extract_metainfo_files_from_package_unsafe(
        package,
        output_path
        ):
    # This is the unwrapped function that will
    # 1. make lots of stdout/stderr noise
    # 2. possibly modify files (if the package source is a local folder)
    # Use extract_metainfo_files_from_package_folder instead which avoids
    # these issues.

    clean_up_path = False
    path_type = "source"
    path = parse_as_folder_reference(package)
    if path is None:
        # This is not a path. Download it:
        (path_type, path) = get_package_as_folder(package)
        if path_type is None:
            # Download failed.
            raise ValueError(
                "cannot get info for this package, " +
                "pip says it has no downloads (conditional dependency?)"
            )
        clean_up_path = True

    try:
        build_requires = []
        metadata_path = None

        if path_type != "wheel":
            # We need to process this first to get the metadata.

            # Ensure pyproject.toml is available (pep517 expects it)
            if not os.path.exists(os.path.join(path, "pyproject.toml")):
                with open(os.path.join(path, "pyproject.toml"), "w") as f:
                    f.write(textwrap.dedent(u"""\
                    [build-system]
                    requires = ["setuptools", "wheel"]
                    build-backend = "setuptools.build_meta"
                    """))

            # Copy the pyproject.toml:
            shutil.copyfile(
                os.path.join(path, 'pyproject.toml'),
                os.path.join(output_path, 'pyproject.toml')
            )

            # Get build backend and requirements from pyproject.toml:
            with open(os.path.join(path, 'pyproject.toml')) as f:
                build_sys = toml.load(f)['build-system']
                backend = build_sys["build-backend"]
                build_requires.extend(build_sys["requires"])

            # Get a virtualenv with build requirements and get all metadata:
            env = BuildEnvironment()
            metadata = None
            with env:
                hooks = Pep517HookCaller(path, backend)
                env.pip_install(
                    [transform_dep_for_pip(req) for req in build_requires]
                )
                reqs = hooks.get_requires_for_build_wheel({})
                env.pip_install([transform_dep_for_pip(req) for req in reqs])
                try:
                    metadata = hooks.prepare_metadata_for_build_wheel(path)
                except Exception:  # sadly, pep517 has no good error here
                    pass
            if metadata is not None:
                metadata_path = os.path.join(
                    path, metadata, "METADATA"
                )
        else:
            # This is a wheel, so metadata should be in *.dist-info folder:
            metadata_path = os.path.join(
                path,
                [f for f in os.listdir(path) if f.endswith(".dist-info")][0],
                "METADATA"
            )

        # Store type of metadata source. Can be "wheel", "source" for source
        # distribution, and others get_package_as_folder() may support
        # in the future.
        with open(os.path.join(output_path, "metadata_source"), "w") as f:
            try:
                f.write(path_type)
            except TypeError:  # in python 2 path_type may be str/bytes:
                f.write(path_type.decode("utf-8", "replace"))

        # Copy the metadata file:
        shutil.copyfile(metadata_path, os.path.join(output_path, "METADATA"))
    finally:
        if clean_up_path:
            shutil.rmtree(path)

def is_filesystem_path(dep):
    """ Convenience function around parse_as_folder_reference() to
        check if a dependency refers to a folder path or something remote.

        Returns True if local, False if remote.
    """
    return (parse_as_folder_reference(dep) is not None)

def parse_as_folder_reference(dep):
    """ See if a dependency reference refers to a folder path.
        If it does, return the folder path (which parses and
        resolves file:// urls in the process).
        If it doesn't, return None.
    """
    # Special case: pep508 urls
    if dep.find("@") > 0 and (
            (dep.find("@") < dep.find("/") or "/" not in dep) and
            (dep.find("@") < dep.find(":") or ":" not in dep)
            ):
        # This should be a 'pkgname @ https://...' style path, or
        # 'pkname @ /local/file/path'.
        return parse_as_folder_reference(dep.partition("@")[2].lstrip())

    # Check if this is either not an url, or a file URL:
    if dep.startswith(("/", "file://")) or (
            dep.find("/") > 0 and
            dep.find("://") < 0) or (dep in ["", "."]):
        if dep.startswith("file://"):
            dep = urlunquote(urlparse(dep).path)
        return dep
    return None

def _extract_info_from_package(dependency,
                               extract_type=None,
                               debug=False,
                               include_build_requirements=False
                               ):
    """ Internal function to extract metainfo from a package.
        Currently supported info types:

        - name
        - dependencies  (a list of dependencies)
    """
    if debug:
        print("_extract_info_from_package called with "
              "extract_type={} include_build_requirements={}".format(
                  extract_type, include_build_requirements,
              ))
    output_folder = tempfile.mkdtemp(prefix="pythonpackage-metafolder-")
    try:
        extract_metainfo_files_from_package(
            dependency, output_folder, debug=debug
        )

        # Extract the type of data source we used to get the metadata:
        with open(os.path.join(output_folder,
                               "metadata_source"), "r") as f:
            metadata_source_type = f.read().strip()

        # Extract main METADATA file:
        with open(os.path.join(output_folder, "METADATA"),
                  "r", encoding="utf-8"
                 ) as f:
            # Get metadata and cut away description (is after 2 linebreaks)
            metadata_entries = f.read().partition("\n\n")[0].splitlines()

        if extract_type == "name":
            name = None
            for meta_entry in metadata_entries:
                if meta_entry.lower().startswith("name:"):
                    return meta_entry.partition(":")[2].strip()
            if name is None:
                raise ValueError("failed to obtain package name")
            return name
        elif extract_type == "dependencies":
            # First, make sure we don't attempt to return build requirements
            # for wheels since they usually come without pyproject.toml
            # and we haven't implemented another way to get them:
            if include_build_requirements and \
                    metadata_source_type == "wheel":
                if debug:
                    print("_extract_info_from_package: was called "
                          "with include_build_requirements=True on "
                          "package obtained as wheel, raising error...")
                raise NotImplementedError(
                    "fetching build requirements for "
                    "wheels is not implemented"
                )

            # Get build requirements from pyproject.toml if requested:
            requirements = []
            if os.path.exists(os.path.join(output_folder,
                                           'pyproject.toml')
                              ) and include_build_requirements:
                # Read build system from pyproject.toml file: (PEP518)
                with open(os.path.join(output_folder, 'pyproject.toml')) as f:
                    build_sys = toml.load(f)['build-system']
                    if "requires" in build_sys:
                        requirements += build_sys["requires"]
            elif include_build_requirements:
                # For legacy packages with no pyproject.toml, we have to
                # add setuptools as default build system.
                requirements.append("setuptools")

            # Add requirements from metadata:
            requirements += [
                entry.rpartition("Requires-Dist:")[2].strip()
                for entry in metadata_entries
                if entry.startswith("Requires-Dist")
            ]

            return list(set(requirements))  # remove duplicates
    finally:
        shutil.rmtree(output_folder)

package_name_cache = dict()

def get_package_name(dependency,
                     use_cache=True):
    def timestamp():
        try:
            return time.monotonic()
        except AttributeError:
            return time.time()  # Python 2.
    try:
        value = package_name_cache[dependency]
        if value[0] + 600.0 > timestamp() and use_cache:
            return value[1]
    except KeyError:
        pass
    result = _extract_info_from_package(dependency, extract_type="name")
    package_name_cache[dependency] = (timestamp(), result)
    return result

def get_package_dependencies(package,
                             recursive=False,
                             verbose=False,
                             include_build_requirements=False):
    """ Obtain the dependencies from a package. Please note this
        function is possibly SLOW, especially if you enable
        the recursive mode.
    """
    packages_processed = set()
    package_queue = [package]
    reqs = set()
    reqs_as_names = set()
    while len(package_queue) > 0:
        current_queue = package_queue
        package_queue = []
        for package_dep in current_queue:
            new_reqs = set()
            if verbose:
                print("get_package_dependencies: resolving dependency "
                      f"to package name: {package_dep}")
            package = get_package_name(package_dep)
            if package.lower() in packages_processed:
                continue
            if verbose:
                print("get_package_dependencies: "
                      "processing package: {}".format(package))
                print("get_package_dependencies: "
                      "Packages seen so far: {}".format(
                          packages_processed
                      ))
            packages_processed.add(package.lower())

            # Use our regular folder processing to examine:
            new_reqs = new_reqs.union(_extract_info_from_package(
                package_dep, extract_type="dependencies",
                debug=verbose,
                include_build_requirements=include_build_requirements,
            ))

            # Process new requirements:
            if verbose:
                print('get_package_dependencies: collected '
                      "deps of '{}': {}".format(
                          package_dep, str(new_reqs),
                      ))
            for new_req in new_reqs:
                try:
                    req_name = get_package_name(new_req)
                except ValueError as e:
                    if new_req.find(";") >= 0:
                        # Conditional dep where condition isn't met?
                        # --> ignore it
                        continue
                    if verbose:
                        print("get_package_dependencies: " +
                              "unexpected failure to get name " +
                              "of '" + str(new_req) + "': " +
                              str(e))
                    raise RuntimeError(
                        "failed to get " +
                        "name of dependency: " + str(e)
                    )
                if req_name.lower() in reqs_as_names:
                    continue
                if req_name.lower() not in packages_processed:
                    package_queue.append(new_req)
                reqs.add(new_req)
                reqs_as_names.add(req_name.lower())

            # Bail out here if we're not scanning recursively:
            if not recursive:
                package_queue[:] = []  # wipe queue
                break
    if verbose:
        print("get_package_dependencies: returning result: {}".format(reqs))
    return reqs

def get_dep_names_of_package(
        package,
        keep_version_pins=False,
        recursive=False,
        verbose=False,
        include_build_requirements=False
        ):
    """ Gets the dependencies from the package in the given folder,
        then attempts to deduce the actual package name resulting
        from each dependency line, stripping away everything else.
    """

    # First, obtain the dependencies:
    dependencies = get_package_dependencies(
        package, recursive=recursive, verbose=verbose,
        include_build_requirements=include_build_requirements,
    )
    if verbose:
        print("get_dep_names_of_package_folder: " +
              "processing dependency list to names: " +
              str(dependencies))

    # Transform dependencies to their stripped down names:
    # (they can still have version pins/restrictions, conditionals, ...)
    dependency_names = set()
    for dep in dependencies:
        # If we are supposed to keep exact version pins, extract first:
        pin_to_append = ""
        if keep_version_pins and "(==" in dep and dep.endswith(")"):
            # This is a dependency of the format: 'pkg (==1.0)'
            pin_to_append = "==" + dep.rpartition("==")[2][:-1]
        elif keep_version_pins and "==" in dep and not dep.endswith(")"):
            # This is a dependency of the format: 'pkg==1.0'
            pin_to_append = "==" + dep.rpartition("==")[2]
        # Now get true (and e.g. case-corrected) dependency name:
        dep_name = get_package_name(dep) + pin_to_append
        dependency_names.add(dep_name)
    return dependency_names


text:
if (false) {} // remove this line. It is only here to fix issue #232
// module('Uniqueness options', {
  // setup: function() {
    // Ember.Validations.forms['new_user'] = {
      // type: 'ActionView::Helpers::FormBuilder',
      // input_tag: '

',
      // label_tag: '

',
      // validators: {'user[email]':{"uniqueness":[{"message": "must be unique", "scope":{'name':"pass"}}]},"presence":[{"message": "must be present"}]}
    // }

    // $('#qunit-fixture')
      // .append($('<form />', {
        // action: '/users',
        // 'data-validate': true,
        // method: 'post',
        // id: 'new_user'
      // }))
      // .find('form')
        // .append($('<input />', {
          // name: 'user[name]',
          // id: 'user_name',
          // type: 'text'
        // }))
        // .append($('<input />', {
          // name: 'user[email]',
          // id: 'user_email',
          // type: 'text'
        // }))

    // $('form#new_user').call();
  // }
// });

// test('when matching uniqueness on a non-nested resource', function() {
  // var element = $('<input type="text" name="user[email]"/>');
  // var options = { 'message': "failed validation" };
  // element.val('nottaken@test.com');
  // equal(Ember.Validations.validators.remote.uniqueness(model, property, options), undefined);
// });

// test('when matching uniqueness on a non-nested resource', function() {
  // var element = $('<input type="text" name="user[email]"/>');
  // var options = { 'message': "failed validation" };
  // element.val('taken@test.com');
  // equal(Ember.Validations.validators.remote.uniqueness(model, property, options), "failed validation");
// });

// test('when matching uniqueness on a nested singular resource', function() {
  // var element = $('<input type="text" name="profile[user_attributes][email]"/>');
  // var options = { 'message': "failed validation" };
  // element.val('nottaken@test.com');
  // equal(Ember.Validations.validators.remote.uniqueness(model, property, options), undefined);
// });

// test('when matching uniqueness on a nested singular resource', function() {
  // var element = $('<input type="text" name="profile[user_attributes][email]"/>');
  // var options = { 'message': "failed validation" };
  // element.val('taken@test.com');
  // equal(Ember.Validations.validators.remote.uniqueness(model, property, options), "failed validation");
// });

// test('when using scopes with no replacement', function() {
  // var element = $('<input type="text" name="person[age]" />');
  // var options = { 'message': "failed validation", 'with': /\d+/, 'scope': { 'name': 'test name' } };
  // element.val('test');
  // equal(Ember.Validations.validators.remote.uniqueness(model, property, options), "failed validation");
// });

// test('when using scopes with replacement', function() {
  // var element = $('<input type="text" name="person[age]" />');
  // var options = { 'message': "failed validation", 'with': /\d+/, 'scope': { 'name': 'test name' } };
  // element.val('test')
  // $('#qunit-fixture').append('<input type="text" name="person[name]" />').find('input[name="person[name]"]').val('other name');
  // equal(Ember.Validations.validators.remote.uniqueness(model, property, options), undefined);
// });

// test('when validating by scope and mixed focus order', function() {
  // var unique_element = $('#user_email'), scope_element = $('#user_name');
  // unique_element.val('free@test.com');
  // unique_element.trigger('change');
  // unique_element.trigger('focusout');
  // equal($('.message[for="user_email"]').text(), '');

  // scope_element.val('test name');
  // scope_element.trigger('change');
  // scope_element.trigger('focusout');
  // equal($('.message[for="user_email"]').text(), 'must be unique');
// });

// test('when using scopes with replacement as checkboxes', function() {
  // var element = $('<input type="text" name="person[age]" />');
  // var options = { 'message': "failed validation", 'with': /\d+/, 'scope': { 'name': 'test name' } };
  // element.val('test')
  // $('#qunit-fixture')
    // .append('<input type="hidden" name="person[name]" value="other name"')
    // .append('<input type="checkbox" name="person[name]" value="test name"/>')
    // .find('input[name="person[name]"]').val('other name');
  // equal(Ember.Validations.validators.remote.uniqueness(model, property, options), undefined);
  // $('[name="person[name]"]:checkbox')[0].checked = true;
  // equal(Ember.Validations.validators.remote.uniqueness(model, property, options), 'failed validation');
// });

// test('when matching uniqueness on a resource with a defined class name', function() {
  // var element = $('<input type="text" name="user2[email]"/>');
  // var options = { 'message': "failed validation", 'class': "active_record_test_module/user2" };
  // element.val('nottaken@test.com');
  // equal(Ember.Validations.validators.remote.uniqueness(model, property, options), 'failed validation');
// });

// test('when allowing blank', function() {
 // var element = $('<input type="text" name="user2[email]" />');
 // var options = { 'message': "failed validation", 'with': /\d+/, 'allowBlank': true };
 // equal(Ember.Validations.validators.remote.uniqueness(model, property, options), undefined);
// });

// test('when not allowing blank', function() {
 // var element = $('<input type="text" name="user2[email]" />');
 // var options = { 'message': "failed validation", 'with': /\d+/ };
 // equal(Ember.Validations.validators.remote.uniqueness(model, property, options), "failed validation");
// });

// test('when matching local uniqueness for nested has-many resources', function() {
  // $('#qunit-fixture')
    // .append($('<form />', {
      // action: '/users',
      // 'data-validate': true,
      // method: 'post',
      // id: 'new_user_2'
    // }))
    // .find('form')
      // .append($('<input />', {
        // name: 'profile[user_attributes][0][email]',
        // id: 'user_0_email',
      // }))
      // .append($('<input />', {
        // name: 'profile[user_attributes][1][email]',
        // id: 'user_1_email',
      // }));

  // Ember.Validations.forms['new_user_2'] = {
    // type: 'ActionView::Helpers::FormBuilder',
    // input_tag: '

',
    // label_tag: '

',
    // validators: { 'user[email]':{"uniqueness":[{"message": "must be unique"}]}}
  // }
  // $('form#new_user_2').call();

  // var user_0_email = $('#user_0_email'),
      // user_1_email = $('#user_1_email'),
      // options = { 'message': "must be unique" };

  // user_0_email.val('not-locally-unique');
  // user_1_email.val('not-locally-unique');

  // equal(Ember.Validations.validators.remote.uniqueness(user_1_email, options), undefined);
  // equal(Ember.Validations.validators.local.uniqueness(user_1_email, options), "must be unique");
// });

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Runtime.InteropServices;

using Saserdote.Mathematics.Collision;

namespace Saserdote.Mathematics
{
	[StructLayout(LayoutKind.Sequential)]
	public struct Point3i
	{
		#region --- Field Variables ---

		// Variables
		public int	x;
		public int	y;
		public int	z;
		public readonly static Point3i	ORIGIN=	new Point3i(0);

		#endregion // Field Variables

		#region --- Constructors ---

		public Point3i(int pmX, int pmY, int pmZ)
		{
			x=	pmX;
			y=	pmY;
			z=	pmZ;
		}
		internal Point3i(int all):this(all, all, all)	{}

		#endregion // Constructors

		#region --- Methods ---

		// Converts the point into a floating point
		public Point3f toPoint3f()
		{
			return new Point3f((float)x, (float)y, (float)z);
		}

		// Converts the 3d point into a 2d point
		public Point2f toPoint2f()
		{
			return new Point2f((float)x, (float)y);
		}

		// Converts the 3d point into a 2d point
		public Point2i toPoint2i()
		{
			return new Point2i(x, y);
		}

		// Converts the point into a vector
		public Vector3 toVector3()
		{
			return new Vector3((float)x, (float)y, (float)z);
		}

		// Converts the point into a vector
		public Vector2 toVector2()
		{
			return new Vector2((float)x, (float)y);
		}

		// Adds the point with the vector to get another point
		public Point3i add(Vector3 vec)
		{
			return new Point3i(x+(int)vec.x, y+(int)vec.y, z+(int)vec.z);
		}

		// Adds the point with the vector to get another point
		public Point3i add(Vector2 vec)
		{
			return new Point3i(x+(int)vec.x, y+(int)vec.y, z);
		}

		// Adds the point with a size to get another point
		public Point3i add(Size3f size)
		{
			return new Point3i(x+(int)size.width, y+(int)size.height, z+(int)size.depth);
		}

		// Adds the point with a size to get another point
		public Point3i add(Size3i size)
		{
			return new Point3i(x+size.width, y+size.height, z+size.depth);
		}

		// Adds the point with a size to get another point
		public Point3i add(Size2f size)
		{
			return new Point3i(x+(int)size.width, y+(int)size.height, z);
		}

		// Adds the point with a size to get another point
		public Point3i add(Size2i size)
		{
			return new Point3i(x+size.width, y+size.height, z);
		}

		// Subtracts the point with the vector to get another point
		public Point3i subtract(Vector3 vec)
		{
			return new Point3i(x-(int)vec.x, y-(int)vec.y, z-(int)vec.z);
		}

		// Subtracts the point with the vector to get another point
		public Point3i subtract(Vector2 vec)
		{
			return new Point3i(x-(int)vec.x, y-(int)vec.y, z);
		}

		// Subtracts the point with a size to get another point
		public Point3i subtract(Size3f size)
		{
			return new Point3i(x-(int)size.width, y-(int)size.height, z-(int)size.depth);
		}

		// Subtracts the point with a size to get another point
		public Point3i subtract(Size3i size)
		{
			return new Point3i(x-size.width, y-size.height, z-size.depth);
		}

		// Subtracts the point with a size to get another point
		public Point3i subtract(Size2f size)
		{
			return new Point3i(x-(int)size.width, y-(int)size.height, z);
		}

		// Subtracts the point with a size to get another point
		public Point3i subtract(Size2i size)
		{
			return new Point3i(x-size.width, y-size.height, z);
		}

		// Subtracts the two points to get a vector pointing in between both
		public Vector3 subtract(Point3i pt)
		{
			return new Vector3((float)(x-pt.x), (float)(y-pt.y), (float)(z-pt.z));
		}

		// Subtracts the two points to get a vector pointing in between both
		public Vector3 subtract(Point3f pt)
		{
			return new Vector3((float)x-pt.x, (float)y-pt.y, (float)z-pt.z);
		}

		// Subtracts the two points to get a vector pointing in between both
		public Vector3 subtract(Point2i pt)
		{
			return new Vector3((float)(x-pt.x), (float)(y-pt.y), (float)z);
		}

		// Subtracts the two points to get a vector pointing in between both
		public Vector3 subtract(Point2f pt)
		{
			return new Vector3((float)x-pt.x, (float)y-pt.y, (float)z);
		}

		// Gets the midpoint of the two points
		public Point3f getMidpoint(Point3f pt)
		{
			return new Point3f(((float)x+pt.x)/2f, ((float)y+pt.y)/2f, ((float)z+pt.z)/2f);
		}

		// Gets the midpoint of the two points
		public Point3f getMidpoint(Point3i pt)
		{
			return new Point3f((float)(x+pt.x)/2f, (float)(y+pt.y)/2f, (float)(z+pt.z)/2f);
		}

		// Gets the midpoint of the two points
		public Point3f getMidpoint(Point2f pt)
		{
			return new Point3f(((float)x+pt.x)/2f, ((float)y+pt.y)/2f, (float)z/2f);
		}

		// Gets the midpoint of the two points
		public Point3f getMidpoint(Point2i pt)
		{
			return new Point3f((float)(x+pt.x)/2f, (float)(y+pt.y)/2f, (float)z/2f);
		}

		// Finds if the two points are equal
		public bool equals(Point3i pt)
		{
			return (x== pt.x && y== pt.y && z== pt.z);
		}

		// Finds if the two points are equal
		public bool equals(Point3f pt)
		{
			return (x== (int)pt.x && y== (int)pt.y && z== (int)pt.z);
		}

		#endregion // Methods

		#region --- Inherited Methods ---

		// Finds out if the given object is equal to the point
		public override bool Equals(object obj)
		{
			if(obj== null)
				return false;

			if(obj is Point3f)
				return equals((Point3f)obj);
			if(obj is Point3i)
				return equals((Point3i)obj);

			return false;
		}

		// Gets the hash code
		public override int GetHashCode()
		{
			return (x^y^z);
		}

		// Prints out the contents of the point
		public override string ToString()
		{
			return "X:"+x+",Y:"+y+",Z:"+z;
		}

		#endregion // Inherited Methods

		#region --- Operators ---

		// Equality operators
		public static bool operator ==(Point3i left, Point3i right)
		{
			return left.equals(right);
		}
		public static bool operator ==(Point3i left, Point3f right)
		{
			return left.equals(right);
		}

		// Inequality operators
		public static bool operator !=(Point3i left, Point3i right)
		{
			return !left.equals(right);
		}
		public static bool operator !=(Point3i left, Point3f right)
		{
			return !left.equals(right);
		}

		// Addition operators
		public static Point3i operator +(Point3i left, Vector3 right)
		{
			return left.add(right);
		}
		public static Point3i operator +(Point3i left, Vector2 right)
		{
			return left.add(right);
		}
		public static Point3i operator +(Point3i left, Size3f right)
		{
			return left.add(right);
		}
		public static Point3i operator +(Point3i left, Size3i right)
		{
			return left.add(right);
		}
		public static Point3i operator +(Point3i left, Size2f right)
		{
			return left.add(right);
		}
		public static Point3i operator +(Point3i left, Size2i right)
		{
			return left.add(right);
		}

		// Subtration operators
		public static Point3i operator -(Point3i left, Vector3 right)
		{
			return left.subtract(right);
		}
		public static Point3i operator -(Point3i left, Vector2 right)
		{
			return left.subtract(right);
		}
		public static Point3i operator -(Point3i left, Size3f right)
		{
			return left.subtract(right);
		}
		public static Point3i operator -(Point3i left, Size3i right)
		{
			return left.subtract(right);
		}
		public static Point3i operator -(Point3i left, Size2f right)
		{
			return left.subtract(right);
		}
		public static Point3i operator -(Point3i left, Size2i right)
		{
			return left.subtract(right);
		}
		public static Vector3 operator -(Point3i left, Point3f right)
		{
			return left.subtract(right);
		}
		public static Vector3 operator -(Point3i left, Point3i right)
		{
			return left.subtract(right);
		}
		public static Vector3 operator -(Point3i left, Point2f right)
		{
			return left.subtract(right);
		}
		public static Vector3 operator -(Point3i left, Point2i right)
		{
			return left.subtract(right);
		}

		// Multiplication operators
		public static bool operator *(Point3i left, BoundingVolume right)
		{
			return right.contains(left);
		}

		// Unkown name operators
		public static Point3f operator |(Point3i left, Point3f right)
		{
			return left.getMidpoint(right);
		}
		public static Point3f operator |(Point3i left, Point3i right)
		{
			return left.getMidpoint(right);
		}
		public static Point3f operator |(Point3i left, Point2f right)
		{
			return left.getMidpoint(right);
		}
		public static Point3f operator |(Point3i left, Point2i right)
		{
			return left.getMidpoint(right);
		}

		// Conversion operators
		// [Point3i to Vector3]
		public static explicit operator Vector3(Point3i castee)
		{
			return castee.toVector3();
		}
		// [Point3i to Vector2]
		public static explicit operator Vector2(Point3i castee)
		{
			return castee.toVector2();
		}
		// [Point3i to Point3f]
		public static implicit operator Point3f(Point3i castee)
		{
			return castee.toPoint3f();
		}
		// [Point3i to Point2f]
		public static explicit operator Point2f(Point3i castee)
		{
			return castee.toPoint2f();
		}
		// [Point3i to Point2i]
		public static explicit operator Point2i(Point3i castee)
		{
			return castee.toPoint2i();
		}

		#endregion // Operators
	}
}

// End of File


text:
<?php

namespace AnyContent\CMCK\Modules\Backend\Core\Listing;

use CMDL\CMDLParserException;

class ContentViewDefault extends BaseContentView
{

    /** @var  CellRenderer */
    protected $cellRenderer;

    public function getTemplate()
    {
        return 'listing-contentview-default.twig';
    }

    public function doesProcessSearch()
    {
        return true;
    }

    public function apply($vars)
    {

        // reset chained save operations (e.g. 'save-insert') to 'save' only upon listing of a content type
        if (key($this->getContext()->getCurrentSaveOperation()) != 'save-list')
        {
            $this->getContext()->setCurrentSaveOperation('save', 'Save');
        }

        // reset sorting order and search query if listing button has been pressed inside a listing
        if ($this->getRequest()->get('_route') == 'listRecordsReset')
        {
            $this->getContext()->setCurrentSortingOrder('.info.lastchange.timestamp-', false);
            $this->getContext()->setCurrentSearchTerm('');
        }

        $filter = $this->getFilter();

        $vars['searchTerm']   = $this->getContext()->getCurrentSearchTerm();
        $vars['itemsPerPage'] = $this->getContext()->getCurrentItemsPerPage();

        $vars['table']  = false;
        $vars['pager']  = false;
        $vars['filter'] = false;

        $records = $this->getRecords($filter);

        if (count($records) > 0)
        {
            $columns = $this->getColumnsDefinition();

            $vars['table'] = $this->buildTable($columns, $records);

            $count = $this->countRecords($filter);

            $vars['pager'] = $this->getPager()->renderPager($count, $this->getContext()
                                                                         ->getCurrentItemsPerPage(), $this->getContext()
                                                                                ->getCurrentListingPage(), 'listRecords', array( 'contentTypeAccessHash' => $this->getContentTypeAccessHash() ));

        }

        $vars['class']='row contenttype-'.strtolower($this->getContext()->getCurrentContentType()->getName());

        return $vars;
    }

    /**
     * backwards compatible converting of sorting instructions
     */
    public function getSortingOrder()
    {
        $sorting = $this->getContext()->getCurrentSortingOrder();

        $map = [ '.lastchange' => '.info.lastchange.timestamp', '.lastchange+' => '.info.lastchange.timestamp', '.lastchange-' => '.info.lastchange.timestamp-',
                 'change'      => '.info.lastchange.timestamp', 'change+' => '.info.lastchange.timestamp', 'change-' => '.info.lastchange.timestamp-',
                 'pos'         => 'position', 'pos+' => 'position', 'pos-' => 'position-'
        ];

        if (array_key_exists($sorting, $map))
        {
            $sorting = $map[$sorting];
        }

        return $sorting;
    }

    public function getFilter()
    {
        $filter = null;

        $searchTerm = $this->getContext()->getCurrentSearchTerm();
        if ($searchTerm != '')
        {
            $filter = FilterUtil::normalizeFilterQuery($this->app, $searchTerm, $this->getContentTypeDefinition());
        }

        return $filter;
    }

    public function getColumnsDefinition()
    {
        $contentTypeDefinition = $this->getContentTypeDefinition();

        $columns = [ ];

        $column = new AttributeColumn();
        $column->setTitle('ID');
        $column->setAttribute('id');
        $column->setLinkToRecord(true);
        $columns[] = $column;

        if ($contentTypeDefinition->hasSubtypes())
        {
            $column = new SubtypeColumn();
            $column->setTitle('Subtype');
            $columns[] = $column;
        }

        $column = new PropertyColumn();
        $column->setTitle('Name');
        $column->setProperty('name');
        $column->setLinkToRecord(true);
        try
        {
            $column->setFormElementDefinition($contentTypeDefinition->getViewDefinition('default')
                                                                    ->getFormElementDefinition('name'));
        }
        catch (CMDLParserException $e)
        {
            // If default view does not have a name form element
        }

        $columns[] = $column;

        $column = new AttributeColumn();
        $column->setTitle('Last Change');
        $column->setAttribute('lastchange');
        $columns[] = $column;

        if ($contentTypeDefinition->hasStatusList())
        {
            $column = new StatusColumn();
            $column->setTitle('Status');
            $columns[] = $column;
        }

        if ($contentTypeDefinition->isSortable())
        {
            $column = new AttributeColumn();
            $column->setTitle('Pos');
            $column->setAttribute('position');
            $columns[] = $column;
        }

        // Add Edit/Delete-Buttons

        $buttonColumn = new ButtonColumn();
        $buttonColumn->setEditButton(true);
        if ($this->canDo('delete', $this->getRepository(), $this->getContentTypeDefinition()))
        {
            $buttonColumn->setDeleteButton(true);
        }
        $buttonColumn->setRenderer($this->getCellRenderer());
        $columns[] = $buttonColumn;

        foreach ($columns as $column)
        {
            $column->setRenderer($this->getCellRenderer());
        }

        return $columns;
    }

    public function buildTable($columns, $records)
    {
        $table = [ ];

        foreach ($columns as $column)
        {
            $table['header'][] = $column;
        }

        $table['body'] = [ ];

        foreach ($records as $record)
        {
            $line = [ ];
            foreach ($columns as $column)
            {
                $line[] = $column->formatValue($record);
            }
            $table['body'][] = $line;
        }

        return $table;
    }

    /**
     * @return CellRenderer
     */
    public function getCellRenderer()
    {
        if (!$this->cellRenderer)
        {
            $this->cellRenderer = new CellRenderer($this->app);
        }

        return $this->cellRenderer;
    }

    public function countRecords($filter)
    {
        $repository = $this->getRepository();

        $page         = $this->getContext()->getCurrentListingPage();
        $itemsPerPage = $this->getContext()->getCurrentItemsPerPage();
        //$viewName     = 'default';

        $sorting = $this->getSortingOrder();

        //$count = $repository->countRecords($this->getContext()->getCurrentWorkspace(), $viewName, $this->getContext()
        //->getCurrentLanguage(), $sorting[0], $sorting[1], $itemsPerPage, $page, $filter, null, $this->getContext()->getCurrentTimeShift());

        $count = $repository->countRecords($filter);

        return $count;
    }

    public function getRecords($filter)
    {
        $repository = $this->getRepository();

        $page         = $this->getContext()->getCurrentListingPage();
        $itemsPerPage = $this->getContext()->getCurrentItemsPerPage();
        //$viewName     = 'default';

        $sorting = $this->getSortingOrder();

        return $repository->getRecords($filter, $sorting, $page, $itemsPerPage);

        //return $repository->getRecords($this->getContext()->getCurrentWorkspace(), $viewName, $this->getContext()
        //->getCurrentLanguage(), $sorting[0], $sorting[1], $itemsPerPage, $page, $filter, null, $this->getContext()
    }
}


text:
const { bold } = require( 'chalk' );
const path = require( 'path' );
const { sync: mkdir } = require( 'mkdirp' );
const Generator = require( 'yeoman-generator' );
const { dependencies, devDependencies } = require( './dependencies.json' );
const {
   getBanner,
   createBanner,
   dependenciesForPackageJson,
   verbatimFileObject
} = require( '../../lib/utils' );
const technologies = require( '../../lib/technologies' );
const commonPrompts = require( '../../lib/common-prompts' );
const { LICENSE_UNLICENSED } = require( '../../lib/constants' );

module.exports = class extends Generator {

   constructor( args, opts ) {
      super( args, opts );
      this.option( 'banner', {
         type: String,
         defaults: '',
         desc: 'Path to a text file whose contents are prepended as (license) header to source files'
      } );
   }

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   initializing() {
      const pathBasename = path.basename( this.destinationRoot() );

      this.vars = {
         name: pathBasename,
         description: '',
         author: this.config.get( 'author' ),
         banner: getBanner( this ),
         homepage: this.config.get( 'homepage' ),
         license: this.config.get( 'license' ) || LICENSE_UNLICENSED,
         privateModule: '',
         version: '0.1.0-pre',

         adapterIncludes: '',
         adapterModules: '[]',
         babelPluginsString: '[ "transform-object-rest-spread" ]',
         contentAreaWidgets: '[]',
         cssClassName: '',
         exampleWidgets: true,
         specRunnerPort: 8180,
         technologies: [],
         webpackResolveExtensionsString: '[ \'.js\', \'.jsx\' ]',
         webpackResolveAliases: '',
         webpackModuleRules: ''
      };
   }

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   prompting() {

      /* eslint-disable max-len */
      this.log( `
LaxarJS application generator v${this.rootGeneratorVersion()}

This generator will create the basic file- and directory structure of a LaxarJS application in the current directory.

For more information about a LaxarJS application, please see the docs at
https://laxarjs.org/docs/laxar-v2-latest/concepts/`
      );
      /* eslint-enable max-len */

      const prompts = [
         ...commonPrompts.prompts( 'application', this.vars ),
         {
            type: 'checkbox',
            name: 'technologies',
            message: 'Select integration technologies to include:\n',
            default: this.vars.technologies,
            choices: technologies
               .filter( _ => !_.isBuiltIn )
               .map( _ => ({
                  name: `${_.name} ("${_.integrationTechnology}")`,
                  value: `${_.integrationTechnology}`
               }) )
         },
         {
            type: 'confirm',
            name: 'exampleWidgets',
            message: 'Should a set of example widgets be generated?',
            default: this.vars.exampleWidgets
         }
      ];

      return this.prompt( prompts )
         .then( answers => {
            Object.assign( this.vars, answers );

            this.selectedAdapters = technologies.filter( _ =>
               _.isBuiltIn || this.vars.technologies.includes( _.integrationTechnology )
            );

            const adapterIncludes = [];
            const adapterModules = [];
            let webpackResolveAliases = '';
            let webpackModuleRules = '';
            const webpackResolveExtensions = [];
            const allDependencies = {
               dependencies: Object.assign( {}, dependencies ),
               devDependencies: Object.assign( {}, devDependencies )
            };
            const babelPlugins = JSON.parse( this.vars.babelPluginsString );
            this.selectedAdapters.forEach( _ => {
               Object.assign( allDependencies.dependencies, _.peerDependencies );
               Object.assign( allDependencies.devDependencies, _.devDependencies );

               if( !_.isBuiltIn ) {
                  const adapterModule = `${_.integrationTechnology}Adapter`;
                  const requireModule = `laxar-${_.integrationTechnology}-adapter`;
                  adapterIncludes.push( `import * as ${adapterModule} from '${requireModule}';`);
                  adapterModules.push( adapterModule );
               }

               if( _.babelPlugins && _.babelPlugins.length ) {
                  _.babelPlugins.forEach( p => babelPlugins.push( p ) );
               }

               if( _.webpackModuleRules && _.webpackModuleRules.length ) {
                  webpackModuleRules = _.webpackModuleRules.reduce( ( rules, rule ) => {
                     return `${rules},\n            ${rule}`;
                  }, webpackModuleRules );
               }
               if( _.webpackResolveAliases ) {
                  webpackResolveAliases = Object.keys( _.webpackResolveAliases )
                     .reduce( ( aliases, key ) => {
                        return `${aliases},\n            '${key}': '${_.webpackResolveAliases[ key ]}'`;
                     }, webpackResolveAliases );
                  Object.assign( webpackResolveAliases, _.webpackResolveAliases );
               }
               _.sourceFileExtensions.map( ext => `'${ext}'` ).forEach( ext => {
                  if( !webpackResolveExtensions.includes( ext ) ) {
                     webpackResolveExtensions.push( ext );
                  }
               } );
            } );
            this.vars.babelPluginsString = jsonList( babelPlugins );
            this.vars.dependenciesString = dependenciesForPackageJson( allDependencies.dependencies );
            this.vars.devDependenciesString = dependenciesForPackageJson( allDependencies.devDependencies );
            this.vars.adapterIncludes = adapterIncludes.join( '\n' );
            this.vars.adapterModules = `[ ${adapterModules.join( ', ' )} ]`;
            this.vars.webpackResolveAliases = webpackResolveAliases;
            this.vars.webpackModuleRules = webpackModuleRules;
            this.vars.webpackResolveExtensionsString = `[ ${webpackResolveExtensions.join( ', ' )} ]`;

            this.vars.cssClassName = this.vars.name.replace( /[_\s]+/, '-' );
            this.vars.banner = createBanner( this );
            this.vars.privateModule = this.vars.license === LICENSE_UNLICENSED ? '\n  "private": true,' : '';
         } );
   }

   configuring() {
      this.config.set( {
         author: this.vars.author,
         homepage: this.vars.homepage,
         license: this.vars.license,
         banner: this.vars.banner
      } );
   }

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   writing() {
      const binaryFilesToCopy = verbatimFileObject( [
         'favicon.ico'
      ] );
      const filesToCopy = verbatimFileObject( [
         'debug.html',
         'favicon.ico',
         'index.html',
         'init.js',
         'laxar.config.js',
         'package.json',
         'README.md',
         'webpack.config.js'
      ] );
      filesToCopy[ '_.babelrc' ] = '.babelrc';
      filesToCopy[ '_.gitignore' ] = '.gitignore';

      if( this.vars.exampleWidgets ) {
         filesToCopy[ 'demo.application/flows' ] = 'application/flows';
         filesToCopy[ 'demo.application/layouts' ] = 'application/layouts';
         filesToCopy[ 'demo.application/pages' ] = 'application/pages';
         this.selectedAdapters
            .map( _ => [
               `demo.application/widgets/example/${_.integrationTechnology}-hello-world-widget`,
               `application/widgets/example/${_.integrationTechnology}-hello-world-widget`
            ] )
            .forEach( ([ source, dest ]) => {
               filesToCopy[ source ] = dest;
            } );
         this.vars.contentAreaWidgets = jsonList( this.selectedAdapters.map(
            _ => ({ widget: `example/${_.integrationTechnology}-hello-world-widget` })
         ), 2 );
      }
      else {
         filesToCopy[ 'bare.application' ] = 'application';
         mkdir( path.join( this.destinationRoot(), 'application', 'widgets' ) );
      }
      mkdir( path.join( this.destinationRoot(), 'application', 'themes' ) );

      Object.keys( filesToCopy ).forEach( sourceFile => {
         this.fs.copyTpl(
            this.templatePath( sourceFile ),
            this.destinationPath( filesToCopy[ sourceFile ] ),
            this.vars
         );
      } );
      Object.keys( binaryFilesToCopy ).forEach( sourceFile => {
         this.fs.copy(
            this.templatePath( sourceFile ),
            this.destinationPath( binaryFilesToCopy[ sourceFile ] )
         );
      } );
   }

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   end() {
      this.log( `
Now run ${bold.italic( 'npm install' )} to get tools and dependencies.
Then you can run ${bold.italic( 'npm start' )} to start the development server.
There, enter the application through the ${bold.italic( 'debug.html' )}.
The ${bold.italic( 'README.md' )} contains more information.

Have fun developing your LaxarJS application!

Also, please have a look at the manuals:
https://laxarjs.org/docs/laxar-v2-latest/manuals/`
      );
   }

};

function jsonList( entries, parentIndent = 1 ) {
   const spacePerIndent = 3;
   const nestedIndentation = new Array( (spacePerIndent * parentIndent) + 1 ).join( ' ' );

   return JSON.stringify( entries, null, spacePerIndent )
      .split( '\n' )
      .join( `\n${nestedIndentation}` );
}


text:
package org.apache.causeway.core.metamodel.valuesemantics;

import javax.annotation.Priority;
import javax.inject.Named;

import org.springframework.stereotype.Component;

import org.apache.causeway.applib.annotation.PriorityPrecedence;
import org.apache.causeway.applib.util.schema.InteractionDtoUtils;
import org.apache.causeway.commons.collections.Can;
import org.apache.causeway.schema.ixn.v2.InteractionDto;

@Component
@Named("causeway.val.InteractionDtoValueSemantics")
@Priority(PriorityPrecedence.LATE)
public class InteractionDtoValueSemantics
extends XmlValueSemanticsAbstract<InteractionDto> {

    @Override
    public final Class<InteractionDto> getCorrespondingClass() {
        return InteractionDto.class;
    }

    // -- ENCODER DECODER

    @Override
    public final String toXml(final InteractionDto interactionDto) {
        return InteractionDtoUtils.toXml(interactionDto);
    }

    @Override
    public final InteractionDto fromXml(final String xml) {
        return InteractionDtoUtils.fromXml(xml);
    }

    // -- EXAMPLES

    @Override
    public Can<InteractionDto> getExamples() {
        return Can.of(new InteractionDto(), new InteractionDto());
    }

}


text:
<?php

class Pages extends CI_Controller{
    public function view($page ='home'){
        if(!file_exists(APPPATH.'views/pages/'.$page.'.php')){
            //load error page

            show_404();
        }
        $data['title']=ucfirst($page);
        $this->load->view('template/header');
        $this->load->view('pages/'.$page,$data);
        $this->load->view('template/footer');
    }
}
?>


text:
export default class DateUtil{

  static getDayText(day){
    switch (day){
      case 1: return '一';
      case 2: return '二';
      case 3: return '三';
      case 4: return '四';
      case 5: return '五';
      case 6: return '六';
      case 0: return '日';
    }
  }

  static getMonthText(month){
    if (month<9) return '0'+(month+1);
    else return month+1+'';
  }

  static getDateDayText(date){
    if (date<10) return '0'+date;
    else return date+'';
  }

  static getDateText(date){
    return this.getMonthText(date.getMonth())+'月'+date.getDate()+'日 星期'+this.getDayText(date.getDay());
  }

  static getBeforeText(date){
    return date.getFullYear()+this.getMonthText(date.getMonth())+this.getDateDayText(date.getDate());
  }

  static getCurrentDateText(){
    let date = new Date();
    return date.getFullYear().toString()+(date.getMonth()+1)+date.getDate();
  }

}


text:
docReady(function(){
	// build action for turning "make changes" on
	$(".page-controls").on("click", ".make-changes",function(){
		// turn off the button
		$(".make-changes").addClass("hidden");
		// turn on the controls
		$(".page-controls .cancel, .page-controls .save").removeClass("hidden");
		// hide the picks
		$(".game:not('.locked')").children(".picks").addClass("hidden");
		// show the controls
		$(".game:not('.locked')").find(".change:not([data-id='0'])").removeClass("hidden");
		// remove the disabled class
		$(".game:not('.locked')").children(".picks .disabled").removeClass("disabled");
		// show the not-picked
		$(".game:not('.locked').not-picked").removeClass("hidden");
	});
	// build action for cancelling changes
	$(".page-controls").on("click", ".cancel", function(){
		if( confirm("Are you sure you want to cancel changes?") ){
			window.location.href = "/?action=pick.set&nWeekID=" + $("#picks").data("id");
		}
	});
	// build actions for marking picks
	$(".game").on("click", "button:not(.cancel-pick)", function(){
		if( !$(this).hasClass("disabled") ){
			// enable the save button
			$(".page-controls .save").removeClass("disabled");
			// remove any alerts
			$(this).closest("tr").removeClass("btn-danger");
			// remove the pick and primary from anyone in this row
			$(this).closest("tr").find(".pick").removeClass("pick btn-success").addClass("btn-default");
			// add the success pick class
			$(this).removeClass("btn-default").addClass("pick btn-success");
			// show the cancel button
			$(this).closest("tr").find(".cancel-pick").removeClass("hidden");
		}
	});
	// build actions for cancelling picks
	$(".cancel-pick").on("click", function(){
		// make sure they want to cancel the pick
		if( confirm("Are you sure you would like to cancel this pick?") ){
			$(this).addClass("hidden").closest("tr").find(".btn-success").removeClass("btn-success pick").addClass("btn-default");
		}
	});
	// bind for saving picks
	$(".page-controls").on("click", ".save:not('.disabled')", function(){
		var stPicks = {};
		var bSendPicks = true;
		// loop through the list of games
		$(".game:not('.locked')").each(function(){
			// append this pick to the list of picks
			stPicks[$(this).data("id")] = $(this).find(".pick").data("id");
		});
		// send the picks
		if( bSendPicks ){
			$.post("/index.cfm?action=pick.save",
				{
					"nWeekID": $("#picks").data("id"),
					"stPicks": $.toJSON(stPicks)
				}, function(sResults){
					//setMessage(sResults);
					window.location.href = "/?action=pick.set&bSaved=true&nWeekID=" + $("#picks").data("id");
				}
			);
		}
	});
	// bind click for bulk saving games
	$("#bulk").on("click", "button", function(){
		var reNewLines=/[\n\r]/g;
		var lstPicks = $("#sPicks").val().replace(reNewLines, ",");
		// if the last character is a comma
		if( lstPicks.substr(lstPicks.length - 1) == "," ){
			lstPicks = lstPicks.substring(0, lstPicks.length - 1);
		}
		// send post
		$.post("/?action=pick.bulk",
			{
				"bDoSave": true,
				"lstPicks": lstPicks,
				"nWeekID": $("#nWeekID").val(),
				"nUserID": $("#nUserID").val()
			}, function(sMessage){
				setMessage(sMessage);
				checkPicks();
				// reset the fields
				$("#sPicks").val("");
				$("#nUserID").val("");
			}
		);
	});
	// bind for checking if user has picks this week
	$("#bulk").on("change", "#nWeekID", function(){
		checkPicks();
	});
	// bind action for comparing picks
	$("#compare").on("click", function(){
		window.location.href = "/?action=pick.compare&nWeekID=" + $("h3").data("id") + "&nViewUserID=" + $("#nUserID").val();
	});
	// bind click for gameinfo
	$(".game-info").on("click", function(){
		window.location.href = "/?action=pick.gameInfo&nWeekID=" + $(this).closest("tr").data("nweekid") + "&nGameID=" + $(this).closest("tr").data("id");
	});
});
// checks to see if the users have picks
function checkPicks(){
	var nWeekID = $("#nWeekID").val();
	var stData = {};
	// remove the "has-picks" class
	$("#nUserID option").removeClass("alert alert-success alert-danger");
	// loop through each user and reset their data
	$("#nUserID").children("option").each(function(){
		stData[$(this).data("id")] = 0
	});
	$.post("/?action=pick.hasPicks",
		{
			"stData": $.toJSON(stData),
			"nCheckWeekID": $("#nWeekID").val()
		}, function(stPicks){
			// loop through the results and update each user
			$("#nUserID").children("option").each(function(){
				if( stPicks[$(this).data("id")] ){
					$(this).addClass("alert alert-success");
				} else {
					$(this).addClass("alert alert-danger");
				}
			});
		}, "json"
	);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revis. gen. pl. (Leipzig) 3: 445 (1898)

#### Original name
Peziza crassipes Pat.

### Remarks
null


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Reflection;
using System.Text;

namespace Test.DALTest
{
    [TestClass]
    public class TestSBuilderFormat
    {
        public int JJH { get; set; }

        [TestMethod]
        public void TestFormat()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("this is {0}","sam");
            Console.WriteLine(sb.ToString());
        }

        [TestMethod]
        public void TestReflection()
        {
            Type t = this.GetType();
            PropertyInfo p = t.GetProperties()[0];
            Console.WriteLine(p.Name);
        }
    }
}


text:
layout: post
title: Some High-level Tips for Python Projects
tags: [Python]
---

Below are tips on a few very high-level and commonly-encountered topics
in Python software development.

* [Directory structure](#directory-structure)
* [Naming](#naming)
* [Documentation](#documentation)
* [Logging](#logging)
* [Testing](#testing)

## Directory structure

Suppose the the probject is called 'becool'.
A largely standard directory structure looks like this:

```
becool/
  |-- archive/
  |-- config/
  |-- doc/
  |-- becool/
  |   |-- __init__.py
  |   |-- module_a.py
  |   |-- module_b.py
  |   |-- becooler/
  |   |   |-- __init__.py
  |   |   |-- module_c.py
  |   |   |-- module_d.py
  |-- tests/
  |   |-- __init__.py
  |   |-- test_module_a.py
  |   |-- test_module_b.py
  |   |-- becooler/
  |   |   |-- __init__.py
  |   |   |-- test_module_c.py
  |   |   |-- test_module_d.py
  |-- scripts/
  |-- README.md
  |-- setup.py
```

Some highlights:

- The project name, 'becool', is also the name of the `git` repo.
  Inside this repo, the main content a Python package called 'becool'.
  Hence the repo and the package are both named after the project.
  This is a common situation.

  Although nothing forbids you from having multiple packages in one project (e.g. having a `behot` parallel to `becool`), it's usually a bad idea. The reason is that if `becool` and `behot` closely interact, then maybe they should be one single package. On the other hand, if they do not closely interact, then they are independently deployable, therefore it's better to have them in separate projects (i.e. repos).

- Maintain a clean project file structure, and do not be afraid to adjust or refactor. [Some reference](http://as.ynchrono.us/2007/12/filesystem-structure-of-python-project_21.html); [some more](http://stackoverflow.com/questions/193161/what-is-the-best-project-structure-for-a-python-application).

- The directory `scripts` should not contain `__init__.py`, but may contain files named like `*_test.py` or `test_*.py` for testing functions in the scripts.

  Ideally, content of `scripts` is mainly short launchers of functions in packages.
  For this reason, the scripts often do not need tests.

  This directory may also be called `bin`.

- `archive` is for any code segments that you have deleted from the "main line" but for some reason still want to keep a visible copy for reference. Do not use a *branch* for this purpose.

The center of gravity of the repo is the Python library (or "package") `becool`.
Scripts are *applications* of this library, and should strive to be short.
In the scripts, the package `becool` should be treated just like any third-party library.
In particular, file-path hacks should be avoided.

If you execute the code in a Docker container like I do,
all dependencies are taken care of by the definition of the Docker image.
In that case, `setup.py` does not need to worry about installing dependencies.

### Where to put tests?

There are mainly two approaches. The first is to have `tests` subdirectories within the package `becool`. Specifically, every directory (includeing the top level `becool`) contains a subdirectory named `tests`, which hosts tests for the modules (i.e. `*.py` files) in its parent directory. The second approach uses a `tests` directory separate from the package being tested. This is the approach shown in the digram above. Both approaches are used by major open source projects.

After some time using the first approach, I switched to the second. The switch is prompted by some confusing situations related to running tests against the package that has been "installed" into the system `site-packages`. I can think of two other reasons. First, conceptually, "tests" are *not* the package's intrinsic functionalities. They are supporting the development of the package, just like "doc" is another supporting component. Second, in substantial projects, one may build some utilities to be used by the test code. In the first approach, the location of this testing infrastructure may become awkward.

### Alternative structure with a `src` sub-directory

There are discussions about having a `src` directory.
[This post](https://hynek.me/articles/testing-packaging/) advocates top-level
directories like `src`, `docs`, `tests`, and a main point for this structure is
related to testing.

Without carefully reading the arguments, **I have switched to use this structure**.
I can think of two advantages of this structure:

1. The top-level directories, like `src`, `docs`, `tests`, are more logical and extensible because they are on the same level of abstraction. It feels better.

2. If there are non-Python code, such as Python extensions in C++, this structure can easily grow with the complexity of the codebase. An [experimental package of mine](https://github.com/zpz/experiments.py) of mine is an example.

## Naming and style

For the project and packages, single-word names (or two words without hyphen) are more desirable.

For functions and variables, multi-word, verboses names are fine.

Use 'snake-case' names; see [examples](http://google.github.io/styleguide/pyguide.html#316-naming).

Do study the ``PEP 8`` style guide; pick and stick to a decent style.

I use `yapf` to format Python code. This frees the developer from thinking about good style,
and help avoids arguments about style between developers. Usually I use the following command:

```
$ yapf -ir -vv --no-local-style ./
```

## Documentation

Do write documentation to help **yourself**, if not others.

- In-source documentation: make use of Python's docstring mechanism;
  follow the Google style; [example 1](http://sphinxcontrib-napoleon.readthedocs.org/en/latest/example_google.html), [example 2](https://www.sphinx-doc.org/en/master/usage/extensions/example_google.html).
- Stand-alone documentation files in source tree (but outside of source code files):
  - `README.md` in the top-level (project root) or second-level (package root)
    directories.
  - Doc files in `doc` directory under the project root directory.
  - Plain text files are perferred. Preferred formats are 'plain text' (`txt`), 'mark-down' (`md`), or 'reStructuredText' (`rst`) (if you intend to do extensive documentation and generate friendly HTML versions using `Sphinx`).
  - If you use Mac, a decent Markdown editor is `MacDown`.
  - To edit `rst` files with live preview, use the `Atom` editor (by Github) with a couple plug-ins.
  - If you use `Sphinx`, `reStructuredText` markup syntax can be used in in-source docstrings as well.
- Outside of source tree: for documentation aimed at non-developers or users from other groups that require different levels of access control.

### How to generate documentation using Sphinx

If you go to the length of writing Sphinx documentation, below is my work flow.

1. Basically, let Sphinx take over the `doc` directory in the repo. In `doc/`, run

   ```
   sphinx-quickstart
   ```

   Make sure you make these particular choices:

   ```
   Separate source and build directories (y/n) [n]: y
   autodoc: automatically insert docstrings from modules (y/n) [n]: y
   imgmath: include math, rendered as PNG or SVG images (y/n) [n]: n
   mathjax: include math, rendered in the browser by MathJax (y/n) [n]: y
   viewcode: include links to the source code of documented Python objects (y/n) [n]: y
   Create Makefile? (y/n) [y]: y
   ```

   In `doc/source/conf.py`, make sure the `extensions` list contains at least these items:

   * `sphinx.ext.autodoc`
   * `sphinx.ext.inheritance_diagram`
   * `sphinx.ext.mathjax`
   * `sphinx.ext.napoleon`
   * `sphinx.ext.todo`
   * `sphinx.ext.viewcode`

   Also make sure `html_theme` is set to `nature` (unless you have another preference).
   After that, search for `alabaster` in `conf.py`, and comment out that block,
   because that block is needed for the default `alabaster` theme but could get in the way
   of other thems.

2. Create `*.rst` files as needed in `doc/source/`. These stand-alone doc files along with doc in source code will be used to generate documentation.

3. In `doc`, run `make html` to generate HTML documentation, which will be located in `doc/build/html/`. View the documentation in a web browser, starting with the file `doc/build/html/index.html`.

4. `git commit` the files `doc/Makefile`, `doc/source/conf.py`, as well as the `*.rst` and other files you've created in `doc/source`. DO NOT `git commit` the generated material in `doc/build`.

## Logging

Prefer logging to `print` in most cases.

- The [twelve factor app](http://12factor.net/logs) advocates treating log events as an event stream, always sending the stream to standard output, and leaving capture of the stream into files to the execution environment.

  For capturing logging into files, see my [other post]({{ site.baseurl }}/blog/log-rotation-of-stdout). A more complete example appears in
  [another post]({{ site.baseurl}}/blog/poor-mans-CD-system-using-Docker/#pipeline-and-pyscript).

- In all modules that need to do logging, always have this, and only this, at the top of the module:

  ```python
  import logging
  logger = logging.getLogger(__name__)
  ```

  then use `logger.info()` etc to create log messages.

  Do not create custom names for the logger. The `__name__` mechanism will create a hierarchy of loggers following your
package structure, e.g. with loggers named

  ```
  package1
  package1.module1
  package1.module1.submodule2
  ```

  Log messages will pass to higher levels in this hierarchy.
Customizing the logger names will disrupt this useful message forwarding.

- In the `__init__.py` file in the top-level directory of your Python package,
include this:

  ```python
  # Set default logging handler to avoid "No handler found" warnings.
  import logging
  logging.getLogger(__name__).addHandler(logging.NullHandler())
  ```

  Do not add any other handler in your package code.

- Do not do any format, handler (e.g. using a file handler), log level,
or other configuration in your package code. These belong in the *launch scripts* and should happen
at exactly **one** place in a running program.

  I basically call something like the following function in the launch script.
  Usually ``level`` is the only argument I need to specify.

  ```python
  import logging
  import os
  import time

  def config_logger(level=None, use_utc=True, datefmt=None, format=None, **kwargs):
    # 'level' is a string form of the logging levels: 'debug', 'info', 'warning', 'error', 'critical'.

    if level is None:
      level = os.environ.get('LOGLEVEL', 'info')

    if level not in [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL]:
      level = getattr(logging, level.upper())

    if use_utc:
      logging.Formatter.converter = time.gmtime
      datefmt = datefmt or '%Y-%m-%d %H:%M:%SZ'
    else:
      logging.Formatter.converter = time.localtime
      datefmt = datefmt or '%Y-%m-%d %H:%M:%S'

    format = format or '[%(asctime)s; %(name)s, %(funcName)s, %(lineno)d; %(levelname)s]    %(message)s'

    logging.basicConfig(format=format, datefmt=datefmt, level=level, **kwargs)
  ```

- Use the old-style string formatting (`%`), not the new-style string formatting (`str.format`).
  The following example should serve most of your fomatting needs:

  ```python
  logger.info('Line %s (%s) has spent %.2f by hour %d', 'asd9123las', 'Huge Sale!', 28.97, 23)
  ```

  [See here](https://pyformat.info) for more about formatting.

## Testing

Write tests, and adopt a testing framework. My recommendation is `py.test`.

You do not need to `import pytest` unless you explicitly use `pytest` in the code.

See [Directory Structure](#directory-structure) above for where to put the test files.

(Lightly revised on December 21, 2018.)


text:
import React from 'react';
import PropTypes from 'prop-types';

// React
import Tags from '../Tags';

// Style
import './style.css';

const EntryFooter = ({ tags }) => {
  return <Tags tags={tags} />;
};

export default EntryFooter;

EntryFooter.propTypes = {
  tags: PropTypes.arrayOf(PropTypes.object).isRequired
};


text:
package app_msg

func Raw(text interface{}) Message {
	return &messageImpl{
		K: KeyRaw,
		P: []P{
			{KeyParamRaw: text},
		},
	}
}


text:
import { Education16 } from "../../";

export = Education16;


text:
Vaultier.LayoutLayoutStandardView = Ember.View.extend({
    templateName: 'Layout/LayoutStandard'
});

Vaultier.LayoutLayoutWindowView = Ember.View.extend({
    templateName: 'Layout/LayoutStandard'
});

Vaultier.LayoutFooterView = Ember.View.extend({
    templateName: 'Layout/Footer'
});


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
<meta charset="utf-8">
<title>PHPExcel classes » \PHPExcel_Reader_Abstract</title>
<meta name="author" content="Mike van Riel">
<meta name="description" content="">
<link href="../css/template.css" rel="stylesheet" media="all">
<link rel="shortcut icon" href="../img/favicon.ico">
<link rel="apple-touch-icon" href="../img/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="../img/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="../img/apple-touch-icon-114x114.png">

PHPExcel classes

                                    API Documentation

Packages

 Default

 JAMA

 JAMA
Cholesky decomposition class
For a symmetric, positive definite matrix A, the Cholesky decomposition
is an lower triangular matrix L so that A = L*L'

 JAMA
Class to obtain eigenvalues and eigenvectors of a real matrix

 JAMA
Error handling

 JAMA
For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n
unit lower triangular matrix L, an n-by-n upper triangular matrix U,
and a permutation vector piv of length m so that A(piv,:) = L*U

 JAMA
For an m-by-n matrix A with m >= n, the QR decomposition is an m-by-n
orthogonal matrix Q and an n-by-n upper triangular matrix R so that
A = Q*R

 JAMA
For an m-by-n matrix A with m >= n, the singular value decomposition is
an m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and
an n-by-n orthogonal matrix V so that A = U*S*V'

 JAMA
Pythagorean Theorem:
a = 3
b = 4
r = sqrt(square(a) + square(b))
r = 5
r = sqrt(a^2 + b^2) without under/overflow

 PHPExcel

                                    Charts

 Class hierarchy diagram

                                    Reports

 Errors
                551

 Markers

todo
                19

fixme
                10

 Deprecated elements
                12

Back to top

                            Javascript is disabled; several features are only available
                            if Javascript is enabled.

<button class="btn public active" title="Show public elements">Public</button><button class="btn protected" title="Show protected elements">Protected</button><button class="btn private" title="Show private elements">Private</button><button class="btn inherited active" title="Show inherited elements">Inherited</button>

<button class="btn details" title="Show descriptions and method names"></button><button class="btn simple" title="Show only method names"></button>

 Methods

Can the current PHPExcel_Reader_IReader read the file?
canRead()

Read charts in workbook?
	If this is true, then the Reader will include any charts that exist in the workbook.
getIncludeCharts()

Get which sheets to load
Returns either an array of worksheet names (the list of worksheets that should be loaded), or a null
	indicating that all worksheets in the workbook should be loaded.
getLoadSheetsOnly()

Read data only?
	If this is true, then the Reader will only read data values for cells, it will not read any formatting information.
getReadDataOnly()

Read filter
getReadFilter()

Loads PHPExcel from file
load()

Set read charts in workbook
	Set to true, to advise the Reader to include any charts that exist in the workbook.
setIncludeCharts()

Set all sheets to load
	Tells the Reader to load all worksheets from the workbook.
setLoadAllSheets()

Set which sheets to load
setLoadSheetsOnly()

Set read data only
	Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information.
setReadDataOnly()

Set read filter
setReadFilter()

» Protected

Open file for reading
_openFile()

 Properties

» Protected

$_fileHandle

$_includeCharts

$_loadSheetsOnly

$_readDataOnly

$_readFilter

\

global

\PHPExcel_Reader_Abstract

PHPExcel_Reader_Abstract

category
PHPExcel

package
PHPExcel_Reader

copyright
Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)

 Methods

Can the current PHPExcel_Reader_IReader read the file?

canRead(string $pFilename) : boolean

Parameters

$pFilename

string

Exceptions

\PHPExcel_Reader_Exception

Returns

boolean

Read charts in workbook?
	If this is true, then the Reader will include any charts that exist in the workbook.

getIncludeCharts() : boolean

Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value.
    If false (the default) it will ignore any charts defined in the workbook file.

Returns

boolean

Get which sheets to load
Returns either an array of worksheet names (the list of worksheets that should be loaded), or a null
	indicating that all worksheets in the workbook should be loaded.

getLoadSheetsOnly() : mixed

Returns

mixed

Read data only?
	If this is true, then the Reader will only read data values for cells, it will not read any formatting information.

getReadDataOnly() : boolean

If false (the default) it will read data and formatting.

Returns

boolean

Read filter

getReadFilter() : \PHPExcel_Reader_IReadFilter

Returns

\PHPExcel_Reader_IReadFilter

Loads PHPExcel from file

load(string $pFilename)

Inherited

inherited_from
\PHPExcel_Reader_IReader::load()

Parameters

$pFilename

string

Exceptions

\PHPExcel_Reader_Exception

Set read charts in workbook
	Set to true, to advise the Reader to include any charts that exist in the workbook.

setIncludeCharts(boolean $pValue) : \PHPExcel_Reader_IReader

Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value.
    Set to false (the default) to discard charts.

Parameters

$pValue

boolean

Returns

\PHPExcel_Reader_IReader

Set all sheets to load
	Tells the Reader to load all worksheets from the workbook.

setLoadAllSheets() : \PHPExcel_Reader_IReader

Returns

\PHPExcel_Reader_IReader

Set which sheets to load

setLoadSheetsOnly(mixed $value) : \PHPExcel_Reader_IReader

Parameters

$value

mixed
This should be either an array of worksheet names to be loaded, or a string containing a single worksheet name.
	If NULL, then it tells the Reader to read all worksheets in the workbook

Returns

\PHPExcel_Reader_IReader

Set read data only
	Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information.

setReadDataOnly(boolean $pValue) : \PHPExcel_Reader_IReader

Set to false (the default) to advise the Reader to read both data and formatting for cells.

Parameters

$pValue

boolean

Returns

\PHPExcel_Reader_IReader

Set read filter

setReadFilter(\PHPExcel_Reader_IReadFilter $pValue) : \PHPExcel_Reader_IReader

Parameters

$pValue

\PHPExcel_Reader_IReadFilter

Returns

\PHPExcel_Reader_IReader

Open file for reading

_openFile(string $pFilename) : resource

Parameters

$pFilename

string

Exceptions

\PHPExcel_Reader_Exception

Returns

resource

 Properties

$_fileHandle

$_includeCharts : boolean

$_loadSheetsOnly : array

If null, then all worksheets will be loaded.

$_readDataOnly : boolean

$_readFilter : \PHPExcel_Reader_IReadFilter

            Template is built using Twitter Bootstrap 2 and icons provided by Glyphicons.

            Documentation is powered by phpDocumentor 2.0.0a12 and

            generated on 2014-03-02T15:27:35Z.