text:
<?php

/**
 * Base static class for performing query and update operations on the 'sf_guard_group' table.
 *
 *
 *
 * This class was autogenerated by Propel 1.3.0-dev on:
 *
 * Sat May 29 00:26:27 2010
 *
 * @package    lib.model.om
 */
abstract class BaseSfGuardGroupPeer {

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

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

	/** A class that can be returned by this peer. */
	const CLASS_DEFAULT = 'lib.model.SfGuardGroup';

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

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

	/** the column name for the ID field */
	const ID = 'sf_guard_group.ID';

	/** the column name for the NAME field */
	const NAME = 'sf_guard_group.NAME';

	/** the column name for the DESCRIPTION field */
	const DESCRIPTION = 'sf_guard_group.DESCRIPTION';

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

	/**
	 * The MapBuilder instance for this peer.
	 * @var        MapBuilder
	 */
	private static $mapBuilder = null;

	/**
	 * holds an array of fieldnames
	 *
	 * first dimension keys are the type constants
	 * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
	 */
	private static $fieldNames = array (
		BasePeer::TYPE_PHPNAME => array ('Id', 'Name', 'Description', ),
		BasePeer::TYPE_STUDLYPHPNAME => array ('id', 'name', 'description', ),
		BasePeer::TYPE_COLNAME => array (self::ID, self::NAME, self::DESCRIPTION, ),
		BasePeer::TYPE_FIELDNAME => array ('id', 'name', 'description', ),
		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
	 */
	private static $fieldKeys = array (
		BasePeer::TYPE_PHPNAME => array ('Id' => 0, 'Name' => 1, 'Description' => 2, ),
		BasePeer::TYPE_STUDLYPHPNAME => array ('id' => 0, 'name' => 1, 'description' => 2, ),
		BasePeer::TYPE_COLNAME => array (self::ID => 0, self::NAME => 1, self::DESCRIPTION => 2, ),
		BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'name' => 1, 'description' => 2, ),
		BasePeer::TYPE_NUM => array (0, 1, 2, )
	);

