text:
<?php

namespace SMW\Tests\MediaWiki\Search;

use SMW\ApplicationFactory;
use SMW\MediaWiki\Search\Search;
use SMWQuery;

/**
 * @covers \SMW\MediaWiki\Search\Search
 * @group semantic-mediawiki
 *
 * @license GNU GPL v2+
 * @since 2.1
 *
 * @author Stephan Gambke
 */
class SearchTest extends \PHPUnit_Framework_TestCase {

	protected function tearDown() {
		ApplicationFactory::clear();

		parent::tearDown();
	}

	public function testCanConstruct() {

		$this->assertInstanceOf(
			'\SMW\MediaWiki\Search\Search',
			new Search()
		);
	}

	public function testGetDefaultDBConnection() {

		$search = new Search();

		$this->assertInstanceOf(
			'DatabaseBase',
			$search->getDB()
		);
	}

	public function testSetGetDBConnection() {

		$dbMock = $this->getMockBuilder( 'DatabaseBase' )
			->disableOriginalConstructor()
			->getMockForAbstractClass();

		$search = new Search();
		$search->setDB( $dbMock );

		$this->assertEquals( $dbMock, $search->getDB() );
	}

	public function testGetDefaultFallbackSearchEngineForNullFallbackSearchType() {

		$dbMock = $this->getMockBuilder( '\DatabaseBase' )
			->disableOriginalConstructor()
			->setMethods( array( 'getSearchEngine' ) )
			->getMockForAbstractClass();

		$dbMock->expects( $this->once() )
			->method( 'getSearchEngine' )
			->will( $this->returnValue( 'SearchEngine' ) );

		ApplicationFactory::getInstance()->getSettings()->set( 'smwgFallbackSearchType', null );

		$search = new Search();
		$search->setDB( $dbMock );

		$this->assertInstanceOf(
			'SearchEngine',
			$search->getFallbackSearchEngine()
		);
	}

	public function testInvalidFallbackSearchEngineThrowsException() {

		ApplicationFactory::getInstance()->getSettings()->set( 'smwgFallbackSearchType', 'InvalidFallbackSearchEngine' );

		$search = new Search();

		$this->setExpectedException( 'RuntimeException' );
		$search->getFallbackSearchEngine();
	}

	public function testSetGetFallbackSearchEngine() {

		$searchEngine = $this->getMockBuilder( 'SearchEngine' )
			->disableOriginalConstructor()
			->getMock();

		$search = new Search();
		$search->setFallbackSearchEngine( $searchEngine );

		$this->assertEquals(
			$searchEngine,
			$search->getFallbackSearchEngine()
		);
	}

	public function testSearchTitle_withNonsemanticQuery() {

		$term = 'Some string that can not be interpreted as a semantic query';

		$searchResultSet = $this->getMockBuilder( 'SearchResultSet' )
			->disableOriginalConstructor()
			->getMock();

		$searchEngine = $this->getMockBuilder( 'SearchEngine' )
			->disableOriginalConstructor()
			->getMock();

		$searchEngine->expects( $this->once() )
			->method( 'transformSearchTerm' )
			->will( $this->returnArgument( 0 ) );

		$searchEngine->expects( $this->once() )
			->method( 'replacePrefixes' )
			->will( $this->returnArgument( 0 ) );

		$searchEngine->expects( $this->once() )
			->method( 'searchTitle')
			->will( $this->returnValueMap( array( array( $term, $searchResultSet ) ) ) );

		$search = new Search();
		$search->setFallbackSearchEngine( $searchEngine );

		$this->assertEquals(
			$searchResultSet,
			$search->searchTitle( $term )
		);
	}

	public function testSearchTitle_withEmptyQuery() {

		$term = '   ';

		$searchResultSet = $this->getMockBuilder( 'SearchResultSet' )
			->disableOriginalConstructor()
			->getMock();

		$searchEngine = $this->getMockBuilder( 'SearchEngine' )
			->disableOriginalConstructor()
			->getMock();

		$searchEngine->expects( $this->once() )
			->method( 'transformSearchTerm' )
			->will( $this->returnArgument( 0 ) );

		$searchEngine->expects( $this->once() )
			->method( 'replacePrefixes' )
			->will( $this->returnArgument( 0 ) );

		$searchEngine->expects( $this->once() )
			->method( 'searchTitle')
			->will( $this->returnValueMap( array( array( $term, $searchResultSet ) ) ) );

		$search = new Search();
		$search->setFallbackSearchEngine( $searchEngine );

		$this->assertEquals(
			$searchResultSet,
			$search->searchTitle( $term )
		);
	}

	public function testSearchTitle_withSemanticQuery() {

		$term = '[[Some string that can be interpreted as a semantic query]]';

		$queryResult = $this->getMockBuilder( '\SMWQueryResult' )
			->disableOriginalConstructor()
			->getMock();

		$store = $this->getMockBuilder( '\SMW\Store' )
			->disableOriginalConstructor()
			->getMockForAbstractClass();

		$store->expects( $this->exactly( 2 ) )
			->method( 'getQueryResult' )
			->will( $this->returnCallback( function ( SMWQuery $query ) use ( $queryResult ) {
				return $query->querymode === SMWQuery::MODE_COUNT ? 9001 : $queryResult;
			} ) );

		ApplicationFactory::getInstance()->registerObject( 'Store', $store );

		$search = new Search();
		$result = $search->searchTitle( $term );

		$this->assertInstanceOf(
			'SMW\MediaWiki\Search\SearchResultSet',
			$result
		);

		$this->assertEquals(
			9001,
			$result->getTotalHits()
		);
	}

	public function testSearchText_withNonsemanticQuery() {

		$term = 'Some string that can not be interpreted as a semantic query';

		$searchResultSet = $this->getMockBuilder( 'SearchResultSet' )
			->disableOriginalConstructor()
			->getMock();

		$searchEngine = $this->getMockBuilder( 'SearchEngine' )
			->disableOriginalConstructor()
			->getMock();

		$searchEngine->expects( $this->once() )
			->method( 'transformSearchTerm' )
			->will( $this->returnArgument( 0 ) );

		$searchEngine->expects( $this->once() )
			->method( 'replacePrefixes' )
			->will( $this->returnArgument( 0 ) );

		$searchEngine->expects( $this->once() )
			->method( 'searchText')
			->will( $this->returnValueMap( array( array( $term, $searchResultSet ) ) ) );

		$search = new Search();
		$search->setFallbackSearchEngine( $searchEngine );

		$this->assertEquals(
			$searchResultSet,
			$search->searchText( $term )
		);
	}

	public function testSearchText_withSemanticQuery() {

		$term = '[[Some string that can be interpreted as a semantic query]]';

		$search = new Search();

		$this->assertNull( $search->searchText( $term ) );
	}

	public function testSupports() {

		$searchEngine = $this->getMockBuilder( 'SearchEngine' )
			->disableOriginalConstructor()
			->getMock();

		$searchEngine->expects( $this->once() )
			->method( 'supports')
			->with( $this->equalTo( 'Some feature' ) )
			->will( $this->returnValueMap( array( array( 'Some feature', true ) ) ) );

		$search = new Search();
		$search->setFallbackSearchEngine( $searchEngine );

		$this->assertTrue( $search->supports( 'Some feature' ) );
	}

	public function testNormalizeText() {

		$searchEngine = $this->getMockBuilder( 'SearchEngine' )
			->disableOriginalConstructor()
			->getMock();

		$searchEngine->expects( $this->once() )
			->method( 'normalizeText')
			->with( $this->equalTo( 'Some text' ) )
			->will( $this->returnValueMap( array( array( 'Some text', 'Some normalized text' ) ) ) );

		$search = new Search();
		$search->setFallbackSearchEngine( $searchEngine );

		$this->assertEquals(
			'Some normalized text',
			$search->normalizeText( 'Some text' )
		);
	}

	public function testGetTextFromContent() {

		if ( ! method_exists( 'SearchEngine', 'getTextFromContent' ) ) {
			$this->markTestSkipped( 'SearchEngine::getTextFromContent() is undefined. Probably not yet present in the tested MW version.' );
		}

		$title = $this->getMockBuilder( 'Title' )
			->disableOriginalConstructor()
			->getMock();

		$content = $this->getMockBuilder( 'Content' )
			->disableOriginalConstructor()
			->getMockForAbstractClass();

		$searchEngine = $this->getMockBuilder( 'SearchEngine' )
			->disableOriginalConstructor()
			->getMock();

		$searchEngine->expects( $this->once() )
			->method( 'getTextFromContent')
			->with(
				$this->equalTo( $title ),
				$this->equalTo( $content ) )
			->will( $this->returnValueMap( array( array( $title, $content, 'text from content for title' ) ) ) );

		$search = new Search();
		$search->setFallbackSearchEngine( $searchEngine );

		$this->assertEquals(
			'text from content for title',
			$search->getTextFromContent( $title, $content )
		);
	}

	public function testTextAlreadyUpdatedForIndex() {

		if ( ! method_exists( 'SearchEngine', 'textAlreadyUpdatedForIndex' ) ) {
			$this->markTestSkipped( 'SearchEngine::textAlreadyUpdatedForIndex() is undefined. Probably not yet present in the tested MW version.' );
		}

		$searchEngine = $this->getMockBuilder( 'SearchEngine' )
			->disableOriginalConstructor()
			->getMock();

		$searchEngine->expects( $this->once() )
			->method( 'textAlreadyUpdatedForIndex')
			->with()
			->will( $this->returnValue( true ) );

		$search = new Search();
		$search->setFallbackSearchEngine( $searchEngine );

		$this->assertTrue( $search->textAlreadyUpdatedForIndex( 'Some text' ) );
	}

	public function testUpdate() {

		$searchEngine = $this->getMockBuilder( 'SearchEngine' )
			->disableOriginalConstructor()
			->getMock();

		$searchEngine->expects( $this->once() )
			->method( 'update')
			->with(
				$this->equalTo( 42 ),
				$this->equalTo( 'Some title' ),
				$this->equalTo( 'Some text' ) );

		$search = new Search();
		$search->setFallbackSearchEngine( $searchEngine );

		$search->update( 42, 'Some title', 'Some text' );
	}

	public function testUpdateTitle() {

		$searchEngine = $this->getMockBuilder( 'SearchEngine' )
			->disableOriginalConstructor()
			->getMock();

		$searchEngine->expects( $this->once() )
			->method( 'updateTitle')
			->with(
				$this->equalTo( 42 ),
				$this->equalTo( 'Some title' ) );

		$search = new Search();
		$search->setFallbackSearchEngine( $searchEngine );

		$search->updateTitle( 42, 'Some title' );
	}

	public function testDelete() {

		if ( ! method_exists( 'SearchEngine', 'delete' ) ) {
			$this->markTestSkipped( 'SearchEngine::delete() is undefined. Probably not yet present in the tested MW version.' );
		}

		$searchEngine = $this->getMockBuilder( 'SearchEngine' )
			->disableOriginalConstructor()
			->getMock();

		$searchEngine->expects( $this->once() )
			->method( 'delete')
			->with(
				$this->equalTo( 42 ),
				$this->equalTo( 'Some title' ) );

		$search = new Search();
		$search->setFallbackSearchEngine( $searchEngine );

		$search->delete( 42, 'Some title' );
	}

	public function testSetFeatureData() {

		if ( ! method_exists( 'SearchEngine', 'delete' ) ) {
			$this->markTestSkipped( 'SearchEngine::delete() is undefined. Probably not yet present in the tested MW version.' );
		}

		$searchEngine = $this->getMockBuilder( 'SearchEngine' )
			->disableOriginalConstructor()
			->getMock();

		$searchEngine->expects( $this->once() )
			->method( 'setFeatureData')
			->with(
				$this->equalTo( 'Some feature name' ),
				$this->equalTo( 'Some feature expression' ) );

		$search = new Search();
		$search->setFallbackSearchEngine( $searchEngine );
		$search->setFeatureData( 'Some feature name', 'Some feature expression' );

		$this->assertEquals(
			'Some feature expression',
			$search->getFeatureData( 'Some feature name' )
		);

		$this->assertNull( $search->getFeatureData( 'Some non-existent feature name' ) );
	}

	public function testReplacePrefixes() {

		$search = new Search();

		$this->assertEquals(
			'Some query',
			$search->replacePrefixes( 'Some query' )
		);
	}

	public function testTransformSearchTerm() {

		$search = new Search();

		$this->assertEquals(
			'Some query',
			$search->transformSearchTerm( 'Some query' )
		);
	}

