text:
<?php

namespace Doctrine\Bundle\DoctrineBundle\DependencyInjection;

use Doctrine\Bundle\DoctrineBundle\Attribute\AsEntityListener;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsMiddleware;
use Doctrine\Bundle\DoctrineBundle\CacheWarmer\DoctrineMetadataCacheWarmer;
use Doctrine\Bundle\DoctrineBundle\Command\Proxy\ImportDoctrineCommand;
use Doctrine\Bundle\DoctrineBundle\Dbal\ManagerRegistryAwareConnectionProvider;
use Doctrine\Bundle\DoctrineBundle\Dbal\RegexSchemaAssetFilter;
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\IdGeneratorPass;
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\ServiceRepositoryCompilerPass;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepositoryInterface;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Connections\PrimaryReadReplicaConnection;
use Doctrine\DBAL\Driver\Middleware as MiddlewareInterface;
use Doctrine\DBAL\Logging\LoggerChain;
use Doctrine\DBAL\Sharding\PoolingShardConnection;
use Doctrine\DBAL\Sharding\PoolingShardManager;
use Doctrine\DBAL\Tools\Console\Command\ImportCommand;
use Doctrine\DBAL\Tools\Console\ConnectionProvider;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Id\AbstractIdGenerator;
use Doctrine\ORM\Proxy\Autoloader;
use Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand;
use Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand;
use Doctrine\ORM\Tools\Export\ClassMetadataExporter;
use Doctrine\ORM\UnitOfWork;
use LogicException;
use ReflectionMethod;
use Symfony\Bridge\Doctrine\ArgumentResolver\EntityValueResolver;
use Symfony\Bridge\Doctrine\Attribute\MapEntity;
use Symfony\Bridge\Doctrine\DependencyInjection\AbstractDoctrineExtension;
use Symfony\Bridge\Doctrine\IdGenerator\UlidGenerator;
use Symfony\Bridge\Doctrine\IdGenerator\UuidGenerator;
use Symfony\Bridge\Doctrine\Messenger\DoctrineClearEntityManagerWorkerSubscriber;
use Symfony\Bridge\Doctrine\Messenger\DoctrineTransactionMiddleware;
use Symfony\Bridge\Doctrine\Middleware\Debug\Middleware as SfDebugMiddleware;
use Symfony\Bridge\Doctrine\PropertyInfo\DoctrineExtractor;
use Symfony\Bridge\Doctrine\SchemaListener\DoctrineDbalCacheAdapterSchemaSubscriber;
use Symfony\Bridge\Doctrine\SchemaListener\MessengerTransportDoctrineSchemaSubscriber;
use Symfony\Bridge\Doctrine\SchemaListener\PdoCacheAdapterDoctrineSchemaSubscriber;
use Symfony\Bridge\Doctrine\SchemaListener\RememberMeTokenProviderDoctrineSchemaSubscriber;
use Symfony\Bridge\Doctrine\Validator\DoctrineLoader;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Adapter\PhpArrayAdapter;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Messenger\Bridge\Doctrine\Transport\DoctrineTransportFactory;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface;
use Symfony\Component\Validator\Mapping\Loader\LoaderInterface;

use function array_intersect_key;
use function array_keys;
use function class_exists;
use function interface_exists;
use function is_dir;
use function method_exists;
use function reset;
use function sprintf;
use function str_replace;
use function trigger_deprecation;

use const PHP_VERSION_ID;

/**
 * DoctrineExtension is an extension for the Doctrine DBAL and ORM library.
 */
class DoctrineExtension extends AbstractDoctrineExtension
{
    /** @var string */
    private $defaultConnection;

    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = $this->getConfiguration($configs, $container);
        $config        = $this->processConfiguration($configuration, $configs);

        if (! empty($config['dbal'])) {
            $this->dbalLoad($config['dbal'], $container);

            $this->loadMessengerServices($container);
        }

        if (empty($config['orm'])) {
            return;
        }

        if (empty($config['dbal'])) {
            throw new LogicException('Configuring the ORM layer requires to configure the DBAL layer as well.');
        }