	/**
	 * Get a (singleton) instance of the MapBuilder for this peer class.
	 * @return     MapBuilder The map builder for this peer
	 */
	public static function getMapBuilder()
	{
		if (self::$mapBuilder === null) {
			self::$mapBuilder = new SfGuardGroupMapBuilder();
		}
		return self::$mapBuilder;
	}
	/**
	 * 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. SfGuardGroupPeer::COLUMN_NAME).
	 * @return     string
	 */
	public static function alias($alias, $column)
	{
		return str_replace(SfGuardGroupPeer::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 object containing the columns to add.
	 * @throws     PropelException Any exceptions caught during processing will be
	 *		 rethrown wrapped into a PropelException.
	 */
	public static function addSelectColumns(Criteria $criteria)
	{

		$criteria->addSelectColumn(SfGuardGroupPeer::ID);

		$criteria->addSelectColumn(SfGuardGroupPeer::NAME);

		$criteria->addSelectColumn(SfGuardGroupPeer::DESCRIPTION);

	}

	/**
	 * 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(SfGuardGroupPeer::TABLE_NAME);

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

		if (!$criteria->hasSelectClause()) {
			SfGuardGroupPeer::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(SfGuardGroupPeer::DATABASE_NAME, Propel::CONNECTION_READ);
		}

    foreach (sfMixer::getCallables('BaseSfGuardGroupPeer:doCount:doCount') as $callable)
    {
      call_user_func($callable, 'BaseSfGuardGroupPeer', $criteria, $con);
    }

		// 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;
	}
	/**
	 * Method to select one object from the DB.
	 *
	 * @param      Criteria $criteria object used to create the SELECT statement.
	 * @param      PropelPDO $con
	 * @return     SfGuardGroup
	 * @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 = SfGuardGroupPeer::doSelect($critcopy, $con);
		if ($objects) {
			return $objects[0];
		}
		return null;
	}
	/**
	 * Method to do selects.
	 *
	 * @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 SfGuardGroupPeer::populateObjects(SfGuardGroupPeer::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)
	{

    foreach (sfMixer::getCallables('BaseSfGuardGroupPeer:doSelectStmt:doSelectStmt') as $callable)
    {
      call_user_func($callable, 'BaseSfGuardGroupPeer', $criteria, $con);
    }

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

		if (!$criteria->hasSelectClause()) {
			$criteria = clone $criteria;
			SfGuardGroupPeer::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      SfGuardGroup $value A SfGuardGroup object.
	 * @param      string $key (optional) key to use for instance map (for performance boost if key was already calculated externally).
	 */
	public static function addInstanceToPool(SfGuardGroup $obj, $key = null)
	{
		if (Propel::isInstancePoolingEnabled()) {
			if ($key === null) {
				$key = (string) $obj->getId();
			} // 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 SfGuardGroup object or a primary key value.
	 */
	public static function removeInstanceFromPool($value)
	{
		if (Propel::isInstancePoolingEnabled() && $value !== null) {
			if (is_object($value) && $value instanceof SfGuardGroup) {
				$key = (string) $value->getId();
			} elseif (is_scalar($value)) {
				// assume we've been passed a primary key
				$key = (string) $value;
			} else {
				$e = new PropelException("Invalid value passed to removeInstanceFromPool().  Expected primary key or SfGuardGroup 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     SfGuardGroup 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();
	}

	/**
	 * 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 + 0] === null) {
			return null;
		}
		return (string) $row[$startcol + 0];
	}

	/**
	 * 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 = SfGuardGroupPeer::getOMClass();
		$cls = substr('.'.$cls, strrpos('.'.$cls, '.') + 1);
		// populate the object(s)
		while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
			$key = SfGuardGroupPeer::getPrimaryKeyHashFromRow($row, 0);
			if (null !== ($obj = SfGuardGroupPeer::getInstanceFromPool($key))) {
				// We no longer rehydrate the object, since this can cause data loss.
				// See http://propel.phpdb.org/trac/ticket/509
				// $obj->hydrate($row, 0, true); // rehydrate
				$results[] = $obj;
			} else {

				$obj = new $cls();
				$obj->hydrate($row);
				$results[] = $obj;
				SfGuardGroupPeer::addInstanceToPool($obj, $key);
			} // if key exists
		}
		$stmt->closeCursor();
		return $results;
	}

  static public function getUniqueColumnNames()
  {
    return array(array('name'));
  }
	/**
	 * 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);
	}

	/**
	 * The class that the Peer will make instances of.
	 *
	 * This 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')
	 *
	 * @return     string path.to.ClassName
	 */
	public static function getOMClass()
	{
		return SfGuardGroupPeer::CLASS_DEFAULT;
	}

	/**
	 * Method perform an INSERT on the database, given a SfGuardGroup or Criteria object.
	 *
	 * @param      mixed $values Criteria or SfGuardGroup 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)
	{

    foreach (sfMixer::getCallables('BaseSfGuardGroupPeer:doInsert:pre') as $callable)
    {
      $ret = call_user_func($callable, 'BaseSfGuardGroupPeer', $values, $con);
      if (false !== $ret)
      {
        return $ret;
      }
    }

		if ($con === null) {
			$con = Propel::getConnection(SfGuardGroupPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
		}

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

		if ($criteria->containsKey(SfGuardGroupPeer::ID) && $criteria->keyContainsValue(SfGuardGroupPeer::ID) ) {
			throw new PropelException('Cannot insert a value for auto-increment primary key ('.SfGuardGroupPeer::ID.')');
		}

		// 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;
		}

    foreach (sfMixer::getCallables('BaseSfGuardGroupPeer:doInsert:post') as $callable)
    {
      call_user_func($callable, 'BaseSfGuardGroupPeer', $values, $con, $pk);
    }

    return $pk;
	}

	/**
	 * Method perform an UPDATE on the database, given a SfGuardGroup or Criteria object.
	 *
	 * @param      mixed $values Criteria or SfGuardGroup 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)
	{

    foreach (sfMixer::getCallables('BaseSfGuardGroupPeer:doUpdate:pre') as $callable)
    {
      $ret = call_user_func($callable, 'BaseSfGuardGroupPeer', $values, $con);
      if (false !== $ret)
      {
        return $ret;
      }
    }

		if ($con === null) {
			$con = Propel::getConnection(SfGuardGroupPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
		}

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

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

			$comparison = $criteria->getComparison(SfGuardGroupPeer::ID);
			$selectCriteria->add(SfGuardGroupPeer::ID, $criteria->remove(SfGuardGroupPeer::ID), $comparison);

		} else { // $values is SfGuardGroup 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);

		$ret = BasePeer::doUpdate($selectCriteria, $criteria, $con);

    foreach (sfMixer::getCallables('BaseSfGuardGroupPeer:doUpdate:post') as $callable)
    {
      call_user_func($callable, 'BaseSfGuardGroupPeer', $values, $con, $ret);
    }

    return $ret;
  }

	/**
	 * Method to DELETE all rows from the sf_guard_group table.
	 *
	 * @return     int The number of affected rows (if supported by underlying database driver).
	 */
	public static function doDeleteAll($con = null)
	{
		if ($con === null) {
			$con = Propel::getConnection(SfGuardGroupPeer::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(SfGuardGroupPeer::TABLE_NAME, $con);
			$con->commit();
			return $affectedRows;
		} catch (PropelException $e) {
			$con->rollBack();
			throw $e;
		}
	}

	/**
	 * Method perform a DELETE on the database, given a SfGuardGroup or Criteria object OR a primary key value.
	 *
	 * @param      mixed $values Criteria or SfGuardGroup 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(SfGuardGroupPeer::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.
			SfGuardGroupPeer::clearInstancePool();

			// rename for clarity
			$criteria = clone $values;
		} elseif ($values instanceof SfGuardGroup) {
			// invalidate the cache for this single object
			SfGuardGroupPeer::removeInstanceFromPool($values);
			// create criteria based on pk values
			$criteria = $values->buildPkeyCriteria();
		} else {
			// it must be the primary key

			$criteria = new Criteria(self::DATABASE_NAME);
			$criteria->add(SfGuardGroupPeer::ID, (array) $values, Criteria::IN);

			foreach ((array) $values as $singleval) {
				// we can invalidate the cache for this single object
				SfGuardGroupPeer::removeInstanceFromPool($singleval);
			}
		}

		// 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);

			$con->commit();
			return $affectedRows;
		} catch (PropelException $e) {
			$con->rollBack();
			throw $e;
		}
	}

	/**
	 * Validates all modified columns of given SfGuardGroup 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      SfGuardGroup $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(SfGuardGroup $obj, $cols = null)
	{
		$columns = array();

		if ($cols) {
			$dbMap = Propel::getDatabaseMap(SfGuardGroupPeer::DATABASE_NAME);
			$tableMap = $dbMap->getTable(SfGuardGroupPeer::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 {

		}

		$res =  BasePeer::doValidate(SfGuardGroupPeer::DATABASE_NAME, SfGuardGroupPeer::TABLE_NAME, $columns);
    if ($res !== true) {
        $request = sfContext::getInstance()->getRequest();
        foreach ($res as $failed) {
            $col = SfGuardGroupPeer::translateFieldname($failed->getColumn(), BasePeer::TYPE_COLNAME, BasePeer::TYPE_PHPNAME);
        }
    }

    return $res;
	}

	/**
	 * Retrieve a single object by pkey.
	 *
	 * @param      int $pk the primary key.
	 * @param      PropelPDO $con the connection to use
	 * @return     SfGuardGroup
	 */
	public static function retrieveByPK($pk, PropelPDO $con = null)
	{

		if (null !== ($obj = SfGuardGroupPeer::getInstanceFromPool((string) $pk))) {
			return $obj;
		}

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

		$criteria = new Criteria(SfGuardGroupPeer::DATABASE_NAME);
		$criteria->add(SfGuardGroupPeer::ID, $pk);

		$v = SfGuardGroupPeer::doSelect($criteria, $con);

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

	/**
	 * Retrieve multiple objects by pkey.
	 *
	 * @param      array $pks List of primary keys
	 * @param      PropelPDO $con the connection to use
	 * @throws     PropelException Any exceptions caught during processing will be
	 *		 rethrown wrapped into a PropelException.
	 */
	public static function retrieveByPKs($pks, PropelPDO $con = null)
	{
		if ($con === null) {
			$con = Propel::getConnection(SfGuardGroupPeer::DATABASE_NAME, Propel::CONNECTION_READ);
		}

		$objs = null;
		if (empty($pks)) {
			$objs = array();
		} else {
			$criteria = new Criteria(SfGuardGroupPeer::DATABASE_NAME);
			$criteria->add(SfGuardGroupPeer::ID, $pks, Criteria::IN);
			$objs = SfGuardGroupPeer::doSelect($criteria, $con);
		}
		return $objs;
	}

} // BaseSfGuardGroupPeer

// This is the static code needed to register the MapBuilder for this table with the main Propel class.
//
// NOTE: This static code cannot call methods on the SfGuardGroupPeer class, because it is not defined yet.
// If you need to use overridden methods, you can add this code to the bottom of the SfGuardGroupPeer class:
//
// Propel::getDatabaseMap(SfGuardGroupPeer::DATABASE_NAME)->addTableBuilder(SfGuardGroupPeer::TABLE_NAME, SfGuardGroupPeer::getMapBuilder());
//
// Doing so will effectively overwrite the registration below.

Propel::getDatabaseMap(BaseSfGuardGroupPeer::DATABASE_NAME)->addTableBuilder(BaseSfGuardGroupPeer::TABLE_NAME, BaseSfGuardGroupPeer::getMapBuilder());


text:
const request = require('request');
const config = require('./../config');

let requestAmount = 0;
const requestLimit = 60;
setInterval(() => { requestAmount = 0; }, 60000);

const locationController = {
  /**
   * Check if a location already exists
   *
   * @param {object} db
   * @param {string} location
   * @param {function} foundCallback
   * @param {function} notFoundCallback
   */
  checkDouble: (db, location, foundCallback, notFoundCallback) => {
    const collection = db.collection('status');
    const filter = { name: location };
    const callback = (err, result) => {
      if (result !== null) {
        foundCallback(result);
      } else {
        notFoundCallback(result);
      }
    };
    collection.findOne(filter, callback);
  },

  /**
   * Get the status of a single location.
   *
   * @param {object} db
   * @param {object} body
   * @param {function} returnCallback
   */
  getSingle: (db, { location }, returnCallback) => {
    // Check if the location already exists
    locationController.checkDouble(db, location, returnCallback, () => {
      // Request the location if it doesn't exist
      locationController.requestSingle(db, location, returnCallback);
    });
  },

  /**
   * Request the status of a single location from the API.
   *
   * @param {object} db
   * @param {string} location
   * @param {function} callback
   */
  requestSingle: (db, location, callback) => {
    requestAmount += 1;
    if (requestAmount >= requestLimit) {
      const warning = 'API limit reached, please try again in a minute!';
      callback(JSON.stringify({ warning }));
      return;
    }

    const headers = {
      'Content-Type': 'application/json',
    };
    const options = {
      url: `${config.owm.url}/weather?q=${location}&appid=${config.owm.KEY}&units=metric`,
      method: 'GET',
      headers,
    };
    request(options, (error, response, body) => {
      const parsedBody = JSON.parse(body);
      locationController.checkDouble(db, parsedBody.name, callback, () => {
        locationController.addLocation(db, parsedBody);
        locationController.addStatus(db, parsedBody);
        callback(JSON.stringify(locationController.getStatus(parsedBody)));
      });
    });
  },

  /**
   * Get the status of multiple locations.
   *
   * @param {object} db
   * @param {object} body
   * @param {function} returnCallback
   */
  getMultiple: (db, { locations }, returnCallback) => {
    const collection = db.collection('status');
    const filter = { id: { $in: locations } };
    const callback = (err, result) => {
      result.toArray().then((response) => {
        const returnValue = [];
        response.forEach(({ id, name, description, temp, icon }) => {
          returnValue.push({ id, name, description, temp, icon });
        });
        returnCallback(JSON.stringify(returnValue));
      });
    };
    collection.find(filter, callback);
  },

  /**
   * Request the status of multiple locations from the API.
   *
   * @param {object} db
   * @param {array} locations
   * @param {function} callback
   */
  requestMultiple: (db, locations, callback) => {
    requestAmount += 1;
    if (requestAmount >= requestLimit) {
      callback(null);
      return;
    }
    const headers = {
      'Content-Type': 'application/json',
    };
    const options = {
      url: `${config.owm.url}/group?id=${locations.join(',')}&appid=${config.owm.KEY}&units=metric`,
      method: 'GET',
      headers,
    };
    request(options, (error, response, body) => {
      const parsedBody = JSON.parse(body);
      if (typeof parsedBody.list !== 'undefined') {
        for (let i = 0; i < parsedBody.list.length; i += 1) {
          locationController.addStatus(db, parsedBody.list[i]);
        }
      }
      callback(parsedBody);
    });
  },

  /**
   * Add a new location to the collection.
   *
   * @param {object} db
   * @param {object} location
   */
  addLocation: (db, { id, name, coord }) => {
    const collection = db.collection('locations');
    const { lat, lon } = coord;
    collection.insert({ id, name, lat, lon });
  },

  /**
   * Add a new status to the collection.
   *
   * @param {object} db
   * @param {object} status
   */
  addStatus: (db, { id, name, weather, main }) => {
    const collection = db.collection('status');
    const { description, icon } = weather[0];
    const { temp } = main;
    const filter = { id };
    const update = { $set: { temp, description, icon } };
    const callback = (err, result) => {
      if (result.value === null) collection.insert({ id, name, temp, description, icon });
    };
    collection.findOneAndUpdate(filter, update, callback);
  },

  /**
   * Get the status of a single location.
   *
   * @param {object} status
   */
  getStatus: ({ id, name, weather, main }) => {
    const { description, icon } = weather[0];
    const { temp } = main;
    return { id, name, temp, description, icon };
  },
};

module.exports = locationController;

redpajama_set_name: RedPajamaGithub


text: <meta http-equiv="refresh" content="0; url=Threads.html#thread%20numbers">


text:
import * as variantsView from './variantsViewTypes';

export {variantsView};


text:
(function (angular) {
  'use strict';

  angular.module('pickadate', []);

  angular.module('pickadate').directive('pickADate', ['$parse', '$timeout', function ($parse, $timeout) {
    return {
      restrict: 'A',
      link: function (scope, element, attrs) {
        var model = {
          pickADate: $parse(attrs.pickADate),
          minDate: $parse(attrs.minDate),
          maxDate: $parse(attrs.maxDate),
          pickADateOptions: $parse(attrs.pickADateOptions),
          dateType: attrs.dateType,
          callBack: $parse(attrs.callBack)
        };

        var userOptions = model.pickADateOptions(scope) || {};
        var options = angular.extend({}, userOptions);
        var dateType = model.dateType;
        options.onSet = function (e) {
          if (userOptions && userOptions.onSet) {
            userOptions.onSet.apply(this, arguments);
          }
          var select = element.pickadate('picker').get('select'); // selected date

          scope.$evalAsync(function () {
            if (e.hasOwnProperty('clear')) {
              model.pickADate.assign(scope, null);
              return;
            }
            if (select) {
              var date = model.pickADate(scope);
              if (!date) {
                date = new Date(0);
                model.pickADate.assign(scope, date);
              }
              date.setYear(select.obj.getFullYear());
              date.setDate(select.obj.getDate());
              date.setMonth(select.obj.getMonth());
            } else {
              model.pickADate.assign(scope, select);
            }
          });
        };

        options.onClose = function () {
          if (userOptions && userOptions.onClose) {
            userOptions.onClose.apply(this, arguments);
          }
          element.blur();
        };

        element.pickadate(options);
        function updateValue(newValue) {
          if (newValue) {
            var date = (newValue instanceof Date) ? newValue : new Date(newValue);
            element.pickadate('picker').set('select', date.getTime());
            model.pickADate.assign(scope, date);
            if(dateType=='daily'){
               scope.$emit('dSet');
            }
             else if(dateType=='weekly'){
               scope.$emit('wSet');
             }
          } else {
            element.pickadate('picker').clear();
            model.pickADate.assign(scope, null);
          }
        }

        updateValue(model.pickADate(scope));
        var minDate = model.minDate(scope);
        var maxDate = model.maxDate(scope);
        element.pickadate('picker').set('min', minDate ? minDate : false);
        element.pickadate('picker').set('max', maxDate ? maxDate : false);
        element.pickadate('picker').on('close', function(){
          if(model.callBack!=null){
            $timeout(function(){
              scope.$eval(model.callBack);
            });
          }
        });
        scope.$watch(attrs.pickADate, function (newValue, oldValue) {
          if (newValue === oldValue) {
            return;
          }
          updateValue(newValue);
        }, true);
        scope.$watch(attrs.minDate, function (newValue) {
          element.pickadate('picker').set('min', newValue ? newValue : false);
        }, true);
        scope.$watch(attrs.maxDate, function (newValue) {
          element.pickadate('picker').set('max', newValue ? newValue : false);
        }, true);
      }
    };
  }]);

  angular.module('pickadate').directive('pickATime', ['$parse',function ($parse) {
    return {
      restrict: 'A',
      link: function (scope, element, attrs) {
        var model = {
          pickATime: $parse(attrs.pickATime),
          pickATimeOptions: $parse(attrs.pickATimeOptions)
        };

        var userOptions = model.pickATimeOptions(scope) || {};
        var options = angular.extend({}, userOptions);

        options.onSet = function (e) {
          if (userOptions && userOptions.onSet) {
            userOptions.onSet.apply(this, arguments);
          }
          var select = element.pickatime('picker').get('select'); // selected date

          scope.$evalAsync(function () {
            if (e.hasOwnProperty('clear')) {
              model.pickATime.assign(scope, null);
              return;
            }
            if (select) {
              var date = model.pickATime(scope);
              if (!date) {
                date = new Date(0);
                model.pickATime.assign(scope, date);
              }
              date.setHours(select.hour);
              date.setMinutes(select.mins);
              date.setSeconds(0);
              date.setMilliseconds(0);
            } else {
              model.pickATime.assign(scope, select);
            }
          });
        };

        options.onClose = function () {
          if (userOptions && userOptions.onClose) {
            userOptions.onClose.apply(this, arguments);
          }
          element.blur();
        };

        element.pickatime(options);
        function updateValue(newValue) {
          if (newValue) {
            var date = (newValue instanceof Date) ? newValue : new Date(newValue);
            var totalMins = date.getHours() * 60 + date.getMinutes();
            element.pickatime('picker').set('select', totalMins);
            model.pickATime.assign(scope, date);
          } else {
            element.pickatime('picker').clear();
            model.pickATime.assign(scope, null);
          }
        }

        updateValue(model.pickATime(scope));
        scope.$watch(attrs.pickATime, function (newValue, oldValue) {
          if (newValue === oldValue) {
            return;
          }
          updateValue(newValue);
        }, true);
      }
    };
  }]);
})(angular);


text:
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../../../shared/continuation/new', __FILE__)

with_feature :continuation_library do
  require 'continuation'

  describe "Continuation.new" do
    it_behaves_like :continuation_new, :new
  end
end


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class RaceFinishUIText : MonoBehaviour
{

    private Text uiText;

    private Animator textAnimator;

    private const string finishedText = "FINISHED!";

    private void Start()
    {
        uiText = GetComponent<Text>();
        textAnimator = GetComponent<Animator>();
    }

    private void OnRaceFinished()
    {
        uiText.text = finishedText;
        textAnimator.SetBool("raceFinished", true);
    }

    private void OnEnable()
    {
        Checkpoint.RaceFinished += OnRaceFinished;
    }

    private void OnDisable()
    {
        Checkpoint.RaceFinished -= OnRaceFinished;
    }
}


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Windows.Media.Animation
{
  abstract public partial class VectorKeyFrame : System.Windows.Freezable, IKeyFrame
  {
    #region Methods and constructors
    public System.Windows.Vector InterpolateValue(System.Windows.Vector baseValue, double keyFrameProgress)
    {
      return default(System.Windows.Vector);
    }

    protected abstract System.Windows.Vector InterpolateValueCore(System.Windows.Vector baseValue, double keyFrameProgress);

    protected VectorKeyFrame()
    {
    }

    protected VectorKeyFrame(System.Windows.Vector value)
    {
    }

    protected VectorKeyFrame(System.Windows.Vector value, KeyTime keyTime)
    {
    }
    #endregion

    #region Properties and indexers
    public KeyTime KeyTime
    {
      get
      {
        return default(KeyTime);
      }
      set
      {
      }
    }

    Object System.Windows.Media.Animation.IKeyFrame.Value
    {
      get
      {
        return default(Object);
      }
      set
      {
      }
    }

    public System.Windows.Vector Value
    {
      get
      {
        return default(System.Windows.Vector);
      }
      set
      {
      }
    }
    #endregion

    #region Fields
    public readonly static System.Windows.DependencyProperty KeyTimeProperty;
    public readonly static System.Windows.DependencyProperty ValueProperty;
    #endregion
  }
}


text:
<?php

namespace Lexide\PuzzleDI\Compiler;

abstract class AbstractPuzzleConfig
{

    protected static $configList = [];

    public static function getConfigPaths($key) {
        if (empty(static::$configList[$key])) {
            // return an empty array
            return [];
        }
        return static::$configList[$key];
    }

}


text:
EA4S - Antura and the Letters
=================
the full Unity3D project
by CGL / VGWB / Wixel

the developer docs are here: [/Docs/](https://github.com/VGWB/EA4S_Antura_U3D/tree/master/docs)

## Licensing

read LICENSE.md


text:
package ru.atom.files;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.atom.exception.ExceptionHandler;

import java.util.List;

import static junit.framework.Assert.assertEquals;

public class ResourceReadTest {
    private static final Logger log = LoggerFactory.getLogger(ExceptionHandler.class);

    @Test
    public void testReadResource() throws Exception {
        List<String> lines = ResourceReader.readFromResource("FileToRead.txt");
        lines.stream()
                .filter(s -> !s.isEmpty())
                .map(String::trim)
                .forEach(System.out::println);
        assertEquals(2, lines.size());
    }
}


text:
"""
Set of Classifiers
"""

import copy

require_tests = {
    "none": lambda identified, total: identified == 0,
    "one":  lambda identified, total: identified == 1,
    "any":  lambda identified, total: identified > 0,
    "all":  lambda identified, total: identified == total
}

class ClassifierSet(object):

    """
    Class that holds and processes identifiers
    """

    def __init__(self,
                 fodder,           # Set of classifiers as read from a limit file
                 identifiers       # An IdentifierSet
                 ):

        self.classifiers = {}

        # Create a summary of what the classifiers want

        for classifier in fodder:

            name = classifier["name"]
            if name in self.classifiers:
                raise ValueError("Duplicate classifier '%s'" % name)

            # Make sure all of the identifiers called for
            class_identifiers = classifier["identifiers"]
            missing = list(filter(
                lambda identifier: identifier not in identifiers,
                list(class_identifiers)
            ))
            if missing:
                raise ValueError("Unknown identifiers: %s" % (", ".join(missing)))

            self.classifiers[name] = {
                "identifiers": class_identifiers,
                "check_count": require_tests[classifier.get("require", "any")]
            }

    def __contains__(self, name):
        return name in self.classifiers

    def classifications(self,
                 identifiers  # List of identifiers to classify
                 ):

        """
        Given a set of identifiers, return a list of the classifications
        they fall into.
        """

        identifier_lookup = dict([ (name, 1) for name in identifiers ])

        classified = []

        for name in self.classifiers:
            classifier = self.classifiers[name]
            met = (list(filter(lambda value: value in identifier_lookup, classifier["identifiers"])))
            if classifier["check_count"](len(met), len(classifier["identifiers"])):
                classified.append(name)

        # TODO: Is there any reason to sort this for consistency?
        return classified

# A short test program

if __name__ == "__main__":

    cset = ClassifierSet([
        {
            "name": "neither",
            "description": "Neither odd nor even",
            "identifiers": [ "0" ]
        },
        {
            "name": "odd",
            "description": "Odd",
            "identifiers": [ "1", "3", "5", "7", "9" ],
        },
        {
            "name": "even",
            "description": "Even",
            "identifiers": [ "2", "4", "6", "8", "10" ],
        },
        {
            "name": "small",
            "description": "small numbers",
            "identifiers": [ "1", "2", "3" ],
        },
        {
            "name": "no-small",
            "description": "No small numbers",
            "identifiers": [ "1", "2", "3" ],
            "require": "none"
        },
        {
            "name": "one-small",
            "description": "Small odd numbers.",
            "identifiers": [ "1", "2", "3" ],
            "require": "one"
        },
        {
            "name": "small-odd",
            "description": "Small odd numbers.",
            "identifiers": [ "1", "3" ],
            "require": "any"
        },
        {
            "name": "set-of-three",
            "description": "Some set of three.",
            "identifiers": [ "4", "5", "6" ],
            "require": "all"
        }
        ],
        {
            "0": 0,
            "1": 1,
            "2": 2,
            "3": 3,
            "4": 4,
            "5": 5,
            "6": 6,
            "7": 7,
            "8": 8,
            "9": 9,
            "10": 10
        }
    )

    idents = ["3", "5", "7"]
    for num in range(0,10):
        print(idents, '->', cset.classifications(idents))
        idents.append(str(num))

    while len(idents):
        del idents[0]
        print(idents, '->', cset.classifications(idents))


text:
Rails.application.routes.draw do

  devise_for :users, :controllers => { :omniauth_callbacks => "omniauth_callbacks" }
  root 'lessons#index'

  # Limit lessons action to index and show for the time being
  resources :lessons, only: [:index, :show]
  resources :users

  post 'lessons/submit', to: 'lessons#submit'
end


text:
use super::Config;

use std::borrow::Cow;
use url::Url;
use parser_nom::NomBytes;
use primitives::{Protocol, Rabbitmq9_1};

use channel;
use session::BlockingSession;
use session::auth::{Authenticator, PlainAuthenticator};
use super::ParseUrlError;

type DefaultAuthenticator = PlainAuthenticator<'static>;
type DefaultProtocol = Rabbitmq9_1;

/// Provides an interface to build a session configuration (`SessionConfig`)
#[derive(Debug, Clone, PartialEq)]
pub struct ConfigBuilder<'config, S, A, C>
    where A: Authenticator,
          C: channel::IdStrategy
{
    config: Config<'config, S, A, C>
}

impl<'config> ConfigBuilder<'config, Rabbitmq9_1, PlainAuthenticator<'config>, channel::DefaultIdStrategy> {
    pub fn parse_url<U>(url: U) -> Result<Self, ParseUrlError>
        where U: AsRef<str>
    {
        let parsed = try!(Url::parse(url.as_ref()));

        let mut config = match parsed.scheme() {
            "amqps" => Self::with_tls(),
            "amqp" => Self::without_tls(),
            invalid_scheme => return Err(ParseUrlError::InvalidScheme(invalid_scheme.to_string())),
        };

        if let Some(host) = parsed.host_str() {
            config = config.host(host.to_string());
        }
        if let Some(port) = parsed.port() {
            config = config.port(port);
        }

        match parsed.path() {
            "" => (),
            virtual_host => config = config.virtual_host(virtual_host.to_string())
        }

        let username = parsed.username();
        let password = parsed.password().unwrap_or("");
        config = config.plain_auth(username.to_string(), password.to_string());

        Ok(config)
    }

    pub fn without_tls() -> Self {
        ConfigBuilder {
            config: Config::new("localhost", 5671, "/", false)
        }
    }

    pub fn with_tls() -> Self {
        ConfigBuilder {
            config: Config::new("localhost", 5672, "/", true)
        }
    }
}

impl<'config, P, A, C> ConfigBuilder<'config, P, A, C>
    where A: Authenticator,
          C: channel::IdStrategy
{
    pub fn into_blocking(self) -> BlockingSession<'config, P, A, C> {
        BlockingSession::from_config(self.into())
    }
}

impl<'config, P, A, C> ConfigBuilder<'config, P, A, C>
    where A: Authenticator,
          C: channel::IdStrategy
{
    pub fn host<H>(mut self, host: H) -> Self
        where H: Into<Cow<'config, str>>
    {
        self.config.host = host.into();
        self
    }

    pub fn port(mut self, port: u16) -> Self {
        self.config.port = port.into();
        self
    }

    pub fn virtual_host<V>(mut self, virtual_host: V) -> Self
        where V: Into<Cow<'config, str>>
    {
        self.config.virtual_host = virtual_host.into();
        self
    }

    pub fn use_tls(mut self, use_tls: bool) -> Self {
        self.config.use_tls = use_tls;
        self
    }

    pub fn locale<L>(mut self, locale: L) -> Self
        where L: Into<Cow<'config, str>>
    {
        self.config.locale = locale.into();
        self
    }

    pub fn channel_max(mut self, channel_max: u16) -> Self {
        self.config.channel_max = channel_max;
        self
    }

    pub fn plain_auth<T, U>(self, username: T, password: U) -> ConfigBuilder<'config, P, PlainAuthenticator<'config>, C>
        where T: Into<Cow<'config, str>>,
              U: Into<Cow<'config, str>>
    {
        let authenticator = PlainAuthenticator::new("", username.into(), password.into());
        ConfigBuilder {
            config: self.config.with_authenticator(authenticator)
        }
    }

    pub fn with_protocol<'a, SS>(self) -> ConfigBuilder<'config, SS, A, C>
        where SS: Protocol<'a>
    {
        ConfigBuilder {
            config: self.config.with_protocol::<SS>()
        }
    }

    pub fn with_authenticator<T, U>(self, authenticator: U) -> ConfigBuilder<'config, P, T, C>
        where T: Authenticator,
              U: Into<T>
    {
        ConfigBuilder {
            config: self.config.with_authenticator(authenticator)
        }
    }

    pub fn with_channel_id_strategy<T, U>(self, channel_id_strategy: U) -> ConfigBuilder<'config, P, A, T>
        where T: channel::IdStrategy,
              U: Into<T>
    {
        ConfigBuilder {
            config: self.config.with_channel_id_strategy(channel_id_strategy)
        }
    }
}

impl<'config, P, A, C> From<ConfigBuilder<'config, P, A, C>> for Config<'config, P, A, C>
    where A: Authenticator,
          C: channel::IdStrategy
{
    fn from(config: ConfigBuilder<'config, P, A, C>) -> Self {
        config.config
    }
}


text:
<?php

namespace Application\Util;

use Application\Core\Datasource;
use Application\Models\Book;
use Application\Models\Category;
use Application\Models\People;
use Application\Models\Publisher;
use Application\Models\Rent;
use Application\Models\User;

class Installer {
    public static function install() {
        echo "===================================\n";
        echo "Installing...\n";
        User::generate_sql_creation();

        $login_register_table = "CREATE TABLE `LOGIN_REGISTER` (
  `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `user` INT(11) DEFAULT NULL,
  `date` DATETIME DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=latin1;";

        $conn = null;

        try {
            $conn = Datasource::get_conn();
        } catch (\PDOException $ex) {
            throw $ex;
        }

        $conn->query($login_register_table);

        echo "Tables created successfully\n";

        if (User::count_all() == 0) {
            echo "===================================\n";
            echo "Creating Master User\n";
            $user = new User();
            $user->name = "administrator";
            $user->email = "admin@server.com";
            $user->login = "admin";
            $user->pwrd = "admin";
            $user->is_admin = true;
            if ($user->save()) {
                echo "\tCreated Master User\n";
                echo "\tLogin: admin\n";
                echo "\tPassw: admin\n";
            } else {
                echo "Error creating Master User\n";
            }
        } else {
            echo "===================================\n";
            echo "Table USERS exists and contains rows\n";
        }

    }
}


text:
const {prompt} = require('inquirer');

module.exports = async markdown => {
  const answers = await prompt([
    {
      name: 'intro',
      message: 'One-Line Release Summary'
    }
  ]);

  const {intro} = answers;

  if (intro === '') {
    //eslint-disable-next-line no-console
    console.error('Please specify a release summary!');

    // eslint-disable-next-line unicorn/no-process-exit
    process.exit(1);
  }

  return `${intro}\n\n${markdown}`;
};


text:
using System;

namespace MsgPack.Serialization.AbstractSerializers
{
	/// <summary>
	///		Defines common interfaces and features for context objects for serializer generation.
	/// </summary>
	/// <typeparam name="TConstruct">The contextType of the code construct for serializer builder.</typeparam>
	internal abstract class SerializerGenerationContext<TConstruct>
	{
		/// <summary>
		///		Gets the serialization context which holds various serialization configuration.
		/// </summary>
		/// <value>
		///		The serialization context. This value will not be <c>null</c>.
		/// </value>
		public SerializationContext SerializationContext { get; private set; }

		/// <summary>
		///		Gets the code construct which represents the argument for the packer.
		/// </summary>
		/// <value>
		///		The code construct which represents the argument for the packer.
		///		This value will not be <c>null</c>.
		/// </value>
		public TConstruct Packer { get; protected set; }

		/// <summary>
		///		Gets the code construct which represents the argument for the packing target object tree root.
		/// </summary>
		/// <returns>
		///		The code construct which represents the argument for the packing target object tree root.
		///		This value will not be <c>null</c>.
		/// </returns>
		public TConstruct PackToTarget { get; protected set; }

		/// <summary>
		///		Gets the code construct which represents the argument for the unpacker.
		/// </summary>
		/// <value>
		///		The code construct which represents the argument for the unpacker.
		///		This value will not be <c>null</c>.
		/// </value>
		public TConstruct Unpacker { get; protected set; }

		/// <summary>
		///		Gets the code construct which represents the argument for the collection which will hold unpacked items.
		/// </summary>
		/// <returns>
		///		The code construct which represents the argument for the collection which will hold unpacked items.
		///		This value will not be <c>null</c>.
		/// </returns>
		public TConstruct UnpackToTarget { get; protected set; }

		/// <summary>
		///		Gets the configured nil-implication for collection items.
		/// </summary>
		/// <value>
		///		The configured nil-implication for collection items.
		/// </value>
		public NilImplication CollectionItemNilImplication { get; private set; }

		/// <summary>
		///		Gets the configured nil-implication for dictionary keys.
		/// </summary>
		/// <value>
		///		The configured nil-implication for dictionary keys.
		/// </value>
		public NilImplication DictionaryKeyNilImplication { get; private set; }

		// NOTE: Missing map value is MemberDefault

		/// <summary>
		///		Gets the configured nil-implication for tuple items.
		/// </summary>
		/// <value>
		///		The configured nil-implication for tuple items.
		/// </value>
		public NilImplication TupleItemNilImplication { get; private set; }

		/// <summary>
		///		Initializes a new instance of the <see cref="SerializerGenerationContext{TConstruct}"/> class.
		/// </summary>
		/// <param name="context">The serialization context.</param>
		protected SerializerGenerationContext( SerializationContext context )
		{
			this.SerializationContext = context;
			this.CollectionItemNilImplication = NilImplication.Null;
			this.DictionaryKeyNilImplication = NilImplication.Prohibit;
			this.TupleItemNilImplication = NilImplication.Null;
		}

		/// <summary>
		///		Resets internal states for specified target type.
		/// </summary>
		/// <param name="targetType">Type of the serialization target.</param>
		public void Reset( Type targetType )
		{
			this.ResetCore( targetType );
		}

		/// <summary>
		///		Resets internal states for specified target type.
		/// </summary>
		/// <param name="targetType">Type of the serialization target.</param>
		protected abstract void ResetCore( Type targetType );
	}
}


text:
//
//  YPTabItem.h
//  YPTabBarController
//
//  Created by 喻平 on 15/8/11.
//  Copyright (c) 2015年 YPTabBarController. All rights reserved.
//

#import <UIKit/UIKit.h>

/**
 *  Badge样式
 */
typedef NS_ENUM(NSInteger, YPTabItemBadgeStyle) {
    YPTabItemBadgeStyleNumber = 0, // 数字样式
    YPTabItemBadgeStyleDot = 1, // 小圆点
};

@interface YPTabItem : UIButton

/**
 *  item在tabBar中的index,此属性不能手动设置
 */
@property (nonatomic, assign) NSUInteger index;

/**
 *  用于记录tabItem在缩放前的frame,
 *  在YPTabBar的属性itemFontChangeFollowContentScroll == YES时会用到
 */
@property (nonatomic, assign, readonly) CGRect frameWithOutTransform;
@property (nonatomic, assign) CGSize size;

@property (nonatomic, copy) NSString *title;
@property (nonatomic, strong) UIColor *titleColor;
@property (nonatomic, strong) UIColor *titleSelectedColor;
@property (nonatomic, strong) UIFont *titleFont;

@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) UIImage *selectedImage;
@property (nonatomic, strong) UIColor *imageColor;
@property (nonatomic, strong) UIColor *imageSelectedColor;

@property (nonatomic, assign, readonly) CGFloat titleWidth;
@property (nonatomic, assign) UIEdgeInsets indicatorInsets;
@property (nonatomic, assign, readonly) CGRect indicatorFrame;

/**
 *  当badgeStyle == YPTabItemBadgeStyleNumber时,可以设置此属性,显示badge数值
 *  badge > 99,显示99+
 *  badge <= 99 && badge > -99,显示具体数值
 *  badge < -99,显示-99+
 */
@property (nonatomic, assign) NSInteger badge;

/**
 *  badge的样式,支持数字样式和小圆点
 */
@property (nonatomic, assign) YPTabItemBadgeStyle badgeStyle;

/**
 *  badge的背景颜色
 */
@property (nonatomic, strong) UIColor *badgeBackgroundColor;

/**
 *  badge的背景图片
 */
@property (nonatomic, strong) UIImage *badgeBackgroundImage;

/**
 *  badge的标题颜色
 */
@property (nonatomic, strong) UIColor *badgeTitleColor;

/**
 *  badge的标题字体,默认13号
 */
@property (nonatomic, strong) UIFont *badgeTitleFont;

/**
 *  设置Image和Title水平居中
 */
@property (nonatomic, assign) BOOL contentHorizontalCenter;

/**
 *  设置Image和Title水平居中
 *
 *  @param marginTop   与顶部的距离
 *  @param spacing     Image与Title的间距
 */
- (void)setContentHorizontalCenterAndMarginTop:(CGFloat)marginTop
                                       spacing:(CGFloat)spacing;
/**
 *  添加双击事件回调
 */
- (void)setDoubleTapHandler:(void (^)(void))handler;

/**
 *  设置数字Badge的位置
 *
 *  @param marginTop            与TabItem顶部的距离
 *  @param centerMarginRight    中心与TabItem右侧的距离
 *  @param titleHorizonalSpace  标题水平方向的空间
 *  @param titleVerticalSpace   标题竖直方向的空间
 */
- (void)setNumberBadgeMarginTop:(CGFloat)marginTop
              centerMarginRight:(CGFloat)centerMarginRight
            titleHorizonalSpace:(CGFloat)titleHorizonalSpace
             titleVerticalSpace:(CGFloat)titleVerticalSpace;
/**
 *  设置小圆点Badge的位置
 *
 *  @param marginTop            与TabItem顶部的距离
 *  @param centerMarginRight    中心与TabItem右侧的距离
 *  @param sideLength           小圆点的边长
 */
- (void)setDotBadgeMarginTop:(CGFloat)marginTop
           centerMarginRight:(CGFloat)centerMarginRight
                  sideLength:(CGFloat)sideLength;

@end


text:
package org.lds.example;

import java.util.logging.Logger;

import javax.annotation.PostConstruct;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;

import static org.lds.stack.logging.LogUtils.*;

/**
 *
 * @author Robert Thornton <thorntonrp@ldschurch.org>
 */
@Controller
@Lazy(false)
public class Application {

	private static final Logger LOG = getLogger();

	@PostConstruct
	public void startup() {
		info(LOG, "Starting up...");

		// TODO write your application
		info(LOG, "\n------------------------------------------------------------------------" +
				  "\n Welcome to Java REST Training" +
				  "\n------------------------------------------------------------------------");

		info(LOG, "Shutting down...");
	}
}


text:
{-# LANGUAGE DeriveAnyClass    #-}
{-# LANGUAGE DeriveGeneric     #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards   #-}
{-# LANGUAGE TemplateHaskell   #-}

module Game.Api.Types where

import           Control.Arrow        (second)
import           Control.Lens.TH      (makeLenses)
import           Data.Aeson           (FromJSON, ToJSON)
import           Data.Functor         ((<$>))
import           Data.Monoid          ((<>))
import           Data.Proxy           (Proxy (..))
import           Data.Text            (Text)
import           GHC.Generics         (Generic)
import           TextShow             (TextShow (..))

import           Servant.Docs         (ToSample (..), singleSample)

import           Game.Types
import           HttpApp.BotKey.Types (BotKey, sampleBotKey)

-- TODO: custom json instances
--  * check overloaded record fields

newtype GameError = GameError { unGameError :: Text }
  deriving (Generic, ToJSON)

instance TextShow GameError where
  showb b = "GameError: " <> showb (unGameError b)

data ErrorOr a
  = Error { geMsg :: GameError }
  | Result a
  deriving (Generic, ToJSON)

instance ToSample a => ToSample (ErrorOr a) where
  toSamples _ =
    let results = second Result <$> toSamples (Proxy :: Proxy a)
        geMsg = GameError "Illegal play: skull. Your hand doesn't have the skull card."
        error = singleSample Error{..}
    in  error <> results

data GameJoinRequest = GameJoinRequest
  { _gjrGameKey :: GameKey
  , _gjrBotKey  :: BotKey
  } deriving (Generic, FromJSON, ToJSON)

instance ToSample GameJoinRequest where
  toSamples _ =
    let _gjrGameKey = sampleGameKey
        _gjrBotKey  = sampleBotKey
    in  singleSample GameJoinRequest{..}

-- authentication information for every move

data AuthInfo = AuthInfo
  { _aiGameKey   :: GameKey
  , _aiPlayerKey :: PlayerKey
  } deriving (Generic, FromJSON, ToJSON)

sampleAuthInfo :: AuthInfo
sampleAuthInfo = AuthInfo
  { _aiGameKey   = sampleGameKey
  , _aiPlayerKey = samplePlayerKey
  }

makeLenses ''AuthInfo


text:
title: 'E Pluribus Unum/ Ex Uno Plura: Legislating and Deregulating American Studies post 9/11.'
date: 2008-01-01 12:00:00
category: what-im-watching
permalink: /writing/e-pluribus-unum-ex-uno-plura-legislating-and-deregulating-american-studies-post-911/
publication:
  - 'CR: The New Centennial Review'
---
"E Pluribus Unum/ Ex Uno Plura: Legislating and Deregulating American Studies post 9/11" appeared in CR: The New Centennial Review 8.1 (2008): 145–75.


text:
{% extends "base/base.html" %}

{% block title %}{{ block.super }}{% endblock %}

{% block body_id %}boxed{% endblock %}
{% block body_classes %}boxed-wrapper{% endblock %}

{% block navbar_active_home %}active{% endblock %}

{% block breadcrumbs_wrapper %}{% endblock %}

{% block body %}

  {{ block.super }}

{% endblock %}

{% block css %}
{{ block.super }}
<link href="{% static "rs-plugin/css/settings.css" %}" rel="stylesheet" type="text/css" media="screen"/>
<link href="{% static "css/rev-style.css" %}" rel="stylesheet" type="text/css" media="screen"/>
{% endblock %}

{% block script %}
{{ block.super }}

{% endblock %}

{% block container %}

          Simple medication reminders

          for you and yours

          Take Your Meds is a telephone service to help you remember to take your medication.

          It's easy to set up, and you can start receiving your reminder
          phonecalls today.

          Set up a reminder now

What We Offer

Customisable schedule

              Tell us when you need your reminders and
              let us do the work for you. Whether you need 1 or 100 reminders a day, we can help.

Record your own message

             Add your own reminder message, or you could ask a family member to record one for you. You can also write a custom text message if that's what you'd prefer.

Person-centred monitoring

              Keep track of your reminders and if they are acknowledged, so you can easily see how medication is being taken.

  Set up a reminder now

Why use Take Your Meds?

Taking medication is hard

                                    Even remembering to take one pill in the morning can be difficult, but add in another pill three times a day and another one at bedtime and things soon get very complicated.

Not all medications are tablets

                                    If you need to use a particular mouthwash, apply a cream, replace a patch or use anything that isn't a tablet then classic pill-helper boxes can't help.

Not everyone uses a smartphone

                                    All you need in order to use Take Your Meds is a phone number, whether a landline or a mobile. You can receive phonecalls or text messages as you prefer.

                              Set up a reminder now

{% endblock%}


text:
class PSD
  module ImageFormat
    # Some method overrides for layer images.
    module LayerRLE
      private

      def parse_byte_counts!
        byte_counts = []
        height.times do
          byte_counts << @file.read_short
        end

        return byte_counts
      end

      def parse_channel_data!
        @line_index = 0

        PSD.logger.debug "Parsing RLE channel ##{@ch_info[:id]}: file position = #{@file.tell}, image position = #{@chan_pos}, line = #{@line_index}"
        decode_rle_channel
      end
    end
  end
end


text:
CKEDITOR.plugins.setLang( 'elementspath', 'de', {
	eleLabel: 'Elementepfad',
	eleTitle: '%1 Element'
} );


text:
package net.yadaframework.web.dialect;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.model.AttributeValueQuotes;
import org.thymeleaf.model.ICloseElementTag;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IModelFactory;
import org.thymeleaf.model.IOpenElementTag;
import org.thymeleaf.model.ITemplateEvent;
import org.thymeleaf.model.IText;
import org.thymeleaf.processor.element.AbstractElementModelProcessor;
import org.thymeleaf.processor.element.IElementModelStructureHandler;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.thymeleaf.templatemode.TemplateMode;

import net.yadaframework.core.YadaConfiguration;

/**
 * Defines the <yada:inputCounter> tag
 *
 */
public class YadaInputCounterTagProcessor extends AbstractElementModelProcessor {
	// Tag syntax:
	//	<yada:inputCounter></yada:inputCounter>

	@SuppressWarnings("unused")
	private final transient Logger log = LoggerFactory.getLogger(getClass());

	private static final String TAG_NAME = "inputCounter";
	public static final int PRECEDENCE = 12000; // Must be higher than any yada: attribute

    private final String dialectPrefix;

    private final YadaDialectUtil yadaDialectUtil;

	public YadaInputCounterTagProcessor(String dialectPrefix, YadaConfiguration config) {
		super(
			TemplateMode.HTML, // This processor will apply only to HTML mode
			dialectPrefix,     // Prefix to be applied to name for matching
			TAG_NAME,          // Tag name: match specifically this tag
			true,              // Apply dialect prefix to tag name
			null,              // No attribute name: will match by tag name
			false,             // No prefix to be applied to attribute name
			PRECEDENCE);       // Precedence (inside dialect's own precedence)

		this.dialectPrefix = dialectPrefix;
		this.yadaDialectUtil = new YadaDialectUtil(config);
	}

	@Override
	protected void doProcess(ITemplateContext context, IModel model, IElementModelStructureHandler structureHandler) {

        for (int i = 0; i < model.size(); i++) {
        	ITemplateEvent iTemplateEvent = model.get(i);
        	if (iTemplateEvent instanceof IOpenElementTag) {
        		final IOpenElementTag openTag = (IOpenElementTag) iTemplateEvent;
        		String tagName = yadaDialectUtil.removePrefix(openTag.getElementCompleteName(), dialectPrefix);
        		switch (tagName) {
        		case "inputCounter":
        			processTag(openTag, context, structureHandler);
        			structureHandler.setLocalVariable("yadaTagId",  yadaDialectUtil.makeYadaTagId(openTag)); // Not used yet
        			break;
        		}
        	}
		}

        // Add the replacement tag
        Map<String, String> divAttributes = new HashMap<>();
        divAttributes.put("th:replace", "/yada/formfields/inputCounter::field");
        final IModelFactory modelFactory = context.getModelFactory();
        IOpenElementTag replacementTagOpen = modelFactory.createOpenElementTag("div", divAttributes, AttributeValueQuotes.DOUBLE, false);
        ICloseElementTag replacementTagClose = modelFactory.createCloseElementTag("div");
        model.reset(); // Remove the yada tag completely
        model.add(replacementTagOpen);
        model.add(replacementTagClose);
	}

	private void processTag(IOpenElementTag sourceTag, ITemplateContext context, IElementModelStructureHandler structureHandler) {
        // Convert all attributes of the source tag
        Map<String, String> inputSourceAttributes = sourceTag.getAttributeMap();
        String targetAttributesString = yadaDialectUtil.getConvertedCustomTagAttributeString(sourceTag, context);
        structureHandler.setLocalVariable(TAG_NAME, inputSourceAttributes); // So I can do like ${input.id} to get the original id attribute and so on
        structureHandler.setLocalVariable("targetAttributesString", targetAttributesString);
	}

}


text:
package hex.tree;

import hex.*;
import hex.genmodel.GenModel;
import hex.genmodel.utils.DistributionFamily;
import hex.tree.gbm.GBMModel;
import org.apache.log4j.Logger;
import water.Iced;
import water.Key;
import water.fvec.C0DChunk;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.Vec;
import water.udf.CFuncRef;

/** Score the tree columns, and produce a confusion matrix and AUC
 */
public class Score extends CMetricScoringTask<Score> {

  private static final Logger LOG = Logger.getLogger(Score.class);

  final SharedTree _bldr;
  final boolean _is_train;      // Scoring on pre-scored training data vs full-score data
  final boolean _oob;           // Computed on OOB
  final Key<Vec> _kresp;        // Response vector key (might be either train or validation)
  final ModelCategory _mcat;    // Model category (Binomial, Regression, etc)

  final boolean _computeGainsLift;
  final ScoreIncInfo _sii;      // Incremental scoring (on a validation dataset), null indicates full scoring
  final Frame _preds;           // Prediction cache (typically not too many Vecs => it is not too costly embed the object in MRTask)

  /** Output parameter: Metric builder */
  ModelMetrics.MetricBuilder _mb;

  /** Compute ModelMetrics on the testing dataset.
   *  It expect already adapted validation dataset which is adapted to a model
   *  and contains a response which is adapted to confusion matrix domain.
   */
  public Score(SharedTree bldr, boolean is_train, boolean oob, Vec kresp, ModelCategory mcat, boolean computeGainsLift, Frame preds, CFuncRef customMetricFunc) {
    this(bldr, is_train, null, oob, kresp, mcat, computeGainsLift, preds, customMetricFunc);
  }

  public Score(SharedTree bldr, ScoreIncInfo sii, boolean oob, Vec kresp, ModelCategory mcat, boolean computeGainsLift, Frame preds, CFuncRef customMetricFunc) {
    this(bldr, false, sii, oob, kresp, mcat, computeGainsLift, preds, customMetricFunc);
  }

  private Score(SharedTree bldr, boolean is_train, ScoreIncInfo sii, boolean oob, Vec kresp, ModelCategory mcat, boolean computeGainsLift, Frame preds, CFuncRef customMetricFunc) {
  super(customMetricFunc);
    _bldr = bldr; _is_train = is_train; _sii = sii; _oob = oob; _kresp = kresp != null ? kresp._key : null; _mcat = mcat; _computeGainsLift = computeGainsLift;
    _preds = computeGainsLift ? preds : null; // don't keep the prediction cache if we don't need to compute gainslift
    assert _kresp != null || !_bldr.isSupervised();
    assert (! _is_train) || (_sii == null);
  }

  @Override public void map(Chunk allchks[]) {
    final Chunk[] chks = getScoringChunks(allchks);
    Chunk ys; // Response
    if (_bldr.isSupervised()) {
      ys = _bldr.chk_resp(chks);
    } else if (_bldr.isResponseOptional() && _kresp != null) {
      ys = _kresp.get().chunkForChunkIdx(chks[0].cidx());
    } else {
      ys = new C0DChunk(0, chks[0]._len); // Dummy response to simplify code
    }
    SharedTreeModel m = _bldr._model;
    Chunk weightsChunk = m._output.hasWeights() ? chks[m._output.weightsIdx()] : null;
    Chunk offsetChunk = m._output.hasOffset() ? chks[m._output.offsetIdx()] : null;
    // Because of adaption - the validation training set has at least as many
    // classes as the training set (it may have more).  The Confusion Matrix
    // needs to be at least as big as the training set domain.
    final String[] domain;
    if (m._parms._distribution == DistributionFamily.quasibinomial) {
      domain = ((GBMModel) m)._output._quasibinomialDomains;
    } else {
      domain = _kresp != null ? _kresp.get().domain() : null;
    }
    final int nclass = _bldr.nclasses();
    _mb = m.makeMetricBuilder(domain);
    // If this is a score-on-train AND DRF, then oobColIdx makes sense,
    // otherwise this field is unused.
    final int oobColIdx = _bldr.idx_oobt();
    final double[] cdists = _mb._work; // Temp working array for class distributions
    // If working a validation set, need to push thru official model scoring
    // logic which requires a temp array to hold the features.
    final double[] tmp = _is_train && _bldr._ntrees > 0 ? null : new double[_bldr._ncols];

    // Score all Rows
    float [] val= new float[1];
    for( int row=0; row<ys._len; row++ ) {
      if( ys.isNA(row) ) continue; // Ignore missing response vars only if it was actual NA
      // Ignore rows that were never out-of-bag (= were always used to build trees so far)
      if( _oob && chks[oobColIdx].atd(row)==0 ) continue;
      double weight = weightsChunk!=null?weightsChunk.atd(row):1;
      if (weight == 0) continue; //ignore holdout rows
      double offset = offsetChunk!=null?offsetChunk.atd(row):0;
      if( _is_train ) // Passed in the model-specific columns
        _bldr.score2(chks, weight, offset, cdists, row); // Use the training data directly (per-row predictions already made)
      else if (_sii != null)
        m.score0Incremental(_sii, chks, offset, row, tmp, cdists); // Incremental scoring (only use new trees)
      else            // Must score "the hard way"
        m.score0(chks, offset, row, tmp, cdists);

      // fill tmp with training data for null model - to have proper tie breaking
      if (_is_train && _bldr._ntrees == 0)
        for( int i=0; i< tmp.length; i++ )
          tmp[i] = chks[i].atd(row);

      if (nclass > 2) { // Fill in prediction for multinomial
        cdists[0] = GenModel.getPredictionMultinomial(cdists, m._output._priorClassDist, tmp);
      } else if (nclass == 2) {
        // for binomial the predicted class is not needed
        // and it even cannot be returned because the threshold is calculated based on model metrics that are not known yet
        // (we are just building the metrics)
        cdists[0] = -1;
      }
      val[0] = (float)ys.atd(row);
      _mb.perRow(cdists, val, weight, offset, m);

      if (_preds != null) {
        _mb.cachePrediction(cdists, allchks, row, chks.length, m);
      }

      // Compute custom metric if necessary
      customMetricPerRow(cdists, val, weight, offset, m);
    }
  }

  // scoring chunks are those chunks that make the input to one of the scoring functions
  private Chunk[] getScoringChunks(Chunk[] allChunks) {
    if (_preds == null)
      return allChunks;
    Chunk[] chks = new Chunk[allChunks.length - _preds.numCols()];
    System.arraycopy(allChunks, 0, chks, 0, chks.length);
    return chks;
  }

  @Override
  protected boolean modifiesVolatileVecs() {
    return _sii != null || _preds != null;
  }

  @Override public void reduce(Score t) {
    super.reduce(t);
    _mb.reduce(t._mb);
  }

  // We need to satsify MB invariant
  @Override protected void postGlobal() {
    super.postGlobal();
    if(_mb != null) {
      _mb.postGlobal(getComputedCustomMetric());
    }
  }

  ModelMetrics scoreAndMakeModelMetrics(SharedTreeModel model, Frame fr, Frame adaptedFr, boolean buildTreeOneNode) {
    Frame input = _preds != null ? new Frame(adaptedFr).add(_preds) : adaptedFr;
    return doAll(input, buildTreeOneNode)
            .makeModelMetrics(model, fr, adaptedFr, _preds);
  }

  // Run after the doAll scoring to convert the MetricsBuilder to a ModelMetrics
  private ModelMetrics makeModelMetrics(SharedTreeModel model, Frame fr, Frame adaptedFr, Frame preds) {
    ModelMetrics mm;
    if (model._output.nclasses() == 2 && _computeGainsLift) {
      assert preds != null : "Predictions were pre-created";
      mm = _mb.makeModelMetrics(model, fr, adaptedFr, preds);
    } else {
      boolean calculatePreds = preds == null && model.isDistributionHuber();
      // FIXME: PUBDEV-4992 we should avoid doing full scoring!
      if (calculatePreds) {
        LOG.warn("Going to calculate predictions from scratch. This can be expensive for large models! See PUBDEV-4992");
        preds = model.score(fr);
      }
      mm = _mb.makeModelMetrics(model, fr, null, preds);
      if (calculatePreds && (preds != null))
        preds.remove();
    }
    return mm;
  }

  static Frame makePredictionCache(SharedTreeModel model, Vec templateVec, String[] domain) {
    ModelMetrics.MetricBuilder mb = model.makeMetricBuilder(domain);
    return mb.makePredictionCache(model, templateVec);
  }

  public static class ScoreIncInfo extends Iced<ScoreIncInfo> {
    public final int _startTree;
    public final int _workspaceColIdx;
    public final int _workspaceColCnt;
    public final int _predsAryOffset;

    public ScoreIncInfo(int startTree, int workspaceColIdx, int workspaceColCnt, int predsAryOffset) {
      _startTree = startTree;
      _workspaceColIdx = workspaceColIdx;
      _workspaceColCnt = workspaceColCnt;
      _predsAryOffset = predsAryOffset;
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2010-2017 Evolveum
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<shadow
	xmlns='http://midpoint.evolveum.com/xml/ns/public/common/common-3'
	xmlns:c='http://midpoint.evolveum.com/xml/ns/public/common/common-3'
	xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3"
	xmlns:icfs="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/resource-schema-3"
	xmlns:ri="http://midpoint.evolveum.com/xml/ns/public/resource/instance-3">
	<name>pirate</name>
	<resourceRef oid="10000000-0000-0000-0000-000000000004"/>
	<objectClass>ri:GroupObjectClass</objectClass>
	<kind>entitlement</kind>
	<intent>group</intent>
	<iteration>0</iteration>
	<iterationToken></iterationToken>
	<attributes>
		<icfs:name>pirate</icfs:name>
		<icfs:uid>pirate</icfs:uid>
	</attributes>
</shadow>


text:
'use strict';

import {assert} from 'chai';
import sinon from 'sinon';

import {InfinityRandomNumberDeck} from '../../src/model/deck.js';
import RNG from '../../src/model/rng.js';

describe('deck', () => {
    describe('infinity RNG based', () => {
        it('should accept PRNG and return cards', () => {
            let rng = new RNG(),
                stub = sinon.stub(rng, 'next');
            stub.onCall(0).returns(5);
            stub.onCall(1).returns(7);

            let deck = new InfinityRandomNumberDeck(rng);

            assert.equal(5, deck.next());
            assert.equal(7, deck.next());
        });
    });
});


text:
require "active_model"

module AcceptValuesFor
  class Matcher
    def initialize(attribute, *values)
      @attribute = attribute
      @values = values
      @failed_values = {}
    end

    def matches?(model)
      base_matches?(model) do |value|
        unless model.errors[@attribute].to_a.empty?
          @failed_values[value] = Array(model.errors[@attribute]).join(", ")
        end
      end
    end

    def does_not_match?(model)
      base_matches?(model) do |value|
        if model.errors[@attribute].to_a.empty?
          @failed_values[value] = nil
        end
      end
    end

    def failure_message
      result = "expected #{@model.inspect} to accept values #{formatted_failed_values} for #{@attribute.inspect}, but it was not\n"
      sorted_failed_values.each do |key|
        result << "\nValue: #{key.inspect}\tErrors: #{@attribute} #{@failed_values[key]}"
      end
      result
    end

    def failure_message_when_negated
      "expected #{@model.inspect} to not accept values #{formatted_failed_values} for #{@attribute.inspect} attribute, but was"
    end

    alias :failure_message_for_should :failure_message
    alias :failure_message_for_should_not :failure_message_when_negated

    def description
      "accept values #{@values.map(&:inspect).join(', ')} for #{@attribute.inspect} attribute"
    end

    private
    def base_matches?(model)
      @model = model
      !has_validations_module?(model) and return false
      old_value = @model.send(@attribute)
      @values.each do |value|
        model.send("#@attribute=", value)
        model.valid?
        yield(value) if @model.respond_to?(:errors) && @model.errors.is_a?(ActiveModel::Errors)
      end
      return @failed_values.empty?
    ensure
      @model.send("#@attribute=", old_value) if defined?(old_value)
    end

    def has_validations_module?(model)
      model.class.included_modules.include?(ActiveModel::Validations)
    end

    def formatted_failed_values
      sorted_failed_values.map(&:inspect).join(", ")
    end

    def sorted_failed_values
      @failed_values.keys.sort_by(&:to_s)
    end
  end
end


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/ec2/model/UnsuccessfulInstanceCreditSpecificationErrorCode.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace EC2
{
namespace Model
{

  /**
   *
Information about the error for the T2 or T3 instance whose credit option for
   * CPU usage was not modified.

See Also:
   AWS
   * API Reference

   */
  class AWS_EC2_API UnsuccessfulInstanceCreditSpecificationItemError
  {
  public:
    UnsuccessfulInstanceCreditSpecificationItemError();
    UnsuccessfulInstanceCreditSpecificationItemError(const Aws::Utils::Xml::XmlNode& xmlNode);
    UnsuccessfulInstanceCreditSpecificationItemError& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    /**
     *
The error code.

     */
    inline const UnsuccessfulInstanceCreditSpecificationErrorCode& GetCode() const{ return m_code; }

    /**
     *
The error code.

     */
    inline void SetCode(const UnsuccessfulInstanceCreditSpecificationErrorCode& value) { m_codeHasBeenSet = true; m_code = value; }

    /**
     *
The error code.

     */
    inline void SetCode(UnsuccessfulInstanceCreditSpecificationErrorCode&& value) { m_codeHasBeenSet = true; m_code = std::move(value); }

    /**
     *
The error code.

     */
    inline UnsuccessfulInstanceCreditSpecificationItemError& WithCode(const UnsuccessfulInstanceCreditSpecificationErrorCode& value) { SetCode(value); return *this;}

    /**
     *
The error code.

     */
    inline UnsuccessfulInstanceCreditSpecificationItemError& WithCode(UnsuccessfulInstanceCreditSpecificationErrorCode&& value) { SetCode(std::move(value)); return *this;}

    /**
     *
The applicable error message.

     */
    inline const Aws::String& GetMessage() const{ return m_message; }

    /**
     *
The applicable error message.

     */
    inline void SetMessage(const Aws::String& value) { m_messageHasBeenSet = true; m_message = value; }

    /**
     *
The applicable error message.

     */
    inline void SetMessage(Aws::String&& value) { m_messageHasBeenSet = true; m_message = std::move(value); }

    /**
     *
The applicable error message.

     */
    inline void SetMessage(const char* value) { m_messageHasBeenSet = true; m_message.assign(value); }

    /**
     *
The applicable error message.

     */
    inline UnsuccessfulInstanceCreditSpecificationItemError& WithMessage(const Aws::String& value) { SetMessage(value); return *this;}

    /**
     *
The applicable error message.

     */
    inline UnsuccessfulInstanceCreditSpecificationItemError& WithMessage(Aws::String&& value) { SetMessage(std::move(value)); return *this;}

    /**
     *
The applicable error message.

     */
    inline UnsuccessfulInstanceCreditSpecificationItemError& WithMessage(const char* value) { SetMessage(value); return *this;}

  private:

    UnsuccessfulInstanceCreditSpecificationErrorCode m_code;
    bool m_codeHasBeenSet;

    Aws::String m_message;
    bool m_messageHasBeenSet;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
@implementation AsyncPost

- (id)init {
    self = [super init];

    if(self){
        httpResponse = [[NSMutableData alloc] init];
    }

    return self;
}

// Sends an asynchronous HTTP POST request
- (void)sendRequest:(NSString*)url payLoad:(NSString*)body sender:(NSObject*) sender {

    NSMutableString* requestURL = [[NSMutableString alloc] init];
    [requestURL appendString:url];

    NSMutableString* requestBody = [[NSMutableString alloc] init];
    [requestBody appendString:body];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: [NSString stringWithString:requestURL]]];

    NSString* requestBodyString = [NSString stringWithString:requestBody];
    NSData *requestData = [NSData dataWithBytes: [requestBodyString UTF8String] length: [requestBodyString length]];

    [request setHTTPMethod: @"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    [request setHTTPBody: requestData];
    NSLog(@"request = %@", request);

    //NSURLResponse *theRespose;
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:sender];

    if (!theConnection) {
        NSLog(@"ERROR -- COULD NOT OPEN A CONNECTION");
    }
}
- (NSData *)sendSynchronousRequest:(NSString*)url payLoad:(NSString*)body sender:(NSObject*) sender {
    NSMutableString* requestURL = [[NSMutableString alloc] init];
    [requestURL appendString:url];

    NSMutableString* requestBody = [[NSMutableString alloc] init];
    [requestBody appendString:body];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: [NSString stringWithString:requestURL]]];

    NSString* requestBodyString = [NSString stringWithString:requestBody];
    NSData *requestData = [NSData dataWithBytes: [requestBodyString UTF8String] length: [requestBodyString length]];

    [request setHTTPMethod: @"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    [request setHTTPBody: requestData];
    NSLog(@"request = %@", request);

    NSURLResponse *theRespose;
    NSData *responseData = [[NSURLConnection sendSynchronousRequest:request returningResponse:&theRespose error:nil] copy];

    return responseData;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [httpResponse setLength:0];
}

// Called when data has been received
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [httpResponse appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //NSString* responseString = [[[NSString alloc] initWithData:httpResponse encoding:NSUTF8StringEncoding] copy];

    // Do something with the response

    connection = nil;
    httpResponse = nil;
}

@end


text:
class TestChannel: public Poco::Channel
{
public:
	typedef std::list<Poco::Message> MsgList;

	TestChannel();
	~TestChannel();

	void log(const Poco::Message& msg);
	MsgList& list();
	void clear();
	const Poco::Message& getLastMessage() const { return _lastMessage; }

private:
	MsgList _msgList;
	Poco::Message _lastMessage;
};

#endif // TestChannel_INCLUDED


text:
Theme configuration reference
=============================

.. code-block:: json

    {
        "name": "vendor/sylius-theme",
        "title": "Great Sylius theme!",
        "description": "Optional description",
        "authors": [
            {
                "name": "Kamil Kokot",
                "email": "kamil@kokot.me",
                "homepage": "http://kamil.kokot.me",
                "role": "Developer"
            }
        ],
        "parents": [
            "vendor/common-sylius-theme",
            "another-vendor/not-so-cool-looking-sylius-theme"
        ]
    }

.. warning::

    Theme configuration was meant to be mixed with the one from Composer. Fields ``name``, ``description`` and
    ``authors`` are shared between these by default. To use different values for Composer & ThemeBundle,
    have a look below.

Composer integration
--------------------

.. code-block:: json

    {
        "name": "vendor/sylius-theme",
        "type": "sylius-theme",
        "description": "Composer package description",
        "authors": [
            {
                "name": "Kamil Kokot"
            }
        ],
        "extra": {
            "sylius-theme": {
                "description": "Theme description",
                "parents": [
                    "vendor/other-sylius-theme"
                ]
            }
        }
    }

.. note::

    By configuring Composer package along with theme we do not have to duplicate fields like ``name`` or ``authors``,
    but we are free to overwrite them in any time, just like the ``description`` field in example above.
    The theme configuration is complementary to the Composer configuration and results in perfectly valid ``composer.json``.


text:
<?php

// security - hide paths
if (!defined('ADODB_DIR')) die();

global $ADODB_INCLUDED_MEMCACHE;
$ADODB_INCLUDED_MEMCACHE = 1;

global $ADODB_INCLUDED_CSV;
if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');

	class ADODB_Cache_MemCache {
		var $createdir = false; // create caching directory structure?

		// $library will be populated with the proper library on connect
		// and is used later when there are differences in specific calls
		// between memcache and memcached
		var $library = false;

		//-----------------------------
		// memcache specific variables

		var $hosts;	// array of hosts
		var $port = 11211;
		var $compress = false; // memcache compression with zlib

		var $_connected = false;
		var $_memcache = false;

		function __construct(&$obj)
		{
			$this->hosts = $obj->memCacheHost;
			$this->port = $obj->memCachePort;
			$this->compress = $obj->memCacheCompress;
		}

		// implement as lazy connection. The connection only occurs on CacheExecute call
		function connect(&$err)
		{
			// do we have memcache or memcached?
			if (class_exists('Memcache')) {
				$this->library='Memcache';
				$memcache = new MemCache;
			} elseif (class_exists('Memcached')) {
				$this->library='Memcached';
				$memcache = new MemCached;
			} else {
				$err = 'Neither the Memcache nor Memcached PECL extensions were found!';
				return false;
			}

			if (!is_array($this->hosts)) $this->hosts = array($this->hosts);

			$failcnt = 0;
			foreach($this->hosts as $host) {
				if (!@$memcache->addServer($host,$this->port)) {
					$failcnt += 1;
				}
			}
			if ($failcnt == sizeof($this->hosts)) {
				$err = 'Can\'t connect to any memcache server';
				return false;
			}
			$this->_connected = true;
			$this->_memcache = $memcache;
			return true;
		}

		// returns true or false. true if successful save
		function writecache($filename, $contents, $debug, $secs2cache)
		{
			if (!$this->_connected) {
				$err = '';
				if (!$this->connect($err) && $debug) ADOConnection::outp($err);
			}
			if (!$this->_memcache) return false;

			$failed=false;
			switch ($this->library) {
				case 'Memcache':
					if (!$this->_memcache->set($filename, $contents, $this->compress ? MEMCACHE_COMPRESSED : 0, $secs2cache)) {
						$failed=true;
					}
					break;
				case 'Memcached':
					if (!$this->_memcache->set($filename, $contents, $secs2cache)) {
						$failed=true;
					}
					break;
				default:
					$failed=true;
					break;
			}

			if($failed) {
				if ($debug) ADOConnection::outp(" Failed to save data at the memcache server!
\n");
				return false;
			}

			return true;
		}

		// returns a recordset
		function readcache($filename, &$err, $secs2cache, $rsClass)
		{
			$false = false;
			if (!$this->_connected) $this->connect($err);
			if (!$this->_memcache) return $false;

			$rs = $this->_memcache->get($filename);
			if (!$rs) {
				$err = 'Item with such key doesn\'t exist on the memcache server.';
				return $false;
			}

			// hack, should actually use _csv2rs
			$rs = explode("\n", $rs);
            unset($rs[0]);
            $rs = join("\n", $rs);
 			$rs = unserialize($rs);
			if (! is_object($rs)) {
				$err = 'Unable to unserialize $rs';
				return $false;
			}
			if ($rs->timeCreated == 0) return $rs; // apparently have been reports that timeCreated was set to 0 somewhere

			$tdiff = intval($rs->timeCreated+$secs2cache - time());
			if ($tdiff <= 2) {
				switch($tdiff) {
					case 2:
						if ((rand() & 15) == 0) {
							$err = "Timeout 2";
							return $false;
						}
						break;
					case 1:
						if ((rand() & 3) == 0) {
							$err = "Timeout 1";
							return $false;
						}
						break;
					default:
						$err = "Timeout 0";
						return $false;
				}
			}
			return $rs;
		}

		function flushall($debug=false)
		{
			if (!$this->_connected) {
				$err = '';
				if (!$this->connect($err) && $debug) ADOConnection::outp($err);
			}
			if (!$this->_memcache) return false;

			$del = $this->_memcache->flush();

			if ($debug)
				if (!$del) ADOConnection::outp("flushall: failed!
\n");
				else ADOConnection::outp("flushall: succeeded!
\n");

			return $del;
		}

		function flushcache($filename, $debug=false)
		{
			if (!$this->_connected) {
  				$err = '';
  				if (!$this->connect($err) && $debug) ADOConnection::outp($err);
			}
			if (!$this->_memcache) return false;

			$del = $this->_memcache->delete($filename);

			if ($debug)
				if (!$del) ADOConnection::outp("flushcache: $key entry doesn't exist on memcache server!
\n");
				else ADOConnection::outp("flushcache: $key entry flushed from memcache server!
\n");

			return $del;
		}

		// not used for memcache
		function createdir($dir, $hash)
		{
			return true;
		}
	}


text:
require 'json'

module Bling
  module API
    class Parser

      def initialize(text, klass_name)
        @text, @klass_name = text, klass_name
      end

      def result
        raw_response = JSON.parse(@text)
        Translator.translate_hash(raw_response, to: :en)
      end

      def records
        raw_records = result[:return][plural_klass_name]
        return [] if raw_records.nil?
        raw_records.each_with_object([]) { |record, result| result << Record.new(record[@klass_name]) }
      end

      private

      def plural_klass_name
        @klass_name.to_s.pluralize.to_sym
      end

    end
  end
end


text:
import Test.Hspec
import Test.QuickCheck
import Deprecated.DiGraph.SampleData

main :: IO ()
main = hspec $ do
  describe "env sanity test" $ do
    context "read" $ do
      it "is inverse to show" $ property $
        \x -> (read . show) x == (x :: Int)
  describe "can access src" $ do
      it "accessing sample data" $ do
        length testEdges == 10


text:
import copy
import sys
import random
from Board import Board
from random import choice
import Player

class NegamaxPruningPlayer(Player.Player):
    def generate_move(self, game):
        """
        Generate and return a move for the current turn color.
        The caller ensures that a legal move exists.
        Takes a move based on a search down a few moves.
        """
        # negamax it!
        a = -500000
        b = -a
        value, move = self.negamax(game, 6, a, b)
        print("Value:", value)
        return move

    def negamax(self, state, max_depth, alpha, beta):
        # base case
        if max_depth <= 0:
            return (state.score(), None)

        # recursive case
        legal_moves = state.legal_moves()

        # pre sort the moves! best first!
        sorted_moves = []
        for move in legal_moves:
            score = state.score_after(move)
            sorted_moves.append((score, move))

        # sort the moves on their score
        sorted_moves = sorted(sorted_moves, key=lambda t: t[0])

        best_value = -sys.maxsize

        # number of equal valued moves
        num_equal_best = 0

        for value, move in sorted_moves:
            newstate = Board.from_other(state)
            result = newstate.move(move)
            if result in ('W','B'):
                value = -newstate.score()
            elif result == '=':
                value = 0
            else:
                value = -self.negamax(newstate, max_depth-1, -beta, -alpha)[0]

            if value >= beta:
                return (value, move)
            if value > alpha:
                alpha = value

            if value > best_value:
                best_value = value
                best_move = move
            elif value == best_value:
                # choose one move at random
                num_equal_best += 1
                if random.random() > (1 / (num_equal_best)):
                    best_value = value
                    best_move = move
        return (best_value, best_move)


text:
Enriches domains using one or more integrations.

Domain enrichment includes:
* Threat information

## Dependencies
This playbook uses the following sub-playbooks, integrations, and scripts.

### Sub-playbooks
This playbook does not use any sub-playbooks.

### Integrations
* VirusTotal - Private API

### Scripts
This playbook does not use any scripts.

### Commands
* vt-private-get-domain-report
* umbrella-domain-categorization

## Playbook Inputs
---

| **Name** | **Description** | **Default Value** | **Source** | **Required** |
| --- | --- | --- | --- | --- |
| Domain | The domain name to enrich. | Name | Domain | Optional |

## Playbook Outputs
---

| **Path** | **Description** | **Type** |
| --- | --- | --- |
| Domain | The domain objects. | unknown |
| DBotScore | The indicator, score, type, and vendor. | unknown |

## Playbook Image
---
![Domain_Enrichment_Generic_v2](https://raw.githubusercontent.com/demisto/content/1bdd5229392bd86f0cc58265a24df23ee3f7e662/docs/images/playbooks/Domain_Enrichment_Generic_v2.png)