text:
<?php

namespace Doctrine\ORM\Tools;

use Doctrine\ORM\Mapping\ClassMetadataInfo,
    Doctrine\Common\Util\Inflector,
    Doctrine\DBAL\Types\Type;

/**
 * Generic class used to generate PHP5 entity classes from ClassMetadataInfo instances
 *
 *     [php]
 *     $classes = $em->getClassMetadataFactory()->getAllMetadata();
 *
 *     $generator = new \Doctrine\ORM\Tools\EntityGenerator();
 *     $generator->setGenerateAnnotations(true);
 *     $generator->setGenerateStubMethods(true);
 *     $generator->setRegenerateEntityIfExists(false);
 *     $generator->setUpdateEntityIfExists(true);
 *     $generator->generate($classes, '/path/to/generate/entities');
 *
 *
 * @link    www.doctrine-project.org
 * @since   2.0
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
 */
class EntityGenerator
{
    /**
     * Specifies class fields should be protected
     */
    const FIELD_VISIBLE_PROTECTED = 'protected';

    /**
     * Specifies class fields should be private
     */
    const FIELD_VISIBLE_PRIVATE = 'private';

    /**
     * @var bool
     */
    private $backupExisting = true;

    /**
     * The extension to use for written php files
     *
     * @var string
     */
    private $extension = '.php';

    /**
     * Whether or not the current ClassMetadataInfo instance is new or old
     *
     * @var boolean
     */
    private $isNew = true;

    /**
     * @var array
     */
    private $staticReflection = array();

    /**
     * Number of spaces to use for indention in generated code
     */
    private $numSpaces = 4;

    /**
     * The actual spaces to use for indention
     *
     * @var string
     */
    private $spaces = '    ';

    /**
     * The class all generated entities should extend
     *
     * @var string
     */
    private $classToExtend;

    /**
     * Whether or not to generation annotations
     *
     * @var boolean
     */
    private $generateAnnotations = false;

    /**
     * @var string
     */
    private $annotationsPrefix = '';

    /**
     * Whether or not to generated sub methods
     *
     * @var boolean
     */
    private $generateEntityStubMethods = false;

    /**
     * Whether or not to update the entity class if it exists already
     *
     * @var boolean
     */
    private $updateEntityIfExists = false;

    /**
     * Whether or not to re-generate entity class if it exists already
     *
     * @var boolean
     */
    private $regenerateEntityIfExists = false;

    /**
     * @var boolean
     */
    private $fieldVisibility = 'private';

    /**
     * Hash-map for handle types
     *
     * @var array
     */
    private $typeAlias = array(
        Type::DATETIMETZ    => '\DateTime',
        Type::DATETIME      => '\DateTime',
        Type::DATE          => '\DateTime',
        Type::TIME          => '\DateTime',
        Type::OBJECT        => '\stdClass',
        Type::BIGINT        => 'integer',
        Type::SMALLINT      => 'integer',
        Type::TEXT          => 'string',
        Type::BLOB          => 'string',
        Type::DECIMAL       => 'string',
        Type::JSON_ARRAY    => 'array',
        Type::SIMPLE_ARRAY  => 'array',
    );

    /**
     * @var array Hash-map to handle generator types string.
     */
    protected static $generatorStrategyMap = array(
        ClassMetadataInfo::GENERATOR_TYPE_AUTO      => 'AUTO',
        ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE  => 'SEQUENCE',
        ClassMetadataInfo::GENERATOR_TYPE_TABLE     => 'TABLE',
        ClassMetadataInfo::GENERATOR_TYPE_IDENTITY  => 'IDENTITY',
        ClassMetadataInfo::GENERATOR_TYPE_NONE      => 'NONE',
        ClassMetadataInfo::GENERATOR_TYPE_UUID      => 'UUID',
        ClassMetadataInfo::GENERATOR_TYPE_CUSTOM    => 'CUSTOM'
    );

    /**
     * @var array Hash-map to handle the change tracking policy string.
     */
    protected static $changeTrackingPolicyMap = array(
        ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT  => 'DEFERRED_IMPLICIT',
        ClassMetadataInfo::CHANGETRACKING_DEFERRED_EXPLICIT  => 'DEFERRED_EXPLICIT',
        ClassMetadataInfo::CHANGETRACKING_NOTIFY             => 'NOTIFY',
    );

    /**
     * @var array Hash-map to handle the inheritance type string.
     */
    protected static $inheritanceTypeMap = array(
        ClassMetadataInfo::INHERITANCE_TYPE_NONE            => 'NONE',
        ClassMetadataInfo::INHERITANCE_TYPE_JOINED          => 'JOINED',
        ClassMetadataInfo::INHERITANCE_TYPE_SINGLE_TABLE    => 'SINGLE_TABLE',
        ClassMetadataInfo::INHERITANCE_TYPE_TABLE_PER_CLASS => 'TABLE_PER_CLASS',
    );

    /**
     * @var string
     */
    private static $classTemplate =
'<?php

<namespace>

use Doctrine\ORM\Mapping as ORM;

<entityAnnotation>
<entityClassName>
{
<entityBody>
}
';

    /**
     * @var string
     */
    private static $getMethodTemplate =
'/**
 * <description>
 *
 * @return <variableType>
 */
public function <methodName>()
{
<spaces>return $this-><fieldName>;
}';

    /**
     * @var string
     */
    private static $setMethodTemplate =
'/**
 * <description>
 *
 * @param <variableType>$<variableName>
 * @return <entity>
 */
public function <methodName>(<methodTypeHint>$<variableName><variableDefault>)
{
<spaces>$this-><fieldName> = $<variableName>;

<spaces>return $this;
}';

    /**
     * @var string
     */
    private static $addMethodTemplate =
'/**
 * <description>
 *
 * @param <variableType>$<variableName>
 * @return <entity>
 */
public function <methodName>(<methodTypeHint>$<variableName>)
{
<spaces>$this-><fieldName>[] = $<variableName>;

<spaces>return $this;
}';

    /**
     * @var string
     */
    private static $removeMethodTemplate =
'/**
 * <description>
 *
 * @param <variableType>$<variableName>
 */
public function <methodName>(<methodTypeHint>$<variableName>)
{
<spaces>$this-><fieldName>->removeElement($<variableName>);
}';

    /**
     * @var string
     */
    private static $lifecycleCallbackMethodTemplate =
'/**
 * @<name>
 */
public function <methodName>()
{
<spaces>// Add your code here
}';

    /**
     * @var string
     */
    private static $constructorMethodTemplate =
'/**
 * Constructor
 */
public function __construct()
{
<spaces><collections>
}
';

    public function __construct()
    {
        if (version_compare(\Doctrine\Common\Version::VERSION, '2.2.0-DEV', '>=')) {
            $this->annotationsPrefix = 'ORM\\';
        }
    }

    /**
     * Generate and write entity classes for the given array of ClassMetadataInfo instances
     *
     * @param array $metadatas
     * @param string $outputDirectory
     * @return void
     */
    public function generate(array $metadatas, $outputDirectory)
    {
        foreach ($metadatas as $metadata) {
            $this->writeEntityClass($metadata, $outputDirectory);
        }
    }

    /**
     * Generated and write entity class to disk for the given ClassMetadataInfo instance
     *
     * @param ClassMetadataInfo $metadata
     * @param string $outputDirectory
     * @return void
     */
    public function writeEntityClass(ClassMetadataInfo $metadata, $outputDirectory)
    {
        $path = $outputDirectory . '/' . str_replace('\\', DIRECTORY_SEPARATOR, $metadata->name) . $this->extension;
        $dir = dirname($path);

        if ( ! is_dir($dir)) {
            mkdir($dir, 0777, true);
        }

        $this->isNew = !file_exists($path) || (file_exists($path) && $this->regenerateEntityIfExists);

        if ( ! $this->isNew) {
            $this->parseTokensInEntityFile(file_get_contents($path));
        } else {
            $this->staticReflection[$metadata->name] = array('properties' => array(), 'methods' => array());
        }

        if ($this->backupExisting && file_exists($path)) {
            $backupPath = dirname($path) . DIRECTORY_SEPARATOR . basename($path) . "~";
            if (!copy($path, $backupPath)) {
                throw new \RuntimeException("Attempt to backup overwritten entity file but copy operation failed.");
            }
        }

        // If entity doesn't exist or we're re-generating the entities entirely
        if ($this->isNew) {
            file_put_contents($path, $this->generateEntityClass($metadata));
        // If entity exists and we're allowed to update the entity class
        } else if ( ! $this->isNew && $this->updateEntityIfExists) {
            file_put_contents($path, $this->generateUpdatedEntityClass($metadata, $path));
        }
    }

    /**
     * Generate a PHP5 Doctrine 2 entity class from the given ClassMetadataInfo instance
     *
     * @param ClassMetadataInfo $metadata
     * @return string $code
     */
    public function generateEntityClass(ClassMetadataInfo $metadata)
    {
        $placeHolders = array(
            '<namespace>',
            '<entityAnnotation>',
            '<entityClassName>',
            '<entityBody>'
        );

        $replacements = array(
            $this->generateEntityNamespace($metadata),
            $this->generateEntityDocBlock($metadata),
            $this->generateEntityClassName($metadata),
            $this->generateEntityBody($metadata)
        );

        $code = str_replace($placeHolders, $replacements, self::$classTemplate);
        return str_replace('<spaces>', $this->spaces, $code);
    }

    /**
     * Generate the updated code for the given ClassMetadataInfo and entity at path
     *
     * @param ClassMetadataInfo $metadata
     * @param string $path
     * @return string $code;
     */
    public function generateUpdatedEntityClass(ClassMetadataInfo $metadata, $path)
    {
        $currentCode = file_get_contents($path);

        $body = $this->generateEntityBody($metadata);
        $body = str_replace('<spaces>', $this->spaces, $body);
        $last = strrpos($currentCode, '}');

        return substr($currentCode, 0, $last) . $body . (strlen($body) > 0 ? "\n" : ''). "}";
    }

    /**
     * Set the number of spaces the exported class should have
     *
     * @param integer $numSpaces
     * @return void
     */
    public function setNumSpaces($numSpaces)
    {
        $this->spaces = str_repeat(' ', $numSpaces);
        $this->numSpaces = $numSpaces;
    }

    /**
     * Set the extension to use when writing php files to disk
     *
     * @param string $extension
     * @return void
     */
    public function setExtension($extension)
    {
        $this->extension = $extension;
    }

    /**
     * Set the name of the class the generated classes should extend from
     *
     * @return void
     */
    public function setClassToExtend($classToExtend)
    {
        $this->classToExtend = $classToExtend;
    }

    /**
     * Set whether or not to generate annotations for the entity
     *
     * @param bool $bool
     * @return void
     */
    public function setGenerateAnnotations($bool)
    {
        $this->generateAnnotations = $bool;
    }

    /**
     * Set the class fields visibility for the entity (can either be private or protected)
     *
     * @param bool $bool
     * @return void
     */
    public function setFieldVisibility($visibility)
    {
        if ($visibility !== self::FIELD_VISIBLE_PRIVATE && $visibility !== self::FIELD_VISIBLE_PROTECTED) {
            throw new \InvalidArgumentException('Invalid provided visibilty (only private and protected are allowed): ' . $visibility);
        }

        $this->fieldVisibility = $visibility;
    }