        $this->ormLoad($config['orm'], $container);
    }

    /**
     * Loads the DBAL configuration.
     *
     * Usage example:
     *
     *      <doctrine:dbal id="myconn" dbname="sfweb" user="root" />
     *
     * @param array<string, mixed> $config    An array of configuration settings
     * @param ContainerBuilder     $container A ContainerBuilder instance
     */
    protected function dbalLoad(array $config, ContainerBuilder $container)
    {
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('dbal.xml');

        if (class_exists(ImportCommand::class)) {
            $container->register('doctrine.database_import_command', ImportDoctrineCommand::class)
                ->addTag('console.command', ['command' => 'doctrine:database:import']);
        }

        if (empty($config['default_connection'])) {
            $keys                         = array_keys($config['connections']);
            $config['default_connection'] = reset($keys);
        }

        $this->defaultConnection = $config['default_connection'];

        $container->setAlias('database_connection', sprintf('doctrine.dbal.%s_connection', $this->defaultConnection));
        $container->getAlias('database_connection')->setPublic(true);
        $container->setAlias('doctrine.dbal.event_manager', new Alias(sprintf('doctrine.dbal.%s_connection.event_manager', $this->defaultConnection), false));

        $container->setParameter('doctrine.dbal.connection_factory.types', $config['types']);

        $connections = [];

        foreach (array_keys($config['connections']) as $name) {
            $connections[$name] = sprintf('doctrine.dbal.%s_connection', $name);
        }

        $container->setParameter('doctrine.connections', $connections);
        $container->setParameter('doctrine.default_connection', $this->defaultConnection);

        $connWithLogging   = [];
        $connWithProfiling = [];
        $connWithBacktrace = [];
        foreach ($config['connections'] as $name => $connection) {
            if ($connection['logging']) {
                $connWithLogging[] = $name;
            }

            if ($connection['profiling']) {
                $connWithProfiling[] = $name;

                if ($connection['profiling_collect_backtrace']) {
                    $connWithBacktrace[] = $name;
                }
            }

            $this->loadDbalConnection($name, $connection, $container);
        }

        /** @psalm-suppress UndefinedClass */
        $container->registerForAutoconfiguration(MiddlewareInterface::class)->addTag('doctrine.middleware');

        if (PHP_VERSION_ID >= 80000 && method_exists(ContainerBuilder::class, 'registerAttributeForAutoconfiguration')) {
            $container->registerAttributeForAutoconfiguration(AsMiddleware::class, static function (ChildDefinition $definition, AsMiddleware $attribute) {
                if ($attribute->connections === []) {
                    $definition->addTag('doctrine.middleware');

                    return;
                }

                foreach ($attribute->connections as $connName) {
                    $definition->addTag('doctrine.middleware', ['connection' => $connName]);
                }
            });
        }

        $this->useMiddlewaresIfAvailable($container, $connWithLogging, $connWithProfiling, $connWithBacktrace);
    }

    /**
     * Loads a configured DBAL connection.
     *
     * @param string               $name       The name of the connection
     * @param array<string, mixed> $connection A dbal connection configuration.
     * @param ContainerBuilder     $container  A ContainerBuilder instance
     */
    protected function loadDbalConnection($name, array $connection, ContainerBuilder $container)
    {
        $configuration = $container->setDefinition(sprintf('doctrine.dbal.%s_connection.configuration', $name), new ChildDefinition('doctrine.dbal.connection.configuration'));
        $logger        = null;

        /** @psalm-suppress UndefinedClass */
        if (! interface_exists(MiddlewareInterface::class) && $connection['logging']) {
            $logger = new Reference('doctrine.dbal.logger');
        }

        unset($connection['logging']);

        $dataCollectorDefinition = $container->getDefinition('data_collector.doctrine');
        $dataCollectorDefinition->replaceArgument(1, $connection['profiling_collect_schema_errors']);

        if (! $this->isSfDebugMiddlewareAvailable() && $connection['profiling']) {
            $profilingAbstractId = $connection['profiling_collect_backtrace'] ?
                'doctrine.dbal.logger.backtrace' :
                'doctrine.dbal.logger.profiling';

            $profilingLoggerId = $profilingAbstractId . '.' . $name;
            $container->setDefinition($profilingLoggerId, new ChildDefinition($profilingAbstractId));
            $profilingLogger = new Reference($profilingLoggerId);
            $dataCollectorDefinition->addMethodCall('addLogger', [$name, $profilingLogger]);

            if ($logger !== null) {
                $chainLogger = $container->register(
                    'doctrine.dbal.logger.chain',
                    LoggerChain::class
                );
                $chainLogger->addArgument([$logger, $profilingLogger]);

                $loggerId = 'doctrine.dbal.logger.chain.' . $name;
                $container->setDefinition($loggerId, $chainLogger);
                $logger = new Reference($loggerId);
            } else {
                $logger = $profilingLogger;
            }
        }

        unset(
            $connection['profiling'],
            $connection['profiling_collect_backtrace'],
            $connection['profiling_collect_schema_errors']
        );

        if (isset($connection['auto_commit'])) {
            $configuration->addMethodCall('setAutoCommit', [$connection['auto_commit']]);
        }

        unset($connection['auto_commit']);

        if (isset($connection['schema_filter']) && $connection['schema_filter']) {
            $definition = new Definition(RegexSchemaAssetFilter::class, [$connection['schema_filter']]);
            $definition->addTag('doctrine.dbal.schema_filter', ['connection' => $name]);
            $container->setDefinition(sprintf('doctrine.dbal.%s_regex_schema_filter', $name), $definition);
        }

        unset($connection['schema_filter']);

        if ($logger) {
            $configuration->addMethodCall('setSQLLogger', [$logger]);
        }

        // event manager
        $container->setDefinition(sprintf('doctrine.dbal.%s_connection.event_manager', $name), new ChildDefinition('doctrine.dbal.connection.event_manager'));

        // connection
        $options = $this->getConnectionOptions($connection);

        $connectionId = sprintf('doctrine.dbal.%s_connection', $name);

        $def = $container
            ->setDefinition($connectionId, new ChildDefinition('doctrine.dbal.connection'))
            ->setPublic(true)
            ->setArguments([
                $options,
                new Reference(sprintf('doctrine.dbal.%s_connection.configuration', $name)),
                new Reference(sprintf('doctrine.dbal.%s_connection.event_manager', $name)),
                $connection['mapping_types'],
            ]);

        $container
            ->registerAliasForArgument($connectionId, Connection::class, sprintf('%sConnection', $name))
            ->setPublic(false);

        // Set class in case "wrapper_class" option was used to assist IDEs
        if (isset($options['wrapperClass'])) {
            $def->setClass($options['wrapperClass']);
        }

        if (! empty($connection['use_savepoints'])) {
            $def->addMethodCall('setNestTransactionsWithSavepoints', [$connection['use_savepoints']]);
        }

        // Create a shard_manager for this connection
        if (isset($options['shards'])) {
            trigger_deprecation(
                'doctrine/doctrine-bundle',
                '2.7',
                'Using shards for connection "%s" is deprecated. DBAL 3 does not support shards anymore.',
                $name
            );
            $shardManagerDefinition = new Definition($options['shardManagerClass'], [new Reference($connectionId)]);
            $container->setDefinition(sprintf('doctrine.dbal.%s_shard_manager', $name), $shardManagerDefinition);
        }

        // dbal < 2.11 BC layer
        if (! interface_exists(ConnectionProvider::class)) {
            return;
        }

        $container->setDefinition(
            ManagerRegistryAwareConnectionProvider::class,
            new Definition(ManagerRegistryAwareConnectionProvider::class, [$container->getDefinition('doctrine')])
        );
    }

    /**
     * @param array<string, mixed> $connection
     *
     * @return mixed[]
     */
    protected function getConnectionOptions(array $connection): array
    {
        $options = $connection;

        $connectionDefaults = [
            'host' => 'localhost',
            'port' => null,
            'user' => 'root',
            'password' => null,
        ];

        if ($options['override_url'] ?? false) {
            $options['connection_override_options'] = array_intersect_key($options, ['dbname' => null] + $connectionDefaults);
        }

        unset($options['override_url']);

        $options += $connectionDefaults;

        foreach (['shards', 'replicas', 'slaves'] as $connectionKey) {
            foreach (array_keys($options[$connectionKey]) as $name) {
                $options[$connectionKey][$name] += $connectionDefaults;
            }
        }

        if (isset($options['platform_service'])) {
            $options['platform'] = new Reference($options['platform_service']);
            unset($options['platform_service']);
        }

        unset($options['mapping_types']);

        if (isset($options['shard_choser_service'])) {
            $options['shard_choser'] = new Reference($options['shard_choser_service']);
            unset($options['shard_choser_service']);
        }

        foreach (
            [
                'options' => 'driverOptions',
                'driver_class' => 'driverClass',
                'wrapper_class' => 'wrapperClass',
                'keep_slave' => 'keepReplica',
                'keep_replica' => 'keepReplica',
                'replicas' => 'replica',
                'shard_choser' => 'shardChoser',
                'shard_manager_class' => 'shardManagerClass',
                'server_version' => 'serverVersion',
                'default_table_options' => 'defaultTableOptions',
            ] as $old => $new
        ) {
            if (! isset($options[$old])) {
                continue;
            }

            $options[$new] = $options[$old];
            unset($options[$old]);
        }

        if (! empty($options['slaves']) && ! empty($options['replica']) && ! empty($options['shards'])) {
            throw new InvalidArgumentException('Sharding and primary-replica connection cannot be used together');
        }

        foreach (['shards', 'replica', 'slaves'] as $connectionKey) {
            foreach ($options[$connectionKey] as $name => $value) {
                $driverOptions       = $value['driverOptions'] ?? [];
                $parentDriverOptions = $options['driverOptions'] ?? [];
                if ($driverOptions === [] && $parentDriverOptions === []) {
                    continue;
                }

                $options[$connectionKey][$name]['driverOptions'] = $driverOptions + $parentDriverOptions;
            }
        }

        if (! empty($options['slaves']) || ! empty($options['replica'])) {
            $nonRewrittenKeys = [
                'driver' => true,
                'driverClass' => true,
                'wrapperClass' => true,
                'keepSlave' => true,
                'keepReplica' => true,
                'shardChoser' => true,
                'platform' => true,
                'slaves' => true,
                'primary' => true,
                'replica' => true,
                'shards' => true,
                'serverVersion' => true,
                'defaultTableOptions' => true,
                // included by safety but should have been unset already
                'logging' => true,
                'profiling' => true,
                'mapping_types' => true,
                'platform_service' => true,
            ];
            foreach ($options as $key => $value) {
                if (isset($nonRewrittenKeys[$key])) {
                    continue;
                }

                $options['primary'][$key] = $value;
                unset($options[$key]);
            }

            if (empty($options['wrapperClass'])) {
                // Change the wrapper class only if user did not configure custom one.
                $options['wrapperClass'] = PrimaryReadReplicaConnection::class;
            }
        } else {
            unset($options['slaves'], $options['replica']);
        }

        if (! empty($options['shards'])) {
            $nonRewrittenKeys = [
                'driver' => true,
                'driverOptions' => true,
                'driverClass' => true,
                'wrapperClass' => true,
                'keepSlave' => true,
                'keepReplica' => true,
                'shardChoser' => true,
                'platform' => true,
                'slaves' => true,
                'replica' => true,
                'global' => true,
                'shards' => true,
                'serverVersion' => true,
                'defaultTableOptions' => true,
                // included by safety but should have been unset already
                'logging' => true,
                'profiling' => true,
                'mapping_types' => true,
                'platform_service' => true,
                'shardManagerClass' => true,
            ];
            foreach ($options as $key => $value) {
                if (isset($nonRewrittenKeys[$key])) {
                    continue;
                }

                $options['global'][$key] = $value;
                unset($options[$key]);
            }

            if (empty($options['wrapperClass'])) {
                // Change the wrapper class only if the user does not already forced using a custom one.
                $options['wrapperClass'] = PoolingShardConnection::class;
            }

            if (empty($options['shardManagerClass'])) {
                // Change the shard manager class only if the user does not already forced using a custom one.
                $options['shardManagerClass'] = PoolingShardManager::class;
            }
        } else {
            unset($options['shards']);
        }

        return $options;
    }

    /**
     * Loads the Doctrine ORM configuration.
     *
     * Usage example:
     *
     *     <doctrine:orm id="mydm" connection="myconn" />
     *
     * @param array<string, mixed> $config    An array of configuration settings
     * @param ContainerBuilder     $container A ContainerBuilder instance
     */
    protected function ormLoad(array $config, ContainerBuilder $container)
    {
        if (! class_exists(UnitOfWork::class)) {
            throw new LogicException('To configure the ORM layer, you must first install the doctrine/orm package.');
        }

        $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('orm.xml');

        if (! (new ReflectionMethod(EntityManager::class, '__construct'))->isPublic()) {
            $container->getDefinition('doctrine.orm.entity_manager.abstract')
                ->setFactory(['%doctrine.orm.entity_manager.class%', 'create']);
        }

        if (class_exists(AbstractType::class)) {
            $container->getDefinition('form.type.entity')->addTag('kernel.reset', ['method' => 'reset']);
        }

        // available in Symfony 5.4 and higher
        if (! class_exists(DoctrineDbalCacheAdapterSchemaSubscriber::class)) {
            $container->removeDefinition('doctrine.orm.listeners.doctrine_dbal_cache_adapter_schema_subscriber');
        }

        // available in Symfony 5.1 and up to Symfony 5.4 (deprecated)
        if (! class_exists(PdoCacheAdapterDoctrineSchemaSubscriber::class)) {
            $container->removeDefinition('doctrine.orm.listeners.pdo_cache_adapter_doctrine_schema_subscriber');
        }

        // available in Symfony 5.3 and higher
        if (! class_exists(RememberMeTokenProviderDoctrineSchemaSubscriber::class)) {
            $container->removeDefinition('doctrine.orm.listeners.doctrine_token_provider_schema_subscriber');
        }

        if (! class_exists(UlidGenerator::class)) {
            $container->removeDefinition('doctrine.ulid_generator');
        }

        if (! class_exists(UuidGenerator::class)) {
            $container->removeDefinition('doctrine.uuid_generator');
        }

        // available in Symfony 6.2 and higher
        if (! class_exists(EntityValueResolver::class)) {
            $container->removeDefinition('doctrine.orm.entity_value_resolver');
            $container->removeDefinition('doctrine.orm.entity_value_resolver.expression_language');
        } else {
            if (! class_exists(ExpressionLanguage::class)) {
                $container->removeDefinition('doctrine.orm.entity_value_resolver.expression_language');
            }

            $controllerResolverDefaults = [];

            if (! $config['controller_resolver']['enabled']) {
                $controllerResolverDefaults['disabled'] = true;
            }

            if (! $config['controller_resolver']['auto_mapping']) {
                $controllerResolverDefaults['mapping'] = [];
            }

            if ($config['controller_resolver']['evict_cache']) {
                $controllerResolverDefaults['evict_cache'] = true;
            }

            if ($controllerResolverDefaults) {
                $container->getDefinition('doctrine.orm.entity_value_resolver')->setArgument(2, (new Definition(MapEntity::class))->setArguments([
                    null,
                    null,
                    null,
                    $controllerResolverDefaults['mapping'] ?? null,
                    null,
                    null,
                    null,
                    $controllerResolverDefaults['evict_cache'] ?? null,
                    $controllerResolverDefaults['disabled'] ?? false,
                ]));
            }
        }

        // not available in Doctrine ORM 3.0 and higher
        if (! class_exists(ConvertMappingCommand::class)) {
            $container->removeDefinition('doctrine.mapping_convert_command');
        }

        if (! class_exists(EnsureProductionSettingsCommand::class)) {
            $container->removeDefinition('doctrine.ensure_production_settings_command');
        }

        if (! class_exists(ClassMetadataExporter::class)) {
            $container->removeDefinition('doctrine.mapping_import_command');
        }

        $entityManagers = [];
        foreach (array_keys($config['entity_managers']) as $name) {
            $entityManagers[$name] = sprintf('doctrine.orm.%s_entity_manager', $name);
        }

        $container->setParameter('doctrine.entity_managers', $entityManagers);

        if (empty($config['default_entity_manager'])) {
            $tmp                              = array_keys($entityManagers);
            $config['default_entity_manager'] = reset($tmp);
        }

        $container->setParameter('doctrine.default_entity_manager', $config['default_entity_manager']);

        $options = ['auto_generate_proxy_classes', 'proxy_dir', 'proxy_namespace'];
        foreach ($options as $key) {
            $container->setParameter('doctrine.orm.' . $key, $config[$key]);
        }

        $container->setAlias('doctrine.orm.entity_manager', $defaultEntityManagerDefinitionId = sprintf('doctrine.orm.%s_entity_manager', $config['default_entity_manager']));
        $container->getAlias('doctrine.orm.entity_manager')->setPublic(true);

        $config['entity_managers'] = $this->fixManagersAutoMappings($config['entity_managers'], $container->getParameter('kernel.bundles'));

        foreach ($config['entity_managers'] as $name => $entityManager) {
            $entityManager['name'] = $name;
            $this->loadOrmEntityManager($entityManager, $container);

            if (interface_exists(PropertyInfoExtractorInterface::class)) {
                $this->loadPropertyInfoExtractor($name, $container);
            }

            if (! interface_exists(LoaderInterface::class)) {
                continue;
            }

            $this->loadValidatorLoader($name, $container);
        }

        if ($config['resolve_target_entities']) {
            $def = $container->findDefinition('doctrine.orm.listeners.resolve_target_entity');
            foreach ($config['resolve_target_entities'] as $name => $implementation) {
                $def->addMethodCall('addResolveTargetEntity', [
                    $name,
                    $implementation,
                    [],
                ]);
            }

            $def->addTag('doctrine.event_subscriber');
        }

        $container->registerForAutoconfiguration(ServiceEntityRepositoryInterface::class)
            ->addTag(ServiceRepositoryCompilerPass::REPOSITORY_SERVICE_TAG);

        $container->registerForAutoconfiguration(EventSubscriberInterface::class)
            ->addTag('doctrine.event_subscriber');

        $container->registerForAutoconfiguration(AbstractIdGenerator::class)
            ->addTag(IdGeneratorPass::ID_GENERATOR_TAG);

        if (method_exists($container, 'registerAttributeForAutoconfiguration')) {
            $container->registerAttributeForAutoconfiguration(AsEntityListener::class, static function (ChildDefinition $definition, AsEntityListener $attribute) {
                $definition->addTag('doctrine.orm.entity_listener', [
                    'event'          => $attribute->event,
                    'method'         => $attribute->method,
                    'lazy'           => $attribute->lazy,
                    'entity_manager' => $attribute->entityManager,
                    'entity'         => $attribute->entity,
                ]);
            });
        }

        /** @see DoctrineBundle::boot() */
        $container->getDefinition($defaultEntityManagerDefinitionId)
            ->addTag('container.preload', [
                'class' => Autoloader::class,
            ]);
    }

    /**
     * Loads a configured ORM entity manager.
     *
     * @param array<string, mixed> $entityManager A configured ORM entity manager.
     * @param ContainerBuilder     $container     A ContainerBuilder instance
     */
    protected function loadOrmEntityManager(array $entityManager, ContainerBuilder $container)
    {
        $ormConfigDef = $container->setDefinition(sprintf('doctrine.orm.%s_configuration', $entityManager['name']), new ChildDefinition('doctrine.orm.configuration'));
        $ormConfigDef->addTag(IdGeneratorPass::CONFIGURATION_TAG);

        $this->loadOrmEntityManagerMappingInformation($entityManager, $ormConfigDef, $container);
        $this->loadOrmCacheDrivers($entityManager, $container);

        if (isset($entityManager['entity_listener_resolver']) && $entityManager['entity_listener_resolver']) {
            $container->setAlias(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name']), $entityManager['entity_listener_resolver']);
        } else {
            $definition = new Definition('%doctrine.orm.entity_listener_resolver.class%');
            $definition->addArgument(new Reference('service_container'));
            $container->setDefinition(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name']), $definition);
        }

        $methods = [
            'setMetadataCache' => new Reference(sprintf('doctrine.orm.%s_metadata_cache', $entityManager['name'])),
            'setQueryCache' => new Reference(sprintf('doctrine.orm.%s_query_cache', $entityManager['name'])),
            'setResultCache' => new Reference(sprintf('doctrine.orm.%s_result_cache', $entityManager['name'])),
            'setMetadataDriverImpl' => new Reference('doctrine.orm.' . $entityManager['name'] . '_metadata_driver'),
            'setProxyDir' => '%doctrine.orm.proxy_dir%',
            'setProxyNamespace' => '%doctrine.orm.proxy_namespace%',
            'setAutoGenerateProxyClasses' => '%doctrine.orm.auto_generate_proxy_classes%',
            'setSchemaIgnoreClasses' => $entityManager['schema_ignore_classes'],
            'setClassMetadataFactoryName' => $entityManager['class_metadata_factory_name'],
            'setDefaultRepositoryClassName' => $entityManager['default_repository_class'],
            'setNamingStrategy' => new Reference($entityManager['naming_strategy']),
            'setQuoteStrategy' => new Reference($entityManager['quote_strategy']),
            'setEntityListenerResolver' => new Reference(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name'])),
        ];

        $listenerId        = sprintf('doctrine.orm.%s_listeners.attach_entity_listeners', $entityManager['name']);
        $listenerDef       = $container->setDefinition($listenerId, new Definition('%doctrine.orm.listeners.attach_entity_listeners.class%'));
        $listenerTagParams = ['event' => 'loadClassMetadata'];
        if (isset($entityManager['connection'])) {
            $listenerTagParams['connection'] = $entityManager['connection'];
        }

        $listenerDef->addTag('doctrine.event_listener', $listenerTagParams);

        if (isset($entityManager['second_level_cache'])) {
            $this->loadOrmSecondLevelCache($entityManager, $ormConfigDef, $container);
        }

        if ($entityManager['repository_factory']) {
            $methods['setRepositoryFactory'] = new Reference($entityManager['repository_factory']);
        }

        foreach ($methods as $method => $arg) {
            $ormConfigDef->addMethodCall($method, [$arg]);
        }

        foreach ($entityManager['hydrators'] as $name => $class) {
            $ormConfigDef->addMethodCall('addCustomHydrationMode', [$name, $class]);
        }

        if (! empty($entityManager['dql'])) {
            foreach ($entityManager['dql']['string_functions'] as $name => $function) {
                $ormConfigDef->addMethodCall('addCustomStringFunction', [$name, $function]);
            }

            foreach ($entityManager['dql']['numeric_functions'] as $name => $function) {
                $ormConfigDef->addMethodCall('addCustomNumericFunction', [$name, $function]);
            }

            foreach ($entityManager['dql']['datetime_functions'] as $name => $function) {
                $ormConfigDef->addMethodCall('addCustomDatetimeFunction', [$name, $function]);
            }
        }

        $enabledFilters    = [];
        $filtersParameters = [];
        foreach ($entityManager['filters'] as $name => $filter) {
            $ormConfigDef->addMethodCall('addFilter', [$name, $filter['class']]);
            if ($filter['enabled']) {
                $enabledFilters[] = $name;
            }

            if (! $filter['parameters']) {
                continue;
            }

            $filtersParameters[$name] = $filter['parameters'];
        }

        $managerConfiguratorName = sprintf('doctrine.orm.%s_manager_configurator', $entityManager['name']);
        $container
            ->setDefinition($managerConfiguratorName, new ChildDefinition('doctrine.orm.manager_configurator.abstract'))
            ->replaceArgument(0, $enabledFilters)
            ->replaceArgument(1, $filtersParameters);

        if (! isset($entityManager['connection'])) {
            $entityManager['connection'] = $this->defaultConnection;
        }

        $entityManagerId = sprintf('doctrine.orm.%s_entity_manager', $entityManager['name']);

        $container
            ->setDefinition($entityManagerId, new ChildDefinition('doctrine.orm.entity_manager.abstract'))
            ->setPublic(true)
            ->setArguments([
                new Reference(sprintf('doctrine.dbal.%s_connection', $entityManager['connection'])),
                new Reference(sprintf('doctrine.orm.%s_configuration', $entityManager['name'])),
            ])
            ->setConfigurator([new Reference($managerConfiguratorName), 'configure']);

        $container
            ->registerAliasForArgument($entityManagerId, EntityManagerInterface::class, sprintf('%sEntityManager', $entityManager['name']))
            ->setPublic(false);

        $container->setAlias(
            sprintf('doctrine.orm.%s_entity_manager.event_manager', $entityManager['name']),
            new Alias(sprintf('doctrine.dbal.%s_connection.event_manager', $entityManager['connection']), false)
        );

        if (! isset($entityManager['entity_listeners'])) {
            return;
        }

        $entities = $entityManager['entity_listeners']['entities'];

        foreach ($entities as $entityListenerClass => $entity) {
            foreach ($entity['listeners'] as $listenerClass => $listener) {
                foreach ($listener['events'] as $listenerEvent) {
                    $listenerEventName = $listenerEvent['type'];
                    $listenerMethod    = $listenerEvent['method'];

                    $listenerDef->addMethodCall('addEntityListener', [
                        $entityListenerClass,
                        $listenerClass,
                        $listenerEventName,
                        $listenerMethod,
                    ]);
                }
            }
        }
    }

    /**
     * Loads an ORM entity managers bundle mapping information.
     *
     * There are two distinct configuration possibilities for mapping information:
     *
     * 1. Specify a bundle and optionally details where the entity and mapping information reside.
     * 2. Specify an arbitrary mapping location.
     *
     * @param array<string, mixed> $entityManager A configured ORM entity manager
     * @param Definition           $ormConfigDef  A Definition instance
     * @param ContainerBuilder     $container     A ContainerBuilder instance
     *
     * @example
     *
     *  doctrine.orm:
     *     mappings:
     *         MyBundle1: ~
     *         MyBundle2: yml
     *         MyBundle3: { type: annotation, dir: Entities/ }
     *         MyBundle4: { type: xml, dir: Resources/config/doctrine/mapping }
     *         MyBundle5: { type: attribute, dir: Entities/ }
     *         MyBundle6:
     *             type: yml
     *             dir: bundle-mappings/
     *             alias: BundleAlias
     *         arbitrary_key:
     *             type: xml
     *             dir: %kernel.project_dir%/src/vendor/DoctrineExtensions/lib/DoctrineExtensions/Entities
     *             prefix: DoctrineExtensions\Entities\
     *             alias: DExt
     *
     * In the case of bundles everything is really optional (which leads to autodetection for this bundle) but
     * in the mappings key everything except alias is a required argument.
     */
    protected function loadOrmEntityManagerMappingInformation(array $entityManager, Definition $ormConfigDef, ContainerBuilder $container)
    {
        // reset state of drivers and alias map. They are only used by this methods and children.
        $this->drivers  = [];
        $this->aliasMap = [];

        $this->loadMappingInformation($entityManager, $container);
        $this->registerMappingDrivers($entityManager, $container);

        $ormConfigDef->addMethodCall('setEntityNamespaces', [$this->aliasMap]);
    }

    /**
     * Loads an ORM second level cache bundle mapping information.
     *
     * @param array<string, mixed> $entityManager A configured ORM entity manager
     * @param Definition           $ormConfigDef  A Definition instance
     * @param ContainerBuilder     $container     A ContainerBuilder instance
     *
     * @example
     *  entity_managers:
     *      default:
     *          second_level_cache:
     *              region_lifetime: 3600
     *              region_lock_lifetime: 60
     *              region_cache_driver: apc
     *              log_enabled: true
     *              regions:
     *                  my_service_region:
     *                      type: service
     *                      service : "my_service_region"
     *
     *                  my_query_region:
     *                      lifetime: 300
     *                      cache_driver: array
     *                      type: filelock
     *
     *                  my_entity_region:
     *                      lifetime: 600
     *                      cache_driver:
     *                          type: apc
     */
    protected function loadOrmSecondLevelCache(array $entityManager, Definition $ormConfigDef, ContainerBuilder $container)
    {
        $driverId = null;
        $enabled  = $entityManager['second_level_cache']['enabled'];

        if (isset($entityManager['second_level_cache']['region_cache_driver'])) {
            $driverName = 'second_level_cache.region_cache_driver';
            $driverMap  = $entityManager['second_level_cache']['region_cache_driver'];
            $driverId   = $this->loadCacheDriver($driverName, $entityManager['name'], $driverMap, $container);
        }

        $configId   = sprintf('doctrine.orm.%s_second_level_cache.cache_configuration', $entityManager['name']);
        $regionsId  = sprintf('doctrine.orm.%s_second_level_cache.regions_configuration', $entityManager['name']);
        $driverId   = $driverId ?: sprintf('doctrine.orm.%s_second_level_cache.region_cache_driver', $entityManager['name']);
        $configDef  = $container->setDefinition($configId, new Definition('%doctrine.orm.second_level_cache.cache_configuration.class%'));
        $regionsDef = $container
            ->setDefinition($regionsId, new Definition('%doctrine.orm.second_level_cache.regions_configuration.class%'))
            ->setArguments([$entityManager['second_level_cache']['region_lifetime'], $entityManager['second_level_cache']['region_lock_lifetime']]);

        $slcFactoryId = sprintf('doctrine.orm.%s_second_level_cache.default_cache_factory', $entityManager['name']);
        $factoryClass = $entityManager['second_level_cache']['factory'] ?? '%doctrine.orm.second_level_cache.default_cache_factory.class%';

        $definition = new Definition($factoryClass, [new Reference($regionsId), new Reference($driverId)]);

        $slcFactoryDef = $container
            ->setDefinition($slcFactoryId, $definition);

        if (isset($entityManager['second_level_cache']['regions'])) {
            foreach ($entityManager['second_level_cache']['regions'] as $name => $region) {
                $regionRef  = null;
                $regionType = $region['type'];

                if ($regionType === 'service') {
                    $regionId  = sprintf('doctrine.orm.%s_second_level_cache.region.%s', $entityManager['name'], $name);
                    $regionRef = new Reference($region['service']);

                    $container->setAlias($regionId, new Alias($region['service'], false));
                }

                if ($regionType === 'default' || $regionType === 'filelock') {
                    $regionId   = sprintf('doctrine.orm.%s_second_level_cache.region.%s', $entityManager['name'], $name);
                    $driverName = sprintf('second_level_cache.region.%s_driver', $name);
                    $driverMap  = $region['cache_driver'];
                    $driverId   = $this->loadCacheDriver($driverName, $entityManager['name'], $driverMap, $container);
                    $regionRef  = new Reference($regionId);

                    $container
                        ->setDefinition($regionId, new Definition('%doctrine.orm.second_level_cache.default_region.class%'))
                        ->setArguments([$name, new Reference($driverId), $region['lifetime']]);
                }

                if ($regionType === 'filelock') {
                    $regionId = sprintf('doctrine.orm.%s_second_level_cache.region.%s_filelock', $entityManager['name'], $name);

                    $container
                        ->setDefinition($regionId, new Definition('%doctrine.orm.second_level_cache.filelock_region.class%'))
                        ->setArguments([$regionRef, $region['lock_path'], $region['lock_lifetime']]);

                    $regionRef = new Reference($regionId);
                    $regionsDef->addMethodCall('getLockLifetime', [$name, $region['lock_lifetime']]);
                }

                $regionsDef->addMethodCall('setLifetime', [$name, $region['lifetime']]);
                $slcFactoryDef->addMethodCall('setRegion', [$regionRef]);
            }
        }

        if ($entityManager['second_level_cache']['log_enabled']) {
            $loggerChainId   = sprintf('doctrine.orm.%s_second_level_cache.logger_chain', $entityManager['name']);
            $loggerStatsId   = sprintf('doctrine.orm.%s_second_level_cache.logger_statistics', $entityManager['name']);
            $loggerChaingDef = $container->setDefinition($loggerChainId, new Definition('%doctrine.orm.second_level_cache.logger_chain.class%'));
            $loggerStatsDef  = $container->setDefinition($loggerStatsId, new Definition('%doctrine.orm.second_level_cache.logger_statistics.class%'));

            $loggerChaingDef->addMethodCall('setLogger', ['statistics', $loggerStatsDef]);
            $configDef->addMethodCall('setCacheLogger', [$loggerChaingDef]);

            foreach ($entityManager['second_level_cache']['loggers'] as $name => $logger) {
                $loggerId  = sprintf('doctrine.orm.%s_second_level_cache.logger.%s', $entityManager['name'], $name);
                $loggerRef = new Reference($logger['service']);

                $container->setAlias($loggerId, new Alias($logger['service'], false));
                $loggerChaingDef->addMethodCall('setLogger', [$name, $loggerRef]);
            }
        }

        $configDef->addMethodCall('setCacheFactory', [$slcFactoryDef]);
        $configDef->addMethodCall('setRegionsConfiguration', [$regionsDef]);
        $ormConfigDef->addMethodCall('setSecondLevelCacheEnabled', [$enabled]);
        $ormConfigDef->addMethodCall('setSecondLevelCacheConfiguration', [$configDef]);
    }

    /**
     * {@inheritDoc}
     */
    protected function getObjectManagerElementName($name): string
    {
        return 'doctrine.orm.' . $name;
    }

    protected function getMappingObjectDefaultName(): string
    {
        return 'Entity';
    }

    protected function getMappingResourceConfigDirectory(?string $bundleDir = null): string
    {
        if ($bundleDir !== null && is_dir($bundleDir . '/config/doctrine')) {
            return 'config/doctrine';
        }

        return 'Resources/config/doctrine';
    }

    protected function getMappingResourceExtension(): string
    {
        return 'orm';
    }

    /**
     * {@inheritDoc}
     */
    protected function loadCacheDriver($cacheName, $objectManagerName, array $cacheDriver, ContainerBuilder $container): string
    {
        $aliasId = $this->getObjectManagerElementName(sprintf('%s_%s', $objectManagerName, $cacheName));

        switch ($cacheDriver['type'] ?? 'pool') {
            case 'service':
                $serviceId = $cacheDriver['id'];
                break;

            case 'pool':
                $serviceId = $cacheDriver['pool'] ?? $this->createArrayAdapterCachePool($container, $objectManagerName, $cacheName);
                break;

            default:
                throw new \InvalidArgumentException(sprintf(
                    'Unknown cache of type "%s" configured for cache "%s" in entity manager "%s".',
                    $cacheDriver['type'],
                    $cacheName,
                    $objectManagerName
                ));
        }

        $container->setAlias($aliasId, new Alias($serviceId, false));

        return $aliasId;
    }

    /**
     * Loads a configured entity managers cache drivers.
     *
     * @param array<string, mixed> $entityManager A configured ORM entity manager.
     */
    protected function loadOrmCacheDrivers(array $entityManager, ContainerBuilder $container)
    {
        if (isset($entityManager['metadata_cache_driver'])) {
            $this->loadCacheDriver('metadata_cache', $entityManager['name'], $entityManager['metadata_cache_driver'], $container);
        } else {
            $this->createMetadataCache($entityManager['name'], $container);
        }

        $this->loadCacheDriver('result_cache', $entityManager['name'], $entityManager['result_cache_driver'], $container);
        $this->loadCacheDriver('query_cache', $entityManager['name'], $entityManager['query_cache_driver'], $container);
    }

    private function createMetadataCache(string $objectManagerName, ContainerBuilder $container): void
    {
        $aliasId = $this->getObjectManagerElementName(sprintf('%s_%s', $objectManagerName, 'metadata_cache'));
        $cacheId = sprintf('cache.doctrine.orm.%s.%s', $objectManagerName, 'metadata');

        $cache = new Definition(ArrayAdapter::class);

        if (! $container->getParameter('kernel.debug')) {
            $phpArrayFile         = '%kernel.cache_dir%' . sprintf('/doctrine/orm/%s_metadata.php', $objectManagerName);
            $cacheWarmerServiceId = $this->getObjectManagerElementName(sprintf('%s_%s', $objectManagerName, 'metadata_cache_warmer'));

            $container->register($cacheWarmerServiceId, DoctrineMetadataCacheWarmer::class)
                ->setArguments([new Reference(sprintf('doctrine.orm.%s_entity_manager', $objectManagerName)), $phpArrayFile])
                ->addTag('kernel.cache_warmer', ['priority' => 1000]); // priority should be higher than ProxyCacheWarmer

            $cache = new Definition(PhpArrayAdapter::class, [$phpArrayFile, $cache]);
        }

        $container->setDefinition($cacheId, $cache);
        $container->setAlias($aliasId, $cacheId);
    }

    /**
     * Loads a property info extractor for each defined entity manager.
     */
    private function loadPropertyInfoExtractor(string $entityManagerName, ContainerBuilder $container): void
    {
        $propertyExtractorDefinition = $container->register(sprintf('doctrine.orm.%s_entity_manager.property_info_extractor', $entityManagerName), DoctrineExtractor::class);
        $argumentId                  = sprintf('doctrine.orm.%s_entity_manager', $entityManagerName);

        $propertyExtractorDefinition->addArgument(new Reference($argumentId));

        $propertyExtractorDefinition->addTag('property_info.list_extractor', ['priority' => -1001]);
        $propertyExtractorDefinition->addTag('property_info.type_extractor', ['priority' => -999]);
        $propertyExtractorDefinition->addTag('property_info.access_extractor', ['priority' => -999]);
    }

    /**
     * Loads a validator loader for each defined entity manager.
     */
    private function loadValidatorLoader(string $entityManagerName, ContainerBuilder $container): void
    {
        $validatorLoaderDefinition = $container->register(sprintf('doctrine.orm.%s_entity_manager.validator_loader', $entityManagerName), DoctrineLoader::class);
        $validatorLoaderDefinition->addArgument(new Reference(sprintf('doctrine.orm.%s_entity_manager', $entityManagerName)));

        $validatorLoaderDefinition->addTag('validator.auto_mapper', ['priority' => -100]);
    }

    /**
     * @param array<string, mixed> $objectManager
     * @param string               $cacheName
     *
     * @psalm-suppress MoreSpecificImplementedParamType
     */
    public function loadObjectManagerCacheDriver(array $objectManager, ContainerBuilder $container, $cacheName)
    {
        $this->loadCacheDriver($cacheName, $objectManager['name'], $objectManager[$cacheName . '_driver'], $container);
    }

    public function getXsdValidationBasePath(): string
    {
        return __DIR__ . '/../Resources/config/schema';
    }

    public function getNamespace(): string
    {
        return 'http://symfony.com/schema/dic/doctrine';
    }

    /**
     * {@inheritDoc}
     */
    public function getConfiguration(array $config, ContainerBuilder $container): Configuration
    {
        return new Configuration((bool) $container->getParameter('kernel.debug'));
    }

    protected function getMetadataDriverClass(string $driverType): string
    {
        return '%' . $this->getObjectManagerElementName('metadata.' . $driverType . '.class') . '%';
    }

    private function loadMessengerServices(ContainerBuilder $container): void
    {
        // If the Messenger component is installed and the doctrine transaction middleware is available, wire it:
        /** @psalm-suppress UndefinedClass Optional dependency */
        if (! interface_exists(MessageBusInterface::class) || ! class_exists(DoctrineTransactionMiddleware::class)) {
            return;
        }

        $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('messenger.xml');

        if (! class_exists(DoctrineClearEntityManagerWorkerSubscriber::class)) {
            $container->removeDefinition('doctrine.orm.messenger.event_subscriber.doctrine_clear_entity_manager');
        }

        // available in Symfony 5.1 and higher
        if (! class_exists(MessengerTransportDoctrineSchemaSubscriber::class)) {
            $container->removeDefinition('doctrine.orm.messenger.doctrine_schema_subscriber');
        }

        $transportFactoryDefinition = $container->getDefinition('messenger.transport.doctrine.factory');
        if (! class_exists(DoctrineTransportFactory::class)) {
            // If symfony/messenger < 5.1
            if (! class_exists(\Symfony\Component\Messenger\Transport\Doctrine\DoctrineTransportFactory::class)) {
                // Dont add the tag
                return;
            }

            $transportFactoryDefinition->setClass(\Symfony\Component\Messenger\Transport\Doctrine\DoctrineTransportFactory::class);
        }

        $transportFactoryDefinition->addTag('messenger.transport_factory');
    }

    private function createArrayAdapterCachePool(ContainerBuilder $container, string $objectManagerName, string $cacheName): string
    {
        $id = sprintf('cache.doctrine.orm.%s.%s', $objectManagerName, str_replace('_cache', '', $cacheName));

        $poolDefinition = $container->register($id, ArrayAdapter::class);
        $poolDefinition->addTag('cache.pool');
        $container->setDefinition($id, $poolDefinition);

        return $id;
    }

    /**
     * @param string[] $connWithLogging
     * @param string[] $connWithProfiling
     * @param string[] $connWithBacktrace
     */
    private function useMiddlewaresIfAvailable(
        ContainerBuilder $container,
        array $connWithLogging,
        array $connWithProfiling,
        array $connWithBacktrace
    ): void {
        /** @psalm-suppress UndefinedClass */
        if (! interface_exists(MiddlewareInterface::class)) {
            return;
        }

        $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('middlewares.xml');

        $container
            ->getDefinition('doctrine.dbal.logger')
            ->replaceArgument(0, null);

        $loggingMiddlewareAbstractDef = $container->getDefinition('doctrine.dbal.logging_middleware');
        foreach ($connWithLogging as $connName) {
            $loggingMiddlewareAbstractDef->addTag('doctrine.middleware', ['connection' => $connName]);
        }

        if ($this->isSfDebugMiddlewareAvailable()) {
            $container->getDefinition('doctrine.debug_data_holder')->replaceArgument(0, $connWithBacktrace);
            $debugMiddlewareAbstractDef = $container->getDefinition('doctrine.dbal.debug_middleware');
            foreach ($connWithProfiling as $connName) {
                $debugMiddlewareAbstractDef
                    ->addTag('doctrine.middleware', ['connection' => $connName]);
            }
        } else {
            $container->removeDefinition('doctrine.dbal.debug_middleware');
            $container->removeDefinition('doctrine.debug_data_holder');
        }
    }

    private function isSfDebugMiddlewareAvailable(): bool
    {
        /** @psalm-suppress UndefinedClass */
        return interface_exists(MiddlewareInterface::class) && class_exists(SfDebugMiddleware::class);
    }
}


text:
namespace base {

#if defined(PA_THREAD_CACHE_SUPPORTED)

namespace {

void DisableThreadCacheForRootIfEnabled(ThreadSafePartitionRoot* root) {
  // Some platforms don't have a thread cache, or it could already have been
  // disabled.
  if (!root || !root->with_thread_cache)
    return;

  internal::ThreadCacheRegistry::Instance().PurgeAll();
  root->with_thread_cache = false;
  // Doesn't destroy the thread cache object(s). For background threads, they
  // will be collected (and free cached memory) at thread destruction
  // time. For the main thread, we leak it.
}

void EnablePartitionAllocThreadCacheForRootIfDisabled(
    ThreadSafePartitionRoot* root) {
  if (!root)
    return;
  root->with_thread_cache = true;
}

#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
void DisablePartitionAllocThreadCacheForProcess() {
  auto* regular_allocator = internal::PartitionAllocMalloc::Allocator();
  auto* aligned_allocator = internal::PartitionAllocMalloc::AlignedAllocator();
  DisableThreadCacheForRootIfEnabled(regular_allocator);
  if (aligned_allocator != regular_allocator)
    DisableThreadCacheForRootIfEnabled(aligned_allocator);
  DisableThreadCacheForRootIfEnabled(
      internal::PartitionAllocMalloc::OriginalAllocator());
}
#endif  // defined(USE_PARTITION_ALLOC_AS_MALLOC)

}  // namespace

#endif  // defined(PA_THREAD_CACHE_SUPPORTED)

void SwapOutProcessThreadCacheForTesting(ThreadSafePartitionRoot* root) {
#if defined(PA_THREAD_CACHE_SUPPORTED)

#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
  DisablePartitionAllocThreadCacheForProcess();
#else
  PA_CHECK(!internal::ThreadCache::IsValid(internal::ThreadCache::Get()));
#endif  // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)

  internal::ThreadCache::SwapForTesting(root);
  EnablePartitionAllocThreadCacheForRootIfDisabled(root);

#endif  // defined(PA_THREAD_CACHE_SUPPORTED)
}

void SwapInProcessThreadCacheForTesting(ThreadSafePartitionRoot* root) {
#if defined(PA_THREAD_CACHE_SUPPORTED)

  // First, disable the test thread cache we have.
  DisableThreadCacheForRootIfEnabled(root);

#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
  auto* regular_allocator = internal::PartitionAllocMalloc::Allocator();
  EnablePartitionAllocThreadCacheForRootIfDisabled(regular_allocator);

  internal::ThreadCache::SwapForTesting(regular_allocator);
#else
  internal::ThreadCache::SwapForTesting(nullptr);
#endif  // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)

#endif  // defined(PA_THREAD_CACHE_SUPPORTED)
}

}  // namespace base

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>naručili smo 4 sira. obilna porcija, bogato nadjeveno, stiglo je skoro 10 min prije procijenjenog vremena.naručujem opet.</Text>
  <Rating>6</Rating>
  <Source>http://pauza.hr/menu/pizzeria6</Source>
</CrawlItem>


text:
class HowlUserSerializer < ActiveModel::Serializer
  attributes :human_name, :doggo_name, :bio
end


text:
Uses the Fitbit API in order to send you a morning email about how you slept the night before

Fitbit's Sleep Efficiency score is presented along with sleep start time, duration, and restlessness information

### installation

Using Go 1.11+, clone this repo and run `go build`


text:
<?php

namespace Caronna\Model;

/**
 * data type longtext
 *
 *
 * @author GOX
 *
 */
class DataTypeLongtext extends DataType
{

	public function __construct($i_minLength){
		$this->_SQLName = 'longtext';
		$this->_length = 0;
		$this->_lengthRequired = false;
		if($i_minLength>0)	$this->_validators[] = new ValidatorMinLength($i_minLength);
		$this->_validators[] = new ValidatorLongtext();
		$this->_codeCreateDataType = "new \\".__CLASS__."($i_minLength)";
	}

	public function getPHPDatatype(){
		return 'string';
	}

}

?>


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="remunerate">
        <note>
            Frames file for 'remunerate' based on survey of sentences in the WSJ
            corpus.
        </note>

        <roleset id="remunerate.01" name="to make a payment, compensate" vncls="-">
            <roles>
                <role descr="payer, agent" n="0"/>
                <role descr="entity remunerated" n="1"/>
                <role descr="compensation" n="2"/>
            </roles>

            <example name="passive">
                <inflection aspect="ns" form="infinitive" person="ns" tense="ns" voice="passive"/>
                <text>
                    The longstanding position of the Recording Industry Association of America , a trade group based [*] in Washington , D.C. , is that [record companies , performers , songwriters and music publishers]-2 need [*-2]-1 to be remunerated [*-1] by government-imposed fees on the sale of blank tapes and recording equipment [*] to make up for royalties lost [*] to home taping .
                </text>
                <rel>remunerated</rel>
                <arg n="1">[*-1]</arg>
                <arg n="2">by government-imposed fees on the sale of blank tapes and recording equipment</arg>
            </example>

        </roleset>
    </predicate>

    <note>
        frames created by Olga
    </note>

</frameset>


text:
import csv
import sys
import re

old_fn = sys.argv[1]
new_fn = sys.argv[2]

class DicLine:
    def __init__(self, en, hu, la, pl, key, status="u", pos="N", definition="TODO", comment="%"):
        self.en = en
        self.hu = hu
        self.la = la
        self.pl = pl
        self.key = key
        self.status = status if status else "u"
        self.pos = pos if pos else "N"
        self.definition = definition if definition else "TODO"
        if comment == "" or not re.match(r'%', comment):
            self.comment = "%" + comment
        else:
            self.comment = comment

    def __str__(self):
        return '\t'.join([self.en, self.hu, self.la, self.pl, self.key, self.status, self.pos, self.definition, self.comment])

old_lines = {}
with open(old_fn) as old_file:
    csv_reader = csv.reader(old_file, delimiter='\t')
    for row in csv_reader:
        curline = DicLine(*row[:9])
        if curline.key in old_lines:
            raise ValueError(f'{curline.key} is already in use!')
        old_lines[curline.key] = curline

def syntax_error(entry):
    return (
        not re.match(r'^(\w|[#-_])*$', entry.en) or
        not re.match(r'^(\w|[#-_])*$', entry.pl) or
        not re.match(r'^(\w|[#-_])*$', entry.la) or
        not re.match(r'^(\w|[#-_])*$', entry.hu) or
        not entry.key.isnumeric() or
        not entry.status in {"u", "c", "p", "e"} or
        not entry.pos in {"N", "A", "G", "U", "V", "D"} or
        entry.definition == "" or
        not re.match(r'%', entry.comment)
    )

for line_num, line in old_lines.items():
    if syntax_error(line):
        print(str(line))  # python magic method __XX__

with open(new_fn, 'w') as outfile:
    for entry_id in old_lines:
        print(str(old_lines[entry_id]), file=outfile)


text:
import bisect
import collections
import random

from .statemachine import StateMachine
from .transitiongraph import TransitionGraph, TransitionGraphDrivenMixin

class MarkovChainTransitionGraph(TransitionGraph):

    def __init__(self, transitions=()):
        self.arcs = collections.defaultdict(list)
        self.total_weight = collections.defaultdict(float)
        self.update(transitions)

    def add(self, transition):
        history, weight, target = transition
        if not isinstance(history, tuple):
            raise TypeError("history must be a tuple of states")
        if weight <= 0:
            raise ValueError("transition weight must be positive")
        total_weight = self.total_weight[history] + weight
        self.arcs[history].append((total_weight, target))
        self.total_weight[history] = total_weight

    def target(self, history, rng):
        if not isinstance(history, tuple):
            raise TypeError("history must be a tuple of states")
        arcs = self.arcs[history]
        x = rng.random() * self.total_weight[history]
        i = bisect.bisect_left(arcs, (x, None))
        _, target = arcs[i]
        return target

class MarkovChain(TransitionGraphDrivenMixin, StateMachine):
    """In a Markov chain, the target state of a transition depends not on an input symbol,
    but on a weight assigned to each outgoing arc. The target state is randomly selected with
    each target state having a probability proportional to its weight.

    This class supports Markov chains with arbitrary finite memory. Memory size is automatically
    computed as the longest number of prior states in the transition graph.
    """

    # Provide access to the transition graph class that should be used when constructing the
    # class or instance's transition graph.
    TransitionGraph = MarkovChainTransitionGraph

    # Default pseudo-random number generator used when triggering transitions. Can be overridden
    # at instance level. By default it uses the random module.
    rng = random

    def __init__(self, initial_state=None, transition_graph=None, rng=None):
        TransitionGraphDrivenMixin.__init__(self, transition_graph)
        StateMachine.__init__(self, initial_state)
        memory = max(len(h) for h in self.transition_graph.arcs.keys())
        self._history = collections.deque(maxlen=memory)
        if rng is not None:
            self.rng = rng
        if self.initial_state is None:
            self.initial_state = self.transition_graph.target(history=(), rng=self.rng)

    def step(self, n=1):
        """Advance the Markov chain `n` steps.

        Call this method on Markov chains instead of using `input()`. Markov chains any ignore
        input symbols, and instead base their transitions on recent state(s) and the RNG.

        Note:
            This method automatically calls the `.start()` method on the Markov chain object if
            necessary. In such cases, the number of steps `n` is reduced by 1.
        """
        if not self.started:
            self.start()
            n -= 1
        for _ in range(n):
            self.input(None)

    def _enter(self, state, args, kwargs):
        self._history.append(state)
        return super()._enter(state, args, kwargs)

    def target(self, source, symbol):
        """The transition target is obtained from the transition graph, and does not depend on
        any input symbol. Instead, the transition graph uses the chain's recent history (which
        includes the current state) and its RNG to obtain the next state.
        """
        return self.transition_graph.target(history=tuple(self._history), rng=self.rng)


text:
using System;
using System.Threading.Tasks;
using NBitcoin;

namespace Stratis.Bitcoin.Interfaces
{
    ///
    /// Represent access to the store of <see cref="Block"/>.
    ///
    public interface IBlockStore : IDisposable
    {
        ///
        /// Initializes the blockchain storage and ensure the genesis block has been created in the database.
        ///
        void Initialize();

        /// Retrieve the transaction information asynchronously using transaction id.
        /// <param name="trxid">The transaction id to find.</param>
        Transaction GetTransactionById(uint256 trxid);

        /// Retrieve transactions information asynchronously using transaction ids.
        /// <param name="trxids">Ids of transactions to find.</param>
        /// <returns>List of transactions or <c>null</c> if txindexing is disabled.</returns>
        Transaction[] GetTransactionsByIds(uint256[] trxids);

        ///
        /// Get the corresponding block hash by using transaction hash.
        ///
        /// <param name="trxid">The transaction hash.</param>
        uint256 GetBlockIdByTransactionId(uint256 trxid);

        ///
        /// Get the block from the database by using block hash.
        ///
        /// <param name="blockHash">The block hash.</param>
        Block GetBlock(uint256 blockHash);
    }
}


text:
<?php
declare(strict_types=1);
/**
 * © 2015 Procurios - License MIT
 */
namespace Procurios\Json\JsonRpc\exception;

class MissingParameter extends JsonRpcError
{
}


text:
import type { ReactElement } from "react";

import { Provider, useStylesState } from "./context";
import StyledTable from "./StyledTable";
import TableConfiguration from "./TableConfiguration";

export default function DefaultStylesConfigurable(): ReactElement {
  const value = useStylesState();

  return (
    <Provider value={value}>
      <TableConfiguration />
      <StyledTable />
    </Provider>
  );
}


text:
<TITLE>Review for Life as a House (2001)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Life as a House (2001)

reviewed by
Norm Schrager

LIFE AS A HOUSE
A film review by Norm Schrager
Copyright 2001 filmcritic.com

The good news for George, a middle-aged, washed up architect, is that an
enormous life change has motivated him to connect with his horrible
teenage son and build a house by the ocean.  The bad news is that the
change is terminal cancer.  The good news for moviegoers is that Irwin
Winkler's Life As A House is filled with sharp, solid acting, a decent,
sometimes harsh, script, and a few surprises.  The bad news is that
anything worth seeing here lives within an uneven sap of a film, unable
to break free from the traditional Hollywood devices.

But much of Life As A House is completely watchable.  Mark Andrus's
script (he's written As Good As It Gets and the underrated, rarely seen
Late For Dinner) appears cookie-cutter: he gives us the lazy, lonely,
eccentric nobody (Kevin Kline); his estranged family, including
beautiful ex-wife (Kristin Scott Thomas) and alienated teen (Hayden
Christensen); and his predictably uptight neighbors, pissed off that his
ramshackle of a house has stood in their beautiful oceanside
neighborhood for twenty years.

But Andrus gives the telling a hard edge from the get-go, which keeps
Life As A House interesting in the first act.  Kline, who we're used to
seeing as generally kind-hearted, blurts to neighbor Mary Steenburgen,
"How far did you just have to stick your head out the window in order to
see my dick?!" after he uses God's ocean as his own personal
receptacle.  In the same introduction, George's son Sam (Christensen,
soon appearing as a little-known character called Anakin Skywalker),
wearing heavy eye makeup, sniffs glue, applies a noose, and attempts to
pleasure himself.  This is stuff I'd expect from David O. Russell (Three
Kings), not Irwin Winkler (The Net).

