text:
<?php

namespace Tekstove\ApiBundle\Model\Base;

use \Exception;
use \PDO;
use Propel\Runtime\Propel;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Propel\Runtime\ActiveQuery\ModelJoin;
use Propel\Runtime\Collection\ObjectCollection;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\Exception\PropelException;
use Tekstove\ApiBundle\Model\AlbumArtist as ChildAlbumArtist;
use Tekstove\ApiBundle\Model\AlbumArtistQuery as ChildAlbumArtistQuery;
use Tekstove\ApiBundle\Model\Map\AlbumArtistTableMap;

/**
 * Base class that represents a query for the 'album_artist' table.
 *
 *
 *
 * @method     ChildAlbumArtistQuery orderById($order = Criteria::ASC) Order by the id column
 * @method     ChildAlbumArtistQuery orderByAlbumId($order = Criteria::ASC) Order by the album_id column
 * @method     ChildAlbumArtistQuery orderByArtistId($order = Criteria::ASC) Order by the artist_id column
 * @method     ChildAlbumArtistQuery orderByOrder($order = Criteria::ASC) Order by the order column
 *
 * @method     ChildAlbumArtistQuery groupById() Group by the id column
 * @method     ChildAlbumArtistQuery groupByAlbumId() Group by the album_id column
 * @method     ChildAlbumArtistQuery groupByArtistId() Group by the artist_id column
 * @method     ChildAlbumArtistQuery groupByOrder() Group by the order column
 *
 * @method     ChildAlbumArtistQuery leftJoin($relation) Adds a LEFT JOIN clause to the query
 * @method     ChildAlbumArtistQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query
 * @method     ChildAlbumArtistQuery innerJoin($relation) Adds a INNER JOIN clause to the query
 *
 * @method     ChildAlbumArtistQuery leftJoinWith($relation) Adds a LEFT JOIN clause and with to the query
 * @method     ChildAlbumArtistQuery rightJoinWith($relation) Adds a RIGHT JOIN clause and with to the query
 * @method     ChildAlbumArtistQuery innerJoinWith($relation) Adds a INNER JOIN clause and with to the query
 *
 * @method     ChildAlbumArtistQuery leftJoinAlbum($relationAlias = null) Adds a LEFT JOIN clause to the query using the Album relation
 * @method     ChildAlbumArtistQuery rightJoinAlbum($relationAlias = null) Adds a RIGHT JOIN clause to the query using the Album relation
 * @method     ChildAlbumArtistQuery innerJoinAlbum($relationAlias = null) Adds a INNER JOIN clause to the query using the Album relation
 *
 * @method     ChildAlbumArtistQuery joinWithAlbum($joinType = Criteria::INNER_JOIN) Adds a join clause and with to the query using the Album relation
 *
 * @method     ChildAlbumArtistQuery leftJoinWithAlbum() Adds a LEFT JOIN clause and with to the query using the Album relation
 * @method     ChildAlbumArtistQuery rightJoinWithAlbum() Adds a RIGHT JOIN clause and with to the query using the Album relation
 * @method     ChildAlbumArtistQuery innerJoinWithAlbum() Adds a INNER JOIN clause and with to the query using the Album relation
 *
 * @method     ChildAlbumArtistQuery leftJoinArtist($relationAlias = null) Adds a LEFT JOIN clause to the query using the Artist relation
 * @method     ChildAlbumArtistQuery rightJoinArtist($relationAlias = null) Adds a RIGHT JOIN clause to the query using the Artist relation
 * @method     ChildAlbumArtistQuery innerJoinArtist($relationAlias = null) Adds a INNER JOIN clause to the query using the Artist relation
 *
 * @method     ChildAlbumArtistQuery joinWithArtist($joinType = Criteria::INNER_JOIN) Adds a join clause and with to the query using the Artist relation
 *
 * @method     ChildAlbumArtistQuery leftJoinWithArtist() Adds a LEFT JOIN clause and with to the query using the Artist relation
 * @method     ChildAlbumArtistQuery rightJoinWithArtist() Adds a RIGHT JOIN clause and with to the query using the Artist relation
 * @method     ChildAlbumArtistQuery innerJoinWithArtist() Adds a INNER JOIN clause and with to the query using the Artist relation
 *
 * @method     \Tekstove\ApiBundle\Model\AlbumQuery|\Tekstove\ApiBundle\Model\ArtistQuery endUse() Finalizes a secondary criteria and merges it with its primary Criteria
 *
 * @method     ChildAlbumArtist findOne(ConnectionInterface $con = null) Return the first ChildAlbumArtist matching the query
 * @method     ChildAlbumArtist findOneOrCreate(ConnectionInterface $con = null) Return the first ChildAlbumArtist matching the query, or a new ChildAlbumArtist object populated from the query conditions when no match is found
 *
 * @method     ChildAlbumArtist findOneById(int $id) Return the first ChildAlbumArtist filtered by the id column
 * @method     ChildAlbumArtist findOneByAlbumId(int $album_id) Return the first ChildAlbumArtist filtered by the album_id column
 * @method     ChildAlbumArtist findOneByArtistId(int $artist_id) Return the first ChildAlbumArtist filtered by the artist_id column
 * @method     ChildAlbumArtist findOneByOrder(int $order) Return the first ChildAlbumArtist filtered by the order column *

 * @method     ChildAlbumArtist requirePk($key, ConnectionInterface $con = null) Return the ChildAlbumArtist by primary key and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
 * @method     ChildAlbumArtist requireOne(ConnectionInterface $con = null) Return the first ChildAlbumArtist matching the query and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
 *
 * @method     ChildAlbumArtist requireOneById(int $id) Return the first ChildAlbumArtist filtered by the id column and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
 * @method     ChildAlbumArtist requireOneByAlbumId(int $album_id) Return the first ChildAlbumArtist filtered by the album_id column and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
 * @method     ChildAlbumArtist requireOneByArtistId(int $artist_id) Return the first ChildAlbumArtist filtered by the artist_id column and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
 * @method     ChildAlbumArtist requireOneByOrder(int $order) Return the first ChildAlbumArtist filtered by the order column and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
 *
 * @method     ChildAlbumArtist[]|ObjectCollection find(ConnectionInterface $con = null) Return ChildAlbumArtist objects based on current ModelCriteria
 * @method     ChildAlbumArtist[]|ObjectCollection findById(int $id) Return ChildAlbumArtist objects filtered by the id column
 * @method     ChildAlbumArtist[]|ObjectCollection findByAlbumId(int $album_id) Return ChildAlbumArtist objects filtered by the album_id column
 * @method     ChildAlbumArtist[]|ObjectCollection findByArtistId(int $artist_id) Return ChildAlbumArtist objects filtered by the artist_id column
 * @method     ChildAlbumArtist[]|ObjectCollection findByOrder(int $order) Return ChildAlbumArtist objects filtered by the order column
 * @method     ChildAlbumArtist[]|\Propel\Runtime\Util\PropelModelPager paginate($page = 1, $maxPerPage = 10, ConnectionInterface $con = null) Issue a SELECT query based on the current ModelCriteria and uses a page and a maximum number of results per page to compute an offset and a limit
 *
 */
abstract class AlbumArtistQuery extends ModelCriteria
{
    protected $entityNotFoundExceptionClass = '\\Propel\\Runtime\\Exception\\EntityNotFoundException';

    /**
     * Initializes internal state of \Tekstove\ApiBundle\Model\Base\AlbumArtistQuery object.
     *
     * @param     string $dbName The database name
     * @param     string $modelName The phpName of a model, e.g. 'Book'
     * @param     string $modelAlias The alias for the model in this query, e.g. 'b'
     */
    public function __construct($dbName = 'default', $modelName = '\\Tekstove\\ApiBundle\\Model\\AlbumArtist', $modelAlias = null)
    {
        parent::__construct($dbName, $modelName, $modelAlias);
    }

    /**
     * Returns a new ChildAlbumArtistQuery object.
     *
     * @param     string $modelAlias The alias of a model in the query
     * @param     Criteria $criteria Optional Criteria to build the query from
     *
     * @return ChildAlbumArtistQuery
     */
    public static function create($modelAlias = null, Criteria $criteria = null)
    {
        if ($criteria instanceof ChildAlbumArtistQuery) {
            return $criteria;
        }
        $query = new ChildAlbumArtistQuery();
        if (null !== $modelAlias) {
            $query->setModelAlias($modelAlias);
        }
        if ($criteria instanceof Criteria) {
            $query->mergeWith($criteria);
        }

        return $query;
    }

    /**
     * Find object by primary key.
     * Propel uses the instance pool to skip the database if the object exists.
     * Go fast if the query is untouched.
     *
     *
     * $obj  = $c->findPk(12, $con);
     *
     *
     * @param mixed $key Primary key to use for the query
     * @param ConnectionInterface $con an optional connection object
     *
     * @return ChildAlbumArtist|array|mixed the result, formatted by the current formatter
     */
    public function findPk($key, ConnectionInterface $con = null)
    {
        if ($key === null) {
            return null;
        }

        if ($con === null) {
            $con = Propel::getServiceContainer()->getReadConnection(AlbumArtistTableMap::DATABASE_NAME);
        }

        $this->basePreSelect($con);

        if (
            $this->formatter || $this->modelAlias || $this->with || $this->select
            || $this->selectColumns || $this->asColumns || $this->selectModifiers
            || $this->map || $this->having || $this->joins
        ) {
            return $this->findPkComplex($key, $con);
        }

        if ((null !== ($obj = AlbumArtistTableMap::getInstanceFromPool(null === $key || is_scalar($key) || is_callable([$key, '__toString']) ? (string) $key : $key)))) {
            // the object is already in the instance pool
            return $obj;
        }

        return $this->findPkSimple($key, $con);
    }

    /**
     * Find object by primary key using raw SQL to go fast.
     * Bypass doSelect() and the object formatter by using generated code.
     *
     * @param     mixed $key Primary key to use for the query
     * @param     ConnectionInterface $con A connection object
     *
     * @throws \Propel\Runtime\Exception\PropelException
     *
     * @return ChildAlbumArtist A model object, or null if the key is not found
     */
    protected function findPkSimple($key, ConnectionInterface $con)
    {
        $sql = 'SELECT `id`, `album_id`, `artist_id`, `order` FROM `album_artist` WHERE `id` = :p0';
        try {
            $stmt = $con->prepare($sql);
            $stmt->bindValue(':p0', $key, PDO::PARAM_INT);
            $stmt->execute();
        } catch (Exception $e) {
            Propel::log($e->getMessage(), Propel::LOG_ERR);
            throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e);
        }
        $obj = null;
        if ($row = $stmt->fetch(\PDO::FETCH_NUM)) {
            /** @var ChildAlbumArtist $obj */
            $obj = new ChildAlbumArtist();
            $obj->hydrate($row);
            AlbumArtistTableMap::addInstanceToPool($obj, null === $key || is_scalar($key) || is_callable([$key, '__toString']) ? (string) $key : $key);
        }
        $stmt->closeCursor();