    /**
     * Set an annotation prefix.
     *
     * @param string $prefix
     */
    public function setAnnotationPrefix($prefix)
    {
        $this->annotationsPrefix = $prefix;
    }

    /**
     * Set whether or not to try and update the entity if it already exists
     *
     * @param bool $bool
     * @return void
     */
    public function setUpdateEntityIfExists($bool)
    {
        $this->updateEntityIfExists = $bool;
    }

    /**
     * Set whether or not to regenerate the entity if it exists
     *
     * @param bool $bool
     * @return void
     */
    public function setRegenerateEntityIfExists($bool)
    {
        $this->regenerateEntityIfExists = $bool;
    }

    /**
     * Set whether or not to generate stub methods for the entity
     *
     * @param bool $bool
     * @return void
     */
    public function setGenerateStubMethods($bool)
    {
        $this->generateEntityStubMethods = $bool;
    }

    /**
     * Should an existing entity be backed up if it already exists?
     */
    public function setBackupExisting($bool)
    {
        $this->backupExisting = $bool;
    }

     /**
     * @param   string $type
     * @return  string
     */
    private function getType($type)
    {
        if (isset($this->typeAlias[$type])) {
            return $this->typeAlias[$type];
        }

        return $type;
    }

    private function generateEntityNamespace(ClassMetadataInfo $metadata)
    {
        if ($this->hasNamespace($metadata)) {
            return 'namespace ' . $this->getNamespace($metadata) .';';
        }
    }

    private function generateEntityClassName(ClassMetadataInfo $metadata)
    {
        return 'class ' . $this->getClassName($metadata) .
            ($this->extendsClass() ? ' extends ' . $this->getClassToExtendName() : null);
    }

    private function generateEntityBody(ClassMetadataInfo $metadata)
    {
        $fieldMappingProperties = $this->generateEntityFieldMappingProperties($metadata);
        $associationMappingProperties = $this->generateEntityAssociationMappingProperties($metadata);
        $stubMethods = $this->generateEntityStubMethods ? $this->generateEntityStubMethods($metadata) : null;
        $lifecycleCallbackMethods = $this->generateEntityLifecycleCallbackMethods($metadata);

        $code = array();

        if ($fieldMappingProperties) {
            $code[] = $fieldMappingProperties;
        }

        if ($associationMappingProperties) {
            $code[] = $associationMappingProperties;
        }

        $code[] = $this->generateEntityConstructor($metadata);

        if ($stubMethods) {
            $code[] = $stubMethods;
        }

        if ($lifecycleCallbackMethods) {
            $code[] = $lifecycleCallbackMethods;
        }

        return implode("\n", $code);
    }

    private function generateEntityConstructor(ClassMetadataInfo $metadata)
    {
        if ($this->hasMethod('__construct', $metadata)) {
            return '';
        }

        $collections = array();

        foreach ($metadata->associationMappings as $mapping) {
            if ($mapping['type'] & ClassMetadataInfo::TO_MANY) {
                $collections[] = '$this->'.$mapping['fieldName'].' = new \Doctrine\Common\Collections\ArrayCollection();';
            }
        }

        if ($collections) {
            return $this->prefixCodeWithSpaces(str_replace("<collections>", implode("\n".$this->spaces, $collections), self::$constructorMethodTemplate));
        }

        return '';
    }

    /**
     * @todo this won't work if there is a namespace in brackets and a class outside of it.
     * @param string $src
     */
    private function parseTokensInEntityFile($src)
    {
        $tokens = token_get_all($src);
        $lastSeenNamespace = "";
        $lastSeenClass = false;

        $inNamespace = false;
        $inClass = false;
        for ($i = 0; $i < count($tokens); $i++) {
            $token = $tokens[$i];
            if (in_array($token[0], array(T_WHITESPACE, T_COMMENT, T_DOC_COMMENT))) {
                continue;
            }

            if ($inNamespace) {
                if ($token[0] == T_NS_SEPARATOR || $token[0] == T_STRING) {
                    $lastSeenNamespace .= $token[1];
                } else if (is_string($token) && in_array($token, array(';', '{'))) {
                    $inNamespace = false;
                }
            }

            if ($inClass) {
                $inClass = false;
                $lastSeenClass = $lastSeenNamespace . ($lastSeenNamespace ? '\\' : '') . $token[1];
                $this->staticReflection[$lastSeenClass]['properties'] = array();
                $this->staticReflection[$lastSeenClass]['methods'] = array();
            }

            if ($token[0] == T_NAMESPACE) {
                $lastSeenNamespace = "";
                $inNamespace = true;
            } else if ($token[0] == T_CLASS) {
                $inClass = true;
            } else if ($token[0] == T_FUNCTION) {
                if ($tokens[$i+2][0] == T_STRING) {
                    $this->staticReflection[$lastSeenClass]['methods'][] = $tokens[$i+2][1];
                } else if ($tokens[$i+2] == "&" && $tokens[$i+3][0] == T_STRING) {
                    $this->staticReflection[$lastSeenClass]['methods'][] = $tokens[$i+3][1];
                }
            } else if (in_array($token[0], array(T_VAR, T_PUBLIC, T_PRIVATE, T_PROTECTED)) && $tokens[$i+2][0] != T_FUNCTION) {
                $this->staticReflection[$lastSeenClass]['properties'][] = substr($tokens[$i+2][1], 1);
            }
        }
    }

    private function hasProperty($property, ClassMetadataInfo $metadata)
    {
        if ($this->extendsClass()) {
            // don't generate property if its already on the base class.
            $reflClass = new \ReflectionClass($this->getClassToExtend());
            if ($reflClass->hasProperty($property)) {
                return true;
            }
        }

        return (
            isset($this->staticReflection[$metadata->name]) &&
            in_array($property, $this->staticReflection[$metadata->name]['properties'])
        );
    }

    private function hasMethod($method, ClassMetadataInfo $metadata)
    {
        if ($this->extendsClass()) {
            // don't generate method if its already on the base class.
            $reflClass = new \ReflectionClass($this->getClassToExtend());
            if ($reflClass->hasMethod($method)) {
                return true;
            }
        }

        return (
            isset($this->staticReflection[$metadata->name]) &&
            in_array($method, $this->staticReflection[$metadata->name]['methods'])
        );
    }

    private function hasNamespace(ClassMetadataInfo $metadata)
    {
        return strpos($metadata->name, '\\') ? true : false;
    }

    private function extendsClass()
    {
        return $this->classToExtend ? true : false;
    }

    private function getClassToExtend()
    {
        return $this->classToExtend;
    }

    private function getClassToExtendName()
    {
        $refl = new \ReflectionClass($this->getClassToExtend());

        return '\\' . $refl->getName();
    }

    private function getClassName(ClassMetadataInfo $metadata)
    {
        return ($pos = strrpos($metadata->name, '\\'))
            ? substr($metadata->name, $pos + 1, strlen($metadata->name)) : $metadata->name;
    }

    private function getNamespace(ClassMetadataInfo $metadata)
    {
        return substr($metadata->name, 0, strrpos($metadata->name, '\\'));
    }

    private function generateEntityDocBlock(ClassMetadataInfo $metadata)
    {
        $lines = array();
        $lines[] = '/**';
        $lines[] = ' * ' . $this->getClassName($metadata);

        if ($this->generateAnnotations) {
            $lines[] = ' *';

            $methods = array(
                'generateTableAnnotation',
                'generateInheritanceAnnotation',
                'generateDiscriminatorColumnAnnotation',
                'generateDiscriminatorMapAnnotation'
            );

            foreach ($methods as $method) {
                if ($code = $this->$method($metadata)) {
                    $lines[] = ' * ' . $code;
                }
            }

            if ($metadata->isMappedSuperclass) {
                $lines[] = ' * @' . $this->annotationsPrefix . 'MappedSuperClass';
            } else {
                $lines[] = ' * @' . $this->annotationsPrefix . 'Entity';
            }

            if ($metadata->customRepositoryClassName) {
                $lines[count($lines) - 1] .= '(repositoryClass="' . $metadata->customRepositoryClassName . '")';
            }

            if (isset($metadata->lifecycleCallbacks) && $metadata->lifecycleCallbacks) {
                $lines[] = ' * @' . $this->annotationsPrefix . 'HasLifecycleCallbacks';
            }
        }

        $lines[] = ' */';

        return implode("\n", $lines);
    }

    private function generateTableAnnotation($metadata)
    {
        $table = array();

        if (isset($metadata->table['schema'])) {
            $table[] = 'schema="' . $metadata->table['schema'] . '"';
        }

        if (isset($metadata->table['name'])) {
            $table[] = 'name="' . $metadata->table['name'] . '"';
        }

        if (isset($metadata->table['uniqueConstraints']) && $metadata->table['uniqueConstraints']) {
            $constraints = $this->generateTableConstraints('UniqueConstraint', $metadata->table['uniqueConstraints']);
            $table[] = 'uniqueConstraints={' . $constraints . '}';
        }

        if (isset($metadata->table['indexes']) && $metadata->table['indexes']) {
            $constraints = $this->generateTableConstraints('Index', $metadata->table['indexes']);
            $table[] = 'indexes={' . $constraints . '}';
        }

        return '@' . $this->annotationsPrefix . 'Table(' . implode(', ', $table) . ')';
    }

    private function generateTableConstraints($constraintName, $constraints)
    {
        $annotations = array();
        foreach ($constraints as $name => $constraint) {
            $columns = array();
            foreach ($constraint['columns'] as $column) {
                $columns[] = '"' . $column . '"';
            }
            $annotations[] = '@' . $this->annotationsPrefix . $constraintName . '(name="' . $name . '", columns={' . implode(', ', $columns) . '})';
        }
        return implode(', ', $annotations);
    }

    private function generateInheritanceAnnotation($metadata)
    {
        if ($metadata->inheritanceType != ClassMetadataInfo::INHERITANCE_TYPE_NONE) {
            return '@' . $this->annotationsPrefix . 'InheritanceType("'.$this->getInheritanceTypeString($metadata->inheritanceType).'")';
        }
    }

    private function generateDiscriminatorColumnAnnotation($metadata)
    {
        if ($metadata->inheritanceType != ClassMetadataInfo::INHERITANCE_TYPE_NONE) {
            $discrColumn = $metadata->discriminatorValue;
            $columnDefinition = 'name="' . $discrColumn['name']
                . '", type="' . $discrColumn['type']
                . '", length=' . $discrColumn['length'];

            return '@' . $this->annotationsPrefix . 'DiscriminatorColumn(' . $columnDefinition . ')';
        }
    }

    private function generateDiscriminatorMapAnnotation($metadata)
    {
        if ($metadata->inheritanceType != ClassMetadataInfo::INHERITANCE_TYPE_NONE) {
            $inheritanceClassMap = array();

            foreach ($metadata->discriminatorMap as $type => $class) {
                $inheritanceClassMap[] .= '"' . $type . '" = "' . $class . '"';
            }

            return '@' . $this->annotationsPrefix . 'DiscriminatorMap({' . implode(', ', $inheritanceClassMap) . '})';
        }
    }

