text:
<?php

	/**
	 * Database Interaction Class (PostgreSQL)
	 *
	 * @category	Database
	 * @author		Kristopher Wilson
	 * @link		http://www.openavanti.com/docs/postgresdatabase
	 */
	class PostgresDatabase extends Database
	{
		private $hDatabase = null;

      	protected static $aSchemas = array();

      	private static $sCacheDirectory = "";
      	private static $bCacheSchemas = false;

		/**
		 * The constructor sets up a new connection to the PostgreSQL database. This method is
		 * protected, and can only be called from within the class, normally through the
		 * GetConnection() method. This helps support the singleton methodology.
		 *
		 * @argument array The database profile array containing connection information
		 */
		protected function __construct( $aProfile )
      	{
            $sString = "";

	      	if( isset( $aProfile[ "host" ] ) )
	      	{
	      		$sString .= " host=" . $aProfile[ "host" ] . " ";
	      	}

			$sString .= " dbname=" . $aProfile[ "name" ] . " ";

	      	if( isset( $aProfile[ "user" ] ) )
	      	{
	      		$sString .= " user=" . $aProfile[ "user" ] . " ";
	      	}

	      	if( isset( $aProfile[ "password" ] ) )
	      	{
	      		$sString .= " password=" . $aProfile[ "password" ] . " ";
	      	}

			$this->hDatabase = pg_connect( $sString );

			if( !$this->hDatabase )
			{
				throw new DatabaseConnectionException( "Failed to connect to Postgres server: " .
					$aProfile[ "host" ] . "." . $aProfile[ "name" ] );
			}

		} // __construct()

		/**
		 * Queries the PostgreSQL database using the supplied SQL query.
		 *
		 * @argument string The PostgreSQL query to execute
		 * @returns string A ResultSet object containing the results of the database query
		 */
		public function Query( $sSQL )
		{
			$rResult = @pg_query( $this->hDatabase, $sSQL );

			if( !$rResult )
			{
				return( null );
			}

			return( new ResultSet( $this, $rResult ) );

		} // Query()

		/**
		 * Pulls the next record from specified database resource and returns it as an object.
		 *
		 * @argument resource The database connection resource to pull the next record from
		 * @returns object The next record from the database, or null if there are no more records
		 */
		public function PullNextResult( &$rResult )
		{
			if( !is_null( $rResult ) )
			{
				return( pg_fetch_object( $rResult ) );
			}
			else
			{
				return( null );
			}

		} // PullNextResult()

		/**
		 * Returns the number of results from the last query performed on the specified database
		 * resource object.
		 *
		 * @argument resource The database connection resource
		 * @returns int The number of rows in the specified database resource
		 */
		public function CountFromResult( &$rResult )
		{
			if( $rResult )
			{
				return( pg_num_rows( $rResult ) );
			}
			else
			{
			 	return( 0 );
			}

		} // CountFromResult()

		/**
		 * Attempts to return the internal pointer of the specified database resource to the
		 * first row.
		 *
		 * @argument resource The database connection resource to pull the next record from
		 * @returns bool True if the operation was successful, false otherwise
		 */
		public function ResetResult( &$rResult )
		{
			return( @pg_result_seek( $rResult, 0 ) );

		} // ResetResult()

		/**
		 * The Begin() method begins a database transaction which persists until either Commit() or
		 * Rollback() is called, or the request ends. If Commit() is not called before the end of the
		 * request, the database transaction will automatically roll back.
		 *
		 * @returns void
		 */
		public function Begin()
		{
			$rResult = @pg_query( $this->hDatabase, "BEGIN" ) or
				trigger_error( "Failed to begin transaction", E_USER_ERROR );

			return( $rResult ? true : false );

		} // Begin()

		/**
		 * The Commit() method commits a database transaction (assuming one was started with
		 * Begin()). If Commit() is not called before the end of the request, the database
		 * transaction will automatically roll back.
		 *
		 * @returns void
		 */
		public function Commit()
		{
			$rResult = @pg_query( $this->hDatabase, "COMMIT" ) or
				trigger_error( "Failed to commit transaction", E_USER_ERROR );

			return( $rResult ? true : false );

		} // Commit()

		/**
		 * The Rollback() method rolls back a database transaction (assuming one was started with
		 * Begin()). The database transaction is automatically rolled back if Commit() is not called.
		 *
		 * @returns void
		 */
		public function Rollback()
		{
			$rResult = @pg_query( $this->hDatabase, "ROLLBACK" ) or
				trigger_error( "Failed to rollback transaction", E_USER_ERROR );

			return( $rResult ? true : false );

		} // Rollback()

		/**
		 * Advances the value of the supplied sequence and returns the new value.
		 *
		 * @argument string The name of the database sequence to advance and get the current value of
		 * @returns integer An integer representation of the next value of the sequence
		 */
		public function NextVal( $sSequenceName )
		{
			$sSQL = "SELECT
				NEXTVAL( '{$sSequenceName}' )
			AS
				next_val";

        	$rResult = @pg_query( $this->hDatabase, $sSQL ) or
            	trigger_error( "Failed to query sequence value: " . $this->getLastError(),
				 	E_USER_ERROR );

     		$oRecord = pg_fetch_object( $rResult );

	     	if( $oRecord )
	     	{
	     		return( $oRecord->next_val );
	     	}

     		return( null );

		} // NextVal()

		/**
		 * Gets the current value of the specified sequence.
		 *
		 * This method does not alter the current value of the sequence.
		 *
		 * This method will only work if the value of the sequence has already been altered during
		 * the current database transaction; meaning that you must call NextVal() or SerialNextVal()
		 * prior to using this method.
		 *
		 * @argument string The name of the database sequence to get the current value of
		 * @returns integer An integer representation of the current value of the sequence.
		 */
		public function CurrVal( $sSequenceName )
		{
			$sSQL = "SELECT
				CURRVAL( '{$sSequence}' )
			AS
				current_value";

	        $rResult = @pg_query( $this->hDatabase, $sSQL ) or
	            trigger_error( "Failed to query sequence value: " . $this->getLastError(),
					 	E_USER_ERROR );

	     	$oRecord = pg_fetch_object( $rResult );

	     	if( $oRecord )
	     	{
	     		return( $oRecord->current_value );
	     	}

	     	return( null );

		} // CurrVal()

		/**
		 * Gets the current value of the specified sequence by the name of the table and the name of
		 * the database column. This will only work if a sequence is defined as the default value of
		 * a table column.
		 *
		 * This method does not alter the current value of the sequence.
		 *
		 * This method will only work if the value of the sequence has already been altered during
		 * the current database transaction; meaning that you must call NextVal() or SerialNextVal()
		 * prior to using this method.
		 *
		 * @argument string The name of the database table that holds the column with the sequence as
		 * 		 a default value
		 * @argument string The name of the database table column with the sequence as a default value
		 * @returns integer An integer representation of the current value of the sequence
		 */
		public function SerialCurrVal( $sTableName, $sColumnName )
		{
			$sSQL = "SELECT
				CURRVAL(
					PG_GET_SERIAL_SEQUENCE(
						'{$sTableName}',
						'{$sColumnName}'
					)
				)
			AS
				current_value";

			$rResult = @pg_query( $this->hDatabase, $sSQL ) or
				trigger_error( "Failed to query sequence value: " . $this->getLastError(),
				E_USER_ERROR );

			$oRecord = pg_fetch_object( $rResult );

			if( $oRecord )
	     	{
	     		return( $oRecord->current_value );
	     	}

	     	return( null );

		} // SerialCurrVal()

		/**
		 * Advances the value of the supplied sequence and returns the new value by the name of the
		 * table and the name of the column. This will only work if a sequence is defined as the
		 * default value of a table column.
		 *
		 * @argument string The name of the database table that holds the column with the sequence as
		 * 		 a default value
		 * @argument string The name of the database table column with the sequence as a default value
		 * @returns integer An integer representation of the next value of the sequence
		 */
		public function SerialNextVal( $sTableName, $sColumnName )
		{
			$sSQL = "SELECT
				NEXTVAL(
					PG_GET_SERIAL_SEQUENCE(
						'{$sTableName}',
						'{$sColumnName}'
					)
				)
			AS
				next_value";

	      $rResult = @pg_query( $this->hDatabase, $sSQL ) or
	         trigger_error( "Failed to query sequence value: " . $this->getLastError(),
					E_USER_ERROR );

	     	$oRecord = pg_fetch_object( $rResult );

	     	if( $oRecord )
	     	{
	     		return( $oRecord->next_value );
	     	}

	     	return( null );

		} // SerialNextVal()

		/**
		 * Returns the last PostgreSQL database error, if any.
		 *
		 * @returns string A string representation of the last PostgreSQL error
		 */
		public function GetLastError()
		{
			return( pg_last_error() );

		} // GetLastError()

		/**
		 * The SetCacheDirectory() method stores which directory should be used to load and store
		 * database schema cache files. If the directory does not exist, an exception will be thrown.
		 *
		 * Setting the cache directory is useless unless schema caching is turned on using
		 * CacheSchemas().
		 *
		 * Schema caching is primarily used by the CRUD object, which analyzes database schemas to
		 * automate database operations.
		 *
		 * @argument The absolute path to the directory in the system to store and read cached
		 * 		 database schema files
		 * @returns void
		 */
		public function SetCacheDirectory( $sDirectoryName )
		{
			self::$sCacheDirectory = $sDirectoryName;

		} // SetCacheDirectory()

		/**
		 * The CacheSchemas() method toggles whether or not database schemas discovered through the
		 * GetSchema(), GetTableColumns(), GetTableForeignKeys() and GetTablePrimaryKey() methods
		 * should be cached, and also whether or not those methods will pull their information from a
		 * cache, if available.
		 *
		 * Attempting to cache schemas without properly setting the cache directory using
		 * SetCacheDirectory(). If caching is attempted without setting the directory, an exception
		 * will be thrown.
		 *
		 * Schema caching is primarily used by the CRUD object, which analyzes database schemas to
		 * automate database operations.
		 *
		 * @argument boolean Toggles whether or not to cache discovered database schemas
		 * @returns void
		 */
		public function CacheSchemas( $bEnable )
		{
			self::$bCacheSchemas = $bEnable;

		} // CacheSchemas()

		/**
		 * Returns the native PHP database resource
		 *
		 * @returns resource The native PHP database resource
		 */
		public function GetResource()
		{
			return( $this->hDatabase );

		} // GetResource()

		/**
		 * Returns a database-safe formatted representation of the supplied data, based on the
		 * supplied data type.
		 *
		 * 1. If the supplied data is empty and does not equal zero, this method returns NULL.
		 * 2. If the data type is of text, varchar, timestamp, or bool, this method returns that
		 * 		 value surrounded in single quotes.
		 *
		 * @argument string The data type of the supplied value
		 * @argument string The value to be formatted into a database-safe representation
		 * @returns string A string of the formatted value supplied
		 */
		public function FormatData( $sType, $sValue )
		{
            $aQuoted_Types = array( "/text/", "/character varying/", "/date/",
                "/timestamp/", "/time without time zone/" );

            if( strlen( $sValue ) == 0 )
            {
                return( "NULL" );
            }

            if( preg_replace( $aQuoted_Types, "", $sType ) != $sType )
            {
                return( "'" . addslashes( $sValue ) . "'" );
            }
            else if( strpos( $sType, "bool" ) !== false )
            {
                if( $sValue === true || strtolower( $sValue ) == "true" ||
                    strtolower( $sValue ) == "t" )
                {
                    return( "true" );
                }
                else
                {
                    return( "false" );
                }
            }

            return( $sValue );

		} // FormatData()

		/**
		 * This method returns all databases on the database server.
		 *
		 * @returns array An array of all databases on the database server in the formation of
		 * 		 database_name => database_name
		 */
		public function GetDatabases()
		{
			$sSQL = "SELECT
				datname
			FROM
				pg_database
			ORDER BY
				datname";

			if( !( $oDatabases = $this->Query( $sSQL ) ) )
			{
				throw new QueryFailedException( $this->GetLastError() );
			}

			$aDatabases = array();

			foreach( $oDatabases as $oDatabase )
			{
				$aDatabases[ $oDatabase->datname ] = $oDatabase->datname;
			}

			return( $aDatabases );

		} // GetDatabases()

		/**
		 * This method returns all tables for the database the class is currently connected to.
		 *
		 * @returns array Returns an array of all tables in the form of table_name => table_name.
		 */
		public function GetTables()
		{
			$aTables = array();

			$sSQL = "SELECT
				pt.tablename,
				pp.typrelid
			FROM
				pg_tables AS pt
			INNER JOIN
				pg_type AS pp ON pp.typname = pt.tablename
			WHERE
				pt.tablename NOT LIKE 'pg_%'
			AND
				pt.tablename NOT LIKE 'sql_%'";

			if( !( $oTables = $this->Query( $sSQL ) ) )
			{
				throw new QueryFailedException( $this->GetLastError() );
			}

			$aTables = array();

			foreach( $oTables as $oTable )
			{
				$aTables[ $oTable->typrelid ] = $oTable->tablename;
			}

			return( $aTables );

		} // GetTables()

		/**
		 * Collects all fields/columns in the specified database table, as well as data type
		 * and key information.
		 *
		 */
		public function GetSchema( $sTableName )
		{
			$sCacheFile = self::$sCacheDirectory . "/" . md5( $sTableName );

			if( self::$bCacheSchemas && !isset( self::$aSchemas[ $sTableName ] ) && Cache::Exists( $sCacheFile ) )
			{
				$oCache = new Cache( $sCacheFile );
				self::$aSchemas[ $sTableName ] = unserialize( $oCache );
			}
			else
			{
                $this->GetTableColumns( $sTableName );
                $this->GetTablePrimaryKey( $sTableName );
                $this->GetTableForeignKeys( $sTableName );

                if( self::$bCacheSchemas )
                {
                    $oCache = new Cache();
                    $oCache->Save( $sCacheFile, serialize( self::$aSchemas[ $sTableName ] ), true );
                }
			}

			return( self::$aSchemas[ $sTableName ] );

		} // GetSchema()

		/**
		 * Returns an array of columns that belong to the specified table.
		 *
		 * This method stores its information the static variable $aSchemas so that if the data is
		 * required again, the database does not have to be consoluted.
		 *
		 * If schema caching is on, this method can pull data from a schema cache.
		 *
		 * @argument string The name of the table for the requested columns
		 * @returns array An array of columns that belong to the specified table
		 */
		public function GetTableColumns( $sTableName )
		{
			if( isset( self::$aSchemas[ $sTableName ][ "fields" ] ) )
			{
				return( self::$aSchemas[ $sTableName ][ "fields" ] );
			}

			$aFields = array();

			$sSQL = "SELECT
				pa.attname,
				pa.attnum,
				pat.typname,
				pa.atttypmod,
				pa.attnotnull,
				pg_get_expr( pad.adbin, pa.attrelid, true ) AS default_value,
				format_type( pa.atttypid, pa.atttypmod ) AS data_type
			FROM
				pg_attribute AS pa
			INNER JOIN
				pg_type AS pt
			ON
				pt.typrelid = pa.attrelid
			INNER JOIN
				pg_type AS pat
			ON
				pat.typelem = pa.atttypid
			LEFT JOIN
				pg_attrdef AS pad
			ON
				pad.adrelid = pa.attrelid
			AND
				pad.adnum = pa.attnum
			WHERE
				pt.typname = '{$sTableName}'
			AND
				pa.attnum > 0
			ORDER BY
				pa.attnum";

			if( !( $oFields = $this->Query( $sSQL ) ) )
			{
				throw new QueryFailedException( $this->GetLastError() );
			}

			foreach( $oFields as $iCount => $oField )
			{
				// When dropping a column with PostgreSQL, you get a lovely .pg.dropped. column
				// in the PostgreSQL catalog

				if( strpos( $oField->attname, ".pg.dropped." ) !== false )
				{
					continue;
				}

				$aFields[ $oField->attname ] = array(
					"number" => $oField->attnum,
					"field" => $oField->attname,
					"type" => $oField->data_type,
					"not-null" => $oField->attnotnull == "t",
					"default" => $oField->default_value
				);

				if( $oField->typname == "_varchar" )
				{
					$aFields[ $oField->attname ][ "size" ] = $oField->atttypmod - 4;
				}
			}

			self::$aSchemas[ $sTableName ][ "fields" ] = $aFields;

			return( $aFields );

		} // GetTableColumns()

		/**
		 * Returns an array of columns that belong to the primary key for the specified table.
		 * This method stores its information the static variable $aSchemas so that if the data is
		 * required again, the database does not have to be consoluted.
		 *
		 * If schema caching is on, this method can pull data from a schema cache.
		 *
		 * @argument string The name of hte table for the requested primary key
		 * @returns An array of columns that belong to the primary key for the specified table
		 */
		public function GetTablePrimaryKey( $sTableName )
		{
			if( isset( self::$aSchemas[ $sTableName ][ "primary_key" ] ) )
			{
				return( self::$aSchemas[ $sTableName ][ "primary_key" ] );
			}

			$aLocalTable = $this->GetTableColumns( $sTableName );

			self::$aSchemas[ $sTableName ][ "primary_key" ] = array();

			$sSQL = "SELECT
				pi.indkey
			FROM
				pg_index AS pi
			INNER JOIN
				pg_type AS pt
			ON
				pt.typrelid = pi.indrelid
			WHERE
				pt.typname = '{$sTableName}'
			AND
				pi.indisprimary = true";

			if( !( $oPrimaryKeys = $this->Query( $sSQL ) ) )
			{
				throw new QueryFailedException( $this->GetLastError() );
			}

			if( $oPrimaryKeys->Count() != 0 )
			{
				$oPrimaryKeys->Next();
				$oPrimaryKey = $oPrimaryKeys->Current();

				$aIndexFields = explode( " ", $oPrimaryKey->indkey );

				foreach( $aIndexFields as $iField )
				{
					$aField = $this->GetColumnByNumber( $sTableName, $iField );

					self::$aSchemas[ $sTableName ][ "primary_key" ][] =
						$aField[ "field" ];
				}
			}

			return( self::$aSchemas[ $sTableName ][ "primary_key" ] );

		} // GetTablePrimaryKey()

		/**
		 * Returns an array of relationships (foreign keys) for the specified table.
		 *
		 * This method stores its information the static variable $aSchemas so that if the data
		 * is required again, the database does not have to be consoluted.
		 *
		 * If schema caching is on, this method can pull data from a schema cache.
		 *
		 * @argument string The name of the table for the requested relationships
		 * @returns array An array of relationships for the table
		 */
		public function GetTableForeignKeys( $sTableName )
		{
			if( isset( self::$aSchemas[ $sTableName ][ "foreign_key" ] ) )
			{
				return( self::$aSchemas[ $sTableName ][ "foreign_key" ] );
			}

			//
			// This method needs to be cleaned up and consolidated
			//

			$aLocalTable = $this->GetTableColumns( $sTableName );

			self::$aSchemas[ $sTableName ][ "foreign_key" ] = array();

			$sSQL = "SELECT
				rpt.typname,
				pc.confrelid,
				pc.conkey,
				pc.confkey
			FROM
				pg_constraint AS pc
			INNER JOIN
				pg_type AS pt
			ON
				pt.typrelid = pc.conrelid
			INNER JOIN
				pg_type AS rpt
			ON
				rpt.typrelid = confrelid
			WHERE
				pt.typname = '{$sTableName}'
			AND
				contype = 'f'
			AND
				confrelid IS NOT NULL";

			if( !( $oForeignKeys = $this->Query( $sSQL ) ) )
			{
				throw new QueryFailedException( "Failed on Query: " . $sSQL . "\n" . $this->GetLastError() );
			}

			$iCount = 0;

			foreach( $oForeignKeys as $oForeignKey )
			{
				$aLocalFields = $aArray = explode( ",",
					str_replace( array( "{", "}" ), "", $oForeignKey->conkey ) );

				$aForeignFields = $aArray = explode( ",",
					str_replace( array( "{", "}" ), "", $oForeignKey->confkey ) );

				$aFields = $this->GetTableColumns( $oForeignKey->typname );

				foreach( $aForeignFields as $iIndex => $iField )
				{
					$aField = $this->GetColumnByNumber( $oForeignKey->typname, $iField );
					$aForeignFields[ $iIndex ] = $aField[ "field" ];
				}

				foreach( $aLocalFields as $iIndex => $iField )
				{
					$aField = $this->GetColumnByNumber( $sTableName, $iField );
					$aLocalFields[ $iIndex ] = $aField[ "field" ];
				}

				// we currently do not handle references to multiple fields:

				$localField = current( $aLocalFields );

	         	$sName = substr( $localField, strlen( $localField ) - 3 ) == "_id" ?
	         		substr( $localField, 0, strlen( $localField ) - 3 ) : $localField;

	         	$sName = StringFunctions::ToSingular( $sName );

	         	self::$aSchemas[ $sTableName ][ "foreign_key" ][ $sName ] = array(
	         		"table" => $oForeignKey->typname,
	         		"name" => $sName,
	         		"local" => $aLocalFields,
	         		"foreign" => $aForeignFields,
	         		"type" => "m-1",
	         		"dependency" => true
	         	);

	      		$iCount++;
			}

			// find tables that reference us:

			$sSQL = "SELECT
				ptr.typname,
				pc.conrelid,
				pc.conkey,
				pc.confkey
			FROM
				pg_constraint AS pc
			INNER JOIN
				pg_type AS pt
			ON
				pt.typrelid = pc.confrelid
			INNER JOIN
				pg_type AS ptr
			ON
				ptr.typrelid = pc.conrelid
			WHERE
				pt.typname = '{$sTableName}'
			AND
				contype = 'f'
			AND
				confrelid IS NOT NULL";

			if( !( $oForeignKeys = $this->Query( $sSQL ) ) )
			{
				throw new QueryFailedException( $this->GetLastError() );
			}

			foreach( $oForeignKeys as $oForeignKey )
			{
				$aLocalFields = $aArray = explode( ",",
					str_replace( array( "{", "}" ), "", $oForeignKey->confkey ) );

			 	$aForeignFields = $aArray = explode( ",",
					str_replace( array( "{", "}" ), "", $oForeignKey->conkey ) );

				$this->GetSchema( $oForeignKey->typname );

				$aFields = $this->GetTableColumns( $oForeignKey->typname );

				foreach( $aForeignFields as $iIndex => $iField )
				{
					$aField = $this->GetColumnByNumber( $oForeignKey->typname, $iField );
					$aForeignFields[ $iIndex ] = $aField[ "field" ];
				}

				foreach( $aLocalFields as $iIndex => $iField )
				{
					$aField = $this->GetColumnByNumber( $sTableName, $iField );
					$aLocalFields[ $iIndex ] = $aField[ "field" ];
				}

				$localField = reset( $aLocalFields );
				$foreignField = reset( $aForeignFields );

				// if foreign_table.local_field == foreign_table.primary_key AND
				// if local_table.foreign_key == local_table.primary_key THEN
				//		Relationship = 1-1
				// end

				$aTmpForeignPrimaryKey = &self::$aSchemas[ $oForeignKey->typname ][ "primary_key" ];
				$aTmpLocalPrimaryKey = &self::$aSchemas[ $sTableName ][ "primary_key" ];

				$bForeignFieldIsPrimary = count( $aTmpForeignPrimaryKey ) == 1 &&
					reset( $aTmpForeignPrimaryKey ) == $foreignField;
				$bLocalFieldIsPrimary = count( $aTmpLocalPrimaryKey ) &&
					reset( $aTmpLocalPrimaryKey ) == $localField;
				$bForeignIsSingular = count( $aForeignFields ) == 1;

				$sType = "1-m";

				if( $bForeignFieldIsPrimary && $bLocalFieldIsPrimary && $bForeignIsSingular )
				{
					$sType = "1-1";
				}

				self::$aSchemas[ $sTableName ][ "foreign_key" ][ $oForeignKey->typname ] = array(
					"table" => $oForeignKey->typname,
					"name" => $oForeignKey->typname,
						"local" => $aLocalFields,
					"foreign" => $aForeignFields,
					"type" => $sType,
					"dependency" => false
				);

				$iCount++;
			}

			return( self::$aSchemas[ $sTableName ][ "foreign_key" ] );

		} // GetTableForeignKeys()

		/**
		 * This method determines if the specified tables primary key (or a single column from
		 * a compound primary key) references another table.
		 *
		 * @argument string The name of the table that the key exists on
		 * @argument string The column that is, or is part of, the primary key for the table
		 * @returns boolean True if the primary key references another table, false otherwise
		 */
		public function IsPrimaryKeyReference( $sTableName, $sColumnName )
		{
			$aForeignKeys = $this->GetTableForeignKeys( $sTableName );

			foreach( $aForeignKeys as $aForeignKey )
			{
				if( $aForeignKey[ "dependency" ] && reset( $aForeignKey[ "local" ] ) == $sColumnName )
				{
					return( true );
				}
			}

			return( false );

		} // IsPrimaryKeyReference()

		/**
		 * Returns the data type of the specified column in the specified table.
		 *
		 * @argument string The name of the table that the desired column belongs to
		 * @argument string The name of the column that is desired to know the type of
		 * @returns string The data type of the column, if one is found, or null.
		 */
		public function GetColumnType( $sTableName, $sFieldName )
		{
			$aFields = $this->GetTableColumns( $sTableName );

			foreach( $aFields as $aField )
			{
				if( $sFieldName == $aField[ "field" ] )
				{
					return( $aField[ "type" ] );
				}
			}

			return( null );

		} // GetColumnType()

		/**
		 * Determines whether the specified table exists in the current database.
		 *
		 * This method first determines whether or not the table exists in the schemas array. If not,
		 * it attempts to find the table in the PostgreSQL catalog.
		 *
		 * @argument string The name of the table to determine existence
		 * @returns boolean True or false, depending on whether the table exists
		 */
		public function TableExists( $sTableName )
		{
			if( isset( self::$aSchemas[ $sTableName ] ) )
			{
				return( true );
			}

			$sSQL = "SELECT
				1
			FROM
				pg_tables
			WHERE
				LOWER( tablename ) = '" . strtolower( addslashes( $sTableName ) ) . "'";

			if( !( $oResultSet = $this->Query( $sSQL ) ) )
			{
				throw new QueryFailedException( $this->GetLastError() );
			}

			return( $oResultSet->Count() );

		} // TableExists()

		/**
		 * Returns the name of the column at the specified position from the specified table.
		 * This method is primarily interally as, in the PostgreSQL catalog, table references,
		 * indexes, etc, are stored by column number in the catalog tables.
		 *
		 * @argument string The name of the table that the desired column belongs to
		 * @argument int The column number from the table (from the PostgreSQL catalog)
		 * @returns string The name of the column, if one is found, or null
		 */
		protected function GetColumnByNumber( $sTableName, $iColumnNumber )
		{
			foreach( self::$aSchemas[ $sTableName ][ "fields" ] as $aField )
			{
				if( $aField[ "number" ] == $iColumnNumber )
				{
					return( $aField );
				}
			}

			return( null );

		} // GetColumnByNumber()

    } // PostgresDatabase()

