text:
package jp.yokomark.widget.compound;

import android.content.Context;
import android.util.AttributeSet;

/**
 * @author yokomakukeishin
 * @since 2014/03/16
 */
public class RadioLinearLayout extends CompoundLinearLayout{
    public static final String TAG = RadioLinearLayout.class.getSimpleName();

    public RadioLinearLayout(Context context) {
        super(context);
    }

    public RadioLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RadioLinearLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void toggle() {
        if (!isChecked()) {
            super.toggle();
        }
    }
}


text:
    <router-outlet></router-outlet>

            ID
            First Name
            Last Name
            Email

                {{ account.id }}
                {{ account.first_name }}
                {{ account.last_name }}
                {{ account.email }}

        <button class="btn btn-success" type="button" routerLink="add">Add</button>
        <button class="btn btn-warning" type="button" routerLink="edit" [attr.disabled]="canEdit()">Edit</button>

            <<
            <
            25
            50
            100
            >
            >>

redpajama_set_name: RedPajamaGithub


text:
// macros.h
//
// Copyright (c) 2016 Frank Lin (lin.xiaoe.f@gmail.com)
//
// 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.

#ifndef LERC_CORE_MACROS_H_
#define LERC_CORE_MACROS_H_

#include <assert.h>

// platform enum
#define SKR_PLATFORM_UNKNOWN            0
#define SKR_PLATFORM_IOS                1
#define SKR_PLATFORM_ANDROID            2
#define SKR_PLATFORM_MAC                3
#define SKR_PLATFORM_WIN32              5
#define SKR_PLATFORM_LINUX              6

// DISALLOW_COPY_AND_ASSIGN
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)

// namespace Gago {}
#ifdef __cplusplus
#define NS_GAGO_BEGIN                     namespace gago {
#define NS_GAGO_END                       }
#define USING_NS_GAGO                     using namespace gago
#else
#define NS_GAGO_BEGIN
#define NS_GAGO_END
#define USING_NS_GAGO
#endif

// namespace sakura {}
#ifdef __cplusplus
#define NS_SKR_BEGIN                  namespace sakura {
#define NS_SKR_END                    }
#define USING_NS_SKR                  using namespace sakura
#else
#define NS_SKR_BEGIN
#define NS_SKR_END
#define USING_NS_SKR
#endif

// SKR_DLL
#if SKR_PLATFORM == SKR_PLATFORM_WIN32
#if defined(SKR_STATIC)
#define SKR_DLL
#else
#if defined(_USRDLL)
#define SKR_DLL     __declspec(dllexport)
#else
#define SKR_DLL     __declspec(dllimport)
#endif
#endif
#else
#define SKR_DLL
#endif // SKR_PLATFORM == SKR_PLATFORM_WIN32

// assert
#ifdef SKR_USING_ASSERT
#include <assert.h>
#define SKR_ASSERT(p) assert(p)
#else
#define SKR_ASSERT(p)
#endif

// delete/free
#define SKR_SAFE_DELETE(p) do { if(p) { delete (p); (p) = nullptr; } } while(0)
#define SKR_SAFE_DELETE_ARRAY(p) do { if(p) { delete[] (p); (p) = nullptr; } } while(0)
#define SKR_SAFE_FREE(p) do { if(p) { free(p); (p) = 0; } } while(0)

#define SKR_SAFE_RELEASE(p) do { if(p) { (p)->Release(); (p)=nullptr; } } while(0)

// Break if
#define SKR_BREAK_IF(XXXX) if(XXXX)break;

// SKR_DEBUG_LOG_DATA
#define SKR_DEBUG_LOG_DATA

#endif /* LERC_CORE_MACROS_H_ */


text:
import createIsSubmitting from '../isSubmitting';
import plain from '../../structure/plain';
import plainExpectations from '../../structure/plain/expectations';
import immutable from '../../structure/immutable';
import immutableExpectations from '../../structure/immutable/expectations';
import addExpectations from '../../__tests__/addExpectations';

var describeIsSubmitting = function describeIsSubmitting(name, structure, expect) {
  var isSubmitting = createIsSubmitting(structure);

  var fromJS = structure.fromJS,
      getIn = structure.getIn;

  describe(name, function () {
    it('should return a function XXX', function () {
      expect(isSubmitting('foo')).toBeA('function');
    });

    it('should return false when value not present', function () {
      expect(isSubmitting('foo')(fromJS({
        form: {}
      }))).toBe(false);
    });

    it('should return true when submitting', function () {
      expect(isSubmitting('foo')(fromJS({
        form: {
          foo: {
            submitting: true
          }
        }
      }))).toBe(true);
    });

    it('should use getFormState if provided', function () {
      expect(isSubmitting('foo', function (state) {
        return getIn(state, 'someOtherSlice');
      })(fromJS({
        someOtherSlice: {
          foo: {
            submitting: true
          }
        }
      }))).toBe(true);
    });
  });
};

describeIsSubmitting('isSubmitting.plain', plain, addExpectations(plainExpectations));
describeIsSubmitting('isSubmitting.immutable', immutable, addExpectations(immutableExpectations));


text:
import { fromJS } from 'immutable';

import {
  SET_REPO,
  RECEIVED_BUILDS,
  NEW_BUILD,
  UPDATE_BUILD,
  CLEAR_BUILDS,
} from './constants';

// The initial state of the App
const initialState = fromJS({
  repo: null,
  builds: null,
});

function buildReducer(state = initialState, action) {
  switch (action.type) {
    case SET_REPO:
      return state.set('repo', action.repo);
    case CLEAR_BUILDS:
      return state.set('builds', []);
    case RECEIVED_BUILDS:
      return state.set('builds', action.builds);
    case NEW_BUILD:
      return state.set('builds', [...state.get('builds'), action.build]);
    case UPDATE_BUILD:
      const update = state.get('builds').map((build) => {
        if (build.build_start === action.build.build_start) {
          return action.build;
        }
        return build;
      });
      return state.set('builds', update);
    default:
      return state;
  }
}

export default buildReducer;


text:
BEGIN;

-- Change date type

ALTER TABLE OrleansStorage
ALTER COLUMN modifiedon TYPE TIMESTAMPTZ USING modifiedon AT TIME ZONE 'UTC';

-- Recreate routines

CREATE OR REPLACE FUNCTION writetostorage(
    _grainidhash integer,
    _grainidn0 bigint,
    _grainidn1 bigint,
    _graintypehash integer,
    _graintypestring character varying,
    _grainidextensionstring character varying,
    _serviceid character varying,
    _grainstateversion integer,
    _payloadbinary bytea)
    RETURNS TABLE(newgrainstateversion integer)
    LANGUAGE 'plpgsql'
AS $function$
    DECLARE
     _newGrainStateVersion integer := _GrainStateVersion;
     RowCountVar integer := 0;

    BEGIN

    -- Grain state is not null, so the state must have been read from the storage before.
    -- Let's try to update it.
    --
    -- When Orleans is running in normal, non-split state, there will
    -- be only one grain with the given ID and type combination only. This
    -- grain saves states mostly serially if Orleans guarantees are upheld. Even
    -- if not, the updates should work correctly due to version number.
    --
    -- In split brain situations there can be a situation where there are two or more
    -- grains with the given ID and type combination. When they try to INSERT
    -- concurrently, the table needs to be locked pessimistically before one of
    -- the grains gets @GrainStateVersion = 1 in return and the other grains will fail
    -- to update storage. The following arrangement is made to reduce locking in normal operation.
    --
    -- If the version number explicitly returned is still the same, Orleans interprets it so the update did not succeed
    -- and throws an InconsistentStateException.
    --
    -- See further information at https://docs.microsoft.com/dotnet/orleans/grains/grain-persistence.
    IF _GrainStateVersion IS NOT NULL
    THEN
        UPDATE OrleansStorage
        SET
            PayloadBinary = _PayloadBinary,
            ModifiedOn = (now() at time zone 'utc'),
            Version = Version + 1

        WHERE
            GrainIdHash = _GrainIdHash AND _GrainIdHash IS NOT NULL
            AND GrainTypeHash = _GrainTypeHash AND _GrainTypeHash IS NOT NULL
            AND GrainIdN0 = _GrainIdN0 AND _GrainIdN0 IS NOT NULL
            AND GrainIdN1 = _GrainIdN1 AND _GrainIdN1 IS NOT NULL
            AND GrainTypeString = _GrainTypeString AND _GrainTypeString IS NOT NULL
            AND ((_GrainIdExtensionString IS NOT NULL AND GrainIdExtensionString IS NOT NULL AND GrainIdExtensionString = _GrainIdExtensionString) OR _GrainIdExtensionString IS NULL AND GrainIdExtensionString IS NULL)
            AND ServiceId = _ServiceId AND _ServiceId IS NOT NULL
            AND Version IS NOT NULL AND Version = _GrainStateVersion AND _GrainStateVersion IS NOT NULL;

        GET DIAGNOSTICS RowCountVar = ROW_COUNT;
        IF RowCountVar > 0
        THEN
            _newGrainStateVersion := _GrainStateVersion + 1;
        END IF;
    END IF;

    -- The grain state has not been read. The following locks rather pessimistically
    -- to ensure only one INSERT succeeds.
    IF _GrainStateVersion IS NULL
    THEN
        INSERT INTO OrleansStorage
        (
            GrainIdHash,
            GrainIdN0,
            GrainIdN1,
            GrainTypeHash,
            GrainTypeString,
            GrainIdExtensionString,
            ServiceId,
            PayloadBinary,
            ModifiedOn,
            Version
        )
        SELECT
            _GrainIdHash,
            _GrainIdN0,
            _GrainIdN1,
            _GrainTypeHash,
            _GrainTypeString,
            _GrainIdExtensionString,
            _ServiceId,
            _PayloadBinary,
           now(),
            1
        WHERE NOT EXISTS
         (
            -- There should not be any version of this grain state.
            SELECT 1
            FROM OrleansStorage
            WHERE
                GrainIdHash = _GrainIdHash AND _GrainIdHash IS NOT NULL
                AND GrainTypeHash = _GrainTypeHash AND _GrainTypeHash IS NOT NULL
                AND GrainIdN0 = _GrainIdN0 AND _GrainIdN0 IS NOT NULL
                AND GrainIdN1 = _GrainIdN1 AND _GrainIdN1 IS NOT NULL
                AND GrainTypeString = _GrainTypeString AND _GrainTypeString IS NOT NULL
                AND ((_GrainIdExtensionString IS NOT NULL AND GrainIdExtensionString IS NOT NULL AND GrainIdExtensionString = _GrainIdExtensionString) OR _GrainIdExtensionString IS NULL AND GrainIdExtensionString IS NULL)
                AND ServiceId = _ServiceId AND _ServiceId IS NOT NULL
         );

        GET DIAGNOSTICS RowCountVar = ROW_COUNT;
        IF RowCountVar > 0
        THEN
            _newGrainStateVersion := 1;
        END IF;
    END IF;

    RETURN QUERY SELECT _newGrainStateVersion AS NewGrainStateVersion;
END

$function$;

COMMIT;


text:
            {{ div.name }}

            {{ fields }}


text:
package com.iluwatar;

