text:
<?php

namespace Doctrine\ORM\Persisters;

use PDO,
    Doctrine\DBAL\LockMode,
    Doctrine\DBAL\Types\Type,
    Doctrine\ORM\ORMException,
    Doctrine\ORM\OptimisticLockException,
    Doctrine\ORM\EntityManager,
    Doctrine\ORM\Query,
    Doctrine\ORM\PersistentCollection,
    Doctrine\ORM\Mapping\MappingException,
    Doctrine\ORM\Mapping\ClassMetadata;

/**
 * A BasicEntityPersiter maps an entity to a single table in a relational database.
 *
 * A persister is always responsible for a single entity type.
 *
 * EntityPersisters are used during a UnitOfWork to apply any changes to the persistent
 * state of entities onto a relational database when the UnitOfWork is committed,
 * as well as for basic querying of entities and their associations (not DQL).
 *
 * The persisting operations that are invoked during a commit of a UnitOfWork to
 * persist the persistent entity state are:
 *
 *   - {@link addInsert} : To schedule an entity for insertion.
 *   - {@link executeInserts} : To execute all scheduled insertions.
 *   - {@link update} : To update the persistent state of an entity.
 *   - {@link delete} : To delete the persistent state of an entity.
 *
 * As can be seen from the above list, insertions are batched and executed all at once
 * for increased efficiency.
 *
 * The querying operations invoked during a UnitOfWork, either through direct find
 * requests or lazy-loading, are the following:
 *
 *   - {@link load} : Loads (the state of) a single, managed entity.
 *   - {@link loadAll} : Loads multiple, managed entities.
 *   - {@link loadOneToOneEntity} : Loads a one/many-to-one entity association (lazy-loading).
 *   - {@link loadOneToManyCollection} : Loads a one-to-many entity association (lazy-loading).
 *   - {@link loadManyToManyCollection} : Loads a many-to-many entity association (lazy-loading).
 *
 * The BasicEntityPersister implementation provides the default behavior for
 * persisting and querying entities that are mapped to a single database table.
 *
 * Subclasses can be created to provide custom persisting and querying strategies,
 * i.e. spanning multiple tables.
 *
 * @author Roman Borschel <roman@code-factory.org>
 * @author Giorgio Sironi <piccoloprincipeazzurro@gmail.com>
 * @since 2.0
 */
class BasicEntityPersister
{
    /**
     * Metadata object that describes the mapping of the mapped entity class.
     *
     * @var Doctrine\ORM\Mapping\ClassMetadata
     */
    protected $_class;

    /**
     * The underlying DBAL Connection of the used EntityManager.
     *
     * @var Doctrine\DBAL\Connection $conn
     */
    protected $_conn;

    /**
     * The database platform.
     *
     * @var Doctrine\DBAL\Platforms\AbstractPlatform
     */
    protected $_platform;

    /**
     * The EntityManager instance.
     *
     * @var Doctrine\ORM\EntityManager
     */
    protected $_em;

    /**
     * Queued inserts.
     *
     * @var array
     */
    protected $_queuedInserts = array();

    /**
     * Case-sensitive mappings of column names as they appear in an SQL result set
     * to column names as they are defined in the mapping. This is necessary because different
     * RDBMS vendors return column names in result sets in different casings.
     *
     * @var array
     */
    protected $_resultColumnNames = array();

    /**
     * The map of column names to DBAL mapping types of all prepared columns used
     * when INSERTing or UPDATEing an entity.
     *
     * @var array
     * @see _prepareInsertData($entity)
     * @see _prepareUpdateData($entity)
     */
    protected $_columnTypes = array();

    /**
     * The INSERT SQL statement used for entities handled by this persister.
     * This SQL is only generated once per request, if at all.
     *
     * @var string
     */
    private $_insertSql;

    /**
     * The SELECT column list SQL fragment used for querying entities by this persister.
     * This SQL fragment is only generated once per request, if at all.
     *
     * @var string
     */
    protected $_selectColumnListSql;

    /**
     * Counter for creating unique SQL table and column aliases.
     *
     * @var integer
     */
    protected $_sqlAliasCounter = 0;

    /**
     * Map from class names (FQCN) to the corresponding generated SQL table aliases.
     *
     * @var array
     */
    protected $_sqlTableAliases = array();

    /**
     * Initializes a new <tt>BasicEntityPersister</tt> that uses the given EntityManager
     * and persists instances of the class described by the given ClassMetadata descriptor.
     *
     * @param Doctrine\ORM\EntityManager $em
     * @param Doctrine\ORM\Mapping\ClassMetadata $class
     */
    public function __construct(EntityManager $em, ClassMetadata $class)
    {
        $this->_em = $em;
        $this->_class = $class;
        $this->_conn = $em->getConnection();
        $this->_platform = $this->_conn->getDatabasePlatform();
    }

    /**
     * Adds an entity to the queued insertions.
     * The entity remains queued until {@link executeInserts} is invoked.
     *
     * @param object $entity The entity to queue for insertion.
     */
    public function addInsert($entity)
    {
        $this->_queuedInserts[spl_object_hash($entity)] = $entity;
    }

    /**
     * Executes all queued entity insertions and returns any generated post-insert
     * identifiers that were created as a result of the insertions.
     *
     * If no inserts are queued, invoking this method is a NOOP.
     *
     * @return array An array of any generated post-insert IDs. This will be an empty array
     *               if the entity class does not use the IDENTITY generation strategy.
     */
    public function executeInserts()
    {
        if ( ! $this->_queuedInserts) {
            return;
        }

        $postInsertIds = array();
        $idGen = $this->_class->idGenerator;
        $isPostInsertId = $idGen->isPostInsertGenerator();

        $stmt = $this->_conn->prepare($this->_getInsertSQL());
        $tableName = $this->_class->table['name'];

        foreach ($this->_queuedInserts as $entity) {
            $insertData = $this->_prepareInsertData($entity);

            if (isset($insertData[$tableName])) {
                $paramIndex = 1;
                foreach ($insertData[$tableName] as $column => $value) {
                    $stmt->bindValue($paramIndex++, $value, $this->_columnTypes[$column]);
                }
            }

            $stmt->execute();

            if ($isPostInsertId) {
                $id = $idGen->generate($this->_em, $entity);
                $postInsertIds[$id] = $entity;
            } else {
                $id = $this->_class->getIdentifierValues($entity);
            }

            if ($this->_class->isVersioned) {
                $this->_assignDefaultVersionValue($this->_class, $entity, $id);
            }
        }

        $stmt->closeCursor();
        $this->_queuedInserts = array();

        return $postInsertIds;
    }

    /**
     * Retrieves the default version value which was created
     * by the preceding INSERT statement and assigns it back in to the
     * entities version field.
     *
     * @param Doctrine\ORM\Mapping\ClassMetadata $class
     * @param object $entity
     * @param mixed $id
     */
    protected function _assignDefaultVersionValue($class, $entity, $id)
    {
        $versionField = $this->_class->versionField;
        $identifier = $this->_class->getIdentifierColumnNames();
        $versionFieldColumnName = $this->_class->getColumnName($versionField);
        //FIXME: Order with composite keys might not be correct
        $sql = "SELECT " . $versionFieldColumnName . " FROM " . $class->getQuotedTableName($this->_platform)
               . " WHERE " . implode(' = ? AND ', $identifier) . " = ?";
        $value = $this->_conn->fetchColumn($sql, array_values((array)$id));
        $this->_class->setFieldValue($entity, $versionField, $value);
    }

    /**
     * Updates a managed entity. The entity is updated according to its current changeset
     * in the running UnitOfWork. If there is no changeset, nothing is updated.
     *
     * The data to update is retrieved through {@link _prepareUpdateData}.
     * Subclasses that override this method are supposed to obtain the update data
     * in the same way, through {@link _prepareUpdateData}.
     *
     * Subclasses are also supposed to take care of versioning when overriding this method,
     * if necessary. The {@link _updateTable} method can be used to apply the data retrieved
     * from {@_prepareUpdateData} on the target tables, thereby optionally applying versioning.
     *
     * @param object $entity The entity to update.
     */
    public function update($entity)
    {
        $updateData = $this->_prepareUpdateData($entity);
        $tableName = $this->_class->table['name'];
        if (isset($updateData[$tableName]) && $updateData[$tableName]) {
            $this->_updateTable($entity, $tableName, $updateData[$tableName], $this->_class->isVersioned);
        }
    }

    /**
     * Performs an UPDATE statement for an entity on a specific table.
     * The UPDATE can optionally be versioned, which requires the entity to have a version field.
     *
     * @param object $entity The entity object being updated.
     * @param string $tableName The name of the table to apply the UPDATE on.
     * @param array $updateData The map of columns to update (column => value).
     * @param boolean $versioned Whether the UPDATE should be versioned.
     */
    protected final function _updateTable($entity, $tableName, array $updateData, $versioned = false)
    {
        $set = $params = $types = array();

        foreach ($updateData as $columnName => $value) {
            if (isset($this->_class->fieldNames[$columnName])) {
                $set[] = $this->_class->getQuotedColumnName($this->_class->fieldNames[$columnName], $this->_platform) . ' = ?';
            } else {
                $set[] = $columnName . ' = ?';
            }
            $params[] = $value;
            $types[] = $this->_columnTypes[$columnName];
        }

        $where = array();
        $id = $this->_em->getUnitOfWork()->getEntityIdentifier($entity);
        foreach ($this->_class->identifier as $idField) {
            $where[] = $this->_class->getQuotedColumnName($idField, $this->_platform);
            $params[] = $id[$idField];
            $types[] = $this->_class->fieldMappings[$idField]['type'];
        }

        if ($versioned) {
            $versionField = $this->_class->versionField;
            $versionFieldType = $this->_class->getTypeOfField($versionField);
            $versionColumn = $this->_class->getQuotedColumnName($versionField, $this->_platform);
            if ($versionFieldType == Type::INTEGER) {
                $set[] = $versionColumn . ' = ' . $versionColumn . ' + 1';
            } else if ($versionFieldType == Type::DATETIME) {
                $set[] = $versionColumn . ' = CURRENT_TIMESTAMP';
            }
            $where[] = $versionColumn;
            $params[] = $this->_class->reflFields[$versionField]->getValue($entity);
            $types[] = $this->_class->fieldMappings[$versionField]['type'];
        }

        $sql = "UPDATE $tableName SET " . implode(', ', $set)
            . ' WHERE ' . implode(' = ? AND ', $where) . ' = ?';

        $result = $this->_conn->executeUpdate($sql, $params, $types);

        if ($this->_class->isVersioned && ! $result) {
            throw OptimisticLockException::lockFailed($entity);
        }
    }