        return $obj;
    }

    /**
     * Find object by primary key.
     *
     * @param     mixed $key Primary key to use for the query
     * @param     ConnectionInterface $con A connection object
     *
     * @return ChildAlbumArtist|array|mixed the result, formatted by the current formatter
     */
    protected function findPkComplex($key, ConnectionInterface $con)
    {
        // As the query uses a PK condition, no limit(1) is necessary.
        $criteria = $this->isKeepQuery() ? clone $this : $this;
        $dataFetcher = $criteria
            ->filterByPrimaryKey($key)
            ->doSelect($con);

        return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher);
    }

    /**
     * Find objects by primary key
     *
     * $objs = $c->findPks(array(12, 56, 832), $con);
     *
     * @param     array $keys Primary keys to use for the query
     * @param     ConnectionInterface $con an optional connection object
     *
     * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter
     */
    public function findPks($keys, ConnectionInterface $con = null)
    {
        if (null === $con) {
            $con = Propel::getServiceContainer()->getReadConnection($this->getDbName());
        }
        $this->basePreSelect($con);
        $criteria = $this->isKeepQuery() ? clone $this : $this;
        $dataFetcher = $criteria
            ->filterByPrimaryKeys($keys)
            ->doSelect($con);

        return $criteria->getFormatter()->init($criteria)->format($dataFetcher);
    }

    /**
     * Filter the query by primary key
     *
     * @param     mixed $key Primary key to use for the query
     *
     * @return $this|ChildAlbumArtistQuery The current query, for fluid interface
     */
    public function filterByPrimaryKey($key)
    {

        return $this->addUsingAlias(AlbumArtistTableMap::COL_ID, $key, Criteria::EQUAL);
    }

    /**
     * Filter the query by a list of primary keys
     *
     * @param     array $keys The list of primary key to use for the query
     *
     * @return $this|ChildAlbumArtistQuery The current query, for fluid interface
     */
    public function filterByPrimaryKeys($keys)
    {

        return $this->addUsingAlias(AlbumArtistTableMap::COL_ID, $keys, Criteria::IN);
    }

    /**
     * Filter the query on the id column
     *
     * Example usage:
     *
     * $query->filterById(1234); // WHERE id = 1234
     * $query->filterById(array(12, 34)); // WHERE id IN (12, 34)
     * $query->filterById(array('min' => 12)); // WHERE id > 12
     *
     *
     * @param     mixed $id The value to use as filter.
     *              Use scalar values for equality.
     *              Use array values for in_array() equivalent.
     *              Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return $this|ChildAlbumArtistQuery The current query, for fluid interface
     */
    public function filterById($id = null, $comparison = null)
    {
        if (is_array($id)) {
            $useMinMax = false;
            if (isset($id['min'])) {
                $this->addUsingAlias(AlbumArtistTableMap::COL_ID, $id['min'], Criteria::GREATER_EQUAL);
                $useMinMax = true;
            }
            if (isset($id['max'])) {
                $this->addUsingAlias(AlbumArtistTableMap::COL_ID, $id['max'], Criteria::LESS_EQUAL);
                $useMinMax = true;
            }
            if ($useMinMax) {
                return $this;
            }
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }
        }

        return $this->addUsingAlias(AlbumArtistTableMap::COL_ID, $id, $comparison);
    }

    /**
     * Filter the query on the album_id column
     *
     * Example usage:
     *
     * $query->filterByAlbumId(1234); // WHERE album_id = 1234
     * $query->filterByAlbumId(array(12, 34)); // WHERE album_id IN (12, 34)
     * $query->filterByAlbumId(array('min' => 12)); // WHERE album_id > 12
     *
     *
     * @see       filterByAlbum()
     *
     * @param     mixed $albumId The value to use as filter.
     *              Use scalar values for equality.
     *              Use array values for in_array() equivalent.
     *              Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return $this|ChildAlbumArtistQuery The current query, for fluid interface
     */
    public function filterByAlbumId($albumId = null, $comparison = null)
    {
        if (is_array($albumId)) {
            $useMinMax = false;
            if (isset($albumId['min'])) {
                $this->addUsingAlias(AlbumArtistTableMap::COL_ALBUM_ID, $albumId['min'], Criteria::GREATER_EQUAL);
                $useMinMax = true;
            }
            if (isset($albumId['max'])) {
                $this->addUsingAlias(AlbumArtistTableMap::COL_ALBUM_ID, $albumId['max'], Criteria::LESS_EQUAL);
                $useMinMax = true;
            }
            if ($useMinMax) {
                return $this;
            }
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }
        }

        return $this->addUsingAlias(AlbumArtistTableMap::COL_ALBUM_ID, $albumId, $comparison);
    }

    /**
     * Filter the query on the artist_id column
     *
     * Example usage:
     *
     * $query->filterByArtistId(1234); // WHERE artist_id = 1234
     * $query->filterByArtistId(array(12, 34)); // WHERE artist_id IN (12, 34)
     * $query->filterByArtistId(array('min' => 12)); // WHERE artist_id > 12
     *
     *
     * @see       filterByArtist()
     *
     * @param     mixed $artistId The value to use as filter.
     *              Use scalar values for equality.
     *              Use array values for in_array() equivalent.
     *              Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return $this|ChildAlbumArtistQuery The current query, for fluid interface
     */
    public function filterByArtistId($artistId = null, $comparison = null)
    {
        if (is_array($artistId)) {
            $useMinMax = false;
            if (isset($artistId['min'])) {
                $this->addUsingAlias(AlbumArtistTableMap::COL_ARTIST_ID, $artistId['min'], Criteria::GREATER_EQUAL);
                $useMinMax = true;
            }
            if (isset($artistId['max'])) {
                $this->addUsingAlias(AlbumArtistTableMap::COL_ARTIST_ID, $artistId['max'], Criteria::LESS_EQUAL);
                $useMinMax = true;
            }
            if ($useMinMax) {
                return $this;
            }
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }
        }

        return $this->addUsingAlias(AlbumArtistTableMap::COL_ARTIST_ID, $artistId, $comparison);
    }

    /**
     * Filter the query on the order column
     *
     * Example usage:
     *
     * $query->filterByOrder(1234); // WHERE order = 1234
     * $query->filterByOrder(array(12, 34)); // WHERE order IN (12, 34)
     * $query->filterByOrder(array('min' => 12)); // WHERE order > 12
     *
     *
     * @param     mixed $order The value to use as filter.
     *              Use scalar values for equality.
     *              Use array values for in_array() equivalent.
     *              Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return $this|ChildAlbumArtistQuery The current query, for fluid interface
     */
    public function filterByOrder($order = null, $comparison = null)
    {
        if (is_array($order)) {
            $useMinMax = false;
            if (isset($order['min'])) {
                $this->addUsingAlias(AlbumArtistTableMap::COL_ORDER, $order['min'], Criteria::GREATER_EQUAL);
                $useMinMax = true;
            }
            if (isset($order['max'])) {
                $this->addUsingAlias(AlbumArtistTableMap::COL_ORDER, $order['max'], Criteria::LESS_EQUAL);
                $useMinMax = true;
            }
            if ($useMinMax) {
                return $this;
            }
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }
        }

        return $this->addUsingAlias(AlbumArtistTableMap::COL_ORDER, $order, $comparison);
    }

    /**
     * Filter the query by a related \Tekstove\ApiBundle\Model\Album object
     *
     * @param \Tekstove\ApiBundle\Model\Album|ObjectCollection $album The related object(s) to use as filter
     * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @throws \Propel\Runtime\Exception\PropelException
     *
     * @return ChildAlbumArtistQuery The current query, for fluid interface
     */
    public function filterByAlbum($album, $comparison = null)
    {
        if ($album instanceof \Tekstove\ApiBundle\Model\Album) {
            return $this
                ->addUsingAlias(AlbumArtistTableMap::COL_ALBUM_ID, $album->getId(), $comparison);
        } elseif ($album instanceof ObjectCollection) {
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }

            return $this
                ->addUsingAlias(AlbumArtistTableMap::COL_ALBUM_ID, $album->toKeyValue('PrimaryKey', 'Id'), $comparison);
        } else {
            throw new PropelException('filterByAlbum() only accepts arguments of type \Tekstove\ApiBundle\Model\Album or Collection');
        }
    }

    /**
     * Adds a JOIN clause to the query using the Album relation
     *
     * @param     string $relationAlias optional alias for the relation
     * @param     string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
     *
     * @return $this|ChildAlbumArtistQuery The current query, for fluid interface
     */
    public function joinAlbum($relationAlias = null, $joinType = Criteria::INNER_JOIN)
    {
        $tableMap = $this->getTableMap();
        $relationMap = $tableMap->getRelation('Album');

        // create a ModelJoin object for this join
        $join = new ModelJoin();
        $join->setJoinType($joinType);
        $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias);
        if ($previousJoin = $this->getPreviousJoin()) {
            $join->setPreviousJoin($previousJoin);
        }

        // add the ModelJoin to the current object
        if ($relationAlias) {
            $this->addAlias($relationAlias, $relationMap->getRightTable()->getName());
            $this->addJoinObject($join, $relationAlias);
        } else {
            $this->addJoinObject($join, 'Album');
        }

        return $this;
    }

    /**
     * Use the Album relation Album object
     *
     * @see useQuery()
     *
     * @param     string $relationAlias optional alias for the relation,
     *                                   to be used as main alias in the secondary query
     * @param     string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
     *
     * @return \Tekstove\ApiBundle\Model\AlbumQuery A secondary query class using the current class as primary query
     */
    public function useAlbumQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN)
    {
        return $this
            ->joinAlbum($relationAlias, $joinType)
            ->useQuery($relationAlias ? $relationAlias : 'Album', '\Tekstove\ApiBundle\Model\AlbumQuery');
    }

    /**
     * Filter the query by a related \Tekstove\ApiBundle\Model\Artist object
     *
     * @param \Tekstove\ApiBundle\Model\Artist|ObjectCollection $artist The related object(s) to use as filter
     * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @throws \Propel\Runtime\Exception\PropelException
     *
     * @return ChildAlbumArtistQuery The current query, for fluid interface
     */
    public function filterByArtist($artist, $comparison = null)
    {
        if ($artist instanceof \Tekstove\ApiBundle\Model\Artist) {
            return $this
                ->addUsingAlias(AlbumArtistTableMap::COL_ARTIST_ID, $artist->getId(), $comparison);
        } elseif ($artist instanceof ObjectCollection) {
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }

            return $this
                ->addUsingAlias(AlbumArtistTableMap::COL_ARTIST_ID, $artist->toKeyValue('PrimaryKey', 'Id'), $comparison);
        } else {
            throw new PropelException('filterByArtist() only accepts arguments of type \Tekstove\ApiBundle\Model\Artist or Collection');
        }
    }

    /**
     * Adds a JOIN clause to the query using the Artist relation
     *
     * @param     string $relationAlias optional alias for the relation
     * @param     string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
     *
     * @return $this|ChildAlbumArtistQuery The current query, for fluid interface
     */
    public function joinArtist($relationAlias = null, $joinType = Criteria::INNER_JOIN)
    {
        $tableMap = $this->getTableMap();
        $relationMap = $tableMap->getRelation('Artist');

        // create a ModelJoin object for this join
        $join = new ModelJoin();
        $join->setJoinType($joinType);
        $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias);
        if ($previousJoin = $this->getPreviousJoin()) {
            $join->setPreviousJoin($previousJoin);
        }

        // add the ModelJoin to the current object
        if ($relationAlias) {
            $this->addAlias($relationAlias, $relationMap->getRightTable()->getName());
            $this->addJoinObject($join, $relationAlias);
        } else {
            $this->addJoinObject($join, 'Artist');
        }

        return $this;
    }

    /**
     * Use the Artist relation Artist object
     *
     * @see useQuery()
     *
     * @param     string $relationAlias optional alias for the relation,
     *                                   to be used as main alias in the secondary query
     * @param     string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
     *
     * @return \Tekstove\ApiBundle\Model\ArtistQuery A secondary query class using the current class as primary query
     */
    public function useArtistQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN)
    {
        return $this
            ->joinArtist($relationAlias, $joinType)
            ->useQuery($relationAlias ? $relationAlias : 'Artist', '\Tekstove\ApiBundle\Model\ArtistQuery');
    }

    /**
     * Exclude object from result
     *
     * @param   ChildAlbumArtist $albumArtist Object to remove from the list of results
     *
     * @return $this|ChildAlbumArtistQuery The current query, for fluid interface
     */
    public function prune($albumArtist = null)
    {
        if ($albumArtist) {
            $this->addUsingAlias(AlbumArtistTableMap::COL_ID, $albumArtist->getId(), Criteria::NOT_EQUAL);
        }

        return $this;
    }

    /**
     * Deletes all rows from the album_artist table.
     *
     * @param ConnectionInterface $con the connection to use
     * @return int The number of affected rows (if supported by underlying database driver).
     */
    public function doDeleteAll(ConnectionInterface $con = null)
    {
        if (null === $con) {
            $con = Propel::getServiceContainer()->getWriteConnection(AlbumArtistTableMap::DATABASE_NAME);
        }

        // use transaction because $criteria could contain info
        // for more than one table or we could emulating ON DELETE CASCADE, etc.
        return $con->transaction(function () use ($con) {
            $affectedRows = 0; // initialize var to track total num of affected rows
            $affectedRows += parent::doDeleteAll($con);
            // Because this db requires some delete cascade/set null emulation, we have to
            // clear the cached instance *after* the emulation has happened (since
            // instances get re-added by the select statement contained therein).
            AlbumArtistTableMap::clearInstancePool();
            AlbumArtistTableMap::clearRelatedInstancePool();

            return $affectedRows;
        });
    }

    /**
     * Performs a DELETE on the database based on the current ModelCriteria
     *
     * @param ConnectionInterface $con the connection to use
     * @return int             The number of affected rows (if supported by underlying database driver).  This includes CASCADE-related rows
     *                         if supported by native driver or if emulated using Propel.
     * @throws PropelException Any exceptions caught during processing will be
     *                         rethrown wrapped into a PropelException.
     */
    public function delete(ConnectionInterface $con = null)
    {
        if (null === $con) {
            $con = Propel::getServiceContainer()->getWriteConnection(AlbumArtistTableMap::DATABASE_NAME);
        }

        $criteria = $this;

        // Set the correct dbName
        $criteria->setDbName(AlbumArtistTableMap::DATABASE_NAME);

        // use transaction because $criteria could contain info
        // for more than one table or we could emulating ON DELETE CASCADE, etc.
        return $con->transaction(function () use ($con, $criteria) {
            $affectedRows = 0; // initialize var to track total num of affected rows

            AlbumArtistTableMap::removeInstanceFromPool($criteria);

            $affectedRows += ModelCriteria::delete($con);
            AlbumArtistTableMap::clearRelatedInstancePool();

            return $affectedRows;
        });
    }

} // AlbumArtistQuery


