text:
<?php
ob_start();

ini_set( 'display_errors', true );
error_reporting(E_ALL & ~ E_NOTICE & ~ E_DEPRECATED);

session_start();
session_destroy();

?>
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <title>Omega Inc - Delivery</title>

  <link rel="stylesheet" href="css/framework7.material.min.css">
  <link rel="stylesheet" href="css/framework7.material.colors.min.css">

  <link rel="stylesheet" href="css/delivery.min.css">

</script>

<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">

Menu

Consultar Pedido

Sobre

Sobre o Aplicativo

Fechar

Informaões da empresa que administra o aplicativo.

        Sobre a empresa

Desenvolvimento

Este aplicativo foi desenvolvido por Copyright Omega Inc. Todos os direitos Reservados

Click the button to get your coordinates.

      <button onclick="getLocation()">Try It</button>

Consultar Pedido

Fechar

search

                <input type="text"  id="numeropedido" placeholder="Numero do Pedido"  required>

lock_outline

                <input type="text"  id="token" placeholder="Token"  required>

              Pesquisar

Consultar CEP

        <form class="searchbar">

            <input id="nomedarua" onkeyup="getCEP(this.value)" type="search" placeholder="Nome da Rua">

          Cancel
        </form>

            Nenhum Endereço Encontrado

Fechar

Delivery

Delivery

                    <form action="." method="get">

near_me

                                <input onkeypress="formataCEP();" type="text"  id="cep" name="cep" placeholder="CEP"  maxlength="8" required autofocus>

Não sei meu cep.

location_on

                                  <input style="color: green" type="text" id="endereco" name="endereco" placeholder="" disabled>

person

                          <input type="text" onfocus="position('#nome')" id="nome" name="nome" placeholder="Seu Nome" required>

email

                          <input type="email" onfocus="position('#email')" id="email" name="email" placeholder="Seu Email" required>

                    <input name="cep" type="hidden" id="cep" value="" size="15" maxlength="8" />
                    <input name="rua" type="hidden" id="rua" size="60" />
                    <input name="bairro" type="hidden" id="bairro" class="form-control" size="60" />
                    <input name="cidade" type="hidden" id="cidade" size="60" />

                        Pronto

              </form>

                    Horário de Atendimento: Ter. à Dom. das 18h as 00h.

                    Telefone:

                    Email:


text:
<?php

use MediaWiki\Session\Session;
use MediaWiki\Session\SessionId;
use MediaWiki\Session\SessionManager;

/**
 * The WebRequest class encapsulates getting at data passed in the
 * URL or via a POSTed form stripping illegal input characters and
 * normalizing Unicode sequences.
 *
 * @ingroup HTTP
 */
class WebRequest {
	protected $data, $headers = [];

	/**
	 * Flag to make WebRequest::getHeader return an array of values.
	 * @since 1.26
	 */
	const GETHEADER_LIST = 1;

	/**
	 * The unique request ID.
	 * @var string
	 */
	private static $reqId;

	/**
	 * Lazy-init response object
	 * @var WebResponse
	 */
	private $response;

	/**
	 * Cached client IP address
	 * @var string
	 */
	private $ip;

	/**
	 * The timestamp of the start of the request, with microsecond precision.
	 * @var float
	 */
	protected $requestTime;

	/**
	 * Cached URL protocol
	 * @var string
	 */
	protected $protocol;

	/**
	 * @var SessionId|null Session ID to use for this
	 *  request. We can't save the session directly due to reference cycles not
	 *  working too well (slow GC in Zend and never collected in HHVM).
	 */
	protected $sessionId = null;

	/** @var bool Whether this HTTP request is "safe" (even if it is an HTTP post) */
	protected $markedAsSafe = false;

	public function __construct() {
		$this->requestTime = isset( $_SERVER['REQUEST_TIME_FLOAT'] )
			? $_SERVER['REQUEST_TIME_FLOAT'] : microtime( true );

		// POST overrides GET data
		// We don't use $_REQUEST here to avoid interference from cookies...
		$this->data = $_POST + $_GET;
	}