/**
 *
 * Wizard party member.
 *
 */
public class Wizard extends PartyMemberBase {

	@Override
	public String toString() {
		return "Wizard";
	}

}


text:
<?php

namespace AppBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

/**
 * Class VoteAdmin
 * @package AppBundle\Admin
 */
class VoteAdmin extends Admin
{
    /**
     * Configure the fields available in the edition and creation page
     * @param FormMapper $formMapper
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper->add('dateVote', 'date');
        $formMapper->add('vote', 'checkbox', array('required' => false));
        $formMapper->add('hunt', 'entity', array('class' => 'AppBundle\Entity\Hunt',));
        $formMapper->add('hunter', 'entity', array('class' => 'AppBundle\Entity\Hunter'));
    }

    /**
     * Configure all the filter available
     * @param DatagridMapper $datagridMapper
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper->add('id');
    }

    /**
     * Configure the fields available in the list view
     * @param ListMapper $listMapper
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper->addIdentifier('id');
        $listMapper->addIdentifier('dateVote');
        $listMapper->addIdentifier('vote');
        $listMapper->addIdentifier('hunt');
        $listMapper->addIdentifier('hunter');
    }
}


text:
import sys
import os
import subprocess

# input/output utils
def ask(question, default='yes'):
    """
    Ask a yes/no question via raw_input() and return their answer.

    source: http://stackoverflow.com/questions/3041986/python-command-line-yes-no-input
    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
    It must be "yes" (the default), "no" or None (meaning
        an answer is required of the user).

    The "answer" return value is True for "yes" or False for "no".
    """

    valid = {
        'yes': True, 'y': True, 'ye': True,
        'no': False, 'n': False}

    if default is None:
        prompt = ' [y/n] '
    elif default == 'yes':
        prompt = ' [Y/n] '
    elif default == 'no':
        prompt = ' [y/N] '
    else:
        raise ValueError('Invalid default answer: "%s"' % default)

    while True:
        sys.stdout.write(question + prompt)
        choice = raw_input().lower().strip()
        if default is not None and choice == '':
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write(
                'Please respond with "yes" or "no" '
                '(or "y" or "n").\n')

def get_input(prompt, default=None):
    """
    Get user's input, only checking for non-empty response.
    """
    user_input = ''
    if default is not None:
        prompt = (
            '{prompt} (default: {})').format(default, prompt=prompt)

    while user_input == '':
        user_input = raw_input(prompt + '\n').strip()

        if user_input == '':
            if default is not None:
                user_input = default
            else:
                print 'The value cannot be blank.'

    return user_input

# helper functions converted from one line script utils to python callable
def print_warn(msg):
    call_command('tput setaf 3')  # 3 = yellow
    sys.stdout.write('[ WARNING ]\n')
    call_command('tput sgr0')
    sys.stderr.write(msg + '\n')

def print_failure():
    call_command('tput setaf 1')  # 1 = red
    print_right('[ FAILED ]')
    call_command('tput sgr0')

def print_success():
    call_command('tput setaf 2')  # 2 = green
    print_right('[ OK ]')
    call_command('tput sgr0')

def print_step(msg):
    call_command('tput setaf 6')
    sys.stdout.write(msg + '\n')
    call_command('tput sgr0')

def print_right(msg):
    call_command('tput cuu1')
    call_command('tput cuf $(tput cols)')
    call_command('tput cub %d' % len(msg))
    sys.stdout.write(msg + '\n')

def exit_with_message(msg):
    sys.stderr.write(msg + '\n')
    sys.exit(1)

def exit_with_failrue(msg):
    print_failure()
    exit_with_message(msg)

# utils using subprocess
def call_command(command):
    """
    Process the given command in a bash shell and return the returncode.

    Warning: Make sure the command is sanitized before
    calling this function to prevent any vulnerability.
    """
    res = subprocess.call(
        command, shell=True,
        executable='/bin/bash')
    return res

def command_exists(command):
    """check if hash can find a path for the command

    From install.sh
    """
    res = call_command('hash ' + command + ' >/dev/null 2>&1')
    if res != 0:
        return False
    else:
        return True

def get_command_output(command):
    try:
        res = subprocess.check_output(
            command, shell=True,
            stderr=subprocess.STDOUT,
            executable='/bin/bash')
    except:
        res = None

    return res

# utils using os
def check_path_exists(path, expand=False):
    if(expand):
        path = os.path.expanduser(path)

    return os.path.exists(path)

# Other helpers
def write_file(filename):
    try:
        out = open(filename, 'w')
    except:
        sys.stderr.write('Unable to write %s.\n' % filename)
        out = None
    return out

def get_http_status(url):
    status_cmd = 'curl --head -s ' + url + ' | head -n 1'
    return get_command_output(status_cmd)

if __name__ == '__main__':
    print_warn('This is for testing install_utils.py')
    ask('Begin testing')
    print call_command('ls > /dev/null')
    print command_exists('python')
    print_step('Next step is')
    print_warn('REALLY long text'*10)
    get_input('just checking:', 'default')


text:
import domUtils from './domUtils';

const utils = {

  getContainerDimensions(containerNode) {
    let width, height, scroll;

    if (containerNode.tagName === 'BODY') {
      width = window.innerWidth;
      height = window.innerHeight;
      scroll =
        domUtils.ownerDocument(containerNode).documentElement.scrollTop ||
        containerNode.scrollTop;
    } else {
      width = containerNode.offsetWidth;
      height = containerNode.offsetHeight;
      scroll = containerNode.scrollTop;
    }

    return {width, height, scroll};
  },

  getPosition(target, container) {
    const offset = container.tagName === 'BODY' ?
      domUtils.getOffset(target) : domUtils.getPosition(target, container);

    return {
      ...offset,

      // In Firefox, the target does not have a offsetHeight or offsetWidth
      // property. For now, default them to 0 to keep code from breaking.
      height: target.offsetHeight || 0,
      width: target.offsetWidth || 0
    };
  },

  calcOverlayPosition(placement, overlayNode, target, container, padding) {
    const childOffset = utils.getPosition(target, container);

    const overlayHeight = overlayNode.offsetHeight;
    const overlayWidth = overlayNode.offsetWidth;

    let positionLeft, positionTop, arrowOffsetLeft, arrowOffsetTop;

    if (placement === 'left' || placement === 'right') {
      positionTop = childOffset.top + (childOffset.height - overlayHeight) / 2;

      if (placement === 'left') {
        positionLeft = childOffset.left - overlayWidth;
      } else {
        positionLeft = childOffset.left + childOffset.width;
      }

      const topDelta = getTopDelta(positionTop, overlayHeight, container, padding);

      positionTop += topDelta;
      arrowOffsetTop = 50 * (1 - 2 * topDelta / overlayHeight) + '%';
      arrowOffsetLeft = null;

    } else if (placement === 'top' || placement === 'bottom') {
      positionLeft = childOffset.left + (childOffset.width - overlayWidth) / 2;

      if (placement === 'top') {
        positionTop = childOffset.top - overlayHeight;
      } else {
        positionTop = childOffset.top + childOffset.height;
      }

      const leftDelta = getLeftDelta(positionLeft, overlayWidth, container, padding);
      positionLeft += leftDelta;
      arrowOffsetLeft = 50 * (1 - 2 * leftDelta / overlayWidth) + '%';
      arrowOffsetTop = null;
    } else {
      throw new Error(
        `calcOverlayPosition(): No such placement of "${placement }" found.`
      );
    }

    return { positionLeft, positionTop, arrowOffsetLeft, arrowOffsetTop };
  }
};

function getTopDelta(top, overlayHeight, container, padding) {
  const containerDimensions = utils.getContainerDimensions(container);
  const containerScroll = containerDimensions.scroll;
  const containerHeight = containerDimensions.height;

  const topEdgeOffset = top - padding - containerScroll;
  const bottomEdgeOffset = top + padding - containerScroll + overlayHeight;

  if (topEdgeOffset < 0) {
    return -topEdgeOffset;
  } else if (bottomEdgeOffset > containerHeight) {
    return containerHeight - bottomEdgeOffset;
  } else {
    return 0;
  }
}

function getLeftDelta(left, overlayWidth, container, padding) {
  const containerDimensions = utils.getContainerDimensions(container);
  const containerWidth = containerDimensions.width;

  const leftEdgeOffset = left - padding;
  const rightEdgeOffset = left + padding + overlayWidth;

  if (leftEdgeOffset < 0) {
    return -leftEdgeOffset;
  } else if (rightEdgeOffset > containerWidth) {
    return containerWidth - rightEdgeOffset;
  } else {
    return 0;
  }
}
export default utils;


text:
<?php
/**
 * PackageResponse
 *
 * PHP version 5
 *
 * @category Class
 * @package  InPlayer
 * @author   Swaagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * InPlayer APIs
 *
 * Our Paywall platform enables you up to create a detailed subscription business, allowing you to build a consumer base and drive significant revenues. Our paywall supports recurring payments and billing, consumer acquisition, subscriber lifecycle management and gives you consumer retention CRM tools.
 *
 * OpenAPI spec version: 1.0.0
 * Contact: support@inplayer.com
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace InPlayer\Models;

use \ArrayAccess;

/**
 * PackageResponse Class Doc Comment
 *
 * @category    Class
 * @package     InPlayer
 * @author      Swagger Codegen team
 * @link        https://github.com/swagger-api/swagger-codegen
 */
class PackageResponse implements ArrayAccess
{
    const DISCRIMINATOR = null;

    /**
      * The original name of the model.
      * @var string
      */
    protected static $swaggerModelName = 'PackageResponse';

    /**
      * Array of property to type mappings. Used for (de)serialization
      * @var string[]
      */
    protected static $swaggerTypes = [
        'number_of_items' => 'int',
        'access_fees' => '\InPlayer\Models\AccessFee[]'
    ];

    /**
      * Array of property to format mappings. Used for (de)serialization
      * @var string[]
      */
    protected static $swaggerFormats = [
        'number_of_items' => null,
        'access_fees' => null
    ];

    public static function swaggerTypes()
    {
        return self::$swaggerTypes;
    }

    public static function swaggerFormats()
    {
        return self::$swaggerFormats;
    }

    /**
     * Array of attributes where the key is the local name, and the value is the original name
     * @var string[]
     */
    protected static $attributeMap = [
        'number_of_items' => 'number_of_items',
        'access_fees' => 'access_fees'
    ];

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     * @var string[]
     */
    protected static $setters = [
        'number_of_items' => 'setNumberOfItems',
        'access_fees' => 'setAccessFees'
    ];

    /**
     * Array of attributes to getter functions (for serialization of requests)
     * @var string[]
     */
    protected static $getters = [
        'number_of_items' => 'getNumberOfItems',
        'access_fees' => 'getAccessFees'
    ];

    public static function attributeMap()
    {
        return self::$attributeMap;
    }

    public static function setters()
    {
        return self::$setters;
    }

    public static function getters()
    {
        return self::$getters;
    }

    /**
     * Associative array for storing property values
     * @var mixed[]
     */
    protected $container = [];

