text:
/*******************************************************************************
 *
 * Module Name: dbexec - debugger control method execution
 *
 ******************************************************************************/

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

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

#ifdef ACPI_DEBUGGER

#define _COMPONENT          ACPI_CA_DEBUGGER
        ACPI_MODULE_NAME    ("dbexec")

static ACPI_DB_METHOD_INFO          AcpiGbl_DbMethodInfo;

/* Local prototypes */

static ACPI_STATUS
AcpiDbExecuteMethod (
    ACPI_DB_METHOD_INFO     *Info,
    ACPI_BUFFER             *ReturnObj);

static void
AcpiDbExecuteSetup (
    ACPI_DB_METHOD_INFO     *Info);

static UINT32
AcpiDbGetOutstandingAllocations (
    void);

static void ACPI_SYSTEM_XFACE
AcpiDbMethodThread (
    void                    *Context);

static ACPI_STATUS
AcpiDbExecutionWalk (
    ACPI_HANDLE             ObjHandle,
    UINT32                  NestingLevel,
    void                    *Context,
    void                    **ReturnValue);

/*******************************************************************************
 *
 * FUNCTION:    AcpiDbDeleteObjects
 *
 * PARAMETERS:  Count               - Count of objects in the list
 *              Objects             - Array of ACPI_OBJECTs to be deleted
 *
 * RETURN:      None
 *
 * DESCRIPTION: Delete a list of ACPI_OBJECTS. Handles packages and nested
 *              packages via recursion.
 *
 ******************************************************************************/

