text:
<?php

/**
 * Base class that represents a query for the 'contact' table.
 *
 *
 *
 * @method     ContactQuery orderById($order = Criteria::ASC) Order by the id column
 * @method     ContactQuery orderByFirstName($order = Criteria::ASC) Order by the first_name column
 * @method     ContactQuery orderByLastName($order = Criteria::ASC) Order by the last_name column
 * @method     ContactQuery orderByCompanyName($order = Criteria::ASC) Order by the company_name column
 * @method     ContactQuery orderByEmailAddress($order = Criteria::ASC) Order by the email_address column
 * @method     ContactQuery orderByPhoneMainNumber($order = Criteria::ASC) Order by the phone_main_number column
 * @method     ContactQuery orderByPhoneOtherNumber($order = Criteria::ASC) Order by the phone_other_number column
 * @method     ContactQuery orderByMailingAddress($order = Criteria::ASC) Order by the mailing_address column
 * @method     ContactQuery orderByMailingAddressLatitude($order = Criteria::ASC) Order by the mailing_address_latitude column
 * @method     ContactQuery orderByMailingAddressLongitude($order = Criteria::ASC) Order by the mailing_address_longitude column
 * @method     ContactQuery orderByCity($order = Criteria::ASC) Order by the city column
 * @method     ContactQuery orderByStateId($order = Criteria::ASC) Order by the state_id column
 * @method     ContactQuery orderByZipCode($order = Criteria::ASC) Order by the zip_code column
 * @method     ContactQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column
 * @method     ContactQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column
 *
 * @method     ContactQuery groupById() Group by the id column
 * @method     ContactQuery groupByFirstName() Group by the first_name column
 * @method     ContactQuery groupByLastName() Group by the last_name column
 * @method     ContactQuery groupByCompanyName() Group by the company_name column
 * @method     ContactQuery groupByEmailAddress() Group by the email_address column
 * @method     ContactQuery groupByPhoneMainNumber() Group by the phone_main_number column
 * @method     ContactQuery groupByPhoneOtherNumber() Group by the phone_other_number column
 * @method     ContactQuery groupByMailingAddress() Group by the mailing_address column
 * @method     ContactQuery groupByMailingAddressLatitude() Group by the mailing_address_latitude column
 * @method     ContactQuery groupByMailingAddressLongitude() Group by the mailing_address_longitude column
 * @method     ContactQuery groupByCity() Group by the city column
 * @method     ContactQuery groupByStateId() Group by the state_id column
 * @method     ContactQuery groupByZipCode() Group by the zip_code column
 * @method     ContactQuery groupByCreatedAt() Group by the created_at column
 * @method     ContactQuery groupByUpdatedAt() Group by the updated_at column
 *
 * @method     ContactQuery leftJoin($relation) Adds a LEFT JOIN clause to the query
 * @method     ContactQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query
 * @method     ContactQuery innerJoin($relation) Adds a INNER JOIN clause to the query
 *
 * @method     ContactQuery leftJoinState($relationAlias = null) Adds a LEFT JOIN clause to the query using the State relation
 * @method     ContactQuery rightJoinState($relationAlias = null) Adds a RIGHT JOIN clause to the query using the State relation
 * @method     ContactQuery innerJoinState($relationAlias = null) Adds a INNER JOIN clause to the query using the State relation
 *
 * @method     ContactQuery leftJoinUser($relationAlias = null) Adds a LEFT JOIN clause to the query using the User relation
 * @method     ContactQuery rightJoinUser($relationAlias = null) Adds a RIGHT JOIN clause to the query using the User relation
 * @method     ContactQuery innerJoinUser($relationAlias = null) Adds a INNER JOIN clause to the query using the User relation
 *
 * @method     Contact findOne(PropelPDO $con = null) Return the first Contact matching the query
 * @method     Contact findOneOrCreate(PropelPDO $con = null) Return the first Contact matching the query, or a new Contact object populated from the query conditions when no match is found
 *
 * @method     Contact findOneById(int $id) Return the first Contact filtered by the id column
 * @method     Contact findOneByFirstName(string $first_name) Return the first Contact filtered by the first_name column
 * @method     Contact findOneByLastName(string $last_name) Return the first Contact filtered by the last_name column
 * @method     Contact findOneByCompanyName(string $company_name) Return the first Contact filtered by the company_name column
 * @method     Contact findOneByEmailAddress(string $email_address) Return the first Contact filtered by the email_address column
 * @method     Contact findOneByPhoneMainNumber(string $phone_main_number) Return the first Contact filtered by the phone_main_number column
 * @method     Contact findOneByPhoneOtherNumber(string $phone_other_number) Return the first Contact filtered by the phone_other_number column
 * @method     Contact findOneByMailingAddress(string $mailing_address) Return the first Contact filtered by the mailing_address column
 * @method     Contact findOneByMailingAddressLatitude(double $mailing_address_latitude) Return the first Contact filtered by the mailing_address_latitude column
 * @method     Contact findOneByMailingAddressLongitude(double $mailing_address_longitude) Return the first Contact filtered by the mailing_address_longitude column
 * @method     Contact findOneByCity(string $city) Return the first Contact filtered by the city column
 * @method     Contact findOneByStateId(int $state_id) Return the first Contact filtered by the state_id column
 * @method     Contact findOneByZipCode(string $zip_code) Return the first Contact filtered by the zip_code column
 * @method     Contact findOneByCreatedAt(string $created_at) Return the first Contact filtered by the created_at column
 * @method     Contact findOneByUpdatedAt(string $updated_at) Return the first Contact filtered by the updated_at column
 *
 * @method     array findById(int $id) Return Contact objects filtered by the id column
 * @method     array findByFirstName(string $first_name) Return Contact objects filtered by the first_name column
 * @method     array findByLastName(string $last_name) Return Contact objects filtered by the last_name column
 * @method     array findByCompanyName(string $company_name) Return Contact objects filtered by the company_name column
 * @method     array findByEmailAddress(string $email_address) Return Contact objects filtered by the email_address column
 * @method     array findByPhoneMainNumber(string $phone_main_number) Return Contact objects filtered by the phone_main_number column
 * @method     array findByPhoneOtherNumber(string $phone_other_number) Return Contact objects filtered by the phone_other_number column
 * @method     array findByMailingAddress(string $mailing_address) Return Contact objects filtered by the mailing_address column
 * @method     array findByMailingAddressLatitude(double $mailing_address_latitude) Return Contact objects filtered by the mailing_address_latitude column
 * @method     array findByMailingAddressLongitude(double $mailing_address_longitude) Return Contact objects filtered by the mailing_address_longitude column
 * @method     array findByCity(string $city) Return Contact objects filtered by the city column
 * @method     array findByStateId(int $state_id) Return Contact objects filtered by the state_id column
 * @method     array findByZipCode(string $zip_code) Return Contact objects filtered by the zip_code column
 * @method     array findByCreatedAt(string $created_at) Return Contact objects filtered by the created_at column
 * @method     array findByUpdatedAt(string $updated_at) Return Contact objects filtered by the updated_at column
 *
 * @package    propel.generator.lib.model.om
 */
abstract class BaseContactQuery extends ModelCriteria
{

    /**
     * Initializes internal state of BaseContactQuery object.
     *
     * @param     string $dbName The dabase 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 = 'propel', $modelName = 'Contact', $modelAlias = null)
    {
        parent::__construct($dbName, $modelName, $modelAlias);
    }

    /**
     * Returns a new ContactQuery object.
     *
     * @param     string $modelAlias The alias of a model in the query
     * @param     ContactQuery|Criteria $criteria Optional Criteria to build the query from
     *
     * @return ContactQuery
     */
    public static function create($modelAlias = null, $criteria = null)
    {
        if ($criteria instanceof ContactQuery) {
            return $criteria;
        }
        $query = new ContactQuery();
        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     PropelPDO $con an optional connection object
     *
     * @return   Contact|Contact[]|mixed the result, formatted by the current formatter
     */
    public function findPk($key, $con = null)
    {
        if ($key === null) {
            return null;
        }
        if ((null !== ($obj = ContactPeer::getInstanceFromPool((string) $key))) && !$this->formatter) {
            // the object is alredy in the instance pool
            return $obj;
        }
        if ($con === null) {
            $con = Propel::getConnection(ContactPeer::DATABASE_NAME, Propel::CONNECTION_READ);
        }
        $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);
        } else {
            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     PropelPDO $con A connection object
     *
     * @return   Contact A model object, or null if the key is not found
     * @throws   PropelException
     */
    protected function findPkSimple($key, $con)
    {
        $sql = 'SELECT `ID`, `FIRST_NAME`, `LAST_NAME`, `COMPANY_NAME`, `EMAIL_ADDRESS`, `PHONE_MAIN_NUMBER`, `PHONE_OTHER_NUMBER`, `MAILING_ADDRESS`, `MAILING_ADDRESS_LATITUDE`, `MAILING_ADDRESS_LONGITUDE`, `CITY`, `STATE_ID`, `ZIP_CODE`, `CREATED_AT`, `UPDATED_AT` FROM `contact` 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), $e);
        }
        $obj = null;
        if ($row = $stmt->fetch(PDO::FETCH_NUM)) {
            $obj = new Contact();
            $obj->hydrate($row);
            ContactPeer::addInstanceToPool($obj, (string) $key);
        }
        $stmt->closeCursor();

        return $obj;
    }

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

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

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

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

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