    private function generateEntityStubMethods(ClassMetadataInfo $metadata)
    {
        $methods = array();

        foreach ($metadata->fieldMappings as $fieldMapping) {
            if ( ! isset($fieldMapping['id']) || ! $fieldMapping['id'] || $metadata->generatorType == ClassMetadataInfo::GENERATOR_TYPE_NONE) {
                if ($code = $this->generateEntityStubMethod($metadata, 'set', $fieldMapping['fieldName'], $fieldMapping['type'])) {
                    $methods[] = $code;
                }
            }

            if ($code = $this->generateEntityStubMethod($metadata, 'get', $fieldMapping['fieldName'], $fieldMapping['type'])) {
                $methods[] = $code;
            }
        }

        foreach ($metadata->associationMappings as $associationMapping) {
            if ($associationMapping['type'] & ClassMetadataInfo::TO_ONE) {
                $nullable = $this->isAssociationIsNullable($associationMapping) ? 'null' : null;
                if ($code = $this->generateEntityStubMethod($metadata, 'set', $associationMapping['fieldName'], $associationMapping['targetEntity'], $nullable)) {
                    $methods[] = $code;
                }
                if ($code = $this->generateEntityStubMethod($metadata, 'get', $associationMapping['fieldName'], $associationMapping['targetEntity'])) {
                    $methods[] = $code;
                }
            } else if ($associationMapping['type'] & ClassMetadataInfo::TO_MANY) {
                if ($code = $this->generateEntityStubMethod($metadata, 'add', $associationMapping['fieldName'], $associationMapping['targetEntity'])) {
                    $methods[] = $code;
                }
                if ($code = $this->generateEntityStubMethod($metadata, 'remove', $associationMapping['fieldName'], $associationMapping['targetEntity'])) {
                    $methods[] = $code;
                }
                if ($code = $this->generateEntityStubMethod($metadata, 'get', $associationMapping['fieldName'], 'Doctrine\Common\Collections\Collection')) {
                    $methods[] = $code;
                }
            }
        }

        return implode("\n\n", $methods);
    }

    private function isAssociationIsNullable($associationMapping)
    {
        if (isset($associationMapping['id']) && $associationMapping['id']) {
            return false;
        }
        if (isset($associationMapping['joinColumns'])) {
            $joinColumns = $associationMapping['joinColumns'];
        } else {
            //@todo thereis no way to retreive targetEntity metadata
            $joinColumns = array();
        }
        foreach ($joinColumns as $joinColumn) {
            if(isset($joinColumn['nullable']) && !$joinColumn['nullable']) {
                return false;
            }
        }
        return true;
    }

    private function generateEntityLifecycleCallbackMethods(ClassMetadataInfo $metadata)
    {
        if (isset($metadata->lifecycleCallbacks) && $metadata->lifecycleCallbacks) {
            $methods = array();

            foreach ($metadata->lifecycleCallbacks as $name => $callbacks) {
                foreach ($callbacks as $callback) {
                    if ($code = $this->generateLifecycleCallbackMethod($name, $callback, $metadata)) {
                        $methods[] = $code;
                    }
                }
            }

            return implode("\n\n", $methods);
        }

        return "";
    }

    private function generateEntityAssociationMappingProperties(ClassMetadataInfo $metadata)
    {
        $lines = array();

        foreach ($metadata->associationMappings as $associationMapping) {
            if ($this->hasProperty($associationMapping['fieldName'], $metadata)) {
                continue;
            }

            $lines[] = $this->generateAssociationMappingPropertyDocBlock($associationMapping, $metadata);
            $lines[] = $this->spaces . $this->fieldVisibility . ' $' . $associationMapping['fieldName']
                     . ($associationMapping['type'] == 'manyToMany' ? ' = array()' : null) . ";\n";
        }

        return implode("\n", $lines);
    }

    private function generateEntityFieldMappingProperties(ClassMetadataInfo $metadata)
    {
        $lines = array();

        foreach ($metadata->fieldMappings as $fieldMapping) {
            if ($this->hasProperty($fieldMapping['fieldName'], $metadata) ||
                $metadata->isInheritedField($fieldMapping['fieldName'])) {
                continue;
            }

            $lines[] = $this->generateFieldMappingPropertyDocBlock($fieldMapping, $metadata);
            $lines[] = $this->spaces . $this->fieldVisibility . ' $' . $fieldMapping['fieldName']
                     . (isset($fieldMapping['default']) ? ' = ' . var_export($fieldMapping['default'], true) : null) . ";\n";
        }

        return implode("\n", $lines);
    }

