text:
<?php

namespace Symfony\Component\HttpKernel\Tests\DependencyInjection;

use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\DependencyInjection\Attribute\Target;
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\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\DependencyInjection\TypedReference;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DependencyInjection\RegisterControllerArgumentLocatorsPass;
use Symfony\Component\HttpKernel\Tests\Fixtures\Suit;

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

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

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

    public function testNoAction()
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Missing "action" attribute on tag "controller.service_arguments" {"argument":"bar"} for service "foo".');
        $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);
    }

    public function testNoArgument()
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Missing "argument" attribute on tag "controller.service_arguments" {"action":"fooAction"} for service "foo".');
        $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);
    }

    public function testNoService()
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Missing "id" attribute on tag "controller.service_arguments" {"action":"fooAction","argument":"bar"} for service "foo".');
        $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);
    }

    public function testInvalidMethod()
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Invalid "action" attribute on tag "controller.service_arguments" for service "foo": no public "barAction()" method found on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController".');
        $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);
    }

    public function testInvalidArgument()
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Invalid "controller.service_arguments" tag for service "foo": method "fooAction()" has no "baz" argument on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController".');
        $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));
    }

    public function testExceptionOnNonExistentTypeHint()
    {
        $this->expectException(\RuntimeException::class);
        $this->expectExceptionMessage('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?');
        $container = new ContainerBuilder();
        $container->register('argument_resolver.service')->addArgument([]);

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

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

        $error = $container->getDefinition('argument_resolver.service')->getArgument(0);
        $error = $container->getDefinition($error)->getArgument(0)['foo::fooAction']->getValues()[0];
        $error = $container->getDefinition($error)->getArgument(0)['nonExistent']->getValues()[0];

        $container->get($error);
    }

    public function testExceptionOnNonExistentTypeHintDifferentNamespace()
    {
        $this->expectException(\RuntimeException::class);
        $this->expectExceptionMessage('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".');
        $container = new ContainerBuilder();
        $container->register('argument_resolver.service')->addArgument([]);

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

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

        $error = $container->getDefinition('argument_resolver.service')->getArgument(0);
        $error = $container->getDefinition($error)->getArgument(0)['foo::fooAction']->getValues()[0];
        $error = $container->getDefinition($error)->getArgument(0)['nonExistent']->getValues()[0];

        $container->get($error);
    }

    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->assertEqualsCanonicalizing(['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();
        $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', 'stdClass')->addArgument([]);

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

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

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

        $locatorId = (string) $resolver->getArgument(0);
        $container->getDefinition($locatorId)->setPublic(true);

        $container->compile();

        $locator = $container->get($locatorId);
        $this->assertSame('foo_val', $locator->get('foo::fooAction')->get('someArg'));
    }

    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]);
    }

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

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

        $locatorArgument = $container->getDefinition('argument_resolver.not_tagged_controller')->getArgument(0);

        $this->assertInstanceOf(Reference::class, $locatorArgument);
    }

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

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

        $container->setAlias(RegisterTestController::class, 'foo')->setPublic(true);

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

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

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

        $container->register('foo', NonNullableEnumArgumentWithDefaultController::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), 'enum typed argument is ignored');
    }

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

        $container->register(ControllerDummy::class, 'bar');
        $container->register(ControllerDummy::class.' $imageStorage', 'baz');

        $container->register('foo', WithTarget::class)
            ->setBindings(['string $someApiKey' => new Reference('the_api_key')])
            ->addTag('controller.service_arguments');

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

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

        $expected = [
            'apiKey' => new ServiceClosureArgument(new Reference('the_api_key')),
            'service1' => new ServiceClosureArgument(new TypedReference(ControllerDummy::class, ControllerDummy::class, ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE, 'imageStorage')),
            'service2' => new ServiceClosureArgument(new TypedReference(ControllerDummy::class, ControllerDummy::class, ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE, 'service2')),
        ];
        $this->assertEquals($expected, $locator->getArgument(0));
    }

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

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

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

        $locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
        $this->assertEmpty(array_keys($locator), 'Response typed argument is ignored');
    }

    public function testAutowireAttribute()
    {
        if (!class_exists(Autowire::class)) {
            $this->markTestSkipped('#[Autowire] attribute not available.');
        }

        $container = new ContainerBuilder();
        $resolver = $container->register('argument_resolver.service', 'stdClass')->addArgument([]);

        $container->register('some.id', \stdClass::class);
        $container->setParameter('some.parameter', 'foo');

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

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

        $locatorId = (string) $resolver->getArgument(0);
        $container->getDefinition($locatorId)->setPublic(true);

        $container->compile();

        $locator = $container->get($locatorId)->get('foo::fooAction');

        $this->assertCount(7, $locator->getProvidedServices());
        $this->assertInstanceOf(\stdClass::class, $locator->get('service1'));
        $this->assertSame('foo/bar', $locator->get('value'));
        $this->assertSame('foo', $locator->get('expression'));
        $this->assertInstanceOf(\stdClass::class, $locator->get('serviceAsValue'));
        $this->assertInstanceOf(\stdClass::class, $locator->get('expressionAsValue'));
        $this->assertSame('bar', $locator->get('rawValue'));
        $this->assertSame('@bar', $locator->get('escapedRawValue'));
        $this->assertFalse($locator->has('service2'));
    }
}

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)
    {
    }
}

class NonNullableEnumArgumentWithDefaultController
{
    public function fooAction(Suit $suit = Suit::Spades)
    {
    }
}

class WithTarget
{
    public function fooAction(
        #[Target('some.api.key')]
        string $apiKey,
        #[Target('image.storage')]
        ControllerDummy $service1,
        ControllerDummy $service2
    ) {
    }
}

class WithResponseArgument
{
    public function fooAction(Response $response, ?Response $nullableResponse)
    {
    }
}

class WithAutowireAttribute
{
    public function fooAction(
        #[Autowire(service: 'some.id')]
        \stdClass $service1,
        #[Autowire(value: '%some.parameter%/bar')]
        string $value,
        #[Autowire(expression: "parameter('some.parameter')")]
        string $expression,
        #[Autowire('@some.id')]
        \stdClass $serviceAsValue,
        #[Autowire("@=service('some.id')")]
        \stdClass $expressionAsValue,
        #[Autowire('bar')]
        string $rawValue,
        #[Autowire('@@bar')]
        string $escapedRawValue,
        #[Autowire(service: 'invalid.id')]
        \stdClass $service2 = null,
    ) {
    }
}


text:
Nutzung

                Gesamte Wohnfläche
                <input ng-model="vm.nutzung.gesamte" id="gesamte" type="text">

                Wie wird die Wohnfläche genutzt?

                        <input ng-model="vm.nutzung.gewerbeflache" value="Eigengenutzt"
                               name="vorh5" id="Eigengenutzt" type="radio">
                        Eigengenutzt

                        <input ng-model="vm.nutzung.gewerbeflache" value="Vermietet"
                               name="vorh5" id="Vermietet" type="radio">
                        Vermietet

                        <input ng-model="vm.nutzung.gewerbeflache" value="Beides" name="vorh5"
                               id="Beides" type="radio">
                        Beides

                    Mieteinnahmen
                    <input format="currency" ng-model="vm.nutzung.gewerbeflachemieteinnahmen" id="mieteinnahmen"
                           type="text">

                    Mieteinnahmen
                    <input format="currency" ng-model="vm.nutzung.gewerbeflachemieteinnahmen" id="mieteinnahmen"
                           type="text">

                    Vermietete Wohnfläche
                    <input ng-model="vm.nutzung.gewerbeflachevermietetegewerbeflache" id="vermietetegewerbeflache"
                           type="text">

                Gewerbefläche vorhanden

                        <input ng-model="vm.nutzung.gewerbeflacheja" value="1" name="vorh7"
                               id="gewerbeflacheja" type="radio">
                        ja

                        <input ng-model="vm.nutzung.gewerbeflacheja" value="0" name="vorh7"
                               id="gewerbeflachenein" type="radio">
                        nein

                Gesamte Gewerbefläche
                <input ng-model="vm.nutzung.gesamtegewerbeflache" id="Gewerbefläche" type="text">

                Wie wird die Gewerbefläche genutzt?

                        <input ng-model="vm.nutzung.gewerbeflachegenutzt" value="Eigengenutzt"
                               name="vorh51" id="Eigengenutzt1" type="radio">
                        Eigengenutzt

                        <input ng-model="vm.nutzung.gewerbeflachegenutzt" value="Vermietet"
                               name="vorh51" id="Vermietet1" type="radio">
                        Vermietet

                        <input ng-model="vm.nutzung.gewerbeflachegenutzt" value="Beides" name="vorh51"
                               id="Beides1" type="radio">
                        Beides

                Mieteinnahmen
                <input format="currency" ng-model="vm.nutzung.vermietete51" id="mieteinnahmen51" type="text">

                Mieteinnahmen
                <input format="currency" ng-model="vm.nutzung.vermietete51" id="mieteinnahmen51" type="text">

                Vermietete Gewerbefläche
                <input ng-model="vm.nutzung.vermieteteGewerbeflache51" id="vermietetegewerbeflache51" type="text">

                Gesamte Gewerbefläche
                <input ng-model="vm.nutzung.gesamtegewerbeflache" id="gesamte" type="text">

                Wie wird die Gewerbefläche genutzt?

                        <input ng-model="vm.nutzung.wiegewerbeflache" value="Eigengenutzt"
                               name="vorh6" id="Eigengenutzt2" type="radio">
                        Eigengenutzt

                        <input ng-model="vm.nutzung.wiegewerbeflache" value="Vermietet"
                               name="vorh6" id="Vermietet2" type="radio">
                        Vermietet

                        <input ng-model="vm.nutzung.wiegewerbeflache" value="Beides" name="vorh6"
                               id="Beides2" type="radio">
                        Beides

                    Mieteinnahmen
                    <input format="currency" ng-model="vm.nutzung.mieteinnahmen" id="mieteinnahmen" type="text">

                    Mieteinnahmen
                    <input format="currency" ng-model="vm.nutzung.mieteinnahmen" id="mieteinnahmen" type="text">

                    Vermietete Gewerbefläche
                    <input ng-model="vm.nutzung.vermietetegewerbeflache" id="vermietetegewerbeflache" type="text">