    /**
     * Constructor
     * @param mixed[] $data Associated array of property values initializing the model
     */
    public function __construct(array $data = null)
    {
        $this->container['number_of_items'] = isset($data['number_of_items']) ? $data['number_of_items'] : null;
        $this->container['access_fees'] = isset($data['access_fees']) ? $data['access_fees'] : null;
    }

    /**
     * show all the invalid properties with reasons.
     *
     * @return array invalid properties with reasons
     */
    public function listInvalidProperties()
    {
        $invalid_properties = [];

        return $invalid_properties;
    }

    /**
     * validate all the properties in the model
     * return true if all passed
     *
     * @return bool True if all properties are valid
     */
    public function valid()
    {

        return true;
    }

    /**
     * Gets number_of_items
     * @return int
     */
    public function getNumberOfItems()
    {
        return $this->container['number_of_items'];
    }

    /**
     * Sets number_of_items
     * @param int $number_of_items
     * @return $this
     */
    public function setNumberOfItems($number_of_items)
    {
        $this->container['number_of_items'] = $number_of_items;

        return $this;
    }

    /**
     * Gets access_fees
     * @return \InPlayer\Models\AccessFee[]
     */
    public function getAccessFees()
    {
        return $this->container['access_fees'];
    }

    /**
     * Sets access_fees
     * @param \InPlayer\Models\AccessFee[] $access_fees
     * @return $this
     */
    public function setAccessFees($access_fees)
    {
        $this->container['access_fees'] = $access_fees;

        return $this;
    }
    /**
     * Returns true if offset exists. False otherwise.
     * @param  integer $offset Offset
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * Gets offset.
     * @param  integer $offset Offset
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    /**
     * Sets value based on offset.
     * @param  integer $offset Offset
     * @param  mixed   $value  Value to be set
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * Unsets offset.
     * @param  integer $offset Offset
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * Gets the string presentation of the object
     * @return string
     */
    public function __toString()
    {
        if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
            return json_encode(\InPlayer\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT);
        }

        return json_encode(\InPlayer\ObjectSerializer::sanitizeForSerialization($this));
    }
}


text:
module Sequel
  class Dataset
    # ---------------------
    # :section: 7 - Mutation methods
    # These methods modify the receiving dataset and should be used with care.
    # ---------------------

    # All methods that should have a ! method added that modifies the receiver.
    MUTATION_METHODS = QUERY_METHODS - [:naked, :from_self]

    # Setup mutation (e.g. filter!) methods.  These operate the same as the
    # non-! methods, but replace the options of the current dataset with the
    # options of the resulting dataset.
    #
    # Do not call this method with untrusted input, as that can result in
    # arbitrary code execution.
    def self.def_mutation_method(*meths)
      options = meths.pop if meths.last.is_a?(Hash)
      mod = options[:module] if options
      mod ||= self
      meths.each do |meth|
        mod.class_eval("def #{meth}!(*args, &block); mutation_method(:#{meth}, *args, &block) end", __FILE__, __LINE__)
      end
    end

    # Add the mutation methods via metaprogramming
    def_mutation_method(*MUTATION_METHODS)

    # The row_proc for this database, should be any object that responds to +call+ with
    # a single hash argument and returns the object you want #each to return.
    attr_reader :row_proc

    # Load an extension into the receiver.  In addition to requiring the extension file, this
    # also modifies the dataset to work with the extension (usually extending it with a
    # module defined in the extension file).  If no related extension file exists or the
    # extension does not have specific support for Database objects, an Error will be raised.
    # Returns self.
    def extension!(*exts)
      raise_if_frozen!
      Sequel.extension(*exts)
      exts.each do |ext|
        if pr = Sequel.synchronize{EXTENSIONS[ext]}
          pr.call(self)
        else
          raise(Error, "Extension #{ext} does not have specific support handling individual datasets")
        end
      end
      self
    end

    # Avoid self-referential dataset by cloning.
    def from_self!(*args, &block)
      raise_if_frozen!
      @opts = clone.from_self(*args, &block).opts
      self
    end

    # Set the method to call on identifiers going into the database for this dataset
    def identifier_input_method=(v)
      raise_if_frozen!
      @identifier_input_method = v
    end

    # Set the method to call on identifiers coming the database for this dataset
    def identifier_output_method=(v)
      raise_if_frozen!
      @identifier_output_method = v
    end

    # Remove the row_proc from the current dataset.
    def naked!
      raise_if_frozen!
      self.row_proc = nil
      self
    end

    # Set whether to quote identifiers for this dataset
    def quote_identifiers=(v)
      raise_if_frozen!
      @quote_identifiers = v
    end

    # Override the row_proc for this dataset
    def row_proc=(v)
      raise_if_frozen!
      @row_proc = v
    end

    private

    # Modify the receiver with the results of sending the meth, args, and block
    # to the receiver and merging the options of the resulting dataset into
    # the receiver's options.
    def mutation_method(meth, *args, &block)
      raise_if_frozen!
      @opts = send(meth, *args, &block).opts
      self
    end

    # Raise a RuntimeError if the receiver is frozen
    def raise_if_frozen!
      if frozen?
        raise RuntimeError, "can't modify frozen #{visible_class_name}"
      end
    end
  end
end


text:
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import inspect
from sqlalchemy import Integer
from sqlalchemy import literal
from sqlalchemy import literal_column
from sqlalchemy import null
from sqlalchemy import select
from sqlalchemy import String
from sqlalchemy import testing
from sqlalchemy.orm import aliased
from sqlalchemy.orm import Bundle
from sqlalchemy.orm import class_mapper
from sqlalchemy.orm import create_session
from sqlalchemy.orm import joinedload
from sqlalchemy.orm import mapper
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import subqueryload
from sqlalchemy.orm import with_polymorphic
from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import Table

