text:
<?php
/**
 * MagpieRSS: a simple RSS integration tool
 *
 * A compiled file for RSS syndication
 *
 * @author Kellan Elliott-McCrea <kellan@protest.net>
 * @version 0.51
 * @license GPL
 *
 * @package External
 * @subpackage MagpieRSS
 * @deprecated 3.0.0 Use SimplePie instead.
 */

/**
 * Deprecated. Use SimplePie (class-simplepie.php) instead.
 */
_deprecated_file( basename( __FILE__ ), '3.0.0', WPINC . '/class-simplepie.php' );

/**
 * Fires before MagpieRSS is loaded, to optionally replace it.
 *
 * @since 2.3.0
 * @deprecated 3.0.0
 */
do_action( 'load_feed_engine' );

/** RSS feed constant. */
define('RSS', 'RSS');
define('ATOM', 'Atom');
define('MAGPIE_USER_AGENT', 'WordPress/' . $GLOBALS['wp_version']);

class MagpieRSS {
	var $parser;
	var $current_item	= array();	// item currently being parsed
	var $items			= array();	// collection of parsed items
	var $channel		= array();	// hash of channel fields
	var $textinput		= array();
	var $image			= array();
	var $feed_type;
	var $feed_version;

	// parser variables
	var $stack				= array(); // parser stack
	var $inchannel			= false;
	var $initem 			= false;
	var $incontent			= false; // if in Atom <content mode="xml"> field
	var $intextinput		= false;
	var $inimage 			= false;
	var $current_field		= '';
	var $current_namespace	= false;

	//var $ERROR = "";

	var $_CONTENT_CONSTRUCTS = array('content', 'summary', 'info', 'title', 'tagline', 'copyright');

	/**
	 * PHP5 constructor.
	 */
	function __construct( $source ) {

		# Check if PHP xml isn't compiled
		#
		if ( ! function_exists('xml_parser_create') ) {
			return trigger_error( "PHP's XML extension is not available. Please contact your hosting provider to enable PHP's XML extension." );
		}

		$parser = xml_parser_create();

		$this->parser = $parser;

		# pass in parser, and a reference to this object
		# set up handlers
		#
		xml_set_object( $this->parser, $this );
		xml_set_element_handler($this->parser,
				'feed_start_element', 'feed_end_element' );

		xml_set_character_data_handler( $this->parser, 'feed_cdata' );

		$status = xml_parse( $this->parser, $source );

		if (! $status ) {
			$errorcode = xml_get_error_code( $this->parser );
			if ( $errorcode != XML_ERROR_NONE ) {
				$xml_error = xml_error_string( $errorcode );
				$error_line = xml_get_current_line_number($this->parser);
				$error_col = xml_get_current_column_number($this->parser);
				$errormsg = "$xml_error at line $error_line, column $error_col";

				$this->error( $errormsg );
			}
		}

		xml_parser_free( $this->parser );
		unset( $this->parser );

		$this->normalize();
	}

	/**
	 * PHP4 constructor.
	 */
	public function MagpieRSS( $source ) {
		self::__construct( $source );
	}

	function feed_start_element($p, $element, &$attrs) {
		$el = $element = strtolower($element);
		$attrs = array_change_key_case($attrs, CASE_LOWER);

		// check for a namespace, and split if found
		$ns	= false;
		if ( strpos( $element, ':' ) ) {
			list($ns, $el) = explode( ':', $element, 2);
		}
		if ( $ns and $ns != 'rdf' ) {
			$this->current_namespace = $ns;
		}

		# if feed type isn't set, then this is first element of feed
		# identify feed from root element
		#
		if (!isset($this->feed_type) ) {
			if ( $el == 'rdf' ) {
				$this->feed_type = RSS;
				$this->feed_version = '1.0';
			}
			elseif ( $el == 'rss' ) {
				$this->feed_type = RSS;
				$this->feed_version = $attrs['version'];
			}
			elseif ( $el == 'feed' ) {
				$this->feed_type = ATOM;
				$this->feed_version = $attrs['version'];
				$this->inchannel = true;
			}
			return;
		}

		if ( $el == 'channel' )
		{
			$this->inchannel = true;
		}
		elseif ($el == 'item' or $el == 'entry' )
		{
			$this->initem = true;
			if ( isset($attrs['rdf:about']) ) {
				$this->current_item['about'] = $attrs['rdf:about'];
			}
		}

		// if we're in the default namespace of an RSS feed,
		//  record textinput or image fields
		elseif (
			$this->feed_type == RSS and
			$this->current_namespace == '' and
			$el == 'textinput' )
		{
			$this->intextinput = true;
		}

		elseif (
			$this->feed_type == RSS and
			$this->current_namespace == '' and
			$el == 'image' )
		{
			$this->inimage = true;
		}

		# handle atom content constructs
		elseif ( $this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) )
		{
			// avoid clashing w/ RSS mod_content
			if ($el == 'content' ) {
				$el = 'atom_content';
			}

			$this->incontent = $el;

		}

		// if inside an Atom content construct (e.g. content or summary) field treat tags as text
		elseif ($this->feed_type == ATOM and $this->incontent )
		{
			// if tags are inlined, then flatten
			$attrs_str = join(' ',
					array_map(array('MagpieRSS', 'map_attrs'),
					array_keys($attrs),
					array_values($attrs) ) );

			$this->append_content( "<$element $attrs_str>"  );

			array_unshift( $this->stack, $el );
		}

		// Atom support many links per containging element.
		// Magpie treats link elements of type rel='alternate'
		// as being equivalent to RSS's simple link element.
		//
		elseif ($this->feed_type == ATOM and $el == 'link' )
		{
			if ( isset($attrs['rel']) and $attrs['rel'] == 'alternate' )
			{
				$link_el = 'link';
			}
			else {
				$link_el = 'link_' . $attrs['rel'];
			}

			$this->append($link_el, $attrs['href']);
		}
		// set stack[0] to current element
		else {
			array_unshift($this->stack, $el);
		}
	}

	function feed_cdata ($p, $text) {

		if ($this->feed_type == ATOM and $this->incontent)
		{
			$this->append_content( $text );
		}
		else {
			$current_el = join('_', array_reverse($this->stack));
			$this->append($current_el, $text);
		}
	}

	function feed_end_element ($p, $el) {
		$el = strtolower($el);

		if ( $el == 'item' or $el == 'entry' )
		{
			$this->items[] = $this->current_item;
			$this->current_item = array();
			$this->initem = false;
		}
		elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'textinput' )
		{
			$this->intextinput = false;
		}
		elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'image' )
		{
			$this->inimage = false;
		}
		elseif ($this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) )
		{
			$this->incontent = false;
		}
		elseif ($el == 'channel' or $el == 'feed' )
		{
			$this->inchannel = false;
		}
		elseif ($this->feed_type == ATOM and $this->incontent  ) {
			// balance tags properly
			// note: This may not actually be necessary
			if ( $this->stack[0] == $el )
			{
				$this->append_content("</$el>");
			}
			else {
				$this->append_content("<$el />");
			}

			array_shift( $this->stack );
		}
		else {
			array_shift( $this->stack );
		}

		$this->current_namespace = false;
	}

	function concat (&$str1, $str2="") {
		if (!isset($str1) ) {
			$str1="";
		}
		$str1 .= $str2;
	}

	function append_content($text) {
		if ( $this->initem ) {
			$this->concat( $this->current_item[ $this->incontent ], $text );
		}
		elseif ( $this->inchannel ) {
			$this->concat( $this->channel[ $this->incontent ], $text );
		}
	}

	// smart append - field and namespace aware
	function append($el, $text) {
		if (!$el) {
			return;
		}
		if ( $this->current_namespace )
		{
			if ( $this->initem ) {
				$this->concat(
					$this->current_item[ $this->current_namespace ][ $el ], $text);
			}
			elseif ($this->inchannel) {
				$this->concat(
					$this->channel[ $this->current_namespace][ $el ], $text );
			}
			elseif ($this->intextinput) {
				$this->concat(
					$this->textinput[ $this->current_namespace][ $el ], $text );
			}
			elseif ($this->inimage) {
				$this->concat(
					$this->image[ $this->current_namespace ][ $el ], $text );
			}
		}
		else {
			if ( $this->initem ) {
				$this->concat(
					$this->current_item[ $el ], $text);
			}
			elseif ($this->intextinput) {
				$this->concat(
					$this->textinput[ $el ], $text );
			}
			elseif ($this->inimage) {
				$this->concat(
					$this->image[ $el ], $text );
			}
			elseif ($this->inchannel) {
				$this->concat(
					$this->channel[ $el ], $text );
			}

		}
	}

	function normalize () {
		// if atom populate rss fields
		if ( $this->is_atom() ) {
			$this->channel['descripton'] = $this->channel['tagline'];
			for ( $i = 0; $i < count($this->items); $i++) {
				$item = $this->items[$i];
				if ( isset($item['summary']) )
					$item['description'] = $item['summary'];
				if ( isset($item['atom_content']))
					$item['content']['encoded'] = $item['atom_content'];

				$this->items[$i] = $item;
			}
		}
		elseif ( $this->is_rss() ) {
			$this->channel['tagline'] = $this->channel['description'];
			for ( $i = 0; $i < count($this->items); $i++) {
				$item = $this->items[$i];
				if ( isset($item['description']))
					$item['summary'] = $item['description'];
				if ( isset($item['content']['encoded'] ) )
					$item['atom_content'] = $item['content']['encoded'];

				$this->items[$i] = $item;
			}
		}
	}

	function is_rss () {
		if ( $this->feed_type == RSS ) {
			return $this->feed_version;
		}
		else {
			return false;
		}
	}

	function is_atom() {
		if ( $this->feed_type == ATOM ) {
			return $this->feed_version;
		}
		else {
			return false;
		}
	}

	function map_attrs($k, $v) {
		return "$k=\"$v\"";
	}

	function error( $errormsg, $lvl = E_USER_WARNING ) {
		if ( MAGPIE_DEBUG ) {
			trigger_error( $errormsg, $lvl);
		} else {
			error_log( $errormsg, 0);
		}
	}

}

if ( !function_exists('fetch_rss') ) :
/**
 * Build Magpie object based on RSS from URL.
 *
 * @since 1.5.0
 * @package External
 * @subpackage MagpieRSS
 *
 * @param string $url URL to retrieve feed.
 * @return MagpieRSS|false MagpieRSS object on success, false on failure.
 */
