text:
<?php
namespace TYPO3\Flow\Object\DependencyInjection;

use TYPO3\Flow\Object\Configuration\Configuration;
use TYPO3\Flow\Object\Configuration\ConfigurationArgument;
use TYPO3\Flow\Object\Configuration\ConfigurationProperty;
use TYPO3\Flow\Utility\Arrays;
use TYPO3\Flow\Configuration\ConfigurationManager;
use Doctrine\ORM\Mapping as ORM;
use TYPO3\Flow\Annotations as Flow;

/**
 * A Proxy Class Builder which integrates Dependency Injection.
 *
 * @Flow\Scope("singleton")
 * @Flow\Proxy(false)
 */
class ProxyClassBuilder
{
    /**
     * @var \TYPO3\Flow\Reflection\ReflectionService
     */
    protected $reflectionService;

    /**
     * @var \TYPO3\Flow\Object\Proxy\Compiler
     */
    protected $compiler;

    /**
     * @var \TYPO3\Flow\Log\SystemLoggerInterface
     */
    protected $systemLogger;

    /**
     * @var \TYPO3\Flow\Configuration\ConfigurationManager
     */
    protected $configurationManager;

    /**
     * @var \TYPO3\Flow\Object\CompileTimeObjectManager
     */
    protected $objectManager;

    /**
     * @var array<\TYPO3\Flow\Object\Configuration\Configuration>
     */
    protected $objectConfigurations;

    /**
     * @var array
     */
    protected $classesWithCompileStaticAnnotation;

    /**
     * @param \TYPO3\Flow\Reflection\ReflectionService $reflectionService
     * @return void
     */
    public function injectReflectionService(\TYPO3\Flow\Reflection\ReflectionService $reflectionService)
    {
        $this->reflectionService = $reflectionService;
    }

    /**
     * @param \TYPO3\Flow\Object\Proxy\Compiler $compiler
     * @return void
     */
    public function injectCompiler(\TYPO3\Flow\Object\Proxy\Compiler $compiler)
    {
        $this->compiler = $compiler;
    }

    /**
     * @param \TYPO3\Flow\Configuration\ConfigurationManager $configurationManager
     * @return void
     */
    public function injectConfigurationManager(\TYPO3\Flow\Configuration\ConfigurationManager $configurationManager)
    {
        $this->configurationManager = $configurationManager;
    }

    /**
     * @param \TYPO3\Flow\Log\SystemLoggerInterface $systemLogger
     * @return void
     */
    public function injectSystemLogger(\TYPO3\Flow\Log\SystemLoggerInterface $systemLogger)
    {
        $this->systemLogger = $systemLogger;
    }

    /**
     * @param \TYPO3\Flow\Object\CompileTimeObjectManager $objectManager
     * @return void
     */
    public function injectObjectManager(\TYPO3\Flow\Object\CompileTimeObjectManager $objectManager)
    {
        $this->objectManager = $objectManager;
    }

    /**
     * Analyzes the Object Configuration provided by the compiler and builds the necessary PHP code for the proxy classes
     * to realize dependency injection.
     *
     * @return void
     */
    public function build()
    {
        $this->objectConfigurations = $this->objectManager->getObjectConfigurations();

        foreach ($this->objectConfigurations as $objectName => $objectConfiguration) {
            $className = $objectConfiguration->getClassName();
            if ($className === '' || $this->compiler->hasCacheEntryForClass($className) === true) {
                continue;
            }

            if ($objectName !== $className || $this->reflectionService->isClassAbstract($className) || $this->reflectionService->isClassFinal($className)) {
                continue;
            }
            $proxyClass = $this->compiler->getProxyClass($className);
            if ($proxyClass === false) {
                continue;
            }
            $this->systemLogger->log('Building DI proxy for "' . $className . '".', LOG_DEBUG);

            $constructorPreCode = '';
            $constructorPostCode = '';

            $constructorPreCode .= $this->buildSetInstanceCode($objectConfiguration);
            $constructorPreCode .= $this->buildConstructorInjectionCode($objectConfiguration);

            $setRelatedEntitiesCode = '';
            if (!$this->reflectionService->hasMethod($className, '__sleep')) {
                $proxyClass->addTraits(['\TYPO3\Flow\Object\Proxy\ObjectSerializationTrait']);
                $sleepMethod = $proxyClass->getMethod('__sleep');
                $sleepMethod->addPostParentCallCode($this->buildSerializeRelatedEntitiesCode($objectConfiguration));

                $setRelatedEntitiesCode = "\n        " . '$this->Flow_setRelatedEntities();' . "\n";
            }

            $wakeupMethod = $proxyClass->getMethod('__wakeup');
            $wakeupMethod->addPreParentCallCode($this->buildSetInstanceCode($objectConfiguration));
            $wakeupMethod->addPreParentCallCode($setRelatedEntitiesCode);
            $wakeupMethod->addPostParentCallCode($this->buildLifecycleInitializationCode($objectConfiguration, \TYPO3\Flow\Object\ObjectManagerInterface::INITIALIZATIONCAUSE_RECREATED));
            $wakeupMethod->addPostParentCallCode($this->buildLifecycleShutdownCode($objectConfiguration));

            $injectPropertiesCode = $this->buildPropertyInjectionCode($objectConfiguration);
            if ($injectPropertiesCode !== '') {
                $proxyClass->addTraits(['\TYPO3\Flow\Object\DependencyInjection\PropertyInjectionTrait']);
                $proxyClass->getMethod('Flow_Proxy_injectProperties')->addPreParentCallCode($injectPropertiesCode);
                $proxyClass->getMethod('Flow_Proxy_injectProperties')->overrideMethodVisibility('private');
                $wakeupMethod->addPreParentCallCode("        \$this->Flow_Proxy_injectProperties();\n");

                $constructorPostCode .= '        if (\'' . $className . '\' === get_class($this)) {' . "\n";
                $constructorPostCode .= '            $this->Flow_Proxy_injectProperties();' . "\n";
                $constructorPostCode .= '        }' . "\n";
            }

            $constructorPostCode .= $this->buildLifecycleInitializationCode($objectConfiguration, \TYPO3\Flow\Object\ObjectManagerInterface::INITIALIZATIONCAUSE_CREATED);
            $constructorPostCode .= $this->buildLifecycleShutdownCode($objectConfiguration);

            $constructor = $proxyClass->getConstructor();
            $constructor->addPreParentCallCode($constructorPreCode);
            $constructor->addPostParentCallCode($constructorPostCode);

            if ($this->objectManager->getContext()->isProduction()) {
                $this->compileStaticMethods($className, $proxyClass);
            }
        }
    }

    /**
     * Renders additional code which registers the instance of the proxy class at the Object Manager
     * before constructor injection is executed. Used in constructors and wakeup methods.
     *
     * This also makes sure that object creation does not end in an endless loop due to bi-directional dependencies.
     *
     * @param Configuration $objectConfiguration
     * @return string
     */
    protected function buildSetInstanceCode(Configuration $objectConfiguration)
    {
        if ($objectConfiguration->getScope() === Configuration::SCOPE_PROTOTYPE) {
            return '';
        }

        $code = '        if (get_class($this) === \'' . $objectConfiguration->getClassName() . '\') \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->setInstance(\'' . $objectConfiguration->getObjectName() . '\', $this);' . "\n";

        $className = $objectConfiguration->getClassName();
        foreach ($this->objectConfigurations as $otherObjectConfiguration) {
            if ($otherObjectConfiguration !== $objectConfiguration && $otherObjectConfiguration->getClassName() === $className) {
                $code .= '        if (get_class($this) === \'' . $otherObjectConfiguration->getClassName() . '\') \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->setInstance(\'' . $otherObjectConfiguration->getObjectName() . '\', $this);' . "\n";
            }
        }

        return $code;
    }

    /**
     * Renders code to create identifier/type information from related entities in an object.
     * Used in sleep methods.
     *
     * @param Configuration $objectConfiguration
     * @return string
     */
    protected function buildSerializeRelatedEntitiesCode(Configuration $objectConfiguration)
    {
        $className = $objectConfiguration->getClassName();
        $code = '';
        if ($this->reflectionService->hasMethod($className, '__sleep') === false) {
            $transientProperties = $this->reflectionService->getPropertyNamesByAnnotation($className, 'TYPO3\Flow\Annotations\Transient');
            $propertyVarTags = [];
            foreach ($this->reflectionService->getPropertyNamesByTag($className, 'var') as $propertyName) {
                $varTagValues = $this->reflectionService->getPropertyTagValues($className, $propertyName, 'var');
                $propertyVarTags[$propertyName] = isset($varTagValues[0]) ? $varTagValues[0] : null;
            }
            $code = "        \$this->Flow_Object_PropertiesToSerialize = array();

        \$transientProperties = " . var_export($transientProperties, true) . ";
        \$propertyVarTags = " . var_export($propertyVarTags, true) . ";
        \$result = \$this->Flow_serializeRelatedEntities(\$transientProperties, \$propertyVarTags);\n";
        }
        return $code;
    }

