text:
module LazyTranslate
  class TranslationElement
    attr_reader :original, :applied, :line, :start, :finish, :location
    attr_accessor :translation_content, :translation_key

    def initialize(line:, start:, finish:, location: nil, original: nil, translation_content: nil, translation_key: nil)
      @original             = original
      @translation_content  = translation_content
      @translation_key      = translation_key
      @line         = line
      @start        = start
      @finish       = finish
      @location     = location
      @applied      = false
    end

    def apply_translation(text)
      raise 'Translation key not provided' unless translation_key
      raise 'Translation already applied' if applied
      @applied = true
      new_text = remove_old_text_part(text)
      add_translation_part(new_text)
    end

    private

    def remove_old_text_part(text)
      lines = text.split "\n"
      lines[line] = lines[line][0...start] + lines[line][finish..-1]
      lines.join "\n"
    end

    def add_translation_part(text)
      lines = text.split "\n"
      lines[line] = lines[line][0...start] + translation_key + lines[line][start..-1]
      lines.join("\n") + "\n"
    end
  end
end


text:
const http = require('http');

const notFound = (res) => {
  res.statusCode = 404;
  res.end();
};

const movedPermanently = (res, location) => {
  res.statusCode = 301;
  res.setHeader('Location', location);
  res.end();
};

const getNewLocation = (urlArr, canWebp) => {
  const newUri = urlArr.slice(2).join('/');
  return `https://dn-tatpics.qbox.me/${newUri}!normal${canWebp ? '.webp' : ''}`;
};

const server = http.createServer((req, res) => {
  const urlArr = req.url.split('/');
  const accept = req.headers['accept'] || '';
  const webp = accept.indexOf('webp') !== -1;
  if (urlArr[1] !== 'v') return notFound(res);
  return movedPermanently(res, getNewLocation(urlArr, webp));
});

server.listen(2333, () => console.log('serverStart'));

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Doctrine\Tests\ORM\Functional\Ticket;

/**
 * Class DDC2895Test
 * @package Doctrine\Tests\ORM\Functional\Ticket
 * @author http://github.com/gwagner
 */
class DDC2895Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
    protected function setUp() : void
    {
        parent::setUp();
        try {
            $this->_schemaTool->createSchema(
                [
                $this->_em->getClassMetadata(DDC2895::class),
                ]
            );
        } catch(\Exception $e) {

        }
    }

    public function testPostLoadOneToManyInheritance()
    {
        $cm = $this->_em->getClassMetadata(DDC2895::class);

        $this->assertEquals(
            [
                "prePersist" => ["setLastModifiedPreUpdate"],
                "preUpdate" => ["setLastModifiedPreUpdate"],
            ],
            $cm->lifecycleCallbacks
        );

        $ddc2895 = new DDC2895();

        $this->_em->persist($ddc2895);
        $this->_em->flush();
        $this->_em->clear();

        /** @var DDC2895 $ddc2895 */
        $ddc2895 = $this->_em->find(get_class($ddc2895), $ddc2895->id);

        $this->assertNotNull($ddc2895->getLastModified());

    }
}

/**
 * @MappedSuperclass
 * @HasLifecycleCallbacks
 */
abstract class AbstractDDC2895
{
    /**
     * @Column(name="last_modified", type="datetimetz", nullable=false)
     * @var \DateTime
     */
    protected $lastModified;

    /**
     * @PrePersist
     * @PreUpdate
     */
    public function setLastModifiedPreUpdate()
    {
        $this->setLastModified(new \DateTime());
    }

    /**
     * @param \DateTime $lastModified
     */
    public function setLastModified( $lastModified )
    {
        $this->lastModified = $lastModified;
    }

    /**
     * @return \DateTime
     */
    public function getLastModified()
    {
        return $this->lastModified;
    }
}

/**
 * @Entity
 * @HasLifecycleCallbacks
 */
class DDC2895 extends AbstractDDC2895
{
    /** @Id @GeneratedValue @Column(type="integer") */
    public $id;

    /**
     * @param mixed $id
     */
    public function setId( $id )
    {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }
}


text:
<!--
Copyright (C) 2006, 2007, 2008 Apple Inc.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1.  Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
2.  Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
    its contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
<!doctype html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta http-equiv="Content-Security-Policy" content="object-src 'none'; script-src 'self' 'unsafe-eval'">
    <link rel="stylesheet" type="text/css" href="inspector.css">
    <script type="text/javascript" src="main/Main.js"></script>
</head>
<body class="undocked" id="-blink-dev-tools"></body>
</html>