text:
typedef std::vector<std::vector<std::vector<double>>> vector3D;
typedef std::vector<std::vector<double>> vector2D;
typedef std::vector<double> vector1D;

class LSH{
    public:

    LSH();

    LSH(size_t N, size_t Q, size_t D, size_t L, size_t K, double W,  size_t T);

   // ~LSH();

    void loadSetQ(const char *filePath, int fileSize);

    void loadSetN(const char *filePath, int fileSize);

    void saveCandidateSet(const char *filePath);

    bool setUseHdfs(bool useHdfs);

    bool setThreadMode(int threadMode); //default 0-singleThread 1-openMP, 2-stdthread 3-pthread

    bool setDefault();

    int saveHashNToMemc(const char *server, unsigned short port, time_t exp);

    void readHashNFromMemc(const char *server, unsigned short port, std::string runId);

    int saveHashNToRedis(const char *server, unsigned short port);

    int readHashNFromRedis(const char *server, unsigned short port, std::string srunId);

    void clearHashMatrix();

    void clearCollisionMatrix();

    void clearCandidateSet();

    vector2D getCollisionMatrix();

    vector2D getCandidateSet();

    bool setComputeMode(int computeMode);

    void reportStatus();

    void clear();

    int reset();

    const vector2D &getSetN() const;

    void setSetN(const vector2D &setN);

    const vector2D &getSetQ() const;

    void setSetQ(const vector2D &setQ);

    const vector2D &getHashMatrixN() const;

    const vector2D &getHashMatrixQ() const;

private:

    int threadMode; //default 0-singleThread 1-openMP, 2-stdthread 3-pthread
    int computeMode; //default 0-normal((g-collisionmatrix-> candidate)need more memory)   1-quickMode(need less memory, the collision matrix won't be generated
    std::string runID; //runID for recognize this particular run -- mainly for get value from in-memory storage

    FileLoader *theFileLoader;
    Generator *theGenerator;
    ParameterHolder ph;

    vector2D setN; // original data set of N
    vector2D setQ; // original data set of Q

    vector2D hashMatrixN; // hashMatrix of N where hash value is stored
    vector2D hashMatrixQ; // hashMatrix of Q where hash value is stored

    vector2D collisionMatrix; //the place to store collision
    vector2D candidateSet; //Qx--, candidate set

    vector2D normalize(vector2D dataset);

    vector3D generateRandomLine();
    vector1D generateUniformRandomVector(size_t number, double maxium);

    std::string generateRunId();

};

#endif //FASTLSH_LSH_H

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Linq.Expressions;
using System.Reflection;

namespace AntData.ORM.Mapping
{
	using Common;
	using Data;
	using Expressions;

	using Extensions;

	using Reflection;

	public class ColumnDescriptor
	{
		public ColumnDescriptor(MappingSchema mappingSchema, ColumnAttribute columnAttribute, MemberAccessor memberAccessor)
		{
			//MappingSchema  = mappingSchema;
			MemberAccessor = memberAccessor;
			MemberInfo     = memberAccessor.MemberInfo;

			if (MemberInfo.IsFieldEx())
			{
				var fieldInfo = (FieldInfo)MemberInfo;
				MemberType = fieldInfo.FieldType;
			}
			else if (MemberInfo.IsPropertyEx())
			{
				var propertyInfo = (PropertyInfo)MemberInfo;
				MemberType = propertyInfo.PropertyType;
			}

			MemberName      = columnAttribute.MemberName ?? MemberInfo.Name;
			ColumnName      = columnAttribute.Name       ?? MemberInfo.Name;
			Storage         = columnAttribute.Storage;
			PrimaryKeyOrder = columnAttribute.PrimaryKeyOrder;
			IsDiscriminator = columnAttribute.IsDiscriminator;
			DataType        = columnAttribute.DataType;
			DbType          = columnAttribute.DbType;
			CreateFormat    = columnAttribute.CreateFormat;

			if (columnAttribute.HasLength   ()) Length    = columnAttribute.Length;
			if (columnAttribute.HasPrecision()) Precision = columnAttribute.Precision;
			if (columnAttribute.HasScale    ()) Scale     =  columnAttribute.Scale;

			var defaultCanBeNull = false;

			if (columnAttribute.HasCanBeNull())
				CanBeNull = columnAttribute.CanBeNull;
			else
			{
				var na = mappingSchema.GetAttribute<NullableAttribute>(MemberInfo, attr => attr.Configuration);

				if (na != null)
				{
					CanBeNull = na.CanBeNull;
				}
				else
				{
					CanBeNull        = mappingSchema.GetCanBeNull(MemberType);
					defaultCanBeNull = true;
				}
			}

			if (columnAttribute.HasIsIdentity())
				IsIdentity = columnAttribute.IsIdentity;
			else
			{
				var a = mappingSchema.GetAttribute<IdentityAttribute>(MemberInfo, attr => attr.Configuration);
				if (a != null)
					IsIdentity = true;
			}

			SkipOnInsert = columnAttribute.HasSkipOnInsert() ? columnAttribute.SkipOnInsert : IsIdentity;
			SkipOnUpdate = columnAttribute.HasSkipOnUpdate() ? columnAttribute.SkipOnUpdate : IsIdentity;

			if (defaultCanBeNull && IsIdentity)
				CanBeNull = false;

			if (columnAttribute.HasIsPrimaryKey())
				IsPrimaryKey = columnAttribute.IsPrimaryKey;
			else
			{
				var a = mappingSchema.GetAttribute<PrimaryKeyAttribute>(MemberInfo, attr => attr.Configuration);

				if (a != null)
				{
					IsPrimaryKey    = true;
					PrimaryKeyOrder = a.Order;
				}
			}

			if (DbType == null || DataType == DataType.Undefined)
			{
				var a = mappingSchema.GetAttribute<DataTypeAttribute>(MemberInfo, attr => attr.Configuration);

				if (a != null)
				{
					if (DbType == null)
						DbType = a.DbType;

					if (DataType == DataType.Undefined && a.DataType.HasValue)
						DataType = a.DataType.Value;
				}
			}
		}

