text:
/****************************************************************************/
/*                                                                          */
/*  Module:         QstDLL.c                                                */
/*                                                                          */
/*  Description:    One of a set of modules that  implement  the  Intel(R)  */
/*                  Quiet System Technology (QST) Instrumentation Library.  */
/*                  This  library exposes a set of functions that simplify  */
/*                  support for the  enumeration  and  monitoring  of  the  */
/*                  various  sensors  and  fan  speed controllers that are  */
/*                  supported  by  QST.   This   module   implements   the  */
/*                  environment-specific  portion  of  the  library, which  */
/*                  allows it to be built  into  a  Windows  Dynamic  Link  */
/*                  Library (DLL), a Linux Shared Object (SO) file or as a  */
/*                  bindable function library for DOS.                      */
/*                                                                          */
/****************************************************************************/

/****************************************************************************/
/*                                                                          */
/*     Copyright (c) 2005-2009, Intel Corporation. All Rights Reserved.     */
/*                                                                          */
/*  Redistribution and use in source and binary  forms,  with  or  without  */
/*  modification, are permitted provided that the following conditions are  */
/*  met:                                                                    */
/*                                                                          */
/*    - Redistributions of source code must  retain  the  above  copyright  */
/*      notice, this list of conditions and the following disclaimer.       */
/*                                                                          */
/*    - Redistributions  in binary form must reproduce the above copyright  */
/*      notice, this list of conditions and the  following  disclaimer  in  */
/*      the   documentation  and/or  other  materials  provided  with  the  */
/*      distribution.                                                       */
/*                                                                          */
/*    - Neither the name  of  Intel  Corporation  nor  the  names  of  its  */
/*      contributors  may  be  used to endorse or promote products derived  */
/*      from this software without specific prior written permission.       */
/*                                                                          */
/*  DISCLAIMER: 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 MERCHANTABILITY AND  */
/*  FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN  NO  EVENT  SHALL  */
/*  INTEL  CORPORATION  OR  THE  CONTRIBUTORS  BE  LIABLE  FOR ANY DIRECT,  */
/*  INDIRECT, INCIDENTAL, 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 DAMAGE.                                             */
/*                                                                          */
/****************************************************************************/

#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>

#if defined(__WIN32__) || defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__)
#include <windows.h>
#include "RegAccess.h"
#elif defined(__SOLARIS__) || defined(__sun__) || defined(__LINUX__) || defined(__linux__)
#include "INIFile.h"
#endif

#include "QstDll.h"
#include "CritSect.h"
#include "GlobMem.h"

/****************************************************************************/
/* Variables                                                                */
/****************************************************************************/

QST_DATA_SEGMENT                *pQstSeg;

HCRITSECT                       hCritSect;
HGLOBMEM                        hGlobMem;

#if defined(__WIN32__)
   DWORD                        dwInitError;
#else
   int                          iInitErrno;
#endif

/****************************************************************************/
/* Definitions                                                              */
/****************************************************************************/

#define GLOB_MEM_ID             0xAF5C020           // Global Memory Id
#define CRIT_SECT_TYPE          0xAF5C030           // Critical Section Type

#define QST_DEF_POLLING         1000                // Default = 1000ms (1 second)

#if defined(__WIN32__)

#define QST_REG_KEY             "Software\\Intel\\QST"
#define QST_REG_POLLING         "Polling Interval"

#elif defined(__LINUX__) || defined(__SOLARIS__)

#define INI_FILE_NAME           "QST.ini"           // INI file name
#define INI_FILE_PARAG          "Instrumentation"   // Paragraph name
#define INI_FILE_PARAM          "PollingInterval"   // Parameter name
#define BUFF_SIZE               131                 // Buffer size

/****************************************************************************/
/* strupr() - Converts string to uppercase. Provided here for Linux, which  */
/* doesn't provide one.                                                     */
/****************************************************************************/

static strupr( char *pszString )
{
    for( ; *pszString; pszString++ )
    {
        if( islower( *pszString ) )
            *pszString = toupper( *pszString );
    }
}

/****************************************************************************/
/* CleanupString() - Trims whitespace and control characters from beginning */
/* and end of string and converts alphabetic characters to uppercase. We    */
/* need this function to support Linux, since we're using INI files for     */
/* persistent variable storage.                                             */
/****************************************************************************/

static void CleanupString( char *szString )
{
   int iIndex;

   // Strip off trailing spaces

   for( iIndex = strlen( szString ) - 1;
        iIndex && (isspace( szString[iIndex] ) || iscntrl( szString[iIndex] ));
        --iIndex )
   {
      szString[iIndex] = '\0';
   }

   // Strip off leading spaces

   for( iIndex = 0; isspace(szString[iIndex]); iIndex++ );

   if( iIndex )
      strcpy( szString, &szString[iIndex] );

   strupr( szString );
}

#endif  // defined(__LINUX__)

/****************************************************************************/
/* Delay() - Implements an 'n' millisecond delay. May be called with 0 as   */
/* the count, in order to implement recovery delays for slow ASICs.         */
/****************************************************************************/

static void Delay( int iMilliseconds )
{
    if( iMilliseconds )
    {

#if defined(__WIN32__)

        Sleep( iMilliseconds );

#elif defined(__LINUX__) || defined(__SOLARIS__)

        struct timespec stTime;

        stTime.tv_sec   = (time_t)(iMilliseconds / 1000);
        stTime.tv_nsec  = 1000000L * (iMilliseconds % 1000);    // 1,000,000 ns = 1 ms

        while( (nanosleep( &stTime, &stTime ) == -1) && (errno == EINTR) );

#elif defined(__MSDOS__)

#if (CLOCKS_PER_SEC != 1000)
#error clock() implementation does not support millisecond resolution!!
#endif

        clock_t tStart, tCurrent, tEnd;

        tCurrent = tStart = clock();
        tEnd = tStart + (clock_t)iMilliseconds;

        // Handle wraparound

        if( tEnd < tCurrent )
        {
          while( tCurrent )
             tCurrent = clock();
        }

        // Complete the delay

        while( tCurrent < tEnd )
            tCurrent = clock();

#else
#error Operating environment not recognized
#endif

    }
}

/****************************************************************************/
/* InitRegistryAccess() - Initializes access to DLL's registry key content  */
/****************************************************************************/

static BOOL InitRegistryAccess( BOOL bInitQstSeg )
{

#if defined(__WIN32__)

   if( !OpenRegistry( QST_REG_KEY ) )
      return( FALSE );

#endif

   if( bInitQstSeg )
   {

#if defined(__WIN32__)

      int iValue;

      if( !iReadRegistry( QST_REG_POLLING, NO_INDEX, QST_DEF_POLLING, &iValue ) )
         return( FALSE );

      pQstSeg->dwPollingInterval = (DWORD)iValue;

#elif defined(__LINUX__) || defined(__SOLARIS__)

      char szBuff[BUFF_SIZE+1], *pszBuff;

      // Get and process entry from INI file

      if( GetINIEntry( INI_FILE_NAME, INI_FILE_PARAG, INI_FILE_PARAM, szBuff, BUFF_SIZE ) )
      {
         CleanupString( szBuff );
         pQstSeg->dwPollingInterval = (int)strtol( szBuff, &pszBuff, 10 );

         if( *pszBuff == '\0' )
            return( TRUE );
      }

      // No INI file, no entry in file or entry was bad...

      pQstSeg->dwPollingInterval = QST_DEF_POLLING;
      sprintf( szBuff, "%d", pQstSeg->dwPollingInterval );

      return( PutINIEntry( INI_FILE_NAME, INI_FILE_PARAG, INI_FILE_PARAM, szBuff ) );

#else

      pQstSeg->dwPollingInterval = QST_DEF_POLLING;

#endif

   }

   return( TRUE );
}

/****************************************************************************/
/* CleanupRegistryAccess() - Cleans up access to DLL's registry key content */
/****************************************************************************/

static void CleanupRegistryAccess( void )
{

#if defined(__WIN32__)
   CloseRegistry();
#endif

}

/****************************************************************************/
/* UpdatePollingInterval() - Updates Polling Interval value in registry     */
/****************************************************************************/

BOOL UpdatePollingInterval( DWORD dwInterval )
{

#if defined(__WIN32__)

   if( !iWriteRegistry( QST_REG_POLLING, NO_INDEX, (int)dwInterval ) )
      return( FALSE );

#elif defined(__LINUX__) || defined(__SOLARIS__)

   char szBuff[16];

   sprintf( szBuff, "%d", dwInterval );

   if( !PutINIEntry( INI_FILE_NAME, INI_FILE_PARAG, INI_FILE_PARAM, szBuff ) )
      return( FALSE );

#endif

   pQstSeg->dwPollingInterval = dwInterval;
   time( &pQstSeg->tTimePollingIntervalChanged );
   return( TRUE );
}

/****************************************************************************/
/* EnterCriticalSection() - Initiates critical section                      */
/****************************************************************************/

BOOL BeginCriticalSection( void )
{
   return( EnterCritSect( hCritSect ) );
}

/****************************************************************************/
/* EndCriticalSection - Terminates critical section                         */
/****************************************************************************/

void EndCriticalSection( void )
{
   LeaveCritSect( hCritSect );
}

/****************************************************************************/
/* InitSharedMemoryPrimary() - Performs initialization for primary user     */
/* (creator) of the shared memory segment.                                  */
/****************************************************************************/

static BOOL InitSharedMemory( BOOL bCreator )
{
   // Clear its contents (sets bInitComplete to FALSE)

   if( bCreator )
       memset( pQstSeg, 0, sizeof(QST_DATA_SEGMENT) );

   // Do full initializaton for QST Subsystem access

   if( InitializeQst( bCreator ) )
   {
      // Do full initialization for Registry access

      if( InitRegistryAccess( bCreator ) )
      {
         // Do initialization for Critical Section support

         hCritSect = CreateCritSect( CRIT_SECT_TYPE, FALSE );

         if( hCritSect )
         {
            // We're successfully initialized!

            if( bCreator )
               pQstSeg->bInitComplete = TRUE;
            else
               while( !pQstSeg->bInitComplete )
                  Delay( 5 );

            return( TRUE );
         }

         // Failed, start unwinding

         CloseCritSect( hCritSect );
      }

      CleanupRegistryAccess();
   }

   CleanupQst();
   return( FALSE );
}

/****************************************************************************/
/* QstInstInitialize() - Initializes global memory segment access and       */
/* interface to QST Subsystem.                                              */
/****************************************************************************/

#if defined(__WIN32__) || defined(__LINUX__) || defined(__SOLARIS__)
   static
#endif