text:
(function () {

'use strict';

/**
 * @module spring-data-rest
 * @version 0.3.1
 *
 * An AngularJS module to ease the work with a Spring Data REST backend.
 */
angular.module("spring-data-rest", ["ngResource"]);

/**
 * @module spring-data-rest
 * @version 0.3.1
 *
 * Provider for the SpringDataRestAdapter which is the core of this module.
 */
angular.module("spring-data-rest").provider("SpringDataRestAdapter", function () {

    /**
     * Default configuration for spring data rest defaults
     */
    var config = {
        'linksKey': '_links',
        'linksHrefKey': 'href',
        'linksSelfLinkName': 'self',
        'embeddedKey': '_embedded',
        'embeddedNewKey': '_embeddedItems',
        'resourcesKey': '_resources',
        'resourcesFunction': undefined,
        'fetchFunction': undefined,
        'fetchAllKey': '_allLinks'
    };

    return {

        /**
         * Sets and gets the configuration object.
         *
         * @param {object} newConfig the new configuration to be set
         * @returns {object} the configuration object
         */
        config: function (newConfig) {
            // if the configuration object is 'undefined' then return the configuration object
            if (typeof newConfig !== 'undefined') {
                // throw an error if the given configuration is not an object
                if (!angular.isObject(newConfig)) {
                    throw new Error("The given configuration '" + newConfig + "' is not an object.");
                }

                // check if the given resource function is not undefined and is of type function
                if (newConfig.resourcesFunction != undefined && typeof(newConfig.resourcesFunction) != "function") {
                    throw new Error("The given resource function '" + newConfig.resourcesFunction + "' is not of type function.")
                }

                // check if the given fetch function is not undefined and is of type function
                if (newConfig.fetchFunction != undefined && typeof(newConfig.fetchFunction) != "function") {
                    throw new Error("The given fetch function '" + newConfig.fetchFunction + "' is not of type function.")
                }

                // override the default configuration properties with the given new configuration
                config = deepExtend(config, newConfig);
            }
            return config;
        },

        $get: ["$injector", function ($injector) {

            /**
             * Returns the Angular $resource method which is configured with the given parameters.
             *
             * @param {string} url the url at which the resource is available
             * @param {object} paramDefaults optional $resource method parameter defaults
             * @param {object} actions optional $resource method actions
             * @param {object} options additional $resource method options
             * @returns {*}
             */
            function resourcesFunction(url, paramDefaults, actions, options) {
                if (config.resourcesFunction == undefined) {
                    return $injector.get("$resource")(url, paramDefaults, actions, options);
                } else {
                    return config.resourcesFunction(url, paramDefaults, actions, options);
                }
            }

            /**
             * Fetches the given URL and adds the response to the given data object as a property
             * with the name of the given key.
             *
             * @param {string} url the url at which the resource is available
             * @param {string} key the key inside the data object where to store the returned response
             * @param {object} data the data object reference in which the response is stored
             * @param {[string]|string} fetchLinkNames the fetch link names to allow to process the fetched response
             * @param {boolean} recursive true if the fetched response should be processed recursively with the
             * adapter, false otherwise
             */
            function fetchFunction(url, key, data, fetchLinkNames, recursive) {
                if (config.fetchFunction == undefined) {
                    $injector.get("$http").get(url)
                        .success(function (responseData) {

                            // wrap the response again with the adapter if the recursive flag is set
                            data[key] = recursive ? processData(responseData, fetchLinkNames, true) : responseData;
                        })
                        .error(function (data, status) {
                            throw new Error("There was an error (" + status + ") retrieving the data from '" + url + "'");
                        });
                } else {
                    config.fetchFunction(url, key, data, fetchLinkNames, recursive);
                }
            }

            /**
             * The actual adapter method which processes the given JSON data object and adds
             * the wrapped resource property to all embedded elements where resources are available.
             *
             * @param {object} data the given JSON data
             * @param {object|string} fetchLinkNames the link names to be fetched automatically or the
             * 'fetchAllLinkNamesKey' key from the config object to fetch all links except the 'self' key.
             * @param {boolean} recursive true if the automatically fetched response should be processed recursively with the
             * adapter, false otherwise
             * @returns {object} the processed JSON data
             */
            var processData = function processDataFunction(data, fetchLinkNames, recursive) {

                /**
                 * Wraps the Angular $resource method and adds the ability to retrieve the available resources. If no
                 * parameter is given it will return an array with the available resources in this object.
                 *
                 * @param {string|object} resourceObject the resource name to be retrieved or an object which holds the
                 * resource name and the parameters
                 * @param {object} paramDefaults optional $resource method parameter defaults
                 * @param {object} actions optional $resource method actions
                 * @param {object} options additional $resource method options
                 * @returns {object} the result of the $resource method or the available resources as a resource object array
                 *
                 * @see https://docs.angularjs.org/api/ngResource/service/$resource
                 */
                var resources = function (resourceObject, paramDefaults, actions, options) {
                    var resources = this[config.linksKey];
                    var parameters = paramDefaults;

                    // if a resource object is given process it
                    if (angular.isObject(resourceObject)) {
                        if (!resourceObject.name) {
                            throw new Error("The provided resource object must contain a name property.");
                        }

                        var resourceObjectParameters = resourceObject.parameters;

                        // if the default parameters and the resource object parameters are objects, then merge these two objects
                        // if not use the objects themselves as parameters
                        if (paramDefaults && angular.isObject(paramDefaults)) {
                            if (resourceObjectParameters && angular.isObject(resourceObjectParameters)) {
                                parameters = angular.extend(angular.copy(paramDefaults), angular.copy(resourceObjectParameters));
                            } else {
                                parameters = angular.copy(paramDefaults);
                            }
                        } else {
                            if (resourceObjectParameters && angular.isObject(resourceObjectParameters)) {
                                parameters = angular.copy(resourceObjectParameters);
                            }
                        }

                        // remove parameters which have an empty string as value
                        angular.forEach(parameters, function (value, key) {
                            if (value === "") {
                                delete parameters[key];
                            }
                        });

                        // process the url and call the resources function with the given parameters
                        return resourcesFunction(getProcessedUrl(data, resourceObject.name), parameters, actions, options);
                    } else if (resourceObject in resources) {

                        // process the url and call the resources function with the given parameters
                        return resourcesFunction(getProcessedUrl(data, resourceObject), parameters, actions, options);
                    }

                    // return the available resources as resource object array if the resource object parameter is not set
                    var availableResources = [];
                    angular.forEach(resources, function (value, key) {

                        // if the URL is templated add the available template parameters to the returned object
                        if (value.templated) {
                            var templateParameters = extractTemplateParameters(value[config.linksHrefKey]);
                            availableResources.push({"name": key, "parameters": templateParameters});
                        } else {
                            availableResources.push({"name": key});
                        }
                    });
                    return availableResources;
                };

                // throw an exception if given data parameter is not of type object
                if (!angular.isObject(data) || data instanceof Array) {
                    throw new Error("Given data '" + data + "' is not of type object.");
                }

                // throw an exception if given fetch links parameter is not of type array or string
                if (fetchLinkNames != undefined && !(fetchLinkNames instanceof Array || typeof fetchLinkNames === "string")) {
                    throw new Error("Given fetch links '" + fetchLinkNames + "' is not of type array or string.");
                }

                var processedData = undefined;

                // only add the resource method to the object if the links key is present
                if (config.linksKey in data) {

                    // add Angular resources property to object
                    var resourcesObject = {};
                    resourcesObject[config.resourcesKey] = resources;
                    processedData = angular.extend(angular.copy(data), resourcesObject);

                    // if there are links to fetch, then process and fetch them
                    if (fetchLinkNames != undefined) {

                        // make a defensive copy if the processedData variable is undefined
                        if (!processedData) {
                            processedData = angular.copy(data);
                        }

                        // process all links
                        angular.forEach(data[config.linksKey], function (linkValue, linkName) {

                            // if the link name is not 'self' then process the link name
                            if (linkName != config.linksSelfLinkName) {

                                // check if:
                                // 1. the all link names key is given then fetch the link
                                // 2. the given key is equal
                                // 3. the given key is inside the array
                                if (fetchLinkNames == config.fetchAllKey ||
                                    (typeof fetchLinkNames === "string" && linkName == fetchLinkNames) ||
                                    (fetchLinkNames instanceof Array && fetchLinkNames.indexOf(linkName) >= 0)) {
                                    fetchFunction(getProcessedUrl(data, linkName), linkName,
                                        processedData, fetchLinkNames, recursive);
                                }
                            }
                        });
                    }
                }

                // only move the embedded values to a top level property if the embedded key is present
                if (config.embeddedKey in data) {

                    // make a defensive copy if the processedData variable is undefined
                    if (!processedData) {
                        processedData = angular.copy(data);
                    }

                    // process the embedded key and move it to an embedded value key
                    processedData = moveArray(processedData, config.embeddedKey, config.embeddedNewKey);

                    // recursively process all contained objects in the embedded value array
                    angular.forEach(processedData[config.embeddedNewKey], function (value, key) {
                        processedData[config.embeddedNewKey][key] = processDataFunction(value, fetchLinkNames, recursive);
                    });
                }

                // return the original data object if no processing is done
                return processedData ? processedData : data;

                /**
                 * Gets the processed URL of the given resource name form the given data object.
                 * @param {object} data the given data object
                 * @param {string} resourceName the resource name from which the URL is retrieved
                 * @returns {string} the processed url
                 */
                function getProcessedUrl(data, resourceName) {
                    // get the raw URL out of the resource name and check if it is valid
                    var rawUrl = checkUrl(data[config.linksKey][resourceName][config.linksHrefKey], resourceName,
                        config.linksHrefKey);

                    // extract the template parameters of the raw URL
                    return extractUrl(rawUrl, data[config.linksKey][resourceName].templated);
                }
            };

            /**
             * The actual adapter method which processes the given promise object and adds
             * the wrapped resource property to all embedded elements where resources are available.
             *
             * @param {promise} promise the given promise which resolves with a promise data object which holds a data
             * property with the given response
             * @param {object|string} fetchLinkNames the link names to be fetched automatically or the
             * 'fetchAllLinkNamesKey' key from the config object to fetch all links except the 'self' key.
             * @param {boolean} recursive true if the automatically fetched response should be processed recursively with the
             * adapter, false otherwise
             * @returns {object} the processed JSON data
             */
            var processDataWithPromise = function processDataFunction(promise, fetchLinkNames, recursive) {

                // convert the given promise to a $q promise
                var qPromise = $injector.get("$q").when(promise);
                var deferred = $injector.get("$q").defer();

                qPromise.then(function (promiseData) {
                    // process the given promiseData and resolve the promise with the processed data
                    var processedData = processData(promiseData.data, fetchLinkNames, recursive);
                    deferred.resolve(processedData);
                }, function (error) {
                    deferred.reject(error);

                    // reject the error because we do not handle the error here
                    return $injector.get("$q").reject(error);
                });

                // return the promise
                return deferred.promise;
            };

            // return an object with the processData function
            return { process: processData, processWithPromise: processDataWithPromise };
        }]
    };

});

/**
 * @module spring-data-rest
 * @version 0.3.1
 *
 * Provider for the interceptor which wraps the SpringDataRestAdapter around the response object.
 */
angular.module("spring-data-rest").provider("SpringDataRestInterceptor",
    ["$httpProvider", "SpringDataRestAdapterProvider",
        function ($httpProvider) {
            return {

                apply: function () {
                    $httpProvider.interceptors.push("SpringDataRestInterceptor");
                },

                $get: ["SpringDataRestAdapter", "$q", function (SpringDataRestAdapter, $q) {

                    return {
                        response: function (response) {
                            if (response && angular.isObject(response.data)) {
                                response.data = SpringDataRestAdapter.process(response.data);
                            }
                            return response || $q.when(response);
                        }
                    };
                }]

            };

        }]
);

/**
 * Makes a deep extend of the given destination object and the source objects.
 *
 * @param {object} destination the destination object
 * @returns {object} a copy of the extended destination object
 */
function deepExtend(destination) {
    angular.forEach(arguments, function (obj) {
        if (obj !== destination) {
            angular.forEach(obj, function (value, key) {
                if (destination[key] && destination[key].constructor && destination[key].constructor === Object) {
                    deepExtend(destination[key], value);
                } else {
                    destination[key] = value;
                }
            });
        }
    });
    return angular.copy(destination);
}

/**
 * Moves a key with an array value to the destination key.
 *
 * @param {object} object the object in which the source key exists and destination key is created
 * @param {string} sourceKey the source key from which the array is moved
 * @param {string} destinationKey the destination key to which the array is moved
 * @returns {object} the processed object
 */
function moveArray(object, sourceKey, destinationKey) {
    var embeddedObject = object[sourceKey];
    if (embeddedObject) {
        var key = Object.keys(embeddedObject)[0];
        var processedData = {};
        processedData[destinationKey] = embeddedObject[key];

        object = angular.extend(object, processedData);
        delete object[sourceKey];
    }
    return object;
}

/**
 * Extracts the url out of a url string. If template parameters exist, they will be removed from the
 * returned url.
 *
 * @param {string} url the url string from which to extract the url
 * @param {boolean} templated true if the url is templated
 * @returns {string} the url of the resource object
 */
function extractUrl(url, templated) {
    if (templated) {
        url = removeTemplateParameters(url)
    }
    return url;
}

/**
 * Checks the given URL if it is valid and throws a parameterized exception containing the resource name and the
 * URL property name.
 *
 * @param {string} url the URL to check
 * @param {string} resourceName the name of the resource
 * @param {string} hrefKey the URL property key
 * @returns {string} the URL if it is valid
 * @throws Error if the URL is not valid
 */
function checkUrl(url, resourceName, hrefKey) {
    if (url == undefined || !url) {
        throw new Error("The provided resource name '" + resourceName + "' has no valid URL in the '" +
            hrefKey + "' property.");
    }
    return url
}

/**
 * Removes the template parameters of the given url. e.g. from this url
 * 'http://localhost:8080/categories{?page,size,sort}' it will remove the curly braces
 * and everything within.
 *
 * @param {string} url the url with the template parameters
 * @returns {string} the url without the template parameters
 */
function removeTemplateParameters(url) {
    return url.replace(/{.*}/g, '');
}

/**
 * Returns the template parameters of the given url as object. e.g. from this url
 * 'http://localhost:8080/categories{?page,size,sort}' it will return the following object:
 * {'page': "", 'size': "", 'sort': ""}
 *
 * @param {string} url the url with the template parameters
 * @returns {object} the object containing the template parameters
 */
function extractTemplateParameters(url) {
    var templateParametersObject = {};

    var regexp = /{\?(.*)}/g;
    var templateParametersArray = regexp.exec(url)[1].split(',');

    angular.forEach(templateParametersArray, function (value) {
        templateParametersObject[value] = "";
    });

    return templateParametersObject;
}

})();


text:
#ifndef CPP_OUT_PARAMS_OOULA_H_
# define CPP_OUT_PARAMS_OOLUA_H_

#	include "oolua_tests_pch.h"
#	include "gmock/gmock.h"
#	include "cpp_stub_classes.h"

class OutParamsTest
{
public:
	enum PARAM_CONSTANTS
	{
		Return = -1
		, Param1 = 1
		, Param2 = 2
		, Param3 = 3
		, Dummy = 6500
	};
    virtual ~OutParamsTest(){}
	/**[CppTraitInOut]*/
	virtual void int_ref(int&) =0;
	/**[CppTraitInOut]*/
	virtual void two_int_refs(int&, int&) =0;
	/**[CppOutTraitExampleFunction]*/
	virtual void int_ref_change(int& i)
	{
		i =static_cast<int>(Param1);
	}
	/**[CppOutTraitExampleFunction]*/

	virtual void int_ptr(int* i)=0;
	virtual void int_ptr_change_pointee(int* i)
	{
		*i =static_cast<int>(Param1);
	}
	/**[CppTraitReturnOrder]*/
	virtual int return_int_and_2_int_refs(int& i1, int& i2)
	{
		i1 = static_cast<int>(Param1);
		i2 = static_cast<int>(Param2);
		return Return;
	}
	/**[CppTraitReturnOrder]*/
};