    /**
     * @todo Add check for platform if it supports foreign keys/cascading.
     * @param array $identifier
     * @return void
     */
    protected function deleteJoinTableRecords($identifier)
    {
        foreach ($this->_class->associationMappings as $mapping) {
            if ($mapping['type'] == ClassMetadata::MANY_TO_MANY) {
                // @Todo this only covers scenarios with no inheritance or of the same level. Is there something
                // like self-referential relationship between different levels of an inheritance hierachy? I hope not!
                $selfReferential = ($mapping['targetEntity'] == $mapping['sourceEntity']);

                if ( ! $mapping['isOwningSide']) {
                    $relatedClass = $this->_em->getClassMetadata($mapping['targetEntity']);
                    $mapping = $relatedClass->associationMappings[$mapping['mappedBy']];
                    $keys = array_keys($mapping['relationToTargetKeyColumns']);
                    if ($selfReferential) {
                        $otherKeys = array_keys($mapping['relationToSourceKeyColumns']);
                    }
                } else {
                    $keys = array_keys($mapping['relationToSourceKeyColumns']);
                    if ($selfReferential) {
                        $otherKeys = array_keys($mapping['relationToTargetKeyColumns']);
                    }
                }

                if ( ! isset($mapping['isOnDeleteCascade'])) {
                    $this->_conn->delete($mapping['joinTable']['name'], array_combine($keys, $identifier));

                    if ($selfReferential) {
                        $this->_conn->delete($mapping['joinTable']['name'], array_combine($otherKeys, $identifier));
                    }
                }
            }
        }
    }

    /**
     * Deletes a managed entity.
     *
     * The entity to delete must be managed and have a persistent identifier.
     * The deletion happens instantaneously.
     *
     * Subclasses may override this method to customize the semantics of entity deletion.
     *
     * @param object $entity The entity to delete.
     */
    public function delete($entity)
    {
        $identifier = $this->_em->getUnitOfWork()->getEntityIdentifier($entity);
        $this->deleteJoinTableRecords($identifier);

        $id = array_combine($this->_class->getIdentifierColumnNames(), $identifier);
        $this->_conn->delete($this->_class->table['name'], $id);
    }

    /**
     * Gets the ClassMetadata instance of the entity class this persister is used for.
     *
     * @return Doctrine\ORM\Mapping\ClassMetadata
     */
    public function getClassMetadata()
    {
        return $this->_class;
    }

    /**
     * Prepares the changeset of an entity for database insertion (UPDATE).
     *
     * The changeset is obtained from the currently running UnitOfWork.
     *
     * During this preparation the array that is passed as the second parameter is filled with
     * <columnName> => <value> pairs, grouped by table name.
     *
     * Example:
     * <code>
     * array(
     *    'foo_table' => array('column1' => 'value1', 'column2' => 'value2', ...),
     *    'bar_table' => array('columnX' => 'valueX', 'columnY' => 'valueY', ...),
     *    ...
     * )
     * </code>
     *
     * @param object $entity The entity for which to prepare the data.
     * @return array The prepared data.
     */
    protected function _prepareUpdateData($entity)
    {
        $result = array();
        $uow = $this->_em->getUnitOfWork();

        if ($versioned = $this->_class->isVersioned) {
            $versionField = $this->_class->versionField;
        }

        foreach ($uow->getEntityChangeSet($entity) as $field => $change) {
            if ($versioned && $versionField == $field) {
                continue;
            }

            $oldVal = $change[0];
            $newVal = $change[1];

            if (isset($this->_class->associationMappings[$field])) {
                $assoc = $this->_class->associationMappings[$field];
                // Only owning side of x-1 associations can have a FK column.
                if ( ! $assoc['isOwningSide'] || ! ($assoc['type'] & ClassMetadata::TO_ONE)) {
                    continue;
                }

                if ($newVal !== null) {
                    $oid = spl_object_hash($newVal);
                    if (isset($this->_queuedInserts[$oid]) || $uow->isScheduledForInsert($newVal)) {
                        // The associated entity $newVal is not yet persisted, so we must
                        // set $newVal = null, in order to insert a null value and schedule an
                        // extra update on the UnitOfWork.
                        $uow->scheduleExtraUpdate($entity, array(
                            $field => array(null, $newVal)
                        ));
                        $newVal = null;
                    }
                }

                if ($newVal !== null) {
                    $newValId = $uow->getEntityIdentifier($newVal);
                }

                $targetClass = $this->_em->getClassMetadata($assoc['targetEntity']);
                $owningTable = $this->getOwningTable($field);

                foreach ($assoc['sourceToTargetKeyColumns'] as $sourceColumn => $targetColumn) {
                    if ($newVal === null) {
                        $result[$owningTable][$sourceColumn] = null;
                    } else {
                        $result[$owningTable][$sourceColumn] = $newValId[$targetClass->fieldNames[$targetColumn]];
                    }
                    $this->_columnTypes[$sourceColumn] = $targetClass->getTypeOfColumn($targetColumn);
                }
            } else {
                $columnName = $this->_class->columnNames[$field];
                $this->_columnTypes[$columnName] = $this->_class->fieldMappings[$field]['type'];
                $result[$this->getOwningTable($field)][$columnName] = $newVal;
            }
        }
        return $result;
    }

    /**
     * Prepares the data changeset of a managed entity for database insertion (initial INSERT).
     * The changeset of the entity is obtained from the currently running UnitOfWork.
     *
     * The default insert data preparation is the same as for updates.
     *
     * @param object $entity The entity for which to prepare the data.
     * @return array The prepared data for the tables to update.
     * @see _prepareUpdateData
     */
    protected function _prepareInsertData($entity)
    {
        return $this->_prepareUpdateData($entity);
    }

    /**
     * Gets the name of the table that owns the column the given field is mapped to.
     *
     * The default implementation in BasicEntityPersister always returns the name
     * of the table the entity type of this persister is mapped to, since an entity
     * is always persisted to a single table with a BasicEntityPersister.
     *
     * @param string $fieldName The field name.
     * @return string The table name.
     */
    public function getOwningTable($fieldName)
    {
        return $this->_class->table['name'];
    }

    /**
     * Loads an entity by a list of field criteria.
     *
     * @param array $criteria The criteria by which to load the entity.
     * @param object $entity The entity to load the data into. If not specified,
     *        a new entity is created.
     * @param $assoc The association that connects the entity to load to another entity, if any.
     * @param array $hints Hints for entity creation.
     * @param int $lockMode
     * @return object The loaded and managed entity instance or NULL if the entity can not be found.
     * @todo Check identity map? loadById method? Try to guess whether $criteria is the id?
     */
    public function load(array $criteria, $entity = null, $assoc = null, array $hints = array(), $lockMode = 0)
    {
        $sql = $this->_getSelectEntitiesSQL($criteria, $assoc, $lockMode);
        $stmt = $this->_conn->executeQuery($sql, array_values($criteria));
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $stmt->closeCursor();

        return $this->_createEntity($result, $entity, $hints);
    }

    /**
     * Loads an entity of this persister's mapped class as part of a single-valued
     * association from another entity.
     *
     * @param array $assoc The association to load.
     * @param object $sourceEntity The entity that owns the association (not necessarily the "owning side").
     * @param object $targetEntity The existing ghost entity (proxy) to load, if any.
     * @param array $identifier The identifier of the entity to load. Must be provided if
     *                          the association to load represents the owning side, otherwise
     *                          the identifier is derived from the $sourceEntity.
     * @return object The loaded and managed entity instance or NULL if the entity can not be found.
     */
    public function loadOneToOneEntity(array $assoc, $sourceEntity, $targetEntity, array $identifier = array())
    {
        $targetClass = $this->_em->getClassMetadata($assoc['targetEntity']);

        if ($assoc['isOwningSide']) {
            $isInverseSingleValued = $assoc['inversedBy'] && ! $targetClass->isCollectionValuedAssociation($assoc['inversedBy']);

            // Mark inverse side as fetched in the hints, otherwise the UoW would
            // try to load it in a separate query (remember: to-one inverse sides can not be lazy).
            $hints = array();
            if ($isInverseSingleValued) {
                $hints['fetched'][$targetClass->name][$assoc['inversedBy']] = true;
                if ($targetClass->subClasses) {
                    foreach ($targetClass->subClasses as $targetSubclassName) {
                        $hints['fetched'][$targetSubclassName][$assoc['inversedBy']] = true;
                    }
                }
            }
            /* cascade read-only status
            if ($this->_em->getUnitOfWork()->isReadOnly($sourceEntity)) {
                $hints[Query::HINT_READ_ONLY] = true;
            }
            */

            $targetEntity = $this->load($identifier, $targetEntity, $assoc, $hints);

            // Complete bidirectional association, if necessary
            if ($targetEntity !== null && $isInverseSingleValued) {
                $targetClass->reflFields[$assoc['inversedBy']]->setValue($targetEntity, $sourceEntity);
            }
        } else {
            $sourceClass = $this->_em->getClassMetadata($assoc['sourceEntity']);
            $owningAssoc = $targetClass->getAssociationMapping($assoc['mappedBy']);
            // TRICKY: since the association is specular source and target are flipped
            foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) {
                if (isset($sourceClass->fieldNames[$sourceKeyColumn])) {
                    $identifier[$targetKeyColumn] = $sourceClass->reflFields[$sourceClass->fieldNames[$sourceKeyColumn]]->getValue($sourceEntity);
                } else {
                    throw MappingException::joinColumnMustPointToMappedField(
                        $sourceClass->name, $sourceKeyColumn
                    );
                }
            }

            $targetEntity = $this->load($identifier, $targetEntity, $assoc);

            if ($targetEntity !== null) {
                $targetClass->setFieldValue($targetEntity, $assoc['mappedBy'], $sourceEntity);
            }
        }

