text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.plugin.mysql;

import com.facebook.presto.Session;
import com.facebook.presto.testing.MaterializedResult;
import com.facebook.presto.testing.MaterializedRow;
import com.facebook.presto.testing.QueryRunner;
import com.facebook.presto.testing.mysql.MySqlOptions;
import com.facebook.presto.testing.mysql.TestingMySqlServer;
import com.facebook.presto.tests.AbstractTestIntegrationSmokeTest;
import com.facebook.presto.tests.DistributedQueryRunner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.airlift.units.Duration;
import org.intellij.lang.annotations.Language;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;

import static com.facebook.presto.common.type.VarcharType.VARCHAR;
import static com.facebook.presto.plugin.mysql.MySqlQueryRunner.createMySqlQueryRunner;
import static com.facebook.presto.testing.TestingSession.testSessionBuilder;
import static com.facebook.presto.testing.assertions.Assert.assertEquals;
import static com.google.common.collect.Iterables.getOnlyElement;
import static io.airlift.tpch.TpchTable.ORDERS;
import static java.lang.String.format;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;

@Test
public class TestMySqlIntegrationSmokeTest
        extends AbstractTestIntegrationSmokeTest
{
    private static final MySqlOptions MY_SQL_OPTIONS = MySqlOptions.builder()
            .setCommandTimeout(new Duration(90, SECONDS))
            .build();

    private final TestingMySqlServer mysqlServer;

    public TestMySqlIntegrationSmokeTest()
            throws Exception
    {
        this.mysqlServer = new TestingMySqlServer("testuser", "testpass", ImmutableList.of("tpch", "test_database"), MY_SQL_OPTIONS);
    }

    @Override
    protected QueryRunner createQueryRunner()
            throws Exception
    {
        return createMySqlQueryRunner(mysqlServer, ORDERS);
    }

    @AfterClass(alwaysRun = true)
    public final void destroy()
            throws IOException
    {
        mysqlServer.close();
    }

    @Override
    public void testDescribeTable()
    {
        // we need specific implementation of this tests due to specific Presto<->Mysql varchar length mapping.
        MaterializedResult actualColumns = computeActual("DESC ORDERS").toTestTypes();

        MaterializedResult expectedColumns = MaterializedResult.resultBuilder(getQueryRunner().getDefaultSession(), VARCHAR, VARCHAR, VARCHAR, VARCHAR)
                .row("orderkey", "bigint", "", "")
                .row("custkey", "bigint", "", "")
                .row("orderstatus", "varchar(255)", "", "")
                .row("totalprice", "double", "", "")
                .row("orderdate", "date", "", "")
                .row("orderpriority", "varchar(255)", "", "")
                .row("clerk", "varchar(255)", "", "")
                .row("shippriority", "integer", "", "")
                .row("comment", "varchar(255)", "", "")
                .build();
        assertEquals(actualColumns, expectedColumns);
    }

    @Test
    public void testDropTable()
    {
        assertUpdate("CREATE TABLE test_drop AS SELECT 123 x", 1);
        assertTrue(getQueryRunner().tableExists(getSession(), "test_drop"));

        assertUpdate("DROP TABLE test_drop");
        assertFalse(getQueryRunner().tableExists(getSession(), "test_drop"));
    }

    @Test
    public void testViews()
            throws SQLException
    {
        execute("CREATE OR REPLACE VIEW tpch.test_view AS SELECT * FROM tpch.orders");
        assertQuery("SELECT orderkey FROM test_view", "SELECT orderkey FROM orders");
        execute("DROP VIEW IF EXISTS tpch.test_view");
    }

    @Test
    public void testInsert()
            throws Exception
    {
        execute("CREATE TABLE tpch.test_insert (x bigint, y varchar(100))");
        assertUpdate("INSERT INTO test_insert VALUES (123, 'test')", 1);
        assertQuery("SELECT * FROM test_insert", "SELECT 123 x, 'test' y");
        assertUpdate("DROP TABLE test_insert");
    }

    @Test
    public void testNameEscaping()
    {
        Session session = testSessionBuilder()
                .setCatalog("mysql")
                .setSchema("test_database")
                .build();

        assertFalse(getQueryRunner().tableExists(session, "test_table"));

        assertUpdate(session, "CREATE TABLE test_table AS SELECT 123 x", 1);
        assertTrue(getQueryRunner().tableExists(session, "test_table"));

        assertQuery(session, "SELECT * FROM test_table", "SELECT 123");

        assertUpdate(session, "DROP TABLE test_table");
        assertFalse(getQueryRunner().tableExists(session, "test_table"));
    }

    @Test
    public void testMySqlTinyint1()
            throws Exception
    {
        execute("CREATE TABLE tpch.mysql_test_tinyint1 (c_tinyint tinyint(1))");

        MaterializedResult actual = computeActual("SHOW COLUMNS FROM mysql_test_tinyint1");
        MaterializedResult expected = MaterializedResult.resultBuilder(getSession(), VARCHAR, VARCHAR, VARCHAR, VARCHAR)
                .row("c_tinyint", "tinyint", "", "")
                .build();

        assertEquals(actual, expected);

        execute("INSERT INTO tpch.mysql_test_tinyint1 VALUES (127), (-128)");
        MaterializedResult materializedRows = computeActual("SELECT * FROM tpch.mysql_test_tinyint1 WHERE c_tinyint = 127");
        assertEquals(materializedRows.getRowCount(), 1);
        MaterializedRow row = getOnlyElement(materializedRows);

        assertEquals(row.getFields().size(), 1);
        assertEquals(row.getField(0), (byte) 127);

        assertUpdate("DROP TABLE mysql_test_tinyint1");
    }

    @Test
    public void testCharTrailingSpace()
            throws Exception
    {
        execute("CREATE TABLE tpch.char_trailing_space (x char(10))");
        assertUpdate("INSERT INTO char_trailing_space VALUES ('test')", 1);

        assertQuery("SELECT * FROM char_trailing_space WHERE x = char 'test'", "VALUES 'test'");
        assertQuery("SELECT * FROM char_trailing_space WHERE x = char 'test  '", "VALUES 'test'");
        assertQuery("SELECT * FROM char_trailing_space WHERE x = char 'test        '", "VALUES 'test'");

        assertEquals(getQueryRunner().execute("SELECT * FROM char_trailing_space WHERE x = char ' test'").getRowCount(), 0);

        Map<String, String> properties = ImmutableMap.of("deprecated.legacy-char-to-varchar-coercion", "true");
        Map<String, String> connectorProperties = ImmutableMap.of("connection-url", mysqlServer.getJdbcUrl());

        try (QueryRunner queryRunner = new DistributedQueryRunner(getSession(), 3, properties);) {
            queryRunner.installPlugin(new MySqlPlugin());
            queryRunner.createCatalog("mysql", "mysql", connectorProperties);

            assertEquals(queryRunner.execute("SELECT * FROM char_trailing_space WHERE x = char 'test'").getRowCount(), 0);
            assertEquals(queryRunner.execute("SELECT * FROM char_trailing_space WHERE x = char 'test  '").getRowCount(), 0);
            assertEquals(queryRunner.execute("SELECT * FROM char_trailing_space WHERE x = char 'test       '").getRowCount(), 0);

            MaterializedResult result = queryRunner.execute("SELECT * FROM char_trailing_space WHERE x = char 'test      '");
            assertEquals(result.getRowCount(), 1);
            assertEquals(result.getMaterializedRows().get(0).getField(0), "test      ");
        }

        assertUpdate("DROP TABLE char_trailing_space");
    }

    @Test
    public void testInsertIntoNotNullColumn()
    {
        String createTableFormat = "CREATE TABLE %s.tpch.test_insert_not_null (\n" +
                "   %s date,\n" +
                "   %s date NOT NULL\n" +
                ")";
        @Language("SQL") String createTableSql = format(
                createTableFormat,
                getSession().getCatalog().get(),
                "column_a",
                "column_b");
        @Language("SQL") String expectedCreateTableSql = format(
                createTableFormat,
                getSession().getCatalog().get(),
                "\"column_a\"",
                "\"column_b\"");
        assertUpdate(createTableSql);
        assertEquals(computeScalar("SHOW CREATE TABLE test_insert_not_null"), expectedCreateTableSql);

        assertQueryFails("INSERT INTO test_insert_not_null (column_a) VALUES (date '2012-12-31')", "NULL value not allowed for NOT NULL column: column_b");
        assertQueryFails("INSERT INTO test_insert_not_null (column_a, column_b) VALUES (date '2012-12-31', null)", "NULL value not allowed for NOT NULL column: column_b");

        assertUpdate("ALTER TABLE test_insert_not_null ADD COLUMN column_c BIGINT NOT NULL");

        createTableFormat = "CREATE TABLE %s.tpch.test_insert_not_null (\n" +
                "   %s date,\n" +
                "   %s date NOT NULL,\n" +
                "   %s bigint NOT NULL\n" +
                ")";
        createTableSql = format(
                createTableFormat,
                getSession().getCatalog().get(),
                "column_a",
                "column_b",
                "column_c");
        expectedCreateTableSql = format(
                createTableFormat,
                getSession().getCatalog().get(),
                "\"column_a\"",
                "\"column_b\"",
                "\"column_c\"");
        assertEquals(computeScalar("SHOW CREATE TABLE test_insert_not_null"), expectedCreateTableSql);

        assertQueryFails("INSERT INTO test_insert_not_null (column_b) VALUES (date '2012-12-31')", "NULL value not allowed for NOT NULL column: column_c");
        assertQueryFails("INSERT INTO test_insert_not_null (column_b, column_c) VALUES (date '2012-12-31', null)", "NULL value not allowed for NOT NULL column: column_c");

        assertUpdate("INSERT INTO test_insert_not_null (column_b, column_c) VALUES (date '2012-12-31', 1)", 1);
        assertUpdate("INSERT INTO test_insert_not_null (column_a, column_b, column_c) VALUES (date '2013-01-01', date '2013-01-02', 2)", 1);
        assertQuery(
                "SELECT * FROM test_insert_not_null",
                "VALUES (NULL, CAST('2012-12-31' AS DATE), 1), (CAST('2013-01-01' AS DATE), CAST('2013-01-02' AS DATE), 2)");

        assertUpdate("DROP TABLE test_insert_not_null");
    }

    private void execute(String sql)
            throws SQLException
    {
        try (Connection connection = DriverManager.getConnection(mysqlServer.getJdbcUrl());
                Statement statement = connection.createStatement()) {
            statement.execute(sql);
        }
    }
}


text:
<?php

namespace Chamilo\Core\Queue\Component;

use Chamilo\Core\Queue\Manager;
use Chamilo\Core\Queue\Service\JobEntityManager;
use Chamilo\Libraries\Architecture\Exceptions\NotAllowedException;

/**
 * @package Chamilo\Core\Queue\Component
 *
 * @author Sven Vanpoucke - Hogeschool Gent
 */
class FailedJobsBrowserComponent extends Manager
{

    /**
     * @return string
     *
     * @throws \Chamilo\Libraries\Architecture\Exceptions\NotAllowedException
     * @throws \Twig_Error_Loader
     * @throws \Twig_Error_Runtime
     * @throws \Twig_Error_Syntax
     */
    function run()
    {
        if(!$this->getUser()->is_platform_admin())
        {
            throw new NotAllowedException();
        }

        $retryURL = $this->get_url(
            [self::PARAM_ACTION => self::ACTION_RETRY_FAILED_JOB, self::PARAM_JOB_ID => '__JOB_ID__']
        );

        $failedJobs = $this->getJobEntityManager()->findFailedJobs();

        return $this->getTwig()->render(
            Manager::context() . ':FailedJobsBrowser.html.twig',
            [
                'FAILED_JOBS' => $failedJobs,
                'HEADER' => $this->render_header(),
                'FOOTER' => $this->render_footer(),
                'RETRY_URL' => $retryURL
            ]
        );
    }