void
AcpiDbDeleteObjects (
    UINT32                  Count,
    ACPI_OBJECT             *Objects)
{
    UINT32                  i;

    for (i = 0; i < Count; i++)
    {
        switch (Objects[i].Type)
        {
        case ACPI_TYPE_BUFFER:

            ACPI_FREE (Objects[i].Buffer.Pointer);
            break;

        case ACPI_TYPE_PACKAGE:

            /* Recursive call to delete package elements */

            AcpiDbDeleteObjects (Objects[i].Package.Count,
                Objects[i].Package.Elements);

            /* Free the elements array */

            ACPI_FREE (Objects[i].Package.Elements);
            break;

        default:

            break;
        }
    }
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiDbExecuteMethod
 *
 * PARAMETERS:  Info            - Valid info segment
 *              ReturnObj       - Where to put return object
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Execute a control method.
 *
 ******************************************************************************/

static ACPI_STATUS
AcpiDbExecuteMethod (
    ACPI_DB_METHOD_INFO     *Info,
    ACPI_BUFFER             *ReturnObj)
{
    ACPI_STATUS             Status;
    ACPI_OBJECT_LIST        ParamObjects;
    ACPI_OBJECT             Params[ACPI_DEBUGGER_MAX_ARGS + 1];
    UINT32                  i;

    ACPI_FUNCTION_TRACE (DbExecuteMethod);

    if (AcpiGbl_DbOutputToFile && !AcpiDbgLevel)
    {
        AcpiOsPrintf ("Warning: debug output is not enabled!\n");
    }

    ParamObjects.Count = 0;
    ParamObjects.Pointer = NULL;

    /* Pass through any command-line arguments */

    if (Info->Args && Info->Args[0])
    {
        /* Get arguments passed on the command line */

        for (i = 0; (Info->Args[i] && *(Info->Args[i])); i++)
        {
            /* Convert input string (token) to an actual ACPI_OBJECT */

            Status = AcpiDbConvertToObject (Info->Types[i],
                Info->Args[i], &Params[i]);
            if (ACPI_FAILURE (Status))
            {
                ACPI_EXCEPTION ((AE_INFO, Status,
                    "While parsing method arguments"));
                goto Cleanup;
            }
        }

        ParamObjects.Count = i;
        ParamObjects.Pointer = Params;
    }

    /* Prepare for a return object of arbitrary size */

    ReturnObj->Pointer = AcpiGbl_DbBuffer;
    ReturnObj->Length  = ACPI_DEBUG_BUFFER_SIZE;

    /* Do the actual method execution */

    AcpiGbl_MethodExecuting = TRUE;
    Status = AcpiEvaluateObject (NULL, Info->Pathname,
        &ParamObjects, ReturnObj);

    AcpiGbl_CmSingleStep = FALSE;
    AcpiGbl_MethodExecuting = FALSE;

    if (ACPI_FAILURE (Status))
    {
        ACPI_EXCEPTION ((AE_INFO, Status,
            "while executing %s from debugger", Info->Pathname));

        if (Status == AE_BUFFER_OVERFLOW)
        {
            ACPI_ERROR ((AE_INFO,
                "Possible overflow of internal debugger buffer (size 0x%X needed 0x%X)",
                ACPI_DEBUG_BUFFER_SIZE, (UINT32) ReturnObj->Length));
        }
    }

Cleanup:
    AcpiDbDeleteObjects (ParamObjects.Count, Params);
    return_ACPI_STATUS (Status);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiDbExecuteSetup
 *
 * PARAMETERS:  Info            - Valid method info
 *
 * RETURN:      None
 *
 * DESCRIPTION: Setup info segment prior to method execution
 *
 ******************************************************************************/

static void
AcpiDbExecuteSetup (
    ACPI_DB_METHOD_INFO     *Info)
{

    /* Catenate the current scope to the supplied name */

    Info->Pathname[0] = 0;
    if ((Info->Name[0] != '\\') &&
        (Info->Name[0] != '/'))
    {
        ACPI_STRCAT (Info->Pathname, AcpiGbl_DbScopeBuf);
    }

    ACPI_STRCAT (Info->Pathname, Info->Name);
    AcpiDbPrepNamestring (Info->Pathname);

    AcpiDbSetOutputDestination (ACPI_DB_DUPLICATE_OUTPUT);
    AcpiOsPrintf ("Evaluating %s\n", Info->Pathname);

    if (Info->Flags & EX_SINGLE_STEP)
    {
        AcpiGbl_CmSingleStep = TRUE;
        AcpiDbSetOutputDestination (ACPI_DB_CONSOLE_OUTPUT);
    }

    else
    {
        /* No single step, allow redirection to a file */

        AcpiDbSetOutputDestination (ACPI_DB_REDIRECTABLE_OUTPUT);
    }
}

#ifdef ACPI_DBG_TRACK_ALLOCATIONS
UINT32
AcpiDbGetCacheInfo (
    ACPI_MEMORY_LIST        *Cache)
{

    return (Cache->TotalAllocated - Cache->TotalFreed - Cache->CurrentDepth);
}
#endif

/*******************************************************************************
 *
 * FUNCTION:    AcpiDbGetOutstandingAllocations
 *
 * PARAMETERS:  None
 *
 * RETURN:      Current global allocation count minus cache entries
 *
 * DESCRIPTION: Determine the current number of "outstanding" allocations --
 *              those allocations that have not been freed and also are not
 *              in one of the various object caches.
 *
 ******************************************************************************/

static UINT32
AcpiDbGetOutstandingAllocations (
    void)
{
    UINT32                  Outstanding = 0;

#ifdef ACPI_DBG_TRACK_ALLOCATIONS

    Outstanding += AcpiDbGetCacheInfo (AcpiGbl_StateCache);
    Outstanding += AcpiDbGetCacheInfo (AcpiGbl_PsNodeCache);
    Outstanding += AcpiDbGetCacheInfo (AcpiGbl_PsNodeExtCache);
    Outstanding += AcpiDbGetCacheInfo (AcpiGbl_OperandCache);
#endif

    return (Outstanding);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiDbExecutionWalk
 *
 * PARAMETERS:  WALK_CALLBACK
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Execute a control method. Name is relative to the current
 *              scope.
 *
 ******************************************************************************/

static ACPI_STATUS
AcpiDbExecutionWalk (
    ACPI_HANDLE             ObjHandle,
    UINT32                  NestingLevel,
    void                    *Context,
    void                    **ReturnValue)
{
    ACPI_OPERAND_OBJECT     *ObjDesc;
    ACPI_NAMESPACE_NODE     *Node = (ACPI_NAMESPACE_NODE *) ObjHandle;
    ACPI_BUFFER             ReturnObj;
    ACPI_STATUS             Status;

    ObjDesc = AcpiNsGetAttachedObject (Node);
    if (ObjDesc->Method.ParamCount)
    {
        return (AE_OK);
    }

    ReturnObj.Pointer = NULL;
    ReturnObj.Length = ACPI_ALLOCATE_BUFFER;

    AcpiNsPrintNodePathname (Node, "Evaluating");

    /* Do the actual method execution */

    AcpiOsPrintf ("\n");
    AcpiGbl_MethodExecuting = TRUE;

    Status = AcpiEvaluateObject (Node, NULL, NULL, &ReturnObj);

    AcpiOsPrintf ("Evaluation of [%4.4s] returned %s\n", AcpiUtGetNodeName (Node),
            AcpiFormatException (Status));
    AcpiGbl_MethodExecuting = FALSE;

    return (AE_OK);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiDbExecute
 *
 * PARAMETERS:  Name                - Name of method to execute
 *              Args                - Parameters to the method
 *              Flags               - single step/no single step
 *
 * RETURN:      None
 *
 * DESCRIPTION: Execute a control method. Name is relative to the current
 *              scope.
 *
 ******************************************************************************/

void
AcpiDbExecute (
    char                    *Name,
    char                    **Args,
    ACPI_OBJECT_TYPE        *Types,
    UINT32                  Flags)
{
    ACPI_STATUS             Status;
    ACPI_BUFFER             ReturnObj;
    char                    *NameString;

#ifdef ACPI_DEBUG_OUTPUT
    UINT32                  PreviousAllocations;
    UINT32                  Allocations;

    /* Memory allocation tracking */

    PreviousAllocations = AcpiDbGetOutstandingAllocations ();
#endif

    if (*Name == '*')
    {
        (void) AcpiWalkNamespace (ACPI_TYPE_METHOD, ACPI_ROOT_OBJECT,
                    ACPI_UINT32_MAX, AcpiDbExecutionWalk, NULL, NULL, NULL);
        return;
    }
    else
    {
        NameString = ACPI_ALLOCATE (ACPI_STRLEN (Name) + 1);
        if (!NameString)
        {
            return;
        }

        ACPI_MEMSET (&AcpiGbl_DbMethodInfo, 0, sizeof (ACPI_DB_METHOD_INFO));

        ACPI_STRCPY (NameString, Name);
        AcpiUtStrupr (NameString);
        AcpiGbl_DbMethodInfo.Name = NameString;
        AcpiGbl_DbMethodInfo.Args = Args;
        AcpiGbl_DbMethodInfo.Types = Types;
        AcpiGbl_DbMethodInfo.Flags = Flags;

        ReturnObj.Pointer = NULL;
        ReturnObj.Length = ACPI_ALLOCATE_BUFFER;

        AcpiDbExecuteSetup (&AcpiGbl_DbMethodInfo);

        /* Get the NS node, determines existence also */

        Status = AcpiGetHandle (NULL, AcpiGbl_DbMethodInfo.Pathname,
            &AcpiGbl_DbMethodInfo.Method);
        if (ACPI_SUCCESS (Status))
        {
            Status = AcpiDbExecuteMethod (&AcpiGbl_DbMethodInfo, &ReturnObj);
        }
        ACPI_FREE (NameString);
    }

    /*
     * Allow any handlers in separate threads to complete.
     * (Such as Notify handlers invoked from AML executed above).
     */
    AcpiOsSleep ((UINT64) 10);

#ifdef ACPI_DEBUG_OUTPUT

    /* Memory allocation tracking */

    Allocations = AcpiDbGetOutstandingAllocations () - PreviousAllocations;

    AcpiDbSetOutputDestination (ACPI_DB_DUPLICATE_OUTPUT);

    if (Allocations > 0)
    {
        AcpiOsPrintf ("0x%X Outstanding allocations after evaluation of %s\n",
                        Allocations, AcpiGbl_DbMethodInfo.Pathname);
    }
#endif

    if (ACPI_FAILURE (Status))
    {
        AcpiOsPrintf ("Evaluation of %s failed with status %s\n",
            AcpiGbl_DbMethodInfo.Pathname, AcpiFormatException (Status));
    }
    else
    {
        /* Display a return object, if any */

        if (ReturnObj.Length)
        {
            AcpiOsPrintf (
                "Evaluation of %s returned object %p, external buffer length %X\n",
                AcpiGbl_DbMethodInfo.Pathname, ReturnObj.Pointer,
                (UINT32) ReturnObj.Length);
            AcpiDbDumpExternalObject (ReturnObj.Pointer, 1);

            /* Dump a _PLD buffer if present */

            if (ACPI_COMPARE_NAME ((ACPI_CAST_PTR (ACPI_NAMESPACE_NODE,
                    AcpiGbl_DbMethodInfo.Method)->Name.Ascii), METHOD_NAME__PLD))
            {
                AcpiDbDumpPldBuffer (ReturnObj.Pointer);
            }
        }
        else
        {
            AcpiOsPrintf ("No object was returned from evaluation of %s\n",
                AcpiGbl_DbMethodInfo.Pathname);
        }
    }

    AcpiDbSetOutputDestination (ACPI_DB_CONSOLE_OUTPUT);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiDbMethodThread
 *
 * PARAMETERS:  Context             - Execution info segment
 *
 * RETURN:      None
 *
 * DESCRIPTION: Debugger execute thread. Waits for a command line, then
 *              simply dispatches it.
 *
 ******************************************************************************/

static void ACPI_SYSTEM_XFACE
AcpiDbMethodThread (
    void                    *Context)
{
    ACPI_STATUS             Status;
    ACPI_DB_METHOD_INFO     *Info = Context;
    ACPI_DB_METHOD_INFO     LocalInfo;
    UINT32                  i;
    UINT8                   Allow;
    ACPI_BUFFER             ReturnObj;

    /*
     * AcpiGbl_DbMethodInfo.Arguments will be passed as method arguments.
     * Prevent AcpiGbl_DbMethodInfo from being modified by multiple threads
     * concurrently.
     *
     * Note: The arguments we are passing are used by the ASL test suite
     * (aslts). Do not change them without updating the tests.
     */
    (void) AcpiOsWaitSemaphore (Info->InfoGate, 1, ACPI_WAIT_FOREVER);

    if (Info->InitArgs)
    {
        AcpiDbUint32ToHexString (Info->NumCreated, Info->IndexOfThreadStr);
        AcpiDbUint32ToHexString ((UINT32) AcpiOsGetThreadId (), Info->IdOfThreadStr);
    }

    if (Info->Threads && (Info->NumCreated < Info->NumThreads))
    {
        Info->Threads[Info->NumCreated++] = AcpiOsGetThreadId();
    }

    LocalInfo = *Info;
    LocalInfo.Args = LocalInfo.Arguments;
    LocalInfo.Arguments[0] = LocalInfo.NumThreadsStr;
    LocalInfo.Arguments[1] = LocalInfo.IdOfThreadStr;
    LocalInfo.Arguments[2] = LocalInfo.IndexOfThreadStr;
    LocalInfo.Arguments[3] = NULL;

    LocalInfo.Types = LocalInfo.ArgTypes;

    (void) AcpiOsSignalSemaphore (Info->InfoGate, 1);

    for (i = 0; i < Info->NumLoops; i++)
    {
        Status = AcpiDbExecuteMethod (&LocalInfo, &ReturnObj);
        if (ACPI_FAILURE (Status))
        {
            AcpiOsPrintf ("%s During evaluation of %s at iteration %X\n",
                AcpiFormatException (Status), Info->Pathname, i);
            if (Status == AE_ABORT_METHOD)
            {
                break;
            }
        }

#if 0
        if ((i % 100) == 0)
        {
            AcpiOsPrintf ("%u loops, Thread 0x%x\n", i, AcpiOsGetThreadId ());
        }

        if (ReturnObj.Length)
        {
            AcpiOsPrintf ("Evaluation of %s returned object %p Buflen %X\n",
                Info->Pathname, ReturnObj.Pointer, (UINT32) ReturnObj.Length);
            AcpiDbDumpExternalObject (ReturnObj.Pointer, 1);
        }
#endif
    }

    /* Signal our completion */

    Allow = 0;
    (void) AcpiOsWaitSemaphore (Info->ThreadCompleteGate, 1, ACPI_WAIT_FOREVER);
    Info->NumCompleted++;

    if (Info->NumCompleted == Info->NumThreads)
    {
        /* Do signal for main thread once only */
        Allow = 1;
    }

    (void) AcpiOsSignalSemaphore (Info->ThreadCompleteGate, 1);

    if (Allow)
    {
        Status = AcpiOsSignalSemaphore (Info->MainThreadGate, 1);
        if (ACPI_FAILURE (Status))
        {
            AcpiOsPrintf ("Could not signal debugger thread sync semaphore, %s\n",
                AcpiFormatException (Status));
        }
    }
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiDbCreateExecutionThreads
 *
 * PARAMETERS:  NumThreadsArg           - Number of threads to create
 *              NumLoopsArg             - Loop count for the thread(s)
 *              MethodNameArg           - Control method to execute
 *
 * RETURN:      None
 *
 * DESCRIPTION: Create threads to execute method(s)
 *
 ******************************************************************************/

void
AcpiDbCreateExecutionThreads (
    char                    *NumThreadsArg,
    char                    *NumLoopsArg,
    char                    *MethodNameArg)
{
    ACPI_STATUS             Status;
    UINT32                  NumThreads;
    UINT32                  NumLoops;
    UINT32                  i;
    UINT32                  Size;
    ACPI_MUTEX              MainThreadGate;
    ACPI_MUTEX              ThreadCompleteGate;
    ACPI_MUTEX              InfoGate;

    /* Get the arguments */

    NumThreads = ACPI_STRTOUL (NumThreadsArg, NULL, 0);
    NumLoops   = ACPI_STRTOUL (NumLoopsArg, NULL, 0);

    if (!NumThreads || !NumLoops)
    {
        AcpiOsPrintf ("Bad argument: Threads %X, Loops %X\n",
            NumThreads, NumLoops);
        return;
    }

    /*
     * Create the semaphore for synchronization of
     * the created threads with the main thread.
     */
    Status = AcpiOsCreateSemaphore (1, 0, &MainThreadGate);
    if (ACPI_FAILURE (Status))
    {
        AcpiOsPrintf ("Could not create semaphore for synchronization with the main thread, %s\n",
            AcpiFormatException (Status));
        return;
    }

    /*
     * Create the semaphore for synchronization
     * between the created threads.
     */
    Status = AcpiOsCreateSemaphore (1, 1, &ThreadCompleteGate);
    if (ACPI_FAILURE (Status))
    {
        AcpiOsPrintf ("Could not create semaphore for synchronization between the created threads, %s\n",
            AcpiFormatException (Status));
        (void) AcpiOsDeleteSemaphore (MainThreadGate);
        return;
    }

    Status = AcpiOsCreateSemaphore (1, 1, &InfoGate);
    if (ACPI_FAILURE (Status))
    {
        AcpiOsPrintf ("Could not create semaphore for synchronization of AcpiGbl_DbMethodInfo, %s\n",
            AcpiFormatException (Status));
        (void) AcpiOsDeleteSemaphore (ThreadCompleteGate);
        (void) AcpiOsDeleteSemaphore (MainThreadGate);
        return;
    }

    ACPI_MEMSET (&AcpiGbl_DbMethodInfo, 0, sizeof (ACPI_DB_METHOD_INFO));

    /* Array to store IDs of threads */

    AcpiGbl_DbMethodInfo.NumThreads = NumThreads;
    Size = sizeof (ACPI_THREAD_ID) * AcpiGbl_DbMethodInfo.NumThreads;
    AcpiGbl_DbMethodInfo.Threads = AcpiOsAllocate (Size);
    if (AcpiGbl_DbMethodInfo.Threads == NULL)
    {
        AcpiOsPrintf ("No memory for thread IDs array\n");
        (void) AcpiOsDeleteSemaphore (MainThreadGate);
        (void) AcpiOsDeleteSemaphore (ThreadCompleteGate);
        (void) AcpiOsDeleteSemaphore (InfoGate);
        return;
    }
    ACPI_MEMSET (AcpiGbl_DbMethodInfo.Threads, 0, Size);

    /* Setup the context to be passed to each thread */

    AcpiGbl_DbMethodInfo.Name = MethodNameArg;
    AcpiGbl_DbMethodInfo.Flags = 0;
    AcpiGbl_DbMethodInfo.NumLoops = NumLoops;
    AcpiGbl_DbMethodInfo.MainThreadGate = MainThreadGate;
    AcpiGbl_DbMethodInfo.ThreadCompleteGate = ThreadCompleteGate;
    AcpiGbl_DbMethodInfo.InfoGate = InfoGate;

    /* Init arguments to be passed to method */

    AcpiGbl_DbMethodInfo.InitArgs = 1;
    AcpiGbl_DbMethodInfo.Args = AcpiGbl_DbMethodInfo.Arguments;
    AcpiGbl_DbMethodInfo.Arguments[0] = AcpiGbl_DbMethodInfo.NumThreadsStr;
    AcpiGbl_DbMethodInfo.Arguments[1] = AcpiGbl_DbMethodInfo.IdOfThreadStr;
    AcpiGbl_DbMethodInfo.Arguments[2] = AcpiGbl_DbMethodInfo.IndexOfThreadStr;
    AcpiGbl_DbMethodInfo.Arguments[3] = NULL;

    AcpiGbl_DbMethodInfo.Types = AcpiGbl_DbMethodInfo.ArgTypes;
    AcpiGbl_DbMethodInfo.ArgTypes[0] = ACPI_TYPE_INTEGER;
    AcpiGbl_DbMethodInfo.ArgTypes[1] = ACPI_TYPE_INTEGER;
    AcpiGbl_DbMethodInfo.ArgTypes[2] = ACPI_TYPE_INTEGER;

    AcpiDbUint32ToHexString (NumThreads, AcpiGbl_DbMethodInfo.NumThreadsStr);

    AcpiDbExecuteSetup (&AcpiGbl_DbMethodInfo);

    /* Get the NS node, determines existence also */

    Status = AcpiGetHandle (NULL, AcpiGbl_DbMethodInfo.Pathname,
        &AcpiGbl_DbMethodInfo.Method);
    if (ACPI_FAILURE (Status))
    {
        AcpiOsPrintf ("%s Could not get handle for %s\n",
            AcpiFormatException (Status), AcpiGbl_DbMethodInfo.Pathname);
        goto CleanupAndExit;
    }

    /* Create the threads */

    AcpiOsPrintf ("Creating %X threads to execute %X times each\n",
        NumThreads, NumLoops);

    for (i = 0; i < (NumThreads); i++)
    {
        Status = AcpiOsExecute (OSL_DEBUGGER_THREAD, AcpiDbMethodThread,
            &AcpiGbl_DbMethodInfo);
        if (ACPI_FAILURE (Status))
        {
            break;
        }
    }

    /* Wait for all threads to complete */

    (void) AcpiOsWaitSemaphore (MainThreadGate, 1, ACPI_WAIT_FOREVER);

    AcpiDbSetOutputDestination (ACPI_DB_DUPLICATE_OUTPUT);
    AcpiOsPrintf ("All threads (%X) have completed\n", NumThreads);
    AcpiDbSetOutputDestination (ACPI_DB_CONSOLE_OUTPUT);

CleanupAndExit:

    /* Cleanup and exit */

    (void) AcpiOsDeleteSemaphore (MainThreadGate);
    (void) AcpiOsDeleteSemaphore (ThreadCompleteGate);
    (void) AcpiOsDeleteSemaphore (InfoGate);

    AcpiOsFree (AcpiGbl_DbMethodInfo.Threads);
    AcpiGbl_DbMethodInfo.Threads = NULL;
}

#endif /* ACPI_DEBUGGER */


text:
var ProfileParameterService = function($http, messageModel, ENV) {

	this.unlinkProfileParameter = function(profileId, paramId) {
		return $http.delete(ENV.api['root'] + 'profileparameters/' + profileId + '/' + paramId).then(
				function(result) {
					messageModel.setMessages([ { level: 'success', text: 'Profile and parameter were unlinked.' } ], false);
					return result;
				},
				function(err) {
					messageModel.setMessages(err.data.alerts, true);
					throw err;
				}
			);
	};

	this.linkProfileParameters = function(profile, params) {
		return $http.post(ENV.api['root'] + 'profileparameter', { profileId: profile.id, paramIds: params, replace: true }).then(
			function(result) {
				return result;
			},
			function(err) {
				messageModel.setMessages(err.data.alerts, false);
				throw err;
			}
		);
	};

	this.linkParamProfiles = function(paramId, profiles) {
		return $http.post(ENV.api['root'] + 'parameterprofile', { paramId: paramId, profileIds: profiles, replace: true }).then(
			function(result) {
				messageModel.setMessages([ { level: 'success', text: 'Profiles linked to parameter' } ], false);
				return result;
			},
			function(err) {
				messageModel.setMessages(err.data.alerts, false);
				throw err;
			}
		);
	};

};

ProfileParameterService.$inject = ['$http', 'messageModel', 'ENV'];
module.exports = ProfileParameterService;

redpajama_set_name: RedPajamaGithub


text:
var currentRoute = null;
var coordOfUser = null;
var points = [];
var isAndroid = Ti.Platform.osname == 'android';
var sourcePosition = null;
var locationAdded = false;
var userAnnotation = null;

var removeCurrentRoute = function () {
	if (currentRoute != null) {
		$.mapview.removeRoute(currentRoute);
		return true;
	}
	return false;
};

var decodeLine = function (encoded, points) {
	var len = encoded.length;
    var index = 0;

    var lat = 0;
    var lng = 0;

    while(index < len) {
        var b;
        var shift = 0;
        var result = 0;
        do {
            b = encoded.charCodeAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charCodeAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        // Create new Vars for the created lats and lng
        var newLat = lat * 1e-5;
        var newLon = lng * 1e-5;

        // push them into the array at the end (thus adding it to the correct place)
        points.push({
            latitude: newLat,
            longitude: newLon
        });
    }
};

var traceRoteWithGetDirection = function (origin, destination) {
	removeCurrentRoute();

	var url = "https://maps.googleapis.com/maps/api/directions/json?sensor=false&mode=driving&alternatives=true&units=imperial&origin=" + origin.latitude + "," + origin.longitude + "&destination="+ destination.latitude + "," + destination.longitude + "&key=" + Alloy.CFG.googlekey;

    var xhr = Ti.Network.createHTTPClient();
    xhr.setTimeout(15000);
    xhr.open('GET', url);

    xhr.onload = function() {
        var result = JSON.parse(this.responseText);

        if (result.status != 'OK') {
        	alert("Mapping Error - Cannot find a valid route");
            return;
        }

        var params = [],
        routes = result.routes;
        points = [];
        for (var i = 0, ii = routes.length; i < 1; i++) {
            var leg = routes[i].legs[0];

            for(var j = 0, jj = leg.steps.length; j < jj; j++){
                var step = leg.steps[j],  point = step.start_location;

                points.push({ latitude: point.lat, longitude: point.lng });

                decodeLine(step.polyline.points, points);
            };

            var lastPoint = leg.end_location;
            points.push({ latitude: lastPoint.lat,  longitude: lastPoint.lng });

        }

        var route = {
                name:"route",
                points: points,
                color:"blue",
                width:4
        };

        currentRoute = Alloy.Globals.Map.createRoute(route);
        $.mapview.addRoute(currentRoute);
    };

    xhr.send();
};

var showRoteInAppleMaps = function (lat, lng) {
	Ti.Platform.openURL("http://maps.apple.com/?daddr=" + lat + ',' + lng + "&saddr=" + coordOfUser.latitude + ',' + coordOfUser.longitude);
};

var showRoteInGoogleMaps = function (lat, lng) {
	if (isAndroid) {
		Ti.Platform.openURL('http://maps.google.com/maps?f=d&daddr=' + lat + ',' + lng);
	} else {
		Ti.Platform.openURL("comgooglemaps://?saddr=" + coordOfUser.latitude + ',' + coordOfUser.longitude + "&daddr=" + lat + ',' + lng + "&directionsmode=transit");
	}
};

var showRoteInWaze = function (lat, lng) {
	if (!Ti.Platform.openURL('waze://?ll=' + lat + ',' + lng + "&navigate=yes")) {
		if (isAndroid) {
			Ti.Platform.openURL("https://play.google.com/store/apps/details?id=com.waze");
		} else {
			Ti.Platform.openURL("http://itunes.apple.com/us/app/id323229106");
		}
	}
};

var showRote = function (lat, lng) {
	var dialog = Ti.UI.createOptionDialog({
        title:'Route in:',
        cancel: isAndroid ? 3 : 4,
        options: isAndroid ? [ 'Google Maps', 'Waze', 'Own App', 'Cancel'] : ['Apple Maps', 'Google Maps', 'Waze', 'Own App' ,'Cancel'],
    });

    dialog.show();

    dialog.addEventListener('click', function(e) {

		switch(e.index) {
			case 0:
				if (isAndroid) {
					showRoteInGoogleMaps(lat, lng);
				} else {
					showRoteInAppleMaps(lat, lng);
               	}
            break;

            case 1:
            	if (isAndroid) {
        			showRoteInWaze(lat, lng);
        		} else {
            		showRoteInGoogleMaps(lat, lng);
            	}
            break;

            case 2:
				if (isAndroid) {
					sourcePosition = { latitude: lat, longitude: lng };
					traceRoteWithGetDirection({ latitude: lat, longitude: lng }, { latitude: coordOfUser.latitude, longitude: coordOfUser.longitude });
				} else {
					showRoteInWaze(lat, lng);
				}
            break;

            case 3:
            	if (!isAndroid) {
            		sourcePosition = { latitude: lat, longitude: lng };
            		traceRoteWithGetDirection({latitude: lat, longitude: lng}, {latitude: coordOfUser.latitude, longitude: coordOfUser.longitude});
            	}
            break;
        }
    });
};

var data = [ { title: "Point 1 - Title", subTitle: "Point 1 - SubTitle", latitude: -23.0807, longitude: -47.2056 },
		     { title: "Point 2 - Title", subTitle: "Point 2 - SubTitle", latitude: -22.9008, longitude: -47.0572 },
		     { title: "Point 3 - Title", subTitle: "Point 3 - SubTitle", latitude: -23.1531, longitude: -47.0578 },
		     { title: "Point 4 - Title", subTitle: "Point 4 - SubTitle", latitude: -23.5017, longitude: -47.4581 },
		     { title: "Point 5 - Title", subTitle: "Point 5 - SubTitle", latitude: -23.2642, longitude: -47.2992 },
		     { title: "Point 6 - Title", subTitle: "Point 6 - SubTitle", latitude: -23.2008, longitude: -47.2869 }
		   ];

function report(evt) {
    if (evt.clicksource == "rightButton" || (isAndroid && evt.clicksource == "rightPane")) {
    	showRote(data[evt.annotation.annotationIndex].latitude, data[evt.annotation.annotationIndex].longitude);
    }
}

var annotations = [];

for (var i = 0 ; i < data.length ; i++ ) {

	annotations.push(Alloy.Globals.Map.createAnnotation({
        latitude: data[i].latitude,
    	longitude: data[i].longitude,
        title: data[i].title,
        subtitle: data[i].subTitle,
        pincolor: Alloy.Globals.Map.ANNOTATION_RED,
        draggable: true,
        showInfoWindow: true,
        annotationIndex: i,
        rightButton: "/images/ic_action_directions.png",
    	animate: true,
	}));
}

$.mapview.addAnnotations(annotations);

if (isAndroid) {
	var gpsProvider = Ti.Geolocation.Android.createLocationProvider({
	    name: Ti.Geolocation.PROVIDER_GPS,
	    minUpdateTime: 60,
	    minUpdateDistance: 100
	});

	Ti.Geolocation.Android.addLocationProvider(gpsProvider);

	var gpsRule = Ti.Geolocation.Android.createLocationRule({
	    provider: Ti.Geolocation.PROVIDER_GPS,
	    accuracy: 10,
	    maxAge: 300000,
	    minAge: 10000
	});
	Ti.Geolocation.Android.addLocationRule(gpsRule);
} else {
	Ti.Geolocation.distanceFilter = 10;
}

Ti.Geolocation.accuracy = Ti.Geolocation.ACCURACY_BEST;
Ti.Geolocation.preferredProvider = Ti.Geolocation.PROVIDER_GPS;

var handleLocation = function(e) {
 	if (!e.error && e.coords != null && e.coords.accuracy <= 10 && (coordOfUser == null || coordOfUser.latitude !== e.coords.latitude || coordOfUser.longitude !== e.coords.longitude)) {
        coordOfUser = e.coords;

        if (userAnnotation != null) {
        	$.mapview.removeAnnotation(userAnnotation);
        	if (removeCurrentRoute()) {
        		traceRoteWithGetDirection({latitude: sourcePosition.latitude, longitude: sourcePosition.longitude}, {latitude: coordOfUser.latitude, longitude: coordOfUser.longitude});
        	}
        } else {
        	$.mapview.setRegion({latitude: coordOfUser.latitude, longitude: coordOfUser.longitude});
        }

        userAnnotation = Alloy.Globals.Map.createAnnotation({
	        latitude: coordOfUser.latitude,
	    	longitude: coordOfUser.longitude,
	        pincolor: Alloy.Globals.Map.ANNOTATION_GREEN,
	        draggable: false,
	        showInfoWindow: false,
	    	animate: true,
		});

        $.mapview.addAnnotation(userAnnotation);
    }
};

var addHandler = function() {
 if (!locationAdded) {
        locationAdded = true;
        Ti.Geolocation.addEventListener('location', handleLocation);
    }
};

var removeHandler = function () {
 	if (locationAdded) {
        locationAdded = false;
        Ti.Geolocation.removeEventListener('location', handleLocation);
    }
};

if (Ti.Geolocation.locationServicesEnabled) {
    Ti.Geolocation.getCurrentPosition(function (e) {
		addHandler();
	});
	if (isAndroid) {
		var activity = Ti.Android.currentActivity;
	    activity.addEventListener('destroy', removeHandler);
	}

} else {
    alert('Please enable location services');
}

$.index.open();


text:
<?php

// $Id: vpage_cache_edit_wp.class.php 1570 2009-01-13 12:44:02Z ogrebg $

require_once(DIR_INC.'modules/tangra_cms/_sys/tcms_admin_page_w_fctrl_ua.class.php');
require_once(DIR_INC.'modules/tangra_cms/forms/vpage_cache/vpage_cache_form_ctrl.class.php');

class VPage_Cache_Edit_WP extends TCMS_Admin_Page_W_FCtrl_UA {
	public function create_view($name = 'default') {
		$ret = new TCMS_Admin_Page_View($this, $name, 'modules/tangra_cms/pages/_vpage/');

		return $ret;
	}

	protected function init_transit_vars() {
		$this->add_transit_var('category');
	}

	protected function create_form_ctrl() {
		$dbc = $this->get_dbc();
		$tvm = $this->get_tvm();

		$config = $this->get__config();

		$ret = new VPage_Cache_Form_Ctrl('vpage_cache', $tvm, $dbc, 'obj_id');

		return $ret;
	}

	protected function on_add_new() {
		throw new Tangra_Module_Exception();
	}

	protected function on_received_id($object_id) {
		$current_user = $this->get_user();
		$this->form_ctrl->set_permanent_external_param('user', $current_user->get_id());

		$this->export('vpage_id', $object_id);

//		$category_id = $this->get_transit_var('category', true);
//		if ($category_id) {
//			$this->export('category_id', $category_id);
//		}
	}

	protected function create_default_redir_view() {
		$object = $this->form_ctrl->get_object();
		$redir_view = $this->create_redirect_view($this->get_redir_on_success(), array('manage' => $object->get_id()));

		return $redir_view;
	}
}


text:
package com.scooter1556.sms.android.fragment.tv;

import android.annotation.TargetApi;
import android.content.ComponentName;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.MediaDescriptionCompat;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.leanback.app.BackgroundManager;
import androidx.leanback.app.PlaybackSupportFragment;
import androidx.leanback.app.VideoSupportFragment;
import androidx.leanback.app.VideoSupportFragmentGlueHost;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.ext.leanback.LeanbackPlayerAdapter;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.text.Cue;
import com.google.android.exoplayer2.text.TextOutput;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.MappingTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.ui.SubtitleView;
import com.scooter1556.sms.android.R;
import com.scooter1556.sms.android.glue.LeanbackPlayerGlue;
import com.scooter1556.sms.android.playback.PlaybackManager;
import com.scooter1556.sms.android.service.MediaService;
import com.scooter1556.sms.android.utils.TrackSelectionUtils;

import java.util.List;

public class TvVideoPlayerFragment extends VideoSupportFragment implements TextOutput, Player.EventListener, PlaybackManager.PlaybackListener, LeanbackPlayerGlue.ActionListener {
    private static final String TAG = "TvVideoPlayerFragment";

    // Saved instance state keys.
    private static final String KEY_TRACK_SELECTOR_PARAMETERS = "track_selector_parameters";

    private static final int UPDATE_DELAY = 16;
    private static final int BACKGROUND_TYPE = PlaybackSupportFragment.BG_LIGHT;

    private static final int CARD_SIZE = 240;

    private SimpleExoPlayer player;
    private LeanbackPlayerGlue playerGlue;
    private LeanbackPlayerAdapter playerAdapter;
    private boolean isInitialised = false;

    private DefaultTrackSelector trackSelector;
    private DefaultTrackSelector.Parameters trackSelectorParameters;
    private TrackSelectionUtils trackSelectionUtils;
    private TrackGroupArray lastSeenTrackGroupArray;

    private SubtitleView subtitleView;

    private MediaBrowserCompat mediaBrowser;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        Log.d(TAG, "onActivityCreated()");

        super.onActivityCreated(savedInstanceState);

        subtitleView = getActivity().findViewById(R.id.subtitle_view);
        if (subtitleView != null) {
            subtitleView.setUserDefaultStyle();
            subtitleView.setUserDefaultTextSize();
        }

        if (savedInstanceState != null) {
            trackSelectorParameters = savedInstanceState.getParcelable(KEY_TRACK_SELECTOR_PARAMETERS);
        } else {
            trackSelectorParameters = new DefaultTrackSelector.ParametersBuilder().build();
        }

        setBackgroundType(BACKGROUND_TYPE);
        setControlsOverlayAutoHideEnabled(true);

        // Connect a media browser to keep media service alive
        mediaBrowser = new MediaBrowserCompat(getActivity(),
                new ComponentName(getActivity(), MediaService.class), new MediaBrowserCompat.ConnectionCallback(), null);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setBackgroundResource(android.R.color.black);
    }

    @Override
    public void onResume() {
        Log.d(TAG, "onResume()");

        super.onResume();

        if(isInitialised) {
            playerGlue.playWhenPrepared();
        } else {
            initialise();
        }

        // Keep screen on and prevent screensaver
        getSurfaceView().setKeepScreenOn(true);
    }

    /** Pauses the player. */
    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public void onPause() {
        Log.d(TAG, "onPause()");

        super.onPause();

        if (playerGlue != null && playerGlue.isPlaying()) {
            playerGlue.pause();
        }

        getSurfaceView().setKeepScreenOn(false);
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy()");

        super.onDestroy();

        // Remove playback manager listener
        PlaybackManager.getInstance().removeListener(this);

        // Stop and reset player
        player.stop(true);

        // Remove listener
        player.removeListener(this);

        playerGlue = null;
        playerAdapter = null;
        trackSelector = null;
    }

    @Override
    public void onStart() {
        Log.d(TAG, "onStart()");

        super.onStart();

        if (mediaBrowser != null) {
            mediaBrowser.connect();
        }
    }

    @Override
    public void onStop() {
        Log.d(TAG, "onStop()");

        super.onStop();

        if (mediaBrowser != null) {
            mediaBrowser.disconnect();
        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);

        updateTrackSelectorParameters();
        outState.putParcelable(KEY_TRACK_SELECTOR_PARAMETERS, trackSelectorParameters);
    }

    private void initialise() {
        Log.d(TAG, "initialise()");

        // Add listener for playback manager
        PlaybackManager.getInstance().addListener(this);

        // Setup player
        player = (SimpleExoPlayer) PlaybackManager.getInstance().getCurrentPlayer();
        player.addListener(this);
        player.addTextOutput(this);

        // Setup player adapter
        playerAdapter = new LeanbackPlayerAdapter(getActivity(), player, UPDATE_DELAY);

        // Setup player glue
        playerGlue = new LeanbackPlayerGlue(getActivity(), LeanbackPlayerGlue.Mode.VIDEO, playerAdapter, this);
        playerGlue.setHost(new VideoSupportFragmentGlueHost(this));
        playerGlue.playWhenPrepared();

        // Setup track selectors
        trackSelector = PlaybackManager.getInstance().getCurrentTrackSelector();
        trackSelectionUtils = new TrackSelectionUtils(getContext(), trackSelector);

        isInitialised = true;

        updateMetadata();
    }

    public void skipToNext() {
        player.next();
    }

    public void skipToPrevious() {
        player.previous();
    }

    public void rewind() {
        playerGlue.rewind();
    }

    public void fastForward() {
        playerGlue.fastForward();
    }

    private void updateMetadata() {
        Log.d(TAG, "updateMetadata()");

        MediaDescriptionCompat mediaDescription = PlaybackManager.getInstance().getMediaDescription();

        if(mediaDescription == null) {
            return;
        }

        playerGlue.setTitle(mediaDescription.getTitle());
        playerGlue.setSubtitle(mediaDescription.getSubtitle());

        Glide.with(this)
                .asBitmap()
                .load(mediaDescription.getIconUri())
                .into(new SimpleTarget<Bitmap>(CARD_SIZE, CARD_SIZE) {
                    @Override
                    public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                        if(playerGlue.getControlsRow() != null) {
                            playerGlue.getControlsRow().setImageBitmap(requireContext(), resource);
                            notifyPlaybackRowChanged();
                        }
                    }
                });
    }

    @Override
    public void onCues(List<Cue> cues) {
        if (subtitleView != null)
            subtitleView.onCues(cues);
    }

    private void updateTrackSelectorParameters() {
        if(trackSelector != null) {
            trackSelectorParameters = trackSelector.getParameters();
        }
    }

    @Override
    public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
        Log.d(TAG, "onTracksChanged()");

        if (trackGroups != lastSeenTrackGroupArray) {
            lastSeenTrackGroupArray = trackGroups;

            // Update glue actions
            for (int i = 0; i < trackSelections.length; i++) {
                switch(player.getRendererType(i)) {
                    case C.TRACK_TYPE_AUDIO:
                        playerGlue.audioTrackAction.setIndex(i);
                        break;

                    case C.TRACK_TYPE_TEXT:
                        playerGlue.textTrackAction.setIndex(i);
                        break;
                }
            }
        }
    }

    @Override
    public void onActionClicked(int action) {
        Log.d(TAG, "onActionClicked() -> " + action);

        if (action == LeanbackPlayerGlue.ACTION_NEXT) {
            skipToNext();
        } else if (action == LeanbackPlayerGlue.ACTION_PREVIOUS) {
            skipToPrevious();
        } else if (action == LeanbackPlayerGlue.ACTION_AUDIO_TRACK) {
            MappingTrackSelector.MappedTrackInfo mappedTrackInfo = trackSelector.getCurrentMappedTrackInfo();

            if (mappedTrackInfo != null) {
                trackSelectionUtils.showSelectionDialog(getActivity(), trackSelector.getCurrentMappedTrackInfo(), playerGlue.audioTrackAction.getIndex());
            }
        } else if (action == LeanbackPlayerGlue.ACTION_TEXT_TRACK) {
             MappingTrackSelector.MappedTrackInfo mappedTrackInfo = trackSelector.getCurrentMappedTrackInfo();

            if (mappedTrackInfo != null) {
                trackSelectionUtils.showSelectionDialog(getActivity(), trackSelector.getCurrentMappedTrackInfo(), playerGlue.textTrackAction.getIndex());
            }
        }
    }

    @Override
    public void onQueuePositionChanged(int previousIndex, int newIndex) {
        updateMetadata();
    }

    @Override
    public void onPlayerChanged(Player player) {
        // Nothing to do here...
    }
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import unittest

import measurement_stats as mstats

class TestDensity(unittest.TestCase):

    def test_no_overlap(self):
        """
        """

        dist = mstats.create_distribution([-2000], [1.0])
        comp = mstats.create_distribution([2000], [1.0])

        result = mstats.distributions.overlap2(dist, comp)
        self.assertAlmostEqual(result.value, 0)

    def test_low_overlap(self):
        """
        """

        values = [-10, 2, 20]
        uncertainties = [0.5, 0.5, 0.5]
        measurements = mstats.values.join(values, uncertainties)

        dist = mstats.create_distribution(measurements)
        comp = mstats.create_distribution(
            [mstats.mean.weighted_mean_and_deviation(measurements)]
        )

        result = mstats.distributions.overlap2(dist, comp)
        self.assertGreater(result.value, 0.3)

    def test_perfect_overlap(self):
        """ """

        values = [1, 1]
        uncertainties = [0.5, 0.5]
        measurements = mstats.values.join(values, uncertainties)

        dist = mstats.create_distribution(measurements)
        comp = mstats.create_distribution(
            [mstats.ValueUncertainty(values[0], uncertainties[0])]
        )

        result = mstats.distributions.overlap2(dist, comp)
        self.assertEqual(result.value, 1.0)

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(TestDensity)
    unittest.TextTestRunner(verbosity=2).run(suite)


text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.contracts.productadmin;

import java.util.List;
import java.util.HashMap;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.joda.time.DateTime;
import java.io.IOException;
import java.lang.ClassNotFoundException;
import com.mozu.api.contracts.core.AuditInfo;
import com.mozu.api.contracts.productadmin.DiscountCondition;
import com.mozu.api.contracts.productadmin.DiscountLocalizedContent;
import com.mozu.api.contracts.productadmin.DiscountTarget;

/**
 *	Name of the discount added and applied to a shopping cart and order for a shopper's purchase.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class Discount implements Serializable
{
	// Default Serial Version UID
	private static final long serialVersionUID = 1L;

	/**
	 * The integer amount of the discount. For example, an entry of "10" could represent a discount of $10.00 or a discount of 10%, depending on the type.
	 */
	protected  Double amount;

	public Double getAmount() {
		return this.amount;
	}

	public void setAmount(Double amount) {
		this.amount = amount;
	}

	/**
	 * The type of discount amount, such as an amount or a percentage.
	 */
	protected  String amountType;

	public String getAmountType() {
		return this.amountType;
	}

	public void setAmountType(String amountType) {
		this.amountType = amountType;
	}

	/**
	 * Signifies that the discount is not referenced and can be hard deleted
	 */
	protected  Boolean canBeDeleted;

	public Boolean getCanBeDeleted() {
		return this.canBeDeleted;
	}

	public void setCanBeDeleted(Boolean canBeDeleted) {
		this.canBeDeleted = canBeDeleted;
	}

	/**
	 * The number of times this discount has been redeemed.
	 */
	protected  Integer currentRedemptionCount;

	public Integer getCurrentRedemptionCount() {
		return this.currentRedemptionCount;
	}

	public void setCurrentRedemptionCount(Integer currentRedemptionCount) {
		this.currentRedemptionCount = currentRedemptionCount;
	}

	/**
	 * Determines whether or not a discount applies to a items with a sale price. Applicable on order and line item discounts. For line items, when this is true, the discount will be disqualified. For order level discounts, when true, the discount will not be applied to those items have a sale price.
	 */
	protected  Boolean doesNotApplyToProductsWithSalePrice;

	public Boolean getDoesNotApplyToProductsWithSalePrice() {
		return this.doesNotApplyToProductsWithSalePrice;
	}

	public void setDoesNotApplyToProductsWithSalePrice(Boolean doesNotApplyToProductsWithSalePrice) {
		this.doesNotApplyToProductsWithSalePrice = doesNotApplyToProductsWithSalePrice;
	}

	/**
	 * If true, this discount does not apply to a line item product with a defined sale price. The default is false, which applies the discount to products with and without defined sale prices.
	 */
	protected  Boolean doesNotApplyToSalePrice;

	public Boolean getDoesNotApplyToSalePrice() {
		return this.doesNotApplyToSalePrice;
	}

	public void setDoesNotApplyToSalePrice(Boolean doesNotApplyToSalePrice) {
		this.doesNotApplyToSalePrice = doesNotApplyToSalePrice;
	}

	/**
	 * Unique identifier of the source product property. For a product field it will be the name of the field. For a product attribute it will be the Attribute FQN.
	 */
	protected  Integer id;

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	/**
	 * Products receiving a price from a price list specified here or a child of a specified price list can be discounted.
	 */
	protected List<String> includedPriceLists;
	public List<String> getIncludedPriceLists() {
		return this.includedPriceLists;
	}
	public void setIncludedPriceLists(List<String> includedPriceLists) {
		this.includedPriceLists = includedPriceLists;
	}

	/**
	 * Maximum impact this discount can apply on a single order. Must be either null or greater than zero.
	 */
	protected  Double maximumDiscountImpactPerOrder;

	public Double getMaximumDiscountImpactPerOrder() {
		return this.maximumDiscountImpactPerOrder;
	}

	public void setMaximumDiscountImpactPerOrder(Double maximumDiscountImpactPerOrder) {
		this.maximumDiscountImpactPerOrder = maximumDiscountImpactPerOrder;
	}

	/**
	 * Maximum impact this discount can apply on a single line item. Must be either null or greater than zero.
	 */
	protected  Double maximumDiscountImpactPerRedemption;

	public Double getMaximumDiscountImpactPerRedemption() {
		return this.maximumDiscountImpactPerRedemption;
	}

	public void setMaximumDiscountImpactPerRedemption(Double maximumDiscountImpactPerRedemption) {
		this.maximumDiscountImpactPerRedemption = maximumDiscountImpactPerRedemption;
	}

	/**
	 * Maximum number of redemptions allowed per order. If null, defaults to unlimited.
	 */
	protected  Integer maximumRedemptionsPerOrder;

	public Integer getMaximumRedemptionsPerOrder() {
		return this.maximumRedemptionsPerOrder;
	}

	public void setMaximumRedemptionsPerOrder(Integer maximumRedemptionsPerOrder) {
		this.maximumRedemptionsPerOrder = maximumRedemptionsPerOrder;
	}

	/**
	 * The maximum number of times an individual shopper can redeem the discount.
	 */
	protected  Integer maximumUsesPerUser;

	public Integer getMaximumUsesPerUser() {
		return this.maximumUsesPerUser;
	}

	public void setMaximumUsesPerUser(Integer maximumUsesPerUser) {
		this.maximumUsesPerUser = maximumUsesPerUser;
	}

	/**
	 * The scope to which the discount applies, which is "Order" for order discounts or "LineItem" for individual product discounts.
	 */
	protected  String scope;

	public String getScope() {
		return this.scope;
	}

	public void setScope(String scope) {
		this.scope = scope;
	}

	/**
	 * The current status of an object. This status is specific to the object including payment (New, Authorized, Captured, Declined, Failed, Voided, Credited, CheckRequested, or RolledBack), discount (Active, Scheduled, or Expired), returns (ReturnAuthorized), tenant, package (Fulfilled or NotFulfilled), application, master and product catalogs, orders (Pending, Submitted, Processing, Pending Review, Closed, or Canceled), and order validation results (Pass, Fail, Error, or Review).
	 */
	protected  String status;

	public String getStatus() {
		return this.status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	/**
	 * Identifier and datetime stamp information recorded when a user or application creates, updates, or deletes a resource entity. This value is system-supplied and read-only.
	 */
	protected  AuditInfo auditInfo;

	public AuditInfo getAuditInfo() {
		return this.auditInfo;
	}

	public void setAuditInfo(AuditInfo auditInfo) {
		this.auditInfo = auditInfo;
	}

	/**
	 * List of conditions that must be met for the discount to apply.
	 */
	protected  DiscountCondition conditions;

	public DiscountCondition getConditions() {
		return this.conditions;
	}

	public void setConditions(DiscountCondition conditions) {
		this.conditions = conditions;
	}

	/**
	 * Complex type that contains content for a language specified by LocaleCode.
	 */
	protected  DiscountLocalizedContent content;

	public DiscountLocalizedContent getContent() {
		return this.content;
	}

	public void setContent(DiscountLocalizedContent content) {
		this.content = content;
	}

	/**
	 * Targets represent the object, such as an item to apply discounts (products or orders) or a view field for content. When accessing MZDB APIs for Mongo interactions, targets are the dot notation that links to the source document property. For example, firstitem for the direc level or firstitem.seconditem.thirditem for a deeper property.
	 */
	protected  DiscountTarget target;

	public DiscountTarget getTarget() {
		return this.target;
	}

	public void setTarget(DiscountTarget target) {
		this.target = target;
	}

}


text:
using System;

namespace Microsoft.DirectX.Direct3D
{
	public class FunctionDescription
	{
		public FunctionDescription ()
		{
		}
	}
}


text:
/*
 * This is not the original file distributed by the Apache Software Foundation
 * It has been modified by the Hipparchus project
 */
package org.hipparchus.stat.correlation;

import java.util.Arrays;

import org.hipparchus.exception.MathIllegalArgumentException;
import org.hipparchus.linear.BlockRealMatrix;
import org.hipparchus.linear.MatrixUtils;
import org.hipparchus.linear.RealMatrix;
import org.hipparchus.util.FastMath;
import org.hipparchus.util.MathArrays;

/**
 * Implementation of Kendall's Tau-b rank correlation.
 *

 * A pair of observations (x1, y1) and
 * (x2, y2) are considered concordant if
 * x1 < x2 and y1 < y2
 * or x2 < x1 and y2 < y1.
 * The pair is discordant if x1 < x2 and
 * y2 < y1 or x2 < x1 and
 * y1 < y2.  If either x1 = x2
 * or y1 = y2, the pair is neither concordant nor
 * discordant.
 *

 * Kendall's Tau-b is defined as:
 *

 * taub = (nc - nd) / sqrt((n0 - n1) * (n0 - n2))
 *

 *

 * where:
 *

 *
n0 = n * (n - 1) / 2

 *
nc = Number of concordant pairs

 *
nd = Number of discordant pairs

 *
n1 = sum of ti * (ti - 1) / 2 for all i

 *
n2 = sum of uj * (uj - 1) / 2 for all j

 *
ti = Number of tied values in the ith group of ties in x

 *
uj = Number of tied values in the jth group of ties in y

 *

 *

 * This implementation uses the O(n log n) algorithm described in
 * William R. Knight's 1966 paper "A Computer Method for Calculating
 * Kendall's Tau with Ungrouped Data" in the Journal of the American
 * Statistical Association.
 *
 * @see
 * Kendall tau rank correlation coefficient (Wikipedia)
 * @see A Computer
 * Method for Calculating Kendall's Tau with Ungrouped Data
 */
public class KendallsCorrelation {

    /** correlation matrix */
    private final RealMatrix correlationMatrix;

    /**
     * Create a KendallsCorrelation instance without data.
     */
    public KendallsCorrelation() {
        correlationMatrix = null;
    }

    /**
     * Create a KendallsCorrelation from a rectangular array
     * whose columns represent values of variables to be correlated.
     *
     * @param data rectangular array with columns representing variables
     * @throws IllegalArgumentException if the input data array is not
     * rectangular with at least two rows and two columns.
     */
    public KendallsCorrelation(double[][] data) {
        this(MatrixUtils.createRealMatrix(data));
    }

    /**
     * Create a KendallsCorrelation from a RealMatrix whose columns
     * represent variables to be correlated.
     *
     * @param matrix matrix with columns representing variables to correlate
     */
    public KendallsCorrelation(RealMatrix matrix) {
        correlationMatrix = computeCorrelationMatrix(matrix);
    }

    /**
     * Returns the correlation matrix.
     *
     * @return correlation matrix
     */
    public RealMatrix getCorrelationMatrix() {
        return correlationMatrix;
    }

    /**
     * Computes the Kendall's Tau rank correlation matrix for the columns of
     * the input matrix.
     *
     * @param matrix matrix with columns representing variables to correlate
     * @return correlation matrix
     */
    public RealMatrix computeCorrelationMatrix(final RealMatrix matrix) {
        int nVars = matrix.getColumnDimension();
        RealMatrix outMatrix = new BlockRealMatrix(nVars, nVars);
        for (int i = 0; i < nVars; i++) {
            for (int j = 0; j < i; j++) {
                double corr = correlation(matrix.getColumn(i), matrix.getColumn(j));
                outMatrix.setEntry(i, j, corr);
                outMatrix.setEntry(j, i, corr);
            }
            outMatrix.setEntry(i, i, 1d);
        }
        return outMatrix;
    }

    /**
     * Computes the Kendall's Tau rank correlation matrix for the columns of
     * the input rectangular array.  The columns of the array represent values
     * of variables to be correlated.
     *
     * @param matrix matrix with columns representing variables to correlate
     * @return correlation matrix
     */
    public RealMatrix computeCorrelationMatrix(final double[][] matrix) {
       return computeCorrelationMatrix(new BlockRealMatrix(matrix));
    }

    /**
     * Computes the Kendall's Tau rank correlation coefficient between the two arrays.
     *
     * @param xArray first data array
     * @param yArray second data array
     * @return Returns Kendall's Tau rank correlation coefficient for the two arrays
     * @throws MathIllegalArgumentException if the arrays lengths do not match
     */
    public double correlation(final double[] xArray, final double[] yArray)
            throws MathIllegalArgumentException {

        MathArrays.checkEqualLength(xArray, yArray);

        final int n = xArray.length;
        final long numPairs = sum(n - 1);

        DoublePair[] pairs = new DoublePair[n];
        for (int i = 0; i < n; i++) {
            pairs[i] = new DoublePair(xArray[i], yArray[i]);
        }

        Arrays.sort(pairs, (p1, p2) -> {
            int compareKey = Double.compare(p1.getFirst(), p2.getFirst());
            return compareKey != 0 ? compareKey : Double.compare(p1.getSecond(), p2.getSecond());
        });

        long tiedXPairs = 0;
        long tiedXYPairs = 0;
        long consecutiveXTies = 1;
        long consecutiveXYTies = 1;
        DoublePair prev = pairs[0];
        for (int i = 1; i < n; i++) {
            final DoublePair curr = pairs[i];
            if (Double.compare(curr.getFirst(), prev.getFirst()) == 0) {
                consecutiveXTies++;
                if (Double.compare(curr.getSecond(), prev.getSecond()) == 0) {
                    consecutiveXYTies++;
                } else {
                    tiedXYPairs += sum(consecutiveXYTies - 1);
                    consecutiveXYTies = 1;
                }
            } else {
                tiedXPairs += sum(consecutiveXTies - 1);
                consecutiveXTies = 1;
                tiedXYPairs += sum(consecutiveXYTies - 1);
                consecutiveXYTies = 1;
            }
            prev = curr;
        }
        tiedXPairs += sum(consecutiveXTies - 1);
        tiedXYPairs += sum(consecutiveXYTies - 1);

        long swaps = 0;
        DoublePair[] pairsDestination = new DoublePair[n];
        for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) {
            for (int offset = 0; offset < n; offset += 2 * segmentSize) {
                int i = offset;
                final int iEnd = FastMath.min(i + segmentSize, n);
                int j = iEnd;
                final int jEnd = FastMath.min(j + segmentSize, n);

                int copyLocation = offset;
                while (i < iEnd || j < jEnd) {
                    if (i < iEnd) {
                        if (j < jEnd) {
                            if (Double.compare(pairs[i].getSecond(), pairs[j].getSecond()) <= 0) {
                                pairsDestination[copyLocation] = pairs[i];
                                i++;
                            } else {
                                pairsDestination[copyLocation] = pairs[j];
                                j++;
                                swaps += iEnd - i;
                            }
                        } else {
                            pairsDestination[copyLocation] = pairs[i];
                            i++;
                        }
                    } else {
                        pairsDestination[copyLocation] = pairs[j];
                        j++;
                    }
                    copyLocation++;
                }
            }
            final DoublePair[] pairsTemp = pairs;
            pairs = pairsDestination;
            pairsDestination = pairsTemp;
        }

        long tiedYPairs = 0;
        long consecutiveYTies = 1;
        prev = pairs[0];
        for (int i = 1; i < n; i++) {
            final DoublePair curr = pairs[i];
            if (Double.compare(curr.getSecond(), prev.getSecond()) == 0) {
                consecutiveYTies++;
            } else {
                tiedYPairs += sum(consecutiveYTies - 1);
                consecutiveYTies = 1;
            }
            prev = curr;
        }
        tiedYPairs += sum(consecutiveYTies - 1);

        final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps;
        final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs);
        return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied);
    }

    /**
     * Returns the sum of the number from 1 .. n according to Gauss' summation formula:
     * \[ \sum\limits_{k=1}^n k = \frac{n(n + 1)}{2} \]
     *
     * @param n the summation end
     * @return the sum of the number from 1 to n
     */
    private static long sum(long n) {
        return n * (n + 1) / 2l;
    }

    /**
     * Helper data structure holding a (double, double) pair.
     */
    private static class DoublePair {
        /** The first value */
        private final double first;
        /** The second value */
        private final double second;

        /**
         * @param first first value.
         * @param second second value.
         */
        DoublePair(double first, double second) {
            this.first = first;
            this.second = second;
        }

        /** @return the first value. */
        public double getFirst() {
            return first;
        }

        /** @return the second value. */
        public double getSecond() {
            return second;
        }

    }

}


text:
package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"net/http"
)

const (
	// change these settings
	slackWebHookURL = "Slack Webhook URL"
	diffURL         = "http://www.gerrit.net/gitweb?p=%s.git;a=commitdiff;h=%s"
)

type payload struct {
	Text string `json:"text"`
}

// ref-updated --oldrev <old rev> --newrev <new rev> --refname <ref name> --project <project name> --submitter <submitter>
func main() {
	var oldrev string
	var newrev string
	var refname string
	var project string
	var submitter string

	flag.StringVar(&oldrev, "oldrev", "", "old rev")
	flag.StringVar(&newrev, "newrev", "", "new rev")
	flag.StringVar(&refname, "refname", "", "ref name")
	flag.StringVar(&project, "project", "", "project name")
	flag.StringVar(&submitter, "submitter", "", "submitter")

	flag.Parse()

	diffURL := fmt.Sprintf(diffURL, project, newrev)
	text := fmt.Sprintf("%s has updated %s (%s) to %s - <%s|diff>", submitter, project, refname, newrev, diffURL)

	p := payload{text}

	payloadJSON, err := json.Marshal(p)
	if err != nil {
		log.Fatalln(err)
	}

	_, err = http.Post(slackWebHookURL, "application/json", bytes.NewReader(payloadJSON))
	if err != nil {
		log.Fatalln(err)
	}
}


text:
'use strict';

/**
 * Module dependencies.
 */
var should = require('should'),
  mongoose = require('mongoose'),
  User = mongoose.model('User'),
  Feat = mongoose.model('Feat');

/**
 * Globals
 */
var user, feat;

/**
 * Unit tests
 */
describe('Feat Model Unit Tests:', function() {
  beforeEach(function(done) {
    user = new User({
      firstName: 'Full',
      lastName: 'Name',
      displayName: 'Full Name',
      email: 'test@test.com',
      username: 'username',
      password: 'password'
    });

    user.save(function() {
      feat = new Feat({
        name: 'Feat Name',
        user: user
      });

      done();
    });
  });

  describe('Method Save', function() {
    it('should be able to save without problems', function(done) {
      this.timeout(0);
      return feat.save(function(err) {
        should.not.exist(err);
        done();
      });
    });

    it('should be able to show an error when try to save without name', function(done) {
      feat.name = '';

      return feat.save(function(err) {
        should.exist(err);
        done();
      });
    });
  });

  afterEach(function(done) {
    Feat.remove().exec(function(){
      User.remove().exec(function(){
        done();
      });
    });
  });
});


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Maxillaria caespitifica Rchb.f.

### Remarks
null


text:
package io.github.zwieback.relef.services;

import io.github.zwieback.relef.configs.PropertyConfig;
import io.github.zwieback.relef.configs.ServiceConfigForTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.net.URISyntaxException;
import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {
        PropertyConfig.class,
        ServiceConfigForTest.class
})
public class UrlBuilderTest {