Zusätzliche Angaben

                Erbbaurecht vorhanden?

                        <input ng-model="vm.zusatzliche.erbbaurecht" value="1" name="vorh10"
                               id="erbbaurecht" type="radio">
                        ja

                        <input ng-model="vm.zusatzliche.erbbaurecht" value="0" name="vorh10"
                               id="erbbaurechtnein" type="radio">
                        nein

            Erbbauzins jährlich
            <input format="currency" ng-model="vm.zusatzliche.erbbauzins" id="erbbauzins" type="text"
                   ng-blur="vm.zusatzliche.erbbauzins = vm.parseEuroFormat(vm.zusatzliche.erbbauzins)">

                Grundstückseigentümer

                        <input ng-model="vm.zusatzliche.grundstuckseigentumer" value="1" name="vorh12"
                               id="erbbaurecht" type="radio">
                        Öffentlich / Kirchlich

                        <input ng-model="vm.zusatzliche.grundstuckseigentumer" value="0" name="vorh12"
                               id="erbbaurechtnein" type="radio">
                        Andere

            Laufzeit bis
            <input ng-model="vm.zusatzliche.laufzeit" id="laufzeit" type="text">

              Wurde das Objekt in der Vergangenheit modernisiert?

                            <input ng-model="vm.zusatzliche.wurde" value="1" name="vorh8"
                                   id="Wurdeja" type="radio">
                            ja

                            <input ng-model="vm.zusatzliche.wurde" value="0" name="vorh8"
                                   id="Wurdenein" type="radio">
                            nein

                        Modernisierungsjahr
                        <input ng-model="vm.zusatzliche.modernisierungsjahr"
                               id="modernisierungsjahr" type="text">

                        Modernisierungsgrad
                        <select id="modernisierungsgrad" ng-model="vm.zusatzliche.modernisierungsgrad">
                            <option value="-1" selected="selected">Bitte wählen Sie...</option>
                            <option value="1" selected="selected">Hoch</option>
                            <option value="2" selected="selected">Mittel</option>
                            <option value="3" selected="selected">Gering</option>
                        </select>

redpajama_set_name: RedPajamaGithub


text:
package com.wada811.android.paint.drawings;

import android.graphics.Canvas;
import android.graphics.Paint;
import com.wada811.android.paint.tools.Brush;

/**
 * Some dots.
 */
public class Dots extends Drawing {

    private Paint paint;

    public Dots(){
        paint = new Paint(Brush.getPen());
        paint.setStyle(Paint.Style.FILL);
    }

    @Override
    public void draw(Canvas canvas){
        canvas.drawCircle(stopX, stopY, Brush.getPen().getStrokeWidth() + 1, paint);
    }

    @Override
    public void fingerDown(float x, float y, Canvas canvas){
        canvas.drawCircle(x, y, Brush.getPen().getStrokeWidth() + 1, paint);
    }

    @Override
    public void fingerMove(float x, float y, Canvas canvas){
        canvas.drawCircle(x, y, Brush.getPen().getStrokeWidth() + 1, paint);
    }
}


text:
Excel.removeSheet

The removeSheet function is established to remove a sheet.

Sample

	var excel = new Excel("test.xlsx");
	excel.removeSheet("Sheet1");

API

Calling	Returning

Excel . removeSheet ( sheetName )	Excel

Parameters	Type	Description

sheetName	String	The sheet name.


text:
module.exports = {

    'facebookAuth' : {
        'clientID'      : 'your-secret-clientID-here', // your App ID
        'clientSecret'  : 'your-client-secret-here', // your App Secret
        'callbackURL'   : 'http://localhost:8080/auth/facebook/callback'
    },

    'twitterAuth' : {
        'consumerKey'       : 'your-consumer-key-here',
        'consumerSecret'    : 'your-client-secret-here',
        'callbackURL'       : 'http://localhost:8080/auth/twitter/callback'
    },

    'googleAuth' : {
        'clientID'      : 'your-secret-clientID-here',
        'clientSecret'  : 'your-client-secret-here',
        'callbackURL'   : 'http://localhost:8080/auth/google/callback'
    }

};


text:
package it.alidays.mapengine.enginedirectives.fetch;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlValue;

public class Bind {

	private String attribute;
	private String type;
	private Integer length;
	private Integer decimal;
	private String value;

	@XmlAttribute(name = "attribute", required = true)
	public String getAttribute() {
		return this.attribute;
	}

	public void setAttribute(String attribute) {
		this.attribute = attribute;
	}

	@XmlAttribute(name = "type", required = true)
	public String getType() {
		return this.type;
	}

	public void setType(String type) {
		this.type = type;
	}

	@XmlAttribute(name = "length", required = false)
	public Integer getLength() {
		return this.length;
	}

	public void setLength(Integer length) {
		this.length = length;
	}

	@XmlAttribute(name = "decimal", required = false)
	public Integer getDecimal() {
		return this.decimal;
	}

	public void setDecimal(Integer decimal) {
		this.decimal = decimal;
	}

	@XmlValue
	public String getValue() {
		return this.value;
	}

	public void setValue(String value) {
		this.value = value;
	}

}


text:
app.submitToServer = function() {
	var userPasscode = document.getElementById('userPasscode').value;
	var numOfUsers = document.getElementById('numOfUsers').value;
	numOfUsers = (numOfUsers == "") ? 1 : numOfUsers;

	if(app.position!=undefined && app.position!=null){
		if (((new Date().getTime() / 1000) - app.timeLastSubmit) > 59
				|| app.forcedSubmit) {
			app.timeLastSubmit = new Date().getTime() / 1000;
			app.checkConnection();

			$.ajax(app.SERVER_URL, {
				contentType : "application/json",
				type : "GET",
				data : {
					"passcode" : userPasscode,
					"deviceId" : app.deviceId,
					"marker" : JSON.stringify({
						"numOfUsers" : numOfUsers,
						"lat" : app.position.coords.latitude,
						"lng" : app.position.coords.longitude,
						"accuracy" : app.position.coords.accuracy,
						"heading" : app.position.coords.heading
					})
				},
				timeout : 10000,
				success : function(response) {
					app.serverSuccess(response);
				},
				error : function(request, errorType, errorMessage) {
					app.serverError(request, errorType, errorMessage);
				}
			});
		}
		else {
			console.log('too soon');
			// Too Soon: commented out because not useful for user and confusing.
			// var serverError = document.getElementById('serverResponse');
			// serverError.innerHTML = "Too soon: "+app.getReadableTime( new Date())
			// ;
		}
	}
	else{
	navigator.notification
					.alert(
							"No position available to submit.", null,
							"Location Tracker");
	}
};

app.serverSuccess = function(response) {
	var responseObj = jQuery.parseJSON(response);
	var serverResponse = document.getElementById('serverResponse');
	serverResponse.innerHTML = "auto-submit: " + responseObj.message + ": "
			+ app.getReadableTime(new Date());

	if (responseObj.message == "not authorized") {
		if (app.forcedSubmit) {
			app.forcedSubmit = false;
			navigator.notification
					.alert(
							"This passcode is not authorized. Try again or contact Britta. Your device id is: "
									+ app.deviceId, null,
							"Tracking App");
		}
		$(serverResponse).removeClass("success");
		$(serverResponse).addClass("fail");
	} else {
		if (app.forcedSubmit) {
			navigator.notification.alert("Success. Thank you!", null,
					"Tracking App");
			app.forcedSubmit = false;
		}
		$(serverResponse).removeClass("fail");
		$(serverResponse).addClass("success");

		// Show or hide num of users option
		if (responseObj.advanced > 0) {
			document.getElementById("numUsersContainer").style.display = "block";
		} else {
			document.getElementById("numUsersContainer").style.display = "none";
		}
	}

};

app.serverError = function(request, errorType, errorMessage) {
	var serverError = document.getElementById('serverResponse');
	$(serverError).removeClass("success");
	$(serverError).addClass("fail");
	serverError.innerHTML = "Error: " + errorMessage + " "
			+ app.getReadableTime(new Date());
	if (app.forcedSubmit) {
		navigator.notification.alert(
				"Error, please check your internet connection", null,
				"Tracking App");
		app.forcedSubmit = false;
	}
};


text:
from sys import  maxsize