Life As A House goes south, however, as soon as young Sam, softens for
his Dad. When George, upon getting the news of his impending demise,
decides to replace the old shack, he forces Sam to spend the summer with
him.  The fact that he's erecting a house at the same time he wants to
build a relationship with his son, and reconstruct his emotional
architecture as well, is painfully blatant.  At the very least, however,
Andrus's script is smart enough to make mention of the parallel: Sam, in
being asked to help knock down the house says to George, "You're just
trying to tear down your father."  George's reply: "You should try it."
[See also the title of the film... -Ed.]

Andrus's reputation for good dialogue, and there is some above-average
stuff here, must have convinced some name actors to take wasted, bit
parts.  Steenburgen, Scott Bakula, Jamey Sheridan, and Sam Robards
could've probably taken meatier, more meaningful roles elsewhere (even
if Steenburgen does get to show off her finely-aged body).

And as competently good as Kline's and Christensen's performances are,
(and I believe Christensen is a real find), they're overrun by
poorly-timed, heart-tugging music, and choppy direction (will somebody
please stop the overuse of slow-motion!?).  Winkler alternates between
the standard camera setup you've seen before, and a feigned attempt at
Altmanesque, herky-jerky "verité."  It's messy.

There are a few sequences -- one in particular has a variety of
characters jumping into each other's beds -- that definitely raise
eyebrows and keep the proceedings interesting.  But for every leap into
exciting waves of edgier content, there are too many jumps into the
giant movie ocean of mediocrity.