	public function testSetLimitOffset() {

		$searchEngine = $this->getMockBuilder( 'SearchEngine' )
			->disableOriginalConstructor()
			->getMock();

		$searchEngine->expects( $this->once() )
			->method( 'setLimitOffset')
			->with(
				$this->equalTo( 9001 ),
				$this->equalTo( 42 ) );

		$search = new Search();
		$search->setFallbackSearchEngine( $searchEngine );

		$search->setLimitOffset( 9001, 42 );

		$this->assertEquals( 9001, $search->getLimit() );
		$this->assertEquals( 42, $search->getOffset() );
	}

	public function testSetNamespaces() {

		$searchEngine = $this->getMockBuilder( 'SearchEngine' )
			->disableOriginalConstructor()
			->getMock();

		$searchEngine->expects( $this->once() )
			->method( 'setNamespaces')
			->with( $this->equalTo( array( 1, 2, 3, 5, 8 ) ) );

		$search = new Search();
		$search->setFallbackSearchEngine( $searchEngine );
		$search->setNamespaces( array( 1, 2, 3, 5, 8 ) );

		$this->assertEquals(
			array( 1, 2, 3, 5, 8 ),
			$search->namespaces
		);
	}

	public function testSetShowSuggestion() {

		if ( ! method_exists( 'SearchEngine', 'setShowSuggestion' ) ) {
			$this->markTestSkipped( 'SearchEngine::setShowSuggestion() is undefined. Probably not yet present in the tested MW version.' );
		}

		$searchEngine = $this->getMockBuilder( 'SearchEngine' )
			->disableOriginalConstructor()
			->getMock();

		$searchEngine->expects( $this->once() )
			->method( 'setShowSuggestion')
			->with( $this->equalTo( true ) );

		$search = new Search();
		$search->setFallbackSearchEngine( $searchEngine );
		$search->setShowSuggestion( true );

		$this->assertTrue( $search->getShowSuggestion() );
	}

}


text:
// +build pkcs11

package pkcs11

import (
	"crypto/elliptic"
	"crypto/rand"
	"crypto/sha256"
	"encoding/asn1"
	"io/ioutil"
	"os"
	"strconv"
	"strings"
	"testing"
	"time"

	"github.com/hyperledger/fabric/bccsp"
	"github.com/hyperledger/fabric/bccsp/sw"
	"github.com/hyperledger/fabric/bccsp/utils"
	"github.com/miekg/pkcs11"
	"github.com/stretchr/testify/require"
)

func defaultOptions() PKCS11Opts {
	lib, pin, label := FindPKCS11Lib()
	return PKCS11Opts{
		Library:                 lib,
		Label:                   label,
		Pin:                     pin,
		Hash:                    "SHA2",
		Security:                256,
		SoftwareVerify:          false,
		createSessionRetryDelay: time.Millisecond,
	}
}

func newKeyStore(t *testing.T) (bccsp.KeyStore, func()) {
	tempDir, err := ioutil.TempDir("", "pkcs11_ks")
	require.NoError(t, err)
	ks, err := sw.NewFileBasedKeyStore(nil, tempDir, false)
	require.NoError(t, err)

	return ks, func() { os.RemoveAll(tempDir) }
}

func newProvider(t *testing.T, opts PKCS11Opts) (*Provider, func()) {
	ks, ksCleanup := newKeyStore(t)
	csp, err := New(opts, ks)
	require.NoError(t, err)

	cleanup := func() {
		csp.ctx.Destroy()
		ksCleanup()
	}
	return csp, cleanup
}

func TestNew(t *testing.T) {
	ks, cleanup := newKeyStore(t)
	defer cleanup()

	t.Run("DefaultConfig", func(t *testing.T) {
		opts := defaultOptions()
		opts.createSessionRetryDelay = 0

		csp, err := New(opts, ks)
		require.NoError(t, err)
		defer func() { csp.ctx.Destroy() }()

		curve, err := curveForSecurityLevel(opts.Security)
		require.NoError(t, err)

		require.NotNil(t, csp.BCCSP)
		require.Equal(t, opts.Pin, csp.pin)
		require.NotNil(t, csp.ctx)
		require.True(t, curve.Equal(csp.curve))
		require.Equal(t, opts.SoftwareVerify, csp.softVerify)
		require.Equal(t, opts.Immutable, csp.immutable)
		require.Equal(t, defaultCreateSessionRetries, csp.createSessionRetries)
		require.Equal(t, defaultCreateSessionRetryDelay, csp.createSessionRetryDelay)
		require.Equal(t, defaultSessionCacheSize, cap(csp.sessPool))
	})

	t.Run("ConditionalOverride", func(t *testing.T) {
		opts := defaultOptions()
		opts.createSessionRetries = 3
		opts.createSessionRetryDelay = time.Second
		opts.sessionCacheSize = -1

		csp, err := New(opts, ks)
		require.NoError(t, err)
		defer func() { csp.ctx.Destroy() }()

		require.Equal(t, 3, csp.createSessionRetries)
		require.Equal(t, time.Second, csp.createSessionRetryDelay)
		require.Nil(t, csp.sessPool)
	})
}

func TestInvalidNewParameter(t *testing.T) {
	ks, cleanup := newKeyStore(t)
	defer cleanup()

	t.Run("BadSecurityLevel", func(t *testing.T) {
		opts := defaultOptions()
		opts.Security = 0

		_, err := New(opts, ks)
		require.EqualError(t, err, "Failed initializing configuration: Security level not supported [0]")
	})

	t.Run("BadHashFamily", func(t *testing.T) {
		opts := defaultOptions()
		opts.Hash = "SHA8"

		_, err := New(opts, ks)
		require.EqualError(t, err, "Failed initializing fallback SW BCCSP: Failed initializing configuration at [256,SHA8]: Hash Family not supported [SHA8]")
	})

	t.Run("BadKeyStore", func(t *testing.T) {
		_, err := New(defaultOptions(), nil)
		require.EqualError(t, err, "Failed initializing fallback SW BCCSP: Invalid bccsp.KeyStore instance. It must be different from nil.")
	})

	t.Run("MissingLibrary", func(t *testing.T) {
		opts := defaultOptions()
		opts.Library = ""

		_, err := New(opts, ks)
		require.Error(t, err)
		require.Contains(t, err.Error(), "pkcs11: library path not provided")
	})
}

func TestFindPKCS11LibEnvVars(t *testing.T) {
	const (
		dummy_PKCS11_LIB   = "/usr/lib/pkcs11"
		dummy_PKCS11_PIN   = "23456789"
		dummy_PKCS11_LABEL = "testing"
	)

	// Set environment variables used for test and preserve
	// original values for restoration after test completion
	orig_PKCS11_LIB := os.Getenv("PKCS11_LIB")
	orig_PKCS11_PIN := os.Getenv("PKCS11_PIN")
	orig_PKCS11_LABEL := os.Getenv("PKCS11_LABEL")

	t.Run("ExplicitEnvironment", func(t *testing.T) {
		os.Setenv("PKCS11_LIB", dummy_PKCS11_LIB)
		os.Setenv("PKCS11_PIN", dummy_PKCS11_PIN)
		os.Setenv("PKCS11_LABEL", dummy_PKCS11_LABEL)

		lib, pin, label := FindPKCS11Lib()
		require.EqualValues(t, dummy_PKCS11_LIB, lib, "FindPKCS11Lib did not return expected library")
		require.EqualValues(t, dummy_PKCS11_PIN, pin, "FindPKCS11Lib did not return expected pin")
		require.EqualValues(t, dummy_PKCS11_LABEL, label, "FindPKCS11Lib did not return expected label")
	})

	t.Run("MissingEnvironment", func(t *testing.T) {
		os.Unsetenv("PKCS11_LIB")
		os.Unsetenv("PKCS11_PIN")
		os.Unsetenv("PKCS11_LABEL")

		_, pin, label := FindPKCS11Lib()
		require.EqualValues(t, "98765432", pin, "FindPKCS11Lib did not return expected pin")
		require.EqualValues(t, "ForFabric", label, "FindPKCS11Lib did not return expected label")
	})

	os.Setenv("PKCS11_LIB", orig_PKCS11_LIB)
	os.Setenv("PKCS11_PIN", orig_PKCS11_PIN)
	os.Setenv("PKCS11_LABEL", orig_PKCS11_LABEL)
}

func TestInvalidSKI(t *testing.T) {
	csp, cleanup := newProvider(t, defaultOptions())
	defer cleanup()

	_, err := csp.GetKey(nil)
	require.EqualError(t, err, "Failed getting key for SKI [[]]: invalid SKI. Cannot be of zero length")

	_, err = csp.GetKey([]byte{0, 1, 2, 3, 4, 5, 6})
	require.Error(t, err)
	require.True(t, strings.HasPrefix(err.Error(), "Failed getting key for SKI [[0 1 2 3 4 5 6]]: "))
}

func TestKeyGenECDSAOpts(t *testing.T) {
	tests := map[string]struct {
		curve     elliptic.Curve
		immutable bool
		opts      bccsp.KeyGenOpts
	}{
		"Default":             {elliptic.P256(), false, &bccsp.ECDSAKeyGenOpts{Temporary: false}},
		"P256":                {elliptic.P256(), false, &bccsp.ECDSAP256KeyGenOpts{Temporary: false}},
		"P384":                {elliptic.P384(), false, &bccsp.ECDSAP384KeyGenOpts{Temporary: false}},
		"Immutable":           {elliptic.P384(), true, &bccsp.ECDSAP384KeyGenOpts{Temporary: false}},
		"Ephemeral/Default":   {elliptic.P256(), false, &bccsp.ECDSAKeyGenOpts{Temporary: true}},
		"Ephemeral/P256":      {elliptic.P256(), false, &bccsp.ECDSAP256KeyGenOpts{Temporary: true}},
		"Ephemeral/P384":      {elliptic.P384(), false, &bccsp.ECDSAP384KeyGenOpts{Temporary: true}},
		"Ephemeral/Immutable": {elliptic.P384(), true, &bccsp.ECDSAP384KeyGenOpts{Temporary: false}},
	}
	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			opts := defaultOptions()
			opts.Immutable = tt.immutable
			csp, cleanup := newProvider(t, opts)
			defer cleanup()

			k, err := csp.KeyGen(tt.opts)
			require.NoError(t, err)
			require.True(t, k.Private(), "key should be private")
			require.False(t, k.Symmetric(), "key should be asymmetric")

			ecdsaKey := k.(*ecdsaPrivateKey).pub
			require.Equal(t, tt.curve, ecdsaKey.pub.Curve, "wrong curve")

			raw, err := k.Bytes()
			require.EqualError(t, err, "Not supported.")
			require.Empty(t, raw, "result should be empty")

			pk, err := k.PublicKey()
			require.NoError(t, err)
			require.NotNil(t, pk)

			sess, err := csp.getSession()
			require.NoError(t, err)
			defer csp.returnSession(sess)

			for _, kt := range []keyType{publicKeyType, privateKeyType} {
				handle, err := csp.findKeyPairFromSKI(sess, k.SKI(), kt)
				require.NoError(t, err)

				attr, err := csp.ctx.GetAttributeValue(sess, handle, []*pkcs11.Attribute{{Type: pkcs11.CKA_TOKEN}})
				require.NoError(t, err)
				require.Len(t, attr, 1)

				if tt.opts.Ephemeral() {
					require.Equal(t, []byte{0}, attr[0].Value)
				} else {
					require.Equal(t, []byte{1}, attr[0].Value)
				}

				attr, err = csp.ctx.GetAttributeValue(sess, handle, []*pkcs11.Attribute{{Type: pkcs11.CKA_MODIFIABLE}})
				require.NoError(t, err)
				require.Len(t, attr, 1)

				if tt.immutable {
					require.Equal(t, []byte{0}, attr[0].Value)
				} else {
					require.Equal(t, []byte{1}, attr[0].Value)
				}
			}
		})
	}
}

func TestKeyGenMissingOpts(t *testing.T) {
	csp, cleanup := newProvider(t, defaultOptions())
	defer cleanup()

	_, err := csp.KeyGen(bccsp.KeyGenOpts(nil))
	require.Error(t, err)
	require.Contains(t, err.Error(), "Invalid Opts parameter. It must not be nil")
}

func TestECDSAGetKeyBySKI(t *testing.T) {
	csp, cleanup := newProvider(t, defaultOptions())
	defer cleanup()

	k, err := csp.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
	require.NoError(t, err)

	k2, err := csp.GetKey(k.SKI())
	require.NoError(t, err)

	require.True(t, k2.Private(), "key should be private")
	require.False(t, k2.Symmetric(), "key should be asymmetric")
	require.Equalf(t, k.SKI(), k2.SKI(), "expected %x got %x", k.SKI(), k2.SKI())
}