class Contact:

    # def __init__(self, firstname=None, middlename=None, lastname=None, nickname=None, title=None, company=None, address=None, home=None, mobile=None, work=None, fax=None, email=None, email2=None, email3=None, homepage=None, byear=None, ayear=None, address2=None, phone2=None, notes=None, id = None):
    def __init__(self, id=None, firstname=None, lastname=None, notes=None, home=None, mobile=None, work=None, phone2=None ):
        self.id = id
        self.firstname = firstname
        self.lastname = lastname
        self.notes = notes
        self.home = home
        self.mobile = mobile
        self.work = work
        self.phone2=phone2
        # self.middlename = middlename
        # self.nickname = nickname
        # self.title = title
        # self.company = company
        # self.address = address

        # self.fax = fax
        # self.email = email
        # self.email2 = email2
        # self.email3 = email3
        # self.homepage = homepage
        # self.byear=byear
        # self.ayear=ayear
        # self.address2=address2

    def __repr__(self):
        return "%s:%s:%s" % (self.id, self.firstname,self.lastname)

    def __eq__(self, other):
        return (self.id is None or other.id is None or self.id == other.id) and self.firstname == other.firstname

    def id_or_max(self):
        if self.id:
            return int(self.id)
        else:
            return maxsize


text:
package com.lamfire.json;

import java.io.IOException;

public interface JSONWriter {

    void write(Appendable out) throws IOException;
}


text:
u32 jffs2_1pass_ls(struct part_info *part,const char *fname);
u32 jffs2_1pass_load(char *dest, struct part_info *part,const char *fname);
u32 jffs2_1pass_info(struct part_info *part);


text:
export default {
  'template-caption': 'Шаблон класса',
  'packet-caption': 'Пакет',
  'packet-placeholder': 'Наименование пакета',
  'namespace-postfix-caption': 'Постфикс пространства имен',
  'namespace-postfix-placeholder': 'Наименование постфикса',
};


text:
! Program to test caracter string return values
function test ()
   implicit none
   character(len=10) :: test
   test = "World"
end function

function test2 () result (r)
   implicit none
   character(len=5) :: r
   r = "Hello"
end function

