text:
/******************************************************************************
 *
 * Module Name: evregion - Operation Region support
 *
 *****************************************************************************/

/******************************************************************************
 *
 * 1. Copyright Notice
 *
 * Some or all of this work - Copyright (c) 1999 - 2013, Intel Corp.
 * All rights reserved.
 *
 * 2. License
 *
 * 2.1. This is your license from Intel Corp. under its intellectual property
 * rights. You may have additional license terms from the party that provided
 * you this software, covering your right to use that party's intellectual
 * property rights.
 *
 * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
 * copy of the source code appearing in this file ("Covered Code") an
 * irrevocable, perpetual, worldwide license under Intel's copyrights in the
 * base code distributed originally by Intel ("Original Intel Code") to copy,
 * make derivatives, distribute, use and display any portion of the Covered
 * Code in any form, with the right to sublicense such rights; and
 *
 * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
 * license (with the right to sublicense), under only those claims of Intel
 * patents that are infringed by the Original Intel Code, to make, use, sell,
 * offer to sell, and import the Covered Code and derivative works thereof
 * solely to the minimum extent necessary to exercise the above copyright
 * license, and in no event shall the patent license extend to any additions
 * to or modifications of the Original Intel Code. No other license or right
 * is granted directly or by implication, estoppel or otherwise;
 *
 * The above copyright and patent license is granted only if the following
 * conditions are met:
 *
 * 3. Conditions
 *
 * 3.1. Redistribution of Source with Rights to Further Distribute Source.
 * Redistribution of source code of any substantial portion of the Covered
 * Code or modification with rights to further distribute source must include
 * the above Copyright Notice, the above License, this list of Conditions,
 * and the following Disclaimer and Export Compliance provision. In addition,
 * Licensee must cause all Covered Code to which Licensee contributes to
 * contain a file documenting the changes Licensee made to create that Covered
 * Code and the date of any change. Licensee must include in that file the
 * documentation of any changes made by any predecessor Licensee. Licensee
 * must include a prominent statement that the modification is derived,
 * directly or indirectly, from Original Intel Code.
 *
 * 3.2. Redistribution of Source with no Rights to Further Distribute Source.
 * Redistribution of source code of any substantial portion of the Covered
 * Code or modification without rights to further distribute source must
 * include the following Disclaimer and Export Compliance provision in the
 * documentation and/or other materials provided with distribution. In
 * addition, Licensee may not authorize further sublicense of source of any
 * portion of the Covered Code, and must include terms to the effect that the
 * license from Licensee to its licensee is limited to the intellectual
 * property embodied in the software Licensee provides to its licensee, and
 * not to intellectual property embodied in modifications its licensee may
 * make.
 *
 * 3.3. Redistribution of Executable. Redistribution in executable form of any
 * substantial portion of the Covered Code or modification must reproduce the
 * above Copyright Notice, and the following Disclaimer and Export Compliance
 * provision in the documentation and/or other materials provided with the
 * distribution.
 *
 * 3.4. Intel retains all right, title, and interest in and to the Original
 * Intel Code.
 *
 * 3.5. Neither the name Intel nor any other trademark owned or controlled by
 * Intel shall be used in advertising or otherwise to promote the sale, use or
 * other dealings in products derived from or relating to the Covered Code
 * without prior written authorization from Intel.
 *
 * 4. Disclaimer and Export Compliance
 *
 * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
 * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
 * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE,
 * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY
 * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY
 * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
 * PARTICULAR PURPOSE.
 *
 * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
 * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
 * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
 * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
 * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
 * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS
 * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
 * LIMITED REMEDY.
 *
 * 4.3. Licensee shall not export, either directly or indirectly, any of this
 * software or system incorporating such software without first obtaining any
 * required license or other approval from the U. S. Department of Commerce or
 * any other agency or department of the United States Government. In the
 * event Licensee exports any such software from the United States or
 * re-exports any such software from a foreign destination, Licensee shall
 * ensure that the distribution and export/re-export of the software is in
 * compliance with all laws, regulations, orders, or other restrictions of the
 * U.S. Export Administration Regulations. Licensee agrees that neither it nor
 * any of its subsidiaries will export/re-export any technical data, process,
 * software, or service, directly or indirectly, to any country for which the
 * United States government or any agency thereof requires an export license,
 * other governmental approval, or letter of assurance, without first obtaining
 * such license, approval or letter.
 *
 *****************************************************************************/

#define __EVREGION_C__

#include "acpi.h"
#include "accommon.h"
#include "acevents.h"
#include "acnamesp.h"
#include "acinterp.h"

#define _COMPONENT          ACPI_EVENTS
        ACPI_MODULE_NAME    ("evregion")

extern UINT8        AcpiGbl_DefaultAddressSpaces[];

/* Local prototypes */

static void
AcpiEvOrphanEcRegMethod (
    ACPI_NAMESPACE_NODE     *EcDeviceNode);

static ACPI_STATUS
AcpiEvRegRun (
    ACPI_HANDLE             ObjHandle,
    UINT32                  Level,
    void                    *Context,
    void                    **ReturnValue);

/*******************************************************************************
 *
 * FUNCTION:    AcpiEvInitializeOpRegions
 *
 * PARAMETERS:  None
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Execute _REG methods for all Operation Regions that have
 *              an installed default region handler.
 *
 ******************************************************************************/

ACPI_STATUS
AcpiEvInitializeOpRegions (
    void)
{
    ACPI_STATUS             Status;
    UINT32                  i;

    ACPI_FUNCTION_TRACE (EvInitializeOpRegions);

    Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE);
    if (ACPI_FAILURE (Status))
    {
        return_ACPI_STATUS (Status);
    }

    /* Run the _REG methods for OpRegions in each default address space */

    for (i = 0; i < ACPI_NUM_DEFAULT_SPACES; i++)
    {
        /*
         * Make sure the installed handler is the DEFAULT handler. If not the
         * default, the _REG methods will have already been run (when the
         * handler was installed)
         */
        if (AcpiEvHasDefaultHandler (AcpiGbl_RootNode,
               AcpiGbl_DefaultAddressSpaces[i]))
        {
            Status = AcpiEvExecuteRegMethods (AcpiGbl_RootNode,
                        AcpiGbl_DefaultAddressSpaces[i]);
        }
    }

    AcpiGbl_RegMethodsExecuted = TRUE;

    (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE);
    return_ACPI_STATUS (Status);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiEvAddressSpaceDispatch
 *
 * PARAMETERS:  RegionObj           - Internal region object
 *              FieldObj            - Corresponding field. Can be NULL.
 *              Function            - Read or Write operation
 *              RegionOffset        - Where in the region to read or write
 *              BitWidth            - Field width in bits (8, 16, 32, or 64)
 *              Value               - Pointer to in or out value, must be
 *                                    a full 64-bit integer
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Dispatch an address space or operation region access to
 *              a previously installed handler.
 *
 ******************************************************************************/