class MockOutParamsTest : public OutParamsTest
{
public:
	MOCK_METHOD1(int_ref, void(int&));
	MOCK_METHOD2(two_int_refs, void(int&, int&) );
	MOCK_METHOD1(int_ptr, void(int*)); //NOLINT(readability/function)
};

struct MockParamWithStringMember
{
	std::string str;
};
/**[CppOutParamsUserData]*/
class OutParamsUserData
{
public:
	virtual ~OutParamsUserData(){}
	virtual void ref(Stub1 & stub)=0;
	virtual void ptr(Stub1* stub) = 0;
	virtual void by_value(Stub1 stub) = 0;
	virtual void ref_param(MockParamWithStringMember& mock) = 0;
};
/**[CppOutParamsUserData]*/

class MockOutParamsUserData : public OutParamsUserData
{
public:
	MOCK_METHOD1(ref, void(Stub1&));
	MOCK_METHOD1(ptr, void(Stub1*)); //NOLINT(readability/function)
	MOCK_METHOD1(by_value, void(Stub1));
	MOCK_METHOD1(ref_param, void(MockParamWithStringMember&));
};

#endif


text:
var gulp = require("gulp"),
	del = require("del"),
	babel = require("gulp-babel"),
	concat = require("gulp-concat"),
	cssnext = require("gulp-cssnext"),
	beeper = require("beeper"),
	mergeStream = require("merge-stream");

gulp.task("clean", function(c) {
	del("dist/**", c);
});

// Transpile to ES5
// Input: All JS files but those under libs/
gulp.task("to-ES5", ["clean"], function() {
	return gulp.src([
		"src/**/*.js",
		"!src/**/libs/**"
	], { base: "src/" })
		.pipe(babel())
		.pipe(gulp.dest("dist/"));
});

var buildThemedCss = function(theme) {
	var appCssBundle;
	var sandboxCssBundle;

	// Input: All CSS files but the sandbox's, and only the current theme
	appCssBundle = gulp.src([
		"src/**/*.css",
		"!src/sandbox/css/*.css",
		"!src/app-shared/css/themes/**/!(" + theme + "-theme-vars.css)"
	], { base: "src/" })
		.pipe(concat("css/bundle-" + theme + "-theme.css"))
		.pipe(cssnext())
		.pipe(gulp.dest("dist/"));

	// Input: app-shared's main.css for rules that are unrelated to the Chrome
	// app's UI, the sandbox's CSS files, and only the current theme
	sandboxCssBundle = gulp.src([
		"src/app-shared/css/main.css",
		"src/sandbox/css/*.css",
		"src/app-shared/css/themes/" + theme + "-theme-vars.css"
	], { base: "src/" })
		.pipe(concat("sandbox/css/bundle-" + theme + "-theme.css"))
		.pipe(cssnext())
		.pipe(gulp.dest("dist/"));

	return mergeStream(appCssBundle, sandboxCssBundle);
};

gulp.task("build-css-theme-light", ["clean"], buildThemedCss.bind(null, "light"));
gulp.task("build-css-theme-dark", ["clean"], buildThemedCss.bind(null, "dark"));

// Simply copy the rest of the files from src/ to dist/
// Input: All files but JS files that are not under libs/
gulp.task("copy", ["clean"], function() {
	return gulp.src([
		"src/**",
		"!src/**/*.css",
		"!src/**/!(libs)/*.js" // With this glob, JS files must be directly under libs/ (change the glob if nesting folders)
	], { base: "src/" })
		.pipe(gulp.dest("dist/"));
});

gulp.task("default", ["to-ES5", "build-css-theme-light", "build-css-theme-dark", "copy"], function() {
	console.log("Watching...");
});

gulp.task("build-from-watch", ["default"], function() {
	if (getArg("--beep")) beeper(2); // Audio feedback when build is complete (enable by passing --beep param)
});

// Build as soon as a file changes
gulp.watch("src/**", ["build-from-watch"])
	.on("change", function(event) {
		console.log("Watch: file " + event.path + " was " + event.type + ", building...");
	});

// From http://stackoverflow.com/a/26946499/408173
// Eases reading command line params
function getArg(key) {
	var index = process.argv.indexOf(key);
	var next = process.argv[index + 1];
	return (index < 0) ? null : (!next || next[0] === "-") ? true : next;
}


text:
package io.vertx.test.linktofield;

/**
 * @author Julien Viet
 */
public class TheClass {

  public String f1;

}


text:
<?php

	$about = array(
		'name' => 'Русский',
		'author' => array(
			'name' => 'Александр Бирюков',
			'email' => 'info@alexbirukov.ru',
			'website' => 'http://alexbirukov.ru'
		),
		'release-date' => '2012-12-11'
	);

	/**
	 * CKEditor
	 */
	$dictionary = array(

		'CKEditor File Browser' =>
		'Браузер файлов CKEditor',

		'Field to display as name' =>
		'Поле для отображения в качестве имени',

		'Link template' =>
		'Шаблон ссылки',

		'Link templates:' =>
		'Шаблоны ссылок:',

		'Permitted sections for the file browser:' =>
		'Разделы доступные для браузера файлов:',

		'Section' =>
		'Раздел',

		'Section to get the entries from' =>
		'Раздел из которого производить выбор записей',

		'There are no sections available. Please select which sections are permitted to use the CKEditor file upload feature in the Symphony System Preferences.' =>
		'Не указаны доступные разделы. Пожалуйста, укажите в настройках системы разделы, которые доступны для загрузки файлов через CKEditor.',

		'Use {$id} for the entry ID, and {$fieldname} for field-placeholders. If the field has a handle, this is automatically used.' =>
		'Используйте переменную {$id} для вывода ID записи и {$fieldname} для подстановки значения поля.',

		'create new' =>
		'добавить',

		'Styles: (one style per line: h3.example { color: #f00; background: #0f0; }) Class name is converted to name (h3.hello-world = Hello World).' =>
		'Стили: (один стиль в строке: h3.example { color: #f00; background: #0f0; }) имя класса ковертируется в имя (h3.hello-world = Hello World).',

	);


text:
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
import argparse
import gym
from handson_2.agents import RandomAgent, FunFunAgent, TrackAgent

def main(episode_count):
    env = gym.make("Pong-v0")
    action_number = env.action_space.n
    action_up = 2
    action_down = 3
    action_stop = 0

    # your code here

    for i in range(episode_count):
        observation = env.reset()
        done = False
        agent.init()
        name = agent.__class__.__name__

        while not done:
            env.render()
            action = agent.act(observation)  # agent takes observation, and decide action
            next_observation, reward, done, info = env.step(action)
            print("{} takes action={}, and get reward={}.".format(name, action, reward))

            observation = next_observation
            agent.reward += reward

            if done:
                print("Episode {}: {} gets total reward={}.".format(i, name, agent.reward))

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Let's Start OpenAI Gym")
    parser.add_argument("--episode", type=int, help="Episode Count to work", default=2)

    args = parser.parse_args()
    main(args.episode)


text:
<?php

class Braintree_OAuthGateway
{
    private $_gateway;
    private $_config;
    private $_http;

    public function __construct($gateway)
    {
        $this->_gateway = $gateway;
        $this->_config = $gateway->config;
        $this->_http = new Braintree_HttpOAuth($gateway->config);

        $this->_config->assertHasClientCredentials();
    }

    public function createTokenFromCode($params)
    {
        $params['grantType'] = "authorization_code";
        $response = $this->_http->post('/oauth/access_tokens', $params);
        return $this->_verifyGatewayResponse($response);
    }

    public function createTokenFromRefreshToken($params)
    {
        $params['grantType'] = "refresh_token";
        $response = $this->_http->post('/oauth/access_tokens', $params);
        return $this->_verifyGatewayResponse($response);
    }

    private function _verifyGatewayResponse($response)
    {
        $result = Braintree_OAuthCredentials::factory($response);
        $result->success = !isset($response['error']);
        return $result;
    }

    public function connectUrl($params = array())
    {
        $query = Braintree_Util::camelCaseToDelimiterArray($params, '_');
        $query['client_id'] = $this->_config->getClientId();
        $url = $this->_config->baseUrl() . '/oauth/connect?' . http_build_query($query);

        return $this->signUrl($url);
    }

    private function signUrl($url)
    {
        $key = hash('sha256', $this->_config->getClientSecret(), true);
        return $url . '&signature=' . hash_hmac('sha256', $url, $key) . '&algorithm=SHA256';
    }
}


text:
package com.test.demo.myapp.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.test.demo.myapp.R;

public class ViewAsListActivity extends AppCompatActivity {

    private ViewGroup rootLayout;