BOOL QstInstInitialize( void )
{
   // Start with attempt to lookup existing segment

   BOOL bCreator = FALSE;
   hGlobMem      = LookupGlobMem( GLOB_MEM_ID, sizeof(QST_DATA_SEGMENT) );

   // If that failed, we're creator; attempt creation

   if( !hGlobMem )
   {
       bCreator = TRUE;
       hGlobMem = CreateGlobMem( GLOB_MEM_ID, sizeof(QST_DATA_SEGMENT), TRUE );
   }

   if( hGlobMem )
   {
      // We have segment, map it into address space

      pQstSeg = (QST_DATA_SEGMENT *)MapGlobMem( hGlobMem );

      if( pQstSeg )
      {
         // Now initialize the segment as appropriate

         if( InitSharedMemory( bCreator ) )
            return( TRUE );

         // Failed, start unwinding

         UnmapGlobMem( pQstSeg );
      }

      CloseGlobMem( hGlobMem );
   }

   // If we get to here, initialization failed. Save error info for later

#if defined(__WIN32__)
   dwInitError = GetLastError();
#else
   iInitErrno = errno;
#endif

   pQstSeg = NULL;
   return( FALSE );
}

/****************************************************************************/
/* QstInstCleanup() - Cleans up global memory segment access and interface  */
/* to QST Subsystem.                                                        */
/****************************************************************************/

#if defined(__WIN32__) || defined(__LINUX__) || defined(__SOLARIS__)
   static
#endif

void QstInstCleanup( void )
{
   CloseCritSect( hCritSect );
   CleanupRegistryAccess();
   CleanupQst();

   UnmapGlobMem( pQstSeg );
   CloseGlobMem( hGlobMem );
}

#if defined(__WIN32__)
/****************************************************************************/
/* DllMain() - Handles Processes attaching to and detaching from DLL        */
/****************************************************************************/

BOOL WINAPI DllMain( HANDLE hModule, DWORD dwReason, LPVOID pvReserved )
{
   switch( dwReason )
   {
   case DLL_PROCESS_ATTACH:

      if( !QstInstInitialize() )
         return( FALSE );

      break;

   case DLL_PROCESS_DETACH:

      QstInstCleanup();
      break;
   }

   return( TRUE );

   UNREFERENCED_PARAMETER( hModule );
   UNREFERENCED_PARAMETER( pvReserved );
}

#elif defined(__LINUX__) || defined(__SOLARIS__)
/****************************************************************************/
/* Bind main init/cleanup functions for load-/unload-time execution         */
/****************************************************************************/

static void ModuleInit( void ) { QstInstInitialize(); }

#ifdef USE_CTORS
   static void (*const init_array [])( void ) __attribute__ ((section (".ctors")))      = { ModuleInit,     };
   static void (*const fini_array [])( void ) __attribute__ ((section (".dtors")))      = { QstInstCleanup, };
#else
   static void (*const init_array [])( void ) __attribute__ ((section (".init_array"))) = { ModuleInit,     };
   static void (*const fini_array [])( void ) __attribute__ ((section (".fini_array"))) = { QstInstCleanup, };
#endif

#endif


text:
module Droom
  class EnquiriesController < Droom::EngineController
    respond_to :html, :js
    layout :no_layout_if_pjax

    skip_before_action :authenticate_user!, only: [:new, :create, :show]
    skip_before_action :set_exception_context
    skip_before_action :require_password, only: [:new, :create, :show]
    skip_before_action :note_current_user, only: [:new, :create, :show]

    load_and_authorize_resource

    def index
      limit = params[:limit].presence || 5
      @enquiries = paginated(@enquiries, limit)
      respond_with @enquiries
    end

    def show
      respond_with @enquiry
    end

    def new
      @enquiry.request = request
      respond_with @enquiry
    end

    def test
      @enquiry = Droom::Enquiry.new
      @enquiry.request = request
      respond_with @enquiry
    end

    def edit
      respond_with @enquiry
    end

    def update
      @enquiry.update_attributes(enquiry_params)
      respond_with @enquiry
    end

    def create
      @enquiry.request = request
      if @enquiry.update_attributes(enquiry_params)
        render
      else
        render template: 'edit'
      end
    end

    def destroy
      @enquiry.destroy
      head :ok
    end

  protected

    def enquiry_params
      params.require(:enquiry).permit(:name, :email, :message, :closed, :robot)
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You 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.
--><!-- The contents of this file will be loaded for each web application --><Context>

    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <!-- Uncomment this to enable Comet connection tacking (provides events
         on session expiration as well as webapp lifecycle) -->
    <!--
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    -->
 <Resource auth="Container" brokerName="LocalActiveMQBroker" brokerURL="tcp://localhost:61616" description="JMS Connection Factory" factory="org.apache.activemq.jndi.JNDIReferenceFactory" name="queue/connectionFactory" type="org.apache.activemq.ActiveMQConnectionFactory"/>

<Resource auth="Container" description="My Queue" factory="org.apache.activemq.jndi.JNDIReferenceFactory" name="queue/queue0" physicalName="TomcatQueue" type="org.apache.activemq.command.ActiveMQQueue"/>
</Context>


text:
// ***********************************************************************
// Copyright (c) 2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************

using System;
using System.Collections.Generic;
using System.Threading;

namespace NUnit.Framework.Internal.Commands
{
    using Interfaces;

    /// <summary>
    /// TestActionCommand runs the BeforeTest actions for a test,
    /// then runs the test and finally runs the AfterTestActions.
    /// </summary>
    public class TestActionCommand : DelegatingTestCommand
    {
        private IList<TestActionItem> _actions = new List<TestActionItem>();

        /// <summary>
        /// Initializes a new instance of the <see cref="TestActionCommand"/> class.
        /// </summary>
        /// <param name="innerCommand">The inner command.</param>
        public TestActionCommand(TestCommand innerCommand)
            : base(innerCommand)
        {
            Guard.ArgumentValid(innerCommand.Test is TestMethod, "TestActionCommand may only apply to a TestMethod", "innerCommand");
        }

        /// <summary>
        /// Runs the test, saving a TestResult in the supplied TestExecutionContext.
        /// </summary>
        /// <param name="context">The context in which the test should run.</param>
        /// <returns>A TestResult</returns>
        public override TestResult Execute(TestExecutionContext context)
        {
            if (Test.Fixture == null)
                Test.Fixture = context.TestObject;

            // In the current implementation, upstream actions only apply to tests. If that should change in the future,
            // then actions would have to be tested for here. For now we simply assert it in Debug. We allow
            // ActionTargets.Default, because it is passed down by ParameterizedMethodSuite.
            foreach (ITestAction action in context.UpstreamActions)
            {
                System.Diagnostics.Debug.Assert(
                    action.Targets == ActionTargets.Default || (action.Targets & ActionTargets.Test) == ActionTargets.Test,
                    "Invalid target on upstream action: " + action.Targets.ToString());

                _actions.Add(new TestActionItem(action));
            }

            foreach (ITestAction action in ActionsHelper.GetActionsFromAttributeProvider(((TestMethod)Test).Method.MethodInfo))
                if (action.Targets == ActionTargets.Default || (action.Targets & ActionTargets.Test) == ActionTargets.Test)
                    _actions.Add(new TestActionItem(action));

            try
            {
                for (int i = 0; i < _actions.Count; i++)
                    _actions[i].BeforeTest(Test);

                context.CurrentResult = innerCommand.Execute(context);
            }
            catch (Exception ex)
            {
#if !NETCF && !SILVERLIGHT && !PORTABLE
                if (ex is ThreadAbortException)
                    Thread.ResetAbort();
#endif
                context.CurrentResult.RecordException(ex);
            }
            finally
            {
                if (context.ExecutionStatus != TestExecutionStatus.AbortRequested)
                    for (int i = _actions.Count - 1; i >= 0; i--)
                        _actions[i].AfterTest(Test);
            }

            return context.CurrentResult;
        }
    }
}


text:
import numpy as np
from enum import Enum
import heapq

class CustomerTypes(Enum):
    Innovator = 99
    Early_Adopter = 96.5
    Early_Majority = 83
    Late_Majority = 49
    Laggard = 15

class Product(object):

    def __init__(self):
        self.version = 0
        self.price = np.infinite
        self.innovation_points = 0.
        self.quality = 0.

    def change_params(self, params, bump_version=True):
        if bump_version:
            self.version += 1
        self.price = params.get('price', np.infinite)
        self.innovation_points = params.get('innovation', 0.)
        self.quality = params.get('quality', 0.)

class Company(object):
    def __init__(self, name, market__share):
        self.name = name
        self.market_share = market__share
        self.product = None
        self.type = None
        self.competitive_advantage = 0.
        self.industry_attractiveness = 0.
        self.environmental_stability = 0.
        self.financial_strength = 0.

        self.history = []

        self.customer_loyalty = 3
        self.space_params = {
            'competitive_advantage': {
                'market_share': 3,
                'product_quality': 3,
                'product_life_cycle': 3,  # late to early
                'product_replacement_cycle': 3, # variable to fixed
                'customer_loyalty': self.customer_loyalty,
                'know_how': 3,
                'vertical_integration': 3,
            },
            'industry_attractiveness': {
                'growth_potential': 3,
                'profit_potential': 3,
                'financial_stability': 3,
                'know_how': 3,
                'resource_utilization': 3,
                'capital_intensity': 3,
                'ease_of_entry': 3,
                'capacity_utilization': 3,
            },
            'environmental_stability': {
                'technological_changes': 3,
                'rate_of_inflation': 3,
                'demand_variability': 3,
                'barriers_to_entry': 3,
                'competitive_pressure': 3,
                'price_elasticity_of_demand': 3,
                'pressure_from_substitutes': 3
            },
            'financial_strength': {
                'ROI': 3,
                'leverage': 3,
                'liquidity': 3,
                'required_to_available_capital': 3,
                'cash_flow': 3,
                'ease_of_exit': 3,
                'risk_doing_business': 3, # much to little
                'inventory_turnover': 3,
            }
        }

    def set_space_params(self, args=None):
        # if args exist then add copy them to space params
        if args:
            for k in args:
                if self.space_params.get(k, None):
                    for k2 in args[k]:
                        if self.space_params[k].get(k2, None):
                            self.space_params[k][k2] = args[k][k2]
        # calculate the SPACE parameters
        for key in self.space_params:
            category_sum = 0
            for i, category in enumerate(self.space_params[key]):
                category_sum += self.space_params[key][category]
            setattr(self, key,  float(category_sum) / float(i + 1))

    def set_space_values(self, ca, ia, es, fs):
        self.competitive_advantage = ca
        self.industry_attractiveness = ia
        self.environmental_stability = es
        self.financial_strength = fs
        self._define_quadrant()

    def _define_quadrant(self):
        # TODO do this
        attrs = [self.competitive_advantage,
                 self.industry_attractiveness,
                 self.environmental_stability,
                 self.financial_strength]
        maxes = heapq.nlargest(2, attrs)
        ind1 = attrs.index(maxes[0])
        ind2 = attrs.index(maxes[2])

    def make_product(self, params):
        self.product = Product()
        self.product.change_params(params)

    def make_move(self):
        pass