?>


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Km.Toi.EntityFramework.Test.Model
{
    public class Product
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int ProductID { get; set; }

        public string ProductName { get; set; }

        public int? SupplierID { get; set; }

        public int? CategoryID { get; set; }

        public string QuantityPerUnit { get; set; }

        public decimal? UnitPrice { get; set; }

        public short? UnitsInStock { get; set; }

        public short? UnitsOnOrder { get; set; }

        public short? ReorderLevel { get; set; }

        public bool Discontinued { get; set; }

    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "VCharacterLiteral.h"

#include "ModelBase/src/model/Model.h"

using namespace OOModel;
using namespace Visualization;

namespace OOVisualization {

ITEM_COMMON_DEFINITIONS(VCharacterLiteral, "item")

VCharacterLiteral::VCharacterLiteral(Item* parent, NodeType* literal, const StyleType* style) :
	Super(parent, literal, style),
	vis_(nullptr)
{
}

VCharacterLiteral::~VCharacterLiteral()
{
	SAFE_DELETE_ITEM(vis_);
}

void VCharacterLiteral::determineChildren()
{
	synchronizeItem(vis_, node()->valueNode(), style());
	vis_->setStyle( style() );
}

void VCharacterLiteral::updateGeometry(int availableWidth, int availableHeight)
{
	Item::updateGeometry(vis_, availableWidth, availableHeight);
}

}


text:
[![Build Status](https://travis-ci.org/cvmfs/cvmfs.svg?branch=devel)](https://travis-ci.org/cvmfs/cvmfs) [![Documentation Status](https://readthedocs.org/projects/cvmfs/badge/?version=latest)](http://cvmfs.readthedocs.org/en/latest/?badge=master)

CVMFS is a FUSE module which implements an HTTP read-only filesystem. The idea
is based on the GROW-FS filesystem, which makes use of Parrot, a component of
the CCTools package developed at the University of Notre Dame.

CVMFS presents a remote HTTP directory as a local file system, in which the
client has read access to all available files. On its first access request, a
file is downloaded and cached locally. All downloaded pieces are verified with
SHA-1.

To do so, a directory structure is transformed into a CVMFS "repository", a
form of content-addressable storage.

This preparation of directories is transparent to web servers and web proxies,
which serve only static content, i.e., arbitrary files. Any HTTP server can do
the job.

CVMFS was created chiefly for the delivery of experiment software stacks for
the LHC experiments at CERN; development continues to address the software
distribution needs of experiments worldwide.


text:
<?php

namespace MatryoshkaTest\Model\Service;

use Matryoshka\Model\Service\AbstractServiceFactoryTrait;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Class AbstractServiceFactoryTraitTest
 */
class AbstractServiceFactoryTraitTest extends \PHPUnit_Framework_TestCase
{
    use AbstractServiceFactoryTrait;

    private $config;

    private $configKey;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    private $serviceLocatorMock;

    public function setUp()
    {
        $this->config = null;
        $this->configKey = 'test';

        $this->serviceLocatorMock = $this->getMockBuilder('\Zend\ServiceManager\ServiceLocatorInterface')
            ->setMethods(['has', 'get'])
            ->getMock();
    }

    public function testGetHydratorByNameWithoutHydratorManager()
    {
        $name = 'Zend\Stdlib\Hydrator\ObjectProperty';
        $hydrator = new $name;

        $this->serviceLocatorMock->expects($this->at(0))
            ->method('has')
            ->with('HydratorManager')
            ->will($this->returnValue(false));

        $this->serviceLocatorMock->expects($this->at(1))
            ->method('get')
            ->with($name)
            ->will($this->returnValue($hydrator));

        /** @var $serviceLocator ServiceLocatorInterface */
        $serviceLocator = $this->serviceLocatorMock;
        //Test valid hydrator type
        $return = $this->getHydratorByName($serviceLocator, $name);
        $this->assertSame($hydrator, $return);
    }

    public function testGetHydratorByNameWithoutHydratorManagerShouldThrowExceptionWhenNotValidHydrator()
    {
        $name = '\stdClass';
        $hydrator = new $name;

        $this->serviceLocatorMock->expects($this->at(0))
            ->method('has')
            ->with('HydratorManager')
            ->will($this->returnValue(false));

        $this->serviceLocatorMock->expects($this->at(1))
            ->method('get')
            ->with($name)
            ->will($this->returnValue($hydrator));

        /** @var $serviceLocator ServiceLocatorInterface */
        $serviceLocator = $this->serviceLocatorMock;
        //Test invalid hydrator tupe
        $this->setExpectedException('\Matryoshka\Model\Exception\RuntimeException');
        $this->getHydratorByName($serviceLocator, $name);
    }

    public function testGetHydratorByNameWithHydratorManager()
    {
        $name = 'Zend\Stdlib\Hydrator\ObjectProperty';
        $hydrator = new $name;
        $hydratorManagerMock = $this->getMockBuilder('Zend\Stdlib\Hydrator\HydratorPluginManager')
            ->setMethods(['get'])
            ->getMock();

        $this->serviceLocatorMock->expects($this->at(0))
            ->method('has')
            ->with('HydratorManager')
            ->will($this->returnValue(true));

        $this->serviceLocatorMock->expects($this->at(1))
            ->method('get')
            ->with('HydratorManager')
            ->will($this->returnValue($hydratorManagerMock));

        $hydratorManagerMock->expects($this->at(0))
            ->method('get')
            ->with($name)
            ->will($this->returnValue($hydrator));

        /** @var $serviceLocator ServiceLocatorInterface */
        $serviceLocator = $this->serviceLocatorMock;
        //Test valid hydrator type
        $return = $this->getHydratorByName($serviceLocator, $name);
        $this->assertSame($hydrator, $return);
    }

    public function testGetHydratorByNameWithHydratorManagerShouldThrowExceptionWhenHydratorNotValid()
    {
        $name = '\stdClass';
        $hydrator = new $name;
        $hydratorManagerMock = $this->getMockBuilder('Zend\Stdlib\Hydrator\HydratorPluginManager')
            ->setMethods(['get'])
            ->getMock();

        $this->serviceLocatorMock->expects($this->at(0))
            ->method('has')
            ->with('HydratorManager')
            ->will($this->returnValue(true));

        $this->serviceLocatorMock->expects($this->at(1))
            ->method('get')
            ->with('HydratorManager')
            ->will($this->returnValue($hydratorManagerMock));

        $hydratorManagerMock->expects($this->at(0))
            ->method('get')
            ->with($name)
            ->will($this->returnValue($hydrator));

        /** @var $serviceLocator ServiceLocatorInterface */
        $serviceLocator = $this->serviceLocatorMock;
        //Test invalid hydrator tupe
        $this->setExpectedException('\Matryoshka\Model\Exception\RuntimeException');
        $this->getHydratorByName($serviceLocator, $name);
    }

    public function testGetInputFilterByNameWithoutInputFilterManager()
    {
        $name = 'Zend\InputFilter\InputFilter';
        $inputFilter = new $name;

        $this->serviceLocatorMock->expects($this->at(0))
            ->method('has')
            ->with('InputFilterManager')
            ->will($this->returnValue(false));

        $this->serviceLocatorMock->expects($this->at(1))
            ->method('get')
            ->with($name)
            ->will($this->returnValue($inputFilter));

        /** @var $serviceLocator ServiceLocatorInterface */
        $serviceLocator = $this->serviceLocatorMock;
        //Test valid InputFilter type
        $return = $this->getInputFilterByName($serviceLocator, $name);
        $this->assertSame($inputFilter, $return);
    }

    public function testGetInputFilterByNameWithoutInputFilterManagerShouldThrowExceptionWhenNotValidInputFilter()
    {
        $name = '\stdClass';
        $inputFilter = new $name;

        $this->serviceLocatorMock->expects($this->at(0))
            ->method('has')
            ->with('InputFilterManager')
            ->will($this->returnValue(false));

        $this->serviceLocatorMock->expects($this->at(1))
            ->method('get')
            ->with($name)
            ->will($this->returnValue($inputFilter));

        /** @var $serviceLocator ServiceLocatorInterface */
        $serviceLocator = $this->serviceLocatorMock;
        //Test invalid InputFilter tupe
        $this->setExpectedException('\Matryoshka\Model\Exception\RuntimeException');
        $this->getInputFilterByName($serviceLocator, $name);
    }

    public function testGetInputFilterByNameWithInputFilterManager()
    {
        $name = 'Zend\InputFilter\InputFilter';
        $inputFilter = new $name;
        $inputFilterManagerMock = $this->getMockBuilder('Zend\InputFilter\InputFilterPluginManager')
            ->setMethods(['get'])
            ->getMock();

        $this->serviceLocatorMock->expects($this->at(0))
            ->method('has')
            ->with('InputFilterManager')
            ->will($this->returnValue(true));

        $this->serviceLocatorMock->expects($this->at(1))
            ->method('get')
            ->with('InputFilterManager')
            ->will($this->returnValue($inputFilterManagerMock));

        $inputFilterManagerMock->expects($this->at(0))
            ->method('get')
            ->with($name)
            ->will($this->returnValue($inputFilter));

        /** @var $serviceLocator ServiceLocatorInterface */
        $serviceLocator = $this->serviceLocatorMock;
        //Test valid InputFilter type
        $return = $this->getInputFilterByName($serviceLocator, $name);
        $this->assertSame($inputFilter, $return);
    }

    public function testGetInputFilterByNameWithInputFilterManagerShouldThrowExceptionWhenInputFilterNotValid()
    {
        $name = '\stdClass';
        $inputFilter = new $name;
        $inputFilterManagerMock = $this->getMockBuilder('Zend\InputFilter\InputFilterPluginManager')
            ->setMethods(['get'])
            ->getMock();

        $this->serviceLocatorMock->expects($this->at(0))
            ->method('has')
            ->with('InputFilterManager')
            ->will($this->returnValue(true));

        $this->serviceLocatorMock->expects($this->at(1))
            ->method('get')
            ->with('InputFilterManager')
            ->will($this->returnValue($inputFilterManagerMock));

        $inputFilterManagerMock->expects($this->at(0))
            ->method('get')
            ->with($name)
            ->will($this->returnValue($inputFilter));

        /** @var $serviceLocator ServiceLocatorInterface */
        $serviceLocator = $this->serviceLocatorMock;
        //Test invalid InputFilter tupe
        $this->setExpectedException('\Matryoshka\Model\Exception\RuntimeException');
        $this->getInputFilterByName($serviceLocator, $name);
    }

    public function testGetConfigWhenNodeConfigDoesNotExists()
    {
        $cfg = [];

        $this->serviceLocatorMock->expects($this->at(0))
            ->method('has')
            ->with('Config')
            ->will($this->returnValue(false));

        /** @var $serviceLocator ServiceLocatorInterface */
        $serviceLocator = $this->serviceLocatorMock;
        $return = $this->getConfig($serviceLocator);
        $this->assertSame($cfg, $return);
    }

    public function testGetConfigWhenNodeConfigExists()
    {
        $cfg = [
            $this->configKey => ['test']
        ];

        $this->serviceLocatorMock->expects($this->at(0))
            ->method('has')
            ->with('Config')
            ->will($this->returnValue(true));

        $this->serviceLocatorMock->expects($this->at(1))
            ->method('get')
            ->with('Config')
            ->will($this->returnValue($cfg));

        /** @var $serviceLocator ServiceLocatorInterface */
        $serviceLocator = $this->serviceLocatorMock;
        $return = $this->getConfig($serviceLocator);
        $this->assertSame($cfg[$this->configKey], $return);
    }

    public function testGetConfigWhenNodeConfigExistsButIsNotValid()
    {
        $cfg = [
            $this->configKey => 'string'
        ];

        $this->serviceLocatorMock->expects($this->at(0))
            ->method('has')
            ->with('Config')
            ->will($this->returnValue(true));

        $this->serviceLocatorMock->expects($this->at(1))
            ->method('get')
            ->with('Config')
            ->will($this->returnValue($cfg));

        /** @var $serviceLocator ServiceLocatorInterface */
        $serviceLocator = $this->serviceLocatorMock;
        $return = $this->getConfig($serviceLocator);
        $this->assertSame([], $return);
    }

    public function testGetConfigWhenConfigFieldNotNull()
    {
        $this->config = [];

        /** @var $serviceLocator ServiceLocatorInterface */
        $serviceLocator = $this->serviceLocatorMock;
        $return = $this->getConfig($serviceLocator);
        $this->assertSame($this->config, $return);
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Class template attribute_matches</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Boost.Log v2">
<link rel="up" href="../../../expressions.html#header.boost.log.expressions.predicates.matches_hpp" title="Header <boost/log/expressions/predicates/matches.hpp>">
<link rel="prev" href="is_in_ra_idm45948778949792.html" title="Function template is_in_range">
<link rel="next" href="matches_idm45948778927264.html" title="Function template matches">

Class template attribute_matches

boost::log::expressions::attribute_matches

Synopsis

// In header: <boost/log/expressions/predicates/matches.hpp>

template<typename T, typename RegexT,
         typename FallbackPolicyT = fallback_to_none>
class attribute_matches {
public:
  // construct/copy/destruct
  attribute_matches(attribute_name const &, RegexT const &);
  template<typename U>
    attribute_matches(attribute_name const &, RegexT const &, U const &);
};

Description

The predicate checks if the attribute value matches a regular expression. The attribute value is assumed to be of a string type.

attribute_matches
        public
       construct/copy/destruct

attribute_matches(attribute_name const & name, RegexT const & rex);

Initializing constructor

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

Parameters:

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

name

Attribute name

rex

The regular expression to match the attribute value against

template<typename U>
  attribute_matches(attribute_name const & name, RegexT const & rex,
                    U const & arg);

Initializing constructor

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

Parameters:

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

arg

Additional parameter for the fallback policy

name

Attribute name

rex

The regular expression to match the attribute value against

Copyright © 2007-2016 Andrey Semashev

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).


text:
See [https://projecteuler.net/problem=8]()

Run: `node project-euler 0008`


text:
/* 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.
 */

package org.flowable.engine.impl.migration;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.flowable.common.engine.api.FlowableException;
import org.flowable.engine.migration.ActivityMigrationMapping;
import org.flowable.engine.migration.ProcessInstanceMigrationDocument;
import org.flowable.engine.migration.ProcessInstanceMigrationDocumentConverter;

import com.fasterxml.jackson.databind.JsonNode;

/**
 * @author Dennis Federico
 */
public class ProcessInstanceMigrationDocumentImpl implements ProcessInstanceMigrationDocument {

    protected String migrateToProcessDefinitionId;
    protected String migrateToProcessDefinitionKey;
    protected Integer migrateToProcessDefinitionVersion;
    protected String migrateToProcessDefinitionTenantId;
    protected List<ActivityMigrationMapping> activityMigrationMappings;
    protected Map<String, Map<String, Object>> activitiesLocalVariables;
    protected Map<String, Object> processInstanceVariables;

    public static ProcessInstanceMigrationDocument fromProcessInstanceMigrationDocumentJson(String processInstanceMigrationDocumentJson) {
        return ProcessInstanceMigrationDocumentConverter.convertFromJson(processInstanceMigrationDocumentJson);
    }

    public void setMigrateToProcessDefinitionId(String processDefinitionId) {
        this.migrateToProcessDefinitionId = processDefinitionId;
    }

    public void setMigrateToProcessDefinition(String processDefinitionKey, Integer processDefinitionVersion) {
        this.migrateToProcessDefinitionKey = processDefinitionKey;
        this.migrateToProcessDefinitionVersion = processDefinitionVersion;
    }

    public void setMigrateToProcessDefinition(String processDefinitionKey, Integer processDefinitionVersion, String processDefinitionTenantId) {
        this.migrateToProcessDefinitionKey = processDefinitionKey;
        this.migrateToProcessDefinitionVersion = processDefinitionVersion;
        this.migrateToProcessDefinitionTenantId = processDefinitionTenantId;
    }

    @Override
    public String getMigrateToProcessDefinitionId() {
        return migrateToProcessDefinitionId;
    }

    @Override
    public String getMigrateToProcessDefinitionKey() {
        return migrateToProcessDefinitionKey;
    }

    @Override
    public Integer getMigrateToProcessDefinitionVersion() {
        return migrateToProcessDefinitionVersion;
    }

    @Override
    public String getMigrateToProcessDefinitionTenantId() {
        return migrateToProcessDefinitionTenantId;
    }

    public void setActivityMigrationMappings(List<ActivityMigrationMapping> activityMigrationMappings) {
        List<String> duplicates = findDuplicatedFromActivityIds(activityMigrationMappings);
        if (duplicates.isEmpty()) {
            this.activityMigrationMappings = activityMigrationMappings;
            this.activitiesLocalVariables = buildActivitiesLocalVariablesMap(activityMigrationMappings);
        } else {
            throw new FlowableException("From activity '" + Arrays.toString(duplicates.toArray()) + "' is mapped more than once");
        }
    }

    protected static List<String> findDuplicatedFromActivityIds(List<ActivityMigrationMapping> activityMigrationMappings) {
        //Frequency Map
        Map<String, Long> frequencyMap = activityMigrationMappings.stream()
            .filter(mapping -> !mapping.isToParentProcess())
            .flatMap(mapping -> mapping.getFromActivityIds().stream())
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        //Duplicates
        List<String> duplicatedActivityIds = frequencyMap.entrySet()
            .stream()
            .filter(entry -> entry.getValue() > 1)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());

        return duplicatedActivityIds;
    }

    protected static Map<String, Map<String, Object>> buildActivitiesLocalVariablesMap(List<ActivityMigrationMapping> activityMigrationMappings) {

        Map<String, Map<String, Object>> variablesMap = new HashMap<>();
        activityMigrationMappings.forEach(mapping -> {
            mapping.getToActivityIds().forEach(activityId -> {
                Map<String, Object> mappedLocalVariables = null;
                if (mapping instanceof ActivityMigrationMapping.OneToOneMapping) {
                    mappedLocalVariables = ((ActivityMigrationMapping.OneToOneMapping) mapping).getActivityLocalVariables();
                }
                if (mapping instanceof ActivityMigrationMapping.ManyToOneMapping) {
                    mappedLocalVariables = ((ActivityMigrationMapping.ManyToOneMapping) mapping).getActivityLocalVariables();
                }
                if (mapping instanceof ActivityMigrationMapping.OneToManyMapping) {
                    mappedLocalVariables = ((ActivityMigrationMapping.OneToManyMapping) mapping).getActivitiesLocalVariables().get(activityId);
                }
                if (mappedLocalVariables != null && !mappedLocalVariables.isEmpty()) {
                    Map<String, Object> activityLocalVariables = variablesMap.computeIfAbsent(activityId, key -> new HashMap<>());
                    activityLocalVariables.putAll(mappedLocalVariables);
                }
            });
        });
        return variablesMap;
    }

    @Override
    public List<ActivityMigrationMapping> getActivityMigrationMappings() {
        return activityMigrationMappings;
    }

    @Override
    public Map<String, Map<String, Object>> getActivitiesLocalVariables() {
        return activitiesLocalVariables;
    }

    public void setProcessInstanceVariables(Map<String, Object> processInstanceVariables) {
        this.processInstanceVariables = processInstanceVariables;
    }

    @Override
    public Map<String, Object> getProcessInstanceVariables() {
        return processInstanceVariables;
    }

    @Override
    public String asJsonString() {
        JsonNode jsonNode = ProcessInstanceMigrationDocumentConverter.convertToJson(this);
        return jsonNode.toString();
    }

    @Override
    public String toString() {
        return ProcessInstanceMigrationDocumentConverter.convertToJsonString(this);
    }
}


text:
/*
* Cipher Modes
* (C) 2013,2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#ifndef BOTAN_CIPHER_MODE_H_
#define BOTAN_CIPHER_MODE_H_

#include <botan/secmem.h>
#include <botan/sym_algo.h>
#include <botan/exceptn.h>
#include <string>
#include <vector>

namespace Botan {

/**
* The two possible directions for cipher filters, determining whether they
* actually perform encryption or decryption.
*/
enum Cipher_Dir : int { ENCRYPTION, DECRYPTION };

/**
* Interface for cipher modes
*/
class BOTAN_PUBLIC_API(2,0) Cipher_Mode : public SymmetricAlgorithm
   {
   public:
      /**
      * @return list of available providers for this algorithm, empty if not available
      * @param algo_spec algorithm name
      */
      static std::vector<std::string> providers(const std::string& algo_spec);

      /**
      * Create an AEAD mode
      * @param algo the algorithm to create
      * @param direction specify if this should be an encryption or decryption AEAD
      * @param provider optional specification for provider to use
      * @return an AEAD mode or a null pointer if not available
      */
      static std::unique_ptr<Cipher_Mode> create(const std::string& algo,
                                                 Cipher_Dir direction,
                                                 const std::string& provider = "");

      /**
      * Create an AEAD mode, or throw
      * @param algo the algorithm to create
      * @param direction specify if this should be an encryption or decryption AEAD
      * @param provider optional specification for provider to use
      * @return an AEAD mode, or throw an exception
      */
      static std::unique_ptr<Cipher_Mode> create_or_throw(const std::string& algo,
                                                          Cipher_Dir direction,
                                                          const std::string& provider = "");

      /*
      * Prepare for processing a message under the specified nonce
      */
      virtual void start_msg(const uint8_t nonce[], size_t nonce_len) = 0;

      /**
      * Begin processing a message.
      * @param nonce the per message nonce
      */
      template<typename Alloc>
      void start(const std::vector<uint8_t, Alloc>& nonce)
         {
         start_msg(nonce.data(), nonce.size());
         }

      /**
      * Begin processing a message.
      * @param nonce the per message nonce
      * @param nonce_len length of nonce
      */
      void start(const uint8_t nonce[], size_t nonce_len)
         {
         start_msg(nonce, nonce_len);
         }

      /**
      * Begin processing a message.
      */
      void start()
         {
         return start_msg(nullptr, 0);
         }

      /**
      * Process message blocks
      *
      * Input must be a multiple of update_granularity
      *
      * Processes msg in place and returns bytes written. Normally
      * this will be either msg_len (indicating the entire message was
      * processed) or for certain AEAD modes zero (indicating that the
      * mode requires the entire message be processed in one pass).
      *
      * @param msg the message to be processed
      * @param msg_len length of the message in bytes
      */
      virtual size_t process(uint8_t msg[], size_t msg_len) = 0;

      /**
      * Process some data. Input must be in size update_granularity() uint8_t blocks.
      * @param buffer in/out parameter which will possibly be resized
      * @param offset an offset into blocks to begin processing
      */
      void update(secure_vector<uint8_t>& buffer, size_t offset = 0)
         {
         BOTAN_ASSERT(buffer.size() >= offset, "Offset ok");
         uint8_t* buf = buffer.data() + offset;
         const size_t buf_size = buffer.size() - offset;

         const size_t written = process(buf, buf_size);
         buffer.resize(offset + written);
         }

      /**
      * Complete processing of a message.
      *
      * @param final_block in/out parameter which must be at least
      *        minimum_final_size() bytes, and will be set to any final output
      * @param offset an offset into final_block to begin processing
      */
      virtual void finish(secure_vector<uint8_t>& final_block, size_t offset = 0) = 0;

      /**
      * Returns the size of the output if this transform is used to process a
      * message with input_length bytes. In most cases the answer is precise.
      * If it is not possible to precise (namely for CBC decryption) instead a
      * lower bound is returned.
      */
      virtual size_t output_length(size_t input_length) const = 0;

      /**
      * @return size of required blocks to update
      */
      virtual size_t update_granularity() const = 0;

      /**
      * @return required minimium size to finalize() - may be any
      *         length larger than this.
      */
      virtual size_t minimum_final_size() const = 0;

      /**
      * @return the default size for a nonce
      */
      virtual size_t default_nonce_length() const = 0;

      /**
      * @return true iff nonce_len is a valid length for the nonce
      */
      virtual bool valid_nonce_length(size_t nonce_len) const = 0;

      /**
      * Resets just the message specific state and allows encrypting again under the existing key
      */
      virtual void reset() = 0;

      /**
      * @return true iff this mode provides authentication as well as
      * confidentiality.
      */
      bool authenticated() const { return this->tag_size() > 0; }

      /**
      * @return the size of the authentication tag used (in bytes)
      */
      virtual size_t tag_size() const { return 0; }

      /**
      * @return provider information about this implementation. Default is "base",
      * might also return "sse2", "avx2", "openssl", or some other arbitrary string.
      */
      virtual std::string provider() const { return "base"; }
   };

/**
* Get a cipher mode by name (eg "AES-128/CBC" or "Serpent/XTS")
* @param algo_spec cipher name
* @param direction ENCRYPTION or DECRYPTION
* @param provider provider implementation to choose
*/
inline Cipher_Mode* get_cipher_mode(const std::string& algo_spec,
                                    Cipher_Dir direction,
                                    const std::string& provider = "")
   {
   return Cipher_Mode::create(algo_spec, direction, provider).release();
   }

}

#endif


text:
'use strict';

/**
 * Module dependencies.
 */

var extend = require('extend-shallow');
var parsePath = require('parse-filepath');

/**
 * Expose `rte`
 */

module.exports = rte;

/**
 * Expose `rte.Rte`
 */

module.exports.Rte = Rte;

/**
 * Generate a file path from properties on the given object.
 *
 * **Examples:**
 *
 * ```js
 * rte(':a/:b:.c', { a: 'aaa', b: 'bbb', c: 'js' });
 * //=> 'aaa/bbb/c.js'
 * ```
 *
 * When a `source` file path is passed as the first argument, it will
 * be parsed and the resulting object will merged with the data
 * object (properties on the data object take precendence).
 *
 * ```js
 * rte('a/b/c.html', ':destbase/:basename', { destbase: 'foo' });
 * //=> 'foo/c.html'
 * ```
 *
 * @param {String} `src` Optionally pass a source file path to parse.
 * @param {String} `dest` Template for the destination file path with `:properties` to replace.
 * @param {Object} `data` Object with values to pass to the dest.
 * @api public
 */

function rte(src, dest, data) {
  if (typeof dest === 'object') {
    data = dest; dest = src;
  }
  var rte = new Rte(src, data);
  return rte.stringify(dest);
}

/**
 * Create an instance of Rte with the `src` file path to re-write,
 * and the `data` object with values to be used for replacing
 * `:properties`
 *
 * ```js
 * var Rte = require('rte');
 * var rte = new Rte('foo/bar/baz.hbs');
 * ```
 *
 * @param {String} `src`
 * @param {Object} `data`
 * @api private
 */

function Rte(path, data) {
  this.data = data || {};
  this.path = path;
  this.data.path = this.path;
}

/**
 * Parse a file path into an object.
 *
 * ```js
 * var parse = new rte.Rte().parse;
 * parse('a/b.html');
 *
 * // Results in:
 * // { dirname: 'a/b',
 * //   basename: 'c.coffee',
 * //   name: 'c',
 * //   extname: '.coffee',
 * //   extSegments: [ '.coffee' ] }
 * ```
 *
 * @param {String} `path` Path to parse.
 * @api private
 */

Rte.prototype.parse = function (path) {
  return parsePath(path || this.path);
};

/**
 * Process `path` and resolve template variables using values from the
 * given `data`.
 *
 * ```js
 * rte.stringify(':foo/:name.html', { foo: 'quux' });
 * //=> 'quux/baz.html'
 * ```
 *
 * @param {String} `path` Dest path with variables to replace.
 * @param {Object} `data` Object with properties used to replace variables in the path.
 * @api private
 */

Rte.prototype.stringify = function (path, data) {
  if (typeof path !== 'string') {
    data = path; path = this.path;
  }

  var ctx = extend({}, this.parse(), this.data, data);

  return path.replace(/:(\w+)/g, function (_, prop) {
    var val = ctx[prop] || '';
    if (typeof val === 'function') {
      return val.call(this, prop, ctx);
    }
    return val;
  }.bind(this));
};


text:
module CarrierWave
  module Meta
    extend ActiveSupport::Concern

    mattr_accessor :ghostscript_enabled
    self.ghostscript_enabled = false

    included do
      include CarrierWave::ModelDelegateAttribute
      include CarrierWave::MimeTypes

      set_content_type(true)

      after :retrieve_from_cache, :set_content_type
      after :retrieve_from_cache, :call_store_meta
      after :retrieve_from_store, :set_content_type unless storage.name =~ /Fog/
      after :retrieve_from_store, :call_store_meta

      model_delegate_attribute :content_type, ''
      model_delegate_attribute :file_size, 0
      model_delegate_attribute :image_size, []
      model_delegate_attribute :width, 0
      model_delegate_attribute :height, 0
      model_delegate_attribute :md5sum, ''
    end

    def store_meta(options = {})
      if self.file.present?
        dimensions = get_dimensions
        width, height = dimensions
        self.content_type = self.file.content_type
        self.file_size = self.file.size
        self.image_size = dimensions
        self.width = width
        self.height = height
        if options[:md5sum]
          self.md5sum = Digest::MD5.hexdigest(File.read(self.file.path))
        end
      end
    end

    def image_size_s
      image_size.join('x')
    end

    private
    def call_store_meta(file = nil)
      # Re-retrieve metadata for a file only if model is not present OR
      # model is not saved.
      if model.nil? || (model.respond_to?(:new_record?) && model.new_record?)
        processor_options = processors.
          find { |p| p.first == :store_meta }.
          try(:[], 1)

        store_meta(*processor_options)
      end
    end

    def get_dimensions
      [].tap do |size|
        is_image = file.content_type =~ /image/
        is_pdf =
          file.content_type =~ /postscript|pdf/ &&
          CarrierWave::Meta.ghostscript_enabled

        is_dimensionable = is_image || is_pdf

        manipulate! do |img|
          if processor?(:rmagick, img) && is_dimensionable
            size << img.columns
            size << img.rows
          elsif processor?(:mini_magick, img) && is_dimensionable
            size << img['width']
            size << img['height']
          elsif processor?(:socrecy, img) && is_image
            size << img.dimensions[:x].to_i
            size << img.dimensions[:y].to_i
          elsif processor?(:vips, img) && is_image
            size << img.x_size
            size << img.y_size
          else
            raise "Unsupported file type/image processor (use RMagick, MiniMagick, ImageSorcery, VIPS)"
          end
          img
        end
      end
    rescue CarrierWave::ProcessingError
    end

    def processor?(processor, img)
      processor = PROCESSORS[processor]
      processor_class = processor.constantize rescue nil
      processor_class.present? && img.is_a?(processor_class)
    end

    PROCESSORS = {
      rmagick: 'Magick::Image',
      mini_magick: 'MiniMagick::Image',
      socrecy: 'ImageSorcery',
      vips: 'VIPS::Image'
    }
  end
end


text:
package com.aerolitec.SMXL.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import com.aerolitec.SMXL.R;
import com.aerolitec.SMXL.model.Brand;
import com.aerolitec.SMXL.model.GarmentType;
import com.aerolitec.SMXL.tools.Constants;
import com.aerolitec.SMXL.tools.UtilityMethodsv2;
import com.aerolitec.SMXL.ui.adapter.FavoriteCheckableBrandAdapter;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class QuickMeasureCategoryShoes extends Fragment {

    private EditText et_Pointure;

    public static QuickMeasureCategoryShoes newInstance() {
        QuickMeasureCategoryShoes fragment = new QuickMeasureCategoryShoes();
        return fragment;
    }

    public QuickMeasureCategoryShoes() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_category_quick_measure_shoes, container, false);
        et_Pointure =(EditText) view.findViewById(R.id.editSize);
        ListView listView = (ListView) view.findViewById(R.id.listViewPointure);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        ArrayList<Brand> brands = new ArrayList<>();
        brands.add(new Brand(0, "POINTURE"));
        FavoriteCheckableBrandAdapter brandAdapter = new FavoriteCheckableBrandAdapter(getActivity(), R.layout.item_favorite_brand, brands);
        listView.setAdapter(brandAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                InputMethodManager mgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                et_Pointure.requestFocus();
                mgr.showSoftInput(et_Pointure, InputMethodManager.SHOW_IMPLICIT);
            }
        });
        ImageView imageView = (ImageView) view.findViewById(R.id.imageGarment);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager mgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                et_Pointure.requestFocus();
                mgr.showSoftInput(et_Pointure, InputMethodManager.SHOW_IMPLICIT);
            }
        });
        return view;

    }

    public double calculateFeetUsingSize(){
        double feet=0.0,size=0.0;
        if (!et_Pointure.getText().toString().isEmpty()){
            size = Double.valueOf(et_Pointure.getText().toString());
            feet = UtilityMethodsv2.convertFeetSizeToCm(size);
        }
        return feet;
    }
}