    private static int BREAKS_THE_APP = 17010;
    private static int PAIN_LEVEL = 16000;
    private static int PRETTY_SMOOTH = 10000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_as_list);
        rootLayout = (ViewGroup) findViewById(R.id.root_linear_layout);
        for (int i = 0; i < BREAKS_THE_APP; i++) {
            addElement();
        }
    }

    private void addElement() {
        View view = getLayoutInflater().inflate(R.layout.my_text_view, rootLayout, false);
        ImageView thumbnail = (ImageView) view.findViewById(R.id.image_content);
        TextView textContent = (TextView) view.findViewById(R.id.text_content);
        textContent.setText("This is text");
        Picasso.with(getApplicationContext()).load("http://eskipaper.com/images/large-2.jpg").into(thumbnail);
        rootLayout.addView(view);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Jint.Expressions {
    public interface IForStatement {
        Statement InitialisationStatement { get; set; }
        Statement Statement { get; set; }
    }
}


text:
<?php
namespace Test\DbImplementations\Mongo;

use DbMockLibrary\DbImplementations\Mongo;

class InitTest extends \Test\TestCase
{
    public function tearDown()
    {
        Mongo::getInstance()->destroy();
    }

    /**
     * @return void
     */
    public function test_function()
    {
        // prepare
        $dataArray = ['testCollection' => [1 => ['foo' => 1, 'id' => 1]]];

        // invoke logic
        Mongo::initMongo($dataArray, 'DbMockLibraryTest', []);

        // prepare
        $reflection = new \ReflectionClass('\DbMockLibrary\DbImplementations\Mongo');
        $staticProperties = $reflection->getStaticProperties();

        // test
        $this->assertInstanceOf('\DbMockLibrary\DbImplementations\Mongo', $staticProperties['instance']);
        $this->assertEquals($dataArray, $staticProperties['initialData']);

        // prepare
        $dataProperty = $reflection->getProperty('data');
        $dataProperty->setAccessible(true);

        // test
        $this->assertEquals($dataArray, $dataProperty->getValue($staticProperties['instance']));
    }
}


text:
<?php

class La_View_Helper_SimpleTable extends Zend_View_Helper_Abstract
{
    /**
     *
     * @var int
     */
    protected $_id;

    /**
     *
     * @var array
     */
    protected $_headers = array();

    /**
     *
     * @var array|Zend_Db_Table_Rowset
     */
    protected $_data = array();

    /**
     *
     * @var array
     */
    protected $_buttons = array();

    /**
     *
     * @var array
     */
    protected $_formaters = array();

    /**
     *
     * @var int
     */
    protected $_parentId;

    /**
     *
     * @var type boolean
     */
    protected $_activePaginator = true;

    /**
     *
     * @var type boolean
     */
    protected $_showCheckbox = true;

    /**
     *
     * @var type boolean
     */
    protected $_lineLink = '%s';

    /**
     *
     * @var type string
     */
    protected $_module;

    /**
     *
     * @var type string
     */
    protected $_controller;

    /**
     *
     * @var type string
     */
    protected $_action;

    /**
     *
     * @var type string
     */
    protected $_deleteUrl;

    /**
     *
     * @var type array
     */
    protected $_totalizers;

    /**
     *
     * @var type bool
     */
    protected $_responsive = true;

    /**
     *
     * @var type bool
     */
    protected $_dataProp = false;

    /**
     *
     * @param array $headers
     * @param array|Zend_Db_Table_Rowset $data
     * @param array $buttons
     *
     * @return \La_View_Helper_SimpleTable
     */
    public function simpleTable($headers = array(), $data = array(), $buttons = array())
    {
        $this->_id = uniqid();

        if (!$headers) {
            $headers = $this->view->headers;
        }

        if (!$data) {
            $data = $this->view->data;
        }

        $this->setHeaders($headers);
        $this->setData($data);
        $this->setButtons($buttons);

        return $this;
    }

    /**
     *
     * @return int
     */
    public function getId()
    {
        return $this->_id;
    }

    /**
     *
     * @param array $headers
     *
     * @return \La_View_Helper_SimpleTable
     */
    public function setHeaders(array $headers)
    {
        $this->_headers = $headers;
        return $this;
    }

    /**
     *
     * @param string $module
     *
     * @return \La_View_Helper_SimpleTable
     */
    public function setModule($module)
    {
        $this->_module = $module;
        return $this;
    }

    /**
     *
     * @param string $controller
     *
     * @return \La_View_Helper_SimpleTable
     */
    public function setController($controller)
    {
        $this->_controller = $controller;
        return $this;
    }

    /**
     *
     * @param string bool
     *
     * @return \La_View_Helper_SimpleTable
     */
    public function setResponsive($bool)
    {
        $this->_responsive = $bool;
        return $this;
    }

    /**
     *
     * @param string $header
     *
     * @return \La_View_Helper_SimpleTable
     */
    public function addHeader($header)
    {
        $this->_headers[] = $header;
        return $this;
    }

    /**
     *
     * @param array $formaters
     *
     * @return \La_View_Helper_SimpleTable
     */
    public function setFormaters(array $formaters)
    {
        $this->_formaters = $formaters;
        return $this;
    }

    /**
     *
     * @param string $key
     * @param string $formater
     *
     * @return \La_View_Helper_SimpleTable
     */
    public function addFormater($key, $formater)
    {
        $this->_formaters[$key] = $formater;
        return $this;
    }

    /**
     *
     * @param type $data
     *
     * @return \La_View_Helper_SimpleTable
     */
    public function setData($data)
    {
        $this->_data = $data;
        return $this;
    }

    /**
     *
     * @param array $buttons
     *
     * @return \La_View_Helper_SimpleTable
     */
    public function setButtons(array $buttons)
    {
        $this->_buttons = $buttons;
        return $this;
    }

    /**
     *
     * @return int
     */
    public function getParentId()
    {
        return $this->_parentId;
    }

    /**
     *
     * @param int $parentId
     * @return \La_View_Helper_SimpleTable
     */
    public function setParentId($parentId)
    {
        $this->_parentId = $parentId;
        return $this;
    }

    /**
     *
     * @return boolean
     */
    public function getActivePaginator()
    {
        return $this->_activePaginator;
    }

    /**
     * @param $activePaginator boolean
     * @return \La_View_Helper_SimpleTable
     */
    public function setActivePaginator($activePaginator)
    {
        $this->_activePaginator = $activePaginator;
        return $this;
    }

    /**
     *
     * @return boolean
     */
    public function getLineLink()
    {
        return $this->_lineLink;
    }

    /**
     * @param $lineLink boolean
     * @return \La_View_Helper_SimpleTable
     */
    public function setLineLink($lineLink)
    {
        $this->_lineLink = $lineLink;
        return $this;
    }

    /**
     *
     * @return string
     */
    public function getDeleteUrl()
    {
        return $this->_deleteUrl;
    }

    /**
     * @param $$deleteUrl string
     * @return \La_View_Helper_SimpleTable
     */
    public function setDeleteUrl($deleteUrl)
    {
        $this->_deleteUrl = $deleteUrl;
        return $this;
    }

    /**
     * @param $showCheckbox boolean
     * @return \La_View_Helper_SimpleTable
     */
    public function setShowCheckbox($showCheckbox)
    {
        $this->_showCheckbox = $showCheckbox;
        return $this;
    }

    public function getTotalizers()
    {
        return $this->_totalizers;
    }

    public function setTotalizers($totalizers)
    {
        $this->_totalizers = $totalizers;
        return $this;
    }

    public function getDataProp()
    {
        return $this->_dataProp;
    }

    public function setDataProp($bool = true)
    {
        $this->_dataProp = $bool;
        return $this;
    }

    /**
     *
     * @param string $button
     *
     * @return \La_View_Helper_SimpleTable
     */
    public function addButton($button)
    {
        $this->_buttons[] = $button;
        return $this;
    }

    public function __toString()
    {
        try {
            $request       = Zend_Controller_Front::getInstance()->getRequest();
            $buttonsLength = count($this->_buttons);
            $module        = $this->_module;
            $controller    = $this->_controller;

            if (!$module) {
                $module = $request->getModuleName();
            }

            if (!$controller) {
                $controller = $request->getControllerName();
            }

            $url = sprintf("%s/%s/delete/parent_id/%s/table/%s", $module, $controller, $this->getParentId(), $this->view->table);
            if ($this->_deleteUrl) {
                $url = $this->_deleteUrl;
            }

            $html  = '';

            if ($this->_responsive) {
                $html  = '
';
            }

            $html .= sprintf('<form action="%s" method="post" id="%s">', $url, $this->_id);
            $html .= '
';
            $html .= '
';
            $html .= '
';

            if ($this->_showCheckbox) {
                $html .= sprintf('<input type="checkbox" id="check-%s">	', $this->_id);
            }

            if ($buttonsLength) {
                $html .= sprintf(' 	', ($buttonsLength * 40));
            }

            foreach ($this->_headers as $key => $header) {
                if ($key == 'id') {
                    $html .= sprintf('%s	', $header);
                } else {
                    $html .= sprintf('%s	', $header);
                }
            }

            $html .= '
';
            $html .= '
';
            $html .= '
';

            $formater = $this->view->formater($this->_formaters);

            if (count($this->_data)) {
                foreach ($this->_data as $key => $data) {
                    if ($this->_dataProp) {
                        $html .= '
renderDataProp($data) . ' >';
                    } else {
                        $html .= '
';
                    }

                    if ($this->_showCheckbox) {
                        $html .= sprintf('<input class="check-delete" type="checkbox" name="id[]" value="%s">	', $data['id']);
                    }

                    if ($buttonsLength) {
                        $html .= '';

                        foreach ($this->_buttons as $button) {
                            $html .= sprintf($button, $data['id']);
                        }

                        $html .= "	";
                    }

                    foreach ($this->_headers as $field => $header) {
                        $formaterHelper = $formater->getHelperByKey($field);
                        if ($this->getLineLink()) {
                            $td = sprintf('' . $this->getLineLink() . '	', $module, $controller, $data['id'], $this->view->table, '%s');
                        } else {
                            $td = "%s	";
                        }

                        if ($formater->getHelperByKey($field)) {
                            $html .= sprintf($td, $formater->$formaterHelper($field, $data));
                        } else {
                            $html .= sprintf($td, $this->view->dynamicFormat($data[$field]));
                        }
                    }

                    $html .= "
";
                }

                if ($this->getTotalizers() != null) {
                    $totalizers   = $this->getTotalizers();
                    $countHeaders = count($this->_headers);

                    if ($this->_showCheckbox) {
                        $countHeaders++;
                    }

                    if ($buttonsLength) {
                        $countHeaders++;
                    }

                    $colspan = ($countHeaders - count($totalizers));
                    $html .= '
';
                    $html .= sprintf('	', $colspan);

                    foreach ($totalizers as $i => $totalizer) {
                        $html .= sprintf('%s	', $i, $totalizer);
                    }

                    $html .= '
';
                }
            } else {
                $html .= sprintf('Nenhum registro encontrado.	', (count($this->_headers)+1));
            }

            $html .= '
';
            $html .= '
';
            $html .= '</form>';

            if ($this->_responsive) {
                $html .= '
';
            }

            if ($this->getActivePaginator()
                && $this->_data instanceof Zend_Paginator
                && $this->_data->getTotalItemCount() > 10)
            {
                $html .= $this->view->paginationControl($this->_data);
            }

            $html .= '';
        } catch ( Exception $e ) {
            return $e->getMessage();
        }
        return $html;
    }

    private function renderDataProp(array $data)
    {
        $html = "";

        foreach ($data as $key => $value) {
            if ($value) {
                $html .= "data-$key='$value' ";
            }
        }

        return $html;
    }
}


text:
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Feedbook.Model;
using System.Collections.Specialized;
using CoreSystem.RefTypeExtension;
using System.Collections.ObjectModel;
using Feedbook.Services;

namespace Feedbook.Helper
{
    internal class FeedEventArgs : EventArgs
    {
        public FeedSource Source { get; private set; }

        public Account Account { get; private set; }

        public Channel Channel { get; private set; }

        public Feed Feed { get; private set; }

        public FeedEventArgs(FeedSource source, Account account, Channel channel, Feed feed)
        {
            this.Source = source;
            this.Account = account;
            this.Channel = channel;
            this.Feed = feed;
        }
    }

    internal delegate void FeedEventHandler(object sender, FeedEventArgs e);

    internal static class GlobalEventManager
    {
        public static event FeedEventHandler OnFeedAdd;

        public static event FeedEventHandler OnFeedRemove;

        public static void Initialize()
        {
            Add(FeedSource.RSS, DataStore.Channels);
            Add(FeedSource.Twitter, DataStore.TwitterAccounts);
            Add(FeedSource.GoogleBuzz, DataStore.GBuzzAccounts);
        }

        private static void Add(FeedSource source, ObservableCollection<Account> collection)
        {
            collection.CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs e)
                      {
                          if (e.NewItems != null)
                              foreach (Account account in e.NewItems)
                                  Add(source, account);

                          if (e.OldItems != null)
                              foreach (Account account in e.OldItems)
                                  Remove(source, account);
                      };

            collection.ForEach(account => Add(source, account));
        }

        private static void Add(FeedSource source, ObservableCollection<Channel> collection)
        {
            collection.CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs e)
            {
                if (e.NewItems != null)
                    foreach (Channel channel in e.NewItems)
                        Add(source, null, channel);

                if (e.OldItems != null)
                    foreach (Channel channel in e.OldItems)
                        Remove(source, null, channel);
            };

            collection.ForEach(channel => Add(source, null, channel));
        }

        private static void Add(FeedSource source, Account account)
        {
            account.Channels.CollectionChanged += Handler(source, account);
            account.Channels.ForEach(channel => Add(source, account, channel));
        }

        private static void Remove(FeedSource source, Account account)
        {
            account.Channels.CollectionChanged -= Handler(source, account);
            account.Channels.ForEach(channel => Remove(source, account, channel));
        }

        private static void Add(FeedSource source, Account account, Channel channel)
        {
            channel.Feeds.CollectionChanged += Handler(source, account, channel);
            //channel.Feeds.ForEach(feed => RaiseOnFeedAdd(channel, new FeedEventArgs(source, account, channel, feed)));
        }

        private static void Remove(FeedSource source, Account account, Channel channel)
        {
            channel.Feeds.CollectionChanged -= Handler(source, account, channel);
            //channel.Feeds.ForEach(feed => RaiseOnFeedRemove(channel, new FeedEventArgs(source, account, channel, feed)));
        }

        private static NotifyCollectionChangedEventHandler Handler(FeedSource source, Account account)
        {
            return delegate(object sender, NotifyCollectionChangedEventArgs e)
            {
                if (e.NewItems != null)
                    foreach (Channel channel in e.NewItems)
                        Add(source, account, channel);

                if (e.OldItems != null)
                    foreach (Channel channel in e.OldItems)
                        Remove(source, account, channel);
            };
        }

        private static NotifyCollectionChangedEventHandler Handler(FeedSource source, Account account, Channel channel)
        {
            return delegate(object sender, NotifyCollectionChangedEventArgs e)
            {
                if (e.NewItems != null)
                    foreach (Feed feed in e.NewItems)
                        RaiseOnFeedAdd(sender, new FeedEventArgs(source, account, channel, feed));

                if (e.OldItems != null)
                {
                    foreach (Feed feed in e.OldItems)
                        RaiseOnFeedRemove(sender, new FeedEventArgs(source, account, channel, feed));
                }
            };
        }

        private static void RaiseOnFeedAdd(object sender, FeedEventArgs e)
        {
            if (OnFeedAdd != null)
                OnFeedAdd(sender, e);
        }

        private static void RaiseOnFeedRemove(object sender, FeedEventArgs e)
        {
            if (OnFeedRemove != null)
                OnFeedRemove(sender, e);
        }
    }
}


