text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mongo="http://www.springframework.org/schema/data/mongo"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
		"
        >
    <description>Spring公共配置文件</description>

    <!-- 加载配置属性文件 -->
    <context:property-placeholder ignore-unresolvable="true" location="classpath:mysite.properties"/>
    <!-- 加载应用属性实例,可通过  @Value("#{APP_PROP['jdbc.driver']}") String jdbcDriver 方式引用 -->
   <!-- <util:properties id="APP_PROP" location="classpath:mysite.properties" local-override="true"/>-->

    <!-- 使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,
        在SpringMvc中只扫描@Controller注解,并保证@Required、@Autowired、@Resource的属性被注入   -->
    <!-- 扫描注解Bean -->
    <context:component-scan base-package="com.github.mysite"><!-- base-package 如果多个,用","分隔 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- MyBatis begin -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 显式指定Mapper文件位置 -->
        <property name="mapperLocations" value="classpath:/mapper/**/*.xml"/>
        <property name="configLocation" value="classpath:/mybatis/mybatis-config.xml"></property>
    </bean>

    <!-- 扫描basePackage下所有以@MyBatisDao注解的接口 -->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.github.mysite"/>
        <property name="annotationClass" value="com.github.mysite.common.annotation.MyBatisDao"/>
    </bean>

    <!-- 定义事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置 Annotation 驱动,扫描@Transactional注解的类定义事务  -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
    <!--<aop:aspectj-autoproxy proxy-target-class="true"/>-->
    <!-- MyBatis end -->

    <!-- 配置 JSR303 Bean Validator 定义 -->
   <!-- <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>-->

    <!-- 计划任务配置,用 @Service @Lazy(false)标注类,用@Scheduled(cron = "0 0 2 * * ?")标注方法 -->
   <!-- <task:executor id="executor" pool-size="10"/>
    <task:scheduler id="scheduler" pool-size="10"/>
    <task:annotation-driven scheduler="scheduler" executor="executor" proxy-target-class="true"/>-->

      <!--配置 druid 数据源 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">

       <!-- <property name="driverClassName" value="${jdbc.driver}"/>-->

        <!-- 基本属性 url、user、password -->
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="${jdbc.pool.init}"/>
        <property name="minIdle" value="${jdbc.pool.minIdle}"/>
        <property name="maxActive" value="${jdbc.pool.maxActive}"/>

        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="${jdbc.maxWait}"/>

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"/>

        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"/>

        <property name="validationQuery" value="${jdbc.testSql}"/>
        <property name="testWhileIdle" value="${jdbc.testWhileIdle}"/>
        <property name="testOnBorrow" value="${jdbc.testOnBorrow}"/>
        <property name="testOnReturn" value="${jdbc.testOnReturn}"/>

        <!-- 配置监控统计拦截的filters -->
        <property name="filters" value="${jdbc.filters}"/>

        <property name="removeAbandoned" value="${jdbc.removeAbandoned}"/>
        <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}"/>
        <property name="logAbandoned" value="${jdbc.logAbandoned}"/>

        <!-- 配置监控统计拦截的filters -->
        <property name="proxyFilters">
            <list>
                <ref bean="stat-filter"/>
                <ref bean="wall-filter"/>
            </list>
        </property>
        <property name="useGlobalDataSourceStat" value="${jdbc.useGlobalDataSourceStat}"/>
        <!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用)-->
        <!--<property name="poolPreparedStatements" value="true" />-->
        <!--<property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> -->
        <!--提示Druid数据源需要对数据库密码进行解密,ConfigFilter解密-->
        <property name="connectionProperties" value="config.decrypt=true"/>
    </bean>

    <!-- 支持命名参数特性 :name -->
    <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
        <constructor-arg ref="dataSource" index="0">
        </constructor-arg>
    </bean>

    <bean id="stat-filter" class="com.alibaba.druid.filter.stat.StatFilter">
       <property name="slowSqlMillis" value="${jdbc.slowSqlMillis}"/>
       <property name="logSlowSql" value="${jdbc.logSlowSql}"/>
       <property name="mergeSql" value="${jdbc.mergeSql}"/>
   </bean>

   <!--<!–防御SQL注入攻击–>-->
   <!--<bean id="wall-filter-config" class="com.alibaba.druid.wall.WallConfig" init-method="init">-->
       <!--<!– 指定配置装载的目录,缺省 META-INF/druid/wall/mysql  –>-->
       <!--<!–<property name="dir" value="META-INF/druid/wall/mysql"/>–>-->
       <!--<!– 检查SELECT语句的WHERE子句是否是一个永真条件,默认true –>-->
       <!--<property name="selectWhereAlwayTrueCheck" value="false"/>-->
       <!--<!– 检查SELECT语句的HAVING子句是否是一个永真条件 –>-->
       <!--<property name="selectHavingAlwayTrueCheck" value="false"/>-->
   <!--</bean>-->

   <bean id="wall-filter" class="com.alibaba.druid.wall.WallFilter">
       <property name="dbType" value="mysql"/>
       <!--<property name="config" ref="wall-filter-config"/>-->
   </bean>

    <!-- file upload -->
   <!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!– one of the properties available; the maximum file size in bytes –>
        <property name="maxUploadSize" value="30000000"/>
    </bean>-->

    <!-- Email support -->
    <!--<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${mail.host}"/>
        <property name="port" value="${mail.port}"/>
        <property name="protocol" value="${mail.protocol}"/>
        <property name="username" value="${mail.username}"/>
        <property name="password" value="${mail.password}"/>
        <property name="defaultEncoding" value="${mail.encoding}"/>
        <property name="javaMailProperties">
            <util:properties location="classpath:javamail.properties"/>
        </property>
    </bean>
    <!– Apache velocity email template engine –>
    <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
        <property name="velocityProperties">
            <value>
                resource.loader=class
                class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
            </value>
        </property>
    </bean>-->
    <!-- Email support end -->

     <!--mongodb begin-->
    <!-- 定义mongo对象,对应的是mongodb官方jar包中的Mongo,replica-set设置集群副本的ip地址和端口 -->
   <!-- <mongo:mongo id="mongo" host="localhost" port="27017"></mongo:mongo>-->
    <!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->
    <!-- <mongo:db-factory id="mongoDbFactory"
                      host="domainName"
                      port="portNumber"
                      username="userName"
                      password="passWord"
                      dbname="DBName"
                      mongo-ref="mongo" /> -->
   <!-- <mongo:db-factory id="mongoDbFactory" dbname="test" mongo-ref="mongo"/>-->

    <!-- mongodb的主要操作对象,所有对mongodb的增删改查的操作都是通过它完成 -->
    <!--<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    </bean>-->
    <!-- 另一种简便的方式 -->
    <!--    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="mongo"/>
        <constructor-arg name="databaseName" value="mysite"/>
    </bean>-->

    <!-- 映射转换器,扫描back-package目录下的文件,根据注释,把它们作为mongodb的一个collection的映射 -->
    <!--<mongo:mapping-converter base-package="com.github.mysite" />-->
    <!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 -->
    <!--<mongo:repositories base-package="com.github.mysite"/>-->

    <!-- 国际化的消息资源文件(主要用于显示/错误消息定制) -->
    <!-- <bean id="messageSource"
           class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
         <property name="basenames">
             <list>
                 <value>classpath:i18n/messages_zh</value>
             </list>
         </property>
         <!– 默认为false,这样当Spring在ResourceBundle中找不到messageKey的话,就抛出NoSuchMessageException
             把它设置为True,则找不到不会抛出异常,而是使用messageKey作为返回值 –>
         <property name="useCodeAsDefaultMessage" value="true"/>
         <property name="defaultEncoding" value="UTF-8"/>
         <property name="cacheSeconds" value="60"/>
     </bean>-->

</beans>


text:
extern "C" {
#endif

#define crypto_scalarmult_curve25519_BYTES 32U
SODIUM_EXPORT
size_t crypto_scalarmult_curve25519_bytes(void);

#define crypto_scalarmult_curve25519_SCALARBYTES 32U
SODIUM_EXPORT
size_t crypto_scalarmult_curve25519_scalarbytes(void);

SODIUM_EXPORT
int crypto_scalarmult_curve25519(unsigned char *q, const unsigned char *n,
                                 const unsigned char *p)
            __attribute__ ((warn_unused_result));

SODIUM_EXPORT
int crypto_scalarmult_curve25519_base(unsigned char *q, const unsigned char *n);

#ifdef __cplusplus
}
#endif

#endif

redpajama_set_name: RedPajamaGithub


text:
require 'scenery/of_flexslider/engine'

module Scenery
  module OfFlexslider
  end
end


text:
typedef struct {
	uint32 start_addr;
	uint32 start_sector;
	uint32 max_sector_count;
	uint32 last_sector_erased;
	uint8 extra_count;
	uint8 extra_bytes[4];
	rboot_ota *ota;
	uint32 total_len;
	uint32 content_len;
	struct espconn *conn;
} upgrade_param;

static upgrade_param *upgrade;
static os_timer_t ota_timer;

// get current boot rom
uint8 ICACHE_FLASH_ATTR rboot_get_current_rom() {
	if ((uint32)rboot_get_current_rom & 0x80000)
		return 1;
	return 0;
}