    /**
     * Renders additional code for the __construct() method of the Proxy Class which realizes constructor injection.
     *
     * @param Configuration $objectConfiguration
     * @return string The built code
     * @throws \TYPO3\Flow\Object\Exception\UnknownObjectException
     */
    protected function buildConstructorInjectionCode(Configuration $objectConfiguration)
    {
        $assignments = array();

        $argumentConfigurations = $objectConfiguration->getArguments();
        $constructorParameterInfo = $this->reflectionService->getMethodParameters($objectConfiguration->getClassName(), '__construct');
        $argumentNumberToOptionalInfo = array();
        foreach ($constructorParameterInfo as $parameterInfo) {
            $argumentNumberToOptionalInfo[($parameterInfo['position'] + 1)] = $parameterInfo['optional'];
        }

        $highestArgumentPositionWithAutowiringEnabled = -1;
        foreach ($argumentConfigurations as $argumentNumber => $argumentConfiguration) {
            if ($argumentConfiguration === null) {
                continue;
            }
            $argumentPosition = $argumentNumber - 1;
            if ($argumentConfiguration->getAutowiring() === Configuration::AUTOWIRING_MODE_ON) {
                $highestArgumentPositionWithAutowiringEnabled = $argumentPosition;
            }

            $argumentValue = $argumentConfiguration->getValue();
            $assignmentPrologue = 'if (!array_key_exists(' . ($argumentNumber - 1) . ', $arguments)) $arguments[' . ($argumentNumber - 1) . '] = ';
            if ($argumentValue === null && isset($argumentNumberToOptionalInfo[$argumentNumber]) && $argumentNumberToOptionalInfo[$argumentNumber] === true) {
                $assignments[$argumentPosition] = $assignmentPrologue . 'NULL';
            } else {
                switch ($argumentConfiguration->getType()) {
                    case ConfigurationArgument::ARGUMENT_TYPES_OBJECT:
                        if ($argumentValue instanceof Configuration) {
                            $argumentValueObjectName = $argumentValue->getObjectName();
                            $argumentValueClassName = $argumentValue->getClassName();
                            if ($argumentValueClassName === null) {
                                $preparedArgument = $this->buildCustomFactoryCall($argumentValue->getFactoryObjectName(), $argumentValue->getFactoryMethodName(), $argumentValue->getArguments());
                                $assignments[$argumentPosition] = $assignmentPrologue . $preparedArgument;
                            } else {
                                if ($this->objectConfigurations[$argumentValueObjectName]->getScope() === Configuration::SCOPE_PROTOTYPE) {
                                    $assignments[$argumentPosition] = $assignmentPrologue . 'new \\' . $argumentValueObjectName . '(' . $this->buildMethodParametersCode($argumentValue->getArguments()) . ')';
                                } else {
                                    $assignments[$argumentPosition] = $assignmentPrologue . '\TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get(\'' . $argumentValueObjectName . '\')';
                                }
                            }
                        } else {
                            if (strpos($argumentValue, '.') !== false) {
                                $settingPath = explode('.', $argumentValue);
                                $settings = Arrays::getValueByPath($this->configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS), array_shift($settingPath));
                                $argumentValue = Arrays::getValueByPath($settings, $settingPath);
                            }
                            if (!isset($this->objectConfigurations[$argumentValue])) {
                                throw new \TYPO3\Flow\Object\Exception\UnknownObjectException('The object "' . $argumentValue . '" which was specified as an argument in the object configuration of object "' . $objectConfiguration->getObjectName() . '" does not exist.', 1264669967);
                            }
                            $assignments[$argumentPosition] = $assignmentPrologue . '\TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get(\'' . $argumentValue . '\')';
                        }
                    break;

                    case ConfigurationArgument::ARGUMENT_TYPES_STRAIGHTVALUE:
                        $assignments[$argumentPosition] = $assignmentPrologue . var_export($argumentValue, true);
                    break;

                    case ConfigurationArgument::ARGUMENT_TYPES_SETTING:
                        $assignments[$argumentPosition] = $assignmentPrologue . '\TYPO3\Flow\Core\Bootstrap::$staticObjectManager->getSettingsByPath(explode(\'.\', \'' . $argumentValue . '\'))';
                    break;
                }
            }
        }

        for ($argumentCounter = count($assignments) - 1; $argumentCounter > $highestArgumentPositionWithAutowiringEnabled; $argumentCounter--) {
            unset($assignments[$argumentCounter]);
        }

        $code = $argumentCounter >= 0 ? "\n        " . implode(";\n        ", $assignments) . ";\n" : '';

        $index = 0;
        foreach ($constructorParameterInfo as $parameterName => $parameterInfo) {
            if ($parameterInfo['optional'] === true) {
                break;
            }
            if ($objectConfiguration->getScope() === Configuration::SCOPE_SINGLETON) {
                $code .= '        if (!array_key_exists(' . $index . ', $arguments)) throw new \TYPO3\Flow\Object\Exception\UnresolvedDependenciesException(\'Missing required constructor argument $' . $parameterName . ' in class \' . __CLASS__ . \'. Please check your calling code and Dependency Injection configuration.\', 1296143787);' . "\n";
            } else {
                $code .= '        if (!array_key_exists(' . $index . ', $arguments)) throw new \TYPO3\Flow\Object\Exception\UnresolvedDependenciesException(\'Missing required constructor argument $' . $parameterName . ' in class \' . __CLASS__ . \'. Note that constructor injection is only support for objects of scope singleton (and this is not a singleton) – for other scopes you must pass each required argument to the constructor yourself.\', 1296143788);' . "\n";
            }
            $index++;
        }