function fetch_rss ($url) {
	// initialize constants
	init();

	if ( !isset($url) ) {
		// error("fetch_rss called without a url");
		return false;
	}

	// if cache is disabled
	if ( !MAGPIE_CACHE_ON ) {
		// fetch file, and parse it
		$resp = _fetch_remote_file( $url );
		if ( is_success( $resp->status ) ) {
			return _response_to_rss( $resp );
		}
		else {
			// error("Failed to fetch $url and cache is off");
			return false;
		}
	}
	// else cache is ON
	else {
		// Flow
		// 1. check cache
		// 2. if there is a hit, make sure it's fresh
		// 3. if cached obj fails freshness check, fetch remote
		// 4. if remote fails, return stale object, or error

		$cache = new RSSCache( MAGPIE_CACHE_DIR, MAGPIE_CACHE_AGE );

		if (MAGPIE_DEBUG and $cache->ERROR) {
			debug($cache->ERROR, E_USER_WARNING);
		}

		$cache_status 	 = 0;		// response of check_cache
		$request_headers = array(); // HTTP headers to send with fetch
		$rss 			 = 0;		// parsed RSS object
		$errormsg		 = 0;		// errors, if any

		if (!$cache->ERROR) {
			// return cache HIT, MISS, or STALE
			$cache_status = $cache->check_cache( $url );
		}

		// if object cached, and cache is fresh, return cached obj
		if ( $cache_status == 'HIT' ) {
			$rss = $cache->get( $url );
			if ( isset($rss) and $rss ) {
				$rss->from_cache = 1;
				if ( MAGPIE_DEBUG > 1) {
				debug("MagpieRSS: Cache HIT", E_USER_NOTICE);
			}
				return $rss;
			}
		}

		// else attempt a conditional get

		// set up headers
		if ( $cache_status == 'STALE' ) {
			$rss = $cache->get( $url );
			if ( isset($rss->etag) and $rss->last_modified ) {
				$request_headers['If-None-Match'] = $rss->etag;
				$request_headers['If-Last-Modified'] = $rss->last_modified;
			}
		}

		$resp = _fetch_remote_file( $url, $request_headers );

		if (isset($resp) and $resp) {
			if ($resp->status == '304' ) {
				// we have the most current copy
				if ( MAGPIE_DEBUG > 1) {
					debug("Got 304 for $url");
				}
				// reset cache on 304 (at minutillo insistent prodding)
				$cache->set($url, $rss);
				return $rss;
			}
			elseif ( is_success( $resp->status ) ) {
				$rss = _response_to_rss( $resp );
				if ( $rss ) {
					if (MAGPIE_DEBUG > 1) {
						debug("Fetch successful");
					}
					// add object to cache
					$cache->set( $url, $rss );
					return $rss;
				}
			}
			else {
				$errormsg = "Failed to fetch $url. ";
				if ( $resp->error ) {
					# compensate for Snoopy's annoying habbit to tacking
					# on '\n'
					$http_error = substr($resp->error, 0, -2);
					$errormsg .= "(HTTP Error: $http_error)";
				}
				else {
					$errormsg .=  "(HTTP Response: " . $resp->response_code .')';
				}
			}
		}
		else {
			$errormsg = "Unable to retrieve RSS file for unknown reasons.";
		}

		// else fetch failed

		// attempt to return cached object
		if ($rss) {
			if ( MAGPIE_DEBUG ) {
				debug("Returning STALE object for $url");
			}
			return $rss;
		}

		// else we totally failed
		// error( $errormsg );

		return false;

	} // end if ( !MAGPIE_CACHE_ON ) {
} // end fetch_rss()
endif;

/**
 * Retrieve URL headers and content using WP HTTP Request API.
 *
 * @since 1.5.0
 * @package External
 * @subpackage MagpieRSS
 *
 * @param string $url URL to retrieve
 * @param array $headers Optional. Headers to send to the URL.
 * @return Snoopy style response
 */
function _fetch_remote_file($url, $headers = "" ) {
	$resp = wp_safe_remote_request( $url, array( 'headers' => $headers, 'timeout' => MAGPIE_FETCH_TIME_OUT ) );
	if ( is_wp_error($resp) ) {
		$error = array_shift($resp->errors);

		$resp = new stdClass;
		$resp->status = 500;
		$resp->response_code = 500;
		$resp->error = $error[0] . "\n"; //\n = Snoopy compatibility
		return $resp;
	}

	// Snoopy returns headers unprocessed.
	// Also note, WP_HTTP lowercases all keys, Snoopy did not.
	$return_headers = array();
	foreach ( wp_remote_retrieve_headers( $resp ) as $key => $value ) {
		if ( !is_array($value) ) {
			$return_headers[] = "$key: $value";
		} else {
			foreach ( $value as $v )
				$return_headers[] = "$key: $v";
		}
	}

	$response = new stdClass;
	$response->status = wp_remote_retrieve_response_code( $resp );
	$response->response_code = wp_remote_retrieve_response_code( $resp );
	$response->headers = $return_headers;
	$response->results = wp_remote_retrieve_body( $resp );

	return $response;
}

/**
 * Retrieve
 *
 * @since 1.5.0
 * @package External
 * @subpackage MagpieRSS
 *
 * @param array $resp
 * @return MagpieRSS|bool
 */
function _response_to_rss ($resp) {
	$rss = new MagpieRSS( $resp->results );

	// if RSS parsed successfully
	if ( $rss && (!isset($rss->ERROR) || !$rss->ERROR) ) {

		// find Etag, and Last-Modified
		foreach ( (array) $resp->headers as $h) {
			// 2003-03-02 - Nicola Asuni (www.tecnick.com) - fixed bug "Undefined offset: 1"
			if (strpos($h, ": ")) {
				list($field, $val) = explode(": ", $h, 2);
			}
			else {
				$field = $h;
				$val = "";
			}

			if ( $field == 'etag' ) {
				$rss->etag = $val;
			}

			if ( $field == 'last-modified' ) {
				$rss->last_modified = $val;
			}
		}

		return $rss;
	} // else construct error message
	else {
		$errormsg = "Failed to parse RSS file.";

		if ($rss) {
			$errormsg .= " (" . $rss->ERROR . ")";
		}
		// error($errormsg);

		return false;
	} // end if ($rss and !$rss->error)
}

/**
 * Set up constants with default values, unless user overrides.
 *
 * @since 1.5.0
 * @package External
 * @subpackage MagpieRSS
 */
function init () {
	if ( defined('MAGPIE_INITALIZED') ) {
		return;
	}
	else {
		define('MAGPIE_INITALIZED', 1);
	}

	if ( !defined('MAGPIE_CACHE_ON') ) {
		define('MAGPIE_CACHE_ON', 1);
	}

	if ( !defined('MAGPIE_CACHE_DIR') ) {
		define('MAGPIE_CACHE_DIR', './cache');
	}

	if ( !defined('MAGPIE_CACHE_AGE') ) {
		define('MAGPIE_CACHE_AGE', 60*60); // one hour
	}

	if ( !defined('MAGPIE_CACHE_FRESH_ONLY') ) {
		define('MAGPIE_CACHE_FRESH_ONLY', 0);
	}

		if ( !defined('MAGPIE_DEBUG') ) {
		define('MAGPIE_DEBUG', 0);
	}

	if ( !defined('MAGPIE_USER_AGENT') ) {
		$ua = 'WordPress/' . $GLOBALS['wp_version'];

		if ( MAGPIE_CACHE_ON ) {
			$ua = $ua . ')';
		}
		else {
			$ua = $ua . '; No cache)';
		}

		define('MAGPIE_USER_AGENT', $ua);
	}

	if ( !defined('MAGPIE_FETCH_TIME_OUT') ) {
		define('MAGPIE_FETCH_TIME_OUT', 2);	// 2 second timeout
	}

	// use gzip encoding to fetch rss files if supported?
	if ( !defined('MAGPIE_USE_GZIP') ) {
		define('MAGPIE_USE_GZIP', true);
	}
}

function is_info ($sc) {
	return $sc >= 100 && $sc < 200;
}

function is_success ($sc) {
	return $sc >= 200 && $sc < 300;
}

function is_redirect ($sc) {
	return $sc >= 300 && $sc < 400;
}

function is_error ($sc) {
	return $sc >= 400 && $sc < 600;
}

function is_client_error ($sc) {
	return $sc >= 400 && $sc < 500;
}

function is_server_error ($sc) {
	return $sc >= 500 && $sc < 600;
}

class RSSCache {
	var $BASE_CACHE;	// where the cache files are stored
	var $MAX_AGE	= 43200;  		// when are files stale, default twelve hours
	var $ERROR 		= '';			// accumulate error messages

	/**
	 * PHP5 constructor.
	 */
	function __construct( $base = '', $age = '' ) {
		$this->BASE_CACHE = WP_CONTENT_DIR . '/cache';
		if ( $base ) {
			$this->BASE_CACHE = $base;
		}
		if ( $age ) {
			$this->MAX_AGE = $age;
		}

	}

	/**
	 * PHP4 constructor.
	 */
	public function RSSCache( $base = '', $age = '' ) {
		self::__construct( $base, $age );
	}

/*=======================================================================*\
	Function:	set
	Purpose:	add an item to the cache, keyed on url
	Input:		url from which the rss file was fetched
	Output:		true on success
\*=======================================================================*/
	function set ($url, $rss) {
		$cache_option = 'rss_' . $this->file_name( $url );

		set_transient($cache_option, $rss, $this->MAX_AGE);

		return $cache_option;
	}

/*=======================================================================*\
	Function:	get
	Purpose:	fetch an item from the cache
	Input:		url from which the rss file was fetched
	Output:		cached object on HIT, false on MISS
\*=======================================================================*/
	function get ($url) {
		$this->ERROR = "";
		$cache_option = 'rss_' . $this->file_name( $url );

		if ( ! $rss = get_transient( $cache_option ) ) {
			$this->debug(
				"Cache doesn't contain: $url (cache option: $cache_option)"
			);
			return 0;
		}

		return $rss;
	}

/*=======================================================================*\
	Function:	check_cache
	Purpose:	check a url for membership in the cache
				and whether the object is older then MAX_AGE (ie. STALE)
	Input:		url from which the rss file was fetched
	Output:		cached object on HIT, false on MISS
\*=======================================================================*/
	function check_cache ( $url ) {
		$this->ERROR = "";
		$cache_option = 'rss_' . $this->file_name( $url );

		if ( get_transient($cache_option) ) {
			// object exists and is current
				return 'HIT';
		} else {
			// object does not exist
			return 'MISS';
		}
	}

/*=======================================================================*\
	Function:	serialize
\*=======================================================================*/
	function serialize ( $rss ) {
		return serialize( $rss );
	}

/*=======================================================================*\
	Function:	unserialize
\*=======================================================================*/
	function unserialize ( $data ) {
		return unserialize( $data );
	}

/*=======================================================================*\
	Function:	file_name
	Purpose:	map url to location in cache
	Input:		url from which the rss file was fetched
	Output:		a file name
\*=======================================================================*/
	function file_name ($url) {
		return md5( $url );
	}

/*=======================================================================*\
	Function:	error
	Purpose:	register error
\*=======================================================================*/
	function error ($errormsg, $lvl=E_USER_WARNING) {
		$this->ERROR = $errormsg;
		if ( MAGPIE_DEBUG ) {
			trigger_error( $errormsg, $lvl);
		}
		else {
			error_log( $errormsg, 0);
		}
	}
			function debug ($debugmsg, $lvl=E_USER_NOTICE) {
		if ( MAGPIE_DEBUG ) {
			$this->error("MagpieRSS [debug] $debugmsg", $lvl);
		}
	}
}