		//public MappingSchema  MappingSchema   { get; private set; }
		public MemberAccessor MemberAccessor  { get; private set; }
		public MemberInfo     MemberInfo      { get; private set; }
		public Type           MemberType      { get; private set; }
		public string         MemberName      { get; private set; }
		public string         ColumnName      { get; private set; }
		public string         Storage         { get; private set; }
		public bool           IsDiscriminator { get; private set; }
		public DataType       DataType        { get; private set; }
		public string         DbType          { get; private set; }
		public bool           IsIdentity      { get; private set; }
		public bool           SkipOnInsert    { get; private set; }
		public bool           SkipOnUpdate    { get; private set; }
		public bool           IsPrimaryKey    { get; private set; }
		public int            PrimaryKeyOrder { get; private set; }
		public bool           CanBeNull       { get; private set; }
		public long?           Length          { get; private set; }
		public int?           Precision       { get; private set; }
		public int?           Scale           { get; private set; }
		public string         CreateFormat    { get; private set; }

		Func<object,object> _getter;

		public virtual object GetValue(MappingSchema mappingSchema, object obj)
		{
			if (_getter == null)
			{
				var objParam   = Expression.Parameter(typeof(object), "obj");
				var getterExpr = MemberAccessor.GetterExpression.GetBody(Expression.Convert(objParam, MemberAccessor.TypeAccessor.Type));

				var expr = mappingSchema.GetConvertExpression(MemberType, typeof(DataParameter), createDefault : false);

				if (expr != null)
				{
					getterExpr = expr.GetBody(getterExpr);
				}
				else
				{
					var type = Converter.GetDefaultMappingFromEnumType(mappingSchema, MemberType);

					if (type != null)
					{
						expr = mappingSchema.GetConvertExpression(MemberType, type);
						getterExpr = expr.GetBody(getterExpr);
					}
				}

				var getter = Expression.Lambda<Func<object,object>>(Expression.Convert(getterExpr, typeof(object)), objParam);

				_getter = getter.Compile();
			}

			return _getter(obj);
		}
	}
}


text:
Elm.TestHelloWorld = Elm.TestHelloWorld || {};
Elm.TestHelloWorld.make = function (_elm) {
   "use strict";
   _elm.TestHelloWorld = _elm.TestHelloWorld || {};
   if (_elm.TestHelloWorld.values)
   return _elm.TestHelloWorld.values;
   var _op = {},
   _N = Elm.Native,
   _U = _N.Utils.make(_elm),
   _L = _N.List.make(_elm),
   _A = _N.Array.make(_elm),
   _E = _N.Error.make(_elm),
   $moduleName = "TestHelloWorld",
   $Graphics$Element = Elm.Graphics.Element.make(_elm),
   $Text = Elm.Text.make(_elm);
   var main = $Text.plainText("Hello, World! This is a test of grunt-elm.");
   _elm.TestHelloWorld.values = {_op: _op
                                ,main: main};
   return _elm.TestHelloWorld.values;
};


text:
"use strict";

var app = angular.module('datathonApp', [
  'ngRoute',
  'ui.bootstrap',
  'mdo-angular-cryptography',
  'btford.socket-io',
  'angular-md5'
]);

app.API_ROOT = "http://localhost:3000"
// app.API_ROOT = "http://4b87350e.ngrok.io"

app.config(function($routeProvider, $cryptoProvider) {
  $cryptoProvider.setCryptographyKey('datathon2017');
  $routeProvider
    .when("/login", {
      templateUrl : "login/login.template.html",
      controller: "LoginCtrl"
    })
    .when("/home", {
      templateUrl : "home/home.template.html",
      controller: "HomeCtrl"
    })
    .otherwise({redirectTo: '/login'});
});


text:
use std::error::Error;
use std::fmt;

/// Error returned by the `Sender`.
#[derive(Debug)]
pub struct SendError<T>(pub T);

impl<T> fmt::Display for SendError<T> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(fmt, "channel closed")
    }
}

impl<T: fmt::Debug> std::error::Error for SendError<T> {}

// ===== TrySendError =====

/// This enumeration is the list of the possible error outcomes for the
/// [try_send](super::Sender::try_send) method.
#[derive(Debug, Eq, PartialEq)]
pub enum TrySendError<T> {
    /// The data could not be sent on the channel because the channel is
    /// currently full and sending would require blocking.
    Full(T),

    /// The receive half of the channel was explicitly closed or has been
    /// dropped.
    Closed(T),
}

impl<T: fmt::Debug> Error for TrySendError<T> {}

impl<T> fmt::Display for TrySendError<T> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            fmt,
            "{}",
            match self {
                TrySendError::Full(..) => "no available capacity",
                TrySendError::Closed(..) => "channel closed",
            }
        )
    }
}

impl<T> From<SendError<T>> for TrySendError<T> {
    fn from(src: SendError<T>) -> TrySendError<T> {
        TrySendError::Closed(src.0)
    }
}

// ===== TryRecvError =====

/// Error returned by `try_recv`.
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum TryRecvError {
    /// This **channel** is currently empty, but the **Sender**(s) have not yet
    /// disconnected, so data may yet become available.
    Empty,
    /// The **channel**'s sending half has become disconnected, and there will
    /// never be any more data received on it.
    Disconnected,
}

impl fmt::Display for TryRecvError {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            TryRecvError::Empty => "receiving on an empty channel".fmt(fmt),
            TryRecvError::Disconnected => "receiving on a closed channel".fmt(fmt),
        }
    }
}

impl Error for TryRecvError {}

// ===== RecvError =====

/// Error returned by `Receiver`.
#[derive(Debug, Clone)]
#[doc(hidden)]
#[deprecated(note = "This type is unused because recv returns an Option.")]
pub struct RecvError(());

#[allow(deprecated)]
impl fmt::Display for RecvError {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(fmt, "channel closed")
    }
}

#[allow(deprecated)]
impl Error for RecvError {}

cfg_time! {
    // ===== SendTimeoutError =====

    #[derive(Debug, Eq, PartialEq)]
    /// Error returned by [`Sender::send_timeout`](super::Sender::send_timeout)].
    pub enum SendTimeoutError<T> {
        /// The data could not be sent on the channel because the channel is
        /// full, and the timeout to send has elapsed.
        Timeout(T),

        /// The receive half of the channel was explicitly closed or has been
        /// dropped.
        Closed(T),
    }

    impl<T: fmt::Debug> Error for SendTimeoutError<T> {}

    impl<T> fmt::Display for SendTimeoutError<T> {
        fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(
                fmt,
                "{}",
                match self {
                    SendTimeoutError::Timeout(..) => "timed out waiting on send operation",
                    SendTimeoutError::Closed(..) => "channel closed",
                }
            )
        }
    }
}


text:
package org.theospi.portfolio.admin.service;

import org.quartz.*;
import org.sakaiproject.api.app.scheduler.SchedulerManager;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.tool.api.Session;
import org.sakaiproject.tool.cover.SessionManager;
import org.theospi.portfolio.admin.intf.SakaiIntegrationPlugin;
import org.theospi.portfolio.admin.model.IntegrationOption;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: John Ellis
 * Date: Mar 2, 2006
 * Time: 10:52:35 PM
 * To change this template use File | Settings | File Templates.
 */
public class PluginOptionJob implements Job {

   public final static String PLUGIN = "org.theospi.portfolio.admin.service.PluginOptionJob.job";
   public final static String INTERVAL = "org.theospi.portfolio.admin.service.PluginOptionJob.interval";

   public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
      Session sakaiSession = SessionManager.getCurrentSession();
      String userId = sakaiSession.getUserId();

      try {
         sakaiSession.setUserId("admin");
         sakaiSession.setUserEid("admin");
         Map details = jobExecutionContext.getJobDetail().getJobDataMap();
         SchedulerManager manager = (SchedulerManager) ComponentManager.get(SchedulerManager.class);
         String pluginId = (String) details.get(PLUGIN);
         SakaiIntegrationPlugin plugin = (SakaiIntegrationPlugin) ComponentManager.get(pluginId);
         long millis = Long.parseLong((String) details.get(INTERVAL));

         boolean done = true;
         for (Iterator i=plugin.getPotentialIntegrations().iterator();i.hasNext();) {
            if (!plugin.executeOption((IntegrationOption) i.next())) {
               done = false;
               break;
            }
         }

         if (!done) {
            try {
               schedule(manager, pluginId, millis);
            } catch (SchedulerException e) {
               throw new JobExecutionException(e);
            }
         }
      } finally {
         sakaiSession.setUserEid(userId);
         sakaiSession.setUserId(userId);
      }
   }

   public static void schedule(SchedulerManager manager, String pluginId, long millis) throws SchedulerException {
      JobDetail detail = new JobDetail(truncateTriggerName(pluginId + "." + System.currentTimeMillis()),
         truncateTriggerName(PluginOptionJob.class.toString()), PluginOptionJob.class);
      detail.getJobDataMap().put(PLUGIN, pluginId);
      detail.getJobDataMap().put(INTERVAL, millis + "");
      manager.getScheduler().scheduleJob(detail, new SimpleTrigger(
         truncateTriggerName(pluginId + ".trigger." + System.currentTimeMillis()),
         PluginOptionJob.class.toString(), new Date(System.currentTimeMillis() + millis)));
   }

   protected static String truncateTriggerName(String s) {
      if (s.length() > 80) {
         return s.substring(s.length() - 80);
      }
      return s;
   }
}


text:
package org.calrissian.mango.domain.event;

import org.calrissian.mango.domain.AbstractAttributeStoreBuilder;

import static java.util.Objects.requireNonNull;

public class EventBuilder extends AbstractAttributeStoreBuilder<Event, EventBuilder> {