        return $this->addUsingAlias(ContactPeer::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 ContactQuery The current query, for fluid interface
     */
    public function filterByPrimaryKeys($keys)
    {

        return $this->addUsingAlias(ContactPeer::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 ContactQuery The current query, for fluid interface
     */
    public function filterById($id = null, $comparison = null)
    {
        if (is_array($id) && null === $comparison) {
            $comparison = Criteria::IN;
        }

        return $this->addUsingAlias(ContactPeer::ID, $id, $comparison);
    }

    /**
     * Filter the query on the first_name column
     *
     * Example usage:
     *
     * $query->filterByFirstName('fooValue');   // WHERE first_name = 'fooValue'
     * $query->filterByFirstName('%fooValue%'); // WHERE first_name LIKE '%fooValue%'
     *
     *
     * @param     string $firstName The value to use as filter.
     *              Accepts wildcards (* and % trigger a LIKE)
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return ContactQuery The current query, for fluid interface
     */
    public function filterByFirstName($firstName = null, $comparison = null)
    {
        if (null === $comparison) {
            if (is_array($firstName)) {
                $comparison = Criteria::IN;
            } elseif (preg_match('/[\%\*]/', $firstName)) {
                $firstName = str_replace('*', '%', $firstName);
                $comparison = Criteria::LIKE;
            }
        }

        return $this->addUsingAlias(ContactPeer::FIRST_NAME, $firstName, $comparison);
    }

    /**
     * Filter the query on the last_name column
     *
     * Example usage:
     *
     * $query->filterByLastName('fooValue');   // WHERE last_name = 'fooValue'
     * $query->filterByLastName('%fooValue%'); // WHERE last_name LIKE '%fooValue%'
     *
     *
     * @param     string $lastName The value to use as filter.
     *              Accepts wildcards (* and % trigger a LIKE)
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return ContactQuery The current query, for fluid interface
     */
    public function filterByLastName($lastName = null, $comparison = null)
    {
        if (null === $comparison) {
            if (is_array($lastName)) {
                $comparison = Criteria::IN;
            } elseif (preg_match('/[\%\*]/', $lastName)) {
                $lastName = str_replace('*', '%', $lastName);
                $comparison = Criteria::LIKE;
            }
        }

        return $this->addUsingAlias(ContactPeer::LAST_NAME, $lastName, $comparison);
    }

    /**
     * Filter the query on the company_name column
     *
     * Example usage:
     *
     * $query->filterByCompanyName('fooValue');   // WHERE company_name = 'fooValue'
     * $query->filterByCompanyName('%fooValue%'); // WHERE company_name LIKE '%fooValue%'
     *
     *
     * @param     string $companyName The value to use as filter.
     *              Accepts wildcards (* and % trigger a LIKE)
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return ContactQuery The current query, for fluid interface
     */
    public function filterByCompanyName($companyName = null, $comparison = null)
    {
        if (null === $comparison) {
            if (is_array($companyName)) {
                $comparison = Criteria::IN;
            } elseif (preg_match('/[\%\*]/', $companyName)) {
                $companyName = str_replace('*', '%', $companyName);
                $comparison = Criteria::LIKE;
            }
        }

        return $this->addUsingAlias(ContactPeer::COMPANY_NAME, $companyName, $comparison);
    }

    /**
     * Filter the query on the email_address column
     *
     * Example usage:
     *
     * $query->filterByEmailAddress('fooValue');   // WHERE email_address = 'fooValue'
     * $query->filterByEmailAddress('%fooValue%'); // WHERE email_address LIKE '%fooValue%'
     *
     *
     * @param     string $emailAddress The value to use as filter.
     *              Accepts wildcards (* and % trigger a LIKE)
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return ContactQuery The current query, for fluid interface
     */
    public function filterByEmailAddress($emailAddress = null, $comparison = null)
    {
        if (null === $comparison) {
            if (is_array($emailAddress)) {
                $comparison = Criteria::IN;
            } elseif (preg_match('/[\%\*]/', $emailAddress)) {
                $emailAddress = str_replace('*', '%', $emailAddress);
                $comparison = Criteria::LIKE;
            }
        }

        return $this->addUsingAlias(ContactPeer::EMAIL_ADDRESS, $emailAddress, $comparison);
    }

    /**
     * Filter the query on the phone_main_number column
     *
     * Example usage:
     *
     * $query->filterByPhoneMainNumber('fooValue');   // WHERE phone_main_number = 'fooValue'
     * $query->filterByPhoneMainNumber('%fooValue%'); // WHERE phone_main_number LIKE '%fooValue%'
     *
     *
     * @param     string $phoneMainNumber The value to use as filter.
     *              Accepts wildcards (* and % trigger a LIKE)
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return ContactQuery The current query, for fluid interface
     */
    public function filterByPhoneMainNumber($phoneMainNumber = null, $comparison = null)
    {
        if (null === $comparison) {
            if (is_array($phoneMainNumber)) {
                $comparison = Criteria::IN;
            } elseif (preg_match('/[\%\*]/', $phoneMainNumber)) {
                $phoneMainNumber = str_replace('*', '%', $phoneMainNumber);
                $comparison = Criteria::LIKE;
            }
        }

        return $this->addUsingAlias(ContactPeer::PHONE_MAIN_NUMBER, $phoneMainNumber, $comparison);
    }

    /**
     * Filter the query on the phone_other_number column
     *
     * Example usage:
     *
     * $query->filterByPhoneOtherNumber('fooValue');   // WHERE phone_other_number = 'fooValue'
     * $query->filterByPhoneOtherNumber('%fooValue%'); // WHERE phone_other_number LIKE '%fooValue%'
     *
     *
     * @param     string $phoneOtherNumber The value to use as filter.
     *              Accepts wildcards (* and % trigger a LIKE)
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return ContactQuery The current query, for fluid interface
     */
    public function filterByPhoneOtherNumber($phoneOtherNumber = null, $comparison = null)
    {
        if (null === $comparison) {
            if (is_array($phoneOtherNumber)) {
                $comparison = Criteria::IN;
            } elseif (preg_match('/[\%\*]/', $phoneOtherNumber)) {
                $phoneOtherNumber = str_replace('*', '%', $phoneOtherNumber);
                $comparison = Criteria::LIKE;
            }
        }

        return $this->addUsingAlias(ContactPeer::PHONE_OTHER_NUMBER, $phoneOtherNumber, $comparison);
    }

    /**
     * Filter the query on the mailing_address column
     *
     * Example usage:
     *
     * $query->filterByMailingAddress('fooValue');   // WHERE mailing_address = 'fooValue'
     * $query->filterByMailingAddress('%fooValue%'); // WHERE mailing_address LIKE '%fooValue%'
     *
     *
     * @param     string $mailingAddress The value to use as filter.
     *              Accepts wildcards (* and % trigger a LIKE)
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return ContactQuery The current query, for fluid interface
     */
    public function filterByMailingAddress($mailingAddress = null, $comparison = null)
    {
        if (null === $comparison) {
            if (is_array($mailingAddress)) {
                $comparison = Criteria::IN;
            } elseif (preg_match('/[\%\*]/', $mailingAddress)) {
                $mailingAddress = str_replace('*', '%', $mailingAddress);
                $comparison = Criteria::LIKE;
            }
        }

        return $this->addUsingAlias(ContactPeer::MAILING_ADDRESS, $mailingAddress, $comparison);
    }

    /**
     * Filter the query on the mailing_address_latitude column
     *
     * Example usage:
     *
     * $query->filterByMailingAddressLatitude(1234); // WHERE mailing_address_latitude = 1234
     * $query->filterByMailingAddressLatitude(array(12, 34)); // WHERE mailing_address_latitude IN (12, 34)
     * $query->filterByMailingAddressLatitude(array('min' => 12)); // WHERE mailing_address_latitude > 12
     *
     *
     * @param     mixed $mailingAddressLatitude 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 ContactQuery The current query, for fluid interface
     */
    public function filterByMailingAddressLatitude($mailingAddressLatitude = null, $comparison = null)
    {
        if (is_array($mailingAddressLatitude)) {
            $useMinMax = false;
            if (isset($mailingAddressLatitude['min'])) {
                $this->addUsingAlias(ContactPeer::MAILING_ADDRESS_LATITUDE, $mailingAddressLatitude['min'], Criteria::GREATER_EQUAL);
                $useMinMax = true;
            }
            if (isset($mailingAddressLatitude['max'])) {
                $this->addUsingAlias(ContactPeer::MAILING_ADDRESS_LATITUDE, $mailingAddressLatitude['max'], Criteria::LESS_EQUAL);
                $useMinMax = true;
            }
            if ($useMinMax) {
                return $this;
            }
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }
        }

        return $this->addUsingAlias(ContactPeer::MAILING_ADDRESS_LATITUDE, $mailingAddressLatitude, $comparison);
    }

    /**
     * Filter the query on the mailing_address_longitude column
     *
     * Example usage:
     *
     * $query->filterByMailingAddressLongitude(1234); // WHERE mailing_address_longitude = 1234
     * $query->filterByMailingAddressLongitude(array(12, 34)); // WHERE mailing_address_longitude IN (12, 34)
     * $query->filterByMailingAddressLongitude(array('min' => 12)); // WHERE mailing_address_longitude > 12
     *
     *
     * @param     mixed $mailingAddressLongitude 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 ContactQuery The current query, for fluid interface
     */
    public function filterByMailingAddressLongitude($mailingAddressLongitude = null, $comparison = null)
    {
        if (is_array($mailingAddressLongitude)) {
            $useMinMax = false;
            if (isset($mailingAddressLongitude['min'])) {
                $this->addUsingAlias(ContactPeer::MAILING_ADDRESS_LONGITUDE, $mailingAddressLongitude['min'], Criteria::GREATER_EQUAL);
                $useMinMax = true;
            }
            if (isset($mailingAddressLongitude['max'])) {
                $this->addUsingAlias(ContactPeer::MAILING_ADDRESS_LONGITUDE, $mailingAddressLongitude['max'], Criteria::LESS_EQUAL);
                $useMinMax = true;
            }
            if ($useMinMax) {
                return $this;
            }
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }
        }

        return $this->addUsingAlias(ContactPeer::MAILING_ADDRESS_LONGITUDE, $mailingAddressLongitude, $comparison);
    }

    /**
     * Filter the query on the city column
     *
     * Example usage:
     *
     * $query->filterByCity('fooValue');   // WHERE city = 'fooValue'
     * $query->filterByCity('%fooValue%'); // WHERE city LIKE '%fooValue%'
     *
     *
     * @param     string $city The value to use as filter.
     *              Accepts wildcards (* and % trigger a LIKE)
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return ContactQuery The current query, for fluid interface
     */
    public function filterByCity($city = null, $comparison = null)
    {
        if (null === $comparison) {
            if (is_array($city)) {
                $comparison = Criteria::IN;
            } elseif (preg_match('/[\%\*]/', $city)) {
                $city = str_replace('*', '%', $city);
                $comparison = Criteria::LIKE;
            }
        }

        return $this->addUsingAlias(ContactPeer::CITY, $city, $comparison);
    }

    /**
     * Filter the query on the state_id column
     *
     * Example usage:
     *
     * $query->filterByStateId(1234); // WHERE state_id = 1234
     * $query->filterByStateId(array(12, 34)); // WHERE state_id IN (12, 34)
     * $query->filterByStateId(array('min' => 12)); // WHERE state_id > 12
     *
     *
     * @see       filterByState()
     *
     * @param     mixed $stateId 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 ContactQuery The current query, for fluid interface
     */
    public function filterByStateId($stateId = null, $comparison = null)
    {
        if (is_array($stateId)) {
            $useMinMax = false;
            if (isset($stateId['min'])) {
                $this->addUsingAlias(ContactPeer::STATE_ID, $stateId['min'], Criteria::GREATER_EQUAL);
                $useMinMax = true;
            }
            if (isset($stateId['max'])) {
                $this->addUsingAlias(ContactPeer::STATE_ID, $stateId['max'], Criteria::LESS_EQUAL);
                $useMinMax = true;
            }
            if ($useMinMax) {
                return $this;
            }
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }
        }

        return $this->addUsingAlias(ContactPeer::STATE_ID, $stateId, $comparison);
    }