ACPI_STATUS
AcpiEvAddressSpaceDispatch (
    ACPI_OPERAND_OBJECT     *RegionObj,
    ACPI_OPERAND_OBJECT     *FieldObj,
    UINT32                  Function,
    UINT32                  RegionOffset,
    UINT32                  BitWidth,
    UINT64                  *Value)
{
    ACPI_STATUS             Status;
    ACPI_ADR_SPACE_HANDLER  Handler;
    ACPI_ADR_SPACE_SETUP    RegionSetup;
    ACPI_OPERAND_OBJECT     *HandlerDesc;
    ACPI_OPERAND_OBJECT     *RegionObj2;
    void                    *RegionContext = NULL;
    ACPI_CONNECTION_INFO    *Context;

    ACPI_FUNCTION_TRACE (EvAddressSpaceDispatch);

    RegionObj2 = AcpiNsGetSecondaryObject (RegionObj);
    if (!RegionObj2)
    {
        return_ACPI_STATUS (AE_NOT_EXIST);
    }

    /* Ensure that there is a handler associated with this region */

    HandlerDesc = RegionObj->Region.Handler;
    if (!HandlerDesc)
    {
        ACPI_ERROR ((AE_INFO,
            "No handler for Region [%4.4s] (%p) [%s]",
            AcpiUtGetNodeName (RegionObj->Region.Node),
            RegionObj, AcpiUtGetRegionName (RegionObj->Region.SpaceId)));

        return_ACPI_STATUS (AE_NOT_EXIST);
    }

    Context = HandlerDesc->AddressSpace.Context;

    /*
     * It may be the case that the region has never been initialized.
     * Some types of regions require special init code
     */
    if (!(RegionObj->Region.Flags & AOPOBJ_SETUP_COMPLETE))
    {
        /* This region has not been initialized yet, do it */

        RegionSetup = HandlerDesc->AddressSpace.Setup;
        if (!RegionSetup)
        {
            /* No initialization routine, exit with error */

            ACPI_ERROR ((AE_INFO,
                "No init routine for region(%p) [%s]",
                RegionObj, AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
            return_ACPI_STATUS (AE_NOT_EXIST);
        }

        /*
         * We must exit the interpreter because the region setup will
         * potentially execute control methods (for example, the _REG method
         * for this region)
         */
        AcpiExExitInterpreter ();

        Status = RegionSetup (RegionObj, ACPI_REGION_ACTIVATE,
                    Context, &RegionContext);

        /* Re-enter the interpreter */

        AcpiExEnterInterpreter ();

        /* Check for failure of the Region Setup */

        if (ACPI_FAILURE (Status))
        {
            ACPI_EXCEPTION ((AE_INFO, Status,
                "During region initialization: [%s]",
                AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
            return_ACPI_STATUS (Status);
        }

        /* Region initialization may have been completed by RegionSetup */

        if (!(RegionObj->Region.Flags & AOPOBJ_SETUP_COMPLETE))
        {
            RegionObj->Region.Flags |= AOPOBJ_SETUP_COMPLETE;

            /*
             * Save the returned context for use in all accesses to
             * the handler for this particular region
             */
            if (!(RegionObj2->Extra.RegionContext))
            {
                RegionObj2->Extra.RegionContext = RegionContext;
            }
        }
    }

    /* We have everything we need, we can invoke the address space handler */

    Handler = HandlerDesc->AddressSpace.Handler;

    ACPI_DEBUG_PRINT ((ACPI_DB_OPREGION,
        "Handler %p (@%p) Address %8.8X%8.8X [%s]\n",
        &RegionObj->Region.Handler->AddressSpace, Handler,
        ACPI_FORMAT_NATIVE_UINT (RegionObj->Region.Address + RegionOffset),
        AcpiUtGetRegionName (RegionObj->Region.SpaceId)));

    /*
     * Special handling for GenericSerialBus and GeneralPurposeIo:
     * There are three extra parameters that must be passed to the
     * handler via the context:
     *   1) Connection buffer, a resource template from Connection() op.
     *   2) Length of the above buffer.
     *   3) Actual access length from the AccessAs() op.
     */
    if (((RegionObj->Region.SpaceId == ACPI_ADR_SPACE_GSBUS) ||
            (RegionObj->Region.SpaceId == ACPI_ADR_SPACE_GPIO)) &&
        Context &&
        FieldObj)
    {
        /* Get the Connection (ResourceTemplate) buffer */

        Context->Connection = FieldObj->Field.ResourceBuffer;
        Context->Length = FieldObj->Field.ResourceLength;
        Context->AccessLength = FieldObj->Field.AccessLength;
    }

    if (!(HandlerDesc->AddressSpace.HandlerFlags &
            ACPI_ADDR_HANDLER_DEFAULT_INSTALLED))
    {
        /*
         * For handlers other than the default (supplied) handlers, we must
         * exit the interpreter because the handler *might* block -- we don't
         * know what it will do, so we can't hold the lock on the intepreter.
         */
        AcpiExExitInterpreter();
    }

    /* Call the handler */

    Status = Handler (Function,
        (RegionObj->Region.Address + RegionOffset), BitWidth, Value,
        Context, RegionObj2->Extra.RegionContext);

    if (ACPI_FAILURE (Status))
    {
        ACPI_EXCEPTION ((AE_INFO, Status, "Returned by Handler for [%s]",
            AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
    }

    if (!(HandlerDesc->AddressSpace.HandlerFlags &
            ACPI_ADDR_HANDLER_DEFAULT_INSTALLED))
    {
        /*
         * We just returned from a non-default handler, we must re-enter the
         * interpreter
         */
       AcpiExEnterInterpreter ();
    }

    return_ACPI_STATUS (Status);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiEvDetachRegion
 *
 * PARAMETERS:  RegionObj           - Region Object
 *              AcpiNsIsLocked      - Namespace Region Already Locked?
 *
 * RETURN:      None
 *
 * DESCRIPTION: Break the association between the handler and the region
 *              this is a two way association.
 *
 ******************************************************************************/

void
AcpiEvDetachRegion(
    ACPI_OPERAND_OBJECT     *RegionObj,
    BOOLEAN                 AcpiNsIsLocked)
{
    ACPI_OPERAND_OBJECT     *HandlerObj;
    ACPI_OPERAND_OBJECT     *ObjDesc;
    ACPI_OPERAND_OBJECT     **LastObjPtr;
    ACPI_ADR_SPACE_SETUP    RegionSetup;
    void                    **RegionContext;
    ACPI_OPERAND_OBJECT     *RegionObj2;
    ACPI_STATUS             Status;

    ACPI_FUNCTION_TRACE (EvDetachRegion);

    RegionObj2 = AcpiNsGetSecondaryObject (RegionObj);
    if (!RegionObj2)
    {
        return_VOID;
    }
    RegionContext = &RegionObj2->Extra.RegionContext;

    /* Get the address handler from the region object */

    HandlerObj = RegionObj->Region.Handler;
    if (!HandlerObj)
    {
        /* This region has no handler, all done */

        return_VOID;
    }

    /* Find this region in the handler's list */

    ObjDesc = HandlerObj->AddressSpace.RegionList;
    LastObjPtr = &HandlerObj->AddressSpace.RegionList;

    while (ObjDesc)
    {
        /* Is this the correct Region? */

        if (ObjDesc == RegionObj)
        {
            ACPI_DEBUG_PRINT ((ACPI_DB_OPREGION,
                "Removing Region %p from address handler %p\n",
                RegionObj, HandlerObj));

            /* This is it, remove it from the handler's list */

            *LastObjPtr = ObjDesc->Region.Next;
            ObjDesc->Region.Next = NULL;        /* Must clear field */

            if (AcpiNsIsLocked)
            {
                Status = AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE);
                if (ACPI_FAILURE (Status))
                {
                    return_VOID;
                }
            }

            /* Now stop region accesses by executing the _REG method */

            Status = AcpiEvExecuteRegMethod (RegionObj, ACPI_REG_DISCONNECT);
            if (ACPI_FAILURE (Status))
            {
                ACPI_EXCEPTION ((AE_INFO, Status, "from region _REG, [%s]",
                    AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
            }

            if (AcpiNsIsLocked)
            {
                Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE);
                if (ACPI_FAILURE (Status))
                {
                    return_VOID;
                }
            }

            /*
             * If the region has been activated, call the setup handler with
             * the deactivate notification
             */
            if (RegionObj->Region.Flags & AOPOBJ_SETUP_COMPLETE)
            {
                RegionSetup = HandlerObj->AddressSpace.Setup;
                Status = RegionSetup (RegionObj, ACPI_REGION_DEACTIVATE,
                    HandlerObj->AddressSpace.Context, RegionContext);

                /*
                 * RegionContext should have been released by the deactivate
                 * operation. We don't need access to it anymore here.
                 */
                if (RegionContext)
                {
                    *RegionContext = NULL;
                }

                /* Init routine may fail, Just ignore errors */

                if (ACPI_FAILURE (Status))
                {
                    ACPI_EXCEPTION ((AE_INFO, Status,
                        "from region handler - deactivate, [%s]",
                        AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
                }

                RegionObj->Region.Flags &= ~(AOPOBJ_SETUP_COMPLETE);
            }

            /*
             * Remove handler reference in the region
             *
             * NOTE: this doesn't mean that the region goes away, the region
             * is just inaccessible as indicated to the _REG method
             *
             * If the region is on the handler's list, this must be the
             * region's handler
             */
            RegionObj->Region.Handler = NULL;
            AcpiUtRemoveReference (HandlerObj);

            return_VOID;
        }

        /* Walk the linked list of handlers */

        LastObjPtr = &ObjDesc->Region.Next;
        ObjDesc = ObjDesc->Region.Next;
    }

    /* If we get here, the region was not in the handler's region list */

    ACPI_DEBUG_PRINT ((ACPI_DB_OPREGION,
        "Cannot remove region %p from address handler %p\n",
        RegionObj, HandlerObj));

    return_VOID;
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiEvAttachRegion
 *
 * PARAMETERS:  HandlerObj          - Handler Object
 *              RegionObj           - Region Object
 *              AcpiNsIsLocked      - Namespace Region Already Locked?
 *
 * RETURN:      None
 *
 * DESCRIPTION: Create the association between the handler and the region
 *              this is a two way association.
 *
 ******************************************************************************/

ACPI_STATUS
AcpiEvAttachRegion (
    ACPI_OPERAND_OBJECT     *HandlerObj,
    ACPI_OPERAND_OBJECT     *RegionObj,
    BOOLEAN                 AcpiNsIsLocked)
{

    ACPI_FUNCTION_TRACE (EvAttachRegion);

    ACPI_DEBUG_PRINT ((ACPI_DB_OPREGION,
        "Adding Region [%4.4s] %p to address handler %p [%s]\n",
        AcpiUtGetNodeName (RegionObj->Region.Node),
        RegionObj, HandlerObj,
        AcpiUtGetRegionName (RegionObj->Region.SpaceId)));

    /* Link this region to the front of the handler's list */

    RegionObj->Region.Next = HandlerObj->AddressSpace.RegionList;
    HandlerObj->AddressSpace.RegionList = RegionObj;

    /* Install the region's handler */

    if (RegionObj->Region.Handler)
    {
        return_ACPI_STATUS (AE_ALREADY_EXISTS);
    }

    RegionObj->Region.Handler = HandlerObj;
    AcpiUtAddReference (HandlerObj);

    return_ACPI_STATUS (AE_OK);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiEvExecuteRegMethod
 *
 * PARAMETERS:  RegionObj           - Region object
 *              Function            - Passed to _REG: On (1) or Off (0)
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Execute _REG method for a region
 *
 ******************************************************************************/

ACPI_STATUS
AcpiEvExecuteRegMethod (
    ACPI_OPERAND_OBJECT     *RegionObj,
    UINT32                  Function)
{
    ACPI_EVALUATE_INFO      *Info;
    ACPI_OPERAND_OBJECT     *Args[3];
    ACPI_OPERAND_OBJECT     *RegionObj2;
    ACPI_STATUS             Status;

    ACPI_FUNCTION_TRACE (EvExecuteRegMethod);

    RegionObj2 = AcpiNsGetSecondaryObject (RegionObj);
    if (!RegionObj2)
    {
        return_ACPI_STATUS (AE_NOT_EXIST);
    }

    if (RegionObj2->Extra.Method_REG == NULL)
    {
        return_ACPI_STATUS (AE_OK);
    }

    /* Allocate and initialize the evaluation information block */

    Info = ACPI_ALLOCATE_ZEROED (sizeof (ACPI_EVALUATE_INFO));
    if (!Info)
    {
        return_ACPI_STATUS (AE_NO_MEMORY);
    }

    Info->PrefixNode = RegionObj2->Extra.Method_REG;
    Info->RelativePathname = NULL;
    Info->Parameters = Args;
    Info->Flags = ACPI_IGNORE_RETURN_VALUE;

    /*
     * The _REG method has two arguments:
     *
     * Arg0 - Integer:
     *  Operation region space ID Same value as RegionObj->Region.SpaceId
     *
     * Arg1 - Integer:
     *  connection status 1 for connecting the handler, 0 for disconnecting
     *  the handler (Passed as a parameter)
     */
    Args[0] = AcpiUtCreateIntegerObject ((UINT64) RegionObj->Region.SpaceId);
    if (!Args[0])
    {
        Status = AE_NO_MEMORY;
        goto Cleanup1;
    }

    Args[1] = AcpiUtCreateIntegerObject ((UINT64) Function);
    if (!Args[1])
    {
        Status = AE_NO_MEMORY;
        goto Cleanup2;
    }

    Args[2] = NULL; /* Terminate list */

    /* Execute the method, no return value */

    ACPI_DEBUG_EXEC (
        AcpiUtDisplayInitPathname (ACPI_TYPE_METHOD, Info->PrefixNode, NULL));

    Status = AcpiNsEvaluate (Info);
    AcpiUtRemoveReference (Args[1]);

Cleanup2:
    AcpiUtRemoveReference (Args[0]);

Cleanup1:
    ACPI_FREE (Info);
    return_ACPI_STATUS (Status);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiEvExecuteRegMethods
 *
 * PARAMETERS:  Node            - Namespace node for the device
 *              SpaceId         - The address space ID
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Run all _REG methods for the input Space ID;
 *              Note: assumes namespace is locked, or system init time.
 *
 ******************************************************************************/

ACPI_STATUS
AcpiEvExecuteRegMethods (
    ACPI_NAMESPACE_NODE     *Node,
    ACPI_ADR_SPACE_TYPE     SpaceId)
{
    ACPI_STATUS             Status;

    ACPI_FUNCTION_TRACE (EvExecuteRegMethods);

    /*
     * Run all _REG methods for all Operation Regions for this space ID. This
     * is a separate walk in order to handle any interdependencies between
     * regions and _REG methods. (i.e. handlers must be installed for all
     * regions of this Space ID before we can run any _REG methods)
     */
    Status = AcpiNsWalkNamespace (ACPI_TYPE_ANY, Node, ACPI_UINT32_MAX,
                ACPI_NS_WALK_UNLOCK, AcpiEvRegRun, NULL,
                &SpaceId, NULL);

    /* Special case for EC: handle "orphan" _REG methods with no region */

    if (SpaceId == ACPI_ADR_SPACE_EC)
    {
        AcpiEvOrphanEcRegMethod (Node);
    }

    return_ACPI_STATUS (Status);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiEvRegRun
 *
 * PARAMETERS:  WalkNamespace callback
 *
 * DESCRIPTION: Run _REG method for region objects of the requested spaceID
 *
 ******************************************************************************/

static ACPI_STATUS
AcpiEvRegRun (
    ACPI_HANDLE             ObjHandle,
    UINT32                  Level,
    void                    *Context,
    void                    **ReturnValue)
{
    ACPI_OPERAND_OBJECT     *ObjDesc;
    ACPI_NAMESPACE_NODE     *Node;
    ACPI_ADR_SPACE_TYPE     SpaceId;
    ACPI_STATUS             Status;

    SpaceId = *ACPI_CAST_PTR (ACPI_ADR_SPACE_TYPE, Context);

    /* Convert and validate the device handle */

    Node = AcpiNsValidateHandle (ObjHandle);
    if (!Node)
    {
        return (AE_BAD_PARAMETER);
    }

    /*
     * We only care about regions.and objects that are allowed to have address
     * space handlers
     */
    if ((Node->Type != ACPI_TYPE_REGION) &&
        (Node != AcpiGbl_RootNode))
    {
        return (AE_OK);
    }

    /* Check for an existing internal object */

    ObjDesc = AcpiNsGetAttachedObject (Node);
    if (!ObjDesc)
    {
        /* No object, just exit */

        return (AE_OK);
    }

    /* Object is a Region */

    if (ObjDesc->Region.SpaceId != SpaceId)
    {
        /* This region is for a different address space, just ignore it */

        return (AE_OK);
    }

    Status = AcpiEvExecuteRegMethod (ObjDesc, ACPI_REG_CONNECT);
    return (Status);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiEvOrphanEcRegMethod
 *
 * PARAMETERS:  EcDeviceNode        - Namespace node for an EC device
 *
 * RETURN:      None
 *
 * DESCRIPTION: Execute an "orphan" _REG method that appears under the EC
 *              device. This is a _REG method that has no corresponding region
 *              within the EC device scope. The orphan _REG method appears to
 *              have been enabled by the description of the ECDT in the ACPI
 *              specification: "The availability of the region space can be
 *              detected by providing a _REG method object underneath the
 *              Embedded Controller device."
 *
 *              To quickly access the EC device, we use the EcDeviceNode used
 *              during EC handler installation. Otherwise, we would need to
 *              perform a time consuming namespace walk, executing _HID
 *              methods to find the EC device.
 *
 *  MUTEX:      Assumes the namespace is locked
 *
 ******************************************************************************/

static void
AcpiEvOrphanEcRegMethod (
    ACPI_NAMESPACE_NODE     *EcDeviceNode)
{
    ACPI_HANDLE             RegMethod;
    ACPI_NAMESPACE_NODE     *NextNode;
    ACPI_STATUS             Status;
    ACPI_OBJECT_LIST        Args;
    ACPI_OBJECT             Objects[2];

    ACPI_FUNCTION_TRACE (EvOrphanEcRegMethod);

    if (!EcDeviceNode)
    {
        return_VOID;
    }

    /* Namespace is currently locked, must release */

    (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE);

    /* Get a handle to a _REG method immediately under the EC device */

    Status = AcpiGetHandle (EcDeviceNode, METHOD_NAME__REG, &RegMethod);
    if (ACPI_FAILURE (Status))
    {
        goto Exit; /* There is no _REG method present */
    }

    /*
     * Execute the _REG method only if there is no Operation Region in
     * this scope with the Embedded Controller space ID. Otherwise, it
     * will already have been executed. Note, this allows for Regions
     * with other space IDs to be present; but the code below will then
     * execute the _REG method with the EmbeddedControl SpaceID argument.
     */
    NextNode = AcpiNsGetNextNode (EcDeviceNode, NULL);
    while (NextNode)
    {
        if ((NextNode->Type == ACPI_TYPE_REGION) &&
            (NextNode->Object) &&
            (NextNode->Object->Region.SpaceId == ACPI_ADR_SPACE_EC))
        {
            goto Exit; /* Do not execute the _REG */
        }

        NextNode = AcpiNsGetNextNode (EcDeviceNode, NextNode);
    }

    /* Evaluate the _REG(EmbeddedControl,Connect) method */

    Args.Count = 2;
    Args.Pointer = Objects;
    Objects[0].Type = ACPI_TYPE_INTEGER;
    Objects[0].Integer.Value = ACPI_ADR_SPACE_EC;
    Objects[1].Type = ACPI_TYPE_INTEGER;
    Objects[1].Integer.Value = ACPI_REG_CONNECT;

    Status = AcpiEvaluateObject (RegMethod, NULL, &Args, NULL);

Exit:
    /* We ignore all errors from above, don't care */

    Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE);
    return_VOID;
}


text:
"""
   Copyright 2015 Creare

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
"""

import gdal
import gdalconst
import os
import numpy as np
import datetime

from traits.api import *
from my_types import GridCoordinates, InputRasterDataLayer, d_wkt_to_name

# I have to define UTC time myself.
ZERO = datetime.timedelta(0)
class UTC(datetime.tzinfo):
    def utcoffset(self, dt): return ZERO
    def tzname(self, dt): return "UTC"
    def dst(self, dt): return ZERO
utc = UTC()

class Reader(HasStrictTraits):
    pass

class DiskReader(Reader):

    file_types = List(Str)

    def update(self):
        """Forces input file to be read."""

    def read_file_into_simulation(self, file_name, simulation):
        """Loads data from file directly into a simulation object.

        Parameters
        ----------
        file_name: str
            Path to the file to load.
        simulation: dassp.Simulation
            Simulation into which the data should be read.

        Raises
        ------
        IOError:
            If file not found.
        RuntimeError:
            If the file cannot be loaded.

        .. note:: Overwrites any current input layers in simulation.
        """
        # Check for errors...
        self._read_file_into_simulation(file_name, simulation)

    def _read_file_into_simulation(self, file_name, simulation):
        """Override this with implementation."""
        raise NotImplementedError()

class GdalReader(DiskReader):
    file_types = ListStr([".grib", ".grib2", '.grb', '.gr1', '.tif', '.vrt',
        '.hgt', 'flt', 'adf', '.tiff'])
    acceptable_data_types = ListStr([])
    acceptable_depths = ListStr([])
    file_name = Str()
    _gdal_dataset = Instance(gdal.Dataset)
    grid_coordinates = Property(Array(), depends_on="_gdal_dataset")
    raster_layers = Property(List(Instance(InputRasterDataLayer)),
                      depends_on="_gdal_dataset")

    def summary(self):
        dataset = self._gdal_dataset
        summary_str = "Dataset:\n"
        summary_str += '\tDriver: ' + dataset.GetDriver().ShortName + '/' + \
          dataset.GetDriver().LongName + "\n"
        summary_str += '\tSize is ' + str(dataset.RasterXSize) + 'x' + str(dataset.RasterYSize) + \
              'x' + str(dataset.RasterCount) + "\n"
        summary_str += '\tProjection is ' + str(dataset.GetProjection()) + "\n"
        geotransform = dataset.GetGeoTransform()
        if not geotransform is None:
            summary_str += '\tOrigin = (' + str(geotransform[0]) + ' +' + str(geotransform[3]) + ')'
            summary_str += '\tPixel Size = (' + str(geotransform[1]) + ' +' + str(geotransform[5]) + ')'
        return summary_str

    def update(self):
        """Forces input file to be read."""
        _, _ = self._gdal_dataset, self.grid_coordinates

    def __gdal_dataset_default(self):
        """DiskReader implementation."""

        if not os.path.exists(self.file_name):
            return None
        if os.path.splitext(self.file_name)[1].lower() not in self.file_types:
            raise RuntimeError('Filename %s does not have extension type %s.' % (self.file_name, self.file_types))

        dataset = gdal.OpenShared(self.file_name, gdalconst.GA_ReadOnly)
        if dataset is None:
            raise ValueError('Dataset %s did not load properly.' % self.file_name)

        # Sanity checks.
        assert dataset.RasterCount > 0

        # Seems okay...
        return dataset

    @cached_property
    def _get_grid_coordinates(self):
        dataset = self._gdal_dataset
        geotransform = np.array(dataset.GetGeoTransform())
        assert len(geotransform) == 6
        x_size, y_size = dataset.RasterXSize, dataset.RasterYSize
        assert x_size > 0
        assert y_size > 0

        ds_time = ds_date = None

        wkt_ = dataset.GetProjection()
        wkt = d_wkt_to_name[wkt_]

        return GridCoordinates(x_size=x_size, y_size=y_size,
                               date=ds_date, time=ds_time,
                               geotransform=geotransform,
                               wkt=wkt)

    def _raster_layer_from_raster_band(self, raster_band, arr=None, grid_coordinates=None):
        layer = InputRasterDataLayer()
        if grid_coordinates:
            layer.grid_coordinates = grid_coordinates
        else:
            layer.grid_coordinates = self.grid_coordinates

        # Make sure this dataset doesn't include any features that
        # we're missing...
        # assert raster_band.GetCategoryNames() is None
        assert raster_band.GetColorInterpretation() in [0, 1, 2]  # Not sure what 1 or 2 means.
#        assert raster_band.GetColorTable() is None
#             assert np.count_nonzero(raster_band.GetMaskBand().ReadAsArray()
#                                         < 255) == 0
        assert raster_band.GetRasterCategoryNames() is None
        # assert raster_band.GetOverviewCount() == 0
        # assert raster_band.GetScale() == 1.0
        #assert raster_band.GetUnitType() == ''

        layer.units = ''

        # Read array data.
        if arr is None:
            arr = raster_band.ReadAsArray().copy()
            arr = np.ma.masked_array(arr, np.logical_not(raster_band.GetMaskBand().ReadAsArray()))
            # NAN's:
            # -9999 and 9999 are NaN's... if we eventually get masked data,
            # we'll want to take care of it here.
            if raster_band.GetNoDataValue() is None:
                for nan_value in [-9999, 9999, np.nan]:
                    try:
                        arr = np.ma.masked_equal(arr, nan_value)
                    except:
                        pass
        else:
            arr = np.ma.masked_invalid(arr)
#         if raster_band.GetNoDataValue() is not None:
#             arr = np.ma.masked_equal(arr, raster_band.GetNoDataValue())
        # Check size...
        assert arr.shape[0] == layer.grid_coordinates.y_size
        assert arr.shape[1] == layer.grid_coordinates.x_size

        # Prevent possible rounding errors
        if layer.is_enumerated:
            arr = np.round(arr)

        # It looks valid... assign the raster data to the layer.
        layer.raster_data = arr
        # print "Processed layer:"
        # layer.print_traits()
        return layer

    @cached_property
    def _get_raster_layers(self):
        raster_bands = [self._gdal_dataset.GetRasterBand(i)
                          for i in range(1, self._gdal_dataset.RasterCount + 1)]
        raster_layers = [self._raster_layer_from_raster_band(raster_band)
                         for raster_band in raster_bands]
        return raster_layers

redpajama_set_name: RedPajamaGithub


text:
from PyQt4.Qwt5 import QwtPlot, QwtDial
import PyQt4.Qt as Qt
import PyQt4.Qwt5 as Qwt

class BarCurve(Qwt.QwtPlotCurve):

    def __init__(self, penColor=Qt.Qt.black, brushColor=Qt.Qt.white):
        Qwt.QwtPlotCurve.__init__(self)
        self.penColor = penColor
        self.brushColor = brushColor

    # __init__()

    def drawFromTo(self, painter, xMap, yMap, start, stop):
        """Draws rectangles with the corners taken from the x- and y-arrays.
        """

        painter.setPen(Qt.QPen(self.penColor, 2))
        painter.setBrush(self.brushColor)
        if stop == -1:
            stop = self.dataSize()
        # force 'start' and 'stop' to be even and positive
        if start & 1:
            start -= 1
        if stop & 1:
            stop -= 1
        start = max(start, 0)
        stop = max(stop, 0)
        for i in range(start, stop, 2):
            px1 = xMap.transform(self.x(i))
            py1 = yMap.transform(self.y(i))
            px2 = xMap.transform(self.x(i+1))
            py2 = yMap.transform(self.y(i+1))
            painter.drawRect(px1, py1, (px2 - px1), (py2 - py1))


text:
package org.dnwiebe.orienteer.lookups;

/**
 * Created by dnwiebe on 2/17/17.
 */

/**
 * Looks up values in System.getProperties().  Method name abcDEFGhi becomes abc.def.ghi.
 */
public class SystemPropsLookup extends PropertiesLookup {

  public SystemPropsLookup () {
    super (System.getProperties ());
  }

  public SystemPropsLookup (String name) {
    super (name, System.getProperties ());
  }
}


text:
'use strict';

/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Category = mongoose.model('Category'),
_ = require('lodash');

/**
* Create a Category
*/
exports.create = function(req, res) {
  var category = new Category(req.body);
  category.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.status(201).json(category);
    }
  });
};

/**
* Show the current Category
*/
exports.read = function(req, res) {
  Category.findById(req.params.categoryId).exec(function(err, category) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      if (!category) {
        return res.status(404).send({
          message: 'Category not found'
        });
      }
      res.json(category);
    }
  });
};

/**
* Update a Category
*/
exports.update = function(req, res) {
  var category = req.category;

  category = _.extend(category, req.body);

  category.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(category);
    }
  });
};

/**
* Delete an Category
*/
exports.delete = function(req, res) {
  var category = req.category;

  	category.remove(function(err) {
  		if (err) {
  			return res.status(400).send({
  				message: errorHandler.getErrorMessage(err)
  			});
  		} else {
  			res.json(category);
  		}
  	});
};

/**
* List of Categories
*/
exports.list = function(req, res) {
  Category.find().exec(function(err, categories) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(categories);
    }
  });
};

/**
 * Category middleware
 */
exports.categoryByID = function(req, res, next, id) {

	if (!mongoose.Types.ObjectId.isValid(id)) {
		return res.status(400).send({
			message: 'Category is invalid'
		});
	}

	Category.findById(id).exec(function(err, category) {
		if (err) return next(err);
		if (!category) {
			return res.status(404).send({
  				message: 'Category not found'
  			});
		}
		req.category = category;
		next();
	});
};


text:
<?php
namespace Account\Entity;
use Doctrine\ORM\Mapping as ORM;
use Zend\Form\Annotation;

/**
* Account Entity with Business Logic
*
* An Account provides a payment plan. It calculates the payment total depending on some interest
* and Late Payment Fees if applicable. It has 2 states: Open and Close. An Account is open
* if payments are due. If all payments were done, the account is automatically "close". The account
* is always open until all payments have been submitted.
*
* An Account will create Payment Objects and is the only interface to create and destroy objects
* of type Payment from the database.
*
* The nPaid field keeps track of how many payments have been done so far. It should return the
* number of payments with status ONTIME and/or LATE
*
* Lastly, an account can only be destroyed if the status is closed. It will get destroyed via the Client
* interface only by the owner of the account. All Payments are destroyed with it.
*
* @ORM\Entity
* @Annotation\Name("Account")
* @Annotation\Hydrator({"type":"Zend\Stdlib\Hydrator\ClassMethods", "options": {"underscoreSeparatedKeys": false}})
*/
class Account {
    // ============================== Database Columns ============================== //
    /**
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    * @ORM\Column(type="integer")
    * @Annotation\Attributes({"type":"hidden"})
    * @Annotation\Options({"label":"Id:"})
    */
    protected $accountId;

    /**
    * @ORM\Column(type="date", nullable = false)
    * @Annotation\Attributes({"type":"datetime"})
    * @Annotation\Options({"label":"Needed by:"})
    * @Annotation\Filter({"name": "StringTrim"})
    */
    protected $requestDate;

    /**
    * @ORM\Column(type="date", nullable = false)
    * @Annotation\Attributes({"type":"datetime"})
    * @Annotation\Options({"label":"Payments Start:"})
    * @Annotation\Filter({"name": "StringTrim"})
    */
    protected $firstPayDate;

    /**
    * @ORM\Column(type="text", nullable = false)
    * @Annotation\Attributes({"type":"text"})
    * @Annotation\Options({"label":"Period:"})
    * @Annotation\Filter({"name": "StringTrim"})
    * @Annotation\Validator({"name":"NotEmpty"})
    * @Annotation\Validator({"name":"Regex", "options":{"pattern":"/^\weekly|daily$/"}})
    */
    protected $payPeriod;

    /**
    * @ORM\Column(type="string", nullable = false)
    * @Annotation\Attributes({"type":"text"})
    * @Annotation\Options({"label":"Amount:"})
    * @Annotation\Filter({"name": "StringTrim"})
    * @Annotation\Validator({"name":"NotEmpty"})
    * @Annotation\Validator({"name":"Regex", "options":{"pattern":"/^[1-9]+[0-9]*$/"}})
    */
    protected $amount;

    /**
     * @ORM\OneToMany(targetEntity="Payment\Entity\Payment", mappedBy="account")
     */
    protected $payments;

    /**
    * @ORM\Column(type="string", nullable = false)
    * @Annotation\Attributes({"type":"text"})
    * @Annotation\Options({"label":"number of Payments:"})
    * @Annotation\Filter({"name": "StringTrim"})
    * @Annotation\Validator({"name":"NotEmpty"})
    * @Annotation\Validator({"name":"Regex", "options":{"pattern":"/^[1-9][0-9]*$/"}})
    */
    protected $nPayments;

    /**
    * @ORM\ManyToOne(targetEntity="Client\Entity\Client", inversedBy="accounts")
    * @ORM\JoinColumn(name="myClientId", referencedColumnName="clientId")
    */
    protected $client;

    /**
    * @ORM\Column(type="string", nullable = false)
    * @Annotation\Attributes({"type":"text"})
    * @Annotation\Options({"label":"Number Paid:"})
    * @Annotation\Filter({"name": "StringTrim"})
    * @Annotation\Validator({"name":"NotEmpty"})
    * @Annotation\Validator({"name":"Regex", "options":{"pattern":"/^\d+$/"}})
    */
    protected $nPaid;

    /**
    * @ORM\Column(type="string", nullable = false)
    * @Annotation\Attributes({"type":"text"})
    * @Annotation\Options({"label":"Status:"})
    * @Annotation\Validator({"name":"Regex", "options":{"pattern":"/^\open|close|pending|deny$/"}})
    */
    protected $status;

    /**
    * @ORM\Column(type="datetime")
    * @Annotation\Attributes({"type":"hidden"})
    * @Annotation\Exclude()
    */
    protected $timeStamp;

    /**
    * @ORM\Column(type="string", nullable = false)
    * @Annotation\Attributes({"type":"text"})
    * @Annotation\Options({"label":"Interest (Annual):"})
    * @Annotation\Filter({"name": "StringTrim"})
    * @Annotation\Validator({"name":"NotEmpty"})
    * @Annotation\Validator({"name":"Regex", "options":{"pattern":"/^[1-9]+.[0-9]*$|^[0-9]+.[0-9]*$/"}})
    */
    protected $interest;

    // ------------------------------ Getters ------------------------------ //
    public function getAccountId() {
        return $this->accountId;
    }
    public function getRequestDate() {
        if ($this->requestDate == null) {
            return $this->requestDate;
        }
        return $this->requestDate->format('Y-m-d');
    }
    public function getFirstPayDate() {
        if ($this->firstPayDate == null) {
            return $this->firstPayDate;
        }
        return $this->firstPayDate->format('Y-m-d');
    }
    public function getPayPeriod() {
        return $this->payPeriod;
    }
    public function getAmount() {
        return $this->amount;
    }
    public function getPayments() {
        return $this->payments;
    }
    public function getNPayments() {
        return $this->nPayments;
    }
    public function getClient() {
        return $this->client;
    }
    public function getNPaid() {
        return $this->nPaid;
    }
    public function getStatus() {
        return $this->status;
    }
    public function getTimeStamp() {
        return $this->timeStamp;
    }
    public function getInterest() {
        return $this->interest;
    }
    // ------------------------------ Setters ------------------------------ //
    public function setRequestDate($rd) {
        $this->requestDate = $rd;
    }
    public function setFirstPayDate($fpd) {
        $this->firstPayDate = $fpd;
    }
    public function setPayPeriod($pp) {
        $this->payPeriod = $pp;
    }
    public function setAmount($newAmount) {
        $this->amount = $newAmount;
    }
    public function setPayments($p) {
        $this->payments = $p;
    }
    public function setNPayments($np) {
        $this->nPayments = $np;
    }
    public function setClient($c) {
        $this->client = $c;
    }
    public function setNPaid($np) {
        $this->nPaid = $np;
    }
    public function setStatus($s) {
        $this->status = $s;
    }
    public function setTimeStamp() {
        $this->timeStamp = new \DateTime("now");
    }
    public function setInterest($i) {
        $this->interest = $i;
    }

    // ============================== Business Logic ============================== //

    // ------------------------------ Constants ------------------------------ //

    //Status
    const OPEN = 'open';
    const CLOSE = 'close';
    const PENDING = 'pending';
    const DENY = 'deny';

    //Periods
    const WEEKLY = 'weekly';

    // ------------------------------ Static Properties ------------------------------ //
    private static $count;

    // ------------------------------ Static Methods ------------------------------ //
    public static function getCount() {
        return Account::$count;
    }
    public static function updateCount($objectManager) {
        Account::$count = count($objectManager->getRepository('Account\Entity\Account')->findAll());
    }

    /**
    * @param date $requestDate The expected requested date for an Account
    * @param date $firstPayDate The expected date for when to start making payments
    * @param form $form A reference to the form to which to submit error messages to
    * @return bool If both dates are valid return true, otherwise return false
    */
    public static function areDatesValid($requestDate, $firstPayDate, &$form) {
        $valid = true;
        if (\strtotime($requestDate) < \strtotime(\date("Y-m-d"))) {
            $form->get("requestDate")->setMessages(array("Invalid Date"));
            $valid = false;
        }
        if (\strtotime($firstPayDate) < \strtotime($requestDate)) {
            $form->get("firstPayDate")->setMessages(array("Invalid Date"));
            $valid = false;
        }
        return $valid;
    }

    // ------------------------------ Methods ------------------------------ //
    public function __construct() {
        $this->payments = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
    * It gets called in the addAction function from the controller.
    *
    * This function sets the defaults for a new account. nPaid is handled internally. The
    * Default status is OPEN and payments are generated here.
    *
    * @param Service $objectManager The Entity Manager
    */
    public function approve($objectManager) {
        $this->setStatus(Account::OPEN);
        $this->generatePayments($objectManager);
    }

    public function deny($objectManager) {
        $this->setStatus(Account::DENY);
    }

    public function initRequest() {
        $this->nPaid = "0";
        $this->setTimeStamp();
        $this->setStatus(Account::PENDING);
    }

    /**
    *
    * This function removes a close account from its client's list and all its respective
    * payment objects
    *
    * @param Service $objectManager The Entity Manager
    * @return bool True if all payments were paid with Status ONTIME or LATE and account is CLOSE, else false
    */
    public function initDelete($objectManager) {
        if ($this->removePayments($objectManager) && $this->getStatus == Client::CLOSE) {
            $this->getClient()->getAccounts()->remove($this);
            return true;
        }
        return false;
    }

    /**
    * Creates payments objects.
    *
    * It creates default payments for the newly created account. Should only be called once.
    * Checks if objects already exists and adds new ones if none are found. Defaults for payments
    * is Status due.
    *
    * @param Service $objectManager The Entity Manager
    */
    private function generatePayments($objectManager) {
        if ($this->getPayments()->count() == 0) {
            $paymentAmount = $this->calculatePaymentPerPeriod();
            for ($i = 0 ; $i < $this->getNPayments() ; $i++) {
                $payment = new \Payment\Entity\Payment;
                $payment->setAmount(number_format($paymentAmount, 2, '.', '') + "");
                $payment->setPaymentNumber($i + 1);
                $payment->setAccount($this);
                $payment->setStatus(\Payment\Entity\Payment::DUE);
                $payment->setTimeStamp();
                $payment->setDueDate($this->getFirstPayDateStr(null), $this->getPayPeriod());
                $objectManager->persist($payment);
                $this->getPayments()->add($payment);
            }
        }
    }

    /**
    * Removes payments objects.
    *
    * It removes payments objects from account. Double checks all payments were paid
    *
    * @param Service $objectManager The Entity Manager
    * @return bool True if all payments are ONTIME or LATE, False otherwise
    */
    private function removePayments($objectManager) {
        foreach($this->getPayments as $payment) {
            if ($payment->getStatus() != \Payment\Entity\Payment::ONTIME
                && $payment->getStatus() != \Payment\Entity\Payment::LATE) {
                return false;
            }
        }

        foreach($this->getPayments as $payment) {
            $objectManager->remove($payment);
        }

        return true;
    }

    /**
    * @return Payment|null It returns a Payment object with a due status, depending on its
    * nPayment number. If no more due payments are found, return null
    */
    public function getNextDuePayment() {
        for ($i = 0 ; $i < $this->nPayments ; $i++) {
            $payment = $this->payments[$i];
            if ($payment->getStatus() == \Payment\Entity\Payment::DUE) {
                return $payment;
            }
        }
        return null;
    }

    /**
    * Performs a Legal payment against the account. Marks the account as close if
    * no more payments are due. If account is close, it doesn't do anything
    *
    * @param Service $objectManager The entity Manager
    * @param Payment $payment The next due payment from Account
    */
    public function processNextDuePayment($objectManager, $payment) {
        if ($this->getStatus() != Account::CLOSE) {
            $this->setNPaid($payment->getPaymentNumber());
            if ($this->getNPaid() == $this->getNPayments()) {
                $this->setStatus(Account::CLOSE);
            }
            $payment->processPay();
            $objectManager->persist($payment);
            $objectManager->persist($this);
        }
    }

    /**
    * @param string|null $format If format is provided use it, otherwise, use default
    * @return string firstPayDate formatted to Y-m-d or given format
    */
    public function getFirstPayDateStr($format) {
        if ($format == null) {
            return $this->firstPayDate->format('Y-m-d');
        }
        return $this->firstPayDate->format($format);
    }

    /**
    * @param string|null $format If format is provided use it, otherwise, use default
    * @return string requestDate formatted to Y-m-d or given format
    */
    public function getRequestDateStr($format) {
        if ($format == null) {
            return $this->requestDate->format('Y-m-d');
        }
        return $this->requestDate->format($format);
    }

    /**
    * @return int[string] It returns the number of payments classified by Status
    */
    public  function getPaymentCounts() {
        $counts = array(
            \Payment\Entity\Payment::DUE => 0,
            \Payment\Entity\Payment::LATE => 0,
            \Payment\Entity\Payment::ONTIME => 0,
        );
        foreach ($this->getPayments() as $payment) {
            $counts[$payment->getStatus()] ++;
        }
        return $counts;
    }

    /**
    * @return mixed[string][] It returns an array of labels with dates and respective activities
    */
    public function getPaymentRecord() {
        $record = array(
            'labels' => array(),
            \Payment\Entity\Payment::DUE => array(),
            \Payment\Entity\Payment::LATE => array(),
            \Payment\Entity\Payment::ONTIME => array(),
            );
        foreach ($this->getPayments() as $payment) {
            if ($payment->getStatus() == \Payment\Entity\Payment::DUE) {
                array_push($record['labels'], $payment->getDueDateStr());
                array_push($record[\Payment\Entity\Payment::DUE], $payment->getAmount());
                array_push($record[\Payment\Entity\Payment::LATE], 0);
                array_push($record[\Payment\Entity\Payment::ONTIME], 0);
            } else {
                if ($payment->getStatus() == \Payment\Entity\Payment::ONTIME) {
                    array_push($record[\Payment\Entity\Payment::ONTIME], $payment->getAmount());
                    array_push($record[\Payment\Entity\Payment::LATE], 0);
                } else {
                    array_push($record[\Payment\Entity\Payment::LATE], $payment->getAmount());
                    array_push($record[\Payment\Entity\Payment::ONTIME], 0);
                }
                array_push($record['labels'], $payment->getPaidTimeStamp()->format('Y-m-d'));
                array_push($record[\Payment\Entity\Payment::DUE], 0);
            }
        }
        return $record;
    }

    public function calculatePaymentPerPeriod() {
        if ($this->getPayPeriod() == Account::WEEKLY) {
            $weeklyInterest = $this->getInterest()/52.0;
            $total = $this->getAmount() * pow(1 + $weeklyInterest, $this->getNPayments());
            return $total/$this->getNPayments();
        }
        return 100.0;
    }
}


text:
package com.pathfinder.backendless;

/**
 * Created by dzidzoiev on 2/29/16.
 */
public class Defaults {
    public static final String APPLICATION_ID = "*";
    public static final String SECRET_KEY = "*";
    public static final String VERSION = "*";
}


text:
/**
 * Created by Freddy on 11/03/15.
 */

(function() {

    //Add to Visionscapers namespace
    var NS          = window.__VI__ || window;

    var _           = NS.utils;
    var _l          = NS.logger;

    var Class       = window.jsface.Class;

    NS.ControllerProcessesState = Class({

        $statics : {
            REQUIRED_CONTROLLER_API : {
                methods : ['isValid', '_dispatchToModel', '_dispatchToView']
            }
        },

        _stateProcessingInitialized : false,

        /**
         *
         * ControllerProcessesState Mixin for Controller classes. Adds functionality to process, edit and sync
         * state in a standardized way.
         *
         * This mixin provides functionality to process the following model events
         *
         *  - dataStateUpdated
         *  - globalSyncStateUpdated
         *  - globalErrorStateUpdated
         *  - errorStateUpdated
         *  - globalValidityStateUpdated
         *  - validityStateUpdated
         *
         *  It also processes the following view events:
         *  - wantToEdit
         *  - wantToUpdateToRemote
         *  - wantToUpdateFromRemote
         *
         * **Processing model events**
         * By default, the event and data is forwarded to the connected view.
         * However, the class using this mixin can define custom methods to:
         *
         * A) Transform the event value, when required.  The value needs to be returned such that it
         *    can be forwarded to the view.
         * B) Send messages to the state manager, when required.
         * C) Evaluate if the the event (with (transformed) value) must be forwarded or not
         *
         * The default processing methods will try to call one of the following custom methods, depending on which
         * event they process:
         *
         * - _processDataState(model, property, value);
         *
         * - _processGlobalSyncState(model, value);
         *   value : <new global sync state value>
         *
         * - _processGlobalErrorState(model, value);
         *   value : <new global sync state value>
         *
         * - _processErrorState(model, property, value);
         * - _processGlobalValidityState(model, value);
         *
         * - _processValidityState(model, property, value);
         *
         * IMPORTANT : These custom methods must return the following object :
         * {
         *      success : <boolean, true when processing was successful, else false>,
         *      value   : <*, the input value, optionally transformed>,
         *      forward : <boolean, true when the event with value needs to be forwarded to the view, else false>
         * }
         *
         *
         * **Processing view events**
         * The class using this mixin can implement the following custom methods that are called when the view
         * events are received:
         *
         * [before processing]
         * - _onWantToEdit(property, value)
         * - _onWantToUpdateToRemote()
         * - _onWantToUpdateFromRemote()
         *
         * [after processing]
         * - _onUpdatedToRemote()
         * - _onUpdatedFromRemote()
         *
         * These methods are called before the view events are forwarded to the connected model.
         *
         * For convenience these events can called using the following public methods:
         *
         *  resetData()                                 reset all data in model
         *  edit(property, value, editProcessedCb)      edit local property value
         *  updateToRemote(updateReadyCb)               send local property values to server
         *                                              updateReadyCb(responseData, err)
         *
         *  updateFromRemote(updateReadyCb)             Get remote property values from server
         *                                              updateReadyCb(responseData, err)
         *
         *
         * @class   ControllerProcessesState
         * @module  M*C
         *
         * @for     Controller
         *
         */

        resetData : function(readyCb) {
            this._dispatchToModel("wantToResetModel", null, readyCb);
        },

        /**
         *
         * Edit data <property> by setting it to a new <value>
         *
         * @param property          property for which to edit a value
         * @param value             New value for property
         * @param editProcessedCb   function(result, err), callback called when the edit has been processed throughout
         *                          the whole MVC
         *
         */
        edit : function(property, value, editProcessedCb) {
            this._wantToEdit(
                    this,
                    {
                        what : property,
                        data : value
                    },
                    editProcessedCb);
        },

        /**
         *
         * Get remote property values from server based on some optional context
         *
         * @param {function} updateReadyCb     function(result, err), value of result depends on implementation
         *
         */
        updateFromRemote : function(updateReadyCb, context) {

            this._wantToUpdateFromRemote(
                    this,
                    context,
                    updateReadyCb);
        },

        /**
         *
         * @param updateToRemoteCb     function(result, err), value of result depends on implementation
         *
         */
        updateToRemote : function(updateToRemoteCb) {
            this._wantToUpdateToRemote(
                    this,
                    null,
                    updateToRemoteCb);
        },

        /*********************************************************************
         *
         * PROTECTED METHODS
         *
         *********************************************************************/

        _initStateProcessing : function() {
            var iName           = _.exec(this, 'getIName') || "[UNKOWN]";
            var me              = "{0}::ControllerProcessesState::_initStateProcessing";

            if (!_.interfaceAdheres(this, ControllerProcessesState.REQUIRED_CONTROLLER_API)) {
                _l.error(me, "Init state processing failed : this controller does not adhere to " +
                             "the required interface for this mixin");

                var api = ControllerProcessesState.REQUIRED_CONTROLLER_API;
                _l.info(me, "Required controller interface : ", _.stringify(api));

                return this._stateProcessingInitialized;
            }

            return (this._stateProcessingInitialized = true);
        },

        /********************************************************************
         *
         * MODEL EVENT HANDLERS
         *
         ********************************************************************/

        _dataStateUpdated : function(model, data, eventProcessedCb) {
            this._processModelEvent(
                    "_processDataState",
                    "dataStateUpdated",
                    false,
                    arguments);
        },

        _globalSyncStateUpdated : function(model, data, eventProcessedCb) {
            this._processModelEvent(
                    "_processGlobalSyncState",
                    "globalSyncStateUpdated",
                    true,
                    arguments);
        },

        _globalErrorStateUpdated : function(model, data, eventProcessedCb) {
            this._processModelEvent(
                    "_processGlobalErrorState",
                    "globalErrorStateUpdated",
                    true,
                    arguments);
        },

        _errorStateUpdated : function(model, data, eventProcessedCb) {
            this._processModelEvent(
                    "_processErrorState",
                    "errorStateUpdated",
                    false,
                    arguments);
        },

        _globalValidityStateUpdated : function(model, data, eventProcessedCb) {
            this._processModelEvent(
                    "_processGlobalValidityState",
                    "globalValidityStateUpdated",
                    true,
                    arguments);
        },

        _validityStateUpdated : function(model, data, eventProcessedCb) {
            this._processModelEvent(
                    "_processValidityState",
                    "validityStateUpdated",
                    false,
                    arguments);
        },

        /********************************************************************
         *
         * VIEW EVENT HANDLERS
         *
         ********************************************************************/

        _wantToEdit : function(origin, data, editProcessedCb) {
            var iName           = _.exec(this, 'getIName') || "[UNKOWN]";
            var me              = "{0}::ControllerProcessesState::_wantToEdit".fmt(iName);

            var callbackGiven   = _.func(editProcessedCb);

            var __returnError   = function(errStr) {
                callbackGiven ? editProcessedCb(null, { message : errStr }) :  _l.error(me, errStr);
            };

            if (!this._stateProcessingInitialized) {
                __returnError("State processing is not initialized (correctly), call _initStateProcessing() in " +
                              "your controller-constructor first");
                return;
            }

            if (this.isValid() === false) {
                __returnError("Controller is invalid, unable to edit property {0}".fmt(property));
                return;
            }

            var dataDesc        = 'Data of wantToEdit event';
            var property        = _.get(data, 'what', dataDesc);
            var newValue        = _.get(data, 'data', dataDesc);

            if (_.func(this._onWantToEdit)) {
                this._onWantToEdit(property, newValue);
            }

            if (!_.func(this._dispatchToModel)) {
                __returnError(("_dispatchToModel method missing : this is not a Controller class, " +
                               "unable to edit property {0}").fmt(property));
                return;
            }

            this._dispatchToModel(
                    "wantToEdit",
                    {
                        what : property,
                        data : newValue
                    },
                    editProcessedCb);
        },

        _wantToUpdateToRemote : function(origin, data, updateReadyCb) {
            var iName           = _.exec(this, 'getIName') || "[UNKOWN]";
            var me              = "{0}::ControllerProcessesState::_wantToUpdateToRemote".fmt(iName);
            var self            = this;

            var callbackGiven   = _.func(updateReadyCb);

            var __returnError   = function(err) {
                callbackGiven ? updateReadyCb(null, err) :  _l.error(me, "Error occurred : " + _.stringify(err));
            };

            if (!this._stateProcessingInitialized) {
                __returnError({
                    message : "State processing is not initialized (correctly), call _initStateProcessing() in " +
                              "your controller-constructor first"
                });
                return;
            }

            if (this.isValid() === false) {
                __returnError({
                    message : "Controller is invalid, unable to update to remote"
                });
                return;
            }

            if (_.func(this._onWantToUpdateToRemote)) {
                this._onWantToUpdateToRemote();
            }

            this._dispatchToModel(
                    "wantToUpdateToRemote",
                    data,
                    function(responseData, err) {
                        var onUpdatedToRemote = _.func(self._onUpdatedToRemote) ?
                            self._onUpdatedToRemote.bind(self) :
                            // Dummy function that calls callback immediately
                            function(respondsData, err, callback) {
                                callback();
                            };

                        onUpdatedToRemote(responseData, err, function(err) {
                            if (_.def(err)) {
                                __returnError(err);
                                return;
                            }

                            if (callbackGiven) { updateReadyCb(responseData); }
                        });
                    });
        },

        _wantToUpdateFromRemote : function(origin, data, updateReadyCb) {
            var iName           = _.exec(this, 'getIName') || "[UNKOWN]";
            var me              = "{0}::ControllerProcessesState::_wantToUpdateFromRemote".fmt(iName);
            var self            = this;

            var callbackGiven   = _.func(updateReadyCb);

            var __returnError   = function(err) {
                callbackGiven ? updateReadyCb(null, err) :  _l.error(me, "Error occurred : " + _.stringify(err));
            };

            if (!this._stateProcessingInitialized) {
                __returnError({
                    message : "State processing is not initialized (correctly), call _initStateProcessing() in " +
                               "your controller-constructor first"
                });
                return;
            }

            if (this.isValid() === false) {
                __returnError({
                    message : "Controller is invalid, unable to update to remote"
                });
                return;
            }

            if (_.func(this._onWantToUpdateFromRemote)) {
                this._onWantToUpdateFromRemote();
            }

            this._dispatchToModel(
                    "wantToUpdateFromRemote",
                    data,
                    function(respondsData, err) {
                        var onUpdatedFromRemote = _.func(self._onUpdatedFromRemote) ?
                            self._onUpdatedFromRemote.bind(self) :
                            // Dummy function that calls callback immediately
                            function(respondsData, err, callback) {
                                callback();
                            };

                        onUpdatedFromRemote(respondsData, err, function(err) {
                            if (_.def(err)) {
                                __returnError(err);
                                return;
                            }

                            if (callbackGiven) { updateReadyCb(respondsData); }
                        });
                    });
        },

        _processModelEvent : function(customProcessMethodName, eventName, isGlobal, processingArguments) {
            var iName           = _.exec(this, 'getIName') || "[UNKOWN]";
            var me              = "{0}::ControllerProcessesState::_processModelEvent({1})"
                                  .fmt(iName, eventName);

            //unpack arguments
            processingArguments = processingArguments || [];
            var model           = processingArguments[0];
            var data            = processingArguments[1];
            var eventProcessedCb= processingArguments[2];

            var callbackGiven   = _.func(eventProcessedCb);

            var __returnError   = function(errStr) {
                callbackGiven ? eventProcessedCb(null, { message : errStr }) : _l.error(me, errStr);
            };

            if (!this._stateProcessingInitialized) {
                __returnError("State processing is not initialized (correctly), call _initStateProcessing() in " +
                              "your controller-constructor first");
                return;
            }

            if (this.isValid() === false) {
                __returnError("Controller is invalid, unable to process {0} event".fmt(eventName));
                return;
            }

            var dataDesc        = 'Data of {0} event'.fmt(eventName);
            var property        = isGlobal ? null : _.get(data, 'what', dataDesc);
            var value           = isGlobal ? data : _.get(data, 'data', dataDesc);

            //Default behavior is to forward the event and value
            var forward         = true;

            if (!isGlobal && (!_.string(property) || _.empty(property))) {
                __returnError("No valid data property name provided, unable to process {0} event".fmt(eventName));
                return;
            }

            var customFunc = this[customProcessMethodName];
            if (_.func(customFunc)) {
                var result = isGlobal ? customFunc.call(this, model, value) :
                                           customFunc.call(this, model, property, value);
                if (!_.obj(result)) {
                    __returnError(("{0} did not return an object with results, " +
                                   "unable to process {1} event").fmt(customProcessMethodName, eventName));
                    return;
                }

                if (result.success !== true) {
                    __returnError("Custom processing of the {0} event was not successful".fmt(eventName));
                    return;
                }

                value   = result.value;
                forward = _.bool(result.forward) ? result.forward : forward;
            }

            //Forward
            if (forward) {
                var eventData = isGlobal ? value : { what : property, data : value };
                this._dispatchToView(eventName, eventData, eventProcessedCb);
            } else {
                eventProcessedCb();
            }
        }

    });
})();


text:
package org.apache.camel.language.tokenizer;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.builder.xml.Namespaces;
import org.junit.Before;
import org.junit.Test;

public class XMLTokenizeLanguageStreamingFileTest extends ContextTestSupport {

    @Override
    @Before
    public void setUp() throws Exception {
        deleteDirectory("target/xmltokenize");
        super.setUp();
    }

    @Test
    public void testFromFile() throws Exception {
        getMockEndpoint("mock:result").expectedBodiesReceived("<c:child some_attr='a' anotherAttr='a' xmlns:c=\"urn:c\"></c:child>",
                "<c:child some_attr='b' anotherAttr='b' xmlns:c=\"urn:c\"></c:child>",
                "<c:child some_attr='c' anotherAttr='c' xmlns:c=\"urn:c\"></c:child>",
                "<c:child some_attr='d' anotherAttr='d' xmlns:c=\"urn:c\"></c:child>");

        String body = "<?xml version='1.0' encoding='UTF-8'?>"
                + "<c:parent xmlns:c='urn:c'>"
                +   "<c:child some_attr='a' anotherAttr='a'></c:child>"
                +   "<c:child some_attr='b' anotherAttr='b'></c:child>"
                +   "<c:child some_attr='c' anotherAttr='c'></c:child>"
                +   "<c:child some_attr='d' anotherAttr='d'></c:child>"
                + "</c:parent>";

        deleteDirectory("target/xmltokenize");
        template.sendBodyAndHeader("file:target/xmltokenize", body, Exchange.FILE_NAME, "myxml.xml");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            Namespaces ns = new Namespaces("C", "urn:c");
            public void configure() {
                from("file:target/xmltokenize?initialDelay=0&delay=10")
                    .split().xtokenize("//C:child", ns).streaming()
                        .to("mock:result")
                    .end();
            }
        };
    }
}


text:
package dao

import (
	"strconv"
	"time"

	"github.com/garyburd/redigo/redis"
	"github.com/golang/glog"
	"github.com/liberalman/im/server/notify/conf"
	"golang.org/x/net/context"
)

const (
	_keyOnline = "rgo_"
	_keyAccess = "rga_"
	_keyToken  = "rgt_"
	_online    = 1
	_offline   = 0
)

func keyOnline(uid int64) string {
	return _keyOnline + strconv.FormatInt(uid, 10)
}

func keyAccess(uid int64) string {
	return _keyAccess + strconv.FormatInt(uid, 10)
}

func keyToken(uid int64) string {
	return _keyToken + strconv.FormatInt(uid, 10)
}

func (dao *Dao) Token(ctx context.Context, uid int64) (res string, err error) {
	conn := dao.redis.Get(ctx)
	defer conn.Close()
	res, err = redis.String(conn.Do("GET", keyToken(uid)))
	if err != nil {
		glog.Error(err)
	}
	return
}

func (dao *Dao) SetToken(ctx context.Context, uid int64, token string) (err error) {
	conn := dao.redis.Get(ctx)
	defer conn.Close()
	_, err = conn.Do("SETEX", keyToken(uid), int(time.Duration(conf.Conf.Redis.Expire)/time.Second), token)
	if err != nil {
		glog.Error(err)
	}
	return
}

func (dao *Dao) RegisterAccess(ctx context.Context, uid int64, accessAddr string) (err error) {
	conn := dao.redis.Get(ctx)
	defer conn.Close()
	_, err = conn.Do("SET", keyAccess(uid), accessAddr)
	if err != nil {
		glog.Error(err)
	}
	return
}

func (dao *Dao) RouterAccess(ctx context.Context, uid int64) (res string, err error) {
	conn := dao.redis.Get(ctx)
	defer conn.Close()
	res, err = redis.String(conn.Do("GET", keyAccess(uid)))
	if err != nil {
		glog.Error(err)
	}
	return
}

func (dao *Dao) GetOnline(ctx context.Context, uid int64) (res int, err error) {
	conn := dao.redis.Get(ctx)
	defer conn.Close()
	res, err = redis.Int(conn.Do("GET", keyOnline(uid)))
	if err != nil {
		res = _offline
		glog.Error(err)
	}
	return
}

func (dao *Dao) SetOnline(ctx context.Context, uid int64) (err error) {
	conn := dao.redis.Get(ctx)
	defer conn.Close()
	_, err = conn.Do("SETEX", keyOnline(uid), int(time.Duration(conf.Conf.Redis.Expire)/time.Second), _online)
	if err != nil {
		glog.Error(err)
	}
	return
}


text:
+++
date = "2016-01-01T01:01:01-06:00"
title = "welcome"
type = "event"
aliases = ["/events/2015-toronto"]

+++

OLD

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="content-type" content="text/html; charset=utf-8" >
<title>Toronto 2015
 - Welcome</title>
<meta name="author" content="" >

<link rel="alternate" type="application/rss+xml" title="devopsdays RSS Feed" href="http://www.devopsdays.org/feed/" >

<link rel="stylesheet" href="/css/devops.min.css" type="text/css" media="screen, projection">
<link rel="stylesheet" href="/css/blueprint/print.css" type="text/css" media="print">

      Home

      Contact

      Events

      Presentations

      Blog

Toronto 2015
 - Welcome

Platinum sponsors

    Welcome
    Location
    Program
    Register
    Propose
    Sponsor
    Contact
    Conduct

You can find information on DevOpsDays Toronto 2016 information is available at DevOpsDays Toronto 2016!

DevOpsDays Toronto 2015 was Thursday & Friday May 14-15, 2015 at Glenn Gould Studios in Toronto. You can review the 2015 program and watch the videos.

Email the organizers.

  Follow @DevOpsDaysTO

  Subscribe to the DevOpsDays mailing list

Venue/Party sponsor

Gold sponsors

Silver sponsors

Media sponsors

Community Partners


text:
package org.apache.isis.viewer.dnd.example.border;

import org.apache.isis.noa.adapter.ObjectAdapter;
import org.apache.isis.noa.reflect.Allow;
import org.apache.isis.noa.reflect.Consent;
import org.apache.isis.noa.reflect.ObjectActionType;
import org.apache.isis.noa.reflect.Veto;
import org.apache.isis.viewer.dnd.ButtonAction;
import org.apache.isis.viewer.dnd.Content;
import org.apache.isis.viewer.dnd.View;
import org.apache.isis.viewer.dnd.ViewAxis;
import org.apache.isis.viewer.dnd.ViewSpecification;
import org.apache.isis.viewer.dnd.Workspace;
import org.apache.isis.viewer.dnd.border.ButtonBorder;
import org.apache.isis.viewer.dnd.content.RootObject;
import org.apache.isis.viewer.dnd.drawing.Location;
import org.apache.isis.viewer.dnd.drawing.Size;
import org.apache.isis.viewer.dnd.example.ExampleViewSpecification;
import org.apache.isis.viewer.dnd.example.view.TestObjectView;
import org.apache.isis.viewer.dnd.example.view.TestViews;

public class ButtonBorderExample extends TestViews {

    public static void main(final String[] args) {
        new ButtonBorderExample();
    }

    protected void views(final Workspace workspace) {
        ButtonAction[] actions = new ButtonAction[] { new ButtonAction() {

            public Consent disabled(final View view) {
                return Allow.DEFAULT;
            }

            public void execute(final Workspace workspace, final View view, final Location at) {
                view.getFeedbackManager().addMessage("Button 1 pressed");
            }

            public String getDescription(final View view) {
                return "Button that can be pressed";
            }

            public String getName(final View view) {
                return "Action";
            }

            public ObjectActionType getType() {
                return USER;
            }

            public boolean isDefault() {
                return true;
            }

            public String getHelp(final View view) {
                return null;
            }
        },

        new ButtonAction() {

            public Consent disabled(final View view) {
                return Veto.DEFAULT;
            }

            public void execute(final Workspace workspace, final View view, final Location at) {
                view.getFeedbackManager().addMessage("Button 2 pressed");
            }

            public String getDescription(final View view) {
                return "Button that can't be pressed";
            }

            public String getName(final View view) {
                return "Disabled";
            }

            public ObjectActionType getType() {
                return USER;
            }

            public boolean isDefault() {
                return false;
            }

            public String getHelp(final View view) {
                return null;
            }
        } };

        ObjectAdapter object = createExampleObjectForView();
        Content content = new RootObject(object);
        ViewSpecification specification = new ExampleViewSpecification();
        ViewAxis axis = null;

        View view = new ButtonBorder(actions, new TestObjectView(content, specification, axis, 200, 80, "VIEW in border"));

        view.setLocation(new Location(100, 100));
        view.setSize(view.getRequiredSize(new Size()));
        workspace.addView(view);

    }
}


text:
import { scheduleOnce } from '@ember/runloop';
import { inject as service } from '@ember/service';
import { alias } from '@ember/object/computed';
import Component from '@ember/component';
import NewOrEdit from 'shared/mixins/new-or-edit';
import ModalBase from 'shared/mixins/modal-base';
import { set } from '@ember/object';
import layout from './template';

export default Component.extend(ModalBase, NewOrEdit, {
  layout,
  classNames: ['large-modal', 'alert'],
  originalModel: alias('modalService.modalOpts'),
  settings: service(),

  clone           : null,
  primaryResource : alias('originalModel'),
  errors          : null,

  actions: {
    updateWhitelist(list) {
      set(this, 'primaryResource.whitelistDomains', list);
    },
  },

  init() {
    this._super(...arguments);
    this.set('clone', this.get('originalModel').clone());
    this.set('model', this.get('originalModel').clone());
    scheduleOnce('afterRender', () => {
      this.$('INPUT')[0].focus();
    });
  },

  editing: function() {
    return !!this.get('clone.id');
  }.property('clone.id'),

  doneSaving() {
    this.send('cancel');
  }
});


text:
/* globals MONGODB_URI, process, module */

module.exports = {
    'secretKey': '12345-67890-09876-54321',
}
    module.exports.port = process.env.PORT || 3000;

    if(module.exports.port == 3000 || module.exports.port == 8080) { //we are in a local environment, provision config variables accordingly
        module.exports.port = 8081; //when running a vite frontend
        module.exports.mongoUrl = "mongodb+srv://whiplashomega:1jGvRAba41WB8Nsf@elthelas.o7jzd.mongodb.net/heroku_4r630pjp?retryWrites=true&w=majority"; //'mongodb://0.0.0.0:27017/elthelas';
        module.exports.facebook = {
            clientID: '1915523602044424',
            clientSecret: 'c5bd3fd394b3e67c7624da4aac935e06',
            callbackURL: 'https://elthelas2-whiplashomega.c9users.io/users/facebook/callback'
        };
        module.exports.staticDir = "/elthelasapp/dist";
        // module.exports.port = 8081;
    } else {
        console.log(process.env.MONGODB_URI);
        module.exports.mongoUrl = "mongodb+srv://whiplashomega:1jGvRAba41WB8Nsf@elthelas.o7jzd.mongodb.net/heroku_4r630pjp?retryWrites=true&w=majority";
        module.exports.facebook = {
            clientID: '1706715636300300',
            clientSecret: '409369a75ffe5ece6c1dbfa040ed8c6e',
            callbackURL: 'https://elthelas.com/users/facebook/callback'
        };
        module.exports.staticDir = '/elthelasapp/dist';
    }


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
#if EXPERIMENTAL_SPATIAL
using Azure.Core.GeoJson;
#endif
using Azure.Core.TestFramework;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.Models;
using Microsoft.Spatial;
using NUnit.Framework;

namespace Azure.Search.Documents.Tests
{
    /// <summary>
    /// Base class for Search unit tests that adds shared infrastructure on top
    /// of the Azure.Core testing framework.
    /// </summary>
    [ClientTestFixture(SearchClientOptions.ServiceVersion.V2020_06_30)]
    public abstract partial class SearchTestBase : RecordedTestBase<SearchTestEnvironment>
    {
        /// <summary>
        /// Shared HTTP client instance with a longer timeout.  It's
        /// gratuitously long for the sake of live tests in a hammered
        /// environment.
        /// </summary>
        private static readonly HttpClient s_httpClient =
            new HttpClient() { Timeout = TimeSpan.FromMinutes(5) };

        /// <summary>
        /// The version of the REST API to test against.  This will be passed
        /// to the .ctor via ClientTestFixture's values.
        /// </summary>
        protected SearchClientOptions.ServiceVersion ServiceVersion { get; }

        /// <summary>
        /// Creates a new SearchTestBase instance.
        /// </summary>
        /// <param name="async">
        /// When false, we'll rewrite our tests methods to call the sync
        /// versions of async APIs.
        /// </param>
        /// <param name="serviceVersion">
        /// Version of the REST API to test against.
        /// </param>
        /// <param name="mode">
        /// Whether to run in Playback, Record, or Live mode.  The default
        /// value is pulled from the AZURE_TEST_MODE environment variable.
        /// </param>
        public SearchTestBase(bool async, SearchClientOptions.ServiceVersion serviceVersion, RecordedTestMode? mode = null)
            : base(async, mode ?? RecordedTestUtilities.GetModeFromEnvironment())
        {
            ServiceVersion = serviceVersion;
            Sanitizer = new SearchRecordedTestSanitizer();
            Matcher = new RecordMatcher(compareBodies: false);
        }

        /// <summary>
        /// Create default client options for testing (and instrument them with
        /// the recording transports).
        /// </summary>
        /// <param name="options">Optional client options.</param>
        /// <returns>SearchClientOptions for testing</returns>
        public SearchClientOptions GetSearchClientOptions(SearchClientOptions options = null)
        {
            options ??= new SearchClientOptions(ServiceVersion);
            options.Diagnostics.IsLoggingEnabled = true;
            options.Retry.Mode = RetryMode.Exponential;
            options.Retry.MaxRetries = 10;
            options.Retry.Delay = TimeSpan.FromSeconds(Mode == RecordedTestMode.Playback ? 0.01 : 1);
            options.Retry.MaxDelay = TimeSpan.FromSeconds(Mode == RecordedTestMode.Playback ? 0.1 : 600);
            options.Transport = new HttpClientTransport(s_httpClient);
            return InstrumentClientOptions(options);
        }

        /// <summary>
        /// A number of our tests have built in delays while we wait an expected
        /// amount of time for a service operation to complete and this method
        /// allows us to wait (unless we're playing back recordings, which can
        /// complete immediately).
        /// </summary>
        /// <param name="delay">The time to wait.  Defaults to 1s.</param>
        /// <param name="playbackDelay">
        /// An optional time wait if we're playing back a recorded test.  This
        /// is useful for allowing client side events to get processed.
        /// </param>
        /// <param name="cancellationToken">Optional <see cref="CancellationToken"/> to check.</param>
        /// <returns>A task that will (optionally) delay.</returns>
        /// <exception cref="OperationCanceledException">The <paramref name="cancellationToken"/> was signaled.</exception>
        public async Task DelayAsync(TimeSpan? delay = null, TimeSpan? playbackDelay = null, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (Mode != RecordedTestMode.Playback)
            {
                await Task.Delay(delay ?? TimeSpan.FromSeconds(1));
            }
            else if (playbackDelay != null)
            {
                await Task.Delay(playbackDelay.Value);
            }
        }

        /// <summary>
        /// Assert that we can catch the desired exception.  NUnit's default
        /// forces everything to be sync.
        /// </summary>
        /// <typeparam name="T">The type of the exception.</typeparam>
        /// <param name="action">An action that raises the exception.</param>
        /// <returns>The caught exception.</returns>
        public static async Task<T> CatchAsync<T>(Func<Task> action)
            where T : Exception
        {
            Assert.IsNotNull(action);
            try
            {
                await action().ConfigureAwait(false);
                Assert.Fail("Expected exception not found");
            }
            catch (T ex)
            {
                return ex;
            }
            catch (Exception other)
            {
                Assert.Fail($"Expected exception of type {typeof(T).Name}, not {other.ToString()}");
            }

            // The compiler doesn't realize Assert.Fail is a hard stop.
            throw new InvalidOperationException("Won't ever get here!");
        }

        /// <summary>
        /// Assert that two documents are the same.  This is a regular
        /// Assert.AreEqual check for statically typed documents.
        /// Dynamic documents will ignore any extra fields on the actual
        /// document that weren't present on the expected document.
        /// </summary>
        /// <param name="expected">The expected document.</param>
        /// <param name="actual">The actual document.</param>
        /// <param name="path">Optional expression path.</param>
        public static void AssertApproximate(object expected, object actual, string path = null)
        {
            if (expected is SearchDocument e && actual is SearchDocument a)
            {
                foreach (string key in e.Keys)
                {
                    object eValue = e[key];
                    object aValue =
                        (eValue is DateTimeOffset) ? a.GetDateTimeOffset(key) :
                        (eValue is double) ? a.GetDouble(key) :
                        a[key];
                    AssertApproximate(eValue, aValue, path != null ? path + "." + key : key);
                }
            }
#if EXPERIMENTAL_SPATIAL
            else if (expected is GeoPoint ePt && actual is GeoPoint aPt)
            {
                AssertEqual(ePt.Position, aPt.Position, path != null ? $"{path}.{nameof(GeoPoint.Position)}" : nameof(GeoPoint.Position));
            }
#endif
            else if (expected is GeographyPoint eGpt && actual is GeographyPoint aGpt)
            {
                AssertEqual(eGpt, aGpt, path);
            }
            else
            {
                AssertEqual(expected, actual, path);
            }

            static void AssertEqual(object e, object a, string path)
            {
                string location = path != null ? " at path " + path : "";
                Assert.AreEqual(e, a, $"Expected value `{e}`{location}, not `{a}`.");
            }
        }

        /// <summary>
        /// Waits for an indexer to complete up to the given <paramref name="timeout"/>.
        /// </summary>
        /// <param name="client">The <see cref="SearchIndexerClient"/> to use for requests.</param>
        /// <param name="indexerName">The name of the <see cref="SearchIndexer"/> to check.</param>
        /// <param name="timeout">The amount of time before being canceled. The default is 10 minutes.</param>
        /// <returns>A <see cref="Task"/> to await.</returns>
        protected async Task WaitForIndexingAsync(
            SearchIndexerClient client,
            string indexerName,
            TimeSpan? timeout = null)
        {
            TimeSpan delay = TimeSpan.FromSeconds(10);
            TimeSpan maxDelay = TimeSpan.FromMinutes(1);

            timeout ??= TimeSpan.FromMinutes(10);

            using CancellationTokenSource cts = new CancellationTokenSource(timeout.Value);

            while (true)
            {
                SearchIndexerStatus status = null;
                try
                {
                    await DelayAsync(delay, cancellationToken: cts.Token);

                    status = await client.GetIndexerStatusAsync(
                        indexerName,
                        cancellationToken: cts.Token);
                }
                catch (TaskCanceledException)
                {
                    // TODO: Remove this when we figure out a more correlative way of checking status.
                    Assert.Inconclusive("Timed out while waiting for the indexer to complete");
                }

                if (status.Status == IndexerStatus.Running)
                {
                    if (status.LastResult?.Status == IndexerExecutionStatus.Success)
                    {
                        return;
                    }
                    else if (status.LastResult?.Status == IndexerExecutionStatus.TransientFailure &&
                        status.LastResult is IndexerExecutionResult lastResult)
                    {
                        TestContext.WriteLine($"Transient error: {lastResult.ErrorMessage}");
                    }
                }
                else if (status.Status == IndexerStatus.Error &&
                    status.LastResult is IndexerExecutionResult lastResult)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine($"Error: {lastResult.ErrorMessage}");

                    if (lastResult.Errors?.Count > 0)
                    {
                        foreach (SearchIndexerError error in lastResult.Errors)
                        {
                            sb.AppendLine($" ---> {error.ErrorMessage}");
                        }
                    }

                    Assert.Fail(sb.ToString());
                }

                // Exponentially increase the delay to mitigate server throttling.
                delay = TimeSpan.FromSeconds(Math.Min(delay.TotalSeconds * 2, maxDelay.TotalSeconds));
            }
        }

        /// <summary>
        /// Wait until the document count for a given search index has crossed
        /// a minimum value.  This only does simple linear retries for a fixed
        /// number of attempts.
        /// </summary>
        /// <param name="searchClient">Client for the index.</param>
        /// <param name="minimumCount">Minimum document count to verify indexing.</param>
        /// <param name="attempts">Maximum number of attempts to retry.</param>
        /// <param name="delay">Delay between attempts.</param>
        /// <returns>A <see cref="Task"/> to await.</returns>
        protected async Task WaitForDocumentCountAsync(
            SearchClient searchClient,
            int minimumCount,
            int attempts = 3,
            TimeSpan? delay = null)
        {
            delay ??= TimeSpan.FromSeconds(1);
            int count = 0;
            for (int i = 0; i < attempts; i++)
            {
                count = (int)await searchClient.GetDocumentCountAsync();
                if (count >= minimumCount)
                {
                    // When using the free SKU, there may be enough load to prevent
                    // immediately replication to all replicas and we get back the
                    // wrong count. Wait a bit longer before checking again. We may
                    // also upgrade to a basic SKU, but that will take longer to
                    // provision.
                    await DelayAsync(delay);

                    return;
                }
                await DelayAsync(delay);
            }
            Assert.Fail($"Indexing only reached {count} documents and not the expected {minimumCount}!");
        }
    }
}


text:
class EnvoyIdempotenceCreatePublishedMessages < ActiveRecord::Migration
  def change
    create_table :published_messages, id: :uuid do |t|
      t.timestamps

      t.string :topic, null: false
      t.json :message, null: false
      t.json :response

      t.integer :attempts, null: false, default: 0
      t.datetime :attempted_at

      t.string :published_by
      t.datetime :published_at

      t.index :published_by
      t.index :published_at
    end
  end
end


text:
import * as gulp from 'gulp';
import * as htmlmin from 'gulp-htmlmin';
import { join } from 'path';
import { Config } from '../../config';

/**
 * Minifies the final index.html file.
 */
export = () => {
  return gulp.src([join(Config.APP_DEST, 'index.html')])
    .pipe(htmlmin({
      collapseWhitespace: true,
      removeComments: true,
      minifyJS: true
    }))
    .pipe(gulp.dest(Config.APP_DEST));
};