text:
<?php

namespace Symfony\Component\HttpKernel\Tests\DependencyInjection;

use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\DependencyInjection\TypedReference;
use Symfony\Component\HttpKernel\DependencyInjection\RegisterControllerArgumentLocatorsPass;

class RegisterControllerArgumentLocatorsPassTest extends TestCase
{
    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
     * @expectedExceptionMessage Class "Symfony\Component\HttpKernel\Tests\DependencyInjection\NotFound" used for service "foo" cannot be found.
     */
    public function testInvalidClass()
    {
        $container = new ContainerBuilder();
        $container->register('argument_resolver.service')->addArgument([]);

        $container->register('foo', NotFound::class)
            ->addTag('controller.service_arguments')
        ;

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
     * @expectedExceptionMessage Missing "action" attribute on tag "controller.service_arguments" {"argument":"bar"} for service "foo".
     */
    public function testNoAction()
    {
        $container = new ContainerBuilder();
        $container->register('argument_resolver.service')->addArgument([]);

        $container->register('foo', RegisterTestController::class)
            ->addTag('controller.service_arguments', ['argument' => 'bar'])
        ;

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
     * @expectedExceptionMessage Missing "argument" attribute on tag "controller.service_arguments" {"action":"fooAction"} for service "foo".
     */
    public function testNoArgument()
    {
        $container = new ContainerBuilder();
        $container->register('argument_resolver.service')->addArgument([]);

        $container->register('foo', RegisterTestController::class)
            ->addTag('controller.service_arguments', ['action' => 'fooAction'])
        ;

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
     * @expectedExceptionMessage Missing "id" attribute on tag "controller.service_arguments" {"action":"fooAction","argument":"bar"} for service "foo".
     */
    public function testNoService()
    {
        $container = new ContainerBuilder();
        $container->register('argument_resolver.service')->addArgument([]);

        $container->register('foo', RegisterTestController::class)
            ->addTag('controller.service_arguments', ['action' => 'fooAction', 'argument' => 'bar'])
        ;

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
     * @expectedExceptionMessage Invalid "action" attribute on tag "controller.service_arguments" for service "foo": no public "barAction()" method found on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController".
     */
    public function testInvalidMethod()
    {
        $container = new ContainerBuilder();
        $container->register('argument_resolver.service')->addArgument([]);

        $container->register('foo', RegisterTestController::class)
            ->addTag('controller.service_arguments', ['action' => 'barAction', 'argument' => 'bar', 'id' => 'bar_service'])
        ;

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
     * @expectedExceptionMessage Invalid "controller.service_arguments" tag for service "foo": method "fooAction()" has no "baz" argument on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController".
     */
    public function testInvalidArgument()
    {
        $container = new ContainerBuilder();
        $container->register('argument_resolver.service')->addArgument([]);

        $container->register('foo', RegisterTestController::class)
            ->addTag('controller.service_arguments', ['action' => 'fooAction', 'argument' => 'baz', 'id' => 'bar'])
        ;

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);
    }

    public function testAllActions()
    {
        $container = new ContainerBuilder();
        $resolver = $container->register('argument_resolver.service')->addArgument([]);

        $container->register('foo', RegisterTestController::class)
            ->addTag('controller.service_arguments')
        ;

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);

        $locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);

        $this->assertEquals(['foo::fooAction'], array_keys($locator));
        $this->assertInstanceof(ServiceClosureArgument::class, $locator['foo::fooAction']);

        $locator = $container->getDefinition((string) $locator['foo::fooAction']->getValues()[0]);

        $this->assertSame(ServiceLocator::class, $locator->getClass());
        $this->assertFalse($locator->isPublic());

        $expected = ['bar' => new ServiceClosureArgument(new TypedReference(ControllerDummy::class, ControllerDummy::class, ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE, 'bar'))];
        $this->assertEquals($expected, $locator->getArgument(0));
    }

    public function testExplicitArgument()
    {
        $container = new ContainerBuilder();
        $resolver = $container->register('argument_resolver.service')->addArgument([]);

        $container->register('foo', RegisterTestController::class)
            ->addTag('controller.service_arguments', ['action' => 'fooAction', 'argument' => 'bar', 'id' => 'bar'])
            ->addTag('controller.service_arguments', ['action' => 'fooAction', 'argument' => 'bar', 'id' => 'baz']) // should be ignored, the first wins
        ;

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);

        $locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
        $locator = $container->getDefinition((string) $locator['foo::fooAction']->getValues()[0]);

        $expected = ['bar' => new ServiceClosureArgument(new TypedReference('bar', ControllerDummy::class, ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE))];
        $this->assertEquals($expected, $locator->getArgument(0));
    }

    public function testOptionalArgument()
    {
        $container = new ContainerBuilder();
        $resolver = $container->register('argument_resolver.service')->addArgument([]);

        $container->register('foo', RegisterTestController::class)
            ->addTag('controller.service_arguments', ['action' => 'fooAction', 'argument' => 'bar', 'id' => '?bar'])
        ;

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);

        $locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
        $locator = $container->getDefinition((string) $locator['foo::fooAction']->getValues()[0]);

        $expected = ['bar' => new ServiceClosureArgument(new TypedReference('bar', ControllerDummy::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE))];
        $this->assertEquals($expected, $locator->getArgument(0));
    }

    public function testSkipSetContainer()
    {
        $container = new ContainerBuilder();
        $resolver = $container->register('argument_resolver.service')->addArgument([]);

        $container->register('foo', ContainerAwareRegisterTestController::class)
            ->addTag('controller.service_arguments');

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);

        $locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
        $this->assertSame(['foo::fooAction'], array_keys($locator));
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
     * @expectedExceptionMessage Cannot determine controller argument for "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClassController::fooAction()": the $nonExistent argument is type-hinted with the non-existent class or interface: "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClass". Did you forget to add a use statement?
     */
    public function testExceptionOnNonExistentTypeHint()
    {
        $container = new ContainerBuilder();
        $container->register('argument_resolver.service')->addArgument([]);

        $container->register('foo', NonExistentClassController::class)
            ->addTag('controller.service_arguments');

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
     * @expectedExceptionMessage Cannot determine controller argument for "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClassDifferentNamespaceController::fooAction()": the $nonExistent argument is type-hinted with the non-existent class or interface: "Acme\NonExistentClass".
     */
    public function testExceptionOnNonExistentTypeHintDifferentNamespace()
    {
        $container = new ContainerBuilder();
        $container->register('argument_resolver.service')->addArgument([]);

        $container->register('foo', NonExistentClassDifferentNamespaceController::class)
            ->addTag('controller.service_arguments');

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);
    }

    public function testNoExceptionOnNonExistentTypeHintOptionalArg()
    {
        $container = new ContainerBuilder();
        $resolver = $container->register('argument_resolver.service')->addArgument([]);

        $container->register('foo', NonExistentClassOptionalController::class)
            ->addTag('controller.service_arguments');

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);

        $locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
        $this->assertSame(['foo::barAction', 'foo::fooAction'], array_keys($locator));
    }

    public function testArgumentWithNoTypeHintIsOk()
    {
        $container = new ContainerBuilder();
        $resolver = $container->register('argument_resolver.service')->addArgument([]);

        $container->register('foo', ArgumentWithoutTypeController::class)
            ->addTag('controller.service_arguments');

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);

        $locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
        $this->assertEmpty(array_keys($locator));
    }

    public function testControllersAreMadePublic()
    {
        $container = new ContainerBuilder();
        $resolver = $container->register('argument_resolver.service')->addArgument([]);

        $container->register('foo', ArgumentWithoutTypeController::class)
            ->setPublic(false)
            ->addTag('controller.service_arguments');

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);

        $this->assertTrue($container->getDefinition('foo')->isPublic());
    }

    /**
     * @dataProvider provideBindings
     */
    public function testBindings($bindingName)
    {
        $container = new ContainerBuilder();
        $resolver = $container->register('argument_resolver.service')->addArgument([]);

        $container->register('foo', RegisterTestController::class)
            ->setBindings([$bindingName => new Reference('foo')])
            ->addTag('controller.service_arguments');

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);

        $locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);

        $locator = $container->getDefinition((string) $locator['foo::fooAction']->getValues()[0]);

        $expected = ['bar' => new ServiceClosureArgument(new Reference('foo'))];
        $this->assertEquals($expected, $locator->getArgument(0));
    }

    public function provideBindings()
    {
        return [
            [ControllerDummy::class.'$bar'],
            [ControllerDummy::class],
            ['$bar'],
        ];
    }

    /**
     * @dataProvider provideBindScalarValueToControllerArgument
     */
    public function testBindScalarValueToControllerArgument($bindingKey)
    {
        $container = new ContainerBuilder();
        $resolver = $container->register('argument_resolver.service')->addArgument([]);

        $container->register('foo', ArgumentWithoutTypeController::class)
            ->setBindings([$bindingKey => '%foo%'])
            ->addTag('controller.service_arguments');

        $container->setParameter('foo', 'foo_val');

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);

        $locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);

        $locator = $container->getDefinition((string) $locator['foo::fooAction']->getValues()[0]);

        // assert the locator has a someArg key
        $arguments = $locator->getArgument(0);
        $this->assertArrayHasKey('someArg', $arguments);
        $this->assertInstanceOf(ServiceClosureArgument::class, $arguments['someArg']);
        // get the Reference that someArg points to
        $reference = $arguments['someArg']->getValues()[0];
        // make sure this service *does* exist and returns the correct value
        $this->assertTrue($container->has((string) $reference));
        $this->assertSame('foo_val', $container->get((string) $reference));
    }

    public function provideBindScalarValueToControllerArgument()
    {
        yield ['$someArg'];
        yield ['string $someArg'];
    }

    public function testBindingsOnChildDefinitions()
    {
        $container = new ContainerBuilder();
        $resolver = $container->register('argument_resolver.service')->addArgument([]);

        $container->register('parent', ArgumentWithoutTypeController::class);

        $container->setDefinition('child', (new ChildDefinition('parent'))
            ->setBindings(['$someArg' => new Reference('parent')])
            ->addTag('controller.service_arguments')
        );

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);

        $locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
        $this->assertInstanceOf(ServiceClosureArgument::class, $locator['child::fooAction']);

        $locator = $container->getDefinition((string) $locator['child::fooAction']->getValues()[0])->getArgument(0);
        $this->assertInstanceOf(ServiceClosureArgument::class, $locator['someArg']);
        $this->assertEquals(new Reference('parent'), $locator['someArg']->getValues()[0]);
    }
}