	/**
	 * Extract relevant query arguments from the http request uri's path
	 * to be merged with the normal php provided query arguments.
	 * Tries to use the REQUEST_URI data if available and parses it
	 * according to the wiki's configuration looking for any known pattern.
	 *
	 * If the REQUEST_URI is not provided we'll fall back on the PATH_INFO
	 * provided by the server if any and use that to set a 'title' parameter.
	 *
	 * @param string $want If this is not 'all', then the function
	 * will return an empty array if it determines that the URL is
	 * inside a rewrite path.
	 *
	 * @return array Any query arguments found in path matches.
	 */
	public static function getPathInfo( $want = 'all' ) {
		global $wgUsePathInfo;
		// PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
		// And also by Apache 2.x, double slashes are converted to single slashes.
		// So we will use REQUEST_URI if possible.
		$matches = [];
		if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
			// Slurp out the path portion to examine...
			$url = $_SERVER['REQUEST_URI'];
			if ( !preg_match( '!^https?://!', $url ) ) {
				$url = 'http://unused' . $url;
			}
			MediaWiki\suppressWarnings();
			$a = parse_url( $url );
			MediaWiki\restoreWarnings();
			if ( $a ) {
				$path = isset( $a['path'] ) ? $a['path'] : '';

				global $wgScript;
				if ( $path == $wgScript && $want !== 'all' ) {
					// Script inside a rewrite path?
					// Abort to keep from breaking...
					return $matches;
				}

				$router = new PathRouter;

				// Raw PATH_INFO style
				$router->add( "$wgScript/$1" );

				if ( isset( $_SERVER['SCRIPT_NAME'] )
					&& preg_match( '/\.php5?/', $_SERVER['SCRIPT_NAME'] )
				) {
					# Check for SCRIPT_NAME, we handle index.php explicitly
					# But we do have some other .php files such as img_auth.php
					# Don't let root article paths clober the parsing for them
					$router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
				}

				global $wgArticlePath;
				if ( $wgArticlePath ) {
					$router->add( $wgArticlePath );
				}

				global $wgActionPaths;
				if ( $wgActionPaths ) {
					$router->add( $wgActionPaths, [ 'action' => '$key' ] );
				}

				global $wgVariantArticlePath, $wgContLang;
				if ( $wgVariantArticlePath ) {
					$router->add( $wgVariantArticlePath,
						[ 'variant' => '$2' ],
						[ '$2' => $wgContLang->getVariants() ]
					);
				}

				Hooks::run( 'WebRequestPathInfoRouter', [ $router ] );

				$matches = $router->parse( $path );
			}
		} elseif ( $wgUsePathInfo ) {
			if ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
				// Mangled PATH_INFO
				// http://bugs.php.net/bug.php?id=31892
				// Also reported when ini_get('cgi.fix_pathinfo')==false
				$matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );

			} elseif ( isset( $_SERVER['PATH_INFO'] ) && $_SERVER['PATH_INFO'] != '' ) {
				// Regular old PATH_INFO yay
				$matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
			}
		}

		return $matches;
	}

	/**
	 * Work out an appropriate URL prefix containing scheme and host, based on
	 * information detected from $_SERVER
	 *
	 * @return string
	 */
	public static function detectServer() {
		global $wgAssumeProxiesUseDefaultProtocolPorts;

		$proto = self::detectProtocol();
		$stdPort = $proto === 'https' ? 443 : 80;

		$varNames = [ 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' ];
		$host = 'localhost';
		$port = $stdPort;
		foreach ( $varNames as $varName ) {
			if ( !isset( $_SERVER[$varName] ) ) {
				continue;
			}

			$parts = IP::splitHostAndPort( $_SERVER[$varName] );
			if ( !$parts ) {
				// Invalid, do not use
				continue;
			}

			$host = $parts[0];
			if ( $wgAssumeProxiesUseDefaultProtocolPorts && isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
				// Bug 70021: Assume that upstream proxy is running on the default
				// port based on the protocol. We have no reliable way to determine
				// the actual port in use upstream.
				$port = $stdPort;
			} elseif ( $parts[1] === false ) {
				if ( isset( $_SERVER['SERVER_PORT'] ) ) {
					$port = $_SERVER['SERVER_PORT'];
				} // else leave it as $stdPort
			} else {
				$port = $parts[1];
			}
			break;
		}

		return $proto . '://' . IP::combineHostAndPort( $host, $port, $stdPort );
	}

	/**
	 * Detect the protocol from $_SERVER.
	 * This is for use prior to Setup.php, when no WebRequest object is available.
	 * At other times, use the non-static function getProtocol().
	 *
	 * @return array
	 */
	public static function detectProtocol() {
		if ( ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ||
			( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
			$_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) ) {
			return 'https';
		} else {
			return 'http';
		}
	}

	/**
	 * Get the number of seconds to have elapsed since request start,
	 * in fractional seconds, with microsecond resolution.
	 *
	 * @return float
	 * @since 1.25
	 */
	public function getElapsedTime() {
		return microtime( true ) - $this->requestTime;
	}

	/**
	 * Get the unique request ID.
	 * This is either the value of the UNIQUE_ID envvar (if present) or a
	 * randomly-generated 24-character string.
	 *
	 * @return string
	 * @since 1.27
	 */
	public static function getRequestId() {
		if ( !self::$reqId ) {
			self::$reqId = isset( $_SERVER['UNIQUE_ID'] )
				? $_SERVER['UNIQUE_ID'] : wfRandomString( 24 );
		}

		return self::$reqId;
	}

	/**
	 * Override the unique request ID. This is for sub-requests, such as jobs,
	 * that wish to use the same id but are not part of the same execution context.
	 *
	 * @param string $id
	 * @since 1.27
	 */
	public static function overrideRequestId( $id ) {
		self::$reqId = $id;
	}

	/**
	 * Get the current URL protocol (http or https)
	 * @return string
	 */
	public function getProtocol() {
		if ( $this->protocol === null ) {
			$this->protocol = self::detectProtocol();
		}
		return $this->protocol;
	}

	/**
	 * Check for title, action, and/or variant data in the URL
	 * and interpolate it into the GET variables.
	 * This should only be run after $wgContLang is available,
	 * as we may need the list of language variants to determine
	 * available variant URLs.
	 */
	public function interpolateTitle() {
		// bug 16019: title interpolation on API queries is useless and sometimes harmful
		if ( defined( 'MW_API' ) ) {
			return;
		}

		$matches = self::getPathInfo( 'title' );
		foreach ( $matches as $key => $val ) {
			$this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
		}
	}

	/**
	 * URL rewriting function; tries to extract page title and,
	 * optionally, one other fixed parameter value from a URL path.
	 *
	 * @param string $path The URL path given from the client
	 * @param array $bases One or more URLs, optionally with $1 at the end
	 * @param string|bool $key If provided, the matching key in $bases will be
	 *    passed on as the value of this URL parameter
	 * @return array Array of URL variables to interpolate; empty if no match
	 */
	static function extractTitle( $path, $bases, $key = false ) {
		foreach ( (array)$bases as $keyValue => $base ) {
			// Find the part after $wgArticlePath
			$base = str_replace( '$1', '', $base );
			$baseLen = strlen( $base );
			if ( substr( $path, 0, $baseLen ) == $base ) {
				$raw = substr( $path, $baseLen );
				if ( $raw !== '' ) {
					$matches = [ 'title' => rawurldecode( $raw ) ];
					if ( $key ) {
						$matches[$key] = $keyValue;
					}
					return $matches;
				}
			}
		}
		return [];
	}

	/**
	 * Recursively normalizes UTF-8 strings in the given array.
	 *
	 * @param string|array $data
	 * @return array|string Cleaned-up version of the given
	 * @private
	 */
	function normalizeUnicode( $data ) {
		if ( is_array( $data ) ) {
			foreach ( $data as $key => $val ) {
				$data[$key] = $this->normalizeUnicode( $val );
			}
		} else {
			global $wgContLang;
			$data = isset( $wgContLang ) ?
				$wgContLang->normalize( $data ) :
				UtfNormal\Validator::cleanUp( $data );
		}
		return $data;
	}

	/**
	 * Fetch a value from the given array or return $default if it's not set.
	 *
	 * @param array $arr
	 * @param string $name
	 * @param mixed $default
	 * @return mixed
	 */
	private function getGPCVal( $arr, $name, $default ) {
		# PHP is so nice to not touch input data, except sometimes:
		# http://us2.php.net/variables.external#language.variables.external.dot-in-names
		# Work around PHP *feature* to avoid *bugs* elsewhere.
		$name = strtr( $name, '.', '_' );
		if ( isset( $arr[$name] ) ) {
			global $wgContLang;
			$data = $arr[$name];
			if ( isset( $_GET[$name] ) && !is_array( $data ) ) {
				# Check for alternate/legacy character encoding.
				if ( isset( $wgContLang ) ) {
					$data = $wgContLang->checkTitleEncoding( $data );
				}
			}
			$data = $this->normalizeUnicode( $data );
			return $data;
		} else {
			return $default;
		}
	}

	/**
	 * Fetch a scalar from the input or return $default if it's not set.
	 * Returns a string. Arrays are discarded. Useful for
	 * non-freeform text inputs (e.g. predefined internal text keys
	 * selected by a drop-down menu). For freeform input, see getText().
	 *
	 * @param string $name
	 * @param string $default Optional default (or null)
	 * @return string
	 */
	public function getVal( $name, $default = null ) {
		$val = $this->getGPCVal( $this->data, $name, $default );
		if ( is_array( $val ) ) {
			$val = $default;
		}
		if ( is_null( $val ) ) {
			return $val;
		} else {
			return (string)$val;
		}
	}

	/**
	 * Set an arbitrary value into our get/post data.
	 *
	 * @param string $key Key name to use
	 * @param mixed $value Value to set
	 * @return mixed Old value if one was present, null otherwise
	 */
	public function setVal( $key, $value ) {
		$ret = isset( $this->data[$key] ) ? $this->data[$key] : null;
		$this->data[$key] = $value;
		return $ret;
	}

	/**
	 * Unset an arbitrary value from our get/post data.
	 *
	 * @param string $key Key name to use
	 * @return mixed Old value if one was present, null otherwise
	 */
	public function unsetVal( $key ) {
		if ( !isset( $this->data[$key] ) ) {
			$ret = null;
		} else {
			$ret = $this->data[$key];
			unset( $this->data[$key] );
		}
		return $ret;
	}

	/**
	 * Fetch an array from the input or return $default if it's not set.
	 * If source was scalar, will return an array with a single element.
	 * If no source and no default, returns null.
	 *
	 * @param string $name
	 * @param array $default Optional default (or null)
	 * @return array
	 */
	public function getArray( $name, $default = null ) {
		$val = $this->getGPCVal( $this->data, $name, $default );
		if ( is_null( $val ) ) {
			return null;
		} else {
			return (array)$val;
		}
	}

	/**
	 * Fetch an array of integers, or return $default if it's not set.
	 * If source was scalar, will return an array with a single element.
	 * If no source and no default, returns null.
	 * If an array is returned, contents are guaranteed to be integers.
	 *
	 * @param string $name
	 * @param array $default Option default (or null)
	 * @return array Array of ints
	 */
	public function getIntArray( $name, $default = null ) {
		$val = $this->getArray( $name, $default );
		if ( is_array( $val ) ) {
			$val = array_map( 'intval', $val );
		}
		return $val;
	}

	/**
	 * Fetch an integer value from the input or return $default if not set.
	 * Guaranteed to return an integer; non-numeric input will typically
	 * return 0.
	 *
	 * @param string $name
	 * @param int $default
	 * @return int
	 */
	public function getInt( $name, $default = 0 ) {
		return intval( $this->getVal( $name, $default ) );
	}

	/**
	 * Fetch an integer value from the input or return null if empty.
	 * Guaranteed to return an integer or null; non-numeric input will
	 * typically return null.
	 *
	 * @param string $name
	 * @return int|null
	 */
	public function getIntOrNull( $name ) {
		$val = $this->getVal( $name );
		return is_numeric( $val )
			? intval( $val )
			: null;
	}

	/**
	 * Fetch a floating point value from the input or return $default if not set.
	 * Guaranteed to return a float; non-numeric input will typically
	 * return 0.
	 *
	 * @since 1.23
	 * @param string $name
	 * @param float $default
	 * @return float
	 */
	public function getFloat( $name, $default = 0.0 ) {
		return floatval( $this->getVal( $name, $default ) );
	}

	/**
	 * Fetch a boolean value from the input or return $default if not set.
	 * Guaranteed to return true or false, with normal PHP semantics for
	 * boolean interpretation of strings.
	 *
	 * @param string $name
	 * @param bool $default
	 * @return bool
	 */
	public function getBool( $name, $default = false ) {
		return (bool)$this->getVal( $name, $default );
	}

	/**
	 * Fetch a boolean value from the input or return $default if not set.
	 * Unlike getBool, the string "false" will result in boolean false, which is
	 * useful when interpreting information sent from JavaScript.
	 *
	 * @param string $name
	 * @param bool $default
	 * @return bool
	 */
	public function getFuzzyBool( $name, $default = false ) {
		return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
	}

	/**
	 * Return true if the named value is set in the input, whatever that
	 * value is (even "0"). Return false if the named value is not set.
	 * Example use is checking for the presence of check boxes in forms.
	 *
	 * @param string $name
	 * @return bool
	 */
	public function getCheck( $name ) {
		# Checkboxes and buttons are only present when clicked
		# Presence connotes truth, absence false
		return $this->getVal( $name, null ) !== null;
	}

	/**
	 * Fetch a text string from the given array or return $default if it's not
	 * set. Carriage returns are stripped from the text, and with some language
	 * modules there is an input transliteration applied. This should generally
	 * be used for form "<textarea>" and "<input>" fields. Used for
	 * user-supplied freeform text input (for which input transformations may
	 * be required - e.g.  Esperanto x-coding).
	 *
	 * @param string $name
	 * @param string $default Optional
	 * @return string
	 */
	public function getText( $name, $default = '' ) {
		global $wgContLang;
		$val = $this->getVal( $name, $default );
		return str_replace( "\r\n", "\n",
			$wgContLang->recodeInput( $val ) );
	}

	/**
	 * Extracts the given named values into an array.
	 * If no arguments are given, returns all input values.
	 * No transformation is performed on the values.
	 *
	 * @return array
	 */
	public function getValues() {
		$names = func_get_args();
		if ( count( $names ) == 0 ) {
			$names = array_keys( $this->data );
		}

		$retVal = [];
		foreach ( $names as $name ) {
			$value = $this->getGPCVal( $this->data, $name, null );
			if ( !is_null( $value ) ) {
				$retVal[$name] = $value;
			}
		}
		return $retVal;
	}

	/**
	 * Returns the names of all input values excluding those in $exclude.
	 *
	 * @param array $exclude
	 * @return array
	 */
	public function getValueNames( $exclude = [] ) {
		return array_diff( array_keys( $this->getValues() ), $exclude );
	}

	/**
	 * Get the values passed in the query string.
	 * No transformation is performed on the values.
	 *
	 * @return array
	 */
	public function getQueryValues() {
		return $_GET;
	}

	/**
	 * Return the contents of the Query with no decoding. Use when you need to
	 * know exactly what was sent, e.g. for an OAuth signature over the elements.
	 *
	 * @return string
	 */
	public function getRawQueryString() {
		return $_SERVER['QUERY_STRING'];
	}

	/**
	 * Return the contents of the POST with no decoding. Use when you need to
	 * know exactly what was sent, e.g. for an OAuth signature over the elements.
	 *
	 * @return string
	 */
	public function getRawPostString() {
		if ( !$this->wasPosted() ) {
			return '';
		}
		return $this->getRawInput();
	}

	/**
	 * Return the raw request body, with no processing. Cached since some methods
	 * disallow reading the stream more than once. As stated in the php docs, this
	 * does not work with enctype="multipart/form-data".
	 *
	 * @return string
	 */
	public function getRawInput() {
		static $input = null;
		if ( $input === null ) {
			$input = file_get_contents( 'php://input' );
		}
		return $input;
	}

	/**
	 * Get the HTTP method used for this request.
	 *
	 * @return string
	 */
	public function getMethod() {
		return isset( $_SERVER['REQUEST_METHOD'] ) ? $_SERVER['REQUEST_METHOD'] : 'GET';
	}

	/**
	 * Returns true if the present request was reached by a POST operation,
	 * false otherwise (GET, HEAD, or command-line).
	 *
	 * Note that values retrieved by the object may come from the
	 * GET URL etc even on a POST request.
	 *
	 * @return bool
	 */
	public function wasPosted() {
		return $this->getMethod() == 'POST';
	}

	/**
	 * Return the session for this request
	 * @since 1.27
	 * @note For performance, keep the session locally if you will be making
	 *  much use of it instead of calling this method repeatedly.
	 * @return Session
	 */
	public function getSession() {
		if ( $this->sessionId !== null ) {
			$session = SessionManager::singleton()->getSessionById( (string)$this->sessionId, true, $this );
			if ( $session ) {
				return $session;
			}
		}

		$session = SessionManager::singleton()->getSessionForRequest( $this );
		$this->sessionId = $session->getSessionId();
		return $session;
	}

	/**
	 * Set the session for this request
	 * @since 1.27
	 * @private For use by MediaWiki\Session classes only
	 * @param SessionId $sessionId
	 */
	public function setSessionId( SessionId $sessionId ) {
		$this->sessionId = $sessionId;
	}

	/**
	 * Get the session id for this request, if any
	 * @since 1.27
	 * @private For use by MediaWiki\Session classes only
	 * @return SessionId|null
	 */
	public function getSessionId() {
		return $this->sessionId;
	}

	/**
	 * Returns true if the request has a persistent session.
	 * This does not necessarily mean that the user is logged in!
	 *
	 * @deprecated since 1.27, use
	 *  \MediaWiki\Session\SessionManager::singleton()->getPersistedSessionId()
	 *  instead.
	 * @return bool
	 */
	public function checkSessionCookie() {
		global $wgInitialSessionId;
		wfDeprecated( __METHOD__, '1.27' );
		return $wgInitialSessionId !== null &&
			$this->getSession()->getId() === (string)$wgInitialSessionId;
	}

	/**
	 * Get a cookie from the $_COOKIE jar
	 *
	 * @param string $key The name of the cookie
	 * @param string $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
	 * @param mixed $default What to return if the value isn't found
	 * @return mixed Cookie value or $default if the cookie not set
	 */
	public function getCookie( $key, $prefix = null, $default = null ) {
		if ( $prefix === null ) {
			global $wgCookiePrefix;
			$prefix = $wgCookiePrefix;
		}
		return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
	}

	/**
	 * Return the path and query string portion of the main request URI.
	 * This will be suitable for use as a relative link in HTML output.
	 *
	 * @throws MWException
	 * @return string
	 */
	public static function getGlobalRequestURL() {
		if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
			$base = $_SERVER['REQUEST_URI'];
		} elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
			&& strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
		) {
			// Probably IIS; doesn't set REQUEST_URI
			$base = $_SERVER['HTTP_X_ORIGINAL_URL'];
		} elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
			$base = $_SERVER['SCRIPT_NAME'];
			if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
				$base .= '?' . $_SERVER['QUERY_STRING'];
			}
		} else {
			// This shouldn't happen!
			throw new MWException( "Web server doesn't provide either " .
				"REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
				"of your web server configuration to https://phabricator.wikimedia.org/" );
		}
		// User-agents should not send a fragment with the URI, but
		// if they do, and the web server passes it on to us, we
		// need to strip it or we get false-positive redirect loops
		// or weird output URLs
		$hash = strpos( $base, '#' );
		if ( $hash !== false ) {
			$base = substr( $base, 0, $hash );
		}

		if ( $base[0] == '/' ) {
			// More than one slash will look like it is protocol relative
			return preg_replace( '!^/+!', '/', $base );
		} else {
			// We may get paths with a host prepended; strip it.
			return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
		}
	}

	/**
	 * Return the path and query string portion of the request URI.
	 * This will be suitable for use as a relative link in HTML output.
	 *
	 * @throws MWException
	 * @return string
	 */
	public function getRequestURL() {
		return self::getGlobalRequestURL();
	}

	/**
	 * Return the request URI with the canonical service and hostname, path,
	 * and query string. This will be suitable for use as an absolute link
	 * in HTML or other output.
	 *
	 * If $wgServer is protocol-relative, this will return a fully
	 * qualified URL with the protocol that was used for this request.
	 *
	 * @return string
	 */
	public function getFullRequestURL() {
		return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT );
	}

	/**
	 * @param string $key
	 * @param string $value
	 * @return string
	 */
	public function appendQueryValue( $key, $value ) {
		return $this->appendQueryArray( [ $key => $value ] );
	}

	/**
	 * Appends or replaces value of query variables.
	 *
	 * @param array $array Array of values to replace/add to query
	 * @return string
	 */
	public function appendQueryArray( $array ) {
		$newquery = $this->getQueryValues();
		unset( $newquery['title'] );
		$newquery = array_merge( $newquery, $array );

		return wfArrayToCgi( $newquery );
	}

	/**
	 * Check for limit and offset parameters on the input, and return sensible
	 * defaults if not given. The limit must be positive and is capped at 5000.
	 * Offset must be positive but is not capped.
	 *
	 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
	 * @param string $optionname To specify an option other than rclimit to pull from.
	 * @return int[] First element is limit, second is offset
	 */
	public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
		global $wgUser;

		$limit = $this->getInt( 'limit', 0 );
		if ( $limit < 0 ) {
			$limit = 0;
		}
		if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
			$limit = $wgUser->getIntOption( $optionname );
		}
		if ( $limit <= 0 ) {
			$limit = $deflimit;
		}
		if ( $limit > 5000 ) {
			$limit = 5000; # We have *some* limits...
		}

		$offset = $this->getInt( 'offset', 0 );
		if ( $offset < 0 ) {
			$offset = 0;
		}

		return [ $limit, $offset ];
	}

	/**
	 * Return the path to the temporary file where PHP has stored the upload.
	 *
	 * @param string $key
	 * @return string|null String or null if no such file.
	 */
	public function getFileTempname( $key ) {
		$file = new WebRequestUpload( $this, $key );
		return $file->getTempName();
	}

	/**
	 * Return the upload error or 0
	 *
	 * @param string $key
	 * @return int
	 */
	public function getUploadError( $key ) {
		$file = new WebRequestUpload( $this, $key );
		return $file->getError();
	}

	/**
	 * Return the original filename of the uploaded file, as reported by
	 * the submitting user agent. HTML-style character entities are
	 * interpreted and normalized to Unicode normalization form C, in part
	 * to deal with weird input from Safari with non-ASCII filenames.
	 *
	 * Other than this the name is not verified for being a safe filename.
	 *
	 * @param string $key
	 * @return string|null String or null if no such file.
	 */
	public function getFileName( $key ) {
		$file = new WebRequestUpload( $this, $key );
		return $file->getName();
	}

	/**
	 * Return a WebRequestUpload object corresponding to the key
	 *
	 * @param string $key
	 * @return WebRequestUpload
	 */
	public function getUpload( $key ) {
		return new WebRequestUpload( $this, $key );
	}

	/**
	 * Return a handle to WebResponse style object, for setting cookies,
	 * headers and other stuff, for Request being worked on.
	 *
	 * @return WebResponse
	 */
	public function response() {
		/* Lazy initialization of response object for this request */
		if ( !is_object( $this->response ) ) {
			$class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
			$this->response = new $class();
		}
		return $this->response;
	}

	/**
	 * Initialise the header list
	 */
	protected function initHeaders() {
		if ( count( $this->headers ) ) {
			return;
		}

		$apacheHeaders = function_exists( 'apache_request_headers' ) ? apache_request_headers() : false;
		if ( $apacheHeaders ) {
			foreach ( $apacheHeaders as $tempName => $tempValue ) {
				$this->headers[strtoupper( $tempName )] = $tempValue;
			}
		} else {
			foreach ( $_SERVER as $name => $value ) {
				if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
					$name = str_replace( '_', '-', substr( $name, 5 ) );
					$this->headers[$name] = $value;
				} elseif ( $name === 'CONTENT_LENGTH' ) {
					$this->headers['CONTENT-LENGTH'] = $value;
				}
			}
		}
	}

	/**
	 * Get an array containing all request headers
	 *
	 * @return array Mapping header name to its value
	 */
	public function getAllHeaders() {
		$this->initHeaders();
		return $this->headers;
	}

	/**
	 * Get a request header, or false if it isn't set.
	 *
	 * @param string $name Case-insensitive header name
	 * @param int $flags Bitwise combination of:
	 *   WebRequest::GETHEADER_LIST  Treat the header as a comma-separated list
	 *                               of values, as described in RFC 2616 § 4.2.
	 *                               (since 1.26).
	 * @return string|array|bool False if header is unset; otherwise the
	 *  header value(s) as either a string (the default) or an array, if
	 *  WebRequest::GETHEADER_LIST flag was set.
	 */
	public function getHeader( $name, $flags = 0 ) {
		$this->initHeaders();
		$name = strtoupper( $name );
		if ( !isset( $this->headers[$name] ) ) {
			return false;
		}
		$value = $this->headers[$name];
		if ( $flags & self::GETHEADER_LIST ) {
			$value = array_map( 'trim', explode( ',', $value ) );
		}
		return $value;
	}

	/**
	 * Get data from the session
	 *
	 * @note Prefer $this->getSession() instead if making multiple calls.
	 * @param string $key Name of key in the session
	 * @return mixed
	 */
	public function getSessionData( $key ) {
		return $this->getSession()->get( $key );
	}

	/**
	 * Set session data
	 *
	 * @note Prefer $this->getSession() instead if making multiple calls.
	 * @param string $key Name of key in the session
	 * @param mixed $data
	 */
	public function setSessionData( $key, $data ) {
		$this->getSession()->set( $key, $data );
	}

	/**
	 * Check if Internet Explorer will detect an incorrect cache extension in
	 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
	 * message or redirect to a safer URL. Returns true if the URL is OK, and
	 * false if an error message has been shown and the request should be aborted.
	 *
	 * @param array $extWhitelist
	 * @throws HttpError
	 * @return bool
	 */
	public function checkUrlExtension( $extWhitelist = [] ) {
		$extWhitelist[] = 'php';
		if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
			if ( !$this->wasPosted() ) {
				$newUrl = IEUrlExtension::fixUrlForIE6(
					$this->getFullRequestURL(), $extWhitelist );
				if ( $newUrl !== false ) {
					$this->doSecurityRedirect( $newUrl );
					return false;
				}
			}
			throw new HttpError( 403,
				'Invalid file extension found in the path info or query string.' );
		}
		return true;
	}

	/**
	 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
	 * IE 6. Returns true if it was successful, false otherwise.
	 *
	 * @param string $url
	 * @return bool
	 */
	protected function doSecurityRedirect( $url ) {
		header( 'Location: ' . $url );
		header( 'Content-Type: text/html' );
		$encUrl = htmlspecialchars( $url );
		echo <<<HTML
<html>
<head>
<title>Security redirect</title>
</head>
<body>
<h1>Security redirect</h1>
<p>
We can't serve non-HTML content from the URL you have requested, because
Internet Explorer would interpret it as an incorrect and potentially dangerous
content type.</p>
<p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the
URL you have requested, except that "&*" is appended. This prevents Internet
Explorer from seeing a bogus file extension.
</p>
</body>
</html>
HTML;
		echo "\n";
		return true;
	}

	/**
	 * Parse the Accept-Language header sent by the client into an array
	 *
	 * @return array Array( languageCode => q-value ) sorted by q-value in
	 *   descending order then appearing time in the header in ascending order.
	 * May contain the "language" '*', which applies to languages other than those explicitly listed.
	 * This is aligned with rfc2616 section 14.4
	 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
	 */
	public function getAcceptLang() {
		// Modified version of code found at
		// http://www.thefutureoftheweb.com/blog/use-accept-language-header
		$acceptLang = $this->getHeader( 'Accept-Language' );
		if ( !$acceptLang ) {
			return [];
		}

		// Return the language codes in lower case
		$acceptLang = strtolower( $acceptLang );

		// Break up string into pieces (languages and q factors)
		$lang_parse = null;
		preg_match_all(
			'/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
			$acceptLang,
			$lang_parse
		);

		if ( !count( $lang_parse[1] ) ) {
			return [];
		}

		$langcodes = $lang_parse[1];
		$qvalues = $lang_parse[4];
		$indices = range( 0, count( $lang_parse[1] ) - 1 );

		// Set default q factor to 1
		foreach ( $indices as $index ) {
			if ( $qvalues[$index] === '' ) {
				$qvalues[$index] = 1;
			} elseif ( $qvalues[$index] == 0 ) {
				unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
			}
		}

		// Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
		array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );

		// Create a list like "en" => 0.8
		$langs = array_combine( $langcodes, $qvalues );

		return $langs;
	}

	/**
	 * Fetch the raw IP from the request
	 *
	 * @since 1.19
	 *
	 * @throws MWException
	 * @return string
	 */
	protected function getRawIP() {
		if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
			return null;
		}

		if ( is_array( $_SERVER['REMOTE_ADDR'] ) || strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
			throw new MWException( __METHOD__
				. " : Could not determine the remote IP address due to multiple values." );
		} else {
			$ipchain = $_SERVER['REMOTE_ADDR'];
		}

		return IP::canonicalize( $ipchain );
	}

	/**
	 * Work out the IP address based on various globals
	 * For trusted proxies, use the XFF client IP (first of the chain)
	 *
	 * @since 1.19
	 *
	 * @throws MWException
	 * @return string
	 */
	public function getIP() {
		global $wgUsePrivateIPs;

		# Return cached result
		if ( $this->ip !== null ) {
			return $this->ip;
		}

		# collect the originating ips
		$ip = $this->getRawIP();
		if ( !$ip ) {
			throw new MWException( 'Unable to determine IP.' );
		}

		# Append XFF
		$forwardedFor = $this->getHeader( 'X-Forwarded-For' );
		if ( $forwardedFor !== false ) {
			$isConfigured = IP::isConfiguredProxy( $ip );
			$ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
			$ipchain = array_reverse( $ipchain );
			array_unshift( $ipchain, $ip );

			# Step through XFF list and find the last address in the list which is a
			# trusted server. Set $ip to the IP address given by that trusted server,
			# unless the address is not sensible (e.g. private). However, prefer private
			# IP addresses over proxy servers controlled by this site (more sensible).
			# Note that some XFF values might be "unknown" with Squid/Varnish.
			foreach ( $ipchain as $i => $curIP ) {
				$curIP = IP::sanitizeIP( IP::canonicalize( $curIP ) );
				if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] === 'unknown'
					|| !IP::isTrustedProxy( $curIP )
				) {
					break; // IP is not valid/trusted or does not point to anything
				}
				if (
					IP::isPublic( $ipchain[$i + 1] ) ||
					$wgUsePrivateIPs ||
					IP::isConfiguredProxy( $curIP ) // bug 48919; treat IP as sane
				) {
					// Follow the next IP according to the proxy
					$nextIP = IP::canonicalize( $ipchain[$i + 1] );
					if ( !$nextIP && $isConfigured ) {
						// We have not yet made it past CDN/proxy servers of this site,
						// so either they are misconfigured or there is some IP spoofing.
						throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
					}
					$ip = $nextIP;
					// keep traversing the chain
					continue;
				}
				break;
			}
		}

		# Allow extensions to improve our guess
		Hooks::run( 'GetIP', [ &$ip ] );

		if ( !$ip ) {
			throw new MWException( "Unable to determine IP." );
		}

		wfDebug( "IP: $ip\n" );
		$this->ip = $ip;
		return $ip;
	}

	/**
	 * @param string $ip
	 * @return void
	 * @since 1.21
	 */
	public function setIP( $ip ) {
		$this->ip = $ip;
	}

	/**
	 * Check if this request uses a "safe" HTTP method
	 *
	 * Safe methods are verbs (e.g. GET/HEAD/OPTIONS) used for obtaining content. Such requests
	 * are not expected to mutate content, especially in ways attributable to the client. Verbs
	 * like POST and PUT are typical of non-safe requests which often change content.
	 *
	 * @return bool
	 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
	 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
	 * @since 1.28
	 */
	public function hasSafeMethod() {
		if ( !isset( $_SERVER['REQUEST_METHOD'] ) ) {
			return false; // CLI mode
		}

		return in_array( $_SERVER['REQUEST_METHOD'], [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
	}

	/**
	 * Whether this request should be identified as being "safe"
	 *
	 * This means that the client is not requesting any state changes and that database writes
	 * are not inherently required. Ideally, no visible updates would happen at all. If they
	 * must, then they should not be publically attributed to the end user.
	 *
	 * In more detail:
	 *   - Cache populations and refreshes MAY occur.
	 *   - Private user session updates and private server logging MAY occur.
	 *   - Updates to private viewing activity data MAY occur via DeferredUpdates.
	 *   - Other updates SHOULD NOT occur (e.g. modifying content assets).
	 *
	 * @return bool
	 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
	 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
	 * @since 1.28
	 */
	public function isSafeRequest() {
		if ( $this->markedAsSafe && $this->wasPosted() ) {
			return true; // marked as a "safe" POST
		}

		return $this->hasSafeMethod();
	}

	/**
	 * Mark this request as identified as being nullipotent even if it is a POST request
	 *
	 * POST requests are often used due to the need for a client payload, even if the request
	 * is otherwise equivalent to a "safe method" request.
	 *
	 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
	 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
	 * @since 1.28
	 */
	public function markAsSafeRequest() {
		$this->markedAsSafe = true;
	}
}

redpajama_set_name: RedPajamaGithub


text:
wordvis
=======

This is a project to visualize words by coloring them based on their word vector. Sort of a syntax highlighter for English.


text:
package com.google.cloud;

import java.io.IOException;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import com.fasterxml.jackson.core.exc.StreamReadException;
import com.fasterxml.jackson.databind.DatabindException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.jknack.handlebars.Context;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Jackson2Helper;
import com.github.jknack.handlebars.JsonNodeValueResolver;
import com.github.jknack.handlebars.Template;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonTemplateForChatTest {

    @DisplayName("Single test for Card")
    @Test
    void testCard() throws StreamReadException, DatabindException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode masterJSON = mapper.readTree(this.getClass().getClassLoader().getResource("input_01.json"));
        Handlebars handlebars = new Handlebars();
        handlebars.registerHelper("json", Jackson2Helper.INSTANCE);
        Template template = handlebars.compile("template_01");

        Context context = Context
                .newBuilder(masterJSON)
                .resolver(JsonNodeValueResolver.INSTANCE)
                .build();
        log.debug(template.apply(context));
        log.info("Success");
    }

    @DisplayName("Single test for Message")
    @Test
    void testMessage() throws StreamReadException, DatabindException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode masterJSON = mapper.readTree(this.getClass().getClassLoader().getResource("input_02.json"));
        Handlebars handlebars = new Handlebars();
        handlebars.registerHelper("json", Jackson2Helper.INSTANCE);
        Template template = handlebars.compile("message");

        Context context = Context
                .newBuilder(masterJSON)
                .resolver(JsonNodeValueResolver.INSTANCE)
                .build();
        log.debug(template.apply(context));

    }
}