// set current boot rom
bool ICACHE_FLASH_ATTR rboot_set_current_rom(uint8 rom) {
	uint32 flags = 0;
	if (SPI_FLASH_RESULT_OK != rps_get_flags(&flags, ZMOTE_CFG_ADDR)) {
		ERROR("Error reading RPS flags");
		return false;
	}
	flags = (flags & ~0x01) | rom;
	if (SPI_FLASH_RESULT_OK != rps_set_flags(flags, ZMOTE_CFG_ADDR)) {
		ERROR("Error writing RPS flags");
		return false;
	}
	return true;
}

// function to do the actual writing to flash
static bool ICACHE_FLASH_ATTR write_flash(uint8 *data, uint16 len) {

	bool ret = false;
	uint8 *buffer;

	if (data == NULL || len == 0) {
		return true;
	}

	// get a buffer
	buffer = (uint8 *)os_zalloc(len + upgrade->extra_count);

	// copy in any remaining bytes from last chunk
	os_memcpy(buffer, upgrade->extra_bytes, upgrade->extra_count);
	// copy in new data
	os_memcpy(buffer + upgrade->extra_count, data, len);

	// calculate length, must be multiple of 4
	// save any remaining bytes for next go
	len += upgrade->extra_count;
	upgrade->extra_count = len % 4;
	len -= upgrade->extra_count;
	os_memcpy(upgrade->extra_bytes, buffer + len, upgrade->extra_count);

	// check data will fit
	//if (upgrade->start_addr + len < (upgrade->start_sector + upgrade->max_sector_count) * SECTOR_SIZE) {

		if (len > SECTOR_SIZE) {
			// here we should erase current (if not already done), next
			// and possibly later sectors too, but doesn't look like we
			// actually ever get more than 4k at a time though
		} else {
			// check if sector the write finishes in has been erased yet,
			// this is fine as long as data len < sector size
			if (upgrade->last_sector_erased != (upgrade->start_addr + len) / SECTOR_SIZE) {
				upgrade->last_sector_erased = (upgrade->start_addr + len) / SECTOR_SIZE;
				spi_flash_erase_sector(upgrade->last_sector_erased);
			}
		}

		// write current chunk
		if (spi_flash_write(upgrade->start_addr, (uint32 *)buffer, len) == SPI_FLASH_RESULT_OK) {
			ret = true;
			upgrade->start_addr += len;
		}
	//}

	os_free(buffer);
	return ret;
}

// initialise the internal update state structure
static bool ICACHE_FLASH_ATTR rboot_ota_init(rboot_ota *ota) {

	upgrade = (upgrade_param*)os_zalloc(sizeof(upgrade_param));
	if (!upgrade) {
		ERROR("No ram!");
		return false;
	}

	// store user update options
	upgrade->ota = ota;

	// details of rom slot to update
	ota->rom_addr = (1 - rboot_get_current_rom()) * 0x80000 + 0x2000;
	upgrade->start_addr = ota->rom_addr;
	upgrade->start_sector = upgrade->start_addr / SECTOR_SIZE;

	// create connection
	upgrade->conn = (struct espconn *)os_zalloc(sizeof(struct espconn));
	if (!upgrade->conn) {
		ERROR("No ram!");
		os_free(upgrade);
		return false;
	}
	upgrade->conn->proto.tcp = (esp_tcp *)os_zalloc(sizeof(esp_tcp));
	if (!upgrade->conn->proto.tcp) {
		os_free(upgrade->conn);
		upgrade->conn = 0;
		ERROR("No ram!");
		os_free(upgrade);
		return false;
	}

	// set update flag
	system_upgrade_flag_set(UPGRADE_FLAG_START);

	return true;
}

// clean up at the end of the update
// will call the user call back to indicate completion
static void ICACHE_FLASH_ATTR rboot_ota_deinit() {

	bool result;
	rboot_ota *ota;
	struct espconn *conn;

	DEBUG("possible timeout or other error");
	os_timer_disarm(&ota_timer);

	// save only remaining bits of interest from upgrade struct
	// then we can clean it up early, so disconnect callback
	// can distinguish between us calling it after update finished
	// or being called earlier in the update process
	ota = upgrade->ota;
	conn = upgrade->conn;

	// clean up
	os_free(upgrade);
	upgrade = 0;

	// if connected, disconnect and clean up connection
	if (conn) espconn_disconnect(conn);

	// check for completion
	if (system_upgrade_flag_check() == UPGRADE_FLAG_FINISH) {
		result = true;
	} else {
		system_upgrade_flag_set(UPGRADE_FLAG_IDLE);
		result = false;
	}

	// call user call back
	if (ota->callback) {
		ota->callback(ota, result);
	}

}

// called when connection receives data (hopefully the rom)
static void ICACHE_FLASH_ATTR upgrade_recvcb(void *arg, char *pusrdata, unsigned short length) {

	char *ptrData, *ptrLen, *ptr;

	// first reply?
	if (upgrade->content_len == 0) {
		// valid http response?
		if ((ptrLen = (char*)strcasestr(pusrdata, "Content-Length: "))
			&& (ptrData = (char*)os_strstr(ptrLen, "\r\n\r\n"))
			&& (os_strncmp(pusrdata + 9, "200", 3) == 0)) {

			// end of header/start of data
			ptrData += 4;
			// length of data after header in this chunk
			length -= (ptrData - pusrdata);
			// running total of download length
			upgrade->total_len += length;
			// process current chunk
			write_flash((uint8*)ptrData, length);
			// work out total download size
			ptrLen += 16;
			ptr = (char *)os_strstr(ptrLen, "\r\n");
			*ptr = '\0'; // destructive
			upgrade->content_len = atoi(ptrLen);
		} else {
			ERROR("fail, not a valid http header/non-200 response/etc. %s", pusrdata);
			rboot_ota_deinit();
			return;
		}
	} else {
		// not the first chunk, process it
		upgrade->total_len += length;
		write_flash((uint8*)pusrdata, length);
	}

	// check if we are finished
	if (upgrade->total_len == upgrade->content_len) {
		system_upgrade_flag_set(UPGRADE_FLAG_FINISH);
		// clean up and call user callback
		rboot_ota_deinit();
	} else if (upgrade->conn->state != ESPCONN_READ) {
		ERROR("fail, but how do we get here? premature end of stream?");
		rboot_ota_deinit();
	}
}

// disconnect callback, clean up the connection
// we also call this ourselves
static void ICACHE_FLASH_ATTR upgrade_disconcb(void *arg) {
	// use passed ptr, as upgrade struct may have gone by now
	struct espconn *conn = (struct espconn*)arg;

	os_timer_disarm(&ota_timer);
	if (conn) {
		if (conn->proto.tcp) os_free(conn->proto.tcp);
		os_free(conn);
	}

	// is upgrade struct still around?
	// if so disconnect was from remote end, or we called
	// ourselves to cleanup a failed connection attempt
	// must ensure disconnect was for this upgrade attempt,
	// not a previous one! this call back is async so another
	// upgrade struct may have been created already
	if (upgrade && upgrade->conn == conn) {
		// mark connection as gone
		upgrade->conn = 0;
		// end the update process
		ERROR("discon callback");
		rboot_ota_deinit();
	}
}

// successfully connected to update server, send the request
static void ICACHE_FLASH_ATTR upgrade_connect_cb(void *arg) {

	// disable the timeout
	os_timer_disarm(&ota_timer);

	// register connection callbacks
	espconn_regist_disconcb(upgrade->conn, upgrade_disconcb);
	espconn_regist_recvcb(upgrade->conn, upgrade_recvcb);

	// send the http request, with timeout for reply and rest of update to complete
	os_timer_setfn(&ota_timer, (os_timer_func_t *)rboot_ota_deinit, 0);
	os_timer_arm(&ota_timer, OTA_DOWNLOAD_TIMEOUT, 0);
	espconn_sent(upgrade->conn, upgrade->ota->request, os_strlen((char*)upgrade->ota->request));
}

// connection attempt timed out
static void ICACHE_FLASH_ATTR connect_timeout_cb() {
	ERROR("Connect timeout.");
	// not connected so don't call disconnect on the connection
	// but call our own disconnect callback to do the cleanup
	upgrade_disconcb(upgrade->conn);
}

// call back for lost connection
static void ICACHE_FLASH_ATTR upgrade_recon_cb(void *arg, sint8 errType) {
	ERROR("Connection error.");
	// not connected so don't call disconnect on the connection
	// but call our own disconnect callback to do the cleanup
	upgrade_disconcb(upgrade->conn);
}