func TestECDSAPublicKeyFromPrivateKey(t *testing.T) {
	csp, cleanup := newProvider(t, defaultOptions())
	defer cleanup()

	k, err := csp.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
	require.NoError(t, err)

	pk, err := k.PublicKey()
	require.NoError(t, err)
	require.False(t, pk.Private(), "key should be public")
	require.False(t, pk.Symmetric(), "key should be asymmetric")
	require.Equal(t, k.SKI(), pk.SKI(), "SKI should be the same")

	raw, err := pk.Bytes()
	require.NoError(t, err)
	require.NotEmpty(t, raw, "marshaled ECDSA public key must not be empty")
}

func TestECDSASign(t *testing.T) {
	csp, cleanup := newProvider(t, defaultOptions())
	defer cleanup()

	k, err := csp.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
	require.NoError(t, err)

	digest, err := csp.Hash([]byte("Hello World"), &bccsp.SHAOpts{})
	require.NoError(t, err)

	signature, err := csp.Sign(k, digest, nil)
	require.NoError(t, err)
	require.NotEmpty(t, signature, "signature must not be empty")

	t.Run("NoKey", func(t *testing.T) {
		_, err := csp.Sign(nil, digest, nil)
		require.Error(t, err)
		require.Contains(t, err.Error(), "Invalid Key. It must not be nil")
	})

	t.Run("BadSKI", func(t *testing.T) {
		_, err := csp.Sign(&ecdsaPrivateKey{ski: []byte("bad-ski")}, digest, nil)
		require.Error(t, err)
		require.Contains(t, err.Error(), "Private key not found")
	})

	t.Run("MissingDigest", func(t *testing.T) {
		_, err = csp.Sign(k, nil, nil)
		require.Error(t, err)
		require.Contains(t, err.Error(), "Invalid digest. Cannot be empty")
	})
}

func TestECDSAVerify(t *testing.T) {
	csp, cleanup := newProvider(t, defaultOptions())
	defer cleanup()

	k, err := csp.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
	require.NoError(t, err)
	pk, err := k.PublicKey()
	require.NoError(t, err)

	digest, err := csp.Hash([]byte("Hello, World."), &bccsp.SHAOpts{})
	require.NoError(t, err)
	otherDigest, err := csp.Hash([]byte("Bye, World."), &bccsp.SHAOpts{})
	require.NoError(t, err)

	signature, err := csp.Sign(k, digest, nil)
	require.NoError(t, err)

	tests := map[string]bool{
		"WithSoftVerify":    true,
		"WithoutSoftVerify": false,
	}
	for name, softVerify := range tests {
		t.Run(name, func(t *testing.T) {
			opts := defaultOptions()
			opts.SoftwareVerify = softVerify
			csp, cleanup := newProvider(t, opts)
			defer cleanup()

			valid, err := csp.Verify(k, signature, digest, nil)
			require.NoError(t, err)
			require.True(t, valid, "signature should be valid from private key")

			valid, err = csp.Verify(pk, signature, digest, nil)
			require.NoError(t, err)
			require.True(t, valid, "signature should be valid from public key")

			valid, err = csp.Verify(k, signature, otherDigest, nil)
			require.NoError(t, err)
			require.False(t, valid, "signature should be valid from private key")

			valid, err = csp.Verify(pk, signature, otherDigest, nil)
			require.NoError(t, err)
			require.False(t, valid, "signature should not be valid from public key")
		})
	}

	t.Run("MissingKey", func(t *testing.T) {
		_, err := csp.Verify(nil, signature, digest, nil)
		require.Error(t, err)
		require.Contains(t, err.Error(), "Invalid Key. It must not be nil")
	})

	t.Run("MissingSignature", func(t *testing.T) {
		_, err := csp.Verify(pk, nil, digest, nil)
		require.Error(t, err)
		require.Contains(t, err.Error(), "Invalid signature. Cannot be empty")
	})

	t.Run("MissingDigest", func(t *testing.T) {
		_, err = csp.Verify(pk, signature, nil, nil)
		require.Error(t, err)
		require.Contains(t, err.Error(), "Invalid digest. Cannot be empty")
	})
}

func TestECDSALowS(t *testing.T) {
	csp, cleanup := newProvider(t, defaultOptions())
	defer cleanup()

	k, err := csp.KeyGen(&bccsp.ECDSAKeyGenOpts{Temporary: false})
	require.NoError(t, err)

	digest, err := csp.Hash([]byte("Hello World"), &bccsp.SHAOpts{})
	require.NoError(t, err)

	// Ensure that signature with low-S are generated
	t.Run("GeneratesLowS", func(t *testing.T) {
		signature, err := csp.Sign(k, digest, nil)
		require.NoError(t, err)

		_, S, err := utils.UnmarshalECDSASignature(signature)
		require.NoError(t, err)

		if S.Cmp(utils.GetCurveHalfOrdersAt(k.(*ecdsaPrivateKey).pub.pub.Curve)) >= 0 {
			t.Fatal("Invalid signature. It must have low-S")
		}

		valid, err := csp.Verify(k, signature, digest, nil)
		require.NoError(t, err)
		require.True(t, valid, "signature should be valid")
	})

	// Ensure that signature with high-S are rejected.
	t.Run("RejectsHighS", func(t *testing.T) {
		for {
			R, S, err := csp.signP11ECDSA(k.SKI(), digest)
			require.NoError(t, err)
			if S.Cmp(utils.GetCurveHalfOrdersAt(k.(*ecdsaPrivateKey).pub.pub.Curve)) > 0 {
				sig, err := utils.MarshalECDSASignature(R, S)
				require.NoError(t, err)

				valid, err := csp.Verify(k, sig, digest, nil)
				require.Error(t, err, "verification must fail for a signature with high-S")
				require.False(t, valid, "signature must not be valid with high-S")
				return
			}
		}
	})
}

func TestInitialize(t *testing.T) {
	// Setup PKCS11 library and provide initial set of values
	lib, pin, label := FindPKCS11Lib()

	t.Run("MissingLibrary", func(t *testing.T) {
		_, err := (&Provider{}).initialize(PKCS11Opts{Library: "", Pin: pin, Label: label})
		require.Error(t, err)
		require.Contains(t, err.Error(), "pkcs11: library path not provided")
	})

	t.Run("BadLibraryPath", func(t *testing.T) {
		_, err := (&Provider{}).initialize(PKCS11Opts{Library: "badLib", Pin: pin, Label: label})
		require.Error(t, err)
		require.Contains(t, err.Error(), "pkcs11: instantiation failed for badLib")
	})

	t.Run("BadLabel", func(t *testing.T) {
		_, err := (&Provider{}).initialize(PKCS11Opts{Library: lib, Pin: pin, Label: "badLabel"})
		require.Error(t, err)
		require.Contains(t, err.Error(), "could not find token with label")
	})

	t.Run("MissingPin", func(t *testing.T) {
		_, err := (&Provider{}).initialize(PKCS11Opts{Library: lib, Pin: "", Label: label})
		require.Error(t, err)
		require.Contains(t, err.Error(), "Login failed: pkcs11")
	})
}

func TestNamedCurveFromOID(t *testing.T) {
	tests := map[string]struct {
		oid   asn1.ObjectIdentifier
		curve elliptic.Curve
	}{
		"P224":    {oidNamedCurveP224, elliptic.P224()},
		"P256":    {oidNamedCurveP256, elliptic.P256()},
		"P384":    {oidNamedCurveP384, elliptic.P384()},
		"P521":    {oidNamedCurveP521, elliptic.P521()},
		"unknown": {asn1.ObjectIdentifier{4, 9, 15, 1}, nil},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			require.Equal(t, tt.curve, namedCurveFromOID(tt.oid))
		})
	}
}

func TestCurveForSecurityLevel(t *testing.T) {
	tests := map[int]struct {
		expectedErr string
		curve       asn1.ObjectIdentifier
	}{
		256: {curve: oidNamedCurveP256},
		384: {curve: oidNamedCurveP384},
		512: {expectedErr: "Security level not supported [512]"},
	}

	for level, tt := range tests {
		t.Run(strconv.Itoa(level), func(t *testing.T) {
			curve, err := curveForSecurityLevel(level)
			if tt.expectedErr != "" {
				require.EqualError(t, err, tt.expectedErr)
				return
			}
			require.NoError(t, err)
			require.Equal(t, tt.curve, curve)
		})
	}
}

func TestPKCS11GetSession(t *testing.T) {
	opts := defaultOptions()
	opts.sessionCacheSize = 5
	csp, cleanup := newProvider(t, opts)
	defer cleanup()

	sessionCacheSize := opts.sessionCacheSize
	var sessions []pkcs11.SessionHandle
	for i := 0; i < 3*sessionCacheSize; i++ {
		session, err := csp.getSession()
		require.NoError(t, err)
		sessions = append(sessions, session)
	}

	// Return all sessions, should leave sessionCacheSize cached
	for _, session := range sessions {
		csp.returnSession(session)
	}

	// Should be able to get sessionCacheSize cached sessions
	sessions = nil
	for i := 0; i < sessionCacheSize; i++ {
		session, err := csp.getSession()
		require.NoError(t, err)
		sessions = append(sessions, session)
	}

	// Cleanup
	for _, session := range sessions {
		csp.returnSession(session)
	}
}

func TestSessionHandleCaching(t *testing.T) {
	verifyHandleCache := func(t *testing.T, csp *Provider, sess pkcs11.SessionHandle, k bccsp.Key) {
		pubHandle, err := csp.findKeyPairFromSKI(sess, k.SKI(), publicKeyType)
		require.NoError(t, err)
		h, ok := csp.cachedHandle(publicKeyType, k.SKI())
		require.True(t, ok)
		require.Equal(t, h, pubHandle)

		privHandle, err := csp.findKeyPairFromSKI(sess, k.SKI(), privateKeyType)
		require.NoError(t, err)
		h, ok = csp.cachedHandle(privateKeyType, k.SKI())
		require.True(t, ok)
		require.Equal(t, h, privHandle)
	}

	t.Run("SessionCacheDisabled", func(t *testing.T) {
		opts := defaultOptions()
		opts.sessionCacheSize = -1

		csp, cleanup := newProvider(t, opts)
		defer cleanup()

		require.Nil(t, csp.sessPool, "sessPool channel should be nil")
		require.Empty(t, csp.sessions, "sessions set should be empty")
		require.Empty(t, csp.handleCache, "handleCache should be empty")

		sess1, err := csp.getSession()
		require.NoError(t, err)
		require.Len(t, csp.sessions, 1, "expected one open session")

		sess2, err := csp.getSession()
		require.NoError(t, err)
		require.Len(t, csp.sessions, 2, "expected two open sessions")

		// Generate a key
		k, err := csp.KeyGen(&bccsp.ECDSAP256KeyGenOpts{Temporary: false})
		require.NoError(t, err)
		verifyHandleCache(t, csp, sess1, k)
		require.Len(t, csp.handleCache, 2, "expected two handles in handle cache")

		csp.returnSession(sess1)
		require.Len(t, csp.sessions, 1, "expected one open session")
		verifyHandleCache(t, csp, sess1, k)
		require.Len(t, csp.handleCache, 2, "expected two handles in handle cache")

		csp.returnSession(sess2)
		require.Empty(t, csp.sessions, "expected sessions to be empty")
		require.Empty(t, csp.handleCache, "expected handles to be cleared")
	})

	t.Run("SessionCacheEnabled", func(t *testing.T) {
		opts := defaultOptions()
		opts.sessionCacheSize = 1

		csp, cleanup := newProvider(t, opts)
		defer cleanup()

		require.NotNil(t, csp.sessPool, "sessPool channel should not be nil")
		require.Equal(t, 1, cap(csp.sessPool))
		require.Len(t, csp.sessions, 1, "sessions should contain login session")
		require.Len(t, csp.sessPool, 1, "sessionPool should hold login session")
		require.Empty(t, csp.handleCache, "handleCache should be empty")

		sess1, err := csp.getSession()
		require.NoError(t, err)
		require.Len(t, csp.sessions, 1, "expected one open session (sess1 from login)")
		require.Len(t, csp.sessPool, 0, "sessionPool should be empty")

		sess2, err := csp.getSession()
		require.NoError(t, err)
		require.Len(t, csp.sessions, 2, "expected two open sessions (sess1 and sess2)")
		require.Len(t, csp.sessPool, 0, "sessionPool should be empty")

		// Generate a key
		k, err := csp.KeyGen(&bccsp.ECDSAP256KeyGenOpts{Temporary: false})
		require.NoError(t, err)
		verifyHandleCache(t, csp, sess1, k)
		require.Len(t, csp.handleCache, 2, "expected two handles in handle cache")

		csp.returnSession(sess1)
		require.Len(t, csp.sessions, 2, "expected two open sessions (sess2 in-use, sess1 cached)")
		require.Len(t, csp.sessPool, 1, "sessionPool should have one handle (sess1)")
		verifyHandleCache(t, csp, sess1, k)
		require.Len(t, csp.handleCache, 2, "expected two handles in handle cache")

		csp.returnSession(sess2)
		require.Len(t, csp.sessions, 1, "expected one cached session (sess1)")
		require.Len(t, csp.sessPool, 1, "sessionPool should have one handle (sess1)")
		require.Len(t, csp.handleCache, 2, "expected two handles in handle cache")

		sess1, err = csp.getSession()
		require.NoError(t, err)
		require.Len(t, csp.sessions, 1, "expected one open session (sess1)")
		require.Len(t, csp.sessPool, 0, "sessionPool should be empty")
		require.Len(t, csp.handleCache, 2, "expected two handles in handle cache")
	})
}

