text:
<?php

define('OOPS_DB_FEATURELANG_ID_FEATURE', _DB_PREFIX_ . 'feature_lang.ID_FEATURE');
define('OOPS_DB_FEATURELANG_ID_LANG', _DB_PREFIX_ . 'feature_lang.ID_LANG');
define('OOPS_DB_FEATURELANG_NAME', _DB_PREFIX_ . 'feature_lang.NAME');
define('OOPS_DB_FEATURELANG_TABLE_NAME', _DB_PREFIX_ . 'feature_lang');

/**
 * Base static class for performing query and update operations on the 'feature_lang' table.
 *
 *
 *
 * @package    propel.generator.prestashop.om
 */
abstract class Oops_Db_Propel_FeatureLangPeer {

	/** the default database name for this class */
	const DATABASE_NAME = 'prestashop';

	/** the table name for this class */
	const TABLE_NAME = OOPS_DB_FEATURELANG_TABLE_NAME;

	/** the related Propel class for this table */
	const OM_CLASS = 'Oops_Db_FeatureLang';

	/** A class that can be returned by this peer. */
	const CLASS_DEFAULT = 'prestashop.Oops_Db_FeatureLang';

	/** the related TableMap class for this table */
	const TM_CLASS = 'Oops_Db_FeatureLangTableMap';

	/** The total number of columns. */
	const NUM_COLUMNS = 3;

	/** The number of lazy-loaded columns. */
	const NUM_LAZY_LOAD_COLUMNS = 0;

	/** The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */
	const NUM_HYDRATE_COLUMNS = 3;

	/** the column name for the ID_FEATURE field */
	const ID_FEATURE = OOPS_DB_FEATURELANG_ID_FEATURE;

	/** the column name for the ID_LANG field */
	const ID_LANG = OOPS_DB_FEATURELANG_ID_LANG;

	/** the column name for the NAME field */
	const NAME = OOPS_DB_FEATURELANG_NAME;

	/** The default string format for model objects of the related table **/
	const DEFAULT_STRING_FORMAT = 'YAML';

	/**
	 * An identiy map to hold any loaded instances of Oops_Db_FeatureLang objects.
	 * This must be public so that other peer classes can access this when hydrating from JOIN
	 * queries.
	 * @var        array Oops_Db_FeatureLang[]
	 */
	public static $instances = array();

	/**
	 * holds an array of fieldnames
	 *
	 * first dimension keys are the type constants
	 * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
	 */
	protected static $fieldNames = array (
		BasePeer::TYPE_PHPNAME => array ('IdFeature', 'IdLang', 'Name', ),
		BasePeer::TYPE_STUDLYPHPNAME => array ('idFeature', 'idLang', 'name', ),
		BasePeer::TYPE_COLNAME => array (self::ID_FEATURE, self::ID_LANG, self::NAME, ),
		BasePeer::TYPE_RAW_COLNAME => array ('ID_FEATURE', 'ID_LANG', 'NAME', ),
		BasePeer::TYPE_FIELDNAME => array ('id_feature', 'id_lang', 'name', ),
		BasePeer::TYPE_NUM => array (0, 1, 2, )
	);

	/**
	 * holds an array of keys for quick access to the fieldnames array
	 *
	 * first dimension keys are the type constants
	 * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0
	 */
	protected static $fieldKeys = array (
		BasePeer::TYPE_PHPNAME => array ('IdFeature' => 0, 'IdLang' => 1, 'Name' => 2, ),
		BasePeer::TYPE_STUDLYPHPNAME => array ('idFeature' => 0, 'idLang' => 1, 'name' => 2, ),
		BasePeer::TYPE_COLNAME => array (self::ID_FEATURE => 0, self::ID_LANG => 1, self::NAME => 2, ),
		BasePeer::TYPE_RAW_COLNAME => array ('ID_FEATURE' => 0, 'ID_LANG' => 1, 'NAME' => 2, ),
		BasePeer::TYPE_FIELDNAME => array ('id_feature' => 0, 'id_lang' => 1, 'name' => 2, ),
		BasePeer::TYPE_NUM => array (0, 1, 2, )
	);