class Customer(object):

    def __init__(self):
        self.type = None
        self.sensitivity = {
            'price': None,
            'quality': None,
            'features': None
        }
        self.product = None

        self._define_type()

    def decide_to_buy(self, companies):
        # TODO make parameters to buy
        scores = []
        for company in companies:
            temp_product = company.product
            score = 0.  # decided by loyalty, price , quality etc
            scores.append(score)
        product = companies[scores.index(max(scores))].product

    def _define_type(self):
        """
        Use diffusion of innovations model to decide the customer type
        """
        sigma = 1
        mean = 0
        r = np.random.normal(mean, sigma)
        if mean <= r < sigma:
            self.type = CustomerTypes.Late_Majority
        if r >= sigma:
            self.type = CustomerTypes.Laggard
        if -sigma <= r < mean:
            self.type = CustomerTypes.Early_Majority
        if -2 * sigma <= r < -sigma:
            self.type = CustomerTypes.Early_Adopter
        if r <= - 2 * sigma:
            self.type = CustomerTypes.Innovator

class Market(object):
    def __init__(self, args):
        self.growth_rate = args.get('growth_rate', 0.)
        self.value = args.get('market_value', 0.)
        self.customers = []

    def add_customers(self, n_customers=100000):
        """
        Adds customers to the market
        :param n_customers: How many to add to the market
        """
        for i in xrange(n_customers):
            cust = Customer()
            self.customers.append(cust)

    def grow(self):
        """
        Grows the market by adding more customers.
        """
        self.add_customers(int(len(self.customers) * self.growth_rate))

# class Strategy(object):
#
#     def __init__(self, product, params):
#         pass

class TheGame(object):

    def __init__(self, market, companies):
        self.market = market
        self.companies = companies[1:]
        self.ours = companies[0]

    def play(self):
        pass


text:
const ActionHandler = function() {
  const self = {};

  const actionHandlers = {};

  self.register = function(actionType, handler) {
    actionHandlers[actionType] = handler;
  };

  self.execute = function(action) {
    const handler = actionHandlers[action.type];
    if (handler) {
      handler(action);
    }
  };

  return self;
};

module.exports = ActionHandler;


text:
define(function (require, exports, module) {
    'use strict';

    var _ = require('underscore');
    var util = require('../util');
    var config = require('../config');
    var memory = require('fc-storage/memory');
    var browser = require('fc-core/browser');
    var recorder = require('../recorder');
    var logger = require('../logger');

    exports.measure = function () {
        var watchPatternList = config.resourceWatchingList || [];
        if (!window.PerformanceResourceTiming || !util.getEntries) {
            return;
        }
        var list = _.filter(
            util.getEntries.call(window.performance),
            function (resource) {
                if (!(resource instanceof window.PerformanceResourceTiming)) {
                    return false;
                }
                return _.some(watchPatternList, function (patt) {
                    var type = Object.prototype.toString.call(patt);
                    switch (type) {
                        case '[object RegExp]':
                            return patt.test(resource.name);
                        case '[object String]':
                            return patt === resource.name;
                        default:
                            return false;
                    }
                });
            }
        );
        // 没有资源在监控范围内时不处理
        if (list.length === 0) {
            return;
        }

        // 全部资源都命中缓存时才认为缓存命中
        var isCached = _.every(list, function (item) {
            return item.connectStart === item.fetchStart;
        });

        // 缓存计算过的性能,以备不时之需
        memory.updateItem(config.storageKey, {
            performance: {
                resource: {
                    measure: list
                }
            }
        });

        var item = memory.getItem(config.storageKey);
        var staticItem = item && item.performance && item.performance.static;
        var staticData = staticItem && staticItem.data;
        var toSend = {
            target: 'performance_resource_cached',
            isCached: isCached,
            performanceId: config.performanceId,
            detail: list,
            browserData: browser.getBrowserData(),
            staticData: staticData.log,
            pageStabled: recorder.stable ? 1 : 0
        };
        if (recorder.pageInactived) {
            toSend.pageInactived = recorder.pageInactived;
            toSend.inactivedDuration = recorder.inactivedDuration;
        }
        logger.log(toSend);
        return exports;
    };

    return module.exports = exports;
});


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

<TITLE>
Uses of Package org.jgraph (JGraph v5.12.3.1 API Specification)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

JGraph
v5.12.3.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
org.jgraph

Packages that use org.jgraph

org.jgraph
JGraph's topmost package which contains the JGraph class.

org.jgraph.graph
Graphs are made up of a number of classes and interfaces defined in their own
package - the jgraph.graph package.

org.jgraph.plaf
Contains the GraphUI class which extends the Swing ComponentUI class.

org.jgraph.plaf.basic
Contains the BasicGraphUI, which is GraphUI's default implementation.

org.jgraph.util

Classes in org.jgraph used by org.jgraph

JGraph.EmptySelectionModel

          EmptySelectionModel is a GraphSelectionModel
 that does not allow anything to be selected.

JGraph.GraphSelectionRedirector

          Handles creating a new GraphSelectionEvent with the
 JGraph as the source and passing it off to all the
 listeners.

Classes in org.jgraph used by org.jgraph.graph

JGraph

          A control that displays a network of related objects using the well-known
 paradigm of a graph.

Classes in org.jgraph used by org.jgraph.plaf

JGraph

          A control that displays a network of related objects using the well-known
 paradigm of a graph.

Classes in org.jgraph used by org.jgraph.plaf.basic

JGraph

          A control that displays a network of related objects using the well-known
 paradigm of a graph.

Classes in org.jgraph used by org.jgraph.util

JGraph

          A control that displays a network of related objects using the well-known
 paradigm of a graph.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

JGraph
v5.12.3.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright (C) 2001-2008 Gaudenz Alder. All rights reserved.


text:
from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_UpdateProjectDialogBase(object):
    def setupUi(self, UpdateProjectDialogBase):
        UpdateProjectDialogBase.setObjectName(_fromUtf8("UpdateProjectDialogBase"))
        UpdateProjectDialogBase.resize(228, 86)
        self.buttonBox = QtGui.QDialogButtonBox(UpdateProjectDialogBase)
        self.buttonBox.setGeometry(QtCore.QRect(20, 50, 201, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
        self.splitter = QtGui.QSplitter(UpdateProjectDialogBase)
        self.splitter.setGeometry(QtCore.QRect(20, 10, 196, 20))
        self.splitter.setOrientation(QtCore.Qt.Horizontal)
        self.splitter.setObjectName(_fromUtf8("splitter"))
        self.existingProjectsCombo = QtGui.QComboBox(self.splitter)
        self.existingProjectsCombo.setObjectName(_fromUtf8("existingProjectsCombo"))

        self.retranslateUi(UpdateProjectDialogBase)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), UpdateProjectDialogBase.accept)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), UpdateProjectDialogBase.reject)
        QtCore.QMetaObject.connectSlotsByName(UpdateProjectDialogBase)

    def retranslateUi(self, UpdateProjectDialogBase):
        UpdateProjectDialogBase.setWindowTitle(_translate("UpdateProjectDialogBase", "Update project", None))


text:
package org.jglue.totorom;

import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Predicate;
import com.tinkerpop.gremlin.Tokens.T;
import com.tinkerpop.pipes.Pipe;
import com.tinkerpop.pipes.transform.TransformPipe.Order;
import com.tinkerpop.pipes.util.structures.Table;
import com.tinkerpop.pipes.util.structures.Tree;

abstract class EdgeTraversalImpl extends TraversalBase implements EdgeTraversal {

	@Override
	public TEdge next() {

		return graph().frameElement((Edge) pipeline().next(), TEdge.class);
	}

	@Override
	public List toList() {
		return toList(TEdge.class);
	}

	@Override
	public Set toSet() {
		return toSet(TEdge.class);
	}

	@Override
	public EdgeTraversal table() {
		return (EdgeTraversal) super.table();
	}

	@Override
	public EdgeTraversal table(TraversalFunction... columnFunctions) {

		return (EdgeTraversal) super.table(columnFunctions);
	}

	@Override
	public EdgeTraversal table(Table table) {

		return (EdgeTraversal) super.table(table);
	}

	@Override
	public EdgeTraversal table(Table table, Collection stepNames, TraversalFunction... columnFunctions) {

		return (EdgeTraversal) super.table(table, stepNames, columnFunctions);
	}

	@Override
	public EdgeTraversal table(Table table, TraversalFunction... columnFunctions) {
		return (EdgeTraversal) super.table(table, columnFunctions);
	}

	@Override
	public EdgeTraversal tree(Tree tree) {
		return (EdgeTraversal) super.tree(tree);
	}

	@Override
	public EdgeTraversal store() {
		return (EdgeTraversal) super.store();
	}

	@Override
	public EdgeTraversal store(Collection storage) {
		return (EdgeTraversal) super.store(storage);
	}

	@Override
	public EdgeTraversal store(Collection storage, TraversalFunction storageFunction) {
		return (EdgeTraversal) super.store(storage, storageFunction);
	}

	@Override
	public EdgeTraversal store(TraversalFunction storageFunction) {
		return (EdgeTraversal) super.store(storageFunction);
	}

	@Override
	public EdgeTraversal groupCount() {
		return (EdgeTraversal) super.groupCount();
	}

	@Override
	public EdgeTraversal groupCount(Map map) {
		return (EdgeTraversal) super.groupCount(map);
	}

	@Override
	public EdgeTraversal groupCount(Map map, TraversalFunction keyFunction) {
		return (EdgeTraversal) super.groupCount(map, keyFunction);
	}

	@Override
	public EdgeTraversal groupCount(Map map, TraversalFunction keyFunction, TraversalFunction valueFunction) {
		return (EdgeTraversal) super.groupCount(map, keyFunction, valueFunction);
	}

	@Override
	public EdgeTraversal groupCount(TraversalFunction keyFunction) {
		return (EdgeTraversal) super.groupCount(keyFunction);
	}

	@Override
	public EdgeTraversal groupCount(TraversalFunction keyFunction, TraversalFunction valueFunction) {
		return (EdgeTraversal) super.groupCount(keyFunction, valueFunction);
	}