Reviewed as part of our Boston Film Festival coverage (feature story
coming soon).

RATING:  ***

|------------------------------|
 \ ***** Perfection             \
  \ **** Good, memorable film    \
   \ *** Average, hits and misses \
    \ ** Sub-par on many levels    \
     \ * Unquestionably awful       \
      |------------------------------|

MPAA Rating: R

Director: Irwin Winkler
Producer: Rob Cowan, Irwin Winkler
Writer: Mark Andrus
Starring: Kevin Kline, Kristin Scott Thomas, Hayden Christensen, Mary
Steenburgen, Jamey Sheridan, Jena Malone, Sam Robards, Scott Bakula

---
http://www.amazon.com/exec/obidos/redirect?tag=filmcriticcom&path=subst/video/sellers/amazon-top-100-dvd.html
Movie Fiends: Check out Amazon.com's Top 100 Hot DVDs!

Visit filmcritic.com on the Web at http://www.filmcritic.com

==========
X-RAMR-ID: 29431
X-Language: en
X-RT-ReviewID: 247959
X-RT-TitleID: 1110296
X-RT-SourceID: 178
X-RT-AuthorID: 943
X-RT-RatingText: 3/5

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Yenny Dieguez</title>

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

    <link href="lib/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

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

            <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
            </button>
            Bienvenido!

