text:
/******************************************************************************
 *
 * Module Name: nspredef - Validation of ACPI predefined methods and objects
 *
 *****************************************************************************/

/*
 * Copyright (C) 2000 - 2011, Intel Corp.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions, and the following disclaimer,
 *    without modification.
 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
 *    substantially similar to the "NO WARRANTY" disclaimer below
 *    ("Disclaimer") and any redistribution must be conditioned upon
 *    including a substantially similar Disclaimer requirement for further
 *    binary redistribution.
 * 3. Neither the names of the above-listed copyright holders nor the names
 *    of any contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * Alternatively, this software may be distributed under the terms of the
 * GNU General Public License ("GPL") version 2 as published by the Free
 * Software Foundation.
 *
 * NO WARRANTY
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 */

#define ACPI_CREATE_PREDEFINED_TABLE

#include <contrib/dev/acpica/include/acpi.h>
#include <contrib/dev/acpica/include/accommon.h>
#include <contrib/dev/acpica/include/acnamesp.h>
#include <contrib/dev/acpica/include/acpredef.h>

#define _COMPONENT          ACPI_NAMESPACE
        ACPI_MODULE_NAME    ("nspredef")

/*******************************************************************************
 *
 * This module validates predefined ACPI objects that appear in the namespace,
 * at the time they are evaluated (via AcpiEvaluateObject). The purpose of this
 * validation is to detect problems with BIOS-exposed predefined ACPI objects
 * before the results are returned to the ACPI-related drivers.
 *
 * There are several areas that are validated:
 *
 *  1) The number of input arguments as defined by the method/object in the
 *      ASL is validated against the ACPI specification.
 *  2) The type of the return object (if any) is validated against the ACPI
 *      specification.
 *  3) For returned package objects, the count of package elements is
 *      validated, as well as the type of each package element. Nested
 *      packages are supported.
 *
 * For any problems found, a warning message is issued.
 *
 ******************************************************************************/

/* Local prototypes */

static ACPI_STATUS
AcpiNsCheckPackage (
    ACPI_PREDEFINED_DATA        *Data,
    ACPI_OPERAND_OBJECT         **ReturnObjectPtr);

static ACPI_STATUS
AcpiNsCheckPackageList (
    ACPI_PREDEFINED_DATA        *Data,
    const ACPI_PREDEFINED_INFO  *Package,
    ACPI_OPERAND_OBJECT         **Elements,
    UINT32                      Count);

static ACPI_STATUS
AcpiNsCheckPackageElements (
    ACPI_PREDEFINED_DATA        *Data,
    ACPI_OPERAND_OBJECT         **Elements,
    UINT8                       Type1,
    UINT32                      Count1,
    UINT8                       Type2,
    UINT32                      Count2,
    UINT32                      StartIndex);

static ACPI_STATUS
AcpiNsCheckObjectType (
    ACPI_PREDEFINED_DATA        *Data,
    ACPI_OPERAND_OBJECT         **ReturnObjectPtr,
    UINT32                      ExpectedBtypes,
    UINT32                      PackageIndex);

static ACPI_STATUS
AcpiNsCheckReference (
    ACPI_PREDEFINED_DATA        *Data,
    ACPI_OPERAND_OBJECT         *ReturnObject);

static void
AcpiNsGetExpectedTypes (
    char                        *Buffer,
    UINT32                      ExpectedBtypes);

/*
 * Names for the types that can be returned by the predefined objects.
 * Used for warning messages. Must be in the same order as the ACPI_RTYPEs
 */
static const char   *AcpiRtypeNames[] =
{
    "/Integer",
    "/String",
    "/Buffer",
    "/Package",
    "/Reference",
};

/*******************************************************************************
 *
 * FUNCTION:    AcpiNsCheckPredefinedNames
 *
 * PARAMETERS:  Node            - Namespace node for the method/object
 *              UserParamCount  - Number of parameters actually passed
 *              ReturnStatus    - Status from the object evaluation
 *              ReturnObjectPtr - Pointer to the object returned from the
 *                                evaluation of a method or object
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Check an ACPI name for a match in the predefined name list.
 *
 ******************************************************************************/