class RegisterTestController
{
    public function __construct(ControllerDummy $bar)
    {
    }

    public function fooAction(ControllerDummy $bar)
    {
    }

    protected function barAction(ControllerDummy $bar)
    {
    }
}

class ContainerAwareRegisterTestController implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    public function fooAction(ControllerDummy $bar)
    {
    }
}

class ControllerDummy
{
}

class NonExistentClassController
{
    public function fooAction(NonExistentClass $nonExistent)
    {
    }
}

class NonExistentClassDifferentNamespaceController
{
    public function fooAction(\Acme\NonExistentClass $nonExistent)
    {
    }
}

class NonExistentClassOptionalController
{
    public function fooAction(NonExistentClass $nonExistent = null)
    {
    }

    public function barAction(NonExistentClass $nonExistent = null, $bar)
    {
    }
}

class ArgumentWithoutTypeController
{
    public function fooAction(string $someArg)
    {
    }
}


text:
<!DOCTYPE html>

    <title>react-mixin simple example</title>

redpajama_set_name: RedPajamaGithub


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

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Provides information about an S3 object that lists specific text to ignore.
 *

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

    /**
     *

     * The full name of the S3 bucket that contains the object.
     *

     */
    private String bucketName;
    /**
     *

     * The full name (key) of the object.
     *

     */
    private String objectKey;

    /**
     *

     * The full name of the S3 bucket that contains the object.
     *

     *
     * @param bucketName
     *        The full name of the S3 bucket that contains the object.
     */

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }

    /**
     *

     * The full name of the S3 bucket that contains the object.
     *

     *
     * @return The full name of the S3 bucket that contains the object.
     */

    public String getBucketName() {
        return this.bucketName;
    }

    /**
     *

     * The full name of the S3 bucket that contains the object.
     *

     *
     * @param bucketName
     *        The full name of the S3 bucket that contains the object.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public S3WordsList withBucketName(String bucketName) {
        setBucketName(bucketName);
        return this;
    }

    /**
     *

     * The full name (key) of the object.
     *

     *
     * @param objectKey
     *        The full name (key) of the object.
     */

    public void setObjectKey(String objectKey) {
        this.objectKey = objectKey;
    }

    /**
     *

     * The full name (key) of the object.
     *

     *
     * @return The full name (key) of the object.
     */

    public String getObjectKey() {
        return this.objectKey;
    }

    /**
     *

     * The full name (key) of the object.
     *

     *
     * @param objectKey
     *        The full name (key) of the object.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public S3WordsList withObjectKey(String objectKey) {
        setObjectKey(objectKey);
        return this;
    }

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

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

        if (obj instanceof S3WordsList == false)
            return false;
        S3WordsList other = (S3WordsList) obj;
        if (other.getBucketName() == null ^ this.getBucketName() == null)
            return false;
        if (other.getBucketName() != null && other.getBucketName().equals(this.getBucketName()) == false)
            return false;
        if (other.getObjectKey() == null ^ this.getObjectKey() == null)
            return false;
        if (other.getObjectKey() != null && other.getObjectKey().equals(this.getObjectKey()) == false)
            return false;
        return true;
    }

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

        hashCode = prime * hashCode + ((getBucketName() == null) ? 0 : getBucketName().hashCode());
        hashCode = prime * hashCode + ((getObjectKey() == null) ? 0 : getObjectKey().hashCode());
        return hashCode;
    }

    @Override
    public S3WordsList clone() {
        try {
            return (S3WordsList) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.macie2.model.transform.S3WordsListMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
"use strict";

var requestHelper = require('../request-helper');

describe('GET /status', function() {
  before(function(done) {
    requestHelper.sendRequest(this, '/status', null, done);
  });

  it('should return status 200', function() {
    expect(this.res.statusCode).to.equal(200);
  });

  it('should respond with plain text', function() {
    expect(this.res.headers["content-type"]).to.equal("text/plain; charset=utf-8");
  });

  it('should respond with status message', function() {
    expect(this.res.text).to.equal("Authentication Provider up and running\n");
  });
});


text:
package com.akjava.lib.common.form;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.akjava.lib.common.param.Parameter;
import com.akjava.lib.common.param.ParameterUtils;
import com.akjava.lib.common.utils.ValuesUtils;

public class ValidatorTools {

	private ValidatorTools(){}
//private  static BiMap<String,Validator> bimap=null;
	/*
public static BiMap<String,Validator> getValidatorMap(){
	if(bimap==null){
		init();
	}
	return bimap;
}
*/

public static Map<String,Validator> validatorMap=new HashMap<String, Validator>();
public static Validator getValidator(String line) throws ValidatorNotFoundException{
	Validator validator=validatorMap.get(line);
	if(validator!=null){
		return validator;
	}
	Parameter param=ParameterUtils.parse(line);
	String name=param.getName().toLowerCase();
	if(name.equals(StaticValidators.VALIDATOR_NOT_EMPTY.toLowerCase())){
		return StaticValidators.notEmptyValidator();
	}
	else if(name.equals(StaticValidators.VALIDATOR_ASCII_NUMBER.toLowerCase())){
		return StaticValidators.asciiNumberOnly();
	}
	else if(name.equals(StaticValidators.VALIDATOR_ASCII_NUMBER_AND_CHAR.toLowerCase())){
		return StaticValidators.asciiNumberAndCharOnly();
	}
	else if(name.equals(StaticValidators.VALIDATOR_ASCII_NUMBER_AND_CHAR_AND_UNDERBAR.toLowerCase())){
		return StaticValidators.asciiNumberAndCharAndUnderbarOnly();
	}
	else if(name.equals(StaticValidators.VALIDATOR_HANKAKU_KANA.toLowerCase())){
		return StaticValidators.hankakuKana();
	}
	else if(name.equals(StaticValidators.VALIDATOR_HIRAGANA.toLowerCase())){
		return StaticValidators.hiragana();
	}
	else if(name.equals(StaticValidators.VALIDATOR_ASCII_CHAR.toLowerCase())){
		return StaticValidators.asciiCharOnly();
	}
	else if(name.equals(StaticValidators.VALIDATOR_START_ASCII_CHAR.toLowerCase())){
		return StaticValidators.startAsciiChar();
	}else if(name.equals(StaticValidators.VALIDATOR_DECIMAL_NUMBER.toLowerCase())){
		return StaticValidators.decimalNumber();
	}else if(name.equals(StaticValidators.VALIDATOR_INTEGER_NUMBER.toLowerCase())){

		return StaticValidators.integerNumber();
	}else if(name.equals(Validators.VALIDATOR_RANGE_NUMBER.toLowerCase())){

		Double min=null;
		Double max=null;
		if(param.size()>0){
		try{
		min=Double.parseDouble(param.get(0));
		}catch (Exception e) {
			//use null;
		}
		if(param.size()>1){
		try{
			max=Double.parseDouble(param.get(1));
			}catch (Exception e) {
				//use null;
			}
		}
		}
		if(min==null && max==null){
			throw new ValidatorNotFoundException(name+" need min or max value:"+line);
		}
		return Validators.rangedNumber(min, max);
	}
	else if(name.equals(Validators.VALIDATOR_MAX_STRING_SIZE)){
		if(param.size()!=1){
			throw new ValidatorNotFoundException(name+" need size attribute:"+line);
		}else{
			int size;
			try{
				size=Integer.parseInt(param.get(0));
			}catch (Exception e) {
				throw new ValidatorNotFoundException(name+" invalid size attribute:"+line);
			}
			validator=Validators.maxStringSize(size);
		}
	}
	else if(name.equals(Validators.VALIDATOR_MAX_STRING_BYTE_SIZE)){
		if(param.size()!=1){
			throw new ValidatorNotFoundException(name+" need size attribute:"+line);
		}else{
			int size;
			try{
				size=ValuesUtils.parseByte(param.get(0));
			}catch (Exception e) {
				throw new ValidatorNotFoundException(name+" invalid size attribute:"+line);
			}
			validator=Validators.maxStringByteSize(size);
		}
	}
	else if(name.equals(Validators.VALIDATOR_BETWEEN_STRING_SIZE)){
		if(param.size()!=2){
			throw new ValidatorNotFoundException(name+" need min and max attribute:"+line);
		}else{
			int min;
			int max;
			try{
				min=Integer.parseInt(param.get(0));
				max=Integer.parseInt(param.get(1));
			}catch (Exception e) {
				throw new ValidatorNotFoundException(name+" invalid size attribute:"+line);
			}
			validator=Validators.betweenStringSize(min,max);
		}
	}else if(name.equals(Validators.VALIDATOR_AVAIABLE_VALUE_ONLY)){
		if(param.size()<2){
			throw new ValidatorNotFoundException(name+" need at leaset 2 attributes:"+line);
		}else{
			boolean bool;
			try{
				String v=param.get(0).toLowerCase();
				if(v.equals("true")){
					bool=true;
				}else if(v.equals("false")){
					bool=false;
				}else{
					throw new Exception();
				}
			}catch (Exception e) {
				throw new ValidatorNotFoundException(name+" invalid boolean attribute:"+line);
			}
			List<String> values=new ArrayList<String>();
			for(int i=1;i<param.size();i++){
				values.add(param.get(i));
			}
			validator=Validators.avaiableValueOnly(values, bool);
		}
	}

	if(validator!=null){
	validatorMap.put(line, validator);
	return validator;
	}

	throw new ValidatorNotFoundException("not found:"+line);
}