Hey there!

I'm Yenny. Welcome

                Tell Me More

Portfolio

Here are some examples of things I've designed.

David

Drawing

El Pez Chino

Ink Drawing

The House on the Left

Sketch

About Me.

Just a girl trying to make it!

I'm a 20' at Dartmouth and prospective Government major and Public Policy Minor. I'm interested in law, but also enjoy designing and engaging in other creative endeavors. During my free time, I like to cook, draw, and dance.

I was born in Havana and raised in Miami, FL, where I currently live.

I'm very excited to join the DALI family and work on some great projects this coming term! If you see me in the lab stop by, let's chat!

Team

No

Sleep

                    Copyright &copy YDesign 2017

David

A study of David's head.

January 2016

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

El Pez Chino

Drawing with a Japanese ink pen.

September 2013

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

The House on the Left

Improvisation.

June 2015

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>


text:
//===== Copyright © 2011, DJ Fire-Black production, All rights reserved. ======//
//
// Purpose:
//
// $NoKeywords: $
//
//===========================================================================//

//#include "player.h"
#include <functional>
#include <cstring>
#include <stdio.h>
#include <ctype.h>
#include <vector>
#include <algorithm>
#include <string>
#include <list>
#include <map>
#include "MRecipientFilter.h"
#include "bitbuf.h"
#include "interface.h"
#include "engine/iserverplugin.h"
#include "eiface.h"
#include "igameevents.h"
#include "convar.h"
#include "engine/IEngineTrace.h"
#include "tier2/tier2.h"
#ifndef NCZ_EP1
#include "game/server/iplayerinfo.h"
#else
#include "dlls/iplayerinfo.h"
#endif
#ifndef NCZ_CSGO
#include "util.h"
#endif
#include "AutoStatus.h"
#include "MostUsedPointers.h"
#ifdef WIN32
#include <tchar.h>
#else
#ifndef _LINUX
#define _LINUX
#endif
#include <wchar.h>
#define TCHAR wchar_t
#endif
#include <sstream>
//#include "server_class.h"
#include "edict.h"
#include "threadtools.h"
#include "inetchannelinfo.h"
#ifndef NCZ_EP1
#include "mathlib/vector.h"
#else
#include "vector.h"
#endif
//#include "C:\nocheatz3\hl2sdk-ob-valve-77da091662a6\utils\serverplugin_sample\dns.h"