func TestKeyCache(t *testing.T) {
	opts := defaultOptions()
	opts.sessionCacheSize = 1
	csp, cleanup := newProvider(t, opts)
	defer cleanup()

	require.Empty(t, csp.keyCache)

	_, err := csp.GetKey([]byte("nonsense-key"))
	require.Error(t, err) // message comes from software keystore
	require.Empty(t, csp.keyCache)

	k, err := csp.KeyGen(&bccsp.ECDSAP256KeyGenOpts{Temporary: false})
	require.NoError(t, err)
	_, ok := csp.cachedKey(k.SKI())
	require.False(t, ok, "created keys are not (currently) cached")

	key, err := csp.GetKey(k.SKI())
	require.NoError(t, err)
	cached, ok := csp.cachedKey(k.SKI())
	require.True(t, ok, "key should be cached")
	require.Same(t, key, cached, "key from cache should be what was found")

	// Retrieve last session
	sess, err := csp.getSession()
	require.NoError(t, err)
	require.Empty(t, csp.sessPool, "sessionPool should be empty")

	// Force caches to be cleared by closing last session
	csp.closeSession(sess)
	require.Empty(t, csp.sessions, "sessions should be empty")
	require.Empty(t, csp.keyCache, "key cache should be empty")

	_, ok = csp.cachedKey(k.SKI())
	require.False(t, ok, "key should not be in cache")
}

// This helps verify that we're delegating to the software provider.
// This is not intended to test the software provider implementation.
func TestDelegation(t *testing.T) {
	csp, cleanup := newProvider(t, defaultOptions())
	defer cleanup()

	k, err := csp.KeyGen(&bccsp.AES256KeyGenOpts{})
	require.NoError(t, err)

	t.Run("KeyGen", func(t *testing.T) {
		k, err := csp.KeyGen(&bccsp.AES256KeyGenOpts{})
		require.NoError(t, err)
		require.True(t, k.Private())
		require.True(t, k.Symmetric())
	})

	t.Run("KeyDeriv", func(t *testing.T) {
		k, err := csp.KeyDeriv(k, &bccsp.HMACDeriveKeyOpts{Arg: []byte{1}})
		require.NoError(t, err)
		require.True(t, k.Private())
	})

	t.Run("KeyImport", func(t *testing.T) {
		raw := make([]byte, 32)
		_, err := rand.Read(raw)
		require.NoError(t, err)

		k, err := csp.KeyImport(raw, &bccsp.AES256ImportKeyOpts{})
		require.NoError(t, err)
		require.True(t, k.Private())
	})

	t.Run("GetKey", func(t *testing.T) {
		k, err := csp.GetKey(k.SKI())
		require.NoError(t, err)
		require.True(t, k.Private())
	})

	t.Run("Hash", func(t *testing.T) {
		digest, err := csp.Hash([]byte("message"), &bccsp.SHA3_384Opts{})
		require.NoError(t, err)
		require.NotEmpty(t, digest)
	})

	t.Run("GetHash", func(t *testing.T) {
		h, err := csp.GetHash(&bccsp.SHA256Opts{})
		require.NoError(t, err)
		require.Equal(t, sha256.New(), h)
	})

	t.Run("Sign", func(t *testing.T) {
		_, err := csp.Sign(k, []byte("message"), nil)
		require.EqualError(t, err, "Unsupported 'SignKey' provided [*sw.aesPrivateKey]")
	})

	t.Run("Verify", func(t *testing.T) {
		_, err := csp.Verify(k, []byte("signature"), []byte("digest"), nil)
		require.Error(t, err)
		require.Contains(t, err.Error(), "Unsupported 'VerifyKey' provided")
	})

	t.Run("EncryptDecrypt", func(t *testing.T) {
		msg := []byte("message")
		ct, err := csp.Encrypt(k, msg, &bccsp.AESCBCPKCS7ModeOpts{})
		require.NoError(t, err)

		pt, err := csp.Decrypt(k, ct, &bccsp.AESCBCPKCS7ModeOpts{})
		require.NoError(t, err)
		require.Equal(t, msg, pt)
	})
}

func TestHandleSessionReturn(t *testing.T) {
	opts := defaultOptions()
	opts.sessionCacheSize = 5
	csp, cleanup := newProvider(t, opts)
	defer cleanup()

	// Retrieve and destroy default session created during initialization
	session, err := csp.getSession()
	require.NoError(t, err)
	csp.closeSession(session)

	// Verify session pool is empty and place invalid session in pool
	require.Empty(t, csp.sessPool, "sessionPool should be empty")
	csp.returnSession(pkcs11.SessionHandle(^uint(0)))

	// Attempt to generate key with invalid session
	_, err = csp.KeyGen(&bccsp.ECDSAP256KeyGenOpts{Temporary: false})
	require.EqualError(t, err, "Failed generating ECDSA P256 key: P11: keypair generate failed [pkcs11: 0xB3: CKR_SESSION_HANDLE_INVALID]")
	require.Empty(t, csp.sessPool, "sessionPool should be empty")
}

redpajama_set_name: RedPajamaGithub


text:
参考 <https://docs.docker.com/docker-for-mac/install/>

### 方法二 brew

```sh
brew cask install docker
```


text:
int x;

// entryFunction : Called by caller app at dll loadup, sets initial positions and object startup creation data
int entryFunction(int* val)
{
	x = *val;

	*val = x + 1; // Pass value to caller by reference example
	dllCallback(*val + 1); // Pass value to caller through callback function example
	return x; // Pass value to caller through function return value example
}