if ( !function_exists('parse_w3cdtf') ) :
function parse_w3cdtf ( $date_str ) {

	# regex to match wc3dtf
	$pat = "/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/";

	if ( preg_match( $pat, $date_str, $match ) ) {
		list( $year, $month, $day, $hours, $minutes, $seconds) =
			array( $match[1], $match[2], $match[3], $match[4], $match[5], $match[7]);

		# calc epoch for current date assuming GMT
		$epoch = gmmktime( $hours, $minutes, $seconds, $month, $day, $year);

		$offset = 0;
		if ( $match[11] == 'Z' ) {
			# zulu time, aka GMT
		}
		else {
			list( $tz_mod, $tz_hour, $tz_min ) =
				array( $match[8], $match[9], $match[10]);

			# zero out the variables
			if ( ! $tz_hour ) { $tz_hour = 0; }
			if ( ! $tz_min ) { $tz_min = 0; }

			$offset_secs = (($tz_hour*60)+$tz_min)*60;

			# is timezone ahead of GMT?  then subtract offset
			#
			if ( $tz_mod == '+' ) {
				$offset_secs = $offset_secs * -1;
			}

			$offset = $offset_secs;
		}
		$epoch = $epoch + $offset;
		return $epoch;
	}
	else {
		return -1;
	}
}
endif;

if ( !function_exists('wp_rss') ) :
/**
 * Display all RSS items in a HTML ordered list.
 *
 * @since 1.5.0
 * @package External
 * @subpackage MagpieRSS
 *
 * @param string $url URL of feed to display. Will not auto sense feed URL.
 * @param int $num_items Optional. Number of items to display, default is all.
 */
function wp_rss( $url, $num_items = -1 ) {
	if ( $rss = fetch_rss( $url ) ) {
		echo '<ul>';

		if ( $num_items !== -1 ) {
			$rss->items = array_slice( $rss->items, 0, $num_items );
		}

		foreach ( (array) $rss->items as $item ) {
			printf(
				'<li><a href="%1$s" title="%2$s">%3$s</a></li>',
				esc_url( $item['link'] ),
				esc_attr( strip_tags( $item['description'] ) ),
				esc_html( $item['title'] )
			);
		}

		echo '</ul>';
	} else {
		_e( 'An error has occurred, which probably means the feed is down. Try again later.' );
	}
}
endif;

if ( !function_exists('get_rss') ) :
/**
 * Display RSS items in HTML list items.
 *
 * You have to specify which HTML list you want, either ordered or unordered
 * before using the function. You also have to specify how many items you wish
 * to display. You can't display all of them like you can with wp_rss()
 * function.
 *
 * @since 1.5.0
 * @package External
 * @subpackage MagpieRSS
 *
 * @param string $url URL of feed to display. Will not auto sense feed URL.
 * @param int $num_items Optional. Number of items to display, default is all.
 * @return bool False on failure.
 */
function get_rss ($url, $num_items = 5) { // Like get posts, but for RSS
	$rss = fetch_rss($url);
	if ( $rss ) {
		$rss->items = array_slice($rss->items, 0, $num_items);
		foreach ( (array) $rss->items as $item ) {
			echo "<li>\n";
			echo "<a href='$item[link]' title='$item[description]'>";
			echo esc_html($item['title']);
			echo "</a><br />\n";
			echo "</li>\n";
		}
	} else {
		return false;
	}
}
endif;


text:
package org.semanticweb.elk.reasoner.saturation.rules.contextinit;

import org.semanticweb.elk.util.collections.chains.Chain;
import org.semanticweb.elk.util.collections.chains.Chainable;

/**
 * A {@link LinkedContextInitRule} which can be added or removed to
 * {@link Chain}s of such {@link ChainableContextInitRule}s
 *
 * @author "Yevgeny Kazakov"
 *
 */
public interface ChainableContextInitRule extends LinkedContextInitRule,
		Chainable<ChainableContextInitRule> {

	// nothing else

}

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"fmt"
	"log"
)

// ProtoCommon represents a common protocol
type ProtoCommon struct {
	Status  int           `json:"status"`
	Msg     string        `json:"message,omitempty"`
	Results []interface{} `json:"results"`
}

// ProtoPosts represtnts protocol to communicate Posts
type ProtoPosts struct {
	Status int     `json:"status"`
	Msg    string  `json:"message,omitempty"`
	Posts  *[]Post `json:"posts,omitempty"`
	Post   *Post   `json:"post,omitempty"`
}

// Count counts the number of item in the protocol entity list
func (r *ProtoPosts) Count() int {
	if r.Posts == nil {
		return 0
	}
	ps := r.Posts
	return len(*ps)
}

// NthValid examines if the nth item in the entity list is valid
func (r *ProtoPosts) NthValid(n int) (err error) {
	// some test to see nth record is valid
	// such as:
	/*
		if r.Posts[n].Id == 0 {
			return fmt.Errorf("The thing has a StuffId = 0")
		}
	*/
	return
}

// GetNth retrieve the nth item from entity list
func (r *ProtoPosts) GetNth(n int) (item interface{}, err error) {
	// return the nth item
	ps := r.Posts

	// if it is a single item response
	if r.Post != nil {
		if n == 0 {
			log.Printf("run 1")
			item = r.Post
			return
		} else {
			log.Printf("run 2")
			err = fmt.Errorf(
				"n cannot be larger than 0 for single item reponses")
			return
		}
	}

	// check multiple reponse
	if ps == nil {
		err = fmt.Errorf("The list is empty")
		return
	} else if len(*ps) <= n {
		err = fmt.Errorf("Nth item doesn't exists in the response")
		return
	} else {
		fmt.Printf("len %d", len(*ps))
	}
	item = (*ps)[n]
	return
}

// Match test if the given 2 items matches each other
func (r *ProtoPosts) Match(a interface{}, b interface{}) (err error) {

	// cast a and b back to Post
	realA := a.(Post)
	realB := b.(Post)

	if realA.ID != realB.ID && realA.ID != 0 && realB.ID != 0 {
		// if either ID is 0, do not check id match
		err = fmt.Errorf("ID not match")
	} else if realA.UID != realB.UID {
		err = fmt.Errorf("UID not match")
	} else if realA.Title != realB.Title {
		err = fmt.Errorf("Title not match")
	} else if realA.Body != realB.Body {
		err = fmt.Errorf("Body not match")
	} else if realA.Size != realB.Size {
		err = fmt.Errorf("Size not match")
	} else if realA.Date.Unix() != realB.Date.Unix() {
		err = fmt.Errorf("Date not match")
	}

	return
}

// Reset reset the current list
func (r *ProtoPosts) Reset() {
	r.Status = 0
	var ps []Post
	r.Posts = &ps
	r.Post = nil
}


text:
namespace {

class TestResults {
 public:
  TestResults()
    : status_code(0),
      sub_status_code(0),
      delay(0) {
  }

  void reset() {
    url.clear();
    html.clear();
    status_code = 0;
    redirect_url.clear();
    sub_url.clear();
    sub_html.clear();
    sub_status_code = 0;
    sub_allow_origin.clear();
    exit_url.clear();
    delay = 0;
    got_request.reset();
    got_read.reset();
    got_output.reset();
    got_redirect.reset();
    got_error.reset();
    got_sub_request.reset();
    got_sub_read.reset();
    got_sub_success.reset();
  }

  std::string url;
  std::string html;
  int status_code;

  // Used for testing redirects
  std::string redirect_url;

  // Used for testing XHR requests
  std::string sub_url;
  std::string sub_html;
  int sub_status_code;
  std::string sub_allow_origin;
  std::string sub_redirect_url;
  std::string exit_url;

  // Delay for returning scheme handler results.
  int delay;

  TrackCallback
      got_request,
      got_read,
      got_output,
      got_redirect,
      got_error,
      got_sub_redirect,
      got_sub_request,
      got_sub_read,
      got_sub_success;
};

// Current scheme handler object. Used when destroying the test from
// ClientSchemeHandler::ProcessRequest().
class TestSchemeHandler;
TestSchemeHandler* g_current_handler = NULL;

class TestSchemeHandler : public TestHandler {
 public:
  explicit TestSchemeHandler(TestResults* tr)
    : test_results_(tr) {
    g_current_handler = this;
  }

  virtual void RunTest() OVERRIDE {
    CreateBrowser(test_results_->url);
  }

  // Necessary to make the method public in order to destroy the test from
  // ClientSchemeHandler::ProcessRequest().
  void DestroyTest() {
    TestHandler::DestroyTest();
  }

  virtual bool OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser,
                                    CefRefPtr<CefFrame> frame,
                                    CefRefPtr<CefRequest> request) OVERRIDE {
    std::string newUrl = request->GetURL();
    if (!test_results_->exit_url.empty() &&
        newUrl.find(test_results_->exit_url) != std::string::npos) {
      // XHR tests use an exit URL to destroy the test.
      if (newUrl.find("SUCCESS") != std::string::npos)
        test_results_->got_sub_success.yes();
      DestroyTest();
      return true;
    }

    if (!test_results_->sub_redirect_url.empty() &&
        newUrl == test_results_->sub_redirect_url) {
      test_results_->got_sub_redirect.yes();
      // Redirect to the sub URL.
      request->SetURL(test_results_->sub_url);
    } else if (newUrl == test_results_->redirect_url) {
      test_results_->got_redirect.yes();

      // No read should have occurred for the redirect.
      EXPECT_TRUE(test_results_->got_request);
      EXPECT_FALSE(test_results_->got_read);

      // Now loading the redirect URL.
      test_results_->url = test_results_->redirect_url;
      test_results_->redirect_url.clear();
    }

    return false;
  }

  virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
                         CefRefPtr<CefFrame> frame,
                         int httpStatusCode) OVERRIDE {
    std::string url = frame->GetURL();
    if (url == test_results_->url || test_results_->status_code != 200) {
      test_results_->got_output.yes();

      // Test that the status code is correct.
      EXPECT_EQ(httpStatusCode, test_results_->status_code);

      if (test_results_->sub_url.empty())
        DestroyTest();
    }
  }

  virtual void OnLoadError(CefRefPtr<CefBrowser> browser,
                           CefRefPtr<CefFrame> frame,
                           ErrorCode errorCode,
                           const CefString& errorText,
                           const CefString& failedUrl) OVERRIDE {
    test_results_->got_error.yes();
    DestroyTest();
  }

 protected:
  TestResults* test_results_;
};

class ClientSchemeHandler : public CefResourceHandler {
 public:
  explicit ClientSchemeHandler(TestResults* tr)
    : test_results_(tr),
      offset_(0),
      is_sub_(false),
      has_delayed_(false) {
  }

  virtual bool ProcessRequest(CefRefPtr<CefRequest> request,
                              CefRefPtr<CefCallback> callback) OVERRIDE {
    EXPECT_TRUE(CefCurrentlyOn(TID_IO));

    bool handled = false;

    std::string url = request->GetURL();
    is_sub_ = (!test_results_->sub_url.empty() &&
               test_results_->sub_url == url);

    if (is_sub_) {
      test_results_->got_sub_request.yes();

      if (!test_results_->sub_html.empty())
        handled = true;
    } else {
      EXPECT_EQ(url, test_results_->url);

      test_results_->got_request.yes();

      if (!test_results_->html.empty())
        handled = true;
    }

    if (handled) {
      if (test_results_->delay > 0) {
        // Continue after the delay.
        CefPostDelayedTask(TID_IO,
            base::Bind(&CefCallback::Continue, callback),
            test_results_->delay);
      } else {
        // Continue immediately.
        callback->Continue();
      }
      return true;
    }

    // Response was canceled.
    if (g_current_handler)
      g_current_handler->DestroyTest();
    return false;
  }