    private final EventIdentifier identifier;

    public static EventBuilder create(EventIdentifier identifier) {
        requireNonNull(identifier);
        return new EventBuilder(identifier);
    }

    public static EventBuilder create(String type, String id, long timestamp) {
        return create(new EventIdentifier(type, id, timestamp));
    }

    public static EventBuilder create(Event event) {
        return create(event.getIdentifier())
                .attrs(event.getAttributes());
    }

    protected EventBuilder(EventIdentifier identifier) {
        super();
        this.identifier = identifier;
    }

    @Override
    public Event build() {
        return new BaseEvent(identifier, attributes);
    }
}


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

namespace Skeddly.Model
{
	public class CreditTransaction
	{
		public string TransactionId { get; set; }
		public string TransactionDate { get; set; }
		public string TransactionType { get; set; }
		public decimal? Payment { get; set; }
		public decimal? Debit { get; set; }
		public decimal Balance { get; set; }
	}
}


text:
package org.eknet.spray.openid.provider

import org.scalatest.{Matchers, FunSuite}
import scala.util.Failure

class MustacheTest extends FunSuite with Matchers {
  import Mustache._
  import Mustache.TemplateParser._

  test("parse to token stream") {
    val templ = " Hi, I'm {{name}}, so far {{#list}} its {{item}} time {{/list}}."
    val tokens = TemplateParser.parse(templ)
    val expect = List(StringToken(" Hi, I'm "),
      LookupToken("name"), StringToken(", so far "),
      BlockStart("list", false), StringToken(" its "),
      LookupToken("item"), StringToken(" time "),
      BlockEnd("list"), StringToken(".")
    )
    tokens.size should be (expect.size)
    tokens.zip(expect).foreach { case (t, e) =>
      assert(t === e)
    }
  }

  test("makeTemplate") {
    val templ = " Hi, I'm {{name}}, so far{{#list}} its {{item}} time{{/list}}."
    val template = Mustache(templ)
    val context = Map("name" -> "Eike", "list" -> Seq(Map("item" -> "1st"), Map("item"->"2nd")))
    template(context) should be (" Hi, I'm Eike, so far its 1st time its 2nd time.")

    val template2 = Mustache("{{#musketeers}}\n* {{.}}\n{{/musketeers}}")
    val out2 = template2(Map("musketeers" -> List("Athos", "Aramis", "Porthos")))
    out2 should be ("\n* Athos\n\n* Aramis\n\n* Porthos\n")
  }

  test("erroneous templates") {
    val Failure(e) = Mustache.tryApply("{{#list}} {{.}} as")
  }

  test("provided templates") {
    Mustache(getClass.getResourceAsStream("/org/eknet/spray/openid/provider/login-template.mustache"))
    Mustache(getClass.getResourceAsStream("/org/eknet/spray/openid/provider/continue-template.mustache"))
  }

  test("inverse blocks") {
    val template = Mustache("Hallo, {{^name}}Unknown{{/name}}{{#name}}{{name}}{{/name}}.")
    val s1 = template(Map("test" -> "other"))
    s1 should be ("Hallo, Unknown.")
    val s2 = template(Map("name" -> "John"))
    s2 should be ("Hallo, John.")
    val s3 = template(Map("name" -> List()))
    s3 should be ("Hallo, Unknown.")
  }

  test("empty blocks") {
    val template = Mustache("Hello {{#flag}}Sir {{/flag}}Fauntleroy")
    val s1 = template(Map("flag" -> false))
    s1 should be ("Hello Fauntleroy")

    val s2 = template(Map("flag" -> true))
    s2 should be ("Hello Sir Fauntleroy")
  }
}


text:
<?PHP

require_once("PHPMailerAutoload.php");
require_once("formvalidator.php");
$student = new Student("conf_student.ini");

class Student
{

    var $connection;

    var $error_message;

    //-----Initialization -------
    function Student($conf_ini)
    {
        $conf = parse_ini_file($conf_ini, true);

        $this->sitename = $conf['web']['name'];
        $this->admin_email = $conf['web']['email'];
        $this->rand_key = $conf['web']['key'];

        $this->db_host  = $conf['db']['hostname'];
        $this->username = $conf['db']['username'];
        $this->pwd      = $conf['db']['password'];
        $this->database  = $conf['db']['dbname'];
        $this->tablename = $conf['db']['tablename'];

        $this->email_host  = $conf['email']['host'];
        $this->email_port  = $conf['email']['port'];
        $this->email_secure  = $conf['email']['secure'];
        $this->email_username  = $conf['email']['username'];
        $this->email_password  = $conf['email']['password'];
        $this->email_reply_name  = $conf['email']['reply_name'];
        $this->email_reply_addr  = $conf['email']['reply_addr'];
        $this->email_from_name  = $conf['email']['from_name'];
        $this->email_from_addr  = $conf['email']['from_addr'];

    }

    function Email($target,$name,$subject,$body){

        $mail = new PHPMailer(true);
        $mail->CharSet = 'utf-8';
        ini_set('default_charset', 'UTF-8');
        try {
            $to = $target;
        if(!PHPMailer::validateAddress($to)) {
            throw new phpmailerException("Email address " . $to . " is invalid -- aborting!");
        }
        $mail->isSMTP();
        $mail->SMTPDebug  = 0;
        $mail->Host       = $this->email_host;
        $mail->Port       = $this->email_port;
        $mail->SMTPSecure = $this->email_secure;
        $mail->SMTPAuth   = true;
        $mail->Username   = $this->email_username;
        $mail->Password   = $this->email_password;
        $mail->addReplyTo($this->email_reply_addr, $this->email_reply_name);
        $mail->setFrom($this->email_from_addr, $this->email_from_name);
        $mail->addAddress($target, $name);
        $mail->Subject  = $subject;
        $mail->WordWrap = 78;
        $mail->msgHTML($body, dirname(__FILE__), true); //Create message bodies and embed images

        try {
          $mail->send();
          return true;
          //$results_messages[] = "Message has been sent using SMTP";
        }
        catch (phpmailerException $e) {
          throw new phpmailerException('Unable to send to: ' . $to. ': '.$e->getMessage());
        }
        }
        catch (phpmailerException $e) {
            echo "\n";
            echo $e->getMessage();
          return false;
          //$results_messages[] = $e->errorMessage();
        }
        return true;
    }

    //-------Main Operations ----------------------
    function RegisterUser()
    {
        if(!isset($_POST['submitted']))
        {
           return false;
        }

        $formvars = array();

        if(!$this->ValidateRegistrationSubmission())
        {
            return false;
        }

        $this->CollectRegistrationSubmission($formvars);

        if(!$this->SaveToDatabase($formvars))
        {
            return false;
        }
        if(!$this->SendUserConfirmationEmail($formvars))
        {
            return false;
        }

        $this->SendAdminIntimationEmail($formvars);

        return true;
    }

    function CheckUser(&$info){
        if(!isset($_POST['submit']))
        {
           return false;
        }

        if(!$this->ValidateCheckSubmission())
        {
            return false;
        }

        $formvars = array();

        $this->CollectCheckSubmission($formvars);

        return $this->GetStudentByEmailAndFlight($info, $formvars);
    }

    function ConfirmUser()
    {
        if(empty($_GET['code'])||strlen($_GET['code'])<=10)
        {
            $this->HandleError("Please provide the confirm code");
            return false;
        }
        $user_rec = array();
        if(!$this->UpdateDBRecForConfirmation($user_rec))
        {
            return false;
        }

        $this->SendUserWelcomeEmail($user_rec);

        $this->SendAdminIntimationOnRegComplete($user_rec);

        return true;
    }

    function UserFullName()
    {
        return isset($_SESSION['name_of_user'])?$_SESSION['name_of_user']:'';
    }

    function UserEmail()
    {
        return isset($_SESSION['email_of_user'])?$_SESSION['email_of_user']:'';
    }

    //-------Public Helper functions -------------
    function GetSelfScript()
    {
        return htmlentities($_SERVER['PHP_SELF']);
    }

    function SafeDisplay($value_name)
    {
        if(empty($_POST[$value_name]))
        {
            return'';
        }
        return htmlentities($_POST[$value_name]);
    }

    function RedirectToURL($url)
    {
        header("Location: $url");
        exit;
    }

    function GetParentURL(){
        $url  = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
        $url .= $_SERVER['HTTP_HOST'];
        $url .= $_SERVER['REQUEST_URI'];

        return dirname($url);
    }

    function GetSpamTrapInputName()
    {
        return 'sp'.md5('KHGdnbvsgst'.$this->rand_key);
    }

    function GetErrorMessage()
    {
        if(empty($this->error_message))
        {
            return '';
        }
        $errormsg = nl2br(htmlentities($this->error_message));
        return $errormsg;
    }
    //-------Private Helper functions-----------

    function HandleError($err)
    {
        $this->error_message .= $err;
    }