ACPI_STATUS
AcpiNsCheckPredefinedNames (
    ACPI_NAMESPACE_NODE         *Node,
    UINT32                      UserParamCount,
    ACPI_STATUS                 ReturnStatus,
    ACPI_OPERAND_OBJECT         **ReturnObjectPtr)
{
    ACPI_OPERAND_OBJECT         *ReturnObject = *ReturnObjectPtr;
    ACPI_STATUS                 Status = AE_OK;
    const ACPI_PREDEFINED_INFO  *Predefined;
    char                        *Pathname;
    ACPI_PREDEFINED_DATA        *Data;

    /* Match the name for this method/object against the predefined list */

    Predefined = AcpiNsCheckForPredefinedName (Node);

    /* Get the full pathname to the object, for use in warning messages */

    Pathname = AcpiNsGetExternalPathname (Node);
    if (!Pathname)
    {
        return (AE_OK); /* Could not get pathname, ignore */
    }

    /*
     * Check that the parameter count for this method matches the ASL
     * definition. For predefined names, ensure that both the caller and
     * the method itself are in accordance with the ACPI specification.
     */
    AcpiNsCheckParameterCount (Pathname, Node, UserParamCount, Predefined);

    /* If not a predefined name, we cannot validate the return object */

    if (!Predefined)
    {
        goto Cleanup;
    }

    /*
     * If the method failed or did not actually return an object, we cannot
     * validate the return object
     */
    if ((ReturnStatus != AE_OK) && (ReturnStatus != AE_CTRL_RETURN_VALUE))
    {
        goto Cleanup;
    }

    /*
     * If there is no return value, check if we require a return value for
     * this predefined name. Either one return value is expected, or none,
     * for both methods and other objects.
     *
     * Exit now if there is no return object. Warning if one was expected.
     */
    if (!ReturnObject)
    {
        if ((Predefined->Info.ExpectedBtypes) &&
            (!(Predefined->Info.ExpectedBtypes & ACPI_RTYPE_NONE)))
        {
            ACPI_WARN_PREDEFINED ((AE_INFO, Pathname, ACPI_WARN_ALWAYS,
                "Missing expected return value"));

            Status = AE_AML_NO_RETURN_VALUE;
        }
        goto Cleanup;
    }

    /*
     * 1) We have a return value, but if one wasn't expected, just exit, this is
     * not a problem. For example, if the "Implicit Return" feature is
     * enabled, methods will always return a value.
     *
     * 2) If the return value can be of any type, then we cannot perform any
     * validation, exit.
     */
    if ((!Predefined->Info.ExpectedBtypes) ||
        (Predefined->Info.ExpectedBtypes == ACPI_RTYPE_ALL))
    {
        goto Cleanup;
    }

    /* Create the parameter data block for object validation */

    Data = ACPI_ALLOCATE_ZEROED (sizeof (ACPI_PREDEFINED_DATA));
    if (!Data)
    {
        goto Cleanup;
    }
    Data->Predefined = Predefined;
    Data->NodeFlags = Node->Flags;
    Data->Pathname = Pathname;

    /*
     * Check that the type of the main return object is what is expected
     * for this predefined name
     */
    Status = AcpiNsCheckObjectType (Data, ReturnObjectPtr,
                Predefined->Info.ExpectedBtypes, ACPI_NOT_PACKAGE_ELEMENT);
    if (ACPI_FAILURE (Status))
    {
        goto Exit;
    }

    /*
     * For returned Package objects, check the type of all sub-objects.
     * Note: Package may have been newly created by call above.
     */
    if ((*ReturnObjectPtr)->Common.Type == ACPI_TYPE_PACKAGE)
    {
        Data->ParentPackage = *ReturnObjectPtr;
        Status = AcpiNsCheckPackage (Data, ReturnObjectPtr);
        if (ACPI_FAILURE (Status))
        {
            goto Exit;
        }
    }

    /*
     * The return object was OK, or it was successfully repaired above.
     * Now make some additional checks such as verifying that package
     * objects are sorted correctly (if required) or buffer objects have
     * the correct data width (bytes vs. dwords). These repairs are
     * performed on a per-name basis, i.e., the code is specific to
     * particular predefined names.
     */
    Status = AcpiNsComplexRepairs (Data, Node, Status, ReturnObjectPtr);

Exit:
    /*
     * If the object validation failed or if we successfully repaired one
     * or more objects, mark the parent node to suppress further warning
     * messages during the next evaluation of the same method/object.
     */
    if (ACPI_FAILURE (Status) || (Data->Flags & ACPI_OBJECT_REPAIRED))
    {
        Node->Flags |= ANOBJ_EVALUATED;
    }
    ACPI_FREE (Data);

Cleanup:
    ACPI_FREE (Pathname);
    return (Status);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiNsCheckParameterCount
 *
 * PARAMETERS:  Pathname        - Full pathname to the node (for error msgs)
 *              Node            - Namespace node for the method/object
 *              UserParamCount  - Number of args passed in by the caller
 *              Predefined      - Pointer to entry in predefined name table
 *
 * RETURN:      None
 *
 * DESCRIPTION: Check that the declared (in ASL/AML) parameter count for a
 *              predefined name is what is expected (i.e., what is defined in
 *              the ACPI specification for this predefined name.)
 *
 ******************************************************************************/

void
AcpiNsCheckParameterCount (
    char                        *Pathname,
    ACPI_NAMESPACE_NODE         *Node,
    UINT32                      UserParamCount,
    const ACPI_PREDEFINED_INFO  *Predefined)
{
    UINT32                      ParamCount;
    UINT32                      RequiredParamsCurrent;
    UINT32                      RequiredParamsOld;

    /* Methods have 0-7 parameters. All other types have zero. */

    ParamCount = 0;
    if (Node->Type == ACPI_TYPE_METHOD)
    {
        ParamCount = Node->Object->Method.ParamCount;
    }

    if (!Predefined)
    {
        /*
         * Check the parameter count for non-predefined methods/objects.
         *
         * Warning if too few or too many arguments have been passed by the
         * caller. An incorrect number of arguments may not cause the method
         * to fail. However, the method will fail if there are too few
         * arguments and the method attempts to use one of the missing ones.
         */
        if (UserParamCount < ParamCount)
        {
            ACPI_WARN_PREDEFINED ((AE_INFO, Pathname, ACPI_WARN_ALWAYS,
                "Insufficient arguments - needs %u, found %u",
                ParamCount, UserParamCount));
        }
        else if (UserParamCount > ParamCount)
        {
            ACPI_WARN_PREDEFINED ((AE_INFO, Pathname, ACPI_WARN_ALWAYS,
                "Excess arguments - needs %u, found %u",
                ParamCount, UserParamCount));
        }
        return;
    }

    /*
     * Validate the user-supplied parameter count.
     * Allow two different legal argument counts (_SCP, etc.)
     */
    RequiredParamsCurrent = Predefined->Info.ParamCount & 0x0F;
    RequiredParamsOld = Predefined->Info.ParamCount >> 4;

    if (UserParamCount != ACPI_UINT32_MAX)
    {
        if ((UserParamCount != RequiredParamsCurrent) &&
            (UserParamCount != RequiredParamsOld))
        {
            ACPI_WARN_PREDEFINED ((AE_INFO, Pathname, ACPI_WARN_ALWAYS,
                "Parameter count mismatch - "
                "caller passed %u, ACPI requires %u",
                UserParamCount, RequiredParamsCurrent));
        }
    }

    /*
     * Check that the ASL-defined parameter count is what is expected for
     * this predefined name (parameter count as defined by the ACPI
     * specification)
     */
    if ((ParamCount != RequiredParamsCurrent) &&
        (ParamCount != RequiredParamsOld))
    {
        ACPI_WARN_PREDEFINED ((AE_INFO, Pathname, Node->Flags,
            "Parameter count mismatch - ASL declared %u, ACPI requires %u",
            ParamCount, RequiredParamsCurrent));
    }
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiNsCheckForPredefinedName
 *
 * PARAMETERS:  Node            - Namespace node for the method/object
 *
 * RETURN:      Pointer to entry in predefined table. NULL indicates not found.
 *
 * DESCRIPTION: Check an object name against the predefined object list.
 *
 ******************************************************************************/

const ACPI_PREDEFINED_INFO *
AcpiNsCheckForPredefinedName (
    ACPI_NAMESPACE_NODE         *Node)
{
    const ACPI_PREDEFINED_INFO  *ThisName;

    /* Quick check for a predefined name, first character must be underscore */

    if (Node->Name.Ascii[0] != '_')
    {
        return (NULL);
    }

    /* Search info table for a predefined method/object name */

    ThisName = PredefinedNames;
    while (ThisName->Info.Name[0])
    {
        if (ACPI_COMPARE_NAME (Node->Name.Ascii, ThisName->Info.Name))
        {
            return (ThisName);
        }

        /*
         * Skip next entry in the table if this name returns a Package
         * (next entry contains the package info)
         */
        if (ThisName->Info.ExpectedBtypes & ACPI_RTYPE_PACKAGE)
        {
            ThisName++;
        }

        ThisName++;
    }

    return (NULL); /* Not found */
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiNsCheckPackage
 *
 * PARAMETERS:  Data            - Pointer to validation data structure
 *              ReturnObjectPtr - Pointer to the object returned from the
 *                                evaluation of a method or object
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Check a returned package object for the correct count and
 *              correct type of all sub-objects.
 *
 ******************************************************************************/

static ACPI_STATUS
AcpiNsCheckPackage (
    ACPI_PREDEFINED_DATA        *Data,
    ACPI_OPERAND_OBJECT         **ReturnObjectPtr)
{
    ACPI_OPERAND_OBJECT         *ReturnObject = *ReturnObjectPtr;
    const ACPI_PREDEFINED_INFO  *Package;
    ACPI_OPERAND_OBJECT         **Elements;
    ACPI_STATUS                 Status = AE_OK;
    UINT32                      ExpectedCount;
    UINT32                      Count;
    UINT32                      i;

    ACPI_FUNCTION_NAME (NsCheckPackage);

    /* The package info for this name is in the next table entry */

    Package = Data->Predefined + 1;

    ACPI_DEBUG_PRINT ((ACPI_DB_NAMES,
        "%s Validating return Package of Type %X, Count %X\n",
        Data->Pathname, Package->RetInfo.Type, ReturnObject->Package.Count));

    /*
     * For variable-length Packages, we can safely remove all embedded
     * and trailing NULL package elements
     */
    AcpiNsRemoveNullElements (Data, Package->RetInfo.Type, ReturnObject);

    /* Extract package count and elements array */

    Elements = ReturnObject->Package.Elements;
    Count = ReturnObject->Package.Count;

    /* The package must have at least one element, else invalid */

    if (!Count)
    {
        ACPI_WARN_PREDEFINED ((AE_INFO, Data->Pathname, Data->NodeFlags,
            "Return Package has no elements (empty)"));

        return (AE_AML_OPERAND_VALUE);
    }

    /*
     * Decode the type of the expected package contents
     *
     * PTYPE1 packages contain no subpackages
     * PTYPE2 packages contain sub-packages
     */
    switch (Package->RetInfo.Type)
    {
    case ACPI_PTYPE1_FIXED:

        /*
         * The package count is fixed and there are no sub-packages
         *
         * If package is too small, exit.
         * If package is larger than expected, issue warning but continue
         */
        ExpectedCount = Package->RetInfo.Count1 + Package->RetInfo.Count2;
        if (Count < ExpectedCount)
        {
            goto PackageTooSmall;
        }
        else if (Count > ExpectedCount)
        {
            ACPI_DEBUG_PRINT ((ACPI_DB_REPAIR,
                "%s: Return Package is larger than needed - "
                "found %u, expected %u\n",
                Data->Pathname, Count, ExpectedCount));
        }

        /* Validate all elements of the returned package */

        Status = AcpiNsCheckPackageElements (Data, Elements,
                    Package->RetInfo.ObjectType1, Package->RetInfo.Count1,
                    Package->RetInfo.ObjectType2, Package->RetInfo.Count2, 0);
        break;

    case ACPI_PTYPE1_VAR:

        /*
         * The package count is variable, there are no sub-packages, and all
         * elements must be of the same type
         */
        for (i = 0; i < Count; i++)
        {
            Status = AcpiNsCheckObjectType (Data, Elements,
                        Package->RetInfo.ObjectType1, i);
            if (ACPI_FAILURE (Status))
            {
                return (Status);
            }
            Elements++;
        }
        break;

    case ACPI_PTYPE1_OPTION:

        /*
         * The package count is variable, there are no sub-packages. There are
         * a fixed number of required elements, and a variable number of
         * optional elements.
         *
         * Check if package is at least as large as the minimum required
         */
        ExpectedCount = Package->RetInfo3.Count;
        if (Count < ExpectedCount)
        {
            goto PackageTooSmall;
        }

        /* Variable number of sub-objects */

        for (i = 0; i < Count; i++)
        {
            if (i < Package->RetInfo3.Count)
            {
                /* These are the required package elements (0, 1, or 2) */

                Status = AcpiNsCheckObjectType (Data, Elements,
                            Package->RetInfo3.ObjectType[i], i);
                if (ACPI_FAILURE (Status))
                {
                    return (Status);
                }
            }
            else
            {
                /* These are the optional package elements */

                Status = AcpiNsCheckObjectType (Data, Elements,
                            Package->RetInfo3.TailObjectType, i);
                if (ACPI_FAILURE (Status))
                {
                    return (Status);
                }
            }
            Elements++;
        }
        break;

    case ACPI_PTYPE2_REV_FIXED:

        /* First element is the (Integer) revision */

        Status = AcpiNsCheckObjectType (Data, Elements,
                    ACPI_RTYPE_INTEGER, 0);
        if (ACPI_FAILURE (Status))
        {
            return (Status);
        }

        Elements++;
        Count--;

        /* Examine the sub-packages */

        Status = AcpiNsCheckPackageList (Data, Package, Elements, Count);
        break;

    case ACPI_PTYPE2_PKG_COUNT:

        /* First element is the (Integer) count of sub-packages to follow */

        Status = AcpiNsCheckObjectType (Data, Elements,
                    ACPI_RTYPE_INTEGER, 0);
        if (ACPI_FAILURE (Status))
        {
            return (Status);
        }

        /*
         * Count cannot be larger than the parent package length, but allow it
         * to be smaller. The >= accounts for the Integer above.
         */
        ExpectedCount = (UINT32) (*Elements)->Integer.Value;
        if (ExpectedCount >= Count)
        {
            goto PackageTooSmall;
        }

        Count = ExpectedCount;
        Elements++;

        /* Examine the sub-packages */

        Status = AcpiNsCheckPackageList (Data, Package, Elements, Count);
        break;

    case ACPI_PTYPE2:
    case ACPI_PTYPE2_FIXED:
    case ACPI_PTYPE2_MIN:
    case ACPI_PTYPE2_COUNT:

        /*
         * These types all return a single Package that consists of a
         * variable number of sub-Packages.
         *
         * First, ensure that the first element is a sub-Package. If not,
         * the BIOS may have incorrectly returned the object as a single
         * package instead of a Package of Packages (a common error if
         * there is only one entry). We may be able to repair this by
         * wrapping the returned Package with a new outer Package.
         */
        if (*Elements && ((*Elements)->Common.Type != ACPI_TYPE_PACKAGE))
        {
            /* Create the new outer package and populate it */

            Status = AcpiNsRepairPackageList (Data, ReturnObjectPtr);
            if (ACPI_FAILURE (Status))
            {
                return (Status);
            }

            /* Update locals to point to the new package (of 1 element) */

            ReturnObject = *ReturnObjectPtr;
            Elements = ReturnObject->Package.Elements;
            Count = 1;
        }

        /* Examine the sub-packages */

        Status = AcpiNsCheckPackageList (Data, Package, Elements, Count);
        break;

    default:

        /* Should not get here if predefined info table is correct */

        ACPI_WARN_PREDEFINED ((AE_INFO, Data->Pathname, Data->NodeFlags,
            "Invalid internal return type in table entry: %X",
            Package->RetInfo.Type));

        return (AE_AML_INTERNAL);
    }

    return (Status);

PackageTooSmall:

    /* Error exit for the case with an incorrect package count */

    ACPI_WARN_PREDEFINED ((AE_INFO, Data->Pathname, Data->NodeFlags,
        "Return Package is too small - found %u elements, expected %u",
        Count, ExpectedCount));

    return (AE_AML_OPERAND_VALUE);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiNsCheckPackageList
 *
 * PARAMETERS:  Data            - Pointer to validation data structure
 *              Package         - Pointer to package-specific info for method
 *              Elements        - Element list of parent package. All elements
 *                                of this list should be of type Package.
 *              Count           - Count of subpackages
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Examine a list of subpackages
 *
 ******************************************************************************/

static ACPI_STATUS
AcpiNsCheckPackageList (
    ACPI_PREDEFINED_DATA        *Data,
    const ACPI_PREDEFINED_INFO  *Package,
    ACPI_OPERAND_OBJECT         **Elements,
    UINT32                      Count)
{
    ACPI_OPERAND_OBJECT         *SubPackage;
    ACPI_OPERAND_OBJECT         **SubElements;
    ACPI_STATUS                 Status;
    UINT32                      ExpectedCount;
    UINT32                      i;
    UINT32                      j;

    /*
     * Validate each sub-Package in the parent Package
     *
     * NOTE: assumes list of sub-packages contains no NULL elements.
     * Any NULL elements should have been removed by earlier call
     * to AcpiNsRemoveNullElements.
     */
    for (i = 0; i < Count; i++)
    {
        SubPackage = *Elements;
        SubElements = SubPackage->Package.Elements;
        Data->ParentPackage = SubPackage;

        /* Each sub-object must be of type Package */

        Status = AcpiNsCheckObjectType (Data, &SubPackage,
                    ACPI_RTYPE_PACKAGE, i);
        if (ACPI_FAILURE (Status))
        {
            return (Status);
        }

        /* Examine the different types of expected sub-packages */

        Data->ParentPackage = SubPackage;
        switch (Package->RetInfo.Type)
        {
        case ACPI_PTYPE2:
        case ACPI_PTYPE2_PKG_COUNT:
        case ACPI_PTYPE2_REV_FIXED:

            /* Each subpackage has a fixed number of elements */

            ExpectedCount = Package->RetInfo.Count1 + Package->RetInfo.Count2;
            if (SubPackage->Package.Count < ExpectedCount)
            {
                goto PackageTooSmall;
            }

            Status = AcpiNsCheckPackageElements (Data, SubElements,
                        Package->RetInfo.ObjectType1,
                        Package->RetInfo.Count1,
                        Package->RetInfo.ObjectType2,
                        Package->RetInfo.Count2, 0);
            if (ACPI_FAILURE (Status))
            {
                return (Status);
            }
            break;

        case ACPI_PTYPE2_FIXED:

            /* Each sub-package has a fixed length */

            ExpectedCount = Package->RetInfo2.Count;
            if (SubPackage->Package.Count < ExpectedCount)
            {
                goto PackageTooSmall;
            }

            /* Check the type of each sub-package element */

            for (j = 0; j < ExpectedCount; j++)
            {
                Status = AcpiNsCheckObjectType (Data, &SubElements[j],
                            Package->RetInfo2.ObjectType[j], j);
                if (ACPI_FAILURE (Status))
                {
                    return (Status);
                }
            }
            break;

        case ACPI_PTYPE2_MIN:

            /* Each sub-package has a variable but minimum length */

            ExpectedCount = Package->RetInfo.Count1;
            if (SubPackage->Package.Count < ExpectedCount)
            {
                goto PackageTooSmall;
            }

            /* Check the type of each sub-package element */

            Status = AcpiNsCheckPackageElements (Data, SubElements,
                        Package->RetInfo.ObjectType1,
                        SubPackage->Package.Count, 0, 0, 0);
            if (ACPI_FAILURE (Status))
            {
                return (Status);
            }
            break;

        case ACPI_PTYPE2_COUNT:

            /*
             * First element is the (Integer) count of elements, including
             * the count field (the ACPI name is NumElements)
             */
            Status = AcpiNsCheckObjectType (Data, SubElements,
                        ACPI_RTYPE_INTEGER, 0);
            if (ACPI_FAILURE (Status))
            {
                return (Status);
            }

            /*
             * Make sure package is large enough for the Count and is
             * is as large as the minimum size
             */
            ExpectedCount = (UINT32) (*SubElements)->Integer.Value;
            if (SubPackage->Package.Count < ExpectedCount)
            {
                goto PackageTooSmall;
            }
            if (SubPackage->Package.Count < Package->RetInfo.Count1)
            {
                ExpectedCount = Package->RetInfo.Count1;
                goto PackageTooSmall;
            }
            if (ExpectedCount == 0)
            {
                /*
                 * Either the NumEntries element was originally zero or it was
                 * a NULL element and repaired to an Integer of value zero.
                 * In either case, repair it by setting NumEntries to be the
                 * actual size of the subpackage.
                 */
                ExpectedCount = SubPackage->Package.Count;
                (*SubElements)->Integer.Value = ExpectedCount;
            }

            /* Check the type of each sub-package element */

            Status = AcpiNsCheckPackageElements (Data, (SubElements + 1),
                        Package->RetInfo.ObjectType1,
                        (ExpectedCount - 1), 0, 0, 1);
            if (ACPI_FAILURE (Status))
            {
                return (Status);
            }
            break;

        default: /* Should not get here, type was validated by caller */

            return (AE_AML_INTERNAL);
        }

        Elements++;
    }

    return (AE_OK);

PackageTooSmall:

    /* The sub-package count was smaller than required */

    ACPI_WARN_PREDEFINED ((AE_INFO, Data->Pathname, Data->NodeFlags,
        "Return Sub-Package[%u] is too small - found %u elements, expected %u",
        i, SubPackage->Package.Count, ExpectedCount));

    return (AE_AML_OPERAND_VALUE);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiNsCheckPackageElements
 *
 * PARAMETERS:  Data            - Pointer to validation data structure
 *              Elements        - Pointer to the package elements array
 *              Type1           - Object type for first group
 *              Count1          - Count for first group
 *              Type2           - Object type for second group
 *              Count2          - Count for second group
 *              StartIndex      - Start of the first group of elements
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Check that all elements of a package are of the correct object
 *              type. Supports up to two groups of different object types.
 *
 ******************************************************************************/

static ACPI_STATUS
AcpiNsCheckPackageElements (
    ACPI_PREDEFINED_DATA        *Data,
    ACPI_OPERAND_OBJECT         **Elements,
    UINT8                       Type1,
    UINT32                      Count1,
    UINT8                       Type2,
    UINT32                      Count2,
    UINT32                      StartIndex)
{
    ACPI_OPERAND_OBJECT         **ThisElement = Elements;
    ACPI_STATUS                 Status;
    UINT32                      i;

    /*
     * Up to two groups of package elements are supported by the data
     * structure. All elements in each group must be of the same type.
     * The second group can have a count of zero.
     */
    for (i = 0; i < Count1; i++)
    {
        Status = AcpiNsCheckObjectType (Data, ThisElement,
                    Type1, i + StartIndex);
        if (ACPI_FAILURE (Status))
        {
            return (Status);
        }
        ThisElement++;
    }

    for (i = 0; i < Count2; i++)
    {
        Status = AcpiNsCheckObjectType (Data, ThisElement,
                    Type2, (i + Count1 + StartIndex));
        if (ACPI_FAILURE (Status))
        {
            return (Status);
        }
        ThisElement++;
    }

    return (AE_OK);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiNsCheckObjectType
 *
 * PARAMETERS:  Data            - Pointer to validation data structure
 *              ReturnObjectPtr - Pointer to the object returned from the
 *                                evaluation of a method or object
 *              ExpectedBtypes  - Bitmap of expected return type(s)
 *              PackageIndex    - Index of object within parent package (if
 *                                applicable - ACPI_NOT_PACKAGE_ELEMENT
 *                                otherwise)
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Check the type of the return object against the expected object
 *              type(s). Use of Btype allows multiple expected object types.
 *
 ******************************************************************************/

static ACPI_STATUS
AcpiNsCheckObjectType (
    ACPI_PREDEFINED_DATA        *Data,
    ACPI_OPERAND_OBJECT         **ReturnObjectPtr,
    UINT32                      ExpectedBtypes,
    UINT32                      PackageIndex)
{
    ACPI_OPERAND_OBJECT         *ReturnObject = *ReturnObjectPtr;
    ACPI_STATUS                 Status = AE_OK;
    UINT32                      ReturnBtype;
    char                        TypeBuffer[48]; /* Room for 5 types */

    /*
     * If we get a NULL ReturnObject here, it is a NULL package element.
     * Since all extraneous NULL package elements were removed earlier by a
     * call to AcpiNsRemoveNullElements, this is an unexpected NULL element.
     * We will attempt to repair it.
     */
    if (!ReturnObject)
    {
        Status = AcpiNsRepairNullElement (Data, ExpectedBtypes,
                    PackageIndex, ReturnObjectPtr);
        if (ACPI_SUCCESS (Status))
        {
            return (AE_OK); /* Repair was successful */
        }
        goto TypeErrorExit;
    }

    /* A Namespace node should not get here, but make sure */

    if (ACPI_GET_DESCRIPTOR_TYPE (ReturnObject) == ACPI_DESC_TYPE_NAMED)
    {
        ACPI_WARN_PREDEFINED ((AE_INFO, Data->Pathname, Data->NodeFlags,
            "Invalid return type - Found a Namespace node [%4.4s] type %s",
            ReturnObject->Node.Name.Ascii,
            AcpiUtGetTypeName (ReturnObject->Node.Type)));
        return (AE_AML_OPERAND_TYPE);
    }

    /*
     * Convert the object type (ACPI_TYPE_xxx) to a bitmapped object type.
     * The bitmapped type allows multiple possible return types.
     *
     * Note, the cases below must handle all of the possible types returned
     * from all of the predefined names (including elements of returned
     * packages)
     */
    switch (ReturnObject->Common.Type)
    {
    case ACPI_TYPE_INTEGER:
        ReturnBtype = ACPI_RTYPE_INTEGER;
        break;

    case ACPI_TYPE_BUFFER:
        ReturnBtype = ACPI_RTYPE_BUFFER;
        break;

    case ACPI_TYPE_STRING:
        ReturnBtype = ACPI_RTYPE_STRING;
        break;

    case ACPI_TYPE_PACKAGE:
        ReturnBtype = ACPI_RTYPE_PACKAGE;
        break;

    case ACPI_TYPE_LOCAL_REFERENCE:
        ReturnBtype = ACPI_RTYPE_REFERENCE;
        break;

    default:
        /* Not one of the supported objects, must be incorrect */

        goto TypeErrorExit;
    }

    /* Is the object one of the expected types? */

    if (ReturnBtype & ExpectedBtypes)
    {
        /* For reference objects, check that the reference type is correct */

        if (ReturnObject->Common.Type == ACPI_TYPE_LOCAL_REFERENCE)
        {
            Status = AcpiNsCheckReference (Data, ReturnObject);
        }

        return (Status);
    }

    /* Type mismatch -- attempt repair of the returned object */

    Status = AcpiNsRepairObject (Data, ExpectedBtypes,
                PackageIndex, ReturnObjectPtr);
    if (ACPI_SUCCESS (Status))
    {
        return (AE_OK); /* Repair was successful */
    }

TypeErrorExit:

    /* Create a string with all expected types for this predefined object */

    AcpiNsGetExpectedTypes (TypeBuffer, ExpectedBtypes);

    if (PackageIndex == ACPI_NOT_PACKAGE_ELEMENT)
    {
        ACPI_WARN_PREDEFINED ((AE_INFO, Data->Pathname, Data->NodeFlags,
            "Return type mismatch - found %s, expected %s",
            AcpiUtGetObjectTypeName (ReturnObject), TypeBuffer));
    }
    else
    {
        ACPI_WARN_PREDEFINED ((AE_INFO, Data->Pathname, Data->NodeFlags,
            "Return Package type mismatch at index %u - "
            "found %s, expected %s", PackageIndex,
            AcpiUtGetObjectTypeName (ReturnObject), TypeBuffer));
    }

    return (AE_AML_OPERAND_TYPE);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiNsCheckReference
 *
 * PARAMETERS:  Data            - Pointer to validation data structure
 *              ReturnObject    - Object returned from the evaluation of a
 *                                method or object
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Check a returned reference object for the correct reference
 *              type. The only reference type that can be returned from a
 *              predefined method is a named reference. All others are invalid.
 *
 ******************************************************************************/

static ACPI_STATUS
AcpiNsCheckReference (
    ACPI_PREDEFINED_DATA        *Data,
    ACPI_OPERAND_OBJECT         *ReturnObject)
{

    /*
     * Check the reference object for the correct reference type (opcode).
     * The only type of reference that can be converted to an ACPI_OBJECT is
     * a reference to a named object (reference class: NAME)
     */
    if (ReturnObject->Reference.Class == ACPI_REFCLASS_NAME)
    {
        return (AE_OK);
    }

    ACPI_WARN_PREDEFINED ((AE_INFO, Data->Pathname, Data->NodeFlags,
        "Return type mismatch - unexpected reference object type [%s] %2.2X",
        AcpiUtGetReferenceName (ReturnObject),
        ReturnObject->Reference.Class));

    return (AE_AML_OPERAND_TYPE);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiNsGetExpectedTypes
 *
 * PARAMETERS:  Buffer          - Pointer to where the string is returned
 *              ExpectedBtypes  - Bitmap of expected return type(s)
 *
 * RETURN:      Buffer is populated with type names.
 *
 * DESCRIPTION: Translate the expected types bitmap into a string of ascii
 *              names of expected types, for use in warning messages.
 *
 ******************************************************************************/

static void
AcpiNsGetExpectedTypes (
    char                        *Buffer,
    UINT32                      ExpectedBtypes)
{
    UINT32                      ThisRtype;
    UINT32                      i;
    UINT32                      j;

    j = 1;
    Buffer[0] = 0;
    ThisRtype = ACPI_RTYPE_INTEGER;

    for (i = 0; i < ACPI_NUM_RTYPES; i++)
    {
        /* If one of the expected types, concatenate the name of this type */

        if (ExpectedBtypes & ThisRtype)
        {
            ACPI_STRCAT (Buffer, &AcpiRtypeNames[i][j]);
            j = 0;              /* Use name separator from now on */
        }
        ThisRtype <<= 1;    /* Next Rtype */
    }
}


text:
package jonatankarlsson.se.utils;

import java.lang.reflect.Array;

/**
 * Created by foiki on 2016-01-16.
 */
public class Arrays {
    private Arrays() {}

    /**
     * Merges two arrayes of the same type to one array if that type
     */
    public static <T> T[] merge(Class<T> type, T[] a, T[] b) {

        T[] ret = (T[]) Array.newInstance(type, a.length + b.length);

        System.arraycopy(a, 0, ret, 0, a.length);
        System.arraycopy(b, 0, ret, a.length, b.length);

        return ret;
    }
}

redpajama_set_name: RedPajamaGithub


text:
module ApplicationHelper
  def permitted_params
    @permitted_params ||= declared(params, include_missing: false)
  end
end


text:
'use strict';

rockBandsApp.controller('ListSongsController',
    function ListSongsController($scope, $rootScope, $routeParams, $location, rockBandsData) {
        $rootScope.isSearchInputShown = true;
        var bandName = $routeParams.name;

        rockBandsData
            .getSongs(bandName, null)
            .then(function (data) {
                $scope.$apply(function () {
                    if (!data.length && bandName) {
                        $location.path('/songs');
                        return;
                    }

                    $scope.songs = data;
                });
            });
    }
);


text:
class CreateUKRDCTreatments < ActiveRecord::Migration[5.2]
  def change
    within_renalware_schema do
      create_table :ukrdc_treatments do |t|
        t.references :patient, foreign_key: true, index: true, null: false
        t.references :clinician, foreign_key: { to_table: :users }, index: true, null: true
        t.references :modality_code, foreign_key: { to_table: :ukrdc_modality_codes }, index: true, null: false
        t.references :modality, index: true, null: true
        t.references :modality_description, index: true, null: true, foreign_key: true
        t.references :hospital_centre, null: true, foreign_key: true, index: true
        t.references :hospital_unit, null: true, foreign_key: true, index: true
        t.date :started_on, null: false
        t.date :ended_on
        t.timestamps null: false
      end
    end
  end
end


text:
module SimpleNavigation
  module Renderer
    describe List do
      let!(:navigation) { setup_navigation('nav_id', 'nav_class') }

      let(:item) { nil }
      let(:options) { { level: :all } }
      let(:output) { renderer.render(navigation) }
      let(:renderer) { List.new(options) }

      before { select_an_item(navigation[item]) if item }

      describe '#render' do
        it "renders an 'ul' tag for the navigation" do
          expect(output).to have_css('ul')
        end

        it "sets the right html id on the rendered 'ul' tag" do
          expect(output).to have_css('ul#nav_id')
        end

        it "sets the right html classes on the rendered 'ul' tag" do
          expect(output).to have_css('ul.nav_class')
        end

        context 'when an item has no specified id' do
          it "renders the item's 'li' tag with the item's stingified key as id" do
            expect(output).to have_css('li#invoices')
          end
        end

        context 'when an item has a specified id' do
          it "renders the item's 'li' tag with the specified id" do
            expect(output).to have_css('li#users_id')
          end
        end

        context 'when no item is selected' do
          it "renders each item as 'li' tag without any selected class" do
            expect(output).not_to have_css('ul li.selected')
          end

          it "renders each item as 'a' tag without any selected class" do
            expect(output).not_to have_css('ul li a.selected')
          end
        end

        context 'when an item is selected' do
          let(:item) { :invoices }

          it "renders the item's 'li' tag with its id and selected classes" do
            expect(output).to have_css('li#invoices.selected')
          end

          it "renders the item's 'a' tag with the selected classes" do
            expect(output).to have_css('li#invoices a.selected')
          end
        end

        context 'when the :ordered option is true' do
          let(:options) {{ level: :all, ordered: true }}

          it "renders an 'ol' tag for the navigation" do
            expect(output).to have_css('ol')
          end

          it "sets the right html id on the rendered 'ol' tag" do
            expect(output).to have_css('ol#nav_id')
          end

          it "sets the right html classes on the rendered 'ol' tag" do
            expect(output).to have_css('ol.nav_class')
          end
        end

        context 'when a sub navigation item is selected' do
          before do
            allow(navigation[:invoices]).to receive_messages(selected?: true)

            allow(navigation[:invoices].sub_navigation[:unpaid]).to \
              receive_messages(selected?: true, selected_by_condition?: true)
          end

          it 'renders the parent items as selected' do
            expect(output).to have_css('li#invoices.selected')
          end

          it "renders the selected nested item's link as selected" do
            expect(output).to have_css('li#unpaid.selected')
          end
        end
      end
    end
  end
end


text:
package org.opencb.biodata.tools.commons;

import org.opencb.biodata.formats.wig.WigUtils;
import org.opencb.biodata.models.core.Region;
import org.opencb.commons.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.sql.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;

/**
 * Created by jtarraga on 07/11/16.
 */
public class ChunkFrequencyManager {

    private Path databasePath;
    private int chunkSize;
    private int chunkSize64;

    private final static int DEFAULT_CHUNK_SIZE = 1000;

    // main counters and structures to save packed coverages
    int counter1 = 0; // counter for 8-byte mean coverages array
    int counter2 = 0; // counter for 8-long packed coverages array
    byte[] meanCoverages = new byte[8]; // contains 8 coverages
    long[] packedCoverages = new long[8]; // contains 8 x 8 coverages
    private Map chunkIdMap;

    private Logger logger;

    public ChunkFrequencyManager(Path databasePath) throws IOException {
        this(databasePath, DEFAULT_CHUNK_SIZE);
    }

    public ChunkFrequencyManager(Path databasePath, int chunkSize) {
        this.databasePath = databasePath;
        this.chunkSize = chunkSize;
        this.chunkSize64 = chunkSize * 64;

        logger = LoggerFactory.getLogger(this.getClass());
    }

    public void init(List<String> chromosomeNames, List<Integer> chromosomeSizes) {
        Statement stmt = null;
        Connection connection = null;

        try {
            Class.forName("org.sqlite.JDBC");
            connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath);

            // Create tables
            stmt = connection.createStatement();
            String sql = "CREATE TABLE chunk "
                    + "(id INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + "chunk_id VARCHAR NOT NULL,"
                    + "chromosome VARCHAR NOT NULL, "
                    + "start INT NOT NULL, "
                    + "end INT NOT NULL); "
                    + "CREATE UNIQUE INDEX chunk_id_idx ON chunk (chunk_id);"
                    + "CREATE INDEX chrom_start_end_idx ON chunk (chromosome, start, end);";
            stmt.executeUpdate(sql);

            sql = "CREATE TABLE info "
                    + "(id INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + "name VARCHAR NOT NULL,"
                    + "value VARCHAR NOT NULL);"
                    + "CREATE UNIQUE INDEX name_idx ON info (name);";
            stmt.executeUpdate(sql);

            sql = "insert into info (name, value) values ('chunkSize', '" + chunkSize + "');";
            stmt.executeUpdate(sql);

            sql = "CREATE TABLE file "
                    + "(id INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + "path VARCHAR NOT NULL,"
                    + "name VARCHAR NOT NULL);"
                    + "CREATE UNIQUE INDEX path_idx ON file (path);";
            stmt.executeUpdate(sql);

            sql = "CREATE TABLE mean_coverage "
                    + "(chunk_id INTEGER,"
                    + "file_id INTEGER,"
                    + "v1 INTEGER, "
                    + "v2 INTEGER, "
                    + "v3 INTEGER, "
                    + "v4 INTEGER, "
                    + "v5 INTEGER, "
                    + "v6 INTEGER, "
                    + "v7 INTEGER, "
                    + "v8 INTEGER,"
                    + "PRIMARY KEY(chunk_id, file_id));";
            stmt.executeUpdate(sql);

            // Insert all the chunks
            String minorChunkSuffix = (chunkSize / 1000) * 64 + "k";

            PreparedStatement insertChunk = connection.prepareStatement("insert into chunk (chunk_id, chromosome, start, end) "
                    + "values (?, ?, ?, ?)");

            connection.setAutoCommit(false);
            for (int i = 0; i < chromosomeNames.size(); i++) {
                String name = chromosomeNames.get(i);
                int length = chromosomeSizes.get(i);

                int cont = 0;
                for (int j = 0; j < length; j += chunkSize64) {
                    String chunkId = name + "_" + cont + "_" + minorChunkSuffix;
                    insertChunk.setString(1, chunkId);
                    insertChunk.setString(2, name);
                    insertChunk.setInt(3, j + 1);
                    insertChunk.setInt(4, j + chunkSize64);
                    insertChunk.addBatch();
                    cont++;
                }
                insertChunk.executeBatch();
            }
            connection.commit();
            connection.setAutoCommit(true);

            // close both resources
            stmt.close();
            connection.close();
        } catch (SQLException e) {
            logger.error(e.getClass().getName() + ": " + e.getMessage());
            try {
                if (connection != null) {
                    connection.rollback();
                }

                if (stmt != null) {
                    stmt.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
//            System.exit(0);
        } catch (ClassNotFoundException e) {
            logger.error(e.getClass().getName() + ": " + e.getMessage());
            e.printStackTrace();
        }

        logger.debug("Initialized database successfully");
    }

    public void loadWigFile(Path countPath, Path bamPath) throws IOException {
        FileUtils.checkFile(countPath);

        try {
            // Insert into file table
            Class.forName("org.sqlite.JDBC");
            Connection conn = DriverManager.getConnection("jdbc:sqlite:" + databasePath);

            // get chunk size from database
            chunkSize = getChunkSize(conn);
            if (chunkSize == -1) {
                throw new InternalError("Coverage DB does not contain information about chunk size");
            }

            // insert file info get chunk size from database
            int fileId = insertFile(bamPath, conn);
            if (fileId == -1) {
                throw new InternalError("Error inserting file " + bamPath + " into the coverage database");
            }

            // retrieve chunk IDs from database
            chunkIdMap = new HashMap<String, Integer>();
            String sql = "SELECT id, chromosome, start FROM chunk";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                chunkIdMap.put(rs.getString("chromosome") + "_" + rs.getInt("start"), rs.getInt("id"));
            }

            // prepare statement to iterate over the file
            PreparedStatement insertCoverage = conn.prepareStatement("insert into mean_coverage (chunk_id, "
                    + " file_id, v1, v2, v3, v4, v5, v6, v7, v8) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            conn.setAutoCommit(false);

            // reader
            BufferedReader bufferedReader = FileUtils.newBufferedReader(countPath);

            int step = 1;
            int span = 1;
            int position = 1;
            String chromosome = null;

            // main loop
            String line = bufferedReader.readLine();
            while (line != null) {
                // check for header lines
                if (WigUtils.isHeaderLine(line)) {
                    System.out.println("Loading wig data:" + line);
                    if (WigUtils.isVariableStep(line)) {
                        throw new UnsupportedOperationException("Wig coverage file with 'variableStep'"
                                + " is not supported yet.");
                    }

                    // update some values
                    step = WigUtils.getStep(line);
                    span = WigUtils.getSpan(line);
                    position = WigUtils.getStart(line);
                    chromosome = WigUtils.getChromosome(line);

                    if (step != 1) {
                        throw new UnsupportedOperationException("Wig coverage file with"
                                + " 'step' != 1 is not supported yet.");
                    }

                    // next line...
                    line = bufferedReader.readLine();
                } else {
                    // main body, coverage values
                    if (span <= chunkSize) {
                        // span is smaller than chunk size, we have to read n = chunkSize/span lines
                        // and get a mean coverage for the chunk
                        int n = chunkSize / span;
                        int sum = 0;
                        int counter = 0;
                        while (true) {
                            // accumulate the current value, and check if we have a complete value
                            sum += Integer.parseInt(line);
                            if (++counter == n) {
                                updatePackedCoverages((byte) Math.min(sum / counter, 255), getChunkId(chromosome, position),
                                        fileId, insertCoverage);
                                sum = 0;
                                counter = 0;
                            }
                            line = bufferedReader.readLine();
                            if (line == null || (line != null && WigUtils.isHeaderLine(line))) {
                                // pending coverages to save
                                if (counter > 0) {
                                    updatePackedCoverages((byte) Math.min(sum / counter, 255),
                                            getChunkId(chromosome, position), fileId, insertCoverage);
                                }
                                if (counter1 > 0 || counter2 > 0) {
                                    packedCoverages[counter2] = bytesToLong(meanCoverages);
                                    insertPackedCoverages(insertCoverage, getChunkId(chromosome, position),
                                            fileId, packedCoverages);
                                }
                                resetCounters();
                                break;
                            } else {
                                position += span;
                            }
                        }
                    } else {
                        throw new UnsupportedOperationException("span bigger than chunkSize is not supported");
                    }
                }
            }
            bufferedReader.close();

            if (counter1 > 0 || counter2 > 0) {
                packedCoverages[counter2] = bytesToLong(meanCoverages);
                insertPackedCoverages(insertCoverage, getChunkId(chromosome, position), fileId, packedCoverages);
            }

            // insert batch to the DB
            insertCoverage.executeBatch();

            conn.commit();
            stmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ChunkFrequency query(Region region, Path filePath, int windowSize) {
        return query(region, filePath, windowSize, mean());
    }

    //    public ChunkFrequency query(Region region, Path filePath, int windowSize, AggregatorFunction aggregatorFunction) {
    public ChunkFrequency query(Region region, Path filePath, int windowSize, BiFunction aggregatorFunction) {
        if (aggregatorFunction == null) {
            aggregatorFunction = mean();
        }

        windowSize = Math.max(windowSize / chunkSize * chunkSize, chunkSize);
        int size = ((region.getEnd() - region.getStart() + 1) / windowSize) + 1;
        short[] values = new short[size];

        try {
            Class.forName("org.sqlite.JDBC");
            Connection connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath);
            Statement stmt = connection.createStatement();

            String sql = "SELECT id FROM file where path = '" + filePath.getParent() + "';";
            ResultSet rs = stmt.executeQuery(sql);
            int fileId = -1;
            while (rs.next()) {
                fileId = rs.getInt("id");
                break;
            }

            // sanity check
            if (fileId == -1) {
                throw new SQLException("File " + filePath + " not found in the coverage DB");
            }

            sql = "SELECT c.start, c.end, mc.v1, mc.v2, mc.v3, mc.v4, mc.v5, mc.v6, mc.v7, mc.v8"
                    + " FROM chunk c, mean_coverage mc"
                    + " WHERE c.id = mc.chunk_id AND mc.file_id = " + fileId
                    + " AND c.chromosome = '" + region.getChromosome() + "' AND c.start <= " + region.getEnd()
                    + " AND c.end > " + region.getStart() + " ORDER by c.start ASC;";
            rs = stmt.executeQuery(sql);

            int chunksPerWindow = windowSize / chunkSize;
            int chunkCounter = 0;
            int coverageAccumulator = 0;
            int arrayPos = 0;

            int start = 0;
            long packedCoverages;
            byte[] meanCoverages;

            boolean first = true;
            while (rs.next()) {
                if (first) {
                    start = rs.getInt("start");
                    first = false;
                }
                for (int i = 0; i < 8; i++) {
                    packedCoverages = rs.getLong("v" + (i + 1));
                    meanCoverages = longToBytes(packedCoverages);
                    for (int j = 0; j < 8; j++) {
                        if (start <= region.getEnd() && (start + chunkSize) >= region.getStart()) {
                            // A byte is always signed in Java,
                            // we can get its unsigned value by binary-anding it with 0xFF
                            coverageAccumulator += (meanCoverages[j] & 0xFF);
                            if (++chunkCounter >= chunksPerWindow) {
                                values[arrayPos++] = (short) aggregatorFunction.apply(coverageAccumulator, chunkCounter);
//                                        (short) Math.min(Math.round(
//                                        1.0f * coverageAccumulator / chunkCounter), 255);
                                coverageAccumulator = 0;
                                chunkCounter = 0;
                            }
                        }
                        start += chunkSize;
                    }
                }
            }
            if (chunkCounter > 0) {
                values[arrayPos++] = (short) aggregatorFunction.apply(coverageAccumulator, chunkCounter);
//                (short) Math.min(Math.round(1.0f * coverageAccumulator / chunkCounter), 255);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new ChunkFrequency(region, windowSize, values);
    }

    public BiFunction<Integer, Integer, Short> mean() {
        return (a, b) -> (short) Math.min(Math.round(1.0f * a / b), 255);
    }

    public BiFunction<Integer, Integer, Short> addition() {
        return (a, b) -> (short) Math.min(a, 255);
    }

    /**
     *
     * ChunkFrequency object
     *
     */

    public class ChunkFrequency extends Region {

        private int windowSize;
        private short[] values;

        public ChunkFrequency(Region region, int windowSize, short[] values) {
            super(region.getChromosome(), region.getStart(), region.getEnd());
            this.windowSize = windowSize;
            this.values = values;
        }

        public int getWindowSize() { return this.windowSize; }
        public short[] getValues() { return this.values; }
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("ChunkFrequencyManager{");
        sb.append("databasePath=").append(databasePath);
        sb.append(", chunkSize=").append(chunkSize);
        sb.append('}');
        return sb.toString();
    }

    public Path getDatabasePath() {
        return databasePath;
    }

    public ChunkFrequencyManager setDatabasePath(Path databasePath) {
        this.databasePath = databasePath;
        return this;
    }

    public int getChunkSize() {
        return chunkSize;
    }

    public ChunkFrequencyManager setChunkSize(int chunkSize) {
        this.chunkSize = chunkSize;
        return this;
    }

    /**
     *
     * P R I V A T E     F U N C T I O N S
     *
     */

    private int insertFile(Path bamPath, Connection conn) throws SQLException {
        Statement stmt = conn.createStatement();
        String insertFileSql = "insert into file (path, name) values ('" + bamPath.getParent()
                + "', '" + bamPath.getFileName() + "');";
        stmt.executeUpdate(insertFileSql);
        stmt.close();

        ResultSet rs = stmt.executeQuery("SELECT id FROM file where path = '" + bamPath.getParent() + "';");
        int fileId = -1;
        while (rs.next()) {
            fileId = rs.getInt("id");
        }
        stmt.close();

        return fileId;
    }

    private int getChunkSize(Connection conn) throws SQLException {
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT value FROM info where name = 'chunkSize';");
        int chunkSize = -1;
        while (rs.next()) {
            chunkSize = Integer.parseInt(rs.getString("value"));
        }
        return chunkSize;
    }

    private int getChunkId(String chromosome, int position) {
        int chunkId;
        String key = chromosome + "_" + (position / chunkSize64 * chunkSize64 + 1);
        if (chunkIdMap.containsKey(key)) {
            chunkId = (int) chunkIdMap.get(key);
        } else {
            throw new InternalError("Coverage chunk " + chromosome
                    + ":" + position + "-, not found in database");
        }
        return chunkId;
    }

    private void updatePackedCoverages(byte coverage, int chunkId, int fileId, PreparedStatement insertCoverage)
            throws SQLException {
        meanCoverages[counter1] = coverage;
        if (++counter1 == 8) {
            // packed mean coverages and save into the packed coverages array
            packedCoverages[counter2] = bytesToLong(meanCoverages);
            if (++counter2 == 8) {
                // write packed coverages array to DB
                insertPackedCoverages(insertCoverage, chunkId, fileId, packedCoverages);

                // reset packed coverages array and counter2
                Arrays.fill(packedCoverages, 0);
                counter2 = 0;
            }
            // reset mean coverages array and counter1
            counter1 = 0;
            Arrays.fill(meanCoverages, (byte) 0);
        }
    }

    private void resetCounters() {
        Arrays.fill(meanCoverages, (byte) 0);
        Arrays.fill(packedCoverages, 0);
        counter2 = 0;
        counter1 = 0;
    }

    private void insertPackedCoverages(PreparedStatement insertCoverage, int chunkId, int fileId, long[] packedCoverages)
            throws SQLException {
        assert(chunkId != -1);

        insertCoverage.setInt(1, chunkId);
        insertCoverage.setInt(2, fileId);
        for (int i = 0; i < 8; i++) {
            insertCoverage.setLong(i + 3, packedCoverages[i]);
        }
        insertCoverage.addBatch();
    }

    private byte[] longToBytes(long x) {
        ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
        buffer.putLong(x);
        return buffer.array();
    }

    private long bytesToLong(byte[] bytes) {
        ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
        buffer.put(bytes);
        buffer.flip(); // need flip
        return buffer.getLong();
    }
}


text:
package com.github.jobson.scripting.testclasses;

import static com.github.jobson.Helpers.toJSON;

public final class JsonStringifier {

    public String stringify(Object o) {
        return toJSON(o);
    }
}


text:
<?php

/**
 * Book_Model_Category
 *
 * @author Sarjono Mukti Aji <http://simukti.net/>
 * @copyright (c) 2011 - Sarjono Mukti Aji <http://simukti.net/>
 */
class Book_Model_Category extends Minilib_BooksCategory
{
    /**
     * @see Doctrine_Record::save()
     * @param array $data
     * @return void
     */
    public function insertCategory(array $data)
    {
        $this->category_name = $data['category_name'];
        $save = $this->save();
        return $save;
    }

    /**
     * @see Doctrine_Record::save()
     * @param Book_Model_Category $category
     * @param array $new_data
     * @return void
     */
    public function updateCategory(Book_Model_Category $category, array $new_data)
    {
        $category->category_name = $new_data['category_name'];
        $save = $category->save();
        return $save;
    }

    /**
     * This method will cascade delete all related data.
     *
     * @see Minilib_Books::delete()
     * @param Book_Model_Category $category
     * @return bool Deletion status
     */
    public function deleteCategory(Book_Model_Category $category)
    {
        $delete = $category->delete();
        return $delete;
    }

    /**
     * Get single category
     *
     * @param int $id_category
     * @return Doctrine_Record | false
     */
    public function getCategory($id_category)
    {
        $category = $this->getTable()->findOneByIdBooksCategory($id_category);
        return $category;
    }

    /**
     * Get all category from database
     *
     * @return Doctrine_Collection
     */
    public function getAllCategory()
    {
        $categories = $this->getTable()->createQuery('c')
                           ->orderBy('c.category_name')
                           ->execute();
        return $categories;
    }
}


text:
/*
 * @test
 * @bug 4620794
 * @summary compiler allows null + null
 * @author gafter
 *
 * @compile/fail NullAppend.java
 */

class NullAppend {{
    String s = null + null;
}}


text:
namespace hana = boost::hana;

namespace ns {
    struct Person {
        explicit Person(std::string const& name, int age)
            : name_(name), age_(age)
        { }
        std::string const& get_name() const { return name_; }
        int get_age() const { return age_; }

    private:
        std::string name_;
        int age_;
    };
}

BOOST_HANA_ADAPT_ADT(ns::Person,
    (name, [](ns::Person const& p) { return p.get_name(); }),
    (age, [](ns::Person const& p) { return p.get_age(); })
);

// The member names are hana::strings:
auto names = hana::transform(hana::accessors<ns::Person>(), hana::first);
BOOST_HANA_CONSTANT_CHECK(
    names == hana::make_tuple(BOOST_HANA_STRING("name"), BOOST_HANA_STRING("age"))
);

int main() {
    ns::Person john{"John", 30}, bob{"Bob", 40};
    BOOST_HANA_RUNTIME_CHECK(hana::equal(john, john));
    BOOST_HANA_RUNTIME_CHECK(hana::not_equal(john, bob));

    BOOST_HANA_RUNTIME_CHECK(hana::find(john, BOOST_HANA_STRING("name")) == hana::just("John"));
    BOOST_HANA_RUNTIME_CHECK(hana::find(john, BOOST_HANA_STRING("age")) == hana::just(30));
    BOOST_HANA_CONSTANT_CHECK(hana::find(john, BOOST_HANA_STRING("foo")) == hana::nothing);

    BOOST_HANA_RUNTIME_CHECK(hana::to_tuple(john) == hana::make_tuple(
        hana::make_pair(BOOST_HANA_STRING("name"), "John"),
        hana::make_pair(BOOST_HANA_STRING("age"), 30)
    ));

    BOOST_HANA_RUNTIME_CHECK(hana::to_map(john) == hana::make_map(
        hana::make_pair(BOOST_HANA_STRING("name"), "John"),
        hana::make_pair(BOOST_HANA_STRING("age"), 30)
    ));
}


text:
- recognize and apply design principles of functional programs,
- design functional libraries and their APIs,
- competently combine functions and state in one program,
- understand reasoning techniques for programs that combine functions and state,
- write simple functional reactive applications.


text:
'use strict';

const registerComponent = (contentType, { registry, strapi, builders }) => {
  const { service: getService } = strapi.plugin('graphql');

  const { getComponentName } = getService('utils').naming;
  const { KINDS } = getService('constants');

  const name = getComponentName(contentType);
  const definition = builders.buildTypeDefinition(contentType);

  registry.register(name, definition, { kind: KINDS.component, contentType });
};

module.exports = { registerComponent };


text: make INCLUDES=$PREFIX/include INSTALLDIR=$PREFIX/bin install -j${CPU_COUNT}


text:
require 'sqlite3'
require 'fileutils'
require 'delegate'
require 'singleton'
require 'chef-workflow/support/general'

module ChefWorkflow
  class DatabaseSupport < DelegateClass(SQLite3::Database)
    include Singleton

    def initialize
      super(connect)
    end

    def reconnect
      close rescue nil
      __setobj__(connect)
    end

    def connect
      vm_file = ChefWorkflow::GeneralSupport.vm_file
      FileUtils.mkdir_p(File.dirname(vm_file))
      SQLite3::Database.new(vm_file)
    end
  end
end


text:
/**
 * Defines the styles for the prompt UI.
 */

button {
  margin-bottom: 10px;
}

form {
  margin-top: 10px;
}

input[type="text"],
input[type="password"] {
  width: 548px;
}

textarea {
  border: 1px solid YCOLOR_GREY_6;
  height: 200px;
  width: 650px;
}

textarea:hover,
textarea:focus,
#pgpKeySelect:hover,
#pgpKeySelect:focus,
#fromHolder:hover,
#fromHolder:focus {
  border: 1px solid YCOLOR_GREY_10;
  outline: none;
}

#pgpBody {
  padding: 0 8px;
}

#pgpBody input[type="checkbox"],
#pgpBody input[type="password"] {
  margin: 8px 8px 0 0;
}

#pgpBody > #pgpKeySelect {
  margin-bottom: 8px;
}

#menu-container {
  float: right;
  margin-right: 10px;
  margin-top: -4px;
}

#menu-container img {
  cursor: auto;
  opacity: .4;
  padding: 5px 3px 1px 0;
}

#menu-container:hover img {
  cursor: pointer;
  opacity: .8;
}

#errorDiv {
  display: block;
  font-size: 1em;
  height: 16px;
}

.goog-menu {
  background-color: white;
  border: 1px solid YCOLOR_GREY_6;
  box-shadow: 0 4px 16px rgba(0,0,0,0.2);
  cursor: default;
  margin: 0;
  outline: none;
  padding: 4px 0;
  position: absolute;
  z-index: 20000; /* Arbitrary, but some apps depend on it... */
}

/* State: resting. */
.goog-menuitem {
  color: #000;
  font: normal 13px Arial, sans-serif;
  list-style: none;
  margin: 0;
  /* 28px on the left for icon or checkbox; 7em on the right for shortcut. */
  padding: 4px 7em 4px 28px;
  white-space: nowrap;
}

/* If a menu doesn't have checkable items or items with icons, remove padding. */
.goog-menu-nocheckbox .goog-menuitem,
.goog-menu-noicon .goog-menuitem {
  padding-left: 12px;
}

/*
 * If a menu doesn't have items with shortcuts, leave just enough room for
 * submenu arrows, if they are rendered.
 */
.goog-menu-noaccel .goog-menuitem {
  padding-right: 20px;
}

.goog-menuitem-content {
  color: #000;
  font: normal 13px Arial, sans-serif;
}

/* State: disabled. */
.goog-menuitem-disabled .goog-menuitem-accel,
.goog-menuitem-disabled .goog-menuitem-content {
  color: YCOLOR_GREY_4 !important;
}
.goog-menuitem-disabled .goog-menuitem-icon {
  opacity: 0.3;
}

/* State: hover. */
.goog-menuitem-highlight,
.goog-menuitem-hover {
  background-color: YCOLOR_GREY_2;
  /* Use an explicit top and bottom border so that the selection is visible
   * in high contrast mode. */
  border-color: YCOLOR_GREY_4;
  border-style: dotted;
  border-width: 1px 0;
  cursor: pointer;
  padding-bottom: 3px;
  padding-top: 3px;
}

/* State: selected/checked. */
.goog-menuitem-checkbox,
.goog-menuitem-icon {
  background-repeat: no-repeat;
  height: 16px;
  left: 6px;
  position: absolute;
  right: auto;
  vertical-align: middle;
  width: 16px;
}
.goog-option-selected .goog-menuitem-checkbox,
.goog-option-selected .goog-menuitem-icon {
  /* Client apps may override the URL at which they serve the sprite. */
  background: url(https://ssl.gstatic.com/editor/editortoolbar.png) no-repeat -512px 0;
}

/* Keyboard shortcut ("accelerator") style. */
.goog-menuitem-accel {
  color: YCOLOR_GREY_6;
  /* Keyboard shortcuts are untranslated; always left-to-right. */
  /* @noflip */ direction: ltr;
  left: auto;
  padding: 0 6px;
  position: absolute;
  right: 0;
  text-align: right;
}


text:
set -ex
USERNAME=panoplymedia
IMAGE=buildkite-agent
# ensure we're up to date
git pull
# bump version
docker build -t $USERNAME/$IMAGE:latest .
version=`cat VERSION`
echo "version: $version"
# run build
./build.sh
# tag it
git tag -a "$version" -m "version $version"
git push
git push --tags
docker tag $USERNAME/$IMAGE:latest $USERNAME/$IMAGE:$version
# push it
docker push $USERNAME/$IMAGE:latest
docker push $USERNAME/$IMAGE:$version


text:
<?php

use yii\bootstrap\Html;
use yii\bootstrap\ActiveForm;
use yii\jui\DatePicker;
use frontend\models\User;
use dosamigos\selectize\SelectizeTextInput;

/* @var $this yii\web\View */
/* @var $searchModel common\models\TicketSearch */
/* @var $action string */
/* @var $currentPageSize integer */
/* @var $showPriority boolean */

$searchPanelOpen = false;
if (isset($_COOKIE['search-block'])) {
    $searchPanelOpen = $_COOKIE['search-block'] == '1';
}
?>

<button
    id="hide-search-option-button"
    type="button"
    class="btn btn-primary btn-xs <?php echo $searchPanelOpen ? '' : 'hidden'?>"
    data-toggle="collapse"
    data-target="#left-sidebar"
    aria-controls="left-sidebar"
    aria-expanded="<?php echo $searchPanelOpen ? 'false' : 'true'?>">
    <?php echo \Yii::t('app', 'Hide Search Options'); ?>
</button>

<?php
    $form = ActiveForm::begin([
        'action' => [$action],
        'method' => 'post',
    ]);
?>

<?php
    echo Html::hiddenInput('per-page', $currentPageSize, [
        'id' => 'backlog-search-per-page'
    ]);

    $clearIcon = '';
    echo $form->field($searchModel, 'text_search', [
        'template' => "{label}\n{input}$clearIcon\n{hint}\n{error}"
    ]);

    if ($showPriority) {
        echo $form->field($searchModel, 'vote_priority_filter')->checkbox([
            'All' => 0,
            'Voted' => 1,
        ], false);
    }

    $clearIcon = '';
    echo $form->field($searchModel, 'from_date', [
        'template' => "{label}\n{input}$clearIcon\n{hint}\n{error}"
    ])->widget(DatePicker::classname(), [
        'options' => ['class' => 'form-control'],
    ]);

    $clearIcon = '';
    echo $form->field($searchModel, 'to_date', [
        'template' => "{label}\n{input}$clearIcon\n{hint}\n{error}"
    ])->widget(DatePicker::classname(), [
        'options' => ['class' => 'form-control'],
    ]);

    $users = User::getBoardUsers();
    $checkBoxSetup = [];
    foreach ($users as $user) {
        // Include color and grayscale avatar, color when selected, gray when not selected
        // visibility toggled via jQuery/javascript
        $colorId = 'user_search-avatar-color-' . $user->id;
        $grayId = 'user_search-avatar-gray-' . $user->id;
        $showColor = is_array($searchModel->user_search) ? in_array($user->id, $searchModel->user_search) : false;
        $checkBoxSetup[$user->id] =
            html::img($user->avatarUrlColor, [
                'alt' => $user->username,
                'title' => $user->username,
                'id' => $colorId,
                'class' => !$showColor ? 'ticket-avatar-hide' : '',
            ])
            . html::img($user->avatarUrlGray, [
                'alt' => $user->username,
                'title' => $user->username,
                'id' => $grayId,
                'class' => $showColor ? 'ticket-avatar-hide' : '',
            ]);
    }

    echo $form->field($searchModel, 'user_search', ['options' => ['class' => 'clearfix']])
        ->checkboxList($checkBoxSetup, [
                'item' =>
                    function ($index, $label, $name, $checked, $value) {

                        $inlineJS = '$("#user_search-avatar-color-' . $value . '").toggle();';
                        $inlineJS .= '$("#user_search-avatar-gray-' . $value . '").toggle();';
                        return '
'
                        . Html::checkbox($name, $checked, [
                            'label' => $label,
                            'value' => $value,
                            'onclick' => $inlineJS,
                        ]) . '
';
                    }
            ]
        );

    echo $form->field($searchModel, 'tag_search')->widget(SelectizeTextInput::className(), [
        // calls an action that returns a JSON object with matched
        // tags
        'loadUrl' => ['tags/list'],
        'options' => ['class' => 'form-control'],
        'clientOptions' => [
            'plugins' => ['remove_button'],
            'valueField' => 'name',
            'labelField' => 'name',
            'searchField' => ['name'],
            'create' => true,
        ],
    ])->hint(\Yii::t('app', 'Use commas to separate tags'));
?>

    <?php
        echo Html::submitButton(\Yii::t('app', 'Search'), [
            'class' => 'btn btn-primary',
            'id' => 'backlog-search-submit',
        ]);
    ?>

<?php ActiveForm::end(); ?>


text:
#pragma once

#include "IComponent.h"
#include "OgreModuleFwd.h"

#include <QVector3D>
#include <QQuaternion>
#include <OgreTexture.h>

/// EntityComponent that will create a planar mirror texture (and optionally a plane showing it).
/**

PlanarMirror

EntityComponent that will create a planar mirror texture (and optionally a plane showing it).
NOTE: Assumes the the entity already has: EC_Placeable, EC_RttTarget and EC_Camera. Otherwise EC_PlanarMirror cannot function.
Attributes:

bool reflectionPlaneVisible

Do we want to show the mirror plane

Exposes the following scriptable functions:

...

Reacts on the following actions:

...

Does not emit any actions.

Depends on EC_Camera, EC_Placeable and EC_RttTarget.

*/
class EC_PlanarMirror : public IComponent
{
    Q_OBJECT
    COMPONENT_NAME("EC_PlanarMirror", 34)

public:
    EC_PlanarMirror(Scene *scene);
    ~EC_PlanarMirror();

    /// Do we want to show the mirror plane
    Q_PROPERTY(bool reflectionPlaneVisible READ getreflectionPlaneVisible WRITE setreflectionPlaneVisible);
    DEFINE_QPROPERTY_ATTRIBUTE(bool, reflectionPlaneVisible);

    //Returns the texture that you can set to be used on a material. Do not modify this texture yourself
    Ogre::Texture* GetMirrorTexture() const;

public slots:
    void Initialize();
    void Update(float val);
    void OnAttributeUpdated(IAttribute* attr);
    void WindowResized(int w,int h);

private:
    void CreatePlane();

    OgreRenderer::RendererPtr renderer_;

    static int mirror_cam_num_;

    Ogre::Camera* mirror_cam_;
    Ogre::Texture* mirror_texture_;
    Ogre::TextureUnitState* tex_unit_state_;
    Ogre::Material* mat_;
    Ogre::Entity* mirror_plane_entity_;
    Ogre::MovablePlane* mirror_plane_;
};


text:
/**
 * Router for Koa v2
 *
 * @author blaz <blaz@menems.net>
 * @link https://github.com/menems/koa-66
 * @license MIT
 *
 */

'use strict';

const debug = require('debug')('koa-66');
const pathToRegexp = require('path-to-regexp');
const compose = require('koa-compose');
const util = require('util');

const methods = [
    'options',
    'head',
    'get',
    'post',
    'put',
    'patch',
    'delete'
];

/**
 * Expose Koa66 class.
 */
class Koa66 {

    /**
     * Initialise a new Koa66
     *
     * @api public
     */
    constructor() {
        this.stacks = [];
        this.methods = methods;
        this.plugs = [];
    }

    /**
     * Mount a Koa66 instance on a prefix path
     *
     * @todo: too memory expensive instance are clone
     * maybe add a keep args to remove the router instance mounted!
     *
     * @param  {string} prefix
     * @param  {Object} router  Koa66 instance
     * @return {Object}         Koa66 instance
     * @api public
     */
    mount(prefix, router) {
        if (typeof router != 'object')
            throw new TypeError('require a Koa66 instance');

        router.stacks.forEach(s => {
            if (s.paramKey)
                this.register(s.methods, prefix + s.path, s.paramKey, s.middleware);
            else
                this.register(s.methods, prefix + s.path, s.middleware);
        });
        return this;
    }

    /**
     * Use given middleware before route callback
     *
     * @param  {String|Function} path
     * @param  {Function} fn
     * @return {Object} Koa66 instance
     * @api public
     */
    use() {
        const args = Array.prototype.slice.call(arguments);
        if (typeof args[0] != 'string')
            args.unshift('(.*)');
        args.unshift(false);
        return this.register.apply(this, args);
    }

    /**
     * param express like function
     *
     * @param  {String}   key
     * @param  {Function} fn
     * @return {Object}
     */
    param(key, fn) {
        if (typeof key != 'string' || typeof fn != 'function')
            throw new TypeError('usage: param(string, function)');
        return this.register(false, '(.*)', key, fn);
    }

    /**
     * plugin registration method
     *
     * @param  {String}   name
     * @param  {[Function]...}
     * @return {Object}
     */
    plugin(name) {
        if (typeof name != 'string')
            throw new TypeError('usage: plugin(string, function)');

        const args = Array.prototype.slice.call(arguments, 1);

        let middlewares = [];
        args.forEach(m => {
            if (util.isArray(m)) middlewares = middlewares.concat(m);
            if (typeof m == 'function') middlewares.push(m);
        });
        this.plugs[name] = compose(middlewares);
        return this;
    }

    /**
     * Expose middleware for koa
     *
     * @return {Function}
     * @api public
     */
    routes(options) {
        options = options || {};

        return (ctx, next) => {
            const middlewares = [];
            const allowed = [];
            const paramMiddlewares = [];
            let matched;

            this.stacks.forEach(route => {
                // path test
                if (!route.regexp.test(ctx.path)) return;

                // Save the route so we can access ctx.route.path
                ctx.route = route;

                if (route.paramNames)
                    ctx.params = this.parseParams(ctx.params, route.paramNames, ctx.path.match(route.regexp).slice(1));

                if (route.paramKey) {
                    paramMiddlewares[route.paramKey] = (ctx, next) =>
                        route.middleware(ctx, next, ctx.params[route.paramKey]);
                    return;
                }

                if ( typeof route.middleware === 'object') {
                    for (let i in route.middleware) {
                        if ( this.plugs[i]) {
                            middlewares.push((ctx, next) => {
                                ctx.state.plugins = ctx.state.plugins || {};
                                ctx.state.plugins[i] = route.middleware[i];
                                return this.plugs[i](ctx, next);
                            });
                        }
                    }
                    return;
                }

                if (!route.methods)
                    return middlewares.push(route.middleware);

                if (route.methods.indexOf('GET') !== -1)
                    allowed.push('HEAD');
                route.methods.forEach(m => allowed.push(m));

                // method test
                if ((route.methods.indexOf(ctx.method) !== -1) ||
                    (ctx.method === 'HEAD' && route.methods.indexOf('GET') !== -1)) {
                    matched = true;
                    for (let i in ctx.params) {
                        if (paramMiddlewares[i])
                            middlewares.push(paramMiddlewares[i]);
                            delete paramMiddlewares[i]
                    }
                    middlewares.push(route.middleware);
                }
            });

            // only use middleware
            if (!allowed.length) return next();

            // 501
            if (this.methods.indexOf(ctx.method.toLowerCase()) === -1) {
                if (options.throw)
                    ctx.throw(501);
                ctx.status = 501;
                return next();
            }

            // 405
            if (!matched) {
                // automatic OPTIONS response
                if (ctx.method === 'OPTIONS') {
                    ctx.status = 204;
                    return next();
                }

                const _allowed = allowed.filter((value, index, self) => self.indexOf(value) === index).join(', ');

                if (options.throw)
                    ctx.throw(405, {headers: {allow: _allowed}});
                ctx.status = 405;
                ctx.set('Allow', _allowed);
                return next();
            }

            return compose(middlewares)(ctx, next);
        };
    }

    /**
     * Register a route for all methods.
     *
     * @param  {String}  path
     * @return {[Functions]...}  middleware
     */
    all() {
        const args = Array.prototype.slice.call(arguments);

        if (typeof args[0] != 'string') args.unshift('/');

        args.unshift(methods);
        return this.register.apply(this, args);
    }

    sanitizePath(path) {
        if (!path) return '/';

        return '/' + path
            .replace(/^\/+/i, '')
            .replace(/\/+$/, '')
            .replace(/\/{2,}/, '/');
    }

    /**
     * Register a new middleware, http route or use middeware
     *
     * @param  {string} methods
     * @param  {string} path
     * @param  {Function} middleware
     * @return {Object} Koa66 instance
     * @api private
     */
    register(methods, path) {
        debug('Register %s %s', methods, path);
        let middlewares;
        let paramKey;
        if (typeof arguments[2] === 'string') {
            paramKey = arguments[2];
            middlewares = Array.prototype.slice.call(arguments, 3);
        } else
            middlewares = Array.prototype.slice.call(arguments, 2);

        if (!middlewares.length)
            throw new Error('middleware is required');

        middlewares.forEach(m => {
            if (Array.isArray(m)) {
                m.forEach(_m => this.register(methods, path, _m));
                return this;
            }

            if ( typeof m !== 'function' && typeof m !== 'object')
                throw new TypeError('middleware must be a function');

            const keys = [];
            path = (!path || path === '(.*)' || util.isRegExp(path)) ? path : this.sanitizePath(path);
            const regexp = pathToRegexp(path, keys);

            const route = {
                path: path,
                middleware: m,
                regexp: regexp,
                paramNames: keys
            };

            if (paramKey) route.paramKey = paramKey;

            if (methods) route.methods = methods.map((m) => m.toUpperCase());

            this.stacks.push(route);
        });
        return this;
    }

    /**
     * parse params from route
     *
     * @param  {[Object]} paramNames
     * @param  {[String]} captures
     * @return {[Object]}
     * @api private
     */
    parseParams(params, paramNames, captures) {
        const len = captures.length;
        params = params || {};

        for (let i = 0; i < len; i++) {
            if (paramNames[i]) {
                let c = captures[i];
                params[paramNames[i].name] = c ? decodeURIComponent(c) : c;
            }
        }
        return params;
    }
}

/**
 * Add http methods
 *
 * @param  {String}  path
 * @return {[Functions]...}  middleware
 */
methods.forEach(method => {
    Koa66.prototype[method] = function() {
        const args = Array.prototype.slice.call(arguments);

        if (typeof args[0] !== 'string')
            args.unshift('/');

        args.unshift([method]);
        return this.register.apply(this, args);
    };
});

module.exports = Koa66;


text:
namespace OCIO_NAMESPACE
{

void GetRangeGPUShaderProgram(GpuShaderCreatorRcPtr & shaderCreator, ConstRangeOpDataRcPtr & range);

} // namespace OCIO_NAMESPACE

#endif


text:
package org.jasig.portlet.calendar.adapter;

import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.component.VEvent;
import org.jasig.portlet.calendar.mvc.CalendarDisplayEvent;
import org.jasig.portlet.calendar.processor.ICalendarContentProcessorImpl;
import org.jasig.portlet.calendar.processor.IContentProcessor;
import org.joda.time.DateMidnight;
import org.joda.time.DateTimeZone;
import org.joda.time.Interval;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.core.io.Resource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/testContext.xml")
public class CalendarEventsDaoIntegrationTest {

  CalendarEventsDao eventsDao;
  IContentProcessor<Calendar> processor;
  Resource calendarFile;

  @Autowired(required = true)
  ApplicationContext context;

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);

    eventsDao = new CalendarEventsDao();
    eventsDao.setMessageSource((MessageSource) context.getBean("messageSource"));
    processor = new ICalendarContentProcessorImpl();
    calendarFile = context.getResource("classpath:sampleEvents.ics");
  }

  @Test
  public void testGetEvents() throws IOException, URISyntaxException, ParseException {

    DateTimeZone tz = DateTimeZone.forID("America/Los_Angeles");
    DateMidnight start = new DateMidnight(2012, 7, 3, tz);
    Interval interval = new Interval(start, start.plusDays(7));

    Calendar c = processor.getIntermediateCalendar(interval, calendarFile.getInputStream());
    Set<VEvent> events = processor.getEvents(interval, c);

    assertEquals(2, events.size());

    List<CalendarDisplayEvent> displayEvents = new ArrayList<CalendarDisplayEvent>();

    for (VEvent event : events) {
      displayEvents.addAll(eventsDao.getDisplayEvents(event, interval, Locale.US, tz));
    }
    Collections.sort(displayEvents);

    CalendarDisplayEvent event = displayEvents.get(0);
    assertEquals("12:00 AM", event.getStartTime());

    event = displayEvents.get(1);
    assertEquals(9, event.getDayStart().getHourOfDay());
  }

  @Test
  public void testGetEventsAlternateTimezone()
      throws IOException, URISyntaxException, ParseException {

    DateTimeZone tz = DateTimeZone.forID("America/Chicago");
    DateMidnight start = new DateMidnight(2012, 7, 3, tz);
    Interval interval = new Interval(start, start.plusDays(7));

    Calendar c = processor.getIntermediateCalendar(interval, calendarFile.getInputStream());
    Set<VEvent> events = processor.getEvents(interval, c);

    assertEquals(2, events.size());

    List<CalendarDisplayEvent> displayEvents = new ArrayList<CalendarDisplayEvent>();

    for (VEvent event : events) {
      displayEvents.addAll(eventsDao.getDisplayEvents(event, interval, Locale.US, tz));
    }
    Collections.sort(displayEvents);

    CalendarDisplayEvent event = displayEvents.get(0);
    assertEquals(0, event.getDayStart().getHourOfDay());

    event = displayEvents.get(1);
    assertEquals(11, event.getDayStart().getHourOfDay());
  }

  @Test
  public void testGetArizonaEvent() throws IOException, URISyntaxException, ParseException {

    DateTimeZone tz = DateTimeZone.forID("America/Los_Angeles");
    DateMidnight start = new DateMidnight(2013, 2, 3, tz);
    Interval interval = new Interval(start, start.plusDays(7));

    Calendar c = processor.getIntermediateCalendar(interval, calendarFile.getInputStream());
    Set<VEvent> events = processor.getEvents(interval, c);

    assertEquals(1, events.size());

    List<CalendarDisplayEvent> displayEvents = new ArrayList<CalendarDisplayEvent>();

    for (VEvent event : events) {
      displayEvents.addAll(eventsDao.getDisplayEvents(event, interval, Locale.US, tz));
    }
    Collections.sort(displayEvents);

    CalendarDisplayEvent event = displayEvents.get(0);
    assertEquals("9:00 AM", event.getStartTime());
  }

  @Test
  public void testGetUTCEvent() throws IOException, URISyntaxException, ParseException {

    DateTimeZone tz = DateTimeZone.forID("America/Los_Angeles");
    DateMidnight start = new DateMidnight(2013, 1, 3, tz);
    Interval interval = new Interval(start, start.plusDays(7));

    Calendar c = processor.getIntermediateCalendar(interval, calendarFile.getInputStream());
    Set<VEvent> events = processor.getEvents(interval, c);

    assertEquals(1, events.size());

    List<CalendarDisplayEvent> displayEvents = new ArrayList<CalendarDisplayEvent>();

    for (VEvent event : events) {
      displayEvents.addAll(eventsDao.getDisplayEvents(event, interval, Locale.US, tz));
    }
    Collections.sort(displayEvents);

    CalendarDisplayEvent event = displayEvents.get(0);
    assertEquals("2:00 PM", event.getStartTime());
  }

  @Test
  public void testGetBedeworkEvent() throws IOException, URISyntaxException, ParseException {

    DateTimeZone tz = DateTimeZone.forID("America/Phoenix");
    DateMidnight start = new DateMidnight(2014, 2, 2, tz);
    Interval interval = new Interval(start, start.plusDays(1));

    Calendar c = processor.getIntermediateCalendar(interval, calendarFile.getInputStream());
    Set<VEvent> events = processor.getEvents(interval, c);

    assertEquals(1, events.size());

    List<CalendarDisplayEvent> displayEvents = new ArrayList<CalendarDisplayEvent>();

    for (VEvent event : events) {
      displayEvents.addAll(eventsDao.getDisplayEvents(event, interval, Locale.US, tz));
    }
    Collections.sort(displayEvents);

    CalendarDisplayEvent event = displayEvents.get(0);
    assertEquals("2:00 PM", event.getStartTime());
  }
}


text:
package com.kalabron.redpoppy.handlers;

import java.util.Random;

import com.kalabron.redpoppy.items.ModItems;

import net.minecraft.entity.monster.EntityPigZombie;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

public class PigZombieDropsRuggedLeather
{
	@SubscribeEvent
	public void dropBloodyScraps(LivingDeathEvent event)
	{
		if (!(event.entity instanceof EntityPigZombie))
		{
			return;
		}

		Random random = new Random();

		if (!event.entity.worldObj.isRemote)
		{
			event.entity.dropItem(ModItems.ruggedLeather, random.nextInt(3));
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<eu.kanade.tachiyomi.ui.reader.viewer.pager.PageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal"
        android:id="@+id/progress_container"
        android:orientation="vertical">

        <ProgressBar
            android:id="@+id/progress"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:id="@+id/progress_text"
            android:layout_gravity="center"
            android:visibility="invisible"
            android:textSize="16sp" />

    </LinearLayout>

    <include layout="@layout/chapter_image"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/retry_button"
        android:text="@string/action_retry"
        android:layout_gravity="center"
        android:visibility="gone"/>

</eu.kanade.tachiyomi.ui.reader.viewer.pager.PageView>