typedef std::basic_string<TCHAR, std::char_traits<TCHAR>, std::allocator<TCHAR> > tstring;
typedef std::basic_ostringstream<TCHAR, std::char_traits<TCHAR>, std::allocator<TCHAR> > tostringstream;

template<typename T>
std::string tostring(const T & toConvert);
std::string to_lowercase(const std::string& s);

template<class T>
T *FindIFace(const char *IFaceName, CreateInterfaceFn Factory); // factory

edict_t* getSourceTV();

bool isValidEdict(edict_t * entity);

void noTell(edict_t *pEdict, const char *msg); // Send message to all players but not to him (pEdict)

void noTell(edict_t *pEntity, const std::string& msg);

void ForceFile(const char *file);

void contell(edict_t *pEntity,const char * message);

void allTell(const char *message);

std::string formatSeconds(int sec);

bool CreateAThreadAndCallTheFunction();

std::string dumpConfig();

void setCVar(const char * cvarname, int value);

void setCVar(const char * cvarname, float value);

void setCVar(const char * cvarname, const char * value);

void tell(edict_t *pEntity,const char * message);

void tell(edict_t *pEntity, const std::string& message);

int getIndexFromUserID(int userid);

int IndexOfEdict(const edict_t *pEdict);

edict_t *PEntityOfEntIndex(int iEntIndex);