text:
<?php
namespace App\Http\Controllers\Api\V1;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Tymon\JWTAuth\Facades\JWTAuth;

class UserController extends Controller
{
    /**
     * 获取已经登录的用户
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAuthenticatedUser()
    {
        $user = $this->parseUserFromToken();
        return new JsonResponse([
            'data' => $user
        ]);
    }

    /**
     * 解析认证用户
     *
     * @return mixed
     */
    protected function parseUserFromToken()
    {
        if (! $user = JWTAuth::parseToken()->authenticate()) {
            throw new ModelNotFoundException(trans('model_not_found'));
        }
        return $user;
    }

    /**
     * 获取已经登录用户的角色列表
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAuthenticatedUserRoles()
    {
        $user = $this->parseUserFromToken();
        return new JsonResponse([
            'data' => $user->roles->load('permissions')
        ]);
    }

    /**
     * 获取已经登录用户的权限列表
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAuthenticatedUserPermissions()
    {
        $user = $this->parseUserFromToken();
        // 取出所有 permissons 组成一维数组
        $permissions = $user->roles->load('permissions')->transform(function ($item) {
            return $item->permissions;
        })->flatten();

        return new JsonResponse([
            'data' => $permissions
        ]);
    }

}


text:
from django.conf.urls import url
from . import views

urlpatterns = [
    url(
        r'^add-for/(?P<app_label>[\w\-]+)/(?P<model_name>[\w\-]+)/(?P<pk>\d+)/$',
        views.add_attachment,
        name="add_attachment"),
    url(
        r'^delete/(?P<attachment_pk>\d+)/$',
        views.delete_attachment,
        name="delete_attachment"),
]


text:
require 'geocoder'
require 'rest_client'
require 'magic_eightball'
require 'rvg/rvg'
require_relative 'location'
require_relative 'constants'
require_relative 'irc_handlers'
require_relative 'forecasts'
require_relative 'utils'
require_relative 'img_handlers'
require_relative 'img_forecasts'
require_relative 'img_utils'

module Lita
  module Handlers
    class OnewheelForecastIo < Handler
      config :api_key
      config :api_uri
      config :colors
      config :snowflake, default: '❄'
      config :default_location, default: 'Portland, OR'

      config :img_api_key
      config :img_api_uri

      include ::ForecastIo::Constants
      include ::ForecastIo::IrcHandlers
      include ::ForecastIo::Forecasts
      include ::ForecastIo::Utils

      include ::ForecastIo::ImgHandlers
      include ::ForecastIo::ImgForecasts
      include ::ForecastIo::ImgUtils

      # Temperature routes
      route(/^ansitemp\s*$/i, :handle_irc_ansitemp, command: true)
      route(/^ansitemp\s+(.+)/i, :handle_irc_ansitemp, command: true,
            help: {'!ansitemp [location]' => 'The 24h temperature scale for [location].'})
      route(/^dailytemp\s*$/i, :handle_irc_daily_temp, command: true)
      route(/^dailytemp\s+(.+)/i, :handle_irc_daily_temp, command: true,
            help: { '!dailytemp [location]' => '48h temperature scale for [location].'})
      route(/^7day\s*$/i, :handle_irc_seven_day, command: true)
      route(/^7day\s+(.+)/i, :handle_irc_seven_day, command: true,
            help: { '!7day [location]' => '7 day temperature scale, featuring highs and lows.'})
      route(/^weekly\s*$/i, :handle_irc_seven_day, command: true)
      route(/^weekly\s+(.+)/i, :handle_irc_seven_day, command: true,
            help: { '!weekly [location]' => 'Alias for !7day.'})
      route(/^asciitemp\s*$/i, :handle_irc_ascii_temp, command: true)
      route(/^asciitemp\s+(.+)/i, :handle_irc_ascii_temp, command: true,
            help: { '!asciitemp [location]' => 'Like ansitemp, but with less ansi.'})
      route(/^ieeetemp\s*$/i, :handle_irc_ieeetemp, command: true)
      route(/^ieeetemp\s+(.+)/i, :handle_irc_ieeetemp, command: true,
            help: {'!ieeetemp [location]' => 'The 24h temperature scale for [location], kelvin-style.'})

      # General forecast routes
      route(/^forecastallthethings\s*$/i, :handle_irc_all_the_things, command: true)
      route(/^forecastallthethings\s+(.+)/i, :handle_irc_all_the_things, command: true,
            help: { '!forecastallthethings [location]' => 'A huge dump of most available info for [location].'})
      route(/^forecast\s*$/i, :handle_irc_forecast, command: true)
      route(/^forecast\s+(.+)/i, :handle_irc_forecast, command: true,
            help: { '!forecast [location]' => 'Text forcast of the location selected.'})
      route(/^weather\s*$/i, :handle_irc_forecast, command: true)
      route(/^weather\s+(.+)/i, :handle_irc_forecast, command: true,
            help: { '!weather [location]' => 'Alias for !forecast.'})
      route(/^condi*t*i*o*n*s*\s*$/i, :handle_irc_conditions, command: true)
      route(/^condi*t*i*o*n*s*\s+(.+)/i, :handle_irc_conditions, command: true,
            help: { '!cond[itions] [location]' => 'A single-line summary of the conditions at [location].'})

      # One-offs
      route(/^rain\s*$/i, :is_it_raining)
      route(/^rain\s+(.+)/i, :is_it_raining,
            help: { '!rain [location]' => 'Magic Eightball response to whether or not it is raining in [location] right now.'})
      route(/^snow\s*$/i, :is_it_snowing)
      route(/^snow\s+(.+)/i, :is_it_snowing,
            help: { '!snow [location]' => 'Magic Eightball response to whether or not it is snowing in [location] right now.'})
      route(/^geo\s*$/i, :handle_geo_lookup, command: true)
      route(/^geo\s+(.+)/i, :handle_geo_lookup, command: true,
            help: { '!geo [location]' => 'A simple geo-lookup returning GPS coords.'})
      route(/^alerts\s*$/i, :handle_irc_alerts, command: true)
      route(/^alerts\s+(.+)/i, :handle_irc_alerts, command: true,
            help: { '!alerts [location]' => 'NOAA alerts for [location].'})
      route(/^neareststorm\s*$/i, :handle_irc_neareststorm, command: true)
      route(/^neareststorm\s+(.+)$/i, :handle_irc_neareststorm, command: true,
            help: { '!neareststorm [location]' => 'Nearest storm distance for [location].'})
      route(/^tomorrow/i, :handle_irc_tomorrow, command: true,
            help: { '!tomorrow' => 'Give me tomorrow\'s forecast as it relates to today.'})
      route(/^today/i, :handle_irc_today, command: true,
            help: { '!today' => 'Give me today\'s forecast as it relates to yesterday.'})
      route(/^Good morning./, :handle_irc_windows)  # Easter egg alert.  Thank you, zrobo and donpdonp.
      route(/^windows/i, :handle_irc_windows, command: true)
      route(/^windows\s+(.+)/i, :handle_irc_windows, command: true,
            help: { '!windows' => 'Tell me when to close my windows as it\'s warmer outside than in.'})

      # State Commands
      route(/^set scale (c|f|k)/i, :handle_irc_set_scale, command: true,
            help: { '!set scale [c|f|k]' => 'Set the scale to your chosen degrees.'})
      route(/^set scale$/i, :handle_irc_set_scale, command: true,
            help: { '!set scale' => 'Toggle between C and F scales.'})

      # Humidity
      route(/^ansihumidity\s*$/i, :handle_irc_ansi_humidity, command: true)
      route(/^ansihumidity\s+(.+)/i, :handle_irc_ansi_humidity, command: true,
            help: { '!ansihumidity [location]' => '48h humidity report for [location].'})
      route(/^dailyhumidity\s*$/i, :handle_irc_daily_humidity, command: true)
      route(/^dailyhumidity\s+(.+)/i, :handle_irc_daily_humidity, command: true,
            help: { '!dailyhumidity [location]' => '7 day humidity report.'})

      # Rain related.  Where we all started.
      route(/^ansirain\s*$/i, :handle_irc_ansirain, command: true)
      route(/^ansirain\s+(.+)/i, :handle_irc_ansirain, command: true,
            help: { '!ansirain [location]' => '60m rain chance report for [location].'})
      route(/^ansisnow\s*$/i, :handle_irc_ansirain, command: true)
      route(/^ansisnow\s+(.+)/i, :handle_irc_ansirain, command: true,
            help: { '!ansisnow [location]' => 'Alias for !ansirain.'})
      route(/^dailyrain\s*$/i, :handle_irc_daily_rain, command: true)
      route(/^dailyrain\s+(.+)/i, :handle_irc_daily_rain, command: true,
            help: { '!dailyrain [location]' => '48h rain chance report for [location].'})
      route(/^dailysnow\s*$/i, :handle_irc_daily_rain, command: true)
      route(/^dailysnow\s+(.+)/i, :handle_irc_daily_rain, command: true,
            help: { '!dailysnow [location]' => 'Alias for !dailyrain.'})
      route(/^7dayrain\s*$/i, :handle_irc_seven_day_rain, command: true)
      route(/^7dayrain\s+(.+)/i, :handle_irc_seven_day_rain, command: true,
            help: { '!7dayrain [location]' => '7 day rain chance report for [location].'})
      route(/^weeklyrain\s*$/i, :handle_irc_seven_day_rain, command: true)
      route(/^weeklyrain\s+(.+)/i, :handle_irc_seven_day_rain, command: true,
            help: { '!weeklyrain [location]' => 'Alias for !7dayrain.'})
      route(/^weeklysnow\s*$/i, :handle_irc_seven_day_rain, command: true)
      route(/^weeklysnow\s+(.+)/i, :handle_irc_seven_day_rain, command: true,
            help: { '!weeklysnow [location]' => 'Alias for !7dayrain.'})
      route(/^ansiintensity\s*$/i, :handle_irc_ansirain_intensity, command: true)
      route(/^ansiintensity\s+(.+)/i, :handle_irc_ansirain_intensity, command: true,
            help: { '!ansiintensity [location]' => '60m rain intensity report for [location].'})
      route(/^asciirain\s*$/i, :handle_irc_ascii_rain, command: true)
      route(/^asciirain\s+(.+)/i, :handle_irc_ascii_rain, command: true,
            help: { '!asciirain [location]' => '60m rain chance report for [location], ascii style!'})
      route(/^imgrain\s*$/i, :handle_img_rain)
      route(/^imgrain\s+(.+)/i, :handle_img_rain,
            help: { '!imgrain [location]' => ''})

      # don't start singing.
      route(/^sunrise\s*$/i, :handle_irc_sunrise, command: true)
      route(/^sunrise\s+(.+)/i, :handle_irc_sunrise, command: true,
            help: { '!sunrise [location]' => 'Get today\'s sunrise time for [location].'})
      route(/^sunset\s*$/i, :handle_irc_sunset, command: true)
      route(/^sunset\s+(.+)/i, :handle_irc_sunset, command: true,
            help: { '!sunset [location]' => 'Get today\'s sunset time for [location].'})
      route(/^ansisun\s*$/i, :handle_irc_ansisun, command: true)
      route(/^ansisun\s+(.+)/i, :handle_irc_ansisun, command: true,
            help: { '!ansisun [location]' => '48 hour chance-of-sun report for [location].'})
      route(/^dailysun\s*$/i, :handle_irc_dailysun, command: true)
      route(/^dailysun\s+(.+)/i, :handle_irc_dailysun, command: true,
            help: { '!ansisun [location]' => '7 day chance-of-sun report for [location].'})
      route(/^asciisun\s*$/i, :handle_irc_asciisun, command: true)
      route(/^asciisun\s+(.+)/i, :handle_irc_asciisun, command: true,
            help: { '!asciisun [location]' => '7 day chance-of-sun report for [location].'})

      # Mun!

      # Wind
      route(/^ansiwind\s*$/i, :handle_irc_ansiwind, command: true)
      route(/^ansiwind\s+(.+)/i, :handle_irc_ansiwind, command: true,
            help: { '!ansiwind [location]' => '24h wind speed/direction report for [location].'})
      route(/^asciiwind\s*$/i, :handle_irc_ascii_wind, command: true)
      route(/^asciiwind\s+(.+)/i, :handle_irc_ascii_wind, command: true,
            help: { '!asciiwind [location]' => '24h wind speed/direction report for [location], ascii style.'})
      route(/^dailywind\s*$/i, :handle_irc_daily_wind, command: true)
      route(/^dailywind\s+(.+)/i, :handle_irc_daily_wind, command: true,
            help: { '!dailywind [location]' => '7 day wind speed/direction report for [location].'})

      # Cloud cover
      route(/^asciiclouds*\s+(.+)/i, :handle_irc_asciicloud, command: true)
      route(/^asciiclouds*\s*$/i, :handle_irc_asciicloud, command: true,
            help: { '!asciicloud [location]' => '24h cloud cover report for [location].'})
      route(/^ansiclouds*\s*$/i, :handle_irc_ansicloud, command: true)
      route(/^ansiclouds*\s+(.+)/i, :handle_irc_ansicloud, command: true,
            help: { '!ansicloud [location]' => '24h cloud cover report for [location].'})

      # oooOOOoooo
      route(/^ansiozone\s*$/i, :handle_irc_ansiozone, command: true)
      route(/^ansiozone\s+(.+)/i, :handle_irc_ansiozone, command: true,
            help: { '!ansiozone [location]' => '24h ozone level report for [location].'})

      # Pressure
      route(/^ansipressure\s*$/i, :handle_irc_ansi_pressure, command: true)
      route(/^ansipressure\s+(.+)/i, :handle_irc_ansi_pressure, command: true,
            help: { '!ansipressure [location]' => '48h barometric pressure report for [location].'})
      route(/^ansibarometer\s*$/i, :handle_irc_ansi_pressure, command: true)
      route(/^ansibarometer\s+(.+)/i, :handle_irc_ansi_pressure, command: true,
            help: { '!ansibarometer [location]' => 'Alias for !ansipressure.'})
      route(/^dailypressure\s*$/i, :handle_irc_daily_pressure, command: true)
      route(/^dailypressure\s+(.+)/i, :handle_irc_daily_pressure, command: true,
            help: { '!dailypressure [location]' => '7 day barometric pressure report for [location].'})
      route(/^dailybarometer\s*$/i, :handle_irc_daily_pressure, command: true)
      route(/^dailybarometer\s+(.+)/i, :handle_irc_daily_pressure, command: true,
            help: { '!dailybarometer [location]' => 'Alias for !dailypressure.'})

      route(/^duckyou\s+(.+)/i, :handle_img_duckyou)

    end

    Lita.register_handler(OnewheelForecastIo)
  end
end


text:
module Interface
  # Contains interface testing methods to include in your test framework
  module TestHelper
    # Raises <tt>AssertionFailedError</tt> if <tt>object</tt> does not implement all methods from <tt>interfaces</tt>
    #
    # <tt>interfaces</tt> defaults to <tt>object.interfaces</tt> if none are specified
    #
    # Aliased as <tt>assert_implements_interface</tt>
    #
    # Example
    #
    #   module Remote
    #     def on
    #     end
    #
    #     def off
    #     end
    #   end
    #
    #   module MockInterface
    #   end
    #
    #   class BrokenDevice
    #     implements Remote, MockInterface
    #   end
    #
    #   class BrokenDeviceTest < Test::Unit::TestCase
    #     def test_should_implement_interfaces
    #       assert_implements_interfaces BrokenDevice.new # Failure: unimplemented interface methods for BrokenDevice: {Remote=>["off", "on"]}
    #
    #       # you can also explicitly pass interfaces to test
    #       assert_implements_interface BrokenDevice.new, MockInterface # passes
    #     end
    #   end
    def assert_implements_interfaces(object, *interfaces)
      interfaces = interfaces.empty? ? object.interfaces : interfaces.flatten
      unimplemented_methods = object.unimplemented_methods.reject { |interface, methods| !interfaces.include?(interface) }
      assert_block("unimplemented interface methods for #{object.class}: #{unimplemented_methods.inspect}") { unimplemented_methods.empty? }
    end
    alias_method :assert_implements_interface, :assert_implements_interfaces
  end
end


text:
@implementation UIDevice (CCAddition)
- (NSString *)identifierForApplication
{
    static NSString *_idfa = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *storeKey = @"identifierForApplication";
        NSDictionary *info = [NSBundle mainBundle].infoDictionary;
        NSString *bundleId = info[@"CFBundleIdentifier"];
        NSMutableDictionary *query = [NSMutableDictionary dictionary];
        query[(__bridge NSString *)kSecAttrService] = bundleId;
        query[(__bridge NSString *)kSecClass] = (__bridge id)kSecClassGenericPassword;
        query[(__bridge NSString *)kSecAttrAccount] = [storeKey description];

        query[(__bridge NSString *)kSecReturnData] = (__bridge id)kCFBooleanTrue;
        query[(__bridge NSString *)kSecMatchLimit] = (__bridge id)kSecMatchLimitOne;

        CFDataRef result = NULL;
        if (SecItemCopyMatching((__bridge CFDictionaryRef)query, (CFTypeRef *)&result) == errSecSuccess) {
            @try {
                _idfa = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge_transfer NSData *)result];
            } @catch (NSException *exception) {} @finally {}
        }
        if (_idfa == nil || ![_idfa isKindOfClass:[NSString class]] || _idfa.length == 0) {
            CFUUIDRef uuidRef = CFUUIDCreate(NULL);
            CFStringRef uuidStrRef = CFUUIDCreateString(NULL, uuidRef);
            _idfa = (__bridge_transfer NSString *)uuidStrRef;
            if (uuidRef) CFRelease(uuidRef);

            query = [NSMutableDictionary dictionary];
            query[(__bridge NSString *)kSecAttrService] = bundleId;
            query[(__bridge NSString *)kSecClass] = (__bridge id)kSecClassGenericPassword;
            query[(__bridge NSString *)kSecAttrAccount] = [storeKey description];

            query[(__bridge NSString *)kSecValueData] =  [NSKeyedArchiver archivedDataWithRootObject:_idfa];

            SecItemDelete((__bridge CFDictionaryRef)query);
            SecItemAdd((__bridge CFDictionaryRef)query, NULL);
        }
    });
    return _idfa;
}
@end


text:
package org.springframework.cloud.netflix.eureka.server;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;

import static org.springframework.cloud.netflix.eureka.server.InstanceRegistryProperties.PREFIX;

/**
 * @author Spencer Gibb
 */
@ConfigurationProperties(PREFIX)
public class InstanceRegistryProperties {