class SingleInheritanceTest(testing.AssertsCompiledSQL, fixtures.MappedTest):
    __dialect__ = "default"

    @classmethod
    def define_tables(cls, metadata):
        Table(
            "employees",
            metadata,
            Column(
                "employee_id",
                Integer,
                primary_key=True,
                test_needs_autoincrement=True,
            ),
            Column("name", String(50)),
            Column("manager_data", String(50)),
            Column("engineer_info", String(50)),
            Column("type", String(20)),
        )

        Table(
            "reports",
            metadata,
            Column(
                "report_id",
                Integer,
                primary_key=True,
                test_needs_autoincrement=True,
            ),
            Column("employee_id", ForeignKey("employees.employee_id")),
            Column("name", String(50)),
        )

    @classmethod
    def setup_classes(cls):
        global Employee, Manager, Engineer, JuniorEngineer

        class Employee(cls.Comparable):
            pass

        class Manager(Employee):
            pass

        class Engineer(Employee):
            pass

        class JuniorEngineer(Engineer):
            pass

    @classmethod
    def setup_mappers(cls):
        Employee, Manager, JuniorEngineer, employees, Engineer = (
            cls.classes.Employee,
            cls.classes.Manager,
            cls.classes.JuniorEngineer,
            cls.tables.employees,
            cls.classes.Engineer,
        )

        mapper(Employee, employees, polymorphic_on=employees.c.type)
        mapper(Manager, inherits=Employee, polymorphic_identity="manager")
        mapper(Engineer, inherits=Employee, polymorphic_identity="engineer")
        mapper(
            JuniorEngineer,
            inherits=Engineer,
            polymorphic_identity="juniorengineer",
        )

    def _fixture_one(self):
        JuniorEngineer, Manager, Engineer = (
            self.classes.JuniorEngineer,
            self.classes.Manager,
            self.classes.Engineer,
        )

        session = create_session()

        m1 = Manager(name="Tom", manager_data="knows how to manage things")
        e1 = Engineer(name="Kurt", engineer_info="knows how to hack")
        e2 = JuniorEngineer(name="Ed", engineer_info="oh that ed")
        session.add_all([m1, e1, e2])
        session.flush()
        return session, m1, e1, e2

    def test_single_inheritance(self):
        Employee, JuniorEngineer, Manager, Engineer = (
            self.classes.Employee,
            self.classes.JuniorEngineer,
            self.classes.Manager,
            self.classes.Engineer,
        )

        session, m1, e1, e2 = self._fixture_one()

        assert session.query(Employee).all() == [m1, e1, e2]
        assert session.query(Engineer).all() == [e1, e2]
        assert session.query(Manager).all() == [m1]
        assert session.query(JuniorEngineer).all() == [e2]

        m1 = session.query(Manager).one()
        session.expire(m1, ["manager_data"])
        eq_(m1.manager_data, "knows how to manage things")

        row = (
            session.query(Engineer.name, Engineer.employee_id)
            .filter(Engineer.name == "Kurt")
            .first()
        )
        assert row.name == "Kurt"
        assert row.employee_id == e1.employee_id

    def test_multi_qualification(self):
        Manager, Engineer = (self.classes.Manager, self.classes.Engineer)

        session, m1, e1, e2 = self._fixture_one()

        ealias = aliased(Engineer)
        eq_(session.query(Manager, ealias).all(), [(m1, e1), (m1, e2)])

        eq_(session.query(Manager.name).all(), [("Tom",)])

        eq_(
            session.query(Manager.name, ealias.name).all(),
            [("Tom", "Kurt"), ("Tom", "Ed")],
        )

        eq_(
            session.query(
                func.upper(Manager.name), func.upper(ealias.name)
            ).all(),
            [("TOM", "KURT"), ("TOM", "ED")],
        )

        eq_(
            session.query(Manager).add_entity(ealias).all(),
            [(m1, e1), (m1, e2)],
        )

        eq_(
            session.query(Manager.name).add_column(ealias.name).all(),
            [("Tom", "Kurt"), ("Tom", "Ed")],
        )

        # TODO: I think raise error on this for now
        # self.assertEquals(
        #    session.query(Employee.name, Manager.manager_data,
        #    Engineer.engineer_info).all(),
        #    []
        # )

    def test_column_qualification(self):
        Employee, JuniorEngineer, Manager, Engineer = (
            self.classes.Employee,
            self.classes.JuniorEngineer,
            self.classes.Manager,
            self.classes.Engineer,
        )

        session, m1, e1, e2 = self._fixture_one()

        m1id, e1id, e2id = m1.employee_id, e1.employee_id, e2.employee_id

        def scalar(q):
            return [x for x, in q]

        eq_(scalar(session.query(Employee.employee_id)), [m1id, e1id, e2id])

        eq_(scalar(session.query(Engineer.employee_id)), [e1id, e2id])

        eq_(scalar(session.query(Manager.employee_id)), [m1id])

        # this currently emits "WHERE type IN (?, ?) AND type IN (?, ?)",
        # so no result.
        eq_(session.query(Manager.employee_id, Engineer.employee_id).all(), [])

        eq_(scalar(session.query(JuniorEngineer.employee_id)), [e2id])

    def test_bundle_qualification(self):
        Employee, JuniorEngineer, Manager, Engineer = (
            self.classes.Employee,
            self.classes.JuniorEngineer,
            self.classes.Manager,
            self.classes.Engineer,
        )

        session, m1, e1, e2 = self._fixture_one()

        m1id, e1id, e2id = m1.employee_id, e1.employee_id, e2.employee_id

        def scalar(q):
            return [x[0] for x, in q]

        eq_(
            scalar(session.query(Bundle("name", Employee.employee_id))),
            [m1id, e1id, e2id],
        )

        eq_(
            scalar(session.query(Bundle("name", Engineer.employee_id))),
            [e1id, e2id],
        )

        eq_(scalar(session.query(Bundle("name", Manager.employee_id))), [m1id])

        # this currently emits "WHERE type IN (?, ?) AND type IN (?, ?)",
        # so no result.
        eq_(
            session.query(
                Bundle("name", Manager.employee_id, Engineer.employee_id)
            ).all(),
            [],
        )

        eq_(
            scalar(session.query(Bundle("name", JuniorEngineer.employee_id))),
            [e2id],
        )

    def test_from_self(self):
        Engineer = self.classes.Engineer

        sess = create_session()
        self.assert_compile(
            sess.query(Engineer).from_self(),
            "SELECT anon_1.employees_employee_id AS "
            "anon_1_employees_employee_id, "
            "anon_1.employees_name AS "
            "anon_1_employees_name, "
            "anon_1.employees_manager_data AS "
            "anon_1_employees_manager_data, "
            "anon_1.employees_engineer_info AS "
            "anon_1_employees_engineer_info, "
            "anon_1.employees_type AS "
            "anon_1_employees_type FROM (SELECT "
            "employees.employee_id AS "
            "employees_employee_id, employees.name AS "
            "employees_name, employees.manager_data AS "
            "employees_manager_data, "
            "employees.engineer_info AS "
            "employees_engineer_info, employees.type "
            "AS employees_type FROM employees WHERE "
            "employees.type IN (:type_1, :type_2)) AS "
            "anon_1",
            use_default_dialect=True,
        )

    def test_select_from_aliased_w_subclass(self):
        Engineer = self.classes.Engineer

        sess = create_session()

        a1 = aliased(Engineer)
        self.assert_compile(
            sess.query(a1.employee_id).select_from(a1),
            "SELECT employees_1.employee_id AS employees_1_employee_id "
            "FROM employees AS employees_1 WHERE employees_1.type "
            "IN (:type_1, :type_2)",
        )

        self.assert_compile(
            sess.query(literal("1")).select_from(a1),
            "SELECT :param_1 AS param_1 FROM employees AS employees_1 "
            "WHERE employees_1.type IN (:type_1, :type_2)",
        )

    def test_union_modifiers(self):
        Engineer, Manager = self.classes("Engineer", "Manager")

        sess = create_session()
        q1 = sess.query(Engineer).filter(Engineer.engineer_info == "foo")
        q2 = sess.query(Manager).filter(Manager.manager_data == "bar")

        assert_sql = (
            "SELECT anon_1.employees_employee_id AS "
            "anon_1_employees_employee_id, "
            "anon_1.employees_name AS anon_1_employees_name, "
            "anon_1.employees_manager_data AS anon_1_employees_manager_data, "
            "anon_1.employees_engineer_info AS anon_1_employees_engineer_info, "  # noqa
            "anon_1.employees_type AS anon_1_employees_type "
            "FROM (SELECT employees.employee_id AS employees_employee_id, "
            "employees.name AS employees_name, "
            "employees.manager_data AS employees_manager_data, "
            "employees.engineer_info AS employees_engineer_info, "
            "employees.type AS employees_type FROM employees "
            "WHERE employees.engineer_info = :engineer_info_1 "
            "AND employees.type IN (:type_1, :type_2) "
            "%(token)s "
            "SELECT employees.employee_id AS employees_employee_id, "
            "employees.name AS employees_name, "
            "employees.manager_data AS employees_manager_data, "
            "employees.engineer_info AS employees_engineer_info, "
            "employees.type AS employees_type FROM employees "
            "WHERE employees.manager_data = :manager_data_1 "
            "AND employees.type IN (:type_3)) AS anon_1"
        )

        for meth, token in [
            (q1.union, "UNION"),
            (q1.union_all, "UNION ALL"),
            (q1.except_, "EXCEPT"),
            (q1.except_all, "EXCEPT ALL"),
            (q1.intersect, "INTERSECT"),
            (q1.intersect_all, "INTERSECT ALL"),
        ]:
            self.assert_compile(
                meth(q2),
                assert_sql % {"token": token},
                checkparams={
                    "manager_data_1": "bar",
                    "type_2": "juniorengineer",
                    "type_3": "manager",
                    "engineer_info_1": "foo",
                    "type_1": "engineer",
                },
            )

    def test_from_self_count(self):
        Engineer = self.classes.Engineer

        sess = create_session()
        col = func.count(literal_column("*"))
        self.assert_compile(
            sess.query(Engineer.employee_id).from_self(col),
            "SELECT count(*) AS count_1 "
            "FROM (SELECT employees.employee_id AS employees_employee_id "
            "FROM employees "
            "WHERE employees.type IN (:type_1, :type_2)) AS anon_1",
            use_default_dialect=True,
        )

    def test_select_from_count(self):
        Manager, Engineer = (self.classes.Manager, self.classes.Engineer)

        sess = create_session()
        m1 = Manager(name="Tom", manager_data="data1")
        e1 = Engineer(name="Kurt", engineer_info="knows how to hack")
        sess.add_all([m1, e1])
        sess.flush()

        eq_(sess.query(func.count(1)).select_from(Manager).all(), [(1,)])

    def test_select_from_subquery(self):
        Manager, JuniorEngineer, employees, Engineer = (
            self.classes.Manager,
            self.classes.JuniorEngineer,
            self.tables.employees,
            self.classes.Engineer,
        )

        sess = create_session()
        m1 = Manager(name="Tom", manager_data="data1")
        m2 = Manager(name="Tom2", manager_data="data2")
        e1 = Engineer(name="Kurt", engineer_info="knows how to hack")
        e2 = JuniorEngineer(name="Ed", engineer_info="oh that ed")
        sess.add_all([m1, m2, e1, e2])
        sess.flush()

        eq_(
            sess.query(Manager)
            .select_from(employees.select().limit(10))
            .all(),
            [m1, m2],
        )

    def test_count(self):
        Employee = self.classes.Employee
        JuniorEngineer = self.classes.JuniorEngineer
        Manager = self.classes.Manager
        Engineer = self.classes.Engineer

        sess = create_session()
        m1 = Manager(name="Tom", manager_data="data1")
        m2 = Manager(name="Tom2", manager_data="data2")
        e1 = Engineer(name="Kurt", engineer_info="data3")
        e2 = JuniorEngineer(name="marvin", engineer_info="data4")
        sess.add_all([m1, m2, e1, e2])
        sess.flush()

        eq_(sess.query(Manager).count(), 2)
        eq_(sess.query(Engineer).count(), 2)
        eq_(sess.query(Employee).count(), 4)

        eq_(sess.query(Manager).filter(Manager.name.like("%m%")).count(), 2)
        eq_(sess.query(Employee).filter(Employee.name.like("%m%")).count(), 3)

    def test_exists_standalone(self):
        Engineer = self.classes.Engineer

        sess = create_session()

        self.assert_compile(
            sess.query(
                sess.query(Engineer).filter(Engineer.name == "foo").exists()
            ),
            "SELECT EXISTS (SELECT 1 FROM employees WHERE "
            "employees.name = :name_1 AND employees.type "
            "IN (:type_1, :type_2)) AS anon_1",
        )

    def test_type_filtering(self):
        Employee, Manager, reports, Engineer = (
            self.classes.Employee,
            self.classes.Manager,
            self.tables.reports,
            self.classes.Engineer,
        )

        class Report(fixtures.ComparableEntity):
            pass

        mapper(
            Report,
            reports,
            properties={"employee": relationship(Employee, backref="reports")},
        )
        sess = create_session()

        m1 = Manager(name="Tom", manager_data="data1")
        r1 = Report(employee=m1)
        sess.add_all([m1, r1])
        sess.flush()
        rq = sess.query(Report)

        assert (
            len(rq.filter(Report.employee.of_type(Manager).has()).all()) == 1
        )
        assert (
            len(rq.filter(Report.employee.of_type(Engineer).has()).all()) == 0
        )

    def test_type_joins(self):
        Employee, Manager, reports, Engineer = (
            self.classes.Employee,
            self.classes.Manager,
            self.tables.reports,
            self.classes.Engineer,
        )

        class Report(fixtures.ComparableEntity):
            pass

        mapper(
            Report,
            reports,
            properties={"employee": relationship(Employee, backref="reports")},
        )
        sess = create_session()

        m1 = Manager(name="Tom", manager_data="data1")
        r1 = Report(employee=m1)
        sess.add_all([m1, r1])
        sess.flush()

        rq = sess.query(Report)

        assert len(rq.join(Report.employee.of_type(Manager)).all()) == 1
        assert len(rq.join(Report.employee.of_type(Engineer)).all()) == 0

class RelationshipFromSingleTest(
    testing.AssertsCompiledSQL, fixtures.MappedTest
):
    @classmethod
    def define_tables(cls, metadata):
        Table(
            "employee",
            metadata,
            Column(
                "id", Integer, primary_key=True, test_needs_autoincrement=True
            ),
            Column("name", String(50)),
            Column("type", String(20)),
        )

        Table(
            "employee_stuff",
            metadata,
            Column(
                "id", Integer, primary_key=True, test_needs_autoincrement=True
            ),
            Column("employee_id", Integer, ForeignKey("employee.id")),
            Column("name", String(50)),
        )

    @classmethod
    def setup_classes(cls):
        class Employee(cls.Comparable):
            pass

        class Manager(Employee):
            pass

        class Stuff(cls.Comparable):
            pass

    def test_subquery_load(self):
        employee, employee_stuff, Employee, Stuff, Manager = (
            self.tables.employee,
            self.tables.employee_stuff,
            self.classes.Employee,
            self.classes.Stuff,
            self.classes.Manager,
        )

        mapper(
            Employee,
            employee,
            polymorphic_on=employee.c.type,
            polymorphic_identity="employee",
        )
        mapper(
            Manager,
            inherits=Employee,
            polymorphic_identity="manager",
            properties={"stuff": relationship(Stuff)},
        )
        mapper(Stuff, employee_stuff)

        sess = create_session()
        context = (
            sess.query(Manager)
            .options(subqueryload("stuff"))
            ._compile_context()
        )
        subq = context.attributes[
            (
                "subquery",
                (class_mapper(Manager), class_mapper(Manager).attrs.stuff),
            )
        ]

        self.assert_compile(
            subq,
            "SELECT employee_stuff.id AS "
            "employee_stuff_id, employee_stuff.employee"
            "_id AS employee_stuff_employee_id, "
            "employee_stuff.name AS "
            "employee_stuff_name, anon_1.employee_id "
            "AS anon_1_employee_id FROM (SELECT "
            "employee.id AS employee_id FROM employee "
            "WHERE employee.type IN (:type_1)) AS anon_1 "
            "JOIN employee_stuff ON anon_1.employee_id "
            "= employee_stuff.employee_id",
            use_default_dialect=True,
        )