// update : Called by called app at every loop
bool update()
{
	return true;
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var operators_1 = require("rxjs/operators");
exports.buffer = operators_1.buffer;
//# sourceMappingURL=buffer.js.map


text:
<?php

namespace App\Http\Controllers\Backend\Swatch;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class SwatchController extends Controller
{
    //
}


text:
const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();

myEmitter.setMaxListeners(myEmitter.getMaxListeners() + 1);
myEmitter.once('event', () => {
  // do stuff
  console.log('Got an event');
  myEmitter.setMaxListeners(Math.max(myEmitter.getMaxListeners() - 1, 0));
});

myEmitter.emit('event');


text:
To design and realize software for management of a vehicle service station. Automobiles are repaired in the vehicle service station every day and repair cards, which contain information about the repairs performed, the input spare parts and labor are issued. There may be a multitude of repair cards for one automobile, and each of them corresponds to a repair performed. The system should provide various references related to the repairs performed.

#### Users
1. Users of the system are the operators who receive the customers in the vehicle service station and fill in information in the system. This information is shared amongst all the users but solely the user who created a certain repair card shall be entitled to edit it.

2. The following information is preserved for each user in the system:
 * username (it contains solely letters and digits, unique for the system)
 * password
 * name and surname
3. A special user with username "**admin**" and a preliminarily entered into the system password may add, edit and erase users. At erasure the users are deactivated, but remain in the system (aimed at not damaging the references).

4. Solely registered users (after login) and the administrator shall have access to the system.

#### Automobiles
1. The following information shall be maintained about each automobile:
 * State registration number (it should be obligatorily entered, for instance)
 * Brand
 * Model
 * Year of production
 * Number of frame – it should be obligatorily entered (it should be unique in the system)
 * Number of engine – it should be obligatorily entered
 * Color
 * Engine capacity (for instance, 500 cub. cm.)
 * Description (for other information)
 * Name of owner
 * Telephone for contact with the owner
2. The following operations shall be maintained for the automobiles (they may be performed by each operator):
 * Addition of an automobile– it is entered and the information about the automobile shall be stored.
 * Editing an automobile – it allows change of the information about a certain automobile

#### Spare parts
1. The spare parts have:
 * An identification number (a unique code in conformity with a catalogue)
 * Title (text name, for instance "a brake disc")
 * Price
2. Types of spare parts, which may be used at repairs of automobiles, are defined by the administrator. The thus already defined spare parts are used at the creation or editing a repair card.
3. The following operations (accessible solely for the administrator) shall be maintained for the spare parts:
 * Addition of a spare part.
 * Editing a spare part – it allows a change of the title or the price of a spare part already existing in the system.
 * Erasure of a spare part – it erases an already defined spare part. The erasure makes the part inactive and thus it may be included in the reference but it is not accessible at new repairs.

#### Employees (fitters)
The system should maintain a list with the employees in the vehicle service station (the fitters who perform the repairs). Each employee has a name and surname. The administrator may add / edit / erase fitters.


text:
package neural;

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Random;

public class NeuralUtils {

	private static Random random = new Random(400);

	public static double random() {
		return random.nextDouble();
	}

	public static double getRandomNeuronWeight() {
		return random() * 2 - 1;
	}

	public static String randomString(int length) {
		return randomString(length, 0, 256);
	}

	public static String randomString(int length, int charLow, int charHigh) {
		char[] ret = new char[length];
		for (int i = 0; i < length; i++) {
			ret[i] = (char) ((int) (random() * (charHigh - charLow)) + charLow);
		}
		return new String(ret);
	}

	public static double[] toArray(String s) {
		double[] ret = new double[s.length() * 8];
		feedString(s, ret);
		return ret;
	}

	public static String toString(double[] values) {
		char[] out = new char[values.length / 8];
		for (int i = 0; i < out.length; i++) {
			out[i] = (char) toInt(values, i * 8, (i + 1) * 8);
		}
		return new String(out);
	}

	public static double[] getRandomArray(int size, double lowBound, double highBound) {
		double[] ret = new double[size];
		for (int i = 0; i < size; i++) {
			ret[i] = random() * (highBound - lowBound) + lowBound;
		}
		return ret;
	}

	public static double[] getRandomBinaryArray(int size) {
		double[] ret = new double[size];
		for (int i = 0; i < size; i++) {
			if (random() < 0.5) {
				ret[i] = 1;
			}
		}
		return ret;
	}

	public static String compact(double value) {
		long l = Double.doubleToLongBits(value);
		String s = "";
		for (int i = 0; i < 8; i++) {
			s += (char) (l % 256);
			l /= 256;
		}
		return s;
	}

	public static void drawLine(Graphics g, int sx, int sy, int ex, int ey, double width) {
		if (width < 0.1) {
			return;
		}
		Graphics2D g2 = (Graphics2D) g;
		g2.setStroke(new BasicStroke((float) (width)));
		g2.drawLine(sx, sy, ex, ey);
	}

	public static String compact(int value) {
		String s = "";
		for (int i = 0; i < 4; i++) {
			s += (char) (value % 256);
			value /= 256;
		}
		return s;
	}

	public static double parseDouble(String compacted) {
		long l = 0;
		for (int i = 0; i < 8; i++) {
			l *= 256;
			l += compacted.charAt(7 - i);
		}
		return Double.longBitsToDouble(l);
	}

	public static int parseInt(String compacted) {
		int ret = 0;
		for (int i = 0; i < 4; i++) {
			ret *= 256;
			ret += compacted.charAt(3 - i);
		}
		return ret;
	}

	public static void feedChar(char c, double[] networkLayer) {
		feedChar(c, networkLayer, 0);
	}

	public static void feedChar(char c, double[] networkLayer, int startIndex) {
		int num = (int) c;
		for (int i = 0; i < 8; i++) {
			networkLayer[8 - i - 1 + startIndex] = num % 2;
			num /= 2;
		}
	}

	public static void feedString(String s, double[] networkLayer) {
		feedString(s, networkLayer, 0);
	}

	public static void feedString(String s, double[] networkLayer, int startIndex) {
		for (int i = 0; i < s.length(); i++) {
			feedChar(s.charAt(i), networkLayer, startIndex + i * 8);
		}
	}

	public static void feedInt(int num, double[] layer, int si, int ei) {
		for (int i = si; i < ei; i++) {
			layer[i] = num % 2;
			num /= 2;
		}
	}

	public static int toInt(double[] layer) {
		return toInt(layer, 0, layer.length);
	}

	public static int toInt(double[] layer, int si, int ei) {
		int ret = 0;
		for (int i = si; i < ei; i++) {
			ret *= 2;
			if (layer[i] >= 0.5) {
				ret++;
			}
		}
		return ret;
	}

	public static void feedInt(int num, double[] layer) {
		feedInt(num, layer, 0, layer.length);
	}

	/**
	 * Get all possible binary combinations of a given length.
	 *
	 * @templated
	 */
	public static double[][] getBinaryCombos(int length) {
		return getBinaryCombos(0, length, 0);
	}

	/**
	 * Get all possible binary combinations of a given length.
	 *
	 * @templated
	 */
	public static double[][] getBinaryCombos(int preSpace, int length, int postSpace) {
		double[][] ret = new double[(int) Math.pow(2, length)][preSpace + postSpace + length];
		for (int i = 1; i < ret.length; i++) {
			boolean carry = true;
			for (int j = preSpace; j < length + preSpace; j++) {
				if (carry) {
					ret[i][j] = 1 - ret[i - 1][j];
				} else {
					ret[i][j] = ret[i - 1][j];
				}
				if (ret[i][j] == 1) {
					carry = false;
				}
			}
		}
		return ret;
	}

	/**
	 * Prints the given int array.
	 *
	 * @templated
	 */
	public static void print(double[][] values) {
		System.out.println("-----------------");
		for (int i = 0; i < values.length; i++) {
			print(values[i]);
		}
	}

	/**
	 * Prints the given int array.
	 *
	 * @templated
	 */
	public static void print(double[] values) {
		for (int i = 0; i < values.length; i++) {
			if (i > 0) {
				System.out.print(", ");
			}
			System.out.print(values[i]);
		}
		System.out.println();
	}

	public static double toDouble(boolean value) {
		return value ? 0 : 1;
	}
}


text:
package conll;

import static org.junit.Assert.assertEquals;
import org.junit.*;
import java.util.Iterator;

public class SentenceTest {

	private Sentence sentence = null;
	private static String[] tokenLines = new String[] {	"1\tDaarvoor\tdaarvoor\tAdv\tAdv\tpron|aanw\t_\t_\t_\t_",
														"2\tis\tben\tV\tV\thulpofkopp|ott|3|ev\t_\t_\t_\t_",
														"3\tgekozen\tkies\tV\tV\ttrans|verldw|onverv\t_\t_\t_\t_",
														"4\tomdat\tomdat\tConj\tConj\tonder|metfin\t_\t_\t_\t_",
														"5\tgemeenten\tgemeente\tN\tN\tsoort|mv|neut\t_\t_\t_\t_"};

	@Before
	public void setUp() {
		sentence = new Sentence();
	}

	@Test
	public void stringRepresantation() {
		StringBuilder correct = new StringBuilder();
		for (String s : tokenLines) {
			sentence.addToken(new Token(s));
			correct.append(s).append("\n");
		}
		assertEquals("Wrong String representation.", correct.toString(), sentence.toString());
	}
	@Test
	public void stringOfEmptySentence() {
		assertEquals("Wrong String representation.", "", sentence.toString());
	}

	@Test
	public void setTokenIdsIncrementally() {
		sentence.addToken(Token.createEmptyToken());
		Token token = Token.createEmptyToken();
		token.setId(1);
		assertEquals("Wrong token id.", token.toString() + "\n", sentence.toString());
	}

	@Test
	public void iterateThroughTokens() {
		for (String s : tokenLines) {
			sentence.addToken(new Token(s));
		}
		Iterator<Token> it = sentence.getTokenIterator();
		int index = 0;
		while (it.hasNext()) {
			assertEquals("Wrong token id.", Integer.parseInt(tokenLines[index++].substring(0, 1)), it.next().getId());
		}
	}
}


text:
import { sortBy, ListIteratee } from 'lodash';

import {
  print,
  visit,
  DocumentNode,
  OperationDefinitionNode,
  SelectionSetNode,
  FieldNode,
  FragmentSpreadNode,
  InlineFragmentNode,
  FragmentDefinitionNode,
  DirectiveNode,
  IntValueNode,
  FloatValueNode,
  StringValueNode,
  ListValueNode,
  ObjectValueNode,
  separateOperations,
} from 'graphql';

// Replace numeric, string, list, and object literals with "empty"
// values. Leaves enums alone (since there's no consistent "zero" enum). This
// can help combine similar queries if you substitute values directly into
// queries rather than use GraphQL variables, and can hide sensitive data in
// your query (say, a hardcoded API key) from Engine servers, but in general
// avoiding those situations is better than working around them.
export function hideLiterals(ast: DocumentNode): DocumentNode {
  return visit(ast, {
    IntValue(node: IntValueNode): IntValueNode {
      return { ...node, value: '0' };
    },
    FloatValue(node: FloatValueNode): FloatValueNode {
      return { ...node, value: '0' };
    },
    StringValue(node: StringValueNode): StringValueNode {
      return { ...node, value: '', block: false };
    },
    ListValue(node: ListValueNode): ListValueNode {
      return { ...node, values: [] };
    },
    ObjectValue(node: ObjectValueNode): ObjectValueNode {
      return { ...node, fields: [] };
    },
  });
}

// A GraphQL query may contain multiple named operations, with the operation to
// use specified separately by the client. This transformation drops unused
// operations from the query, as well as any fragment definitions that are not
// referenced.  (In general we recommend that unused definitions are dropped on
// the client before sending to the server to save bandwidth and parsing time.)
export function dropUnusedDefinitions(
  ast: DocumentNode,
  operationName: string,
): DocumentNode {
  const separated = separateOperations(ast)[operationName];
  if (!separated) {
    // If the given operationName isn't found, just make this whole transform a
    // no-op instead of crashing.
    return ast;
  }
  return separated;
}

// Like lodash's sortBy, but sorted(undefined) === undefined rather than []. It
// is a stable non-in-place sort.
function sorted<T>(
  items: ReadonlyArray<T> | undefined,
  ...iteratees: Array<ListIteratee<T>>
): Array<T> | undefined {
  if (items) {
    return sortBy(items, ...iteratees);
  }
  return undefined;
}

// sortAST sorts most multi-child nodes alphabetically. Using this as part of
// your signature calculation function may make it easier to tell the difference
// between queries that are similar to each other, and if for some reason your
// GraphQL client generates query strings with elements in nondeterministic
// order, it can make sure the queries are treated as identical.
export function sortAST(ast: DocumentNode): DocumentNode {
  return visit(ast, {
    OperationDefinition(
      node: OperationDefinitionNode,
    ): OperationDefinitionNode {
      return {
        ...node,
        variableDefinitions: sorted(
          node.variableDefinitions,
          'variable.name.value',
        ),
      };
    },
    SelectionSet(node: SelectionSetNode): SelectionSetNode {
      return {
        ...node,
        // Define an ordering for field names in a SelectionSet.  Field first,
        // then FragmentSpread, then InlineFragment.  By a lovely coincidence,
        // the order we want them to appear in is alphabetical by node.kind.
        // Use sortBy instead of sorted because 'selections' is not optional.
        selections: sortBy(node.selections, 'kind', 'name.value'),
      };
    },
    Field(node: FieldNode): FieldNode {
      return {
        ...node,
        arguments: sorted(node.arguments, 'name.value'),
      };
    },
    FragmentSpread(node: FragmentSpreadNode): FragmentSpreadNode {
      return { ...node, directives: sorted(node.directives, 'name.value') };
    },
    InlineFragment(node: InlineFragmentNode): InlineFragmentNode {
      return { ...node, directives: sorted(node.directives, 'name.value') };
    },
    FragmentDefinition(node: FragmentDefinitionNode): FragmentDefinitionNode {
      return {
        ...node,
        directives: sorted(node.directives, 'name.value'),
        variableDefinitions: sorted(
          node.variableDefinitions,
          'variable.name.value',
        ),
      };
    },
    Directive(node: DirectiveNode): DirectiveNode {
      return { ...node, arguments: sorted(node.arguments, 'name.value') };
    },
  });
}

// removeAliases gets rid of GraphQL aliases, a feature by which you can tell a
// server to return a field's data under a different name from the field
// name. Maybe this is useful if somebody somewhere inserts random aliases into
// their queries.
export function removeAliases(ast: DocumentNode): DocumentNode {
  return visit(ast, {
    Field(node: FieldNode): FieldNode {
      return {
        ...node,
        alias: undefined,
      };
    },
  });
}

// Like the graphql-js print function, but deleting whitespace wherever
// feasible. Specifically, all whitespace (outside of string literals) is
// reduced to at most one space, and even that space is removed anywhere except
// for between two alphanumerics.
export function printWithReducedWhitespace(ast: DocumentNode): string {
  // In a GraphQL AST (which notably does not contain comments), the only place
  // where meaningful whitespace (or double quotes) can exist is in
  // StringNodes. So to print with reduced whitespace, we:
  // - temporarily sanitize strings by replacing their contents with hex
  // - use the default GraphQL printer
  // - minimize the whitespace with a simple regexp replacement
  // - convert strings back to their actual value
  // We normalize all strings to non-block strings for simplicity.

  const sanitizedAST = visit(ast, {
    StringValue(node: StringValueNode): StringValueNode {
      return {
        ...node,
        value: Buffer.from(node.value, 'utf8').toString('hex'),
        block: false,
      };
    },
  });
  const withWhitespace = print(sanitizedAST);
  const minimizedButStillHex = withWhitespace
    .replace(/\s+/g, ' ')
    .replace(/([^_a-zA-Z0-9]) /g, (_, c) => c)
    .replace(/ ([^_a-zA-Z0-9])/g, (_, c) => c);
  return minimizedButStillHex.replace(/"([a-f0-9]+)"/g, (_, hex) =>
    JSON.stringify(Buffer.from(hex, 'hex').toString('utf8')),
  );
}

// The default signature function consists of removing unused definitions
// and whitespace.
// XXX consider caching somehow
export function defaultSignature(
  ast: DocumentNode,
  operationName: string,
): string {
  return printWithReducedWhitespace(
    sortAST(
      removeAliases(hideLiterals(dropUnusedDefinitions(ast, operationName))),
    ),
  );
}


text:
#include <aws/pinpoint/model/RecencyType.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace Pinpoint
  {
    namespace Model
    {
      namespace RecencyTypeMapper
      {

        static const int ACTIVE_HASH = HashingUtils::HashString("ACTIVE");
        static const int INACTIVE_HASH = HashingUtils::HashString("INACTIVE");

        RecencyType GetRecencyTypeForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == ACTIVE_HASH)
          {
            return RecencyType::ACTIVE;
          }
          else if (hashCode == INACTIVE_HASH)
          {
            return RecencyType::INACTIVE;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<RecencyType>(hashCode);
          }

          return RecencyType::NOT_SET;
        }

        Aws::String GetNameForRecencyType(RecencyType enumValue)
        {
          switch(enumValue)
          {
          case RecencyType::ACTIVE:
            return "ACTIVE";
          case RecencyType::INACTIVE:
            return "INACTIVE";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace RecencyTypeMapper
    } // namespace Model
  } // namespace Pinpoint
} // namespace Aws


text:
package src.enigma.andrew.proxy;

public class ClientProxy extends CommonProxy {
    @Override
    public void preInit(){
        super.preInit();

    }

    @Override
    public void init(){
        super.init();

    }

    @Override
    public void postInit(){
        super.postInit();

    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('books', '0003_book_category'),
    ]

    operations = [
        migrations.CreateModel(
            name='Tag',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=100)),
            ],
        ),
    ]


text:
var React = require('react');///addons

var PhotoSwipe = require('react-photoswipe').PhotoSwipe;
				 require('react-photoswipe/lib/photoswipe.css');

var Slider = require('../Slider');

require('./index.css');