public static boolean contain(List<Validator> validators,String checkName){
	if(checkName==null || checkName.isEmpty()){
		return false;
	}
	checkName=checkName.toLowerCase();
	for(Validator validator:validators){
		String name=validator.getName().toLowerCase();
		if(name.equals(checkName)){
			return true;
		}
	}

	return false;
}

public static boolean hasLimitValidator(List<Validator> validators){

	for(Validator validator:validators){
		String name=validator.getName().toLowerCase();
		if(name.equals("max")||name.equals("maxb")|| name.equals("between")){
			return true;
		}
	}

	return false;
}
public static boolean hasNumberValidator(List<Validator> validators){

	for(Validator validator:validators){
		String name=validator.getName().toLowerCase();
		if(name.equals("asciiNumber")||name.equals("integerNumber")|| name.equals("range")||name.equals("asciiNumber")){
			return true;
		}
	}

	return false;
}
/*
	private static void init(){
		bimap=HashBiMap.create();
		bimap.put(StaticValidators.VALIDATOR_NOT_EMPTY.toLowerCase(), StaticValidators.notEmptyValidator());
		bimap.put(StaticValidators.VALIDATOR_ASCII_NUMBER.toLowerCase(), StaticValidators.asciiNumberOnly());
		bimap.put(StaticValidators.VALIDATOR_ASCII_NUMBER_AND_CHAR.toLowerCase(), StaticValidators.asciiNumberAndCharOnly());
		bimap.put(StaticValidators.VALIDATOR_ASCII_NUMBER_AND_CHAR_AND_UNDERBAR.toLowerCase(), StaticValidators.asciiNumberAndCharAndUnderbarOnly());

		bimap.put(StaticValidators.VALIDATOR_HANKAKU_KANA.toLowerCase(), StaticValidators.hankakuKana());
		bimap.put(StaticValidators.VALIDATOR_HIRAGANA.toLowerCase(), StaticValidators.hiragana());

		bimap.put(StaticValidators.VALIDATOR_ASCII_CHAR.toLowerCase(), StaticValidators.asciiCharOnly());
		bimap.put(StaticValidators.VALIDATOR_START_ASCII_CHAR.toLowerCase(), StaticValidators.startAsciiChar());

		//TODO should support name contain args like msize(12),bet(6:12)
		bimap.put("between", Validators.betweenStringSize(6, 12));

		bimap.put("less8", Validators.maxStringSize(8));
		bimap.put("less8b", Validators.maxStringByteSize(8));

		bimap.put("less64", Validators.maxStringSize(64));
		bimap.put("less128", Validators.maxStringSize(128));
		bimap.put("less256", Validators.maxStringSize(256));

		bimap.put("less500", Validators.maxStringSize(500));
		bimap.put("less1m", Validators.maxStringByteSize(1024*1024));
	}*/

	public static class ValidatorNotFoundException extends Exception{

		public ValidatorNotFoundException(String string) {
			super(string);
		}

		/**
		 *
		 */
		private static final long serialVersionUID = 1L;

	}

	public static String getValidatorLabel(Validator validator) {
		return validator.toString();
		/*
		String label= bimap.inverse().get(validator);
		if(label==null){
			return validator.getName();
		}else{
			return label;
		}
		*/
	}
	/**
	 * use lower case inside
	 * @param key
	 * @return
	 */
	/*
	public static Validator getValidator(String key)throws ValidatorNotFoundException {
		if(bimap==null){
			init();
		}
		if(key==null){
			throw new ValidatorNotFoundException("null validator key");
		}
		Validator v= bimap.get(key.toLowerCase());
		if(v==null){
			throw new ValidatorNotFoundException("null validator for "+key);
		}
		return v;
	}*/
}


text:
import * as React from 'react';
import {ClientRenderer, expect, simulate, sinon} from 'test-drive-react';

import {ToggleDemo} from '../../demo/components/toggle-demo';
import {Toggle} from '../../src';
import styles from '../../src/components/toggle/toggle.st.css';
import {ToggleDriver} from '../../test-kit';
import {hasCssState} from '../utils';

describe('<Toggle/>', () => {
    const clientRenderer = new ClientRenderer();
    afterEach(() => clientRenderer.cleanup());

    describe('render without options', () => {
        let onChange: any;
        let renderer: any;
        beforeEach(() => {
            onChange = sinon.spy();
            renderer = clientRenderer.render(<Toggle onChange={onChange}/>).withDriver(ToggleDriver);
        });
        it('should have input', () => {
            expect(renderer.driver.nativeInput).to.not.null;
        });
    });

    describe('render with value={true}', () => {
        let onChange: any;
        let renderer: any;
        beforeEach(() => {
            onChange = sinon.spy();
            renderer = clientRenderer.render(<Toggle onChange={onChange} value={true}/>).withDriver(ToggleDriver);
        });
        it('should have input', () => {
            expect(renderer.driver.nativeInput).to.not.null;
        });
    });

    describe('render with onChange', () => {
        let onChange: any;
        let renderer: any;
        beforeEach(() => {
            onChange = sinon.spy();
            renderer = clientRenderer.render(<Toggle onChange={onChange}/>).withDriver(ToggleDriver);
        });

        it('pressing space on focused input should trigger onChange', () => {
            renderer.driver.click();
            expect(onChange).to.have.been.calledOnce;
            expect(onChange).to.have.been.calledWithExactly({value: true});
        });
    });

    describe('render with disabled={true}', () => {
        let onChange: any;
        let renderer: any;
        beforeEach(() => {
            onChange = sinon.spy();
            renderer = clientRenderer.render(<Toggle onChange={onChange} disabled/>).withDriver(ToggleDriver);
        });
        it('should not have input underhood', () => {
            expect(renderer.driver.nativeInput).to.be.null;
        });

        it('click should not trigger onChange', async () => {
            renderer.driver.click();
            await new Promise(resolve => setTimeout(resolve, 500));
            expect(onChange).to.not.have.been.called;
        });
    });

    describe('render <ToggleDemo/>', () => {
        let renderer: any;
        beforeEach(() => {
            renderer = clientRenderer.render(<ToggleDemo/>);
        });

        describe('contorolled toggle', () => {
            let toggle: any;
            beforeEach(() => {
                toggle = renderer.select('TOGGLE_DEMO_CONTROLLED', 'TOGGLE');
            });
            it('should render toggle', () => {
                expect(toggle).to.not.null;
            });
            it('should be unchecked', () => {
                hasCssState(toggle, styles, {checked: false});
            });
            it('should be checked after click', () => {
                simulate.change(toggle.querySelector('input'));
                hasCssState(toggle, styles, {checked: true});
            });
        });

        describe('readonly toggle', () => {
            let toggle: any;
            beforeEach(() => {
                toggle = renderer.select('TOGGLE_DEMO_UNCONTROLLED', 'TOGGLE');
            });
            it('should render toggle', () => {
                expect(toggle).to.not.null;
            });
            it('should be unchecked', () => {
                hasCssState(toggle, styles, {checked: false});
            });
            it('should be unchecked after click', () => {
                simulate.change(toggle.querySelector('input'));
                hasCssState(toggle, styles, {checked: false});
            });
        });
    });

});


text:
namespace net {

class QuicConfig;
class QuicCryptoClientConfig;
class QuicHttpStream;
class QuicStreamFactory;
class QuicChromiumClientSession;
class QuicClientPushPromiseIndex;

namespace test {

class QuicStreamFactoryPeer {
 public:
  static const QuicConfig* GetConfig(QuicStreamFactory* factory);

  static QuicCryptoClientConfig* GetCryptoConfig(QuicStreamFactory* factory);

  static bool HasActiveSession(QuicStreamFactory* factory,
                               const QuicServerId& server_id);

  static bool HasActiveCertVerifierJob(QuicStreamFactory* factory,
                                       const QuicServerId& server_id);