class RelationshipToSingleTest(
    testing.AssertsCompiledSQL, fixtures.MappedTest
):
    __dialect__ = "default"

    @classmethod
    def define_tables(cls, metadata):
        Table(
            "employees",
            metadata,
            Column(
                "employee_id",
                Integer,
                primary_key=True,
                test_needs_autoincrement=True,
            ),
            Column("name", String(50)),
            Column("manager_data", String(50)),
            Column("engineer_info", String(50)),
            Column("type", String(20)),
            Column("company_id", Integer, ForeignKey("companies.company_id")),
        )

        Table(
            "companies",
            metadata,
            Column(
                "company_id",
                Integer,
                primary_key=True,
                test_needs_autoincrement=True,
            ),
            Column("name", String(50)),
        )

    @classmethod
    def setup_classes(cls):
        class Company(cls.Comparable):
            pass

        class Employee(cls.Comparable):
            pass

        class Manager(Employee):
            pass

        class Engineer(Employee):
            pass

        class JuniorEngineer(Engineer):
            pass

    def test_of_type(self):
        (
            JuniorEngineer,
            Company,
            companies,
            Manager,
            Employee,
            employees,
            Engineer,
        ) = (
            self.classes.JuniorEngineer,
            self.classes.Company,
            self.tables.companies,
            self.classes.Manager,
            self.classes.Employee,
            self.tables.employees,
            self.classes.Engineer,
        )

        mapper(
            Company,
            companies,
            properties={
                "employees": relationship(Employee, backref="company")
            },
        )
        mapper(Employee, employees, polymorphic_on=employees.c.type)
        mapper(Manager, inherits=Employee, polymorphic_identity="manager")
        mapper(Engineer, inherits=Employee, polymorphic_identity="engineer")
        mapper(
            JuniorEngineer,
            inherits=Engineer,
            polymorphic_identity="juniorengineer",
        )
        sess = sessionmaker()()

        c1 = Company(name="c1")
        c2 = Company(name="c2")

        m1 = Manager(name="Tom", manager_data="data1", company=c1)
        m2 = Manager(name="Tom2", manager_data="data2", company=c2)
        e1 = Engineer(
            name="Kurt", engineer_info="knows how to hack", company=c2
        )
        e2 = JuniorEngineer(name="Ed", engineer_info="oh that ed", company=c1)
        sess.add_all([c1, c2, m1, m2, e1, e2])
        sess.commit()
        sess.expunge_all()
        eq_(
            sess.query(Company)
            .filter(Company.employees.of_type(JuniorEngineer).any())
            .all(),
            [Company(name="c1")],
        )

        eq_(
            sess.query(Company)
            .join(Company.employees.of_type(JuniorEngineer))
            .all(),
            [Company(name="c1")],
        )

    def test_of_type_aliased_fromjoinpoint(self):
        Company, Employee, Engineer = (
            self.classes.Company,
            self.classes.Employee,
            self.classes.Engineer,
        )
        companies, employees = self.tables.companies, self.tables.employees

        mapper(
            Company, companies, properties={"employee": relationship(Employee)}
        )
        mapper(Employee, employees, polymorphic_on=employees.c.type)
        mapper(Engineer, inherits=Employee, polymorphic_identity="engineer")

        sess = create_session()
        self.assert_compile(
            sess.query(Company).outerjoin(
                Company.employee.of_type(Engineer),
                aliased=True,
                from_joinpoint=True,
            ),
            "SELECT companies.company_id AS companies_company_id, "
            "companies.name AS companies_name FROM companies "
            "LEFT OUTER JOIN employees AS employees_1 ON "
            "companies.company_id = employees_1.company_id "
            "AND employees_1.type IN (:type_1)",
        )

    def test_join_explicit_onclause_no_discriminator(self):
        # test issue #3462
        Company, Employee, Engineer = (
            self.classes.Company,
            self.classes.Employee,
            self.classes.Engineer,
        )
        companies, employees = self.tables.companies, self.tables.employees

        mapper(
            Company,
            companies,
            properties={"employees": relationship(Employee)},
        )
        mapper(Employee, employees)
        mapper(Engineer, inherits=Employee)

        sess = create_session()
        self.assert_compile(
            sess.query(Company, Engineer.name).join(
                Engineer, Company.company_id == Engineer.company_id
            ),
            "SELECT companies.company_id AS companies_company_id, "
            "companies.name AS companies_name, "
            "employees.name AS employees_name "
            "FROM companies JOIN "
            "employees ON companies.company_id = employees.company_id",
        )

    def test_outer_join_prop(self):
        Company, Employee, Engineer = (
            self.classes.Company,
            self.classes.Employee,
            self.classes.Engineer,
        )
        companies, employees = self.tables.companies, self.tables.employees

        mapper(
            Company,
            companies,
            properties={"engineers": relationship(Engineer)},
        )
        mapper(Employee, employees, polymorphic_on=employees.c.type)
        mapper(Engineer, inherits=Employee, polymorphic_identity="engineer")

        sess = create_session()
        self.assert_compile(
            sess.query(Company, Engineer.name).outerjoin("engineers"),
            "SELECT companies.company_id AS companies_company_id, "
            "companies.name AS companies_name, "
            "employees.name AS employees_name "
            "FROM companies LEFT OUTER JOIN employees ON companies.company_id "
            "= employees.company_id AND employees.type IN (:type_1)",
        )

    def test_outer_join_prop_alias(self):
        Company, Employee, Engineer = (
            self.classes.Company,
            self.classes.Employee,
            self.classes.Engineer,
        )
        companies, employees = self.tables.companies, self.tables.employees

        mapper(
            Company,
            companies,
            properties={"engineers": relationship(Engineer)},
        )
        mapper(Employee, employees, polymorphic_on=employees.c.type)
        mapper(Engineer, inherits=Employee, polymorphic_identity="engineer")

        eng_alias = aliased(Engineer)
        sess = create_session()
        self.assert_compile(
            sess.query(Company, eng_alias.name).outerjoin(
                eng_alias, Company.engineers
            ),
            "SELECT companies.company_id AS companies_company_id, "
            "companies.name AS companies_name, employees_1.name AS "
            "employees_1_name FROM companies LEFT OUTER "
            "JOIN employees AS employees_1 ON companies.company_id "
            "= employees_1.company_id AND employees_1.type IN (:type_1)",
        )

    def test_outer_join_literal_onclause(self):
        Company, Employee, Engineer = (
            self.classes.Company,
            self.classes.Employee,
            self.classes.Engineer,
        )
        companies, employees = self.tables.companies, self.tables.employees

        mapper(
            Company,
            companies,
            properties={"engineers": relationship(Engineer)},
        )
        mapper(Employee, employees, polymorphic_on=employees.c.type)
        mapper(Engineer, inherits=Employee, polymorphic_identity="engineer")

        sess = create_session()
        self.assert_compile(
            sess.query(Company, Engineer).outerjoin(
                Engineer, Company.company_id == Engineer.company_id
            ),
            "SELECT companies.company_id AS companies_company_id, "
            "companies.name AS companies_name, "
            "employees.employee_id AS employees_employee_id, "
            "employees.name AS employees_name, "
            "employees.manager_data AS employees_manager_data, "
            "employees.engineer_info AS employees_engineer_info, "
            "employees.type AS employees_type, "
            "employees.company_id AS employees_company_id FROM companies "
            "LEFT OUTER JOIN employees ON "
            "companies.company_id = employees.company_id "
            "AND employees.type IN (:type_1)",
        )

    def test_outer_join_literal_onclause_alias(self):
        Company, Employee, Engineer = (
            self.classes.Company,
            self.classes.Employee,
            self.classes.Engineer,
        )
        companies, employees = self.tables.companies, self.tables.employees

        mapper(
            Company,
            companies,
            properties={"engineers": relationship(Engineer)},
        )
        mapper(Employee, employees, polymorphic_on=employees.c.type)
        mapper(Engineer, inherits=Employee, polymorphic_identity="engineer")

        eng_alias = aliased(Engineer)
        sess = create_session()
        self.assert_compile(
            sess.query(Company, eng_alias).outerjoin(
                eng_alias, Company.company_id == eng_alias.company_id
            ),
            "SELECT companies.company_id AS companies_company_id, "
            "companies.name AS companies_name, "
            "employees_1.employee_id AS employees_1_employee_id, "
            "employees_1.name AS employees_1_name, "
            "employees_1.manager_data AS employees_1_manager_data, "
            "employees_1.engineer_info AS employees_1_engineer_info, "
            "employees_1.type AS employees_1_type, "
            "employees_1.company_id AS employees_1_company_id "
            "FROM companies LEFT OUTER JOIN employees AS employees_1 ON "
            "companies.company_id = employees_1.company_id "
            "AND employees_1.type IN (:type_1)",
        )

    def test_outer_join_no_onclause(self):
        Company, Employee, Engineer = (
            self.classes.Company,
            self.classes.Employee,
            self.classes.Engineer,
        )
        companies, employees = self.tables.companies, self.tables.employees

        mapper(
            Company,
            companies,
            properties={"engineers": relationship(Engineer)},
        )
        mapper(Employee, employees, polymorphic_on=employees.c.type)
        mapper(Engineer, inherits=Employee, polymorphic_identity="engineer")

        sess = create_session()
        self.assert_compile(
            sess.query(Company, Engineer).outerjoin(Engineer),
            "SELECT companies.company_id AS companies_company_id, "
            "companies.name AS companies_name, "
            "employees.employee_id AS employees_employee_id, "
            "employees.name AS employees_name, "
            "employees.manager_data AS employees_manager_data, "
            "employees.engineer_info AS employees_engineer_info, "
            "employees.type AS employees_type, "
            "employees.company_id AS employees_company_id "
            "FROM companies LEFT OUTER JOIN employees ON "
            "companies.company_id = employees.company_id "
            "AND employees.type IN (:type_1)",
        )

    def test_outer_join_no_onclause_alias(self):
        Company, Employee, Engineer = (
            self.classes.Company,
            self.classes.Employee,
            self.classes.Engineer,
        )
        companies, employees = self.tables.companies, self.tables.employees

        mapper(
            Company,
            companies,
            properties={"engineers": relationship(Engineer)},
        )
        mapper(Employee, employees, polymorphic_on=employees.c.type)
        mapper(Engineer, inherits=Employee, polymorphic_identity="engineer")

        eng_alias = aliased(Engineer)
        sess = create_session()
        self.assert_compile(
            sess.query(Company, eng_alias).outerjoin(eng_alias),
            "SELECT companies.company_id AS companies_company_id, "
            "companies.name AS companies_name, "
            "employees_1.employee_id AS employees_1_employee_id, "
            "employees_1.name AS employees_1_name, "
            "employees_1.manager_data AS employees_1_manager_data, "
            "employees_1.engineer_info AS employees_1_engineer_info, "
            "employees_1.type AS employees_1_type, "
            "employees_1.company_id AS employees_1_company_id "
            "FROM companies LEFT OUTER JOIN employees AS employees_1 ON "
            "companies.company_id = employees_1.company_id "
            "AND employees_1.type IN (:type_1)",
        )

    def test_correlated_column_select(self):
        Company, Employee, Engineer = (
            self.classes.Company,
            self.classes.Employee,
            self.classes.Engineer,
        )
        companies, employees = self.tables.companies, self.tables.employees

        mapper(Company, companies)
        mapper(
            Employee,
            employees,
            polymorphic_on=employees.c.type,
            properties={"company": relationship(Company)},
        )
        mapper(Engineer, inherits=Employee, polymorphic_identity="engineer")

        sess = create_session()
        engineer_count = (
            sess.query(func.count(Engineer.employee_id))
            .select_from(Engineer)
            .filter(Engineer.company_id == Company.company_id)
            .correlate(Company)
            .as_scalar()
        )

        self.assert_compile(
            sess.query(Company.company_id, engineer_count),
            "SELECT companies.company_id AS companies_company_id, "
            "(SELECT count(employees.employee_id) AS count_1 "
            "FROM employees WHERE employees.company_id = "
            "companies.company_id AND employees.type IN (:type_1)) AS anon_1 "
            "FROM companies",
        )

    def test_no_aliasing_from_overlap(self):
        # test [ticket:3233]

        Company, Employee, Engineer, Manager = (
            self.classes.Company,
            self.classes.Employee,
            self.classes.Engineer,
            self.classes.Manager,
        )

        companies, employees = self.tables.companies, self.tables.employees

        mapper(
            Company,
            companies,
            properties={
                "employees": relationship(Employee, backref="company")
            },
        )
        mapper(Employee, employees, polymorphic_on=employees.c.type)
        mapper(Engineer, inherits=Employee, polymorphic_identity="engineer")
        mapper(Manager, inherits=Employee, polymorphic_identity="manager")

        s = create_session()

        q1 = (
            s.query(Engineer)
            .join(Engineer.company)
            .join(Manager, Company.employees)
        )

        q2 = (
            s.query(Engineer)
            .join(Engineer.company)
            .join(Manager, Company.company_id == Manager.company_id)
        )

        q3 = (
            s.query(Engineer)
            .join(Engineer.company)
            .join(Manager, Company.employees.of_type(Manager))
        )

        q4 = (
            s.query(Engineer)
            .join(Company, Company.company_id == Engineer.company_id)
            .join(Manager, Company.employees.of_type(Manager))
        )

        q5 = (
            s.query(Engineer)
            .join(Company, Company.company_id == Engineer.company_id)
            .join(Manager, Company.company_id == Manager.company_id)
        )

        # note that the query is incorrect SQL; we JOIN to
        # employees twice.   However, this is what's expected so we seek
        # to be consistent; previously, aliasing would sneak in due to the
        # nature of the "left" side.
        for q in [q1, q2, q3, q4, q5]:
            self.assert_compile(
                q,
                "SELECT employees.employee_id AS employees_employee_id, "
                "employees.name AS employees_name, "
                "employees.manager_data AS employees_manager_data, "
                "employees.engineer_info AS employees_engineer_info, "
                "employees.type AS employees_type, "
                "employees.company_id AS employees_company_id "
                "FROM employees JOIN companies "
                "ON companies.company_id = employees.company_id "
                "JOIN employees "
                "ON companies.company_id = employees.company_id "
                "AND employees.type IN (:type_1) "
                "WHERE employees.type IN (:type_2)",
            )

    def test_relationship_to_subclass(self):
        (
            JuniorEngineer,
            Company,
            companies,
            Manager,
            Employee,
            employees,
            Engineer,
        ) = (
            self.classes.JuniorEngineer,
            self.classes.Company,
            self.tables.companies,
            self.classes.Manager,
            self.classes.Employee,
            self.tables.employees,
            self.classes.Engineer,
        )

        mapper(
            Company,
            companies,
            properties={"engineers": relationship(Engineer)},
        )
        mapper(
            Employee,
            employees,
            polymorphic_on=employees.c.type,
            properties={"company": relationship(Company)},
        )
        mapper(Manager, inherits=Employee, polymorphic_identity="manager")
        mapper(Engineer, inherits=Employee, polymorphic_identity="engineer")
        mapper(
            JuniorEngineer,
            inherits=Engineer,
            polymorphic_identity="juniorengineer",
        )
        sess = sessionmaker()()

        c1 = Company(name="c1")
        c2 = Company(name="c2")

        m1 = Manager(name="Tom", manager_data="data1", company=c1)
        m2 = Manager(name="Tom2", manager_data="data2", company=c2)
        e1 = Engineer(
            name="Kurt", engineer_info="knows how to hack", company=c2
        )
        e2 = JuniorEngineer(name="Ed", engineer_info="oh that ed", company=c1)
        sess.add_all([c1, c2, m1, m2, e1, e2])
        sess.commit()

        eq_(c1.engineers, [e2])
        eq_(c2.engineers, [e1])

        sess.expunge_all()
        eq_(
            sess.query(Company).order_by(Company.name).all(),
            [
                Company(name="c1", engineers=[JuniorEngineer(name="Ed")]),
                Company(name="c2", engineers=[Engineer(name="Kurt")]),
            ],
        )

        # eager load join should limit to only "Engineer"
        sess.expunge_all()
        eq_(
            sess.query(Company)
            .options(joinedload("engineers"))
            .order_by(Company.name)
            .all(),
            [
                Company(name="c1", engineers=[JuniorEngineer(name="Ed")]),
                Company(name="c2", engineers=[Engineer(name="Kurt")]),
            ],
        )

        # join() to Company.engineers, Employee as the requested entity
        sess.expunge_all()
        eq_(
            sess.query(Company, Employee)
            .join(Company.engineers)
            .order_by(Company.name)
            .all(),
            [
                (Company(name="c1"), JuniorEngineer(name="Ed")),
                (Company(name="c2"), Engineer(name="Kurt")),
            ],
        )

        # join() to Company.engineers, Engineer as the requested entity.
        # this actually applies the IN criterion twice which is less than
        # ideal.
        sess.expunge_all()
        eq_(
            sess.query(Company, Engineer)
            .join(Company.engineers)
            .order_by(Company.name)
            .all(),
            [
                (Company(name="c1"), JuniorEngineer(name="Ed")),
                (Company(name="c2"), Engineer(name="Kurt")),
            ],
        )

        # join() to Company.engineers without any Employee/Engineer entity
        sess.expunge_all()
        eq_(
            sess.query(Company)
            .join(Company.engineers)
            .filter(Engineer.name.in_(["Tom", "Kurt"]))
            .all(),
            [Company(name="c2")],
        )

        # this however fails as it does not limit the subtypes to just
        # "Engineer". with joins constructed by filter(), we seem to be
        # following a policy where we don't try to make decisions on how to
        # join to the target class, whereas when using join() we seem to have
        # a lot more capabilities. we might want to document
        # "advantages of join() vs. straight filtering", or add a large
        # section to "inheritance" laying out all the various behaviors Query
        # has.
        @testing.fails_on_everything_except()
        def go():
            sess.expunge_all()
            eq_(
                sess.query(Company)
                .filter(Company.company_id == Engineer.company_id)
                .filter(Engineer.name.in_(["Tom", "Kurt"]))
                .all(),
                [Company(name="c2")],
            )

        go()