	@Override
	public EdgeTraversal groupBy(TraversalFunction keyFunction, TraversalFunction valueFunction, TraversalFunction reduceFunction) {
		return (EdgeTraversal) super.groupBy(keyFunction, valueFunction, reduceFunction);
	}

	@Override
	public EdgeTraversal groupBy(TraversalFunction keyFunction, TraversalFunction valueFunction) {

		return (EdgeTraversal) super.groupBy(keyFunction, valueFunction);
	}

	@Override
	public EdgeTraversal groupBy(Map reduceMap, TraversalFunction keyFunction, TraversalFunction valueFunction,
			TraversalFunction reduceFunction) {
		return (EdgeTraversal) super.groupBy(reduceMap, keyFunction, valueFunction, reduceFunction);
	}

	@Override
	public EdgeTraversal groupBy(Map map, TraversalFunction keyFunction, TraversalFunction valueFunction) {
		return (EdgeTraversal) super.groupBy(map, keyFunction, valueFunction);
	}

	@Override
	public EdgeTraversal has(String key) {
		return (EdgeTraversal) super.has(key);
	}

	@Override
	public EdgeTraversal has(String key, Object value) {
		return (EdgeTraversal) super.has(key, value);
	}

	@Override
	public EdgeTraversal has(String key, Predicate predicate, Object value) {
		return (EdgeTraversal) super.has(key, predicate, value);
	}

	@Override
	public EdgeTraversal has(String key, com.tinkerpop.gremlin.Tokens.T compareToken, Object value) {
		return (EdgeTraversal) super.has(key, compareToken, value);
	}

	@Override
	public EdgeTraversal hasNot(String key) {
		return (EdgeTraversal) super.hasNot(key);
	}

	@Override
	public EdgeTraversal hasNot(String key, Object value) {
		return (EdgeTraversal) super.hasNot(key, value);
	}

	@Override
	public EdgeTraversal as(String name) {
		return (EdgeTraversal) super.as(name);
	}

	@Override
	public EdgeTraversal identity() {

		return (EdgeTraversal) super.identity();
	}

	@Override
	public EdgeTraversal interval(String key, Comparable startValue, Comparable endValue) {
		return (EdgeTraversal) super.interval(key, startValue, endValue);
	}

	@Override
	public VertexTraversal inV() {
		pipeline().inV();
		return castToVertices();
	}

	@Override
	public VertexTraversal outV() {
		pipeline().outV();
		return castToVertices();
	}

	@Override
	public VertexTraversal bothV() {
		pipeline().bothV();
		return castToVertices();
	}

	@Override
	public FramedEdge next(Class kind) {
		return (FramedEdge) graph().frameElement((Element) pipeline().next(), kind);
	}

	@Override
	public List next(int amount, final Class kind) {
		return Lists.transform(pipeline().next(amount), new Function() {

			public Object apply(Object e) {
				return graph().frameElement((Element) e, kind);
			}
		});
	}

	@Override
	public Iterable frame(final Class kind) {
		return Iterables.transform(pipeline(), new Function() {

			public Object apply(Object e) {
				return graph().frameElement((Element) e, kind);
			}
		});
	}

	@Override
	public List<T> toList(final Class kind) {
		return Lists.transform(pipeline().toList(), new Function() {

			public Object apply(Object e) {
				return graph().frameElement((Element) e, kind);
			}
		});
	}

	@Override
	public Set<T> toSet(final Class kind) {
		return Sets.newHashSet(toList(kind));
	}

	@Override
	public Traversal label() {
		pipeline().label();
		return castToTraversal();
	}

	@Override
	public EdgeTraversal filter(TraversalFunction filterFunction) {
		return (EdgeTraversal) super.filter(filterFunction);

	}

	@Override
	public EdgeTraversal aggregate() {
		return (EdgeTraversal) super.aggregate();

	}

	@Override
	public EdgeTraversal aggregate(Collection aggregate) {
		return (EdgeTraversal) super.aggregate(aggregate);

	}

	@Override
	public EdgeTraversal aggregate(Collection aggregate, TraversalFunction aggregateFunction) {
		return (EdgeTraversal) super.aggregate(aggregate, aggregateFunction);

	}

	@Override
	public EdgeTraversal aggregate(TraversalFunction aggregateFunction) {
		return (EdgeTraversal) super.aggregate(aggregateFunction);

	}

	@Override
	public EdgeTraversal and(TraversalFunction... pipes) {
		Collection<Pipe> extractedPipes = Collections2.transform(Arrays.asList(pipes), new Function<TraversalFunction, Pipe>() {

			@Override
			public Pipe apply(TraversalFunction input) {
				return ((TraversalBase) input.compute(new TEdge())).pipeline();
			}
		});
		pipeline().and(extractedPipes.toArray(new Pipe[extractedPipes.size()]));
		return this;
	}

	@Override
	public EdgeTraversal or(TraversalFunction... pipes) {
		Collection<Pipe> extractedPipes = Collections2.transform(Arrays.asList(pipes), new Function<TraversalFunction, Pipe>() {

			@Override
			public Pipe apply(TraversalFunction input) {
				return ((TraversalBase) input.compute(new TEdge())).pipeline();
			}
		});
		pipeline().or(extractedPipes.toArray(new Pipe[extractedPipes.size()]));
		return this;
	}

	@Override
	public EdgeTraversal sideEffect(SideEffectFunction sideEffectFunction) {
		return (EdgeTraversal) super.sideEffect(sideEffectFunction);
	}

	@Override
	public EdgeTraversal random(double bias) {

		return (EdgeTraversal) super.random(bias);
	}

	@Override
	public EdgeTraversal dedup(TraversalFunction dedupFunction) {
		return (EdgeTraversal) super.dedup(dedupFunction);
	}

	@Override
	public EdgeTraversal except(String... namedSteps) {

		return (EdgeTraversal) super.except(namedSteps);
	}

	@Override
	public EdgeTraversal except(Iterable collection) {
		return (EdgeTraversal) super.except(Lists.newArrayList(collection));
	}

	@Override
	public EdgeTraversal range(int low, int high) {
		return (EdgeTraversal) super.range(low, high);
	}

	@Override
	public EdgeTraversal order() {
		return (EdgeTraversal) super.order();
	}

	@Override
	public EdgeTraversal order(Order order) {
		return (EdgeTraversal) super.order(order);
	}

	@Override
	public EdgeTraversal order(Comparator compareFunction) {
		return (EdgeTraversal) super.order(compareFunction);
	}

	@Override
	public EdgeTraversal order(T order) {
		return (EdgeTraversal) super.order(order);
	}

	@Override
	public EdgeTraversal dedup() {

		return (EdgeTraversal) super.dedup();
	}

	@Override
	public EdgeTraversal retain(String... namedSteps) {
		return (EdgeTraversal) super.retain(namedSteps);
	}

	@Override
	public EdgeTraversal simplePath() {
		return (EdgeTraversal) super.simplePath();
	}

	@Override
	public EdgeTraversal memoize(String namedStep) {
		return (EdgeTraversal) super.memoize(namedStep);

	}

	@Override
	public EdgeTraversal memoize(String namedStep, Map map) {
		return (EdgeTraversal) super.memoize(namedStep, map);

	}

	@Override
	public Collection fill(Collection collection) {
		return super.fill(collection);
	}

	@Override
	public Collection fill(Collection collection, Class clazz) {

		return pipeline().fill(new FramingCollection(collection, graph(), clazz));
	}

	public java.util.Iterator<TEdge> iterator() {
		return Iterators.transform(pipeline(), new Function() {

			public Object apply(Object e) {
				return graph().frameElement((Element) e, TEdge.class);
			}
		});
	};

	@Override
	public EdgeTraversal gatherScatter() {

		return (EdgeTraversal) super.gatherScatter();
	}

	@Override
	public EdgeTraversal divert(SideEffectFunction sideEffect) {
		return (EdgeTraversal) super.divert(sideEffect);
	}

	@Override
	public EdgeTraversal retain(FramedEdge... edges) {

		return (EdgeTraversal) super.retain(Arrays.asList(edges));
	}

	@Override
	public EdgeTraversal shuffle() {
		return (EdgeTraversal) super.shuffle();
	}

	@Override
	public EdgeTraversal except(FramedEdge... edges) {
		return (EdgeTraversal) super.retain(Arrays.asList(edges));
	}

	@Override
	public EdgeTraversal retain(Iterable collection) {

		return (EdgeTraversal) super.retain(Lists.newArrayList(collection));
	}

	@Override
	public EdgeTraversal mark() {

		return (EdgeTraversal) super.mark();
	}

	@Override
	public void removeAll() {
		pipeline().removeAll();
	}

	@Override
	public SplitTraversal copySplit(TraversalFunction... traversals) {
		Collection<Pipe> extractedPipes = Collections2.transform(Arrays.asList(traversals),
				new Function<TraversalFunction, Pipe>() {

					@Override
					public Pipe apply(TraversalFunction input) {
						return ((TraversalBase) input.compute(new TEdge())).pipeline();
					}
				});
		pipeline().copySplit(extractedPipes.toArray(new Pipe[extractedPipes.size()]));
		return castToSplit();
	}

	@Override
	public EdgeTraversal tree() {

		return (EdgeTraversal) super.tree();
	}

	@Override
	public EdgeTraversal loop(TraversalFunction input) {
		return (EdgeTraversal) super.loop(input);
	}

	@Override
	public EdgeTraversal loop(TraversalFunction input, int depth) {
		return (EdgeTraversal) super.loop(input, depth);
	}

	@Override
	public EdgeTraversal limit(int limit) {
		return (EdgeTraversal) super.limit(limit);
	}
}


text:
<?php

namespace Oneup\UploaderBundle\Controller;

use Oneup\UploaderBundle\Uploader\File\FileInterface;
use Oneup\UploaderBundle\Uploader\File\FilesystemFile;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\FileBag;

use Oneup\UploaderBundle\UploadEvents;
use Oneup\UploaderBundle\Event\PreUploadEvent;
use Oneup\UploaderBundle\Event\PostPersistEvent;
use Oneup\UploaderBundle\Event\PostUploadEvent;
use Oneup\UploaderBundle\Event\ValidationEvent;
use Oneup\UploaderBundle\Uploader\Storage\StorageInterface;
use Oneup\UploaderBundle\Uploader\Response\ResponseInterface;
use Oneup\UploaderBundle\Uploader\ErrorHandler\ErrorHandlerInterface;

abstract class AbstractController
{
    protected $container;
    protected $storage;
    protected $config;
    protected $type;