    /**
     * Filter the query on the zip_code column
     *
     * Example usage:
     *
     * $query->filterByZipCode('fooValue');   // WHERE zip_code = 'fooValue'
     * $query->filterByZipCode('%fooValue%'); // WHERE zip_code LIKE '%fooValue%'
     *
     *
     * @param     string $zipCode The value to use as filter.
     *              Accepts wildcards (* and % trigger a LIKE)
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return ContactQuery The current query, for fluid interface
     */
    public function filterByZipCode($zipCode = null, $comparison = null)
    {
        if (null === $comparison) {
            if (is_array($zipCode)) {
                $comparison = Criteria::IN;
            } elseif (preg_match('/[\%\*]/', $zipCode)) {
                $zipCode = str_replace('*', '%', $zipCode);
                $comparison = Criteria::LIKE;
            }
        }

        return $this->addUsingAlias(ContactPeer::ZIP_CODE, $zipCode, $comparison);
    }

    /**
     * Filter the query on the created_at column
     *
     * Example usage:
     *
     * $query->filterByCreatedAt('2011-03-14'); // WHERE created_at = '2011-03-14'
     * $query->filterByCreatedAt('now'); // WHERE created_at = '2011-03-14'
     * $query->filterByCreatedAt(array('max' => 'yesterday')); // WHERE created_at > '2011-03-13'
     *
     *
     * @param     mixed $createdAt The value to use as filter.
     *              Values can be integers (unix timestamps), DateTime objects, or strings.
     *              Empty strings are treated as NULL.
     *              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 ContactQuery The current query, for fluid interface
     */
    public function filterByCreatedAt($createdAt = null, $comparison = null)
    {
        if (is_array($createdAt)) {
            $useMinMax = false;
            if (isset($createdAt['min'])) {
                $this->addUsingAlias(ContactPeer::CREATED_AT, $createdAt['min'], Criteria::GREATER_EQUAL);
                $useMinMax = true;
            }
            if (isset($createdAt['max'])) {
                $this->addUsingAlias(ContactPeer::CREATED_AT, $createdAt['max'], Criteria::LESS_EQUAL);
                $useMinMax = true;
            }
            if ($useMinMax) {
                return $this;
            }
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }
        }

        return $this->addUsingAlias(ContactPeer::CREATED_AT, $createdAt, $comparison);
    }

    /**
     * Filter the query on the updated_at column
     *
     * Example usage:
     *
     * $query->filterByUpdatedAt('2011-03-14'); // WHERE updated_at = '2011-03-14'
     * $query->filterByUpdatedAt('now'); // WHERE updated_at = '2011-03-14'
     * $query->filterByUpdatedAt(array('max' => 'yesterday')); // WHERE updated_at > '2011-03-13'
     *
     *
     * @param     mixed $updatedAt The value to use as filter.
     *              Values can be integers (unix timestamps), DateTime objects, or strings.
     *              Empty strings are treated as NULL.
     *              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 ContactQuery The current query, for fluid interface
     */
    public function filterByUpdatedAt($updatedAt = null, $comparison = null)
    {
        if (is_array($updatedAt)) {
            $useMinMax = false;
            if (isset($updatedAt['min'])) {
                $this->addUsingAlias(ContactPeer::UPDATED_AT, $updatedAt['min'], Criteria::GREATER_EQUAL);
                $useMinMax = true;
            }
            if (isset($updatedAt['max'])) {
                $this->addUsingAlias(ContactPeer::UPDATED_AT, $updatedAt['max'], Criteria::LESS_EQUAL);
                $useMinMax = true;
            }
            if ($useMinMax) {
                return $this;
            }
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }
        }

        return $this->addUsingAlias(ContactPeer::UPDATED_AT, $updatedAt, $comparison);
    }

    /**
     * Filter the query by a related State object
     *
     * @param   State|PropelObjectCollection $state The related object(s) to use as filter
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return   ContactQuery The current query, for fluid interface
     * @throws   PropelException - if the provided filter is invalid.
     */
    public function filterByState($state, $comparison = null)
    {
        if ($state instanceof State) {
            return $this
                ->addUsingAlias(ContactPeer::STATE_ID, $state->getId(), $comparison);
        } elseif ($state instanceof PropelObjectCollection) {
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }

            return $this
                ->addUsingAlias(ContactPeer::STATE_ID, $state->toKeyValue('PrimaryKey', 'Id'), $comparison);
        } else {
            throw new PropelException('filterByState() only accepts arguments of type State or PropelCollection');
        }
    }

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

        // 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, 'State');
        }

        return $this;
    }

    /**
     * Use the State relation State 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   StateQuery A secondary query class using the current class as primary query
     */
    public function useStateQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN)
    {
        return $this
            ->joinState($relationAlias, $joinType)
            ->useQuery($relationAlias ? $relationAlias : 'State', 'StateQuery');
    }

    /**
     * Filter the query by a related User object
     *
     * @param   User|PropelObjectCollection $user  the related object to use as filter
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return   ContactQuery The current query, for fluid interface
     * @throws   PropelException - if the provided filter is invalid.
     */
    public function filterByUser($user, $comparison = null)
    {
        if ($user instanceof User) {
            return $this
                ->addUsingAlias(ContactPeer::ID, $user->getContactId(), $comparison);
        } elseif ($user instanceof PropelObjectCollection) {
            return $this
                ->useUserQuery()
                ->filterByPrimaryKeys($user->getPrimaryKeys())
                ->endUse();
        } else {
            throw new PropelException('filterByUser() only accepts arguments of type User or PropelCollection');
        }
    }

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

        // 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, 'User');
        }

        return $this;
    }

    /**
     * Use the User relation User 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   UserQuery A secondary query class using the current class as primary query
     */
    public function useUserQuery($relationAlias = null, $joinType = Criteria::LEFT_JOIN)
    {
        return $this
            ->joinUser($relationAlias, $joinType)
            ->useQuery($relationAlias ? $relationAlias : 'User', 'UserQuery');
    }

    /**
     * Exclude object from result
     *
     * @param   Contact $contact Object to remove from the list of results
     *
     * @return ContactQuery The current query, for fluid interface
     */
    public function prune($contact = null)
    {
        if ($contact) {
            $this->addUsingAlias(ContactPeer::ID, $contact->getId(), Criteria::NOT_EQUAL);
        }

        return $this;
    }

} // BaseContactQuery


text:
<?php

namespace SudoCms\SiteBundle\Form;

use Sudoux\MortgageBundle\Form\PricingConnectionType;

use Sudoux\MortgageBundle\Form\CreditConnectionType;

use Sudoux\MortgageBundle\Entity\LosConnection;

use Sudoux\MortgageBundle\Form\LosConnectionType;

use Sudoux\Cms\SiteBundle\Entity\Site;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * Class SettingsType
 * @package SudoCms\SiteBundle\Form
 * @author Dan Alvare
 */
class SettingsType extends \Sudoux\Cms\SiteBundle\Form\SettingsType
{