module.exports = React.createClass({

	displayName: "SliderPopup",

	getInitialState: function(){

		return	{

			showGallery : false,
			galleryIndex : 0
		}
	},
/*

	clickSlide: function(index){

		var self = this;

		return function(e){

			if(self.props.onClickSlide) self.props.onClickSlide(index,e);
		}
	},*/

	showGallery: function(e){//index, e

		e.preventDefault();
		e.stopPropagation();
		/*
		e.preventDefault();
		e.stopPropagation();

		console.log("showGallery",index);

		this.setState({
			showGallery : true,
			galleryIndex: index
		});*/

		this.setState({ showGallery : true });
	},

	hideGallery: function(){

		this.setState({ showGallery : false });
	},

	render: function () {

		var self = this;
/*
		var hideCaption = this.props.hideCaption;
		var fixedHeight = this.props.fixedHeight;
		var className = this.props.className ? this.props.className : '';
		var imgSize = this.props.imgSize ? this.props.imgSize : 'full';
*/

/*
<SliderPopup items={WPContext.post.meta.galeria} className="SinglePack__carousel" fixedHeight={true} hideCaption={true} />

						<PhotoSwipe isOpen={this.state.showGallery} items={galleryItems} options={{index : this.state.galleryIndex}} onClose={this.hideGallery} />
*/

		var galleryItems = this.props.items.map(function(item){

			return {
			    src: item.sizes.full.url,
			    w: 0,//item.sizes.full.width,
			    h: 0,//item.sizes.full.height,
			    title: item.title,
			    //thumbnail: item.sizes[thumbnailSize]
			}
		});

		var options = {

			index : this.state.galleryIndex,
			history: false,
			//showAnimationDuration: 0,
			//hideAnimationDuration: 0,
			focus: false,
			zoomEl: true
		}

		return (

					<Slider {...this.props} activeIndex={0} noLinks/>

				<PhotoSwipe isOpen={this.state.showGallery} items={galleryItems} options={options} onClose={this.hideGallery} imageLoadComplete={function(instance, index, item){

					//# fix unknown width & height

					if(item.html === undefined && item.onloading === undefined && (item.w < 1 || item.h < 1)) {
					//if (item.w < 1 || item.h < 1) { // unknown size

				        var img = new Image();

				        img.onload = function() { // will get size after load

					        item.w = this.width; // set image width
					        item.h = this.height; // set image height
				           instance.invalidateCurrItems(); // reinit Items
				           instance.updateSize(true); // reinit Items
				        }
				    	img.src = item.src; // let's download image
				    }

				}}/>

		)
	}
});


text:
The class [Albatross.Expression.Parser](xref:Albatross.Expression.Parser) implements interface [Albatross.Expression.IParser](xref:Albatross.Expression.IParser).  It performs the function of processing, evaluating and generating of expressions.

## Design
The [Parser](xref:Albatross.Expression.Parser) class parses the expression by
1. Tokenize the text
1. Build a stack
1. Create a token tree

Once the token tree is created, the parser can evaluate the result of the expression by evaluating the tree nodes recursively.

The implementation of the design supports the following functionalties:
* Tokens
    * String Literal - `"yes"`
    * Numeric Literal - `100 + 4.0`
        * The [NumericLiteralToken](xref:Albatross.Expression.Tokens.NumericLiteralToken) class handles number and it converts all numeric value to C# type `System.Double`.
    * Variable - `a + 4`
    * Parantheses - `4 * (1 + 2)`
* Infix operation - Operations with two operands and a operator in the middle: `1 + 2`
    * operation precedence
* unary operation - Negative sign: `-1`
* prefix operation - Functions with fixed or optional parameter and a return value: `Now(), Left("Orange", 4)`
* unlimited optional function parameters - `max(1,2,3,4,5)`
* Array - Array is a special function that returns an array object: `@(1, 2, 3, 4, 5)`

## Tokenization
Tokenization reads the expression from left to right.  Its function is to recognize individual components (tokens) of an expression.  This step will throw [TokenParsingException](xref:Albatross.Expression.Exceptions.TokenParsingException) if the expression has errors.  The resulting tokens are inserted into a queue.  The implementation is in the [Tokenize](xref:Albatross.Expression.Parser.Tokenize(System.String)) method of the [Parser](xref:Albatross.Expression.Parser) class.

Here are some examples:
* Expression: `4 + 5 * 6 - max(7, 1)`
    * `4`
    * `+`
    * `5`
    * `*`
    * `6`
    * `-`
    * `max`
    * `(`
    * `7`
    * `,`
    * `1`
    * `)`
* Expression: `if (a > b, "Yes", "No")`
    * `if`
    * `(`
    * `a`
    * `>`
    * `b`
    * `,`
    * `"Yes"`
    * `,`
    * `"No"`
    * `)`

Notice that comma and parentheses are considered as control tokens but the string boundary (double quote) are not.  String boundaries are part of the string token and will be stripped and disgarded by the [StringLiteralToken](xref:Albatross.Expression.Tokens.StringLiteralToken) class during the evaluation process.