text:
package org.elasticsearch.indices.recovery;

import org.elasticsearch.Version;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.index.seqno.SequenceNumbers;
import org.elasticsearch.transport.TransportResponse;

import java.io.IOException;

final class RecoveryTranslogOperationsResponse extends TransportResponse {
    final long localCheckpoint;

    RecoveryTranslogOperationsResponse(final long localCheckpoint) {
        this.localCheckpoint = localCheckpoint;
    }

    RecoveryTranslogOperationsResponse(final StreamInput in) throws IOException {
        super(in);
        // before 6.0.0 we received an empty response so we have to maintain that
        if (in.getVersion().onOrAfter(Version.V_6_0_0_alpha1)) {
            localCheckpoint = in.readZLong();
        }
        else {
            localCheckpoint = SequenceNumbers.UNASSIGNED_SEQ_NO;
        }
    }

    @Override
    public void writeTo(final StreamOutput out) throws IOException {
        super.writeTo(out);
        // before 6.0.0 we responded with an empty response so we have to maintain that
        if (out.getVersion().onOrAfter(Version.V_6_0_0_alpha1)) {
            out.writeZLong(localCheckpoint);
        }
    }
}


text:
import pytest

from hypothesis import given, settings, HealthCheck
from hypothesis import reproduce_failure  # pylint: disable=unused-import