  virtual void GetResponseHeaders(CefRefPtr<CefResponse> response,
                                  int64& response_length,
                                  CefString& redirectUrl) OVERRIDE {
    if (is_sub_) {
      response->SetStatus(test_results_->sub_status_code);

      if (!test_results_->sub_allow_origin.empty()) {
        // Set the Access-Control-Allow-Origin header to allow cross-domain
        // scripting.
        CefResponse::HeaderMap headers;
        headers.insert(std::make_pair("Access-Control-Allow-Origin",
                                      test_results_->sub_allow_origin));
        response->SetHeaderMap(headers);
      }

      if (!test_results_->sub_html.empty()) {
        response->SetMimeType("text/html");
        response_length = test_results_->sub_html.size();
      }
    } else if (!test_results_->redirect_url.empty()) {
      redirectUrl = test_results_->redirect_url;
    } else {
      response->SetStatus(test_results_->status_code);

      if (!test_results_->html.empty()) {
        response->SetMimeType("text/html");
        response_length = test_results_->html.size();
      }
    }
  }

  virtual void Cancel() OVERRIDE {
    EXPECT_TRUE(CefCurrentlyOn(TID_IO));
  }

  virtual bool ReadResponse(void* data_out,
                            int bytes_to_read,
                            int& bytes_read,
                            CefRefPtr<CefCallback> callback) OVERRIDE {
    EXPECT_TRUE(CefCurrentlyOn(TID_IO));

    if (test_results_->delay > 0) {
      if (!has_delayed_) {
        // Continue after a delay.
        CefPostDelayedTask(TID_IO,
            base::Bind(&ClientSchemeHandler::ContinueAfterDelay,
                       this, callback),
            test_results_->delay);
         bytes_read = 0;
         return true;
      }

      has_delayed_ = false;
    }

    std::string* data;

    if (is_sub_) {
      test_results_->got_sub_read.yes();
      data = &test_results_->sub_html;
    } else {
      test_results_->got_read.yes();
      data = &test_results_->html;
    }

    bool has_data = false;
    bytes_read = 0;

    size_t size = data->size();
    if (offset_ < size) {
      int transfer_size =
          std::min(bytes_to_read, static_cast<int>(size - offset_));
      memcpy(data_out, data->c_str() + offset_, transfer_size);
      offset_ += transfer_size;

      bytes_read = transfer_size;
      has_data = true;
    }

    return has_data;
  }

 private:
  void ContinueAfterDelay(CefRefPtr<CefCallback> callback) {
    has_delayed_ = true;
    callback->Continue();
  }

  TestResults* test_results_;
  size_t offset_;
  bool is_sub_;
  bool has_delayed_;

  IMPLEMENT_REFCOUNTING(ClientSchemeHandler);
};

class ClientSchemeHandlerFactory : public CefSchemeHandlerFactory {
 public:
  explicit ClientSchemeHandlerFactory(TestResults* tr)
    : test_results_(tr) {
  }

  virtual CefRefPtr<CefResourceHandler> Create(
      CefRefPtr<CefBrowser> browser,
      CefRefPtr<CefFrame> frame,
      const CefString& scheme_name,
      CefRefPtr<CefRequest> request)
      OVERRIDE {
    EXPECT_TRUE(CefCurrentlyOn(TID_IO));
    return new ClientSchemeHandler(test_results_);
  }

  TestResults* test_results_;

  IMPLEMENT_REFCOUNTING(ClientSchemeHandlerFactory);
};

// Global test results object.
TestResults g_TestResults;

// If |domain| is empty the scheme will be registered as non-standard.
void RegisterTestScheme(const std::string& scheme, const std::string& domain) {
  g_TestResults.reset();

  EXPECT_TRUE(CefRegisterSchemeHandlerFactory(scheme, domain,
      new ClientSchemeHandlerFactory(&g_TestResults)));
  WaitForIOThread();
}

void ClearTestSchemes() {
  EXPECT_TRUE(CefClearSchemeHandlerFactories());
  WaitForIOThread();
}

struct XHRTestSettings {
  XHRTestSettings()
      : synchronous(true) {}

  std::string url;
  std::string sub_url;
  std::string sub_allow_origin;
  std::string sub_redirect_url;
  bool synchronous;
};

void SetUpXHR(const XHRTestSettings& settings) {
  g_TestResults.sub_url = settings.sub_url;
  g_TestResults.sub_html = "SUCCESS";
  g_TestResults.sub_status_code = 200;
  g_TestResults.sub_allow_origin = settings.sub_allow_origin;
  g_TestResults.sub_redirect_url = settings.sub_redirect_url;

  std::string request_url;
  if (!settings.sub_redirect_url.empty())
    request_url = settings.sub_redirect_url;
  else
    request_url = settings.sub_url;

  g_TestResults.url = settings.url;
  std::stringstream ss;
  ss << ""
        ""
        ""
        "Running execXMLHttpRequest..."
        "";
  g_TestResults.html = ss.str();
  g_TestResults.status_code = 200;

  g_TestResults.exit_url = "http://tests/exit";
}

void SetUpXSS(const std::string& url, const std::string& sub_url,
              const std::string& domain = std::string()) {
  // 1. Load |url| which contains an iframe.
  // 2. The iframe loads |xss_url|.
  // 3. |xss_url| tries to call a JS function in |url|.
  // 4. |url| tries to call a JS function in |xss_url|.

  std::stringstream ss;
  std::string domain_line;
  if (!domain.empty())
    domain_line = "document.domain = '" + domain + "';";

  g_TestResults.sub_url = sub_url;
  ss << ""
        ""
        ""
        "Running execXSSRequest..."
        "";
  g_TestResults.sub_html = ss.str();
  g_TestResults.sub_status_code = 200;

  g_TestResults.url = url;
  ss.str("");
  ss << ""
        ""
        ""
        "<iframe src=\"" << sub_url.c_str() << "\" id=\"s\">"
        "";
  g_TestResults.html = ss.str();
  g_TestResults.status_code = 200;

  g_TestResults.exit_url = "http://tests/exit";
}

}  // namespace

// Test that scheme registration/unregistration works as expected.
TEST(SchemeHandlerTest, Registration) {
  RegisterTestScheme("customstd", "test");
  g_TestResults.url = "customstd://test/run.html";
  g_TestResults.html =
      "
Success!
";
  g_TestResults.status_code = 200;

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);

  // Unregister the handler.
  EXPECT_TRUE(CefRegisterSchemeHandlerFactory("customstd", "test", NULL));
  WaitForIOThread();

  g_TestResults.got_request.reset();
  g_TestResults.got_read.reset();
  g_TestResults.got_output.reset();
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_error);
  EXPECT_FALSE(g_TestResults.got_request);
  EXPECT_FALSE(g_TestResults.got_read);
  EXPECT_FALSE(g_TestResults.got_output);

  // Re-register the handler.
  EXPECT_TRUE(CefRegisterSchemeHandlerFactory("customstd", "test",
      new ClientSchemeHandlerFactory(&g_TestResults)));
  WaitForIOThread();

  g_TestResults.got_error.reset();
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);

  ClearTestSchemes();
}

// Test that a custom standard scheme can return normal results.
TEST(SchemeHandlerTest, CustomStandardNormalResponse) {
  RegisterTestScheme("customstd", "test");
  g_TestResults.url = "customstd://test/run.html";
  g_TestResults.html =
      "
Success!
";
  g_TestResults.status_code = 200;

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);

  ClearTestSchemes();
}

// Test that a custom standard scheme can return normal results with delayed
// responses.
TEST(SchemeHandlerTest, CustomStandardNormalResponseDelayed) {
  RegisterTestScheme("customstd", "test");
  g_TestResults.url = "customstd://test/run.html";
  g_TestResults.html =
      "
Success!
";
  g_TestResults.status_code = 200;
  g_TestResults.delay = 100;

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);

  ClearTestSchemes();
}

// Test that a custom nonstandard scheme can return normal results.
TEST(SchemeHandlerTest, CustomNonStandardNormalResponse) {
  RegisterTestScheme("customnonstd", std::string());
  g_TestResults.url = "customnonstd:some%20value";
  g_TestResults.html =
      "
Success!
";
  g_TestResults.status_code = 200;

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);

  ClearTestSchemes();
}

// Test that a custom standard scheme can return an error code.
TEST(SchemeHandlerTest, CustomStandardErrorResponse) {
  RegisterTestScheme("customstd", "test");
  g_TestResults.url = "customstd://test/run.html";
  g_TestResults.html =
      "
404
";
  g_TestResults.status_code = 404;

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);

  ClearTestSchemes();
}

// Test that a custom nonstandard scheme can return an error code.
TEST(SchemeHandlerTest, CustomNonStandardErrorResponse) {
  RegisterTestScheme("customnonstd", std::string());
  g_TestResults.url = "customnonstd:some%20value";
  g_TestResults.html =
      "
404
";
  g_TestResults.status_code = 404;

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);

  ClearTestSchemes();
}

// Test that custom standard scheme handling fails when the scheme name is
// incorrect.
TEST(SchemeHandlerTest, CustomStandardNameNotHandled) {
  RegisterTestScheme("customstd", "test");
  g_TestResults.url = "customstd2://test/run.html";

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_FALSE(g_TestResults.got_request);
  EXPECT_FALSE(g_TestResults.got_read);
  EXPECT_FALSE(g_TestResults.got_output);

  ClearTestSchemes();
}

// Test that custom nonstandard scheme handling fails when the scheme name is
// incorrect.
TEST(SchemeHandlerTest, CustomNonStandardNameNotHandled) {
  RegisterTestScheme("customnonstd", std::string());
  g_TestResults.url = "customnonstd2:some%20value";

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_FALSE(g_TestResults.got_request);
  EXPECT_FALSE(g_TestResults.got_read);
  EXPECT_FALSE(g_TestResults.got_output);

  ClearTestSchemes();
}

// Test that custom standard scheme handling fails when the domain name is
// incorrect.
TEST(SchemeHandlerTest, CustomStandardDomainNotHandled) {
  RegisterTestScheme("customstd", "test");
  g_TestResults.url = "customstd://noexist/run.html";

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_FALSE(g_TestResults.got_request);
  EXPECT_FALSE(g_TestResults.got_read);
  EXPECT_FALSE(g_TestResults.got_output);

  ClearTestSchemes();
}

// Test that a custom standard scheme can return no response.
TEST(SchemeHandlerTest, CustomStandardNoResponse) {
  RegisterTestScheme("customstd", "test");
  g_TestResults.url = "customstd://test/run.html";

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_FALSE(g_TestResults.got_read);
  EXPECT_FALSE(g_TestResults.got_output);

  ClearTestSchemes();
}