    function HandleDBError($err)
    {
        $this->HandleError($err."
 mysqlerror:".mysql_error());
    }

    function UpdateDBRecForConfirmation(&$user_rec)
    {
        if(!$this->DBLogin())
        {
            $this->HandleError("Database login failed!");
            return false;
        }
        $email = $this->SanitizeForSQL($_GET['email']);
        $confirmcode = $this->SanitizeForSQL($_GET['code']);

        $result = mysql_query("Select name, confirmcode from $this->tablename where email='$email'",$this->connection);
        if(!$result || mysql_num_rows($result) <= 0)
        {
            $this->HandleError("Wrong credentials.");
            return false;
        }
        $row = mysql_fetch_assoc($result);
        if($row['confirmcode'] == 'y'){
            $this->HandleError("You have already confirmed.");
            return false;
        } else if ($row['confirmcode'] != $confirmcode){
            $this->HandleError("Wrong credentials.");
            return false;
        }
        $user_rec['name'] = $row['name'];
        $user_rec['email']= $email;

        $qry = "Update $this->tablename Set confirmcode='y' Where  confirmcode='$confirmcode'";

        if(!mysql_query( $qry ,$this->connection))
        {
            $this->HandleDBError("Error inserting data to the table\nquery:$qry");
            return false;
        }
        return true;
    }

    function GetUserFromEmail($email,&$user_rec)
    {
        if(!$this->DBLogin())
        {
            $this->HandleError("Database login failed!");
            return false;
        }
        $email = $this->SanitizeForSQL($email);

        $result = mysql_query("Select * from $this->tablename where email='$email'",$this->connection);

        if(!$result || mysql_num_rows($result) <= 0)
        {
            $this->HandleError("There is no user with email: $email");
            return false;
        }
        $user_rec = mysql_fetch_assoc($result);

        return true;
    }

    function GetStudentByEmailAndFlight(&$info, &$formvars) {
        if(!$this->DBLogin())
        {
            $this->HandleError("Database login failed!");
            return false;
        }
        $email = $this->SanitizeForSQL($formvars['email']);
        $flight = $this->SanitizeForSQL($formvars['flight']);

        $qry = "Select * from $this->tablename where email='$email' and flight like '%$flight%'";
        $result = mysql_query($qry,$this->connection);

        if ($row = mysql_fetch_array($result)){
            $info = $row;
            return true;
        } else {
            return false;
        }
    }

    function SendUserWelcomeEmail(&$user_rec)
    {
        $body ="Hello ".$user_rec['name']."

".
        "Thank you! Your registration  with ".$this->sitename." is completed.
".
        "Please wait for our volunteers to contact you.
".
        "
".
        "Regards,
".
        "Webmaster
".
        $this->sitename;

        if ($this->Email($user_rec['email'],$user_rec['name'],"Welcome to ".$this->sitename,$body)){
            return true;
        } else {
            $this->HandleError("Failed sending user welcome email.");
            return false;
        }
    }

    function SendAdminIntimationOnRegComplete(&$user_rec)
    {
        if(empty($this->admin_email))
        {
            return false;
        }
        $body ="A new user registered at ".$this->sitename."
".
        "Name: ".$user_rec['name']."
".
        "Email address: ".$user_rec['email']."
";

        if ($this->Email($this->admin_email,"Admin","Student Registration Completed: ".$user_rec['name'],$body)){
            return true;
        } else {
            return false;
        }
    }

    function ValidateRegistrationSubmission()
    {
        //This is a hidden input field. Humans won't fill this field.
        if(!empty($_POST[$this->GetSpamTrapInputName()]) )
        {
            //The proper error is not given intentionally
            $this->HandleError("Automated submission prevention: case 2 failed");
            return false;
        }

        $validator = new FormValidator();
        $validator->addValidation("name","req","请填写姓名");
        $validator->addValidation("email","req","请填写Email");
        $validator->addValidation("date","req","请填写抵达日期");
        $validator->addValidation("date","regexp=/^[0-9]{2}\/[0-9]{2}$/","日期格式为MM/DD");
        $validator->addValidation("time","req","请填写抵达时间");
        $validator->addValidation("flight","req","请填写航班号");
        $validator->addValidation("flight","regexp=/^[A-Za-z]+[0-9]+$/","请填写正确的航班号(不带空格)");
        $validator->addValidation("nump","req","请填写需接机人数");
        $validator->addValidation("numc","req","请填写行李信息");
        $validator->addValidation("contact","req","请填写电话号码");
        $validator->addValidation("wechat","req","请填写微信/QQ(至少一个)");
        $validator->addValidation("email","duke_email","请提供一个格式为netid@duke.edu的邮箱");

        if(!$validator->ValidateForm())
        {
            $error='';
            $error_hash = $validator->GetErrors();
            foreach($error_hash as $inpname => $inp_err)
            {
                //$error .= $inpname.':'.$inp_err."\n";
                $error .= $inp_err."\n";
            }
            $this->HandleError($error);
            return false;
        }
        return true;
    }

    function CollectRegistrationSubmission(&$formvars)
    {
        //$formvars['ts'] = $_SERVER['REQUEST_TIME'];
        $formvars['name'] = $this->Sanitize($_POST['name']);
        $formvars['email'] = $this->Sanitize($_POST['email']);
        $formvars['gender'] = $this->Sanitize($_POST['gender']);
        $formvars['major'] = $this->Sanitize($_POST['major']);
        $formvars['comp'] = $this->Sanitize($_POST['comp']);
        $formvars['date'] = $this->Sanitize($_POST['date']);
        $formvars['time'] = $this->Sanitize($_POST['time']);
        $formvars['flight'] = $this->Sanitize($_POST['flight']);
        $formvars['nump'] = $this->Sanitize($_POST['nump']);
        $formvars['numc'] = $this->Sanitize($_POST['numc']);
        $formvars['contact'] = $this->Sanitize($_POST['contact']);
        $formvars['wechat'] = $this->Sanitize($_POST['wechat']);
    }

    function ValidateCheckSubmission()
    {
        //This is a hidden input field. Humans won't fill this field.
        if(!empty($_POST[$this->GetSpamTrapInputName()]) )
        {
            //The proper error is not given intentionally
            $this->HandleError("Automated submission prevention: case 2 failed");
            return false;
        }

        $validator = new FormValidator();
        $validator->addValidation("email","req","请填写Email");
        $validator->addValidation("flight","req","请填写航班号");
        $validator->addValidation("flight","num","航班号仅需数字部分");
        $validator->addValidation("email","regexp=/^[\.0-9a-zA-Z-]+@duke+\.+edu$/i","请提供一个以 @duke.edu 结尾的邮箱");

        if(!$validator->ValidateForm())
        {
            $error='';
            $error_hash = $validator->GetErrors();
            foreach($error_hash as $inpname => $inp_err)
            {
                //$error .= $inpname.':'.$inp_err."\n";
                $error .= $inp_err."\n";
            }
            $this->HandleError($error);
            return false;
        }
        return true;
    }

    function CollectCheckSubmission(&$formvars)
    {
        $formvars['email'] = $this->Sanitize($_POST['email']);
        $formvars['flight'] = $this->Sanitize($_POST['flight']);
    }

    function SendUserConfirmationEmail(&$formvars)
    {
        $confirmcode = $formvars['confirmcode'];
        $email = $formvars['email'];

        $confirm_url = $this->GetAbsoluteURLFolder().'/confirmreg.php?email='.$email.'&code='.$confirmcode;

        $body ="Hello ".$formvars['name']."

".
        "Thanks for your registration with ".$this->sitename."
".
        "Please click the link below or enter the url in a web browser to confirm your registration.
".
        "$confirm_url
".
        "
".
        "Regards,
".
        "Webmaster
".
        $this->sitename;

        if ($this->Email($formvars['email'],$formvars['name'],"Your registration with ".$this->sitename,$body)){
            return true;
        } else {
            $this->HandleError("Failed sending registration confirmation email.");
            return false;
        }
    }

    function GetAbsoluteURLFolder()
    {
        $scriptFolder = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://';
        $scriptFolder .= $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']);
        return $scriptFolder;
    }

    function SendAdminIntimationEmail(&$formvars)
    {
        $body ="A new student registered at ".$this->sitename."
".
        "Name: ".$formvars['name']."
".
        "Email address: ".$formvars['email']."
";

        return $this->Email($this->admin_email,"Admin","New Student Registration: ".$formvars['name'],$body);
    }

    function SaveToDatabase(&$formvars)
    {
        if(!$this->DBLogin())
        {
            $this->HandleError("Database login failed!");
            return false;
        }
        if(!$this->Ensuretable())
        {
            return false;
        }
        if(!$this->IsFieldUnique($formvars,'email'))
        {
            $this->HandleError("This email is already registered");
            return false;
        }

        if(!$this->InsertIntoDB($formvars))
        {
            $this->HandleError("Inserting to Database failed!");
            return false;
        }
        return true;
    }

    function IsFieldUnique($formvars,$fieldname)
    {
        $field_val = $this->SanitizeForSQL($formvars[$fieldname]);
        $qry = "select $fieldname from $this->tablename where $fieldname='".$field_val."'";
        $result = mysql_query($qry,$this->connection);
        if($result && mysql_num_rows($result) > 0)
        {
            return false;
        }
        return true;
    }

    function DBLogin()
    {

        $this->connection = mysql_connect($this->db_host,$this->username,$this->pwd);

        if(!$this->connection)
        {
            $this->HandleDBError("Database Login failed! Please make sure that the DB login credentials provided are correct");
            return false;
        }
        if(!mysql_select_db($this->database, $this->connection))
        {
            $this->HandleDBError('Failed to select database: '.$this->database.' Please make sure that the database name provided is correct');
            return false;
        }
        if(!mysql_query("SET NAMES 'UTF8'",$this->connection))
        {
            $this->HandleDBError('Error setting utf8 encoding');
            return false;
        }
        return true;
    }

    function Ensuretable()
    {
        $result = mysql_query("SHOW COLUMNS FROM $this->tablename");
        if(!$result || mysql_num_rows($result) <= 0)
        {
            return $this->CreateTable();
        }
        return true;
    }

    function CreateTable()
    {
        $qry = "Create Table $this->tablename (".
                "id_user INT NOT NULL AUTO_INCREMENT ,".
                "ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,".
                "name VARCHAR( 128 ) NOT NULL ,".
                "email VARCHAR( 64 ) NOT NULL ,".
                "gender VARCHAR( 16 ),".
                "major VARCHAR( 128 ) ,".
                "comp VARCHAR( 128 ) ,".
                "date VARCHAR( 64 ) ,".
                "time VARCHAR( 64 ) ,".
                "flight VARCHAR( 64 ) ,".
                "nump VARCHAR( 64 ) ,".
                "numc VARCHAR( 64 ) ,".
                "contact VARCHAR( 64 ) NOT NULL ,".
                "wechat VARCHAR( 32 ),".
                "volunteer VARCHAR( 128 ),".
                "confirmcode VARCHAR(32) ,".
                "PRIMARY KEY ( id_user )".
                ")DEFAULT CHARSET=utf8";

        if(!mysql_query($qry,$this->connection))
        {
            $this->HandleDBError("Error creating the table \nquery was\n $qry");
            return false;
        }
        return true;
    }

    function InsertIntoDB(&$formvars)
    {

        $confirmcode = $this->MakeConfirmationMd5($formvars['email']);

        $formvars['confirmcode'] = $confirmcode;

        //date('Y-m-d H:i:s',$formvars['ts'])
        $insert_query = 'insert into '.$this->tablename.'(
                name,
                email,
                gender,
                major,
                comp,
                date,
                time,
                flight,
                nump,
                numc,
                contact,
                wechat,
                confirmcode
                )
                values
                (
                "' . $this->SanitizeForSQL($formvars['name']) . '",
                "' . $this->SanitizeForSQL($formvars['email']) . '",
                "' . $this->SanitizeForSQL($formvars['gender']) . '",
                "' . $this->SanitizeForSQL($formvars['major']) . '",
                "' . $this->SanitizeForSQL($formvars['comp']) . '",
                "' . $this->SanitizeForSQL($formvars['date']) . '",
                "' . $this->SanitizeForSQL($formvars['time']) . '",
                "' . $this->SanitizeForSQL($formvars['flight']) . '",
                "' . $this->SanitizeForSQL($formvars['nump']) . '",
                "' . $this->SanitizeForSQL($formvars['numc']) . '",
                "' . $this->SanitizeForSQL($formvars['contact']) . '",
                "' . $this->SanitizeForSQL($formvars['wechat']) . '",
                "' . $confirmcode . '"
                )';
        if(!mysql_query( $insert_query ,$this->connection))
        {
            $this->HandleDBError("Error inserting data to the table\nquery:$insert_query");
            return false;
        }
        return true;
    }
    function MakeConfirmationMd5($email)
    {
        $randno1 = rand();
        $randno2 = rand();
        return md5($email.$this->rand_key.$randno1.''.$randno2);
    }
    function SanitizeForSQL($str)
    {
        if( function_exists( "mysql_real_escape_string" ) )
        {
              $ret_str = mysql_real_escape_string( $str );
        }
        else
        {
              $ret_str = addslashes( $str );
        }
        return $ret_str;
    }