void messagetous(int joueursmax,const char * message);

void message(int index_joueur,const char * message);

//int GetOffset(std::string path);

bool between(const int n, const int min, const int max);

bool between(const float n, const float min, const float max);

bool ReallyUnknownCommand(const char *ccmd);

//void register_va_offset();

std::string NumString_Add(std::string num, std::string add);

void strSplit(std::string str, std::string separator, std::vector<string>* results);

std::string getCommunityID(const char *SteamID);

std::string getStrRates(int index);

void writeToLogfile(std::string text);

int getClosestTeleportEntDistanceFrom(float x, float y, float z);

float GetTime();

std::string getStrGameDir();

bool estImpaire(int num);

void AddTag(char* MyTag);

bool checkForUpdate_thread();

void RemoveTag(char* MyTag);

bool checkForUpdate();

bool isHackOrCheatCommand_Kick(const std::string& commandline);

bool isHackOrCheatCommand_Ban(const std::string& commandline);

std::string quoteQuotes(std::string str);

void SetTranslate(std::string key, std::string sentence);

std::string GetTranslate(const std::string& key);

std::string minStrf(std::string text, unsigned int minSize);

void needUseWeb();

bool estImpaire(int num);

void charencode (unsigned char ch, char dest[4]);

void strSplit(std::string str, std::string separator, std::vector<std::string>* results);

std::string urlencode (const std::string &str);

std::string getStrDateTime(const char *format);

char * nghost(char *host_name);

int WebThread();

void* WebThread_l(void* args);

/*
template<class T>
T & GetPVA(edict_t *pPlayer, bool angle_id);
template<class T>
T & GetGround(edict_t *pPlayer);*/

bool	CreateAThreadAndCallTheFunction();

float positiv(const float n); // Convert unknown float to only positive float
int positiv(const int n);

/*template<class T>
T & GetPVA(CBaseEntity *pBase);*/

std::string format(const char *fmt, ...); // format the specified text
const tchar * format(std::string fmt, ...);

#ifndef NCZ_EP1
#ifndef DEF_HOOKCLASS
#define DEF_HOOKCLASS
/* Prototype de la fonction à appeler lorsque la commande est utilisée
* La fonction pourra retourner true pour interdire l'exécution de la commande hookée
*/
typedef bool (* HookCallback)(int playerIndex, const CCommand & args);

/** Dérivée de ConCommand afin de surcharger ConCommand::Dispatch */
class ConCommandHook : public ConCommand
{
protected:
	/** Pointeur sur la commande hookée */
	ConCommand * hooked;

	/** Fonction à appeler lorsque la commande est utilisée */
	HookCallback callback;
public:
	ConCommandHook(const char * name, HookCallback hookCallback, int flags = FCVAR_NONE);

	// Fonctions héritées de ConCommand
	void Init();
	void Dispatch(const CCommand & args);
};

#endif
#endif

// ##########################################
// Cg_NCZ_PlayerManager
// ##########################################

#ifndef DEF_CGNCZPMANAGERCLASS
#define DEF_CGNCZPMANAGERCLASS
class Cg_NCZ_PlayerManager
{
public:
	// Inits

	Cg_NCZ_PlayerManager();
	~Cg_NCZ_PlayerManager();
	// Methods

	int getPlayerCount();
	int getMaxClients();
	Cg_NCZ_Player* getPlayer(int index);
	Cg_NCZ_Player* getPlayer(edict_t *pPlayer);
	Cg_NCZ_Player* getPlayer(void * myvoid); // CBaseEntity, CCSPlayer ...

	// Functions

	void resetAll();
	void lockAll();
	//void checkAllCvars();
	void checkAllEyeAngles();
	//void checkAllSpeedhacks();
	void checkAllBanRequest();
	void checkAllAimDirChange();
	void checkAllFire();
	void checkAllBunny();
	void updateAll();
	void disconnectPlayer(edict_t *pPlayer);
	void disconnectPlayer(int index);
	void resetAllUkCmd();
	void checkAllUkCmd();
	void fullcheckBanlists();
	void handleAllConvarTest();

	//void updateCheckList();

	std::vector<Cg_NCZ_Player*> g_ncz_playerList;
};

#endif

// ##########################################
// Cg_NCZ_RealPlayers
// ##########################################

/*#ifndef DEF_CGNCZREALP
#define DEF_CGNCZREALP
class Cg_NCZ_RealPlayers
{
public:
	// Inits

	Cg_NCZ_RealPlayers();
	~Cg_NCZ_RealPlayers();

	// Functions

	void addIndex(int index);
	void removeIndex(int index);

	// Methods

	bool isInList(int index);

private:
	std::vector<int> rpList;
};

#endif*/
#ifndef NCZPLUGIN
#define NCZPLUGIN

struct StrCompare : public std::binary_function<const char*, const char*, bool> {
public:
    bool operator() (const char* str1, const char* str2) const
    { return std::strcmp(str1, str2) < 0; }
};

typedef std::map<const char*, const char*, StrCompare> ConvarList;

//---------------------------------------------------------------------------------
// Purpose: a sample 3rd party plugin class
//---------------------------------------------------------------------------------
class NoCheatZ: public IServerPluginCallbacks, public IGameEventListener2, public AutoStatus
{
public:
	NoCheatZ();
	~NoCheatZ();

	// IServerPluginCallbacks methods
	virtual bool			Load(	CreateInterfaceFn interfaceFactory, CreateInterfaceFn gameServerFactory );
	virtual void			Unload( void );
	virtual void			Pause( void );
	virtual void			UnPause( void );
	virtual const char     *GetPluginDescription( void );
	virtual void			LevelInit( char const *pMapName );
	virtual void			ServerActivate( edict_t *pEdictList, int edictCount, int clientMax );
	virtual void			GameFrame( bool simulating );
	virtual void			LevelShutdown( void );
	virtual void			ClientActive( edict_t *pEntity );
#ifdef NCZ_CSGO
	virtual void            ClientFullyConnect(edict_t *) {};
#endif
	virtual void			ClientDisconnect( edict_t *pEntity );
	virtual void			ClientPutInServer( edict_t *pEntity, char const *playername );
	virtual void			SetCommandClient( int index );
	virtual void			ClientSettingsChanged( edict_t *pEdict );
	virtual PLUGIN_RESULT	ClientConnect( bool *bAllowConnect, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen );
#ifndef NCZ_EP1
	virtual PLUGIN_RESULT	ClientCommand( edict_t *pEntity, const CCommand &args );
#else
	virtual PLUGIN_RESULT	ClientCommand( edict_t *pEntity );
#endif
	virtual PLUGIN_RESULT	NetworkIDValidated( const char *pszUserName, const char *pszNetworkID );
	virtual void			OnQueryCvarValueFinished( QueryCvarCookie_t iCookie, edict_t *pPlayerEntity, EQueryCvarValueStatus eStatus, const char *pCvarName, const char *pCvarValue );

	// added with version 3 of the interface.
	virtual void			OnEdictAllocated( edict_t *edict );
	virtual void			OnEdictFreed( const edict_t *edict  );
	//virtual void allstatus();
	//virtual void ForceUnload();

	// IGameEventListener Interface
	virtual void FireGameEvent( IGameEvent * event );
#ifdef NCZ_CSGO
	virtual int	 GetEventDebugID( void ) { return 42; };
#endif

	virtual int GetCommandIndex()
	{
		return m_iClientCommandIndex;
	}
	virtual Cg_NCZ_PlayerManager * get_m_pm();
	//Cg_NCZ_RealPlayers rpl;
private:
	int m_iClientCommandIndex;
	Cg_NCZ_PlayerManager *m_pm;
	ConvarList::iterator cit;
	int ccl;
	//float last_auto_status;
};

#endif

// ##########################################
// Cg_NCZ_Queue
// ##########################################

#ifndef DEF_Cg_NCZ_Queue
#define DEF_Cg_NCZ_Queue
class Cg_NCZ_Queue
{
public:
	Cg_NCZ_Queue();
	~Cg_NCZ_Queue();

	// Methods

	std::string get(); // Get the first element and delete the element after, so you have to register it.
	bool empty();
	void erase();
	// Functions

	void update();
	void send(std::string text);

private:
	// Methods

	bool isLocked();

	// Functions

	void lock();
	void unlock();

	// Vars

	std::vector<std::string> queue;
	std::vector<std::string> temp_queue;
	bool locked;
};
#endif