        return $targetEntity;
    }

    /**
     * Refreshes a managed entity.
     *
     * @param array $id The identifier of the entity as an associative array from
     *                  column or field names to values.
     * @param object $entity The entity to refresh.
     */
    public function refresh(array $id, $entity)
    {
        $sql = $this->_getSelectEntitiesSQL($id);
        $stmt = $this->_conn->executeQuery($sql, array_values($id));
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $stmt->closeCursor();

        $metaColumns = array();
        $newData = array();

        // Refresh simple state
        foreach ($result as $column => $value) {
            $column = $this->_resultColumnNames[$column];
            if (isset($this->_class->fieldNames[$column])) {
                $fieldName = $this->_class->fieldNames[$column];
                $newValue = $this->_conn->convertToPHPValue($value, $this->_class->fieldMappings[$fieldName]['type']);
                $this->_class->reflFields[$fieldName]->setValue($entity, $newValue);
                $newData[$fieldName] = $newValue;
            } else {
                $metaColumns[$column] = $value;
            }
        }

        // Refresh associations
        foreach ($this->_class->associationMappings as $field => $assoc) {
            $value = $this->_class->reflFields[$field]->getValue($entity);
            if ($assoc['type'] & ClassMetadata::TO_ONE) {
                if ($value instanceof Proxy && ! $value->__isInitialized__) {
                    continue; // skip uninitialized proxies
                }

                if ($assoc['isOwningSide']) {
                    $joinColumnValues = array();
                    foreach ($assoc['targetToSourceKeyColumns'] as $targetColumn => $srcColumn) {
                        if ($metaColumns[$srcColumn] !== null) {
                            $joinColumnValues[$targetColumn] = $metaColumns[$srcColumn];
                        }
                    }
                    if ( ! $joinColumnValues && $value !== null) {
                        $this->_class->reflFields[$field]->setValue($entity, null);
                        $newData[$field] = null;
                    } else if ($value !== null) {
                        // Check identity map first, if the entity is not there,
                        // place a proxy in there instead.
                        $targetClass = $this->_em->getClassMetadata($assoc['targetEntity']);
                        if ($found = $this->_em->getUnitOfWork()->tryGetById($joinColumnValues, $targetClass->rootEntityName)) {
                            $this->_class->reflFields[$field]->setValue($entity, $found);
                            // Complete inverse side, if necessary.
                            if ($assoc['inversedBy']) {
                                $inverseAssoc = $targetClass->associationMappings[$assoc['inversedBy']];
                                $targetClass->reflFields[$inverseAssoc['fieldName']]->setValue($found, $entity);
                            }
                            $newData[$field] = $found;
                        } else {
                            // FIXME: What is happening with subClassees here?
                            $proxy = $this->_em->getProxyFactory()->getProxy($assoc['targetEntity'], $joinColumnValues);
                            $this->_class->reflFields[$field]->setValue($entity, $proxy);
                            $newData[$field] = $proxy;
                            $this->_em->getUnitOfWork()->registerManaged($proxy, $joinColumnValues, array());
                        }
                    }
                } else {
                    // Inverse side of 1-1/1-x can never be lazy.
                    //$newData[$field] = $assoc->load($entity, null, $this->_em);
                    $newData[$field] = $this->_em->getUnitOfWork()->getEntityPersister($assoc['targetEntity'])
                            ->loadOneToOneEntity($assoc, $entity, null);
                }
            } else if ($value instanceof PersistentCollection && $value->isInitialized()) {
                $value->setInitialized(false);
                $newData[$field] = $value;
            }
        }

        $this->_em->getUnitOfWork()->setOriginalEntityData($entity, $newData);
    }

    /**
     * Loads a list of entities by a list of field criteria.
     *
     * @param array $criteria
     * @return array
     */
    public function loadAll(array $criteria = array())
    {
        $entities = array();
        $sql = $this->_getSelectEntitiesSQL($criteria);
        $stmt = $this->_conn->executeQuery($sql, array_values($criteria));
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $stmt->closeCursor();

        foreach ($result as $row) {
            $entities[] = $this->_createEntity($row);
        }

        return $entities;
    }

    /**
     * Loads a collection of entities of a many-to-many association.
     *
     * @param ManyToManyMapping $assoc The association mapping of the association being loaded.
     * @param object $sourceEntity The entity that owns the collection.
     * @param PersistentCollection $coll The collection to fill.
     */
    public function loadManyToManyCollection(array $assoc, $sourceEntity, PersistentCollection $coll)
    {
        $criteria = array();
        $sourceClass = $this->_em->getClassMetadata($assoc['sourceEntity']);
        $joinTableConditions = array();
        if ($assoc['isOwningSide']) {
            foreach ($assoc['relationToSourceKeyColumns'] as $relationKeyColumn => $sourceKeyColumn) {
                if (isset($sourceClass->fieldNames[$sourceKeyColumn])) {
                    $criteria[$relationKeyColumn] = $sourceClass->reflFields[$sourceClass->fieldNames[$sourceKeyColumn]]->getValue($sourceEntity);
                } else {
                    throw MappingException::joinColumnMustPointToMappedField(
                        $sourceClass->name, $sourceKeyColumn
                    );
                }
            }
        } else {
            $owningAssoc = $this->_em->getClassMetadata($assoc['targetEntity'])->associationMappings[$assoc['mappedBy']];
            // TRICKY: since the association is inverted source and target are flipped
            foreach ($owningAssoc['relationToTargetKeyColumns'] as $relationKeyColumn => $sourceKeyColumn) {
                if (isset($sourceClass->fieldNames[$sourceKeyColumn])) {
                    $criteria[$relationKeyColumn] = $sourceClass->reflFields[$sourceClass->fieldNames[$sourceKeyColumn]]->getValue($sourceEntity);
                } else {
                    throw MappingException::joinColumnMustPointToMappedField(
                        $sourceClass->name, $sourceKeyColumn
                    );
                }
            }
        }

        $sql = $this->_getSelectEntitiesSQL($criteria, $assoc);
        $stmt = $this->_conn->executeQuery($sql, array_values($criteria));
        while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $coll->hydrateAdd($this->_createEntity($result));
        }
        $stmt->closeCursor();
    }

    /**
     * Creates or fills a single entity object from an SQL result.
     *
     * @param $result The SQL result.
     * @param object $entity The entity object to fill, if any.
     * @param array $hints Hints for entity creation.
     * @return object The filled and managed entity object or NULL, if the SQL result is empty.
     */
    private function _createEntity($result, $entity = null, array $hints = array())
    {
        if ($result === false) {
            return null;
        }

        list($entityName, $data) = $this->_processSQLResult($result);

        if ($entity !== null) {
            $hints[Query::HINT_REFRESH] = true;
            $id = array();
            if ($this->_class->isIdentifierComposite) {
                foreach ($this->_class->identifier as $fieldName) {
                    $id[$fieldName] = $data[$fieldName];
                }
            } else {
                $id = array($this->_class->identifier[0] => $data[$this->_class->identifier[0]]);
            }
            $this->_em->getUnitOfWork()->registerManaged($entity, $id, $data);
        }

        return $this->_em->getUnitOfWork()->createEntity($entityName, $data, $hints);
    }

    /**
     * Processes an SQL result set row that contains data for an entity of the type
     * this persister is responsible for.
     *
     * Subclasses are supposed to override this method if they need to change the
     * hydration procedure for entities loaded through basic find operations or
     * lazy-loading (not DQL).
     *
     * @param array $sqlResult The SQL result set row to process.
     * @return array A tuple where the first value is the actual type of the entity and
     *               the second value the prepared data of the entity (a map from field
     *               names to values).
     */
    protected function _processSQLResult(array $sqlResult)
    {
        $data = array();
        foreach ($sqlResult as $column => $value) {
            $column = $this->_resultColumnNames[$column];
            if (isset($this->_class->fieldNames[$column])) {
                $field = $this->_class->fieldNames[$column];
                if (isset($data[$field])) {
                    $data[$column] = $value;
                } else {
                    $data[$field] = Type::getType($this->_class->fieldMappings[$field]['type'])
                            ->convertToPHPValue($value, $this->_platform);
                }
            } else {
                $data[$column] = $value;
            }
        }

        return array($this->_class->name, $data);
    }

    /**
     * Gets the SELECT SQL to select one or more entities by a set of field criteria.
     *
     * @param array $criteria
     * @param AssociationMapping $assoc
     * @param string $orderBy
     * @param int $lockMode
     * @return string
     * @todo Refactor: _getSelectSQL(...)
     */
    protected function _getSelectEntitiesSQL(array $criteria, $assoc = null, $lockMode = 0)
    {
        $joinSql = $assoc != null && $assoc['type'] == ClassMetadata::MANY_TO_MANY ?
                $this->_getSelectManyToManyJoinSQL($assoc) : '';

        $conditionSql = $this->_getSelectConditionSQL($criteria, $assoc);

        $orderBySql = $assoc !== null && isset($assoc['orderBy']) ?
                $this->_getCollectionOrderBySQL($assoc['orderBy'], $this->_getSQLTableAlias($this->_class->name))
                : '';

        $lockSql = '';
        if ($lockMode == LockMode::PESSIMISTIC_READ) {
            $lockSql = ' ' . $this->_platform->getReadLockSql();
        } else if ($lockMode == LockMode::PESSIMISTIC_WRITE) {
            $lockSql = ' ' . $this->_platform->getWriteLockSql();
        }

        return 'SELECT ' . $this->_getSelectColumnListSQL()
             . ' FROM ' . $this->_class->getQuotedTableName($this->_platform) . ' '
             . $this->_getSQLTableAlias($this->_class->name)
             . $joinSql
             . ($conditionSql ? ' WHERE ' . $conditionSql : '')
             . $orderBySql
             . $lockSql;
    }

    /**
     * Gets the ORDER BY SQL snippet for ordered collections.
     *
     * @param array $orderBy
     * @param string $baseTableAlias
     * @return string
     * @todo Rename: _getOrderBySQL
     */
    protected final function _getCollectionOrderBySQL(array $orderBy, $baseTableAlias)
    {
        $orderBySql = '';
        foreach ($orderBy as $fieldName => $orientation) {
            if ( ! isset($this->_class->fieldMappings[$fieldName])) {
                ORMException::unrecognizedField($fieldName);
            }

            $tableAlias = isset($this->_class->fieldMappings[$fieldName]['inherited']) ?
                    $this->_getSQLTableAlias($this->_class->fieldMappings[$fieldName]['inherited'])
                    : $baseTableAlias;

            $columnName = $this->_class->getQuotedColumnName($fieldName, $this->_platform);
            $orderBySql .= $orderBySql ? ', ' : ' ORDER BY ';
            $orderBySql .= $tableAlias . '.' . $columnName . ' ' . $orientation;
        }

        return $orderBySql;
    }

    /**
     * Gets the SQL fragment with the list of columns to select when querying for
     * an entity in this persister.
     *
     * Subclasses should override this method to alter or change the select column
     * list SQL fragment. Note that in the implementation of BasicEntityPersister
     * the resulting SQL fragment is generated only once and cached in {@link _selectColumnListSql}.
     * Subclasses may or may not do the same.
     *
     * @return string The SQL fragment.
     * @todo Rename: _getSelectColumnsSQL()
     */
    protected function _getSelectColumnListSQL()
    {
        if ($this->_selectColumnListSql !== null) {
            return $this->_selectColumnListSql;
        }

        $columnList = '';

        // Add regular columns to select list
        foreach ($this->_class->fieldNames as $field) {
            if ($columnList) $columnList .= ', ';
            $columnList .= $this->_getSelectColumnSQL($field, $this->_class);
        }

        $this->_selectColumnListSql = $columnList . $this->_getSelectJoinColumnsSQL($this->_class);

        return $this->_selectColumnListSql;
    }

    /**
     * Gets the SQL join fragment used when selecting entities from a
     * many-to-many association.
     *
     * @param ManyToManyMapping $manyToMany
     * @return string
     */
    protected function _getSelectManyToManyJoinSQL(array $manyToMany)
    {
        if ($manyToMany['isOwningSide']) {
            $owningAssoc = $manyToMany;
            $joinClauses = $manyToMany['relationToTargetKeyColumns'];
        } else {
            $owningAssoc = $this->_em->getClassMetadata($manyToMany['targetEntity'])->associationMappings[$manyToMany['mappedBy']];
            $joinClauses = $owningAssoc['relationToSourceKeyColumns'];
        }

        $joinTableName = $this->_class->getQuotedJoinTableName($owningAssoc, $this->_platform);

        $joinSql = '';
        foreach ($joinClauses as $joinTableColumn => $sourceColumn) {
            if ($joinSql != '') $joinSql .= ' AND ';
            $joinSql .= $this->_getSQLTableAlias($this->_class->name) .
                    '.' . $this->_class->getQuotedColumnName($this->_class->fieldNames[$sourceColumn], $this->_platform) . ' = '
                    . $joinTableName . '.' . $joinTableColumn;
        }

        return " INNER JOIN $joinTableName ON $joinSql";
    }

    /**
     * Gets the INSERT SQL used by the persister to persist a new entity.
     *
     * @return string
     */
    protected function _getInsertSQL()
    {
        if ($this->_insertSql === null) {
            $insertSql = '';
            $columns = $this->_getInsertColumnList();
            if (empty($columns)) {
                $insertSql = $this->_platform->getEmptyIdentityInsertSQL(
                        $this->_class->getQuotedTableName($this->_platform),
                        $this->_class->getQuotedColumnName($this->_class->identifier[0], $this->_platform)
                );
            } else {
                $columns = array_unique($columns);
                $values = array_fill(0, count($columns), '?');

                $insertSql = 'INSERT INTO ' . $this->_class->getQuotedTableName($this->_platform)
                        . ' (' . implode(', ', $columns) . ') '
                        . 'VALUES (' . implode(', ', $values) . ')';
            }
            $this->_insertSql = $insertSql;
        }
        return $this->_insertSql;
    }

    /**
     * Gets the list of columns to put in the INSERT SQL statement.
     *
     * Subclasses should override this method to alter or change the list of
     * columns placed in the INSERT statements used by the persister.
     *
     * @return array The list of columns.
     */
    protected function _getInsertColumnList()
    {
        $columns = array();
        foreach ($this->_class->reflFields as $name => $field) {
            if ($this->_class->isVersioned && $this->_class->versionField == $name) {
                continue;
            }
            if (isset($this->_class->associationMappings[$name])) {
                $assoc = $this->_class->associationMappings[$name];
                if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) {
                    foreach ($assoc['targetToSourceKeyColumns'] as $sourceCol) {
                        $columns[] = $sourceCol;
                    }
                }
            } else if ($this->_class->generatorType != ClassMetadata::GENERATOR_TYPE_IDENTITY ||
                    $this->_class->identifier[0] != $name) {
                $columns[] = $this->_class->getQuotedColumnName($name, $this->_platform);
            }
        }

        return $columns;
    }

    /**
     * Gets the SQL snippet of a qualified column name for the given field name.
     *
     * @param string $field The field name.
     * @param ClassMetadata $class The class that declares this field. The table this class is
     *                             mapped to must own the column for the given field.
     */
    protected function _getSelectColumnSQL($field, ClassMetadata $class)
    {
        $columnName = $class->columnNames[$field];
        $sql = $this->_getSQLTableAlias($class->name) . '.' . $class->getQuotedColumnName($field, $this->_platform);
        $columnAlias = $this->_platform->getSQLResultCasing($columnName . $this->_sqlAliasCounter++);
        if ( ! isset($this->_resultColumnNames[$columnAlias])) {
            $this->_resultColumnNames[$columnAlias] = $columnName;
        }

        return "$sql AS $columnAlias";
    }

    /**
     * Gets the SQL snippet for all join columns of the given class that are to be
     * placed in an SQL SELECT statement.
     *
     * @param $class
     * @return string
     * @todo Not reused... inline?
     */
    private function _getSelectJoinColumnsSQL(ClassMetadata $class)
    {
        $sql = '';
        foreach ($class->associationMappings as $assoc) {
            if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) {
                foreach ($assoc['targetToSourceKeyColumns'] as $srcColumn) {
                    $columnAlias = $srcColumn . $this->_sqlAliasCounter++;
                    $sql .= ', ' . $this->_getSQLTableAlias($this->_class->name) . ".$srcColumn AS $columnAlias";
                    $resultColumnName = $this->_platform->getSQLResultCasing($columnAlias);
                    if ( ! isset($this->_resultColumnNames[$resultColumnName])) {
                        $this->_resultColumnNames[$resultColumnName] = $srcColumn;
                    }
                }
            }
        }

        return $sql;
    }

    /**
     * Gets the SQL table alias for the given class name.
     *
     * @param string $className
     * @return string The SQL table alias.
     * @todo Reconsider. Binding table aliases to class names is not such a good idea.
     */
    protected function _getSQLTableAlias($className)
    {
        if (isset($this->_sqlTableAliases[$className])) {
            return $this->_sqlTableAliases[$className];
        }
        $tableAlias = 't' . $this->_sqlAliasCounter++;
        $this->_sqlTableAliases[$className] = $tableAlias;

        return $tableAlias;
    }

    /**
     * Lock all rows of this entity matching the given criteria with the specified pessimistic lock mode
     *
     * @param array $criteria
     * @param int $lockMode
     * @return void
     */
    public function lock(array $criteria, $lockMode)
    {
        $conditionSql = $this->_getSelectConditionSQL($criteria);

        if ($lockMode == LockMode::PESSIMISTIC_READ) {
            $lockSql = $this->_platform->getReadLockSql();
        } else if ($lockMode == LockMode::PESSIMISTIC_WRITE) {
            $lockSql = $this->_platform->getWriteLockSql();
        }

        $sql = 'SELECT 1 '
             . $this->getLockTablesSql()
             . ($conditionSql ? ' WHERE ' . $conditionSql : '') . ' ' . $lockSql;
        $params = array_values($criteria);
        $this->_conn->executeQuery($sql, $params);
    }

    /**
     * Get the FROM and optionally JOIN conditions to lock the entity managed by this persister.
     *
     * @return string
     */
    protected function getLockTablesSql()
    {
        return 'FROM ' . $this->_class->getQuotedTableName($this->_platform) . ' '
                . $this->_getSQLTableAlias($this->_class->name);
    }

    /**
     * Gets the conditional SQL fragment used in the WHERE clause when selecting
     * entities in this persister.
     *
     * Subclasses are supposed to override this method if they intend to change
     * or alter the criteria by which entities are selected.
     *
     * @param array $criteria
     * @param AssociationMapping $assoc
     * @return string
     */
    protected function _getSelectConditionSQL(array $criteria, $assoc = null)
    {
        $conditionSql = '';
        foreach ($criteria as $field => $value) {
            $conditionSql .= $conditionSql ? ' AND ' : '';

            if (isset($this->_class->columnNames[$field])) {
                if (isset($this->_class->fieldMappings[$field]['inherited'])) {
                    $conditionSql .= $this->_getSQLTableAlias($this->_class->fieldMappings[$field]['inherited']) . '.';
                } else {
                    $conditionSql .= $this->_getSQLTableAlias($this->_class->name) . '.';
                }
                $conditionSql .= $this->_class->getQuotedColumnName($field, $this->_platform);
            } else if ($assoc !== null) {
                if ($assoc['type'] == ClassMetadata::MANY_TO_MANY) {
                    $owningAssoc = $assoc['isOwningSide'] ? $assoc : $this->_em->getClassMetadata($assoc['targetEntity'])
                            ->associationMappings[$assoc['mappedBy']];
                    $conditionSql .= $this->_class->getQuotedJoinTableName($owningAssoc, $this->_platform) . '.' . $field;
                } else {
                    $conditionSql .= $field;
                }
            } else {
                throw ORMException::unrecognizedField($field);
            }
            $conditionSql .= ' = ?';
        }
        return $conditionSql;
    }

    /**
     * Loads a collection of entities in a one-to-many association.
     *
     * @param OneToManyMapping $assoc
     * @param array $criteria The criteria by which to select the entities.
     * @param PersistentCollection The collection to load/fill.
     */
    public function loadOneToManyCollection(array $assoc, $sourceEntity, PersistentCollection $coll)
    {
        $criteria = array();
        $owningAssoc = $this->_class->associationMappings[$assoc['mappedBy']];
        $sourceClass = $this->_em->getClassMetadata($assoc['sourceEntity']);
        foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) {
            $criteria[$targetKeyColumn] = $sourceClass->reflFields[$sourceClass->fieldNames[$sourceKeyColumn]]->getValue($sourceEntity);
        }

        $sql = $this->_getSelectEntitiesSQL($criteria, $assoc);
        $params = array_values($criteria);
        $stmt = $this->_conn->executeQuery($sql, $params);
        while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $coll->hydrateAdd($this->_createEntity($result));
        }
        $stmt->closeCursor();
    }

    /**
     * Checks whether the given managed entity exists in the database.
     *
     * @param object $entity
     * @return boolean TRUE if the entity exists in the database, FALSE otherwise.
     */
    public function exists($entity)
    {
        $criteria = $this->_class->getIdentifierValues($entity);
        $sql = 'SELECT 1 FROM ' . $this->_class->getQuotedTableName($this->_platform)
                . ' ' . $this->_getSQLTableAlias($this->_class->name)
                . ' WHERE ' . $this->_getSelectConditionSQL($criteria);

        return (bool) $this->_conn->fetchColumn($sql, array_values($criteria));
    }

    //TODO
    /*protected function _getOneToOneEagerFetchSQL()
    {

    }*/
}