	public function __construct(Site $site)
	{
		parent::__construct($site);
	}

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
    	parent::buildForm($builder, $options);
    	$site = $this->site;
        $builder
            ->add('loan_document_vocab', 'entity', array(
            	'label' => 'Document Checklist Category',
            	'class' => 'Sudoux\Cms\TaxonomyBundle\Entity\Vocabulary',
            	'property' => 'name',
            	'empty_value' => 'Select a Vocabulary',
            	'query_builder' => function(EntityRepository $er) use ($site) {
            		return $er->findAllBySiteQuery($site);
            	},
    		))
    		->add('show_los_milestones', 'checkbox', array(
    			'label' => 'Display Milestones',
    			'required' => false,
    		))
            ->add('send_milestones_notifications', 'checkbox', array(
                'label' => 'Send Milestone Notifications',
                'required' => false,
            ))
            ->add('loan_complete_url', 'text', array(
                'label' => 'Loan Completion URL',
                'attr' => array('class' => 'span5'),
                'required' => false,
            ))
            ->add('prequal_complete_url', 'text', array(
                'label' => 'Prequal Completion URL',
                'attr' => array('class' => 'span5'),
                'required' => false,
            ))
    		->add('loan_officer', 'entity', array(
            	'label' => 'Loan Officer',
            	'class' => 'Sudoux\MortgageBundle\Entity\LoanOfficer',
            	'property' => 'fullName',
            	'empty_value' => 'Select an Officer',
            	'query_builder' => function(EntityRepository $er) use ($site) {
            		return $er->findAllByParentSiteQuery($site);
            	},
    		))
    		->add('branch', 'entity', array(
            	'label' => 'Branch',
            	'class' => 'Sudoux\MortgageBundle\Entity\Branch',
            	'property' => 'name',
            	'empty_value' => 'Select a Branch',
            	'query_builder' => function(EntityRepository $er) use ($site) {
            		return $er->findAllBySiteQuery($site);
            	},
    		))
            ->add('member_portal_enabled', 'checkbox', array(
                'label' => 'Member Portal Enabled',
                'required' => false,
            ))
            ->add('member_portal_documents_enabled', 'checkbox', array(
                'label' => 'Member Portal Documents Enabled',
                'required' => false,
            ))
            ->add('state_license', 'entity', array(
                'label' => 'State Licenses',
                'class' => 'Sudoux\Cms\LocationBundle\Entity\State',
                'property' => 'name',
                'multiple' => true,
                'expanded' => true,
            ))
            ->add('auto_create_loan_officer_user', 'checkbox', array(
                'label' => 'Auto Create Loan Officer User',
                'required' => false,
            ))
        ;

    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    	$resolver->setDefaults(array(
            'data_class' => 'Sudoux\Cms\SiteBundle\Entity\Settings',
            'validation_groups' => array('general', 'website', 'theme_settings', 'wizard_settings', 'wizard_billing', 'mortgage'),
            'cascade_validation' => true,
        ));
    }

    public function getName()
    {
        return 'sudocms_sitebundle_settingstype';
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.ja.markdown.modeller.sc.java.model;

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

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

@Data
@EqualsAndHashCode(callSuper = true, doNotUseGetters = true)
@ToString(callSuper = true, doNotUseGetters = true)
public class JavaMethodParameter extends JavaBase {

	private final String name;

	private final JavaClass type;

	private List<JavaAnnotation> annotations = new ArrayList<>();

	public void add(final JavaAnnotation annotation) {
		annotations.add(annotation);
	}
}


text:
package io.github.skepter.skepbot.modules;

import java.io.IOException;
import java.util.concurrent.ThreadLocalRandom;

import io.github.skepter.skepbot.WebsiteGetters;

public class DadJoke extends Module {

	public DadJoke() {
		super("tell you a dad joke", PatternType.MATCHES, ".*tell me.*dad joke.*");
	}

	@Override
	public String output() {
		if (ThreadLocalRandom.current().nextInt(0, 1000000) == 0) {
			return username + " just activated the special 1 in a million joke! If you don't know SQL, just put NoSQL on your resume!";
		}
		try {
			return WebsiteGetters.getDadJoke();
		} catch (IOException e) {
			return "I tried to think up a dad joke, but I couldn't think of anything.";
		}
	}

}


text:
<!doctype html>
<html style="height: 100%" lang="en">
<head>
  <meta charset="utf-8">
  <title>AngularCliWidgets</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet"
        href="https://unpkg.com/bootstrap@3.3.7/dist/css/bootstrap.min.css">
  <link rel="stylesheet"
        href="https://unpkg.com/@angular/material@2.0.0-beta.3/prebuilt-themes/indigo-pink.css">
</head>
<body style="height: 100%">
  <div class="container">
    <app-root>Loading...</app-root>
  </div>
</body>
</html>


text:
using System;
using System.Collections.Concurrent;
using System.Threading;
using TheCodeKing.Utils.Contract;
using XDMessaging.Transport.Amazon.Interfaces;

namespace XDMessaging.Transport.Amazon
{
    public class ResourceCounter : IResourceCounter
    {
        private static readonly ConcurrentDictionary<string, Semaphore> localTracker =
            new ConcurrentDictionary<string, Semaphore>(StringComparer.InvariantCultureIgnoreCase);

        #region IResourceCounter Members

        public int Decrement(string name)
        {
            Validate.That(name).IsNotNullOrEmpty();

            Semaphore semaphore;
            if (localTracker.TryGetValue(name, out semaphore))
            {
                try
                {
                    var count = (int.MaxValue - semaphore.Release(1)) - 1;
                    return (count < 0) ? 0 : count;
                }
                catch (SemaphoreFullException)
                {
                    return 0;
                }
            }
            semaphore = GetSemaphore(name);
            return GetCurrentCount(semaphore);
        }

        public void Increment(string name)
        {
            Validate.That(name).IsNotNullOrEmpty();

            var semaphore = localTracker.GetOrAdd(name, key => GetSemaphore(name));
            semaphore.WaitOne();
        }

        #endregion

        private static int GetCurrentCount(Semaphore semaphore)
        {
            semaphore.WaitOne();
            var count = (int.MaxValue - semaphore.Release(1)) - 1;
            return (count < 0) ? 0 : count;
        }

        private static Semaphore GetSemaphore(string name)
        {
            name = name.ToLowerInvariant();
            try
            {
                return Semaphore.OpenExisting(name);
            }
            catch (WaitHandleCannotBeOpenedException)
            {
                return new Semaphore(int.MaxValue, int.MaxValue, name);
            }
        }
    }
}


text:
package adsc

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net"
	"strings"
	"sync"
	"time"

	cluster "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3"
	endpoint "github.com/envoyproxy/go-control-plane/envoy/config/endpoint/v3"
	listener "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3"
	route "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"

	"istio.io/istio/pilot/pkg/networking/util"
	v2 "istio.io/istio/pilot/pkg/proxy/envoy/v2"

	xdsapi "github.com/envoyproxy/go-control-plane/envoy/api/v2"
	core "github.com/envoyproxy/go-control-plane/envoy/api/v2/core"
	ads "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v2"
	"github.com/envoyproxy/go-control-plane/pkg/conversion"
	"github.com/gogo/protobuf/types"
	"github.com/golang/protobuf/jsonpb"
	"github.com/golang/protobuf/proto"
	pstruct "github.com/golang/protobuf/ptypes/struct"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"

	mcp "istio.io/api/mcp/v1alpha1"
	"istio.io/api/mesh/v1alpha1"
	"istio.io/pkg/log"

	"istio.io/istio/pilot/pkg/model"
	"istio.io/istio/pkg/config/schema/collections"
)

// Config for the ADS connection.
type Config struct {
	// Namespace defaults to 'default'
	Namespace string

	// Workload defaults to 'test'
	Workload string

	// Meta includes additional metadata for the node
	Meta *pstruct.Struct

	// NodeType defaults to sidecar. "ingress" and "router" are also supported.
	NodeType string

	// IP is currently the primary key used to locate inbound configs. It is sent by client,
	// must match a known endpoint IP. Tests can use a ServiceEntry to register fake IPs.
	IP string
}

// ADSC implements a basic client for ADS, for use in stress tests and tools
// or libraries that need to connect to Istio pilot or other ADS servers.
type ADSC struct {
	// Stream is the GRPC connection stream, allowing direct GRPC send operations.
	// Set after Dial is called.
	stream ads.AggregatedDiscoveryService_StreamAggregatedResourcesClient

	conn *grpc.ClientConn

	// NodeID is the node identity sent to Pilot.
	nodeID string

	certDir string
	url     string

	watchTime time.Time

	// InitialLoad tracks the time to receive the initial configuration.
	InitialLoad time.Duration

	// httpListeners contains received listeners with a http_connection_manager filter.
	httpListeners map[string]*listener.Listener

	// tcpListeners contains all listeners of type TCP (not-HTTP)
	tcpListeners map[string]*listener.Listener

	// All received clusters of type eds, keyed by name
	edsClusters map[string]*cluster.Cluster

	// All received clusters of no-eds type, keyed by name
	clusters map[string]*cluster.Cluster

	// All received routes, keyed by route name
	routes map[string]*route.RouteConfiguration

	// All received endpoints, keyed by cluster name
	eds map[string]*endpoint.ClusterLoadAssignment

	// Metadata has the node metadata to send to pilot.
	// If nil, the defaults will be used.
	Metadata *pstruct.Struct

	// Updates includes the type of the last update received from the server.
	Updates     chan string
	XDSUpdates  chan *xdsapi.DiscoveryResponse
	VersionInfo map[string]string

	// Last received message, by type
	Received map[string]*xdsapi.DiscoveryResponse

	mutex sync.Mutex

	Mesh *v1alpha1.MeshConfig

	// Retrieved configurations can be stored using the common istio model interface.
	Store model.IstioConfigStore

	// Retrieved endpoints can be stored in the memory registry. This is used for CDS and EDS responses.
	Registry *v2.MemServiceDiscovery

	// LocalCacheDir is set to a base name used to save fetched resources.
	// If set, each update will be saved.
	// TODO: also load at startup - so we can support warm up in init-container, and survive
	// restarts.
	LocalCacheDir string
}

const (
	typePrefix = "type.googleapis.com/envoy.api.v2."

	// ListenerType is sent after clusters and endpoints.
	ListenerType = typePrefix + "Listener"
	// RouteType is sent after listeners.
	routeType = typePrefix + "RouteConfiguration"
)

var (
	adscLog = log.RegisterScope("adsc", "adsc debugging", 0)
)

// Dial connects to a ADS server, with optional MTLS authentication if a cert dir is specified.
func Dial(url string, certDir string, opts *Config) (*ADSC, error) {
	adsc := &ADSC{
		Updates:     make(chan string, 100),
		XDSUpdates:  make(chan *xdsapi.DiscoveryResponse, 100),
		VersionInfo: map[string]string{},
		certDir:     certDir,
		url:         url,
		Received:    map[string]*xdsapi.DiscoveryResponse{},
	}
	if opts.Namespace == "" {
		opts.Namespace = "default"
	}
	if opts.NodeType == "" {
		opts.NodeType = "sidecar"
	}
	if opts.IP == "" {
		opts.IP = getPrivateIPIfAvailable().String()
	}
	if opts.Workload == "" {
		opts.Workload = "test-1"
	}
	adsc.Metadata = opts.Meta

	adsc.nodeID = fmt.Sprintf("%s~%s~%s.%s~%s.svc.cluster.local", opts.NodeType, opts.IP,
		opts.Workload, opts.Namespace, opts.Namespace)

	err := adsc.Run()
	return adsc, err
}

// Returns a private IP address, or unspecified IP (0.0.0.0) if no IP is available
func getPrivateIPIfAvailable() net.IP {
	addrs, _ := net.InterfaceAddrs()
	for _, addr := range addrs {
		var ip net.IP
		switch v := addr.(type) {
		case *net.IPNet:
			ip = v.IP
		case *net.IPAddr:
			ip = v.IP
		default:
			continue
		}
		if !ip.IsLoopback() {
			return ip
		}
	}
	return net.IPv4zero
}

func tlsConfig(certDir string) (*tls.Config, error) {
	clientCert, err := tls.LoadX509KeyPair(certDir+"/cert-chain.pem",
		certDir+"/key.pem")
	if err != nil {
		return nil, err
	}

	serverCABytes, err := ioutil.ReadFile(certDir + "/root-cert.pem")
	if err != nil {
		return nil, err
	}
	serverCAs := x509.NewCertPool()
	if ok := serverCAs.AppendCertsFromPEM(serverCABytes); !ok {
		return nil, err
	}

	return &tls.Config{
		Certificates: []tls.Certificate{clientCert},
		RootCAs:      serverCAs,
		ServerName:   "istio-pilot.istio-system",
		VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
			return nil
		},
	}, nil
}

// Close the stream.
func (a *ADSC) Close() {
	a.mutex.Lock()
	a.conn.Close()
	a.mutex.Unlock()
}