    public function __construct(ContainerInterface $container, StorageInterface $storage, ErrorHandlerInterface $errorHandler, array $config, $type)
    {
        $this->errorHandler = $errorHandler;
        $this->container = $container;
        $this->storage = $storage;
        $this->config = $config;
        $this->type = $type;
    }

    abstract public function upload();

    public function progress()
    {
        $request = $this->container->get('request');
        $session = $this->container->get('session');

        $prefix = ini_get('session.upload_progress.prefix');
        $name   = ini_get('session.upload_progress.name');

        // assemble session key
        // ref: http://php.net/manual/en/session.upload-progress.php
        $key = sprintf('%s.%s', $prefix, $request->get($name));
        $value = $session->get($key);

        return new JsonResponse($value);
    }

    public function cancel()
    {
        $request = $this->container->get('request');
        $session = $this->container->get('session');

        $prefix = ini_get('session.upload_progress.prefix');
        $name   = ini_get('session.upload_progress.name');

        $key = sprintf('%s.%s', $prefix, $request->get($name));

        $progress = $session->get($key);
        $progress['cancel_upload'] = false;

        $session->set($key, $progress);

        return new JsonResponse(true);
    }

    /**
     *  Flattens a given filebag to extract all files.
     *
     *  @param bag The filebag to use
     *  @return array An array of files
     */
    protected function getFiles(FileBag $bag)
    {
        $files = array();
        $fileBag = $bag->all();
        $fileIterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($fileBag), \RecursiveIteratorIterator::SELF_FIRST);

        foreach ($fileIterator as $file) {
            if (is_array($file)) {
                continue;
            }

            $files[] = $file;
        }

        return $files;
    }

    /**
     *  This internal function handles the actual upload process
     *  and will most likely be called from the upload()
     *  function in the implemented Controller.
     *
     *  Note: The return value differs when
     *
     *  @param The file to upload
     *  @param response A response object.
     *  @param request The request object.
     */
    protected function handleUpload($file, ResponseInterface $response, Request $request)
    {
        // wrap the file if it is not done yet which can only happen
        // if it wasn't a chunked upload, in which case it is definitely
        // on the local filesystem.
        if (!($file instanceof FileInterface)) {
            $file = new FilesystemFile($file);
        }
        $this->validate($file);

        $this->dispatchPreUploadEvent($file, $response, $request);

        // no error happend, proceed
        $namer = $this->container->get($this->config['namer']);
        $name  = $namer->name($file);

        // perform the real upload
        $uploaded = $this->storage->upload($file, $name);

        $this->dispatchPostEvents($uploaded, $response, $request);
    }

    /**
     *  This function is a helper function which dispatches pre upload event
     *
     *  @param uploaded The uploaded file.
     *  @param response A response object.
     *  @param request The request object.
     */
    protected function dispatchPreUploadEvent(FileInterface $uploaded, ResponseInterface $response, Request $request)
    {
        $dispatcher = $this->container->get('event_dispatcher');

        // dispatch pre upload event (both the specific and the general)
        $postUploadEvent = new PreUploadEvent($uploaded, $response, $request, $this->type, $this->config);
        $dispatcher->dispatch(UploadEvents::PRE_UPLOAD, $postUploadEvent);
        $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::PRE_UPLOAD, $this->type), $postUploadEvent);
    }

    /**
     *  This function is a helper function which dispatches post upload
     *  and post persist events.
     *
     *  @param uploaded The uploaded file.
     *  @param response A response object.
     *  @param request The request object.
     */
    protected function dispatchPostEvents($uploaded, ResponseInterface $response, Request $request)
    {
        $dispatcher = $this->container->get('event_dispatcher');

        // dispatch post upload event (both the specific and the general)
        $postUploadEvent = new PostUploadEvent($uploaded, $response, $request, $this->type, $this->config);
        $dispatcher->dispatch(UploadEvents::POST_UPLOAD, $postUploadEvent);
        $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::POST_UPLOAD, $this->type), $postUploadEvent);

        if (!$this->config['use_orphanage']) {
            // dispatch post persist event (both the specific and the general)
            $postPersistEvent = new PostPersistEvent($uploaded, $response, $request, $this->type, $this->config);
            $dispatcher->dispatch(UploadEvents::POST_PERSIST, $postPersistEvent);
            $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::POST_PERSIST, $this->type), $postPersistEvent);
        }
    }

    protected function validate(FileInterface $file)
    {
        $dispatcher = $this->container->get('event_dispatcher');
        $event = new ValidationEvent($file, $this->container->get('request'), $this->config, $this->type);

        $dispatcher->dispatch(UploadEvents::VALIDATION, $event);
    }

    /**
     * Creates and returns a JsonResponse with the given data.
     *
     * On top of that, if the client does not support the application/json type,
     * then the content type of the response will be set to text/plain instead.
     *
     * @param mixed $data
     *
     * @return JsonResponse
     */
    protected function createSupportedJsonResponse($data)
    {
        $request = $this->container->get('request');
        $response = new JsonResponse($data);
        $response->headers->set('Vary', 'Accept');

        if (!in_array('application/json', $request->getAcceptableContentTypes())) {
            $response->headers->set('Content-type', 'text/plain');
        }

        return $response;
    }
}


text:
#pragma once
#include <aws/states/SFN_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace SFN
{
namespace Model
{

  /**
   *
Contains details about the start of a task during an execution.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_SFN_API TaskStartedEventDetails
  {
  public:
    TaskStartedEventDetails();
    TaskStartedEventDetails(Aws::Utils::Json::JsonView jsonValue);
    TaskStartedEventDetails& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The service name of the resource in a task state.

     */
    inline const Aws::String& GetResourceType() const{ return m_resourceType; }

    /**
     *
The service name of the resource in a task state.

     */
    inline bool ResourceTypeHasBeenSet() const { return m_resourceTypeHasBeenSet; }

    /**
     *
The service name of the resource in a task state.

     */
    inline void SetResourceType(const Aws::String& value) { m_resourceTypeHasBeenSet = true; m_resourceType = value; }

    /**
     *
The service name of the resource in a task state.

     */
    inline void SetResourceType(Aws::String&& value) { m_resourceTypeHasBeenSet = true; m_resourceType = std::move(value); }

    /**
     *
The service name of the resource in a task state.

     */
    inline void SetResourceType(const char* value) { m_resourceTypeHasBeenSet = true; m_resourceType.assign(value); }

    /**
     *
The service name of the resource in a task state.

     */
    inline TaskStartedEventDetails& WithResourceType(const Aws::String& value) { SetResourceType(value); return *this;}

    /**
     *
The service name of the resource in a task state.

     */
    inline TaskStartedEventDetails& WithResourceType(Aws::String&& value) { SetResourceType(std::move(value)); return *this;}

    /**
     *
The service name of the resource in a task state.

     */
    inline TaskStartedEventDetails& WithResourceType(const char* value) { SetResourceType(value); return *this;}

    /**
     *
The action of the resource called by a task state.

     */
    inline const Aws::String& GetResource() const{ return m_resource; }

    /**
     *
The action of the resource called by a task state.

     */
    inline bool ResourceHasBeenSet() const { return m_resourceHasBeenSet; }

    /**
     *
The action of the resource called by a task state.

     */
    inline void SetResource(const Aws::String& value) { m_resourceHasBeenSet = true; m_resource = value; }

    /**
     *
The action of the resource called by a task state.

     */
    inline void SetResource(Aws::String&& value) { m_resourceHasBeenSet = true; m_resource = std::move(value); }

    /**
     *
The action of the resource called by a task state.

     */
    inline void SetResource(const char* value) { m_resourceHasBeenSet = true; m_resource.assign(value); }

    /**
     *
The action of the resource called by a task state.

     */
    inline TaskStartedEventDetails& WithResource(const Aws::String& value) { SetResource(value); return *this;}

    /**
     *
The action of the resource called by a task state.

     */
    inline TaskStartedEventDetails& WithResource(Aws::String&& value) { SetResource(std::move(value)); return *this;}

    /**
     *
The action of the resource called by a task state.

     */
    inline TaskStartedEventDetails& WithResource(const char* value) { SetResource(value); return *this;}

  private:

    Aws::String m_resourceType;
    bool m_resourceTypeHasBeenSet = false;

    Aws::String m_resource;
    bool m_resourceHasBeenSet = false;
  };

} // namespace Model
} // namespace SFN
} // namespace Aws


text:
/* Check exit_group(2) trivially with non-zero status.
#notarget: cris-*-* *-*-elf
#output: exit_group\n
#xerror:
*/
#define EXITVAL 1
#include "exitg1.c"


text:
<?php

	$lacze = mysql_connect('localhost', '18659907_sm_i_kb', '')
	or die("Problem with data base connection");

	$baza = mysql_select_db('18659907_sm_i_kb', $lacze)
	or die("Incorrect data base");

	mysql_query("SET CHARSET utf8");

	$name_lastName = trim($_POST['name_lastName']);
	$e_mail = trim($_POST['e_mail']);
	$subject = trim($_POST['subject']);
	$content_message = $_POST['content_message'];

	$zpt = "INSERT INTO messages(name_lastName, e_mail, subject, content_message) VALUES ('$name_lastName', '$e_mail', '$subject', '$content_message')";

	$rezultat = mysql_query($zpt, $lacze);

?>