        return $code;
    }

    /**
     * Builds the code necessary to inject setter based dependencies.
     *
     * @param Configuration $objectConfiguration (needed to produce helpful exception message)
     * @return string The built code
     * @throws \TYPO3\Flow\Object\Exception\UnknownObjectException
     */
    protected function buildPropertyInjectionCode(Configuration $objectConfiguration)
    {
        $commands = array();
        $injectedProperties = array();
        foreach ($objectConfiguration->getProperties() as $propertyName => $propertyConfiguration) {
            /* @var $propertyConfiguration ConfigurationProperty */
            if ($propertyConfiguration->getAutowiring() === Configuration::AUTOWIRING_MODE_OFF) {
                continue;
            }

            $propertyValue = $propertyConfiguration->getValue();
            switch ($propertyConfiguration->getType()) {
                case ConfigurationProperty::PROPERTY_TYPES_OBJECT:
                    if ($propertyValue instanceof Configuration) {
                        $commands = array_merge($commands, $this->buildPropertyInjectionCodeByConfiguration($objectConfiguration, $propertyName, $propertyValue));
                    } else {
                        $commands = array_merge($commands, $this->buildPropertyInjectionCodeByString($objectConfiguration, $propertyConfiguration, $propertyName, $propertyValue));
                    }

                break;
                case ConfigurationProperty::PROPERTY_TYPES_STRAIGHTVALUE:
                    if (is_string($propertyValue)) {
                        $preparedSetterArgument = '\'' . str_replace('\'', '\\\'', $propertyValue) . '\'';
                    } elseif (is_array($propertyValue)) {
                        $preparedSetterArgument = var_export($propertyValue, true);
                    } elseif (is_bool($propertyValue)) {
                        $preparedSetterArgument = $propertyValue ? 'TRUE' : 'FALSE';
                    } else {
                        $preparedSetterArgument = $propertyValue;
                    }
                    $commands[] = 'if (\TYPO3\Flow\Reflection\ObjectAccess::setProperty($this, \'' . $propertyName . '\', ' . $preparedSetterArgument . ') === FALSE) { $this->' . $propertyName . ' = ' . $preparedSetterArgument . ';}';
                    break;
                case ConfigurationProperty::PROPERTY_TYPES_CONFIGURATION:
                    $configurationType = $propertyValue['type'];
                    if (!in_array($configurationType, $this->configurationManager->getAvailableConfigurationTypes())) {
                        throw new \TYPO3\Flow\Object\Exception\UnknownObjectException('The configuration injection specified for property "' . $propertyName . '" in the object configuration of object "' . $objectConfiguration->getObjectName() . '" refers to the unknown configuration type "' . $configurationType . '".', 1420736211);
                    }
                    $commands = array_merge($commands, $this->buildPropertyInjectionCodeByConfigurationTypeAndPath($objectConfiguration, $propertyName, $configurationType, $propertyValue['path']));
                break;
            }
            $injectedProperties[] = $propertyName;
        }

        if (count($commands) > 0) {
            $commandString = "    " . implode("\n    ", $commands) . "\n";
            $commandString .= '        $this->Flow_Injected_Properties = ' . var_export($injectedProperties, true) . ";\n";
        } else {
            $commandString = '';
        }

        return $commandString;
    }

    /**
     * Builds code which injects an object which was specified by its object configuration
     *
     * @param Configuration $objectConfiguration Configuration of the object to inject into
     * @param string $propertyName Name of the property to inject
     * @param Configuration $propertyConfiguration Configuration of the object to inject
     * @return array PHP code
     * @throws \TYPO3\Flow\Object\Exception\UnknownObjectException
     */
    protected function buildPropertyInjectionCodeByConfiguration(Configuration $objectConfiguration, $propertyName, Configuration $propertyConfiguration)
    {
        $className = $objectConfiguration->getClassName();
        $propertyObjectName = $propertyConfiguration->getObjectName();
        $propertyClassName = $propertyConfiguration->getClassName();
        if ($propertyClassName === null) {
            $preparedSetterArgument = $this->buildCustomFactoryCall($propertyConfiguration->getFactoryObjectName(), $propertyConfiguration->getFactoryMethodName(), $propertyConfiguration->getArguments());
        } else {
            if (!is_string($propertyClassName) || !isset($this->objectConfigurations[$propertyClassName])) {
                $configurationSource = $objectConfiguration->getConfigurationSourceHint();
                throw new \TYPO3\Flow\Object\Exception\UnknownObjectException('Unknown class "' . $propertyClassName . '", specified as property "' . $propertyName . '" in the object configuration of object "' . $objectConfiguration->getObjectName() . '" (' . $configurationSource . ').', 1296130876);
            }
            if ($this->objectConfigurations[$propertyClassName]->getScope() === Configuration::SCOPE_PROTOTYPE) {
                $preparedSetterArgument = 'new \\' . $propertyClassName . '(' . $this->buildMethodParametersCode($propertyConfiguration->getArguments()) . ')';
            } else {
                $preparedSetterArgument = '\TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get(\'' . $propertyClassName . '\')';
            }
        }

        $result = $this->buildSetterInjectionCode($className, $propertyName, $preparedSetterArgument);
        if ($result !== null) {
            return $result;
        }

        return $this->buildLazyPropertyInjectionCode($propertyObjectName, $propertyClassName, $propertyName, $preparedSetterArgument);
    }

    /**
     * Builds code which injects an object which was specified by its object name
     *
     * @param Configuration $objectConfiguration Configuration of the object to inject into
     * @param ConfigurationProperty $propertyConfiguration
     * @param string $propertyName Name of the property to inject
     * @param string $propertyObjectName Object name of the object to inject
     * @return array PHP code
     * @throws \TYPO3\Flow\Object\Exception\UnknownObjectException
     */
    public function buildPropertyInjectionCodeByString(Configuration $objectConfiguration, ConfigurationProperty $propertyConfiguration, $propertyName, $propertyObjectName)
    {
        $className = $objectConfiguration->getClassName();

        if (strpos($propertyObjectName, '.') !== false) {
            $settingPath = explode('.', $propertyObjectName);
            $settings = Arrays::getValueByPath($this->configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS), array_shift($settingPath));
            $propertyObjectName = Arrays::getValueByPath($settings, $settingPath);
        }

        if (!isset($this->objectConfigurations[$propertyObjectName])) {
            $configurationSource = $objectConfiguration->getConfigurationSourceHint();
            if (!isset($propertyObjectName[0])) {
                throw new \TYPO3\Flow\Object\Exception\UnknownObjectException('Malformed DocComent block for a property in class "' . $className . '".', 1360171313);
            }
            if ($propertyObjectName[0] === '\\') {
                throw new \TYPO3\Flow\Object\Exception\UnknownObjectException('The object name "' . $propertyObjectName . '" which was specified as a property in the object configuration of object "' . $objectConfiguration->getObjectName() . '" (' . $configurationSource . ') starts with a leading backslash.', 1277827579);
            } else {
                throw new \TYPO3\Flow\Object\Exception\UnknownObjectException('The object "' . $propertyObjectName . '" which was specified as a property in the object configuration of object "' . $objectConfiguration->getObjectName() . '" (' . $configurationSource . ') does not exist. Check for spelling mistakes and if that dependency is correctly configured.', 1265213849);
            }
        }
        $propertyClassName = $this->objectConfigurations[$propertyObjectName]->getClassName();
        if ($this->objectConfigurations[$propertyObjectName]->getScope() === Configuration::SCOPE_PROTOTYPE && !$this->objectConfigurations[$propertyObjectName]->isCreatedByFactory()) {
            $preparedSetterArgument = 'new \\' . $propertyClassName . '(' . $this->buildMethodParametersCode($this->objectConfigurations[$propertyObjectName]->getArguments()) . ')';
        } else {
            $preparedSetterArgument = '\TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get(\'' . $propertyObjectName . '\')';
        }

        $result = $this->buildSetterInjectionCode($className, $propertyName, $preparedSetterArgument);
        if ($result !== null) {
            return $result;
        }

        if ($propertyConfiguration->isLazyLoading() && $this->objectConfigurations[$propertyObjectName]->getScope() !== Configuration::SCOPE_PROTOTYPE) {
            return $this->buildLazyPropertyInjectionCode($propertyObjectName, $propertyClassName, $propertyName, $preparedSetterArgument);
        } else {
            return array('    $this->' . $propertyName . ' = ' . $preparedSetterArgument . ';');
        }
    }

    /**
     * Builds code which assigns the value stored in the specified configuration into the given class property.
     *
     * @param Configuration $objectConfiguration Configuration of the object to inject into
     * @param string $propertyName Name of the property to inject
     * @param string $configurationType the configuration type of the injected property (one of the ConfigurationManager::CONFIGURATION_TYPE_* constants)
     * @param string $configurationPath Path with "." as separator specifying the setting value to inject or NULL if the complete configuration array should be injected
     * @return array PHP code
     */
    public function buildPropertyInjectionCodeByConfigurationTypeAndPath(Configuration $objectConfiguration, $propertyName, $configurationType, $configurationPath = null)
    {
        $className = $objectConfiguration->getClassName();
        if ($configurationPath !== null) {
            $preparedSetterArgument = '\TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get(\TYPO3\Flow\Configuration\ConfigurationManager::class)->getConfiguration(\'' . $configurationType . '\', \'' . $configurationPath . '\')';
        } else {
            $preparedSetterArgument = '\TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get(\TYPO3\Flow\Configuration\ConfigurationManager::class)->getConfiguration(\'' . $configurationType . '\')';
        }

        $result = $this->buildSetterInjectionCode($className, $propertyName, $preparedSetterArgument);
        if ($result !== null) {
            return $result;
        }
        return array('    $this->' . $propertyName . ' = ' . $preparedSetterArgument . ';');
    }

    /**
     * Builds code which injects a DependencyProxy instead of the actual dependency
     *
     * @param string $propertyObjectName Object name of the dependency to inject
     * @param string $propertyClassName Class name of the dependency to inject
     * @param string $propertyName Name of the property in the class to inject into
     * @param string $preparedSetterArgument PHP code to use for retrieving the value to inject
     * @return array PHP code
     */
    protected function buildLazyPropertyInjectionCode($propertyObjectName, $propertyClassName, $propertyName, $preparedSetterArgument)
    {
        $setterArgumentHash = "'" . md5($preparedSetterArgument) . "'";
        $commands[] = '    $this->Flow_Proxy_LazyPropertyInjection(\'' . $propertyObjectName . '\', \'' . $propertyClassName . '\', \'' . $propertyName . '\', ' . $setterArgumentHash . ', function() { return ' . $preparedSetterArgument . '; });';

        return $commands;
    }

    /**
     * Builds a code snippet which tries to inject the specified property first through calling the related
     * inject*() method and then the set*() method. If neither exists and the property doesn't exist either,
     * an empty array is returned.
     *
     * If neither inject*() nor set*() exists, but the property does exist, NULL is returned
     *
     * @param string $className Name of the class to inject into
     * @param string $propertyName Name of the property to inject
     * @param string $preparedSetterArgument PHP code to use for retrieving the value to inject
     * @return array PHP code
     */
    protected function buildSetterInjectionCode($className, $propertyName, $preparedSetterArgument)
    {
        $setterMethodName = 'inject' . ucfirst($propertyName);
        if ($this->reflectionService->hasMethod($className, $setterMethodName)) {
            return array('    $this->' . $setterMethodName . '(' . $preparedSetterArgument . ');');
        }
        $setterMethodName = 'set' . ucfirst($propertyName);
        if ($this->reflectionService->hasMethod($className, $setterMethodName)) {
            return array('    $this->' . $setterMethodName . '(' . $preparedSetterArgument . ');');
        }
        if (!property_exists($className, $propertyName)) {
            return array();
        }
        return null;
    }

    /**
     * Builds code which calls the lifecycle initialization method, if any.
     *
     * @param Configuration $objectConfiguration
     * @param integer $cause a \TYPO3\Flow\Object\ObjectManagerInterface::INITIALIZATIONCAUSE_* constant which is the cause of the initialization command being called.
     * @return string
     */
    protected function buildLifecycleInitializationCode(Configuration $objectConfiguration, $cause)
    {
        $lifecycleInitializationMethodName = $objectConfiguration->getLifecycleInitializationMethodName();
        if (!$this->reflectionService->hasMethod($objectConfiguration->getClassName(), $lifecycleInitializationMethodName)) {
            return '';
        }
        $className = $objectConfiguration->getClassName();
        $code = "\n" . '        if (get_class($this) === \'' . $className . '\') {' . "\n";
        $code .= '            $this->' . $lifecycleInitializationMethodName . '(' . $cause . ');' . "\n";
        $code .= '        }' . "\n";
        return $code;
    }

    /**
     * Builds code which registers the lifecycle shutdown method, if any.
     *
     * @param Configuration $objectConfiguration
     * @return string
     */
    protected function buildLifecycleShutdownCode(Configuration $objectConfiguration)
    {
        $lifecycleShutdownMethodName = $objectConfiguration->getLifecycleShutdownMethodName();
        if (!$this->reflectionService->hasMethod($objectConfiguration->getClassName(), $lifecycleShutdownMethodName)) {
            return '';
        }
        $className = $objectConfiguration->getClassName();
        $code = "\n" . '        if (get_class($this) === \'' . $className . '\') {' . "\n";
        $code .= '        \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->registerShutdownObject($this, \'' . $lifecycleShutdownMethodName . '\');' . PHP_EOL;
        $code .= '        }' . "\n";
        return $code;
    }

    /**
     * FIXME: Not yet completely refactored to new proxy mechanism
     *
     * @param array $argumentConfigurations
     * @return string
     */
    protected function buildMethodParametersCode(array $argumentConfigurations)
    {
        $preparedArguments = array();

        foreach ($argumentConfigurations as $argument) {
            if ($argument === null) {
                $preparedArguments[] = 'NULL';
            } else {
                $argumentValue = $argument->getValue();

                switch ($argument->getType()) {
                    case ConfigurationArgument::ARGUMENT_TYPES_OBJECT:
                        if ($argumentValue instanceof Configuration) {
                            $argumentValueObjectName = $argumentValue->getObjectName();
                            if ($this->objectConfigurations[$argumentValueObjectName]->getScope() === Configuration::SCOPE_PROTOTYPE) {
                                $preparedArguments[] = 'new \\' . $argumentValueObjectName . '(' . $this->buildMethodParametersCode($argumentValue->getArguments(), $this->objectConfigurations) . ')';
                            } else {
                                $preparedArguments[] = '\TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get(\'' . $argumentValueObjectName . '\')';
                            }
                        } else {
                            if (strpos($argumentValue, '.') !== false) {
                                $settingPath = explode('.', $argumentValue);
                                $settings = Arrays::getValueByPath($this->configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS), array_shift($settingPath));
                                $argumentValue = Arrays::getValueByPath($settings, $settingPath);
                            }
                            $preparedArguments[] = '\TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get(\'' . $argumentValue . '\')';
                        }
                    break;

                    case ConfigurationArgument::ARGUMENT_TYPES_STRAIGHTVALUE:
                        $preparedArguments[] = var_export($argumentValue, true);
                    break;

                    case ConfigurationArgument::ARGUMENT_TYPES_SETTING:
                        $preparedArguments[] = '\TYPO3\Flow\Core\Bootstrap::$staticObjectManager->getSettingsByPath(explode(\'.\', \'' . $argumentValue . '\'))';
                    break;
                }
            }
        }
        return implode(', ', $preparedArguments);
    }

    /**
     * @param string $customFactoryObjectName
     * @param string $customFactoryMethodName
     * @param array $arguments
     * @return string
     */
    protected function buildCustomFactoryCall($customFactoryObjectName, $customFactoryMethodName, array $arguments)
    {
        $parametersCode = $this->buildMethodParametersCode($arguments);
        return '\TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get(\'' . $customFactoryObjectName . '\')->' . $customFactoryMethodName . '(' . $parametersCode . ')';
    }

    /**
     * Compile the result of methods marked with CompileStatic into the proxy class
     *
     * @param string $className
     * @param \TYPO3\Flow\Object\Proxy\ProxyClass $proxyClass
     * @return void
     */
    protected function compileStaticMethods($className, $proxyClass)
    {
        if ($this->classesWithCompileStaticAnnotation === null) {
            $this->classesWithCompileStaticAnnotation = array_flip($this->reflectionService->getClassesContainingMethodsAnnotatedWith(\TYPO3\Flow\Annotations\CompileStatic::class));
        }
        if (!isset($this->classesWithCompileStaticAnnotation[$className])) {
            return;
        }

        $methodNames = get_class_methods($className);
        foreach ($methodNames as $methodName) {
            if ($this->reflectionService->isMethodStatic($className, $methodName) && $this->reflectionService->isMethodAnnotatedWith($className, $methodName, \TYPO3\Flow\Annotations\CompileStatic::class)) {
                $compiledMethod = $proxyClass->getMethod($methodName);

                $value = call_user_func(array($className, $methodName), $this->objectManager);
                $compiledResult = var_export($value, true);
                $compiledMethod->setMethodBody('return ' . $compiledResult . ';');
            }
        }
    }
}