 /*
    Sanitize() function removes any potential threat from the
    data submitted. Prevents email injections or any other hacker attempts.
    if $remove_nl is true, newline chracters are removed from the input.
    */
    function Sanitize($str,$remove_nl=true)
    {
        $str = $this->StripSlashes($str);

        if($remove_nl)
        {
            $injections = array('/(\n+)/i',
                '/(\r+)/i',
                '/(\t+)/i',
                '/(%0A+)/i',
                '/(%0D+)/i',
                '/(%08+)/i',
                '/(%09+)/i'
                );
            $str = preg_replace($injections,'',$str);
        }

        return $str;
    }
    function StripSlashes($str)
    {
        if(get_magic_quotes_gpc())
        {
            $str = stripslashes($str);
        }
        return $str;
    }
}
?>


text:
Client library for SqlManagementClient

## Installation and Usage
```bash
npm install --save @datafire/azure_sql_manageddatabasesecurityalertpolicies
```
```js
let azure_sql_manageddatabasesecurityalertpolicies = require('@datafire/azure_sql_manageddatabasesecurityalertpolicies').create({
  access_token: "",
  refresh_token: "",
  client_id: "",
  client_secret: "",
  redirect_uri: ""
});

.then(data => {
  console.log(data);
});
```

## Description

The Azure SQL Database management API provides a RESTful set of web APIs that interact with Azure SQL Database services to manage your databases. The API enables users to create, retrieve, update, and delete databases, servers, and other entities.

## Actions

### ManagedDatabaseSecurityAlertPolicies_ListByDatabase
Gets a list of managed database's security alert policies.

```js
azure_sql_manageddatabasesecurityalertpolicies.ManagedDatabaseSecurityAlertPolicies_ListByDatabase({
  "resourceGroupName": "",
  "managedInstanceName": "",
  "databaseName": "",
  "subscriptionId": "",
  "api-version": ""
}, context)
```

#### Input
* input `object`
  * resourceGroupName **required** `string`: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
  * managedInstanceName **required** `string`: The name of the managed instance.
  * databaseName **required** `string`: The name of the managed database for which the security alert policies are defined.
  * subscriptionId **required** `string`: The subscription ID that identifies an Azure subscription.
  * api-version **required** `string`: The API version to use for the request.