text:
package org.docksidestage.compatible10x.dbflute.whitebox.bhv;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.dbflute.bhv.referrer.ConditionBeanSetupper;
import org.dbflute.bhv.referrer.ReferrerListHandler;
import org.dbflute.bhv.referrer.ReferrerLoaderHandler;
import org.dbflute.cbean.result.ListResultBean;
import org.docksidestage.compatible10x.dbflute.allcommon.CDef;
import org.docksidestage.compatible10x.dbflute.bsbhv.loader.LoaderOfMember;
import org.docksidestage.compatible10x.dbflute.bsbhv.loader.LoaderOfMemberLogin;
import org.docksidestage.compatible10x.dbflute.bsbhv.loader.LoaderOfMemberService;
import org.docksidestage.compatible10x.dbflute.bsbhv.loader.LoaderOfPurchase;
import org.docksidestage.compatible10x.dbflute.bsbhv.loader.LoaderOfPurchasePayment;
import org.docksidestage.compatible10x.dbflute.bsbhv.loader.LoaderOfServiceRank;
import org.docksidestage.compatible10x.dbflute.bsbhv.loader.LoaderOfWithdrawalReason;
import org.docksidestage.compatible10x.dbflute.cbean.MemberCB;
import org.docksidestage.compatible10x.dbflute.cbean.MemberLoginCB;
import org.docksidestage.compatible10x.dbflute.cbean.MemberServiceCB;
import org.docksidestage.compatible10x.dbflute.cbean.MemberWithdrawalCB;
import org.docksidestage.compatible10x.dbflute.cbean.PurchaseCB;
import org.docksidestage.compatible10x.dbflute.cbean.PurchasePaymentCB;
import org.docksidestage.compatible10x.dbflute.cbean.ServiceRankCB;
import org.docksidestage.compatible10x.dbflute.cbean.WithdrawalReasonCB;
import org.docksidestage.compatible10x.dbflute.exbhv.MemberBhv;
import org.docksidestage.compatible10x.dbflute.exbhv.MemberStatusBhv;
import org.docksidestage.compatible10x.dbflute.exbhv.PurchaseBhv;
import org.docksidestage.compatible10x.dbflute.exbhv.PurchasePaymentBhv;
import org.docksidestage.compatible10x.dbflute.exbhv.ServiceRankBhv;
import org.docksidestage.compatible10x.dbflute.exbhv.WithdrawalReasonBhv;
import org.docksidestage.compatible10x.dbflute.exentity.Member;
import org.docksidestage.compatible10x.dbflute.exentity.MemberLogin;
import org.docksidestage.compatible10x.dbflute.exentity.MemberService;
import org.docksidestage.compatible10x.dbflute.exentity.MemberStatus;
import org.docksidestage.compatible10x.dbflute.exentity.MemberWithdrawal;
import org.docksidestage.compatible10x.dbflute.exentity.Purchase;
import org.docksidestage.compatible10x.dbflute.exentity.PurchasePayment;
import org.docksidestage.compatible10x.dbflute.exentity.ServiceRank;
import org.docksidestage.compatible10x.dbflute.exentity.WithdrawalReason;
import org.docksidestage.compatible10x.unit.UnitContainerTestCase;

/**
 * @author jflute
 * @since 1.0.5F (2014/05/06 Tuesday)
 */
public class WxBhvLoadReferrerNewLoaderTest extends UnitContainerTestCase {

    // ===================================================================================
    //                                                                           Attribute
    //                                                                           =========
    private MemberBhv memberBhv;
    private MemberStatusBhv memberStatusBhv;
    private PurchaseBhv purchaseBhv;
    private PurchasePaymentBhv purchasePaymentBhv;
    private ServiceRankBhv serviceRankBhv;
    private WithdrawalReasonBhv withdrawalReasonBhv;

    // ===================================================================================
    //                                                                               Basic
    //                                                                               =====
    public void test_loadReferrer_basic() {
        // ## Arrange ##
        MemberCB cb = new MemberCB();
        cb.query().setMemberName_PrefixSearch("S");
        cb.query().addOrderBy_MemberId_Asc();

        // ## Act ##
        ListResultBean<Member> memberList = memberBhv.selectList(cb);

        // Member
        //  |-Purchase
        //     |-PurchasePayment
        //
        // if Java8
        // memberBhv.load(memberList, loader -> {
        //     loader.loadPurchaseList(purchaseCB -> {
        //         purchaseCB.query().addOrderBy_PurchasePrice_Asc();
        //     }
        // });
        memberBhv.load(memberList, new ReferrerLoaderHandler<LoaderOfMember>() {
            public void handle(LoaderOfMember loader) {
                loader.loadPurchaseList(new ConditionBeanSetupper<PurchaseCB>() {
                    public void setup(PurchaseCB referrerCB) {
                        referrerCB.query().addOrderBy_PurchasePrice_Asc();
                    }
                });
            }
        });

        // ## Assert ##
        ListResultBean<Member> expectedList = memberBhv.selectList(cb);
        memberBhv.loadPurchaseList(expectedList, new ConditionBeanSetupper<PurchaseCB>() {
            public void setup(PurchaseCB referrerCB) {
                referrerCB.query().addOrderBy_PurchasePrice_Asc();
            }
        });
        assertEquals(expectedList, memberList);
        Map<Integer, Member> expectedMap = newHashMap();
        for (Member member : expectedList) {
            expectedMap.put(member.getMemberId(), member);
        }
        for (Member member : memberList) {
            log(member);
            Member expected = expectedMap.get(member.getMemberId());
            assertEquals(expected.toStringWithRelation(), member.toStringWithRelation());
            assertEquals(expected.getPurchaseList(), member.getPurchaseList());
            assertNull(member.getMemberStatus());
            assertNull(member.getMemberSecurityAsOne());
            assertNull(member.getMemberServiceAsOne());
            List<Purchase> purchaseList = expected.getPurchaseList();
            Map<Long, Purchase> expectedPurchaseMap = newHashMap();
            for (Purchase purchase : expected.getPurchaseList()) {
                expectedPurchaseMap.put(purchase.getPurchaseId(), purchase);
            }
            for (Purchase purchase : purchaseList) {
                log("  " + purchase);
                Purchase expectedPurchase = expectedPurchaseMap.get(purchase.getPurchaseId());
                assertEquals(expectedPurchase.toStringWithRelation(), purchase.toStringWithRelation());
                assertEquals(expectedPurchase.getPurchasePaymentList(), purchase.getPurchasePaymentList());
                assertNull(purchase.getProduct());
                assertTrue(purchase.getPurchasePaymentList().isEmpty());
                markHere("purchase");
            }
            assertTrue(member.getMemberLoginList().isEmpty());
            assertTrue(expected.getMemberLoginList().isEmpty());
        }
        assertMarked("purchase");
    }

    public void test_loadReferrer_nest_and_branch() {
        // ## Arrange ##
        MemberCB cb = new MemberCB();
        cb.query().setMemberName_PrefixSearch("S");
        cb.query().addOrderBy_MemberId_Asc();

        // ## Act ##
        ListResultBean<Member> memberList = memberBhv.selectList(cb);
        memberBhv.load(memberList, new ReferrerLoaderHandler<LoaderOfMember>() {
            public void handle(LoaderOfMember loader) {
                loader.loadPurchaseList(new ConditionBeanSetupper<PurchaseCB>() {
                    public void setup(PurchaseCB referrerCB) {
                        referrerCB.query().addOrderBy_PurchasePrice_Asc();
                    }
                }).withNestedReferrer(new ReferrerLoaderHandler<LoaderOfPurchase>() {
                    public void handle(LoaderOfPurchase loader) {
                        loader.loadPurchasePaymentList(new ConditionBeanSetupper<PurchasePaymentCB>() {
                            public void setup(PurchasePaymentCB referrerCB) {
                                referrerCB.query().addOrderBy_PaymentAmount_Asc();
                            }
                        });
                    }
                });
                loader.loadMemberLoginList(new ConditionBeanSetupper<MemberLoginCB>() {
                    public void setup(MemberLoginCB referrerCB) {
                        referrerCB.query().addOrderBy_LoginDatetime_Desc();
                    }
                });
            }
        });

        // ## Assert ##
        ListResultBean<Member> expectedList = memberBhv.selectList(cb);
        memberBhv.loadPurchaseList(expectedList, new ConditionBeanSetupper<PurchaseCB>() {
            public void setup(PurchaseCB referrerCB) {
                referrerCB.query().addOrderBy_PurchasePrice_Asc();
            }
        }).withNestedReferrer(new ReferrerListHandler<Purchase>() {
            public void handle(List<Purchase> referrerList) {
                purchaseBhv.loadPurchasePaymentList(referrerList, new ConditionBeanSetupper<PurchasePaymentCB>() {
                    public void setup(PurchasePaymentCB referrerCB) {
                        referrerCB.query().addOrderBy_PaymentAmount_Asc();
                    }
                });
            }
        });
        memberBhv.loadMemberLoginList(expectedList, new ConditionBeanSetupper<MemberLoginCB>() {
            public void setup(MemberLoginCB referrerCB) {
                referrerCB.query().addOrderBy_LoginDatetime_Desc();
            }
        });
        assertEquals(expectedList, memberList);
        Map<Integer, Member> expectedMap = newHashMap();
        for (Member member : expectedList) {
            expectedMap.put(member.getMemberId(), member);
        }
        assertHasAnyElement(memberList);
        for (Member member : memberList) {
            log(member);
            Member expected = expectedMap.get(member.getMemberId());
            assertNull(member.getMemberStatus());
            assertNull(member.getMemberSecurityAsOne());
            assertNull(member.getMemberServiceAsOne());
            List<Purchase> purchaseList = expected.getPurchaseList();
            Map<Long, Purchase> expectedPurchaseMap = newHashMap();
            for (Purchase purchase : expected.getPurchaseList()) {
                expectedPurchaseMap.put(purchase.getPurchaseId(), purchase);
            }
            for (Purchase purchase : purchaseList) {
                log("  " + purchase);
                Purchase expectedPurchase = expectedPurchaseMap.get(purchase.getPurchaseId());
                assertNull(purchase.getProduct());
                List<PurchasePayment> paymentList = purchase.getPurchasePaymentList();
                Map<Long, PurchasePayment> expectedPaymentMap = newHashMap();
                for (PurchasePayment payment : expectedPurchase.getPurchasePaymentList()) {
                    expectedPaymentMap.put(payment.getPurchasePaymentId(), payment);
                }
                for (PurchasePayment payment : paymentList) {
                    log("    " + payment);
                    PurchasePayment expectedPayment = expectedPaymentMap.get(payment.getPurchasePaymentId());
                    assertEquals(expectedPayment.toStringWithRelation(), payment.toStringWithRelation());
                    markHere("payment");
                }
                assertEquals(expectedPurchase.toStringWithRelation(), purchase.toStringWithRelation());
            }
            List<MemberLogin> loginList = member.getMemberLoginList();
            Map<Long, MemberLogin> expectedLoginMap = newHashMap();
            for (MemberLogin login : expected.getMemberLoginList()) {
                expectedLoginMap.put(login.getMemberLoginId(), login);
            }
            for (MemberLogin login : loginList) {
                MemberLogin expectedLogin = expectedLoginMap.get(login.getMemberLoginId());
                assertNull(login.getMemberStatus());
                assertEquals(expectedLogin.toStringWithRelation(), login.toStringWithRelation());
                markHere("login");
            }
            assertEquals(expected.toStringWithRelation(), member.toStringWithRelation());
        }
        assertMarked("payment");
        assertMarked("login");
    }