from itertools import product

import numpy as np

from tests.hypothesis_helper import dfs_min2, dfs_no_min

from os import environ

if environ.get("TRAVIS"):
    max_examples = 10
    deadline = None
else:
    max_examples = 100
    deadline = None

strandedness = [False, "same", "opposite"]

binary_methods = [
    "set_union", "set_intersect", "overlap", "nearest", "intersect",
    "subtract", "join"
]

unary_methods = [
    "merge", "sort", "cluster", "pc", "mpc", "spc", "drop_duplicate_positions",
    "drop"
]

method_chain = product(binary_methods, binary_methods)
# cannot start with an operation that makes pyrange unstranded and then try a stranded op
strandedness_chain = list(product(["same", "opposite"], strandedness)) + list(
    product(strandedness, [None]))

@pytest.mark.bedtools
@pytest.mark.parametrize("strandedness_chain,method_chain",
                         product(strandedness_chain, method_chain))
@settings(
    max_examples=max_examples,
    deadline=deadline,
    print_blob=True,
    suppress_health_check=HealthCheck.all())
@given(gr=dfs_no_min(), gr2=dfs_no_min(), gr3=dfs_no_min())  # pylint: disable=no-value-for-parameter
# @reproduce_failure('5.5.4', b'AXicY2RAA4xIJCoLygcAALIABg==') # test_three_in_a_row[strandedness_chain122-method_chain122]
# @reproduce_failure('5.5.4', b'AXicY2QAAUYGKGBkxM9nAAABEAAJ') # test_three_in_a_row[strandedness_chain45-method_chain45]
# @reproduce_failure('5.5.4', b'AXicY2RAA4xIJDY+AAC2AAY=') # test_three_in_a_row[strandedness_chain24-method_chain24]
def test_three_in_a_row(gr, gr2, gr3, strandedness_chain, method_chain):

    print(method_chain)

    s1, s2 = strandedness_chain
    f1, f2 = method_chain

    suffix_methods = ["nearest", "join"]

    if f1 in suffix_methods and f2 in suffix_methods:

        m1 = getattr(gr, f1)
        gr2 = m1(gr2, strandedness=s1)
        if len(gr2) > 0:
            assert gr2.Start.dtype == np.int64
            assert (gr2.Start >= 0).all() and (gr2.End >= 0).all()
        m2 = getattr(gr2, f2)
        gr3 = m2(gr3, strandedness=s2, suffix="_c")
        print(gr3)
        if len(gr3) > 0:
            assert gr3.Start.dtype == np.int64
            assert (gr3.Start >= 0).all() and (gr3.End >= 0).all()

    else:

        m1 = getattr(gr, f1)
        gr2 = m1(gr2, strandedness=s1)
        if len(gr2) > 0:
            assert gr2.Start.dtype == np.int64
            assert (gr2.Start >= 0).all() and (gr2.End >= 0).all()
        m2 = getattr(gr2, f2)
        gr3 = m2(gr3, strandedness=s2)
        print(gr3)
        if len(gr3) > 0:
            assert gr3.Start.dtype == np.int64
            assert (gr3.Start >= 0).all() and (gr3.End >= 0).all()

# @pytest.mark.bedtools
# @pytest.mark.parametrize("strandedness_chain,method_chain",
#                          product(strandedness_chain, method_chain))
# @settings(
#     max_examples=max_examples,
#     deadline=deadline,
#     suppress_health_check=HealthCheck.all())
# @given(gr=dfs_no_min(), gr2=dfs_no_min(), gr3=dfs_no_min())  # pylint: disable=no-value-for-parameter
# def test_three_in_a_row(gr, gr2, gr3, strandedness_chain, method_chain):

#     s1, s2 = strandedness_chain
#     f1, f2 = method_chain

#     # print(s1, s2)
#     # print(f1, f2)

#     m1 = getattr(gr, f1)
#     gr2 = m1(gr2, strandedness=s1)
#     m2 = getattr(gr2, f2)
#     gr3 = m2(gr3, strandedness=s2)


text:
'use strict';

 /**
  * Cobia REST API module..
  * This module implements the RST API of the Cobia web application.
  * @module routes/api
  * @requires module:model/model
  */

const debug = require('debug')('cobia');          // eslint-disable-line no-unused-vars

const transducers = require('transducers-js');

// Polyfills
require('../lib/polyfills.js').arrayIncludes();

// Database access functions
const model = require('../model/model.js');

const VALID_QUERY_TERMS = ['captureType', 'method', 'resourceType'];

// http status code values
const OK = 200;
const NOT_FOUND = 404;
const INTERNAL_SERVER_ERROR = 500;
const NOT_IMPLEMENTED = 501;                    // eslint-disable-line no-unused-vars

// http header content type values
const APPLICATION_JSON = 'application/json';
const TEXT_PLAIN = 'text/plain';

// MongoDB logical operators
const MONGO_EQUALS = '$eq';
const MONGO_AND = '$and';

// Our defaults
const FETCH_SIZE_DEFAULT = 1000;

/**
 * @summary Safety check of query parameters
 * @description
 * Checks the req.query parameters for unsafe terms.
 * For example, the $where term is unsafe because of code injection attacks.
 * @static
 * @param {Object} req The request object from Express.
 * @param {Object} res The response object from Express. Content-Type is 'application/json'
 * @param {Function} next The next() callback for Express.
 * @returns {void}
 */