// Run will run the ADS client.
func (a *ADSC) Run() error {

	// TODO: pass version info, nonce properly
	var err error
	if len(a.certDir) > 0 {
		tlsCfg, err := tlsConfig(a.certDir)
		if err != nil {
			return err
		}
		creds := credentials.NewTLS(tlsCfg)

		opts := []grpc.DialOption{
			// Verify Pilot cert and service account
			grpc.WithTransportCredentials(creds),
		}
		a.conn, err = grpc.Dial(a.url, opts...)
		if err != nil {
			return err
		}
	} else {
		a.conn, err = grpc.Dial(a.url, grpc.WithInsecure())
		if err != nil {
			return err
		}
	}

	xds := ads.NewAggregatedDiscoveryServiceClient(a.conn)
	edsstr, err := xds.StreamAggregatedResources(context.Background())
	if err != nil {
		return err
	}
	a.stream = edsstr
	go a.handleRecv()
	return nil
}

func (a *ADSC) handleRecv() {
	for {
		var err error
		msg, err := a.stream.Recv()
		if err != nil {
			adscLog.Infof("Connection closed for node %v with err: %v", a.nodeID, err)
			a.Close()
			a.WaitClear()
			a.Updates <- ""
			a.XDSUpdates <- nil
			return
		}

		// Group-value-kind - used for high level api generator.
		gvk := strings.SplitN(msg.TypeUrl, "/", 3)

		if msg.TypeUrl == collections.IstioMeshV1Alpha1MeshConfig.Resource().GroupVersionKind().String() &&
			len(msg.Resources) > 0 {
			rsc := msg.Resources[0]
			m := &v1alpha1.MeshConfig{}
			err = proto.Unmarshal(rsc.Value, m)
			if err != nil {
				log.Warna("Failed to unmarshal mesh config", err)
			}
			a.Mesh = m
			if a.LocalCacheDir != "" {
				strResponse, err := json.MarshalIndent(m, "  ", "  ")
				if err != nil {
					continue
				}
				err = ioutil.WriteFile(a.LocalCacheDir+"_mesh.json", strResponse, 0644)
				if err != nil {
					continue
				}
			}
			continue
		}

		listeners := []*listener.Listener{}
		clusters := []*cluster.Cluster{}
		routes := []*route.RouteConfiguration{}
		eds := []*endpoint.ClusterLoadAssignment{}
		for _, rsc := range msg.Resources { // Any
			a.VersionInfo[rsc.TypeUrl] = msg.VersionInfo
			valBytes := rsc.Value
			switch rsc.TypeUrl {
			case v2.ListenerType:
				{
					ll := &listener.Listener{}
					_ = proto.Unmarshal(valBytes, ll)
					listeners = append(listeners, ll)
				}

			case v2.ClusterTypeV3:
				{
					cl := &cluster.Cluster{}
					_ = proto.Unmarshal(valBytes, cl)
					clusters = append(clusters, cl)
				}

			case v2.EndpointTypeV3:
				{
					el := &endpoint.ClusterLoadAssignment{}
					_ = proto.Unmarshal(valBytes, el)
					eds = append(eds, el)
				}

			case v2.RouteType:
				{
					rl := &route.RouteConfiguration{}
					_ = proto.Unmarshal(valBytes, rl)
					routes = append(routes, rl)
				}

			default:
				if len(gvk) != 3 {
					continue
				}
				// Generic - fill up the store
				if a.Store != nil {
					m := &mcp.Resource{}
					err = types.UnmarshalAny(&types.Any{
						TypeUrl: rsc.TypeUrl,
						Value:   rsc.Value,
					}, m)
					if err != nil {
						continue
					}
					val, err := mcpToPilot(m)
					if err != nil {
						continue
					}
					val.Group = gvk[0]
					val.Version = gvk[1]
					val.Type = gvk[2]
					if err != nil {
						adscLog.Warna("Invalid data ", err, " ", string(valBytes))
					} else {
						cfg := a.Store.Get(val.GroupVersionKind(), val.Name, val.Namespace)
						if cfg == nil {
							_, err = a.Store.Create(*val)
							if err != nil {
								continue
							}
						} else {
							_, err = a.Store.Update(*val)
							if err != nil {
								continue
							}
						}
					}
					if a.LocalCacheDir != "" {
						strResponse, err := json.MarshalIndent(val, "  ", "  ")
						if err != nil {
							continue
						}
						err = ioutil.WriteFile(a.LocalCacheDir+"_res."+
							val.Type+"."+val.Namespace+"."+val.Name+".json", strResponse, 0644)
						if err != nil {
							continue
						}
					}
				}
			}
		}

		// If we got no resource - still save to the store with empty name/namespace, to notify sync
		// This scheme also allows us to chunk large responses !

		a.mutex.Lock()
		a.Received[msg.TypeUrl] = msg
		// TODO: add hook to inject nacks
		a.ack(msg)
		a.mutex.Unlock()

		if len(listeners) > 0 {
			a.handleLDS(listeners)
		}
		if len(clusters) > 0 {
			a.handleCDS(clusters)
		}
		if len(eds) > 0 {
			a.handleEDS(eds)
		}
		if len(routes) > 0 {
			a.handleRDS(routes)
		}
		select {
		case a.XDSUpdates <- msg:
		default:
		}
	}

}

func mcpToPilot(m *mcp.Resource) (*model.Config, error) {
	if m == nil || m.Metadata == nil {
		return &model.Config{}, nil
	}
	c := &model.Config{
		ConfigMeta: model.ConfigMeta{
			ResourceVersion: m.Metadata.Version,
			Labels:          m.Metadata.Labels,
			Annotations:     m.Metadata.Annotations,
		},
	}
	nsn := strings.Split(m.Metadata.Name, "/")
	if len(nsn) != 2 {
		return nil, fmt.Errorf("invalid name %s", m.Metadata.Name)
	}
	c.Namespace = nsn[0]
	c.Name = nsn[1]
	var err error
	c.CreationTimestamp, err = types.TimestampFromProto(m.Metadata.CreateTime)
	if err != nil {
		return nil, err
	}

	pb, err := types.EmptyAny(m.Body)
	if err != nil {
		return nil, err
	}
	err = types.UnmarshalAny(m.Body, pb)
	if err != nil {
		return nil, err
	}
	c.Spec = pb
	return c, nil
}

// nolint: staticcheck
func (a *ADSC) handleLDS(ll []*listener.Listener) {
	lh := map[string]*listener.Listener{}
	lt := map[string]*listener.Listener{}

	routes := []string{}
	ldsSize := 0

	for _, l := range ll {
		ldsSize += proto.Size(l)

		// The last filter is the actual destination for inbound listener
		if l.ApiListener != nil {
			// This is an API Listener
			// TODO: extract VIP and RDS or cluster
			continue
		}
		filter := l.FilterChains[len(l.FilterChains)-1].Filters[0]

		// The actual destination will be the next to the last if the last filter is a passthrough filter
		if l.FilterChains[len(l.FilterChains)-1].GetName() == util.PassthroughFilterChain {
			filter = l.FilterChains[len(l.FilterChains)-2].Filters[0]
		}

		if filter.Name == "mixer" {
			filter = l.FilterChains[len(l.FilterChains)-1].Filters[1]
		}
		if filter.Name == "envoy.tcp_proxy" {
			lt[l.Name] = l
			config, _ := conversion.MessageToStruct(filter.GetTypedConfig())
			c := config.Fields["cluster"].GetStringValue()
			adscLog.Debugf("TCP: %s -> %s", l.Name, c)
		} else if filter.Name == "envoy.http_connection_manager" {
			lh[l.Name] = l

			// Getting from config is too painful..
			port := l.Address.GetSocketAddress().GetPortValue()
			if port == 15002 {
				routes = append(routes, "http_proxy")
			} else {
				routes = append(routes, fmt.Sprintf("%d", port))
			}
		} else if filter.Name == "envoy.mongo_proxy" {
			// ignore for now
		} else if filter.Name == "envoy.redis_proxy" {
			// ignore for now
		} else if filter.Name == "envoy.filters.network.mysql_proxy" {
			// ignore for now
		} else {
			tm := &jsonpb.Marshaler{Indent: "  "}
			adscLog.Infof(tm.MarshalToString(l))
		}
	}

	adscLog.Infof("LDS: http=%d tcp=%d size=%d", len(lh), len(lt), ldsSize)
	if adscLog.DebugEnabled() {
		b, _ := json.MarshalIndent(ll, " ", " ")
		adscLog.Debugf(string(b))
	}
	a.mutex.Lock()
	defer a.mutex.Unlock()
	if len(routes) > 0 {
		a.sendRsc(routeType, routes)
	}
	a.httpListeners = lh
	a.tcpListeners = lt

	select {
	case a.Updates <- "lds":
	default:
	}
}

// compact representations, for simplified debugging/testing

// TCPListener extracts the core elements from envoy Listener.
type TCPListener struct {
	// Address is the address, as expected by go Dial and Listen, including port
	Address string

	// LogFile is the access log address for the listener
	LogFile string

	// Target is the destination cluster.
	Target string
}

type Target struct {

	// Address is a go address, extracted from the mangled cluster name.
	Address string

	// Endpoints are the resolved endpoints from eds or cluster static.
	Endpoints map[string]Endpoint
}

type Endpoint struct {
	// Weight extracted from eds
	Weight int
}

// Save will save the json configs to files, using the base directory
func (a *ADSC) Save(base string) error {
	a.mutex.Lock()
	defer a.mutex.Unlock()
	strResponse, err := json.MarshalIndent(a.tcpListeners, "  ", "  ")
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(base+"_lds_tcp.json", strResponse, 0644)
	if err != nil {
		return err
	}
	strResponse, err = json.MarshalIndent(a.httpListeners, "  ", "  ")
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(base+"_lds_http.json", strResponse, 0644)
	if err != nil {
		return err
	}
	strResponse, err = json.MarshalIndent(a.routes, "  ", "  ")
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(base+"_rds.json", strResponse, 0644)
	if err != nil {
		return err
	}
	strResponse, err = json.MarshalIndent(a.edsClusters, "  ", "  ")
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(base+"_ecds.json", strResponse, 0644)
	if err != nil {
		return err
	}
	strResponse, err = json.MarshalIndent(a.clusters, "  ", "  ")
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(base+"_cds.json", strResponse, 0644)
	if err != nil {
		return err
	}
	strResponse, err = json.MarshalIndent(a.eds, "  ", "  ")
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(base+"_eds.json", strResponse, 0644)
	if err != nil {
		return err
	}

	return err
}