    // ===================================================================================
    //                                                                            Pull out
    //                                                                            ========
    public void test_loadReferrer_pullout_basic() {
        // ## Arrange ##
        MemberCB cb = new MemberCB();
        cb.setupSelect_MemberStatus();
        cb.query().setMemberName_PrefixSearch("S");
        cb.query().addOrderBy_MemberId_Asc();

        // ## Act ##
        ListResultBean<Member> memberList = memberBhv.selectList(cb);
        memberBhv.load(memberList, new ReferrerLoaderHandler<LoaderOfMember>() {
            public void handle(LoaderOfMember loader) {
                loader.pulloutMemberStatus().loadMemberLoginList(new ConditionBeanSetupper<MemberLoginCB>() {
                    public void setup(MemberLoginCB referrerCB) {
                        referrerCB.query().setMobileLoginFlg_Equal_False();
                        referrerCB.query().addOrderBy_LoginDatetime_Asc();
                    }
                });
            }
        });

        // ## Assert ##
        ListResultBean<Member> expectedList = memberBhv.selectList(cb);
        memberStatusBhv.loadMemberLoginList(memberBhv.pulloutMemberStatus(expectedList),
                new ConditionBeanSetupper<MemberLoginCB>() {
                    public void setup(MemberLoginCB referrerCB) {
                        referrerCB.query().setMobileLoginFlg_Equal_False();
                        referrerCB.query().addOrderBy_LoginDatetime_Asc();
                    }
                });

        assertEquals(expectedList, memberList);
        Map<Integer, Member> expectedMap = newHashMap();
        for (Member member : expectedList) {
            expectedMap.put(member.getMemberId(), member);
        }
        assertHasAnyElement(memberList);
        for (Member member : memberList) {
            log(member);
            Member expected = expectedMap.get(member.getMemberId());
            assertEquals(expected.getPurchaseList(), member.getPurchaseList());
            assertNotNull(member.getMemberStatus());
            assertNull(member.getMemberSecurityAsOne());
            assertNull(member.getMemberServiceAsOne());
            assertTrue(expected.getPurchaseList().isEmpty());
            assertTrue(member.getPurchaseList().isEmpty());
            assertTrue(expected.getMemberLoginList().isEmpty());
            assertTrue(member.getMemberLoginList().isEmpty());
            MemberStatus status = member.getMemberStatus();
            MemberStatus expectedStatus = expected.getMemberStatus();
            assertEquals(expectedStatus, status);
            Map<Long, MemberLogin> expectedLoginMap = newHashMap();
            for (MemberLogin login : status.getMemberLoginList()) {
                expectedLoginMap.put(login.getMemberLoginId(), login);
            }
            List<MemberLogin> loginList = status.getMemberLoginList();
            for (MemberLogin login : loginList) {
                MemberLogin expectedLogin = expectedLoginMap.get(login.getMemberLoginId());
                log("  " + login, expectedLogin);
                assertEquals(expectedLogin.toStringWithRelation(), login.toStringWithRelation());
                assertNotNull(login.getMemberStatus());
                markHere("login");
            }
            assertEquals(expectedStatus.toStringWithRelation(), status.toStringWithRelation());
            assertEquals(expectedStatus.getMemberLoginList(), status.getMemberLoginList());
            assertEquals(expected.toStringWithRelation(), member.toStringWithRelation());
        }

        assertMarked("login");
    }

    public void test_loadReferrer_pullout_noSetupSelect() {
        // ## Arrange ##
        MemberCB cb = new MemberCB();
        cb.query().setMemberName_PrefixSearch("S");
        cb.query().addOrderBy_MemberId_Asc();

        // ## Act ##
        ListResultBean<Member> memberList = memberBhv.selectList(cb);
        memberBhv.load(memberList, new ReferrerLoaderHandler<LoaderOfMember>() {
            public void handle(LoaderOfMember loader) {
                loader.pulloutMemberStatus().loadMemberLoginList(new ConditionBeanSetupper<MemberLoginCB>() {
                    public void setup(MemberLoginCB referrerCB) {
                        referrerCB.query().setMobileLoginFlg_Equal_False();
                        referrerCB.query().addOrderBy_LoginDatetime_Asc();
                    }
                });
            }
        });

        // ## Assert ##
        ListResultBean<Member> expectedList = memberBhv.selectList(cb);
        memberStatusBhv.loadMemberLoginList(memberBhv.pulloutMemberStatus(expectedList),
                new ConditionBeanSetupper<MemberLoginCB>() {
                    public void setup(MemberLoginCB referrerCB) {
                        referrerCB.query().setMobileLoginFlg_Equal_False();
                        referrerCB.query().addOrderBy_LoginDatetime_Asc();
                    }
                });

        assertEquals(expectedList, memberList);
        Map<Integer, Member> expectedMap = newHashMap();
        for (Member member : expectedList) {
            expectedMap.put(member.getMemberId(), member);
        }
        assertHasAnyElement(memberList);
        for (Member member : memberList) {
            log(member);
            Member expected = expectedMap.get(member.getMemberId());
            assertEquals(expected.getPurchaseList(), member.getPurchaseList());
            assertNull(member.getMemberStatus());
            assertNull(member.getMemberSecurityAsOne());
            assertNull(member.getMemberServiceAsOne());
            assertTrue(expected.getPurchaseList().isEmpty());
            assertTrue(member.getPurchaseList().isEmpty());
            assertTrue(expected.getMemberLoginList().isEmpty());
            assertTrue(member.getMemberLoginList().isEmpty());
            assertNull(expected.getMemberStatus());
        }
    }

    public void test_loadReferrer_pullout_branch() {
        // ## Arrange ##
        ServiceRankCB cb = new ServiceRankCB();
        cb.query().addOrderBy_DisplayOrder_Asc();

        // ## Act ##
        ListResultBean<ServiceRank> rankList = serviceRankBhv.selectList(cb);
        serviceRankBhv.load(rankList, new ReferrerLoaderHandler<LoaderOfServiceRank>() {
            public void handle(LoaderOfServiceRank loader) {
                loader.loadMemberServiceList(new ConditionBeanSetupper<MemberServiceCB>() {
                    public void setup(MemberServiceCB referrerCB) {
                        referrerCB.setupSelect_Member();
                        referrerCB.query().queryMember().setMemberStatusCode_Equal_Formalized();
                    }
                }).withNestedReferrer(new ReferrerLoaderHandler<LoaderOfMemberService>() {
                    public void handle(LoaderOfMemberService loader) {
                        loader.pulloutMember().loadPurchaseList(new ConditionBeanSetupper<PurchaseCB>() {
                            public void setup(PurchaseCB referrerCB) {
                                referrerCB.setupSelect_Product();
                                referrerCB.query().setPaymentCompleteFlg_Equal_True();
                                referrerCB.query().addOrderBy_PurchaseDatetime_Asc();
                            }
                        });
                        loader.pulloutMember().loadMemberLoginList(new ConditionBeanSetupper<MemberLoginCB>() {
                            public void setup(MemberLoginCB referrerCB) {
                                referrerCB.setupSelect_MemberStatus();
                                referrerCB.query().setMobileLoginFlg_Equal_False();
                                referrerCB.query().addOrderBy_LoginDatetime_Asc();
                            }
                        });
                    }
                });
            }
        });

        // ## Assert ##
        assertHasAnyElement(rankList);
        for (ServiceRank rank : rankList) {
            log("  " + rank);
            List<MemberService> serviceList = rank.getMemberServiceList();
            for (MemberService service : serviceList) {
                Member member = service.getMember();
                log("  " + member.getMemberName(), service.getServicePointCount());
                assertTrue(member.isMemberStatusCodeFormalized());
                List<Purchase> purchaseList = member.getPurchaseList();
                for (Purchase purchase : purchaseList) {
                    assertNotNull(purchase.getProduct());
                    log("    purchase: " + purchase.getPurchaseId(), purchase.getProduct().getProductName());
                    assertTrue(purchase.isPaymentCompleteFlgTrue());
                    markHere("purchase");
                }
                List<MemberLogin> loginList = member.getMemberLoginList();
                for (MemberLogin login : loginList) {
                    assertNotNull(login.getMemberStatus());
                    log("    login: " + login.getMemberLoginId(), login.getMemberStatus().getMemberStatusName());
                    assertTrue(login.isMobileLoginFlgFalse());
                    markHere("login");
                }
            }
        }
        assertMarked("purchase");
        assertMarked("login");
    }