// start the ota process, with user supplied options
bool ICACHE_FLASH_ATTR rboot_ota_start(rboot_ota *ota) {

	// check not already updating
	if (system_upgrade_flag_check() == UPGRADE_FLAG_START) {
		return false;
	}

	// check parameters
	if (!ota || !ota->request) {
		ERROR("Invalid parameters.");
		return false;
	}

	// set up update structure
	if (!rboot_ota_init(ota)) {
		return false;
	}

	// set up connection
	upgrade->conn->type = ESPCONN_TCP;
	upgrade->conn->state = ESPCONN_NONE;
	upgrade->conn->proto.tcp->local_port = espconn_port();
	upgrade->conn->proto.tcp->remote_port = ota->port;
//	*(uint32*)upgrade->conn->proto.tcp->remote_ip = *(uint32*)ota->ip;
	upgrade->conn->proto.tcp->remote_ip[0] = ota->ip[0];
	upgrade->conn->proto.tcp->remote_ip[1] = ota->ip[1];
	upgrade->conn->proto.tcp->remote_ip[2] = ota->ip[2];
	upgrade->conn->proto.tcp->remote_ip[3] = ota->ip[3];
	// set connection call backs
	espconn_regist_connectcb(upgrade->conn, upgrade_connect_cb);
	espconn_regist_reconcb(upgrade->conn, upgrade_recon_cb);

	// try to connect
	espconn_connect(upgrade->conn);

	// set connection timeout timer
	os_timer_disarm(&ota_timer);
	os_timer_setfn(&ota_timer, (os_timer_func_t *)connect_timeout_cb, 0);
	os_timer_arm(&ota_timer, OTA_CONNECT_TIMEOUT, 0);

	return true;
}


text:
<?php
declare(strict_types=1);

namespace Citilink\ExpertSenderApi\Tests\Response;

use Citilink\ExpertSenderApi\Model\DataTablesGetTablesSummaryResponse\TableSummary;
use Citilink\ExpertSenderApi\Response;
use Citilink\ExpertSenderApi\Response\DataTablesGetTablesSummaryResponse;
use function iter\toArray;
use PHPUnit\Framework\Assert;

/**
 * DataTablesGetTablesSummaryResponseTest
 *
 * @author Nikita Sapogov <sapogov.n@citilink.ru>
 */
class DataTablesGetTablesSummaryResponseTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test
     */
    public function testCommonUsage()
    {
        $xml = '<ApiResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" '
            . 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
           <TableList>
              <Tables>

                    <Id>1</Id>
                    <Name>Table1</Name>
                    <ColumnsCount>8</ColumnsCount>
                    <RelationshipsCount>0</RelationshipsCount>
                    <RelationshipsDestinationCount>1</RelationshipsDestinationCount>
                    <Rows>5</Rows>
                    <Size>0.05</Size>

                    <Id>2</Id>
                    <Name>Table2</Name>
                    <ColumnsCount>15</ColumnsCount>
                    <RelationshipsCount>3</RelationshipsCount>
                    <RelationshipsDestinationCount>4</RelationshipsDestinationCount>
                    <Rows>5</Rows>
                    <Size>1.09</Size>

              </Tables>
           </TableList>
        </ApiResponse>';
        $response = new DataTablesGetTablesSummaryResponse(
            new Response(
                new \GuzzleHttp\Psr7\Response(
                    200,
                    ['Content-Length' => strlen($xml), 'Content-Type' => 'text/xml'],
                    $xml
                )
            )
        );

        Assert::assertTrue($response->isOk());
        Assert::assertFalse($response->isEmpty());
        Assert::assertEquals(200, $response->getHttpStatusCode());
        /** @var TableSummary[] $tables */
        $tables = toArray($response->getTables());
        Assert::assertCount(2, $tables);
        Assert::assertEquals(1, $tables[0]->getId());
        Assert::assertEquals('Table1', $tables[0]->getName());
        Assert::assertEquals(8, $tables[0]->getColumnsCount());
        Assert::assertEquals(0, $tables[0]->getRelationshipsCount());
        Assert::assertEquals(1, $tables[0]->getRelationshipsDestinationCount());
        Assert::assertEquals(5, $tables[0]->getRowsCount());
        Assert::assertEquals(0.05, $tables[0]->getSize());

        Assert::assertEquals(2, $tables[1]->getId());
        Assert::assertEquals('Table2', $tables[1]->getName());
        Assert::assertEquals(15, $tables[1]->getColumnsCount());
        Assert::assertEquals(3, $tables[1]->getRelationshipsCount());
        Assert::assertEquals(4, $tables[1]->getRelationshipsDestinationCount());
        Assert::assertEquals(5, $tables[1]->getRowsCount());
        Assert::assertEquals(1.09, $tables[1]->getSize());
    }
}