    private static final String INCORRECT_RELATIVE_URL = "A)*(&%(U N)V@*#&";
    private static final String DOMAIN_URL = "http://relefopt.ru/";
    private static final String PRODUCT_URL = "/69702/132654/";
    private static final String BRAND_URL = "/brands/12908290.php";
    private static final Long CATALOG_ID = 69702L;
    private static final Long PRODUCT_ID = 132654L;
    private static final Long NOW = 1492872488282L;
    private static final UUID PRODUCT_XML_ID = UUID.randomUUID();

    @SuppressWarnings("unused")
    @Autowired
    private UrlBuilder urlBuilder;

    @SuppressWarnings("unused")
    @Autowired
    private DateTimeService dateTimeService;

    @Test
    public void test_buildProductUrl_should_be_full_url() {
        String resultUrl = urlBuilder.buildProductUrl(CATALOG_ID, PRODUCT_ID);
        String expectedUrl = DOMAIN_URL + "catalog" + PRODUCT_URL;
        assertThat(resultUrl).isEqualTo(expectedUrl);
    }

    @Test
    public void test_buildTrickyProductUrl_should_contains_bxrand() {
        String resultUrl = urlBuilder.buildTrickyProductUrl(PRODUCT_URL);
        assertThat(resultUrl).contains("bxrand");
    }