function checkQuerySafety (req, res, next) {
  const unsafeTerms = ['$where'];

  try {
    const queryString = req.query ? JSON.stringify(req.query).toLowerCase() : '';
    const safetyChecker = (term) => queryString.indexOf(term) > -1;
    const isUnsafe = unsafeTerms.some(safetyChecker);

    if (isUnsafe) {
      throw new Error('Unsafe query.');
    }
  } catch (err) {
    return void next(err);
  }

  next();

  return void 0;
}

/**
 * @summary **GET /api/hello/**
 * @description
 * Responds with a hello world text string.
 * @static
 * @param {Object} req The request object from Express.
 * @param {Object} res The response object from Express. Content-Type is 'text/plain'
 * @returns {void}
 */
function getHello (req, res) {
  res.set('Content-Type', TEXT_PLAIN).status(OK).send('Hello World! from the cobia api.');

  return void 0;
}

/**
 * @summary **GET /api/list-items/**
 * @description
 * Responds with a json document containing an array of list items.
 * @static
 * @param {Object} req The request object from Express.
 * @param {Object} res The response object from Express. Content-Type is 'application/json'
 * @param {Function} next The next() callback for Express.
 * @returns {void}
 */
function getListItems (req, res, next) {
  model.getListItems().then(function (result) {
    if (result.found) {
      res
        .set('Content-Type', APPLICATION_JSON)
        .status(OK)
        .send(JSON.stringify({
          type: result.type,
          count: result.documents.length,
          listItems: result.documents
        }));
    } else {
      res.sendStatus(NOT_FOUND);
    }
  }).catch(function (err) {
    next(err);
  });

  return void 0;
}

/**
 * @summary Builds the cursor query object for MongoDB
 * @description
 * The query object is built from req.query and is assigned to res.locals.queryParams.
 * Uses a transducer to transform. for example:
 * { captureType: 'monitor', method: 'GET', andAnInvalidOne: 'xxx', resourceType: 'main_frame' }
 * to
 * { $and: [{ captureType: { $eq: 'monitor' } }, { method: { $eq: 'GET' } }, { resourceType: { $eq: 'main_frame' } }] }
 * @see {@link http://phuu.net/2014/08/31/csp-and-transducers.html CSP and transducers in JavaScript by Tom Ashworth.}
 * @see {@link https://github.com/cognitect-labs/transducers-js}
 * @static
 * @param {Object} req The request object from Express.
 * @param {Object} res The response object from Express. Content-Type is 'application/json'
 * @param {Function} next The next() callback for Express.
 * @returns {void}
 */
function buildDbQuery (req, res, next) {
  // Gives us our source collection, for example: ['captureType', 'method', 'andAnInvalidOne', 'resourceType']
  const fetchQueryTermsFromRequest = (request) => Object.keys(request.query);

  // Our filter predicate function
  // Gives us, for example: ['captureType', 'method', 'resourceType']
  const filterer = (validTerms, term) => validTerms.includes(term);
  const filtererCurried = (validTerms) => (term) => filterer(validTerms, term);
  const isValidQueryTerm = filtererCurried(VALID_QUERY_TERMS);

  // Our mapping transform function
  // Gives us, for example: { captureType: { $eq: 'monitor' } }
  const mapper = function (request, term) {
    const condition = {};
    const conditionalValue = {};

    conditionalValue[MONGO_EQUALS] = request.query[term];
    condition[term] = conditionalValue;

    return condition;
  };
  const mapperCurried = (request) => (term) => mapper(request, term);
  const mapTermToCondition = mapperCurried(req);

  // Our reducer builder function
  // Pushes input terms into { '$and': [] }, returning the cursor query object for mongodb.
  const addToCursorQueryObject = function (result, input) {
    // Create the $and, first time round
    result[MONGO_AND] = result[MONGO_AND] || [];
    // Add the input value to the previous result giving the new result
    result[MONGO_AND].push(input);

    return result;
  };

  // Our transducer
  // This looks wrong to me as compose is right to left and we expect to filter first then map.
  // But that gives the filter the mapped result object, so it returns false... I checked in debug.
  // I tried ramda.compose() too... that behaved the same way.
  // So, filter then map, left to right works... I checked it in debug.
  const xf = transducers.comp(
    transducers.filter(isValidQueryTerm),
    transducers.map(mapTermToCondition)
  );

  const transduceCurried = (fetcher) => (transducer) => (builder) => (initial) => (source) => transducers.transduce(transducer, builder, initial, fetcher(source)); // eslint-disable-line max-len
  const buildDbQueryFromRequest = transduceCurried(fetchQueryTermsFromRequest)(xf)(addToCursorQueryObject)({});

  // Finally, do the work...
  // Reduce the query terms using the transducer to build the cursor query object and assign it to res.locals
  res.locals.dbQuery = buildDbQueryFromRequest(req);

  debug(`api.js#buildDbQuery: res.locals.dbQuery is ${JSON.stringify(res.locals.dbQuery, null, 2)}.`);

  next();

  return void 0;
}

/**
* @summary Builds the key or keys set for the sort.
* @description
* The object is assigned to res.locals.queryParams.
* Sorts by dateTime desc, url asc, _id desc.
* @static
* @param {Object} req The request object from Express.
* @param {Object} res The response object from Express. Content-Type is 'application/json'
* @param {Function} next The next() callback for Express.
* @returns {void}
 */
function buildSortCriteria (req, res, next) {
  res.locals.sortCriteria = {
    dateTime: -1,
    url: 1,
    _id: -1
  };
  next();

  return void 0;
}

/**
* @summary Sets up the parameters to control the paging.
* @description
* The res.locals.limit is set to the default page fecth size.
* @static
* @param {Object} req The request object from Express.
* @param {Object} res The response object from Express. Content-Type is 'application/json'
* @param {Function} next The next() callback for Express.
* @returns {void}
 */
function handlePaging (req, res, next) {
  res.locals.limit = FETCH_SIZE_DEFAULT;
  next();

  return void 0;
}

/**
* @summary Sets up the parameters to control field projection for the query.
* @description
* The field projection object is assigned to res.locals.projection.
* @static
* @param {Object} req The request object from Express.
* @param {Object} res The response object from Express. Content-Type is 'application/json'
* @param {Function} next The next() callback for Express.
* @returns {void}
 */
function setupProjection (req, res, next) {
  // res.locals.projection = null;
  // res.locals.projection = {
  //   _id: 1,
  //   captureType: 1,
  //   method: 1,
  //   url: 1,
  //   userEmail: 1,
  //   dateTime: 1,
  //   resourceType: 1
  // };
  res.locals.projection = {
    tabId: 0,
    requestId: 0,
    origin: 0
  };
  next();

  return void 0;
}

/**
 * @summary **GET /api/events/**
 * @description
 * Responds with a json document containing an array of events.
 * @static
 * @param {Object} req The request object from Express.
 * @param {Object} res The response object from Express. Content-Type is 'application/json'
 * @param {Function} next The next() callback for Express.
 * @returns {void}
 */
function getEvents (req, res, next) {
  model
    .getEvents(res.locals.projection, res.locals.limit, res.locals.sortCriteria, res.locals.dbQuery)
    .then(function (result) {
      debug(`api.js#getEvents: promise is fulfilled: found is ${result.found}, type is ${result.type}, and there are ${result.documents.length} documents.`);
      res.locals.found = result.found;
      res.locals.payload = null;
      if (result.found) {
        res.locals.payload = {
          ack: true,
          type: result.type,
          count: result.documents.length,
          data: result.documents
        };
      }
      next();
    }).catch(function (err) {
      next(err);
    });

  return void 0;
}

/**
 * @summary Sets up the response and sends to the client
 * @description
 * The res.locals.found should be set true and the json document to send should be in res.locals.payload.
 * If none found, then set res.locals.found to false and 404 NOT FOUND will be sent.
 * This method calls end() on the resonse, so no next() call is relevant.
 * @static
 * @param {Object} req The request object from Express.
 * @param {Object} res The response object from Express. Content-Type is 'application/json'
 * @returns {void}
 */
function respond (req, res) {
  if (res.locals.found) {
    if (res.locals.payload && typeof res.locals.payload === 'object' && Object.keys(res.locals.payload).length > 0) {
      res
      .set('Content-Type', APPLICATION_JSON)
      .status(OK)
      .send(JSON.stringify(res.locals.payload))
      .end();
    } else {
      res.sendStatus(INTERNAL_SERVER_ERROR);
    }
  } else {
    res.sendStatus(NOT_FOUND);
  }

  return void 0;
}

/**
 * @summary **POST /api/events/**
 * @description
 * Validates a new entry for the Events collection.
 * @static
 * @param {Object} req The request object from Express.
 * @param {Object} res The response object from Express. Content-Type is 'application/json'
 * @param {Function} next The next() callback for Express.
 * @returns {void}
 */
function validateEvent (req, res, next) {
  try {
    if (!(req.body && typeof req.body === 'object' && Object.keys(req.body).length > 0)) {
      throw new Error('No event document found in the request body.');
    }
    if (!(req.body.dateTime && typeof req.body.dateTime === 'string' && Date.parse(req.body.dateTime))) {
      throw new Error('Request body should have a valid dateTime as a string in ISO 8601 format according to universal time.');
    }
  } catch (err) {
    return void next(err);
  }

  next();

  return void 0;
}

/**
 * @summary **POST /api/events/**
 * @description
 * Constructs a new document for insertion into the Events collection.
 * The new event document is built from req.body and is assigned to res.locals.doc.
 * @static
 * @param {Object} req The request object from Express.
 * @param {Object} res The response object from Express. Content-Type is 'application/json'
 * @param {Function} next The next() callback for Express.
 * @returns {void}
 */
function buildNewEvent (req, res, next) {
  res.locals.newDoc = Object.assign(
    {},
    req.body,
    { dateTime: new Date(req.body.dateTime) },
    { origin: req.headers.origin }
  );
  next();

  return void 0;
}

/**
 * @summary **POST /api/events/**
 * @description
 * Creates a new entry in the Events collection and responds with a json document containing the new entry's URI.
 * @static
 * @param {Object} req The request object from Express.
 * @param {Object} res The response object from Express. Content-Type is 'application/json'
 * @param {Function} next The next() callback for Express.
 * @returns {void}
 */
function createEvent (req, res, next) {
  debug(`Creating new event: ${JSON.stringify(res.locals.newDoc, null, 2)}`);
  model.createEvent(res.locals.newDoc).then(function (result) {
    if (result.created) {
      debug(`New event created: ${JSON.stringify(result, null, 2)}`);
      res
        .set('Content-Type', APPLICATION_JSON)
        .status(OK)
        .send(JSON.stringify({
          ack: true,
          count: result.insertedCount,
          uri: `/${result.type}/${result._id}` // eslint-disable-line no-underscore-dangle
        }));
    } else {
      res.sendStatus(INTERNAL_SERVER_ERROR);
    }
  }).catch(function (err) {
    next(err);
  });

  return void 0;
}

module.exports.buildNewEvent = buildNewEvent;
module.exports.buildDbQuery = buildDbQuery;
module.exports.buildSortCriteria = buildSortCriteria;
module.exports.checkQuerySafety = checkQuerySafety;
module.exports.createEvent = createEvent;
module.exports.getEvents = getEvents;
module.exports.getHello = getHello;
module.exports.getListItems = getListItems;
module.exports.handlePaging = handlePaging;
module.exports.respond = respond;
module.exports.setupProjection = setupProjection;
module.exports.validateEvent = validateEvent;


text:
#!/bin/bash
###########################################################################
#
# Copyright 2017 Samsung Electronics All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
#
###########################################################################

# File   : mksampleapp.sh
# Description : make sample app templete

WD=$(cd `dirname $0` && pwd)