  static QuicChromiumClientSession* GetActiveSession(
      QuicStreamFactory* factory,
      const QuicServerId& server_id);

  static std::unique_ptr<QuicHttpStream> CreateFromSession(
      QuicStreamFactory* factory,
      QuicChromiumClientSession* session);

  static bool IsLiveSession(QuicStreamFactory* factory,
                            QuicChromiumClientSession* session);

  static void SetTaskRunner(QuicStreamFactory* factory,
                            base::TaskRunner* task_runner);

  static int GetNumberOfLossyConnections(QuicStreamFactory* factory,
                                         uint16_t port);

  static bool IsQuicDisabled(QuicStreamFactory* factory, uint16_t port);

  static bool GetDelayTcpRace(QuicStreamFactory* factory);

  static void SetDelayTcpRace(QuicStreamFactory* factory, bool delay_tcp_race);

  static bool GetRaceCertVerification(QuicStreamFactory* factory);

  static void SetRaceCertVerification(QuicStreamFactory* factory,
                                      bool race_cert_verification);

  static QuicAsyncStatus StartCertVerifyJob(QuicStreamFactory* factory,
                                            const QuicServerId& server_id,
                                            int cert_verify_flags,
                                            const BoundNetLog& net_log);

  static void SetYieldAfterPackets(QuicStreamFactory* factory,
                                   int yield_after_packets);

  static void SetYieldAfterDuration(QuicStreamFactory* factory,
                                    QuicTime::Delta yield_after_duration);

  static size_t GetNumberOfActiveJobs(QuicStreamFactory* factory,
                                      const QuicServerId& server_id);

  static int GetNumTimeoutsWithOpenStreams(QuicStreamFactory* factory);

  static int GetNumPublicResetsPostHandshake(QuicStreamFactory* factory);

  static void MaybeInitialize(QuicStreamFactory* factory);

  static bool HasInitializedData(QuicStreamFactory* factory);

  static bool SupportsQuicAtStartUp(QuicStreamFactory* factory,
                                    HostPortPair host_port_pair);

  static bool CryptoConfigCacheIsEmpty(QuicStreamFactory* factory,
                                       const QuicServerId& quic_server_id);

  // Creates a dummy QUIC server config and caches it.
  static void CacheDummyServerConfig(QuicStreamFactory* factory,
                                     const QuicServerId& quic_server_id);

  static QuicClientPushPromiseIndex* GetPushPromiseIndex(
      QuicStreamFactory* factory);

  static int GetNumPushStreamsCreated(QuicStreamFactory* factory);

 private:
  DISALLOW_COPY_AND_ASSIGN(QuicStreamFactoryPeer);
};

}  // namespace test
}  // namespace net

#endif  // NET_QUIC_TEST_TOOLS_QUIC_STREAM_FACTORY_PEER_H_


text:
// ***********************************************************************
// Copyright (c) 2017 Dominik Lachance
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************

using System;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Newtonsoft.Json;
using YellowJacket.Api.Extensions;
using YellowJacket.Models;

namespace YellowJacket.Api.Processors
{
    /// <inheritdoc />
    /// <summary>
    /// Used to handle Job Instance api request.
    /// </summary>
    /// <seealso cref="BaseProcessor" />
    public class JobInstanceProcessor : BaseProcessor
    {
        #region Private Members

        private readonly HttpClient _httpClient;

        #endregion

        #region Constructors

        /// <inheritdoc />
        /// <summary>
        /// Initializes a new instance of the <see cref="JobInstanceProcessor" /> class.
        /// </summary>
        /// <param name="httpClient">The HTTP client.</param>
        internal JobInstanceProcessor(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Gets the first job instance available.
        /// </summary>
        /// <param name="agentId">The agent identifier.</param>
        /// <returns><see cref="JobInstanceModel"/>.</returns>
        public async Task<JobInstanceModel> GetFirstAvailable(string agentId)
        {
            try
            {
                HttpResponseMessage httpResponseMessage =
                    await _httpClient.SendRequestAsync(HttpMethod.Get, $"/api/v1/jobinstance/firstAvailable/{agentId}", null);

                return
                    JsonConvert.DeserializeObject<JobInstanceModel>(await httpResponseMessage.Content.ReadAsStringAsync());
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }

            return null;
        }

        /// <summary>
        /// Updates the job instance.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns><see cref="AgentModel"/>.</returns>
        public async Task<JobInstanceModel> Update(JobInstanceModel model)
        {
            try
            {
                HttpResponseMessage httpResponseMessage =
                    await _httpClient.SendRequestAsync(HttpMethod.Put, $"/api/v1/jobinstance/{model.Id}", model);

                return
                    JsonConvert.DeserializeObject<JobInstanceModel>(await httpResponseMessage.Content.ReadAsStringAsync());
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }

            return null;
        }

        #endregion
    }
}


text:
<?php

class password_model extends CI_Model {

    public function get_data_by_email($email) {

        $this->db->select('*');
        $where = "(user_email='$email')";
        $this->db->where($where);
        $query = $this->db->get('users');
        return $query;
    }

    public function insert_token($token, $email) {
        $this->db->where('user_email', $email);
        $query = $this->db->update('users', array('token' => $token));
        return $query;
    }

    public function check_token($user_id) {
        $this->db->select('password_token');
        $this->db->where('user_id', $user_id);
        $token = $this->db->get('users');
        return $token->result();
    }

    public function get_id_by_token($token) {
        $this->db->select('*');
        $where = "(token='$token')";
        $this->db->where($where);
        $query = $this->db->get('users');
        return $query;
    }

    public function update_password($user_password,$user_id){
        $this->db->where('user_id', $user_id);
        $this->db->update('users', array('user_password' => (md5($user_password)), 'token' => (1)));
        return TRUE;

    }

}

?>


text:
<?php

/**
 * A class that maps integers (or a combination of them) to an array of values.
 *
 * @todo Allow different bad word handling strategies; such as string replacement.
 *
 * @category    Drake
 * @package     Drake_Filter
 * @copyright   Copyright (c) 2008-2010 Rob Zienert (http://robzienert.com)
 * @license     http://www.opensource.org/licenses/bsd-license.php New BSD License
 */
class Drake_Filter_BadWords implements Zend_Filter_Interface
{
    /**
     * A nested comma-delimited array of blacklisted words
     *
     * @var array
     */
    protected $_stopwords = array();

    /**
     * Path to the stopwords file
     *
     * @var string
     */
    protected static $_stopwordsFile;

    /**
     * Filter a value
     *
     * @param string $value
     * @return string
     */
    public function filter($value)
    {
        if (is_string($value)) {
            $this->_getStopwords();

            $value = explode(' ', $value);
            foreach ($value as $key => $part) {
                if (in_array(strtolower($part), $this->_stopwords)) {
                    unset($value[$key]);
                }
            }
            $value = implode(' ', $value);
        }

        return $value;
    }

    /**
     * Get the stopwords
     *
     * @return array
     */
    protected function _getStopwords()
    {
        $file = $this->getStopwordsFile();
        $this->_stopwords = preg_split("/[\n\r]+/", file_get_contents($file));

        return $this->_stopwords;
    }

    /**
     * Set the stopwords filepath
     *
     * @param string $file
     * @throws Drake_Filter_InvalidArgumentException
     * @return void
     */
    public static function setStopwordsFile($file)
    {
        if (!file_exists($file)) {
            throw new Drake_Filter_InvalidArgumentException("'$file' does not exist!");
        }

        self::$_stopwordsFile = $file;
    }