class ManyToManyToSingleTest(fixtures.MappedTest, AssertsCompiledSQL):
    __dialect__ = "default"

    @classmethod
    def define_tables(cls, metadata):
        Table(
            "parent",
            metadata,
            Column(
                "id", Integer, primary_key=True, test_needs_autoincrement=True
            ),
        )
        Table(
            "m2m",
            metadata,
            Column(
                "parent_id", Integer, ForeignKey("parent.id"), primary_key=True
            ),
            Column(
                "child_id", Integer, ForeignKey("child.id"), primary_key=True
            ),
        )
        Table(
            "child",
            metadata,
            Column(
                "id", Integer, primary_key=True, test_needs_autoincrement=True
            ),
            Column("discriminator", String(20)),
            Column("name", String(20)),
        )

    @classmethod
    def setup_classes(cls):
        class Parent(cls.Comparable):
            pass

        class Child(cls.Comparable):
            pass

        class SubChild1(Child):
            pass

        class SubChild2(Child):
            pass

    @classmethod
    def setup_mappers(cls):
        mapper(
            cls.classes.Parent,
            cls.tables.parent,
            properties={
                "s1": relationship(
                    cls.classes.SubChild1,
                    secondary=cls.tables.m2m,
                    uselist=False,
                ),
                "s2": relationship(
                    cls.classes.SubChild2, secondary=cls.tables.m2m
                ),
            },
        )
        mapper(
            cls.classes.Child,
            cls.tables.child,
            polymorphic_on=cls.tables.child.c.discriminator,
        )
        mapper(
            cls.classes.SubChild1,
            inherits=cls.classes.Child,
            polymorphic_identity="sub1",
        )
        mapper(
            cls.classes.SubChild2,
            inherits=cls.classes.Child,
            polymorphic_identity="sub2",
        )

    @classmethod
    def insert_data(cls, connection):
        Parent = cls.classes.Parent
        SubChild1 = cls.classes.SubChild1
        SubChild2 = cls.classes.SubChild2
        s = Session(connection)
        s.add_all(
            [
                Parent(
                    s1=SubChild1(name="sc1_1"),
                    s2=[SubChild2(name="sc2_1"), SubChild2(name="sc2_2")],
                )
            ]
        )
        s.commit()

    def test_eager_join(self):
        Parent = self.classes.Parent
        SubChild1 = self.classes.SubChild1

        s = Session()

        p1 = s.query(Parent).options(joinedload(Parent.s1)).all()[0]
        eq_(p1.__dict__["s1"], SubChild1(name="sc1_1"))

    def test_manual_join(self):
        Parent = self.classes.Parent
        Child = self.classes.Child
        SubChild1 = self.classes.SubChild1

        s = Session()

        p1, c1 = s.query(Parent, Child).outerjoin(Parent.s1).all()[0]
        eq_(c1, SubChild1(name="sc1_1"))

    def test_assert_join_sql(self):
        Parent = self.classes.Parent
        Child = self.classes.Child

        s = Session()

        self.assert_compile(
            s.query(Parent, Child).outerjoin(Parent.s1),
            "SELECT parent.id AS parent_id, child.id AS child_id, "
            "child.discriminator AS child_discriminator, "
            "child.name AS child_name "
            "FROM parent LEFT OUTER JOIN (m2m AS m2m_1 "
            "JOIN child ON child.id = m2m_1.child_id "
            "AND child.discriminator IN (:discriminator_1)) "
            "ON parent.id = m2m_1.parent_id",
        )

    def test_assert_joinedload_sql(self):
        Parent = self.classes.Parent

        s = Session()

        self.assert_compile(
            s.query(Parent).options(joinedload(Parent.s1)),
            "SELECT parent.id AS parent_id, child_1.id AS child_1_id, "
            "child_1.discriminator AS child_1_discriminator, "
            "child_1.name AS child_1_name "
            "FROM parent LEFT OUTER JOIN "
            "(m2m AS m2m_1 JOIN child AS child_1 "
            "ON child_1.id = m2m_1.child_id AND child_1.discriminator "
            "IN (:discriminator_1)) ON parent.id = m2m_1.parent_id",
        )