text:
from octavia.common import constants
from octavia.common import data_models
from octavia.db import models
from octavia.tests.unit.db import base

class ModelTestMixin(object):

    FAKE_UUID_1 = '0123456789012345678901234567890123456'
    FAKE_UUID_2 = '1234567890123456789012345678901234567'

    def _insert(self, session, model_cls, model_kwargs):
        with session.begin():
            model = model_cls(**model_kwargs)
            session.add(model)
        return model

    def associate_amphora(self, load_balancer, amphora):
        load_balancer.amphorae.append(amphora)

    def create_listener(self, session, **overrides):
        kwargs = {'tenant_id': self.FAKE_UUID_1,
                  'id': self.FAKE_UUID_1,
                  'protocol': constants.PROTOCOL_HTTP,
                  'protocol_port': 80,
                  'provisioning_status': constants.ACTIVE,
                  'operating_status': constants.ONLINE,
                  'enabled': True}
        kwargs.update(overrides)
        return self._insert(session, models.Listener, kwargs)

    def create_listener_statistics(self, session, listener_id, **overrides):
        kwargs = {'listener_id': listener_id,
                  'bytes_in': 0,
                  'bytes_out': 0,
                  'active_connections': 0,
                  'total_connections': 0}
        kwargs.update(overrides)
        return self._insert(session, models.ListenerStatistics, kwargs)

    def create_pool(self, session, **overrides):
        kwargs = {'tenant_id': self.FAKE_UUID_1,
                  'id': self.FAKE_UUID_1,
                  'protocol': constants.PROTOCOL_HTTP,
                  'lb_algorithm': constants.LB_ALGORITHM_ROUND_ROBIN,
                  'operating_status': constants.ONLINE,
                  'enabled': True}
        kwargs.update(overrides)
        return self._insert(session, models.Pool, kwargs)

    def create_session_persistence(self, session, pool_id, **overrides):
        kwargs = {'pool_id': pool_id,
                  'type': constants.SESSION_PERSISTENCE_HTTP_COOKIE}
        kwargs.update(overrides)
        return self._insert(session, models.SessionPersistence, kwargs)

    def create_health_monitor(self, session, pool_id, **overrides):
        kwargs = {'tenant_id': self.FAKE_UUID_1,
                  'id': self.FAKE_UUID_1,
                  'pool_id': pool_id,
                  'type': constants.HEALTH_MONITOR_HTTP,
                  'delay': 1,
                  'timeout': 1,
                  'fall_threshold': 1,
                  'rise_threshold': 1,
                  'enabled': True}
        kwargs.update(overrides)
        return self._insert(session, models.HealthMonitor, kwargs)

    def create_member(self, session, pool_id, **overrides):
        kwargs = {'tenant_id': self.FAKE_UUID_1,
                  'id': self.FAKE_UUID_1,
                  'pool_id': pool_id,
                  'ip_address': '10.0.0.1',
                  'protocol_port': 80,
                  'operating_status': constants.ONLINE,
                  'enabled': True}
        kwargs.update(overrides)
        return self._insert(session, models.Member, kwargs)

    def create_load_balancer(self, session, **overrides):
        kwargs = {'tenant_id': self.FAKE_UUID_1,
                  'id': self.FAKE_UUID_1,
                  'provisioning_status': constants.ACTIVE,
                  'operating_status': constants.ONLINE,
                  'enabled': True}
        kwargs.update(overrides)
        return self._insert(session, models.LoadBalancer, kwargs)

    def create_vip(self, session, load_balancer_id, **overrides):
        kwargs = {'load_balancer_id': load_balancer_id}
        kwargs.update(overrides)
        return self._insert(session, models.Vip, kwargs)

    def create_sni(self, session, **overrides):
        kwargs = {'listener_id': self.FAKE_UUID_1,
                  'tls_container_id': self.FAKE_UUID_1}
        kwargs.update(overrides)
        return self._insert(session, models.SNI, kwargs)

    def create_amphora(self, session, **overrides):
        kwargs = {'id': self.FAKE_UUID_1,
                  'host_id': self.FAKE_UUID_1,
                  'status': constants.ONLINE}
        kwargs.update(overrides)
        return self._insert(session, models.Amphora, kwargs)

class PoolModelTest(base.OctaviaDBTestBase, ModelTestMixin):

    def test_create(self):
        self.create_pool(self.session)

    def test_update(self):
        pool = self.create_pool(self.session)
        id = pool.id
        pool.name = 'test1'
        new_pool = self.session.query(
            models.Pool).filter_by(id=id).first()
        self.assertEqual('test1', new_pool.name)

    def test_delete(self):
        pool = self.create_pool(self.session)
        id = pool.id
        with self.session.begin():
            self.session.delete(pool)
            self.session.flush()
        new_pool = self.session.query(
            models.Pool).filter_by(id=id).first()
        self.assertIsNone(new_pool)

    def test_member_relationship(self):
        pool = self.create_pool(self.session)
        self.create_member(self.session, pool.id, id=self.FAKE_UUID_1,
                           ip_address="10.0.0.1")
        self.create_member(self.session, pool.id, id=self.FAKE_UUID_2,
                           ip_address="10.0.0.2")
        new_pool = self.session.query(
            models.Pool).filter_by(id=pool.id).first()
        self.assertIsNotNone(new_pool.members)
        self.assertEqual(2, len(new_pool.members))
        self.assertTrue(isinstance(new_pool.members[0], models.Member))

    def test_health_monitor_relationship(self):
        pool = self.create_pool(self.session)
        self.create_health_monitor(self.session, pool.id)
        new_pool = self.session.query(models.Pool).filter_by(
            id=pool.id).first()
        self.assertIsNotNone(new_pool.health_monitor)
        self.assertTrue(isinstance(new_pool.health_monitor,
                                   models.HealthMonitor))

    def test_session_persistence_relationship(self):
        pool = self.create_pool(self.session)
        self.create_session_persistence(self.session, pool_id=pool.id)
        new_pool = self.session.query(models.Pool).filter_by(
            id=pool.id).first()
        self.assertIsNotNone(new_pool.session_persistence)
        self.assertTrue(isinstance(new_pool.session_persistence,
                                   models.SessionPersistence))

    def test_listener_relationship(self):
        pool = self.create_pool(self.session)
        self.create_listener(self.session, default_pool_id=pool.id)
        new_pool = self.session.query(models.Pool).filter_by(
            id=pool.id).first()
        self.assertIsNotNone(new_pool.listener)
        self.assertTrue(isinstance(new_pool.listener, models.Listener))