    private function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, $fieldName, $typeHint = null,  $defaultValue = null)
    {
        $methodName = $type . Inflector::classify($fieldName);
        if (in_array($type, array("add", "remove")) && substr($methodName, -1) == "s") {
            $methodName = substr($methodName, 0, -1);
        }

        if ($this->hasMethod($methodName, $metadata)) {
            return;
        }
        $this->staticReflection[$metadata->name]['methods'][] = $methodName;

        $var = sprintf('%sMethodTemplate', $type);
        $template = self::$$var;

        $methodTypeHint = null;
        $types          = Type::getTypesMap();
        $variableType   = $typeHint ? $this->getType($typeHint) . ' ' : null;

        if ($typeHint && ! isset($types[$typeHint])) {
            $variableType   =  '\\' . ltrim($variableType, '\\');
            $methodTypeHint =  '\\' . $typeHint . ' ';
        }

        $replacements = array(
          '<description>'       => ucfirst($type) . ' ' . $fieldName,
          '<methodTypeHint>'    => $methodTypeHint,
          '<variableType>'      => $variableType,
          '<variableName>'      => Inflector::camelize($fieldName),
          '<methodName>'        => $methodName,
          '<fieldName>'         => $fieldName,
          '<variableDefault>'   => ($defaultValue !== null ) ? (' = '.$defaultValue) : '',
          '<entity>'            => $this->getClassName($metadata)
        );

        $method = str_replace(
            array_keys($replacements),
            array_values($replacements),
            $template
        );

        return $this->prefixCodeWithSpaces($method);
    }

    private function generateLifecycleCallbackMethod($name, $methodName, $metadata)
    {
        if ($this->hasMethod($methodName, $metadata)) {
            return;
        }
        $this->staticReflection[$metadata->name]['methods'][] = $methodName;

        $replacements = array(
            '<name>'        => $this->annotationsPrefix . ucfirst($name),
            '<methodName>'  => $methodName,
        );

        $method = str_replace(
            array_keys($replacements),
            array_values($replacements),
            self::$lifecycleCallbackMethodTemplate
        );

        return $this->prefixCodeWithSpaces($method);
    }

    private function generateJoinColumnAnnotation(array $joinColumn)
    {
        $joinColumnAnnot = array();

        if (isset($joinColumn['name'])) {
            $joinColumnAnnot[] = 'name="' . $joinColumn['name'] . '"';
        }

        if (isset($joinColumn['referencedColumnName'])) {
            $joinColumnAnnot[] = 'referencedColumnName="' . $joinColumn['referencedColumnName'] . '"';
        }

        if (isset($joinColumn['unique']) && $joinColumn['unique']) {
            $joinColumnAnnot[] = 'unique=' . ($joinColumn['unique'] ? 'true' : 'false');
        }

        if (isset($joinColumn['nullable'])) {
            $joinColumnAnnot[] = 'nullable=' . ($joinColumn['nullable'] ? 'true' : 'false');
        }

        if (isset($joinColumn['onDelete'])) {
            $joinColumnAnnot[] = 'onDelete="' . ($joinColumn['onDelete'] . '"');
        }

        if (isset($joinColumn['columnDefinition'])) {
            $joinColumnAnnot[] = 'columnDefinition="' . $joinColumn['columnDefinition'] . '"';
        }

        return '@' . $this->annotationsPrefix . 'JoinColumn(' . implode(', ', $joinColumnAnnot) . ')';
    }

    private function generateAssociationMappingPropertyDocBlock(array $associationMapping, ClassMetadataInfo $metadata)
    {
        $lines = array();
        $lines[] = $this->spaces . '/**';

        if ($associationMapping['type'] & ClassMetadataInfo::TO_MANY) {
            $lines[] = $this->spaces . ' * @var \Doctrine\Common\Collections\Collection';
        } else {
            $lines[] = $this->spaces . ' * @var \\' . ltrim($associationMapping['targetEntity'], '\\');
        }

        if ($this->generateAnnotations) {
            $lines[] = $this->spaces . ' *';

            if (isset($associationMapping['id']) && $associationMapping['id']) {
                $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'Id';

                if ($generatorType = $this->getIdGeneratorTypeString($metadata->generatorType)) {
                    $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'GeneratedValue(strategy="' . $generatorType . '")';
                }
            }

            $type = null;
            switch ($associationMapping['type']) {
                case ClassMetadataInfo::ONE_TO_ONE:
                    $type = 'OneToOne';
                    break;
                case ClassMetadataInfo::MANY_TO_ONE:
                    $type = 'ManyToOne';
                    break;
                case ClassMetadataInfo::ONE_TO_MANY:
                    $type = 'OneToMany';
                    break;
                case ClassMetadataInfo::MANY_TO_MANY:
                    $type = 'ManyToMany';
                    break;
            }
            $typeOptions = array();

            if (isset($associationMapping['targetEntity'])) {
                $typeOptions[] = 'targetEntity="' . $associationMapping['targetEntity'] . '"';
            }

            if (isset($associationMapping['inversedBy'])) {
                $typeOptions[] = 'inversedBy="' . $associationMapping['inversedBy'] . '"';
            }

            if (isset($associationMapping['mappedBy'])) {
                $typeOptions[] = 'mappedBy="' . $associationMapping['mappedBy'] . '"';
            }

            if ($associationMapping['cascade']) {
                $cascades = array();

                if ($associationMapping['isCascadePersist']) $cascades[] = '"persist"';
                if ($associationMapping['isCascadeRemove']) $cascades[] = '"remove"';
                if ($associationMapping['isCascadeDetach']) $cascades[] = '"detach"';
                if ($associationMapping['isCascadeMerge']) $cascades[] = '"merge"';
                if ($associationMapping['isCascadeRefresh']) $cascades[] = '"refresh"';

                $typeOptions[] = 'cascade={' . implode(',', $cascades) . '}';
            }

            if (isset($associationMapping['orphanRemoval']) && $associationMapping['orphanRemoval']) {
                $typeOptions[] = 'orphanRemoval=' . ($associationMapping['orphanRemoval'] ? 'true' : 'false');
            }

            if (isset($associationMapping['fetch']) && $associationMapping['fetch'] !== ClassMetadataInfo::FETCH_LAZY) {
                $fetchMap = array(
                    ClassMetadataInfo::FETCH_EXTRA_LAZY => 'EXTRA_LAZY',
                    ClassMetadataInfo::FETCH_EAGER      => 'EAGER',
                );

                $typeOptions[] = 'fetch="' . $fetchMap[$associationMapping['fetch']] . '"';
            }

            $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . '' . $type . '(' . implode(', ', $typeOptions) . ')';

            if (isset($associationMapping['joinColumns']) && $associationMapping['joinColumns']) {
                $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'JoinColumns({';

                $joinColumnsLines = array();

                foreach ($associationMapping['joinColumns'] as $joinColumn) {
                    if ($joinColumnAnnot = $this->generateJoinColumnAnnotation($joinColumn)) {
                        $joinColumnsLines[] = $this->spaces . ' *   ' . $joinColumnAnnot;
                    }
                }

                $lines[] = implode(",\n", $joinColumnsLines);
                $lines[] = $this->spaces . ' * })';
            }

            if (isset($associationMapping['joinTable']) && $associationMapping['joinTable']) {
                $joinTable = array();
                $joinTable[] = 'name="' . $associationMapping['joinTable']['name'] . '"';

                if (isset($associationMapping['joinTable']['schema'])) {
                    $joinTable[] = 'schema="' . $associationMapping['joinTable']['schema'] . '"';
                }

                $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'JoinTable(' . implode(', ', $joinTable) . ',';
                $lines[] = $this->spaces . ' *   joinColumns={';

                $joinColumnsLines = array();

                foreach ($associationMapping['joinTable']['joinColumns'] as $joinColumn) {
                    $joinColumnsLines[] = $this->spaces . ' *     ' . $this->generateJoinColumnAnnotation($joinColumn);
                }

                $lines[] = implode(",". PHP_EOL, $joinColumnsLines);
                $lines[] = $this->spaces . ' *   },';
                $lines[] = $this->spaces . ' *   inverseJoinColumns={';

                $inverseJoinColumnsLines = array();

                foreach ($associationMapping['joinTable']['inverseJoinColumns'] as $joinColumn) {
                    $inverseJoinColumnsLines[] = $this->spaces . ' *     ' . $this->generateJoinColumnAnnotation($joinColumn);
                }

                $lines[] = implode(",". PHP_EOL, $inverseJoinColumnsLines);
                $lines[] = $this->spaces . ' *   }';
                $lines[] = $this->spaces . ' * )';
            }

            if (isset($associationMapping['orderBy'])) {
                $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'OrderBy({';

                foreach ($associationMapping['orderBy'] as $name => $direction) {
                    $lines[] = $this->spaces . ' *     "' . $name . '"="' . $direction . '",';
                }

                $lines[count($lines) - 1] = substr($lines[count($lines) - 1], 0, strlen($lines[count($lines) - 1]) - 1);
                $lines[] = $this->spaces . ' * })';
            }
        }

        $lines[] = $this->spaces . ' */';

        return implode("\n", $lines);
    }

    private function generateFieldMappingPropertyDocBlock(array $fieldMapping, ClassMetadataInfo $metadata)
    {
        $lines = array();
        $lines[] = $this->spaces . '/**';
        $lines[] = $this->spaces . ' * @var ' . $this->getType($fieldMapping['type']);

        if ($this->generateAnnotations) {
            $lines[] = $this->spaces . ' *';

            $column = array();
            if (isset($fieldMapping['columnName'])) {
                $column[] = 'name="' . $fieldMapping['columnName'] . '"';
            }

            if (isset($fieldMapping['type'])) {
                $column[] = 'type="' . $fieldMapping['type'] . '"';
            }

            if (isset($fieldMapping['length'])) {
                $column[] = 'length=' . $fieldMapping['length'];
            }

            if (isset($fieldMapping['precision'])) {
                $column[] = 'precision=' .  $fieldMapping['precision'];
            }

            if (isset($fieldMapping['scale'])) {
                $column[] = 'scale=' . $fieldMapping['scale'];
            }

            if (isset($fieldMapping['nullable'])) {
                $column[] = 'nullable=' .  var_export($fieldMapping['nullable'], true);
            }

            if (isset($fieldMapping['columnDefinition'])) {
                $column[] = 'columnDefinition="' . $fieldMapping['columnDefinition'] . '"';
            }

            if (isset($fieldMapping['unique'])) {
                $column[] = 'unique=' . var_export($fieldMapping['unique'], true);
            }

            $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'Column(' . implode(', ', $column) . ')';

            if (isset($fieldMapping['id']) && $fieldMapping['id']) {
                $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'Id';

                if ($generatorType = $this->getIdGeneratorTypeString($metadata->generatorType)) {
                    $lines[] = $this->spaces.' * @' . $this->annotationsPrefix . 'GeneratedValue(strategy="' . $generatorType . '")';
                }

                if ($metadata->sequenceGeneratorDefinition) {
                    $sequenceGenerator = array();

                    if (isset($metadata->sequenceGeneratorDefinition['sequenceName'])) {
                        $sequenceGenerator[] = 'sequenceName="' . $metadata->sequenceGeneratorDefinition['sequenceName'] . '"';
                    }

                    if (isset($metadata->sequenceGeneratorDefinition['allocationSize'])) {
                        $sequenceGenerator[] = 'allocationSize=' . $metadata->sequenceGeneratorDefinition['allocationSize'];
                    }

                    if (isset($metadata->sequenceGeneratorDefinition['initialValue'])) {
                        $sequenceGenerator[] = 'initialValue=' . $metadata->sequenceGeneratorDefinition['initialValue'];
                    }

                    $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'SequenceGenerator(' . implode(', ', $sequenceGenerator) . ')';
                }
            }

            if (isset($fieldMapping['version']) && $fieldMapping['version']) {
                $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'Version';
            }
        }

        $lines[] = $this->spaces . ' */';

        return implode("\n", $lines);
    }

    private function prefixCodeWithSpaces($code, $num = 1)
    {
        $lines = explode("\n", $code);

        foreach ($lines as $key => $value) {
            $lines[$key] = str_repeat($this->spaces, $num) . $lines[$key];
        }

        return implode("\n", $lines);
    }

    /**
     * @param integer $type                 The inheritance type used by the class and it's subclasses.
     * @return string                       The literal string for the inheritance type.
     * @throws \InvalidArgumentException    When the inheritance type does not exists.
     */
    protected function getInheritanceTypeString($type)
    {
        if ( ! isset(self::$inheritanceTypeMap[$type])) {
            throw new \InvalidArgumentException(sprintf('Invalid provided InheritanceType: %s', $type));
        }

        return self::$inheritanceTypeMap[$type];
    }

    /**
     * @param integer $type                 The policy used for change-tracking for the mapped class.
     * @return string                       The literal string for the change-tracking type.
     * @throws \InvalidArgumentException    When the change-tracking type does not exists.
     */
    protected function getChangeTrackingPolicyString($type)
    {
        if ( ! isset(self::$changeTrackingPolicyMap[$type])) {
            throw new \InvalidArgumentException(sprintf('Invalid provided ChangeTrackingPolicy: %s', $type));
        }

        return self::$changeTrackingPolicyMap[$type];
    }

    /**
     * @param integer $type                 The generator to use for the mapped class.
     * @return string                       The literal string for the generetor type.
     * @throws \InvalidArgumentException    When the generator type does not exists.
     */
    protected function getIdGeneratorTypeString($type)
    {
        if ( ! isset(self::$generatorStrategyMap[$type])) {
            throw new \InvalidArgumentException(sprintf('Invalid provided IdGeneratorType: %s', $type));
        }

        return self::$generatorStrategyMap[$type];
    }
}


text:
var chai = require('chai');
var expect = chai.expect;

var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);

var Hub = require('..');
var hub = new Hub();

var Service = function () {

};

Service.prototype.successInit = function () {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve();
        }, 100);
    });
};

Service.prototype.failInit = function () {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            reject(new Error('Initialization failed'));
        }, 100);
    });
};

Service.prototype.successDestroy = function () {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve();
        }, 100);
    });
};

Service.prototype.failDestroy = function () {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            reject(new Error('Destruction failed'));
        }, 100);
    });
};

Service.prototype.foo = function () {
    return 'bar';
};

var serviceSuccessConstructor = function () {
    var service = new Service();
    return new Promise(function (resolve, reject) {
        service.successInit().then(function () {
            resolve(service);
        }, function (error) {
            reject(error);
        });
    });
};

var serviceSuccessDestructor = function () {
    var service = new Service();
    return new Promise(function (resolve, reject) {
        service.successDestroy().then(function () {
            resolve();
        }, function (error) {
            reject(error);
        });
    });
};

var serviceFailConstructor = function () {
    var service = new Service();
    return new Promise(function (resolve, reject) {
        service.failInit().then(function () {
            resolve(service);
        }, function (error) {
            reject(error);
        });
    });
};

var serviceFailDestructor = function () {
    var service = new Service();
    return new Promise(function (resolve, reject) {
        service.failDestroy().then(function () {
            resolve();
        }, function (error) {
            reject(error);
        });
    });
};

describe('Hub', function () {
    describe('#register()', function () {
        it('Should register service', function () {
            return expect(hub.register('service1', serviceSuccessConstructor, serviceSuccessDestructor)).to.be.true;
        });

        it('Should not register already registered service', function () {
            return expect(function () {
                hub.register('service1', serviceSuccessConstructor, serviceSuccessDestructor)
            }).to.throw(Error);
        });
    });

    describe('#unregister()', function () {
        it('Should unregister service', function () {
            return expect(hub.unregister('service1', serviceSuccessConstructor, serviceSuccessDestructor)).to.be.true;
        });

        it('Should not unregister not registered service', function () {
            return expect(function () {
                hub.unregister('service1', serviceSuccessConstructor, serviceSuccessDestructor)
            }).to.throw(Error);
        });
    });

    describe('#get()', function () {
        it('Should not initiate unregistered service', function () {
            return expect(hub.get('service1')).to.be.rejectedWith(Error);
        });

        it('Should initiate and return registered service', function () {
            hub.register('service1', serviceSuccessConstructor, serviceSuccessDestructor);
            return expect(hub.get('service1')).to.be.fulfilled;
        });

        it('Should initiate and return registered services', function () {
            hub.register('service3', serviceSuccessConstructor, serviceFailDestructor);
            return expect(hub.get(['service1', 'service3'])).to.be.fulfilled.and.eventually.to.have.length(2);
        });

        it('Should not reinitiate already initiated service', function () {
            return hub.get('service1').then(function (service1) {
                return expect(hub.get('service1')).to.be.fulfilled.and.eventually.be.equal(service1);
            });
        });

        it('Should reinitiate service if standalone is true', function () {
            return hub.get('service1').then(function (service1) {
                return expect(hub.get('service1', true)).to.be.fulfilled.and.eventually.to.be.not.equal(service1);
            });
        });

        it('Should not initiate broken service', function () {
            hub.register('service2', serviceFailConstructor, serviceFailDestructor);
            return expect(hub.get('service2')).to.be.rejectedWith(Error);
        });

    });

    describe('#destroy()', function () {
        it('Should destroy only standalone service', function () {
            return hub.get('service1', true).then(function (service1) {
                hub.destroy('service1', service1).then(function () {
                    return expect(hub.isInitiated('service1')).to.be.true;
                });
            });
        });

        it('Should destroy service', function () {
            return expect(hub.destroy('service1')).to.be.fulfilled;
        });

        it('Should not destroy broken service', function () {
            return hub.get('service3').then(function (service) {
                expect(service.foo()).to.be.equal('bar');
                return expect(hub.destroy('service3')).to.be.rejectedWith(Error);
            });
        });
    });

    describe('#isRegistered()', function () {
        it('Should return true if service is registered', function () {
            return expect(hub.isRegistered('service3')).to.be.true;
        });

        it('Should return false if service is not registered', function () {
            return expect(hub.isRegistered('service4')).to.be.false;
        });
    });

    describe('#getRegistered()', function () {
        it('Should return registered services', function () {
            return expect(hub.getRegistered()).to.be.deep.equal(['service1', 'service3', 'service2']);
        });
    });

    describe('#isInitiated()', function () {
        it('Should return true if service is initiated', function () {
            return expect(hub.isInitiated('service3')).to.be.true;
        });

        it('Should return false if service is not initiated', function () {
            return expect(hub.isInitiated('service2')).to.be.false;
        });
    });

    describe('#getInitiated()', function () {
        it('Should return initiated services', function () {
            return expect(hub.getInitiated()).to.be.deep.equal(['service3']);
        });
    });
});