text:
<title>Berkeley DB: DbEnv::txn_recover</title>
<meta name="description" content="Berkeley DB: An embedded database programmatic toolkit.">
<meta name="keywords" content="embedded,database,programmatic,toolkit,btree,hash,hashing,transaction,transactions,locking,logging,access method,access methods,Java,C,C++">

DbEnv::txn_recover

<tt>

#include <db_cxx.h>

int
DbEnv::txn_recover(DB_PREPLIST preplist[],
    long count, long *retp, u_int32_t flags);

Description: DbEnv::txn_recover

Database environment recovery restores transactions that were prepared,
but not yet resolved at the time of the system shut down or crash, to
their state prior to the shut down or crash, including any locks
previously held.  The DbEnv::txn_recover method returns a list of those
prepared transactions.

The DbEnv::txn_recover method should only be called after the environment has
been recovered.

Multiple threads of control may call DbEnv::txn_recover, but only one
thread of control may resolve each returned transaction, that is, only
one thread of control may call DbTxn::commit or DbTxn::abort
on each returned transaction.  Callers of DbEnv::txn_recover must call
DbTxn::discard to discard each transaction they do not resolve.

On return from DbEnv::txn_recover, the preplist parameter will
be filled in with a list of transactions that must be resolved by the
application (committed, aborted or discarded).  The preplist
parameter is a structure of type DB_PREPLIST; the following DB_PREPLIST
fields will be filled in:

DB_TXN * txn;

The transaction handle for the transaction.

u_int8_t gid[DB_XIDDATASIZE];

The global transaction ID for the transaction.  The global transaction
ID is the one specified when the transaction was prepared.  The
application is responsible for ensuring uniqueness among global
transaction IDs.

The DbEnv::txn_recover method
either returns a non-zero error value
or throws an exception that encapsulates a non-zero error value on
failure, and returns 0 on success.

Parameters

 count

The count parameter specifies the number of available entries
in the passed-in preplist array.  The retp parameter
returns the number of entries DbEnv::txn_recover has filled in, in the
array.

 flags

The flags parameter must be set to one of the following values:

DB_FIRST

Begin returning a list of prepared, but not yet resolved transactions.
Specifying this flag begins a new pass over all prepared, but not yet
completed transactions, regardless of whether they have already been returned
in previous calls to DbEnv::txn_recover.
Calls to DbEnv::txn_recover from different threads of control should not
be intermixed in the same environment.

DB_NEXT

Continue returning a list of prepared, but not yet resolved transactions,
starting where the last call to DbEnv::txn_recover left off.

 preplist

The preplist parameter references memory into which
 the list of transactions to be resolved by the application is copied.

Class
DbEnv, DbTxn

See Also
Transaction Subsystem and Related Methods
</tt>

Copyright (c) 1996,2008 Oracle.  All rights reserved.

redpajama_set_name: RedPajamaGithub


text:
You can access it on the account details page in the "Billing Summary" tab.

Update Interest.

Click on the "Update Interest" button and a new popup will open.

Update Interest Popup.

The interest is calculated and the new invoice appears. The technician must print out this invoice
and mail it to the claimant. It will not be printed by the nightly batch process.

Update Interest Statement.

If the printer jams or the paper is lost, you can reprint this invoice on the same day that you updated
the interest. The "Update Interest" button is still enabled so you can click it again.
Clicking on it again brings up a new prompt.

Update an Already Updated Interest Popup.

When you click "OK", the same invoice appears again because the program did not do another calculation.


text:
Tool for copying and comparing data in Firebird databases

**Features**

*   Copy data between Firebird databases
*   Ability to compare data in databases
*   Can disable triggers to avoid side-effects
*   Understands foreign keys so order of copying is correct
*   Can work in overwrite mode (UPDATE if INSERT fails)
*   Open source under Expat (a.k.a. MIT) license
*   Now you can freely use any part of FBCopy code in your applications
*   Read [HTML manual](fbcopy-manual.html) for usage instructions

**What does it do?**

With FBCopy, you can easily **copy data** between Firebird tables
and databases. FBCopy is a command-line tool, so
you can use it inside batch scripts, cron jobs, etc. Currently,
Linux and Windows versions are available, but I hope it can be built
with any compiler that can build IBPP library. It has been tested and
works on FreeBSD as well.

You can also **compare data** in different databases. It
can output a simple tabular overview of different/same records, or a detailed HTML that
shows each record in both databases. See [manual](fbcopy-manual.html) for details.

**Why use it?**