class SingleOnJoinedTest(fixtures.MappedTest):
    @classmethod
    def define_tables(cls, metadata):
        global persons_table, employees_table

        persons_table = Table(
            "persons",
            metadata,
            Column(
                "person_id",
                Integer,
                primary_key=True,
                test_needs_autoincrement=True,
            ),
            Column("name", String(50)),
            Column("type", String(20), nullable=False),
        )

        employees_table = Table(
            "employees",
            metadata,
            Column(
                "person_id",
                Integer,
                ForeignKey("persons.person_id"),
                primary_key=True,
            ),
            Column("employee_data", String(50)),
            Column("manager_data", String(50)),
        )

    def test_single_on_joined(self):
        class Person(fixtures.ComparableEntity):
            pass

        class Employee(Person):
            pass

        class Manager(Employee):
            pass

        mapper(
            Person,
            persons_table,
            polymorphic_on=persons_table.c.type,
            polymorphic_identity="person",
        )
        mapper(
            Employee,
            employees_table,
            inherits=Person,
            polymorphic_identity="engineer",
        )
        mapper(Manager, inherits=Employee, polymorphic_identity="manager")

        sess = create_session()
        sess.add(Person(name="p1"))
        sess.add(Employee(name="e1", employee_data="ed1"))
        sess.add(Manager(name="m1", employee_data="ed2", manager_data="md1"))
        sess.flush()
        sess.expunge_all()

        eq_(
            sess.query(Person).order_by(Person.person_id).all(),
            [
                Person(name="p1"),
                Employee(name="e1", employee_data="ed1"),
                Manager(name="m1", employee_data="ed2", manager_data="md1"),
            ],
        )
        sess.expunge_all()

        eq_(
            sess.query(Employee).order_by(Person.person_id).all(),
            [
                Employee(name="e1", employee_data="ed1"),
                Manager(name="m1", employee_data="ed2", manager_data="md1"),
            ],
        )
        sess.expunge_all()

        eq_(
            sess.query(Manager).order_by(Person.person_id).all(),
            [Manager(name="m1", employee_data="ed2", manager_data="md1")],
        )
        sess.expunge_all()

        def go():
            eq_(
                sess.query(Person)
                .with_polymorphic("*")
                .order_by(Person.person_id)
                .all(),
                [
                    Person(name="p1"),
                    Employee(name="e1", employee_data="ed1"),
                    Manager(
                        name="m1", employee_data="ed2", manager_data="md1"
                    ),
                ],
            )

        self.assert_sql_count(testing.db, go, 1)

class SingleFromPolySelectableTest(
    fixtures.DeclarativeMappedTest, AssertsCompiledSQL
):
    __dialect__ = "default"

    @classmethod
    def setup_classes(cls, with_polymorphic=None, include_sub_defaults=False):
        Base = cls.DeclarativeBasic

        class Employee(Base):
            __tablename__ = "employee"
            id = Column(Integer, primary_key=True)
            name = Column(String(50))
            type = Column(String(50))

            __mapper_args__ = {
                "polymorphic_identity": "employee",
                "polymorphic_on": type,
            }

        class Engineer(Employee):
            __tablename__ = "engineer"
            id = Column(Integer, ForeignKey("employee.id"), primary_key=True)
            engineer_info = Column(String(50))
            manager_id = Column(ForeignKey("manager.id"))
            __mapper_args__ = {"polymorphic_identity": "engineer"}

        class Manager(Employee):
            __tablename__ = "manager"
            id = Column(Integer, ForeignKey("employee.id"), primary_key=True)
            manager_data = Column(String(50))
            __mapper_args__ = {"polymorphic_identity": "manager"}

        class Boss(Manager):
            __mapper_args__ = {"polymorphic_identity": "boss"}

    def _with_poly_fixture(self):
        employee = self.classes.Employee.__table__
        engineer = self.classes.Engineer.__table__
        manager = self.classes.Manager.__table__

        poly = (
            select(
                [
                    employee.c.id,
                    employee.c.type,
                    employee.c.name,
                    manager.c.manager_data,
                    null().label("engineer_info"),
                    null().label("manager_id"),
                ]
            )
            .select_from(employee.join(manager))
            .apply_labels()
            .union_all(
                select(
                    [
                        employee.c.id,
                        employee.c.type,
                        employee.c.name,
                        null().label("manager_data"),
                        engineer.c.engineer_info,
                        engineer.c.manager_id,
                    ]
                )
                .select_from(employee.join(engineer))
                .apply_labels()
            )
            .alias()
        )

        return poly

    def test_wpoly_single_inh_subclass(self):
        poly = with_polymorphic(
            self.classes.Employee,
            [self.classes.Boss, self.classes.Manager, self.classes.Engineer],
            self._with_poly_fixture(),
        )
        s = Session()
        q = s.query(poly.Boss)
        self.assert_compile(
            q,
            "SELECT "
            "anon_1.employee_id AS anon_1_employee_id, "
            "anon_1.employee_name AS anon_1_employee_name, "
            "anon_1.employee_type AS anon_1_employee_type, "
            "anon_1.manager_manager_data AS anon_1_manager_manager_data "
            "FROM "
            "(SELECT "
            "employee.id AS employee_id, employee.type AS employee_type, "
            "employee.name AS employee_name, "
            "manager.manager_data AS manager_manager_data, "
            "NULL AS engineer_info, NULL AS manager_id FROM employee "
            "JOIN manager ON employee.id = manager.id "
            "UNION ALL "
            "SELECT employee.id AS employee_id, "
            "employee.type AS employee_type, "
            "employee.name AS employee_name, NULL AS manager_data, "
            "engineer.engineer_info AS engineer_engineer_info, "
            "engineer.manager_id AS engineer_manager_id "
            "FROM employee JOIN engineer ON employee.id = engineer.id) "
            "AS anon_1 "
            "WHERE anon_1.employee_type IN (:type_1)",
        )

    def test_query_wpoly_single_inh_subclass(self):
        Boss = self.classes.Boss

        poly = self._with_poly_fixture()

        s = Session()
        q = s.query(Boss).with_polymorphic(Boss, poly)
        self.assert_compile(
            q,
            "SELECT anon_1.employee_id AS anon_1_employee_id, "
            "anon_1.employee_name AS anon_1_employee_name, "
            "anon_1.employee_type AS anon_1_employee_type, "
            "anon_1.manager_manager_data AS anon_1_manager_manager_data "
            "FROM (SELECT employee.id AS employee_id, employee.type "
            "AS employee_type, employee.name AS employee_name, "
            "manager.manager_data AS manager_manager_data, "
            "NULL AS engineer_info, NULL AS manager_id FROM employee "
            "JOIN manager ON employee.id = manager.id "
            "UNION ALL SELECT employee.id AS employee_id, "
            "employee.type AS employee_type, employee.name AS employee_name, "
            "NULL AS manager_data, "
            "engineer.engineer_info AS engineer_engineer_info, "
            "engineer.manager_id AS engineer_manager_id "
            "FROM employee JOIN engineer ON employee.id = engineer.id) "
            "AS anon_1 WHERE anon_1.employee_type IN (:type_1)",
        )

    def test_single_inh_subclass_join_joined_inh_subclass(self):
        Boss, Engineer = self.classes("Boss", "Engineer")
        s = Session()

        q = s.query(Boss).join(Engineer, Engineer.manager_id == Boss.id)

        self.assert_compile(
            q,
            "SELECT manager.id AS manager_id, employee.id AS employee_id, "
            "employee.name AS employee_name, "
            "employee.type AS employee_type, "
            "manager.manager_data AS manager_manager_data "
            "FROM employee JOIN manager ON employee.id = manager.id "
            "JOIN (employee AS employee_1 JOIN engineer AS engineer_1 "
            "ON employee_1.id = engineer_1.id) "
            "ON engineer_1.manager_id = manager.id "
            "WHERE employee.type IN (:type_1)",
        )

    def test_single_inh_subclass_join_wpoly_joined_inh_subclass(self):
        Boss = self.classes.Boss
        poly = with_polymorphic(
            self.classes.Employee,
            [self.classes.Boss, self.classes.Manager, self.classes.Engineer],
            self._with_poly_fixture(),
        )

        s = Session()

        q = s.query(Boss).join(
            poly.Engineer, poly.Engineer.manager_id == Boss.id
        )

        self.assert_compile(
            q,
            "SELECT manager.id AS manager_id, employee.id AS employee_id, "
            "employee.name AS employee_name, employee.type AS employee_type, "
            "manager.manager_data AS manager_manager_data "
            "FROM employee JOIN manager ON employee.id = manager.id "
            "JOIN (SELECT employee.id AS employee_id, "
            "employee.type AS employee_type, employee.name AS employee_name, "
            "manager.manager_data AS manager_manager_data, "
            "NULL AS engineer_info, NULL AS manager_id "
            "FROM employee JOIN manager ON employee.id = manager.id "
            "UNION ALL "
            "SELECT employee.id AS employee_id, "
            "employee.type AS employee_type, employee.name AS employee_name, "
            "NULL AS manager_data, "
            "engineer.engineer_info AS engineer_engineer_info, "
            "engineer.manager_id AS engineer_manager_id "
            "FROM employee "
            "JOIN engineer ON employee.id = engineer.id) AS anon_1 "
            "ON anon_1.manager_id = manager.id "
            "WHERE employee.type IN (:type_1)",
        )

    def test_joined_inh_subclass_join_single_inh_subclass(self):
        Engineer = self.classes.Engineer
        Boss = self.classes.Boss
        s = Session()

        q = s.query(Engineer).join(Boss, Engineer.manager_id == Boss.id)

        self.assert_compile(
            q,
            "SELECT engineer.id AS engineer_id, employee.id AS employee_id, "
            "employee.name AS employee_name, employee.type AS employee_type, "
            "engineer.engineer_info AS engineer_engineer_info, "
            "engineer.manager_id AS engineer_manager_id "
            "FROM employee JOIN engineer ON employee.id = engineer.id "
            "JOIN (employee AS employee_1 JOIN manager AS manager_1 "
            "ON employee_1.id = manager_1.id) "
            "ON engineer.manager_id = manager_1.id "
            "AND employee_1.type IN (:type_1)",
        )

class EagerDefaultEvalTest(fixtures.DeclarativeMappedTest):
    @classmethod
    def setup_classes(cls, with_polymorphic=None, include_sub_defaults=False):
        Base = cls.DeclarativeBasic

        class Foo(Base):
            __tablename__ = "foo"
            id = Column(
                Integer, primary_key=True, test_needs_autoincrement=True
            )
            type = Column(String(50))
            created_at = Column(Integer, server_default="5")

            __mapper_args__ = {
                "polymorphic_on": type,
                "polymorphic_identity": "foo",
                "eager_defaults": True,
                "with_polymorphic": with_polymorphic,
            }

        class Bar(Foo):
            bar = Column(String(50))
            if include_sub_defaults:
                bat = Column(Integer, server_default="10")

            __mapper_args__ = {"polymorphic_identity": "bar"}

    def test_persist_foo(self):
        Foo = self.classes.Foo

        foo = Foo()

        session = Session()
        session.add(foo)
        session.flush()

        eq_(foo.__dict__["created_at"], 5)

        assert "bat" not in foo.__dict__

        session.close()

    def test_persist_bar(self):
        Bar = self.classes.Bar
        bar = Bar()
        session = Session()
        session.add(bar)
        session.flush()

        eq_(bar.__dict__["created_at"], 5)

        if "bat" in inspect(Bar).attrs:
            eq_(bar.__dict__["bat"], 10)

        session.close()