#### Output
* output [ManagedDatabaseSecurityAlertPolicyListResult](#manageddatabasesecurityalertpolicylistresult)

### ManagedDatabaseSecurityAlertPolicies_Get
Gets a managed database's security alert policy.

```js
azure_sql_manageddatabasesecurityalertpolicies.ManagedDatabaseSecurityAlertPolicies_Get({
  "resourceGroupName": "",
  "managedInstanceName": "",
  "databaseName": "",
  "securityAlertPolicyName": "",
  "subscriptionId": "",
  "api-version": ""
}, context)
```

#### Input
* input `object`
  * resourceGroupName **required** `string`: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
  * managedInstanceName **required** `string`: The name of the managed instance.
  * databaseName **required** `string`: The name of the managed database for which the security alert policy is defined.
  * securityAlertPolicyName **required** `string` (values: default): The name of the security alert policy.
  * subscriptionId **required** `string`: The subscription ID that identifies an Azure subscription.
  * api-version **required** `string`: The API version to use for the request.

#### Output
* output [ManagedDatabaseSecurityAlertPolicy](#manageddatabasesecurityalertpolicy)

### ManagedDatabaseSecurityAlertPolicies_CreateOrUpdate
Creates or updates a database's security alert policy.

```js
azure_sql_manageddatabasesecurityalertpolicies.ManagedDatabaseSecurityAlertPolicies_CreateOrUpdate({
  "resourceGroupName": "",
  "managedInstanceName": "",
  "databaseName": "",
  "securityAlertPolicyName": "",
  "parameters": {},
  "subscriptionId": "",
  "api-version": ""
}, context)
```

#### Input
* input `object`
  * resourceGroupName **required** `string`: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
  * managedInstanceName **required** `string`: The name of the managed instance.
  * databaseName **required** `string`: The name of the managed database for which the security alert policy is defined.
  * securityAlertPolicyName **required** `string` (values: default): The name of the security alert policy.
  * parameters **required** [ManagedDatabaseSecurityAlertPolicy](#manageddatabasesecurityalertpolicy)
  * subscriptionId **required** `string`: The subscription ID that identifies an Azure subscription.
  * api-version **required** `string`: The API version to use for the request.

#### Output
* output [ManagedDatabaseSecurityAlertPolicy](#manageddatabasesecurityalertpolicy)

## Definitions

### ManagedDatabaseSecurityAlertPolicy
* ManagedDatabaseSecurityAlertPolicy `object`: A managed database security alert policy.
  * properties [SecurityAlertPolicyProperties](#securityalertpolicyproperties)
  * id `string`: Resource ID.
  * name `string`: Resource name.
  * type `string`: Resource type.

### ManagedDatabaseSecurityAlertPolicyListResult
* ManagedDatabaseSecurityAlertPolicyListResult `object`: A list of the managed database's security alert policies.
  * nextLink `string`: Link to retrieve next page of results.
  * value `array`: Array of results.
    * items [ManagedDatabaseSecurityAlertPolicy](#manageddatabasesecurityalertpolicy)

### SecurityAlertPolicyProperties
* SecurityAlertPolicyProperties `object`: Properties of a security alert policy.
  * creationTime `string`: Specifies the UTC creation time of the policy.
  * disabledAlerts `array`: Specifies an array of alerts that are disabled. Allowed values are: Sql_Injection, Sql_Injection_Vulnerability, Access_Anomaly, Data_Exfiltration, Unsafe_Action
    * items `string`
  * emailAccountAdmins `boolean`: Specifies that the alert is sent to the account administrators.
  * emailAddresses `array`: Specifies an array of e-mail addresses to which the alert is sent.
    * items `string`
  * retentionDays `integer`: Specifies the number of days to keep in the Threat Detection audit logs.
  * state **required** `string` (values: New, Enabled, Disabled): Specifies the state of the policy, whether it is enabled or disabled or a policy has not been applied yet on the specific database.
  * storageAccountAccessKey `string`: Specifies the identifier key of the Threat Detection audit storage account.
  * storageEndpoint `string`: Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). This blob storage will hold all Threat Detection audit logs.


text:
package org.brixen.config;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.Map;
import java.util.Optional;

/**
 * Serves as a POJO to encapsulate the data deserialized by <b>Jackson</b> from the JSON configuration source for a
 * page object that models a component containing web controls that have meaningful side effects whenever they are
 * clicked and/or moused over.
 */
@ToString(callSuper = true, includeFieldNames = true)
@EqualsAndHashCode(callSuper = true)
public class ControllableConfigImpl extends LoadableConfigImpl implements ControllableConfig {

    /**
     * The configuration beans encapsulating the configuration settings for the component's controls which were
     * specified in the component's JSON configuration source. If the value is an {@code Optional} that equal to
     * {@link Optional#empty()} and which returns {@code false} for {@link Optional#isPresent()}, the JSON
     * configuration source for the component in question explicitly defined a {@code null} value for its collection of
     * control configurations. If the specified value is {@code null} the JSON configuration source did not define any
     * value at all for it.
     */
    private @Getter @Setter Optional<Map<String,ControlConfig>> controlConfigs;
}


text:
import re
import json
import datetime

import pytz
import requests
from django.core.files.base import ContentFile
from django.core.management import BaseCommand

from products.models import Product, Photo, Category

PICTURE_URL = 'http://tomat-podarky.ru/pic/%s/%s.jpg'

SIZE2_RE = re.compile(r'(\d+)\*(\d+)')
SIZE_RE = re.compile(r'(\d+)\*(\d+)\*(\d+)')
TIMEZONE = pytz.timezone('Asia/Irkutsk')

class Command(BaseCommand):

    def handle(self, *args, **options):
        path = args[0]

        if path.startswith('http'):
            content = requests.get(path).json()
        else:
            content = json.load(open(path))

        self.retail(content)

    def _images(self, product, item):
        for idx, pic in enumerate(item['pics']):
            try:
                Photo.objects.get(product=product, legacy_hash=pic['md5'])
            except Photo.DoesNotExist:
                url = PICTURE_URL % (pic['md5'], pic['md5'])
                fp = ContentFile(requests.get(url).content)
                photo = Photo(product=product)
                photo.is_main = idx == 0
                photo.legacy_hash = pic['md5']
                photo.save()
                photo.image.save(pic['filename'], fp)

    def _categories(self, product, item):
        for node in item['node_list']:
            for category in Category.objects.filter(legacy_id__icontains=node['id']):
                ids = category.legacy_id.split(',')
                for id_ in ids:
                    if int(node['id']) == int(id_):
                        product.categories.add(category)
                        break

    def _product(self, item):
        try:
            product = Product.objects.get(id=int(item['id']))
        except Product.DoesNotExist:
            product = Product(id=int(item['id']))

        quantity = int(item.get('qtyi', 0))
        if quantity < 0:
            quantity = 0

        weight = int(item.get('weight', 0))
        if weight < 0:
            weight = 0

        product.sku = item['article']
        product.weight = weight
        product.quantity = quantity
        product.code = item['link']
        product.title = item['name']
        product.description = item['descr']
        product.is_visible = bool(int(item['pub']))
        product.is_wholesale = False
        product.created = TIMEZONE.localize(datetime.datetime.fromtimestamp(int(item['dt'])))

        size = None
        try:
            size = SIZE_RE.findall(u' '.join([item['name'], item.get('alt', ''), item['descr']]))[0]
        except IndexError:
            try:
                size = SIZE2_RE.findall(u' '.join([item['name'], item.get('alt', ''), item['descr']]))[0]
            except IndexError:
                pass

        if size:
            product.size = u'×'.join([str(x) for x in size])

        return product

    def retail(self, content):
        """Розница"""

        for item in content:
            product = self._product(item)

            oldprice = float(item['oldprice'])
            price = float(item['price'])

            if oldprice:
                product.price = oldprice
                product.discount = price
                if product.discount == product.price:
                    product.discount = None
            else:
                product.price = price

            product.save()
            self._images(product, item)
            self._categories(product, item)


text:
package com.grasp.exception.dto;

import lombok.Getter;
import lombok.Setter;

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

@Getter
@Setter
public class ExceptionDTO {

    private String message;
    private List<String> errors = new ArrayList<>();

    public ExceptionDTO(String message, List<String> errors) {
        this.message = message;
        this.errors.addAll(errors);
    }

    public ExceptionDTO(String message, String error) {
        this.message = message;
        this.errors.add(error);
    }
}


text:
'use strict';
var expect = require('expect.js')
  , brita  = require('../index')
  , catchErr = require('catch-error');

describe('brita module', function(){
  describe('passing an object and filter function to the module', function(){
    // setup a test object
    it('should return an object', function(){

      //arrange
      var testObj = {
        one:   '',
        two:   '',
        three: '',
        four:  ''
      };
      var filterFunc = function(){};

      //act
      var result = brita(testObj, filterFunc);

      //assert
      expect(result).to.be.an('object');
    });

    describe('passing an invalid object argument', function () {
      it('should throw an exception', function () {
        //arrange
        var randomStr = 'random';
        var filterFunc = function(){};
        //act
        var result = catchErr({func: brita, args: [randomStr, filterFunc]});
        //assert
        expect(result).to.be.an(Error);
      });
    });

    describe('passing a string as filter argument', function () {
      it('should throw an exception', function () {
        //arrange
        var testObj = {};
        var str = 'string';
        //act
        var result = catchErr({func: brita, args: [testObj, str]});
        //assert
        expect(result).to.be.an(Error);
      });
    });

    describe('passing a number as filter argument', function () {
      it('should throw an exception', function () {
        //arrange
        var testObj = {};
        var num = 5;
        //act
        var result = catchErr({func: brita, args: [testObj, num]});
        //assert
        expect(result).to.be.an(Error);
      });
    });

    describe('when passing a filter function that always returns true', function(){
      it('should return an obj equal to the original object', function(){
        //arrange
        var testObj = {
          one:   '1',
          two:   '2',
          three: '3',
          four:  '4'
        };
        var truthyFilter = function(){
          return true;
        };
        // act
        var result = brita(testObj, truthyFilter);
        // assert
        expect(result).to.eql(testObj);
      });
    });

    describe('when passing a filter function that always returns false', function(){
      it('should return an empty object', function(){
        //arrange
        var testObj = {
          one:   '1',
          two:   '2',
          three: '3',
          four:  '4'
        };
        var falsyFilter = function(){
          return false;
        };
        // act
        var result = brita(testObj, falsyFilter);
        // assert
        expect(result).to.eql({});
      });
    });

    describe('when passing a filter function that return true for values less than 3', function(){
      it('should return filtered object with key value pairs where the value is less than 3', function(){
        //arrange
        var testObj = {
          one:   '1',
          two:   '2',
          three: '3',
          four:  '4'
        };
        var filteredObj = {
          one:   '1',
          two:   '2'
        };
        var filter = function(value){
          if (value < 3) {
            return true;
          }
          return false;
        };
        // act
        var result = brita(testObj, filter);
        // assert
        expect(result).to.eql(filteredObj);
      });
    });

    describe('when passing a filter function that return true for a given string', function(){
      it('should return filtered object with key value pairs where the value equal given string', function(){
        //arrange
        var testObj = {
          one:   'one',
          two:   'two',
          three: 'three',
          four:  'four'
        };
        var filteredObj = {
          three:   'three'
        };
        var filter = function(value){
          if (value === 'three') {
            return true;
          }
          return false;
        };
        // act
        var result = brita(testObj, filter);
        // assert
        expect(result).to.eql(filteredObj);
      });
    });

    describe('when passing a filter function that return true for a given string', function(){
      it('should return an empty object if the object has no string values', function(){
        //arrange
        var testObj = {
          one:   1,
          two:   2,
          three: 3,
          four:  4
        };
        var filter = function(value){
          if (value === 'three') {
            return true;
          }
          return false;
        };
        // act
        var result = brita(testObj, filter);
        // assert
        expect(result).to.eql({});
      });
    });

  });

  describe('when passing an object as the filter argument', function(){

    describe('a filter object with key value pair valueType: string', function(){
      it('should return an object containing only string values', function(){
        //arrange
        var testObj = {
          one:   1,
          two:   '2',
          three: 3,
          four:  '4'
        };
        var filter = {
          valueType: 'string'
        };
        var expected = {
          two:  '2',
          four: '4'
        };
        // act
        var result = brita(testObj, filter);
        // assert
        expect(result).to.eql(expected);
      });
    });

    describe('a filter object with key value pair valueType: number', function(){
      it('should return an object containing only number values', function(){
        //arrange
        var testObj = {
          one:   1,
          two:   '2',
          three: 3,
          four:  '4'
        };
        var filter = {
          valueType: 'number'
        };
        var expected = {
          one:   1,
          three: 3,
        };
        // act
        var result = brita(testObj, filter);
        // assert
        expect(result).to.eql(expected);
      });
    });

    describe('a filter object with key value pair valueType: boolean', function(){
      it('should return an object containing only boolean values', function(){
        //arrange
        var testObj = {
          one:   1,
          two:   true,
          three: 3,
          four:  false
        };
        var filter = {
          valueType: 'boolean'
        };
        var expected = {
          two: true,
          four: false,
        };
        // act
        var result = brita(testObj, filter);
        // assert
        expect(result).to.eql(expected);
      });
    });

    describe('a filter object with key value pair valueType: array', function(){
      it('should return an object containing only array values', function(){
        //arrange
        var testObj = {
          one:   1,
          two:   true,
          three: [ 1, 2, 3 ],
          four:  {},
          five:  /regex/,
          six:   ['another array']
        };
        var filter = {
          valueType: 'array'
        };
        var expected = {
          three: [ 1, 2, 3 ],
          six:   ['another array']
        };
        // act
        var result = brita(testObj, filter);
        // assert
        expect(result).to.eql(expected);
      });
    });

    describe('a filter object with key value pair valueType: regex', function(){
      it('should return an object containing only regex values', function(){
        //arrange
        var testObj = {
          one:   1,
          two:   true,
          three: [ 1, 2, 3 ],
          four:  {},
          five:  /regex/,
          six:   ['another array']
        };
        var filter = {
          valueType: 'regex'
        };
        var expected = {
          five:  /regex/
        };
        // act
        var result = brita(testObj, filter);
        // assert
        expect(result).to.eql(expected);
      });
    });

    describe('a filter object with key value pair valueType: object', function(){
      it('should return an object containing only object values', function(){
        //arrange
        var testObj = {
          one:   1,
          two:   true,
          three: [ 1, 2, 3 ],
          four:  {},
          five:  /regex/,
          six:   ['another array']
        };
        var filter = {
          valueType: 'object'
        };
        var expected = {
          four:  {}
        };
        // act
        var result = brita(testObj, filter);
        // assert
        expect(result).to.eql(expected);
      });
    });

    describe('a filter object with key keyFilter', function(){
      describe('with value: /abc/', function(){
        it('should return all key value pairs where key name contains abc', function(){
          var testObj = {
            abc: 'yes',
            dabc: 'yes',
            adbc: 'no',
            bcda: 'no'
          };
          var filter = {
            keyFilter: /abc/
          };
          var expected = {
            abc: 'yes',
            dabc: 'yes'
          };
          var result = brita(testObj, filter);
          expect(result).to.eql(expected);
        });
      });

      describe('with a value that is not a regular expression', function(){
        it('should throw an exception', function(){
          var testObj = {};
          var filter = {
            keyFilter: 'not a regular expression'
          };
          var result = catchErr({func: brita, args: [testObj, filter]});
          expect(result).to.be.an(Error);
        });
      });

    });
  });

});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>Falaise: Class Members - Functions</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Falaise
    2.1.0

SuperNEMO Software Toolkit

Main Page

Related Pages

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

All

Functions

Variables

Typedefs

Enumerations

Enumerator

Related Functions

_

a

b

c

d

e

f

g

h

i

l

m

o

p

q

r

s

t

u

v

w

x

~

- e -

energy_spectrum_at_sea_level_HE()
: snemo::simulation::cosmic_muon_generator

event_display()
: TrackerPreClustering::event_display

event_generator()
: TrackerPreClustering::event_generator

event_header()
: snemo::datamodel::event_header

event_header_cut()
: snemo::cut::event_header_cut

event_header_label()
: snemo::datamodel::event_header

event_header_utils_module()
: snemo::processing::event_header_utils_module

extract_column()
: snemo::geometry::calo_locator
, snemo::geometry::gveto_locator
, snemo::geometry::xcalo_locator

extract_layer()
: snemo::geometry::gg_locator

extract_module()
: snemo::geometry::calo_locator
, snemo::geometry::gg_locator
, snemo::geometry::gveto_locator
, snemo::geometry::xcalo_locator

extract_part()
: snemo::geometry::calo_locator
, snemo::geometry::gveto_locator
, snemo::geometry::xcalo_locator

extract_row()
: snemo::geometry::calo_locator
, snemo::geometry::gg_locator
, snemo::geometry::xcalo_locator

extract_side()
: snemo::geometry::calo_locator
, snemo::geometry::gg_locator
, snemo::geometry::gveto_locator
, snemo::geometry::xcalo_locator

extract_wall()
: snemo::geometry::gveto_locator
, snemo::geometry::xcalo_locator

<address class="footer">
Generated by

 1.8.11
</address>