// Test that a custom nonstandard scheme can return no response.
TEST(SchemeHandlerTest, CustomNonStandardNoResponse) {
  RegisterTestScheme("customnonstd", std::string());
  g_TestResults.url = "customnonstd:some%20value";

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_FALSE(g_TestResults.got_read);
  EXPECT_FALSE(g_TestResults.got_output);

  ClearTestSchemes();
}

// Test that a custom standard scheme can generate redirects.
TEST(SchemeHandlerTest, CustomStandardRedirect) {
  RegisterTestScheme("customstd", "test");
  g_TestResults.url = "customstd://test/run.html";
  g_TestResults.redirect_url = "customstd://test/redirect.html";
  g_TestResults.html =
      "
Redirected
";

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_redirect);

  ClearTestSchemes();
}

// Test that a custom nonstandard scheme can generate redirects.
TEST(SchemeHandlerTest, CustomNonStandardRedirect) {
  RegisterTestScheme("customnonstd", std::string());
  g_TestResults.url = "customnonstd:some%20value";
  g_TestResults.redirect_url = "customnonstd:some%20other%20value";
  g_TestResults.html =
      "
Redirected
";

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_redirect);

  ClearTestSchemes();
}

// Test that a custom standard scheme can generate same origin XHR requests.
TEST(SchemeHandlerTest, CustomStandardXHRSameOriginSync) {
  RegisterTestScheme("customstd", "test");

  XHRTestSettings settings;
  settings.url = "customstd://test/run.html";
  settings.sub_url = "customstd://test/xhr.html";
  SetUpXHR(settings);

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that a custom standard scheme can generate same origin XHR requests.
TEST(SchemeHandlerTest, CustomStandardXHRSameOriginAsync) {
  RegisterTestScheme("customstd", "test");

  XHRTestSettings settings;
  settings.url = "customstd://test/run.html";
  settings.sub_url = "customstd://test/xhr.html";
  settings.synchronous = false;
  SetUpXHR(settings);

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that a custom nonstandard scheme can generate same origin XHR requests.
TEST(SchemeHandlerTest, CustomNonStandardXHRSameOriginSync) {
  RegisterTestScheme("customnonstd", std::string());

  XHRTestSettings settings;
  settings.url = "customnonstd:some%20value";
  settings.sub_url = "customnonstd:xhr%20value";
  SetUpXHR(settings);

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that a custom nonstandard scheme can generate same origin XHR requests.
TEST(SchemeHandlerTest, CustomNonStandardXHRSameOriginAsync) {
  RegisterTestScheme("customnonstd", std::string());

  XHRTestSettings settings;
  settings.url = "customnonstd:some%20value";
  settings.sub_url = "customnonstd:xhr%20value";
  settings.synchronous = false;
  SetUpXHR(settings);

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that a custom standard scheme can generate same origin XSS requests.
TEST(SchemeHandlerTest, CustomStandardXSSSameOrigin) {
  RegisterTestScheme("customstd", "test");
  SetUpXSS("customstd://test/run.html",
           "customstd://test/iframe.html");

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that a custom nonstandard scheme can generate same origin XSS requests.
TEST(SchemeHandlerTest, CustomNonStandardXSSSameOrigin) {
  RegisterTestScheme("customnonstd", std::string());
  SetUpXSS("customnonstd:some%20value",
           "customnonstd:xhr%20value");

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that a custom standard scheme cannot generate cross-domain XHR requests
// by default. Behavior should be the same as with HTTP.
TEST(SchemeHandlerTest, CustomStandardXHRDifferentOriginSync) {
  RegisterTestScheme("customstd", "test1");
  RegisterTestScheme("customstd", "test2");

  XHRTestSettings settings;
  settings.url = "customstd://test1/run.html";
  settings.sub_url = "customstd://test2/xhr.html";
  SetUpXHR(settings);

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_FALSE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that a custom standard scheme cannot generate cross-domain XHR requests
// by default. Behavior should be the same as with HTTP.
TEST(SchemeHandlerTest, CustomStandardXHRDifferentOriginAsync) {
  RegisterTestScheme("customstd", "test1");
  RegisterTestScheme("customstd", "test2");

  XHRTestSettings settings;
  settings.url = "customstd://test1/run.html";
  settings.sub_url = "customstd://test2/xhr.html";
  settings.synchronous = false;
  SetUpXHR(settings);

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_FALSE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that a custom standard scheme cannot generate cross-domain XSS requests
// by default.
TEST(SchemeHandlerTest, CustomStandardXSSDifferentOrigin) {
  RegisterTestScheme("customstd", "test1");
  RegisterTestScheme("customstd", "test2");
  SetUpXSS("customstd://test1/run.html",
           "customstd://test2/iframe.html");

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_FALSE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that an HTTP scheme cannot generate cross-domain XHR requests by
// default.
TEST(SchemeHandlerTest, HttpXHRDifferentOriginSync) {
  RegisterTestScheme("http", "test1");
  RegisterTestScheme("http", "test2");

  XHRTestSettings settings;
  settings.url = "http://test1/run.html";
  settings.sub_url = "http://test2/xhr.html";
  SetUpXHR(settings);

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_FALSE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that an HTTP scheme cannot generate cross-domain XHR requests by
// default.
TEST(SchemeHandlerTest, HttpXHRDifferentOriginAsync) {
  RegisterTestScheme("http", "test1");
  RegisterTestScheme("http", "test2");

  XHRTestSettings settings;
  settings.url = "http://test1/run.html";
  settings.sub_url = "http://test2/xhr.html";
  settings.synchronous = false;
  SetUpXHR(settings);

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_FALSE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that an HTTP scheme cannot generate cross-domain XSS requests by
// default.
TEST(SchemeHandlerTest, HttpXSSDifferentOrigin) {
  RegisterTestScheme("http", "test1");
  RegisterTestScheme("http", "test2");
  SetUpXSS("http://test1/run.html",
           "http://test2/xss.html");

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_FALSE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that a custom standard scheme can generate cross-domain XHR requests
// when setting the Access-Control-Allow-Origin header. Should behave the same
// as HTTP.
TEST(SchemeHandlerTest, CustomStandardXHRDifferentOriginWithHeaderSync) {
  RegisterTestScheme("customstd", "test1");
  RegisterTestScheme("customstd", "test2");

  XHRTestSettings settings;
  settings.url = "customstd://test1/run.html";
  settings.sub_url = "customstd://test2/xhr.html";
  settings.sub_allow_origin = "customstd://test1";
  SetUpXHR(settings);

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that a custom standard scheme can generate cross-domain XHR requests
// when setting the Access-Control-Allow-Origin header. Should behave the same
// as HTTP.
TEST(SchemeHandlerTest, CustomStandardXHRDifferentOriginWithHeaderAsync) {
  RegisterTestScheme("customstd", "test1");
  RegisterTestScheme("customstd", "test2");

  XHRTestSettings settings;
  settings.url = "customstd://test1/run.html";
  settings.sub_url = "customstd://test2/xhr.html";
  settings.sub_allow_origin = "customstd://test1";
  settings.synchronous = false;
  SetUpXHR(settings);

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that a custom standard scheme can generate cross-domain XHR requests
// when using the cross-origin whitelist.
TEST(SchemeHandlerTest, CustomStandardXHRDifferentOriginWithWhitelistSync1) {
  RegisterTestScheme("customstd", "test1");
  RegisterTestScheme("customstd", "test2");

  XHRTestSettings settings;
  settings.url = "customstd://test1/run.html";
  settings.sub_url = "customstd://test2/xhr.html";
  SetUpXHR(settings);

  EXPECT_TRUE(CefAddCrossOriginWhitelistEntry("customstd://test1", "customstd",
      "test2", false));
  WaitForUIThread();

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  EXPECT_TRUE(CefClearCrossOriginWhitelist());
  WaitForUIThread();

  ClearTestSchemes();
}

// Same as above but origin whitelist matches any domain.
TEST(SchemeHandlerTest, CustomStandardXHRDifferentOriginWithWhitelistSync2) {
  RegisterTestScheme("customstd", "test1");
  RegisterTestScheme("customstd", "test2");

  XHRTestSettings settings;
  settings.url = "customstd://test1/run.html";
  settings.sub_url = "customstd://test2/xhr.html";
  SetUpXHR(settings);

  EXPECT_TRUE(CefAddCrossOriginWhitelistEntry("customstd://test1", "customstd",
      CefString(), true));
  WaitForUIThread();

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  EXPECT_TRUE(CefClearCrossOriginWhitelist());
  WaitForUIThread();

  ClearTestSchemes();
}

// Same as above but origin whitelist matches sub-domains.
TEST(SchemeHandlerTest, CustomStandardXHRDifferentOriginWithWhitelistSync3) {
  RegisterTestScheme("customstd", "test1");
  RegisterTestScheme("customstd", "a.test2.foo");

  XHRTestSettings settings;
  settings.url = "customstd://test1/run.html";
  settings.sub_url = "customstd://a.test2.foo/xhr.html";
  SetUpXHR(settings);

  EXPECT_TRUE(CefAddCrossOriginWhitelistEntry("customstd://test1", "customstd",
      "test2.foo", true));
  WaitForUIThread();

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  EXPECT_TRUE(CefClearCrossOriginWhitelist());
  WaitForUIThread();

  ClearTestSchemes();
}

// Test that a custom standard scheme can generate cross-domain XHR requests
// when using the cross-origin whitelist.
TEST(SchemeHandlerTest, CustomStandardXHRDifferentOriginWithWhitelistAsync1) {
  RegisterTestScheme("customstd", "test1");
  RegisterTestScheme("customstd", "test2");

  XHRTestSettings settings;
  settings.url = "customstd://test1/run.html";
  settings.sub_url = "customstd://test2/xhr.html";
  settings.synchronous = false;
  SetUpXHR(settings);

  EXPECT_TRUE(CefAddCrossOriginWhitelistEntry("customstd://test1", "customstd",
      "test2", false));
  WaitForUIThread();

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  EXPECT_TRUE(CefClearCrossOriginWhitelist());
  WaitForUIThread();

  ClearTestSchemes();
}

// Same as above but origin whitelist matches any domain.
TEST(SchemeHandlerTest, CustomStandardXHRDifferentOriginWithWhitelistAsync2) {
  RegisterTestScheme("customstd", "test1");
  RegisterTestScheme("customstd", "test2");

  XHRTestSettings settings;
  settings.url = "customstd://test1/run.html";
  settings.sub_url = "customstd://test2/xhr.html";
  settings.synchronous = false;
  SetUpXHR(settings);

  EXPECT_TRUE(CefAddCrossOriginWhitelistEntry("customstd://test1", "customstd",
      CefString(), true));
  WaitForUIThread();

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  EXPECT_TRUE(CefClearCrossOriginWhitelist());
  WaitForUIThread();

  ClearTestSchemes();
}

// Same as above but origin whitelist matches sub-domains.
TEST(SchemeHandlerTest, CustomStandardXHRDifferentOriginWithWhitelistAsync3) {
  RegisterTestScheme("customstd", "test1");
  RegisterTestScheme("customstd", "a.test2.foo");

  XHRTestSettings settings;
  settings.url = "customstd://test1/run.html";
  settings.sub_url = "customstd://a.test2.foo/xhr.html";
  settings.synchronous = false;
  SetUpXHR(settings);

  EXPECT_TRUE(CefAddCrossOriginWhitelistEntry("customstd://test1", "customstd",
      "test2.foo", true));
  WaitForUIThread();

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  EXPECT_TRUE(CefClearCrossOriginWhitelist());
  WaitForUIThread();

  ClearTestSchemes();
}

// Test that an HTTP scheme can generate cross-domain XHR requests when setting
// the Access-Control-Allow-Origin header.
TEST(SchemeHandlerTest, HttpXHRDifferentOriginWithHeaderSync) {
  RegisterTestScheme("http", "test1");
  RegisterTestScheme("http", "test2");

  XHRTestSettings settings;
  settings.url = "http://test1/run.html";
  settings.sub_url = "http://test2/xhr.html";
  settings.sub_allow_origin = "http://test1";
  SetUpXHR(settings);

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that an HTTP scheme can generate cross-domain XHR requests when setting
// the Access-Control-Allow-Origin header.
TEST(SchemeHandlerTest, HttpXHRDifferentOriginWithHeaderAsync) {
  RegisterTestScheme("http", "test1");
  RegisterTestScheme("http", "test2");

  XHRTestSettings settings;
  settings.url = "http://test1/run.html";
  settings.sub_url = "http://test2/xhr.html";
  settings.sub_allow_origin = "http://test1";
  settings.synchronous = false;
  SetUpXHR(settings);

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that a custom standard scheme can generate cross-domain XSS requests
// when using document.domain.
TEST(SchemeHandlerTest, CustomStandardXSSDifferentOriginWithDomain) {
  RegisterTestScheme("customstd", "a.test.com");
  RegisterTestScheme("customstd", "b.test.com");
  SetUpXSS("customstd://a.test.com/run.html",
           "customstd://b.test.com/iframe.html",
           "test.com");

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that an HTTP scheme can generate cross-domain XSS requests when using
// document.domain.
TEST(SchemeHandlerTest, HttpXSSDifferentOriginWithDomain) {
  RegisterTestScheme("http", "a.test.com");
  RegisterTestScheme("http", "b.test.com");
  SetUpXSS("http://a.test.com/run.html",
           "http://b.test.com/iframe.html",
           "test.com");

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that a custom standard scheme cannot generate cross-domain XHR requests
// that perform redirects.
TEST(SchemeHandlerTest, CustomStandardXHRDifferentOriginRedirectSync) {
  RegisterTestScheme("customstd", "test1");
  RegisterTestScheme("customstd", "test2");

  XHRTestSettings settings;
  settings.url = "customstd://test1/run.html";
  settings.sub_url = "customstd://test2/xhr.html";
  settings.sub_redirect_url = "customstd://test1/xhr.html";
  SetUpXHR(settings);

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_redirect);
  EXPECT_FALSE(g_TestResults.got_sub_request);
  EXPECT_FALSE(g_TestResults.got_sub_read);
  EXPECT_FALSE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that a custom standard scheme cannot generate cross-domain XHR requests
// that perform redirects.
TEST(SchemeHandlerTest, CustomStandardXHRDifferentOriginRedirectAsync) {
  RegisterTestScheme("customstd", "test1");
  RegisterTestScheme("customstd", "test2");

  XHRTestSettings settings;
  settings.url = "customstd://test1/run.html";
  settings.sub_url = "customstd://test2/xhr.html";
  settings.sub_redirect_url = "customstd://test1/xhr.html";
  settings.synchronous = false;
  SetUpXHR(settings);

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_redirect);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_FALSE(g_TestResults.got_sub_success);

  ClearTestSchemes();
}

// Test that a custom standard scheme cannot generate cross-domain XHR requests
// that perform redirects when using the cross-origin whitelist. This is due to
// an explicit check in SyncResourceHandler::OnRequestRedirected() and does not
// represent ideal behavior.
TEST(SchemeHandlerTest,
     CustomStandardXHRDifferentOriginRedirectWithWhitelistSync) {
  RegisterTestScheme("customstd", "test1");
  RegisterTestScheme("customstd", "test2");

  XHRTestSettings settings;
  settings.url = "customstd://test1/run.html";
  settings.sub_url = "customstd://test2/xhr.html";
  settings.sub_redirect_url = "customstd://test1/xhr.html";
  SetUpXHR(settings);

  EXPECT_TRUE(CefAddCrossOriginWhitelistEntry("customstd://test1", "customstd",
      "test2", false));
  WaitForUIThread();

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_redirect);
  EXPECT_FALSE(g_TestResults.got_sub_request);
  EXPECT_FALSE(g_TestResults.got_sub_read);
  EXPECT_FALSE(g_TestResults.got_sub_success);

  EXPECT_TRUE(CefClearCrossOriginWhitelist());
  WaitForUIThread();

  ClearTestSchemes();
}

// Test that a custom standard scheme can generate cross-domain XHR requests
// that perform redirects when using the cross-origin whitelist. This is
// because we add an "Access-Control-Allow-Origin" header internally in
// CefResourceDispatcherHostDelegate::OnRequestRedirected() for the redirect
// request.
TEST(SchemeHandlerTest,
     CustomStandardXHRDifferentOriginRedirectWithWhitelistAsync1) {
  RegisterTestScheme("customstd", "test1");
  RegisterTestScheme("customstd", "test2");

  XHRTestSettings settings;
  settings.url = "customstd://test1/run.html";
  settings.sub_url = "customstd://test2/xhr.html";
  settings.sub_redirect_url = "customstd://test1/xhr.html";
  settings.synchronous = false;
  SetUpXHR(settings);

  EXPECT_TRUE(CefAddCrossOriginWhitelistEntry("customstd://test1", "customstd",
      "test2", false));
  WaitForUIThread();

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_redirect);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  EXPECT_TRUE(CefClearCrossOriginWhitelist());
  WaitForUIThread();

  ClearTestSchemes();
}

// Same as above but origin whitelist matches any domain.
TEST(SchemeHandlerTest,
     CustomStandardXHRDifferentOriginRedirectWithWhitelistAsync2) {
  RegisterTestScheme("customstd", "test1");
  RegisterTestScheme("customstd", "test2");

  XHRTestSettings settings;
  settings.url = "customstd://test1/run.html";
  settings.sub_url = "customstd://test2/xhr.html";
  settings.sub_redirect_url = "customstd://test1/xhr.html";
  settings.synchronous = false;
  SetUpXHR(settings);

  EXPECT_TRUE(CefAddCrossOriginWhitelistEntry("customstd://test1", "customstd",
      CefString(), true));
  WaitForUIThread();

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_redirect);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  EXPECT_TRUE(CefClearCrossOriginWhitelist());
  WaitForUIThread();

  ClearTestSchemes();
}

// Same as above but origin whitelist matches sub-domains.
TEST(SchemeHandlerTest,
     CustomStandardXHRDifferentOriginRedirectWithWhitelistAsync3) {
  RegisterTestScheme("customstd", "test1");
  RegisterTestScheme("customstd", "a.test2.foo");

  XHRTestSettings settings;
  settings.url = "customstd://test1/run.html";
  settings.sub_url = "customstd://a.test2.foo/xhr.html";
  settings.sub_redirect_url = "customstd://test1/xhr.html";
  settings.synchronous = false;
  SetUpXHR(settings);

  EXPECT_TRUE(CefAddCrossOriginWhitelistEntry("customstd://test1", "customstd",
      "test2.foo", true));
  WaitForUIThread();

  CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
  handler->ExecuteTest();

  EXPECT_TRUE(g_TestResults.got_request);
  EXPECT_TRUE(g_TestResults.got_read);
  EXPECT_TRUE(g_TestResults.got_output);
  EXPECT_TRUE(g_TestResults.got_sub_redirect);
  EXPECT_TRUE(g_TestResults.got_sub_request);
  EXPECT_TRUE(g_TestResults.got_sub_read);
  EXPECT_TRUE(g_TestResults.got_sub_success);

  EXPECT_TRUE(CefClearCrossOriginWhitelist());
  WaitForUIThread();

  ClearTestSchemes();
}

// Entry point for registering custom schemes.
// Called from client_app_delegates.cc.
void RegisterSchemeHandlerCustomSchemes(
      CefRefPtr<CefSchemeRegistrar> registrar,
      std::vector<CefString>& cookiable_schemes) {
  // Add a custom standard scheme.
  registrar->AddCustomScheme("customstd", true, false, false);
  // Ad a custom non-standard scheme.
  registrar->AddCustomScheme("customnonstd", false, false, false);
}


text:
<?php
 #21539288 POLELA AL
 include('includes/header.php');
 session_start();
 if(!isset($_SESSION['chat_employee']))
 {
   header('Location: login.php');
 }
 ?>

                           Live Support

                              <button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">

                              </button>

                                  Refresh

                                  Available

                                  Busy

                                      Away

                                      End chat

                        <form class="form" id="chatBox" method="post" action="" onSubmit="">

                                              <input id="btn-input" type="text" name="message" class="form-control input-sm" placeholder="Type your message here...">

                                                  <button class="btn btn-warning btn-sm" onClick="return messageInsert();" name="Send" id="btn-chat">Send</button>

                                      </form>


text:
{{ vm.title }}

            <ng-transclude></ng-transclude>


text:
html,body{scrollbar-face-color:#ffffff;scrollbar-highlight-color:#ffffff;border-bottom:white 2px solid;scrollbar-darkshadow-color:#ffffff;}

/* header */
#header{margin:10px 20px 15px 0;}
#header h1{color: #0663A2;}
#header h1 small{color: #0088CC;}

/* footer */
#footer{margin:15px 0 0 0;padding:15px 0 0 0;font-size:95%;text-align:center;border-top:2px solid #0663A2;}
#footer a{color: #999;}

/* frame */
#left,#right,#openClose{float:left;}
#openClose{width:14px;margin:0 3px;cursor:pointer;background-color:#fcfcfc;}
.open,.close{background:url("images/openclose.png") no-repeat 4px center;}
.open{background-position:-25px center;}

/* form */
.measure-input{background:url("images/ruler.gif") repeat-x scroll 0 13px transparent;}


text:
using namespace boost::polygon;

void point_data_test()
{
  typedef point_data<int> point_type;

  point_type point1(1, 2);
  point_type point2;
  point2 = point1;
  BOOST_TEST_EQ(point1.x(), 1);
  BOOST_TEST_EQ(point1.y(), 2);
  BOOST_TEST_EQ(point2.x(), 1);
  BOOST_TEST_EQ(point2.y(), 2);
  BOOST_TEST(point1 == point2);
  BOOST_TEST(!(point1 != point2));
  BOOST_TEST(!(point1 < point2));
  BOOST_TEST(!(point1 > point2));
  BOOST_TEST(point1 <= point2);
  BOOST_TEST(point1 >= point2);

  point2.x(2);
  point2.y(1);
  BOOST_TEST_EQ(point2.x(), 2);
  BOOST_TEST_EQ(point2.y(), 1);
  BOOST_TEST(!(point1 == point2));
  BOOST_TEST(point1 != point2);
  BOOST_TEST(point1 < point2);
  BOOST_TEST(!(point1 > point2));
  BOOST_TEST(point1 <= point2);
  BOOST_TEST(!(point1 >= point2));

  point2.set(HORIZONTAL, 1);
  point2.set(VERTICAL, 2);
  BOOST_TEST(point1 == point2);
}

void point_traits_test()
{
  typedef point_data<int> point_type;

  point_type point = point_mutable_traits<point_type>::construct(1, 2);
  BOOST_TEST_EQ(point_traits<point_type>::get(point, HORIZONTAL), 1);
  BOOST_TEST_EQ(point_traits<point_type>::get(point, VERTICAL), 2);

  point_mutable_traits<point_type>::set(point, HORIZONTAL, 3);
  point_mutable_traits<point_type>::set(point, VERTICAL, 4);
  BOOST_TEST_EQ(point_traits<point_type>::get(point, HORIZONTAL), 3);
  BOOST_TEST_EQ(point_traits<point_type>::get(point, VERTICAL), 4);
}

template <typename T>
struct Point {
  T x;
  T y;
};

namespace boost {
namespace polygon {
  template <typename T>
  struct geometry_concept< Point<T> > {
    typedef point_concept type;
  };

  template <typename T>
  struct point_traits< Point<T> > {
    typedef T coordinate_type;

    static coordinate_type get(const Point<T>& point, orientation_2d orient) {
      return (orient == HORIZONTAL) ? point.x : point.y;
    }
  };

  template <typename T>
  struct point_mutable_traits< Point<T> > {
    typedef T coordinate_type;

    static void set(Point<T>& point, orientation_2d orient, T value) {
      (orient == HORIZONTAL) ? point.x = value : point.y = value;
    }

    static Point<T> construct(coordinate_type x, coordinate_type y) {
      Point<T> point;
      point.x = x;
      point.y = y;
      return point;
    }
  };
}  // polygon
}  // boost

void point_concept_test1()
{
  typedef Point<int> point_type;

  point_type point1 = construct<point_type>(1, 2);
  BOOST_TEST_EQ(point1.x, 1);
  BOOST_TEST_EQ(point1.y, 2);

  set(point1, HORIZONTAL, 3);
  set(point1, VERTICAL, 4);
  BOOST_TEST_EQ(get(point1, HORIZONTAL), 3);
  BOOST_TEST_EQ(get(point1, VERTICAL), 4);

  point_type point2;
  assign(point2, point1);
  BOOST_TEST(equivalence(point1, point2));

  x(point2, 1);
  y(point2, 2);
  BOOST_TEST_EQ(x(point2), 1);
  BOOST_TEST_EQ(y(point2), 2);
}

void point_concept_test2()
{
  typedef Point<int> point_type;

  point_type point1 = construct<point_type>(1, 2);
  point_type point2 = construct<point_type>(5, 5);
  BOOST_TEST_EQ(euclidean_distance(point1, point2, HORIZONTAL), 4);
  BOOST_TEST_EQ(euclidean_distance(point1, point2, VERTICAL), 3);
  BOOST_TEST_EQ(manhattan_distance(point1, point2), 7);
  BOOST_TEST_EQ(euclidean_distance(point1, point2), 5.0);
}

void point_concept_test3()
{
  typedef Point<int> point_type;

  point_type point = construct<point_type>(1, 2);
  point_type shift = construct<point_type>(4, 3);
  convolve(point, shift);
  BOOST_TEST_EQ(x(point), 5);
  BOOST_TEST_EQ(y(point), 5);

  deconvolve(point, shift);
  BOOST_TEST_EQ(x(point), 1);
  BOOST_TEST_EQ(y(point), 2);

  scale_up(point, 5);
  BOOST_TEST_EQ(x(point), 5);
  BOOST_TEST_EQ(y(point), 10);

  scale_down(point, 5);
  BOOST_TEST_EQ(x(point), 1);
  BOOST_TEST_EQ(y(point), 2);

  move(point, HORIZONTAL, 2);
  move(point, VERTICAL, 3);
  BOOST_TEST_EQ(x(point), 3);
  BOOST_TEST_EQ(y(point), 5);
}

template<typename T>
struct Transformer {
  void scale(T& x, T& y) const {
    x *= 2;
    y *= 2;
  }

  void transform(T& x, T& y) const {
    T tmp = x;
    x = y;
    y = tmp;
  }
};

void point_concept_test4()
{
  typedef Point<int> point_type;

  point_type point = construct<point_type>(1, 2);
  scale(point, Transformer<int>());
  BOOST_TEST_EQ(x(point), 2);
  BOOST_TEST_EQ(y(point), 4);

  transform(point, Transformer<int>());
  BOOST_TEST_EQ(x(point), 4);
  BOOST_TEST_EQ(y(point), 2);
}

int main()
{
    point_data_test();
    point_traits_test();
    point_concept_test1();
    point_concept_test2();
    point_concept_test3();
    point_concept_test4();
    return boost::report_errors();
}


text:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ProductSchema = Schema(
  {
    name:{
      type:String,
      required:true,
      unique:true,
      lowercase: true
    },
    description:{
      type:String,
      required:true,
      lowercase: true
    },
    categories:{
      type:[
        {
          type:Schema.Types.ObjectId,
          refs:'Category'
        }
      ],
      index:true
    },
    pictures:{
      type:[
        {
          picture_id:String,
          filename:String,
          format:String,
          src:String
        }
      ]
    }
  },
  {
    timestamps:true
  }
);

const Product = mongoose.model('Product',ProductSchema);
Product.factory=(data) => {
  return new Product( {
    name:data.name,
    description:data.description,
    categories:data.categories
  })
}
module.exports = Product;


text:
cask 'whatsize' do
  version '7.4.1'
  sha256 '322dea4611bf4019708cf325f6f8b2e0e48a43b9ffba06ffbad30d949dd0197f'

  url "https://www.whatsizemac.com/software/whatsize#{version.major}/whatsize_#{version}.tgz"
  appcast "https://www.whatsizemac.com/software/whatsize#{version.major}/release/notes.xml"
  name 'WhatSize'
  homepage 'https://www.whatsizemac.com/'

  depends_on macos: '>= :sierra'

  pkg 'WhatSize.pkg'

  uninstall pkgutil:   "com.id-design.whatsize#{version.major}.pkg",
            launchctl: "com.id-design.v#{version.major}.whatsizehelper"
end


text:
package org.elasticsearch.index.mapper;

import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.XContentParser;

/**
 *
 */
public class SourceToParse {

    public static SourceToParse source(XContentParser parser) {
        return new SourceToParse(parser);
    }

    public static SourceToParse source(BytesReference source) {
        return new SourceToParse(source);
    }

    private final BytesReference source;

    private final XContentParser parser;

    private boolean flyweight = false;

    private String type;

    private String id;

    private String routing;

    private String parentId;

    private long timestamp;

    private long ttl;

    public SourceToParse(XContentParser parser) {
        this.parser = parser;
        this.source = null;
    }

    public SourceToParse(BytesReference source) {
        // we always convert back to byte array, since we store it and Field only supports bytes..
        // so, we might as well do it here, and improve the performance of working with direct byte arrays
        this.source = source.toBytesArray();
        this.parser = null;
    }

    public XContentParser parser() {
        return this.parser;
    }

    public BytesReference source() {
        return this.source;
    }

    public String type() {
        return this.type;
    }

    public SourceToParse type(String type) {
        this.type = type;
        return this;
    }

    public SourceToParse flyweight(boolean flyweight) {
        this.flyweight = flyweight;
        return this;
    }

    public boolean flyweight() {
        return this.flyweight;
    }

    public String id() {
        return this.id;
    }

    public SourceToParse id(String id) {
        this.id = id;
        return this;
    }

    public String parent() {
        return this.parentId;
    }

    public SourceToParse parent(String parentId) {
        this.parentId = parentId;
        return this;
    }

    public String routing() {
        return this.routing;
    }

    public SourceToParse routing(String routing) {
        this.routing = routing;
        return this;
    }

    public long timestamp() {
        return this.timestamp;
    }

    public SourceToParse timestamp(String timestamp) {
        this.timestamp = Long.parseLong(timestamp);
        return this;
    }

    public SourceToParse timestamp(long timestamp) {
        this.timestamp = timestamp;
        return this;
    }

    public long ttl() {
        return this.ttl;
    }

    public SourceToParse ttl(long ttl) {
        this.ttl = ttl;
        return this;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using PhimHang.Models;
using System.Data.Entity;
using System.Threading.Tasks;

namespace PhimHang
{
    public class ChatHub : Hub
    {
        #region Data Members

        static List<UserDetail> ConnectedUsers = new List<UserDetail>();
        static List<MessageDetail> CurrentMessage = new List<MessageDetail>();

        #endregion

        #region Methods
        DBChatGroup db = new DBChatGroup();
        public void Connect()
        {
            var userName = Context.User.Identity.Name;
            var id = Context.ConnectionId;

            if (ConnectedUsers.Count(x => x.ConnectionId == id) == 0) // check exist user
            {
                ConnectedUsers.Add(new UserDetail { ConnectionId = id, UserName = userName });
                // list user
                var userInDbs = (from u in db.UserLogins
                                 orderby u.UserNameCopy
                                 select new
                                 {
                                     UserName = u.UserNameCopy,
                                     UserId = u.Id

                                 }).ToList();
                var ListUserNameConnection = new List<string>();
                 ConnectedUsers.ForEach(cu=> ListUserNameConnection.Add(cu.UserName));

                var userStatusOnline = userInDbs.Where(u => ListUserNameConnection.Contains(u.UserName)).ToList();
                var userStatusOffline = userInDbs.Where(u => !ListUserNameConnection.Contains(u.UserName)).ToList();

                // list recent
                var idUser = db.UserLogins.FirstOrDefault(u=> u.UserNameCopy == userName).Id;
                var listGroup = (from g in db.Group_User
                                 where g.UserOfGroup == idUser
                                 select new
                                 {
                                    UserId = g.GroupId,
                                    UserName = g.Group.GroupName
                                 }).Distinct().ToList();

                // send to caller
                Clients.Caller.onConnected(id, userName, userStatusOnline, "O"); // List ONLine
                Clients.Caller.onConnected(id, userName, userStatusOffline,"F"); // List OFFLine

                Clients.Caller.onConnected(id, userName, listGroup, "G"); // List Group

                // send to all except caller client switch online
                Clients.AllExcept(id).onNewUserConnected(id, userName);

            }

        }

        public void SendMessageToAll(string userName, string message)
        {
            // store last 100 messages in cache
            AddMessageinCache(userName, message);

            // Broad cast message
            Clients.All.messageReceived(userName, message);
        }

        public async Task SendPrivateMessage(string toUserId, string message)
        {
            string fromUserId = Context.User.Identity.Name;
            var idFromUser = db.UserLogins.FirstOrDefault(u => u.UserNameCopy == fromUserId).Id;
            int i;
            if (int.TryParse(toUserId, out i)) // send group
            {
                var listGroup = db.Group_User.Where(gu => gu.GroupId == i && gu.UserOfGroup != idFromUser).ToList();
                var listUserInGroup = new List<string>();
                var GroupName = db.Groups.FirstOrDefault(g => g.GroupId == i).GroupName;

                foreach (var item in listGroup)
                {
                    listUserInGroup.Add(item.UserLogin.UserNameCopy);
                    //GroupName += item.UserLogin.UserNameCopy + "|";

                    // lưu trạng thái nếu chưa nhận dc tin
                    var group = db.StatusWindows.FirstOrDefault(sw => sw.KeyWindowName == toUserId && sw.UserName == item.UserLogin.UserNameCopy);
                    if (group == null)
                    {
                        StatusWindow sw = new StatusWindow
                        {
                            CtrId = "Group_" + i,
                            WindowName = GroupName,
                            TopPosition = "200" + "px",
                            LeftPosition = "100" + "px",
                            UserName = item.UserLogin.UserNameCopy,
                            KeyWindowName = toUserId

                        };
                        db.StatusWindows.Add(sw);
                        await  db.SaveChangesAsync();
                    }
                }

                Group_User_Messege group_User_Messege = new Group_User_Messege
                {
                    ConentMesseger = message,
                    CreatedDate = DateTime.Now,
                    GroupId = i,
                    WhoChat = fromUserId
                };
                try
                {
                    db.Group_User_Messege.Add(group_User_Messege);
                    db.SaveChanges();
                }
                catch (Exception)
                {

                    throw;
                }
            // send group
                Clients.Users(listUserInGroup).sendPrivateMessage(toUserId, fromUserId, message, "G", GroupName);

                // send to caller user
                Clients.Caller.sendPrivateMessage(toUserId, fromUserId, message, "G", GroupName);

            }
            else // send direct messenge
            {
                var idToUser = db.UserLogins.FirstOrDefault(u => u.UserNameCopy == toUserId).Id;
                MessegeDirect messegeDirect = new MessegeDirect
                {
                    ConentMesseger = message,
                    CreatedDate = DateTime.Now,
                    FromUser = idFromUser,
                    ToUser = idToUser,
                    WhoChat = fromUserId
                };

                // lưu trạng thái nếu chưa nhận dc tin
                var Frompirvate = db.StatusWindows.FirstOrDefault(sw => sw.KeyWindowName == toUserId && sw.UserName == fromUserId);
                if (Frompirvate == null)
                {
                    StatusWindow sw = new StatusWindow
                    {
                        CtrId = "private_" + toUserId,
                        WindowName = toUserId,
                        TopPosition = "200" + "px",
                        LeftPosition = "100" + "px",
                        UserName = fromUserId,
                        KeyWindowName = toUserId

                    };
                    db.StatusWindows.Add(sw);
                    //await db.SaveChangesAsync();
                }
                var topirvate = db.StatusWindows.FirstOrDefault(sw => sw.KeyWindowName == fromUserId && sw.UserName == toUserId);
                if (topirvate == null)
                {
                    StatusWindow sw = new StatusWindow
                    {
                        CtrId = "private_" + fromUserId,
                        WindowName = fromUserId,
                        TopPosition = "200" + "px",
                        LeftPosition = "100" + "px",
                        UserName = toUserId,
                        KeyWindowName = fromUserId

                    };
                    db.StatusWindows.Add(sw);
                    //await db.SaveChangesAsync();
                }
                //end

                db.MessegeDirects.Add(messegeDirect);
                await db.SaveChangesAsync();
                // send to

                Clients.User(toUserId).sendPrivateMessage(fromUserId, fromUserId, message, "P", fromUserId);

                // send to caller user
                Clients.Caller.sendPrivateMessage(toUserId, fromUserId, message, "P", fromUserId);
            }
          // tạo cua so khi khong nhan dc  tin nhắn
            //var checkesistwindow = db.StatusWindows.Where(w => w.CtrId == ctrId && w.UserName == User.Identity.Name).ToList();

        }
        public async Task Disconnected(bool stopCall)
        {
            OnDisconnected(stopCall);
        }

        public override System.Threading.Tasks.Task OnDisconnected(bool stopCall)
        {
            var item = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == Context.ConnectionId);
            if (item != null)
            {
                ConnectedUsers.Remove(item);

                var id = Context.ConnectionId;
                Clients.All.onUserDisconnected(id, item.UserName);

            }

            return base.OnDisconnected(stopCall);
        }

        #endregion

        #region private Messages

        private void AddMessageinCache(string userName, string message)
        {
            CurrentMessage.Add(new MessageDetail { UserName = userName, Message = message });

            if (CurrentMessage.Count > 100)
                CurrentMessage.RemoveAt(0);
        }

        public void CreateGroup_User(string[] listUser, string groupName)
        {
            if (listUser != null)
            {
                string myUserId = Context.User.Identity.Name; // tạo group phải có mình trong đó
                string groupnameDefault = "";
                string NameFirstsend = "";

                foreach (var item in listUser)
                {
                    groupnameDefault += item + "|";
                    NameFirstsend += item + "|";
                }

                groupnameDefault += myUserId;

                Group group = new Group();
                group.GroupName = string.IsNullOrWhiteSpace(groupName) ? groupnameDefault : groupName;
                group.GroupType = "G";
                db.Groups.Add(group);

                foreach (var item in listUser)
                {
                    Group_User userGroup = new Group_User();
                    userGroup.GroupId = group.GroupId;
                    userGroup.UserOfGroup = db.UserLogins.FirstOrDefault(ul => ul.UserNameCopy == item).Id;
                    db.Group_User.Add(userGroup);
                }

                Group_User myGroup = new Group_User();
                myGroup.GroupId = group.GroupId;
                myGroup.UserOfGroup = db.UserLogins.FirstOrDefault(ul => ul.UserNameCopy == myUserId).Id;
                db.Group_User.Add(myGroup);

                try
                {
                    db.SaveChanges();

                }
                catch (Exception)
                {

                    throw;
                }

                SendPrivateMessage(group.GroupId.ToString(), myUserId + " Đã thêm " + NameFirstsend + " vào nhóm ");

            }

        }

        public async Task CloseWindow(string groupid)
        {
            string myUserId = Context.User.Identity.Name;
            var group = db.StatusWindows.FirstOrDefault(sw => sw.KeyWindowName == groupid && sw.UserName == myUserId);
            db.StatusWindows.Remove(group);
            await db.SaveChangesAsync();
        }

        #endregion

        #region load history messege

        #endregion
    }
}


text:
!-------------------------------------------------------------------------------
! Copyright (c) 2019 FrontISTR Commons
! This software is released under the MIT License, see LICENSE.txt
!-------------------------------------------------------------------------------
!> \brief This module contains control file data obtaining functions for dynamic analysis

module fstr_ctrl_eigen
  use m_fstr
  use hecmw
  include 'fstr_ctrl_util_f.inc'

  private :: pc_strupr
contains

  subroutine pc_strupr( s )
    implicit none
    character(*) :: s
    integer :: i, n, a, da

    n = len_trim(s)
    da = iachar('a') - iachar('A')
    do i = 1, n
      a = iachar(s(i:i))
      if( a > iachar('Z')) then
        a = a - da
        s(i:i) = achar(a)
      end if
    end do
  end subroutine pc_strupr

  !> Read in !EIGEN (struct)
  function fstr_ctrl_get_EIGEN( ctrl, nget, tolerance, maxiter)
    implicit none
    integer(kind=kint) :: ctrl
    integer(kind=kint) :: nget
    real(kind=kreal) :: tolerance
    integer(kind=kint) :: maxiter
    integer(kind=kint) :: fstr_ctrl_get_EIGEN

    ! JP-16
    fstr_ctrl_get_EIGEN = fstr_ctrl_get_data_ex( ctrl, 1,  'Iri ',  nget, tolerance, maxiter )

  end function fstr_ctrl_get_EIGEN

  !* ----------------------------------------------------------------------------------------------- *!
end module fstr_ctrl_eigen


text:
package org.apache.ibatis.submitted.flush_statement_npe;

import java.io.PrintWriter;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;
import org.junit.Test;

public class FlushStatementNpeTest {

    private static SqlSessionFactory sqlSessionFactory;

    @BeforeClass
    public static void initDatabase() throws Exception {
        Connection conn = null;

        try {
            Class.forName("org.hsqldb.jdbcDriver");
            conn = DriverManager.getConnection("jdbc:hsqldb:mem:flush_statement_npe", "sa",
                    "");

            Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/flush_statement_npe/CreateDB.sql");

            ScriptRunner runner = new ScriptRunner(conn);
            runner.setLogWriter(null);
            runner.setErrorLogWriter(null);
            runner.runScript(reader);
            conn.commit();
            reader.close();

            reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/flush_statement_npe/ibatisConfig.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
    }

    @Test
    public void testSameUpdateAfterCommitSimple() {
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.SIMPLE);
        try {
            PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
            Person person = personMapper.selectById(1);
            person.setFirstName("Simone");

            // Execute first update then commit.
            personMapper.update(person);
            sqlSession.commit();

            // Execute same update a second time. This used to raise an NPE.
            personMapper.update(person);
            sqlSession.commit();
        } finally {
        	sqlSession.close();
        }
    }
    @Test
    public void testSameUpdateAfterCommitReuse() {
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.REUSE);
        try {
            PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
            Person person = personMapper.selectById(1);
            person.setFirstName("Simone");

            // Execute first update then commit.
            personMapper.update(person);
            sqlSession.commit();

            // Execute same update a second time. This used to raise an NPE.
            personMapper.update(person);
            sqlSession.commit();
        } finally {
        	sqlSession.close();
        }
    }
    @Test
    public void testSameUpdateAfterCommitBatch() {
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
        try {
            PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
            Person person = personMapper.selectById(1);
            person.setFirstName("Simone");

            // Execute first update then commit.
            personMapper.update(person);
            sqlSession.commit();

            // Execute same update a second time. This used to raise an NPE.
            personMapper.update(person);
            sqlSession.commit();
        } finally {
        	sqlSession.close();
        }
    }
}


text:
require "test_helper"

# Tests to assure reviewers can mark agreement variables for resubmission.
class Reviewer::AgreementVariablesControllerTest < ActionDispatch::IntegrationTest
  setup do
    @reviewer = users(:reviewer_on_released)
    @submitted = data_requests(:submitted)
    @specific_purpose = agreement_variables(:submitted_specific_purpose)
  end

  def agreement_variable_params
    {
      reviewer_comment: "Please be more specific."
    }
  end

  test "should update review" do
    login(@reviewer)
    patch reviewer_agreement_variable_url(@submitted, @specific_purpose, format: "js"), params: {
      agreement_variable: agreement_variable_params
    }
    @specific_purpose.reload
    assert_equal true, @specific_purpose.resubmission_required?
    assert_equal "Please be more specific.", @specific_purpose.reviewer_comment
    assert_template "show"
    assert_response :success
  end
end