class EagerDefaultEvalTestSubDefaults(EagerDefaultEvalTest):
    @classmethod
    def setup_classes(cls):
        super(EagerDefaultEvalTestSubDefaults, cls).setup_classes(
            include_sub_defaults=True
        )

class EagerDefaultEvalTestPolymorphic(EagerDefaultEvalTest):
    @classmethod
    def setup_classes(cls):
        super(EagerDefaultEvalTestPolymorphic, cls).setup_classes(
            with_polymorphic="*"
        )


text:
import { Mapping } from './Mapping';
import { Scope } from './Scope';

export interface EntityInterface {
  /**
   * Optional mapping (not required when using decorators).
   *
   * @param mapping
   */
  setMapping?(mapping: Mapping<any>): void;

  beforeCreate?(entityManager: Scope): Promise<any> | void;

  afterCreate?(entityManager: Scope): Promise<any> | void;

  beforeUpdate?(values: Object, entityManager: Scope): Promise<any> | void;

  afterUpdate?(entityManager: Scope): Promise<any> | void;

  beforeRemove?(entityManager: Scope): Promise<any> | void;

  afterRemove?(entityManager: Scope): Promise<any> | void;

  [key: string]: any;
}

export interface ProxyInterface extends EntityInterface {
  isEntityProxy?: boolean;

  activateProxying?(): ProxyInterface;

  deactivateProxying?(): ProxyInterface;

  getTarget?(): EntityInterface;

  isProxyingActive?(): boolean;

  [key: string]: any;
}

export type EntityCtor<T> = new (...args: any[]) => T;


text:
package com.spotify.helios.common.protocol;

import com.google.common.base.Objects;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.spotify.helios.common.Json;
import com.spotify.helios.common.descriptors.JobId;
import com.spotify.helios.common.descriptors.RolloutOptions;

import static com.google.common.base.Preconditions.checkNotNull;

public class RollingUpdateRequest {

  private final JobId job;
  private final RolloutOptions rolloutOptions;

  public RollingUpdateRequest(@JsonProperty("job") final JobId job,
                              @JsonProperty("rolloutOptions") final RolloutOptions rolloutOptions) {
    this.job = checkNotNull(job);
    this.rolloutOptions = rolloutOptions;
  }

  public JobId getJob() {
    return job;
  }

  public RolloutOptions getRolloutOptions() {
    return rolloutOptions;
  }

  @Override
  public String toString() {
    return Objects.toStringHelper(this)
        .add("job", job)
        .add("rolloutOptions", rolloutOptions)
        .toString();
  }

  public String toJsonString() {
    return Json.asStringUnchecked(this);
  }
}


text:
  Inform instance information (example: ORCL).
  You can use global variable like ${INSTANCE}.


text:
python purge.py
go install github.com/cmu440/chatterbox/
./bin/chatterbox -isMaster=true -N=5 -port=8080 -registerAll=false &
PID1=$!
./bin/chatterbox -isMaster=false -N=5 -port=9990 -registerAll=false &
PID2=$!
./bin/chatterbox -isMaster=false -N=5 -port=8081 -registerAll=false &
PID3=$!
./bin/chatterbox -isMaster=false -N=5 -port=8082 -registerAll=false &
PID4=$!
./bin/chatterbox -isMaster=false -N=5 -port=8083 -registerAll=false &
PID5=$!
./bin/chatterbox -isMaster=false -N=5 -port=999 -registerAll=true -testNum=0

kill -9 $PID1
kill -9 $PID2
kill -9 $PID3
kill -9 $PID4
kill -9 $PID5


text:
<?php

namespace mageekguy\atoum\tests\units\report\fields\runner\tests\memory;

use mageekguy\atoum;
use mageekguy\atoum\cli\colorizer;
use mageekguy\atoum\cli\prompt;
use mageekguy\atoum\locale;
use mageekguy\atoum\report\fields\runner\tests\memory;
use mageekguy\atoum\runner;

require_once __DIR__ . '/../../../../../../runner.php';

class cli extends atoum\test
{
    public function testClass()
    {
        $this->testedClass->extends(atoum\report\fields\runner\tests\memory::class);
    }

    public function test__construct()
    {
        $this
            ->if($field = new memory\cli())
            ->then
                ->object($field->getPrompt())->isEqualTo(new prompt())
                ->object($field->getTitleColorizer())->isEqualTo(new colorizer())
                ->object($field->getMemoryColorizer())->isEqualTo(new colorizer())
                ->object($field->getLocale())->isEqualTo(new locale())
                ->variable($field->getValue())->isNull()
                ->variable($field->getTestNumber())->isNull()
                ->array($field->getEvents())->isEqualTo([atoum\runner::runStop])
        ;
    }

    public function testSetPrompt()
    {
        $this
            ->if($field = new memory\cli())
            ->then
                ->object($field->setPrompt($prompt = new prompt(uniqid())))->isIdenticalTo($field)
                ->object($field->getPrompt())->isIdenticalTo($prompt)
                ->object($field->setPrompt())->isIdenticalTo($field)
                ->object($field->getPrompt())
                    ->isNotIdenticalTo($prompt)
                    ->isEqualTo(new prompt())
        ;
    }

    public function testSetTitleColorizer()
    {
        $this
            ->if($field = new memory\cli())
            ->then
                ->object($field->setTitleColorizer($colorizer = new colorizer()))->isIdenticalTo($field)
                ->object($field->getTitleColorizer())->isIdenticalTo($colorizer)
                ->object($field->setTitleColorizer())->isIdenticalTo($field)
                ->object($field->getTitleColorizer())
                    ->isNotIdenticalTo($colorizer)
                    ->isEqualTo(new colorizer())
        ;
    }

    public function testSetMemoryColorizer()
    {
        $this
            ->if($field = new memory\cli())
            ->then
                ->object($field->setMemoryColorizer($colorizer = new colorizer()))->isIdenticalTo($field)
                ->object($field->getMemoryColorizer())->isIdenticalTo($colorizer)
                ->object($field->setMemoryColorizer())->isIdenticalTo($field)
                ->object($field->getMemoryColorizer())
                    ->isNotIdenticalTo($colorizer)
                    ->isEqualTo(new colorizer())
        ;
    }

    public function testSetLocale()
    {
        $this
            ->if($field = new memory\cli())
            ->then
                ->object($field->setLocale($locale = new atoum\locale()))->isIdenticalTo($field)
                ->object($field->getLocale())->isIdenticalTo($locale)
                ->object($field->setLocale())->isIdenticalTo($field)
                ->object($field->getLocale())
                    ->isNotIdenticalTo($locale)
                    ->isEqualTo(new atoum\locale())
        ;
    }

    public function testHandleEvent()
    {
        $this
            ->if($field = new memory\cli())
            ->and($score = new \mock\mageekguy\atoum\runner\score())
            ->and($score->getMockController()->getTotalMemoryUsage = function () use (& $totalMemoryUsage) {
                return $totalMemoryUsage = rand(1, PHP_INT_MAX);
            })
            ->and($runner = new \mock\mageekguy\atoum\runner())
            ->and($runner->setScore($score))
            ->and($runner->getMockController()->getTestNumber = function () use (& $testNumber) {
                return $testNumber = rand(0, PHP_INT_MAX);
            })
            ->then
                ->boolean($field->handleEvent(atoum\runner::runStart, new atoum\runner()))->isFalse()
                ->variable($field->getValue())->isNull()
                ->variable($field->getTestNumber())->isNull()
                ->boolean($field->handleEvent(atoum\runner::runStop, $runner))->isTrue()
                ->integer($field->getValue())->isEqualTo($totalMemoryUsage)
                ->integer($field->getTestNumber())->isEqualTo($testNumber)
        ;
    }

    public function test__toString()
    {
        $this
            ->if($score = new \mock\mageekguy\atoum\runner\score())
            ->and($score->getMockController()->getTotalMemoryUsage = function () use (& $totalMemoryUsage) {
                return $totalMemoryUsage = rand(1, PHP_INT_MAX);
            })
            ->and($runner = new \mock\mageekguy\atoum\runner())
            ->and($runner->setScore($score))
            ->and($runner->getMockController()->getTestNumber = $testNumber = rand(1, PHP_INT_MAX))
            ->and($defaultField = new memory\cli())
            ->then
                ->castToString($defaultField)->isEqualTo(
                        $defaultField->getPrompt() . $defaultField->getTitleColorizer()->colorize($defaultField->getLocale()->__('Total test memory usage', 'Total tests memory usage', 0)) . ': ' . $defaultField->getMemoryColorizer()->colorize($defaultField->getLocale()->_('unknown')) . '.' . PHP_EOL
                    )
            ->if($customField = new memory\cli())
            ->and($customField->setPrompt($prompt = new prompt(uniqid())))
            ->and($customField->setTitleColorizer($titleColorizer = new colorizer(uniqid(), uniqid())))
            ->and($customField->setMemoryColorizer($memoryColorizer = new colorizer(uniqid(), uniqid())))
            ->and($customField->setLocale($locale = new locale()))
            ->then
                ->castToString($customField)->isEqualTo(
                        $prompt . $titleColorizer->colorize($locale->__('Total test memory usage', 'Total tests memory usage', 0)) . ': ' . $memoryColorizer->colorize($locale->_('unknown')) . '.' . PHP_EOL
                    )
            ->if($defaultField->handleEvent(atoum\runner::runStart, $runner))
            ->then
                ->castToString($defaultField)->isEqualTo(
                        $defaultField->getPrompt() . $defaultField->getTitleColorizer()->colorize($defaultField->getLocale()->__('Total test memory usage', 'Total tests memory usage', 0)) . ': ' . $defaultField->getMemoryColorizer()->colorize($defaultField->getLocale()->_('unknown')) . '.' . PHP_EOL
                    )
            ->if($customField->handleEvent(atoum\runner::runStart, $runner))
            ->then
                ->castToString($customField)->isEqualTo(
                        $prompt . $titleColorizer->colorize($locale->__('Total test memory usage', 'Total tests memory usage', 0)) . ': ' . $memoryColorizer->colorize($locale->_('unknown')) . '.' . PHP_EOL
                    )
            ->if($defaultField->handleEvent(atoum\runner::runStop, $runner))
            ->then
                ->castToString($defaultField)->isEqualTo($defaultField->getPrompt() . $defaultField->getTitleColorizer()->colorize($defaultField->getLocale()->__('Total test memory usage', 'Total tests memory usage', $testNumber)) . ': ' . $defaultField->getMemoryColorizer()->colorize(sprintf($defaultField->getLocale()->_('%4.2f Mb'), $totalMemoryUsage / 1048576)) . '.' . PHP_EOL)
            ->if($customField->handleEvent(atoum\runner::runStop, $runner))
            ->then
                ->castToString($customField)->isEqualTo($prompt . $titleColorizer->colorize($locale->__('Total test memory usage', 'Total tests memory usage', $testNumber)) . ': ' . $memoryColorizer->colorize(sprintf($locale->_('%4.2f Mb'), $totalMemoryUsage / 1048576)) . '.' . PHP_EOL)
        ;
    }
}