func (a *ADSC) handleCDS(ll []*cluster.Cluster) {

	cn := []string{}
	cdsSize := 0
	edscds := map[string]*cluster.Cluster{}
	cds := map[string]*cluster.Cluster{}
	for _, c := range ll {
		cdsSize += proto.Size(c)
		switch v := c.ClusterDiscoveryType.(type) {
		case *cluster.Cluster_Type:
			if v.Type != cluster.Cluster_EDS {
				cds[c.Name] = c
				continue
			}
		}
		cn = append(cn, c.Name)
		edscds[c.Name] = c
	}

	adscLog.Infof("CDS: %d size=%d", len(cn), cdsSize)

	if len(cn) > 0 {
		a.sendRsc(v2.EndpointTypeV3, cn)
	}
	if adscLog.DebugEnabled() {
		b, _ := json.MarshalIndent(ll, " ", " ")
		adscLog.Info(string(b))
	}

	a.mutex.Lock()
	defer a.mutex.Unlock()
	a.edsClusters = edscds
	a.clusters = cds

	select {
	case a.Updates <- "cds":
	default:
	}
}

func (a *ADSC) node() *core.Node {
	n := &core.Node{
		Id: a.nodeID,
	}
	if a.Metadata == nil {
		n.Metadata = &pstruct.Struct{
			Fields: map[string]*pstruct.Value{
				"ISTIO_VERSION": {Kind: &pstruct.Value_StringValue{StringValue: "65536.65536.65536"}},
			}}
	} else {
		n.Metadata = a.Metadata
	}
	return n
}

func (a *ADSC) Send(req *xdsapi.DiscoveryRequest) error {
	req.Node = a.node()
	req.ResponseNonce = time.Now().String()
	return a.stream.Send(req)
}

func (a *ADSC) handleEDS(eds []*endpoint.ClusterLoadAssignment) {
	la := map[string]*endpoint.ClusterLoadAssignment{}
	edsSize := 0
	ep := 0
	for _, cla := range eds {
		edsSize += proto.Size(cla)
		la[cla.ClusterName] = cla
		ep += len(cla.Endpoints)
	}

	adscLog.Infof("eds: %d size=%d ep=%d", len(eds), edsSize, ep)
	if adscLog.DebugEnabled() {
		b, _ := json.MarshalIndent(eds, " ", " ")
		adscLog.Info(string(b))
	}
	if a.InitialLoad == 0 {
		// first load - Envoy loads listeners after endpoints
		_ = a.stream.Send(&xdsapi.DiscoveryRequest{
			ResponseNonce: time.Now().String(),
			Node:          a.node(),
			TypeUrl:       ListenerType,
		})
	}

	a.mutex.Lock()
	defer a.mutex.Unlock()
	a.eds = la

	select {
	case a.Updates <- "eds":
	default:
	}
}

func (a *ADSC) handleRDS(configurations []*route.RouteConfiguration) {

	vh := 0
	rcount := 0
	size := 0

	rds := map[string]*route.RouteConfiguration{}

	for _, r := range configurations {
		for _, h := range r.VirtualHosts {
			vh++
			for _, rt := range h.Routes {
				rcount++
				// Example: match:<prefix:"/" > route:<cluster:"outbound|9154||load-se-154.local" ...
				adscLog.Debugf("Handle route %v, path %v, cluster %v", h.Name, rt.Match.PathSpecifier, rt.GetRoute().GetCluster())
			}
		}
		rds[r.Name] = r
		size += proto.Size(r)
	}
	if a.InitialLoad == 0 {
		a.InitialLoad = time.Since(a.watchTime)
		adscLog.Infof("RDS: %d size=%d vhosts=%d routes=%d time=%d", len(configurations), size, vh, rcount, a.InitialLoad)
	} else {
		adscLog.Infof("RDS: %d size=%d vhosts=%d routes=%d", len(configurations), size, vh, rcount)
	}

	if adscLog.DebugEnabled() {
		b, _ := json.MarshalIndent(configurations, " ", " ")
		adscLog.Info(string(b))
	}

	a.mutex.Lock()
	a.routes = rds
	a.mutex.Unlock()

	select {
	case a.Updates <- "rds":
	default:
	}

}

// WaitClear will clear the waiting events, so next call to Wait will get
// the next push type.
func (a *ADSC) WaitClear() {
	for {
		select {
		case <-a.Updates:
		default:
			return
		}
	}
}

// Wait for an updates for all the specified types
// If updates is empty, this will wait for any update
func (a *ADSC) Wait(to time.Duration, updates ...string) ([]string, error) {
	t := time.NewTimer(to)
	want := map[string]struct{}{}
	for _, update := range updates {
		want[update] = struct{}{}
	}
	got := make([]string, 0, len(updates))
	for {
		select {
		case t := <-a.Updates:
			delete(want, t)
			got = append(got, t)
			if len(want) == 0 {
				return got, nil
			}
		case <-t.C:
			return got, fmt.Errorf("timeout, still waiting for updates: %v", want)
		}
	}
}

// WaitVersion waits for a new or updated for a typeURL.
func (a *ADSC) WaitVersion(to time.Duration, typeURL, lastVersion string) (*xdsapi.DiscoveryResponse, error) {
	t := time.NewTimer(to)
	a.mutex.Lock()
	ex := a.Received[typeURL]
	a.mutex.Unlock()
	if ex != nil {
		if lastVersion == "" {
			return ex, nil
		}
		if lastVersion != ex.VersionInfo {
			return ex, nil
		}
	}

	for {
		select {
		case t := <-a.XDSUpdates:
			if t == nil {
				return nil, fmt.Errorf("closed")
			}
			if t.TypeUrl == typeURL {
				return t, nil
			}

		case <-t.C:
			return nil, fmt.Errorf("timeout, still waiting for updates: %v", typeURL)
		}
	}
}

// EndpointsJSON returns the endpoints, formatted as JSON, for debugging.
func (a *ADSC) EndpointsJSON() string {
	a.mutex.Lock()
	defer a.mutex.Unlock()
	out, _ := json.MarshalIndent(a.eds, " ", " ")
	return string(out)
}

// Watch will start watching resources, starting with LDS. Based on the LDS response
// it will start watching RDS and CDS.
func (a *ADSC) Watch() {
	a.watchTime = time.Now()
	_ = a.stream.Send(&xdsapi.DiscoveryRequest{
		ResponseNonce: time.Now().String(),
		Node:          a.node(),
		TypeUrl:       v2.ClusterTypeV3,
	})
}

// WatchConfig will use the new experimental API watching, similar with MCP.
func (a *ADSC) WatchConfig() {
	_ = a.stream.Send(&xdsapi.DiscoveryRequest{
		ResponseNonce: time.Now().String(),
		Node:          a.node(),
		TypeUrl:       collections.IstioMeshV1Alpha1MeshConfig.Resource().GroupVersionKind().String(),
	})

	for _, sch := range collections.Pilot.All() {
		_ = a.stream.Send(&xdsapi.DiscoveryRequest{
			ResponseNonce: time.Now().String(),
			Node:          a.node(),
			TypeUrl:       sch.Resource().GroupVersionKind().String(),
		})
	}
}

func (a *ADSC) sendRsc(typeurl string, rsc []string) {
	_ = a.stream.Send(&xdsapi.DiscoveryRequest{
		ResponseNonce: "",
		Node:          a.node(),
		TypeUrl:       typeurl,
		ResourceNames: rsc,
	})
}

func (a *ADSC) ack(msg *xdsapi.DiscoveryResponse) {
	_ = a.stream.Send(&xdsapi.DiscoveryRequest{
		ResponseNonce: msg.Nonce,
		TypeUrl:       msg.TypeUrl,
		Node:          a.node(),
		VersionInfo:   msg.VersionInfo,
	})
}

// GetHTTPListeners returns all the http listeners.
func (a *ADSC) GetHTTPListeners() map[string]*listener.Listener {
	a.mutex.Lock()
	defer a.mutex.Unlock()
	return a.httpListeners
}

// GetTCPListeners returns all the tcp listeners.
func (a *ADSC) GetTCPListeners() map[string]*listener.Listener {
	a.mutex.Lock()
	defer a.mutex.Unlock()
	return a.tcpListeners
}

// GetEdsClusters returns all the eds type clusters.
func (a *ADSC) GetEdsClusters() map[string]*cluster.Cluster {
	a.mutex.Lock()
	defer a.mutex.Unlock()
	return a.edsClusters
}

// GetClusters returns all the non-eds type clusters.
func (a *ADSC) GetClusters() map[string]*cluster.Cluster {
	a.mutex.Lock()
	defer a.mutex.Unlock()
	return a.clusters
}

// GetRoutes returns all the routes.
func (a *ADSC) GetRoutes() map[string]*route.RouteConfiguration {
	a.mutex.Lock()
	defer a.mutex.Unlock()
	return a.routes
}

// GetEndpoints returns all the routes.
func (a *ADSC) GetEndpoints() map[string]*endpoint.ClusterLoadAssignment {
	a.mutex.Lock()
	defer a.mutex.Unlock()
	return a.eds
}


text:
import vtk