redpajama_set_name: RedPajamaGithub


text:
/* @flow */
import type { SJSymbolMaster } from 'sketchapp-json-flow-types';
import { makeSymbolMaster, makeRect } from '../jsonUtils/models';
import SketchRenderer from './SketchRenderer';
import type { ViewStyle, LayoutInfo, TextStyle } from '../types';

class SymbolMasterRenderer extends SketchRenderer {
  renderGroupLayer(
    layout: LayoutInfo,
    style: ViewStyle,
    textStyle: TextStyle,
    props: any
  ): SJSymbolMaster {
    return makeSymbolMaster(
      makeRect(layout.left, layout.top, layout.width, layout.height),
      props.symbolID,
      props.name
    );
  }
}

module.exports = SymbolMasterRenderer;


text:
<?php

namespace Zelenin\SmsRu\Auth\TokenCache;

class DummyCache implements CacheInterface
{

    /**
     * @inheritdoc
     */
    public function exists($key)
    {
        return false;
    }

    /**
     * @inheritdoc
     */
    public function get($key)
    {
        return false;
    }

    /**
     * @inheritdoc
     */
    public function set($key, $value, $ttl = null)
    {
        return true;
    }

    /**
     * @inheritdoc
     */
    public function remove($key)
    {
        return true;
    }
}


text:
'use strict';
import { TextDocument, CancellationToken, Position, Range } from 'vscode-languageserver';
import { FoldingRange } from 'vscode-languageserver-protocol-foldingprovider';
import { LanguageModes } from './languageModes';

export function getFoldingRanges(languageModes: LanguageModes, document: TextDocument, maxRanges: number | undefined, cancellationToken: CancellationToken | null): FoldingRange[] {
	let htmlMode = languageModes.getMode('html');
	let range = Range.create(Position.create(0, 0), Position.create(document.lineCount, 0));
	let ranges: FoldingRange[] = [];
	if (htmlMode && htmlMode.getFoldingRanges) {
		ranges.push(...htmlMode.getFoldingRanges(document, range));
	}
	let modeRanges = languageModes.getModesInRange(document, range);
	for (let modeRange of modeRanges) {
		let mode = modeRange.mode;
		if (mode && mode !== htmlMode && mode.getFoldingRanges && !modeRange.attributeValue) {
			ranges.push(...mode.getFoldingRanges(document, modeRange));
		}
	}
	if (maxRanges && ranges.length > maxRanges) {
		ranges = limitRanges(ranges, maxRanges);
	}
	return ranges;
}

function limitRanges(ranges: FoldingRange[], maxRanges: number) {
	ranges = ranges.sort((r1, r2) => {
		let diff = r1.startLine - r2.startLine;
		if (diff === 0) {
			diff = r1.endLine - r2.endLine;
		}
		return diff;
	});

	// compute each range's nesting level in 'nestingLevels'.
	// count the number of ranges for each level in 'nestingLevelCounts'
	let top: FoldingRange | undefined = void 0;
	let previous: FoldingRange[] = [];
	let nestingLevels: number[] = [];
	let nestingLevelCounts: number[] = [];

	let setNestingLevel = (index: number, level: number) => {
		nestingLevels[index] = level;
		if (level < 30) {
			nestingLevelCounts[level] = (nestingLevelCounts[level] || 0) + 1;
		}
	};

	// compute nesting levels and sanitize
	for (let i = 0; i < ranges.length; i++) {
		let entry = ranges[i];
		if (!top) {
			top = entry;
			setNestingLevel(i, 0);
		} else {
			if (entry.startLine > top.startLine) {
				if (entry.endLine <= top.endLine) {
					previous.push(top);
					top = entry;
					setNestingLevel(i, previous.length);
				} else if (entry.startLine > top.endLine) {
					do {
						top = previous.pop();
					} while (top && entry.startLine > top.endLine);
					if (top) {
						previous.push(top);
					}
					top = entry;
					setNestingLevel(i, previous.length);
				}
			}
		}
	}
	let entries = 0;
	let maxLevel = 0;
	for (let i = 0; i < nestingLevelCounts.length; i++) {
		let n = nestingLevelCounts[i];
		if (n) {
			if (n + entries > maxRanges) {
				maxLevel = i;
				break;
			}
			entries += n;
		}
	}
	let result = [];
	for (let i = 0; i < ranges.length; i++) {
		let level = nestingLevels[i];
		if (typeof level === 'number') {
			if (level < maxLevel || (level === maxLevel && entries++ < maxRanges)) {
				result.push(ranges[i]);
			}
		}
	}
	return result;
}


text:
PROG=	dup2_slave2master

.include "../Makefile.cprog"


text:
  Lagarde-sur-le-Né est
       un village
       localisé dans le département de Charente en Poitou-Charentes. Elle totalisait 179 habitants en 2008.

Si vous pensez emmenager à Lagarde-sur-le-Né, vous pourrez aisément trouver une maison à acheter.

À proximité de Lagarde-sur-le-Né sont positionnées géographiquement les villes de
Touzac située à 5 km, 464 habitants,
Plassac située à 5 km, 547 habitants,
Barbezieux-Saint-Hilaire située à 5 km, 4 646 habitants,
La Magdeleine à 1 km, 119 habitants,
Sonneville située à 5 km, 210 habitants,
Saint-Médard à 4 km, 239 habitants,
 entre autres. De plus, Lagarde-sur-le-Né est située à seulement 22 km de Cognac.

Le nombre d'habitations, à Lagarde-sur-le-Né, était réparti en 2011 en un appartements et 86 maisons soit
 un marché plutôt équilibré.


text:
google_leveldb
==============