class MemberModelTest(base.OctaviaDBTestBase, ModelTestMixin):

    def setUp(self):
        super(MemberModelTest, self).setUp()
        self.pool = self.create_pool(self.session)

    def test_create(self):
        self.create_member(self.session, self.pool.id)

    def test_update(self):
        member = self.create_member(self.session, self.pool.id)
        member_id = member.id
        member.name = 'test1'
        new_member = self.session.query(
            models.Member).filter_by(id=member_id).first()
        self.assertEqual('test1', new_member.name)

    def test_delete(self):
        member = self.create_member(self.session, self.pool.id)
        member_id = member.id
        with self.session.begin():
            self.session.delete(member)
            self.session.flush()
        new_member = self.session.query(
            models.Member).filter_by(id=member_id).first()
        self.assertIsNone(new_member)

    def test_pool_relationship(self):
        member = self.create_member(self.session, self.pool.id,
                                    id=self.FAKE_UUID_1,
                                    ip_address="10.0.0.1")
        self.create_member(self.session, self.pool.id, id=self.FAKE_UUID_2,
                           ip_address="10.0.0.2")
        new_member = self.session.query(models.Member).filter_by(
            id=member.id).first()
        self.assertIsNotNone(new_member.pool)
        self.assertTrue(isinstance(new_member.pool, models.Pool))

class SessionPersistenceModelTest(base.OctaviaDBTestBase, ModelTestMixin):

    def setUp(self):
        super(SessionPersistenceModelTest, self).setUp()
        self.pool = self.create_pool(self.session)

    def test_create(self):
        self.create_session_persistence(self.session, self.pool.id)

    def test_update(self):
        session_persistence = self.create_session_persistence(self.session,
                                                              self.pool.id)
        session_persistence.name = 'test1'
        new_session_persistence = self.session.query(
            models.SessionPersistence).filter_by(pool_id=self.pool.id).first()
        self.assertEqual('test1', new_session_persistence.name)

    def test_delete(self):
        session_persistence = self.create_session_persistence(self.session,
                                                              self.pool.id)
        with self.session.begin():
            self.session.delete(session_persistence)
            self.session.flush()
        new_session_persistence = self.session.query(
            models.SessionPersistence).filter_by(pool_id=self.pool.id).first()
        self.assertIsNone(new_session_persistence)

    def test_pool_relationship(self):
        self.create_session_persistence(self.session, self.pool.id)
        new_persistence = self.session.query(
            models.SessionPersistence).filter_by(pool_id=self.pool.id).first()
        self.assertIsNotNone(new_persistence.pool)
        self.assertTrue(isinstance(new_persistence.pool, models.Pool))

class ListenerModelTest(base.OctaviaDBTestBase, ModelTestMixin):

    def test_create(self):
        self.create_listener(self.session)

    def test_update(self):
        listener = self.create_listener(self.session)
        listener_id = listener.id
        listener.name = 'test1'
        new_listener = self.session.query(
            models.Listener).filter_by(id=listener_id).first()
        self.assertEqual('test1', new_listener.name)

    def test_delete(self):
        listener = self.create_listener(self.session)
        listener_id = listener.id
        with self.session.begin():
            self.session.delete(listener)
            self.session.flush()
        new_listener = self.session.query(
            models.Listener).filter_by(id=listener_id).first()
        self.assertIsNone(new_listener)

    def test_load_balancer_relationship(self):
        lb = self.create_load_balancer(self.session)
        listener = self.create_listener(self.session, load_balancer_id=lb.id)
        new_listener = self.session.query(
            models.Listener).filter_by(id=listener.id).first()
        self.assertIsNotNone(new_listener.load_balancer)
        self.assertTrue(isinstance(new_listener.load_balancer,
                                   models.LoadBalancer))

    def test_listener_statistics_relationship(self):
        listener = self.create_listener(self.session)
        self.create_listener_statistics(self.session, listener_id=listener.id)
        new_listener = self.session.query(models.Listener).filter_by(
            id=listener.id).first()
        self.assertIsNotNone(new_listener.stats)
        self.assertTrue(isinstance(new_listener.stats,
                                   models.ListenerStatistics))

    def test_pool_relationship(self):
        pool = self.create_pool(self.session)
        listener = self.create_listener(self.session, default_pool_id=pool.id)
        new_listener = self.session.query(models.Listener).filter_by(
            id=listener.id).first()
        self.assertIsNotNone(new_listener.default_pool)
        self.assertTrue(isinstance(new_listener.default_pool, models.Pool))

    def test_sni_relationship(self):
        listener = self.create_listener(self.session)
        self.create_sni(self.session, listener_id=listener.id,
                        tls_container_id=self.FAKE_UUID_1)
        self.create_sni(self.session, listener_id=listener.id,
                        tls_container_id=self.FAKE_UUID_2)
        new_listener = self.session.query(models.Listener).filter_by(
            id=listener.id).first()
        self.assertIsNotNone(new_listener.sni_containers)
        self.assertEqual(2, len(new_listener.sni_containers))

class ListenerStatisticsModelTest(base.OctaviaDBTestBase, ModelTestMixin):

    def setUp(self):
        super(ListenerStatisticsModelTest, self).setUp()
        self.listener = self.create_listener(self.session)

    def test_create(self):
        self.create_listener_statistics(self.session, self.listener.id)

    def test_update(self):
        stats = self.create_listener_statistics(self.session, self.listener.id)
        stats.name = 'test1'
        new_stats = self.session.query(models.ListenerStatistics).filter_by(
            listener_id=self.listener.id).first()
        self.assertEqual('test1', new_stats.name)

    def test_delete(self):
        stats = self.create_listener_statistics(self.session, self.listener.id)
        with self.session.begin():
            self.session.delete(stats)
            self.session.flush()
        new_stats = self.session.query(models.ListenerStatistics).filter_by(
            listener_id=self.listener.id).first()
        self.assertIsNone(new_stats)

    def test_listener_relationship(self):
        self.create_listener_statistics(self.session, self.listener.id)
        new_stats = self.session.query(models.ListenerStatistics).filter_by(
            listener_id=self.listener.id).first()
        self.assertIsNotNone(new_stats.listener)
        self.assertTrue(isinstance(new_stats.listener, models.Listener))

class HealthMonitorModelTest(base.OctaviaDBTestBase, ModelTestMixin):

    def setUp(self):
        super(HealthMonitorModelTest, self).setUp()
        self.pool = self.create_pool(self.session)

    def test_create(self):
        self.create_health_monitor(self.session, self.pool.id)

    def test_update(self):
        health_monitor = self.create_health_monitor(self.session, self.pool.id)
        health_monitor_id = health_monitor.id
        health_monitor.name = 'test1'
        new_health_monitor = self.session.query(
            models.HealthMonitor).filter_by(id=health_monitor_id).first()
        self.assertEqual('test1', new_health_monitor.name)

    def test_delete(self):
        health_monitor = self.create_health_monitor(self.session, self.pool.id)
        health_monitor_id = health_monitor.id
        with self.session.begin():
            self.session.delete(health_monitor)
            self.session.flush()
        new_health_monitor = self.session.query(
            models.HealthMonitor).filter_by(id=health_monitor_id).first()
        self.assertIsNone(new_health_monitor)

    def test_pool_relationship(self):
        health_monitor = self.create_health_monitor(self.session, self.pool.id)
        new_health_monitor = self.session.query(
            models.HealthMonitor).filter_by(id=health_monitor.id).first()
        self.assertIsNotNone(new_health_monitor.pool)
        self.assertTrue(isinstance(new_health_monitor.pool, models.Pool))

class LoadBalancerModelTest(base.OctaviaDBTestBase, ModelTestMixin):

    def test_create(self):
        self.create_load_balancer(self.session)

    def test_update(self):
        load_balancer = self.create_load_balancer(self.session)
        lb_id = load_balancer.id
        load_balancer.name = 'test1'
        new_load_balancer = self.session.query(
            models.LoadBalancer).filter_by(id=lb_id).first()
        self.assertEqual('test1', new_load_balancer.name)

    def test_delete(self):
        load_balancer = self.create_load_balancer(self.session)
        lb_id = load_balancer.id
        with self.session.begin():
            self.session.delete(load_balancer)
            self.session.flush()
        new_load_balancer = self.session.query(
            models.LoadBalancer).filter_by(id=lb_id).first()
        self.assertIsNone(new_load_balancer)

    def test_listener_relationship(self):
        load_balancer = self.create_load_balancer(self.session)
        self.create_listener(self.session, load_balancer_id=load_balancer.id)
        new_load_balancer = self.session.query(
            models.LoadBalancer).filter_by(id=load_balancer.id).first()
        self.assertIsNotNone(new_load_balancer.listeners)
        self.assertEqual(1, len(new_load_balancer.listeners))

    def test_load_balancer_amphora_relationship(self):
        load_balancer = self.create_load_balancer(self.session)
        amphora = self.create_amphora(self.session)
        self.associate_amphora(load_balancer, amphora)
        new_load_balancer = self.session.query(
            models.LoadBalancer).filter_by(id=load_balancer.id).first()
        self.assertIsNotNone(new_load_balancer.amphorae)
        self.assertEqual(1, len(new_load_balancer.amphorae))

    def test_load_balancer_vip_relationship(self):
        load_balancer = self.create_load_balancer(self.session)
        self.create_vip(self.session, load_balancer.id)
        new_load_balancer = self.session.query(
            models.LoadBalancer).filter_by(id=load_balancer.id).first()
        self.assertIsNotNone(new_load_balancer.vip)
        self.assertIsInstance(new_load_balancer.vip, models.Vip)

class VipModelTest(base.OctaviaDBTestBase, ModelTestMixin):

    def setUp(self):
        super(VipModelTest, self).setUp()
        self.load_balancer = self.create_load_balancer(self.session)

    def test_create(self):
        self.create_vip(self.session, self.load_balancer.id)

    def test_update(self):
        vip = self.create_vip(self.session, self.load_balancer.id)
        vip.ip_address = "10.0.0.1"
        new_vip = self.session.query(models.Vip).filter_by(
            load_balancer_id=self.load_balancer.id).first()
        self.assertEqual("10.0.0.1", new_vip.ip_address)

    def test_delete(self):
        vip = self.create_vip(self.session, self.load_balancer.id)
        with self.session.begin():
            self.session.delete(vip)
            self.session.flush()
        new_vip = self.session.query(models.Vip).filter_by(
            load_balancer_id=vip.load_balancer_id).first()
        self.assertIsNone(new_vip)

    def test_vip_load_balancer_relationship(self):
        self.create_vip(self.session, self.load_balancer.id)
        new_vip = self.session.query(models.Vip).filter_by(
            load_balancer_id=self.load_balancer.id).first()
        self.assertIsNotNone(new_vip.load_balancer)
        self.assertTrue(isinstance(new_vip.load_balancer, models.LoadBalancer))