def main():
    colors = vtk.vtkNamedColors()

    filename = get_program_parameters()

    # Create the reader for the data.
    print("Loading ", filename)
    reader = vtk.vtkUnstructuredGridReader()
    reader.SetFileName(filename)
    reader.Update()

    extractEdges = vtk.vtkExtractEdges()
    extractEdges.SetInputConnection(reader.GetOutputPort())

    legendValues = vtk.vtkVariantArray()
    it = reader.GetOutput().NewCellIterator()
    it.InitTraversal()
    while not it.IsDoneWithTraversal():
        cell = vtk.vtkGenericCell()
        it.GetCell(cell)
        cellName = vtk.vtkCellTypes.GetClassNameFromTypeId(cell.GetCellType())
        print(cellName, "NumberOfPoints:", cell.GetNumberOfPoints(), "CellDimension:", cell.GetCellDimension())
        legendValues.InsertNextValue(cellName)
        it.GoToNextCell()

    # Tube the edges
    tubes = vtk.vtkTubeFilter()
    tubes.SetInputConnection(extractEdges.GetOutputPort())
    tubes.SetRadius(.05)
    tubes.SetNumberOfSides(21)

    edgeMapper = vtk.vtkPolyDataMapper()
    edgeMapper.SetInputConnection(tubes.GetOutputPort())
    edgeMapper.SetScalarRange(0, 26)

    edgeActor = vtk.vtkActor()
    edgeActor.SetMapper(edgeMapper)
    edgeActor.GetProperty().SetSpecular(.6)
    edgeActor.GetProperty().SetSpecularPower(30)

    # Glyph the points
    sphere = vtk.vtkSphereSource()
    sphere.SetPhiResolution(21)
    sphere.SetThetaResolution(21)
    sphere.SetRadius(.08)

    pointMapper = vtk.vtkGlyph3DMapper()
    pointMapper.SetInputConnection(reader.GetOutputPort())
    pointMapper.SetSourceConnection(sphere.GetOutputPort())
    pointMapper.ScalingOff()
    pointMapper.ScalarVisibilityOff()

    pointActor = vtk.vtkActor()
    pointActor.SetMapper(pointMapper)
    pointActor.GetProperty().SetDiffuseColor(colors.GetColor3d("Banana"))
    pointActor.GetProperty().SetSpecular(.6)
    pointActor.GetProperty().SetSpecularColor(1.0, 1.0, 1.0)
    pointActor.GetProperty().SetSpecularPower(100)

    # Label the points
    labelMapper = vtk.vtkLabeledDataMapper()
    labelMapper.SetInputConnection(reader.GetOutputPort())
    labelActor = vtk.vtkActor2D()
    labelActor.SetMapper(labelMapper)

    # The geometry
    geometryShrink = vtk.vtkShrinkFilter()
    geometryShrink.SetInputConnection(reader.GetOutputPort())
    geometryShrink.SetShrinkFactor(.8)

    # NOTE: We must copy the originalLut because the CategoricalLegend
    # needs an indexed lookup table, but the geometryMapper uses a
    # non-index lookup table
    categoricalLut = vtk.vtkLookupTable()
    originalLut = reader.GetOutput().GetCellData().GetScalars().GetLookupTable()

    categoricalLut.DeepCopy(originalLut)
    categoricalLut.IndexedLookupOn()

    geometryMapper = vtk.vtkDataSetMapper()
    geometryMapper.SetInputConnection(geometryShrink.GetOutputPort())
    geometryMapper.SetScalarModeToUseCellData()
    geometryMapper.SetScalarRange(0, 11)

    geometryActor = vtk.vtkActor()
    geometryActor.SetMapper(geometryMapper)
    geometryActor.GetProperty().SetLineWidth(3)
    geometryActor.GetProperty().EdgeVisibilityOn()
    geometryActor.GetProperty().SetEdgeColor(0, 0, 0)

    # Legend
    for v in range(0, legendValues.GetNumberOfTuples()):
        categoricalLut.SetAnnotation(legendValues.GetValue(v), legendValues.GetValue(v).ToString())
    legend = vtk.vtkCategoryLegend()
    legend.SetScalarsToColors(categoricalLut)
    legend.SetValues(legendValues)
    legend.SetTitle("Cell Type")
    legend.GetBrush().SetColor(colors.GetColor4ub("Silver"))

    placeLegend = vtk.vtkContextTransform()
    placeLegend.AddItem(legend)
    placeLegend.Translate(640 - 20, 480 - 12 * 16)

    contextView = vtk.vtkContextView()
    contextView.GetScene().AddItem(placeLegend)

    renderer = contextView.GetRenderer()

    renderWindow = contextView.GetRenderWindow()

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(geometryActor)
    renderer.AddActor(labelActor)
    renderer.AddActor(edgeActor)
    renderer.AddActor(pointActor)
    renderer.SetBackground(colors.GetColor3d("SlateGray"))

    aCamera = vtk.vtkCamera()
    aCamera.Azimuth(-40.0)
    aCamera.Elevation(50.0)

    renderer.SetActiveCamera(aCamera)
    renderer.ResetCamera()

    renderWindow.SetSize(640, 480)
    renderWindow.Render()

    renderWindowInteractor.Start()