	/**
	 * Translates a fieldname to another type
	 *
	 * @param      string $name field name
	 * @param      string $fromType One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
	 *                         BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM
	 * @param      string $toType   One of the class type constants
	 * @return     string translated name of the field.
	 * @throws     PropelException - if the specified name could not be found in the fieldname mappings.
	 */
	static public function translateFieldName($name, $fromType, $toType)
	{
		$toNames = self::getFieldNames($toType);
		$key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null;
		if ($key === null) {
			throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true));
		}
		return $toNames[$key];
	}

	/**
	 * Returns an array of field names.
	 *
	 * @param      string $type The type of fieldnames to return:
	 *                      One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
	 *                      BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM
	 * @return     array A list of field names
	 */

	static public function getFieldNames($type = BasePeer::TYPE_PHPNAME)
	{
		if (!array_key_exists($type, self::$fieldNames)) {
			throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. ' . $type . ' was given.');
		}
		return self::$fieldNames[$type];
	}

	/**
	 * Convenience method which changes table.column to alias.column.
	 *
	 * Using this method you can maintain SQL abstraction while using column aliases.
	 * <code>
	 *		$c->addAlias("alias1", TablePeer::TABLE_NAME);
	 *		$c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN);
	 * </code>
	 * @param      string $alias The alias for the current table.
	 * @param      string $column The column name for current table. (i.e. Oops_Db_FeatureLangPeer::COLUMN_NAME).
	 * @return     string
	 */
	public static function alias($alias, $column)
	{
		return str_replace(Oops_Db_FeatureLangPeer::TABLE_NAME.'.', $alias.'.', $column);
	}

	/**
	 * Add all the columns needed to create a new object.
	 *
	 * Note: any columns that were marked with lazyLoad="true" in the
	 * XML schema will not be added to the select list and only loaded
	 * on demand.
	 *
	 * @param      Criteria $criteria object containing the columns to add.
	 * @param      string   $alias    optional table alias
	 * @throws     PropelException Any exceptions caught during processing will be
	 *		 rethrown wrapped into a PropelException.
	 */
	public static function addSelectColumns(Criteria $criteria, $alias = null)
	{
		if (null === $alias) {
			$criteria->addSelectColumn(Oops_Db_FeatureLangPeer::ID_FEATURE);
			$criteria->addSelectColumn(Oops_Db_FeatureLangPeer::ID_LANG);
			$criteria->addSelectColumn(Oops_Db_FeatureLangPeer::NAME);
		} else {
			$criteria->addSelectColumn($alias . '.ID_FEATURE');
			$criteria->addSelectColumn($alias . '.ID_LANG');
			$criteria->addSelectColumn($alias . '.NAME');
		}
	}

	/**
	 * Returns the number of rows matching criteria.
	 *
	 * @param      Criteria $criteria
	 * @param      boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead.
	 * @param      PropelPDO $con
	 * @return     int Number of matching rows.
	 */
	public static function doCount(Criteria $criteria, $distinct = false, PropelPDO $con = null)
	{
		// we may modify criteria, so copy it first
		$criteria = clone $criteria;

		// We need to set the primary table name, since in the case that there are no WHERE columns
		// it will be impossible for the BasePeer::createSelectSql() method to determine which
		// tables go into the FROM clause.
		$criteria->setPrimaryTableName(Oops_Db_FeatureLangPeer::TABLE_NAME);

		if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
			$criteria->setDistinct();
		}

		if (!$criteria->hasSelectClause()) {
			Oops_Db_FeatureLangPeer::addSelectColumns($criteria);
		}

		$criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count
		$criteria->setDbName(self::DATABASE_NAME); // Set the correct dbName

		if ($con === null) {
			$con = Propel::getConnection(Oops_Db_FeatureLangPeer::DATABASE_NAME, Propel::CONNECTION_READ);
		}
		// BasePeer returns a PDOStatement
		$stmt = BasePeer::doCount($criteria, $con);

		if ($row = $stmt->fetch(PDO::FETCH_NUM)) {
			$count = (int) $row[0];
		} else {
			$count = 0; // no rows returned; we infer that means 0 matches.
		}
		$stmt->closeCursor();
		return $count;
	}
	/**
	 * Selects one object from the DB.
	 *
	 * @param      Criteria $criteria object used to create the SELECT statement.
	 * @param      PropelPDO $con
	 * @return     Oops_Db_FeatureLang
	 * @throws     PropelException Any exceptions caught during processing will be
	 *		 rethrown wrapped into a PropelException.
	 */
	public static function doSelectOne(Criteria $criteria, PropelPDO $con = null)
	{
		$critcopy = clone $criteria;
		$critcopy->setLimit(1);
		$objects = Oops_Db_FeatureLangPeer::doSelect($critcopy, $con);
		if ($objects) {
			return $objects[0];
		}
		return null;
	}
	/**
	 * Selects several row from the DB.
	 *
	 * @param      Criteria $criteria The Criteria object used to build the SELECT statement.
	 * @param      PropelPDO $con
	 * @return     array Array of selected Objects
	 * @throws     PropelException Any exceptions caught during processing will be
	 *		 rethrown wrapped into a PropelException.
	 */
	public static function doSelect(Criteria $criteria, PropelPDO $con = null)
	{
		return Oops_Db_FeatureLangPeer::populateObjects(Oops_Db_FeatureLangPeer::doSelectStmt($criteria, $con));
	}
	/**
	 * Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement.
	 *
	 * Use this method directly if you want to work with an executed statement durirectly (for example
	 * to perform your own object hydration).
	 *
	 * @param      Criteria $criteria The Criteria object used to build the SELECT statement.
	 * @param      PropelPDO $con The connection to use
	 * @throws     PropelException Any exceptions caught during processing will be
	 *		 rethrown wrapped into a PropelException.
	 * @return     PDOStatement The executed PDOStatement object.
	 * @see        BasePeer::doSelect()
	 */
	public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null)
	{
		if ($con === null) {
			$con = Propel::getConnection(Oops_Db_FeatureLangPeer::DATABASE_NAME, Propel::CONNECTION_READ);
		}

		if (!$criteria->hasSelectClause()) {
			$criteria = clone $criteria;
			Oops_Db_FeatureLangPeer::addSelectColumns($criteria);
		}

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

		// BasePeer returns a PDOStatement
		return BasePeer::doSelect($criteria, $con);
	}
	/**
	 * Adds an object to the instance pool.
	 *
	 * Propel keeps cached copies of objects in an instance pool when they are retrieved
	 * from the database.  In some cases -- especially when you override doSelect*()
	 * methods in your stub classes -- you may need to explicitly add objects
	 * to the cache in order to ensure that the same objects are always returned by doSelect*()
	 * and retrieveByPK*() calls.
	 *
	 * @param      Oops_Db_FeatureLang $value A Oops_Db_FeatureLang object.
	 * @param      string $key (optional) key to use for instance map (for performance boost if key was already calculated externally).
	 */
	public static function addInstanceToPool($obj, $key = null)
	{
		if (Propel::isInstancePoolingEnabled()) {
			if ($key === null) {
				$key = serialize(array((string) $obj->getIdFeature(), (string) $obj->getIdLang()));
			} // if key === null
			self::$instances[$key] = $obj;
		}
	}

	/**
	 * Removes an object from the instance pool.
	 *
	 * Propel keeps cached copies of objects in an instance pool when they are retrieved
	 * from the database.  In some cases -- especially when you override doDelete
	 * methods in your stub classes -- you may need to explicitly remove objects
	 * from the cache in order to prevent returning objects that no longer exist.
	 *
	 * @param      mixed $value A Oops_Db_FeatureLang object or a primary key value.
	 */
	public static function removeInstanceFromPool($value)
	{
		if (Propel::isInstancePoolingEnabled() && $value !== null) {
			if (is_object($value) && $value instanceof Oops_Db_FeatureLang) {
				$key = serialize(array((string) $value->getIdFeature(), (string) $value->getIdLang()));
			} elseif (is_array($value) && count($value) === 2) {
				// assume we've been passed a primary key
				$key = serialize(array((string) $value[0], (string) $value[1]));
			} else {
				$e = new PropelException("Invalid value passed to removeInstanceFromPool().  Expected primary key or Oops_Db_FeatureLang object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true)));
				throw $e;
			}

			unset(self::$instances[$key]);
		}
	} // removeInstanceFromPool()

	/**
	 * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table.
	 *
	 * For tables with a single-column primary key, that simple pkey value will be returned.  For tables with
	 * a multi-column primary key, a serialize()d version of the primary key will be returned.
	 *
	 * @param      string $key The key (@see getPrimaryKeyHash()) for this instance.
	 * @return     Oops_Db_FeatureLang Found object or NULL if 1) no instance exists for specified key or 2) instance pooling has been disabled.
	 * @see        getPrimaryKeyHash()
	 */
	public static function getInstanceFromPool($key)
	{
		if (Propel::isInstancePoolingEnabled()) {
			if (isset(self::$instances[$key])) {
				return self::$instances[$key];
			}
		}
		return null; // just to be explicit
	}

	/**
	 * Clear the instance pool.
	 *
	 * @return     void
	 */
	public static function clearInstancePool()
	{
		self::$instances = array();
	}

	/**
	 * Method to invalidate the instance pool of all tables related to feature_lang
	 * by a foreign key with ON DELETE CASCADE
	 */
	public static function clearRelatedInstancePool()
	{
	}

	/**
	 * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table.
	 *
	 * For tables with a single-column primary key, that simple pkey value will be returned.  For tables with
	 * a multi-column primary key, a serialize()d version of the primary key will be returned.
	 *
	 * @param      array $row PropelPDO resultset row.
	 * @param      int $startcol The 0-based offset for reading from the resultset row.
	 * @return     string A string version of PK or NULL if the components of primary key in result array are all null.
	 */
	public static function getPrimaryKeyHashFromRow($row, $startcol = 0)
	{
		// If the PK cannot be derived from the row, return NULL.
		if ($row[$startcol] === null && $row[$startcol + 1] === null) {
			return null;
		}
		return serialize(array((string) $row[$startcol], (string) $row[$startcol + 1]));
	}

	/**
	 * Retrieves the primary key from the DB resultset row
	 * For tables with a single-column primary key, that simple pkey value will be returned.  For tables with
	 * a multi-column primary key, an array of the primary key columns will be returned.
	 *
	 * @param      array $row PropelPDO resultset row.
	 * @param      int $startcol The 0-based offset for reading from the resultset row.
	 * @return     mixed The primary key of the row
	 */
	public static function getPrimaryKeyFromRow($row, $startcol = 0)
	{
		return array((int) $row[$startcol], (int) $row[$startcol + 1]);
	}

	/**
	 * The returned array will contain objects of the default type or
	 * objects that inherit from the default.
	 *
	 * @throws     PropelException Any exceptions caught during processing will be
	 *		 rethrown wrapped into a PropelException.
	 */
	public static function populateObjects(PDOStatement $stmt)
	{
		$results = array();

		// set the class once to avoid overhead in the loop
		$cls = Oops_Db_FeatureLangPeer::getOMClass(false);
		// populate the object(s)
		while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
			$key = Oops_Db_FeatureLangPeer::getPrimaryKeyHashFromRow($row, 0);
			if (null !== ($obj = Oops_Db_FeatureLangPeer::getInstanceFromPool($key))) {
				// We no longer rehydrate the object, since this can cause data loss.
				// See http://www.propelorm.org/ticket/509
				// $obj->hydrate($row, 0, true); // rehydrate
				$results[] = $obj;
			} else {
				$obj = new $cls();
				$obj->hydrate($row);
				$results[] = $obj;
				Oops_Db_FeatureLangPeer::addInstanceToPool($obj, $key);
			} // if key exists
		}
		$stmt->closeCursor();
		return $results;
	}
	/**
	 * Populates an object of the default type or an object that inherit from the default.
	 *
	 * @param      array $row PropelPDO resultset row.
	 * @param      int $startcol The 0-based offset for reading from the resultset row.
	 * @throws     PropelException Any exceptions caught during processing will be
	 *		 rethrown wrapped into a PropelException.
	 * @return     array (Oops_Db_FeatureLang object, last column rank)
	 */
	public static function populateObject($row, $startcol = 0)
	{
		$key = Oops_Db_FeatureLangPeer::getPrimaryKeyHashFromRow($row, $startcol);
		if (null !== ($obj = Oops_Db_FeatureLangPeer::getInstanceFromPool($key))) {
			// We no longer rehydrate the object, since this can cause data loss.
			// See http://www.propelorm.org/ticket/509
			// $obj->hydrate($row, $startcol, true); // rehydrate
			$col = $startcol + Oops_Db_FeatureLangPeer::NUM_HYDRATE_COLUMNS;
		} else {
			$cls = Oops_Db_FeatureLangPeer::OM_CLASS;
			$obj = new $cls();
			$col = $obj->hydrate($row, $startcol);
			Oops_Db_FeatureLangPeer::addInstanceToPool($obj, $key);
		}
		return array($obj, $col);
	}

	/**
	 * Returns the number of rows matching criteria, joining the related Feature table
	 *
	 * @param      Criteria $criteria
	 * @param      boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead.
	 * @param      PropelPDO $con
	 * @param      String    $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN
	 * @return     int Number of matching rows.
	 */
	public static function doCountJoinFeature(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN)
	{
		// we're going to modify criteria, so copy it first
		$criteria = clone $criteria;

		// We need to set the primary table name, since in the case that there are no WHERE columns
		// it will be impossible for the BasePeer::createSelectSql() method to determine which
		// tables go into the FROM clause.
		$criteria->setPrimaryTableName(Oops_Db_FeatureLangPeer::TABLE_NAME);

		if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
			$criteria->setDistinct();
		}

		if (!$criteria->hasSelectClause()) {
			Oops_Db_FeatureLangPeer::addSelectColumns($criteria);
		}

		$criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count

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

		if ($con === null) {
			$con = Propel::getConnection(Oops_Db_FeatureLangPeer::DATABASE_NAME, Propel::CONNECTION_READ);
		}

		$criteria->addJoin(Oops_Db_FeatureLangPeer::ID_FEATURE, Oops_Db_FeaturePeer::ID_FEATURE, $join_behavior);

		$stmt = BasePeer::doCount($criteria, $con);

		if ($row = $stmt->fetch(PDO::FETCH_NUM)) {
			$count = (int) $row[0];
		} else {
			$count = 0; // no rows returned; we infer that means 0 matches.
		}
		$stmt->closeCursor();
		return $count;
	}

	/**
	 * Selects a collection of Oops_Db_FeatureLang objects pre-filled with their Oops_Db_Feature objects.
	 * @param      Criteria  $criteria
	 * @param      PropelPDO $con
	 * @param      String    $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN
	 * @return     array Array of Oops_Db_FeatureLang objects.
	 * @throws     PropelException Any exceptions caught during processing will be
	 *		 rethrown wrapped into a PropelException.
	 */
	public static function doSelectJoinFeature(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN)
	{
		$criteria = clone $criteria;

		// Set the correct dbName if it has not been overridden
		if ($criteria->getDbName() == Propel::getDefaultDB()) {
			$criteria->setDbName(self::DATABASE_NAME);
		}

		Oops_Db_FeatureLangPeer::addSelectColumns($criteria);
		$startcol = Oops_Db_FeatureLangPeer::NUM_HYDRATE_COLUMNS;
		Oops_Db_FeaturePeer::addSelectColumns($criteria);

		$criteria->addJoin(Oops_Db_FeatureLangPeer::ID_FEATURE, Oops_Db_FeaturePeer::ID_FEATURE, $join_behavior);

		$stmt = BasePeer::doSelect($criteria, $con);
		$results = array();

		while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
			$key1 = Oops_Db_FeatureLangPeer::getPrimaryKeyHashFromRow($row, 0);
			if (null !== ($obj1 = Oops_Db_FeatureLangPeer::getInstanceFromPool($key1))) {
				// We no longer rehydrate the object, since this can cause data loss.
				// See http://www.propelorm.org/ticket/509
				// $obj1->hydrate($row, 0, true); // rehydrate
			} else {

				$cls = Oops_Db_FeatureLangPeer::getOMClass(false);

				$obj1 = new $cls();
				$obj1->hydrate($row);
				Oops_Db_FeatureLangPeer::addInstanceToPool($obj1, $key1);
			} // if $obj1 already loaded

			$key2 = Oops_Db_FeaturePeer::getPrimaryKeyHashFromRow($row, $startcol);
			if ($key2 !== null) {
				$obj2 = Oops_Db_FeaturePeer::getInstanceFromPool($key2);
				if (!$obj2) {

					$cls = Oops_Db_FeaturePeer::getOMClass(false);

					$obj2 = new $cls();
					$obj2->hydrate($row, $startcol);
					Oops_Db_FeaturePeer::addInstanceToPool($obj2, $key2);
				} // if obj2 already loaded

				// Add the $obj1 (Oops_Db_FeatureLang) to $obj2 (Oops_Db_Feature)
				$obj2->addFeatureLang($obj1);

			} // if joined row was not null

			$results[] = $obj1;
		}
		$stmt->closeCursor();
		return $results;
	}

	/**
	 * Returns the number of rows matching criteria, joining all related tables
	 *
	 * @param      Criteria $criteria
	 * @param      boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead.
	 * @param      PropelPDO $con
	 * @param      String    $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN
	 * @return     int Number of matching rows.
	 */
	public static function doCountJoinAll(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN)
	{
		// we're going to modify criteria, so copy it first
		$criteria = clone $criteria;

		// We need to set the primary table name, since in the case that there are no WHERE columns
		// it will be impossible for the BasePeer::createSelectSql() method to determine which
		// tables go into the FROM clause.
		$criteria->setPrimaryTableName(Oops_Db_FeatureLangPeer::TABLE_NAME);

		if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
			$criteria->setDistinct();
		}

		if (!$criteria->hasSelectClause()) {
			Oops_Db_FeatureLangPeer::addSelectColumns($criteria);
		}

		$criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count

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

		if ($con === null) {
			$con = Propel::getConnection(Oops_Db_FeatureLangPeer::DATABASE_NAME, Propel::CONNECTION_READ);
		}

		$criteria->addJoin(Oops_Db_FeatureLangPeer::ID_FEATURE, Oops_Db_FeaturePeer::ID_FEATURE, $join_behavior);

		$stmt = BasePeer::doCount($criteria, $con);

		if ($row = $stmt->fetch(PDO::FETCH_NUM)) {
			$count = (int) $row[0];
		} else {
			$count = 0; // no rows returned; we infer that means 0 matches.
		}
		$stmt->closeCursor();
		return $count;
	}

	/**
	 * Selects a collection of Oops_Db_FeatureLang objects pre-filled with all related objects.
	 *
	 * @param      Criteria  $criteria
	 * @param      PropelPDO $con
	 * @param      String    $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN
	 * @return     array Array of Oops_Db_FeatureLang objects.
	 * @throws     PropelException Any exceptions caught during processing will be
	 *		 rethrown wrapped into a PropelException.
	 */
	public static function doSelectJoinAll(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN)
	{
		$criteria = clone $criteria;

		// Set the correct dbName if it has not been overridden
		if ($criteria->getDbName() == Propel::getDefaultDB()) {
			$criteria->setDbName(self::DATABASE_NAME);
		}

		Oops_Db_FeatureLangPeer::addSelectColumns($criteria);
		$startcol2 = Oops_Db_FeatureLangPeer::NUM_HYDRATE_COLUMNS;

		Oops_Db_FeaturePeer::addSelectColumns($criteria);
		$startcol3 = $startcol2 + Oops_Db_FeaturePeer::NUM_HYDRATE_COLUMNS;

		$criteria->addJoin(Oops_Db_FeatureLangPeer::ID_FEATURE, Oops_Db_FeaturePeer::ID_FEATURE, $join_behavior);

		$stmt = BasePeer::doSelect($criteria, $con);
		$results = array();

		while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
			$key1 = Oops_Db_FeatureLangPeer::getPrimaryKeyHashFromRow($row, 0);
			if (null !== ($obj1 = Oops_Db_FeatureLangPeer::getInstanceFromPool($key1))) {
				// We no longer rehydrate the object, since this can cause data loss.
				// See http://www.propelorm.org/ticket/509
				// $obj1->hydrate($row, 0, true); // rehydrate
			} else {
				$cls = Oops_Db_FeatureLangPeer::getOMClass(false);

				$obj1 = new $cls();
				$obj1->hydrate($row);
				Oops_Db_FeatureLangPeer::addInstanceToPool($obj1, $key1);
			} // if obj1 already loaded

			// Add objects for joined Oops_Db_Feature rows

			$key2 = Oops_Db_FeaturePeer::getPrimaryKeyHashFromRow($row, $startcol2);
			if ($key2 !== null) {
				$obj2 = Oops_Db_FeaturePeer::getInstanceFromPool($key2);
				if (!$obj2) {

					$cls = Oops_Db_FeaturePeer::getOMClass(false);

					$obj2 = new $cls();
					$obj2->hydrate($row, $startcol2);
					Oops_Db_FeaturePeer::addInstanceToPool($obj2, $key2);
				} // if obj2 loaded

				// Add the $obj1 (Oops_Db_FeatureLang) to the collection in $obj2 (Oops_Db_Feature)
				$obj2->addFeatureLang($obj1);
			} // if joined row not null

			$results[] = $obj1;
		}
		$stmt->closeCursor();
		return $results;
	}

	/**
	 * Returns the TableMap related to this peer.
	 * This method is not needed for general use but a specific application could have a need.
	 * @return     TableMap
	 * @throws     PropelException Any exceptions caught during processing will be
	 *		 rethrown wrapped into a PropelException.
	 */
	public static function getTableMap()
	{
		return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME);
	}

	/**
	 * Add a TableMap instance to the database for this peer class.
	 */
	public static function buildTableMap()
	{
	  $dbMap = Propel::getDatabaseMap(Oops_Db_Propel_FeatureLangPeer::DATABASE_NAME);
	  if (!$dbMap->hasTable(Oops_Db_Propel_FeatureLangPeer::TABLE_NAME))
	  {
	    $dbMap->addTableObject(new Oops_Db_FeatureLangTableMap());
	  }
	}

	/**
	 * The class that the Peer will make instances of.
	 *
	 * If $withPrefix is true, the returned path
	 * uses a dot-path notation which is tranalted into a path
	 * relative to a location on the PHP include_path.
	 * (e.g. path.to.MyClass -> 'path/to/MyClass.php')
	 *
	 * @param      boolean $withPrefix Whether or not to return the path with the class name
	 * @return     string path.to.ClassName
	 */
	public static function getOMClass($withPrefix = true)
	{
		return $withPrefix ? Oops_Db_FeatureLangPeer::CLASS_DEFAULT : Oops_Db_FeatureLangPeer::OM_CLASS;
	}

	/**
	 * Performs an INSERT on the database, given a Oops_Db_FeatureLang or Criteria object.
	 *
	 * @param      mixed $values Criteria or Oops_Db_FeatureLang object containing data that is used to create the INSERT statement.
	 * @param      PropelPDO $con the PropelPDO connection to use
	 * @return     mixed The new primary key.
	 * @throws     PropelException Any exceptions caught during processing will be
	 *		 rethrown wrapped into a PropelException.
	 */
	public static function doInsert($values, PropelPDO $con = null)
	{
		if ($con === null) {
			$con = Propel::getConnection(Oops_Db_FeatureLangPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
		}

		if ($values instanceof Criteria) {
			$criteria = clone $values; // rename for clarity
		} else {
			$criteria = $values->buildCriteria(); // build Criteria from Oops_Db_FeatureLang object
		}

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

		try {
			// use transaction because $criteria could contain info
			// for more than one table (I guess, conceivably)
			$con->beginTransaction();
			$pk = BasePeer::doInsert($criteria, $con);
			$con->commit();
		} catch(PropelException $e) {
			$con->rollBack();
			throw $e;
		}

		return $pk;
	}

	/**
	 * Performs an UPDATE on the database, given a Oops_Db_FeatureLang or Criteria object.
	 *
	 * @param      mixed $values Criteria or Oops_Db_FeatureLang object containing data that is used to create the UPDATE statement.
	 * @param      PropelPDO $con The connection to use (specify PropelPDO connection object to exert more control over transactions).
	 * @return     int The number of affected rows (if supported by underlying database driver).
	 * @throws     PropelException Any exceptions caught during processing will be
	 *		 rethrown wrapped into a PropelException.
	 */
	public static function doUpdate($values, PropelPDO $con = null)
	{
		if ($con === null) {
			$con = Propel::getConnection(Oops_Db_FeatureLangPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
		}

		$selectCriteria = new Criteria(self::DATABASE_NAME);

		if ($values instanceof Criteria) {
			$criteria = clone $values; // rename for clarity

			$comparison = $criteria->getComparison(Oops_Db_FeatureLangPeer::ID_FEATURE);
			$value = $criteria->remove(Oops_Db_FeatureLangPeer::ID_FEATURE);
			if ($value) {
				$selectCriteria->add(Oops_Db_FeatureLangPeer::ID_FEATURE, $value, $comparison);
			} else {
				$selectCriteria->setPrimaryTableName(Oops_Db_FeatureLangPeer::TABLE_NAME);
			}

			$comparison = $criteria->getComparison(Oops_Db_FeatureLangPeer::ID_LANG);
			$value = $criteria->remove(Oops_Db_FeatureLangPeer::ID_LANG);
			if ($value) {
				$selectCriteria->add(Oops_Db_FeatureLangPeer::ID_LANG, $value, $comparison);
			} else {
				$selectCriteria->setPrimaryTableName(Oops_Db_FeatureLangPeer::TABLE_NAME);
			}

		} else { // $values is Oops_Db_FeatureLang object
			$criteria = $values->buildCriteria(); // gets full criteria
			$selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s)
		}

		// set the correct dbName
		$criteria->setDbName(self::DATABASE_NAME);

		return BasePeer::doUpdate($selectCriteria, $criteria, $con);
	}

	/**
	 * Deletes all rows from the feature_lang table.
	 *
	 * @param      PropelPDO $con the connection to use
	 * @return     int The number of affected rows (if supported by underlying database driver).
	 */
	public static function doDeleteAll(PropelPDO $con = null)
	{
		if ($con === null) {
			$con = Propel::getConnection(Oops_Db_FeatureLangPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
		}
		$affectedRows = 0; // initialize var to track total num of affected rows
		try {
			// use transaction because $criteria could contain info
			// for more than one table or we could emulating ON DELETE CASCADE, etc.
			$con->beginTransaction();
			$affectedRows += BasePeer::doDeleteAll(Oops_Db_FeatureLangPeer::TABLE_NAME, $con, Oops_Db_FeatureLangPeer::DATABASE_NAME);
			// Because this db requires some delete cascade/set null emulation, we have to
			// clear the cached instance *after* the emulation has happened (since
			// instances get re-added by the select statement contained therein).
			Oops_Db_FeatureLangPeer::clearInstancePool();
			Oops_Db_FeatureLangPeer::clearRelatedInstancePool();
			$con->commit();
			return $affectedRows;
		} catch (PropelException $e) {
			$con->rollBack();
			throw $e;
		}
	}

	/**
	 * Performs a DELETE on the database, given a Oops_Db_FeatureLang or Criteria object OR a primary key value.
	 *
	 * @param      mixed $values Criteria or Oops_Db_FeatureLang object or primary key or array of primary keys
	 *              which is used to create the DELETE statement
	 * @param      PropelPDO $con the connection to use
	 * @return     int 	The number of affected rows (if supported by underlying database driver).  This includes CASCADE-related rows
	 *				if supported by native driver or if emulated using Propel.
	 * @throws     PropelException Any exceptions caught during processing will be
	 *		 rethrown wrapped into a PropelException.
	 */
	 public static function doDelete($values, PropelPDO $con = null)
	 {
		if ($con === null) {
			$con = Propel::getConnection(Oops_Db_FeatureLangPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
		}

		if ($values instanceof Criteria) {
			// invalidate the cache for all objects of this type, since we have no
			// way of knowing (without running a query) what objects should be invalidated
			// from the cache based on this Criteria.
			Oops_Db_FeatureLangPeer::clearInstancePool();
			// rename for clarity
			$criteria = clone $values;
		} elseif ($values instanceof Oops_Db_FeatureLang) { // it's a model object
			// invalidate the cache for this single object
			Oops_Db_FeatureLangPeer::removeInstanceFromPool($values);
			// create criteria based on pk values
			$criteria = $values->buildPkeyCriteria();
		} else { // it's a primary key, or an array of pks
			$criteria = new Criteria(self::DATABASE_NAME);
			// primary key is composite; we therefore, expect
			// the primary key passed to be an array of pkey values
			if (count($values) == count($values, COUNT_RECURSIVE)) {
				// array is not multi-dimensional
				$values = array($values);
			}
			foreach ($values as $value) {
				$criterion = $criteria->getNewCriterion(Oops_Db_FeatureLangPeer::ID_FEATURE, $value[0]);
				$criterion->addAnd($criteria->getNewCriterion(Oops_Db_FeatureLangPeer::ID_LANG, $value[1]));
				$criteria->addOr($criterion);
				// we can invalidate the cache for this single PK
				Oops_Db_FeatureLangPeer::removeInstanceFromPool($value);
			}
		}

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

		$affectedRows = 0; // initialize var to track total num of affected rows

		try {
			// use transaction because $criteria could contain info
			// for more than one table or we could emulating ON DELETE CASCADE, etc.
			$con->beginTransaction();

			$affectedRows += BasePeer::doDelete($criteria, $con);
			Oops_Db_FeatureLangPeer::clearRelatedInstancePool();
			$con->commit();
			return $affectedRows;
		} catch (PropelException $e) {
			$con->rollBack();
			throw $e;
		}
	}

	/**
	 * Validates all modified columns of given Oops_Db_FeatureLang object.
	 * If parameter $columns is either a single column name or an array of column names
	 * than only those columns are validated.
	 *
	 * NOTICE: This does not apply to primary or foreign keys for now.
	 *
	 * @param      Oops_Db_FeatureLang $obj The object to validate.
	 * @param      mixed $cols Column name or array of column names.
	 *
	 * @return     mixed TRUE if all columns are valid or the error message of the first invalid column.
	 */
	public static function doValidate($obj, $cols = null)
	{
		$columns = array();

		if ($cols) {
			$dbMap = Propel::getDatabaseMap(Oops_Db_FeatureLangPeer::DATABASE_NAME);
			$tableMap = $dbMap->getTable(Oops_Db_FeatureLangPeer::TABLE_NAME);

			if (! is_array($cols)) {
				$cols = array($cols);
			}

			foreach ($cols as $colName) {
				if ($tableMap->containsColumn($colName)) {
					$get = 'get' . $tableMap->getColumn($colName)->getPhpName();
					$columns[$colName] = $obj->$get();
				}
			}
		} else {

		}

		return BasePeer::doValidate(Oops_Db_FeatureLangPeer::DATABASE_NAME, Oops_Db_FeatureLangPeer::TABLE_NAME, $columns);
	}

	/**
	 * Retrieve object using using composite pkey values.
	 * @param      int $id_feature
	 * @param      int $id_lang
	 * @param      PropelPDO $con
	 * @return     Oops_Db_FeatureLang
	 */
	public static function retrieveByPK($id_feature, $id_lang, PropelPDO $con = null) {
		$_instancePoolKey = serialize(array((string) $id_feature, (string) $id_lang));
 		if (null !== ($obj = Oops_Db_FeatureLangPeer::getInstanceFromPool($_instancePoolKey))) {
 			return $obj;
		}

		if ($con === null) {
			$con = Propel::getConnection(Oops_Db_FeatureLangPeer::DATABASE_NAME, Propel::CONNECTION_READ);
		}
		$criteria = new Criteria(Oops_Db_FeatureLangPeer::DATABASE_NAME);
		$criteria->add(Oops_Db_FeatureLangPeer::ID_FEATURE, $id_feature);
		$criteria->add(Oops_Db_FeatureLangPeer::ID_LANG, $id_lang);
		$v = Oops_Db_FeatureLangPeer::doSelect($criteria, $con);

		return !empty($v) ? $v[0] : null;
	}
} // Oops_Db_Propel_FeatureLangPeer

// This is the static code needed to register the TableMap for this table with the main Propel class.
//
Oops_Db_Propel_FeatureLangPeer::buildTableMap();


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

namespace NPOI.POIFS.FileSystem
{
    public class EntryUtils
    {
        /**
     * Copies an Entry into a target POIFS directory, recursively
     */
        public static void CopyNodeRecursively(Entry entry, DirectoryEntry target)
        {
            // System.err.println("copyNodeRecursively called with "+entry.getName()+
            // ","+target.getName());
            DirectoryEntry newTarget = null;
            if (entry.IsDirectoryEntry)
            {
                DirectoryEntry dirEntry = (DirectoryEntry)entry;
                newTarget = target.CreateDirectory(entry.Name);
                newTarget.StorageClsid=(dirEntry.StorageClsid);
                IEnumerator<Entry> entries = dirEntry.Entries;

                while (entries.MoveNext())
                {
                    CopyNodeRecursively((Entry)entries.Current, newTarget);
                }
            }
            else
            {
                DocumentEntry dentry = (DocumentEntry)entry;
                DocumentInputStream dstream = new DocumentInputStream(dentry);
                target.CreateDocument(dentry.Name, dstream);
                dstream.Close();
            }
        }

        /**
         * Copies all the nodes from one POIFS Directory to another
         *
         * @param sourceRoot
         *            is the source Directory to copy from
         * @param targetRoot
         *            is the target Directory to copy to
         */
        public static void CopyNodes(DirectoryEntry sourceRoot,
                DirectoryEntry targetRoot)
        {
            foreach (Entry entry in sourceRoot)
            {
                CopyNodeRecursively(entry, targetRoot);
            }
        }

        /**
         * Copies nodes from one Directory to the other minus the excepts
         *
         * @param filteredSource The filtering source Directory to copy from
         * @param filteredTarget The filtering target Directory to copy to
         */
        public static void CopyNodes(FilteringDirectoryNode filteredSource,
                FilteringDirectoryNode filteredTarget)
        {
            // Nothing special here, just overloaded types to make the
            //  recommended new way to handle this clearer
            CopyNodes((DirectoryEntry)filteredSource, (DirectoryEntry)filteredTarget);
        }

        /**
         * Copies nodes from one Directory to the other minus the excepts
         *
         * @param sourceRoot
         *            is the source Directory to copy from
         * @param targetRoot
         *            is the target Directory to copy to
         * @param excepts
         *            is a list of Strings specifying what nodes NOT to copy
         * @deprecated use {@link FilteringDirectoryNode} instead
         */
        [Obsolete]
        public static void CopyNodes(DirectoryEntry sourceRoot,
                DirectoryEntry targetRoot, List<String> excepts)
        {
            IEnumerator entries = sourceRoot.Entries;
            while (entries.MoveNext())
            {
                Entry entry = (Entry)entries.Current;
                if (!excepts.Contains(entry.Name))
                {
                    CopyNodeRecursively(entry, targetRoot);
                }
            }
        }

        /**
         * Copies all nodes from one POIFS to the other
         *
         * @param source
         *            is the source POIFS to copy from
         * @param target
         *            is the target POIFS to copy to
         */
        public static void CopyNodes(POIFSFileSystem source,
                POIFSFileSystem target)
        {
            CopyNodes(source.Root, target.Root);
        }

        /**
         * Copies nodes from one POIFS to the other, minus the excepts.
         * This delegates the filtering work to {@link FilteringDirectoryNode},
         *  so excepts can be of the form "NodeToExclude" or
         *  "FilteringDirectory/ExcludedChildNode"
         *
         * @param source is the source POIFS to copy from
         * @param target is the target POIFS to copy to
         * @param excepts is a list of Entry Names to be excluded from the copy
         */
        public static void CopyNodes(POIFSFileSystem source,
                POIFSFileSystem target, List<String> excepts)
        {
            CopyNodes(
                  new FilteringDirectoryNode(source.Root, excepts),
                  new FilteringDirectoryNode(target.Root, excepts)
            );
        }

        /**
         * Checks to see if the two Directories hold the same contents.
         * For this to be true, they must have entries with the same names,
         *  no entries in one but not the other, and the size+contents
         *  of each entry must match, and they must share names.
         * To exclude certain parts of the Directory from being checked,
         *  use a {@link FilteringDirectoryNode}
         */
        public static bool AreDirectoriesIdentical(DirectoryEntry dirA, DirectoryEntry dirB)
        {
            // First, check names
            if (!dirA.Name.Equals(dirB.Name))
            {
                return false;
            }

            // Next up, check they have the same number of children
            if (dirA.EntryCount != dirB.EntryCount)
            {
                return false;
            }

            // Next, check entries and their types/sizes
            Dictionary<String, int> aSizes = new Dictionary<String, int>();
            int isDirectory = -12345;
            foreach (Entry a in dirA)
            {
                String aName = a.Name;
                if (a.IsDirectoryEntry)
                {
                    aSizes.Add(aName, isDirectory);
                }
                else
                {
                    aSizes.Add(aName, ((DocumentNode)a).Size);
                }
            }
            foreach (Entry b in dirB)
            {
                String bName = b.Name;
                if (!aSizes.ContainsKey(bName))
                {
                    // In B but not A
                    return false;
                }

                int size;
                if (b.IsDirectoryEntry)
                {
                    size = isDirectory;
                }
                else
                {
                    size = ((DocumentNode)b).Size;
                }
                if (size != aSizes[(bName)])
                {
                    // Either the wrong type, or they're different sizes
                    return false;
                }

                // Track it as checked
                aSizes.Remove(bName);
            }
            if (!(aSizes.Count == 0))
            {
                // Nodes were in A but not B
                return false;
            }

            // If that passed, check entry contents
            foreach (Entry a in dirA)
            {
                try
                {
                    Entry b = dirB.GetEntry(a.Name);
                    bool match;
                    if (a.IsDirectoryEntry)
                    {
                        match = AreDirectoriesIdentical(
                              (DirectoryEntry)a, (DirectoryEntry)b);
                    }
                    else
                    {
                        match = AreDocumentsIdentical(
                              (DocumentEntry)a, (DocumentEntry)b);
                    }
                    if (!match) return false;
                }
                catch (FileNotFoundException)
                {
                    // Shouldn't really happen...
                    return false;
                }
                catch (IOException)
                {
                    // Something's messed up with one document, not a match
                    return false;
                }
            }

            // If we get here, they match!
            return true;
        }

        /**
         * Checks to see if two Documents have the same name
         *  and the same contents. (Their parent directories are
         *  not checked)
         */
        public static bool AreDocumentsIdentical(DocumentEntry docA, DocumentEntry docB)
        {
            if (!docA.Name.Equals(docB.Name))
            {
                // Names don't match, not the same
                return false;
            }
            if (docA.Size != docB.Size)
            {
                // Wrong sizes, can't have the same contents
                return false;
            }

            bool matches = true;
            DocumentInputStream inpA = null, inpB = null;
            try
            {
                inpA = new DocumentInputStream(docA);
                inpB = new DocumentInputStream(docB);

                int readA, readB;
                do
                {
                    readA = inpA.Read();
                    readB = inpB.Read();
                    if (readA != readB)
                    {
                        matches = false;
                        break;
                    }
                } while (readA != -1 && readB != -1);
            }
            finally
            {
                if (inpA != null) inpA.Close();
                if (inpB != null) inpB.Close();
            }

            return matches;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package jaredbgreat.climaticbiome.generation.biome;

import jaredbgreat.climaticbiome.generation.mapgenerator.ChunkTile;

import java.util.StringTokenizer;

import net.minecraft.util.ResourceLocation;
import net.minecraft.world.biome.Biome;
import net.minecraftforge.registries.IForgeRegistry;

public class CentralDoubleBiome extends AbstractTerminalSpecifier {
	private final long a, b;
	private final int boundary;

	public CentralDoubleBiome(long a, int boundary, long b) {
		this.a = a;
		this.b = b;
		this.boundary = boundary;
	}

	public CentralDoubleBiome(Biome a, int boundary, Biome b) {
		this.a = Biome.getIdForBiome(a);
		this.b = Biome.getIdForBiome(b);
		this.boundary = boundary;
	}

	public CentralDoubleBiome(String a, int boundary, String b, IForgeRegistry biomeReg) {
		this.a = getBiomeNumber(a, biomeReg);
		this.b = getBiomeNumber(b, biomeReg);
		this.boundary = boundary;
	}

	@Override
	public long getBiome(ChunkTile tile) {
		if(tile.getCNoise() < boundary) {
			return a;
		} else {
			return b;
		}
	}

	@Override
	public boolean isEmpty() {
		return ((a < 0) || (b < 0));
	}

}


text:
const CrisprDefaults = {
  all: {
    minReadCount: 30,
    minGuides: 4,
    norm: true,
    normCount: 10000000,
  },
  BAGEL: {
    bootstrapIter: 1000,
    essentialVersion: 'v1',
  },
  drugZ: {
    nonEssentialVersion: 'v1',
    pseudoCount: 5,
    removeGenes: '',
  },
  MAGeCKmle: {
    adjustMethod: '',
    genesVarModeling: 1000,
    permutationRounds: 10,
    removeOutliers: false,
  },
  MAGeCKtest: {
    adjustMethod: '',
    geneLfcMethod: 'median',
    geneTestFdrThreshold: 0.25,
    varianceFromAllSamples: false,
  },
  RANKS: {},
};
module.exports = CrisprDefaults;


text:
class CreateDishes < ActiveRecord::Migration[5.0]
  def change
    create_table :dishes do |t|
      t.string :name
      t.string :description
      t.integer :category_id
      t.integer :user_id
      t.integer :restaurant_id

      t.timestamps
    end
  end
end


text:
#pragma once

#include "caffe2/contrib/gloo/common.h"
#include "caffe2/contrib/gloo/store_handler.h"
#include "caffe2/core/operator.h"
#include "caffe2/distributed/store_handler.h"

#include <gloo/common/error.h>
#include <gloo/config.h>
#include <gloo/rendezvous/context.h>
#include <gloo/rendezvous/prefix_store.h>

#if defined(GLOO_USE_MPI) && GLOO_USE_MPI
#include <gloo/mpi/context.h>
#endif

namespace caffe2 {
namespace gloo {

template <class Context>
class CreateCommonWorld final : public Operator<Context> {
 public:
  using CommonWorld = std::shared_ptr<::gloo::Context>;

  USE_OPERATOR_CONTEXT_FUNCTIONS;

  CreateCommonWorld(const OperatorDef& operator_def, Workspace* ws)
      : Operator<Context>(operator_def, ws),
        size_(OperatorBase::template GetSingleArgument<int>("size", 0)),
        rank_(OperatorBase::template GetSingleArgument<int>("rank", 0)),
        sync_(OperatorBase::template GetSingleArgument<bool>("sync", false)),
        transport_(OperatorBase::template GetSingleArgument<std::string>(
                       "transport", "tcp")),
        interface_(OperatorBase::template GetSingleArgument<std::string>(
                       "interface", "")),
        mpi_rendezvous_(OperatorBase::template GetSingleArgument<bool>(
                       "mpi_rendezvous", false)),
        status_blob_(
            OperatorBase::GetSingleArgument<std::string>("status_blob", "")),
        timeout_ms_(OperatorBase::GetSingleArgument<int>("timeout_ms", -1)),
        ws_(ws) {
    CAFFE_ENFORCE(
        operator_def.has_name(), "CreateCommonWorld operator requires name");
    CAFFE_ENFORCE(rank_ >= 0 && rank_ < size_);
    name_ = operator_def.name();
    if (status_blob_ != "") {
      ws_->CreateBlob(status_blob_);
    }
    initialize();
  }

  virtual ~CreateCommonWorld() {
  }

  CommonWorld rendezvousWithMPI() {
#if defined(GLOO_USE_MPI) && GLOO_USE_MPI
    auto context = ::gloo::mpi::Context::createManaged();
    if (timeout_ms_ != -1) {
      context->setTimeout(std::chrono::milliseconds(timeout_ms_));
    }
    context->connectFullMesh(device_);
    return context;
#else
    CAFFE_THROW(
      "Gloo was not compiled with MPI support. ",
      "Please recompile with -DUSE_MPI=1.");
#endif
  }

  CommonWorld rendezvousWithStore(
      const std::unique_ptr<StoreHandler>& handler) {
    // Use PrefixStore to isolate different CreateCommonWorld instances
    StoreHandlerWrapper wrapper(*handler);
    ::gloo::rendezvous::PrefixStore store(name_, wrapper);
    auto context = std::make_shared<::gloo::rendezvous::Context>(rank_, size_);
    if (timeout_ms_ != -1) {
      context->setTimeout(std::chrono::milliseconds(timeout_ms_));
    }
    context->connectFullMesh(store, device_);
    return context;
  }

  bool RunOnDevice() override {
    try {
      CommonWorld context;
      if (mpi_rendezvous_) {
        context = rendezvousWithMPI();
      } else {
        CAFFE_ENFORCE_EQ(InputSize(), 1, "Expected store handler input");
        const auto& handler =
            OperatorBase::Input<std::unique_ptr<StoreHandler>>(STORE_HANDLER);
        context = rendezvousWithStore(handler);
      }

      // Switch pairs to synchronous mode if configured to do so
      if (sync_) {
        for (int i = 0; i < context->size; i++) {
          auto& pair = context->getPair(i);
          if (pair) {
            pair->setSync(true, false);
          }
        }
      }

      *OperatorBase::Output<CommonWorld>(COMM) = std::move(context);
    } catch (::gloo::IoException& ioe) {
      LOG(ERROR) << "Caught gloo IO exception: " << ioe.what();
      return handleException(ioe);
    } catch (::caffe2::StoreHandlerTimeoutException& te) {
      LOG(ERROR) << "Caught store handler timeout exception: " << te.what();
      return handleException(te);
    }
    return true;
  }

 private:
  bool handleException(std::exception& ex) {
    if (status_blob_ != "") {
      signalFailure(ws_->GetBlob(status_blob_), ex);
      return false;
    } else {
      throw ex;
    }
  }

  void initialize() {
    // Share single device between all common worlds.
    static std::once_flag once;
    static std::shared_ptr<::gloo::transport::Device> device;
    std::call_once(once, [&]() {
        createDeviceAttr attr;
        attr.transport = transport_;
        attr.interface = interface_;
        device = createDevice(attr);
      });
    device_ = device;

    // Context specific initialization.
    initializeForContext();
  }

  void initializeForContext();

  const int size_;
  const int rank_;
  const bool sync_;
  const std::string transport_;
  const std::string interface_;
  const bool mpi_rendezvous_;
  const std::string status_blob_;
  const int timeout_ms_;
  Workspace* ws_;

  std::string name_;
  std::shared_ptr<::gloo::transport::Device> device_;

  INPUT_TAGS(STORE_HANDLER);
  OUTPUT_TAGS(COMM);
};

template <class Context>
class CloneCommonWorld final : public Operator<Context> {
 public:
  using CommonWorld = std::shared_ptr<::gloo::Context>;

  USE_OPERATOR_CONTEXT_FUNCTIONS;

  CloneCommonWorld(const OperatorDef& operator_def, Workspace* ws)
      : Operator<Context>(operator_def, ws),
        sync_(OperatorBase::template GetSingleArgument<bool>("sync", false)),
        ws_(ws),
        status_blob_(
            OperatorBase::GetSingleArgument<std::string>("status_blob", "")) {
    if (status_blob_ != "") {
      ws_->CreateBlob(status_blob_);
    }
  }

  virtual ~CloneCommonWorld() {}

  bool RunOnDevice() override {
    try {
      auto existing = OperatorBase::Input<CommonWorld>(EXISTING_COMM);
      ::gloo::rendezvous::ContextFactory factory(existing);
      auto clone = factory.makeContext(existing->getDevice());

      // Switch pairs to synchronous mode if configured to do so
      if (sync_) {
        for (int i = 0; i < clone->size; i++) {
          auto& pair = clone->getPair(i);
          if (pair) {
            pair->setSync(true, false);
          }
        }
      }

      *OperatorBase::Output<CommonWorld>(CLONED_COMM) = std::move(clone);
    } catch (::gloo::IoException& ioe) {
      LOG(ERROR) << "Caught gloo IO exception: " << ioe.what();
      return handleException(ioe);
    }
    return true;
  }

 private:
  bool handleException(std::exception& ex) {
    if (status_blob_ != "") {
      signalFailure(ws_->GetBlob(status_blob_), ex);
      return false;
    } else {
      throw ex;
    }
  }

  const bool sync_;
  Workspace* ws_;
  std::string status_blob_;

  INPUT_TAGS(EXISTING_COMM);
  OUTPUT_TAGS(CLONED_COMM);
};

class DestroyCommonWorld final : public Operator<CPUContext> {
 public:
  DestroyCommonWorld(const OperatorDef& operator_def, Workspace* ws)
      : Operator<CPUContext>(operator_def, ws) {
    cw_name_ = operator_def.input(0);
  }

  bool RunOnDevice() override {
    if (OperatorBase::InputBlob(0).GetRaw() == nullptr) {
      return true;
    }
    const auto& context =
        OperatorBase::Input<std::shared_ptr<::gloo::Context>>(0);

    if (context) {
      LOG(INFO) << "Closing connections: " << cw_name_;
      context->closeConnections();
    }
    return true;
  }

 private:
  std::string cw_name_;
};

} // namespace gloo
} // namespace caffe2


text:
<?php namespace Arcanedev\Head\Support;

use Arcanedev\Head\Exceptions\Exception;
use Arcanedev\Head\Exceptions\InvalidHTMLVersionException;
use Arcanedev\Head\Exceptions\InvalidTypeException;

/**
 * Class HTMLVersion
 * @package Arcanedev\Head\Support
 */
class HTMLVersion
{
    /* ------------------------------------------------------------------------------------------------
     |  Properties
     | ------------------------------------------------------------------------------------------------
     */
    protected $version;

    const HTML_5            = '5';
    const HTML_4            = '4';
    const DEFAULT_VERSION   = self::HTML_5;

    private $supported      = [self::HTML_4, self::HTML_5];

    /* ------------------------------------------------------------------------------------------------
     |  Constructor
     | ------------------------------------------------------------------------------------------------
     */
    public function __construct($version = '')
    {
        if (! empty($version)) {
            $this->set($version);
        }
    }

    /* ------------------------------------------------------------------------------------------------
     |  Getters & Setters
     | ------------------------------------------------------------------------------------------------
     */
    /**
     * @return string
     */
    public function get()
    {
        if ( $this->isEmpty() ) {
            $this->set(self::DEFAULT_VERSION);
        }

        return $this->version;
    }

    /**
     * @param int|string $version
     *
     * @throws InvalidTypeException
     * @throws InvalidHTMLVersionException
     *
     * @return HTMLVersion
     */
    public function set($version)
    {
        $this->check($version);

        $this->version = $version;

        return $this;
    }

    /* ------------------------------------------------------------------------------------------------
     |  Main Functions
     | ------------------------------------------------------------------------------------------------
     */

    /* ------------------------------------------------------------------------------------------------
     |  Check Functions
     | ------------------------------------------------------------------------------------------------
     */
    /**
     * @return bool
     */
    public function isEmpty()
    {
        return empty($this->version);
    }

    /**
     * @param string $version
     *
     * @return bool
     */
    public function isSupported($version)
    {
        return in_array($version, $this->supported);
    }

    /**
     * @return bool
     */
    public function isHTML5()
    {
        return $this->get() === self::HTML_5;
    }

    /**
     * @param string $version
     *
     * @throws Exception
     * @throws InvalidHTMLVersionException
     * @throws InvalidTypeException
     */
    private function check(&$version)
    {
        $this->checkVersionType($version);

        $version = is_string($version)
            ? trim($version)
            : (string) $version;

        if ( empty($version) ) {
            throw new Exception('The HTML Version is empty.');
        }

        if ( ! $this->isSupported($version) ) {
            throw new InvalidHTMLVersionException("The version [$version] is an invalid HTML Version");
        }
    }

    /**
     * @param $version
     *
     * @throws InvalidTypeException
     */
    private function checkVersionType($version)
    {
        if ( ! is_integer($version) and ! is_string($version) ) {
            throw new InvalidTypeException('version', $version, 'string or integer');
        }
    }
}


text:
import unittest

class Solution(object):
    def isMatch(self, s, p):
        # The DP table and the string s and p use the same indexes i and j, but
        # table[i][j] means the match status between p[:i] and s[:j], i.e.
        # table[0][0] means the match status of two empty strings, and
        # table[1][1] means the match status of p[0] and s[0]. Therefore, when
        # refering to the i-th and the j-th characters of p and s for updating
        # table[i][j], we use p[i - 1] and s[j - 1].

        # Initialize the table with False. The first row is satisfied.
        table = [[False] * (len(s) + 1) for _ in range(len(p) + 1)]

        # Update the corner case of matching two empty strings.
        table[0][0] = True

        # Update the corner case of when s is an empty string but p is not.
        # Since each '*' can eliminate the charter before it, the table is
        # vertically updated by the one before previous. [test_symbol_0]
        for i in range(2, len(p) + 1):
            table[i][0] = table[i - 2][0] and p[i - 1] == '*'

        for i in range(1, len(p) + 1):
            for j in range(1, len(s) + 1):
                if p[i - 1] != "*":
                    # Update the table by referring the diagonal element.
                    table[i][j] = table[i - 1][j - 1] and \
                                  (p[i - 1] == s[j - 1] or p[i - 1] == '.')
                else:
                    # Eliminations (referring to the vertical element)
                    # Either refer to the one before previous or the previous.
                    # I.e. * eliminate the previous or count the previous.
                    # [test_symbol_1]
                    table[i][j] = table[i - 2][j] or table[i - 1][j]

                    # Propagations (referring to the horizontal element)
                    # If p's previous one is equal to the current s, with
                    # helps of *, the status can be propagated from the left.
                    # [test_symbol_2]
                    if p[i - 2] == s[j - 1] or p[i - 2] == '.':
                        table[i][j] |= table[i][j - 1]

        return table[-1][-1]

class TestSolution(unittest.TestCase):
    def test_none_0(self):
        s = ""
        p = ""
        self.assertTrue(Solution().isMatch(s, p))

    def test_none_1(self):
        s = ""
        p = "a"
        self.assertFalse(Solution().isMatch(s, p))

    def test_no_symbol_equal(self):
        s = "abcd"
        p = "abcd"
        self.assertTrue(Solution().isMatch(s, p))

    def test_no_symbol_not_equal_0(self):
        s = "abcd"
        p = "efgh"
        self.assertFalse(Solution().isMatch(s, p))

    def test_no_symbol_not_equal_1(self):
        s = "ab"
        p = "abb"
        self.assertFalse(Solution().isMatch(s, p))

    def test_symbol_0(self):
        s = ""
        p = "a*"
        self.assertTrue(Solution().isMatch(s, p))

    def test_symbol_1(self):
        s = "a"
        p = "ab*"
        self.assertTrue(Solution().isMatch(s, p))

    def test_symbol_2(self):
        # E.g.
        #   s a b b
        # p 1 0 0 0
        # a 0 1 0 0
        # b 0 0 1 0
        # * 0 1 1 1
        s = "abb"
        p = "ab*"
        self.assertTrue(Solution().isMatch(s, p))

if __name__ == "__main__":
    unittest.main()


text:
namespace Google.Cloud.Retail.V2.Snippets
{
    // [START retail_v2_generated_CatalogService_UpdateCatalog_sync_flattened]
    using Google.Cloud.Retail.V2;
    using Google.Protobuf.WellKnownTypes;

    public sealed partial class GeneratedCatalogServiceClientSnippets
    {
        /// <summary>Snippet for UpdateCatalog</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void UpdateCatalog()
        {
            // Create client
            CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create();
            // Initialize request argument(s)
            Catalog catalog = new Catalog();
            FieldMask updateMask = new FieldMask();
            // Make the request
            Catalog response = catalogServiceClient.UpdateCatalog(catalog, updateMask);
        }
    }
    // [END retail_v2_generated_CatalogService_UpdateCatalog_sync_flattened]
}


text:
<?php

namespace App\Extractor;

class ExtractorChain
{
    /** @var array */
    private $extractors;

    public function __construct()
    {
        $this->extractors = [];
    }

    /**
     * Add an extractor to the chain.
     *
     * @param string $alias
     */
    public function addExtractor(AbstractExtractor $extractor, $alias): void
    {
        $this->extractors[$alias] = $extractor;
    }

    /**
     * Loop thru all extractor and return one that match.
     *
     * @param string $url An url
     *
     * @return AbstractExtractor|false
     */
    public function match($url)
    {
        foreach ($this->extractors as $alias => $extractor) {
            if (true === $extractor->match($url)) {
                return $extractor;
            }
        }

        return false;
    }
}


text:
const assert = require('assert');
const Player = require('../../models/player');

describe('Update a Player', () => {
  let playerOne;

  beforeEach((done) => {
    playerOne = new Player({
      name: 'Tyler',
      email: 'test@test.com',
      password: 'testpass',
      username: 'testusername',
      avatar: 'http://i.imgur.com/OqQj7v4.jpg',
      gamesWon: 2,
      gamesLost: 3,
      gamesDrawn: 1
    })

    playerOne.save()
      .then(() => done())
  })

  it('can update an email address', (done) => {
    Player.findOneAndUpdate({ username: 'testusername'}, { email: 'updated@email.com'}, {new: true})
      .then((player) => {
        assert(player.email === 'updated@email.com');
        done();
      })
      .catch((err) => console.log(err))
  })

})


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/ship/crafted/shields/shared_adv_deflector_shields.iff"
	result.attribute_template_id = 8
	result.stfName("space_crafting_n","adv_deflector_shields")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
package com.vaadin.tests.layouts;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.interactions.Actions;

import com.vaadin.testbench.elements.AbsoluteLayoutElement;
import com.vaadin.testbench.elements.ButtonElement;
import com.vaadin.testbench.elements.CssLayoutElement;
import com.vaadin.testbench.elements.GridLayoutElement;
import com.vaadin.testbench.elements.LabelElement;
import com.vaadin.testbench.elements.TextFieldElement;
import com.vaadin.testbench.elements.VerticalLayoutElement;
import com.vaadin.tests.tb3.MultiBrowserTest;

/**
 * Tests LayoutClickListener on different layouts.
 *
 * @since
 * @author Vaadin Ltd
 */
public class TestLayoutClickListenersTest extends MultiBrowserTest {

    @Before
    public void before() {
        openTestURL();
    }

    @Test
    public void clickInGridLayout() {
        GridLayoutElement layout = $(GridLayoutElement.class).first();

        // click on a label
        layout.$(LabelElement.class).first().click();
        assertLogText("GridLayout 1st child clicked",
                "1. GridLayout: left click on This is label 1");

        // click on a text field
        layout.$(TextFieldElement.class).get(1).click();
        assertLogText("GridLayout 5th child clicked",
                "2. GridLayout: left click on This is tf5");

        // click on the layout body (not any component inside the layout)
        layout.click(130, 41);
        assertLogText("GridLayout body clicked",
                "3. GridLayout: left click on <none>");
    }

    @Test
    public void clickInVerticalLayout() {
        VerticalLayoutElement layout = $(VerticalLayoutElement.class).get(4);

        // click on a text field
        layout.$(TextFieldElement.class).get(1).click();
        assertLogText("VerticalLayout 6th child clicked",
                "1. VerticalLayout: left click on This is tf6");

        // click on a label
        layout.$(LabelElement.class).get(3).click();
        assertLogText("VerticalLayout 4th child clicked",
                "2. VerticalLayout: left click on This is label 3");
    }

    @Test
    public void clickInAbsoluteLayout() {
        AbsoluteLayoutElement layout = $(AbsoluteLayoutElement.class).first();

        // click on a button that has its own ClickListener (should be ignored
        // by the LayoutClickListener)
        layout.$(ButtonElement.class).first().click();
        assertLogText("A button with a ClickListener clicked",
                "1. Button A button with its own click listener was clicked");

        // click on a text field's caption
        layout.$(TextFieldElement.class).first().click();
        assertLogText("AbsoluteLayout 1st child was clicked",
                "2. AbsoluteLayout: left click on This is its caption");
    }

    @Test
    public void clickInCSSLayout() {
        CssLayoutElement layout = $(CssLayoutElement.class).first();

        // click on a text field's caption
        layout.$(TextFieldElement.class).first().click();
        assertLogText("CSSLayout 1st child clicked",
                "1. CSSLayout: left click on This is its caption");

        // click on a button that has its own ClickListener (should be ignored
        // by the LayoutClickListener)
        layout.$(ButtonElement.class).first().click();
        assertLogText("Abutton with a ClickListener was clicked",
                "2. Button A button with its own click listener was clicked");
    }

    @Test
    public void dragInGridLayout() {
        GridLayoutElement layout = $(GridLayoutElement.class).first();

        // Drag inside the first label in this layout
        new Actions(getDriver())
                .moveToElement(layout.$(LabelElement.class).first(), 40, 8)
                .clickAndHold().moveByOffset(-20, 0).release().perform();
        assertLogText("Mouse dragged in GridLayout",
                "1. GridLayout: left click on This is label 1");

        // Drag from the third label to a text field in this layout
        new Actions(getDriver())
                .moveToElement(layout.$(LabelElement.class).get(2), 40, 8)
                .clickAndHold()
                .moveToElement(layout.$(TextFieldElement.class).get(3), 46, 33)
                .release().perform();
        assertLogText("Expected the drag to be ignored between elements",
                "1. GridLayout: left click on This is label 1");
    }

    @Test
    public void dragInVerticalLayout() {
        VerticalLayoutElement layout = $(VerticalLayoutElement.class).get(4);

        // Drag inside the first text field
        new Actions(getDriver())
                .moveToElement(layout.$(TextFieldElement.class).first(), 25, 9)
                .clickAndHold().moveByOffset(-20, 0).release().perform();
        assertLogText("Mouse dragged in VerticalLayout",
                "1. VerticalLayout: left click on This is tf5");

        // Drag from a caption to its text field
        new Actions(getDriver())
                .moveToElement(layout.$(TextFieldElement.class).get(4), 28, 11)
                .clickAndHold()
                .moveToElement(layout.$(TextFieldElement.class).get(4), 39, 30)
                .release().perform();
        assertLogText("Expected the drag to be ignored between elements",
                "1. VerticalLayout: left click on This is tf5");
    }

    @Test
    public void dragInAbsoluteLayout() {
        AbsoluteLayoutElement layout = $(AbsoluteLayoutElement.class).first();

        // Drag inside the first text field's caption
        new Actions(getDriver())
                .moveToElement(layout.$(TextFieldElement.class).first(), 21, 9)
                .clickAndHold().moveByOffset(-10, 0).release().perform();
        assertLogText("Mouse dragged in AbsoluteLayout",
                "1. AbsoluteLayout: left click on This is its caption");

        // Drag from a text field to another text field
        new Actions(getDriver())
                .moveToElement(layout.$(TextFieldElement.class).get(1), 54, 7)
                .clickAndHold()
                .moveToElement(layout.$(TextFieldElement.class).first(), 52, 10)
                .release().perform();
        assertLogText("Expected the drag to be ignored between elements",
                "1. AbsoluteLayout: left click on This is its caption");
    }

    @Test
    public void dragInCSSLayout() {
        CssLayoutElement layout = $(CssLayoutElement.class).first();

        // Drag inside the first text field's caption
        new Actions(getDriver())
                .moveToElement(layout.$(TextFieldElement.class).first(), 51, 7)
                .clickAndHold().moveByOffset(-20, 0).release().perform();
        assertLogText("Mouse dragged in CSSLayout",
                "1. CSSLayout: left click on This is its caption");

        // Drag from the first text field to the second text field
        new Actions(getDriver())
                .moveToElement(layout.$(TextFieldElement.class).first(), 51, 27)
                .clickAndHold()
                .moveToElement(layout.$(TextFieldElement.class).get(1), 51, 27)
                .release().perform();
        assertLogText("Expected the drag to be ignored between elements",
                "1. CSSLayout: left click on This is its caption");
    }

    private void assertLogText(String message, String expected) {
        String actual = $(LabelElement.class).first().getText();
        Assert.assertEquals(message, expected, actual);
    }
}


text:
..
  This template should be in ReSTructured text.  For help with syntax,
  see http://sphinx-doc.org/rest.html

  To test out your formatting, build the docs using tox, or see:
  http://rst.ninjs.org

  The filename in the git repository should match the launchpad URL,
  for example a URL of
  https://blueprints.launchpad.net/oslo?searchtext=awesome-thing should be
  named awesome-thing.rst.

  For specs targeted at a single project, please prefix the first line
  of your commit message with the name of the project.  For example,
  if you're submitting a new feature for oslo.config, your git commit
  message should start something like: "config: My new feature".

  Wrap text at 79 columns.

  Do not delete any of the sections in this template.  If you have
  nothing to say for a whole section, just write: None

  If you would like to provide a diagram with your spec, ascii diagrams are
  required.  http://asciiflow.com/ is a very nice tool to assist with making
  ascii diagrams.  The reason for this is that the tool used to review specs is
  based purely on plain text.  Plain text will allow review to proceed without
  having to look at additional files which can not be viewed in gerrit.  It
  will also allow inline feedback on the diagram itself.

=========================
 The title of the policy
=========================

Introduction paragraph -- why are we doing anything?

Problem Description
===================

A detailed description of the problem.

Policy
======

Here is where you cover the change you propose to make in detail. How do you
propose to solve this problem?

If the policy seeks to modify a process or workflow followed by the
team, explain how and why.

If this is one part of a larger effort make it clear where this piece ends. In
other words, what's the scope of this policy?

Alternatives & History
======================

What other ways could we do this thing? Why aren't we using those? This doesn't
have to be a full literature review, but it should demonstrate that thought has
been put into why the proposed solution is an appropriate one.

If the policy changes over time, summarize the changes here. The exact
details are always available by looking at the git history, but
summarizing them will make it easier for anyone to follow the desired
policy and understand when and why it might have changed.

Implementation
==============

Author(s)
---------

Who is leading the writing of the policy? If more than one person is
working on it, please designate the primary author and contact.

Primary author:
  <launchpad-id or None>

Other contributors:
  <launchpad-id or None>

Milestones
----------

When will the policy go into effect?

If there is a built-in deprecation period for the policy, or criteria
that would trigger it no longer being in effect, describe them.

Work Items
----------

List any concrete steps we need to take to implement the policy.

References
==========

Please add any useful references here. You are not required to have
any references. Moreover, this policy should still make sense when
your references are unavailable. Examples of what you could include
are:

* Links to mailing list or IRC discussions

* Links to notes from a summit session

* Links to relevant research, if appropriate

* Related policies as appropriate

* Anything else you feel it is worthwhile to refer to

Revision History
================

.. list-table:: Revisions
   :header-rows: 1

   * - Release Name
     - Description
   * -
     - Introduced

.. note::

  This work is licensed under a Creative Commons Attribution 3.0
  Unported License.
  http://creativecommons.org/licenses/by/3.0/legalcode


text:
dojo.provide("sketchSpaceDesigner.designer.modes.AddEllipse");

dojo.require("sketchSpaceDesigner.designer.modes.Edit");

dojo.declare("sketchSpaceDesigner.designer.modes.AddEllipse", [sketchSpaceDesigner.designer.modes.Edit], {
  enable: function () {
    this.inherited(arguments);
    this.shape = undefined;
    this.isStraightOption = new sketchSpaceDesigner.designer.widgets.OptionCheckBox({title:"Straighten [SHIFT]:", optionsPath:"isStraight", designer:this.designer});
    this.designer.ui.options.addChild(this.isStraightOption);
    this.designer.ui.options.layout();
  },
  disable: function () {
    this.inherited(arguments);
    if (this.shape !== undefined) {
      this.shape.removeShape();
    }
    this.isStraightOption.destroyRecursive();
    this.designer.ui.options.layout();
  },
  getContainerShape: function () { return this.designer.surface_transform; },
  onSetOptions: function () {
    if (this.shape !== undefined) {
      this.designer.setShapeFillAndStroke(this.shape, this.designer.options);
      this.updateShape();
    }
  },
  onKeyDown: function (event) {
    this.inherited(arguments);
    if (event.keyCode == dojo.keys.SHIFT) {
      this.designer.setOptions({isStraight: true});
    }
  },
  onKeyUp: function (event) {
    this.inherited(arguments);
    if (event.keyCode == dojo.keys.SHIFT) {
      this.designer.setOptions({isStraight: false});
    }
  },
  onMouseDown: function (event) {
    this.inherited(arguments);
    if (event.button == dojo.mouseButtons.LEFT) {
      this.mouse = this.orig = this.getCurrentMouse(event);
      this.shape = dojox.gfx.utils.deserialize(this.getContainerShape(), {shape:{type:"ellipse", cx:this.orig.x, cy:this.orig.y, rx:1, ry:1}});
      this.onSetOptions();
    }
  },
  onMouseUp: function (event) {
    this.inherited(arguments);
    if (this.shape !== undefined) {
      this.designer.registerObjectShape(this.shape);
      this.designer.saveShapeToStr(this.shape);
      this.designer.imageUpdated();
      this.shape = undefined;
    }
  },
  onMouseMove: function (event) {
    this.inherited(arguments);
    if (this.shape !== undefined) {
      this.mouse = this.getCurrentMouse(event);
      this.updateShape();
    }
  },
  updateShape: function () {
    var shapeData = this.shape.getShape();

    if (this.designer.options.isStraight) {
      shapeData.ry = shapeData.rx = Math.pow(Math.pow(Math.abs(this.mouse.x - this.orig.x), 2) + Math.pow(Math.abs(this.mouse.y - this.orig.y), 2), 1/2);
    } else {
      shapeData.rx = Math.abs(this.mouse.x - this.orig.x);
      shapeData.ry = Math.abs(this.mouse.y - this.orig.y);
    }

    this.shape.setShape(shapeData);
  }
});


text:
from __future__ import unicode_literals

import warnings
import glob, os, sys, re
import six

from django.utils.importlib import import_module

from .conf import conf

class BaseFinder(object):
    def find(self, name):
        raise NotImplementedError()

class FilesystemFinder(BaseFinder):
    @property
    def directories(self):
        return conf.JSTEMPLATE_DIRS

    @property
    def extensions(self):
        return conf.JSTEMPLATE_EXTS

    def find(self, name):
        matches = {}

        for directory in self.directories:
            for extension in self.extensions:
                self._update_matches(matches, name, directory, extension)

        return matches.items()

    def _update_matches(self, matches, pathspec, directory, extension):
        """
        Add names and paths corresponding to the given glob pattern (pathspec)
        to the mapping (matches).  Do not override existing matching entries.
        """

        lenext = len(extension) + 1  # The +1 is for the '.'
        lendir = len(directory)

        # Catch the ending '/', if it's not already accounted for
        if not directory.endswith(os.path.sep):
            lendir += 1

        normdir = os.path.normpath(directory)

        pathname = os.path.join(directory, pathspec + "." + extension)
        pathmatches = glob.glob(pathname)

        for filepath in pathmatches:
            # Remove the template directory name and the extension to
            # get the template name
            matchname = filepath[lendir:-lenext]

            # Add matchname => filepath to the mapping.  Do not override.
            if matchname not in matches:
                absfilepath = os.path.abspath(filepath)
                if absfilepath.startswith(normdir):
                    matches[matchname] = absfilepath

class FilesystemRegexFinder(BaseFinder):
    @property
    def directories(self):
        return conf.JSTEMPLATE_DIRS

    @property
    def extensions(self):
        return conf.JSTEMPLATE_EXTS

    def find(self, name):
        matches = {}

        try:
            pattern = re.compile(name + ".(?:" + '|'.join(self.extensions) + ")$")
        except re.error:
            return []

        # Bail if there are no capturing groups in the pattern
        if pattern.groups == 0:
            return []

        for directory in self.directories:
            self._update_matches(matches, directory, pattern)

        return matches.items()

    def _update_matches(self, matches, directory, pattern):
        # Walk recursively under directory and search for matches
        for root, dirs, files in os.walk(directory):
            # Build relative path to current directory, omit .
            relative_root = os.path.relpath(root, directory).replace('.', '', 1)
            for filename in files:
                # Build relative path to file
                relative_filepath = os.path.join(relative_root, filename)
                match = pattern.match(relative_filepath)
                if match is not None and match.group(1) not in matches:
                    matches[match.group(1)] = os.path.join(directory, relative_filepath)

def _get_app_template_dirs():
    fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
    ret = []
    for app in conf.INSTALLED_APPS:
        try:
            mod = import_module(app)
        except ImportError:
            warnings.warn('Installed app %s is not an importable Python module and will be ignored' % app)
            continue
        app_dir = os.path.dirname(os.path.abspath(mod.__file__))
        for dirname in conf.JSTEMPLATE_APP_DIRNAMES:
            template_dir = os.path.join(app_dir, dirname)
            if os.path.isdir(template_dir):
                if not six.PY3:
                    template_dir = template_dir.decode(fs_encoding)
                ret.append(template_dir)
    return ret

# At import time, cache the app directories to search.
app_template_dirs = _get_app_template_dirs()

class AppFinder(FilesystemFinder):
    @property
    def directories(self):
        return app_template_dirs

class AppRegexFinder(FilesystemRegexFinder):
    @property
    def directories(self):
        return app_template_dirs


text:
package org.fcrepo.utilities;

import java.io.OutputStream;
import java.io.StringReader;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * A DOM-based utility for generating FOXML 1.1 documents.
 *
 * @author Edwin Shin
 * @since 3.0
 * @version $Id$
 */
public class Foxml11Document {

    public static final String FOXML_NS="info:fedora/fedora-system:def/foxml#";

    private Document doc;

    private Element rootElement;

    private Element objectProperties;

    private final XPath xpath;

    public enum Property {
        STATE("info:fedora/fedora-system:def/model#state"),
        LABEL("info:fedora/fedora-system:def/model#label"),
        CONTENT_MODEL("info:fedora/fedora-system:def/model#contentModel"),
        CREATE_DATE("info:fedora/fedora-system:def/model#createdDate"),
        MOD_DATE("info:fedora/fedora-system:def/view#lastModifiedDate");

        private final String uri;

        Property(String uri) {
            this.uri = uri;
        }

        String uri() {
            return uri;
        }
    }

    public enum State {
        A, I, D;
    }

    public enum ControlGroup {
        X, M, E, R;
    }

    public Foxml11Document(String pid) throws Exception {

        DocumentBuilder builder = null;
        try {
            builder = XmlTransformUtility.borrowDocumentBuilder();
            DOMImplementation impl = builder.getDOMImplementation();
            doc = impl.createDocument(FOXML_NS, "foxml:digitalObject", null);
            rootElement = doc.getDocumentElement();
            rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/",
                                "xmlns:xsi",
                                "http://www.w3.org/1999/XMLSchema-instance");
            rootElement.setAttributeNS("http://www.w3.org/1999/XMLSchema-instance",
                                       "xsi:schemaLocation",
                                       "info:fedora/fedora-system:def/foxml# http://www.fedora.info/definitions/1/0/foxml1-1.xsd");
            rootElement.setAttribute("VERSION", "1.1");
            rootElement.setAttribute("PID", pid);
        } finally {
            if (builder != null) {
                XmlTransformUtility.returnDocumentBuilder(builder);
            }
        }

        NamespaceContextImpl nsCtx = new NamespaceContextImpl();
        nsCtx.addNamespace("foxml", FOXML_NS);
        XPathFactory factory = XPathFactory.newInstance();
        xpath = factory.newXPath();
        xpath.setNamespaceContext(nsCtx);

    }

    public void addObjectProperties() {
        if (objectProperties == null) {
            objectProperties =
                    doc.createElementNS(FOXML_NS, "foxml:objectProperties");
            rootElement.appendChild(objectProperties);
        }
    }

    public void addObjectProperty(Property name, String value) {
        addObjectProperties();
        Element property = doc.createElementNS(FOXML_NS, "foxml:property");
        property.setAttribute("NAME", name.uri);
        property.setAttribute("VALUE", value);
        objectProperties.appendChild(property);
    }

    public void addDatastream(String id,
                              State state,
                              ControlGroup controlGroup,
                              boolean versionable) {
        Element ds = doc.createElementNS(FOXML_NS, "foxml:datastream");
        ds.setAttribute("ID", id);
        ds.setAttribute("STATE", state.toString());
        ds.setAttribute("CONTROL_GROUP", controlGroup.toString());
        ds.setAttribute("VERSIONABLE", Boolean.toString(versionable));
        rootElement.appendChild(ds);
    }

    public void addDatastreamVersion(String dsId,
                                     String dsvId,
                                     String mimeType,
                                     String label,
                                     int size,
                                     Date created) {
        String expr = String.format("//foxml:datastream[@ID='%s']", dsId);
        try {
            NodeList nodes = (NodeList)xpath.evaluate(expr, doc, XPathConstants.NODESET);
            Node node = nodes.item(0);
            if (node == null) {
                throw new IllegalArgumentException(dsId + "does not exist.");
            }
            Element dsv = doc.createElementNS(FOXML_NS, "foxml:datastreamVersion");
            dsv.setAttribute("ID", dsvId);
            dsv.setAttribute("MIMETYPE", mimeType);
            dsv.setAttribute("LABEL", label);
            dsv.setAttribute("SIZE", Integer.toString(size));
            dsv.setAttribute("CREATED", DateUtility.convertDateToString(created));
            node.appendChild(dsv);

        } catch (XPathExpressionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void addXmlContent(String dsvId, String xmlContent) {
        DocumentBuilder builder = null;
        try {
            builder = XmlTransformUtility.borrowDocumentBuilder();
            Document contentDoc = builder.parse(new InputSource(new StringReader(xmlContent)));
            Node importedContent = doc.adoptNode(contentDoc.getDocumentElement());
            Node dsv = getDatastreamVersion(dsvId);
            Element content = doc.createElementNS(FOXML_NS, "foxml:xmlContent");
            dsv.appendChild(content);
            content.appendChild(importedContent);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (builder != null) {
                XmlTransformUtility.returnDocumentBuilder(builder);
            }
        }
    }

    public void setContentLocation(String dsvId, String ref, String type) {
        String expr = String.format("//foxml:datastreamVersion[@ID='%s']/foxml:contentLocation", dsvId);

        try {
            NodeList nodes = (NodeList)xpath.evaluate(expr, doc, XPathConstants.NODESET);
            Element location = (Element)nodes.item(0);
            if (location == null) {
                location = addContentLocation(dsvId);
            }
            location.setAttribute("REF", ref);
            location.setAttribute("TYPE", type);

        } catch (XPathExpressionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private Element addContentLocation(String dsvId) {
        Node node = getDatastreamVersion(dsvId);
        Element location = doc.createElementNS(FOXML_NS, "foxml:contentLocation");
        node.appendChild(location);
        return location;
    }

    private Node getDatastreamVersion(String dsvId) {
        String expr = String.format("//foxml:datastreamVersion[@ID='%s']", dsvId);

        try {
            NodeList nodes = (NodeList)xpath.evaluate(expr, doc, XPathConstants.NODESET);
            Node node = nodes.item(0);
            if (node == null) {
                throw new IllegalArgumentException(dsvId + "does not exist.");
            }
            return node;
        } catch (XPathExpressionException e) {
            throw new IllegalArgumentException(dsvId + "does not exist.");
        }
    }

    public void serialize(OutputStream out) throws Exception {
        final Transformer idTransform = XmlTransformUtility.getTransformer();
        Source input = new DOMSource(doc);
        Result output = new StreamResult(out);
        idTransform.transform(input, output);
    }
}


text:
package main

import (
	"log"
	"rulengine"
	"rulengine/facts"
	"rulengine/logic"
)

func main() {
	engine := rulengine.NewRuleEngine()
	engine.AddExpression("$user.age > 35", "age_larger_than_35")
	engine.AddExpression("$user.gender == male", "male")
	engine.AddExpression("$user.gender == female", "female")
	engine.AddRule(&logic.Rule{Expression: "age_larger_than_35 & male", Action: "Pass"})

	data := facts.NewFactCollection()
	user := `
		{
			"age" : 47,
			"gender" : "male"
		}
	`
	fact := facts.NewFact(user)
	data.Add("user", fact)

	exprNames := engine.GetFiredExpressions(data)
	log.Println(exprNames)

	actions := engine.GetAction(data)
	log.Println(actions)
}


text:
#include "pch.h"
#include "MainPage.xaml.h"

using namespace ColorWrap;

using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Interop;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;

using namespace ReflectionHelper;
using namespace PetzoldWindows8Controls;

MainPage::MainPage()
{
    InitializeComponent();

    // Implemented in C# assembly ReflectionHelper
    TypeInformation^ typeInfo = ref new TypeInformation(Colors::typeid);
    IIterable<PropertyInformation^>^ properties = typeInfo->DeclaredProperties;

    for each (PropertyInformation^ property in properties)
    {
        Color clr = static_cast<Color>(property->GetValue(nullptr));
        ColorItem^ colorItem = ref new ColorItem(property->Name, clr);
        wrapPanel->Children->Append(colorItem);
    }
}


text:
package sample;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import sample.webdriver.IndexPage;
import sample.webdriver.LoginPage;

import java.io.IOException;
import java.net.ServerSocket;

/**
 * @author Rob Winch
 * @since 5.0
 */
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = WebfluxFormApplication.class)
@TestPropertySource(properties = "server.port=#{T(sample.WebfluxFormApplicationTests).availablePort()}")
public class WebfluxFormApplicationTests {
	WebDriver driver;

	@Value("#{@tomcat.server.port}")
	int port;

	@Before
	public void setup() {
		this.driver = new HtmlUnitDriver(BrowserVersion.CHROME);
	}

	@Test
	public void loginWhenInvalidUsernameThenError() throws Exception {
		LoginPage login = IndexPage.to(this.driver, this.port, LoginPage.class);
		login.assertAt();

		login
			.loginForm()
			.username("invalid")
			.password("password")
			.submit(LoginPage.class)
			.assertError();
	}

	@Test
	public void loginAndLogout() throws Exception {
		LoginPage login = IndexPage.to(this.driver, this.port, LoginPage.class);
		login.assertAt();

		IndexPage index = login
			.loginForm()
				.username("user")
				.password("password")
				.submit(IndexPage.class);
		index.assertAt();

		login = index.logout();
		login
			.assertAt()
			.assertLogout();
	}

	public static final int availablePort() {
		try(ServerSocket socket = new ServerSocket(0)) {
			return socket.getLocalPort();
		} catch(IOException e) {
			throw new RuntimeException(e);
		}
	}
}


text:
int min_currentSize;
int max_currentSize;

struct Node
{
	long int d_fromsource;
	long int pnodeIndex;
	long int nodeIndex;
};

struct Node minheap[N+1];
struct Node maxheap[N+1];

void removeAll(struct Node *heap, int * currentSize);

void updateDistance(struct Node *heap,long int index,long int d,long int p,int * currentSize);
struct Node firstelement(struct Node * heap,int * currentSize);
void insert(struct Node * heap,struct Node val,int * currentSize);
struct Node removeMin(struct Node * heap, int * currentSize);
void bubbleDown(struct Node * heap,long int index,int * currentSize);
long int parent(struct Node * heap,long int index,int * currentSize);
void bubbleUp(struct Node * heap,long int index,int * currentSize);
void swap(struct Node * heap,long int index1,long int index2, int * currentSize);
void bdown(struct Node * heap,long int index, int * currentSize);


text:
class ColorUtil
{
public:

    static tVector3f ColorToHSV(const tColor4f& color);
    static tColor4f HSVToColor(const tVector3f& hsv);
    static tColor4f HSVToColor(float h, float s, float v);
};


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=fn.SDL_Error.html">

Redirecting to fn.SDL_Error.html...


text:
module RedHillConsulting::Core::ActiveRecord::ConnectionAdapters
  module MysqlColumn
    def initialize(name, default, sql_type = nil, null = true)
      default = nil if !null && default.blank?
      super
    end
  end
end


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sindice.fusepooladapter;

import eu.fusepool.datalifecycle.Interlinker;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.apache.clerezza.rdf.core.MGraph;
import org.apache.clerezza.rdf.core.TripleCollection;
import org.apache.clerezza.rdf.core.serializedform.Parser;
import org.apache.clerezza.rdf.core.serializedform.SupportedFormat;
import org.apache.stanbol.commons.indexedgraph.IndexedMGraph;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

/**
 *
 * @author Reto
 */
@Component(service = Object.class, immediate = true, property = {"javax.ws.rs=true"})
@Path("duke-linker")
public class Runner {

    private Interlinker linker;
    private Parser parser;

    @Activate
    public void activator() throws Exception {
    }

    @GET
    public String test() throws Exception {
        MGraph mGraph = new IndexedMGraph();
        parser.parse(mGraph,getClass().getResourceAsStream("patent-data-sample-short.ttl"), SupportedFormat.TURTLE);
        TripleCollection interlinks = linker.interlink(mGraph, mGraph);
        return "found "+interlinks.size()+" links in patent-data-sample-short.ttl";
    }

    @Reference(target = "(component.name=com.sindice.fusepooladapter.LinkerAdapter)")
    public void setLinker(Interlinker linker) {
        this.linker = linker;
    }
    public void unsetLinker(Interlinker linker) {
        this.linker = null;
    }

    @Reference
    public void setParser(Parser parser) {
        this.parser = parser;
    }
    public void unsetParser(Parser parser) {
        this.parser = null;
    }

}


text:
package org.appenders.log4j2.elasticsearch.hc;

import org.appenders.log4j2.elasticsearch.ItemSource;

public interface ItemSourceWriter<T> {

    ItemSource<T> write(ItemSource<T> itemSource, byte[] bytes);

}


text:
namespace Stripe
{
    public class InvoiceDeleteOptions : BaseOptions
    {
    }
}


text:
require 'spree_core'
require 'spree_my_theme/engine'