# USAGE
usage() {
    cat <<EOF
Usage: `basename $0` [awesome_app]
EOF
  exit $1
}

if test $# -ne 1; then
    echo "`basename $0`: Invaild line width: '$@'"
    usage 1 1>&2
fi

SAMPLES_NAME_L=`echo $1 | tr '[a-z]' '[A-Z]'`
SAMPLES_NAME_S=`echo $1 | tr '[A-Z]' '[a-z]'`
SAMPLES_PATH=${WD}/../examples/${SAMPLES_NAME_S}
SAMPLES_YEAR=$(date +%Y)
SAMPLES_SUB_SRC=src
SAMPLES_SUB_INC=inc

# make directory
mkdir -p ${SAMPLES_PATH}/${SAMPLES_SUB_SRC} ${SAMPLES_PATH}/${SAMPLES_SUB_INC}

# Kconfig
tee ${SAMPLES_PATH}/Kconfig << __EOF__
#
# For a description of the syntax of this configuration file,
# see kconfig-language at https://www.kernel.org/doc/Documentation/kbuild/kconfig-language.txt
#

config EXAMPLES_${SAMPLES_NAME_L}
	bool "${SAMPLES_NAME_S} example"
	default n
	---help---
		Enable ${SAMPLES_NAME_S} example

config USER_ENTRYPOINT
	string
	default "${SAMPLES_NAME_S}_main" if ENTRY_${SAMPLES_NAME_L}
__EOF__

# Kconfig_ENTRY
tee ${SAMPLES_PATH}/Kconfig_ENTRY << __EOF__
#
# For a description of the syntax of this configuration file,
# see kconfig-language at https://www.kernel.org/doc/Documentation/kbuild/kconfig-language.txt
#

config ENTRY_${SAMPLES_NAME_L}
	bool "${SAMPLES_NAME_S} example"
	depends on EXAMPLES_${SAMPLES_NAME_L}
__EOF__

# Make.defs
tee ${SAMPLES_PATH}/Make.defs << __EOF__
###########################################################################
#
# Copyright ${SAMPLES_YEAR} Samsung Electronics All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
#
###########################################################################

ifeq (\$(CONFIG_EXAMPLES_${SAMPLES_NAME_L}),y)
CONFIGURED_APPS += examples/${SAMPLES_NAME_S}
endif
__EOF__

# Makefile
tee ${SAMPLES_PATH}/Makefile << __EOF__
###########################################################################
#
# Copyright ${SAMPLES_YEAR} Samsung Electronics All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
#
###########################################################################

-include \$(TOPDIR)/.config
-include \$(TOPDIR)/Make.defs
include \$(APPDIR)/Make.defs

# built-in application info

APPNAME = ${SAMPLES_NAME_S}
THREADEXEC = TASH_EXECMD_SYNC