I was trying to copy data from one
[Firebird](http://www.firebirdsql.org) database to another.
There are a lot of nice GUI tools that do it, but they all require thay
you have fast access to database. Both databases I had were on
remote server, and all I had was
console access via ssh. Databases were too big to copy them to my
machine, pump the data, and copy back. So I had to pump on the server.
There were no tools for this, so I decided to write one.

**Restrictions**

This tool uses [IBPP library](http://ibpp.sourceforge.net/)
for database access. It supports Firebird 1.0, 1.5, 2.0
databases. If it works for you, please let me
know. As IBPP project grows, I hope to support all database engines
they do.

FBExport doesn't support ARRAY datatype yet. If you need it, please let
[me](mailto:mbabuskov@yahoo.com) know. Also, dialect 1 is not
supported at this time, only Dialect 3.

**License**

FBCopy is Free Software, released under Expat (a.k.a. MIT) license

**Download**

Latest version can be downloaded from [Firebird FAQ website](http://www.firebirdfaq.org/fbcopy.php).


text:
		<title>BUL - Les jeux de bebel</title>
		<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <meta http-equiv="Cache-Control" content="no-cache" />
        <meta http-equiv="X-UA-Compatible" content="IE=Edge" />

        <link rel="shortcut icon" href="app/img/favicon.png" type="image/png">

        <link rel="stylesheet" href="app/css/style.css">


text:
package org.jbson;

import java.io.*;

import org.jruby.*;

import org.bson.*;
import org.bson.io.*;
import org.bson.types.*;
import static org.bson.BSON.*;

public class RubyBSONDecoder extends BasicBSONDecoder {

      protected void _binary( String name )
          throws IOException {
          final int totalLen = _in.readInt();
          final byte bType = _in.read();

          if( bType == 2 ) {
              final int len = _in.readInt();
              if ( len + 4 != totalLen )
                  throw new IllegalArgumentException("Error! Bad data size (Sub-Type 2 Length: " + len +
                                                     ", Total Length: " + totalLen );

              final byte[] data = new byte[len];
              _in.fill( data );
              _callback.gotBinary( name, (byte)2, data );
          }
          else {
              byte[] data = new byte[totalLen];
              _in.fill( data );
              _callback.gotBinary( name, bType, data );
          }
     }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
                                    xmlns:app="http://schemas.android.com/apk/res-auto"
                                    android:layout_width="match_parent"
                                    android:layout_height="wrap_content"
                                    android:layout_marginTop="6dp"
                                    android:layout_marginBottom="6dp"
                                    android:layout_marginLeft="12dp"
                                    android:layout_marginRight="12dp"
                                    app:cardElevation="6dp"
                                    android:id="@+id/cardView">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
        <com.android.volley.toolbox.NetworkImageView
            android:layout_width="46dp"
            android:layout_height="46dp"
            android:id="@+id/profile_image"
            android:layout_marginTop="8dp"
            android:layout_marginLeft="8dp"
            android:visibility="gone"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="16dp"
            android:id="@+id/title"
            android:layout_marginTop="12dp"
            android:paddingLeft="12dp"
            android:layout_toRightOf="@+id/profile_image"
            android:paddingTop="6dp"
            android:layout_marginBottom="8dp"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="CLUBS, ASSOCIATIONS  NON-GOVERNMENTAL ORGANIZATIONS"

            />
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginLeft="12dp"
            android:layout_marginRight="12dp"
            android:id="@+id/addressRel"
            android:layout_below="@+id/title">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/address"
                android:gravity="center_vertical|start"
                android:text="calabarjjjjjj njnjnkjgy gyujyvjy ftftyuft ftfytdt dtyddr
                fttftytygg"
                android:paddingRight="6dp"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_toRightOf="@+id/home_icon"
                android:layout_toEndOf="@+id/home_icon" />
        </RelativeLayout>
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginLeft="12dp"
            android:layout_marginRight="12dp"
            android:layout_below="@+id/addressRel"
            android:id="@+id/workRel">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/workingDays"
                android:gravity="center_vertical|start"
                android:text="Mon - Sat 8-5"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_toRightOf="@+id/work_days"
                android:layout_toEndOf="@+id/work_days" />

        </RelativeLayout>
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/workRel"
            android:layout_marginLeft="12dp"
            android:layout_marginRight="12dp"
            android:layout_marginBottom="8dp"
            android:id="@+id/phoneRel">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_vertical|start"
                android:text="07033383068"
                android:id="@+id/contact"
                android:paddingRight="6dp"
                android:linksClickable="true"
                android:autoLink="phone"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_toRightOf="@+id/phone_icon"
                android:layout_toEndOf="@+id/phone_icon" />

        </RelativeLayout>
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/specialRel"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="12dp"
            android:layout_below="@+id/phoneRel"
            android:layout_marginBottom="6dp">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/specialisation"
                android:gravity="center_vertical|start"
                android:text="Tiling"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_toRightOf="@+id/unit_icon"
                android:layout_toEndOf="@+id/unit_icon" />

        </RelativeLayout>

        <Button
            android:text="Call"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/call"
            android:elevation="8dp"
            android:visibility="gone"
            android:backgroundTint="@color/colorPrimary"
            android:layout_below="@+id/specialRel"
            android:layout_alignParentRight="true"
            android:layout_marginBottom="12dp"
            android:layout_alignParentEnd="true" />

        <TextView
            android:text="0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView4"
            android:layout_marginTop="12dp"
            android:textAppearance="?android:textAppearanceLarge"
            android:layout_marginBottom="12dp"
            android:layout_below="@+id/specialRel"
            android:layout_toLeftOf="@+id/textView6"
            android:layout_marginRight="6dp"
            />

        <TextView
            android:text="Reviews"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView6"
            android:layout_marginRight="12dp"
            android:textAppearance="?android:textAppearanceMedium"
            android:layout_alignBaseline="@+id/textView4"
            android:layout_alignBottom="@+id/textView4"
            android:layout_alignParentRight="true" />

    </RelativeLayout>
</android.support.v7.widget.CardView>


text:
echo ""
echo "Customize Image"
echo ""

cd ~/
## Create Links on Desktop
mkdir -p ~/Desktop
ln -s ~/eclipse/eclipse ~/Desktop/eclipse

ln -s ~/${REPO_NAME} ~/Desktop/${REPO_NAME}
ln -s ~/${REPO_NAME}/README.md ~/Desktop/README.md

echo ""
echo "Customization Done"
echo ""


text:
package logic

import (
	"testing"
	"time"

	"github.com/gunsluo/go-example/xorm/models"
)

func TestGetInspectorById(t *testing.T) {
	expect := &models.Inspector{
		Id:       1,
		Username: "luoji",
		Password: "luoji",
		Created:  time.Now(),
	}

	session := newSession()

	inspector := &models.Inspector{}
	has, err := GetInspectorById(session, inspector, 1)
	if err != nil {
		t.Fatal(err)
	}

	if !has {
		t.Fatal("not found")
	}

	if inspector.Id != expect.Id {
		t.Fatal("failed GetInsinspectorById")
	}
}


text:
package auth

import (
	"fmt"
)

// SessionCookie implements session cookie authentication.
type SessionCookie struct {
	cookie    []byte
	logonname string
	clientID  string
}

// NewSessionCookie creates a new authSessionCookie instance.
func NewSessionCookie(cookie []byte, logonname, clientID string) *SessionCookie {
	return &SessionCookie{cookie: cookie, logonname: logonname, clientID: clientID}
}

func (a *SessionCookie) String() string {
	return fmt.Sprintf("method type %s cookie %v", a.Typ(), a.cookie)
}

// Typ implements the CookieGetter interface.
func (a *SessionCookie) Typ() string { return MtSessionCookie }

// Order implements the CookieGetter interface.
func (a *SessionCookie) Order() byte { return MoSessionCookie }

// PrepareInitReq implements the Method interface.
func (a *SessionCookie) PrepareInitReq(prms *Prms) error {
	prms.addString(a.Typ())
	prms.addBytes(append(a.cookie, a.clientID...)) // cookie + clientID !!!
	return nil
}

// InitRepDecode implements the Method interface.
func (a *SessionCookie) InitRepDecode(d *Decoder) error {
	return nil
}

// PrepareFinalReq implements the Method interface.
func (a *SessionCookie) PrepareFinalReq(prms *Prms) error {
	prms.AddCESU8String(a.logonname)
	prms.addString(a.Typ())
	prms.addEmpty() // empty parameter
	return nil
}

// FinalRepDecode implements the Method interface.
func (a *SessionCookie) FinalRepDecode(d *Decoder) error {
	if err := d.NumPrm(2); err != nil {
		return err
	}
	mt := d.String()
	if err := checkAuthMethodType(mt, a.Typ()); err != nil {
		return err
	}
	d.bytes() // second parameter seems to be empty
	return nil
}


text:
from ..lib import elasticbeanstalk

def get_all_platforms():
    return elasticbeanstalk.get_available_solution_stacks()

def get_environment_platform(app_name, env_name):
    env = elasticbeanstalk.get_environment(app_name, env_name)
    return env.platform


text:
package com.netthreads.transportation.parser;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;

/**
 * Stream parser implementation.
 *
 */
public class StreamParserImpl<T> implements StreamParser<T>
{
	public static final String TEXT_LINK_DELIMETER = ";";
	public static final String TEXT_TITLE_DELIMETER = " ";

	private JsonFactory factory;
	private JsonParser parser;

	// Control
	private int state = WAITING;

	public StreamParserImpl()
	{
		factory = new JsonFactory();
	}

	/**
	 * Fetch and parse data.
	 *
	 * @param stream
	 * @param list
	 * @param dataFactory
	 */
	@Override
	public int fetch(InputStream stream, List<T> list, DataFactory<T> dataFactory, JSONParser<T> pullParser)
	{
		state = BUSY;

		reset();

		try
		{
			parser = factory.createJsonParser(stream);

			JsonToken jsonToken = null;

			while ((jsonToken = parser.nextToken()) != null)
			{
				if (jsonToken.equals(JsonToken.START_OBJECT))
				{
					String tag = parser.getCurrentName();

					if (tag != null)
					{
						pullParser.processStartObject(tag, parser);
					}
				}
				else if (jsonToken.equals(JsonToken.END_OBJECT))
				{
					String tag = parser.getCurrentName();

					if (tag != null)
					{
						// Returns true when object complete.
						if (pullParser.processEndObject(tag, parser))
						{
							// Create holding record
							T data = dataFactory.createRecord();

							pullParser.populateRecord(data);

							list.add(data);
						}
					}
				}
				else
				{
					pullParser.processObject(parser);
				}

			}
		}
		catch (JsonParseException e)
		{
			// Oops
			state = ERROR;
		}
		catch (IOException e)
		{
			// Oops
			state = ERROR;
		}

		if (state != CANCELLED && state != ERROR)
		{
			state = DONE;
		}

		return state;
	}

	/**
	 * Stops the handler process.
	 *
	 */
	@Override
	public void cancel()
	{
		state = CANCELLED;
	}

	/**
	 * Reset parser state.
	 *
	 */
	@Override
	public void reset()
	{
		state = WAITING;
	}

	/**
	 * Return parser state code.
	 *
	 */
	@Override
	public int getState()
	{
		return state;
	}

}


text:
exports.postTest = function(config, passed, testInfo) {
  var nameCorrect = testInfo.name == 'name';
  var categoryCorrect = testInfo.category == 'category';
  return {
    failedCount: passed && nameCorrect && categoryCorrect ? 0 : 1,
    specResults: [{
      description: 'make sure postTest passed correct information',
      assertions: [{
        passed: passed,
        errorMsg: passed ? undefined : '`passed` should have been `true`, but' +
            ' got `' + JSON.stringify(passed) + '`'
      }, {
        passed: nameCorrect,
        errorMsg: nameCorrect ? undefined : '`testInfo.name` should have been' +
            ' `"name"`, but got `' + JSON.stringify(testInfo.name) + '`'
      }, {
        passed: categoryCorrect,
        errorMsg: categoryCorrect ? undefined : '`testInfo.category` should ' +
            'have been `"category"`, but got `' +
            JSON.stringify(testInfo.category) + '`'
      }],
      duration: 0
    }]
  };
};


text:
using System;
using System.Web.Http;

namespace Swashbuckle.Dummy.Controllers
{
    public class IndexerTypesController : ApiController
    {
        public int Create(Lookup lookup)
        {
            throw new NotImplementedException();
        }
    }

    public class Lookup
    {
        public int TotalEntries { get; set; }

        public string this[string name]
        {
            get { throw new NotImplementedException(); }
        }

        public string this[int index]
        {
            get { throw new NotImplementedException(); }
        }
    }
}


text:
<?php

namespace Google\Service\RecommendationsAI;

class GoogleCloudRecommendationengineV1beta1CatalogItemLevelConfig extends \Google\Model
{
  /**
   * @var string
   */
  public $eventItemLevel;
  /**
   * @var string
   */
  public $predictItemLevel;

  /**
   * @param string
   */
  public function setEventItemLevel($eventItemLevel)
  {
    $this->eventItemLevel = $eventItemLevel;
  }
  /**
   * @return string
   */
  public function getEventItemLevel()
  {
    return $this->eventItemLevel;
  }
  /**
   * @param string
   */
  public function setPredictItemLevel($predictItemLevel)
  {
    $this->predictItemLevel = $predictItemLevel;
  }
  /**
   * @return string
   */
  public function getPredictItemLevel()
  {
    return $this->predictItemLevel;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleCloudRecommendationengineV1beta1CatalogItemLevelConfig::class, 'Google_Service_RecommendationsAI_GoogleCloudRecommendationengineV1beta1CatalogItemLevelConfig');


text:
{# http://www.chromium.org/blink/coding-style#TOC-License #}

{# FIXME: Rename to Python when switch #}
// This file has been auto-generated by code_generator_v8.pm. DO NOT MODIFY!

#include "config.h"
{% filter conditional(conditional_string) %}
#include "{{v8_class}}.h"

{% for filename in cpp_includes %}
#include "{{filename}}"
{% endfor %}

namespace WebCore {

static void initializeScriptWrappableForInterface({{cpp_class}}* object)
{
    if (ScriptWrappable::wrapperCanBeStoredInObject(object))
        ScriptWrappable::setTypeInfoInObject(object, &{{v8_class}}::wrapperTypeInfo);
    else
        ASSERT_NOT_REACHED();
}

} // namespace WebCore

// In ScriptWrappable::init, the use of a local function declaration has an issue on Windows:
// the local declaration does not pick up the surrounding namespace. Therefore, we provide this function
// in the global namespace.
// (More info on the MSVC bug here: http://connect.microsoft.com/VisualStudio/feedback/details/664619/the-namespace-of-local-function-declarations-in-c)
void webCoreInitializeScriptWrappableForInterface(WebCore::{{cpp_class}}* object)
{
    WebCore::initializeScriptWrappableForInterface(object);
}

namespace WebCore {
{% set to_active_dom_object = '%s::toActiveDOMObject' % v8_class
                              if is_active_dom_object else '0' %}
{% set to_event_target = '%s::toEventTarget' % v8_class
                         if is_event_target else '0' %}
{% set visit_dom_wrapper = '%s::visitDOMWrapper' % v8_class
                           if has_visit_dom_wrapper else '0' %}
{% set parent_wrapper_type_info = '&V8%s::wrapperTypeInfo' % parent_interface
                                  if parent_interface else '0' %}
const WrapperTypeInfo {{v8_class}}::wrapperTypeInfo = { gin::kEmbedderBlink, {{v8_class}}::domTemplate, {{v8_class}}::derefObject, {{to_active_dom_object}}, {{to_event_target}}, {{visit_dom_wrapper}}, {{v8_class}}::installPerContextEnabledMethods, {{parent_wrapper_type_info}}, WrapperTypeObjectPrototype };

namespace {{cpp_class}}V8Internal {

template <typename T> void V8_USE(T) { }

{# Attributes #}
{% from 'attributes.cpp' import attribute_getter, attribute_getter_callback,
       attribute_setter, attribute_setter_callback
   with context %}
{% for attribute in attributes if not attribute.constructor_type %}
{% for world_suffix in attribute.world_suffixes %}
{% if not attribute.has_custom_getter %}
{{attribute_getter(attribute, world_suffix)}}
{% endif %}
{{attribute_getter_callback(attribute, world_suffix)}}
{% if not attribute.is_read_only %}
{% if not attribute.has_custom_setter %}
{{attribute_setter(attribute, world_suffix)}}
{% endif %}
{{attribute_setter_callback(attribute, world_suffix)}}
{% endif %}
{% endfor %}
{% endfor %}
{% block constructor_getter %}{% endblock %}
{% block replaceable_attribute_setter_and_callback %}{% endblock %}
{% block security_check_functions %}{% endblock %}
{# Methods #}
{% from 'methods.cpp' import generate_method, overload_resolution_method,
       method_callback, origin_safe_method_getter, generate_constructor
       with context %}
{% for method in methods %}
{% for world_suffix in method.world_suffixes %}
{% if not method.is_custom %}
{{generate_method(method, world_suffix)}}
{% endif %}
{% if method.overloads %}
{{overload_resolution_method(method.overloads, world_suffix)}}
{% endif %}
{% if not method.overload_index or method.overloads %}
{# A single callback is generated for overloaded methods #}
{{method_callback(method, world_suffix)}}
{% endif %}
{% if method.is_do_not_check_security %}
{{origin_safe_method_getter(method, world_suffix)}}
{% endif %}
{% endfor %}
{% endfor %}
{% block origin_safe_method_setter %}{% endblock %}
{# Constructors #}
{% for constructor in constructors %}
{{generate_constructor(constructor)}}
{% endfor %}
{% block overloaded_constructor %}{% endblock %}
{% block event_constructor %}{% endblock %}
} // namespace {{cpp_class}}V8Internal

{% block visit_dom_wrapper %}{% endblock %}
{% block class_attributes %}{% endblock %}
{% block class_accessors %}{% endblock %}
{% block class_methods %}{% endblock %}
{% block named_constructor %}{% endblock %}
{% block initialize_event %}{% endblock %}
{% block constructor_callback %}{% endblock %}
{% block configure_class_template %}{% endblock %}
{% block get_template %}{% endblock %}
{% block has_instance_and_has_instance_in_any_world %}{% endblock %}
{% block install_per_context_attributes %}{% endblock %}
{% block install_per_context_methods %}{% endblock %}
{% block to_active_dom_object %}{% endblock %}
{% block to_event_target %}{% endblock %}
{% block wrap %}{% endblock %}
{% block create_wrapper %}{% endblock %}
{% block deref_object_and_to_v8_no_inline %}{% endblock %}
} // namespace WebCore
{% endfilter %}


text:
package io.engagingspaces.graphql.servicediscovery.publisher;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

/**
 * Tests for partial publish exception.
 *
 * @author Arnold Schrijver
 */
public class PartialPublishExceptionTest {

    PartialPublishException ex;

    @Test
    @SuppressWarnings("ThrowableInstanceNeverThrown")
    public void should_Report_And_Return_Publication_Errors() {
        List<Throwable> errors = Arrays.asList(new RuntimeException("Error1"), new RuntimeException("Error2"));
        ex = new PartialPublishException("Publication error test", errors);
        assertEquals("Publication error test", ex.getMessage());
        assertEquals(2, ex.getPublicationErrors().size());
        ex = new PartialPublishException(errors);
        assertEquals("Failed to publish all schema definitions. 2 errors occurred:\n - Error1\n - Error2",
                ex.getMessage());
    }

    @Test
    @SuppressWarnings("ThrowableInstanceNeverThrown")
    public void should_Have_Regular_Exception_Constructors() {
        ex = new PartialPublishException();
        ex = new PartialPublishException("msg");
        ex = new PartialPublishException(new RuntimeException());
        ex = new PartialPublishException("msg", new RuntimeException());
        assertNotNull(ex.getPublicationErrors());
        assertEquals(0, ex.getPublicationErrors().size());
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>Comments for page "Quality Polearm"</title>
		<link>http://bvs.wikidot.com/forum/t-157320/quality-polearm</link>
		<description>Posts in the discussion thread "Quality Polearm"</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 03:53:23 +0000</lastBuildDate>

					<item>
				<guid>http://bvs.wikidot.com/forum/t-157320#post-485922</guid>
				<title>(no title)</title>
				<link>http://bvs.wikidot.com/forum/t-157320/quality-polearm#post-485922</link>
				<description></description>
				<pubDate>Thu, 21 May 2009 11:45:56 +0000</pubDate>
				<wikidot:authorName>bbr</wikidot:authorName>								<content:encoded>
					<![CDATA[

distills into average gear

				 	]]>
				</content:encoded>							</item>
				</channel>
</rss>


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

<title>ShapePreservingDFZeroSmooth</title>
<meta name="date" content="2014-01-13">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.drip.sample.rates

Class ShapePreservingDFZeroSmooth

java.lang.Object

org.drip.sample.rates.ShapePreservingDFZeroSmooth

public class ShapePreservingDFZeroSmooth
extends java.lang.Object

ShapePreservingDFZeroSmooth demonstrates the usage of different shape preserving and smoothing techniques
  involved in the discount curve creation. It shows the following:
        - Construct the Array of Cash/Swap Instruments and their Quotes from the given set of parameters.
        - Construct the Cash/Swap Instrument Set Stretch Builder.
        - Set up the Linear Curve Calibrator using the following parameters:
                - Cubic Exponential Mixture Basis Spline Set
                - Ck = 2, Segment Curvature Penalty = 2
                - Quadratic Rational Shape Controller
                - Natural Boundary Setting
        - Set up the Global Curve Control parameters as follows:
                - Zero Rate Quantification Metric
                - Cubic Polynomial Basis Spline Set
                - Ck = 2, Segment Curvature Penalty = 2
                - Quadratic Rational Shape Controller
                - Natural Boundary Setting
        - Set up the Local Curve Control parameters as follows:
                - C1 Bessel Monotone Smoothener with no spurious extrema elimination and no monotone filter
                - Zero Rate Quantification Metric
                - Cubic Polynomial Basis Spline Set
                - Ck = 2, Segment Curvature Penalty = 2
                - Quadratic Rational Shape Controller
                - Natural Boundary Setting
        - Construct the Shape Preserving Discount Curve by applying the linear curve calibrator to the array of
                Cash and Swap Stretches.
        - Construct the Globally Smoothened Discount Curve by applying the linear curve calibrator and the Global
                Curve Control parameters to the array of Cash and Swap Stretches and the shape preserving discount
                curve.
        - Construct the Locally Smoothened Discount Curve by applying the linear curve calibrator and the Local
                Curve Control parameters to the array of Cash and Swap Stretches and the shape preserving discount
        curve.
        - Cross-Comparison of the Cash/Swap Calibration Instrument "Rate" metric across the different curve
                construction methodologies.
  - Cross-Comparison of the Swap Calibration Instrument "Rate" metric across the different curve
        construction methodologies for a sequence of bespoke swap instruments.

Constructor Summary

Constructors

Constructor and Description

ShapePreservingDFZeroSmooth()

Method Summary

Methods

Modifier and Type
Method and Description

static void
main(java.lang.String[] astrArgs)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ShapePreservingDFZeroSmooth

public ShapePreservingDFZeroSmooth()

Method Detail

main

public static final void main(java.lang.String[] astrArgs)
                       throws java.lang.Exception

Throws:

java.lang.Exception

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package org.wikiup.database.impl;

import org.wikiup.database.inf.ConnectionProvider;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class DataSourceWithAuthConnectionProvider implements ConnectionProvider {
    private DataSource dataSource;
    private String name;
    private String password;

    public DataSourceWithAuthConnectionProvider(DataSource ds, String name, String password) {
        dataSource = ds;
        this.name = name;
        this.password = password;
    }

    public Connection getConnection() throws SQLException {
        return dataSource.getConnection(name, password);
    }
}


text:
<?php

/**
 * Selective dynamic class properties aggregation to an object
 *
 * @phpstub
 *
 * @param object $object
 * @param string $class_name
 * @param array $properties_list
 * @param bool $exclude
 *
 * @return void
 */
function aggregate_properties_by_list($object, $class_name, $properties_list, $exclude = false)
{
}


text:
////////////////////////////////////////////////////////////////////////////////
/// @brief memory mapped files in posix
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Oreste Costa-Panaia
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "memory-map.h"

#ifdef TRI_HAVE_POSIX_MMAP

#include "Basics/logging.h"
#include "Basics/tri-strings.h"

#include <sys/mman.h>

////////////////////////////////////////////////////////////////////////////////
// @brief flush memory mapped file to disk
////////////////////////////////////////////////////////////////////////////////

int TRI_FlushMMFile (int fileDescriptor,
                     void** mmHandle,
                     void* startingAddress,
                     size_t numOfBytesToFlush,
                     int flags) {

  // ...........................................................................
  // Possible flags to send are (based upon the Ubuntu Linux ASM include files:
  // #define MS_ASYNC        1             /* sync memory asynchronously */
  // #define MS_INVALIDATE   2               /* invalidate the caches */
  // #define MS_SYNC         4               /* synchronous memory sync */
  // Note: under windows all flushes are achieved synchronously
  //
  // *mmHandle should always be NULL
  // ...........................................................................

  int res;

  TRI_ASSERT(*mmHandle == NULL);

  res = msync(startingAddress, numOfBytesToFlush, flags);

#ifdef __APPLE__
  if (res == 0) {
    res = fcntl(fileDescriptor, F_FULLFSYNC, 0);
  }
#endif

  if (res == 0) {
    // msync was successful
    return TRI_ERROR_NO_ERROR;
  }

  if (errno == ENOMEM) {
    // we have synced a region that was not mapped

    // set a special error. ENOMEM (out of memory) is not appropriate
    LOG_ERROR("msync failed for range %p - %p", startingAddress, (void*) (((char*) startingAddress) + numOfBytesToFlush));

    return TRI_ERROR_ARANGO_MSYNC_FAILED;
  }

  return TRI_ERROR_SYS_ERROR;
}

////////////////////////////////////////////////////////////////////////////////
// @brief memory map a file
////////////////////////////////////////////////////////////////////////////////

int TRI_MMFile (void* memoryAddress,
                size_t numOfBytesToInitialise,
                int memoryProtection,
                int flags,
                int fileDescriptor,
                void** mmHandle,
                int64_t offset,
                void** result) {

  off_t offsetRetyped = (off_t)(offset);

  *mmHandle = NULL; // only useful for windows

  *result = mmap(memoryAddress, numOfBytesToInitialise, memoryProtection, flags, fileDescriptor, offsetRetyped);

  if (*result != MAP_FAILED) {
    return TRI_ERROR_NO_ERROR;
  }

  if (errno == ENOMEM) {
    return TRI_ERROR_OUT_OF_MEMORY_MMAP;
  }

  return TRI_ERROR_SYS_ERROR;
}

////////////////////////////////////////////////////////////////////////////////
// @brief unmap a memory-mapped file
////////////////////////////////////////////////////////////////////////////////

int TRI_UNMMFile (void* memoryAddress,
                  size_t numOfBytesToUnMap,
                  int fileDescriptor,
                  void** mmHandle) {
  int result;

  TRI_ASSERT(*mmHandle == NULL);

  result = munmap(memoryAddress, numOfBytesToUnMap);

  if (result == 0) {
    return TRI_ERROR_NO_ERROR;
  }

  if (errno == ENOSPC) {
    return TRI_ERROR_ARANGO_FILESYSTEM_FULL;
  }

  return TRI_ERROR_SYS_ERROR;
}

////////////////////////////////////////////////////////////////////////////////
// @brief protect a region in a memory-mapped file
////////////////////////////////////////////////////////////////////////////////

int TRI_ProtectMMFile (void* memoryAddress,
                       size_t numOfBytesToProtect,
                       int flags,
                       int fileDescriptor,
                       void** mmHandle) {
  int result;

  TRI_ASSERT(*mmHandle == NULL);

  result = mprotect(memoryAddress, numOfBytesToProtect, flags);

  if (result == 0) {
    return TRI_ERROR_NO_ERROR;
  }

  return TRI_ERROR_SYS_ERROR;
}

#endif

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:


text:
'use strict';

const core = require('@theme-tools/core');
const gulp = require('gulp');
const defaultConfig = require('./config.default');

module.exports = (userConfig) => {
  const config = core.utils.merge({}, defaultConfig, userConfig);

  /**
   * Run shell
   * @param done
   * @param errorShouldExit {Boolean} [false] - Should it stop the script if an error happens?
   */
  function runner(done, errorShouldExit) {
    core.utils.sh(config.cmd, errorShouldExit, (err) => {
      if (config.triggerBrowserReloadAfter) {
        core.events.emit('reload'); // used by `@theme-tools/plugin-browser-sync`
      }
      done(err);
    });
  }

  function run(done) {
    runner(done, true);
  }
  run.description = `Run shell command: ${config.cmd}`;
  run.displayName = `${config.name}:run`;

  function watch(done) {
    gulp.watch(config.watch, () => runner(done, false));
  }
  watch.description = `Watch and rerun ${config.name}.`;
  watch.displayName = `${config.name}:watch`;

  return {
    run,
    watch,
  };
};


text:
import type { ReactWrapper } from 'enzyme';
import { mount } from 'enzyme';
import React from 'react';

import type { IFilterProps } from './Filter';
import { Filter } from './Filter';
import type { IFilterType } from './SearchFilterTypeRegistry';

describe('<Filter/>', () => {
  let component: ReactWrapper<IFilterProps, any>;

  function getNewFilterType(): IFilterType {
    return {
      key: 'region',
      name: 'Region',
    };
  }

  function getNewTagComponent(filterType: IFilterType, isActive: boolean): ReactWrapper<IFilterProps, any> {
    return mount(<Filter filterType={filterType} isActive={isActive} />);
  }

  it('should display a filter', () => {
    const filterType: IFilterType = getNewFilterType();
    component = getNewTagComponent(filterType, true);

    expect(component.render().hasClass('filter')).toBeTruthy();
    expect(component.find('div.filter__text').text()).toBe(filterType.name);
    expect(component.find('div.filter__modifier').text()).toBe(`[${filterType.key.toLocaleUpperCase()}:]`);
  });

  it('should set the tab focus class when active', () => {
    component = getNewTagComponent(getNewFilterType(), true);
    expect(component.render().hasClass('filter')).toBeTruthy();
    expect(component.render().hasClass('filter--focus')).toBeTruthy();
    expect(component.render().hasClass('filter--blur')).toBeFalsy();
  });

  it('should set the tab blur class when not active', () => {
    component = getNewTagComponent(getNewFilterType(), false);
    expect(component.render().hasClass('filter')).toBeTruthy();
    expect(component.render().hasClass('filter--focus')).toBeFalsy();
    expect(component.render().hasClass('filter--blur')).toBeTruthy();
  });
});


text:
Sobre a Empresa

                A Gerensys Automação Comercial Limitada, foi fundada em Março de 1996, com a Missão de disponibilizar às
                micro e pequenas empresas, um sotware de automação comercial, de fácil operação, completo nas rotinas
                comerciais, com baixo custo e totalmente parametrizável para atender a demanda de seus usuarios.

                Para tanto, a sua Visão é ser empresa de referência, reconhecida como a melhor opção por clientes,
                colaboradores e fornecedores, pela qualidade de seus produtos, serviços e relacionamento.

                E tem como Valores primordiais, a integridade, o compremetimento, a competência, a inovação e a
                sustentabilidade.

            Imagem Empresa


text:
<resources>
  <string name="app_name">Stitch</string>
</resources>


text:
import grpc
import sys
import os
import socket
import logging
import importlib
from concurrent import futures

import jet_to_python_pb2
import jet_to_python_pb2_grpc

logger = logging.getLogger('Python PID %d' % os.getpid())

class JetToPythonServicer(jet_to_python_pb2_grpc.JetToPythonServicer):

    def __init__(self, handler_function):
        self._handler_function = handler_function

    def streamingCall(self, request_iterator, context):
        for request in request_iterator:
            output_list = self._handler_function(request.inputValue)
            output_item = jet_to_python_pb2.OutputMessage(outputValue = output_list)
            yield output_item
        logger.info('gRPC call completed')

def load_handler_function(handler_module_name, handler_function_name):
    try:
        handler_module = importlib.import_module(handler_module_name)
    except ImportError as e:
        raise RuntimeError("Cannot import module %s" % (handler_module_name), e)
    if not hasattr(handler_module, handler_function_name):
        raise RuntimeError("Handler function %s.%s doesn't exist" % (handler_module_name, handler_function_name))
    return getattr(handler_module, handler_function_name)

def serve(phoneback_port, handler_module_name, handler_function_name):
    # Fail as soon as possible for any simple problem with passed-in arguments
    phoneback_port_int = int(phoneback_port)
    handler_function = load_handler_function(handler_module_name, handler_function_name)
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=1), options=[
        ('grpc.max_send_message_length', 100 * 1024 * 1024),
        ('grpc.max_receive_message_length', 100 * 1024 * 1024),
        ('grpc.so_reuseport', 0)
    ])
    jet_to_python_pb2_grpc.add_JetToPythonServicer_to_server(
        JetToPythonServicer(handler_function),
        server
    )
    listen_port = server.add_insecure_port('localhost:0')
    if listen_port == 0:
        logger.error("Couldn't find a port to bind to")
        return
    phoneback_message = ('%d\n' % listen_port).encode('utf-8')
    server.start()
    logger.info('started listening on port %d', listen_port)
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect(('localhost', phoneback_port_int))
        s.sendall(phoneback_message)

    # Wait for a stop signal in stdin
    stdin_message = input()
    if stdin_message == 'stop':
        logger.info('Received a "stop" message from stdin. Stopping the server.')
    else:
        logger.info('Received an unexpected message from stdin: "%s"' % stdin_message)
    server.stop(0).wait()

if __name__ == '__main__':
    logging.basicConfig(stream=sys.stdout, format='%(asctime)s %(levelname)s [%(name)s] %(threadName)s - %(message)s', level=logging.INFO)
    # Expecting these command-line parameters:
    # - $1 is the port where Jet is listening for the Python process to
    #   'phone back' and tell Jet on which port it started its gRPC endpoint.
    # - $2.$3 is the module.function of the handler function that will handle
    #   the input from Jet.
    serve(phoneback_port=sys.argv[1], handler_module_name=sys.argv[2], handler_function_name=sys.argv[3])


text:
class EY::Serverside::Adapter::CommandOptions
  module ClassMethods
    def command_options
      @options ||= EY::Serverside::Adapter::CommandOptions.new
    end

    def option(*args)
      command_options.add(*args)
    end
  end

  attr_accessor :options

  def initialize
    self.options = []
  end

  def add(*args)
    option = EY::Serverside::Adapter::Option.new(*args)
    self.options << option
    option
  end

  def applicable(version)
    select { |option| option.on_version?(version) }
  end

  def required(version)
    select { |option| option.required_on_version?(version) }
  end

  def select(&block)
    self.options.select(&block)
  end

end


text:
package com.github.ldaniels528.trifecta.modules.etl.io

import scala.concurrent.ExecutionContext

/**
  * Represents an executable opCode
  * @author lawrence.daniels@gmail.com
  */
trait OpCode[T] {

  def execute(scope: Scope)(implicit ec: ExecutionContext): T

}


text:
@class NTJsonStore;
@class NTJsonSqlConnection;

@interface NTJsonCollection (Private)

@property (nonatomic,readonly) NSArray *columns;
@property (nonatomic,readonly) NSArray *indexes;

@property (nonatomic,readonly) NTJsonSqlConnection *connection;

-(id)initWithStore:(NTJsonStore *)store name:(NSString *)name;
-(id)initNewCollectionWithStore:(NTJsonStore *)store name:(NSString *)name;

-(void)close;

@end


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

namespace _02CountRealNumbers
{
    class Program
    {
        static void Main()
        {
            double[] nums = Console.ReadLine().Split(' ').Select(double.Parse).ToArray();
            SortedDictionary<double, int> counts = new SortedDictionary<double, int>();

            foreach (var num in nums)
            {
                if (counts.ContainsKey(num))
                {
                    counts[num]++;
                }
                else
                {
                    counts[num] = 1;
                }
            }

            foreach (var num in counts.Keys)
            {
                Console.WriteLine($"{num} -> {counts[num]}");
            }
        }
    }
}


text:
const FONT_WEIGHTS = {
  thin: 100,
  hairline: 100,
  ultralight: 200,
  extralight: 200,
  light: 300,
  normal: 400,
  medium: 500,
  semibold: 600,
  demibold: 600,
  bold: 700,
  ultrabold: 800,
  extrabold: 800,
  heavy: 900,
  black: 900,
};

const processFontWeight = value => {
  if (!value) return FONT_WEIGHTS.normal;
  if (typeof value === 'number') return value;

  const lv = value.toLowerCase();

  if (FONT_WEIGHTS[lv]) return FONT_WEIGHTS[lv];

  return value;
};

export default processFontWeight;


text:
namespace LessonsSamples.Lesson8.AuditLog
{
    internal interface IAuditLog
    {
        void Write(AuditType read, string empty, User user);
    }
}


text:
@interface NSArray (PluckMongoIds)

- (NSArray*) mongoIdArray;

@end