text:
[![Build Status](https://travis-ci.org/ActiDoo/gamification-engine.svg?branch=master)](https://travis-ci.org/ActiDoo/gamification-engine)
[![Requirements Status](https://requires.io/github/ActiDoo/gamification-engine/requirements.svg?branch=master)](https://requires.io/github/ActiDoo/gamification-engine/requirements/?branch=master)
[![Heroku](https://heroku-badge.herokuapp.com/?app=gamification-engine&root=admin)](https://gamification-engine.herokuapp.com)

[![Documentation Status](https://readthedocs.org/projects/gamification-engine/badge/?version=latest)](https://readthedocs.org/projects/gamification-engine/?badge=latest)
[![Latest Version](https://pypip.in/version/gamification-engine/badge.svg)](https://pypi.python.org/pypi/gamification-engine/)
[![Downloads](https://pypip.in/download/gamification-engine/badge.svg?period=month)](https://pypi.python.org/pypi/gamification-engine/)

[![License](https://pypip.in/license/gamification-engine/badge.svg)](https://pypi.python.org/pypi/gamification-engine/)
(commercial support available at https://www.gamification-software.com)

The Gamification-Engine (gengine) is an open source software (MIT) for integrating any kinds of gamification features into your product.

The engine is **not meant to be a platform** including any kinds of predefined graphics, layouts or statistics.
It is framework for developing your own solution, implemented as a **service** to which your application server can talk over a REST api.

## Features

- multi level achievements
- multi goal achievements
- progress and single goals
- leader boards / ladder
- achievements can be reached directly or by evaluating leaderboards daily, weekly, monthly or yearly
- time zone independent (correct daily, weekly.. evaluations among time zones)
- social-awareness (e.g. reach the highest score among your friends)
- geo-awareness (e.g. reach the highest score among all users in your city)
- rules can be defined in python using given variables (e.g. the current level)
- custom definable achievement properties and rewards
- custom definable languages and translations
- dependencies between achievements (prerequisites & postconditions)
- high performance / scalable
- administration ui

## REST Interface

Simple REST-interface to communicate with arbitrary systems

see http://gamification-engine.readthedocs.org/en/latest/rest/index.html

## Demo Installation

A demo installation is available at https://gamification-engine.herokuapp.com/

## Usage

1. A ready-to-use buildpack for Heroku and dokku is available at https://github.com/ActiDoo/gamification-engine-dokku Follow the instructions there.
2. The current stable version is available as phyton package at https://pypi.python.org/pypi/gamification-engine
3. Checkout the source code and configure the PostgreSQL database in `development.ini`. Then run `python setup.py develop` to configure the application and `pserve development.ini` to start it. The front end is available at http://localhost:6543

## Roadmap

Do you want to contribute? We badly need tests!
Also a nicer admin UI would be great or maybe some cool features :-)

For a full list see:

http://gamification-engine.readthedocs.org/en/latest/roadmap.html

## Licenses of dependencies

Pyramid: BSD-derived (http://www.repoze.org/LICENSE.txt)

pyramid_chameleon: BSD-derived (http://www.repoze.org/LICENSE.txt)

pyramid_debugtoolbar: BSD

SQLAlchemy: MIT

zope.sqlalchemy: Zope Public License (ZPL) Version 2.1

waitress: Zope Public License (ZPL) Version 2.1

pytz: MIT

dogpile.cache: BSD

pyramid_dogpile_cache: MIT

flask: BSD

flask-admin: BSD

psycopg2: LGPL / ZPL

pymemcache: Apache License 2.0

mock: BSD

alembic: MIT


text:
<?php

namespace common\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

class Customer extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;

    const GENDER_MALE = 0;
    const GENDER_FEMALE = 10;

    const NEWSLETTER_NO = 0;
    const NEWSLETTER_YES = 10;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'customer';
    }

    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            /*[['customer_dob'], 'safe'],
            [['customer_gender', 'customer_reward_point', 'created_at', 'updated_at'], 'integer'],
            [['customer_address'], 'string'],
            [['username', 'email', 'auth_key', 'password_hash', 'created_at', 'updated_at'], 'required'],
            [['customer_name'], 'string', 'max' => 64],
            [['customer_telephone'], 'string', 'max' => 20],
             [['username', 'email', 'password_hash', 'password_reset_token'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],*/
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
            ['customer_gender', 'in', 'range' => [self::GENDER_MALE, self::GENDER_FEMALE]],
        ];
    }

    public function formatGender() {
        if ($this->customer_gender == 0)
            return "Female";
        else if
            ($this->customer_gender == 10)
            return "Male";
        else
            return "Not Set";
    }

    public function formatStatus() {
        if ($this->status == 0)
            return "Deleted";
        else if
            ($this->status == 10)
            return "Active";
        else
            return "Not Set";
    }

    public function formatNewsletter() {
        if ($this->newsletter == 0)
            return "No";
        else if
            ($this->newsletter == 10)
            return "Yes";
        else
            return "Not Set";
    }

    public static function findIdentity($id)
    {
        return static::findOne(['customer_id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    public function getId()
    {
        return $this->getPrimaryKey();
    }

    public function getAuthKey()
    {
        return $this->auth_key;
    }

    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'customer_id' => 'Customer ID',
            'customer_name' => 'Name',
            'customer_dob' => 'Dob',
            'customer_gender' => 'Gender',
            'customer_telephone' => 'Telephone',
            'customer_address' => 'Address',
            'customer_reward_point' => 'Reward Point',
            'username' => 'Username',
            'email' => 'Email',
            'auth_key' => 'Auth Key',
            'password_hash' => 'Password Hash',
            'password_reset_token' => 'Password Reset Token',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'status' => 'Status',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCarts()
    {
        return $this->hasMany(Cart::className(), ['customer_id' => 'customer_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getComments()
    {
        return $this->hasMany(Comment::className(), ['customer_id' => 'customer_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCouponLists()
    {
        return $this->hasMany(CouponList::className(), ['customer_id' => 'customer_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCoupons()
    {
        return $this->hasMany(Coupon::className(), ['coupon_id' => 'coupon_id'])->viaTable('coupon_list', ['customer_id' => 'customer_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getDeliveryAddresses()
    {
        return $this->hasMany(DeliveryAddress::className(), ['customer_id' => 'customer_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getSupportTickets()
    {
        return $this->hasMany(SupportTicket::className(), ['customer_id' => 'customer_id']);
    }
}


text:
			<form action="#" id="form" method="post" name="form">
			ID : <input id="button_id" type="text" /input>

			Text: <input id="button_text" type="text" /input>

			Action: <input id="button_action" type="text"/input>

			<button id="b2" onclick="exportButton()">Include</button>
			</form>


text:
package scriptella.driver.velocity;

import scriptella.spi.AbstractScriptellaDriver;
import scriptella.spi.Connection;
import scriptella.spi.ConnectionParameters;
import scriptella.spi.DialectIdentifier;

import java.util.logging.Logger;

/**
 * Scriptella Driver for Velocity template engine.
 *
 * @author Fyodor Kupolov
 * @version 1.0
 */
public class Driver extends AbstractScriptellaDriver {
    static final DialectIdentifier DIALECT = new DialectIdentifier("Velocity", "1.4");
    static final Logger LOG = Logger.getLogger(Driver.class.getName());

    public Driver() {
        try { //Check if velocity is on classpath
            Class.forName("org.apache.velocity.VelocityContext");
        } catch (ClassNotFoundException e) {
            throw new VelocityProviderException("Velocity not found on classpath. Check if connection classpath attribute points to velocity-dep.jar");
        }
    }

    /**
     * Implementor should create a new connection based on specified parameters.
     *
     * @param connectionParameters connection parameters defined in <connection> element.
     * @return new connection.
     */
    public Connection connect(ConnectionParameters connectionParameters) {
        return new VelocityConnection(connectionParameters);
    }

}


text:
    Указва параметър-низ, чиято стойност се избира от списък от стойности.
    Тя може да се използва по време на изграждането като променлива на средата
    или за заместване в някоя настройка.


text:
import {NgModule} from '@angular/core';
import {RouterModule} from '@angular/router'
import {MultiSelectDemo} from './multiselectdemo';

@NgModule({
	imports: [
		RouterModule.forChild([
			{path:'',component: MultiSelectDemo}
		])
	],
	exports: [
		RouterModule
	]
})
export class MultiSelectDemoRoutingModule {}


text:
package controller

import (
	"github.com/hearb/hearb/api"
	mw "github.com/hearb/hearb/middleware"
	"github.com/labstack/echo"
)

func AddAPIRoutes(e *echo.Echo) {
	g := e.Group("/api/v1", mw.LoginRequire())
	api.AddUserRoutes(g)
}


text:
{% extends "layout.html" %}

{% block page_title %}
  Publish government data
{% endblock %}

{% block proposition_header %}
  {% include "includes/propositional_navigation_service.html" %}
{% endblock %}

{% block header_class %}
  with-proposition
{% endblock %}

{% block content %}

{% include "includes/phase_banner_alpha.html" %}

    {% include "includes/side-navigation.html" %}

        Edit {{ dataset.title }}

      <form action="edit_submit" method="post" class="form compact">

        <input type="hidden" name="index" value="{{ index }}"/>

          Title
          <input
              class="form-control"
              type="text"
              name="title-dataset"
              value="{{ dataset.title }}"
              id="title"/>

          Description
          <textarea
              class="form-control"
              name="summary-dataset"
              id="summary">{{ dataset.summary }}</textarea>

        <fieldset>
          <legend>Links</legend>

            {% for link in dataset.links %}

                <input
                    class="form-control inline title"
                    type="text"
                    name="link-title"
                    value="{{ link.title }}"/>
                <input
                    class="form-control inline url"
                    type="text"
                    name="link-url"
                    value="{{ link.url }}"
                    id="url"/>

            {% endfor %}

              Add new:

              <input
                  class="form-control inline title"
                  type="text"
                  name="link-title"
                  placeholder="New title"
                  value=""/>
              <input
                  class="form-control inline url"
                  type="text"
                  name="link-url"
                  placeholder="New URL"
                  value=""
                  id="url"/>

        </fieldset>

        <fieldset>
          <legend>Areas</legend>

          {% set areas=[['England', 'england'],
          ['Wales', 'wales'],
          ['Scotland', 'scotland'],
          ['Northern Ireland', 'ni'],
          ['Overseas', 'overseas']
          ] %}

            {% for area in areas %}

              <input
                  type="checkbox"
                  id="{{area[1]}}"
                  name="geo"
                  value="{{area[0]}}"
                  {% if (dataset.geo and dataset.geo.indexOf(area[0]) !== -1) %}
                  checked
                  {% endif %}
              />
              {{area[0]}}

            {% endfor %}

        </fieldset>

        <fieldset>
          <legend>
            licence
          </legend>

              <input
                  type="radio"
                  id="notify-1"
                  name="licence"
                  value="Open Government Licence"
                  {% if (dataset.licence == "Open Government Licence") %}
                  checked
                  {% endif %}
              />
              Open Government Licence

              <input
                  type="radio"
                  id="notify-2"
                  name="licence"
                  value="INSPIRE"
                  {% if (dataset.licence == "INSPIRE") %}
                  checked
                  {% endif %}
              />
              INSPIRE

              <input
                  type="radio"
                  id="other"
                  name="licence"
                  value="Other"
                  {% if (dataset.licence == "Other") %}
                  checked
                  {% endif %}
              />
              Other:
              <input
                  class="inline"
                  type="text"
                  name="other-licence"
                  id="other-licence"
                  value="{{ dataset.otherLicence }}"/>

        </fieldset>

        <fieldset>
          <legend>
            Updates
          </legend>

          {% set frequencies=[['Every day', 'day'],
          ['Every week', 'week'],
          ['Every month', 'month'],
          ['Every quarter', 'quarter'],
          ['Every year', 'year'],
          ['No set schedule', 'none']
          ] %}

            {% for frequency in frequencies %}

              <input
                  type="radio"
                  id="{{frequency[1]}}"
                  name="frequency"
                  value="{{frequency[1]}}"
                  {% if dataset.frequency == frequency[1] %}
                  checked
                  {% endif %}
              />
              {{frequency[0]}}

            {% endfor %}

Start date

              Day
              <input
                  class="form-control"
                  id="start-day"
                  name="start-day"
                  type="number"
                  pattern="[0-9]*"
                  min="0"
                  max="31"
                  value="{{ dataset.startDay }}"
                  aria-describedby="start-hint">
              /

              Month
              <input
                  class="form-control"
                  id="start-month"
                  name="start-month"
                  type="number"
                  pattern="[0-9]*"
                  min="0"
                  max="12"
                  value="{{ dataset.startMonth }}">
              /

              Year
              <input
                  class="form-control"
                  id="start-year"
                  name="start-year"
                  type="number"
                  pattern="[0-9]*"
                  min="0"
                  value="{{ dataset.startYear }}">

End date

              Day
              <input
                  class="form-control"
                  id="end-day"
                  name="end-day"
                  type="number"
                  pattern="[0-9]*"
                  min="0"
                  max="31"
                  value="{{ dataset.endDay }}"
                  aria-describedby="end-hint">
              /

              Month
              <input
                  class="form-control"
                  id="end-month"
                  name="end-month"
                  type="number"
                  pattern="[0-9]*"
                  min="0"
                  max="12"
                  value="{{ dataset.endMonth }}">
              /

              Year
              <input
                  class="form-control"
                  id="end-year"
                  name="end-year"
                  type="number"
                  pattern="[0-9]*"
                  min="0"
                  value="{{ dataset.endYear }}">

Time period

              Month
              <input
                  class="form-control"
                  id="period-month"
                  name="period-month"
                  type="number"
                  pattern="[0-9]*"
                  min="0"
                  max="12"
                  value="{{ dataset.periodMonth }}">
              /

              Year
              <input
                  class="form-control"
                  id="period-year"
                  name="period-year"
                  type="number"
                  pattern="[0-9]*"
                  min="0"
                  value="{{ dataset.periodYear }}">

Time period

              Year
              <input
                  class="form-control"
                  id="period-year"
                  name="period-year"
                  type="number"
                  pattern="[0-9]*"
                  min="0"
                  value="{{ dataset.periodYear }}">

            <select name="period-quarter">
              <option value="first">First quarter</option>
              <option value="second">Second quarter</option>
              <option value="third">Third quarter</option>
              <option value="fourth">Fourth quarter</option>
            </select>

        </fieldset>

        <fieldset
            class="{% if dataset.frequency == 'none' %}js-hidden{% endif %}"
            id="notify">
          <legend>
            Update notifications
          </legend>

              <input
                  type="radio"
                  id="notify-1"
                  name="notify"
                  value="yes"
                  {% if dataset.notify == 'yes' %}checked{% endif %}
              >
              Yes

              <input
                  type="radio"
                  id="notify-2"
                  name="notify"
                  value="no"
                  {% if dataset.notify == 'no' %}checked{% endif %}
              >
              No

        </fieldset>

          <input type="submit" class="button" value="Done" />

      </form>

{% endblock %}


text:
This is awesome.

* a point
* another point
---
My: Word
Author: Eugene
Stuff:
  - My
  - Stuff
---


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

<title>The GNU C Library: Other Mount Information</title>

<meta name="description" content="The GNU C Library: Other Mount Information">
<meta name="keywords" content="The GNU C Library: Other Mount Information">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Concept-Index.html#Concept-Index" rel="index" title="Concept Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Mount-Information.html#Mount-Information" rel="up" title="Mount Information">
<link href="Mount_002dUnmount_002dRemount.html#Mount_002dUnmount_002dRemount" rel="next" title="Mount-Unmount-Remount">
<link href="mtab.html#mtab" rel="prev" title="mtab">

Previous: mtab, Up: Mount Information   [Contents][Index]

31.3.1.3 Other (Non-libc) Sources of Mount Information

On a system with a Linux kernel and the proc filesystem, you can
get information on currently mounted filesystems from the file
<samp>mounts</samp> in the proc filesystem.  Its format is similar to
that of the <samp>mtab</samp> file, but represents what is truly mounted
without relying on facilities outside the kernel to keep <samp>mtab</samp> up
to date.


text:
<?php namespace CJAN\Repositories;

interface UserRepository {

	public function findByUsername($username);

}


text:
package com.opengamma.web.analytics.blotter;

import org.joda.beans.MetaBean;
import org.joda.beans.MetaProperty;

import com.opengamma.util.ArgumentChecker;

/**
 * TODO do I need this?
 */
/* package */ abstract class DelegatingVisitor<T> implements BeanVisitor<T> {

  private final BeanVisitor<T> _delegate;

  /* package */ DelegatingVisitor(BeanVisitor<T> delegate) {
    ArgumentChecker.notNull(delegate, "delegate");
    _delegate = delegate;
  }

  @Override
  public void visitMetaBean(MetaBean metaBean) {
    _delegate.visitMetaBean(metaBean);
  }

  @Override
  public void visitBeanProperty(MetaProperty<?> property, BeanTraverser traverser) {
    _delegate.visitBeanProperty(property, traverser);
  }

  @Override
  public void visitCollectionProperty(MetaProperty<?> property, BeanTraverser traverser) {
    _delegate.visitCollectionProperty(property, traverser);
  }

  @Override
  public void visitSetProperty(MetaProperty<?> property, BeanTraverser traverser) {
    _delegate.visitSetProperty(property, traverser);
  }

  @Override
  public void visitListProperty(MetaProperty<?> property, BeanTraverser traverser) {
    _delegate.visitListProperty(property, traverser);
  }

  @Override
  public void visitMapProperty(MetaProperty<?> property, BeanTraverser traverser) {
    _delegate.visitMapProperty(property, traverser);
  }

  @Override
  public void visitProperty(MetaProperty<?> property, BeanTraverser traverser) {
    _delegate.visitProperty(property, traverser);
  }

  @Override
  public T finish() {
    return _delegate.finish();
  }
}


text:
wifi-cc3000
===========

Deprecated. The wifi-cc3000 lib is now included with Tessel's firmware. Do not `npm install` this package.

The following should work out of the box on Tessel:

```
var wifi = require('wifi-cc3000');

console.log("is wifi connected? ", wifi.isConnected());
```


text:
var _ = require('underscore')

module.exports = function (data, model, properties) {
  var childs
  _.each(properties, function (property, index) {
    if (data[property]) {
      childs = property.split('.')
      data[childs[0]] = model[childs[0]]
      data[childs[0]][childs[1]] = data[property] || data[childs[0]][childs[1]]
      delete data[property]
    }
  })
  return data
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
Author: Stojan Kukrika
Version: 1.0
*/

// ------------------------------------------------------------------------

class Model_customform_field extends CI_Model {

	function __construct()
	{
		parent::__construct();
	}
	public function total_rows() {
        return $this->db->where(array('deleted_at' => NULL))->count_all("custom_form_fields");
    }

    public function fetch_paging($limit, $start) {
        $this->db->limit($limit, $start);
        $query = $this->db->where(array('deleted_at' => NULL))->get("custom_form_fields");

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return false;
   }
	public function getall()
	{
		return $this->db->where(array('deleted_at' => NULL))->get("custom_form_fields")->result();
	}

	public function delete($id) {
		$data = array(
               'deleted_at' => date("Y-m-d H:i:s")
            );
			$this->db->where('id', $id);
			$this->db->update('custom_form_fields', $data);
    }

	public function deletefomid($id) {
		$data = array(
               'deleted_at' => date("Y-m-d H:i:s")
            );
			$this->db->where('custom_form_id', $id);
			$this->db->update('custom_form_fields', $data);
    }

	public function select($id) {
		return $this->db->where('id', $id)->where(array('deleted_at' => NULL))->get('custom_form_fields')->first_row();
    }

	public function selectorder($order,$id) {
		return $this->db->where('custom_form_id', $id)->where(array('deleted_at' => NULL))->order_by($order,'ASC')->get('custom_form_fields')->result();
    }

	public function selectcount($id) {
		return $this->db->where('custom_form_id', $id)->where(array('deleted_at' => NULL))->count_all('custom_form_fields');
    }

	public function insert($data) {
		$this->db->insert('custom_form_fields', $data);
		return $this -> db -> insert_id();
    }

	public function update($data,$id) {
		$this->db->where('id', $id);
		$this->db->update('custom_form_fields', $data);
    }
	public function selectForId($id) {
		return $this->db->where('custom_form_id', $id)
								->where(array('deleted_at' => NULL))
								->select('id, name, options, type, order, mandatory')
								->order_by('order','ASC')
								->get('custom_form_fields')->result();
    }
}


text:
import _ from 'lodash';
import Bluebird from 'bluebird';
import fs from 'fs';
import _path from 'path';
import Storage from './Storage';

/**
 * @class JSONStorage
 */
export default class JSONStorage extends Storage {
  /**
   * Constructs JSON file storage.
   *
   * @param {Object} [options]
   * @param {String} [options.path='./umzug.json'] - Path to JSON file where
   * the log is stored. Defaults './umzug.json' relative to process' cwd.
   */
  constructor ({ path = _path.resolve(process.cwd(), 'umzug.json') } = {}) {
    super();
    this.path = path;
  }

  /**
   * Logs migration to be considered as executed.
   *
   * @param {String} migrationName - Name of the migration to be logged.
   * @returns {Promise}
   */
  logMigration (migrationName) {
    let filePath = this.path;
    let readfile = Bluebird.promisify(fs.readFile);
    let writefile = Bluebird.promisify(fs.writeFile);

    return readfile(filePath)
      .catch(function () { return '[]'; })
      .then(function (content) { return JSON.parse(content); })
      .then(function (content) {
        content.push(migrationName);
        return writefile(filePath, JSON.stringify(content, null, '  '));
      });
  }

  /**
   * Unlogs migration to be considered as pending.
   *
   * @param {String} migrationName - Name of the migration to be unlogged.
   * @returns {Promise}
   */
  unlogMigration (migrationName) {
    let filePath = this.path;
    let readfile = Bluebird.promisify(fs.readFile);
    let writefile = Bluebird.promisify(fs.writeFile);

    return readfile(filePath)
      .catch(function () { return '[]'; })
      .then(function (content) { return JSON.parse(content); })
      .then(function (content) {
        content = _.without(content, migrationName);
        return writefile(filePath, JSON.stringify(content, null, '  '));
      });
  }

  /**
   * Gets list of executed migrations.
   *
   * @returns {Promise.<String[]>}
   */
  executed () {
    let filePath = this.path;
    let readfile = Bluebird.promisify(fs.readFile);

    return readfile(filePath)
      .catch(function () { return '[]'; })
      .then(function (content) {
        return JSON.parse(content);
      });
  }
}


text:
<hadoop-pipes>
  <content>
    <file name='/usr/include/hadoop/Pipes.hh' owners='1' perm='-rw-r--r--' user='root' group='root' />
    <file name='/usr/include/hadoop/SerialUtils.hh' owners='1' perm='-rw-r--r--' user='root' group='root' />
    <file name='/usr/include/hadoop/StringUtils.hh' owners='1' perm='-rw-r--r--' user='root' group='root' />
    <file name='/usr/include/hadoop/TemplateFactory.hh' owners='1' perm='-rw-r--r--' user='root' group='root' />
    <file name='/usr/lib64/libhadooppipes.a' owners='1' perm='-rw-r--r--' user='root' group='root' />
    <file name='/usr/lib64/libhadooputils.a' owners='1' perm='-rw-r--r--' user='root' group='root' />
  </content>
</hadoop-pipes>


text:
<?php

namespace adrianclay\git\References;

use adrianclay\git\SHAReference;

class DirectoryIterator implements \Iterator
{
    /** @var \RecursiveIteratorIterator */
    private $directoryIterator;

    /** @var string */
    private $refsPath;

    /** @var Parser */
    private $refs;

    /**
     * @param Parser   $refs
     * @param string $refsPath
     */
    public function __construct( Parser $refs, $refsPath )
    {
        $this->refs = $refs;
        $this->refsPath = $refsPath;
        $this->directoryIterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $this->refsPath, \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS ) );
    }

    /**
     * @return SHAReference
     */
    public function current()
    {
        return $this->refs->parseRefString( file_get_contents( $this->directoryIterator->current() ) );
    }

    public function next()
    {
        $this->directoryIterator->next();
    }

    /**
     * @return string
     */
    public function key()
    {
        return substr( $this->directoryIterator->key(), strlen( $this->refsPath ) - 4 );
    }

    /**
     * @return bool
     */
    public function valid()
    {
        return $this->directoryIterator->valid();
    }

    public function rewind()
    {
        $this->directoryIterator->rewind();
    }
}


text:
package org.springframework.social.linkedin.api;

import java.io.Serializable;

/**
 * Model class representing a relation.
 *
 * @author Robert Drysdale
 */
public class Relation extends LinkedInObject implements Serializable {

	private static final long serialVersionUID = 1L;

	private final int distance;

	public Relation(int distance) {
		this.distance = distance;
	}

	public int getDistance() {
		return distance;
	}

}


text:
FactoryBot.define do
  factory :container_volume do
    sequence(:name) { |n| "container_volume_#{seq_padded_for_sorting(n)}" }
  end
end


text:
package com.maxplus1.spark.demo.java.service.remote;

import com.maxplus1.spark.demo.java.entity.Test1Pojo;

/**
 * Created by xiaolong.qiu on 2017/1/19.
 */
public interface ITest1Service {

    Test1Pojo getTest1(Long id);
}


text:
<title>OGRE: OgrePlatformInformation.h Source File - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="doxygen.css">
<link type="text/css" rel="stylesheet" href="tabs.css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Directories

File List

File Members

OgreMain

include

OgrePlatformInformation.h

Go to the documentation of this file.

00001
00028 #ifndef __PlatformInformation_H__
00029 #define __PlatformInformation_H__
00030
00031 #include "OgrePrerequisites.h"
00032
00033 namespace Ogre {
00034 //
00035 // TODO: Puts following macros into OgrePlatform.h?
00036 //
00037
00038 /* Initial CPU stuff to set.
00039 */
00040 #define OGRE_CPU_UNKNOWN    0
00041 #define OGRE_CPU_X86        1
00042 #define OGRE_CPU_PPC        2
00043 #define OGRE_CPU_ARM        3
00044
00045 /* Find CPU type
00046 */
00047 #if (defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))) || \
00048     (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)))
00049 #   define OGRE_CPU OGRE_CPU_X86
00050
00051 #elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE && defined(__BIG_ENDIAN__)
00052 #   define OGRE_CPU OGRE_CPU_PPC
00053 #elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
00054 #   define OGRE_CPU OGRE_CPU_X86
00055 #elif OGRE_PLATFORM == OGRE_PLATFORM_IPHONE && (defined(__i386__) || defined(__x86_64__))
00056 #   define OGRE_CPU OGRE_CPU_X86
00057 #elif defined(__arm__)
00058 #   define OGRE_CPU OGRE_CPU_ARM
00059 #else
00060 #   define OGRE_CPU OGRE_CPU_UNKNOWN
00061 #endif
00062
00063 /* Find how to declare aligned variable.
00064 */
00065 #if OGRE_COMPILER == OGRE_COMPILER_MSVC
00066 #   define OGRE_ALIGNED_DECL(type, var, alignment)  __declspec(align(alignment)) type var
00067
00068 #elif OGRE_COMPILER == OGRE_COMPILER_GNUC
00069 #   define OGRE_ALIGNED_DECL(type, var, alignment)  type var __attribute__((__aligned__(alignment)))
00070
00071 #else
00072 #   define OGRE_ALIGNED_DECL(type, var, alignment)  type var
00073 #endif
00074
00077 #if OGRE_CPU == OGRE_CPU_X86
00078 #   define OGRE_SIMD_ALIGNMENT  16
00079
00080 #else
00081 #   define OGRE_SIMD_ALIGNMENT  16
00082 #endif
00083
00084 /* Declare variable aligned to SIMD alignment.
00085 */
00086 #define OGRE_SIMD_ALIGNED_DECL(type, var)   OGRE_ALIGNED_DECL(type, var, OGRE_SIMD_ALIGNMENT)
00087
00088 /* Define whether or not Ogre compiled with SSE supports.
00089 */
00090 #if OGRE_DOUBLE_PRECISION == 0 && OGRE_CPU == OGRE_CPU_X86 && OGRE_COMPILER == OGRE_COMPILER_MSVC
00091 #   define __OGRE_HAVE_SSE  1
00092 #elif OGRE_DOUBLE_PRECISION == 0 && OGRE_CPU == OGRE_CPU_X86 && OGRE_COMPILER == OGRE_COMPILER_GNUC
00093 #   define __OGRE_HAVE_SSE  1
00094 #endif
00095
00096 /* Define whether or not Ogre compiled with VFP supports.
00097  */
00098 #if OGRE_DOUBLE_PRECISION == 0 && OGRE_CPU == OGRE_CPU_ARM && OGRE_COMPILER == OGRE_COMPILER_GNUC && defined(__ARM_ARCH_6K__) && defined(__VFP_FP__)
00099 #   define __OGRE_HAVE_VFP  1
00100 #endif
00101
00102 /* Define whether or not Ogre compiled with NEON supports.
00103  */
00104 #if OGRE_DOUBLE_PRECISION == 0 && OGRE_CPU == OGRE_CPU_ARM && OGRE_COMPILER == OGRE_COMPILER_GNUC && defined(__ARM_ARCH_7A__) && defined(__ARM_NEON__)
00105 #   define __OGRE_HAVE_NEON  1
00106 #endif
00107
00108 #ifndef __OGRE_HAVE_SSE
00109 #   define __OGRE_HAVE_SSE  0
00110 #endif
00111
00112 #ifndef __OGRE_HAVE_VFP
00113 #   define __OGRE_HAVE_VFP  0
00114 #endif
00115
00116 #ifndef __OGRE_HAVE_NEON
00117 #   define __OGRE_HAVE_NEON  0
00118 #endif
00119
00141     class _OgreExport PlatformInformation
00142     {
00143     public:
00144
00146         enum CpuFeatures
00147         {
00148 #if OGRE_CPU == OGRE_CPU_X86
00149             CPU_FEATURE_SSE         = 1 << 0,
00150             CPU_FEATURE_SSE2        = 1 << 1,
00151             CPU_FEATURE_SSE3        = 1 << 2,
00152             CPU_FEATURE_MMX         = 1 << 3,
00153             CPU_FEATURE_MMXEXT      = 1 << 4,
00154             CPU_FEATURE_3DNOW       = 1 << 5,
00155             CPU_FEATURE_3DNOWEXT    = 1 << 6,
00156             CPU_FEATURE_CMOV        = 1 << 7,
00157             CPU_FEATURE_TSC         = 1 << 8,
00158             CPU_FEATURE_FPU         = 1 << 9,
00159             CPU_FEATURE_PRO         = 1 << 10,
00160             CPU_FEATURE_HTT         = 1 << 11,
00161 #elif OGRE_CPU == OGRE_CPU_ARM
00162             CPU_FEATURE_VFP         = 1 << 12,
00163             CPU_FEATURE_NEON        = 1 << 13,
00164 #endif
00165
00166             CPU_FEATURE_NONE        = 0
00167         };
00168
00174         static const String& getCpuIdentifier(void);
00175
00181         static uint getCpuFeatures(void);
00182
00188         static bool hasCpuFeature(CpuFeatures feature);
00189
00190
00192         static void log(Log* pLog);
00193
00194     };
00198 }
00199
00200 #endif  // __PlatformInformation_H__

Copyright © 2008 Torus Knot Software Ltd

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Last modified Wed Nov 3 2010 19:24:52


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>

      Africa Ready to Code –

    Build Africa
  </title>

  <meta name="author" content="Build Africa" />
  <meta name="description" content="BuildAfrica.org is my personal blog which focuses primarily on the convergence of the two passions in my life - technology and Africa." />

  <link rel="alternate" type="application/rss+xml" href="/atom.xml" />

  <link rel="stylesheet" href="/css/base.css" type="text/css" media="screen, projection" />
  <link rel="stylesheet" href="/css/pygments.css" type="text/css" />
  <link media="only screen and (max-device-width: 480px)" href="/css/iphone.css" type="text/css" rel="stylesheet" />
  <link media="only screen and (device-width: 768px)" href="/css/iphone.css" type="text/css" rel="stylesheet" />
  <link href='http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz' rel='stylesheet' type='text/css'>
  <link href='http://fonts.googleapis.com/css?family=Armata' rel='stylesheet' type='text/css'>
  <link rel="apple-touch-icon" href="/apple-touch-icon.png" />

        Build
        Africa

about

posts

projects

    Africa Ready to Code

    August  2, 2009

I am writing this from Kisumu, Kenya.  I’m here to follow up on the progress being made with the RapidResponse Pilot and to work with Dickson Ukanga, a talented young Kenyan programmer, I just hired.

It’s been about a week now since the Seacom cable has come online and according to Dickson Safaricom users are already seeing the benefit.   Today, I also noticed for the first time that Mountain Dew, the drink synonomous to late night coding and considered by some code-junkies “an essential ingredient for successful computer programming”, is now available in shops at Kenya too.  Coincidence? I think not. =)

What encourages me is that African programmers increasingly have access to the tools critical to compete: cheap computers, good internet, solid computer science university programs, time to code and increased inclusion to global geek culture both actual through bar camps and symbolic with Mountain Dew.  Cheaper and faster Internet should also help translate into a larger market for local Internet based services critical for growing the African software industry.

I think it is time to be excited.   As the barriers to entry continue to tumble, the number of really good programmers coming out of places like Nairobi, Kampala, Accra and Dakar will only increase.   It will still take some time but at least but at least Africa is starting to overcome the infrastructure challenges that have choked ICT growth in Africa. It’s hard to train to compete when you are sipping through a straw.  The only thing ultimately inhibiting African programmers from making their mark on a global (and local) stage is hard work and brainpower.

That’s a bet I’m willing to take.

Note:

If you are interested in finding programmers in Africa please checkout this job board at:

http://jobs.whiteafrican.com/

Discussion, links, and tweets

        I'm a technologist/geek living in Nairobi, Kenya. I believe open code and data can make the world a better place. Follow me on Twitter;

      Tweet
      Follow @mberg

    Please enable JavaScript to view the comments powered by Disqus.
    comments powered by Disqus


text:
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');

module.exports = {
  bail: false,
  entry: {
    browser: './src/json_stream_reporter.js'
  },
  module: {
    loaders: [
      {test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel'}
    ]
  },
  output: {
    filename: '[name].js',
    chunkFilename: '[id].js',
    libraryTarget: 'umd',
    library: 'JasmineJsonStreamReporter',
    umdNamedDefine: true,
    pathinfo: false
  },
  plugins: [
    new UglifyJsPlugin({compress: {warnings: false}, sourceMap: false})
  ]
};


text:
layout: index
title: Buy Hugs
tagline: Know all our product from hub 4 hugs
group: navigation
img : v_hug.mp4
img-mobile :
css: products.css
js:
keywords: hug, hugs, happy, hub4hugs, social, love
canonical: https://hub4hugs.github.io
---
{% include JB/setup %}

{% include themes/bootstrap/nav-bar.html %}

Loveable products.

All dressable hugs from the hub.

Wondering how to make your world more beautiful?

After reaching your happiness

the whole world will be much more beautiful and interesting.

Do not you think so?

Treat yourself to an excerpt of happiness, with an hug from the hub.

HUG MINIMAL

A minimal design for an Hug

100% cotton

Slim fit

Superb quality

          Buy it

TIME 4 HUGS

For who have time for hugs

100% cotton

Slim fit

Superb quality

          Buy it

SEARCH 4 HUGS

For who look for new hugs

100% cotton

Slim fit

Superb quality

          Buy it

HEART HUG

For who have heart for an hug

100% cotton

Slim fit

Superb quality

          Buy it

Give a hug to your happiness or your friend

Why should you buy a hug:

Because our hugs are lovingly cared for and guaranteed by high quality standards.

Fast shipping

Every shirt have 2-3 day of shipping for hug yourself quickly.

Limited edition

This line of shirts has a limited edition and will be withdrawn from the market soon! Hurry up to be one of the privileged to possess.

Italian design

The designe and the graphics have been made to develop in Italy by professionals in the field.

Guaranteed by Amazon

All our products are guaranteed and marketed by amazon for better transparency and quality.

Not interested? I am sure you will like still share a hug with a friend!

Do it well through the button below will give you access to the hub 4 hugs!

Choose your social to spear Hugs! And send to your favourites friends!

				  Send my hug!

As seen on:

Find hug products

Stay update to all new hug products.

	              Put me in the Hub

	              Remember about the hugs sharer

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Share an hug with your friends

Share via twitter

Share your hug via one tweet! press the tweet button and remember to tag a friend by using @ and his username

			        Tweet Hugs

Post on Facebook

Share your hug via one post! press the share button and remember to tag a friend by using @ and his username

Hugs

Pin on Pinterest

Pin your hug! press the Pin button and remember to edit the pin and tag a friend by using @ and his username

Buy an Hug from the hub

You shortcomings of affection? Do you know any friend who has? Try to give him a hug by clicking the button below!

		          Take my money and give me my hugs

        <button type="button" class="btn btn-default" data-dismiss="modal">Close Hugs sharer</button>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Didothis dispersa I. Hino & Katum.

### Remarks
null