class SNIModelTest(base.OctaviaDBTestBase, ModelTestMixin):

    def setUp(self):
        super(SNIModelTest, self).setUp()
        self.listener = self.create_listener(self.session)

    def test_create(self):
        self.create_sni(self.session, listener_id=self.listener.id)

    def test_update(self):
        sni = self.create_sni(self.session, listener_id=self.listener.id)
        sni.listener_id = self.FAKE_UUID_2
        new_sni = self.session.query(
            models.SNI).filter_by(listener_id=self.FAKE_UUID_2).first()
        self.assertEqual(self.FAKE_UUID_2, new_sni.listener_id)

    def test_delete(self):
        sni = self.create_sni(self.session, listener_id=self.listener.id)
        with self.session.begin():
            self.session.delete(sni)
            self.session.flush()
        new_sni = self.session.query(
            models.SNI).filter_by(listener_id=self.listener.id).first()
        self.assertIsNone(new_sni)

    def test_sni_relationship(self):
        self.create_sni(self.session, listener_id=self.listener.id)
        new_sni = self.session.query(models.SNI).filter_by(
            listener_id=self.listener.id).first()
        self.assertIsNotNone(new_sni.listener)
        self.assertTrue(isinstance(new_sni.listener, models.Listener))

class AmphoraModelTest(base.OctaviaDBTestBase, ModelTestMixin):

    def setUp(self):
        super(AmphoraModelTest, self).setUp()
        self.load_balancer = self.create_load_balancer(self.session)

    def test_create(self):
        self.create_amphora(self.session)

    def test_update(self):
        amphora = self.create_amphora(
            self.session)
        amphora.amphora_id = self.FAKE_UUID_2
        new_amphora = self.session.query(models.Amphora).filter_by(
            id=amphora.id).first()
        self.assertEqual(self.FAKE_UUID_2, new_amphora.amphora_id)

    def test_delete(self):
        amphora = self.create_amphora(
            self.session)
        with self.session.begin():
            self.session.delete(amphora)
            self.session.flush()
        new_amphora = self.session.query(
            models.Amphora).filter_by(id=amphora.id).first()
        self.assertIsNone(new_amphora)

    def test_load_balancer_relationship(self):
        amphora = self.create_amphora(self.session)
        self.associate_amphora(self.load_balancer, amphora)
        new_amphora = self.session.query(models.Amphora).filter_by(
            id=amphora.id).first()
        self.assertIsNotNone(new_amphora.load_balancer)
        self.assertIsInstance(new_amphora.load_balancer, models.LoadBalancer)

class DataModelConversionTest(base.OctaviaDBTestBase, ModelTestMixin):

    def setUp(self):
        super(DataModelConversionTest, self).setUp()
        self.pool = self.create_pool(self.session)
        self.hm = self.create_health_monitor(self.session, self.pool.id)
        self.member = self.create_member(self.session, self.pool.id,
                                         id=self.FAKE_UUID_1,
                                         ip_address='10.0.0.1')
        self.sp = self.create_session_persistence(self.session, self.pool.id)
        self.lb = self.create_load_balancer(self.session)
        self.vip = self.create_vip(self.session, self.lb.id)
        self.listener = self.create_listener(self.session,
                                             default_pool_id=self.pool.id,
                                             load_balancer_id=self.lb.id)
        self.stats = self.create_listener_statistics(self.session,
                                                     self.listener.id)
        self.sni = self.create_sni(self.session, listener_id=self.listener.id)

    def test_load_balancer_tree(self):
        lb_db = self.session.query(models.LoadBalancer).filter_by(
            id=self.lb.id).first()
        self.check_load_balancer(lb_db.to_data_model())

    def test_vip_tree(self):
        vip_db = self.session.query(models.Vip).filter_by(
            load_balancer_id=self.lb.id).first()
        self.check_vip(vip_db.to_data_model())

    def test_listener_tree(self):
        listener_db = self.session.query(models.Listener).filter_by(
            id=self.listener.id).first()
        self.check_listener(listener_db.to_data_model())

    def test_sni_tree(self):
        sni_db = self.session.query(models.SNI).filter_by(
            listener_id=self.listener.id).first()
        self.check_sni(sni_db.to_data_model())

    def test_listener_statistics_tree(self):
        stats_db = self.session.query(models.ListenerStatistics).filter_by(
            listener_id=self.listener.id).first()
        self.check_listener_statistics(stats_db.to_data_model())

    def test_pool_tree(self):
        pool_db = self.session.query(models.Pool).filter_by(
            id=self.pool.id).first()
        self.check_pool(pool_db.to_data_model())

    def test_session_persistence_tree(self):
        sp_db = self.session.query(models.SessionPersistence).filter_by(
            pool_id=self.pool.id).first()
        self.check_session_persistence(sp_db.to_data_model())

    def test_health_monitor_tree(self):
        hm_db = self.session.query(models.HealthMonitor).filter_by(
            id=self.hm.id).first()
        self.check_health_monitor(hm_db.to_data_model())

    def test_member_tree(self):
        member_db = self.session.query(models.Member).filter_by(
            id=self.member.id).first()
        self.check_member(member_db.to_data_model())

    def check_load_balancer(self, lb, check_listeners=True,
                            check_amphorae=True, check_vip=True):
        self.assertIsInstance(lb, data_models.LoadBalancer)
        self.check_load_balancer_data_model(lb)
        self.assertIsInstance(lb.listeners, list)
        self.assertIsInstance(lb.amphorae, list)
        if check_listeners:
            for listener in lb.listeners:
                self.check_listener(listener, check_lb=False)
        if check_amphorae:
            for amphora in lb.amphorae:
                self.check_amphora(amphora, check_load_balancer=False)
        if check_vip:
            self.check_vip(lb.vip, check_lb=False)

    def check_vip(self, vip, check_lb=True):
        self.assertIsInstance(vip, data_models.Vip)
        self.check_vip_data_model(vip)
        if check_lb:
            self.check_load_balancer(vip.load_balancer, check_vip=False)

    def check_sni(self, sni, check_listener=True):
        self.assertIsInstance(sni, data_models.SNI)
        self.check_sni_data_model(sni)
        if check_listener:
            self.check_listener(sni.listener, check_sni=False)

    def check_listener_statistics(self, stats, check_listener=True):
        self.assertIsInstance(stats, data_models.ListenerStatistics)
        self.check_listener_statistics_data_model(stats)
        if check_listener:
            self.check_listener(stats.listener, check_statistics=False)

    def check_amphora(self, amphora, check_load_balancer=True):
        self.assertIsInstance(amphora, data_models.Amphora)
        self.check_amphora_data_model(amphora)
        if check_load_balancer:
            self.check_load_balancer(amphora.load_balancer)

    def check_listener(self, listener, check_sni=True, check_pool=True,
                       check_lb=True, check_statistics=True):
        self.assertIsInstance(listener, data_models.Listener)
        self.check_listener_data_model(listener)
        if check_lb:
            self.check_load_balancer(listener.load_balancer)
        if check_sni:
            c_containers = listener.sni_containers
            self.assertIsInstance(c_containers, list)
            for sni in c_containers:
                self.check_sni(sni, check_listener=False)
        if check_pool:
            self.check_pool(listener.default_pool, check_listener=False)
        if check_statistics:
            self.check_listener_statistics(listener.stats,
                                           check_listener=False)

    def check_session_persistence(self, session_persistence, check_pool=True):
        self.assertIsInstance(session_persistence,
                              data_models.SessionPersistence)
        self.check_session_persistence_data_model(session_persistence)
        if check_pool:
            self.check_pool(session_persistence.pool, check_sp=False)

    def check_member(self, member, check_pool=True):
        self.assertIsInstance(member, data_models.Member)
        self.check_member_data_model(member)
        if check_pool:
            self.check_pool(member.pool)

    def check_health_monitor(self, health_monitor, check_pool=True):
        self.assertIsInstance(health_monitor, data_models.HealthMonitor)
        self.check_health_monitor_data_model(health_monitor)
        if check_pool:
            self.check_pool(health_monitor.pool, check_hm=False)

    def check_pool(self, pool, check_listener=True, check_sp=True,
                   check_hm=True, check_members=True):
        self.assertIsInstance(pool, data_models.Pool)
        self.check_pool_data_model(pool)
        if check_listener:
            self.check_listener(pool.listener, check_pool=False)
        if check_sp:
            self.check_session_persistence(pool.session_persistence,
                                           check_pool=False)
        if check_members:
            c_members = pool.members
            self.assertIsNotNone(c_members)
            self.assertEqual(1, len(c_members))
            for c_member in c_members:
                self.check_member(c_member, check_pool=False)
        if check_hm:
            self.check_health_monitor(pool.health_monitor, check_pool=False)

    def check_load_balancer_data_model(self, lb):
        self.assertEqual(self.FAKE_UUID_1, lb.tenant_id)
        self.assertEqual(self.FAKE_UUID_1, lb.id)
        self.assertEqual(constants.ACTIVE, lb.provisioning_status)
        self.assertEqual(True, lb.enabled)

    def check_vip_data_model(self, vip):
        self.assertEqual(self.FAKE_UUID_1, vip.load_balancer_id)

    def check_listener_data_model(self, listener):
        self.assertEqual(self.FAKE_UUID_1, listener.tenant_id)
        self.assertEqual(self.FAKE_UUID_1, listener.id)
        self.assertEqual(constants.PROTOCOL_HTTP, listener.protocol)
        self.assertEqual(80, listener.protocol_port)
        self.assertEqual(constants.ACTIVE, listener.provisioning_status)
        self.assertEqual(constants.ONLINE, listener.operating_status)
        self.assertEqual(True, listener.enabled)

    def check_sni_data_model(self, sni):
        self.assertEqual(self.FAKE_UUID_1, sni.listener_id)
        self.assertEqual(self.FAKE_UUID_1, sni.tls_container_id)

    def check_listener_statistics_data_model(self, stats):
        self.assertEqual(self.listener.id, stats.listener_id)
        self.assertEqual(0, stats.bytes_in)
        self.assertEqual(0, stats.bytes_out)
        self.assertEqual(0, stats.active_connections)
        self.assertEqual(0, stats.total_connections)

    def check_pool_data_model(self, pool):
        self.assertEqual(self.FAKE_UUID_1, pool.tenant_id)
        self.assertEqual(self.FAKE_UUID_1, pool.id)
        self.assertEqual(constants.PROTOCOL_HTTP, pool.protocol)
        self.assertEqual(constants.LB_ALGORITHM_ROUND_ROBIN, pool.lb_algorithm)
        self.assertEqual(constants.ONLINE, pool.operating_status)
        self.assertEqual(True, pool.enabled)

    def check_session_persistence_data_model(self, sp):
        self.assertEqual(self.pool.id, sp.pool_id)
        self.assertEqual(constants.SESSION_PERSISTENCE_HTTP_COOKIE, sp.type)

    def check_health_monitor_data_model(self, hm):
        self.assertEqual(self.FAKE_UUID_1, hm.tenant_id)
        self.assertEqual(self.FAKE_UUID_1, hm.id)
        self.assertEqual(constants.HEALTH_MONITOR_HTTP, hm.type)
        self.assertEqual(1, hm.delay)
        self.assertEqual(1, hm.timeout)
        self.assertEqual(1, hm.fall_threshold)
        self.assertEqual(1, hm.rise_threshold)
        self.assertEqual(True, hm.enabled)

    def check_member_data_model(self, member):
        self.assertEqual(self.FAKE_UUID_1, member.tenant_id)
        self.assertEqual(self.FAKE_UUID_1, member.id)
        self.assertEqual(self.pool.id, member.pool_id)
        self.assertEqual('10.0.0.1', member.ip_address)
        self.assertEqual(80, member.protocol_port)
        self.assertEqual(constants.ONLINE, member.operating_status)
        self.assertEqual(True, member.enabled)

    def check_amphora_data_model(self, amphora):
        self.assertEqual(self.FAKE_UUID_1, amphora.id)
        self.assertEqual(self.FAKE_UUID_1, amphora.host_id)
        self.assertEqual(constants.ONLINE, amphora.status)

    def check_load_balancer_amphora_data_model(self, amphora):
        self.assertEqual(self.FAKE_UUID_1, amphora.amphora_id)
        self.assertEqual(self.FAKE_UUID_1, amphora.load_balancer_id)