def get_program_parameters():
    import argparse
    description = 'Display a vtkUnstructuredGrid that contains eleven linear cells.'
    epilogue = '''
    This example also shows how to add a vtkCategoryLegend to a visualization.
   '''
    parser = argparse.ArgumentParser(description=description, epilog=epilogue,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('filename', help='VTKCellTypes.vtk.')
    args = parser.parse_args()
    return args.filename

if __name__ == '__main__':
    main()


text:
namespace Switch {
  /// @brief The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.
  namespace System {
    /// @brief The System::Drawing namespace provides access to GDI+ basic graphics functionality. More advanced functionality is provided in the System::Drawing::Drawing2D, System::Drawing::Imaging, and System::Drawing::Text namespaces.
    namespace Drawing {
      /// @cond
      class Point;
      /// @endcond

      /// @brief Stores an ordered pair of integers, which specify a Height and Width.
      /// @par Library
      /// Switch.System.Drawing
      class system_drawing_export_ Size : public object {
      public:
        /// @brief Gets a Size class that has a Height and Width value of 0. This field is constant.
        static property_<Size, readonly_> Empty;

        /// @brief Initializes a new instance of the Size class that has a Height and Width value of 0.
        Size() = default;

        /// @cond
        Size(const Size& size) : width(size.width), height(size.height) {}
        Size& operator=(const Size&) = default;
        Size operator+(const Size& sz) const;
        Size operator-(const Size& sz) const;
        Size& operator+=(const Size& sz);
        Size& operator-=(const Size& sz);
        bool operator<(const Size& sz) const {return this->height < sz.height || (this->height == sz.height && this->width < sz.width);}
        bool operator>(const Size& sz) const {return this->height > sz.height || (this->height == sz.height && this->width > sz.width);}
        /// @endcond

        /// @brief IInitializes a new instance of the Size class from the specified Point class.
        /// @param point The Point class from which to initialize this Size class
        explicit Size(const Point& point);

        /// @brief Initializes a new instance of the Size class from the specified dimensions.
        /// @param width The width component of the new Size
        /// @param height The height component of the new Size
        Size(int32 width, int32 height) : width(width), height(height) {}

        /// @brief Gets or sets the vertical component of this Size Class.
        /// @return int32 The vertical component of this Size class, typically measured in pixels.
        /// @remarks The unit for the Height and Width of the Size class depend on the PageUnit and PageScale settings for the Graphics object that is used to draw.
        property_<int32> Height {
          get_ {return this->height;},
          set_ {this->height = value;}
        };

        /// @brief Gets or sets the horizontal component of this Size class.
        /// @return int32 The horizontal component of this Size class, typically measured in pixels.
        /// @remarks The unit for the Height and Width of the Size class depend on the PageUnit and PageScale settings for the Graphics object that is used to draw.
        property_<int32> Width {
          get_ {return this->width;},
          set_ {this->width = value;}
        };

        /// @brief Determines whether this instance of Size and a specified object, which must also be a Size object, have the same value.
        /// @param value The Size to compare with the current object.
        /// @return bool true if the specified value is equal to the current object. otherwise, false.
        bool Equals(const Size& value) const;

        /// @brief Determines whether this instance of Size and a specified object, which must also be a Size object, have the same value.
        /// @param obj The object to compare with the current object.
        /// @return bool true if the specified object is equal to the current object. otherwise, false.
        bool Equals(const object& obj) const override;

        /// @brief Tests whether this Size class has width and height of 0.
        /// @return bool Returns true  when this Size class has both a width and height of 0; otherwise, false.
        bool IsEmpty() const;

        /// @brief Creates a human-readable string that represents this Size class.
        /// @return string A string that represents this Size.
        String ToString() const override { return String::Format("{{Width={0}, Height={1}}}", this->width, this->height); }

        /// @brief Adds the width and height of one Size class to the width and height of another Size class.
        /// @param size1 The first Size class to add.
        /// @param size2 The second Size class to add.
        /// @return Size A Size class that is the result of the addition operation.
        static Size Add(const Size& size1, const Size& size2);

        /// @brief Returns the result of subtracting specified Size from the specified Point.
        /// @param sz1 The Size to be subtracted from.
        /// @param sz2 The Size to subtract from the Size.
        /// @return The Size that is the result of the subtraction operation.
        /// @exception ArgumentNullException sz1 or sz2 are null.
        static Size Subtract(const Size& sz1, const Size& sz2);

      private :
        int32 width = 0;
        int32 height = 0;
      };
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<actions>
        <action>
            <actionName>run</actionName>
            <packagings>
                <packaging>jar</packaging>
            </packagings>
            <goals>
                <goal>process-classes</goal>
                <goal>org.codehaus.mojo:exec-maven-plugin:1.2.1:exec</goal>
            </goals>
            <properties>
                <exec.args>-Djava.library.path="C:\Users\tomas\Desktop\Dropbox\prog\lwjgl\lwjgl-asteroides\target\natives" -classpath %classpath newpackage.Main</exec.args>
                <exec.executable>java</exec.executable>
            </properties>
        </action>
        <action>
            <actionName>debug</actionName>
            <packagings>
                <packaging>jar</packaging>
            </packagings>
            <goals>
                <goal>process-classes</goal>
                <goal>org.codehaus.mojo:exec-maven-plugin:1.2.1:exec</goal>
            </goals>
            <properties>
                <exec.args>-Xdebug -Xrunjdwp:transport=dt_socket,server=n,address=${jpda.address} -Djava.library.path="C:\Users\tomas\Desktop\Dropbox\prog\lwjgl\lwjgl-asteroides\target\natives" -classpath %classpath newpackage.Main</exec.args>
                <exec.executable>java</exec.executable>
                <jpda.listen>true</jpda.listen>
            </properties>
        </action>
        <action>
            <actionName>profile</actionName>
            <packagings>
                <packaging>jar</packaging>
            </packagings>
            <goals>
                <goal>process-classes</goal>
                <goal>org.codehaus.mojo:exec-maven-plugin:1.2.1:exec</goal>
            </goals>
            <properties>
                <exec.args>-Djava.library.path="C:\Users\tomas\Desktop\Dropbox\prog\lwjgl\lwjgl-asteroides\target\natives" -classpath %classpath newpackage.Main</exec.args>
                <exec.executable>java</exec.executable>
            </properties>
        </action>
    </actions>


text:
package org.apache.shiro.samples.sprhib.security;

import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.Sha256CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.samples.sprhib.dao.UserDAO;
import org.apache.shiro.samples.sprhib.model.Role;
import org.apache.shiro.samples.sprhib.model.User;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * The Spring/Hibernate sample application's one and only configured Apache Shiro Realm.
 *

 *
Because a Realm is really just a security-specific DAO, we could have just made Hibernate calls directly
 * in the implementation and named it a 'HibernateRealm' or something similar.

 *

 *
But we've decided to make the calls to the database using a UserDAO, since a DAO would be used in other areas
 * of a 'real' application in addition to here. We felt it better to use that same DAO to show code re-use.

 */
@Component
public class SampleRealm extends AuthorizingRealm {

    protected UserDAO userDAO = null;

    public SampleRealm() {
        setName("SampleRealm"); //This name must match the name in the User class's getPrincipals() method
        setCredentialsMatcher(new Sha256CredentialsMatcher());
    }

    @Autowired
    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        User user = userDAO.findUser(token.getUsername());
        if (user != null) {
            return new SimpleAuthenticationInfo(user.getId(), user.getPassword(), getName());
        } else {
            return null;
        }
    }

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Long userId = (Long) principals.fromRealm(getName()).iterator().next();
        User user = userDAO.getUser(userId);
        if (user != null) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            for (Role role : user.getRoles()) {
                info.addRole(role.getName());
                info.addStringPermissions(role.getPermissions());
            }
            return info;
        } else {
            return null;
        }
    }

}


text:
                {{h.display_name}}

                <input type="text"
                       placeholder="Filter {{h.display_name}}"
                       ng-init="filter_key= ''; filter_field = h.field_name"
                       ng-model="filter_key"
                       ng-keyup="filterColumn(filter_key, filter_field)"
                       filter-name="{{h.field_name}}">

                 {{c[h.field_name]}}


text:
Simple plugin which return the list of all images in the device (each local Uri of the images in the media store).

## License

This cordova plugin is developed by Cozy Cloud and distributed under the [MIT](https://github.com/cozy/cordova-images-browser/blob/master/LICENSE.md).

## What is Cozy?

![Cozy Logo](https://raw.github.com/mycozycloud/cozy-setup/gh-pages/assets/images/happycloud.png)

[Cozy](http://cozy.io) is a platform that brings all your web services in the
same private space.  With it, your web apps and your devices can share data
easily, providing you
with a new experience. You can install Cozy on your own hardware where no one
profiles you.

## Community

You can reach the Cozy Community by:

* Chatting with us on IRC #cozycloud on irc.freenode.net
* Posting on our [Forum](https://forum.cozy.io/)
* Posting issues on the [Github repos](https://github.com/cozy/)
* Mentioning us on [Twitter](http://twitter.com/mycozycloud)


text:
package flexiblepower.kisensum.drivers.utility;

import org.flexiblepower.messaging.Port;
import org.flexiblepower.ral.ResourceDriver;

/**
 * The generic {@link UtilityDriver} that uses the {@link UtilityState} and {@link UtilityControlParameters}.
 */
@Port(name = "manager", sends = UtilityState.class, accepts = UtilityControlParameters.class)
public interface UtilityDriver extends ResourceDriver {
}


text:
local o = {}
local SECONDS = 4

o.init = function(dt)
	o.countdown = SECONDS
	o.oldcountdown = o.countdown -1
end

o.update = function(dt)
	o.countdown = o.countdown - dt
	if (o.countdown <= -1)then
		love.setgamestate(1)
		turGame.map.editMode = true;
	end
end

o.draw = function()
	G.setBlendMode("additive")
	G.setFont(FONT_LARGE)
	G.setColor(255, 127, 0, 127)
	local countdown = math.floor(o.countdown+0.5)
	local text = tostring(countdown)
	if countdown <= 0 then
		text = "Go!"
	elseif countdown >= 4 then
		text = ""
	else if countdown >= 1 then
		if (o.oldcountdown == countdown)then
			if countdown == 3 then
				love.sounds.playSound("sounds/super_phaser.mp3")
			end
			love.sounds.playSound("sounds/phaser_2.mp3")
			o.oldcountdown = countdown -1
		end
	end
	end
	local scale = 1-(o.countdown-o.oldcountdown)/2
	G.print(text, W.getWidth() * 0.5, W.getHeight() * 0.5, 0, scale, scale, string.len(text) * 16, 32)
	G.setBlendMode("alpha")
	G.setColor(255, 255, 255)
end

return o


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.anarres.graphviz.builder;

import com.google.common.base.Preconditions;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;

/**
 *
 * @author shevek
 */
public class GraphVizEdge extends GraphVizElement<GraphVizEdge> {

    /* pp */ static final class Key {

        @Nonnull
        private final GraphVizObject.Key sourceKey;
        @Nonnull
        private final GraphVizObject.Key targetKey;
        @CheckForNull
        private final Object edgeId;

        public Key(@Nonnull GraphVizObject.Key sourceKey, @Nonnull GraphVizObject.Key targetKey, @CheckForNull Object edgeId) {
            this.sourceKey = Preconditions.checkNotNull(sourceKey, "Source key was null.");
            this.targetKey = Preconditions.checkNotNull(targetKey, "Target key was null.");
            this.edgeId = edgeId;
        }

        @Nonnull
        public GraphVizObject.Key getSourceKey() {
            return sourceKey;
        }

        @Nonnull
        public GraphVizObject.Key getTargetKey() {
            return targetKey;
        }

        @CheckForNull
        public Object getEdgeId() {
            return edgeId;
        }

        @Override
        public int hashCode() {
            return getSourceKey().hashCode() ^ getTargetKey().hashCode() ^ GraphVizUtils.hashCode(getEdgeId());
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Key k = (Key) obj;
            return getSourceKey().equals(k.getSourceKey())
                    && getTargetKey().equals(k.getTargetKey())
                    && GraphVizUtils.equals(getEdgeId(), k.getEdgeId());
        }
    }
    @Nonnull
    private final Key key;
    @Nonnull
    private final String sourceId;
    @Nonnull
    private final String targetId;
    @CheckForNull
    private String headShape;
    @CheckForNull
    private String headLabel;
    @CheckForNull
    private String tailShape;
    @CheckForNull
    private String tailLabel;
    @CheckForNull
    private String logicalHead;
    @CheckForNull
    private String logicalTail;

    /* pp */ GraphVizEdge(@Nonnull GraphVizGraph graph, @Nonnull Key key, @Nonnull String sourceId, @Nonnull String targetId) {
        super(graph);
        this.key = key;
        this.sourceId = sourceId;
        this.targetId = targetId;
    }

    @Nonnull
    /* pp */ Key getKey() {
        return key;
    }

    @Nonnull
    /* pp */ String getSourceId() {
        return sourceId;
    }

    @Nonnull
    /* pp */ String getTargetId() {
        return targetId;
    }

    @CheckForNull
    public String getHeadShape() {
        return headShape;
    }

    @Nonnull
    public GraphVizEdge headShape(@CheckForNull String headShape) {
        this.headShape = headShape;
        return this;
    }

    @CheckForNull
    public String getHeadLabel() {
        return headLabel;
    }

    @Nonnull
    public GraphVizEdge headLabel(@CheckForNull String headLabel) {
        this.headLabel = headLabel;
        return this;
    }

    @CheckForNull
    public String getTailShape() {
        return tailShape;
    }

    @Nonnull
    public GraphVizEdge tailShape(@CheckForNull String tailShape) {
        this.tailShape = tailShape;
        return this;
    }

    @CheckForNull
    public String getTailLabel() {
        return tailLabel;
    }

    @Nonnull
    public GraphVizEdge tailLabel(@CheckForNull String tailLabel) {
        this.tailLabel = tailLabel;
        return this;
    }

    public String getLogicalHead() {
        return logicalHead;
    }

    @Nonnull
    public GraphVizEdge logicalHead(@CheckForNull String logicalHead) {
        this.logicalHead = logicalHead;
        return this;
    }

    public String getLogicalTail() {
        return logicalTail;
    }

    @Nonnull
    public GraphVizEdge logicalTail(@CheckForNull String logicalTail) {
        this.logicalTail = logicalTail;
        return this;
    }

    @Nonnull
    public GraphVizEdge constraint(boolean value) {
        return attr(GraphVizAttribute.constraint, Boolean.toString(value));
    }
}


text:
<archetype-descriptor xmlns="http://maven.apache.org/plugins/maven-archetype-plugin/archetype-descriptor/1.0.0"
                      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                      xsi:schemaLocation="http://maven.apache.org/plugins/maven-archetype-plugin/archetype-descriptor/1.0.0 http://maven.apache.org/xsd/archetype-descriptor-1.0.0.xsd"
                      name="xenon-quickstart">
    <requiredProperties>
        <requiredProperty key="xenonVersion">
            <defaultValue>${project.version}</defaultValue>
        </requiredProperty>
    </requiredProperties>
    <fileSets>
        <fileSet filtered="true" packaged="true">
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.java</include>
            </includes>
        </fileSet>
        <fileSet filtered="true" packaged="true">
            <directory>src/test/java</directory>
            <includes>
                <include>**/*.java</include>
            </includes>
        </fileSet>

        <fileSet filtered="false" packaged="false">
            <directory></directory>
            <includes>
                <include>**/*</include>
                <include>*</include>
            </includes>
            <excludes>
                <exclude>src/main/java/**</exclude>
                <exclude>src/test/java/**</exclude>
                <exclude>pom.xml</exclude>
                <exclude>**.sh</exclude>
            </excludes>
        </fileSet>
    </fileSets>
</archetype-descriptor>


text:
<?php
namespace Guywithnose\ReleaseNotes\Tests\Change;

use Guywithnose\ReleaseNotes\Change\Change;
use Guywithnose\ReleaseNotes\Change\ChangeFactory;
use Guywithnose\ReleaseNotes\Type\Type;
use Guywithnose\ReleaseNotes\Type\TypeManager;
use PHPUnit\Framework\TestCase;

class ChangeFactoryTest extends TestCase
{
    /**
     * @var array
     */
    private $_commit;

    public function testCreateFromCommit()
    {
        $commit = $this->getCommit();
        $typeManager = TypeManager::getSemanticTypeManager();
        $expectedChange = new Change($commit['commit']['message'], $typeManager->getDefaultType());
        $changeFactory = new ChangeFactory($typeManager);
        $actualChange = $changeFactory->createFromCommit($commit);
        $this->assertEquals($expectedChange, $actualChange);
    }

    protected function setUp()
    {
        $commitJson = file_get_contents('tests/data/commit.json');
        $this->_commit = json_decode($commitJson, true);
    }

    /**
     * @return array
     */
    private function getCommit()
    {
        return $this->_commit;
    }
}


text:
// flow-typed signature: 20d46c927ad527c76cd1fb84db57cc4f
// flow-typed version: <<STUB>>/normalize.css_v^8.0.0/flow_v0.76.0

/**
 * This is an autogenerated libdef stub for:
 *
 *   'normalize.css'
 *
 * Fill this stub out by replacing all the `any` types.
 *
 * Once filled out, we encourage you to share your work with the
 * community by sending a pull request to:
 * https://github.com/flowtype/flow-typed
 */

declare module 'normalize.css' {
  declare module.exports: any;
}