    /**
     * @return JobEntityManager
     */
    protected function getJobEntityManager()
    {
        return $this->getService(JobEntityManager::class);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.identitymanagement.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SetDefaultPolicyVersionRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The Amazon Resource Name (ARN) of the IAM policy whose default version you want to set.
     *

     *

     * For more information about ARNs, see Amazon Resource Names (ARNs)
     * and AWS Service Namespaces in the AWS General Reference.
     *

     */
    private String policyArn;
    /**
     *

     * The version of the policy to set as the default (operative) version.
     *

     *

     * For more information about managed policy versions, see Versioning for Managed
     * Policies in the IAM User Guide.
     *

     */
    private String versionId;

    /**
     *

     * The Amazon Resource Name (ARN) of the IAM policy whose default version you want to set.
     *

     *

     * For more information about ARNs, see Amazon Resource Names (ARNs)
     * and AWS Service Namespaces in the AWS General Reference.
     *

     *
     * @param policyArn
     *        The Amazon Resource Name (ARN) of the IAM policy whose default version you want to set.

     *

     *        For more information about ARNs, see Amazon Resource Names
     *        (ARNs) and AWS Service Namespaces in the AWS General Reference.
     */

    public void setPolicyArn(String policyArn) {
        this.policyArn = policyArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the IAM policy whose default version you want to set.
     *

     *

     * For more information about ARNs, see Amazon Resource Names (ARNs)
     * and AWS Service Namespaces in the AWS General Reference.
     *

     *
     * @return The Amazon Resource Name (ARN) of the IAM policy whose default version you want to set.

     *

     *         For more information about ARNs, see Amazon Resource Names
     *         (ARNs) and AWS Service Namespaces in the AWS General Reference.
     */

    public String getPolicyArn() {
        return this.policyArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the IAM policy whose default version you want to set.
     *

     *

     * For more information about ARNs, see Amazon Resource Names (ARNs)
     * and AWS Service Namespaces in the AWS General Reference.
     *

     *
     * @param policyArn
     *        The Amazon Resource Name (ARN) of the IAM policy whose default version you want to set.

     *

     *        For more information about ARNs, see Amazon Resource Names
     *        (ARNs) and AWS Service Namespaces in the AWS General Reference.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SetDefaultPolicyVersionRequest withPolicyArn(String policyArn) {
        setPolicyArn(policyArn);
        return this;
    }

    /**
     *

     * The version of the policy to set as the default (operative) version.
     *

     *

     * For more information about managed policy versions, see Versioning for Managed
     * Policies in the IAM User Guide.
     *

     *
     * @param versionId
     *        The version of the policy to set as the default (operative) version.

     *

     *        For more information about managed policy versions, see Versioning for
     *        Managed Policies in the IAM User Guide.
     */

    public void setVersionId(String versionId) {
        this.versionId = versionId;
    }

    /**
     *

     * The version of the policy to set as the default (operative) version.
     *

     *

     * For more information about managed policy versions, see Versioning for Managed
     * Policies in the IAM User Guide.
     *

     *
     * @return The version of the policy to set as the default (operative) version.

     *

     *         For more information about managed policy versions, see Versioning for
     *         Managed Policies in the IAM User Guide.
     */

    public String getVersionId() {
        return this.versionId;
    }

    /**
     *

     * The version of the policy to set as the default (operative) version.
     *

     *

     * For more information about managed policy versions, see Versioning for Managed
     * Policies in the IAM User Guide.
     *

     *
     * @param versionId
     *        The version of the policy to set as the default (operative) version.

     *

     *        For more information about managed policy versions, see Versioning for
     *        Managed Policies in the IAM User Guide.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SetDefaultPolicyVersionRequest withVersionId(String versionId) {
        setVersionId(versionId);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getPolicyArn() != null)
            sb.append("PolicyArn: ").append(getPolicyArn()).append(",");
        if (getVersionId() != null)
            sb.append("VersionId: ").append(getVersionId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof SetDefaultPolicyVersionRequest == false)
            return false;
        SetDefaultPolicyVersionRequest other = (SetDefaultPolicyVersionRequest) obj;
        if (other.getPolicyArn() == null ^ this.getPolicyArn() == null)
            return false;
        if (other.getPolicyArn() != null && other.getPolicyArn().equals(this.getPolicyArn()) == false)
            return false;
        if (other.getVersionId() == null ^ this.getVersionId() == null)
            return false;
        if (other.getVersionId() != null && other.getVersionId().equals(this.getVersionId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getPolicyArn() == null) ? 0 : getPolicyArn().hashCode());
        hashCode = prime * hashCode + ((getVersionId() == null) ? 0 : getVersionId().hashCode());
        return hashCode;
    }

    @Override
    public SetDefaultPolicyVersionRequest clone() {
        return (SetDefaultPolicyVersionRequest) super.clone();
    }

}


text:
package japgolly.scalajs.react.extra

import japgolly.scalajs.react._

/**
 * Provides a component with safe R/W access to an external variable.
 *
 * Use [[ReusableVar]] for a reusable version of this.
 */
final class ExternalVar[A](val value: A, val set: A => Callback) {

  def mod(f: A => A): Callback =
    set(f(value))

  // Zoom is dangerously deceptive here as it appears to work but will often override the non-zoomed subset of A's state.
  // Use the zoom methods on CompScopes directly for a reliable function.
  //
  // def zoomL[B](l: Lens[A, B]): ExternalVar[B] =
  //   ExternalVar(l get value)(b => set(l.set(b)(value)))
}

object ExternalVar {
  @inline def apply[A](value: A)(set: A => Callback): ExternalVar[A] =
    new ExternalVar(value, set)

  /** What would you call this? I really can't think of anything meaningful - just follow at the types. */
  def s$[S](s: S, $: CompState.WriteAccess[S]): ExternalVar[S] =
    new ExternalVar(s, $ setState _)

  def state[S]($: CompState.AccessRD[S]): ExternalVar[S] =
    new ExternalVar($.state, $ setState _)
}


text:
using System.Collections.Generic;
using System.Linq;
using SFA.DAS.ReferenceData.Domain.Interfaces.Services;
using SFA.DAS.ReferenceData.Types.DTO;
using SFA.DAS.ReferenceData.Types.Exceptions;

namespace SFA.DAS.ReferenceData.Infrastructure.Services
{
    public class OrganisationTypeHelper : IOrganisationTypeHelper
    {
        private readonly Dictionary<OrganisationType, IOrganisationReferenceSearchService> _referenceSearchers = new Dictionary<OrganisationType, IOrganisationReferenceSearchService>();

        public OrganisationTypeHelper(IEnumerable<IOrganisationReferenceSearchService> referenceSearchServices)
        {
            _referenceSearchers = new Dictionary<OrganisationType, IOrganisationReferenceSearchService>();
            foreach (var referenceSearchService in referenceSearchServices)
            {
                if (_referenceSearchers.ContainsKey(referenceSearchService.OrganisationType))
                {
                    throw new ReferenceDataException($"The organisation type {referenceSearchService.OrganisationType} has more than one implementation of {nameof(IOrganisationReferenceSearchService)} supporting it");
                }

                _referenceSearchers.Add(referenceSearchService.OrganisationType, referenceSearchService);
            }
        }

        public bool TryGetReferenceSearcher(OrganisationType organisationType, out IOrganisationReferenceSearchService referenceSearcher)
        {
            return _referenceSearchers.TryGetValue(organisationType, out referenceSearcher);
        }

        public OrganisationType[] GetIdentifiableOrganisationTypes()
        {
            return _referenceSearchers.Select(rs => rs.Value.OrganisationType).ToArray();
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>Finite Geometry and Physical Space</title>

Finite Geometry Notes
       <nobr>   |   Home |  Site
Map |
       Author |
      </nobr>

Pilate
Goes to
Kindergarten  (April 2009, with update of February 2012)

"There is a pleasantly
discursive treatment of Pontius
Pilate's unanswered question 'What is truth?'."

-- H. S. M. Coxeter,
1987, introduction to Trudeau's The
Non-Euclidean Revolution

Consider the following question in a paper cited
by V.S. Varadarajan:

E. G. Beltrametti, "Can a finite geometry describe physical
space-time?"

 (Universita degli studi di Perugia, Atti del
convegno di geometria combinatoria e sue applicazioni,
Perugia 1971, 57–62)

Simplifying:

"Can a finite geometry describe physical space?"

Simplifying further:

"Yes. Vide 'The
Eightfold Cube.'"

Let G be the group of 1344 transformations of the
3-dimensional affine finite geometry over the 2-element field
GF(2).

The
eightfold cube illustrates one property of physical space--
namely, the invariance under G of the set of seven
partitions
illustrated with kindergarten blocks below.

These seven
partitions are a model, in physical space, of the seven points
of
the 2-dimensional projective finite geometry over GF(2). The partitions
(i.e., the projective points) are permuted by G, a group generated by
physically natural permutations of the eight subcubes.

<big>Update of February 17, 2012

</big>

Pregeometry and Finite Geometry

The February 2012 Scientific American  article "Is Space Digital?"

suggested a review of a notion that the theoretical physicist

John Archibald Wheeler called  pregeometry .

From a paper on that topic—

"… the idea that geometry should constitute

	'the magic building material of the universe'

	had to collapse on behalf of what Wheeler

	has called pregeometry (see Misner et al. 1973,

	pp. 1203-1212; Wheeler 1980), a somewhat

	indefinite term which expresses “a combination

	of hope and need, of philosophy and physics

	and mathematics and logic” (Misner et al. 1973,

	p. 1203)."

— Jacques Demaret, Michael Heller, and

	Dominique Lambert, "Local and Global Properties

	of the World," preprint of paper published in

	Foundations of Science  2 (1): 137-176

Misner, C. W., Thorne, K. S. and Wheeler, J. A.

	1973, Gravitation , W.H. Freeman and Company:

	San Francisco.

Wheeler, J.A. 1980, "Pregeometry: Motivations

	and Prospects," in: Quantum Theory and Gravitation ,

	ed. A.R. Marlow, Academic Press: New York, pp. 1-11.

Some related material from pure mathematics—

Click image for further details.

Page created on April 10, 2009 (Good Friday). Updated February 17, 2012.

p>

Page created on April 10, 2009 (Good Friday). Updated February 17, 2012.


text:
let project = new Project('Kha');

const pcreVersion = '8.42';
const tlsVersion = '2.9.0';
const zlibVersion = '1.2.11';

project.addFiles('Backends/Kore/khacpp/src/**.h', 'Backends/Kore/khacpp/src/**.cpp', 'Backends/Kore/khacpp/include/**.h');
project.addFiles('Backends/Kore/khacpp/project/libs/common/**.h', 'Backends/Kore/khacpp/project/libs/common/**.cpp');
if (platform === Platform.Windows || platform === Platform.WindowsApp) project.addFiles('Backends/Kore/khacpp/project/libs/msvccompat/**.cpp');
if (platform === Platform.Linux) project.addFiles('Backends/Kore/khacpp/project/libs/linuxcompat/**.cpp');
project.addFiles('Backends/Kore/khacpp/project/libs/regexp/**.h', 'Backends/Kore/khacpp/project/libs/regexp/**.cpp', 'Backends/Kore/khacpp/project/libs/std/**.h', 'Backends/Kore/khacpp/project/libs/std/**.cpp');

project.addFiles('Backends/Kore/khacpp/project/thirdparty/pcre-' + pcreVersion + '/**.h', 'Backends/Kore/khacpp/project/thirdparty/pcre-' + pcreVersion + '/**.c');

const zlibFiles = [
	'**.h',
	'adler32.c',
	'compress.c',
	'crc32.c',
	'gzio.c',
	'uncompr.c',
	'deflate.c',
	'trees.c',
	'zutil.c',
	'inflate.c',
	'infback.c',
	'inftrees.c',
	'inffast.c'
];

for (const file of zlibFiles) {
	project.addFile('Backends/Kore/khacpp/project/thirdparty/zlib-' + zlibVersion + '/' + file);
}

project.addFiles('Backends/Kore/khacpp/project/thirdparty/mbedtls-' + tlsVersion + '/**');

project.addFiles('Backends/Kore/*.cpp', 'Backends/Kore/*.h');

const pcreExcludes = [
	'dftables.c',
	'pcredemo.c',
	'pcregrep.c',
	'pcretest.c',
	'pcre_jit_test.c',
	'pcre_printint.c',
	'pcre16_printint.c',
	'pcre32_printint.c',
	'sljit/**'
];

for (const file of pcreExcludes) {
	project.addExclude('Backends/Kore/khacpp/project/thirdparty/pcre-' + pcreVersion + '/' + file);
}
project.addExcludes('Backends/Kore/khacpp/src/ExampleMain.cpp', 'Backends/Kore/khacpp/src/hx/Scriptable.cpp', 'Backends/Kore/khacpp/src/hx/NoFiles.cpp', 'Backends/Kore/khacpp/src/hx/cppia/**');
project.addExcludes('Backends/Kore/khacpp/src/hx/Debugger.cpp', 'Backends/Kore/khacpp/src/hx/Profiler.cpp', 'Backends/Kore/khacpp/src/hx/Telemetry.cpp');
project.addExcludes('Backends/Kore/khacpp/src/hx/NekoAPI.cpp');
project.addExcludes('Backends/Kore/khacpp/src/hx/libs/sqlite/**');
project.addExcludes('Backends/Kore/khacpp/src/hx/libs/mysql/**');

project.addIncludeDirs('Backends/Kore/khacpp/include', 'Backends/Kore/khacpp/project/thirdparty/pcre-' + pcreVersion, 'Backends/Kore/khacpp/project/thirdparty/zlib-' + zlibVersion, 'Backends/Kore/khacpp/project/libs/nekoapi', 'Backends/Kore/khacpp/project/thirdparty/mbedtls-' + tlsVersion + '/include');

//if (options.vrApi == "rift") {
//	out += "project.addIncludeDirs('C:/khaviar/LibOVRKernel/Src/');\n";
//	out += "project.addIncludeDirs('C:/khaviar/LibOVR/Include/');\n";
//}

if (platform !== Platform.Android) {
	project.addExcludes('Backends/Kore/khacpp/src/hx/AndroidCompat.cpp');
}

if (platform === Platform.Windows) project.addDefine('HX_WINDOWS');
if (platform === Platform.WindowsApp) {
	project.addDefine('HX_WINDOWS');
	project.addDefine('HX_WINRT');
}
if (platform !== Platform.Windows || audio !== AudioApi.DirectSound) {
	project.addDefine('KORE_MULTITHREADED_AUDIO');
}
if (platform === Platform.OSX) {
	project.addDefine('HXCPP_M64');
	project.addDefine('HX_MACOS');
}
if (platform === Platform.Linux) project.addDefine('HX_LINUX');
if (platform === Platform.iOS) {
	project.addDefine('IPHONE');
	project.addDefine('HX_IPHONE');
}
if (platform === Platform.tvOS) {
	project.addDefine('APPLETV');
}
if (platform === Platform.Android) {
	project.addDefine('ANDROID');
	project.addDefine('_ANDROID');
	project.addDefine('HX_ANDROID');
	project.addDefine('HXCPP_ANDROID_PLATFORM=24');
}
if (platform === Platform.OSX) {
	project.addDefine('KORE_DEBUGDIR="osx"');
	project.addLib('Security');
}
if (platform === Platform.iOS) project.addDefine('KORE_DEBUGDIR="ios"');

// project:addDefine('HXCPP_SCRIPTABLE');
project.addDefine('STATIC_LINK');
project.addDefine('PCRE_STATIC');
project.addDefine('HXCPP_SET_PROP');
project.addDefine('HXCPP_VISIT_ALLOCS');
project.addDefine('KORE');
project.addDefine('ROTATE90');
project.addDefine('HAVE_CONFIG_H');
project.addDefine('SUPPORT_UTF');
project.addDefine('SUPPORT_UCP');

//if (Options.vrApi === "gearvr") {
//	out += "project.addDefine('VR_GEAR_VR');\n";
//}
//else if (Options.vrApi === "cardboard") {
//	out += "project.addDefine('VR_CARDBOARD');\n";
//}
//else if (Options.vrApi === "rift") {
//	out += "project.addDefine('VR_RIFT');\n";
//}
//
//if (options.vrApi == "rift") {
//	out += "project.addLib('C:/khaviar/LibOVRKernel/Lib/Windows/Win32/Release/VS2013/LibOVRKernel');\n";
//	out += "project.addLib('C:/khaviar/LibOVR/Lib/Windows/Win32/Release/VS2013/LibOVR');\n";
//}

if (platform === Platform.Windows || platform === Platform.WindowsApp) {
	project.addDefine('_WINSOCK_DEPRECATED_NO_WARNINGS');
}
if (platform === Platform.Windows) {
	project.addLib('ws2_32');
}

resolve(project);


text:
<?php

  namespace osCommerce\OM\Core\Site\Shop\Application\Checkout\Action\Billing;

  use osCommerce\OM\Core\ApplicationAbstract;
  use osCommerce\OM\Core\Registry;
  use osCommerce\OM\Core\OSCOM;
  use osCommerce\OM\Core\ObjectInfo;

  class Address {
    public static function execute(ApplicationAbstract $application) {
      $OSCOM_Template = Registry::get('Template');
      $OSCOM_Service = Registry::get('Service');
      $OSCOM_Breadcrumb = Registry::get('Breadcrumb');
      $OSCOM_Customer = Registry::get('Customer');
      $OSCOM_ShoppingCart = Registry::get('ShoppingCart');

      global $osC_oiAddress;

      $application->setPageTitle(OSCOM::getDef('payment_address_heading'));
      $application->setPageContent('billing_address.php');

      $OSCOM_Template->addJavascriptFilename(OSCOM::getPublicSiteLink('javascript/checkout_payment_address.js'));
      $OSCOM_Template->addJavascriptPhpFilename(OSCOM::BASE_DIRECTORY . 'Core/Site/Shop/assets/form_check.js.php');

      if ( $OSCOM_Service->isStarted('Breadcrumb') ) {
        $OSCOM_Breadcrumb->add(OSCOM::getDef('breadcrumb_checkout_payment_address'), OSCOM::getLink(null, null, 'Billing&Address', 'SSL'));
      }

      if ( !$OSCOM_Customer->isLoggedOn() ) {
        $osC_oiAddress = new ObjectInfo($OSCOM_ShoppingCart->getShippingAddress());
      }
    }
  }
?>


text:
"""
sentry.rules.conditions.tagged_event
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""

from __future__ import absolute_import

import json

from collections import OrderedDict
from django import forms

from sentry.rules.conditions.base import EventCondition

class MatchType(object):
    EQUAL = 'eq'
    NOT_EQUAL = 'ne'
    STARTS_WITH = 'sw'
    ENDS_WITH = 'ew'
    CONTAINS = 'co'
    NOT_CONTAINS = 'nc'
    IS_SET = 'is'
    NOT_SET = 'ns'

MATCH_CHOICES = OrderedDict([
    (MatchType.EQUAL, 'equals'),
    (MatchType.NOT_EQUAL, 'does not equal'),
    (MatchType.STARTS_WITH, 'starts with'),
    (MatchType.ENDS_WITH, 'ends with'),
    (MatchType.CONTAINS, 'contains'),
    (MatchType.NOT_CONTAINS, 'does not contain'),
    (MatchType.IS_SET, 'is set'),
    (MatchType.NOT_SET, 'is not set'),
])

ATTR_CHOICES = [
    'message',
    'platform',
    'exception.type',
    'exception.value',
    'user.id',
    'user.ip_address',
    'user.email',
    'http.method',
    'http.url',
    'stacktrace.code',
    'stacktrace.module',
    'stacktrace.filename',
]

class FixedTypeaheadInput(forms.TextInput):
    def __init__(self, choices, *args, **kwargs):
        super(FixedTypeaheadInput, self).__init__(*args, **kwargs)
        self.attrs['data-choices'] = json.dumps(choices)
        self.attrs['class'] = self.attrs.get('class', '') + ' typeahead'

class EventAttributeForm(forms.Form):
    attribute = forms.CharField(widget=FixedTypeaheadInput(
        attrs={'style': 'width:200px', 'placeholder': 'i.e. exception.type'},
        choices=[{'id': a, 'text': a} for a in ATTR_CHOICES],
    ))
    match = forms.ChoiceField(MATCH_CHOICES.items(), widget=forms.Select(
        attrs={'style': 'width:150px'},
    ))
    value = forms.CharField(widget=forms.TextInput(
        attrs={'placeholder': 'value'},
    ), required=False)

class EventAttributeCondition(EventCondition):
    """
    Attributes are a mapping of <logical-key>.<property>.

    For example:

    - message
    - platform
    - exception.{type,value}
    - user.{id,ip_address,email,FIELD}
    - http.{method,url}
    - stacktrace.{code,module,filename}
    - extra.{FIELD}
    """
    # TODO(dcramer): add support for stacktrace.vars.[name]

    form_cls = EventAttributeForm
    label = 'An events {attribute} value {match} {value}'

    def _get_attribute_values(self, event, attr):
        # TODO(dcramer): we should validate attributes (when we can) before

        path = attr.split('.')

        if path[0] in ('message', 'platform'):
            if len(path) != 1:
                return []
            return [getattr(event, path[0])]

        elif len(path) == 1:
            return []

        elif path[0] == 'extra':
            path.pop(0)
            value = event.data['extra']
            while path:
                bit = path.pop(0)
                value = value.get(bit)
                if not value:
                    return []

            if isinstance(value, (list, tuple)):
                return value
            return [value]

        elif len(path) != 2:
            return []

        elif path[0] == 'exception':
            if path[1] not in ('type', 'value'):
                return []

            return [
                getattr(e, path[1])
                for e in event.interfaces['sentry.interfaces.Exception'].values
            ]

        elif path[0] == 'user':
            if path[1] in ('id', 'ip_address', 'email', 'username'):
                return [
                    getattr(event.interfaces['sentry.interfaces.User'], path[1])
                ]
            return [
                getattr(event.interfaces['sentry.interfaces.User'].data, path[1])
            ]

        elif path[0] == 'http':
            if path[1] not in ('url', 'method'):
                return []

            return [
                getattr(event.interfaces['sentry.interfaces.Http'], path[1])
            ]

        elif path[0] == 'stacktrace':
            stacks = event.interfaces.get('sentry.interfaces.Stacktrace')
            if stacks:
                stacks = [stacks]
            else:
                stacks = [
                    e.stacktrace
                    for e in event.interfaces['sentry.interfaces.Exception'].values
                ]

            result = []
            for st in stacks:
                for frame in st.frames:
                    if path[1] in ('filename', 'module'):
                        result.append(getattr(frame, path[1]))
                    elif path[1] == 'code':
                        if frame.pre_context:
                            result.extend(frame.pre_context)
                        if frame.context_line:
                            result.append(frame.context_line)
                        if frame.post_context:
                            result.extend(frame.post_context)
            return result
        return []

    def render_label(self):
        data = {
            'attribute': self.data['attribute'],
            'value': self.data['value'],
            'match': MATCH_CHOICES[self.data['match']],
        }
        return self.label.format(**data)

    def passes(self, event, state, **kwargs):
        attr = self.get_option('attribute')
        match = self.get_option('match')
        value = self.get_option('value')

        if not (attr and match and value):
            return False

        value = value.lower()
        attr = attr.lower()

        try:
            attribute_values = self._get_attribute_values(event, attr)
        except KeyError:
            attribute_values = []

        attribute_values = [v.lower() for v in attribute_values]

        if match == MatchType.EQUAL:
            for a_value in attribute_values:
                if a_value == value:
                    return True
            return False

        elif match == MatchType.NOT_EQUAL:
            for a_value in attribute_values:
                if a_value == value:
                    return False
            return True

        elif match == MatchType.STARTS_WITH:
            for a_value in attribute_values:
                if a_value.startswith(value):
                    return True
            return False

        elif match == MatchType.ENDS_WITH:
            for a_value in attribute_values:
                if a_value.endswith(value):
                    return True
            return False

        elif match == MatchType.CONTAINS:
            for a_value in attribute_values:
                if value in a_value:
                    return True
            return False

        elif match == MatchType.NOT_CONTAINS:
            for a_value in attribute_values:
                if value in a_value:
                    return False
            return True

        elif match == MatchType.IS_SET:
            return bool(attribute_values)

        elif match == MatchType.NOT_SET:
            return not attribute_values


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>本地生活后台管理系统</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<form action="__URL__/checklogin" method="post" name="baseform">

本地生活后台管理系统

用户名:<input type="text" name="username"/>

密   码:<input type="text"  name="userpwd"/>

验证码:<input type="text" name="gbcode" id="gbcode" />

<input type="submit" name="button" id="button" value="登录" />

</form>


text:
require_relative "snapshot"

module Mathtype3
  class RecordFont < BinData::Record
    include Snapshot
    EXPOSED_IN_SNAPSHOT = %i(options name typeface style)

    endian :little

    mandatory_parameter :_options

    virtual :_tag_options, :value => lambda{ _options }

    int8 :_typeface

    int8 :style

    stringz :name
    def typeface
      _typeface + 128
    end

    def options
      _tag_options
    end
  end
end


text:
module("baidu.lang.createClass");

function myClass(option) {
	this.name = "myclass";
	// baidu.lang.Class.call(this);
	// 继承构造器,guid是在baidu.lang.Class的构造函数中生成的
	this.givenName = option.givenName;
	this.company = option.company;
	this.salary = option.salary;
	this.getInfo = option.getInfo;
}

test("default parent class", function(){
	var NewClass = baidu.lang.createClass(myClass);
	var sObject = new NewClass({
		givenName: 'Jim',
		company: 'baidu',
		salary: 10000,
		getInfo: function(){
			return this.company + ' emploee ' + this.givenName + ' can get money ' + this.salary;
		}
	});

	equals(sObject.getInfo(), "baidu emploee Jim can get money 10000", 'sObject.getInfo() = "baidu emploee Jim can get money 10000"');
	equals(sObject.givenName, "Jim", 'givenName = "Jim"');
	equals(sObject.salary, 10000, 'salary = 10000');
	equals(sObject.company, "baidu", '');
	equals(sObject instanceof NewClass, true, 'sObject instanceof NewClass is true');
	equals(sObject instanceof myClass, false, 'sObject instanceof myClass is false'); // sObject is not instance of myClass
	equals(sObject instanceof baidu.lang.Class, true, 'sObject instanceof baidu.lang.Class is true');
});

test("specific parent class point to baidu.lang.Class", function(){
	var NewClass = baidu.lang.createClass(myClass, new function(){
		baidu.lang.Class.call(this);
	});

	var sObject = new NewClass({
		givenName: 'Jim',
		company: 'baidu',
		salary: 10000,
		getInfo: function(){
			return this.company + " employee " + this.givenName + " can get money " + this.salary;
		}
	});
	equals(sObject.getInfo(), "baidu employee Jim can get money 10000", 'sObject.getInfo() = "baidu employee Jim can get money 10000"');
	equals(sObject.givenName, "Jim", 'givenName = "Jim"');
	equals(sObject.salary, 10000, 'salary = 10000');
	equals(sObject.company, "baidu", '');
	equals(sObject instanceof NewClass, true, 'sObject instanceof NewClass is true');
	equals(sObject instanceof myClass, false, 'sObject instanceof myClass is false'); // sObject is not instance of myClass
	equals(sObject instanceof baidu.lang.Class, true, 'sObject instanceof baidu.lang.Class is true');
});

test("specific parent class", function(){
	var NewClass = baidu.lang.createClass(myClass, new function(){
	});

	var sObject = new NewClass({
		givenName: 'Jim',
		company: 'baidu',
		salary: 10000,
		getInfo: function(){
			return this.company + ' employee ' + this.givenName + ' can get money ' + this.salary;
		}
	});

	equals(sObject.getInfo(), "baidu employee Jim can get money 10000", 'sObject.getInfo() = "baidu employee Jim can get money 10000"');
	equals(sObject.givenName, "Jim", 'givenName = "Jim"');
	equals(sObject.salary, 10000, 'salary = 10000');
	equals(sObject.company, "baidu", '');
	equals(sObject instanceof NewClass, true, 'sObject instanceof NewClass is true');
	equals(sObject instanceof myClass, false, 'sObject instanceof myClass is false'); // sObject is not instance of myClass
	equals(sObject instanceof baidu.lang.Class, true, 'sObject instanceof baidu.lang.Class is true');
});

test("option param", function(){
	function superClass(){
		this.superClassname = "superMyclass";
		ok(true,"to superClass !");
	}
	var NewClass = baidu.lang.createClass(myClass, {superClass:superClass});

	var sObject = new NewClass({
		givenName: 'Jim',
		company: 'baidu',
		salary: 10000,
		getInfo: function(){
			return this.company + ' employee ' + this.givenName + ' can get money ' + this.salary;
		}
	});
	equal(sObject.superClassname,new superClass().superClassname,"this is superClassname");
});

test("class extend", function(){
	function superClass(){
		this.superClassname = "superMyclass";
	}
	function extendFunc(){
		return "extend function";
	}
	var NewClass = baidu.lang.createClass(myClass, {superClass:superClass}).extend({extend:extendFunc});
	var sObject = new NewClass({
		givenName: 'Jim',
		company: 'baidu',
		salary: 10000,
		getInfo: function(){
			return this.company + " employee " + this.givenName + " can get money " + this.salary;
		}
	});
	equal(sObject.extend(),extendFunc(),"extend is success");
});

test("global config", function(){
	expect(4);
	var NewClass = baidu.lang.createClass(myClass, {
		options : {subtitle : "test"}
	});
	var sObject = new NewClass({
		givenName: 'Jim'
	});
	var nObject = new NewClass({
		givenName: 'Tom'
	});

	equals(sObject.givenName, "Jim", 'sObject.givenName');
	equals(nObject.givenName, "Tom", 'nObject.givenName');
	equals(sObject.subtitle, "test", 'sObject.subtitle');
	equals(nObject.subtitle, "test", 'nObject.subtitle');
});

//describe('baidu.lang.createClass', {
//	'default parent class' : function() {
//		var NewClass = baidu.lang.createClass(myClass);
//		var sObject = new NewClass( {
//			givenName : 'Jim',
//			company : 'baidu',
//			salary : 10000,
//			getInfo : function() {
//				return this.company + ' employee ' + this.givenName
//						+ ' can get money ' + this.salary;
//			}
//		});
//		value_of(sObject.getInfo()).should_be(
//				'baidu employee Jim can get money 10000');
//		value_of(sObject.givenName).should_be('Jim');
//		value_of(sObject.salary).should_be(10000);
//		value_of(sObject.company).should_be('baidu');
//		value_of(sObject instanceof NewClass).should_be_true();
////		value_of(sObject instanceof MyClass).should_be_true();
//		value_of(sObject instanceof baidu.lang.Class).should_be_true();
//	},
//	'specific parent class point to baidu.lang.Class' : function() {
//		var NewClass = baidu.lang.createClass(myClass, new function() {
//			baidu.lang.Class.call(this);
//		});
//		var sObject = new NewClass( {
//			givenName : 'Jim',
//			company : 'baidu',
//			salary : 10000,
//			getInfo : function() {
//				return this.company + ' employee ' + this.givenName
//						+ ' can get money ' + this.salary;
//			}
//		});
//		value_of(sObject.getInfo()).should_be(
//				'baidu employee Jim can get money 10000');
//		value_of(sObject.givenName).should_be('Jim');
//		value_of(sObject.salary).should_be(10000);
//		value_of(sObject.company).should_be('baidu');
//		value_of(sObject instanceof NewClass).should_be_true();
////		value_of(sObject instanceof MyClass).should_be_true();
//		value_of(sObject instanceof baidu.lang.Class).should_be_true();
//	},
//	'specific parent class' : function() {
//		var NewClass = baidu.lang.createClass(myClass, new function() {
//		});
//		var sObject = new NewClass( {
//			givenName : 'Jim',
//			company : 'baidu',
//			salary : 10000,
//			getInfo : function() {
//				return this.company + ' employee ' + this.givenName
//						+ ' can get money ' + this.salary;
//			}
//		});
//		value_of(sObject.getInfo()).should_be(
//				'baidu employee Jim can get money 10000');
//		value_of(sObject.givenName).should_be('Jim');
//		value_of(sObject.salary).should_be(10000);
//		value_of(sObject.company).should_be('baidu');
//		value_of(sObject instanceof NewClass).should_be_true();
////		value_of(sObject instanceof MyClass).should_be_true();
//		value_of(sObject instanceof baidu.lang.Class).should_be_true();
//	}
//});


text:
module StateShifter
  module Definition
    class Contents

      attr_accessor :states, :initial_state, :events, :state_tags, :on_transition_proc

      def initialize &definition
        @states     = {}
        @events     = {}
        @state_tags = {}
        instance_eval &definition if block_given?
      end

      def state name, &events_and_stuff
        if @states.empty? # first state declared is the initial one
          this_state = State.new(name, true)
          @initial_state = this_state
        else
          this_state = State.new(name)
        end

        raise RedifiningState, this_state.name if @states.has_key?(this_state.name.to_sym)

        @states[this_state.name.to_sym] = this_state
        @current_state = this_state
        instance_eval &events_and_stuff if events_and_stuff
      end

      def tags *names
        names.each do |name|
          @state_tags[name] ||= []
          @state_tags[name] << @current_state.name
        end
      end

      def event hash_or_sym, hash=nil
        this_event =
          if hash.nil?
            if hash_or_sym.is_a?(Symbol)
              # looping event
              event_name = hash_or_sym

              Event.new @current_state.name.to_sym, event_name
            else
              # normal event
              event_guards = hash_or_sym.delete(:if)
              event_name = hash_or_sym.keys.first
              event_next_state = hash_or_sym[event_name.to_sym]

              Event.new @current_state.name.to_sym, event_name, event_next_state, event_guards
            end
          else
            event_guards = hash.delete(:if)
            event_name = hash_or_sym
            event_callback = hash.delete(:call)

            Event.new @current_state.name.to_sym, event_name, @current_state.name.to_sym, event_guards, event_callback
          end

        raise RedifiningEvent, this_event.name if @events.has_key?(this_event.name.to_sym)

        @events[this_event.name.to_sym] = this_event
        @current_state.events[event_name.to_sym] = this_event
      end

      def on_entry event_name=nil, *event_args, &proc_contents
        if event_name.nil?
          @current_state.entry_callback = proc_contents
        else
          @current_state.entry_callback = event_name
          @current_state.entry_callback_args = ( event_args.size == 1 ? event_args.first : event_args ) unless event_args.empty?
        end
      end

      def on_transition &proc_contents
        @on_transition_proc = proc_contents
      end

      ### end of DSL methods

      def get key, what
        case key
        when :event
          @events[what.to_sym] || @events[what.to_s.gsub('!','').to_sym]
        when :state
          @states[what.to_sym] || @states[what.to_s.gsub('!','').to_sym]
        end
      end

      def has_on_transition_proc?
        !@on_transition_proc.nil?
      end

    end
  end
end


text:
<?php

final class PhabricatorOAuthResponse extends AphrontResponse {

  private $state;
  private $content;
  private $clientURI;
  private $error;
  private $errorDescription;

  private function getState() {
    return $this->state;
  }
  public function setState($state) {
    $this->state = $state;
    return $this;
  }

  private function getContent() {
    return $this->content;
  }
  public function setContent($content) {
    $this->content = $content;
    return $this;
  }

  private function getClientURI() {
    return $this->clientURI;
  }
  public function setClientURI(PhutilURI $uri) {
    $this->setHTTPResponseCode(302);
    $this->clientURI = $uri;
    return $this;
  }
  private function getFullURI() {
    $base_uri     = $this->getClientURI();
    $query_params = $this->buildResponseDict();
    foreach ($query_params as $key => $value) {
      $base_uri->setQueryParam($key, $value);
    }
    return $base_uri;
  }

  private function getError() {
    return $this->error;
  }

  public function setError($error) {
    // errors sometimes redirect to the client (302) but otherwise
    // the spec says all code 400
    if (!$this->getClientURI()) {
      $this->setHTTPResponseCode(400);
    }
    $this->error = $error;
    return $this;
  }

  private function getErrorDescription() {
    return $this->errorDescription;
  }

  public function setErrorDescription($error_description) {
    $this->errorDescription = $error_description;
    return $this;
  }

  public function __construct() {
    $this->setHTTPResponseCode(200);      // assume the best
    return $this;
  }

  public function getHeaders() {
    $headers = array(
      array('Content-Type', 'application/json'),
    );
    if ($this->getClientURI()) {
      $headers[] = array('Location', $this->getFullURI());
    }
    // TODO -- T844 set headers with X-Auth-Scopes, etc
    $headers = array_merge(parent::getHeaders(), $headers);
    return $headers;
  }

  private function buildResponseDict() {
    if ($this->getError()) {
      $content = array(
        'error'             => $this->getError(),
        'error_description' => $this->getErrorDescription(),
      );
      $this->setContent($content);
    }

    $content = $this->getContent();
    if (!$content) {
      return '';
    }
    if ($this->getState()) {
      $content['state'] = $this->getState();
    }
    return $content;
  }

  public function buildResponseString() {
    return $this->encodeJSONForHTTPResponse($this->buildResponseDict());
  }

}


text:
"""
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.

This program and the accompanying materials are made available under
the terms of the under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import os
import tinctest

from tinctest.lib import local_path
from tinctest.runner import TINCTestRunner

from mpp.models import SQLTestCase, SQLTestCaseException

import unittest2 as unittest

import shutil

from contextlib import closing
from datetime import datetime
from StringIO import StringIO
from unittest2.runner import _WritelnDecorator

@unittest.skip('mock')
class MockSQLTestCaseWithSubstitutions(SQLTestCase):
    """

    @description test case with metadata
    @created 2012-07-05 12:00:00
    @modified 2012-07-05 12:00:02
    @tags tag1
    @db_name mockdb
    """
    sql_dir = 'sql/'
    ans_dir = 'expected/'

    def get_substitutions(self):
        substitutions = {'%dbname%': self.db_name,
                         '%tags%': ''.join(self.tags),
                         '%foo%': 'foo'}
        return substitutions

@unittest.skip('mock')
class MockSQLTestCaseWithTemplateSubstitutions(SQLTestCase):
    """

    @description test case with metadata
    @created 2012-07-05 12:00:00
    @modified 2012-07-05 12:00:02
    @tags tag1
    @db_name mockdb
    """
    sql_dir = 'sql_template/'
    ans_dir = 'expected_template/'
    db_name = 'mockdb'

    template_subs = {'%dbname%': 'mockdb'}

    def get_substitutions(self):
        substitutions = {'%tags%': ''.join(self.tags),
                         '%foo%': 'foo'}
        return substitutions

class SQLTestCaseSubstitutionTests(unittest.TestCase):

    def test_verify_substitutions(self):
        test_loader = tinctest.TINCTestLoader()
        test_suite = test_loader.loadTestsFromTestCase(MockSQLTestCaseWithSubstitutions)
        for test_case in test_suite._tests:
            test_case.__class__.__unittest_skip__ = False
        test_result = unittest.TestResult()
        test_suite.run(test_result)
        self.assertEqual(test_result.testsRun, 3)
        self.assertEqual(len(test_result.errors), 0)
        self.assertEqual(len(test_result.skipped), 0)
        self.assertEqual(len(test_result.failures), 0)

    def test_verify_substitutions_with_templates(self):
        test_loader = tinctest.TINCTestLoader()
        test_suite = test_loader.loadTestsFromTestCase(MockSQLTestCaseWithTemplateSubstitutions)
        for test_case in test_suite._tests:
            test_case.__class__.__unittest_skip__ = False
        test_result = unittest.TestResult()
        test_suite.run(test_result)
        self.assertEqual(test_result.testsRun, 3)
        self.assertEqual(len(test_result.errors), 0)
        self.assertEqual(len(test_result.skipped), 0)
        self.assertEqual(len(test_result.failures), 0)


text:
package June2021GoogLeetcode;

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

public class _0118PascalsTriangle {
	public static void main(String[] args) {
		System.out.println(generate(5));
	}

	public static List<List<Integer>> generate(int numRows) {
		List<List<Integer>> output = new ArrayList<List<Integer>>();
		if (numRows == 0)
			return output;
		List<Integer> list = new ArrayList<Integer>();
		list.add(1);
		output.add(list);
		if (numRows == 1)
			return output;
		for (int i = 1; i < numRows; i++) {
			List<Integer> currList = output.get(output.size() - 1);
			List<Integer> newList = new ArrayList<Integer>();
			for (int j = 0; j < currList.size(); j++) {
				if (j == 0) {
					newList.add(currList.get(j));
				} else if (j - 1 >= 0) {
					newList.add(currList.get(j) + currList.get(j - 1));
				}
				if (j == currList.size() - 1)
					newList.add(currList.get(j));
			}
			output.add(newList);
		}
		return output;
	}
}


text:
        <md-icon class="md-icon-18" *ngIf="menuItem.icon">{{menuItem.icon}}</md-icon>
        {{menuItem.name}}
        <md-icon [@rotateAnimation]="showMenu ? 'down': 'right'" class="rotate-icon">chevron_right</md-icon>

    <ng-template #linkItem>

            {{menuItem.name}}

    </ng-template>

        <admin-menu-item
                *ngFor="let item of menuItem.subMenu"
                [menuItem]="item"
                (itemHover)="onHoverItem($event)">
        </admin-menu-item>


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("coredb", "0010_auto_20210429_1539"),
    ]

    operations = [
        migrations.AlterField(
            model_name="artifact",
            name="state",
            field=models.UUIDField(db_index=True),
        ),
    ]


text:
title: Combined B.1
permalink: combined/b/1/
---


text:
<template name="projects">

Projects (Add)

<input type="text" name="projectName" id="nameNewProject"/>

<textarea name="projectDescription" id="descriptionNewProject"></textarea>

                <button id="makeNewProject">Save</button>

        {{#if userProjects}}
        {{#each userProjects}}

            <input class="accordionitem" id="{{this._id}}" name="{{this._id}}" type="radio"
            {{#if checkable this._id}}checked="checked" {{/if}}/>

                    {{this.name}}

                {{this.description}}

        {{/each}}
        {{else}}

            No projects here. Add a new project.

        {{/if}}

</template>

<template name="projectsHint">

        To create a new project, click the Add link.

        Move the mouse hover a project to see the available commands.

        Click  to accelerate a project.

        Click  to edit a project.

        Click  to delete a project.

        Click anywhere else to see the project description.

</template>


text:
cp /vagrant/config/.bash_profile /home/vagrant/.bash_profile

# Upgrading nodejs
echo "Upgrading Nodejs"

## Install NVM
wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.29.0/install.sh | bash

## Export NVM for the current session
export NVM_DIR="/home/vagrant/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"  # This loads nvm

## Install nodejs 0.12
nvm install 0.12
npm install webpack -g

echo "Building client app"
cd /vagrant/lib/client
npm install


text:
import {t} from "tcomb-react";
import {isISO8601, isURL} from "validator";

export const ISO8601String = t.refinement(t.String, isISO8601);
export const URLString = t.refinement(t.String, isURL);

export const Code = t.struct({
    code: t.String,
    url: URLString,
    fetchingStats: t.Boolean,
    errorFetchingStats: t.maybe(t.Object),
    newlyCreated: t.Boolean,
    stats: t.maybe(t.struct({
        startDate: ISO8601String,
        lastSeenDate: ISO8601String,
        redirectCount: t.Number
    }))
}, "Code");

export const CodesCollection = t.dict(t.String, Code, "CodesCollection");


text:
using System;
using VkNet.Utils;

namespace VkNet.Model;

/// <summary>
/// Объект, с помощью которого можно подключиться к серверу быстрых сообщений для
/// мгновенного
/// получения приходящих сообщений и других событий.
/// См. описание http://vk.com/dev/messages.getLongPollServer
/// </summary>
[Serializable]
public class LongPollServerResponse
{
	/// <summary>
	/// Ключ для подключения.
	/// </summary>
	public string Key { get; set; }

	/// <summary>
	/// Имя сервера быстрых сообщений.
	/// </summary>
	public string Server { get; set; }

	/// <summary>
	/// Отметка времени.
	/// </summary>
	public string Ts { get; set; }

	/// <summary>
	/// Постоянное событие для работы с методом getLongPoolHistory
	/// </summary>
	public ulong? Pts { get; set; }

	#region Методы

	/// <summary>
	/// Разобрать из json.
	/// </summary>
	/// <param name="response"> Ответ сервера. </param>
	/// <returns> </returns>
	public static LongPollServerResponse FromJson(VkResponse response)
	{
		var longPollServerResponse = new LongPollServerResponse
		{
			Key = response["key"],
			Server = response["server"],
			Ts = response["ts"],
			Pts = response["pts"]
		};

		return longPollServerResponse;
	}

	#endregion
}


text:
package reswing

import javax.swing.Icon

import scala.language.implicitConversions
import scala.swing.{AbstractButton, Alignment, Color, Dimension, Font}
import scala.swing.event.ButtonClicked

class ReAbstractButton(
    val text: ReSwingValue[String] = (),
    val selected: ReSwingValue[Boolean] = (),
    val horizontalAlignment: ReSwingValue[Alignment.Value] = (),
    val verticalAlignment: ReSwingValue[Alignment.Value] = (),
    val horizontalTextPosition: ReSwingValue[Alignment.Value] = (),
    val verticalTextPosition: ReSwingValue[Alignment.Value] = (),
    val icon: ReSwingValue[Icon] = (),
    val pressedIcon: ReSwingValue[Icon] = (),
    val selectedIcon: ReSwingValue[Icon] = (),
    val disabledIcon: ReSwingValue[Icon] = (),
    val disabledSelectedIcon: ReSwingValue[Icon] = (),
    val rolloverIcon: ReSwingValue[Icon] = (),
    val rolloverSelectedIcon: ReSwingValue[Icon] = (),
    background: ReSwingValue[Color] = (),
    foreground: ReSwingValue[Color] = (),
    font: ReSwingValue[Font] = (),
    enabled: ReSwingValue[Boolean] = (),
    minimumSize: ReSwingValue[Dimension] = (),
    maximumSize: ReSwingValue[Dimension] = (),
    preferredSize: ReSwingValue[Dimension] = ())
  extends
    ReComponent(background, foreground, font, enabled,
                minimumSize, maximumSize, preferredSize) {
  override protected lazy val peer = new AbstractButton with ComponentMixin

  text using (peer.text _, peer.text_= _, "text")
  selected using (peer.selected _, peer.selected_= _, classOf[ButtonClicked])

  horizontalAlignment using (peer.horizontalAlignment _,
                             peer.horizontalAlignment= _, "horizontalAlignment")
  verticalAlignment using (peer.verticalAlignment _,
                           peer.verticalAlignment= _, "verticalAlignment")
  horizontalTextPosition using (peer.horizontalTextPosition _,
                                peer.horizontalTextPosition= _, "horizontalTextPosition")
  verticalTextPosition using (peer.verticalTextPosition _,
                              peer.verticalTextPosition_= _, "verticalTextPosition")

  icon using (peer.icon _, peer.icon_= _, "icon")
  pressedIcon using (peer.pressedIcon _, peer.pressedIcon_= _, "pressedIcon")
  selectedIcon using (peer.selectedIcon _, peer.selectedIcon_= _, "selectedIcon")
  disabledIcon using (peer.disabledIcon _, peer.disabledIcon_= _, "disabledIcon")
  disabledSelectedIcon using (peer.disabledSelectedIcon _, peer.disabledSelectedIcon_= _, "disabledSelectedIcon")
  rolloverIcon using (peer.rolloverIcon _, peer.rolloverIcon_= _, "rolloverIcon")
  rolloverSelectedIcon using (peer.rolloverSelectedIcon _, peer.rolloverSelectedIcon_= _, "rolloverSelectedIcon")

  val clicked = ReSwingEvent using classOf[ButtonClicked]
}

object ReAbstractButton {
  implicit def toAbstractButton(component: ReAbstractButton): AbstractButton = component.peer
}


text:
namespace OpenProtocolInterpreter.Job
{
    /// <summary>
    /// Job info acknowledge
    /// <para>Acknowledgement of a Job info message.</para>
    /// <para>Message sent by: Integrator</para>
    /// <para>Answer: None</para>
    /// </summary>
    public class Mid0036 : Mid, IJob, IIntegrator
    {
        private const int LAST_REVISION = 4;
        public const int MID = 36;

        public Mid0036() : this(LAST_REVISION)
        {

        }

        public Mid0036(int revision = LAST_REVISION) : base(MID, revision) {  }
    }
}


text:
import unittest
import datetime
import os

from ocw import dataset_processor as dp
from ocw import dataset as ds
from ocw.data_source import local
import numpy as np
import numpy.ma as ma

import logging
logging.basicConfig(level=logging.CRITICAL)

class TestTemporalSubset(unittest.TestCase):

    def setUp(self):
        self.ten_year_dataset = ten_year_monthly_dataset()

    def test_returned_dataset(self):
        self.dataset_times = np.array([datetime.datetime(year, month, 1)
                                       for year in range(2000, 2010)
                                       for month in range(1, 6)])
        self.tempSubset = dp.temporal_subset(self.ten_year_dataset, 1, 5)
        np.testing.assert_array_equal(
            self.dataset_times, self.tempSubset.times)

    def test_temporal_subset_with_average_time(self):
        self.dataset_times = np.array([datetime.datetime(year, 2, 1)
                                       for year in range(2000, 2010)])
        self.tempSubset = dp.temporal_subset(self.ten_year_dataset,
                                             1, 3,
                                             average_each_year=True)
        np.testing.assert_array_equal(self.dataset_times,
                                      self.tempSubset.times)

    def test_temporal_subset_with_average_values(self):
        self.tempSubset = dp.temporal_subset(self.ten_year_dataset,
                                             1, 3,
                                             average_each_year=True)
        self.dataset_values = np.ones([len(self.tempSubset.times),
                                       len(self.ten_year_dataset.lats),
                                       len(self.ten_year_dataset.lons)])
        np.testing.assert_array_equal(self.dataset_values,
                                      self.tempSubset.values)

    def test_temporal_subset_attributes(self):
        self.tempSubset = dp.temporal_subset(self.ten_year_dataset,
                                             1, 3,
                                             average_each_year=True)
        self.assertEqual(self.tempSubset.name, self.ten_year_dataset.name)
        self.assertEqual(self.tempSubset.variable,
                         self.ten_year_dataset.variable)
        self.assertEqual(self.tempSubset.units, self.ten_year_dataset.units)
        np.testing.assert_array_equal(self.tempSubset.lats,
                                      self.ten_year_dataset.lats)
        np.testing.assert_array_equal(self.tempSubset.lons,
                                      self.ten_year_dataset.lons)

    def test_temporal_subset_equal_start_end_month(self):
        self.dataset_times = np.array([datetime.datetime(year, 1, 1)
                                       for year in range(2000, 2010)])
        self.tempSubset = dp.temporal_subset(self.ten_year_dataset,
                                             1, 1,
                                             average_each_year=True)
        np.testing.assert_array_equal(self.dataset_times,
                                      self.tempSubset.times)

    def test_startMonth_greater_than_endMonth(self):
        self.dataset_times = np.array([datetime.datetime(year, month, 1)
                                       for year in range(2000, 2010)
                                       for month in [1, 8, 9, 10, 11, 12]])
        self.tempSubset = dp.temporal_subset(self.ten_year_dataset, 8, 1)
        np.testing.assert_array_equal(
            self.dataset_times, self.tempSubset.times)

class TestTemporalRebinWithTimeIndex(unittest.TestCase):

    def setUp(self):
        self.ten_year_dataset = ten_year_monthly_dataset()

    def test_time_dimension_multiple_of_orig_time_dimension(self):
        # ten_year_dataset.times.size is 120
        nt_avg = self.ten_year_dataset.times.size // 2
        # Temporal Rebin to exactly 2 (time) values
        dataset = dp.temporal_rebin_with_time_index(
            self.ten_year_dataset, nt_avg)
        start_time = self.ten_year_dataset.times[0]
        # First month of the middle year
        middle_element = self.ten_year_dataset.times.size // 2
        end_time = self.ten_year_dataset.times[middle_element]
        self.assertEqual(dataset.times.size,
                         self.ten_year_dataset.times.size // nt_avg)
        np.testing.assert_array_equal(dataset.times, [start_time, end_time])

    def test_time_dimension_not_multiple_of_orig_time_dimension(self):
        # ten_year_dataset.times.size is 120
        nt_avg = 11
        # Temporal Rebin to exactly 10 (time) values
        dataset = dp.temporal_rebin_with_time_index(
            self.ten_year_dataset, nt_avg)
        new_times = self.ten_year_dataset.times[::11][:-1]
        self.assertEqual(dataset.times.size,
                         self.ten_year_dataset.times.size // nt_avg)
        np.testing.assert_array_equal(dataset.times, new_times)

    def test_returned_dataset_attributes(self):
        nt_avg = 3
        dataset = dp.temporal_rebin_with_time_index(
            self.ten_year_dataset, nt_avg)
        new_times = self.ten_year_dataset.times[::3]
        new_values = self.ten_year_dataset.values[::3]
        self.assertEqual(self.ten_year_dataset.name, dataset.name)
        self.assertEqual(self.ten_year_dataset.origin, dataset.origin)
        self.assertEqual(self.ten_year_dataset.units, dataset.units)
        self.assertEqual(self.ten_year_dataset.variable, dataset.variable)
        np.testing.assert_array_equal(new_times, dataset.times)
        np.testing.assert_array_equal(new_values, dataset.values)
        np.testing.assert_array_equal(self.ten_year_dataset.lats, dataset.lats)
        np.testing.assert_array_equal(self.ten_year_dataset.lons, dataset.lons)

class TestVariableUnitConversion(unittest.TestCase):

    def setUp(self):
        self.ten_year_dataset = ten_year_monthly_dataset()
        self.ten_year_dataset.variable = 'temp'
        self.ten_year_dataset.units = 'celsius'

    def test_returned_variable_unit_celsius(self):
        ''' Tests returned dataset unit if original dataset unit is celcius '''
        dp.variable_unit_conversion(self.ten_year_dataset)
        self.assertEqual(self.ten_year_dataset.units, 'K')

    def test_returned_variable_unit_kelvin(self):
        ''' Tests returned dataset unit if original dataset unit is kelvin '''
        self.ten_year_dataset.units = 'K'
        another_dataset = dp.variable_unit_conversion(self.ten_year_dataset)
        self.assertEqual(another_dataset.units, self.ten_year_dataset.units)

    def test_temp_unit_conversion(self):
        ''' Tests returned dataset temp values '''
        self.ten_year_dataset.values = np.ones([
            len(self.ten_year_dataset.times),
            len(self.ten_year_dataset.lats),
            len(self.ten_year_dataset.lons)])
        values = self.ten_year_dataset.values + 273.15
        dp.variable_unit_conversion(self.ten_year_dataset)
        np.testing.assert_array_equal(self.ten_year_dataset.values, values)

    def test_returned_variable_unit_swe(self):
        ''' Tests returned dataset unit if original dataset unit is swe '''
        self.ten_year_dataset.variable = 'swe'
        self.ten_year_dataset.units = 'm'
        dp.variable_unit_conversion(self.ten_year_dataset)
        self.assertEqual(self.ten_year_dataset.variable, 'swe')
        self.assertEqual(self.ten_year_dataset.units, 'km')

    def test_returned_variable_unit_pr(self):
        '''
        Tests returned dataset unit if original dataset unit is kgm^-2s^-1
        '''
        self.ten_year_dataset.variable = 'pr'
        self.ten_year_dataset.units = 'kg m-2 s-1'
        dp.variable_unit_conversion(self.ten_year_dataset)
        self.assertEqual(self.ten_year_dataset.variable, 'pr')
        self.assertEqual(self.ten_year_dataset.units, 'mm/day')

    def test_water_flux_unit_conversion_swe(self):
        ''' Tests variable values in returned dataset '''
        self.ten_year_dataset.variable = 'swe'
        self.ten_year_dataset.units = 'm'
        values = self.ten_year_dataset.values + 999
        dp.variable_unit_conversion(self.ten_year_dataset)
        np.testing.assert_array_equal(self.ten_year_dataset.values, values)

    def test_water_flux_unit_conversion_pr(self):
        ''' Tests variable values in returned dataset '''
        self.ten_year_dataset.variable = 'pr'
        self.ten_year_dataset.units = 'kg m-2 s-1'
        values = self.ten_year_dataset.values + 86399
        dp.variable_unit_conversion(self.ten_year_dataset)
        np.testing.assert_array_equal(self.ten_year_dataset.values, values)

class TestTemporalSlice(unittest.TestCase):

    def test_returned_dataset_times(self):
        ''' Tests returned dataset times values '''
        self.ten_year_dataset = ten_year_monthly_dataset()
        start_index = 1
        end_index = 4
        dates = np.array([datetime.datetime(2000, month, 1)
                          for month in range(start_index + 1, end_index + 2)])
        new_dataset = dp.temporal_slice(self.ten_year_dataset,
                                        start_time = self.ten_year_dataset.times[start_index],
                                        end_time = self.ten_year_dataset.times[end_index])
        np.testing.assert_array_equal(new_dataset.times, dates)

    def test_returned_dataset_values(self):
        ''' Tests returned dataset variable values '''
        self.ten_year_dataset = ten_year_monthly_dataset()
        start_index = 1
        end_index = 4
        values = self.ten_year_dataset.values[start_index:end_index + 1]
        new_dataset = dp.temporal_slice(self.ten_year_dataset,
                                        start_time = self.ten_year_dataset.times[start_index],
                                        end_time = self.ten_year_dataset.times[end_index])
        np.testing.assert_array_equal(new_dataset.values, values)

class TestEnsemble(unittest.TestCase):

    def test_unequal_dataset_shapes(self):
        self.ten_year_dataset = ten_year_monthly_dataset()
        self.two_year_dataset = two_year_daily_dataset()
        with self.assertRaises(ValueError):
            self.ensemble_dataset = dp.ensemble(
                [self.ten_year_dataset, self.two_year_dataset])

    def test_ensemble_logic(self):
        self.datasets = []
        self.datasets.append(build_ten_cube_dataset(1))
        self.datasets.append(build_ten_cube_dataset(2))
        self.three = build_ten_cube_dataset(3)
        self.datasets.append(self.three)
        self.datasets.append(build_ten_cube_dataset(4))
        self.datasets.append(build_ten_cube_dataset(5))
        self.ensemble = dp.ensemble(self.datasets)
        self.ensemble_flat = self.ensemble.values.flatten()
        self.three_flat = self.three.values.flatten()
        np.testing.assert_array_equal(self.ensemble_flat, self.three_flat)

    def test_ensemble_name(self):
        self.ensemble_dataset_name = "Dataset Ensemble"
        self.datasets = []
        self.datasets.append(build_ten_cube_dataset(1))
        self.datasets.append(build_ten_cube_dataset(2))
        self.ensemble = dp.ensemble(self.datasets)
        self.assertEquals(self.ensemble.name, self.ensemble_dataset_name)

class TestTemporalRebin(unittest.TestCase):

    def setUp(self):
        self.ten_year_monthly_dataset = ten_year_monthly_dataset()
        self.ten_year_annual_times = np.array(
            [datetime.datetime(year, 7, 2) for year in range(2000, 2010)])
        self.two_years_daily_dataset = two_year_daily_dataset()

    def test_monthly_to_annual_rebin(self):
        annual_dataset = dp.temporal_rebin(
            self.ten_year_monthly_dataset, "annual")
        np.testing.assert_array_equal(
            annual_dataset.times, self.ten_year_annual_times)

    def test_monthly_to_full_rebin(self):
        full_dataset = dp.temporal_rebin(self.ten_year_monthly_dataset, "full")
        full_times = [datetime.datetime(2005, 1, 1)]
        self.assertEqual(full_dataset.times, full_times)

    def test_daily_to_monthly_rebin(self):
        """
        This test takes a really long time to run.
        TODO: Figure out where the performance drag is
        """
        monthly_dataset = dp.temporal_rebin(
            self.two_years_daily_dataset, "monthly")
        bins = list(set([datetime.datetime(
                        time_reading.year, time_reading.month, 15)
                    for time_reading in self.two_years_daily_dataset.times]))
        bins = np.array(bins)
        bins.sort()
        np.testing.assert_array_equal(monthly_dataset.times, bins)

    def test_daily_to_annual_rebin(self):
        annual_dataset = dp.temporal_rebin(
            self.two_years_daily_dataset, "annual")
        bins = list(set([datetime.datetime(
                        time_reading.year, 7, 2)
                    for time_reading in self.two_years_daily_dataset.times]))
        bins = np.array(bins)
        bins.sort()
        np.testing.assert_array_equal(annual_dataset.times, bins)

    def test_non_rebin(self):
        """
        This will take a monthly dataset and ask for a monthly rebin of
        28 days. The resulting dataset should have the same time values
        """
        monthly_dataset = dp.temporal_rebin(
            self.ten_year_monthly_dataset, "monthly")
        bins = list(set([datetime.datetime(
                        time_reading.year, time_reading.month, 15)
                    for time_reading in self.ten_year_monthly_dataset.times]))
        bins = np.array(bins)
        bins.sort()
        np.testing.assert_array_equal(monthly_dataset.times, bins)

    def test_variable_propagation(self):
        annual_dataset = dp.temporal_rebin(self.ten_year_monthly_dataset,
                                           "annual")
        self.assertEquals(annual_dataset.name,
                          self.ten_year_monthly_dataset.name)
        self.assertEquals(annual_dataset.variable,
                          self.ten_year_monthly_dataset.variable)

    def test_daily_to_daily_rebin(self):
        daily_dataset = dp.temporal_rebin(
            self.two_years_daily_dataset, "daily")
        np.testing.assert_array_equal(
            daily_dataset.times, self.two_years_daily_dataset.times)

    def test_invalid_unit_rebin(self):
        with self.assertRaises(ValueError):
            dp.temporal_rebin(self.two_years_daily_dataset, "days")

class TestRcmesSpatialRegrid(unittest.TestCase):

    def test_return_array_shape(self):
        spatial_values = np.ones([90, 180])
        spatial_values = ma.array(spatial_values)

        lat_range = ma.array(range(-89, 90, 2))
        lon_range = ma.array(range(-179, 180, 2))

        lons, lats = np.meshgrid(lon_range, lat_range)
        # Convert these to masked arrays
        lats = ma.array(lats)
        lons = ma.array(lons)

        lat2_range = np.array(range(-89, 90, 4))
        lon2_range = np.array(range(-179, 180, 4))

        lons2, lats2 = np.meshgrid(lon2_range, lat2_range)
        # Convert to masked arrays
        lats2 = ma.array(lats2)
        lons2 = ma.array(lons2)

        regridded_values = dp._rcmes_spatial_regrid(
            spatial_values, lats, lons, lats2, lons2)
        self.assertEqual(regridded_values.shape, lats2.shape)
        self.assertEqual(regridded_values.shape, lons2.shape)

class TestSpatialRegrid(unittest.TestCase):

    def setUp(self):
        self.input_dataset = ten_year_monthly_dataset()
        self.new_lats = np.array(range(-89, 90, 4))
        self.new_lons = np.array(range(-179, 180, 4))
        self.regridded_dataset = dp.spatial_regrid(
            self.input_dataset, self.new_lats, self.new_lons)

    def test_returned_lats(self):
        np.testing.assert_array_equal(
            self.regridded_dataset.lats, self.new_lats)

    def test_returned_lons(self):
        np.testing.assert_array_equal(
            self.regridded_dataset.lons, self.new_lons)

    def test_shape_of_values(self):
        regridded_data_shape = self.regridded_dataset.values.shape
        expected_data_shape = (len(self.input_dataset.times), len(
            self.new_lats), len(self.new_lons))
        self.assertSequenceEqual(regridded_data_shape, expected_data_shape)

    def test_variable_propagation(self):
        self.assertEquals(self.input_dataset.name, self.regridded_dataset.name)
        self.assertEquals(self.input_dataset.variable,
                          self.regridded_dataset.variable)

    def test_two_dimensional_lats_lons(self):
        self.input_dataset.lons, self.input_dataset.lats = np.meshgrid(
                                  np.array(range(-179, 180, 2)), np.array(range(-89, 90, 2)))
        new_dataset = dp.spatial_regrid(
            self.input_dataset, self.new_lats, self.new_lons)
        np.testing.assert_array_equal(new_dataset.lats, self.new_lats)

class TestNormalizeDatasetDatetimes(unittest.TestCase):

    def setUp(self):
        self.monthly_dataset = ten_year_monthly_15th_dataset()
        self.daily_dataset = two_year_daily_2hr_dataset()

    def test_daily(self):
        new_ds = dp.normalize_dataset_datetimes(self.monthly_dataset, 'daily')

        # Check that all the days have been shifted to the first of the month
        self.assertTrue(all(x.hour == 0 for x in new_ds.times))

    def test_montly(self):
        new_ds = dp.normalize_dataset_datetimes(
            self.monthly_dataset, 'monthly')

        # Check that all the days have been shifted to the first of the month
        self.assertTrue(all(x.day == 1 for x in new_ds.times))

    def test_daily_time(self):
        # Test daily with time.hour != 0
        self.monthly_dataset.times = np.array([
                                              datetime.datetime(
                                                  year, month, 15, 5)
                                              for year in range(2000, 2010)
                                              for month in range(1, 13)])
        new_ds = dp.normalize_dataset_datetimes(self.monthly_dataset, 'daily')
        # Check that all the days have been shifted to the first of the month
        self.assertTrue(all(x.hour == 0 for x in new_ds.times))

class TestSubset(unittest.TestCase):

    def setUp(self):
        self.target_dataset = ten_year_monthly_dataset()
        self.name = 'foo'

        self.subregion = ds.Bounds(
            lat_min=-81, lat_max=81,
            lon_min=-161, lon_max=161,
            start=datetime.datetime(2001, 1, 1),
            end=datetime.datetime(2004, 1, 1)
        )
        self.non_exact_spatial_subregion = ds.Bounds(
            lat_min=-80.25, lat_max=80.5,
            lon_min=-160.25, lon_max=160.5,
            start=datetime.datetime(2001, 1, 1),
            end=datetime.datetime(2004, 1, 1)
        )
        self.non_exact_temporal_subregion = ds.Bounds(
            lat_min=-80.25, lat_max=80.5,
            lon_min=-160.25, lon_max=160.5,
            start=datetime.datetime(2001, 1, 15),
            end=datetime.datetime(2004, 2, 15)
        )

    def test_subset(self):
        subset = dp.subset(self.target_dataset, self.subregion)
        self.assertEqual(subset.lats.shape[0], 82)
        self.assertSequenceEqual(list(np.array(range(-81, 82, 2))),
                                 list(subset.lats))
        self.assertEqual(subset.lons.shape[0], 162)
        self.assertEqual(subset.times.shape[0], 37)
        self.assertEqual(subset.values.shape, (37, 82, 162))

    def test_subset_name(self):
        subset = dp.subset(self.target_dataset, self.subregion)
        self.assertEqual(subset.name, self.name)

    def test_subset_name_propagation(self):
        subset_name = 'foo_subset_name'
        subset = dp.subset(self.target_dataset, self.subregion, subset_name)
        self.assertEqual(subset.name, subset_name)

    def test_subset_using_non_exact_spatial_bounds(self):
        index_slices = dp._get_subregion_slice_indices(
            self.target_dataset, self.non_exact_spatial_subregion)
        control_index_slices = {"lat_start": 5,
                                "lat_end": 84,
                                "lon_start": 10,
                                "lon_end": 169,
                                "time_start": 12,
                                "time_end": 48}
        self.assertDictEqual(index_slices, control_index_slices)

    def test_subset_using_non_exact_temporal_bounds(self):
        index_slices = dp._get_subregion_slice_indices(
            self.target_dataset, self.non_exact_temporal_subregion)
        control_index_slices = {"lat_start": 5,
                                "lat_end": 84,
                                "lon_start": 10,
                                "lon_end": 169,
                                "time_start": 13,
                                "time_end": 49}
        self.assertDictEqual(index_slices, control_index_slices)

    def test_subset_without_start_index(self):
        self.subregion = ds.Bounds(
            lat_min=-81, lat_max=81,
            lon_min=-161, lon_max=161,
        )
        subset = dp.subset(self.target_dataset, self.subregion)
        times = np.array([datetime.datetime(year, month, 1)
                          for year in range(2000, 2010)
                          for month in range(1, 13)])
        self.assertEqual(subset.lats.shape[0], 82)
        self.assertSequenceEqual(list(np.array(range(-81, 82, 2))),
                                 list(subset.lats))
        self.assertEqual(subset.lons.shape[0], 162)
        self.assertEqual(subset.values.shape, (120, 82, 162))
        self.assertEqual(subset.times.shape[0], 120)
        np.testing.assert_array_equal(subset.times, times)

class TestSafeSubset(unittest.TestCase):

    def setUp(self):
        lats = np.array(range(-60, 61, 1))
        lons = np.array(range(-170, 171, 1))
        times = np.array([datetime.datetime(year, month, 1)
                          for year in range(2000, 2010)
                          for month in range(1, 13)])
        values = np.ones([len(times), len(lats), len(lons)])
        self.target_dataset = ds.Dataset(lats,
                                         lons,
                                         times,
                                         values,
                                         variable="test variable name",
                                         units='test variable units',
                                         name='foo')

        self.spatial_out_of_bounds = ds.Bounds(
            lat_min=-65, lat_max=65,
            lon_min=-180, lon_max=180,
            start=datetime.datetime(2001, 1, 1),
            end=datetime.datetime(2004, 1, 1)
        )

        self.temporal_out_of_bounds = ds.Bounds(
            lat_min=-40, lat_max=40,
            lon_min=-160.25, lon_max=160.5,
            start=datetime.datetime(1999, 1, 15),
            end=datetime.datetime(2222, 2, 15)
        )

        self.everything_out_of_bounds = ds.Bounds(
            lat_min=-65, lat_max=65,
            lon_min=-180, lon_max=180,
            start=datetime.datetime(1999, 1, 15),
            end=datetime.datetime(2222, 2, 15)
        )

    def test_partial_spatial_overlap(self):
        '''Ensure that safe_subset can handle out of bounds spatial values'''
        ds = dp.safe_subset(self.target_dataset, self.spatial_out_of_bounds)
        spatial_bounds = ds.spatial_boundaries()
        self.assertEquals(spatial_bounds[0], -60)
        self.assertEquals(spatial_bounds[1], 60)
        self.assertEquals(spatial_bounds[2], -170)
        self.assertEquals(spatial_bounds[3], 170)

    def test_partial_temporal_overlap(self):
        '''Ensure that safe_subset can handle out of bounds temporal values'''
        ds = dp.safe_subset(self.target_dataset, self.temporal_out_of_bounds)
        temporal_bounds = ds.temporal_boundaries()
        start = datetime.datetime(2000, 1, 1)
        end = datetime.datetime(2009, 12, 1)

        self.assertEquals(temporal_bounds[0], start)
        self.assertEquals(temporal_bounds[1], end)

    def test_entire_bounds_overlap(self):
        ds = dp.safe_subset(self.target_dataset, self.everything_out_of_bounds)
        spatial_bounds = ds.spatial_boundaries()
        temporal_bounds = ds.temporal_boundaries()
        start = datetime.datetime(2000, 1, 1)
        end = datetime.datetime(2009, 12, 1)

        self.assertEquals(spatial_bounds[0], -60)
        self.assertEquals(spatial_bounds[1], 60)
        self.assertEquals(spatial_bounds[2], -170)
        self.assertEquals(spatial_bounds[3], 170)
        self.assertEquals(temporal_bounds[0], start)
        self.assertEquals(temporal_bounds[1], end)

class TestFailingSubset(unittest.TestCase):

    def setUp(self):
        self.target_dataset = ten_year_monthly_dataset()
        self.target_dataset.lats = np.array(range(-89, 88, 2))
        self.target_dataset.lons = np.array(range(-179, 178, 2))

        self.subregion = ds.Bounds(
            lat_min=-81, lat_max=81,
            lon_min=-161, lon_max=161,
            start=datetime.datetime(2001, 1, 1),
            end=datetime.datetime(2004, 1, 1)
        )

    def test_out_of_dataset_bounds_lat_min(self):
        self.subregion.lat_max = -90
        with self.assertRaises(ValueError):
            dp.subset(self.target_dataset, self.subregion)

    def test_out_of_dataset_bounds_lat_max(self):
        self.subregion.lat_min = 90
        with self.assertRaises(ValueError):
            dp.subset(self.target_dataset, self.subregion)

    def test_out_of_dataset_bounds_lon_min(self):
        self.subregion.lon_max = -180
        with self.assertRaises(ValueError):
            dp.subset(self.target_dataset, self.subregion)

    def test_out_of_dataset_bounds_lon_max(self):
        self.subregion.lon_min = 180
        with self.assertRaises(ValueError):
            dp.subset(self.target_dataset, self.subregion)

    def test_out_of_dataset_bounds_start(self):
        self.subregion.start = datetime.datetime(1999, 1, 1)
        with self.assertRaises(ValueError):
            dp.subset(self.target_dataset, self.subregion)

    def test_out_of_dataset_bounds_end(self):
        self.subregion.end = datetime.datetime(2011, 1, 1)
        with self.assertRaises(ValueError):
            dp.subset(self.target_dataset, self.subregion)

class TestNetCDFWrite(unittest.TestCase):

    def setUp(self):
        self.ds = ten_year_monthly_dataset()
        self.ds_2d = ten_year_monthly_dataset(latlon2d=True)
        self.file_name = 'test.nc'

    def tearDown(self):
        if os.path.isfile(self.file_name):
            os.remove(self.file_name)

    def test_file_write(self):
        dp.write_netcdf(self.ds, self.file_name)
        self.assertTrue(os.path.isfile(self.file_name))

    def test_file_write_2d(self):
        dp.write_netcdf(self.ds_2d, self.file_name)
        self.assertTrue(os.path.isfile(self.file_name))

    def test_file_write(self):
        dp.write_netcdf(self.ds, self.file_name)
        self.assertTrue(os.path.isfile(self.file_name))

    def test_that_file_contents_are_valid(self):
        dp.write_netcdf(self.ds, self.file_name)
        new_ds = local.load_file(self.file_name, self.ds.variable)

        self.assertEqual(self.ds.variable, new_ds.variable)
        np.testing.assert_array_equal(self.ds.lats, new_ds.lats)
        np.testing.assert_array_equal(self.ds.lons, new_ds.lons)
        np.testing.assert_array_equal(self.ds.times, new_ds.times)
        np.testing.assert_array_equal(self.ds.values, new_ds.values)

def ten_year_monthly_dataset(latlon2d=False):
    lats = np.array(range(-89, 90, 2))
    lons = np.array(range(-179, 180, 2))
    # Need separate variable for input lats / lons because dataset only
    # makes shallow copies of them.
    ilats, ilons = lats, lons
    # For testing 2D lat lon grids
    if latlon2d:
        lons2, lats2 = np.meshgrid(lons, lats)
        ilats, ilons = lats2, lons2
    # Ten Years of monthly data
    times = np.array([datetime.datetime(year, month, 1)
                      for year in range(2000, 2010) for month in range(1, 13)])
    values = np.ones([len(times), len(lats), len(lons)])
    input_dataset = ds.Dataset(ilats,
                               ilons,
                               times,
                               values,
                               variable="test variable name",
                               units='test variable units',
                               name='foo')
    return input_dataset

def ten_year_monthly_15th_dataset():
    lats = np.array(range(-89, 90, 2))
    lons = np.array(range(-179, 180, 2))
    # Ten Years of monthly 15th data
    times = np.array([datetime.datetime(year, month, 15)
                      for year in range(2000, 2010) for month in range(1, 13)])
    values = np.ones([len(times), len(lats), len(lons)])
    input_dataset = ds.Dataset(lats,
                               lons,
                               times,
                               values,
                               variable="test variable name",
                               units='test variable units')
    return input_dataset

def two_year_daily_dataset():
    lats = np.array(range(-89, 90, 2))
    lons = np.array(range(-179, 180, 2))
    times = np.array([datetime.datetime(2001, 1, 1) +
                      datetime.timedelta(days=d) for d in range(730)])
    values = np.ones([len(times), len(lats), len(lons)])
    dataset = ds.Dataset(lats, lons, times, values,
                         variable='random data', units='test variable units')
    return dataset

def two_year_daily_2hr_dataset():
    lats = np.array(range(-89, 90, 2))
    lons = np.array(range(-179, 180, 2))
    times = np.array([datetime.datetime(2001, 1, 1) +
                      datetime.timedelta(days=d, hours=2) for d in range(730)])
    values = np.ones([len(times), len(lats), len(lons)])
    dataset = ds.Dataset(lats, lons, times, values,
                         variable='random data', units='test variable units')
    return dataset

def build_ten_cube_dataset(value):
    lats = np.array(range(-89, 90, 18))
    lons = np.array(range(-179, 180, 36))
    times = np.array([datetime.datetime(year, 1, 1)
                      for year in range(2000, 2010)])
    values = np.ones([len(times), len(lats), len(lons)])
    values = values * value
    dataset = ds.Dataset(lats, lons, times, values)
    return dataset

if __name__ == '__main__':
    unittest.main()


text:
#ifndef __btkSeparateKnownVirtualMarkersFilter_h
#define __btkSeparateKnownVirtualMarkersFilter_h

#include "btkProcessObject.h"
#include "btkPointCollection.h"

namespace btk
{
  class SeparateKnownVirtualMarkersFilter : public ProcessObject
  {
  public:
    enum {AllMarkers = 4, Markers = 0, VirtualReferenceFrames = 1, VirtualMarkers = 2, OtherPoints = 3};

    struct StringAxes
    {
      StringAxes(const std::string& o = "", const std::string& a1 = "", const std::string& a2 = "", const std::string& a3 = "")
      : Origin(o), Axis1(a1), Axis2(a2), Axis3(a3)
      {};

      friend bool operator==(const StringAxes& lhs, const StringAxes& rhs)
      {
        if ((lhs.Origin.compare(rhs.Origin) == 0)
            && (lhs.Axis1.compare(rhs.Axis1) == 0)
            && (lhs.Axis2.compare(rhs.Axis2) == 0)
            && (lhs.Axis3.compare(rhs.Axis3) == 0))
          return true;
        return false;
      };

      std::string Origin;
      std::string Axis1;
      std::string Axis2;
      std::string Axis3;
    };

    typedef btkSharedPtr<SeparateKnownVirtualMarkersFilter> Pointer;
    typedef btkSharedPtr<const SeparateKnownVirtualMarkersFilter> ConstPointer;

    static Pointer New() {return Pointer(new SeparateKnownVirtualMarkersFilter());};

    // ~SeparateKnownVirtualMarkersFilter(); // Implicit

    PointCollection::Pointer GetInput() {return this->GetInput(0);};
    void SetInput(PointCollection::Pointer input) {this->SetNthInput(0, input);};
    PointCollection::Pointer GetOutput(int idx) {return static_pointer_cast<PointCollection>(this->GetNthOutput(idx));};

    void AppendVirtualReferenceFrame(const std::string& o, const std::string& a1, const std::string& a2, const std::string& a3) {this->AppendVirtualReferenceFrame(StringAxes(o,a1,a2,a3));};
    BTK_BASICFILTERS_EXPORT void AppendVirtualReferenceFrame(const StringAxes& label);
    BTK_BASICFILTERS_EXPORT void AppendVirtualReferenceFrames(const std::list<StringAxes>& labels);
    BTK_BASICFILTERS_EXPORT void SetVirtualReferenceFrames(const std::list<StringAxes>& labels);
    const std::list<StringAxes>& GetVirtualReferenceFrames() const {return this->m_VirtualReferenceFrames;};

    BTK_BASICFILTERS_EXPORT void AppendVirtualMarker(const std::string& label);
    BTK_BASICFILTERS_EXPORT void AppendVirtualMarkers(const std::list<std::string>& labels);
    BTK_BASICFILTERS_EXPORT void SetVirtualMarkers(const std::list<std::string>& labels);
    const std::list<std::string>& GetVirtualMarkers() const {return this->m_VirtualMarkers;};

    BTK_BASICFILTERS_EXPORT void ResetDefinitions();

    BTK_BASICFILTERS_EXPORT void SetLabelPrefix(const std::string& prefix);
    const std::string& GetLabelPrefix() const {return this->m_Prefix;};

  protected:
    BTK_BASICFILTERS_EXPORT SeparateKnownVirtualMarkersFilter();

    PointCollection::Pointer GetInput(int idx) {return static_pointer_cast<PointCollection>(this->GetNthInput(idx));};
    BTK_BASICFILTERS_EXPORT virtual DataObject::Pointer MakeOutput(int idx);
    BTK_BASICFILTERS_EXPORT virtual void GenerateData();

  private:
    BTK_BASICFILTERS_EXPORT bool FindLabel(std::list<std::string>* references, const std::string& l, bool usePrefix) const;
    BTK_BASICFILTERS_EXPORT PointCollection::ConstIterator FindLabel(PointCollection* references, const std::string& l, bool usePrefix) const;

    SeparateKnownVirtualMarkersFilter(const SeparateKnownVirtualMarkersFilter& ); // Not implemented.
    SeparateKnownVirtualMarkersFilter& operator=(const SeparateKnownVirtualMarkersFilter& ); // Not implemented.

    std::list<StringAxes> m_VirtualReferenceFrames;
    std::list<std::string> m_VirtualMarkers;
    std::string m_Prefix;
  };
};

#endif // __btkSeparateKnownVirtualMarkersFilter_h