text:
import React from 'react';
import { PageTask as Task } from '../task';

export default {
  component: Task,
  title: 'Pages/Task',
}

export const Default = () => (
  <Task
    router={{
      query: {
        openshiftProjectName: 'Example',
        taskId: 42,
      },
    }}
  />
);


text:
CREATE EXTENSION IF NOT EXISTS hstore;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE TABLE deployments (
  id uuid NOT NULL DEFAULT uuid_generate_v4() primary key,
  status text NOT NULL,
  github_id int NOT NULL,
  sha text NOT NULL,
  ref text NOT NULL,
  environment text NOT NULL,
  description text NOT NULL,
  repo text NOT NULL,
  provider text NOT NULL,
  error text NOT NULL,
  created_at timestamp without time zone default (now() at time zone 'utc') NOT NULL,
  started_at timestamp without time zone,
  completed_at timestamp without time zone
);

CREATE TABLE logs (
  id uuid NOT NULL DEFAULT uuid_generate_v4() primary key,
  deployment_id uuid NOT NULL references deployments(id) ON DELETE CASCADE,
  text text NOT NULL,
  at timestamp without time zone NOT NULL
);

CREATE INDEX index_deployments_on_github_id ON deployments USING btree (github_id);
CREATE INDEX index_deployments_on_created_at ON deployments USING btree (created_at);
CREATE INDEX index_logs_on_at ON logs USING btree (at);


text:
<?php

namespace RedKiteLabs\ThemeEngineBundle\Tests\Unit\Core\Asset;

use RedKiteLabs\ThemeEngineBundle\Tests\TestCase;
use RedKiteLabs\ThemeEngineBundle\Core\Rendering\DependencyInjection\BaseExtension;
use org\bovigo\vfs\vfsStream;

/**
 * ExtensionTester
 *
 * @author RedKite Labs <webmaster@redkite-labs.com>
 */
class ExtensionTester extends BaseExtension
{
    public function configureTheme()
    {
        return array(
                    array(
                        'path' => vfsStream::url('root/Resources/config'),
                        'configFiles' =>
                        array(
                            'theme_name.xml',
                        ),
                        'configuration' =>
                        array(
                            array(
                                'path' => vfsStream::url('root/Resources/config/templates'),
                                'configFiles' =>
                                array(
                                    'template.xml',
                                ),
                                'configuration' =>
                                array(
                                    array(
                                        'path' => vfsStream::url('root/Resources/config/templates/slots'),
                                        'configFiles' =>
                                        array(
                                            'slots.xml',
                                        ),
                                    ),
                                ),
                            ),
                        ),
                    ),
                );
    }

    public function getAlias() {
        return "ExtensionTester";
    }
}

/**
 * ExtensionTest
 *
 * @author RedKite Labs <webmaster@redkite-labs.com>
 */
class ExtensionTest extends TestCase
{
    private $templateAssets;
    private $kernel;
    private $templateSlots;

    protected function setUp()
    {
        $this->root = vfsStream::setup('root', null, array(
            'Resources' => array(
                'config' => array(
                    'templates'=> array(
                            'slots'=> array(
                                'slots.xml' => '<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="red_kite_labs_theme.theme.template.apps.slots.nav_menu_blocks_title" class="%red_kite_labs_theme_engine.slot.class%" public="false">
            <argument type="string">nav_menu_blocks_title</argument>
            <argument type="collection" >
                <argument key="repeated">language</argument>
                <argument key="htmlContent">
                    <![CDATA[
Block Apps
]]>
                </argument>
            </argument>
            <tag name="red_kite_labs_theme.theme.template.apps.slots" />
        </service>
    </services>
</container>',
                            ),

                        'template.xml' => '<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="red_kite_labs_theme.theme.template_assets.apps" class="%red_kite_labs_theme_engine.template_assets.class%" public="false">
        </service>

        <service id="red_kite_labs_theme.theme.template.apps.slots" class="%red_kite_labs_theme_engine.template_slots.class%" public="false">
            <tag name="red_kite_labs_theme.theme.template.apps" />
        </service>

        <service id="red_kite_labs_theme.theme.template.apps" class="%red_kite_labs_theme_engine.template.class%" public="false">
            <argument type="service" id="kernel" />
            <argument type="service" id="red_kite_labs_theme.theme.template_assets.apps" />
            <argument type="service" id="red_kite_labs_theme.theme.template.apps.slots" />
            <tag name="red_kite_labs_theme.theme.template" />

            <call method="setThemeName">
                <argument type="string">RedKiteLabsThemeBundle</argument>
            </call>
            <call method="setTemplateName">
                <argument type="string">apps</argument>
            </call>
        </service>
    </services>
</container>',
                    ),
                    'theme_name.xml' => '<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="red_kite_labs_theme.theme" class="%red_kite_labs_theme_engine.theme.class%">
            <argument type="string">RedKiteLabsTheme</argument>
            <tag name="red_kite_labs_theme_engine.themes.theme" />
        </service>
    </services>
</container>',
                ),
            ),
        ));
    }

    public function testAAA()
    {
        $container = $this->getMock('\Symfony\Component\DependencyInjection\ContainerBuilder');

        $extensionTester = new ExtensionTester();
        $extensionTester->load(array('templates' => array()), $container);
    }
}


text:
package io.smartcat.ranger;

import java.util.LinkedHashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

import io.smartcat.ranger.core.CompositeValue;
import io.smartcat.ranger.core.ConstantValue;
import io.smartcat.ranger.core.TypeConverterValue;
import io.smartcat.ranger.core.Value;

/**
 * Builder for {@link ObjectGenerator}.
 */
public class ObjectGeneratorBuilder {

    private final Map<String, Value<?>> propertyValues;

    /**
     * Constructs {@link ObjectGeneratorBuilder}.
     */
    public ObjectGeneratorBuilder() {
        this.propertyValues = new LinkedHashMap<>();
    }

    /**
     * Sets the value to be used for generating values for property.
     *
     * @param property Name of the property.
     * @param value Value to be used for generating values.
     * @param <V> Type of object which value will be generate.
     * @return This builder.
     */
    @SuppressWarnings({ "rawtypes" })
    public <V> ObjectGeneratorBuilder prop(String property, V value) {
        propertyValues.put(property,
                value instanceof ObjectGenerator ? ((ObjectGenerator) value).value : ConstantValue.of(value));
        return this;
    }

    /**
     * Builds {@link ObjectGenerator} based on current builder configuration. Resulting {@link ObjectGenerator} will
     * have {@code Map<String, Object>} as return type.
     *
     * @return Instance of {@link ObjectGenerator}.
     */
    public ObjectGenerator<Map<String, Object>> build() {
        return new ObjectGenerator<>(new CompositeValue(propertyValues));
    }

    /**
     * Builds {@link ObjectGenerator} based on current builder configuration. Resulting {@link ObjectGenerator} will try
     * to convert configured output to specified objectType.
     *
     * @param objectType Type of object to which conversion will be attempted.
     * @param <T> Type of object {@link ObjectGenerator} will generate.
     * @return Instance of {@link ObjectGenerator}.
     */
    public <T> ObjectGenerator<T> build(Class<T> objectType) {
        return build(objectType, new ObjectMapper());
    }

    /**
     * Builds {@link ObjectGenerator} based on current builder configuration. Resulting {@link ObjectGenerator} will try
     * to convert configured output to specified objectType.
     *
     * @param objectType Type of object to which conversion will be attempted.
     * @param objectMapper Object mapper which will be used for conversion.
     * @param <T> Type of object {@link ObjectGenerator} will generate.
     * @return Instance of {@link ObjectGenerator}.
     */
    public <T> ObjectGenerator<T> build(Class<T> objectType, ObjectMapper objectMapper) {
        if (objectType == null) {
            throw new RuntimeException("objectType cannot be null.");
        }
        CompositeValue compositeValue = new CompositeValue(propertyValues);
        return new ObjectGenerator<T>(new TypeConverterValue<>(objectType, compositeValue, objectMapper));
    }

}