	/**
	 * Prefix for Eureka instance registry properties.
	 */
	public static final String PREFIX = "eureka.instance.registry";

	/*
	 * Default number of expected client, defaults to 1. Setting
	 * expectedNumberOfClientsSendingRenews to non-zero to ensure that even an isolated
	 * server can adjust its eviction policy to the number of registrations (when it's
	 * zero, even a successful registration won't reset the rate threshold in
	 * InstanceRegistry.register()).
	 */
	@Value("${eureka.server.expectedNumberOfRenewsPerMin:1}") // for backwards
	// compatibility
	private int expectedNumberOfClientsSendingRenews = 1;

	/**
	 * Value used in determining when leases are cancelled, default to 1 for standalone.
	 * Should be set to 0 for peer replicated eurekas
	 */
	@Value("${eureka.server.defaultOpenForTrafficCount:1}") // for backwards compatibility
	private int defaultOpenForTrafficCount = 1;

	public int getExpectedNumberOfClientsSendingRenews() {
		return expectedNumberOfClientsSendingRenews;
	}

	public void setExpectedNumberOfClientsSendingRenews(int expectedNumberOfClientsSendingRenews) {
		this.expectedNumberOfClientsSendingRenews = expectedNumberOfClientsSendingRenews;
	}

	public int getDefaultOpenForTrafficCount() {
		return defaultOpenForTrafficCount;
	}

	public void setDefaultOpenForTrafficCount(int defaultOpenForTrafficCount) {
		this.defaultOpenForTrafficCount = defaultOpenForTrafficCount;
	}

}


text:
from .repl import *
from .subprocess_repl import *
from .sublimehaskell_repl import *
from .telnet_repl import *
from .sublimepython_repl import *
from .powershell_repl import *
from .sublimeutop_repl import *
# from .execnet_repl import *  # disabled for now