ASRCS =
CSRCS =
MAINSRC = ${SAMPLES_NAME_S}_main.c
CSRCS += \$(wildcard ${SAMPLES_SUB_SRC}

#include <stdio.h>

#ifdef CONFIG_BUILD_KERNEL
int main(int argc, FAR char *argv[])
#else
int ${SAMPLES_NAME_S}_main(int argc, FAR char *argv[])
#endif
{
	printf("%s\n", __func__);

	return 0;
}
__EOF__


text:
/* global appendChartID, coordsFromTranslate, loadDateFixture */
describe('dc.legend', () => {
    let id, chart, dateDimension, dateValueSumGroup, dateIdSumGroup;

    beforeEach(() => {
        const data = crossfilter(loadDateFixture());
        dateDimension = data.dimension(d => d3.utcDay(d.dd));
        dateValueSumGroup = dateDimension.group().reduceSum(d => d.value);
        dateIdSumGroup = dateDimension.group().reduceSum(d => d.id);

        id = 'legend-chart';
        appendChartID(id);
        chart = new dc.LineChart(`#${id}`);

        chart
            .dimension(dateDimension)
            .group(dateIdSumGroup, 'Id Sum')
            .stack(dateValueSumGroup, 'Value Sum')
            .stack(dateValueSumGroup, 'Fixed', () => {})
            .x(d3.scaleUtc().domain([new Date(2012, 4, 20), new Date(2012, 7, 15)]))
            .legend(new dc.Legend().x(400).y(10).itemHeight(13).gap(5));
    });

    describe('rendering the legend', () => {
        beforeEach(() => {
            chart.render();
        });

        it('should generate a legend', () => {
            expect(chart.select('g.dc-legend').empty()).toBeFalsy();
        });

        it('should place the legend using the provided x and y values', () => {
            expect(chart.select('g.dc-legend').attr('transform')).toMatchTranslate(400, 10);
        });

        it('should generate a legend item for each stacked line', () => {
            expect(chart.select('g.dc-legend').selectAll('g.dc-legend-item').size()).toBe(3);
        });

        it('should generate legend item boxes', () => {
            expect(legendIcon(0).attr('width')).toBeWithinDelta(13, 2);
            expect(legendIcon(0).attr('height')).toBeWithinDelta(13, 2);
        });

        it('should color the legend item boxes using the chart line colors', () => {
            expect(legendIcon(0).attr('fill')).toMatch(/#1f77b4/i);
            expect(legendIcon(1).attr('fill')).toMatch(/#ff7f0e/i);
            expect(legendIcon(2).attr('fill')).toMatch(/#2ca02c/i);
        });

        it('should generate a legend label for each chart line', () => {
            expect(chart.selectAll('g.dc-legend g.dc-legend-item text').size()).toBe(3);
        });

        it('should position the legend labels', () => {
            expect(legendLabel(0).attr('x')).toBeWithinDelta(15, 2);
            expect(legendLabel(0).attr('y')).toBeWithinDelta(11.75, 2);
            expect(legendLabel(1).attr('x')).toBeWithinDelta(15, 2);
            expect(legendLabel(1).attr('y')).toBeWithinDelta(11.75, 2);
            expect(legendLabel(2).attr('x')).toBeWithinDelta(15, 2);
            expect(legendLabel(2).attr('y')).toBeWithinDelta(11.75, 2);
        });

        it('should label the legend items with the names of their associated stacks', () => {
            expect(legendLabel(0).text()).toBe('Id Sum');
            expect(legendLabel(1).text()).toBe('Value Sum');
            expect(legendLabel(2).text()).toBe('Fixed');
        });

        it('not allow hiding stacks be default', () => {
            dc.d3compat.callHandler(legendItem(0).on('click'), legendItem(0).nodes()[0], {}, legendItem(0).datum());
            expect(chart.selectAll('path.line').size()).toBe(3);
        });

        describe('without .horizontal(true)', () => {
            it('should place legend items vertically', () => {
                expect(coordsFromTranslate(legendItem(0).attr('transform')).y).toBeWithinDelta(0, 1);
                expect(coordsFromTranslate(legendItem(1).attr('transform')).y).toBeWithinDelta(18, 2);
                expect(coordsFromTranslate(legendItem(2).attr('transform')).y).toBeWithinDelta(36, 4);
            });
        });

        describe('with .horizontal(true)', () => {
            beforeEach(() => {
                chart.legend(new dc.Legend().horizontal(true));
                chart.render();
            });

            it('should place legend items horizontally', () => {
                expect(coordsFromTranslate(legendItem(0).attr('transform')).x).toBeWithinDelta(0, 1);
                expect(coordsFromTranslate(legendItem(1).attr('transform')).x).toBeWithinDelta(65, 5);
                expect(coordsFromTranslate(legendItem(2).attr('transform')).x).toBeWithinDelta(155, 15);
            });
        });

        describe('with .horizontal(true) and defined legendWidth and itemWidth', () => {
            let legendCoords;
            beforeEach(() => {
                chart.legend(new dc.Legend().horizontal(true).legendWidth(60).itemWidth(30));
                chart.render();
                legendCoords = d3.range(3).map(i => coordsFromTranslate(legendItem(i).attr('transform')));
            });

            it('should place legend items in two columns. third item is new row', () => {
                expect(legendCoords[0].x).toBeWithinDelta(0, 1);
                expect(legendCoords[0].y).toBeWithinDelta(0, 1);
                expect(legendCoords[1].x).toBeWithinDelta(30, 5);
                expect(legendCoords[1].y).toBeWithinDelta(0, 1);
                expect(legendCoords[2].x).toBeWithinDelta(0, 1);
                expect(legendCoords[2].y).toBeWithinDelta(13, 5);
            });
        });

        describe('with .autoItemWidth not called', () => {
            beforeEach(() => {
                chart.legend(new dc.Legend());
            });

            it('_autoItemWidth should be false', () => {
                expect(chart.legend().autoItemWidth()).toBe(false);
            });
        });

        describe('with .autoItemWidth(false)', () => {
            beforeEach(() => {
                chart.legend(new dc.Legend().autoItemWidth(false));
            });

            it('_autoItemWidth should be false', () => {
                expect(chart.legend().autoItemWidth()).toBe(false);
            });
        });

        describe('with .autoItemWidth(true)', () => {
            beforeEach(() => {
                chart.legend(new dc.Legend().autoItemWidth(true));
            });
            it('_autoItemWidth should be true', () => {
                expect(chart.legend().autoItemWidth()).toBe(true);
            });
        });

        describe('with .horizontal(true) and .autoItemWidth(true)', () => {

            let fixedWidthOffset1, autoWidthCoords;

            beforeEach(() => {
                chart.legend(new dc.Legend().horizontal(true).itemWidth(30).autoItemWidth(false));
                chart.render();
                fixedWidthOffset1 = coordsFromTranslate(legendItem(1).attr('transform')).x;
                chart.legend(new dc.Legend().horizontal(true).itemWidth(30).autoItemWidth(true).legendWidth(160));
                chart.render();
                autoWidthCoords = d3.range(3).map(i => coordsFromTranslate(legendItem(i).attr('transform')));
            });

            it('autoWidth x offset should be greater than fixedWidth x offset for the second item', () => {
                expect(autoWidthCoords[1].x).toBeGreaterThan(fixedWidthOffset1);
            });
            it('should wrap the third item based on actual widths', () => {
                expect(autoWidthCoords[2].x).toBe(0);
                expect(autoWidthCoords[2].y).toBeWithinDelta(13, 5);
            });
        });

        describe('with .legendText()', () => {
            beforeEach(() => {
                chart.legend(new dc.Legend().legendText((d, i) => {
                    const _i = i + 1;

                    return `${_i}. ${d.name}`;
                }));
                chart.render();
            });

            it('should label the legend items with the names of their associated stacks', () => {
                expect(legendLabel(0).text()).toBe('1. Id Sum');
                expect(legendLabel(1).text()).toBe('2. Value Sum');
                expect(legendLabel(2).text()).toBe('3. Fixed');
            });
        });

        describe('with .maxItems(2)', () => {
            beforeEach(() => {
                chart.legend()
                    .maxItems(2);
                chart.render();
            });
            it('should display two items', () => {
                expect(chart.select('g.dc-legend').selectAll('g.dc-legend-item').size()).toBe(2);
            });
        });

        describe('with invalid .maxItems', () => {
            beforeEach(() => {
                chart.legend()
                    .maxItems('foo');
                chart.render();
            });
            it('should display three items', () => {
                expect(chart.select('g.dc-legend').selectAll('g.dc-legend-item').size()).toBe(3);
            });
        });
    });

    describe('legends with dashed lines', () => {
        beforeEach(() => {
            id = 'legend-chart-dashed';
            appendChartID(id);
            chart = new dc.CompositeChart(`#${id}`);

            const subChart1 = new dc.LineChart(chart);
            subChart1
                .dimension(dateDimension)
                .group(dateIdSumGroup, 'Id Sum')
                .dashStyle([10,1]);

            const subChart2 = new dc.LineChart(chart);
            subChart2
                .dimension(dateDimension)
                .group(dateValueSumGroup, 'Value Sum')
                .dashStyle([2,1]);

            chart
                .x(d3.scaleLinear().domain([0,20]))
                .legend(new dc.Legend().x(400).y(10).itemHeight(13).gap(5))
                .compose([subChart1, subChart2])
                .render();
        });

        it('should style legend line correctly', () => {
            expect(legendLine(0).attr('stroke-dasharray')).toEqualIntOrPixelList('10,1');
            expect(legendLine(1).attr('stroke-dasharray')).toEqualIntOrPixelList('2,1');
        });
    });

    describe('legends with hidable stacks', () => {
        beforeEach(() => {
            chart.hidableStacks(true).render();
        });

        describe('clicking on a legend item', () => {
            beforeEach(() => {
                dc.d3compat.callHandler(legendItem(0).on('click'), legendItem(0).nodes()[0], {}, legendItem(0).datum());
            });

            it('should fade out the legend item', () => {
                expect(legendItem(0).classed('fadeout')).toBeTruthy();
            });

            it('should hide its associated stack', () => {
                expect(chart.selectAll('path.line').size()).toEqual(2);
            });

            it('disable hover highlighting for that legend item', () => {
                dc.d3compat.callHandler(legendItem(0).on('mouseover'), null, {}, legendItem(0).datum());
                expect(d3.select(chart.selectAll('path.line').nodes()[1]).classed('fadeout')).toBeFalsy();
            });

            describe('clicking on a faded out legend item', () => {
                beforeEach(() => {
                    dc.d3compat.callHandler(legendItem(0).on('click'), legendItem(0).nodes()[0], {}, legendItem(0).datum());
                });

                it('should unfade the legend item', () => {
                    expect(legendItem(0).classed('fadeout')).toBeFalsy();
                });

                it('should unfade its associated stack', () => {
                    expect(chart.selectAll('path.line').size()).toEqual(3);
                });
            });
        });
    });

    describe('accessible legends', () => {
        beforeEach(() => {
            chart.legend(new dc.Legend().keyboardAccessible(true)).render();
        });

        it('legend items should be focusable from keyboard', () => {

            chart.select('g.dc-legend').selectAll('g.dc-legend-item text').each(function () {
                const item = d3.select(this);
                expect(item.attr('tabindex')).toEqual('0');
            });

        });

        it('keyboard focus on legend item should highlight chart item', () => {

            dc.d3compat.callHandler(
                chart.select('g.dc-legend').select('g.dc-legend-item text').on('focus'),
                legendItem(0).nodes()[0], {}, legendItem(0).datum());

            expect(d3.select(chart.selectAll('path.line').nodes()[0]).classed('highlight')).toBeTruthy();
        });

    });

    function legendItem (n) {
        return d3.select(chart.selectAll('g.dc-legend g.dc-legend-item').nodes()[n]);
    }
    function legendLabel (n) {
        return d3.select(chart.selectAll('g.dc-legend g.dc-legend-item text').nodes()[n]);
    }
    function legendIcon (n) {
        return d3.select(chart.selectAll('g.dc-legend g.dc-legend-item rect').nodes()[n]);
    }
    function legendLine (n) {
        return d3.select(chart.selectAll('g.dc-legend g.dc-legend-item line').nodes()[n]);
    }
});


text:
// Copyright 2012 Traceur Authors.
//
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import {AlphaRenamer} from './AlphaRenamer.js';
import {
  BINDING_IDENTIFIER,
  BLOCK,
  VARIABLE_DECLARATION_LIST
} from '../syntax/trees/ParseTreeType.js';
import {
  FunctionDeclaration,
  FunctionExpression
} from '../syntax/trees/ParseTrees.js';
import {ParseTreeTransformer} from './ParseTreeTransformer.js';
import {
  CONST,
  LET,
  VAR
} from '../syntax/TokenType.js';
import {
  createAssignmentExpression,
  createBindingIdentifier,
  createBlock,
  createCatch,
  createEmptyStatement,
  createExpressionStatement,
  createFinally,
  createForInStatement,
  createForStatement,
  createIdentifierExpression,
  createIdentifierToken,
  createThrowStatement,
  createTryStatement,
  createUndefinedExpression,
  createVariableDeclaration,
  createVariableDeclarationList,
  createVariableStatement
} from './ParseTreeFactory.js';

/**
 * Transforms the block bindings from traceur to js.
 * The scope for let binding is just the containing block which can be achieved
 * in javascript in two ways: nested function or catch block.
 *
 * Nested function only works if there is no control flow passing through the
 * let block (break, continue, return), there is no const variable contained
 * anywhere within the let block and 'this' or 'arguments' are not used.
 * Given how uncommon the let block unaffected by any of these is, all blocks
 * are transformed using catch:
 *
 * try { throw uninitialized; } catch (let_var) { ... }
 *
 * const variables and nested function declarations are handled the same way,
 * the final solution for const is to be implemented.
 *
 * 'var' variables are unaffected by the rewrite because their scope is whole
 * function, and that is not affected by try .. catch blocks.
 *
 * The block binding rewrite pass assumes that deconstructing assignments
 * and variable declarations have already been desugared. See getVariableName_.
 *
 * TODO: Implement const support (currently rewritten exactly as 'let')
 */

var ScopeType = {
  PROGRAM: 'PROGRAM',
  FUNCTION: 'FUNCTION',
  BLOCK: 'BLOCK'
};

/**
 * Represents the link in the scope chain.
 */
class Scope {
  /**
   * @param {Scope} parent The parent scope, or null if top level (program)
   *     scope.
   * @param {ScopeType} type Scope type: global, function, block.
   */
  constructor(parent, type) {
    this.parent = parent;
    this.type = type;
    /** Block scoped variables accumulated within the block. */
    this.blockVariables = null;
  }

  /**
   * Stores a block scoped variable for future processing.
   * @param {string} value
   */
  addBlockScopedVariable(value) {
    if (!this.blockVariables) {
      this.blockVariables = Object.create(null);
    }
    this.blockVariables[value] = true;
  }
};

class Rename {
  /**
   * @param {string} oldName
   * @param {string} newName
   */
  constructor(oldName, newName) {
    this.oldName = oldName;
    this.newName = newName;
  }
}

/**
 * @param {Array.<Rename>} renames
 * @param {ParseTree} tree
 * @return {ParseTree}
 */
function renameAll(renames, tree) {
  renames.forEach((rename) => {
    tree = AlphaRenamer.rename(tree, rename.oldName, rename.newName);
  });
  return tree;
}

/**
 * Wraps a statement in a block if needed.
 * @param {ParseTree} statements
 * @return {Block}
 */
function toBlock(statement) {
  return statement.type == BLOCK ? statement : createBlock(statement);
}

export class BlockBindingTransformer extends ParseTreeTransformer {
  constructor(stateAllocator) {
    super();
    this.scope_ = null;
  }

  /**
   * Creates top level (program) scope.
   * Inside the scope, let/const become vars (const only temporarily),
   * functions are unchanged.
   * @return {Scope}
   */
  createProgramScope_() {
    // program scope is never a block/let scope
    return new Scope(this.scope_, ScopeType.PROGRAM);
  }

  /**
   * Creates function level scope.
   * let/const is rewritten, function names are not.
   * @return {Scope}
   */
  createFunctionScope_() {
    if (this.scope_ == null) {
      throw new Error('Top level function scope found.');
    }
    // program scope is never a block/let scope
    return new Scope(this.scope_, ScopeType.FUNCTION);
  }

  /**
   * Creates block scope - inside it let/const/function have limited scope.
   * @return {Scope}
   */
  createBlockScope_() {
    if (this.scope_ == null) {
      throw new Error('Top level block scope found.');
    }
    // contained within block scope
    return new Scope(this.scope_, ScopeType.BLOCK);
  }

  /**
   * Pushes new scope
   * @param {Scope} scope
   * @return {Scope}
   */
  push_(scope) {
    this.scope_ = scope;
    return scope;
  }

  /**
   * Pops scope, tracks proper matching of push_/pop_ operations.
   * @param {Scope} scope
   */
  pop_(scope) {
    if (this.scope_ != scope) {
      throw new Error('BlockBindingTransformer scope mismatch');
    }

    this.scope_ = scope.parent;
  }

  // The transform methods override from the base.

  /**
   * Transforms block scope, rewriting all block-scoped variables/functions.
   * @param {Block} tree
   * @return {ParseTree}
   */
  transformBlock(tree) {
    // Push new scope.
    var scope = this.push_(this.createBlockScope_());

    // Transform the block contents
    var statements = this.transformList(tree.statements);

    if (scope.blockVariables != null) {
      // rewrite into catch construct
      tree = toBlock(
          this.rewriteAsCatch_(scope.blockVariables, createBlock(statements)));
    } else if (statements != tree.statements) {
      tree = createBlock(statements);
    }

    this.pop_(scope);
    return tree;
  }

  /**
   * Declares block-scoped variables. Does so by wrapping a block in
   * a try .. catch for each block scoped variable in the set.
   *
   * 'let x = 1;' turns into:
   *
   * try {
   *   throw undefined;
   * } catch (x) {
   *   x = 1;   // let x = 1
   *   ...
   *   }
   * }
   *
   * @param {Object} blockVariables
   * @param {ParseTree} statements
   * @return {ParseTree}
   */
  rewriteAsCatch_(blockVariables, statement) {
    // Build the try .. catch structure from within.
    // try {
    //   throw undefined;
    // } catch (<block scoped variable>) {
    //   <block>
    // }
    for (var variable in blockVariables) {
      statement =
          createTryStatement(
              createBlock(                  // try
                  createThrowStatement(
                      createUndefinedExpression())),
              createCatch(                  // catch
                  createBindingIdentifier(variable),
                  toBlock(statement)),
              null);                       // finally
    }

    return statement;
  }

  /** Class declarations should have been transformed away. */
  /**
   * @param {ClassDeclaration} tree
   * @return {ParseTree}
   */
  transformClassDeclaration(tree) {
    throw new Error('ClassDeclaration should be transformed away.');
  }

  /**
   * Transforms for .. in statement.
   */
  /**
   * @param {ForInStatement} tree
   * @return {ParseTree}
   */
  transformForInStatement(tree) {
    // Save it here because tree may change in the variable rewrite
    var treeBody = tree.body;

    var initializer;
    if (tree.initializer != null &&
        tree.initializer.type == VARIABLE_DECLARATION_LIST) {

      // for (var/let/const x [ = ...] in ...)
      var variables = tree.initializer;

      // Only one declaration allowed.
      if (variables.declarations.length != 1) {
        throw new Error('for .. in has != 1 variables');
      }

      var variable = variables.declarations[0];
      var variableName = this.getVariableName_(variable);

      switch (variables.declarationType) {
        case LET:
        case CONST: {
          // initializer is illegal in for (const/let x in ...)
          // this should have been caught in the parser.
          if (variable.initializer != null) {
            throw new Error(
                'const/let in for-in may not have an initializer');
          }

          // Build the result
          // for (var $x in ...) {
          //   let x = $x;
          //   ...
          // }
          // TODO: Use temp allocator.
          initializer = createVariableDeclarationList(
              VAR, `$${variableName}`, null);

          // Add the let statement into the block and rewrite it next.
          // It is easier than creating the catch block manually etc.
          treeBody = this.prependToBlock_(
              createVariableStatement(
                  LET,
                  variableName,
                  createIdentifierExpression(`$${variableName}`)),
              treeBody);
          break;
        }

        case VAR:
          // No special work for var
          initializer = this.transformVariables_(variables);
          break;

        default:
          throw new Error('Unreachable.');
      }
    } else {
      initializer = this.transformAny(tree.initializer);
    }

    var result = tree;
    var collection = this.transformAny(tree.collection);
    var body = this.transformAny(treeBody);

    if (initializer != tree.initializer ||
        collection != tree.collection ||
        body != tree.body) {
      result = createForInStatement(initializer, collection, body);
    }

    return result;
  }

  /**
   * TODO: Use non-scoped blocks (statement comma) when available.
   * @param {ParseTree} statement
   * @param {ParseTree} body
   * @return {Block}
   */
  prependToBlock_(statement, body) {
    if (body.type == BLOCK) {
      var block = body;
      var list = [statement, ... block.statements];
      return createBlock(list);
    } else {
      return createBlock(statement, body);
    }
  }

  /**
   * Transforms the for ( ... ; ... ; ... ) { ... } statement.
   * @param {ForStatement} tree
   * @return {ParseTree}
   */
  transformForStatement(tree) {
    var initializer;
    if (tree.initializer != null &&
        tree.initializer.type == VARIABLE_DECLARATION_LIST) {

      // for (var/let/const ... ; ; ) { ... }
      var variables = tree.initializer;

      switch (variables.declarationType) {
        case LET:
        case CONST:
          // let/const are rewritten differently so the code below doesn't apply
          return this.transformForLet_(tree, variables);

        case VAR:
          // No special work for var.
          initializer = this.transformVariables_(variables);
          break;

        default:
          throw new Error('Reached unreachable.');
      }
    } else {
      // The non-var case: for (x = ...; ; ) { ... }
      initializer = this.transformAny(tree.initializer);
    }

    // Finish transforming the body.
    var condition = this.transformAny(tree.condition);
    var increment = this.transformAny(tree.increment);
    var body = this.transformAny(tree.body);

    var result = tree;

    if (initializer != tree.initializer ||
        condition != tree.condition ||
        increment != tree.increment ||
        body != tree.body) {
      // Create new for statement.
      result = createForStatement(initializer, condition, increment, body);
    }

    return result;
  }

  /*
   * Transforms the for (let ...; ...; ...) { ... } statement. There are few
   * steps to this:
   *
   * 1. Hoist the declaration out of the for loop (keep as let for further
   *    rewrite)
   * 2. Rename the hoisted declared variables
   * 3. Wrap the for loop body in a try..finally block
   * 4. Before the try block, copy all variables into new block scoped
   *    variables (using original names)
   * 5. In the finally, write-back the to the hoisted variables
   *
   * For example:
   *
   * for (let x = 1, y = x + 2; x + y < 10, x ++, y ++) {
   *  if (condition) {
   *    continue;
   *  }
   * }
   *
   * translates into:
   *
   * {
   *   let $x = 1, $y = $x + 2;     // initializer dependencies
   *   for ( ; $x + $y < 10; $x++, $y++) {
   *     let x = $x, y = $y;
   *     try {
   *       // for loop body
   *       if (condition) {
   *         continue;
   *       }
   *
   *     } finally {
   *       $x = x;    // write-backs into the hoisted variables
   *       $y = y;
   *     }
   *   }
   * }
   * @param {ForStatement} tree
   * @param {VariableDeclarationList} variables
   * @return {ParseTree}
   */
  transformForLet_(tree, variables) {

    // Accumulator for 'let x = $x;'
    var copyFwd = [];

    // Accumulator for '$x = x' copybacks
    var copyBak = [];

    // Accumulator for the hoisted declaration: let $x = 1, ...;
    var hoisted = [];

    var renames = [];

    variables.declarations.forEach((variable) => {
      var variableName = this.getVariableName_(variable);
      var hoistedName = `$${variableName}`;

      // perform renames in the initializer
      var initializer = renameAll(renames, variable.initializer);

      // hoisted declaration: let $x = 1
      hoisted.push(createVariableDeclaration(hoistedName, initializer));

      // copy forward: let x = $x;
      copyFwd.push(
          createVariableDeclaration(
              variableName,
              createIdentifierExpression(hoistedName)));

      // copy back: $x = x;
      copyBak.push(
          createExpressionStatement(
              createAssignmentExpression(
                  createIdentifierExpression(hoistedName),
                  createIdentifierExpression(variableName))));

      // Remember rename for the subsequent initializers
      renames.push(new Rename(variableName, hoistedName));
    });

    // 'tree.condition' with renamed variables
    var condition = renameAll(renames, tree.condition);
    // 'tree.increment' with renamed variables
    var increment = renameAll(renames, tree.increment);

    // package it all up
    var transformedForLoop = createBlock(
        // hoisted declaration
        createVariableStatement(
            createVariableDeclarationList(
                LET, hoisted)),
        // for loop
        createForStatement(
            null,
            condition,
            increment,
            // body
            createBlock(
                createVariableStatement(
                    // let x = $x;
                    createVariableDeclarationList(LET, copyFwd)),
                // try { ... } finally { copyBak }
                createTryStatement(
                    // try - the original for loop body
                    toBlock(tree.body),
                    // catch (none)
                    null,
                    // finally - the writebacks
                    createFinally(createBlock(copyBak))))));

    // Now transform the rewritten for loop! This is safe to do because the
    return this.transformAny(transformedForLoop);
  }

  /**
   * Transforms a function declaration statement. Function name in the block
   * scope is scoped to the block only, so the same rewrite applies.
   *
   * @param {FunctionDeclaration} tree
   * @return {ParseTree}
   */
  transformFunctionDeclaration(tree) {
    var body = this.transformFunctionBody(tree.functionBody);
    var formalParameterList = this.transformAny(tree.formalParameterList);

    if (this.scope_.type === ScopeType.BLOCK) {
      // Named function in a block scope is only scoped to the block.
      // Add function name into variable hash to later 'declare' the
      // block scoped variable for it.
      this.scope_.addBlockScopedVariable(tree.name.identifierToken.value);

      // f = function( ... ) { ... }
      return createExpressionStatement(
          createAssignmentExpression(
              createIdentifierExpression(tree.name.identifierToken),
              new FunctionExpression(tree.location, null, tree.isGenerator,
                                     formalParameterList, body)));
    }

    if (body === tree.functionBody &&
        formalParameterList === tree.formalParameterList) {
      return tree;
    }

    return new FunctionDeclaration(tree.location, tree.name, tree.isGenerator,
                                   formalParameterList, body);
  }

  /**
   * Transforms the whole program.
   * @param {Program} tree
   * @return {ParseTree}
   */
  transformProgram(tree) {
    // Push new scope
    var scope = this.push_(this.createProgramScope_());

    var result = super.transformProgram(tree);

    this.pop_(scope);
    return result;
  }

  /**
   * Variable declarations are detected earlier and handled elsewhere.
   * @param {VariableDeclaration} tree
   * @return {ParseTree}
   */
  transformVariableDeclaration(tree) {
    throw new Error('Should never see variable declaration tree.');
  }

  /**
   * Variable declarations are detected earlier and handled elsewhere.
   * @param {VariableDeclarationList} tree
   * @return {ParseTree}
   */
  transformVariableDeclarationList(tree) {
    throw new Error('Should never see variable declaration list.');
  }

  /**
   * Transforms the variable statement. Inside a block const and let
   * are transformed into block-scoped variables.
   * Outside of the block, const and let becomes regular variables.
   * @param {VariableStatement} tree
   * @return {ParseTree}
   */
  transformVariableStatement(tree) {
    if (this.scope_.type == ScopeType.BLOCK) {
      // let/const have block scoped meaning only in block scope.
      switch (tree.declarations.declarationType) {
        case CONST:
        case LET:
          return this.transformBlockVariables_(tree.declarations);

        default:
          break;
      }
    }

    // Default handling.
    var variables = this.transformVariables_(tree.declarations);

    if (variables != tree.declarations) {
      tree = createVariableStatement(variables);
    }

    return tree;
  }

  /**
   * Transforms block scoped variables.
   * Series of declarations become a comma of assignment expressions
   * which is later turned into a statement, minimizing block creation
   * overhead.
   * @param {VariableDeclarationList} tree
   * @return {ParseTree}
   */
  transformBlockVariables_(tree) {
    var variables = tree.declarations;
    var comma = [];

    variables.forEach((variable) => {
      switch (tree.declarationType) {
        case LET:
        case CONST:
          break;
        default:
          throw new Error('Only let/const allowed here.');
      }

      var variableName = this.getVariableName_(variable);

      // Store the block scoped variable for future 'declaration'.
      this.scope_.addBlockScopedVariable(variableName);
      var initializer = this.transformAny(variable.initializer);

      if (initializer != null) {
        // varname = initializer, ...
        comma.push(
            createAssignmentExpression(
                createIdentifierExpression(variableName),
                initializer));
      }
    });

    switch (comma.length) {
      case 0:
        return createEmptyStatement();
      case 1:
        return createExpressionStatement(comma[0]);
      default:
        // Turn comma into statements
        for (var i = 0; i < comma.length; i++) {
          comma[i] = createExpressionStatement(comma[i]);
        }
        return createBlock(comma);
    }
  }

  /**
   * Transforms variables unaffected by block scope.
   * @param {VariableDeclarationList} tree
   * @return {VariableDeclarationList}
   */
  transformVariables_(tree) {

    var variables = tree.declarations;
    var transformed = null;

    for (var index = 0; index < variables.length; index++) {
      var variable = variables[index];
      var variableName = this.getVariableName_(variable);

      // Transform the initializer.
      var initializer = this.transformAny(variable.initializer);

      if (transformed != null || initializer != variable.initializer) {
        // Variable was rewritten.
        if (transformed == null) {
          transformed = variables.slice(0, index);
        }

        // var/const x = <initializer>;
        transformed.push(
            createVariableDeclaration(
                createIdentifierToken(variableName), initializer));
      }
    }

    // Package up in the declaration list.
    if (transformed != null || tree.declarationType != VAR) {
      var declarations = transformed != null ? transformed : tree.declarations;
      var declarationType = tree.declarationType != VAR ?
          VAR :
          tree.declarationType;

      tree = createVariableDeclarationList(declarationType, declarations);
    }
    return tree;
  }

  /**
   * @param {Block} tree
   * @return {Block}
   */
  transformFunctionBody(body) {
    // Push new function context
    var scope = this.push_(this.createFunctionScope_());

    body = this.transformBlockStatements_(body);

    this.pop_(scope);
    return body;
  }

  /**
   * @param {Block} tree
   * @return {Block}
   */
  transformBlockStatements_(tree) {
    var statements = this.transformList(tree.statements);

    if (this.scope_.blockVariables != null) {
      // rewrite into catch construct
      tree = toBlock(
          this.rewriteAsCatch_(
              this.scope_.blockVariables,
              createBlock(statements)));
    } else if (statements != tree.statements) {
      tree = createBlock(statements);
    }

    return tree;
  }

  /**
   * @param {VariableDeclaration} variable
   * @return {string}
   */
  getVariableName_(variable) {
    // TODO(arv): This should just be a visitor visiting BindingIdentifier
    var lvalue = variable.lvalue;
    if (lvalue.type == BINDING_IDENTIFIER) {
      return lvalue.identifierToken.value;
    }
    throw new Error('Unexpected destructuring declaration found.');
  }

  /**
   * @param {Program} tree
   * @return {Program}
   */
  static transformTree(tree) {
    return new BlockBindingTransformer().transformAny(tree);
  }
}