    @Test
    public void test_buildTrickyProductUrl_should_contains_now_as_timestamp() {
        when(dateTimeService.nowAsMilliseconds()).thenReturn(NOW);

        String resultUrl = urlBuilder.buildTrickyProductUrl(PRODUCT_URL);
        String[] dividedUrl = resultUrl.split("="); // timestamp as ms in last value
        Long timestamp = Long.valueOf(dividedUrl[dividedUrl.length - 1]);
        assertThat(timestamp).isEqualTo(NOW);
    }

    @Test
    public void test_buildProductPhotoUrl_should_ends_with_xmlId_of_product() {
        String resultUrl = urlBuilder.buildProductPhotoUrl(PRODUCT_XML_ID);
        assertThat(resultUrl).endsWith(PRODUCT_XML_ID.toString());
    }

    @Test
    public void test_buildPathUrl_should_starts_with_domainUrl() {
        String resultUrl = urlBuilder.buildPathUrl(PRODUCT_URL);
        assertThat(resultUrl).startsWith(DOMAIN_URL);
    }

    @Test
    public void test_buildPathUrl_should_contains_productUrl() {
        String resultUrl = urlBuilder.buildPathUrl(PRODUCT_URL);
        assertThat(resultUrl).contains(PRODUCT_URL);
    }

    @Test
    public void test_buildPathUrl_should_ends_with_slash() {
        String resultUrl = urlBuilder.buildPathUrl(PRODUCT_URL);
        assertThat(resultUrl).endsWith("/");
    }

    @Test
    public void test_buildQueryUrl_should_starts_with_domainUrl() {
        String resultUrl = urlBuilder.buildPathUrl(PRODUCT_URL);
        assertThat(resultUrl).startsWith(DOMAIN_URL);
    }

    @Test
    public void test_buildQueryUrl_should_contains_brandUrl() {
        String resultUrl = urlBuilder.buildPathUrl(BRAND_URL);
        assertThat(resultUrl).contains(BRAND_URL);
    }

    @Test
    public void test_buildQueryUrl_should_not_ends_with_slash() {
        String resultUrl = urlBuilder.buildQueryUrl(BRAND_URL);
        assertThat(resultUrl).doesNotEndWith("/");
    }

    @Test(expected = URISyntaxException.class)
    public void test_buildQueryUrl_should_throw_exception() {
        urlBuilder.buildQueryUrl(INCORRECT_RELATIVE_URL);
    }
}