    public void test_loadReferrer_pullout_branch_nested() {
        // ## Arrange ##
        ServiceRankCB cb = new ServiceRankCB();
        cb.query().addOrderBy_DisplayOrder_Asc();

        // ## Act ##
        ListResultBean<ServiceRank> rankList = serviceRankBhv.selectList(cb);
        serviceRankBhv.load(rankList, new ReferrerLoaderHandler<LoaderOfServiceRank>() {
            public void handle(LoaderOfServiceRank loader) {
                loader.loadMemberServiceList(new ConditionBeanSetupper<MemberServiceCB>() {
                    public void setup(MemberServiceCB referrerCB) {
                        referrerCB.setupSelect_Member().withMemberStatus();
                        List<CDef.MemberStatus> cdefList = new ArrayList<CDef.MemberStatus>();
                        cdefList.add(CDef.MemberStatus.Provisional);
                        cdefList.add(CDef.MemberStatus.Withdrawal);
                        referrerCB.query().queryMember().setMemberStatusCode_InScope_AsMemberStatus(cdefList);
                    }
                }).withNestedReferrer(new ReferrerLoaderHandler<LoaderOfMemberService>() {
                    public void handle(LoaderOfMemberService loader) {
                        loader.pulloutMember().loadPurchaseList(new ConditionBeanSetupper<PurchaseCB>() {
                            public void setup(PurchaseCB referrerCB) {
                                referrerCB.setupSelect_Product();
                                referrerCB.query().setPaymentCompleteFlg_Equal_True();
                                referrerCB.query().addOrderBy_PurchaseDatetime_Asc();
                            }
                        }).withNestedReferrer(new ReferrerLoaderHandler<LoaderOfPurchase>() {
                            public void handle(LoaderOfPurchase loader) {
                                loader.loadPurchasePaymentList(new ConditionBeanSetupper<PurchasePaymentCB>() {
                                    public void setup(PurchasePaymentCB referrerCB) {
                                        referrerCB.query().setPaymentMethodCode_Equal_BankTransfer();
                                        referrerCB.query().addOrderBy_PaymentDatetime_Desc();
                                    }
                                });
                            }
                        });
                        loader.pulloutMember().loadMemberLoginList(new ConditionBeanSetupper<MemberLoginCB>() {
                            public void setup(MemberLoginCB referrerCB) {
                                referrerCB.setupSelect_MemberStatus();
                                referrerCB.query().setMobileLoginFlg_Equal_False();
                                referrerCB.query().addOrderBy_LoginDatetime_Asc();
                            }
                        }).withNestedReferrer(new ReferrerLoaderHandler<LoaderOfMemberLogin>() {
                            public void handle(LoaderOfMemberLogin loader) {
                                loader.pulloutMemberStatus().loadMemberList(new ConditionBeanSetupper<MemberCB>() {
                                    public void setup(MemberCB referrerCB) {
                                        referrerCB.query().setMemberName_PrefixSearch("S");
                                    }
                                });
                            }
                        });
                    }
                });
            }
        });

        // ## Assert ##
        assertHasAnyElement(rankList);
        for (ServiceRank rank : rankList) {
            log("  " + rank);
            List<MemberService> serviceList = rank.getMemberServiceList();
            for (MemberService service : serviceList) {
                Member member = service.getMember();
                log("  " + member.getMemberName(), service.getServicePointCount(), member.getMemberStatus()
                        .getMemberStatusName());
                assertTrue(member.isMemberStatusCodeProvisional() || member.isMemberStatusCodeWithdrawal());
                List<Purchase> purchaseList = member.getPurchaseList();
                for (Purchase purchase : purchaseList) {
                    assertNotNull(purchase.getProduct());
                    log("    purchase: " + purchase.getPurchaseId(), purchase.getProduct().getProductName());
                    assertTrue(purchase.isPaymentCompleteFlgTrue());
                    markHere("purchase");
                    List<PurchasePayment> paymentList = purchase.getPurchasePaymentList();
                    for (PurchasePayment payment : paymentList) {
                        log("      payment: " + payment.getPaymentAmount());
                        markHere("payment");
                    }
                }
                List<MemberLogin> loginList = member.getMemberLoginList();
                for (MemberLogin login : loginList) {
                    assertNotNull(login.getMemberStatus());
                    log("    login: " + login.getMemberLoginId(), login.getMemberStatus().getMemberStatusName());
                    assertTrue(login.isMobileLoginFlgFalse());
                    markHere("login");
                    MemberStatus status = login.getMemberStatus();
                    List<Member> memberList = status.getMemberList();
                    for (Member statusMember : memberList) {
                        log("      statusMember: " + status.getMemberStatusName() + ", " + statusMember.getMemberName());
                        assertTrue(statusMember.getMemberName().startsWith("S"));
                        assertEquals(status.getMemberStatusCode(), statusMember.getMemberStatusCode());
                        markHere("statusMember");
                        if (statusMember.isMemberStatusCodeFormalized()) {
                            markHere("formalized");
                        }
                    }
                }
            }
        }
        assertMarked("purchase");
        assertMarked("payment");
        assertMarked("login");
        assertMarked("statusMember");
        assertMarked("formalized");
    }

    public void test_loadReferrer_pullout_setupSelect_mightBeNull() throws Exception {
        // ## Arrange ##
        MemberCB cb = new MemberCB();
        cb.setupSelect_MemberWithdrawalAsOne().withWithdrawalReason();
        cb.query().addOrderBy_Birthdate_Desc();

        // ## Act ##
        ListResultBean<Member> memberList = memberBhv.selectList(cb);
        memberBhv.load(memberList, new ReferrerLoaderHandler<LoaderOfMember>() {
            public void handle(LoaderOfMember loader) {
                loader.pulloutMemberWithdrawalAsOne().pulloutWithdrawalReason()
                        .loadMemberWithdrawalList(new ConditionBeanSetupper<MemberWithdrawalCB>() {
                            public void setup(MemberWithdrawalCB referrerCB) {
                            }
                        });
            }
        });

        // ## Assert ##
        assertHasAnyElement(memberList);
        for (Member member : memberList) {
            MemberWithdrawal withdrawal = member.getMemberWithdrawalAsOne();
            if (withdrawal != null) {
                WithdrawalReason reason = withdrawal.getWithdrawalReason();
                if (reason != null) {
                    List<MemberWithdrawal> withdrawalList = reason.getMemberWithdrawalList();
                    log(member.getMemberName(), withdrawal.getWithdrawalDatetime(), reason.getDisplayOrder(),
                            withdrawalList.size());
                    markHere("exists");
                } else {
                    log(member.getMemberName(), withdrawal.getWithdrawalDatetime());
                    markHere("noReason");
                }
            } else {
                log(member.getMemberName());
                markHere("noWithdrawal");
            }
        }
        log(currentUtilDate().getTime());
        assertMarked("exists");
        assertMarked("noReason");
        assertMarked("noWithdrawal");
    }

    // ===================================================================================
    //                                                                         No Referrer
    //                                                                         ===========
    public void test_loadReferrer_noReferrer_pulloutOnly() throws Exception {
        // ## Arrange ##
        PurchasePaymentCB cb = new PurchasePaymentCB();
        cb.setupSelect_Purchase().withMember().withMemberLoginAsLatest();

        // ## Act ##
        ListResultBean<PurchasePayment> paymentList = purchasePaymentBhv.selectList(cb);

        // ## Assert ##
        assertHasAnyElement(paymentList);
        purchasePaymentBhv.load(paymentList, new ReferrerLoaderHandler<LoaderOfPurchasePayment>() {
            public void handle(LoaderOfPurchasePayment loader) {
                loader.pulloutPurchase().pulloutMember()
                        .loadMemberLoginList(new ConditionBeanSetupper<MemberLoginCB>() {
                            public void setup(MemberLoginCB referrerCB) {
                                referrerCB.setupSelect_MemberStatus();
                            }
                        }).withNestedReferrer(new ReferrerLoaderHandler<LoaderOfMemberLogin>() {
                            public void handle(LoaderOfMemberLogin loader) {
                                loader.pulloutMemberStatus().loadMemberList(new ConditionBeanSetupper<MemberCB>() {
                                    public void setup(MemberCB referrerCB) {
                                        referrerCB.query().setMemberName_PrefixSearch("S");
                                    }
                                });
                            }
                        });
            }
        });
        for (PurchasePayment payment : paymentList) {
            Member member = payment.getPurchase().getMember();
            if (!member.isMemberStatusCodeFormalized()) {
                markHere("check");
            }
            List<MemberLogin> loginList = member.getMemberLoginList();
            for (MemberLogin login : loginList) {
                MemberStatus status = login.getMemberStatus();
                assertNotNull(status);
                List<Member> farMemberList = status.getMemberList();
                for (Member farMember : farMemberList) {
                    assertTrue(farMember.getMemberName().startsWith("S"));
                    markHere("exists");
                }
            }
        }
        assertMarked("check");
        assertMarked("exists");
    }

    // ===================================================================================
    //                                                                             Null FK
    //                                                                             =======
    public void test_loadReferrer_nullFK() {
        // ## Arrange ##
        WithdrawalReasonCB cb = new WithdrawalReasonCB();

        // ## Act ##
        ListResultBean<WithdrawalReason> reasonList = withdrawalReasonBhv.selectList(cb);
        withdrawalReasonBhv.load(reasonList, new ReferrerLoaderHandler<LoaderOfWithdrawalReason>() {
            public void handle(LoaderOfWithdrawalReason loader) {
                loader.loadMemberWithdrawalList(new ConditionBeanSetupper<MemberWithdrawalCB>() {
                    public void setup(MemberWithdrawalCB referrerCB) {
                    }
                });
            }
        });

        // ## Assert ##
        assertHasAnyElement(reasonList);
        for (WithdrawalReason reason : reasonList) {
            log(reason);
            List<MemberWithdrawal> withdrawalList = reason.getMemberWithdrawalList();
            for (MemberWithdrawal withdrawal : withdrawalList) {
                markHere("exists");
                log("  " + withdrawal);
            }
        }
        assertMarked("exists");
    }
}


text:
<?php

namespace ephFrame\test\HTML\Form;

use
	ephFrame\HTML\Form\Element\Element,
	ephFrame\validator\Integer
	;

/**
 * @group Form
 * @group Element
 */
class ElementTest extends \PHPUnit_Framework_TestCase
{
	public function setUp()
	{
		$this->fixture = new Element('fieldname', 'value', array(
			'attributes' => array(
				'class' => 'pink',
			),
			'validators' => array(
				new Integer(),
			)
		));
	}

	public function testAutoName()
	{
		$field = new Element(null, 'myvalue');
		$this->assertEquals($field->attributes['name'], 'element');
	}

	public function testRequiredWithEmptyData()
	{
		$this->assertFalse($this->fixture->submit(Null)->ok());
	}

	public function testRequiredWithValue()
	{
		$this->fixture->required = false;
		$this->assertTrue($this->fixture->submit('value')->ok());
	}

	public function testTrim()
	{
		$this->assertEquals(
			'trim me',
			$this->fixture->submit('  trim me ')->data
		);
	}

	public function testStripTags()
	{
		$this->assertEquals(
			$this->fixture->submit('strong value')->data,
			'strong value'
		);
	}

	public function testAttributesInConstructor()
	{
		$this->assertEquals('pink', $this->fixture->attributes['class']);
		$this->assertEquals('fieldname', $this->fixture->attributes['name']);
	}

	public function testAttributesAdd()
	{
		$value = '1px solid red';
		$this->fixture->attributes['style'] = $value;
		$this->assertEquals($value, $this->fixture->attributes['style']);
	}

	public function testValidate()
	{
		$this->assertFalse($this->fixture->validate('string'));
	}

	public function testError()
	{
		$this->fixture->submit(12323);
		$this->assertFalse($this->fixture->error());
		$this->assertTrue($this->fixture->ok());
	}

	public function testNoDecorators()
	{
		$element = new Element('field1', true, array('decorators' => false));
		$this->assertFalse($element->decorators);
	}

	public function testSubmit()
	{
		$element = new Element('field1', true, array('decorators' => false));
		$this->assertTrue(empty($element->data));
		$element->submit('myvalue');
		$this->assertEquals('myvalue', $element->data);
	}
}


text:
package gpio;

import gpio.beaglebone.InputPinChangeMonitor;

import java.io.IOException;

/**
 * Input pin.
 * @author Koert Zeilstra
 */
public interface BinaryInputPin {

    /**
     * @return True if pin is high, false otherwise.
     * @throws java.io.IOException Failed to read/write device.
     */
    boolean isHigh() throws IOException;

    /**
     * Wait for change.
     * @param edge Spcified edge.
     * @throws IOException Failed to use device.
     */
    void waitForEdge(Edge edge) throws IOException;

    /**
     * Create change monitor.
     * @param edge Edge to monitor for.
     * @return Change monitor.
     * @throws IOException Failed to use device.
     */
    public InputPinChangeMonitor monitorChange(Edge edge) throws IOException;

        /**
         * Stop using this pin.
         */
    void close() throws IOException;

}