## Create a Stack
This step converts the tokenized queue into a postfix stack using the [Shunting-yard algorithm](https://en.wikipedia.org/wiki/Shunting-yard_algorithm).  The implementation is in the [BuildStack](xref:Albatross.Expression.Parser.BuildStack(System.Collections.Generic.Queue{Albatross.Expression.Tokens.IToken})) method of the [Parser](xref:Albatross.Expression.Parser) class.  A postfix stack is also called a [Reverse polish notion](https://en.wikipedia.org/wiki/Reverse_Polish_notation).

Here are the top popping stack for the example above:
* Expression: `4 + 5 * 6 - max(7, 1)`
    * `-`
	* `max`
	* `1`
	* `7`
	* `$`
	* `+`
	* `*`
	* `6`
	* `5`
	* `4`
* Expression: `if (a > b, "Yes", "No")`
	* `If`
	* `"No"`
	* `"Yes"`
	* `>`
	* `b`
	* `a`
	* `$`
* Expression: `Format(Today(), "yyyy-MM-DD")`
	* `Format`
	* `"yyyy-MM-DD"`
	* `Today`
	* `$`
	* `$`

A special control token `$` is used to indicate the end of parameters for prefix operations.  This allows functions with unknown number of optional parameters.  It also simplify the tree creation logic because it doesn't need to know how many parameters the prefix function has.

## Create a Tree
This step is to create a tree from the postfix stack.  The process of converting a stack to a tree is the same process of evaluating (popping) the postfix stack.  The tree is created so that the expression can be evaluated multiple times without rebuilding the stack.  The result object is of type [IToken](xref:Albatross.Expression.Tokens.IToken).

Here are the trees for the example above:

* Expression: `4 + 5 * 6 - max(7, 1)`
	* `-`
		* `+`
			* `4`
			* `*`
				* `5`
				* `6`
		* `max`
			* `7`
			* `1`
* Expression: `if (a > b, "Yes", "No")`
	* `If`
		* `>`
			* `a`
			* `b`
		* `"Yes"`
		* `"No"`
* Expression: `Format(Today(), "yyyy-MM-DD")`
	* `Format`
		* `Today`
		* `"yyyy-MM-DD"`

## Evaluate a tree
With a tree built, the evaluation process is a simple recursive call to the [EvalValue](xref:Albatross.Expression.Tokens.IToken.EvalValue(System.Func{System.String,System.Object})) function of the [IToken](xref:Albatross.Expression.Tokens.IToken) interface.

## Regenerate the expression
Using the same [IToken](xref:Albatross.Expression.Tokens.IToken) object, the parser can regenerate the original expression or convert it to an expression of different format by calling the [EvalText](xref:Albatross.Expression.Tokens.IToken.EvalText(System.String)) method.  The default EvalText method will produce an expression string with equal functionality as the original with consistent spacing and mininum usage of parantheses.  For example: if the original expression is `1+(2*3)`, the regenerated expression will be: `1 + 2 * 3`.

## Use of variable in an expression
When evaluating expressions with variables, the [EvalValue](xref:Albatross.Expression.Tokens.IToken.EvalValue(System.Func{System.String,System.Object})) has a second parameter of type `Func<object, string>` that can be used to return the value of a variable. Here is an example:
```csharp
[TestCase("a + b * c", ExpectedResult = 7)]
[TestCase("a + b + c", ExpectedResult =6)]
public object Run(string expression) {
	Func<string, object> func = name => {
		switch (name.ToLower()) {
			case "a":
				return 1;
			case "b":
				return 2;
			case "c":
				return 3;
			default:
				return null;
		}
	};
	IParser parser = Factory.Instance.Create();
	return parser.Compile(expression).EvalValue(func);
}
```


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="Parallax One Pager" content="">
    <meta name="Nishant Srivastava" content="">

    <title>Parallax One Pager</title>

    <link rel="icon" type="image/png" href="favicon.ico">

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/scrolling-nav.css" rel="stylesheet">

    <link href="css/style.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                    Toggle navigation

                </button>
                Parallax One Pager

                        Contentment

                        Curiosity

                        Happiness

                        Satisfaction

                        Zeal

                        Desire

Parallax One Pager

                        Dive into the
                    colors of emotions

                    Click to scroll down

                        You must take personal responsibility. You cannot change the circumstances, the seasons, or the wind, but you can change yourself. That is something you have charge of.

Contentment

When all the world appears to be in a tumult, and nature itself is feeling the assault of climate change, the seasons retain their essential rhythm. Yes, fall gives us a premonition of winter, but then, winter, will be forced to relent, once again, to the new beginnings of soft greens, longer light, and the sweet air of spring.

Curiosity

Every corny thing that's said about living with nature - being in harmony with the earth, feeling the cycle of the seasons - happens to be true.

Happiness

The coming and going of the seasons give us more than the springtimes, summers, autumns, and winters of our lives. It reflects the coming and going of the circumstances of our lives like the glassy surface of a pond that shows our faces radiant with joy or contorted with pain.

Satisfaction

To be interested in the changing seasons is a happier state of mind than to be hopelessly in love with spring.

Zeal

There are seasons in life. Don't ever let anyone try to deny you the joy of one season because they believe you should stay in another season... Listen to yourself. Trust your instincts. Keep your perspective.

Desire

I need the seasons to live to the rhythm of rain and sun.

                        © Excogitation


text:
require File.expand_path('../../spec_helper', __dir__)

module Selenium
  module WebDriver
    describe PointerActions do
      let(:mouse) { Interactions::PointerInput.new(:mouse, name: 'pointer') }
      let(:bridge) { instance_double(Remote::Bridge) }
      let(:builder) { ActionBuilder.new(bridge, devices: [mouse]) }
      let(:element) { Element.new(bridge, 'element') }
      let(:element2) { Element.new(bridge, 'element2') }
      let(:duration) { builder.default_move_duration }
      let(:dimension) { 100 }

      describe '#pointer_input' do
        it 'gets key input by name' do
          expect(builder.send(:pointer_input, mouse.name)).to eq mouse
        end

        it 'raises ArgumentError if no device exists with that name' do
          expect { builder.send(:pointer_input, 'none') }.to raise_error(ArgumentError)
        end

        it 'gets default pointer input' do
          expect(builder.send(:pointer_input)).to eq mouse
        end
      end

      describe '#pointer_down' do
        it 'gets pointer_input' do
          allow(builder).to receive(:pointer_input).and_call_original

          builder.pointer_down :left, device: mouse.name

          expect(builder).to have_received(:pointer_input).with(mouse.name)
        end

        it 'passes the pointer to the #tick method' do
          allow(builder).to receive(:tick)

          builder.pointer_down :left
          expect(builder).to have_received(:tick).with(mouse)
        end

        it 'returns itself' do
          expect(builder.pointer_down(:left)).to eq(builder)
        end
      end

      describe '#pointer_up' do
        it 'gets pointer_input' do
          allow(builder).to receive(:pointer_input).and_call_original

          builder.pointer_up :left, device: mouse.name

          expect(builder).to have_received(:pointer_input).with(mouse.name)
        end

        it 'calls #create_pointer_up' do
          allow(mouse).to receive(:create_pointer_up)
          builder.pointer_up :left

          expect(mouse).to have_received :create_pointer_up
        end

        it 'passes the pointer to the #tick method' do
          allow(builder).to receive(:tick)

          builder.pointer_up :left
          expect(builder).to have_received(:tick).with(mouse)
        end

        it 'returns itself' do
          expect(builder.pointer_up(:left)).to eq(builder)
        end
      end

      describe '#move_to' do
        it 'gets pointer_input' do
          allow(builder).to receive(:pointer_input).and_call_original
          allow(bridge).to receive(:element_size).and_return(height: 768, width: 1024)

          builder.move_to element, 5, 5, device: mouse.name

          expect(builder).to have_received(:pointer_input).with(mouse.name)
        end

        it 'calls create_pointer_move with offsets' do
          allow(mouse).to receive(:create_pointer_move).and_call_original

          right_by = 5
          down_by = 8

          builder.move_to(element, right_by, down_by)
          expect(mouse).to have_received(:create_pointer_move).with(duration: duration,
                                                                    x: right_by,
                                                                    y: down_by,
                                                                    origin: element)
        end

        it 'passes the pointer to the #tick method' do
          allow(builder).to receive(:tick)

          builder.move_to(element)
          expect(builder).to have_received(:tick).with(mouse)
        end

        it 'returns itself' do
          expect(builder.move_to(element)).to eq(builder)
        end
      end

      describe '#move_by' do
        it 'gets pointer_input' do
          allow(builder).to receive(:pointer_input).and_call_original

          builder.move_by 5, 5, device: mouse.name

          expect(builder).to have_received(:pointer_input).with(mouse.name)
        end

        it 'calls create_pointer_move with offsets' do
          allow(mouse).to receive(:create_pointer_move).and_call_original

          builder.move_by(5, 5)

          expect(mouse).to have_received(:create_pointer_move).with(duration: duration, origin: :pointer, x: 5, y: 5)
        end

        it 'passes the pointer to the #tick method' do
          allow(builder).to receive(:tick)

          builder.move_by(5, 5)

          expect(builder).to have_received(:tick).with(mouse)
        end

        it 'returns itself' do
          expect(builder.move_by(5, 5)).to eq(builder)
        end
      end

      describe '#move_to_location' do
        it 'gets pointer_input' do
          allow(builder).to receive(:pointer_input).and_call_original

          builder.move_to_location 5, 5, device: mouse.name

          expect(builder).to have_received(:pointer_input).with(mouse.name)
        end

        it 'calls create_pointer_move with offsets' do
          allow(mouse).to receive(:create_pointer_move).and_call_original

          builder.move_to_location(5, 5)

          expect(mouse).to have_received(:create_pointer_move).with(duration: duration, origin: :viewport, x: 5, y: 5)
        end

        it 'passes the pointer to the #tick method' do
          allow(builder).to receive(:tick)

          builder.move_to_location(5, 5)
          expect(builder).to have_received(:tick).with(mouse)
        end

        it 'returns itself' do
          expect(builder.move_to_location(5, 5)).to eq(builder)
        end
      end

      describe '#click_and_hold' do
        it 'calls move_to and pointer_down with specified pointer' do
          allow(builder).to receive(:pointer_down)
          allow(builder).to receive(:move_to)

          builder.click_and_hold(element, device: 'pointer')

          expect(builder).to have_received(:pointer_down).with(:left, device: 'pointer')
          expect(builder).to have_received(:move_to).with(element, device: 'pointer')
        end

        it 'calls move_to and pointer_down with the supplied pointer by default' do
          allow(builder).to receive(:pointer_down)
          allow(builder).to receive(:move_to)

          builder.click_and_hold(element)

          expect(builder).to have_received(:pointer_down).with(:left, device: nil)
          expect(builder).to have_received(:move_to).with(element, device: nil)
        end

        it 'returns itself' do
          expect(builder.click_and_hold(element)).to eq(builder)
        end
      end

      describe '#release' do
        it 'calls pointer_up with specified pointer' do
          allow(builder).to receive(:pointer_up)

          builder.release(device: 'pointer')

          expect(builder).to have_received(:pointer_up).with(:left, device: 'pointer')
        end

        it 'calls pointer_up with the supplied pointer by default' do
          allow(builder).to receive(:pointer_up)

          builder.release
          expect(builder).to have_received(:pointer_up).with(:left, device: nil)
        end

        it 'returns itself' do
          expect(builder.release).to eq(builder)
        end
      end

      describe '#click' do
        context 'with element specified' do
          it 'calls move and presses with specified pointer' do
            allow(builder).to receive(:move_to)
            allow(builder).to receive(:pointer_down)
            allow(builder).to receive(:pointer_up)

            builder.click(element, device: 'pointer')

            expect(builder).to have_received(:move_to).with(element, device: 'pointer')
            expect(builder).to have_received(:pointer_down).with(:left, device: 'pointer')
            expect(builder).to have_received(:pointer_up).with(:left, device: 'pointer')
          end

          it 'calls move and presses with the supplied pointer by default' do
            allow(builder).to receive(:move_to)
            allow(builder).to receive(:pointer_down)
            allow(builder).to receive(:pointer_up)

            builder.click(element)

            expect(builder).to have_received(:move_to).with(element, device: nil)
            expect(builder).to have_received(:pointer_down).with(:left, device: nil)
            expect(builder).to have_received(:pointer_up).with(:left, device: nil)
          end
        end

        context 'without element specified' do
          it 'calls presses with specified pointer' do
            allow(builder).to receive(:move_to)
            allow(builder).to receive(:pointer_down)
            allow(builder).to receive(:pointer_up)

            builder.click(device: 'pointer')

            expect(builder).not_to have_received(:move_to)
            expect(builder).to have_received(:pointer_down).with(:left, device: 'pointer')
            expect(builder).to have_received(:pointer_up).with(:left, device: 'pointer')
          end

          it 'calls presses with the supplied pointer by default' do
            allow(builder).to receive(:move_to)
            allow(builder).to receive(:pointer_down)
            allow(builder).to receive(:pointer_up)

            builder.click

            expect(builder).not_to have_received(:move_to)
            expect(builder).to have_received(:pointer_down).with(:left, device: nil)
            expect(builder).to have_received(:pointer_up).with(:left, device: nil)
          end
        end

        it 'returns itself' do
          expect(builder.click(element)).to eq(builder)
        end
      end

      describe '#double_click' do
        context 'with element specified' do
          it 'calls move and presses with specified pointer' do
            allow(builder).to receive(:move_to)
            allow(builder).to receive(:pointer_down)
            allow(builder).to receive(:pointer_up)

            builder.double_click(element, device: 'pointer')

            expect(builder).to have_received(:move_to).with(element, device: 'pointer')
            expect(builder).to have_received(:pointer_down).with(:left, device: 'pointer').twice
            expect(builder).to have_received(:pointer_up).with(:left, device: 'pointer').twice
          end

          it 'calls move and presses with the supplied pointer by default' do
            allow(builder).to receive(:move_to)
            allow(builder).to receive(:pointer_down)
            allow(builder).to receive(:pointer_up)

            builder.double_click(element)

            expect(builder).to have_received(:move_to).with(element, device: nil)
            expect(builder).to have_received(:pointer_down).with(:left, device: nil).twice
            expect(builder).to have_received(:pointer_up).with(:left, device: nil).twice
          end
        end

        context 'without element specified' do
          it 'calls presses with specified pointer' do
            allow(builder).to receive(:move_to)
            allow(builder).to receive(:pointer_down)
            allow(builder).to receive(:pointer_up)

            builder.double_click(device: 'pointer')

            expect(builder).not_to have_received(:move_to)
            expect(builder).to have_received(:pointer_down).with(:left, device: 'pointer').twice
            expect(builder).to have_received(:pointer_up).with(:left, device: 'pointer').twice
          end

          it 'calls presses with the supplied pointer by default' do
            allow(builder).to receive(:move_to)
            allow(builder).to receive(:pointer_down)
            allow(builder).to receive(:pointer_up)

            builder.double_click

            expect(builder).not_to have_received(:move_to)
            expect(builder).to have_received(:pointer_down).with(:left, device: nil).twice
            expect(builder).to have_received(:pointer_up).with(:left, device: nil).twice
          end
        end

        it 'returns itself' do
          expect(builder.double_click(element)).to eq(builder)
        end
      end

      describe '#context_click' do
        context 'with element specified' do
          it 'calls move and presses with specified pointer' do
            allow(builder).to receive(:move_to)
            allow(builder).to receive(:pointer_down)
            allow(builder).to receive(:pointer_up)

            builder.context_click(element, device: 'pointer')

            expect(builder).to have_received(:move_to).with(element, device: 'pointer')
            expect(builder).to have_received(:pointer_down).with(:right, device: 'pointer')
            expect(builder).to have_received(:pointer_up).with(:right, device: 'pointer')
          end

          it 'calls move and presses with the supplied pointer by default' do
            allow(builder).to receive(:move_to)
            allow(builder).to receive(:pointer_down)
            allow(builder).to receive(:pointer_up)

            builder.context_click(element)

            expect(builder).to have_received(:move_to).with(element, device: nil)
            expect(builder).to have_received(:pointer_down).with(:right, device: nil)
            expect(builder).to have_received(:pointer_up).with(:right, device: nil)
          end
        end

        context 'without element specified' do
          it 'calls presses with specified pointer' do
            allow(builder).to receive(:move_to)
            allow(builder).to receive(:pointer_down)
            allow(builder).to receive(:pointer_up)

            builder.context_click(device: 'pointer')

            expect(builder).not_to have_received(:move_to)
            expect(builder).to have_received(:pointer_down).with(:right, device: 'pointer')
            expect(builder).to have_received(:pointer_up).with(:right, device: 'pointer')
          end

          it 'calls presses with the supplied pointer by default' do
            allow(builder).to receive(:move_to)
            allow(builder).to receive(:pointer_down)
            allow(builder).to receive(:pointer_up)

            builder.context_click

            expect(builder).not_to have_received(:move_to)
            expect(builder).to have_received(:pointer_down).with(:right, device: nil)
            expect(builder).to have_received(:pointer_up).with(:right, device: nil)
          end
        end

        it 'returns itself' do
          expect(builder.context_click(element)).to eq(builder)
        end
      end

      describe '#drag_and_drop' do
        it 'calls click_and_hold, move_to and release with specified pointer' do
          allow(builder).to receive(:click_and_hold)
          allow(builder).to receive(:move_to)
          allow(builder).to receive(:release)

          builder.drag_and_drop(element, element2, device: 'pointer')

          expect(builder).to have_received(:click_and_hold).with(element, device: 'pointer')
          expect(builder).to have_received(:move_to).with(element2, device: 'pointer')
          expect(builder).to have_received(:release).with(device: 'pointer')
        end

        it 'calls click_and_hold, move_to and release with the supplied pointer by default' do
          allow(builder).to receive(:click_and_hold)
          allow(builder).to receive(:move_to)
          allow(builder).to receive(:release)

          builder.drag_and_drop(element, element2)

          expect(builder).to have_received(:click_and_hold).with(element, device: nil)
          expect(builder).to have_received(:move_to).with(element2, device: nil)
          expect(builder).to have_received(:release).with(device: nil)
        end

        it 'returns itself' do
          expect(builder.drag_and_drop(element, element2)).to eq(builder)
        end
      end

      describe '#drag_and_drop_by' do
        it 'calls click_and_hold, move_by and release with specified pointer' do
          allow(builder).to receive(:click_and_hold)
          allow(builder).to receive(:move_by)
          allow(builder).to receive(:release)
          right_by = 5
          left_by = 5

          builder.drag_and_drop_by(element, right_by, left_by, device: 'pointer')

          expect(builder).to have_received(:click_and_hold).with(element, device: 'pointer')
          expect(builder).to have_received(:move_by).with(right_by, left_by, device: 'pointer')
          expect(builder).to have_received(:release).with(device: 'pointer')
        end

        it 'calls click_and_hold, move_by and release with the supplied pointer by default' do
          allow(builder).to receive(:click_and_hold)
          allow(builder).to receive(:move_by)
          allow(builder).to receive(:release)
          right_by = 5
          left_by = 5

          builder.drag_and_drop_by(element, right_by, left_by)

          expect(builder).to have_received(:click_and_hold).with(element, device: nil)
          expect(builder).to have_received(:move_by).with(right_by, left_by, device: nil)
          expect(builder).to have_received(:release).with(device: nil)
        end

        it 'returns itself' do
          expect(builder.drag_and_drop_by(element, 5, 5)).to eq(builder)
        end
      end
    end
  end # WebDriver
end # Selenium


text:
<?php

namespace Mage\Catalog\Test\Fixture\CatalogCategory;

use Magento\Mtf\Fixture\FixtureInterface;
use Magento\Mtf\Fixture\FixtureFactory;
use Mage\Catalog\Test\Fixture\CatalogCategory;

/**
 * Prepare parent category.
 */
class ParentId implements FixtureInterface
{
    /**
     * Return category.
     *
     * @var CatalogCategory
     */
    protected $parentCategory = null;

    /**
     * Fixture params.
     *
     * @var array
     */
    protected $params;

    /**
     * @constructor
     * @param FixtureFactory $fixtureFactory
     * @param array $params
     * @param array|int $data
     */
    public function __construct(FixtureFactory $fixtureFactory, array $params, $data = [])
    {
        $this->params = $params;
        if (isset($data['dataset'])) {
            $this->parentCategory = $fixtureFactory->createByCode('catalogCategory', ['dataset' => $data['dataset']]);
            if (!$this->parentCategory->hasData('id')) {
                $this->parentCategory->persist();
            }
            $this->data = $this->parentCategory->getId();
        } elseif (isset($data['data']) && isset($data['parent_category'])) {
            $this->data = $data['data'];
            $this->parentCategory = $data['parent_category'];
        } else {
            $this->data = $data;
        }
    }

    /**
     * Persist attribute options.
     *
     * @return void
     */
    public function persist()
    {
        //
    }

    /**
     * Return prepared data set.
     *
     * @param string|null $key
     * @return mixed
     *
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function getData($key = null)
    {
        return $this->data;
    }

    /**
     * Return data set configuration settings.
     *
     * @return array
     */
    public function getDataConfig()
    {
        return $this->params;
    }

    /**
     * Return entity.
     *
     * @return CatalogCategory
     */
    public function getParentCategory()
    {
        return $this->parentCategory;
    }
}


text:
package org.locationtech.geomesa.index.index.s3

import org.locationtech.geomesa.index.api.ShardStrategy.ZShardStrategy
import org.locationtech.geomesa.index.api.{GeoMesaFeatureIndex, IndexKeySpace}
import org.locationtech.geomesa.index.geotools.GeoMesaDataStore
import org.locationtech.geomesa.index.index.ConfiguredIndex
import org.locationtech.geomesa.index.strategies.SpatioTemporalFilterStrategy
import org.locationtech.geomesa.utils.index.IndexMode.IndexMode
import org.opengis.feature.simple.SimpleFeatureType

class S3Index protected (
    ds: GeoMesaDataStore[_],
    sft: SimpleFeatureType,
    version: Int,
    geom: String,
    dtg: String,
    mode: IndexMode
  ) extends GeoMesaFeatureIndex[S3IndexValues, S3IndexKey](ds, sft, S3Index.name, version, Seq(geom, dtg), mode)
      with SpatioTemporalFilterStrategy[S3IndexValues, S3IndexKey] {

  def this(ds: GeoMesaDataStore[_], sft: SimpleFeatureType, geomField: String, dtgField: String, mode: IndexMode) =
    this(ds, sft, S3Index.version, geomField, dtgField, mode)

  override val keySpace: IndexKeySpace[S3IndexValues, S3IndexKey] =
    new S3IndexKeySpace(sft, ZShardStrategy(sft), geom, dtg)

  override def tieredKeySpace: Option[IndexKeySpace[_, _]] = None
}

object S3Index extends ConfiguredIndex {

  override val name = "s3"
  override val version = 1

  override def supports(sft: SimpleFeatureType, attributes: Seq[String]): Boolean =
    S3IndexKeySpace.supports(sft, attributes)

  override def defaults(sft: SimpleFeatureType): Seq[Seq[String]] = Seq.empty
}


text:
module Fayde.Media {
    export class PathFigure extends DependencyObject {
        static IsClosedProperty = DependencyProperty.RegisterCore("IsClosed", () => Boolean, PathFigure, false, (d: PathFigure, args) => d.InvalidatePathFigure());
        static StartPointProperty = DependencyProperty.RegisterCore("StartPoint", () => Point, PathFigure, undefined, (d: PathFigure, args) => d.InvalidatePathFigure());
        static IsFilledProperty = DependencyProperty.RegisterCore("IsFilled", () => Boolean, PathFigure, true, (d: PathFigure, args) => d.InvalidatePathFigure());
        static SegmentsProperty = DependencyProperty.RegisterImmutable<PathSegmentCollection>("Segments", () => PathSegmentCollection, PathFigure);
        static SegmentsSourceProperty = DependencyProperty.Register("SegmentsSource", () => nullstone.IEnumerable_, PathFigure, undefined, (d: PathFigure, args) => d._OnSegmentsSourceChanged(args));
        IsClosed: boolean;
        Segments: PathSegmentCollection;
        SegmentsSource: nullstone.IEnumerable<PathSegment>;
        StartPoint: Point;
        IsFilled: boolean;

        private _OnSegmentsSourceChanged (args: IDependencyPropertyChangedEventArgs) {
            this.Segments.SetSource(args.NewValue);
        }

        private _Path: minerva.path.Path = null;

        constructor() {
            super();
            var coll = PathFigure.SegmentsProperty.Initialize(this);
            coll.AttachTo(this);
            ReactTo(coll, this, () => this.InvalidatePathFigure());
        }

        private _Build(): minerva.path.Path {
            var p = new minerva.path.Path();

            var start = this.StartPoint;
            p.move(start.x, start.y);

            var enumerator = this.Segments.getEnumerator();
            while (enumerator.moveNext()) {
                (<PathSegment>enumerator.current)._Append(p);
            }
            if (this.IsClosed)
                p.close();

            return p;
        }

        private InvalidatePathFigure() {
            this._Path = null;
            Incite(this);
        }

        MergeInto(rp: minerva.path.Path) {
            if (!this._Path)
                this._Path = this._Build();
            minerva.path.Path.Merge(rp, this._Path);
        }
    }
    Fayde.CoreLibrary.add(PathFigure);
    Markup.Content(PathFigure, PathFigure.SegmentsProperty);

    export class PathFigureCollection extends XamlObjectCollection<PathFigure> {
        AddingToCollection(value: PathFigure, error: BError): boolean {
            if (!super.AddingToCollection(value, error))
                return false;
            ReactTo(value, this, () => Incite(this));
            Incite(this);
            return true;
        }
        RemovedFromCollection(value: PathFigure, isValueSafe: boolean) {
            super.RemovedFromCollection(value, isValueSafe);
            UnreactTo(value, this);
            Incite(this);
        }
    }
    Fayde.CoreLibrary.add(PathFigureCollection);
}


text:
'use strict';
var grunt = require('grunt');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports.autoversion = {
  setUp: function(done) {
    // setup here if necessary
    done();
  },
  default_options: function(test) {
    test.expect(1);

    var packageVersion = grunt.file.readJSON('./package.json').version;

    var exec = require('child_process').exec,
    child;

    child = exec('git status', function(error, stdout){
        test.equal(packageVersion, stdout.match(/^On branch (?:.+\/)?(.+?)$/m)[1], 'default version equal');
        test.done();
    });

  },
  custom_options: function(test) {
    test.expect(1);

    var packageVersion = grunt.file.readJSON('./package.json').version;

    var exec = require('child_process').exec,
    child;

    child = exec('git status', function(error, stdout){
        test.equal(packageVersion, stdout.match(/^On branch (?:.+\/)?(.+?)$/m)[1], 'custom version equal');
        test.done();
    });

  }
};


text:
<form name="form" novalidate>

{{title}}

{{message}}

    <button type="button" class="btn btn-default" ng-click="$dismiss()">{{dismissButtonLabel}}</button>
    <button type="button" class="btn btn-default" ng-if="canDiscard" ng-click="discard()">{{discardButtonLabel}}</button>
    <button type="button" class="btn" ng-class="closeButtonCssClass" ng-click="$close()" ng-auto-focus="true">{{closeButtonLabel}}</button>

</form>


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

<title>InputEx - using XML, example with RSS</title>

<link rel="stylesheet" href="http://yui.yahooapis.com/combo?3.6.0/build/cssreset/reset-min.css&3.6.0/build/cssfonts/fonts-min.css">
<link rel="stylesheet" href="../res/demo.css">
<link rel="stylesheet" href="../res/syntaxhighlighter/styles/shCore.css">
<link rel="stylesheet" href="../res/syntaxhighlighter/styles/shThemeDefault.css">

Using XML

Let's use some inputEx wisdom to create an editor for a RSS feed

var rssFormDef = {
  type: 'group',
  parentEl: 'container1',
  fields: [
    {type: 'select', label: 'Version', name: '-version', choices: ['1.0','2.0'] },
    {
      type: 'group',
      name: 'channel',
      fields: [
        {type: 'string', label: 'Title', name: 'title'},
        {type: 'string', label: 'Description', name: 'description', size: 53},
        {type: 'url', label: 'Link', name: 'link'},
        {type: 'select', label: 'Language', name: 'language', choices: ['en', 'fr']},
        {
          label: 'Posts',
          type: 'list',
          name: 'item',
          elementType:{
            type: 'group',
            fields: [
              {type: 'string', label: 'Title', name: 'title', size: 60},
              {type: 'string', label: 'Description', name: 'description', size: 60},
              {type: 'inplaceedit', editorField:{type: 'url', showMsg: true}, name: 'link', label: 'Link', animColors:{from:"#FFFF99" , to:"#DDDDFF"} }
            ]
          }
        }
      ]
    }
  ]
};

// Get the rss and populate the form
Y.io('rss-example.xml', {
  method: 'GET',
  on: {
	  success: function(id, o, args) {
		  var xotree = new XML.ObjTree();
	    var tree = xotree.parseXML( o.responseText );
	    console.log(tree.rss);
		  Y.inputEx(rssFormDef).setValue(tree.rss);
	  }
  }
});


text:
/* Import plugin specific language pack */
tinyMCE.importPluginLanguagePack('preview', 'en,tr,cs,de,el,fr_ca,it,ko,pt,sv,zh_cn,fa,fr,pl,pt_br,nl,da,he,nb,hu,ru,ru_KOI8-R,ru_UTF-8,nn,es,cy,is,zh_tw,zh_tw_utf8,sk');

var TinyMCE_PreviewPlugin = {
	getInfo : function() {
		return {
			longname : 'Preview',
			author : 'Moxiecode Systems',
			authorurl : 'http://tinymce.moxiecode.com',
			infourl : 'http://tinymce.moxiecode.com/tinymce/docs/plugin_preview.html',
			version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion
		};
	},

	/**
	 * Returns the HTML contents of the preview control.
	 */
	getControlHTML : function(cn) {
		switch (cn) {
			case "preview":
				return tinyMCE.getButtonHTML(cn, 'lang_preview_desc', '{$pluginurl}/images/preview.gif', 'mcePreview');
		}

		return "";
	},

	/**
	 * Executes the mcePreview command.
	 */
	execCommand : function(editor_id, element, command, user_interface, value) {
		// Handle commands
		switch (command) {
			case "mcePreview":
				var previewPage = tinyMCE.getParam("plugin_preview_pageurl", null);
				var previewWidth = tinyMCE.getParam("plugin_preview_width", "550");
				var previewHeight = tinyMCE.getParam("plugin_preview_height", "600");

				// Use a custom preview page
				if (previewPage) {
					var template = new Array();

					template['file'] = previewPage;
					template['width'] = previewWidth;
					template['height'] = previewHeight;

					tinyMCE.openWindow(template, {editor_id : editor_id, resizable : "yes", scrollbars : "yes", inline : "yes", content : tinyMCE.getContent(), content_css : tinyMCE.getParam("content_css")});
				} else {
					var win = window.open("", "mcePreview", "menubar=no,toolbar=no,scrollbars=yes,resizable=yes,left=20,top=20,width=" + previewWidth + ",height="  + previewHeight);
					var html = "";
					var c = tinyMCE.getContent();
					var pos = c.indexOf('', pos);
						pos2 = c.lastIndexOf('');
						c = c.substring(pos + 1, pos2);
					}

					html += tinyMCE.getParam('doctype');
					html += '';
					html += '';
					html += '<title>' + tinyMCE.getLang('lang_preview_desc') + '</title>';
					html += '<base href="' + tinyMCE.settings['base_href'] + '" />';
					html += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
					html += '<link href="' + tinyMCE.getParam("content_css") + '" rel="stylesheet" type="text/css" />';
					html += '';
					html += '';
					html += c;
					html += '';
					html += '';

					win.document.write(html);
					win.document.close();
				}

				return true;
		}

		return false;
	}
};

tinyMCE.addPlugin("preview", TinyMCE_PreviewPlugin);


text:
<?php

namespace App\Http\Controllers;

use App\Character;
use App\Skill;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function commonPage($url, $data = []) {
        $data['skill_count'] = Skill::count();
        $data['chara_count'] = Character::count();
        return view($url, $data);
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return $this->commonPage('home');
    }
}