text:
{-# LANGUAGE RecordWildCards            #-}
{-# LANGUAGE TypeFamilies               #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE OverloadedStrings          #-}

module Aws.ElasticTranscoder.Commands.TestRole
    ( TestRole(..)
    , TestRoleResponse(..)
    ) where

import           Aws.Core
import           Aws.ElasticTranscoder.Core
import           Control.Applicative
import           Data.Aeson
import           Data.Text                      as T

data TestRole
    = TestRole
        { trInputBucket  :: S3Object
        , trOutputBucket :: S3Object
        , trRole         :: IAMRole
        , trTopics       :: [SNSTopic]
        }
    deriving (Show,Eq)

data TestRoleResponse
    = TestRoleResponse
        { trrMessages :: [T.Text]
        , trrSuccess  :: Bool
        }
    deriving (Show,Eq)

instance SignQuery TestRole where

    type ServiceConfiguration TestRole = EtsConfiguration

    signQuery TestRole{..} = etsSignQuery
        EtsQuery
            { etsqMethod  = Get
            , etsqRequest = "roleTests"
            , etsqQuery   = []
            , etsqBody    = Just $ toJSON $
                                RoleTest
                                    trInputBucket
                                    trOutputBucket
                                    trRole
                                    trTopics
            }

instance ResponseConsumer TestRole TestRoleResponse where

    type ResponseMetadata TestRoleResponse = EtsMetadata

    responseConsumer _ mref = etsResponseConsumer mref $ \rsp ->
                                                    cnv <$> jsonConsumer rsp
          where
            cnv (MessagesSuccess a b) = TestRoleResponse a b

instance Transaction TestRole TestRoleResponse

instance AsMemoryResponse TestRoleResponse where

    type MemoryResponse TestRoleResponse = TestRoleResponse

    loadToMemory = return


text: > *It's a good practice to create guidelines for contributors*


text:
package net.ssehub.easy.reasoning.drools2.functions;

/**
 * Wrapper (helper) class that holds Drools def functions.
 * Functions: size()
 * @author Sizonenko
 *
 */
public class DefFunctions {

    /**
     * Implementation for the operation size().
     * @param value Object.
     * @return if value is null returns false.
     */
    public static boolean isDefined(Object value) {
        boolean isDefined = false;
        if ((Object) value != null) {
            isDefined = true;
        }
        return isDefined;
    }

}


text:
[![Build Status](https://travis-ci.org/mak-it/periodic_records.svg?branch=master)](https://travis-ci.org/mak-it/periodic_records)

Support functions for ActiveRecord models with periodic entries.

* Supports periods where the smallest unit is a whole day
* Adjusts and splits overlapping records
* Preloads currently active records to avoid N+1 queries
* Easy querying within history - join returns 0..1 records (no grouping needed)
  `LEFT JOIN ... ON ... AND <date> BETWEEN start_at AND end_at`

For example you have employees table and assignments table that stores all the
employment history.

Employees:

| id | name |
|:---|:-----|
| 1  | John |

Employee assignments:

| id | employee_id | start_at   | end_at     | job_title |
|:---|:------------|:-----------|:-----------|:----------|
| 1  | 1           | 2014-01-01 | 9999-01-01 | Developer |

Now John is promoted to "Senior Developer" and you create a new employee
assignment record and this gem will take care of adjusting and splitting
overlapping records. In this case it will adjust the `end_at` field for the
previous assignment.

| id | employee_id | start_at   | end_at     | job_title        |
|:---|:------------|:-----------|:-----------|:-----------------|
| 1  | 1           | 2014-01-01 | 2018-05-04 | Developer        |
| 2  | 1           | 2018-05-05 | 9999-01-01 | Senior Developer |

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'periodic_records'
```

And then execute:

```bash
$ bundle
```

Or install it yourself as:

```bash
$ gem install periodic_records
```

## Preparation

Ensure `start_at` and `end_at` date columns on the model that will have
periodic versions.
Include `PeriodicRecords::Model` and define `siblings` method:

```ruby
class EmployeeAssignment < ActiveRecord::Base
  include PeriodicRecords::Model

  belongs_to :employee

  def siblings
    self.class.where(employee_id: employee_id).where.not(id: id)
  end
end
```

Include `PeriodicRecords::Associations` in the model that has periodic
associations, and call `has_periodic`:

```ruby
class Employee < ActiveRecord::Base
  include PeriodicRecords::Associations

  has_many :employee_assignments, inverse_of: :employee
  has_periodic :employee_assignments, as: :assignments
end
```

## Usage

Look up the currently active record with `model.current_association`:

```ruby
employee.current_assignment
```

Look up records for specific date or period
with `within_date` and `within_interval`:

```ruby
employee.employee_assignments.within_date(Date.tomorrow)
```

```ruby
employee.employee_assignments.within_interval(Date.current.beginning_of_month...Date.current.end_of_month)
```

Look up records starting with specific date with `from_date`

```ruby
employee.employee_assignments.from_date(Date.tomorrow)
```

Preload currently active records, to avoid N+1 queries on `current_assignment`.

```ruby
employees = Employee.all
Employee.preload_current_assignments(employees)
employees.each do |employee|
  puts employee.current_assignment.to_s
end
```

## Database Constraints

To avoid inconsistent data in race conditions, you can add database constraint
that checks overlapping periods.

Postgres:

```ruby
class AddEmployeeAssignmentsOverlappingDatesConstraint < ActiveRecord::Migration
  def up
    execute "CREATE EXTENSION IF NOT EXISTS btree_gist"
    execute <<-SQL
      ALTER TABLE employee_assignments
      ADD CONSTRAINT employee_assignments_overlapping_dates
      EXCLUDE USING GIST(
        employee_id WITH =,
        DATERANGE(start_at, end_at, '[]') WITH &&
      )
    SQL
  end

  def down
    execute <<-SQL.squish
      ALTER TABLE employee_assignments
      DROP CONSTRAINT employee_assignments_overlapping_dates
    SQL
  end
end
```

## Time sensitive records

If you need your records to be split with time component, then set `start_at` and `end_at` columns to `datetime` type.

Use `TSRANGE` instead of `DATERANGE` when creating database constraint.

## Gapless records

If you want to avoid gaps between records, you can include also `PeriodicRecords::Gapless`.

```ruby
class EmployeeAssignment < ActiveRecord::Base
  include PeriodicRecords::Model
  include PeriodicRecords::Gapless

  belongs_to :employee

  def siblings
    self.class.where(employee_id: employee_id).where.not(id: id)
  end
end
```

Example:

| id | employee_id | start_at   | end_at     | job_title        |
|:---|:------------|:-----------|:-----------|:-----------------|
| 1  | 1           | 0001-01-01 | 2018-01-15 | Junior Developer |
| 2  | 1           | 2018-01-16 | 2018-02-15 | Developer        |
| 3  | 1           | 2018-02-16 | 9999-01-01 | Senior Developer |

If you update #2 from `2018-01-16 - 2018-02-15` to `2018-01-20 - 2018-02-10`, it
will also adjust end at for #1 and start at for #3 to avoid gaps between records.

After (with `Gapless`):

| id | employee_id | start_at   | end_at     | job_title        |
|:---|:------------|:-----------|:-----------|:-----------------|
| 1  | 1           | 0001-01-01 | 2018-01-19 | Junior Developer |
| 2  | 1           | 2018-01-20 | 2018-02-10 | Developer        |
| 3  | 1           | 2018-02-11 | 9999-01-01 | Senior Developer |

After (without `Gapless`):

| id | employee_id | start_at   | end_at     | job_title        |
|:---|:------------|:-----------|:-----------|:-----------------|
| 1  | 1           | 0001-01-01 | 2018-01-15 | Junior Developer |
| 2  | 1           | 2018-01-20 | 2018-02-10 | Developer        |
| 3  | 1           | 2018-02-16 | 9999-01-01 | Senior Developer |

If you delete #2 then it will adjust end at for #1.

You will not be able to delete entry that is at the beginning (#1) or at the end (#3).

You will not be able to adjust start at for the beginning entry (#1).

You will not be able to adjust end at for the ending entry (#3).

For more examples see [gapless_spec.rb](spec/periodic_records/gapless_spec.rb).

## Development

After checking out the repo, run `bin/setup` to install dependencies.
Then, run `bin/console` for an interactive prompt that will allow you to
experiment.

To install this gem onto your local machine, run `bundle exec rake install`.
To release a new version, update the version number in `version.rb`,
and then run `bundle exec rake release` to create a git tag for the version,
push git commits and tags, and push the `.gem` file
to [rubygems.org](https://rubygems.org).

## Contributing

1. Fork it ( https://github.com/mak-it/periodic_records/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
package Google::Ads::GoogleAds::V10::Resources::OfflineUserDataJob;

use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);

use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;

sub new {
  my ($class, $args) = @_;
  my $self = {
    customerMatchUserListMetadata => $args->{customerMatchUserListMetadata},
    externalId                    => $args->{externalId},
    failureReason                 => $args->{failureReason},
    id                            => $args->{id},
    operationMetadata             => $args->{operationMetadata},
    resourceName                  => $args->{resourceName},
    status                        => $args->{status},
    storeSalesMetadata            => $args->{storeSalesMetadata},
    type                          => $args->{type}};

  # Delete the unassigned fields in this object for a more concise JSON payload
  remove_unassigned_fields($self, $args);

  bless $self, $class;
  return $self;
}

1;


text:
class Shoes
  module Swt
    class Color
      include DisposedProtection

      def self.create(color)
        color ? new(color) : NullColor.new
      end

      # @param [Shoes::Color] color the DSL representation of this color
      def initialize(color)
        @dsl = color
        @real = ::Swt::Graphics::Color.new(Shoes.display, @dsl.red, @dsl.green, @dsl.blue)
      end

      attr_reader :dsl

      # @return [Integer] the alpha value, from 0 (transparent) to 255 (opaque)
      def alpha
        @dsl.alpha
      end

      # @param [Swt::Graphics::GC] gc the graphics context on which to apply fill
      # @note left, top, width, height, and angle are not used in this method, and only
      #   exist to satisfy the Pattern interface
      def apply_as_fill(gc, left = nil, top = nil, width = nil, height = nil, angle = nil)
        gc.set_background real
        gc.set_alpha alpha
      end

      # @param [Swt::Graphics::GC] gc the graphics context on which to apply stroke
      def apply_as_stroke(gc, left = nil, top = nil, width = nil, height = nil, angle = nil)
        gc.set_foreground real
        gc.set_alpha alpha
      end
    end

    class NullColor
      attr_reader :alpha, :dsl, :real
      def apply_as_fill(gc); end
      def apply_as_stroke(gc); end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/KWBeBetweenMatcher.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/KWBeBetweenMatcher</TokenIdentifier>
			<Abstract></Abstract>
			<DeclaredIn>KWBeBetweenMatcher.h</DeclaredIn>

			<NodeRef refid="6"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/KWBeBetweenMatcher/beBetween:and:</TokenIdentifier>
			<Abstract></Abstract>
			<DeclaredIn>KWBeBetweenMatcher.h</DeclaredIn>

			<Declaration>- (void)beBetween:(id)aLowerEndpoint and:(id)anUpperEndpoint</Declaration>

			<Anchor>//api/name/beBetween:and:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/KWBeBetweenMatcher/beInTheIntervalFrom:to:</TokenIdentifier>
			<Abstract></Abstract>
			<DeclaredIn>KWBeBetweenMatcher.h</DeclaredIn>

			<Declaration>- (void)beInTheIntervalFrom:(id)aLowerEndpoint to:(id)anUpperEndpoint</Declaration>

			<Anchor>//api/name/beInTheIntervalFrom:to:</Anchor>
		</Token>

	</File>
</Tokens>


text:
package org.apache.commons.ssl.asn1;

import java.io.IOException;

/** DER VisibleString object. */
public class DERVisibleString
    extends ASN1Object
    implements DERString {
    String string;

    /**
     * return a Visible String from the passed in object.
     *
     * @throws IllegalArgumentException if the object cannot be converted.
     */
    public static DERVisibleString getInstance(
        Object obj) {
        if (obj == null || obj instanceof DERVisibleString) {
            return (DERVisibleString) obj;
        }

        if (obj instanceof ASN1OctetString) {
            return new DERVisibleString(((ASN1OctetString) obj).getOctets());
        }

        if (obj instanceof ASN1TaggedObject) {
            return getInstance(((ASN1TaggedObject) obj).getObject());
        }

        throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
    }

    /**
     * return a Visible String from a tagged object.
     *
     * @param obj      the tagged object holding the object we want
     * @param explicit true if the object is meant to be explicitly
     *                 tagged false otherwise.
     * @throws IllegalArgumentException if the tagged object cannot
     *                                  be converted.
     */
    public static DERVisibleString getInstance(
        ASN1TaggedObject obj,
        boolean explicit) {
        return getInstance(obj.getObject());
    }

    /** basic constructor - byte encoded string. */
    public DERVisibleString(
        byte[] string) {
        char[] cs = new char[string.length];

        for (int i = 0; i != cs.length; i++) {
            cs[i] = (char) (string[i] & 0xff);
        }

        this.string = new String(cs);
    }

    /** basic constructor */
    public DERVisibleString(
        String string) {
        this.string = string;
    }

    public String getString() {
        return string;
    }

    public String toString() {
        return string;
    }

    public byte[] getOctets() {
        char[] cs = string.toCharArray();
        byte[] bs = new byte[cs.length];

        for (int i = 0; i != cs.length; i++) {
            bs[i] = (byte) cs[i];
        }

        return bs;
    }

    void encode(
        DEROutputStream out)
        throws IOException {
        out.writeEncoded(VISIBLE_STRING, this.getOctets());
    }

    boolean asn1Equals(
        DERObject o) {
        if (!(o instanceof DERVisibleString)) {
            return false;
        }

        return this.getString().equals(((DERVisibleString) o).getString());
    }

    public int hashCode() {
        return this.getString().hashCode();
    }
}


text:
var x = require("my-module");
TAJS_assertEquals(10, x);


text:
================================================================================
NetIpRouteConfigSpecIpRouteSpec
================================================================================

.. describe:: Property of

    :py:class:`~pyvisdk.do.net_ip_route_config_spec.NetIpRouteConfigSpec`

.. describe:: See also

    :py:class:`~pyvisdk.do.net_ip_route_config_spec_gateway_spec.NetIpRouteConfigSpecGatewaySpec`

.. describe:: Since

    vSphere API 4.1

.. describe:: Extends

    :py:class:`~pyvisdk.mo.dynamic_data.DynamicData`

.. class:: pyvisdk.do.net_ip_route_config_spec_ip_route_spec.NetIpRouteConfigSpecIpRouteSpec

    .. py:attribute:: gateway

        Where to send the packets for this route.

    .. py:attribute:: network

        IP Address of the destination IP network. IPv6 addresses are 128-bit addresses represented as eight fields of up to four hexadecimal digits. A colon separates each field (:). For example, 2001:DB8:101::230:6eff:fe04:d9ff. The address can also consist of symbol '::' to represent multiple 16-bit groups of contiguous 0's only once in an address as described in RFC 2373. To Specify a default network use the value: 0 with prefixLenth 0.

    .. py:attribute:: operation

        Requires one of the values from HostConfigChangeOperation.

    .. py:attribute:: prefixLength

        The prefix length. For IPv4 the value range is 0-31. For IPv6 prefixLength is a decimal value range 0-127. The property represents the number of contiguous, higher-order bits of the address that make up the network portion of the IP address.


text:
#ifndef RTTR_DESTRUCTOR_WRAPPER_H_
#define RTTR_DESTRUCTOR_WRAPPER_H_

#include "rttr/detail/base/core_prerequisites.h"
#include "rttr/detail/destructor/destructor_wrapper_base.h"
#include "rttr/variant.h"

namespace rttr
{
namespace detail
{

template<typename ClassType>
class destructor_wrapper : public destructor_wrapper_base
{
    public:
        type get_destructed_type() const RTTR_NOEXCEPT { return type::get<ClassType*>(); }

        bool is_valid() const RTTR_NOEXCEPT { return true; }

        bool invoke(variant& obj) const RTTR_NOEXCEPT
        {
            if (obj.is_type<ClassType*>())
            {
                // although an exception can occur when calling 'delete',
                // nobody should throw an exception in destructor, so we don't catch the exception
                // and just terminate the application
                delete obj.get_value<ClassType*>();
                obj = variant();
                return true;
            }
            else
            {
                return false;
            }
        }
};

} // end namespace detail
} // end namespace rttr

#endif // RTTR_DESTRUCTOR_WRAPPER_H_


text:
/* */
System.register(["./aurelia", "aurelia-dependency-injection", "aurelia-binding", "aurelia-metadata", "aurelia-templating", "aurelia-loader", "aurelia-task-queue", "aurelia-logging"], function (_export) {
  "use strict";

  var TheLogManager, LogManager;
  return {
    setters: [function (_aurelia) {
      _export("Aurelia", _aurelia.Aurelia);
    }, function (_aureliaDependencyInjection) {
      for (var _key in _aureliaDependencyInjection) {
        _export(_key, _aureliaDependencyInjection[_key]);
      }
    }, function (_aureliaBinding) {
      for (var _key2 in _aureliaBinding) {
        _export(_key2, _aureliaBinding[_key2]);
      }
    }, function (_aureliaMetadata) {
      for (var _key3 in _aureliaMetadata) {
        _export(_key3, _aureliaMetadata[_key3]);
      }
    }, function (_aureliaTemplating) {
      for (var _key4 in _aureliaTemplating) {
        _export(_key4, _aureliaTemplating[_key4]);
      }
    }, function (_aureliaLoader) {
      for (var _key5 in _aureliaLoader) {
        _export(_key5, _aureliaLoader[_key5]);
      }
    }, function (_aureliaTaskQueue) {
      for (var _key6 in _aureliaTaskQueue) {
        _export(_key6, _aureliaTaskQueue[_key6]);
      }
    }, function (_aureliaLogging) {
      TheLogManager = _aureliaLogging;
    }],
    execute: function () {
      LogManager = _export("LogManager", TheLogManager);
    }
  };
});


text:
import React, { Component } from "react";
import { makeCollection, localize } from "./utils";
import { mount } from "enzyme";
import { Provider } from "react-redux";
import { configureStore } from "store";
import * as actions from "./actions";

describe('makeCollection', () => {
    it('should return a collection of localized messages plus a hash parameter', () => {
        const testMessages = {
            'it': {
                testId: 'Test ID (it)'
            },
            'en': {
                testId: 'Test ID (en)'
            }
        }
        let collection = makeCollection(testMessages);
        expect(collection).toEqual({
            messages: testMessages,
            hash: expect.any(String)
        })
    })
})

describe('localize', () => {
    let collection;
    let App;
    let store;
    let renderCount = 0;

    // Helper to quickly get a test component with the localize decorator applied
    function getLocalizedClass(params) {
        @localize(params)
        class Test extends Component {
            renderCount = 0;
            render() {
                renderCount++;
                let {testMessage} = this.props;
                return (

{testMessage && testMessage.format(this.props)}

                )
            }
        }
        return Test;
    }

    // Create test collection
    beforeAll(() => {
        collection = makeCollection({
            'it': {
                'test.id': 'Traduzione',
                'test.id2': 'Traduzione 2',
                'complexMessage': 'Traduzione {param}'
            },
            'en': {
                'test.id': 'Translation',
                'test.id2': 'Translation 2',
                'complexMessage': 'Translation {param}'
            }
        })
    })

    // Reset render count and recreate store and App component before each test
    beforeEach(() => {
        renderCount = 0;
        store = configureStore();
        App = props => (
            <Provider store={store} >
                {props.children}
            </Provider>
        )
    })

    it('should render the base component class', () => {
        let LocalizedTest = getLocalizedClass({collections:collection})
        let wrapper = mount(
            <App>
                <LocalizedTest />
            </App>
        )
        expect(wrapper.find('.test-class').length).toBe(1);
    })

    it('should add the message collection to the store on component mount', () => {
        let LocalizedTest = getLocalizedClass({collections:collection})
        store.dispatch(actions.changeLocale('en'))
        let state = store.getState();
        let messages = state.i18n.messages;
        let loaded = state.i18n.loaded;
        expect(loaded[collection.hash]).not.toBe(true);
        expect(messages).toEqual({})
        mount(
            <App>
                <LocalizedTest />
            </App>
        )
        state = store.getState();
        messages = state.i18n.messages;
        loaded = state.i18n.loaded;
        expect(loaded[collection.hash]).toBe(true);
        expect(messages).toEqual(collection.messages)
    })

    it('shouldn\'t change state on multiple mounts with the same collection', () => {
        let LocalizedTest = getLocalizedClass({collections:collection})
        store.dispatch(actions.changeLocale('en'))
        let initialState = store.getState();
        mount(
            <App>
                <LocalizedTest />
            </App>
        )
        let firstMountState = store.getState();
        let LocalizedTest2 = getLocalizedClass({collections:collection})
        mount(
            <App>
                <LocalizedTest2 />
            </App>
        )
        let secondMountState = store.getState();

        expect(initialState).not.toBe(firstMountState);
        expect(firstMountState).toBe(secondMountState);
    })

    it('should pass the correct props', () => {
        let LocalizedTest = getLocalizedClass({collections:collection, messageIds:{testMessage:'test.id'}})
        store.dispatch(actions.changeLocale('en'))
        let wrapper = mount(
            <App>
                <LocalizedTest />
            </App>
        )
        let connectedComponentWrapper = wrapper.find('Test');
        expect(connectedComponentWrapper.props()).toEqual({testMessage:{format:expect.any(Function)}})
    })

    it('should correctly update props on locale change', () => {
        let LocalizedTest = getLocalizedClass({collections:collection, messageIds:{testMessage:'test.id'}})
        store.dispatch(actions.changeLocale('en'))
        let wrapper = mount(
            <App>
                <LocalizedTest />
            </App>
        )
        let connectedComponentWrapper = wrapper.find('Test');
        let props = connectedComponentWrapper.props();
        expect(props.testMessage.format()).toBe('Translation')
        store.dispatch(actions.changeLocale('it'))
        props = connectedComponentWrapper.props();
        expect(props.testMessage.format()).toBe('Traduzione')
    })

    it('should correctly format messages', () => {
        let LocalizedTest = getLocalizedClass({collections:collection, messageIds:{testMessage:'complexMessage'}})

        /**
         * Wrapper that will pass test props to the LocalizedTest component.
         * The onclick handler will increment the state and pass the updated state
         * as a prop to the LocalizedTest component.
         * (I couldn't find an easier way to change props on a mounted component
         * that is not the root component)
         */
        class LocalizedTestWrapper extends Component {
            state = {
                test: 1
            }
            handleClick = () => {
                this.setState(s => ({test:s.test +1}))
            }
            render() {
                return (

                        <LocalizedTest param={this.state.test} />

                )
            }
        }

        store.dispatch(actions.changeLocale('en'))

        let wrapper = mount(
            <App>
                <LocalizedTestWrapper />
            </App>
        )

        // get the formatted message, it should be "Translation "+ param
        let formattedMessage = wrapper.text();
        expect(formattedMessage).toBe('Translation 1')

        // changing locale should still correctly format the message in the
        // new language
        store.dispatch(actions.changeLocale('it'))
        formattedMessage = wrapper.text();
        expect(formattedMessage).toBe('Traduzione 1')

        // simulate a click to change the param prop and check that the
        // text updates
        wrapper.find('LocalizedTestWrapper').simulate('click')
        formattedMessage = wrapper.text();
        expect(formattedMessage).toBe('Traduzione 2')
    })

    it('shouldn\'t re-render on unrelated dispatches', () => {
        let LocalizedTest = getLocalizedClass({collections:collection, messageIds:{testMessage:'complexMessage'}})
        store.dispatch(actions.changeLocale('en'))
        mount(
            <App>
                <LocalizedTest param="test"/>
            </App>
        )
        let initialRenderCount = renderCount;
        store.dispatch(actions.changeLocale('it'))
        let expectedRenderCount = initialRenderCount + 1
        expect(renderCount).toBe(expectedRenderCount)

        // dispatch an addMessages action that adds messages unrelated to
        // the test component
        let unrelatedCollection = makeCollection({
            'it': {
                'unrelated.id': 'Traduzione',
            },
            'en': {
                'unrelated.id': 'Translation',
            }
        })
        store.dispatch(actions.addMessages(unrelatedCollection))

        expect(renderCount).toBe(expectedRenderCount)
    })
})


text:
package beaform.entities;

/**
 * This interface represents an ingredient
 *
 * @author steven
 *
 */
public interface Ingredient {

	String getAmount();

}


text:
default['maas']['create_superuser'] = true

# Superuser name
default['maas']['superuser_name'] = 'admin'
# Superuser password
default['maas']['superuser_password'] = 'admin'
# Superuser email
default['maas']['superuser_email'] = 'fakeemail@fake.com'

# secret for your cluster controller
default['maas']['cluster_secret'] = 'f0a6035342ed1651f822d26fe1ed0109'

# your region controller, just ip or hostname
default['maas']['cluster_region_controller'] = '127.0.0.1'


text:
require File.expand_path('../../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/classes', __FILE__)

describe "Enumerator::Lazy#reject" do
  before :each do
    @yieldsmixed = EnumeratorLazySpecs::YieldsMixed.new.to_enum.lazy
    @eventsmixed = EnumeratorLazySpecs::EventsMixed.new.to_enum.lazy
    ScratchPad.record []
  end

  after :each do
    ScratchPad.clear
  end

  it "returns a new instance of Enumerator::Lazy" do
    ret = @yieldsmixed.reject {}
    ret.should be_an_instance_of(enumerator_class::Lazy)
    ret.should_not equal(@yieldsmixed)
  end

  it "sets nil to size" do
    enumerator_class::Lazy.new(Object.new, 100) {}.reject {}.size.should == nil
  end

  describe "when the returned lazy enumerator is evaluated by Enumerable#first" do
    it "stops after specified times" do
      (0..Float::INFINITY).lazy.reject(&:even?).first(3).should == [1, 3, 5]

      @eventsmixed.reject { false }.first(1)
      ScratchPad.recorded.should == [:before_yield]
    end
  end

  it "calls the block with a gathered array when yield with multiple arguments" do
    yields = []
    @yieldsmixed.reject { |v| yields << v }.force
    yields.should == EnumeratorLazySpecs::YieldsMixed.gathered_yields
  end

  it "raises an ArgumentError when not given a block" do
    lambda { @yieldsmixed.reject }.should raise_error(ArgumentError)
  end

  describe "on a nested Lazy" do
    it "sets nil to size" do
      enumerator_class::Lazy.new(Object.new, 100) {}.take(20).reject {}.size.should == nil
    end

    describe "when the returned lazy enumerator is evaluated by Enumerable#first" do
      it "stops after specified times" do
        (0..Float::INFINITY).lazy.reject { |n| n < 4 }.reject(&:even?).first(3).should == [5, 7, 9]

        @eventsmixed.reject { false }.reject { false }.first(1)
        ScratchPad.recorded.should == [:before_yield]
      end
    end
  end
end


text:
package org.terasology.rendering.shader;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.terasology.rendering.dag.nodes.LateBlurNode;
import org.terasology.rendering.dag.nodes.ToneMappingNode;
import org.terasology.rendering.opengl.fbms.DisplayResolutionDependentFBOs;
import org.terasology.utilities.Assets;
import org.terasology.assets.ResourceUrn;
import org.terasology.config.Config;
import org.terasology.input.cameraTarget.CameraTargetSystem;
import org.terasology.registry.CoreRegistry;
import org.terasology.rendering.assets.material.Material;
import org.terasology.rendering.assets.texture.Texture;
import org.terasology.rendering.assets.texture.TextureUtil;
import org.terasology.rendering.cameras.Camera;
import org.terasology.rendering.nui.properties.Range;
import org.terasology.rendering.opengl.FBO;
import org.terasology.rendering.world.WorldRenderer;
import org.terasology.utilities.random.FastRandom;
import org.terasology.utilities.random.Random;

import static org.lwjgl.opengl.GL11.glBindTexture;
import static org.terasology.rendering.opengl.fbms.DisplayResolutionDependentFBOs.READONLY_GBUFFER;

/**
 * Shader parameters for the Post-processing shader program.
 *
 */
public class ShaderParametersPost extends ShaderParametersBase {
    private Random rand = new FastRandom();

    @Range(min = 0.0f, max = 1.0f)
    private float filmGrainIntensity = 0.05f;

    @Override
    public void applyParameters(Material program) {
        super.applyParameters(program);

        // TODO: obtain these only once in superclass and monitor from there?
        CameraTargetSystem cameraTargetSystem = CoreRegistry.get(CameraTargetSystem.class);
        DisplayResolutionDependentFBOs displayResolutionDependentFBOs = CoreRegistry.get(DisplayResolutionDependentFBOs.class); // TODO: switch from CoreRegistry to Context.

        // TODO: move into node
        int texId = 0;
        GL13.glActiveTexture(GL13.GL_TEXTURE0 + texId);
        displayResolutionDependentFBOs.bindFboColorTexture(ToneMappingNode.TONE_MAPPED_FBO);
        program.setInt("texScene", texId++, true);

        // TODO: monitor property rather than check every frame
        if (CoreRegistry.get(Config.class).getRendering().getBlurIntensity() != 0) {
            GL13.glActiveTexture(GL13.GL_TEXTURE0 + texId);
            displayResolutionDependentFBOs.get(LateBlurNode.SECOND_LATE_BLUR_FBO).bindTexture();
            program.setInt("texBlur", texId++, true);

            if (cameraTargetSystem != null) {
                program.setFloat("focalDistance", cameraTargetSystem.getFocalDistance(), true); //for use in DOF effect
            }
        }

        // TODO: move to node - obtain only once and then subscribe to it
        // TODO: take advantage of Texture.subscribeToDisposal(Runnable) to reobtain the asset only if necessary
        Texture colorGradingLut = Assets.getTexture("engine:colorGradingLut1").get();

        if (colorGradingLut != null) { // TODO: review need for null check
            GL13.glActiveTexture(GL13.GL_TEXTURE0 + texId);
            glBindTexture(GL12.GL_TEXTURE_3D, colorGradingLut.getId());
            program.setInt("texColorGradingLut", texId++, true);
        }

        FBO sceneCombined = displayResolutionDependentFBOs.get(READONLY_GBUFFER);

        if (sceneCombined != null) { // TODO: review need for null check
            GL13.glActiveTexture(GL13.GL_TEXTURE0 + texId);
            sceneCombined.bindDepthTexture();
            program.setInt("texDepth", texId++, true);

            // TODO: review - is this loading a noise texture every frame? And why is it not in the IF(grain) block?
            // TODO:          and must it be monitored like a standard texture?
            ResourceUrn noiseTextureUri = TextureUtil.getTextureUriForWhiteNoise(1024, 0x1234, 0, 512);
            Texture filmGrainNoiseTexture = Assets.getTexture(noiseTextureUri).get();

            // TODO: monitor property rather than check every frame
            if (CoreRegistry.get(Config.class).getRendering().isFilmGrain()) {
                // TODO: move into node
                GL13.glActiveTexture(GL13.GL_TEXTURE0 + texId);
                glBindTexture(GL11.GL_TEXTURE_2D, filmGrainNoiseTexture.getId());

                // TODO: move into material?
                program.setInt("texNoise", texId++, true);
                program.setFloat("grainIntensity", filmGrainIntensity, true);
                program.setFloat("noiseOffset", rand.nextFloat(), true);

                program.setFloat2("noiseSize", filmGrainNoiseTexture.getWidth(), filmGrainNoiseTexture.getHeight(), true);
                program.setFloat2("renderTargetSize", sceneCombined.width(), sceneCombined.height(), true);
            }
        }

        // TODO: monitor property rather than check every frame
        Camera activeCamera = CoreRegistry.get(WorldRenderer.class).getActiveCamera();
        if (activeCamera != null && CoreRegistry.get(Config.class).getRendering().isMotionBlur()) {
            // TODO: move into material?
            program.setMatrix4("invViewProjMatrix", activeCamera.getInverseViewProjectionMatrix(), true);
            program.setMatrix4("prevViewProjMatrix", activeCamera.getPrevViewProjectionMatrix(), true);
        }
    }
}


text:
package net.rubyeye.memcached;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicLong;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class BaseReadWriteThread extends Thread {

	private final Logger log;
	protected final int repeats;
	protected final CyclicBarrier barrier;
	protected final int offset;
	protected final int length;
	protected final AtomicLong miss;
	protected final AtomicLong fail;
	protected final AtomicLong hit;

	public BaseReadWriteThread(int repeats, CyclicBarrier barrier, int offset,
			int length, AtomicLong miss, AtomicLong fail, AtomicLong hit) {
		super();
		this.repeats = repeats;
		this.barrier = barrier;
		this.offset = offset;
		this.length = length;
		this.miss = miss;
		this.fail = fail;
		this.hit = hit;
		this.log = LoggerFactory.getLogger(BaseReadWriteThread.class);
	}

	public abstract boolean set(int i, String s) throws Exception;

	public abstract String get(int n) throws Exception;

	public void run() {

		int writeTimes = (int) (this.repeats * Constants.WRITE_RATE);
		try {
			barrier.await();
			int writeMax = offset + writeTimes;
			for (int i = offset; i <= writeMax; i++) {
				String s = StringGenerator.generate(i, length);
				if (!set(i, s)) {
					log.error("set error");
					System.exit(1);
				}
			}
			int countMax = (int) ((1 - Constants.WRITE_RATE) / Constants.WRITE_RATE);
			for (int count = 0; count < countMax; count++) {
				for (int i = offset; i <= writeMax; i++) {
					String s = StringGenerator.generate(i, length);
					String result = get(i);
					if (result != null && !s.equals(result)) {
						log.error("get error,expected " + s
								+ ",actual " + result);
						fail.incrementAndGet();
					} else if (result == null) {
						miss.incrementAndGet();
					} else if (result != null && result.equals(s)) {
						hit.incrementAndGet();
					}
				}
			}

			barrier.await();
		} catch (Exception e) {
			log.error(e.getMessage(), e);

		}
	}

}


text:
package org.efaps.esjp.sales.listener;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import org.efaps.admin.datamodel.Status;
import org.efaps.admin.datamodel.Type;
import org.efaps.admin.event.Parameter;
import org.efaps.admin.program.esjp.EFapsApplication;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.db.Instance;
import org.efaps.db.MultiPrintQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.db.SelectBuilder;
import org.efaps.db.Update;
import org.efaps.esjp.admin.datamodel.AbstractSetStatusListener;
import org.efaps.esjp.common.properties.PropertiesUtil;
import org.efaps.esjp.sales.util.Sales;
import org.efaps.util.EFapsException;

/**
 * The Class OnStatusChange4DependentDocument_Base.
 *
 * @author The eFaps Team
 */
@EFapsUUID("03f9b920-d33a-40a8-957d-212867ef9b5f")
@EFapsApplication("eFapsApp-Sales")
public abstract class OnStatusChange4DependentDocument_Base
    extends AbstractSetStatusListener
{

    @Override
    public void after(final Parameter _parameter,
                      final Instance _instance,
                      final Status _status)
        throws EFapsException
    {
        final String typeName = _instance.getType().getName();
        final Properties props = PropertiesUtil.getProperties4Prefix(Sales.DEPENDENTSLISTENER.get(), typeName, true);
        final Map<Integer, String> relationTypes = PropertiesUtil.analyseProperty(props, "RelationType", 0);
        final Map<Integer, String> instanceLinks = PropertiesUtil.analyseProperty(props, "InstanceLink", 0);
        final Map<Integer, String> dependentLinks = PropertiesUtil.analyseProperty(props, "DependentLink", 0);
        final Map<Integer, String> dependentStatus = PropertiesUtil.analyseProperty(props, "DependentStatus", 0);
        final Map<Integer, String> dependentStatusGrp = PropertiesUtil.analyseProperty(props, "DependentStatusGroup",
                        0);

        for (final Entry<Integer, String> entry : relationTypes.entrySet()) {
            final QueryBuilder queryBldr = new QueryBuilder(Type.get(entry.getValue()));
            queryBldr.addWhereAttrEqValue(instanceLinks.get(entry.getKey()), _instance);
            final MultiPrintQuery multi = queryBldr.getPrint();
            final SelectBuilder depInstSel = SelectBuilder.get().linkto(dependentLinks.get(entry.getKey())).instance();
            multi.addSelect(depInstSel);
            multi.execute();
            while (multi.next()) {
                final Instance depInst = multi.<Instance>getSelect(depInstSel);
                final Update update = new Update(depInst);
                final Status depstatus = Status.find(dependentStatusGrp.get(entry.getKey()), dependentStatus.get(entry
                                .getKey()));
                update.add(depInst.getType().getStatusAttribute(), depstatus);
                update.execute();
            }
        }
    }

    @Override
    public Set<Status> getStatus()
        throws EFapsException
    {
        final Set<Status> ret = super.getStatus();
        final Properties props = PropertiesUtil.getProperties4Prefix(Sales.DEPENDENTSLISTENER.get(), "TriggerStatus",
                        true);
        ret.addAll(getStatusListFromProperties(new Parameter(), props));
        return ret;
    }
}


text:
import sys
import logging

major, minor, micro = sys.version_info[:3]
if major < 3:
    PY3, Unicode, Bytes = False, unicode, str
else:
    PY3, Unicode, Bytes = True, str, bytes

def to_bytes(v, encoding="utf-8", errors="strict"):
    if isinstance(v, Bytes):
        return v
    elif isinstance(v, Unicode):
        return v.encode(encoding, errors)
    return to_bytes(str(v), encoding=encoding, errors=errors)

def to_unicode(v, encoding="utf-8", errors="strict"):
    if isinstance(v, Bytes):
        return v.decode(encoding, errors)
    elif isinstance(v, Unicode):
        return v
    return to_unicode(str(v), encoding=encoding, errors=errors)

to_str = to_unicode if PY3 else to_bytes
is_bytes = lambda s: isinstance(s, Bytes)
is_unicode = lambda s: isinstance(s, Unicode)
is_string = lambda s: isinstance(s, (Bytes, Unicode))
LOG = logging.getLogger("gunicorn.error" if "gunicorn" in sys.modules else None)

class Object(object):
    def __repr__(self):
        attrs = self.items() if hasattr(self, 'items') else vars(self).items()
        ss = ("%s=%s" % (k, v) for k, v in attrs if not k.startswith("_"))
        return "%s(%s)" % (self.__class__.__name__, ", ".join(ss))

class AttributeProxy(Object):
    def __init__(self, obj):
        '''The argument may be a dict or object.'''
        self._is_dict = isinstance(obj, dict)
        self._obj = obj

    def __contains__(self, name):
        return name in self._obj if self._is_dict else hasattr(self._obj, name)

    def __getattr__(self, name):
        if self._is_dict:
            try:
                return self._obj[name]
            except KeyError:
                raise AttributeError("'%s' object has no attribute '%s'" %
                                     (self._obj.__class__.__name__, name))
        else:
            try:
                return getattr(self._obj, name)
            except AttributeError:
                raise AttributeError("'%s' object has no attribute '%s'" %
                                     (self._obj.__class__.__name__, name))

    def __setattr__(self, name, value):
        if name == '_is_dict' or name == '_obj':
            object.__setattr__(self, name, value)
            return

        if self._is_dict:
            self._obj[name] = value
        else:
            setattr(self._obj, name, value)

    def __setitem__(self, name, value):
        if self._is_dict:
            self._obj[name] = value
        else:
            setattr(self._obj, name, value)

    def __getitem__(self, name):
        if self._is_dict:
            return self._obj[name]

        try:
            return getattr(self._obj, name)
        except AttributeError:
            raise KeyError(name)

    def items(self):
        if self._is_dict:
            return self._obj.items()
        return vars(self._obj).items()

    def get(self, name, default=None):
        if self._is_dict:
            return self._obj.get(name, default)
        return getattr(self._obj, name, default)


text:
//
// Fruit Link - HTML5 mobile game built with Hydra
// https://github.com/aduros/hydra/blob/master/projects/LICENSE.txt

goog.provide("jam.PlayingScene");

goog.require("hydra.Scene");
goog.require("hydra.task.SetCss");

goog.require("jam.Board");
goog.require("jam.BoardSprite");
goog.require("jam.ctx");

/**
 * @constructor
 * @extends {hydra.Scene}
 */
jam.PlayingScene = function () {
    goog.base(this, "playing");
}
goog.inherits(jam.PlayingScene, hydra.Scene);

jam.PlayingScene.prototype.load = function () {
    jam.ctx.board = new jam.Board();

    this.clock = new hydra.Sprite(hydra.dom.div("clock"));
    this.clock.setXY(200, 10);
    var self = this;
    this.addTask(new hydra.task.Repeat(new hydra.task.Sequence([
        new hydra.task.Delay(1),
        new hydra.task.CallFunction(function () {
            ++jam.ctx.board.elapsed;
            self.updateClock();
        })
    ])));
    this.clock.registerListener(jam.ctx.board, jam.BoardEvent.SCORE_CHANGED, goog.bind(this.onScoreChanged, this));
    this.clock.registerListener(jam.ctx.board, jam.BoardEvent.GAME_OVER, goog.bind(this.onGameOver, this));
    this.clock.registerListener(jam.ctx.board, jam.BoardEvent.GAME_STARTED, function () {
        self.updateClock();
    });
    this.addEntity(this.clock);

    this.score = new hydra.Sprite(hydra.dom.div("score"));
    this.score.setXY(32, 10);
    this.addEntity(this.score);

    var muteButton = hydra.Button.div("mute-button");
    muteButton.onTap = function () {
        var oldValue = muteButton.isToggled();
        if (oldValue) {
            jam.ctx.music.play();
        } else {
            jam.ctx.music.pause();
        }
        hydra.account["mute"] = !oldValue;
        hydra.storage.saveAccount();
        muteButton.setToggled(!oldValue);
    }
    muteButton.setToggled(hydra.account["mute"]);
    muteButton.setXY(320-40-8, 10);
    this.addEntity(muteButton);

    var pauseButton = hydra.Button.div("pause-button");
    pauseButton.setXY(0, 10);
    pauseButton.onTap = function () {
        var pauseScene = new hydra.Scene("pause");
        var fader = new hydra.Group(hydra.dom.div("fader"));
        fader.element.style.opacity = "0";
        fader.registerListener(document, "touchstart", function () {
            fader.removeAllTasks();
            fader.addTask(new hydra.task.Sequence([
                hydra.task.StyleTo.linear("opacity", "0", 0.5),
                new hydra.task.CallFunction(hydra.director.popScene)
            ]));
        });
        fader.addTask(hydra.task.StyleTo.linear("opacity", "0.9", 0.5));
        pauseScene.addEntity(fader);

        var label = new hydra.Sprite(hydra.dom.div("paused"));
        label.element.textContent = "PAUSED";
        label.setXY(320, 416/2-50);
        label.addTask(new hydra.task.Sequence([
            hydra.task.MoveTo.easeOut(320/2-80, 416/2-50, 1),
            new hydra.task.Repeat(new hydra.task.Sequence([
                hydra.task.ScaleTo.easeIn(1.2, 1, 0.5),
                hydra.task.ScaleTo.easeOut(1, 1, 0.5)
            ]))
        ]));
        fader.addSprite(label);

        hydra.director.pushScene(pauseScene);
    }
    this.addEntity(pauseButton);

//    jam.ctx.board.startGame();

    var board = new jam.BoardSprite();
    board.setY(56-3);
    this.addEntity(board);

    var interstitial = new hydra.Scene("interstitial");
    var ready = new hydra.Sprite(hydra.dom.div("ready"));
    ready.setXY(60, 0);
    ready.element.textContent = "Ready...";
    ready.element.style.opacity = "0";
    ready.addTask(new hydra.task.Sequence([
        new hydra.task.Parallel([
            hydra.task.MoveTo.linear(60, 416/2, 3),
            new hydra.task.Sequence([
                hydra.task.StyleTo.easeIn("opacity", "1", 1),
                new hydra.task.Delay(1.5),
                hydra.task.StyleTo.easeOut("opacity", "0", 0.5)
            ])
        ]),
        new hydra.task.CallFunction(function () {
            var go = new hydra.Sprite(hydra.dom.div("go"));
            go.element.textContent = "GO!";
            go.setXY(40, 416/3);
            go.setScale(0.25);
            go.addTask(new hydra.task.Sequence([
                new hydra.task.Parallel([
                    hydra.task.ScaleTo.easeOut(1, 1, 1),
                    new hydra.task.Sequence([
                        new hydra.task.Delay(0.5),
                        hydra.task.StyleTo.linear("opacity", "0", 0.5)
                    ])
                ]),
                new hydra.task.SelfDestruct()
            ]));
            self.addEntity(go);
            hydra.director.popScene();
            jam.ctx.board.startGame();
        })
    ]));
    interstitial.addEntity(ready);

    // Play the interstitial after the first tick
    this.addTask(new hydra.task.CallFunction(function () {
        hydra.director.pushScene(interstitial);
    }));
}

jam.PlayingScene.prototype.onScoreChanged = function () {
    if (jam.ctx.board.pathList.length) {
        this.score.removeAllTasks();
        this.score.addTask(new hydra.task.Sequence([
            hydra.task.ScaleTo.easeOut(1.2, 1.2, 0.1),
            hydra.task.ScaleTo.easeIn(1, 1, 0.1)
        ]));
    }
    this.score.element.textContent = String(jam.ctx.board.score);
}

jam.PlayingScene.prototype.updateClock = function () {
    var remaining = 90 - jam.ctx.board.elapsed;
    if (remaining >= 0) {
        var mins = hydra.math.toInt(remaining / 60);
        var secs = remaining % 60;
        this.clock.element.textContent = mins + ((secs > 9) ? ":" : ":0") + secs;
        if (remaining < 10) {
            this.clock.setCss("color", "red");
        }
    } else {
        jam.ctx.board.endGame();
    }
}

jam.PlayingScene.prototype.onGameOver = function () {
    var best = hydra.account["best"] || 0;
    if (jam.ctx.board.score > best) {
        best = jam.ctx.board.score;
        hydra.account["best"] = best;
        hydra.storage.saveAccount();
    }
    hydra.api.admob.showAd(jam.adBanner);
    hydra.director.replaceScene(
        confirm("Game over! You scored " + jam.ctx.board.score + " points." +
        "\n" +
        "\n" +
        "Your personal best is " + best + " points. Play again?") ?
        new jam.PlayingScene() : new jam.MainMenuScene());
        //hydra.director.unwindToScene(new jam.PlayingScene()); // Doesn't work in my janky android emulator for some reason
}


text:
package org.drools.core.base.extractors;

import org.drools.core.base.mvel.MVELCompileable;
import org.drools.core.common.InternalWorkingMemory;
import org.drools.core.definitions.rule.impl.RuleImpl;
import org.drools.core.rule.MVELDialectRuntimeData;
import org.drools.core.util.MVELSafeHelper;
import org.mvel2.compiler.ExecutableStatement;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

/**
 * A class field extractor that uses MVEL engine to extract the actual value for a given
 * expression. We use MVEL to resolve nested accessor expressions.
 */
public class MVELDateClassFieldReader extends BaseDateClassFieldReader implements Externalizable, MVELCompileable, MVELClassFieldReader {

    private static final long   serialVersionUID = 510l;

    private ExecutableStatement mvelExpression   = null;

    private String              className;
    private String              expr;
    private boolean             typesafe;
    private Object              evaluationContext;

    public MVELDateClassFieldReader() {
    }

    public MVELDateClassFieldReader(String className,
                                    String expr,
                                    boolean typesafe) {
        this.className = className;
        this.expr = expr;
        this.typesafe = typesafe;
        setIndex( -1 );

        // field (returns) type and value type are set during compile
    }

    public void readExternal(ObjectInput in) throws IOException,
                                            ClassNotFoundException {
        super.readExternal( in );
        this.className = ( String ) in.readObject();
        this.expr = ( String ) in.readObject();
        this.typesafe = in.readBoolean();
        this.evaluationContext = in.readObject();
    }

    public void writeExternal(ObjectOutput out) throws IOException {
        super.writeExternal( out );
        out.writeObject( this.className );
        out.writeObject(this.expr );
        out.writeBoolean(this.typesafe);
        out.writeObject(this.evaluationContext );
    }

    public void setExecutableStatement(ExecutableStatement expression) {
        this.mvelExpression = expression;
    }

    public String getClassName() {
        return this.className;
    }

    public boolean isTypeSafe() {
        return this.typesafe;
    }

    public String getExpression() {
        return this.expr;
    }

    public Object getEvaluationContext() {
        return evaluationContext;
    }

    public void setEvaluationContext(Object evaluationContext) {
        this.evaluationContext = evaluationContext;
    }

    public void compile(MVELDialectRuntimeData runtimeData) {
        MVELObjectClassFieldReader.doCompile(this, runtimeData, getEvaluationContext());
    }

    public void compile(MVELDialectRuntimeData runtimeData, RuleImpl rule) {
        MVELObjectClassFieldReader.doCompile(this, runtimeData, rule.toRuleNameAndPathString());
    }

    /* (non-Javadoc)
     * @see org.kie.base.extractors.BaseObjectClassFieldExtractor#getValue(java.lang.Object)
     */
    public Object getValue(InternalWorkingMemory workingMemory,
                           Object object) {
        return MVELSafeHelper.getEvaluator().executeExpression( mvelExpression,
                                       object  );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = super.hashCode();
        result = prime * result + ((className == null) ? 0 : className.hashCode());
        result = prime * result + ((expr == null) ? 0 : expr.hashCode());
        result = prime * result + (typesafe ? 1231 : 1237);
        return result;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean equals( Object obj ) {
        if ( this == obj ) return true;
        if ( !super.equals( obj ) ) return false;
        if ( getClass() != obj.getClass() ) return false;
        MVELDateClassFieldReader other = (MVELDateClassFieldReader) obj;
        if ( className == null ) {
            if ( other.className != null ) return false;
        } else if ( !className.equals( other.className ) ) return false;
        if ( expr == null ) {
            if ( other.expr != null ) return false;
        } else if ( !expr.equals( other.expr ) ) return false;
        return typesafe == other.typesafe;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return "[MVELDateClassFieldReader className=" + className + ", expr=" + expr + ", typesafe=" + typesafe + "]";
    }

}