/*#ifdef WIN32
#ifndef ClassCNCZWebThread
#define ClassCNCZWebThread
class CNCZWebThread: public CWorkerThread
{
public:
	CNCZWebThread()
	{
		SetName( "NCZWebThread" );
	}

	~CNCZWebThread()
	{
	}

	enum
	{
		CALL_FUNC,
		EXIT,
	};

	bool	CallThreadFunction()
	{
		CallWorker( CALL_FUNC );
		return true;
	}

	int Run()
	{
		unsigned nCall;
		while ( WaitForCall( &nCall ) )
		{
			if ( nCall == EXIT )
			{
				Reply( 1 );
				break;
			}

			Reply( 1 );
			WebThread();

		}
		return 0;
	}

private:
};

static CNCZWebThread g_CNCZWebThread;
#endif
#endif*/
/*
// ##########################################
// Cg_NCZ_Lang
// ##########################################

typedef struct ncz_lang ncz_lang;
struct ncz_lang
{
	std::string textIndex;
	std::string dg;
};

#ifndef DEF_Cg_NCZ_Lang
#define DEF_Cg_NCZ_Lang
class Cg_NCZ_Lang
{
public:
	Cg_NCZ_Lang();
	~Cg_NCZ_Lang();

	// Methods

	std::string get(std::string textIndex); // Get the first element and delete the element after, so you have to register it.
	bool empty();

	// Functions

	void init(std::string PathToLangFile);
	void setLang(std::string Lang);

private:

};
#endif*/
/*
class CNczBasePlayer : public CBasePlayer
{
	CNczBasePlayer();
	virtual ~CNczBasePlayer();

	virtual int ShouldTransmit( const CCheckTransmitInfo *pInfo );
};*/


text:
Object.prototype.random = function() {
  return this.toRandomArray()[0];
};

Object.prototype.toRandomArray = function() {
  function object_values(object, values) {
    Object.keys(object).forEach(function (key) {
      typeof object[key] === 'object'
        ? object_values(object[key], values)
        : values.push(object[key]);
    });
    return values;
  }

  return object_values(this, []).sort(function() {
    return 0.5 - Math.random();
  });
};


text:
class Taskflow::Record
    include ::Mongoid::Document
    embedded_in :logger,:class_name=>'Taskflow::Logger',:inverse_of=>:records

    field :step_id, type: Integer
    field :writer, type: String
    field :written_at, type: Time, default: ->{ Time.now }
    field :level, type: String, default:  'INFO'
    field :content, type: String
    field :tags, type: Hash, default: {}
end


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="author" content="Tom Copeland" />
    <meta name="Date-Revision-yyyymmdd" content="20141203" />
    <meta http-equiv="Content-Language" content="en" />
    <title>PMD Java – Ruleset: Empty Code</title>
    <link rel="stylesheet" href="../../css/apache-maven-fluido-1.3.0.min.css" />
    <link rel="stylesheet" href="../../css/site.css" />
    <link rel="stylesheet" href="../../css/print.css" media="print" />

        Parent Project

      PMD

        Rule Sets

                                      java

      Android

      Basic

      Braces

      Clone Implementation

      Code Size

      Comments

      Controversial

      Coupling

      Design

      Empty Code

      Finalizer

      Import Statements

      J2EE

      JavaBeans

      JUnit

      Jakarta Commons Logging

      Java Logging

      Migration

      Naming

      Optimization

      Strict Exceptions

      String and StringBuffer

      Security Code Guidelines

      Type Resolution

      Unnecessary

      Unused Code

        Project Documentation

                                      Project Information

      Project Summary

      Dependencies

      Project Team

      Mailing Lists

      Continuous Integration

      Issue Tracking

      Project License

      Source Repository

                                      Project Reports

      Test Source Xref

      Source Xref

      JavaDocs

      Test JavaDocs

      CPD

      PMD

      Checkstyle

      Surefire Report

      Dependency Updates Report

      Plugin Updates Report

      Property Updates Report

                External Links

      SourceForge.net Project Page

      Hosted by SourceForge

Last Published: 2014-12-03

|

Version: 5.2.2

|

        SourceForge

/

        PMD

/

        PMD Java

/

Ruleset: Empty Code

Parent Project

        PMD

Rule Sets

        java

        Android

        Basic

        Braces

        Clone Implementation

        Code Size

        Comments

        Controversial

        Coupling

        Design

            Empty Code

        Finalizer

        Import Statements

        J2EE

        JavaBeans

        JUnit

        Jakarta Commons Logging

        Java Logging

        Migration

        Naming

        Optimization

        Strict Exceptions

        String and StringBuffer

        Security Code Guidelines

        Type Resolution

        Unnecessary

        Unused Code

Project Documentation

        Project Information

        Project Reports

Empty Code

The Empty Code ruleset contains rules that find empty statements of any kind (empty method,
empty block statement, empty try or catch block,...).

EmptyCatchBlock

Since: PMD 0.1

Empty Catch Block finds instances where an exception is caught, but nothing is done.
In most circumstances, this swallows an exception which should either be acted on
or reported.

//CatchStatement
 [count(Block/BlockStatement) = 0 and ($allowCommentedBlocks != 'true' or Block/@containsComment = 'false')]
 [FormalParameter/Type/ReferenceType
   /ClassOrInterfaceType[@Image != 'InterruptedException' and @Image != 'CloneNotSupportedException']
 ]

Example(s):

public void doSomething() {
  try {
    FileInputStream fis = new FileInputStream("/tmp/bugger");
  } catch (IOException ioe) {
      // not good
  }
}

This rule has the following properties:

Name

Default Value

Description

allowCommentedBlocks

false

Empty blocks containing comments will be skipped

EmptyIfStmt

Since: PMD 0.1

Empty If Statement finds instances where a condition is checked but nothing is done about it.

//IfStatement/Statement
 [EmptyStatement or Block[count(*) = 0]]

Example(s):

public class Foo {
 void bar(int x) {
  if (x == 0) {
   // empty!
  }
 }
}

EmptyWhileStmt

Since: PMD 0.2

Empty While Statement finds all instances where a while statement does nothing.
If it is a timing loop, then you should use Thread.sleep() for it; if it is
a while loop that does a lot in the exit expression, rewrite it to make it clearer.

//WhileStatement/Statement[./Block[count(*) = 0]  or ./EmptyStatement]

Example(s):

void bar(int a, int b) {
	while (a == b) {
	// empty!
	}
}

EmptyTryBlock

Since: PMD 0.4

Avoid empty try blocks - what's the point?

//TryStatement/Block[1][count(*) = 0]

Example(s):

public class Foo {
 public void bar() {
  try {
  } catch (Exception e) {
    e.printStackTrace();
  }
 }
}

EmptyFinallyBlock

Since: PMD 0.4

Empty finally blocks serve no purpose and should be removed.

//FinallyStatement[count(Block/BlockStatement) = 0]

Example(s):

public class Foo {
 public void bar() {
  try {
    int x=2;
   } finally {
    // empty!
   }
 }
}

EmptySwitchStatements

Since: PMD 1.0

Empty switch statements serve no purpose and should be removed.

//SwitchStatement[count(*) = 1]

Example(s):

public void bar() {
	int x = 2;
	switch (x) {
	// once there was code here
	// but it's been commented out or something
	}
}

EmptySynchronizedBlock

Since: PMD 1.3

Empty synchronized blocks serve no purpose and should be removed.

//SynchronizedStatement/Block[1][count(*) = 0]

Example(s):

public class Foo {
 public void bar() {
  synchronized (this) {
   // empty!
  }
 }
}

EmptyStatementNotInLoop

Since: PMD 1.5

An empty statement (or a semicolon by itself) that is not used as the sole body of a 'for'
or 'while' loop is probably a bug.  It could also be a double semicolon, which has no purpose
and should be removed.

//EmptyStatement
 [not(
       ../../../ForStatement
       or ../../../WhileStatement
       or ../../../BlockStatement/ClassOrInterfaceDeclaration
       or ../../../../../../ForStatement/Statement[1]
        /Block[1]/BlockStatement[1]/Statement/EmptyStatement
       or ../../../../../../WhileStatement/Statement[1]
        /Block[1]/BlockStatement[1]/Statement/EmptyStatement)
 ]

Example(s):

public void doit() {
      // this is probably not what you meant to do
      ;
      // the extra semicolon here this is not necessary
      System.out.println("look at the extra semicolon");;
}

EmptyInitializer

Since: PMD 5.0

Empty initializers serve no purpose and should be removed.

//Initializer/Block[count(*)=0]

Example(s):

public class Foo {

   static {} // Why ?

   {} // Again, why ?

}

EmptyStatementBlock

Since: PMD 5.0

Empty block statements serve no purpose and should be removed.

//BlockStatement/Statement/Block[count(*) = 0]

Example(s):

public class Foo {

   private int _bar;

   public void setBar(int bar) {
      { _bar = bar; } // Why not?
      {} // But remove this.
   }

}

EmptyStaticInitializer

Since: PMD 1.5

An empty static initializer serve no purpose and should be removed.

//Initializer[@Static='true']/Block[count(*)=0]

Example(s):

public class Foo {
	static {
	// empty
	}
}

Copyright ©                    2002-2014
                        InfoEther.
            All Rights Reserved.


text:
package org.apache.wicket.examples.authentication1;

import org.apache.wicket.Page;
import org.apache.wicket.RestartResponseAtInterceptPageException;
import org.apache.wicket.Session;
import org.apache.wicket.authorization.IAuthorizationStrategy;
import org.apache.wicket.examples.WicketExampleApplication;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.component.IRequestableComponent;

/**
 * Forms example.
 *
 * @author Jonathan Locke
 */
public final class SignInApplication extends WicketExampleApplication
{
	@Override
	public Class<? extends Page> getHomePage()
	{
		return Home.class;
	}

	@Override
	public Session newSession(Request request, Response response)
	{
		return new SignInSession(request);
	}

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

		// Register the authorization strategy
		getSecuritySettings().setAuthorizationStrategy(new IAuthorizationStrategy.AllowAllAuthorizationStrategy()
		{
			@Override
			public <T extends IRequestableComponent> boolean isInstantiationAuthorized(
				Class<T> componentClass)
			{
				// Check if the new Page requires authentication (implements the marker interface)
				if (AuthenticatedWebPage.class.isAssignableFrom(componentClass))
				{
					// Is user signed in?
					if (((SignInSession)Session.get()).isSignedIn())
					{
						// okay to proceed
						return true;
					}

					// Intercept the request, but remember the target for later.
					// Invoke Component.continueToOriginalDestination() after successful logon to
					// continue with the target remembered.

					throw new RestartResponseAtInterceptPageException(SignIn.class);
				}

				// okay to proceed
				return true;
			}
		});
	}
}


text:
export App from './App/App';
export Home from './Home/Home';
export NotFound from './NotFound/NotFound';
export ProjectsMain from './ProjectsMain/ProjectsMain';


text: This represents one wrapper for interaction with filemaker database using PHP