    /**
     * Get the stopwords filepath
     *
     * @throws Drake_Filter_RuntimeException
     * @return string
     */
    public static function getStopwordsFile()
    {
        if (null === self::$_stopwordsFile) {
            $file = dirname(__FILE__) . '/_files/badwords.txt';
            if (!file_exists($file)) {
                throw new Drake_Filter_RuntimeException(
                    'Stopwords file was not set and the default file could not be found');
            }
            self::$_stopwordsFile = $file;
        }

        return self::$_stopwordsFile;
    }
}


text:
<?xml version="1.0" ?>
<doc>
	<str name="Patent Number">
		US20090239135A1
	</str>
	<str name="Application Number">
		US12332535
	</str>
	<str name="Kind Code">
		A1
	</str>
	<str name="Title">
		BATTERY COVER AND PORTABLE ELECTRONIC DEVICE USING THE SAME
	</str>
	<str name="Abstract">
		A battery cover which detachably mounted on a portable electronic device to protect the battery of the portable electronic device. The battery cover includes a main cover and a sliding cover, the sliding cover is slidably mounted on the main cover. Two opposite ends of the main cover and the sliding cover each includes at least one tab or projection protruding there from respectively. The battery cover has a simple structure, and is easy for operating. The invention also includes a portable electronic device using the battery cover.
	</str>
	<str name="Document Types">
		US | USA | DOCDB
	</str>
	<str name="Application Date">
		2008-12-11
	</str>
	<str name="Application Year">
		2008
	</str>
	<str name="Application(Year/Month)">
		2008-12
	</str>
	<str name="Publication Date">
		2009-09-24
	</str>
	<str name="Publication Year">
		2009
	</str>
	<str name="Publication(Year/Month)">
		2009-09
	</str>
	<str name="All IPC">
		H01M2/10 | H01M2/00
	</str>
	<str name="IPC Primary">
		H01M2/10
	</str>
	<str name="IPC Section">
		H
	</str>
	<str name="IPC Class">
		H01
	</str>
	<str name="IPC Subclass">
		H01M
	</str>
	<str name="IPC Group">
		H01M2
	</str>
	<str name="All UPC">
		416/232 | 416/91 | 429/175 | 416/97R | 429/100
	</str>
	<str name="UPC Primary">
		416/232
	</str>
	<str name="UPC Class">
		416
	</str>
	<str name="Family Members">
		US20090239135A1 | CN101540384A
	</str>
	<str name="Family Member Count">
		2
	</str>
	<str name="Family Members Cited By Count">
		0
	</str>
	<str name="Other References Count">
		0
	</str>
	<str name="Priority Country">
		CN
	</str>
	<str name="Priority Number">
		200810300621.6
	</str>
	<str name="Priority Date">
		2008-03-18
	</str>
	<str name="Assignee(s)">
		SHENZHEN FUTAIHONG PRECISION INDUSTRY CO., LTD. | FIH (HONG KONG) LIMITED
	</str>
	<str name="1st Assignee">
		SHENZHEN FUTAIHONG PRECISION INDUSTRY CO., LTD.
	</str>
	<str name="Number of Assignees">
		2
	</str>
	<str name="1st Assignee Address">
		ShenZhen City,CN
	</str>
	<str name="Assignee(s) Address">
		ShenZhen City,CN | Kowloon,HK
	</str>
	<str name="Inventor(s)">
		WANG JUN | TU HSIAO-HUA | YANG GANG | SONG WEN-WEI | WANG YING-ZHUO
	</str>
	<str name="1st Inventor">
		WANG JUN
	</str>
	<str name="Number of Inventors">
		5
	</str>
	<str name="1st Inventor Address">
		Shenzhen City,CN
	</str>
	<str name="Inventor(s) Address">
		Shenzhen City,CN | Shindian,TW | Shenzhen City,CN | Shenzhen City,CN | Shenzhen City,CN
	</str>
	<str name="Agent/Attorney">
		PCE INDUSTRY, INC.,ATT. STEVEN REISS
	</str>
	<str name="cited by within 3 years">
		0
	</str>
	<str name="cited by within 5 years">
		0
	</str>
</doc>


text:
// Manage the small views in the sidebar, which show only a subset of the data
view.manageSideViews=function(animate){

// Compute the size of the histogram, as it impacts the number of authors that can be shown
var histogramWidth = Math.max(window.innerWidth/10,180),
    histogramHeight=150;

//////////////////      authors list       ///////////////////////////////

//------------------DATA JOIN-------------------//
var authors = d3.select("#authors-list").selectAll(".author")
.data(global.frequentAuthors)

//--------------------ENTER---------------------//
var enteringAuthors = authors.enter()
.append("li")
.attr("class","author")
.style("display",function(a,i) { return (i*20+164) < window.innerHeight-histogramHeight-20? "":"none";  })
// this is super ugly...

//------------------ENTER+UPDATE-------------------//
authors
.text(function(d) { return d.author + " (" + d.frequency + ")"; })

//--------------------EXIT---------------------//
authors.exit().remove();

//////////////////		histogram 		///////////////////////////////

var values=global.publicationYears();

var margin = {top: 10, right: 15, bottom: 30, left: 5},
    innerWidth = histogramWidth - margin.left - margin.right,
    innerHeight = histogramHeight - margin.top - margin.bottom;

// fixed boundaries to allow comparisons across different sets of papers
var x = d3.scale.linear()
    .domain([global.oldestPublicationYear, global.latestPublicationYear])
    .range([0, innerWidth])

// Generate a histogram using uniformly-spaced bins.
var data = d3.layout.histogram()
    //.bins(x.ticks(parameters.nBinsYears))
    .bins(x.ticks(global.latestPublicationYear-global.oldestPublicationYear))
    (values);

var y = d3.scale.linear()
    .domain([0, Math.max(3,d3.max(data, function(d) { return d.y; })) ])
    .range([innerHeight, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .ticks(parameters.nBinsYears)
    .tickFormat(d3.format("d"))
    .orient("bottom");

//--------------- draw static elements ----------//
d3.select("svg#publication-years").attr("width", innerWidth + margin.left + margin.right)
    .attr("height", innerHeight + margin.top + margin.bottom)

var histogram = d3.select("svg#publication-years #histogram")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

histogram.select("#x-axis")
    .attr("transform", "translate(0," + innerHeight + ")")
    .call(xAxis);

//------------------DATA JOIN-------------------//
var bars = histogram.selectAll(".bar")
    .data(data)

//--------------------ENTER---------------------//
var enteringBars = bars.enter()
    .append("g")
    .attr("class", "bar")
    .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

enteringBars.append("rect")
    .attr("x", 1)
    .attr("width", x(data[1].x)-x(data[0].x))
    .attr("y", function(d) { return innerHeight - y(d.y); })
    .attr("height", 0)

    .append("svg:title")
    .attr("class","tooltip")

/*
* Since the bars are very narrow, we don't show a number inside them
enteringBars.append("text")
    .attr("dy", ".75em")
    .attr("text-anchor", "middle")
    .attr("x", (x(data[1].x)-x(data[0].x)) / 2)
    .attr("y",innerHeight)
    .text(function(d) { return d.y>0? d.y : ""; });
*/

//------------------ENTER+UPDATE----------------//
var t0=bars.transition().duration(parameters.fringePapersPositionTransitionDuration[animate])
        .ease(parameters.fringePapersTransitionEasing)

t0.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

t0.select("rect")
    .attr("y", 0)
    .attr("height", function(d) { return innerHeight - y(d.y); })
    .attr("width", x(data[1].x)-x(data[0].x))

    .select(".tooltip")
    .text(function(d) { return d.y+" paper"+(d.y>1? "s":"")+" in "+d.x; })

/*t0.select("text")
    .attr("y", 6)
    .attr("x", (x(data[1].x)-x(data[0].x)) / 2)
    .text(function(d) { return d.y>0? d.y : ""; })*/

//--------------------EXIT---------------------//
// although this should probably never happen (always same number of bins)
bars.exit().remove();
}


text:
package LinkFuture.Core.MemoryManager.Meta;

import LinkFuture.Init.ObjectExtend.JAXBMapAdaptor;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.util.HashMap;

/**
 * User: Cyokin Zhang
 * Date: 10/12/13
 * Time: 2:19 PM
 */
@XmlRootElement(name="MemoryCacheConfiguration")
@XmlSeeAlso(MemorySettingInfo.class)
public class MemorySettingListInfo {

    @XmlElement(name="CacheSettingList")
    @XmlJavaTypeAdapter(value=JAXBMapAdaptor.class)
    public HashMap<String,MemorySettingInfo> SettingList;

    @XmlElement(name="RedisUrl")
    public String RedisUrl;
}


text:
<?php
return array(
	'_root_'  => 'story/index',  // The default route
	'_404_'   => '',    // The main 404 route

	//'hello(/:name)?' => array('welcome/hello', 'name' => 'hello'),
	'register' => 'users/register_character',
	'login' => 'users/login',
	'logout' => 'users/logout',
	'character_sheet' => 'character/sheet/view'
);


text:
/**
 * Created by Nicholas Hallahan on 1/22/15.
 * nhallahan@spatialdev.com
 */

package com.spatialdev.osm.renderer;

import android.graphics.Canvas;
import android.graphics.PointF;

import com.mapbox.mapboxsdk.R;
import com.mapbox.mapboxsdk.geometry.BoundingBox;
import com.mapbox.mapboxsdk.overlay.Icon;
import com.mapbox.mapboxsdk.overlay.Overlay;
import com.mapbox.mapboxsdk.views.MapView;
import com.spatialdev.osm.marker.OSMMarker;
import com.spatialdev.osm.model.JTSModel;
import com.spatialdev.osm.model.OSMColorConfig;
import com.spatialdev.osm.model.OSMNode;
import com.spatialdev.osm.model.OSMElement;
import com.spatialdev.osm.model.OSMWay;
import com.vividsolutions.jts.geom.Envelope;

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

public class OSMOverlay extends Overlay {

    private static final int DEFAULT_OVERLAY_INDEX = 4;

    private JTSModel model;
    private Envelope envelope;

    private float minVectorRenderZoom = 0;
    private float zoom = 0; // current zoom of map

    private List<OSMNode> viewPortNodes = new ArrayList<>();

    private boolean needToAddItemizedOverlay = true;

    /**
     * This should only be created by OSMMap.
     * * *
     * @param model
     */
    public OSMOverlay(JTSModel model) {
        this.model = model;
        setOverlayIndex(DEFAULT_OVERLAY_INDEX);
    }

    /**
     * This should only be created by OSMMap.
     * * *
     * @param model
     * @param minVectorRenderZoom
     */
    public OSMOverlay(JTSModel model, float minVectorRenderZoom) {
        this(model);
        this.minVectorRenderZoom = minVectorRenderZoom;
    }

    public void updateBoundingBox(BoundingBox bbox) {
        double x1 = bbox.getLonWest();
        double x2 = bbox.getLonEast();
        double y1 = bbox.getLatSouth();
        double y2 = bbox.getLatNorth();
        envelope = new Envelope(x1, x2, y1, y2);
    }

    /**
     * Have the map set the current zoom.
     * *
     * @param zoom
     */
    public void updateZoom(float zoom) {
        this.zoom = zoom;
    }

    public List<OSMNode> getViewPortNodes() {
        return viewPortNodes;
    }

    @Override
    protected void draw(Canvas c, MapView mapView, boolean shadow) {
        // no shadow support & need a bounding box to query rtree & at or above min render zoom
        if (shadow || envelope == null || zoom < minVectorRenderZoom) {
            return;
        }

        List<OSMWay> polys = new ArrayList<>();
        List<OSMWay> lines = new ArrayList<>();

        // We want to always be referring to the same list so external sources
        // do not reference stale lists.
        viewPortNodes.clear();

        List<OSMElement> viewPortElements = model.queryFromEnvelope(envelope);

        // Sort the elements into their geom types so we can draw
        // points on top of lines on top of polys.
        for (OSMElement el : viewPortElements) {
            if (el instanceof OSMWay) {
                OSMWay w = (OSMWay) el;
                if (w.isClosed()) {
                    polys.add(w);
                } else {
                    lines.add(w);
                }
                continue;
            }
            // If it isn't a Way, it's a Node.
            // We need to render the marker...
            renderMarker(mapView, (OSMNode) el);
        }

        // Draw polygons
        for (OSMWay w : polys) {
            w.getOSMPath(mapView).draw(c);
        }

        // Draw lines
        for (OSMWay w : lines) {
            w.getOSMPath(mapView).draw(c);
        }
    }

    private void renderMarker(MapView mapView, OSMNode node) {
        viewPortNodes.add(node);
        if (node.getMarker() == null) {
            OSMMarker marker = new OSMMarker(mapView, node);
            marker.setMarker(OSMColorConfig.getFocusOutDrawable(node, mapView.getContext().getResources().getDrawable(R.mipmap.maki_star_blue), mapView.getContext().getResources().getDrawable(R.mipmap.maki_star_white)));
            /**
             * Issue #81
             * setMarker doesn't position bitmaps in the same way as setIcon.
             * By setting the anchor, we bring down the image slightly so that the marker
             * does indeed point to the point it refers to.
             */
            PointF anchor = new PointF(0.5f, 0.8f);
            marker.setAnchor(anchor);
            mapView.addOSMMarker(this, marker);
        } else if (needToAddItemizedOverlay){
            mapView.setDefaultOSMItemizedOverlay(this);
            needToAddItemizedOverlay = false;
        }
    }

}


text:
// Segregated Binary-Buddy memory allocator.
// This is an implementation of a binary-buddy memory allocator that keeps
// its bookkeeping separate from the heap itself so that write-combined
// memory can be managed. To keep the bookkeeping small this uses a compact
// binary tree comprised of 1 bit per allocation block at any level rather
// than a linked-list freelist node. O(log n) allocation/free time.
// Per-sbb overhead: 32-bit: 24-bytes + pages; 64-bit: 32-bytes + pages.

#pragma once
#include <cstddef>

typedef struct sbb__ {}* sbb_t;

// returns the bytes required to maintain bookkeeping for the allocator
size_t sbb_bookkeeping_size(size_t arena_bytes, size_t min_block_size);

// initializes an sbb for the specified arena. Its size must be a power or two
// and the minimum block size must also be a power of two. bookkeeping should
// be allocated to the sized returned by sbb_bookkeeping_size.
sbb_t sbb_create(void* arena, size_t arena_bytes, size_t min_block_size, void* bookkeeping);

// deinitializes an sbb after this the sbb is no longer valid
void sbb_destroy(sbb_t sbb);

// returns the pointer passed as arena in sbb_create
void* sbb_arena(sbb_t sbb);

// returns the size specified for the arena in sbb_create
size_t sbb_arena_bytes(sbb_t sbb);

// returns the pointer passed as bookkeeping in sbb_create
void* sbb_bookkeeping(sbb_t sbb);

// returns the internal block size (not user size) allocated for ptr
// O(log n). If the size is already known, the blocks size is the next
// larget power of 2.
size_t sbb_block_size(sbb_t sbb, void* ptr);

// returns the minimum block size specified in sbb_create
size_t sbb_min_block_size(sbb_t sbb);

// returns the maximum block size currently available for allocation
// use this as a fragmentation hint
size_t sbb_max_free_block_size(sbb_t sbb);

// returns the number of blocks marked as free
// use this as a fragmentation hint
size_t sbb_num_free_blocks(sbb_t sbb);

// returns the fixed overhead for the allocator
size_t sbb_overhead(sbb_t sbb);

// walks used and largest available blocks
typedef void (*sbb_walker)(void* ptr, size_t size, int used, void* user);
void sbb_walk_heap(sbb_t sbb, sbb_walker walker, void* user);

// returns true if the heap is valid
bool sbb_check_heap(sbb_t sbb);

// common malloc api: bytes will be rounded to the next power of two consistent
// with the binary-buddy algorithm.
void* sbb_malloc(sbb_t sbb, size_t bytes);
void* sbb_realloc(sbb_t sbb, void* ptr, size_t bytes);
void sbb_free(sbb_t sbb, void* ptr);
void* sbb_memalign(sbb_t sbb, size_t align, size_t bytes);


text:
<?php

namespace Schema\Bundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class SchemaBundle extends Bundle
{
}


text:
require 'green_shoes'
require_relative './../lib/player'

Shoes.app title: "Mp3 Player", top: 0, left: 0, width: 400, height: 200 do
  @player = Player.new :audite
  background "#dadada"
  stack margin: 10 do

    flow margin_left: 10 do
      button('Open') do
        filename = ask_open_file
        filename = filename.split('/').last if filename.include? ".yaml"
        @player.play filename
        #song.text = @player.current_song[:title] + " - " + @player.current_song[:artist]
      end
      button('Filter') do

      end
    end
    fill lime
    @progress_bar = rect(left:  20, top: 50, width: 360, height: 6)
    fill black
    @progress_handle = rect(left: 20, top: 44, width: 6, height: 18)
    @move = false

    @progress_bar.click do
      left = @progress_handle.left
      @progress_handle.move mouse[1], 44
      #@player.seek_forward (@progress_handle.left - left).floor
    end

    @progress_handle.click do
      @move = true
      motion do |left, top|
        if left >= 20 and left <= 380 and @move
          @progress_handle.move left, 44
        end
      end
    end

    release do
      @move = false
    end

    @player.player.adapter.events.on(:position_change) do |pos|
      @progress_handle.move 20 + pos.floor * @player.player.adapter.length_in_seconds / 360, 44
    end

  end

end


text:
<templates type="mustache">
    <template name="Plugin.h">
        <config id="Plugin.h" name="Plugin Hdr">

        </config>
        <content>
            <![CDATA[
#pragma once

#include <core/ext/Plugin.h>

namespace Quartz {

class QzAppContext;

namespace Ext { namespace {{PLUGIN_NAMESPACE}} {

class Plugin : public Ext::Plugin
{

public:
    Plugin();

    ~Plugin();

    const ExtensionList & extensions() const override;

    const DependencyList & dependencies() const override;

    const AdapterList &adapters() const override;

    static const QString PLUGIN_ID;

    static const QString PLUGIN_NAME;

private:
    struct Data;
    std::unique_ptr<Data> m_data;
};

} } }
            ]]>
        </content>
    </template>
</templates>


text:
package org.eknet.publet.gitr.partition

import java.io.File
import org.eknet.publet.vfs.fs.DirectoryResource
import org.eknet.publet.vfs.{ContainerResource, Path, Resource}
import com.google.common.eventbus.EventBus

class GitDirectory(dir: File,
                   root: Path,
                   gp: GitPartition)
    extends DirectoryResource(dir, root, gp.bus) with ContainerResource {

  override protected def newDirectory(f: File, root: Path, bus: EventBus) = GitPartition.newDirectory(f, root, gp)

  override protected def newFile(f: File, root: Path, bus: EventBus) = GitPartition.newFile(f, root, gp)

  override def children: Iterable[_ <: Resource] = super.children.filterNot(_.name.name.startsWith(".git"))

}


text:
function checkRelationships(data) {
    var relName = data[0];
    var relLength = relName.length;
    var removed = 0;
    $("#mySelect option").each(function (index,element) {
        console.log(index);
        console.log(element.value);
        console.log(element.text);
//        var fileName = $(this).val().split(/[\\/]/).pop();
//        if (fileName.substr(0, relLength) == relName) {
        //Remove the relationship metadata
        if(strstr(fileName,relName+'MetaData.php')!=false) {
            console.log('Removed: ' + $(this).val());
            $("#mySelect option[value='"+element.value+"']").remove();
            removed++;
            counter--;
            updateCounter();
        }
    });
    if (removed > 0) {
        return true;
    } else {
        return false;
    }
}

function addRelationshipTable() {
    var table1 = $('#relationship_table').DataTable({
        dom: 'Bfrtip',
        buttons: [
            'selectNone',
            'selectAll'
        ],
        select: {
            style: 'multi'
        }
    });
    $('#relationship_table tbody').on('click', 'tr', function () {
        var id = table1.row( this ).index();
        //Add remove from the selected list
        var index = $.inArray(id, selectList);
        var data = table1.row( this ).data();
        if ($(this).hasClass('selected')) {
            selectList.push( id );
            console.log('add');
            console.log(selectList);
            if(checkRelationships(data)) {
                $().toastmessage('showToast', {
                    text     : 'Removed relationship files from installdefs',
                    stayTime: 	3000,
                    sticky   : false,
                    position : 'top-right',
                    type     : 'warning',
                    close    : function () {console.log("Closed Relationship message...");}
                });
            }
        } else {
            selectList.splice( id, 1 );
            console.log('remove');
            console.log(selectList);
        }
    } );
}

function strstr(haystack, needle, bool) {
    // Finds first occurrence of a string within another
    //
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/strstr    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: strstr('Kevin van Zonneveld', 'van');
    // *     returns 1: 'van Zonneveld'    // *     example 2: strstr('Kevin van Zonneveld', 'van', true);
    // *     returns 2: 'Kevin '
    // *     example 3: strstr('name@example.com', '@');
    // *     returns 3: '@example.com'
    // *     example 4: strstr('name@example.com', '@', true);    // *     returns 4: 'name'
    var pos = 0;

    haystack += "";
    pos = haystack.indexOf(needle); if (pos == -1) {
        return false;
    } else {
        if (bool) {
            return haystack.substr(0, pos);
        } else {
            return haystack.slice(pos);
        }
    }
}


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

public class LagBomb : MonoBehaviour {

    public GameObject ExplosionRoot;
    public GameObject ShellRoot;
    public ParticleSystem ps1, ps2, ps3;
    private bool firing;
    private HarmonicUtils.LerpContext BombLerp;
    private float radius;
    private ICombatant sender;

    public void Fire (ICombatant attacker, Vector3 target, float duration, float lagPenalty, float radius = 60f) {
        this.firing = true;
        this.radius = radius;
        this.sender = attacker;
        BombLerp = new HarmonicUtils.LerpContext(duration)
        {
            From = this.transform.position,
            To = target
        };

        ExplosionRoot.SetActive(false);
        ShellRoot.SetActive(true);
    }

	// Update is called once per frame
	void Update () {
        if (firing)
        {
            if (BombLerp.IsPastDuration())
            {
                this.transform.position = BombLerp.Finalize();
                ExplodeLagBomb();
            }
            else
            {
                this.transform.position = BombLerp.Lerp();
                BombLerp.CurrentTime += InterruptTime.deltaTime;
            }
        }
    }

    private void ExplodeLagBomb()
    {
        firing = false;

        LagTargetsInProximity(this.transform.position);

        ExplosionRoot.SetActive(true);
        //doesn''t work!
        //ExplosionRoot.GetComponent<ParticleSystem>().Play(true);
        ps1.Play();
        //it's a bug,
        //https://issuetracker.unity3d.com/issues/particle-system-plays-only-once
        //how the heck is this a workaround
        ps2.Play();
        ps2.startLifetime = ps2.startLifetime;
        ps3.Play();
        ps3.startLifetime = ps3.startLifetime;

        ShellRoot.SetActive(false);
        StartCoroutine(LetExplode());
    }

    private IEnumerator LetExplode()
    {
        yield return new WaitForSeconds(3f);
        ps1.Stop();
        ps2.Stop();
        ps3.Stop();
        //doesn't work!
        //ExplosionRoot.GetComponent<ParticleSystem>().Stop(true);
        //ExplosionRoot.GetComponent<ParticleSystem>().Clear(true);
    }

    private void LagTargetsInProximity(Vector3 position)
    {
        foreach(IMalware m in ActiveSubroutines.MalwareList)
        {
            if ((position - m.transform.position).sqrMagnitude < radius * radius)
            {
#warning if sender is dead this causes NRE
                sender.DoAttack(m, AttackType.Lag);
            }
        }
    }
}


text:
using FrannHammer.Domain.Contracts;
using FrannHammer.Utility;
using FrannHammer.WebScraping.Contracts;
using FrannHammer.WebScraping.Contracts.Attributes;
using FrannHammer.WebScraping.Contracts.HtmlParsing;

namespace FrannHammer.WebScraping.Attributes
{
    public class DefaultAttributeScrapingServices : IAttributeScrapingServices
    {
        private readonly IAttributeProvider _attributeProvider;
        private readonly IWebServices _webServices;

        public DefaultAttributeScrapingServices(IAttributeProvider attributeProvider, IWebServices webServices)
        {
            Guard.VerifyObjectNotNull(attributeProvider, nameof(attributeProvider));
            _attributeProvider = attributeProvider;
            _webServices = webServices;
        }

        public IAttribute CreateAttribute() => _attributeProvider.CreateAttribute();
        public ICharacterAttributeRow CreateCharacterAttributeRow() => _attributeProvider.CreateCharacterAttributeRow();
        public IHtmlParser CreateParserFromSourceUrl(string url)
        {
            return _webServices.CreateParserFromSourceUrl(url);
        }
    }
}


text:
using MeetMe.Data.Models;

namespace MeetMe.Services.Contracts
{
    public interface IConversationFactory
    {
        Conversation CreateConversation(string firstUserId, string secondUserId);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    tools:context="com.nightonke.wowoviewpagerexample.WoWoScaleAnimationActivity">

    <com.nightonke.wowoviewpager.WoWoViewPager
        android:id="@+id/wowo_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

    <!--The view that need to play a scale animation-->
    <View
        android:id="@+id/test"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_centerInParent="true"
        android:background="@drawable/background_scale"
        />

    <TextView style="@style/PageIndexTextView" />

</RelativeLayout>


text:
layout: page
title: resume
permalink: /resume/
description:
nav: true
---
---
<object data="../assets/pdf/resume/resume.pdf" width="1000" height="1000" type='application/pdf'>
</object>


text:
package com.amee.platform.resource.dataitem.v_3_0;

import com.amee.base.domain.Since;
import com.amee.base.resource.RequestWrapper;
import com.amee.base.transaction.AMEETransaction;
import com.amee.domain.data.DataCategory;
import com.amee.domain.item.data.DataItem;
import com.amee.platform.resource.ResourceService;
import com.amee.platform.resource.dataitem.DataItemResource;
import com.amee.platform.resource.dataitem.v_3_4.DataItemBuilder_3_4_0;
import com.amee.service.auth.ResourceAuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Scope("prototype")
@Since("3.0.0")
public class DataItemBuilder_3_0_0 extends DataItemBuilder_3_4_0 {

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private ResourceAuthorizationService resourceAuthorizationService;

    /**
     * Override because version 3.0 does not support the startDate parameter.
     *
     * @param requestWrapper the current {@link RequestWrapper}
     * @return the response object
     */
    @Override
    @AMEETransaction
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Object handle(RequestWrapper requestWrapper) {

        // Get resource entities for this request.
        DataCategory dataCategory = resourceService.getDataCategoryWhichHasItemDefinition(requestWrapper);
        DataItem dataItem = resourceService.getDataItem(requestWrapper, dataCategory);

        // Authorized for DataItem?
        resourceAuthorizationService.ensureAuthorizedForBuild(
                requestWrapper.getAttributes().get("activeUserUid"), dataItem);

        // Handle the DataItem.
        handle(requestWrapper, dataItem);
        DataItemResource.Renderer renderer = getRenderer(requestWrapper);
        renderer.ok();
        return renderer.getObject();
    }
}


text:
package scalapb.lenses

import munit.FunSuite

case class Person(firstName: String, lastName: String, age: Int, address: Address)
    extends Updatable[Person]

case class Address(street: String, city: String, state: String, residents: Seq[Person] = Nil)
    extends Updatable[Address]

case class Role(name: String, person: Person, replacement: Option[Person] = None)
    extends Updatable[Role]

case class MapTest(
    intMap: Map[Int, String] = Map.empty,
    nameMap: Map[String, Person] = Map.empty,
    addressMap: Map[Person, Address] = Map.empty
) extends Updatable[MapTest]

case class CollectionTypes(
    iSeq: collection.immutable.Seq[String] = Nil,
    vector: Vector[String] = Vector.empty,
    list: List[String] = Nil,
    sett: Set[String] = Set.empty
) extends Updatable[CollectionTypes]

class SimpleTest extends FunSuite {
  implicit class RoleMutation[U](f: Lens[U, Role]) extends ObjectLens[U, Role](f) {
    def name = field(_.name)((p, f) => p.copy(name = f))

    def person = field(_.person)((p, f) => p.copy(person = f))

    def replacement = field(_.replacement)((p, f) => p.copy(replacement = f))
  }

  implicit class PersonMutation[U](f: Lens[U, Person]) extends ObjectLens[U, Person](f) {
    def firstName = field(_.firstName)((p, f) => p.copy(firstName = f))

    def lastName = field(_.lastName)((p, f) => p.copy(lastName = f))

    def address: Lens[U, Address] = field(_.address)((p, f) => p.copy(address = f))
  }

  implicit class AddressLens[U](val f: Lens[U, Address]) extends ObjectLens[U, Address](f) {
    def city = field(_.city)((p, f) => p.copy(city = f))

    def street = field(_.street)((p, f) => p.copy(street = f))

    def residents: Lens[U, Seq[Person]] = field(_.residents)((p, f) => p.copy(residents = f))
  }

  implicit class MapTestLens[U](val f: Lens[U, MapTest]) extends ObjectLens[U, MapTest](f) {
    def intMap = field(_.intMap)((p, f) => p.copy(intMap = f))

    def nameMap = field(_.nameMap)((p, f) => p.copy(nameMap = f))

    def addressMap = field(_.addressMap)((p, f) => p.copy(addressMap = f))
  }

  implicit class CollectionTypesLens[U](val f: Lens[U, CollectionTypes])
      extends ObjectLens[U, CollectionTypes](f) {
    def iSeq = field(_.iSeq)((p, f) => p.copy(iSeq = f))

    def vector = field(_.vector)((p, f) => p.copy(vector = f))

    def list = field(_.list)((p, f) => p.copy(list = f))

    def sett = field(_.sett)((p, f) => p.copy(sett = f))
  }

  object RoleMutation extends RoleMutation(Lens.unit)

  val mosh = Person(
    firstName = "Mosh",
    lastName = "Ben",
    age = 19,
    address = Address("Main St.", "San Jose", "CA")
  )
  val josh = Person(
    firstName = "Josh",
    lastName = "Z",
    age = 19,
    address = Address("Fremont", "Sunnyvale", "CA")
  )
  val chef = Role(name = "Chef", person = mosh)

  val mapTest = MapTest(
    intMap = Map(3 -> "three", 4 -> "four"),
    addressMap = Map(mosh -> Address("someStreet", "someCity", "someState"))
  )

  test("update should return an updated object") {
    assertEquals(
      mosh.update(_.firstName := "foo"),
      (mosh.copy(firstName = "foo"))
    )
  }

  test("it should allow mutating nested fields") {
    assertEquals(
      mosh.update(_.address.city := "Valejo"),
      (mosh.copy(
        address = mosh.address.copy(city = "Valejo")
      ))
    )
  }

  test("it should allow nested updates") {
    assertEquals(
      mosh.update(
        _.address.update(
          _.city   := "Valejo",
          _.street := "Fourth"
        )
      ),
      (mosh.copy(address = mosh.address.copy(city = "Valejo", street = "Fourth")))
    )
  }

  test("it should allow replacing an entire field") {
    val portland = Address("2nd", "Portland", "Oregon")
    assertEquals(mosh.update(_.address := portland), (mosh.copy(address = portland)))
  }

  test("it should support an existing value for an optional set") {
    assertEquals(mosh.update(_.firstName setIfDefined Some("foo")), mosh.copy(firstName = "foo"))
  }

  test("it should support a non-existing value for an optional set") {
    assertEquals(mosh.update(_.firstName setIfDefined None), mosh)
  }

  test("it should allow adding to a sequence") {
    assertEquals(
      mosh.update(_.address.residents :+= josh),
      (mosh.copy(
        address = mosh.address.copy(residents = mosh.address.residents :+ josh)
      ))
    )
  }

  test("it should allow replacing a sequence") {
    assertEquals(
      mosh.update(_.address.residents := Seq(josh, mosh)),
      (mosh.copy(
        address = mosh.address.copy(residents = Seq(josh, mosh))
      ))
    )
  }

  test("it should allow mutating an element of a sequence by index") {
    assertEquals(
      mosh.update(
        _.address.residents              := Seq(josh, mosh),
        _.address.residents(1).firstName := "ModName"
      ),
      (mosh.copy(
        address = mosh.address.copy(residents = Seq(josh, mosh.copy(firstName = "ModName")))
      ))
    )
  }

  test("it should allow mutating all element of a sequence with forEach") {
    assertEquals(
      mosh.update(
        _.address.residents := Seq(josh, mosh),
        _.address.residents.foreach(_.lastName.modify(_ + "Suffix"))
      ),
      (mosh.copy(
        address = mosh.address
          .copy(residents = Seq(josh.copy(lastName = "ZSuffix"), mosh.copy(lastName = "BenSuffix")))
      ))
    )
  }

  test("it should allow mapping over an option") {
    assertEquals(
      chef.update(
        _.replacement.inplaceMap(_.firstName := "Zoo")
      ),
      chef
    )

    assertEquals(
      chef
        .update(
          _.replacement := Some(josh),
          _.replacement.inplaceMap(_.firstName := "Yosh")
        )
        .replacement
        .get,
      (josh.copy(firstName = "Yosh"))
    )
  }

  test("it should allow updating a map") {
    assertEquals(
      mapTest.update(_.intMap(5) := "hello"),
      (mapTest.copy(
        intMap = mapTest.intMap.updated(5, "hello")
      ))
    )
    assertEquals(
      mapTest.update(_.intMap(2) := "ttt"),
      (mapTest.copy(
        intMap = mapTest.intMap.updated(2, "ttt")
      ))
    )
    assertEquals(
      mapTest.update(_.nameMap("mmm") := mosh),
      (mapTest.copy(
        nameMap = mapTest.nameMap.updated("mmm", mosh)
      ))
    )
    assertEquals(
      mapTest.update(_.addressMap(josh) := mosh.address),
      (mapTest.copy(
        addressMap = mapTest.addressMap.updated(josh, mosh.address)
      ))
    )
  }

  test("it should allow nested updated in a map") {
    assertEquals(
      mapTest.update(_.nameMap("mosh") := mosh, _.nameMap("mosh").firstName := "boo"),
      (mapTest
        .copy(nameMap = mapTest.nameMap.updated("mosh", mosh.copy(firstName = "boo"))))
    )
  }

  test("it should raise an exception on nested key update for a missing key") {
    intercept[NoSuchElementException] {
      mapTest.update(
        _.nameMap("mosh").firstName := "Boo"
      )
    }
  }

  test("it should allow transforming the map values with forEachValue") {
    assertEquals(
      mapTest
        .update(
          _.nameMap("mosh") := mosh,
          _.nameMap("josh") := josh,
          _.nameMap.foreachValue(_.firstName := "ttt")
        )
        .nameMap
        .values
        .map(_.firstName)
        .toSeq,
      (Seq("ttt", "ttt"))
    )
  }

  test("it should allow transforming the map values with mapValues") {
    assertEquals(
      mapTest
        .update(
          _.intMap.mapValues("hello " + _)
        )
        .intMap,
      (Map(3 -> "hello three", 4 -> "hello four"))
    )

    assertEquals(
      mapTest
        .update(
          _.nameMap("mosh") := mosh,
          _.nameMap("josh") := josh,
          _.nameMap.mapValues(m => m.update(_.firstName := "*" + m.firstName))
        )
        .nameMap
        .values
        .map(_.firstName)
        .toSeq,
      (Seq("*Mosh", "*Josh"))
    )
  }

  test("it should allow transforming the map values with forEach") {
    assertEquals(
      mapTest.update(_.intMap.foreach(_.modify(k => (k._1 - 1, "*" + k._2)))).intMap,
      Map(
        2 -> "*three",
        3 -> "*four"
      )
    )
  }

  test("it should support other collection types") {
    val ct = CollectionTypes().update(
      _.iSeq := collection.immutable.Seq("3", "4", "5"),
      _.iSeq :+= "foo",
      _.iSeq :++= collection.immutable.Seq("6", "7", "8"),
      _.iSeq :++= Seq("6", "7", "8"),
      _.iSeq(5) := "11",
      _.vector  := Vector("3", "4", "5"),
      _.vector :+= "foo",
      _.vector :++= collection.immutable.Seq("6", "7", "8"),
      _.vector :++= Seq("6", "7", "8"),
      _.vector(5) := "11",
      _.list      := List("3", "4", "5"),
      _.list :+= "foo",
      _.list :++= collection.immutable.Seq("6", "7", "8"),
      _.list :++= Seq("6", "7", "8"),
      _.list(5) := "11",
      _.sett    := Set("3", "4", "5"),
      _.sett :+= "foo",
      _.sett :++= collection.immutable.Seq("6", "7", "8"),
      _.sett :++= Seq("6", "7", "8")
    )
    val expected = Seq("3", "4", "5", "foo", "6", "11", "8", "6", "7", "8")
    assertEquals(ct.iSeq.toVector, expected.toVector)
    assertEquals(ct.vector, expected.toVector)
    assertEquals(ct.list, expected.toList)
  }

  test("it should work with zipped lenses") {
    assertEquals(
      CollectionTypes().update(k => k.list zip k.vector := ((List("3", "4"), Vector("x", "y")))),
      CollectionTypes(
        list = List("3", "4"),
        vector = Vector("x", "y")
      )
    )
  }
}


text:
package oci // import "github.com/docker/docker/oci"

import specs "github.com/opencontainers/runtime-spec/specs-go"

// RemoveNamespace removes the `nsType` namespace from OCI spec `s`
func RemoveNamespace(s *specs.Spec, nsType specs.LinuxNamespaceType) {
	for i, n := range s.Linux.Namespaces {
		if n.Type == nsType {
			s.Linux.Namespaces = append(s.Linux.Namespaces[:i], s.Linux.Namespaces[i+1:]...)
			return
		}
	}
}


text:
package com.raycoarana.baindo.state.saver;

import android.os.Bundle;
import android.os.Parcelable;

import com.raycoarana.baindo.state.ValueSaver;

public class ParcelableArrayValueSaver implements ValueSaver<Parcelable[]> {

    @Override
    public void save(Bundle state, String key, Parcelable[] value) {
        state.putParcelableArray(key, value);
    }

}