program strret
   implicit none
   character(len=15) :: s
   character(len=10) :: test
   character(len=5) :: test2

   s = test ()
   if (s .ne. "World") call abort

   s = "Hello " // test ()
   if (s .ne. test2 () //" World") call abort
end


text:
import glob
import logging
import os
import shutil
from threading import Thread, Lock

class ClientFiles:
    """Processes the clients files to be moved etc"""

    def __init__(self, settings, clients):
        self.settings = settings
        self.clients = clients

        # Logging
        self._logger = logging.getLogger(__name__)

        # Dictionary of files to be moved, client is key
        self.client_files = dict()

        self.client_list = []

        # Path templates
        self.file_path = ("\\\\{0}\\" +
                          self.settings.client_path +
                          "\\" +
                          "*")

        # Threading lock
        self.lock = Lock()

    def file_list(self, client):
        """
        Creates a list of files for each client to be moved

        :param client: Client to have file list generated
        :return: Client files if any, otherwise returns None
        """
        # print("Checking " + client + " for files")
        client_files = []

        for file_type in self.settings.file_types:
            client_files.extend(glob.glob(self.file_path.format(client) +
                                          file_type))

        if len(client_files) > 0:
            client_files = [file for file in client_files
                            if os.stat(file).st_size >=
                            self.settings.file_minsize]

            if len(client_files) > 0:
                self._logger.log(logging.INFO, client + ": " +
                                 str(len(client_files)) + " file(s)")
                # print(client, client_files)
                self.client_files[client] = client_files

    def thread_file_list(self):
        """
        Threadsafe queue support function to prevent conflicts
        """
        client_list = self.clients.clients_online

        while len(client_list) > 0:
            self.lock.acquire()
            client = client_list.pop()
            self.lock.release()

            # Pass popped client to function
            self.file_list(client)

    def build_file_list(self):
        """
        Processes clients to construct class file list
        """
        active_threads = []

        # Spawn instances for multithreading
        for i in range(self.settings.client_connections):
            instance = Thread(target=self.thread_file_list)
            active_threads.append(instance)
            instance.start()

        # Allow threads to complete before proceeding
        for instance in active_threads:
            instance.join()

    def thread_move_files(self):

        while len(self.client_list) > 0:
            self.lock.acquire()
            client = self.client_list.pop()
            self.lock.release()

            # Pass popped client to function
            self.move_files(self.client_files[client])

    def move_files(self, file_list):
        # print(file_list)
        for file in file_list:
            # print(os.path.basename(file))
            os.chdir(self.settings.local_queue)

            # Check if file exists locally already
            if os.path.exists(os.path.basename(file)):
                os.remove(os.path.basename(file))
                self._logger.log(logging.WARNING, file + " exists. "
                                                         "Current file removed")

            try:
                shutil.move(file, self.settings.local_queue)
                # self.files.append(os.path.basename(file))
            except OSError as error:
                self._logger.log(logging.CRITICAL, file + " " + str(error))
                # print(error)

            self._logger.log(logging.INFO, file + " moved successfully")

    def build_move_files(self):
        """
        Move files from client to local store. This is done as a list per client
        so as to not flood a specific sites WAN link and cause issues with
        stores connectivity.
        """
        active_threads = []
        self.client_list = list(self.client_files.keys())

        for i in range(self.settings.client_connections):
            instance = Thread(target=self.thread_move_files)
            active_threads.append(instance)
            instance.start()

        # Allow threads to complete before proceeding
        for instance in active_threads:
            instance.join()

    def run(self):
        self.build_file_list()

        self.build_move_files()


text:
[![Build Status](https://travis-ci.org/tuki0918/totoro.svg?branch=master)](https://travis-ci.org/tuki0918/totoro)
[![Latest Stable Version](https://poser.pugx.org/tuki0918/totoro/v/stable)](https://packagist.org/packages/tuki0918/totoro)
[![Latest Unstable Version](https://poser.pugx.org/tuki0918/totoro/v/unstable)](https://packagist.org/packages/tuki0918/totoro)
[![Coverage Status](https://coveralls.io/repos/github/tuki0918/totoro/badge.svg?branch=master)](https://coveralls.io/github/tuki0918/totoro?branch=master)
[![Total Downloads](https://poser.pugx.org/tuki0918/totoro/downloads)](https://packagist.org/packages/tuki0918/totoro)
[![License](https://poser.pugx.org/tuki0918/totoro/license)](https://packagist.org/packages/tuki0918/totoro)

# totoro

```
<?php

use Abraham\TwitterOAuth\TwitterOAuth;
use Totoro\General\TwitterApiClient;

define('CONSUMER_KEY', getenv('CONSUMER_KEY'));
define('CONSUMER_SECRET', getenv('CONSUMER_SECRET'));

$accessToken = getenv('ACCESS_TOKEN');
$accessTokenSecret = getenv('ACCESS_TOKEN_SECRET');

$client = new TwitterApiClient(new TwitterOAuth(
    CONSUMER_KEY,
    CONSUMER_SECRET,
    $accessToken,
    $accessTokenSecret
));

// get: user timeline
$tweets = $client->getStatusesUserTimeline([
    'screen_name' => 'tuki0918',
    'count' => 5
])->entities();

// return: Totoro\General\Entities\Tweet[]
print_r($tweets);

// post: tweet
$tweet = $client->postStatusesUpdate(
    ['status' => 'twitter api post.']
)->entity();

// post: alias tweet
$tweet = $client->tweet(
    ['status' => 'twitter api post.']
)->entity();

// return: Totoro\General\Entities\Tweet
print_r($tweet);

```


text:
require 'artii'
require 'rack2aws/version'
require 'rack2aws/colorizer'

module Rack2Aws
  module Logger

    def show_welcome
      welcome_art = Artii::Base.new
      $stdout.puts "##############################################################".bold.blue
      output = welcome_art.asciify("Rack2Aws").bold.blue
      output << "v#{Rack2Aws::VERSION} (>o<)".bold.blue
      $stdout.puts output
      $stdout.puts "#############################################################".bold.blue
    end

    def warn(msg)
      output = "WARNING: ".bold
      output << msg
      output.brown
    end

  end
end


text:
package com.percolate.sdk.android.dto;

import android.os.Parcel;
import android.os.Parcelable;

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

/**
 * Android version of {@link com.percolate.sdk.dto.FacebookUserDataList}.  Implements {@link Parcelable}
 */
public class FacebookUserDataList extends com.percolate.sdk.dto.FacebookUserDataList implements Parcelable {
    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeList(this.data);
        dest.writeMap(this.extraFields);
    }

    public FacebookUserDataList() {
    }

    protected FacebookUserDataList(Parcel in) {
        this.data = new ArrayList<com.percolate.sdk.dto.FacebookUser>();
        in.readList(this.data, List.class.getClassLoader());
        this.extraFields = new HashMap<>();
        in.readMap(this.extraFields, HashMap.class.getClassLoader());
    }

    public static final Creator<FacebookUserDataList> CREATOR = new Creator<FacebookUserDataList>() {
        public FacebookUserDataList createFromParcel(Parcel source) {
            return new FacebookUserDataList(source);
        }

        public FacebookUserDataList[] newArray(int size) {
            return new FacebookUserDataList[size];
        }
    };
}


text:
package org.gephi.maven;

import org.apache.netbeans.nbm.utils.ExamineManifest;
import org.gephi.maven.json.PluginMetadata;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.tools.ant.taskdefs.Manifest;
import org.apache.tools.ant.taskdefs.ManifestException;
import org.codehaus.plexus.util.IOUtil;
import org.apache.maven.plugin.logging.Log;

/**
 * Utilities to read and check values in modules manifest.
 */
public class ManifestUtils {

    /**
     * List of allowed plugin categories
     */
    protected final static String[] CATEGORIES = new String[]{
        "Layout", "Export", "Import", "Data Laboratory",
        "Filter", "Generator", "Metric", "Preview", "Tool",
        "Appearance", "Clustering", "Other Category"
    };

    private final Log log;
    private final String sourceManifestFile;

    public ManifestUtils(String sourceManifestFile, Log log) {
        this.sourceManifestFile = sourceManifestFile;
        this.log = log;
    }

    /**
     * Check that the given project has the AutoUpdate-Show-In-Client
     * entry set to false in its manifest.
     *
     * @param proj project
     * @throws MojoExecutionException if an error occurs
     */
    protected void checkManifestShowClientFalse(MavenProject proj) throws MojoExecutionException {
        Manifest manifest = getManifest(proj);

        Manifest.Section mainSection = manifest.getMainSection();
        String showInClient = mainSection.getAttributeValue("AutoUpdate-Show-In-Client");
        if (showInClient == null || showInClient.isEmpty() || !showInClient.equals("false")) {
            throw new MojoExecutionException("The manifest.mf file for project '" + proj.getName() + "' should contain a 'AutoUpdate-Show-In-Client' entry set at 'false'");
        }
    }

    protected void readManifestMetadata(MavenProject proj, PluginMetadata metadata) throws MojoExecutionException {
        Manifest manifest = getManifest(proj);

        // Read branding attributes
        Manifest.Section mainSection = manifest.getMainSection();
        String brandingName = mainSection.getAttributeValue("OpenIDE-Module-Name");
        String brandingShortDescription = mainSection.getAttributeValue("OpenIDE-Module-Short-Description");
        String brandingLongDescrption = mainSection.getAttributeValue("OpenIDE-Module-Long-Description");
        String brandingDisplayCategory = mainSection.getAttributeValue("OpenIDE-Module-Display-Category");

        //Read localized
        if (mainSection.getAttribute("OpenIDE-Module-Localizing-Bundle") != null) {
            File folder = proj.getBasedir();
            String path = mainSection.getAttributeValue("OpenIDE-Module-Localizing-Bundle");
            File bundlerFile = new File(folder, "src" + File.separator + "main" + File.separator + "resources");
            if (!bundlerFile.exists()) {
                throw new MojoExecutionException("The 'src/main/resources' folder can't be found in '" + folder.getAbsolutePath() + "'");
            }
            bundlerFile = new File(bundlerFile, path.replace('/', File.separatorChar));
            if (!bundlerFile.exists()) {
                throw new MojoExecutionException("The '" + path + "' file can't be found");
            }
            Properties prop = new Properties();
            FileReader bundleReader = null;
            try {
                bundleReader = new FileReader(bundlerFile);
                prop.load(bundleReader);
                brandingName = prop.getProperty("OpenIDE-Module-Name", brandingName);
                brandingDisplayCategory = prop.getProperty("OpenIDE-Module-Display-Category", brandingDisplayCategory);
                brandingShortDescription = prop.getProperty("OpenIDE-Module-Short-Description", brandingShortDescription);
                brandingLongDescrption = prop.getProperty("OpenIDE-Module-Long-Description", brandingLongDescrption);
            } catch (IOException e) {
                throw new MojoExecutionException("Error while reading '" + bundlerFile.getAbsolutePath() + "'", e);
            } finally {
                if (bundleReader != null) {
                    try {
                        bundleReader.close();
                    } catch (IOException ex) {
                    }
                }
            }
        }

        if (brandingName == null || brandingName.isEmpty()) {
            throw new MojoExecutionException("The manifest.mf file for project '" + proj.getName() + "' should contain a 'OpenIDE-Module-Name' entry");
        }
        if (brandingShortDescription == null || brandingShortDescription.isEmpty()) {
            throw new MojoExecutionException("The manifest.mf file for project '" + proj.getName() + "' should contain a 'OpenIDE-Module-Short-Description' entry");
        }
        if (brandingLongDescrption == null || brandingLongDescrption.isEmpty()) {
            throw new MojoExecutionException("The manifest.mf file for project '" + proj.getName() + "' should contain a 'OpenIDE-Module-Long-Description' entry");
        }
        if (brandingDisplayCategory == null || brandingDisplayCategory.isEmpty()) {
            throw new MojoExecutionException("The manifest.mf file for project '" + proj.getName() + "' should contain a 'OpenIDE-Module-Display-Category' entry");
        }

        if (!validateCategory(brandingDisplayCategory)) {
            throw new MojoExecutionException("The manifest entry 'OpenIDE-Module-Display-Category' is '"+brandingDisplayCategory+"' but should be one of the following values: " + Arrays.toString(CATEGORIES).replace("[", "").replace("]", ""));
        }

        metadata.name = brandingName;
        metadata.short_description = brandingShortDescription;
        metadata.long_description = brandingLongDescrption;
        metadata.category = brandingDisplayCategory;
    }

    /**
     * Find and return the Manifest for the given project.
     *
     * @param proj project
     * @return manifest
     * @throws MojoExecutionException if an error occurs
     */
    protected Manifest getManifest(MavenProject proj) throws MojoExecutionException {
        // Read project manifest file
        File manifestFile = new File(proj.getBasedir(), sourceManifestFile);
        if (!manifestFile.exists()) {
            throw new MojoExecutionException("Cannot locate a manifest.mf file at " + manifestFile.getAbsolutePath() + " for project " + proj.getName());
        }

        // Check validity
        ExamineManifest examinator = new ExamineManifest(log);
        examinator.setManifestFile(manifestFile);
        examinator.checkFile();

        // Read manifest
        Manifest manifest = null;
        Reader reader = null;
        try {
            reader = new InputStreamReader(new FileInputStream(manifestFile));
            manifest = new Manifest(reader);
        } catch (IOException exc) {
            throw new MojoExecutionException("Error reading manifest at " + manifestFile, exc);
        } catch (ManifestException ex) {
            throw new MojoExecutionException("Error reading manifest at " + manifestFile, ex);
        } finally {
            IOUtil.close(reader);
        }
        return manifest;
    }

    protected static boolean validateCategory(String category) {
        Set<String> allowedCategories = new HashSet<String>(Arrays.asList(CATEGORIES));
        return allowedCategories.contains(category);
    }
}


text:
package com.cognifide.aet.job.common.comparators.layout;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.when;

import com.cognifide.aet.job.api.comparator.ComparatorProperties;
import com.cognifide.aet.job.common.comparators.layout.utils.ImageComparisonResult;
import com.cognifide.aet.vs.ArtifactsDAO;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class LayoutComparatorTest {

  @Mock
  private ComparatorProperties comparatorProperties;

  @Mock
  private ArtifactsDAO artifactsDAO;

  @Mock
  private ImageComparisonResult imageComparisonResult;

  private LayoutComparator layoutComparator;

  @Before
  public void setUp() {
    //given
    this.layoutComparator = new LayoutComparator(this.comparatorProperties, this.artifactsDAO);
  }

  @Test
  public void hasMaskThresholdWithAcceptableDifference_withoutThreshold_expectFalse() {
    //when
    when(imageComparisonResult.getPercentagePixelDifference()).thenReturn(12.567);
    when(imageComparisonResult.getPixelDifferenceCount()).thenReturn(300);

    //then
    assertThat(
        this.layoutComparator.hasMaskThresholdWithAcceptableDifference(imageComparisonResult),
        is(false));
  }

  @Test
  public void hasMaskThresholdWithAcceptableDifference_withThreshold_expectFalse() {
    //when
    when(imageComparisonResult.getPercentagePixelDifference()).thenReturn(12.567);
    when(imageComparisonResult.getPixelDifferenceCount()).thenReturn(300);

    this.layoutComparator.setPixelThreshold(299);
    this.layoutComparator.setPercentageThreshold(null);

    //then
    assertThat(this.layoutComparator.hasMaskThresholdWithAcceptableDifference(imageComparisonResult),
        is(false));

    //when
    this.layoutComparator.setPixelThreshold(null);
    this.layoutComparator.setPercentageThreshold(12.566);

    //then
    assertThat(this.layoutComparator.hasMaskThresholdWithAcceptableDifference(imageComparisonResult),
        is(false));
  }

  @Test
  public void hasMaskThresholdWithAcceptableDifference_withThreshold_expectTrue() {
    //when
    when(imageComparisonResult.getPercentagePixelDifference()).thenReturn(12.567);
    when(imageComparisonResult.getPixelDifferenceCount()).thenReturn(300);

    this.layoutComparator.setPixelThreshold(300);
    this.layoutComparator.setPercentageThreshold(null);

    //then
    assertThat(this.layoutComparator.hasMaskThresholdWithAcceptableDifference(imageComparisonResult),
        is(true));

    //when
    this.layoutComparator.setPixelThreshold(null);
    this.layoutComparator.setPercentageThreshold(12.567);

    //then
    assertThat(this.layoutComparator.hasMaskThresholdWithAcceptableDifference(imageComparisonResult),
        is(true));
  }

  @Test
  public void hasMaskThresholdWithAcceptableDifference_withBothThreshold_expectFalse() {
    //when
    when(imageComparisonResult.getPercentagePixelDifference()).thenReturn(12.567);
    when(imageComparisonResult.getPixelDifferenceCount()).thenReturn(300);

    this.layoutComparator.setPixelThreshold(299);
    this.layoutComparator.setPercentageThreshold(30.0);

    //then
    assertThat(this.layoutComparator.hasMaskThresholdWithAcceptableDifference(imageComparisonResult),
        is(false));

    //when
    this.layoutComparator.setPixelThreshold(301);
    this.layoutComparator.setPercentageThreshold(12.566);

    //then
    assertThat(this.layoutComparator.hasMaskThresholdWithAcceptableDifference(imageComparisonResult),
        is(false));
  }

  @Test
  public void hasMaskThresholdWithAcceptableDifference_withBothThreshold_expectTrue() {
    //when
    when(imageComparisonResult.getPercentagePixelDifference()).thenReturn(12.567);
    when(imageComparisonResult.getPixelDifferenceCount()).thenReturn(300);

    this.layoutComparator.setPixelThreshold(300);
    this.layoutComparator.setPercentageThreshold(12.567);

    //then
    assertThat(this.layoutComparator.hasMaskThresholdWithAcceptableDifference(imageComparisonResult),
        is(true));
  }

}


text:
/**
 * @fileoverview Restrict usage of specified node imports.
 * @author Guy Ellis
 */
"use strict";

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

const DEFAULT_MESSAGE_TEMPLATE = "'{{importSource}}' import is restricted from being used.";
const CUSTOM_MESSAGE_TEMPLATE = "'{{importSource}}' import is restricted from being used. {{customMessage}}";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

const ignore = require("ignore");

const arrayOfStrings = {
    type: "array",
    items: { type: "string" },
    uniqueItems: true
};

const arrayOfStringsOrObjects = {
    type: "array",
    items: {
        anyOf: [
            { type: "string" },
            {
                type: "object",
                properties: {
                    name: { type: "string" },
                    message: {
                        type: "string",
                        minLength: 1
                    },
                    importNames: {
                        type: "array",
                        items: {
                            type: "string"
                        }
                    }
                },
                additionalProperties: false,
                required: ["name"]
            }
        ]
    },
    uniqueItems: true
};

module.exports = {
    meta: {
        type: "suggestion",

        docs: {
            description: "disallow specified modules when loaded by `import`",
            category: "ECMAScript 6",
            recommended: false,
            url: "https://eslint.org/docs/rules/no-restricted-imports"
        },

        schema: {
            anyOf: [
                arrayOfStringsOrObjects,
                {
                    type: "array",
                    items: {
                        type: "object",
                        properties: {
                            paths: arrayOfStringsOrObjects,
                            patterns: arrayOfStrings
                        },
                        additionalProperties: false
                    },
                    additionalItems: false
                }
            ]
        }
    },

    create(context) {
        const options = Array.isArray(context.options) ? context.options : [];
        const isPathAndPatternsObject =
            typeof options[0] === "object" &&
            (Object.prototype.hasOwnProperty.call(options[0], "paths") || Object.prototype.hasOwnProperty.call(options[0], "patterns"));

        const restrictedPaths = (isPathAndPatternsObject ? options[0].paths : context.options) || [];
        const restrictedPatterns = (isPathAndPatternsObject ? options[0].patterns : []) || [];

        const restrictedPathMessages = restrictedPaths.reduce((memo, importSource) => {
            if (typeof importSource === "string") {
                memo[importSource] = { message: null };
            } else {
                memo[importSource.name] = {
                    message: importSource.message,
                    importNames: importSource.importNames
                };
            }
            return memo;
        }, {});

        // if no imports are restricted we don"t need to check
        if (Object.keys(restrictedPaths).length === 0 && restrictedPatterns.length === 0) {
            return {};
        }

        const restrictedPatternsMatcher = ignore().add(restrictedPatterns);

        /**
         * Checks to see if "*" is being used to import everything.
         * @param {Set.<string>} importNames - Set of import names that are being imported
         * @returns {boolean} whether everything is imported or not
         */
        function isEverythingImported(importNames) {
            return importNames.has("*");
        }

        /**
         * Report a restricted path.
         * @param {node} node representing the restricted path reference
         * @returns {void}
         * @private
         */
        function reportPath(node) {
            const importSource = node.source.value.trim();
            const customMessage = restrictedPathMessages[importSource] && restrictedPathMessages[importSource].message;
            const message = customMessage
                ? CUSTOM_MESSAGE_TEMPLATE
                : DEFAULT_MESSAGE_TEMPLATE;

            context.report({
                node,
                message,
                data: {
                    importSource,
                    customMessage
                }
            });
        }

        /**
         * Report a restricted path specifically for patterns.
         * @param {node} node - representing the restricted path reference
         * @returns {void}
         * @private
         */
        function reportPathForPatterns(node) {
            const importSource = node.source.value.trim();

            context.report({
                node,
                message: "'{{importSource}}' import is restricted from being used by a pattern.",
                data: {
                    importSource
                }
            });
        }

        /**
         * Report a restricted path specifically when using the '*' import.
         * @param {string} importSource - path of the import
         * @param {node} node - representing the restricted path reference
         * @returns {void}
         * @private
         */
        function reportPathForEverythingImported(importSource, node) {
            const importNames = restrictedPathMessages[importSource].importNames;

            context.report({
                node,
                message: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted.",
                data: {
                    importSource,
                    importNames
                }
            });
        }

        /**
         * Check if the given importSource is restricted because '*' is being imported.
         * @param {string} importSource - path of the import
         * @param {Set.<string>} importNames - Set of import names that are being imported
         * @returns {boolean} whether the path is restricted
         * @private
         */
        function isRestrictedForEverythingImported(importSource, importNames) {
            return Object.prototype.hasOwnProperty.call(restrictedPathMessages, importSource) &&
                restrictedPathMessages[importSource].importNames &&
                isEverythingImported(importNames);
        }

        /**
         * Check if the given importNames are restricted given a list of restrictedImportNames.
         * @param {Set.<string>} importNames - Set of import names that are being imported
         * @param {[string]} restrictedImportNames - array of import names that are restricted for this import
         * @returns {boolean} whether the objectName is restricted
         * @private
         */
        function isRestrictedObject(importNames, restrictedImportNames) {
            return restrictedImportNames.some(restrictedObjectName => (
                importNames.has(restrictedObjectName)
            ));
        }

        /**
         * Check if the given importSource is a restricted path.
         * @param {string} importSource - path of the import
         * @param {Set.<string>} importNames - Set of import names that are being imported
         * @returns {boolean} whether the variable is a restricted path or not
         * @private
         */
        function isRestrictedPath(importSource, importNames) {
            let isRestricted = false;

            if (Object.prototype.hasOwnProperty.call(restrictedPathMessages, importSource)) {
                if (restrictedPathMessages[importSource].importNames) {
                    isRestricted = isRestrictedObject(importNames, restrictedPathMessages[importSource].importNames);
                } else {
                    isRestricted = true;
                }
            }

            return isRestricted;
        }

        /**
         * Check if the given importSource is restricted by a pattern.
         * @param {string} importSource - path of the import
         * @returns {boolean} whether the variable is a restricted pattern or not
         * @private
         */
        function isRestrictedPattern(importSource) {
            return restrictedPatterns.length > 0 && restrictedPatternsMatcher.ignores(importSource);
        }

        /**
         * Checks a node to see if any problems should be reported.
         * @param {ASTNode} node The node to check.
         * @returns {void}
         * @private
         */
        function checkNode(node) {
            const importSource = node.source.value.trim();
            const importNames = node.specifiers ? node.specifiers.reduce((set, specifier) => {
                if (specifier.type === "ImportDefaultSpecifier") {
                    set.add("default");
                } else if (specifier.type === "ImportNamespaceSpecifier") {
                    set.add("*");
                } else if (specifier.imported) {
                    set.add(specifier.imported.name);
                } else if (specifier.local) {
                    set.add(specifier.local.name);
                }
                return set;
            }, new Set()) : new Set();

            if (isRestrictedForEverythingImported(importSource, importNames)) {
                reportPathForEverythingImported(importSource, node);
            }

            if (isRestrictedPath(importSource, importNames)) {
                reportPath(node);
            }
            if (isRestrictedPattern(importSource)) {
                reportPathForPatterns(node);
            }
        }

        return {
            ImportDeclaration: checkNode,
            ExportNamedDeclaration(node) {
                if (node.source) {
                    checkNode(node);
                }
            },
            ExportAllDeclaration: checkNode
        };
    }
};


text:
test_description='git rebase --root

Tests if git rebase --root --onto <newparent> can rebase the root commit.
'
. ./test-lib.sh

log_with_names () {
	git rev-list --topo-order --parents --pretty="tformat:%s" HEAD |
	git name-rev --stdin --name-only --refs=refs/heads/$1
}

test_expect_success 'prepare repository' '
	test_commit 1 A &&
	test_commit 2 A &&
	git symbolic-ref HEAD refs/heads/other &&
	rm .git/index &&
	test_commit 3 B &&
	test_commit 1b A 1 &&
	test_commit 4 B
'

test_expect_success 'rebase --root fails with too many args' '
	git checkout -B fail other &&
	test_must_fail git rebase --onto master --root fail fail
'

test_expect_success 'setup pre-rebase hook' '
	mkdir -p .git/hooks &&
	cat >.git/hooks/pre-rebase <<EOF &&
#!$SHELL_PATH
echo "\$1,\$2" >.git/PRE-REBASE-INPUT
EOF
	chmod +x .git/hooks/pre-rebase
'
cat > expect <<EOF
4
3
2
1
EOF

test_expect_success 'rebase --root --onto <newbase>' '
	git checkout -b work other &&
	git rebase --root --onto master &&
	git log --pretty=tformat:"%s" > rebased &&
	test_cmp expect rebased
'

test_expect_success 'pre-rebase got correct input (1)' '
	test "z$(cat .git/PRE-REBASE-INPUT)" = z--root,
'

test_expect_success 'rebase --root --onto <newbase> <branch>' '
	git branch work2 other &&
	git rebase --root --onto master work2 &&
	git log --pretty=tformat:"%s" > rebased2 &&
	test_cmp expect rebased2
'

test_expect_success 'pre-rebase got correct input (2)' '
	test "z$(cat .git/PRE-REBASE-INPUT)" = z--root,work2
'

test_expect_success 'rebase -i --root --onto <newbase>' '
	git checkout -b work3 other &&
	git rebase -i --root --onto master &&
	git log --pretty=tformat:"%s" > rebased3 &&
	test_cmp expect rebased3
'

test_expect_success 'pre-rebase got correct input (3)' '
	test "z$(cat .git/PRE-REBASE-INPUT)" = z--root,
'

test_expect_success 'rebase -i --root --onto <newbase> <branch>' '
	git branch work4 other &&
	git rebase -i --root --onto master work4 &&
	git log --pretty=tformat:"%s" > rebased4 &&
	test_cmp expect rebased4
'

test_expect_success 'pre-rebase got correct input (4)' '
	test "z$(cat .git/PRE-REBASE-INPUT)" = z--root,work4
'

test_expect_success 'rebase -i -p with linear history' '
	git checkout -b work5 other &&
	git rebase -i -p --root --onto master &&
	git log --pretty=tformat:"%s" > rebased5 &&
	test_cmp expect rebased5
'

test_expect_success 'pre-rebase got correct input (5)' '
	test "z$(cat .git/PRE-REBASE-INPUT)" = z--root,
'

test_expect_success 'set up merge history' '
	git checkout other^ &&
	git checkout -b side &&
	test_commit 5 C &&
	git checkout other &&
	git merge side
'

cat > expect-side <<'EOF'
commit work6 work6~1 work6^2
Merge branch 'side' into other
commit work6^2 work6~2
5
commit work6~1 work6~2
4
commit work6~2 work6~3
3
commit work6~3 work6~4
2
commit work6~4
1
EOF

test_expect_success 'rebase -i -p with merge' '
	git checkout -b work6 other &&
	git rebase -i -p --root --onto master &&
	log_with_names work6 > rebased6 &&
	test_cmp expect-side rebased6
'

test_expect_success 'set up second root and merge' '
	git symbolic-ref HEAD refs/heads/third &&
	rm .git/index &&
	rm A B C &&
	test_commit 6 D &&
	git checkout other &&
	git merge third
'

cat > expect-third <<'EOF'
commit work7 work7~1 work7^2
Merge branch 'third' into other
commit work7^2 work7~4
6
commit work7~1 work7~2 work7~1^2
Merge branch 'side' into other
commit work7~1^2 work7~3
5
commit work7~2 work7~3
4
commit work7~3 work7~4
3
commit work7~4 work7~5
2
commit work7~5
1
EOF

test_expect_success 'rebase -i -p with two roots' '
	git checkout -b work7 other &&
	git rebase -i -p --root --onto master &&
	log_with_names work7 > rebased7 &&
	test_cmp expect-third rebased7
'

test_expect_success 'setup pre-rebase hook that fails' '
	mkdir -p .git/hooks &&
	cat >.git/hooks/pre-rebase <<EOF &&
#!$SHELL_PATH
false
EOF
	chmod +x .git/hooks/pre-rebase
'

test_expect_success 'pre-rebase hook stops rebase' '
	git checkout -b stops1 other &&
	test_must_fail git rebase --root --onto master &&
	test "z$(git symbolic-ref HEAD)" = zrefs/heads/stops1 &&
	test 0 = $(git rev-list other...stops1 | wc -l)
'

test_expect_success 'pre-rebase hook stops rebase -i' '
	git checkout -b stops2 other &&
	test_must_fail git rebase --root --onto master &&
	test "z$(git symbolic-ref HEAD)" = zrefs/heads/stops2 &&
	test 0 = $(git rev-list other...stops2 | wc -l)
'

test_expect_success 'remove pre-rebase hook' '
	rm -f .git/hooks/pre-rebase
'

test_expect_success 'set up a conflict' '
	git checkout master &&
	echo conflict > B &&
	git add B &&
	git commit -m conflict
'

test_expect_success 'rebase --root with conflict (first part)' '
	git checkout -b conflict1 other &&
	test_must_fail git rebase --root --onto master &&
	git ls-files -u | grep "B$"
'

test_expect_success 'fix the conflict' '
	echo 3 > B &&
	git add B
'

cat > expect-conflict <<EOF
6
5
4
3
conflict
2
1
EOF

test_expect_success 'rebase --root with conflict (second part)' '
	git rebase --continue &&
	git log --pretty=tformat:"%s" > conflict1 &&
	test_cmp expect-conflict conflict1
'

test_expect_success 'rebase -i --root with conflict (first part)' '
	git checkout -b conflict2 other &&
	test_must_fail git rebase -i --root --onto master &&
	git ls-files -u | grep "B$"
'

test_expect_success 'fix the conflict' '
	echo 3 > B &&
	git add B
'

test_expect_success 'rebase -i --root with conflict (second part)' '
	git rebase --continue &&
	git log --pretty=tformat:"%s" > conflict2 &&
	test_cmp expect-conflict conflict2
'

cat >expect-conflict-p <<\EOF
commit conflict3 conflict3~1 conflict3^2
Merge branch 'third' into other
commit conflict3^2 conflict3~4
6
commit conflict3~1 conflict3~2 conflict3~1^2
Merge branch 'side' into other
commit conflict3~1^2 conflict3~3
5
commit conflict3~2 conflict3~3
4
commit conflict3~3 conflict3~4
3
commit conflict3~4 conflict3~5
conflict
commit conflict3~5 conflict3~6
2
commit conflict3~6
1
EOF

test_expect_success 'rebase -i -p --root with conflict (first part)' '
	git checkout -b conflict3 other &&
	test_must_fail git rebase -i -p --root --onto master &&
	git ls-files -u | grep "B$"
'

test_expect_success 'fix the conflict' '
	echo 3 > B &&
	git add B
'

test_expect_success 'rebase -i -p --root with conflict (second part)' '
	git rebase --continue &&
	log_with_names conflict3 >out &&
	test_cmp expect-conflict-p out
'

test_done


text:
+++
title = "PostgreSQL"
weight = 2
+++

The unsupported SQL list for PostgreSQL are as follows:

TODO


text:
define(
  [
    'backbone'
  ],
  function(Backbone) {
    'use strict';

    var LocalCollection = Backbone.Collection.extend({

    });

    return LocalCollection;
  }
);


text:
"""Represent a blind."""
from pytradfri.const import ATTR_START_BLINDS, ATTR_BLIND_CURRENT_POSITION

class Blind:
    """Represent a blind."""

    def __init__(self, device, index):
        self.device = device
        self.index = index

    @property
    def raw(self):
        """Return raw data that it represents."""
        return self.device.raw[ATTR_START_BLINDS][self.index]

    @property
    def current_cover_position(self):
        """Get the current position of the blind."""
        return self.raw.get(ATTR_BLIND_CURRENT_POSITION)


text:
<?php

namespace Magento\Test\Di;

require_once __DIR__ . '/DiInterface.php';
class DiParent implements \Magento\Test\Di\DiInterface
{
    /**
     * @var string
     */
    protected $_wrapperSymbol;

    /**
     * @param string $wrapperSymbol
     */
    public function __construct($wrapperSymbol = '|')
    {
        $this->_wrapperSymbol = $wrapperSymbol;
    }

    /**
     * @param string $param
     * @return mixed
     */
    public function wrap($param)
    {
        return $this->_wrapperSymbol . $param . $this->_wrapperSymbol;
    }
}


text:
require_relative '../spec_helper_lite'
require 'cluster'

describe Cluster do
  subject { Cluster.new(names, attribute_names) }
  let(:attribute_names) { ['tech'] }
  let(:names) { ['a'] }

  describe '#each_node' do
    it 'should yield the nodes' do
      expected_output = [1,2,3]
      subject.node_collection_builder = lambda { expected_output }
      @yielded = []
      subject.each_node do |node|
        @yielded << node
      end
      @yielded.must_equal(expected_output)
    end
  end

  describe '#nodes' do
    it 'should delegate node creation to node_maker' do
      expected_output = ['output']
      maker = MiniTest::Mock.new
      maker.expect(:call, expected_output)
      subject.node_collection_builder = maker
      subject.nodes.must_equal(expected_output)
      maker.verify
    end
  end

  describe '#each_edge' do
    it 'should yield the edges' do
      expected_output = [1,2,3]
      subject.edge_collection_builder = lambda { expected_output }
      @yielded = []
      subject.each_edge do |edge|
        @yielded << edge
      end
      @yielded.must_equal(expected_output)
    end
  end

  describe '#edges' do
    it 'should delegate edge drawing to the edge_collection_builder' do
      expected_output = ['output']
      drawer = MiniTest::Mock.new
      drawer.expect(:call, expected_output)
      subject.edge_collection_builder = drawer
      subject.edges.must_equal(expected_output)
      drawer.verify
    end
  end

  describe '#each_attribute' do
    it 'should yield the attributes' do
      expected_output = [1,2,3]
      subject.attribute_collection_builder = lambda { expected_output }
      @yielded = []
      subject.each_attribute do |attribute|
        @yielded << attribute
      end
      @yielded.must_equal(expected_output)
    end
  end

  describe '#attributes' do
    it 'should delegate attribute creation to the attribute_collection_builder' do
      expected_output = ['output']
      builder = MiniTest::Mock.new
      builder.expect(:call, expected_output)
      subject.attribute_collection_builder = builder
      subject.attributes.must_equal(expected_output)
      builder.verify
    end
  end
end


text:
package org.apache.cassandra.utils;

import java.io.DataInputStream;
import java.io.IOException;

import org.junit.Assert;
import org.junit.Test;
import org.apache.cassandra.AbstractSerializationsTester;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.io.util.DataInputPlus.DataInputStreamPlus;
import org.apache.cassandra.io.util.DataOutputStreamPlus;
import org.apache.cassandra.service.StorageService;

public class SerializationsTest extends AbstractSerializationsTester
{

    private void testBloomFilterWrite(boolean offheap) throws IOException
    {
        IPartitioner partitioner = StorageService.getPartitioner();
        try (IFilter bf = FilterFactory.getFilter(1000000, 0.0001, offheap))
        {
            for (int i = 0; i < 100; i++)
                bf.add(partitioner.decorateKey(partitioner.getTokenFactory().toByteArray(partitioner.getRandomToken())));
            try (DataOutputStreamPlus out = getOutput("utils.BloomFilter.bin"))
            {
                FilterFactory.serialize(bf, out);
            }
        }
    }

    @Test
    public void testBloomFilterReadMURMUR3() throws IOException
    {
        if (EXECUTE_WRITES)
            testBloomFilterWrite(true);

        try (DataInputStream in = getInput("utils.BloomFilter.bin");
             IFilter filter = FilterFactory.deserialize(in, true))
        {
            Assert.assertNotNull(filter);
        }
    }

    private void testEstimatedHistogramWrite() throws IOException
    {
        EstimatedHistogram hist0 = new EstimatedHistogram();
        EstimatedHistogram hist1 = new EstimatedHistogram(5000);
        long[] offsets = new long[1000];
        long[] data = new long[offsets.length + 1];
        for (int i = 0; i < offsets.length; i++)
        {
            offsets[i] = i;
            data[i] = 10 * i;
        }
        data[offsets.length] = 100000;
        EstimatedHistogram hist2 = new EstimatedHistogram(offsets, data);

        try (DataOutputStreamPlus out = getOutput("utils.EstimatedHistogram.bin"))
        {
            EstimatedHistogram.serializer.serialize(hist0, out);
            EstimatedHistogram.serializer.serialize(hist1, out);
            EstimatedHistogram.serializer.serialize(hist2, out);
        }
    }

    @Test
    public void testEstimatedHistogramRead() throws IOException
    {
        if (EXECUTE_WRITES)
            testEstimatedHistogramWrite();

        try (DataInputStreamPlus in = getInput("utils.EstimatedHistogram.bin"))
        {
            Assert.assertNotNull(EstimatedHistogram.serializer.deserialize(in));
            Assert.assertNotNull(EstimatedHistogram.serializer.deserialize(in));
            Assert.assertNotNull(EstimatedHistogram.serializer.deserialize(in));
        }
    }
}


text:
<?php

/**
 * A special page that displays a list of pages that are not on anyones watchlist.
 *
 * @ingroup SpecialPage
 */
class UnwatchedpagesPage extends QueryPage {

	function __construct( $name = 'Unwatchedpages' ) {
		parent::__construct( $name, 'unwatchedpages' );
	}

	function isExpensive() { return true; }
	function isSyndicated() { return false; }

	function getQueryInfo() {
		return array (
			'tables' => array ( 'page', 'watchlist' ),
			'fields' => array ( 'page_namespace AS namespace',
					'page_title AS title',
					'page_namespace AS value' ),
			'conds' => array ( 'wl_title IS NULL',
					'page_is_redirect' => 0,
					"page_namespace != '" . NS_MEDIAWIKI .
					"'" ),
			'join_conds' => array ( 'watchlist' => array (
				'LEFT JOIN', array ( 'wl_title = page_title',
					'wl_namespace = page_namespace' ) ) )
		);
	}

	function sortDescending() { return false; }

	function getOrderFields() {
		return array( 'page_namespace', 'page_title' );
	}

	/**
	 * @param $skin Skin
	 * @param $result
	 * @return string
	 */
	function formatResult( $skin, $result ) {
		global $wgContLang;

		$nt = Title::makeTitle( $result->namespace, $result->title );
		$text = $wgContLang->convert( $nt->getPrefixedText() );

		$plink = Linker::linkKnown(
			$nt,
			htmlspecialchars( $text )
		);
		$token = WatchAction::getWatchToken( $nt, $this->getUser() );
		$wlink = Linker::linkKnown(
			$nt,
			wfMsgHtml( 'watch' ),
			array(),
			array( 'action' => 'watch', 'token' => $token )
		);

		return $this->getLanguage()->specialList( $plink, $wlink );
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Using as: ARM Directives</title>

<meta name="description" content="Using as: ARM Directives">
<meta name="keywords" content="Using as: ARM Directives">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="AS-Index.html#AS-Index" rel="index" title="AS Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="ARM_002dDependent.html#ARM_002dDependent" rel="up" title="ARM-Dependent">
<link href="ARM-Opcodes.html#ARM-Opcodes" rel="next" title="ARM Opcodes">
<link href="ARM-Floating-Point.html#ARM-Floating-Point" rel="prev" title="ARM Floating Point">

Next: ARM Opcodes, Previous: ARM Floating Point, Up: ARM-Dependent   [Contents][Index]

9.4.4 ARM Machine Directives

.2byte <var>expression</var> [, <var>expression</var>]*

.4byte <var>expression</var> [, <var>expression</var>]*

.8byte <var>expression</var> [, <var>expression</var>]*

These directives write 2, 4 or 8 byte values to the output section.

.align <var>expression</var> [, <var>expression</var>]

This is the generic <var>.align</var> directive.  For the ARM however if the
first argument is zero (ie no alignment is needed) the assembler will
behave as if the argument had been 2 (ie pad to the next four byte
boundary).  This is for compatibility with ARM’s own assembler.

.arch <var>name</var>

Select the target architecture.  Valid values for <var>name</var> are the same as
for the <samp>-march</samp> commandline option.

Specifying .arch clears any previously selected architecture
extensions.

.arch_extension <var>name</var>

Add or remove an architecture extension to the target architecture.  Valid
values for <var>name</var> are the same as those accepted as architectural
extensions by the <samp>-mcpu</samp> commandline option.

.arch_extension may be used multiple times to add or remove extensions
incrementally to the architecture being compiled for.

.arm

This performs the same action as <var>.code 32</var>.

.bss

This directive switches to the .bss section.

.cantunwind

Prevents unwinding through the current function.  No personality routine
or exception table data is required or permitted.

.code [16|32]

This directive selects the instruction set being generated. The value 16
selects Thumb, with the value 32 selecting ARM.

.cpu <var>name</var>

Select the target processor.  Valid values for <var>name</var> are the same as
for the <samp>-mcpu</samp> commandline option.

Specifying .cpu clears any previously selected architecture
extensions.

<var>name</var> .dn <var>register name</var> [<var>.type</var>] [[<var>index</var>]]

<var>name</var> .qn <var>register name</var> [<var>.type</var>] [[<var>index</var>]]

The dn and qn directives are used to create typed
and/or indexed register aliases for use in Advanced SIMD Extension
(Neon) instructions.  The former should be used to create aliases
of double-precision registers, and the latter to create aliases of
quad-precision registers.

If these directives are used to create typed aliases, those aliases can
be used in Neon instructions instead of writing types after the mnemonic
or after each operand.  For example:

        x .dn d2.f32
        y .dn d3.f32
        z .dn d4.f32[1]
        vmul x,y,z

This is equivalent to writing the following:

        vmul.f32 d2,d3,d4[1]

Aliases created using dn or qn can be destroyed using
unreq.

.eabi_attribute <var>tag</var>, <var>value</var>

Set the EABI object attribute <var>tag</var> to <var>value</var>.

The <var>tag</var> is either an attribute number, or one of the following:
Tag_CPU_raw_name, Tag_CPU_name, Tag_CPU_arch,
Tag_CPU_arch_profile, Tag_ARM_ISA_use,
Tag_THUMB_ISA_use, Tag_FP_arch, Tag_WMMX_arch,
Tag_Advanced_SIMD_arch, Tag_PCS_config,
Tag_ABI_PCS_R9_use, Tag_ABI_PCS_RW_data,
Tag_ABI_PCS_RO_data, Tag_ABI_PCS_GOT_use,
Tag_ABI_PCS_wchar_t, Tag_ABI_FP_rounding,
Tag_ABI_FP_denormal, Tag_ABI_FP_exceptions,
Tag_ABI_FP_user_exceptions, Tag_ABI_FP_number_model,
Tag_ABI_align_needed, Tag_ABI_align_preserved,
Tag_ABI_enum_size, Tag_ABI_HardFP_use,
Tag_ABI_VFP_args, Tag_ABI_WMMX_args,
Tag_ABI_optimization_goals, Tag_ABI_FP_optimization_goals,
Tag_compatibility, Tag_CPU_unaligned_access,
Tag_FP_HP_extension, Tag_ABI_FP_16bit_format,
Tag_MPextension_use, Tag_DIV_use,
Tag_nodefaults, Tag_also_compatible_with,
Tag_conformance, Tag_T2EE_use,
Tag_Virtualization_use

The <var>value</var> is either a number, "string", or
number, "string" depending on the tag.

Note - the following legacy values are also accepted by <var>tag</var>:
Tag_VFP_arch, Tag_ABI_align8_needed,
Tag_ABI_align8_preserved, Tag_VFP_HP_extension,

.even

This directive aligns to an even-numbered address.

.extend  <var>expression</var> [, <var>expression</var>]*

.ldouble  <var>expression</var> [, <var>expression</var>]*

These directives write 12byte long double floating-point values to the
output section.  These are not compatible with current ARM processors
or ABIs.

.fnend

Marks the end of a function with an unwind table entry.  The unwind index
table entry is created when this directive is processed.

If no personality routine has been specified then standard personality
routine 0 or 1 will be used, depending on the number of unwind opcodes
required.

.fnstart

Marks the start of a function with an unwind table entry.

.force_thumb

This directive forces the selection of Thumb instructions, even if the
target processor does not support those instructions

.fpu <var>name</var>

Select the floating-point unit to assemble for.  Valid values for <var>name</var>
are the same as for the <samp>-mfpu</samp> commandline option.

.handlerdata

Marks the end of the current function, and the start of the exception table
entry for that function.  Anything between this directive and the
.fnend directive will be added to the exception table entry.

Must be preceded by a .personality or .personalityindex
directive.

.inst <var>opcode</var> [ , … ]

.inst.n <var>opcode</var> [ , … ]

.inst.w <var>opcode</var> [ , … ]

Generates the instruction corresponding to the numerical value <var>opcode</var>.
.inst.n and .inst.w allow the Thumb instruction size to be
specified explicitly, overriding the normal encoding rules.

.ldouble  <var>expression</var> [, <var>expression</var>]*

See .extend.

.ltorg

This directive causes the current contents of the literal pool to be
dumped into the current section (which is assumed to be the .text
section) at the current location (aligned to a word boundary).
GAS maintains a separate literal pool for each section and each
sub-section.  The .ltorg directive will only affect the literal
pool of the current section and sub-section.  At the end of assembly
all remaining, un-empty literal pools will automatically be dumped.

Note - older versions of GAS would dump the current literal
pool any time a section change occurred.  This is no longer done, since
it prevents accurate control of the placement of literal pools.

.movsp <var>reg</var> [, #<var>offset</var>]

Tell the unwinder that <var>reg</var> contains an offset from the current
stack pointer.  If <var>offset</var> is not specified then it is assumed to be
zero.

.object_arch <var>name</var>

Override the architecture recorded in the EABI object attribute section.
Valid values for <var>name</var> are the same as for the .arch directive.
Typically this is useful when code uses runtime detection of CPU features.

.packed  <var>expression</var> [, <var>expression</var>]*

This directive writes 12-byte packed floating-point values to the
output section.  These are not compatible with current ARM processors
or ABIs.

.pad #<var>count</var>

Generate unwinder annotations for a stack adjustment of <var>count</var> bytes.
A positive value indicates the function prologue allocated stack space by
decrementing the stack pointer.

.personality <var>name</var>

Sets the personality routine for the current function to <var>name</var>.

.personalityindex <var>index</var>

Sets the personality routine for the current function to the EABI standard
routine number <var>index</var>

.pool

This is a synonym for .ltorg.

<var>name</var> .req <var>register name</var>

This creates an alias for <var>register name</var> called <var>name</var>.  For
example:

        foo .req r0

.save <var>reglist</var>

Generate unwinder annotations to restore the registers in <var>reglist</var>.
The format of <var>reglist</var> is the same as the corresponding store-multiple
instruction.

core registers

  .save {r4, r5, r6, lr}
  stmfd sp!, {r4, r5, r6, lr}

FPA registers

  .save f4, 2
  sfmfd f4, 2, [sp]!

VFP registers

  .save {d8, d9, d10}
  fstmdx sp!, {d8, d9, d10}

iWMMXt registers

  .save {wr10, wr11}
  wstrd wr11, [sp, #-8]!
  wstrd wr10, [sp, #-8]!
or
  .save wr11
  wstrd wr11, [sp, #-8]!
  .save wr10
  wstrd wr10, [sp, #-8]!

.setfp <var>fpreg</var>, <var>spreg</var> [, #<var>offset</var>]

Make all unwinder annotations relative to a frame pointer.  Without this
the unwinder will use offsets from the stack pointer.

The syntax of this directive is the same as the add or mov
instruction used to set the frame pointer.  <var>spreg</var> must be either
sp or mentioned in a previous .movsp directive.

.movsp ip
mov ip, sp
…
.setfp fp, ip, #4
add fp, ip, #4

.secrel32 <var>expression</var> [, <var>expression</var>]*

This directive emits relocations that evaluate to the section-relative
offset of each expression’s symbol.  This directive is only supported
for PE targets.

.syntax [unified | divided]

This directive sets the Instruction Set Syntax as described in the
ARM-Instruction-Set section.

.thumb

This performs the same action as <var>.code 16</var>.

.thumb_func

This directive specifies that the following symbol is the name of a
Thumb encoded function.  This information is necessary in order to allow
the assembler and linker to generate correct code for interworking
between Arm and Thumb instructions and should be used even if
interworking is not going to be performed.  The presence of this
directive also implies .thumb

This directive is not neccessary when generating EABI objects.  On these
targets the encoding is implicit when generating Thumb code.

.thumb_set

This performs the equivalent of a .set directive in that it
creates a symbol which is an alias for another symbol (possibly not yet
defined).  This directive also has the added property in that it marks
the aliased symbol as being a thumb function entry point, in the same
way that the .thumb_func directive does.

.tlsdescseq <var>tls-variable</var>

This directive is used to annotate parts of an inlined TLS descriptor
trampoline.  Normally the trampoline is provided by the linker, and
this directive is not needed.

.unreq <var>alias-name</var>

This undefines a register alias which was previously defined using the
req, dn or qn directives.  For example:

        foo .req r0
        .unreq foo

An error occurs if the name is undefined.  Note - this pseudo op can
be used to delete builtin in register name aliases (eg ’r0’).  This
should only be done if it is really necessary.

.unwind_raw <var>offset</var>, <var>byte1</var>, …

Insert one of more arbitary unwind opcode bytes, which are known to adjust
the stack pointer by <var>offset</var> bytes.

For example .unwind_raw 4, 0xb1, 0x01 is equivalent to
.save {r0}

.vsave <var>vfp-reglist</var>

Generate unwinder annotations to restore the VFP registers in <var>vfp-reglist</var>
using FLDMD.  Also works for VFPv3 registers
that are to be restored using VLDM.
The format of <var>vfp-reglist</var> is the same as the corresponding store-multiple
instruction.

VFP registers

  .vsave {d8, d9, d10}
  fstmdd sp!, {d8, d9, d10}

VFPv3 registers

  .vsave {d15, d16, d17}
  vstm sp!, {d15, d16, d17}

Since FLDMX and FSTMX are now deprecated, this directive should be
used in favour of .save for saving VFP registers for ARMv6 and above.

Next: ARM Opcodes, Previous: ARM Floating Point, Up: ARM-Dependent   [Contents][Index]


text:
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
//
// Constants that pertain to CI processes/tests only. No dependencies on vscode!
//
exports.IS_APPVEYOR = process.env.APPVEYOR === 'true';
exports.IS_TRAVIS = process.env.TRAVIS === 'true';
exports.IS_VSTS = process.env.TF_BUILD !== undefined;
exports.IS_CI_SERVER = exports.IS_TRAVIS || exports.IS_APPVEYOR || exports.IS_VSTS;
// Control JUnit-style output logging for reporting purposes.
let reportJunit = false;
if (exports.IS_CI_SERVER && process.env.MOCHA_REPORTER_JUNIT !== undefined) {
    reportJunit = process.env.MOCHA_REPORTER_JUNIT.toLowerCase() === 'true';
}
exports.MOCHA_REPORTER_JUNIT = reportJunit;
exports.MOCHA_CI_REPORTFILE = exports.MOCHA_REPORTER_JUNIT && process.env.MOCHA_CI_REPORTFILE !== undefined ?
    process.env.MOCHA_CI_REPORTFILE : './junit-out.xml';
exports.MOCHA_CI_PROPERTIES = exports.MOCHA_REPORTER_JUNIT && process.env.MOCHA_CI_PROPERTIES !== undefined ?
    process.env.MOCHA_CI_PROPERTIES : '';
exports.MOCHA_CI_REPORTER_ID = exports.MOCHA_REPORTER_JUNIT && process.env.MOCHA_CI_REPORTER_ID !== undefined ?
    process.env.MOCHA_CI_REPORTER_ID : 'mocha-junit-reporter';
exports.IS_CI_SERVER_TEST_DEBUGGER = process.env.IS_CI_SERVER_TEST_DEBUGGER === '1';
//# sourceMappingURL=ciConstants.js.map