text:
**Daum Search** is a very simple Mac App lets you find something very fast and conveniently.

<img src="https://raw.githubusercontent.com/likejazz/daum-search-mac-app/master/Screenshot.png" width="400" />

# Download

To download the latest release, [click here](https://github.com/likejazz/daum-search-mac-app/releases/latest)

# Usage

- Hit `CMD + L` to focus on search box for convenient use.
- If you want current URL to open in external default browser(e.g. Chrome, Safari, Firefox), click button named '새 창'.

# App Icon

AppIcon derived from 'Muir: the Master Collection's browser icon for personal use only.
<http://dewith.com/2015/muir-the-master-collection/>

# License

These works are available under the MIT license. See the [license](LICENSE) file for more info.

redpajama_set_name: RedPajamaGithub


text:
set DOCKER_OPTIONS=-e jdbc.dbms.default=postgres-xa

call start.bat


text:
Pattern: Redirecting to command that does not read from stdin

Issue: -

## Description

You are redirecting to one of several commands that don't read from stdin.

This may happen when:

* Confusing one command for another, e.g. using `echo` where `cat` was intended.
* Incorrectly quoting angle brackets, e.g. using `echo <p>Hello` which tries to read from a file `p`.
* Missing `xargs`, e.g. `mv -t dir < files` instead of `xargs mv -t dir < files` (or more safely, `tr '\n' '\0' < files | xargs -0 mv -t dir`), because stdin should be passed as parameters.

Check your logic, and rewrite the command so data is passed correctly.

Example of **incorrect** code:

```sh
echo << eof
  Hello World
eof
```

Example of **correct** code:

```sh
cat << eof
  Hello World
eof
```

## Exceptions

If you've overridden a command to return output, you can either rename it to make this obvious, or ignore this message.

## Further Reading

* [ShellCheck - SC2217](https://github.com/koalaman/shellcheck/wiki/SC2217)


text:
package com.amazonaws.services.elasticache.model.transform;

import java.util.ArrayList;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.elasticache.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * CacheNodeTypeSpecificParameter StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CacheNodeTypeSpecificParameterStaxUnmarshaller implements Unmarshaller<CacheNodeTypeSpecificParameter, StaxUnmarshallerContext> {

    public CacheNodeTypeSpecificParameter unmarshall(StaxUnmarshallerContext context) throws Exception {
        CacheNodeTypeSpecificParameter cacheNodeTypeSpecificParameter = new CacheNodeTypeSpecificParameter();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return cacheNodeTypeSpecificParameter;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("ParameterName", targetDepth)) {
                    cacheNodeTypeSpecificParameter.setParameterName(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("Description", targetDepth)) {
                    cacheNodeTypeSpecificParameter.setDescription(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("Source", targetDepth)) {
                    cacheNodeTypeSpecificParameter.setSource(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("DataType", targetDepth)) {
                    cacheNodeTypeSpecificParameter.setDataType(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("AllowedValues", targetDepth)) {
                    cacheNodeTypeSpecificParameter.setAllowedValues(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("IsModifiable", targetDepth)) {
                    cacheNodeTypeSpecificParameter.setIsModifiable(BooleanStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("MinimumEngineVersion", targetDepth)) {
                    cacheNodeTypeSpecificParameter.setMinimumEngineVersion(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("CacheNodeTypeSpecificValues", targetDepth)) {
                    cacheNodeTypeSpecificParameter.withCacheNodeTypeSpecificValues(new ArrayList<CacheNodeTypeSpecificValue>());
                    continue;
                }

                if (context.testExpression("CacheNodeTypeSpecificValues/CacheNodeTypeSpecificValue", targetDepth)) {
                    cacheNodeTypeSpecificParameter
                            .withCacheNodeTypeSpecificValues(CacheNodeTypeSpecificValueStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("ChangeType", targetDepth)) {
                    cacheNodeTypeSpecificParameter.setChangeType(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return cacheNodeTypeSpecificParameter;
                }
            }
        }
    }

    private static CacheNodeTypeSpecificParameterStaxUnmarshaller instance;

    public static CacheNodeTypeSpecificParameterStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new CacheNodeTypeSpecificParameterStaxUnmarshaller();
        return instance;
    }
}


text:
import './ek-confirm.less';
import Directive from 'directive';
import Controller from './ek-confirm.controller';
import template from './ek-confirm.html';

class ConfirmDirective extends Directive {

    constructor($compile) {
        super({ Controller, template });

        this._$compile = $compile;
    }

    compile(tElement) {
        tElement.addClass('ek-confirm');

        return ($scope, $element, attrs, ctrl) => {
            ctrl.options = $scope.$parent.options;
            _.extend($scope, $scope.$parent.options.scope);

            if (ctrl.options.template) {
                const element = angular.element(`<md-dialog-content class="ek-confirm__dialog__content">
                        ${ctrl.options.template}
                    </md-dialog-content>`);

                $element.find('.ek-confirm__dialog').append(element);
                this._$compile(element)($scope);
            }
        };
    }
}

export default ConfirmDirective;


text:
package info.rolandkrueger.userservice.api.model;

import com.google.common.base.MoreObjects;
import info.rolandkrueger.userservice.api._internal.model.AbstractBaseApiData;
import info.rolandkrueger.userservice.api.resources.AuthorityResource;
import org.springframework.hateoas.Link;
import org.springframework.security.core.GrantedAuthority;

import java.time.LocalDateTime;

/**
 * Client-side representation of the Authority domain object. Implements Spring Security's
 * {@link GrantedAuthority} interface and can thus be used in a {@link org.springframework.security.core.userdetails.UserDetailsService}.
 *
 * @author Roland Krüger
 */
public class AuthorityApiData extends AbstractBaseApiData<AuthorityResource> implements GrantedAuthority {
    private Long version;
    private LocalDateTime lastModified;
    private String authority;
    private String description;

    public AuthorityApiData() {
    }

    /**
     * Create a new {@link AuthorityApiData} object with the given authority name and description.
     *
     * @param authority   name of the authority
     * @param description description of the authority
     */
    public AuthorityApiData(String authority, String description) {
        setAuthority(authority);
        setDescription(description);
    }

    public Long getVersion() {
        return version;
    }

    public void setVersion(Long version) {
        this.version = version;
    }

    public LocalDateTime getLastModified() {
        return lastModified;
    }

    public void setLastModified(LocalDateTime lastModified) {
        this.lastModified = lastModified;
    }

    public String getAuthority() {
        return authority;
    }

    public void setAuthority(String authority) {
        this.authority = authority;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(AuthorityApiData.class)
                .add("authority", authority)
                .add("description", description)
                .toString();
    }

    @Override
    protected AuthorityResource createNewResource(Link self) {
        return new AuthorityResource(self, this);
    }
}


text:
namespace syntaxnet {
namespace dragnn {

// Returns OK if the 0'th input of the |context| is compatible with the shape of
// a ComputeSession handle.
inline tensorflow::Status ComputeSessionHandleInputShape(
    tensorflow::shape_inference::InferenceContext *context) {
  tensorflow::shape_inference::ShapeHandle unused;
  return context->Merge(context->input(0), context->Vector(2), &unused);
}

// Sets the 0'th output of the |context| to have the shape of a ComputeSession
// handle.  Always returns OK.
inline tensorflow::Status ComputeSessionHandleOutputShape(
    tensorflow::shape_inference::InferenceContext *context) {
  context->set_output(0, context->Vector(2));
  return tensorflow::Status::OK();
}

// For convenience, combines ComputeSessionHandle{Input,Output}Shape().
inline tensorflow::Status ComputeSessionHandleInputAndOutputShape(
    tensorflow::shape_inference::InferenceContext *context) {
  TF_RETURN_IF_ERROR(ComputeSessionHandleInputShape(context));
  return ComputeSessionHandleOutputShape(context);
}

}  // namespace dragnn
}  // namespace syntaxnet

#endif  // DRAGNN_CORE_OPS_SHAPE_HELPERS_H_


text:
module Babushka

  def VersionOf first, *rest
    # Convert the arguments into a VersionOf. If a single string argument is
    # passed, try splitting it on space to separate name and version. Otherwise,
    # pass the arguments as-is, splatting if required.
    if rest.any?
      Babushka::VersionOf.new(*[first].concat(rest))
    elsif first.is_a?(String)
      name, version = first.split(' ', 2)
      if version && VersionStr.parseable_version?(version)
        Babushka::VersionOf.new(name, version)
      else
        Babushka::VersionOf.new(first)
      end
    elsif first.is_a?(Array)
      Babushka::VersionOf.new(*first)
    else
      Babushka::VersionOf.new(first)
    end
  end

  module_function :VersionOf

  class VersionOf
    module Helpers
      def VersionOf first, *rest
        # TODO: decide on the form for this and deprecate the others.
        Babushka.VersionOf(first, *rest)
      end
      module_function :VersionOf
    end

    attr_accessor :name, :version

    def initialize name, version = nil
      @name = name.is_a?(VersionOf) ? name.name : name
      @version = if version.nil?
        name.version if name.respond_to?(:version)
      elsif version.is_a? VersionStr
        version
      else
        version.to_version
      end
    end

    def == other
      if other.is_a? VersionOf
        name == other.name &&
        version == other.version
      else
        to_s == other.to_s
      end
    end

    def <=> other
      return nil if other.nil?
      return nil unless name == other.name
      version <=> other.version
    end

    def matches? other
      if other.is_a? VersionStr
        version.nil? || other.send(version.operator, version)
      else
        matches? other.to_version
      end
    end

    def to_s
      # == joins with a dash to produce versions like 'rack-1.4.1'; anything
      # else joins with space like 'rack >= 1.4'.
      [name, version].compact * (exact? ? '-' : ' ')
    end

    def exact?
      !version.nil? && version.operator == '=='
    end

    def inspect
      "#<VersionOf #{name}#{", v#{version}" unless version.nil?}>"
    end
  end
end


text:
/** This is generated, do not edit by hand. **/

#include <jni.h>

#include "Proxy.h"

		namespace titanium {
			namespace calendar {

class EventProxy : public titanium::Proxy
{
public:
	explicit EventProxy(jobject javaObject);

	static void bindProxy(v8::Handle<v8::Object> exports);
	static v8::Handle<v8::FunctionTemplate> getProxyTemplate();
	static void dispose();

	static v8::Persistent<v8::FunctionTemplate> proxyTemplate;
	static jclass javaClass;

private:
	// Methods -----------------------------------------------------------
	static v8::Handle<v8::Value> getStatus(const v8::Arguments&);
	static v8::Handle<v8::Value> getHasAlarm(const v8::Arguments&);
	static v8::Handle<v8::Value> getAlerts(const v8::Arguments&);
	static v8::Handle<v8::Value> getRecurrenceDate(const v8::Arguments&);
	static v8::Handle<v8::Value> getDescription(const v8::Arguments&);
	static v8::Handle<v8::Value> getVisibility(const v8::Arguments&);
	static v8::Handle<v8::Value> createReminder(const v8::Arguments&);
	static v8::Handle<v8::Value> getExtendedProperties(const v8::Arguments&);
	static v8::Handle<v8::Value> getRecurrenceRule(const v8::Arguments&);
	static v8::Handle<v8::Value> getExtendedProperty(const v8::Arguments&);
	static v8::Handle<v8::Value> getEnd(const v8::Arguments&);
	static v8::Handle<v8::Value> getBegin(const v8::Arguments&);
	static v8::Handle<v8::Value> getRecurrenceExceptionRule(const v8::Arguments&);
	static v8::Handle<v8::Value> getLocation(const v8::Arguments&);
	static v8::Handle<v8::Value> createAlert(const v8::Arguments&);
	static v8::Handle<v8::Value> getHasExtendedProperties(const v8::Arguments&);
	static v8::Handle<v8::Value> getReminders(const v8::Arguments&);
	static v8::Handle<v8::Value> getTitle(const v8::Arguments&);
	static v8::Handle<v8::Value> getRecurrenceExceptionDate(const v8::Arguments&);
	static v8::Handle<v8::Value> getAllDay(const v8::Arguments&);
	static v8::Handle<v8::Value> getLastDate(const v8::Arguments&);
	static v8::Handle<v8::Value> setExtendedProperty(const v8::Arguments&);
	static v8::Handle<v8::Value> getId(const v8::Arguments&);

	// Dynamic property accessors ----------------------------------------
	static v8::Handle<v8::Value> getter_hasExtendedProperties(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_reminders(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_recurrenceExceptionDate(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_visibility(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_status(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_allDay(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_location(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_recurrenceExceptionRule(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_lastDate(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_hasAlarm(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_begin(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_id(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_title(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_recurrenceDate(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_description(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_alerts(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_recurrenceRule(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_end(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_extendedProperties(v8::Local<v8::String> property, const v8::AccessorInfo& info);

};

			} // namespace calendar
		} // titanium


text:
//Switch to the appropriate trace level
#define TRACE_LEVEL NIC_TRACE_LEVEL

//Dependencies
#include <limits.h>
#include "at91sam9263.h"
#include "core/net.h"
#include "drivers/sam9263_eth.h"
#include "debug.h"

//Underlying network interface
static NetInterface *nicDriverInterface;

//TX buffer
static uint8_t txBuffer[SAM9263_ETH_TX_BUFFER_COUNT][SAM9263_ETH_TX_BUFFER_SIZE]
   __attribute__((aligned(8)));
//RX buffer
static uint8_t rxBuffer[SAM9263_ETH_RX_BUFFER_COUNT][SAM9263_ETH_RX_BUFFER_SIZE]
   __attribute__((aligned(8)));
//TX buffer descriptors
static Sam9263TxBufferDesc txBufferDesc[SAM9263_ETH_TX_BUFFER_COUNT]
   __attribute__((aligned(4)));
//RX buffer descriptors
static Sam9263RxBufferDesc rxBufferDesc[SAM9263_ETH_RX_BUFFER_COUNT]
   __attribute__((aligned(4)));

//TX buffer index
static uint_t txBufferIndex;
//RX buffer index
static uint_t rxBufferIndex;

/**
 * @brief SAM9263 Ethernet MAC driver
 **/

const NicDriver sam9263EthDriver =
{
   NIC_TYPE_ETHERNET,
   ETH_MTU,
   sam9263EthInit,
   sam9263EthTick,
   sam9263EthEnableIrq,
   sam9263EthDisableIrq,
   sam9263EthEventHandler,
   sam9263EthSetMacFilter,
   sam9263EthSendPacket,
   sam9263EthWritePhyReg,
   sam9263EthReadPhyReg,
   TRUE,
   TRUE,
   TRUE
};

/**
 * @brief SAM9263 Ethernet MAC initialization
 * @param[in] interface Underlying network interface
 * @return Error code
 **/

error_t sam9263EthInit(NetInterface *interface)
{
   error_t error;
   volatile uint32_t status;

   //Debug message
   TRACE_INFO("Initializing SAM9263 Ethernet MAC...\r\n");

   //Save underlying network interface
   nicDriverInterface = interface;

   //Enable EMAC peripheral clock
   AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_EMAC);

   //GPIO configuration
   sam9263EthInitGpio(interface);

   //Configure MDC clock speed
   AT91C_BASE_EMAC->EMAC_NCFGR = AT91C_EMAC_CLK_HCLK_64;
   //Enable management port (MDC and MDIO)
   AT91C_BASE_EMAC->EMAC_NCR |= AT91C_EMAC_MPE;

   //PHY transceiver initialization
   error = interface->phyDriver->init(interface);
   //Failed to initialize PHY transceiver?
   if(error) return error;

   //Set the MAC address
   AT91C_BASE_EMAC->EMAC_SA1L = interface->macAddr.w[0] | (interface->macAddr.w[1] << 16);
   AT91C_BASE_EMAC->EMAC_SA1H = interface->macAddr.w[2];

   //Configure the receive filter
   AT91C_BASE_EMAC->EMAC_NCFGR |= AT91C_EMAC_UNI | AT91C_EMAC_MTI;

   //Initialize hash table
   AT91C_BASE_EMAC->EMAC_HRB = 0;
   AT91C_BASE_EMAC->EMAC_HRT = 0;

   //Initialize buffer descriptors
   sam9263EthInitBufferDesc(interface);

   //Clear transmit status register
   AT91C_BASE_EMAC->EMAC_TSR = AT91C_EMAC_UND | AT91C_EMAC_COMP | AT91C_EMAC_BEX |
      AT91C_EMAC_TGO | AT91C_EMAC_RLES | AT91C_EMAC_COL | AT91C_EMAC_UBR;
   //Clear receive status register
   AT91C_BASE_EMAC->EMAC_RSR = AT91C_EMAC_OVR | AT91C_EMAC_REC | AT91C_EMAC_BNA;

   //First disable all EMAC interrupts
   AT91C_BASE_EMAC->EMAC_IDR = 0xFFFFFFFF;
   //Only the desired ones are enabled
   AT91C_BASE_EMAC->EMAC_IER = AT91C_EMAC_ROVR | AT91C_EMAC_TCOMP | AT91C_EMAC_TXERR |
      AT91C_EMAC_RLEX | AT91C_EMAC_TUNDR | AT91C_EMAC_RXUBR | AT91C_EMAC_RCOMP;

   //Read EMAC ISR register to clear any pending interrupt
   status = AT91C_BASE_EMAC->EMAC_ISR;

   //Configure interrupt controller
   AT91C_BASE_AIC->AIC_SMR[AT91C_ID_EMAC] = AT91C_AIC_SRCTYPE_INT_HIGH_LEVEL | AT91C_AIC_PRIOR_LOWEST;
   AT91C_BASE_AIC->AIC_SVR[AT91C_ID_EMAC] = (uint32_t) emacIrqWrapper;

   //Clear EMAC interrupt flag
   AT91C_BASE_AIC->AIC_ICCR = (1 << AT91C_ID_EMAC);

   //Enable the EMAC to transmit and receive data
   AT91C_BASE_EMAC->EMAC_NCR |= AT91C_EMAC_TE | AT91C_EMAC_RE;

   //Force the TCP/IP stack to check the link state
   osSetEvent(&interface->nicRxEvent);
   //SAM9263 Ethernet MAC is now ready to send
   osSetEvent(&interface->nicTxEvent);

   //Successful initialization
   return NO_ERROR;
}

//SAM9263-EK evaluation board?
#if defined(USE_SAM9263_EK)

/**
 * @brief GPIO configuration
 * @param[in] interface Underlying network interface
 **/

void sam9263EthInitGpio(NetInterface *interface)
{
   //Enable PIO peripheral clocks
   AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_PIOA) | (1 << AT91C_ID_PIOCDE);

   //Disable pull-up resistors on RMII pins
   AT91C_BASE_PIOC->PIO_PPUDR = AT91C_EMAC_RMII_MASK_C;
   AT91C_BASE_PIOE->PIO_PPUDR = AT91C_EMAC_RMII_MASK_E;
   //Disable interrupts-on-change
   AT91C_BASE_PIOC->PIO_IDR = AT91C_EMAC_RMII_MASK_C;
   AT91C_BASE_PIOE->PIO_IDR = AT91C_EMAC_RMII_MASK_E;
   //Assign RMII pins to to the relevant peripheral function
   AT91C_BASE_PIOC->PIO_BSR = AT91C_EMAC_RMII_MASK_C;
   AT91C_BASE_PIOE->PIO_ASR = AT91C_EMAC_RMII_MASK_E;
   //Disable the PIO from controlling the corresponding pins
   AT91C_BASE_PIOC->PIO_PDR = AT91C_EMAC_RMII_MASK_C;
   AT91C_BASE_PIOE->PIO_PDR = AT91C_EMAC_RMII_MASK_E;

   //Select RMII operation mode and enable transceiver clock
   AT91C_BASE_EMAC->EMAC_USRIO = AT91C_EMAC_CLKEN | AT91C_EMAC_RMII;
}

#endif

/**
 * @brief Initialize buffer descriptors
 * @param[in] interface Underlying network interface
 **/

void sam9263EthInitBufferDesc(NetInterface *interface)
{
   uint_t i;
   uint32_t address;

   //Initialize TX buffer descriptors
   for(i = 0; i < SAM9263_ETH_TX_BUFFER_COUNT; i++)
   {
      //Calculate the address of the current TX buffer
      address = (uint32_t) txBuffer[i];
      //Write the address to the descriptor entry
      txBufferDesc[i].address = address;
      //Initialize status field
      txBufferDesc[i].status = AT91C_EMAC_TX_USED;
   }

   //Mark the last descriptor entry with the wrap flag
   txBufferDesc[i - 1].status |= AT91C_EMAC_TX_WRAP;
   //Initialize TX buffer index
   txBufferIndex = 0;

   //Initialize RX buffer descriptors
   for(i = 0; i < SAM9263_ETH_RX_BUFFER_COUNT; i++)
   {
      //Calculate the address of the current RX buffer
      address = (uint32_t) rxBuffer[i];
      //Write the address to the descriptor entry
      rxBufferDesc[i].address = address & AT91C_EMAC_RX_ADDRESS;
      //Clear status field
      rxBufferDesc[i].status = 0;
   }

   //Mark the last descriptor entry with the wrap flag
   rxBufferDesc[i - 1].address |= AT91C_EMAC_RX_WRAP;
   //Initialize RX buffer index
   rxBufferIndex = 0;

   //Start location of the TX descriptor list
   AT91C_BASE_EMAC->EMAC_TBQP = (uint32_t) txBufferDesc;
   //Start location of the RX descriptor list
   AT91C_BASE_EMAC->EMAC_RBQP = (uint32_t) rxBufferDesc;
}

/**
 * @brief SAM9263 Ethernet MAC timer handler
 *
 * This routine is periodically called by the TCP/IP stack to
 * handle periodic operations such as polling the link state
 *
 * @param[in] interface Underlying network interface
 **/

void sam9263EthTick(NetInterface *interface)
{
   //Handle periodic operations
   interface->phyDriver->tick(interface);
}

/**
 * @brief Enable interrupts
 * @param[in] interface Underlying network interface
 **/

void sam9263EthEnableIrq(NetInterface *interface)
{
   //Enable Ethernet MAC interrupts
   AT91C_BASE_AIC->AIC_IECR = (1 << AT91C_ID_EMAC);
   //Enable Ethernet PHY interrupts
   interface->phyDriver->enableIrq(interface);
}

/**
 * @brief Disable interrupts
 * @param[in] interface Underlying network interface
 **/

void sam9263EthDisableIrq(NetInterface *interface)
{
   //Disable Ethernet MAC interrupts
   AT91C_BASE_AIC->AIC_IDCR = (1 << AT91C_ID_EMAC);
   //Disable Ethernet PHY interrupts
   interface->phyDriver->disableIrq(interface);
}

/**
 * @brief SAM9263 Ethernet MAC interrupt service routine
 **/

void sam9263EthIrqHandler(void)
{
   bool_t flag;
   volatile uint32_t isr;
   volatile uint32_t tsr;
   volatile uint32_t rsr;

   //Enter interrupt service routine
   osEnterIsr();

   //This flag will be set if a higher priority task must be woken
   flag = FALSE;

   //Each time the software reads EMAC_ISR, it has to check the
   //contents of EMAC_TSR, EMAC_RSR and EMAC_NSR
   isr = AT91C_BASE_EMAC->EMAC_ISR;
   tsr = AT91C_BASE_EMAC->EMAC_TSR;
   rsr = AT91C_BASE_EMAC->EMAC_RSR;

   //A packet has been transmitted?
   if(tsr & (AT91C_EMAC_UND | AT91C_EMAC_COMP | AT91C_EMAC_BEX |
      AT91C_EMAC_TGO | AT91C_EMAC_RLES | AT91C_EMAC_COL | AT91C_EMAC_UBR))
   {
      //Only clear TSR flags that are currently set
      AT91C_BASE_EMAC->EMAC_TSR = tsr;

      //Check whether the TX buffer is available for writing
      if(txBufferDesc[txBufferIndex].status & AT91C_EMAC_TX_USED)
      {
         //Notify the user that the transmitter is ready to send
         flag |= osSetEventFromIsr(&nicDriverInterface->nicTxEvent);
      }
   }
   //A packet has been received?
   if(rsr & (AT91C_EMAC_OVR | AT91C_EMAC_REC | AT91C_EMAC_BNA))
   {
      //Notify the user that a packet has been received
      flag |= osSetEventFromIsr(&nicDriverInterface->nicRxEvent);
   }

   //Write AIC_EOICR register before exiting
   AT91C_BASE_AIC->AIC_EOICR = 0;

   //Leave interrupt service routine
   osExitIsr(flag);
}

/**
 * @brief SAM9263 Ethernet MAC event handler
 * @param[in] interface Underlying network interface
 **/

void sam9263EthEventHandler(NetInterface *interface)
{
   uint32_t rsr;
   uint_t length;
   bool_t linkStateChange;

   //Read receive status
   rsr = AT91C_BASE_EMAC->EMAC_RSR;

   //PHY event is pending?
   if(interface->phyEvent)
   {
      //Acknowledge the event by clearing the flag
      interface->phyEvent = FALSE;
      //Handle PHY specific events
      linkStateChange = interface->phyDriver->eventHandler(interface);

      //Check whether the link state has changed?
      if(linkStateChange)
      {
         //Set speed and duplex mode for proper operation
         if(interface->linkState)
         {
            //Read network configuration register
            uint32_t config = AT91C_BASE_EMAC->EMAC_NCFGR;

            //10BASE-T or 100BASE-TX operation mode?
            if(interface->speed100)
               config |= AT91C_EMAC_SPD;
            else
               config &= ~AT91C_EMAC_SPD;

            //Half-duplex or full-duplex mode?
            if(interface->fullDuplex)
               config |= AT91C_EMAC_FD;
            else
               config &= ~AT91C_EMAC_FD;

            //Write configuration value back to NCFGR register
            AT91C_BASE_EMAC->EMAC_NCFGR = config;
         }

         //Process link state change event
         nicNotifyLinkChange(interface);
      }
   }

   //Packet received?
   if(rsr & (AT91C_EMAC_OVR | AT91C_EMAC_REC | AT91C_EMAC_BNA))
   {
      //Only clear RSR flags that are currently set
      AT91C_BASE_EMAC->EMAC_RSR = rsr;

      //Process all the pending packets
      while(1)
      {
         //Check whether a packet has been received
         length = sam9263EthReceivePacket(interface, interface->ethFrame, ETH_MAX_FRAME_SIZE);
         //No packet is pending in the receive buffer?
         if(!length) break;
         //Pass the packet to the upper layer
         nicProcessPacket(interface, interface->ethFrame, length);
      }
   }
}

/**
 * @brief Configure multicast MAC address filtering
 * @param[in] interface Underlying network interface
 * @return Error code
 **/

error_t sam9263EthSetMacFilter(NetInterface *interface)
{
   uint_t i;
   uint_t j;
   uint32_t hashTable[2];

   //Debug message
   TRACE_DEBUG("Updating SAM9263 hash table...\r\n");

   //Clear hash table
   hashTable[0] = 0;
   hashTable[1] = 0;

   //The MAC filter table contains the multicast MAC addresses
   //to accept when receiving an Ethernet frame
   for(i = 0; i < interface->macFilterSize; i++)
   {
      //Point to the current address
      MacAddr *addr = &interface->macFilter[i].addr;
      //Reset hash value
      uint_t hashIndex = 0;

      //Apply the hash function
      for(j = 0; j < 48; j += 6)
      {
         //Calculate the shift count
         uint_t n = j / 8;
         uint_t m = j % 8;

         //Update hash value
         if(!m)
            hashIndex ^= addr->b[n];
         else
            hashIndex ^= (addr->b[n] >> m) | (addr->b[n + 1] << (8 - m));
      }

      //The hash value is reduced to a 6-bit index
      hashIndex &= 0x3F;
      //Update hash table contents
      hashTable[hashIndex / 32] |= (1 << (hashIndex % 32));
   }

   //Write the hash table
   AT91C_BASE_EMAC->EMAC_HRB = hashTable[0];
   AT91C_BASE_EMAC->EMAC_HRT = hashTable[1];

   //Debug message
   TRACE_DEBUG("  HRB = %08" PRIX32 "\r\n", AT91C_BASE_EMAC->EMAC_HRB);
   TRACE_DEBUG("  HRT = %08" PRIX32 "\r\n", AT91C_BASE_EMAC->EMAC_HRT);

   //Successful processing
   return NO_ERROR;
}

/**
 * @brief Send a packet
 * @param[in] interface Underlying network interface
 * @param[in] buffer Multi-part buffer containing the data to send
 * @param[in] offset Offset to the first data byte
 * @return Error code
 **/

error_t sam9263EthSendPacket(NetInterface *interface,
   const NetBuffer *buffer, size_t offset)
{
   //Retrieve the length of the packet
   size_t length = netBufferGetLength(buffer) - offset;

   //Check the frame length
   if(length > SAM9263_ETH_TX_BUFFER_SIZE)
   {
      //The transmitter can accept another packet
      osSetEvent(&interface->nicTxEvent);
      //Report an error
      return ERROR_INVALID_LENGTH;
   }

   //Make sure the current buffer is available for writing
   if(!(txBufferDesc[txBufferIndex].status & AT91C_EMAC_TX_USED))
      return ERROR_FAILURE;

   //Copy user data to the transmit buffer
   netBufferRead(txBuffer[txBufferIndex], buffer, offset, length);

   //Set the necessary flags in the descriptor entry
   if(txBufferIndex < (SAM9263_ETH_TX_BUFFER_COUNT - 1))
   {
      //Write the status word
      txBufferDesc[txBufferIndex].status =
         AT91C_EMAC_TX_LAST | (length & AT91C_EMAC_TX_LENGTH);

      //Point to the next buffer
      txBufferIndex++;
   }
   else
   {
      //Write the status word
      txBufferDesc[txBufferIndex].status = AT91C_EMAC_TX_WRAP |
         AT91C_EMAC_TX_LAST | (length & AT91C_EMAC_TX_LENGTH);

      //Wrap around
      txBufferIndex = 0;
   }

   //Set the TSTART bit to initiate transmission
   AT91C_BASE_EMAC->EMAC_NCR |= AT91C_EMAC_TSTART;

   //Check whether the next buffer is available for writing
   if(txBufferDesc[txBufferIndex].status & AT91C_EMAC_TX_USED)
   {
      //The transmitter can accept another packet
      osSetEvent(&interface->nicTxEvent);
   }

   //Successful processing
   return NO_ERROR;
}

/**
 * @brief Receive a packet
 * @param[in] interface Underlying network interface
 * @param[out] buffer Buffer where to store the incoming data
 * @param[in] size Maximum number of bytes that can be received
 * @return Number of bytes that have been received
 **/

uint_t sam9263EthReceivePacket(NetInterface *interface,
   uint8_t *buffer, size_t size)
{
   uint_t i;
   uint_t j;
   uint_t n;
   uint_t index;

   //Indexes of SOF and EOF
   uint_t sofIndex = UINT_MAX;
   uint_t eofIndex = UINT_MAX;

   //Total number of bytes received
   uint_t length = 0;

   //Search for SOF and EOF flags
   for(i = 0; i < SAM9263_ETH_RX_BUFFER_COUNT; i++)
   {
      //Point to the current descriptor
      index = rxBufferIndex + i;
      //Wrap around to the beginning of the buffer if necessary
      if(index >= SAM9263_ETH_RX_BUFFER_COUNT)
         index -= SAM9263_ETH_RX_BUFFER_COUNT;

      //No more entries to process?
      if(!(rxBufferDesc[index].address & AT91C_EMAC_RX_OWNERSHIP))
      {
         break;
      }
      //A valid SOF has been found?
      if(rxBufferDesc[index].status & AT91C_EMAC_RX_SOF)
      {
         //Save the position of the SOF
         sofIndex = i;
      }
      //A valid EOF has been found?
      if((rxBufferDesc[index].status & AT91C_EMAC_RX_EOF) && sofIndex != UINT_MAX)
      {
         //Save the position of the EOF
         eofIndex = i;
         //Retrieve the length of the frame
         n = rxBufferDesc[index].status & AT91C_EMAC_RX_LENGTH;
         //Limit the number of data to read
         size = MIN(n, size);
         //Stop processing since we have reached the end of the frame
         break;
      }
   }

   //Determine the number of entries to process
   if(eofIndex != UINT_MAX)
      j = eofIndex + 1;
   else if(sofIndex != UINT_MAX)
      j = sofIndex;
   else
      j = i;

   //Process incoming frame
   for(i = 0; i < j; i++)
   {
      //Any data to copy from current buffer?
      if(eofIndex != UINT_MAX && i >= sofIndex && i <= eofIndex)
      {
         //Calculate the number of bytes to read at a time
         n = MIN(size, SAM9263_ETH_RX_BUFFER_SIZE);
         //Copy data from receive buffer
         memcpy(buffer, rxBuffer[rxBufferIndex], n);
         //Advance data pointer
         buffer += n;
         //Update byte counters
         length += n;
         size -= n;
      }

      //Mark the current buffer as free
      rxBufferDesc[rxBufferIndex].address &= ~AT91C_EMAC_RX_OWNERSHIP;

      //Point to the following entry
      rxBufferIndex++;
      //Wrap around to the beginning of the buffer if necessary
      if(rxBufferIndex >= SAM9263_ETH_RX_BUFFER_COUNT)
         rxBufferIndex = 0;
   }

   //Return the number of bytes that have been received
   return length;
}

/**
 * @brief Write PHY register
 * @param[in] phyAddr PHY address
 * @param[in] regAddr Register address
 * @param[in] data Register value
 **/

void sam9263EthWritePhyReg(uint8_t phyAddr, uint8_t regAddr, uint16_t data)
{
   //Set up a write operation
   uint32_t value = AT91C_EMAC_SOF_01 | AT91C_EMAC_RW_01 | AT91C_EMAC_CODE_10;
   //PHY address
   value |= (phyAddr << 23) & AT91C_EMAC_PHYA;
   //Register address
   value |= (regAddr << 18) & AT91C_EMAC_REGA;
   //Register value
   value |= data & AT91C_EMAC_DATA;

   //Start a write operation
   AT91C_BASE_EMAC->EMAC_MAN = value;
   //Wait for the write to complete
   while(!(AT91C_BASE_EMAC->EMAC_NSR & AT91C_EMAC_IDLE));
}

/**
 * @brief Read PHY register
 * @param[in] phyAddr PHY address
 * @param[in] regAddr Register address
 * @return Register value
 **/

uint16_t sam9263EthReadPhyReg(uint8_t phyAddr, uint8_t regAddr)
{
   //Set up a read operation
   uint32_t value = AT91C_EMAC_SOF_01 | AT91C_EMAC_RW_10 | AT91C_EMAC_CODE_10;
   //PHY address
   value |= (phyAddr << 23) & AT91C_EMAC_PHYA;
   //Register address
   value |= (regAddr << 18) & AT91C_EMAC_REGA;

   //Start a read operation
   AT91C_BASE_EMAC->EMAC_MAN = value;
   //Wait for the read to complete
   while(!(AT91C_BASE_EMAC->EMAC_NSR & AT91C_EMAC_IDLE));

   //Return PHY register contents
   return AT91C_BASE_EMAC->EMAC_MAN & AT91C_EMAC_DATA;
}


text:
/*
 * In order to solve the single number problem, we need to calculate the number
 * of times each number appears in the array. While we could loop the array for
 * each number, this will result in the O(n^2) performance. Arguably, the smarter
 * way would be to sort the array, which will enable us to calculate the frequency
 * of each number in O(n) time.
 */

#include <stdlib.h>

int compareIntegers(const int *lhs, const int *rhs) {
    return *lhs - *rhs;
}

int singleNumber(int* nums, int numsSize) {
    if (numsSize > 1) {
        // Sort the array to enable frequency counting in O(n) time.
        qsort(nums, numsSize, sizeof(nums[0]), compareIntegers);

        for (int index = 1, count = 1; index < numsSize; ++count, ++index) {
            // Is this a duplicate of the previous value?
            if (nums[index] != nums[index - 1]) {
                // If it's not a duplicate, is it single?
                if (count == 1) {
                    return nums[index - 1];
                }
                count = 0;
            }
        }

        return nums[numsSize - 1];
    } else if (numsSize == 1) {
        return nums[0];
    }
    return 0;
}


text:
package plugins

import (
	"reflect"
	"testing"
)

func TestNewEvent(t *testing.T) {
	tests := []struct {
		description string
		matcher     EventMatcher
	}{
		{"", FalseEvent{}},
		{"labeled:something", LabelEvent{Label: "something"}},
		{"unlabeled:something", UnlabelEvent{Label: "something"}},
		{"merged", MergeEvent{}},
		{"closed", CloseEvent{}},
		{"reopened", ReopenEvent{}},
		{"opened", OpenEvent{}},
	}

	for _, test := range tests {
		got := NewEventMatcher(test.description)
		want := test.matcher
		if !reflect.DeepEqual(got, want) {
			t.Errorf("NewEvent(%s) = %#v, want %#v",
				test.description, got, want)
		}
	}
}


text:
package inject

import (
	"fmt"
	"reflect"
)

type provider struct {
	constructor interface{}
	argPtrs     []interface{}
}

// NewProvider specifies how to construct a value given its constructor function and argument pointers
func NewProvider(constructor interface{}, argPtrs ...interface{}) Provider {
	fnValue := reflect.ValueOf(constructor)
	if fnValue.Kind() != reflect.Func {
		panic(fmt.Sprintf("constructor (%v) is not a function, found %v", fnValue, fnValue.Kind()))
	}

	fnType := reflect.TypeOf(constructor)
	if fnType.NumOut() != 1 {
		panic(fmt.Sprintf("constructor must have exactly 1 return value, found %v", fnType.NumOut()))
	}

	argCount := fnType.NumIn()
	if argCount != len(argPtrs) {
		panic(fmt.Sprintf("argPtrs (%d) must match constructor arguments (%d)", len(argPtrs), argCount))
	}

	for i, argPtr := range argPtrs {
		if reflect.TypeOf(argPtr).Kind() != reflect.Ptr {
			panic(fmt.Sprintf("argPtrs must all be pointers, found %v", reflect.TypeOf(argPtr)))
		}
		if reflect.ValueOf(argPtr).Elem().Kind() != fnType.In(i).Kind() {
			panic("argPtrs must match constructor argument types")
		}
	}

	return provider{
		constructor: constructor,
		argPtrs:     argPtrs,
	}
}

// Provide returns the result of executing the constructor with argument values resolved from a dependency graph
func (p provider) Provide(g Graph) reflect.Value {
	fnType := reflect.TypeOf(p.constructor)

	argCount := fnType.NumIn()
	args := make([]reflect.Value, argCount, argCount)
	for i := 0; i < argCount; i++ {
		arg := g.Resolve(p.argPtrs[i])
		argType := arg.Type()
		inType := fnType.In(i)
		if !argType.AssignableTo(inType) {
			if !argType.ConvertibleTo(inType) {
				panic(fmt.Sprintf(
					"arg %d of type %q cannot be assigned or converted to type %q for provider constructor (%s)",
					i, argType, inType, p.constructor,
				))
			}
			arg = arg.Convert(inType)
		}
		args[i] = arg
	}

	return reflect.ValueOf(p.constructor).Call(args)[0]
}

// Type returns the type of value to expect from Provide
func (p provider) ReturnType() reflect.Type {
	return reflect.TypeOf(p.constructor).Out(0)
}

// String returns a multiline string representation of the provider
func (p provider) String() string {
	return fmt.Sprintf("&provider{\n%s,\n%s\n}",
		indent(fmt.Sprintf("constructor: %s", reflect.TypeOf(p.constructor)), 1),
		indent(fmt.Sprintf("argPtrs: %s", p.fmtArgPtrs()), 1),
	)
}

func (p provider) fmtArgPtrs() string {
	b := make([]string, len(p.argPtrs), len(p.argPtrs))
	for i, argPtr := range p.argPtrs {
		b[i] = ptrString(argPtr)
	}
	return arrayString(b)
}


text:
create index roomstate_name on roomstate(name asc);
create index roomstate_at on roomstate(at asc);
create index outdoor_name on outdoor(name asc);
create index outdoor_at on outdoor(at asc);
create index securityevents_at on securityevents(at asc);


text:
 - Install `wd` package from npm
 - Install [Selenium Stand-alone Server](http://docs.seleniumhq.org/download/) [Download](http://selenium.googlecode.com/files/selenium-server-standalone-2.33.0.jar)
 - Start Selenium server ( open the `.jar` file )
 - `node test/basic-test.js`

Note: The basic tests use the `firefox` browser, so you will need to have that installed.


text:
/*
 * Benchmark tracing utility
 */
#include <linux/module.h>

#ifndef TB_TRACE_H

#define TB_TRACE_H

#define TB_MALLOC(size) kmalloc(size, GFP_KERNEL);
#define TB_FREE         kfree
#define TB_PRINTF       printk
#define TB_ID           current->pid

#endif


text:
package com.sonaive.v2ex.util;

import android.accounts.Account;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.sonaive.v2ex.R;

import static com.sonaive.v2ex.util.LogUtils.LOGD;
import static com.sonaive.v2ex.util.LogUtils.makeLogTag;
/**
 * Account and login utilities. This class manages a local shared preferences object
 * that stores which account is currently active.
 *
 * Created by liutao on 12/11/14.
 */
public class AccountUtils {
    private static final String TAG = makeLogTag(AccountUtils.class);

    private static final String PREF_ACTIVE_ACCOUNT = "chosen_account";

    // these names are are prefixes; the account is appended to them
    private static final String PREFIX_PREF_ID = "id_";
    private static final String PREFIX_PREF_AVATAR_MINI = "avatar_mini_";
    private static final String PREFIX_PREF_AVATAR_NORMAL = "avatar_mini_";
    private static final String PREFIX_PREF_AVATAR_LARGE = "avatar_large_";

    private static SharedPreferences getSharedPreferences(final Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context);
    }

    public static boolean hasActiveAccount(final Context context) {
        return !TextUtils.isEmpty(getActiveAccountName(context));
    }

    public static String getActiveAccountName(final Context context) {
        SharedPreferences sp = getSharedPreferences(context);
        return sp.getString(PREF_ACTIVE_ACCOUNT, null);
    }

    public static Account getActiveAccount(final Context context) {
        String account = getActiveAccountName(context);
        String accountType = context.getResources().getString(R.string.authority);
        if (account != null) {
            return new Account(account, accountType);
        } else {
            String defaultName = context.getResources().getString(R.string.app_name);
            return new Account(defaultName, accountType);
        }
    }

    public static boolean setActiveAccount(final Context context, final String accountName) {
        LOGD(TAG, "Set active account to: " + accountName);
        SharedPreferences sp = getSharedPreferences(context);
        sp.edit().putString(PREF_ACTIVE_ACCOUNT, accountName).commit();
        return true;
    }

    private static String makeAccountSpecificPrefKey(Context ctx, String prefix) {
        return hasActiveAccount(ctx) ? makeAccountSpecificPrefKey(getActiveAccountName(ctx),
                prefix) : null;
    }

    private static String makeAccountSpecificPrefKey(String accountName, String prefix) {
        return prefix + accountName;
    }

    public static void setAccountId(final Context context, final String accountName, final String id) {
        SharedPreferences sp = getSharedPreferences(context);
        sp.edit().putString(makeAccountSpecificPrefKey(accountName, PREFIX_PREF_ID),
                id).commit();
    }

    public static String getAccountId(final Context context) {
        SharedPreferences sp = getSharedPreferences(context);
        return hasActiveAccount(context) ? sp.getString(makeAccountSpecificPrefKey(context,
                PREFIX_PREF_ID), null) : null;
    }

    public static void setAvatarMini(final Context context, final String accountName, final String imageUrl) {
        SharedPreferences sp = getSharedPreferences(context);
        sp.edit().putString(makeAccountSpecificPrefKey(accountName, PREFIX_PREF_AVATAR_MINI),
                imageUrl).commit();
    }

    public static String getAvatarMini(final Context context) {
        SharedPreferences sp = getSharedPreferences(context);
        return hasActiveAccount(context) ? sp.getString(makeAccountSpecificPrefKey(context,
                PREFIX_PREF_AVATAR_MINI), null) : null;
    }

    public static void setAvatarNormal(final Context context, final String accountName, final String imageUrl) {
        SharedPreferences sp = getSharedPreferences(context);
        sp.edit().putString(makeAccountSpecificPrefKey(accountName, PREFIX_PREF_AVATAR_NORMAL),
                imageUrl).commit();
    }

    public static String getAvatarNormal(final Context context) {
        SharedPreferences sp = getSharedPreferences(context);
        return hasActiveAccount(context) ? sp.getString(makeAccountSpecificPrefKey(context,
                PREFIX_PREF_AVATAR_NORMAL), null) : null;
    }

    public static void setAvatarLarge(final Context context, final String accountName, final String imageUrl) {
        SharedPreferences sp = getSharedPreferences(context);
        sp.edit().putString(makeAccountSpecificPrefKey(accountName, PREFIX_PREF_AVATAR_LARGE),
                imageUrl).commit();
    }

    public static String getAvatarLarge(final Context context) {
        SharedPreferences sp = getSharedPreferences(context);
        return hasActiveAccount(context) ? sp.getString(makeAccountSpecificPrefKey(context,
                PREFIX_PREF_AVATAR_LARGE), null) : null;
    }
}


text:
package org.moserp.customer.domain;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.moserp.common.annotations.ValueListKey;
import org.moserp.common.domain.DependentEntity;
import org.moserp.common.domain.Price;
import org.moserp.product.domain.ProductInstance;

@Slf4j
@Data
@ToString(callSuper = false)
@EqualsAndHashCode(callSuper = false)
public class OrderItem extends DependentEntity {

    private Integer amount;
    private Price price;
    private ProductInstance productInstance;

    @ValueListKey("Currency")
    private String currency;

    @ValueListKey("OrderItemStatus")
    private String status = "CREATED";

}


text:
<link rel="import" href="../../../bower_components/polymer/polymer.html">
<link rel="import" href="../../../bower_components/paper-toggle-button/paper-toggle-button.html">
<link rel="import" href="../../../bower_components/paper-icon-button/paper-icon-button.html">

<dom-module id="ha-entity-toggle">
  <style>
    paper-icon-button {
      transition: color .5s;
    }
    paper-icon-button[state-active] {
      color: var(--default-primary-color);
    }
    paper-toggle-button {
      cursor: pointer;
      --paper-toggle-button-label-spacing: 0;
    }
  </style>
  <template>
    <template is='dom-if' if='[[stateObj.attributes.assumed_state]]'>
      <paper-icon-button icon="mdi:flash-off" on-tap="turnOff" state-active$='[[!isOn]]'></paper-icon-button>
      <paper-icon-button icon="mdi:flash" on-tap="turnOn" state-active$='[[isOn]]'></paper-icon-button>
    </template>
    <template is='dom-if' if='[[!stateObj.attributes.assumed_state]]'>
      <paper-toggle-button class='self-center'
        checked="[[toggleChecked]]"
        on-change="toggleChanged"></paper-toggle-button>
    </template>
  </template>
</dom-module>