text:
<?php

if( !function_exists( 'curl_init' ) )
{
		throw new Exception( 'Facebook needs the CURL PHP extension.' );
}
if( !function_exists( 'json_decode' ) )
{
		throw new Exception( 'Facebook needs the JSON PHP extension.' );
}

/**
 * Thrown when an API call returns an exception.
 *
 * @author Naitik Shah <naitik@facebook.com>
 */
class FacebookApiException extends Exception {

		/**
		 * The result from the API server that represents the exception information.
		 */
		protected $result;

		/**
		 * Make a new API Exception with the given result.
		 *
		 * @param array $result The result from the API server
		 */
		public function __construct( $result )
		{
				$this->result = $result;

				$code = isset( $result['error_code'] ) ? $result['error_code'] : 0;

				if( isset( $result['error_description'] ) )
				{
						// OAuth 2.0 Draft 10 style
						$msg = $result['error_description'];
				}
				else if( isset( $result['error'] ) && is_array( $result['error'] ) )
				{
						// OAuth 2.0 Draft 00 style
						$msg = $result['error']['message'];
				}
				else if( isset( $result['error_msg'] ) )
				{
						// Rest server style
						$msg = $result['error_msg'];
				}
				else
				{
						$msg = 'Unknown Error. Check getResult()';
				}

				parent::__construct( $msg, $code );
		}

		/**
		 * Return the associated result object returned by the API server.
		 *
		 * @return array The result from the API server
		 */
		public function getResult()
		{
				return $this->result;
		}

		/**
		 * Returns the associated type for the error. This will default to
		 * 'Exception' when a type is not available.
		 *
		 * @return string
		 */
		public function getType()
		{
				if( isset( $this->result['error'] ) )
				{
						$error = $this->result['error'];
						if( is_string( $error ) )
						{
								// OAuth 2.0 Draft 10 style
								return $error;
						}
						else if( is_array( $error ) )
						{
								// OAuth 2.0 Draft 00 style
								if( isset( $error['type'] ) )
								{
										return $error['type'];
								}
						}
				}

				return 'Exception';
		}

		/**
		 * To make debugging easier.
		 *
		 * @return string The string representation of the error
		 */
		public function __toString()
		{
				$str = $this->getType().': ';
				if( $this->code != 0 )
				{
						$str .= $this->code.': ';
				}
				return $str.$this->message;
		}

}

/**
 * Provides access to the Facebook Platform.  This class provides
 * a majority of the functionality needed, but the class is abstract
 * because it is designed to be sub-classed.  The subclass must
 * implement the four abstract methods listed at the bottom of
 * the file.
 *
 * @author Naitik Shah <naitik@facebook.com>
 */
abstract class BaseFacebook {
		/**
		 * Version.
		 */
		const VERSION = '3.1.1';

		/**
		 * Default options for curl.
		 */
		public static $CURL_OPTS = array(
				CURLOPT_CONNECTTIMEOUT => 10,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_TIMEOUT => 60,
				CURLOPT_USERAGENT => 'facebook-php-3.1',
		);

		/**
		 * List of query parameters that get automatically dropped when rebuilding
		 * the current URL.
		 */
		protected static $DROP_QUERY_PARAMS = array(
				'code',
				'state',
				'signed_request',
		);

		/**
		 * Maps aliases to Facebook domains.
		 */
		public static $DOMAIN_MAP = array(
				'api' => 'https://api.facebook.com/',
				'api_video' => 'https://api-video.facebook.com/',
				'api_read' => 'https://api-read.facebook.com/',
				'graph' => 'https://graph.facebook.com/',
				'www' => 'https://www.facebook.com/',
		);

		/**
		 * The Application ID.
		 *
		 * @var string
		 */
		protected $appId;

		/**
		 * The Application API Secret.
		 *
		 * @var string
		 */
		protected $apiSecret;

		/**
		 * The ID of the Facebook user, or 0 if the user is logged out.
		 *
		 * @var integer
		 */
		protected $user;

		/**
		 * The data from the signed_request token.
		 */
		protected $signedRequest;

		/**
		 * A CSRF state variable to assist in the defense against CSRF attacks.
		 */
		protected $state;

		/**
		 * The OAuth access token received in exchange for a valid authorization
		 * code.  null means the access token has yet to be determined.
		 *
		 * @var string
		 */
		protected $accessToken = null;

		/**
		 * Indicates if the CURL based @ syntax for file uploads is enabled.
		 *
		 * @var boolean
		 */
		protected $fileUploadSupport = false;

		/**
		 * Initialize a Facebook Application.
		 *
		 * The configuration:
		 * - appId: the application ID
		 * - secret: the application secret
		 * - fileUpload: (optional) boolean indicating if file uploads are enabled
		 *
		 * @param array $config The application configuration
		 */
		public function __construct( $config )
		{
				$this->setAppId( $config['appId'] );
				$this->setApiSecret( $config['secret'] );
				if( isset( $config['fileUpload'] ) )
				{
						$this->setFileUploadSupport( $config['fileUpload'] );
				}

				$state = $this->getPersistentData( 'state' );
				if( !empty( $state ) )
				{
						$this->state = $this->getPersistentData( 'state' );
				}
		}

		/**
		 * Set the Application ID.
		 *
		 * @param string $appId The Application ID
		 * @return BaseFacebook
		 */
		public function setAppId( $appId )
		{
				$this->appId = $appId;
				return $this;
		}

		/**
		 * Get the Application ID.
		 *
		 * @return string the Application ID
		 */
		public function getAppId()
		{
				return $this->appId;
		}

		/**
		 * Set the API Secret.
		 *
		 * @param string $apiSecret The API Secret
		 * @return BaseFacebook
		 */
		public function setApiSecret( $apiSecret )
		{
				$this->apiSecret = $apiSecret;
				return $this;
		}

		/**
		 * Get the API Secret.
		 *
		 * @return string the API Secret
		 */
		public function getApiSecret()
		{
				return $this->apiSecret;
		}

		/**
		 * Set the file upload support status.
		 *
		 * @param boolean $fileUploadSupport The file upload support status.
		 * @return BaseFacebook
		 */
		public function setFileUploadSupport( $fileUploadSupport )
		{
				$this->fileUploadSupport = $fileUploadSupport;
				return $this;
		}

		/**
		 * Get the file upload support status.
		 *
		 * @return boolean true if and only if the server supports file upload.
		 */
		public function useFileUploadSupport()
		{
				return $this->fileUploadSupport;
		}

		/**
		 * Sets the access token for api calls.  Use this if you get
		 * your access token by other means and just want the SDK
		 * to use it.
		 *
		 * @param string $access_token an access token.
		 * @return BaseFacebook
		 */
		public function setAccessToken( $access_token )
		{
				$this->accessToken = $access_token;
				return $this;
		}

		/**
		 * Determines the access token that should be used for API calls.
		 * The first time this is called, $this->accessToken is set equal
		 * to either a valid user access token, or it's set to the application
		 * access token if a valid user access token wasn't available.  Subsequent
		 * calls return whatever the first call returned.
		 *
		 * @return string The access token
		 */
		public function getAccessToken()
		{
				if( $this->accessToken !== null )
				{
						// we've done this already and cached it.  Just return.
						return $this->accessToken;
				}

				// first establish access token to be the application
				// access token, in case we navigate to the /oauth/access_token
				// endpoint, where SOME access token is required.
				$this->setAccessToken( $this->getApplicationAccessToken() );
				$user_access_token = $this->getUserAccessToken();
				if( $user_access_token )
				{
						$this->setAccessToken( $user_access_token );
				}

				return $this->accessToken;
		}

		/**
		 * Determines and returns the user access token, first using
		 * the signed request if present, and then falling back on
		 * the authorization code if present.  The intent is to
		 * return a valid user access token, or false if one is determined
		 * to not be available.
		 *
		 * @return string A valid user access token, or false if one
		 *                could not be determined.
		 */
		protected function getUserAccessToken()
		{
				// first, consider a signed request if it's supplied.
				// if there is a signed request, then it alone determines
				// the access token.
				$signed_request = $this->getSignedRequest();
				if( $signed_request )
				{
						// apps.facebook.com hands the access_token in the signed_request
						if( array_key_exists( 'oauth_token', $signed_request ) )
						{
								$access_token = $signed_request['oauth_token'];
								$this->setPersistentData( 'access_token', $access_token );
								return $access_token;
						}

						// the JS SDK puts a code in with the redirect_uri of ''
						if( array_key_exists( 'code', $signed_request ) )
						{
								$code = $signed_request['code'];
								$access_token = $this->getAccessTokenFromCode( $code, '' );
								if( $access_token )
								{
										$this->setPersistentData( 'code', $code );
										$this->setPersistentData( 'access_token', $access_token );
										return $access_token;
								}
						}

						// signed request states there's no access token, so anything
						// stored should be cleared.
						$this->clearAllPersistentData();
						return false; // respect the signed request's data, even
						// if there's an authorization code or something else
				}

				$code = $this->getCode();
				if( $code && $code != $this->getPersistentData( 'code' ) )
				{
						$access_token = $this->getAccessTokenFromCode( $code );
						if( $access_token )
						{
								$this->setPersistentData( 'code', $code );
								$this->setPersistentData( 'access_token', $access_token );
								return $access_token;
						}

						// code was bogus, so everything based on it should be invalidated.
						$this->clearAllPersistentData();
						return false;
				}

				// as a fallback, just return whatever is in the persistent
				// store, knowing nothing explicit (signed request, authorization
				// code, etc.) was present to shadow it (or we saw a code in $_REQUEST,
				// but it's the same as what's in the persistent store)
				return $this->getPersistentData( 'access_token' );
		}

		/**
		 * Retrieve the signed request, either from a request parameter or,
		 * if not present, from a cookie.
		 *
		 * @return string the signed request, if available, or null otherwise.
		 */
		public function getSignedRequest()
		{
				if( !$this->signedRequest )
				{
						if( isset( $_REQUEST['signed_request'] ) )
						{
								$this->signedRequest = $this->parseSignedRequest(
												$_REQUEST['signed_request'] );
						}
						else if( isset( $_COOKIE[$this->getSignedRequestCookieName()] ) )
						{
								$this->signedRequest = $this->parseSignedRequest(
												$_COOKIE[$this->getSignedRequestCookieName()] );
						}
				}
				return $this->signedRequest;
		}

		/**
		 * Get the UID of the connected user, or 0
		 * if the Facebook user is not connected.
		 *
		 * @return string the UID if available.
		 */
		public function getUser()
		{
				if( $this->user !== null )
				{
						// we've already determined this and cached the value.
						return $this->user;
				}

				return $this->user = $this->getUserFromAvailableData();
		}

		/**
		 * Determines the connected user by first examining any signed
		 * requests, then considering an authorization code, and then
		 * falling back to any persistent store storing the user.
		 *
		 * @return integer The id of the connected Facebook user,
		 *                 or 0 if no such user exists.
		 */
		protected function getUserFromAvailableData()
		{
				// if a signed request is supplied, then it solely determines
				// who the user is.
				$signed_request = $this->getSignedRequest();
				if( $signed_request )
				{
						if( array_key_exists( 'user_id', $signed_request ) )
						{
								$user = $signed_request['user_id'];
								$this->setPersistentData( 'user_id', $signed_request['user_id'] );
								return $user;
						}

						// if the signed request didn't present a user id, then invalidate
						// all entries in any persistent store.
						$this->clearAllPersistentData();
						return 0;
				}

				$user = $this->getPersistentData( 'user_id', $default = 0 );
				$persisted_access_token = $this->getPersistentData( 'access_token' );

				// use access_token to fetch user id if we have a user access_token, or if
				// the cached access token has changed.
				$access_token = $this->getAccessToken();
				if( $access_token &&
								$access_token != $this->getApplicationAccessToken() &&
								!($user && $persisted_access_token == $access_token) )
				{
						$user = $this->getUserFromAccessToken();
						if( $user )
						{
								$this->setPersistentData( 'user_id', $user );
						}
						else
						{
								$this->clearAllPersistentData();
						}
				}

				return $user;
		}

		/**
		 * Get a Login URL for use with redirects. By default, full page redirect is
		 * assumed. If you are using the generated URL with a window.open() call in
		 * JavaScript, you can pass in display=popup as part of the $params.
		 *
		 * The parameters:
		 * - redirect_uri: the url to go to after a successful login
		 * - scope: comma separated list of requested extended perms
		 *
		 * @param array $params Provide custom parameters
		 * @return string The URL for the login flow
		 */
		public function getLoginUrl( $params=array( ) )
		{
				$this->establishCSRFTokenState();
				$currentUrl = $this->getCurrentUrl();

				// if 'scope' is passed as an array, convert to comma separated list
				$scopeParams = isset( $params['scope'] ) ? $params['scope'] : null;
				if( $scopeParams && is_array( $scopeParams ) )
				{
						$params['scope'] = implode( ',', $scopeParams );
				}

				return $this->getUrl(
												'www', 'dialog/oauth', array_merge( array(
														'client_id' => $this->getAppId(),
														'redirect_uri' => $currentUrl, // possibly overwritten
														'state' => $this->state ), $params ) );
		}

		/**
		 * Get a Logout URL suitable for use with redirects.
		 *
		 * The parameters:
		 * - next: the url to go to after a successful logout
		 *
		 * @param array $params Provide custom parameters
		 * @return string The URL for the logout flow
		 */
		public function getLogoutUrl( $params=array( ) )
		{
				return $this->getUrl(
												'www', 'logout.php', array_merge( array(
														'next' => $this->getCurrentUrl(),
														'access_token' => $this->getAccessToken(),
																), $params )
				);
		}

		/**
		 * Get a login status URL to fetch the status from Facebook.
		 *
		 * The parameters:
		 * - ok_session: the URL to go to if a session is found
		 * - no_session: the URL to go to if the user is not connected
		 * - no_user: the URL to go to if the user is not signed into facebook
		 *
		 * @param array $params Provide custom parameters
		 * @return string The URL for the logout flow
		 */
		public function getLoginStatusUrl( $params=array( ) )
		{
				return $this->getUrl(
												'www', 'extern/login_status.php', array_merge( array(
														'api_key' => $this->getAppId(),
														'no_session' => $this->getCurrentUrl(),
														'no_user' => $this->getCurrentUrl(),
														'ok_session' => $this->getCurrentUrl(),
														'session_version' => 3,
																), $params )
				);
		}

		/**
		 * Make an API call.
		 *
		 * @return mixed The decoded response
		 */
		public function api( /* polymorphic */ )
		{
				$args = func_get_args();
				if( is_array( $args[0] ) )
				{
						return $this->_restserver( $args[0] );
				}
				else
				{
						return call_user_func_array( array( $this, '_graph' ), $args );
				}
		}

		/**
		 * Constructs and returns the name of the cookie that
		 * potentially houses the signed request for the app user.
		 * The cookie is not set by the BaseFacebook class, but
		 * it may be set by the JavaScript SDK.
		 *
		 * @return string the name of the cookie that would house
		 *         the signed request value.
		 */
		protected function getSignedRequestCookieName()
		{
				return 'fbsr_'.$this->getAppId();
		}

		/**
		 * Get the authorization code from the query parameters, if it exists,
		 * and otherwise return false to signal no authorization code was
		 * discoverable.
		 *
		 * @return mixed The authorization code, or false if the authorization
		 *               code could not be determined.
		 */
		protected function getCode()
		{
				if( isset( $_REQUEST['code'] ) )
				{
						if( $this->state !== null &&
										isset( $_REQUEST['state'] ) &&
										$this->state === $_REQUEST['state'] )
						{

								// CSRF state has done its job, so clear it
								$this->state = null;
								$this->clearPersistentData( 'state' );
								return $_REQUEST['code'];
						}
						else
						{
								self::errorLog( 'CSRF state token does not match one provided.' );
								return false;
						}
				}

				return false;
		}

		/**
		 * Retrieves the UID with the understanding that
		 * $this->accessToken has already been set and is
		 * seemingly legitimate.  It relies on Facebook's Graph API
		 * to retrieve user information and then extract
		 * the user ID.
		 *
		 * @return integer Returns the UID of the Facebook user, or 0
		 *                 if the Facebook user could not be determined.
		 */
		protected function getUserFromAccessToken()
		{
				try
				{
						$user_info = $this->api( '/me' );
						return $user_info['id'];
				}
				catch( FacebookApiException $e )
				{
						return 0;
				}
		}

		/**
		 * Returns the access token that should be used for logged out
		 * users when no authorization code is available.
		 *
		 * @return string The application access token, useful for gathering
		 *                public information about users and applications.
		 */
		protected function getApplicationAccessToken()
		{
				return $this->appId.'|'.$this->apiSecret;
		}

		/**
		 * Lays down a CSRF state token for this process.
		 *
		 * @return void
		 */
		protected function establishCSRFTokenState()
		{
				if( $this->state === null )
				{
						$this->state = md5( uniqid( mt_rand(), true ) );
						$this->setPersistentData( 'state', $this->state );
				}
		}

		/**
		 * Retrieves an access token for the given authorization code
		 * (previously generated from www.facebook.com on behalf of
		 * a specific user).  The authorization code is sent to graph.facebook.com
		 * and a legitimate access token is generated provided the access token
		 * and the user for which it was generated all match, and the user is
		 * either logged in to Facebook or has granted an offline access permission.
		 *
		 * @param string $code An authorization code.
		 * @return mixed An access token exchanged for the authorization code, or
		 *               false if an access token could not be generated.
		 */
		protected function getAccessTokenFromCode( $code, $redirect_uri = null )
		{
				if( empty( $code ) )
				{
						return false;
				}

				if( $redirect_uri === null )
				{
						$redirect_uri = $this->getCurrentUrl();
				}

				try
				{
						// need to circumvent json_decode by calling _oauthRequest
						// directly, since response isn't JSON format.
						$access_token_response =
										$this->_oauthRequest(
										$this->getUrl( 'graph', '/oauth/access_token' ), $params = array( 'client_id' => $this->getAppId(),
								'client_secret' => $this->getApiSecret(),
								'redirect_uri' => $redirect_uri,
								'code' => $code ) );
				}
				catch( FacebookApiException $e )
				{
						// most likely that user very recently revoked authorization.
						// In any event, we don't have an access token, so say so.
						return false;
				}

				if( empty( $access_token_response ) )
				{
						return false;
				}

				$response_params = array( );
				parse_str( $access_token_response, $response_params );
				if( !isset( $response_params['access_token'] ) )
				{
						return false;
				}

				return $response_params['access_token'];
		}

		/**
		 * Invoke the old restserver.php endpoint.
		 *
		 * @param array $params Method call object
		 *
		 * @return mixed The decoded response object
		 * @throws FacebookApiException
		 */
		protected function _restserver( $params )
		{
				// generic application level parameters
				$params['api_key'] = $this->getAppId();
				$params['format'] = 'json-strings';

				$result = json_decode( $this->_oauthRequest(
												$this->getApiUrl( $params['method'] ), $params
								), true );

				// results are returned, errors are thrown
				if( is_array( $result ) && isset( $result['error_code'] ) )
				{
						$this->throwAPIException( $result );
				}

				if( $params['method'] === 'auth.expireSession' ||
								$params['method'] === 'auth.revokeAuthorization' )
				{
						$this->destroySession();
				}

				return $result;
		}

		/**
		 * Invoke the Graph API.
		 *
		 * @param string $path The path (required)
		 * @param string $method The http method (default 'GET')
		 * @param array $params The query/post data
		 *
		 * @return mixed The decoded response object
		 * @throws FacebookApiException
		 */
		protected function _graph( $path, $method = 'GET', $params = array( ) )
		{
				if( is_array( $method ) && empty( $params ) )
				{
						$params = $method;
						$method = 'GET';
				}
				$params['method'] = $method; // method override as we always do a POST

				$result = json_decode( $this->_oauthRequest(
												$this->getUrl( 'graph', $path ), $params
								), true );

				// results are returned, errors are thrown
				if( is_array( $result ) && isset( $result['error'] ) )
				{
						$this->throwAPIException( $result );
				}

				return $result;
		}

		/**
		 * Make a OAuth Request.
		 *
		 * @param string $url The path (required)
		 * @param array $params The query/post data
		 *
		 * @return string The decoded response object
		 * @throws FacebookApiException
		 */
		protected function _oauthRequest( $url, $params )
		{
				if( !isset( $params['access_token'] ) )
				{
						$params['access_token'] = $this->getAccessToken();
				}

				// json_encode all params values that are not strings
				foreach( $params as $key => $value )
				{
						if( !is_string( $value ) )
						{
								$params[$key] = json_encode( $value );
						}
				}

				return $this->makeRequest( $url, $params );
		}

		/**
		 * Makes an HTTP request. This method can be overridden by subclasses if
		 * developers want to do fancier things or use something other than curl to
		 * make the request.
		 *
		 * @param string $url The URL to make the request to
		 * @param array $params The parameters to use for the POST body
		 * @param CurlHandler $ch Initialized curl handle
		 *
		 * @return string The response text
		 */
		protected function makeRequest( $url, $params, $ch=null )
		{
				if( !$ch )
				{
						$ch = curl_init();
				}

				$opts = self::$CURL_OPTS;
				if( $this->useFileUploadSupport() )
				{
						$opts[CURLOPT_POSTFIELDS] = $params;
				}
				else
				{
						$opts[CURLOPT_POSTFIELDS] = http_build_query( $params, null, '&' );
				}
				$opts[CURLOPT_URL] = $url;

				// disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
				// for 2 seconds if the server does not support this header.
				if( isset( $opts[CURLOPT_HTTPHEADER] ) )
				{
						$existing_headers = $opts[CURLOPT_HTTPHEADER];
						$existing_headers[] = 'Expect:';
						$opts[CURLOPT_HTTPHEADER] = $existing_headers;
				}
				else
				{
						$opts[CURLOPT_HTTPHEADER] = array( 'Expect:' );
				}

				curl_setopt_array( $ch, $opts );
				$result = curl_exec( $ch );

				if( curl_errno( $ch ) == 60 )
				{ // CURLE_SSL_CACERT
						self::errorLog( 'Invalid or no certificate authority found, '.
										'using bundled information' );
						curl_setopt( $ch, CURLOPT_CAINFO, dirname( __FILE__ ).'/fb_ca_chain_bundle.crt' );
						$result = curl_exec( $ch );
				}

				if( $result === false )
				{
						$e = new FacebookApiException( array(
												'error_code' => curl_errno( $ch ),
												'error' => array(
														'message' => curl_error( $ch ),
														'type' => 'CurlException',
												),
										) );
						curl_close( $ch );
						throw $e;
				}
				curl_close( $ch );
				return $result;
		}

		/**
		 * Parses a signed_request and validates the signature.
		 *
		 * @param string $signed_request A signed token
		 * @return array The payload inside it or null if the sig is wrong
		 */
		protected function parseSignedRequest( $signed_request )
		{
				list($encoded_sig, $payload) = explode( '.', $signed_request, 2 );

				// decode the data
				$sig = self::base64UrlDecode( $encoded_sig );
				$data = json_decode( self::base64UrlDecode( $payload ), true );

				if( strtoupper( $data['algorithm'] ) !== 'HMAC-SHA256' )
				{
						self::errorLog( 'Unknown algorithm. Expected HMAC-SHA256' );
						return null;
				}

				// check sig
				$expected_sig = hash_hmac( 'sha256', $payload, $this->getApiSecret(), $raw = true );
				if( $sig !== $expected_sig )
				{
						self::errorLog( 'Bad Signed JSON signature!' );
						return null;
				}

				return $data;
		}

		/**
		 * Build the URL for api given parameters.
		 *
		 * @param $method String the method name.
		 * @return string The URL for the given parameters
		 */
		protected function getApiUrl( $method )
		{
				static $READ_ONLY_CALLS =
				array( 'admin.getallocation' => 1,
						'admin.getappproperties' => 1,
						'admin.getbannedusers' => 1,
						'admin.getlivestreamvialink' => 1,
						'admin.getmetrics' => 1,
						'admin.getrestrictioninfo' => 1,
						'application.getpublicinfo' => 1,
						'auth.getapppublickey' => 1,
						'auth.getsession' => 1,
						'auth.getsignedpublicsessiondata' => 1,
						'comments.get' => 1,
						'connect.getunconnectedfriendscount' => 1,
						'dashboard.getactivity' => 1,
						'dashboard.getcount' => 1,
						'dashboard.getglobalnews' => 1,
						'dashboard.getnews' => 1,
						'dashboard.multigetcount' => 1,
						'dashboard.multigetnews' => 1,
						'data.getcookies' => 1,
						'events.get' => 1,
						'events.getmembers' => 1,
						'fbml.getcustomtags' => 1,
						'feed.getappfriendstories' => 1,
						'feed.getregisteredtemplatebundlebyid' => 1,
						'feed.getregisteredtemplatebundles' => 1,
						'fql.multiquery' => 1,
						'fql.query' => 1,
						'friends.arefriends' => 1,
						'friends.get' => 1,
						'friends.getappusers' => 1,
						'friends.getlists' => 1,
						'friends.getmutualfriends' => 1,
						'gifts.get' => 1,
						'groups.get' => 1,
						'groups.getmembers' => 1,
						'intl.gettranslations' => 1,
						'links.get' => 1,
						'notes.get' => 1,
						'notifications.get' => 1,
						'pages.getinfo' => 1,
						'pages.isadmin' => 1,
						'pages.isappadded' => 1,
						'pages.isfan' => 1,
						'permissions.checkavailableapiaccess' => 1,
						'permissions.checkgrantedapiaccess' => 1,
						'photos.get' => 1,
						'photos.getalbums' => 1,
						'photos.gettags' => 1,
						'profile.getinfo' => 1,
						'profile.getinfooptions' => 1,
						'stream.get' => 1,
						'stream.getcomments' => 1,
						'stream.getfilters' => 1,
						'users.getinfo' => 1,
						'users.getloggedinuser' => 1,
						'users.getstandardinfo' => 1,
						'users.hasapppermission' => 1,
						'users.isappuser' => 1,
						'users.isverified' => 1,
						'video.getuploadlimits' => 1 );
				$name = 'api';
				if( isset( $READ_ONLY_CALLS[strtolower( $method )] ) )
				{
						$name = 'api_read';
				}
				else if( strtolower( $method ) == 'video.upload' )
				{
						$name = 'api_video';
				}
				return self::getUrl( $name, 'restserver.php' );
		}

		/**
		 * Build the URL for given domain alias, path and parameters.
		 *
		 * @param $name string The name of the domain
		 * @param $path string Optional path (without a leading slash)
		 * @param $params array Optional query parameters
		 *
		 * @return string The URL for the given parameters
		 */
		protected function getUrl( $name, $path='', $params=array( ) )
		{
				$url = self::$DOMAIN_MAP[$name];
				if( $path )
				{
						if( $path[0] === '/' )
						{
								$path = substr( $path, 1 );
						}
						$url .= $path;
				}
				if( $params )
				{
						$url .= '?'.http_build_query( $params, null, '&' );
				}

				return $url;
		}

		/**
		 * Returns the Current URL, stripping it of known FB parameters that should
		 * not persist.
		 *
		 * @return string The current URL
		 */
		protected function getCurrentUrl()
		{
				if( isset( $_SERVER['HTTPS'] ) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1)
								|| isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'
				)
				{
						$protocol = 'https://';
				}
				else
				{
						$protocol = 'http://';
				}
				$currentUrl = $protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
				$parts = parse_url( $currentUrl );

				$query = '';
				if( !empty( $parts['query'] ) )
				{
						// drop known fb params
						$params = explode( '&', $parts['query'] );
						$retained_params = array( );
						foreach( $params as $param )
						{
								if( $this->shouldRetainParam( $param ) )
								{
										$retained_params[] = $param;
								}
						}

						if( !empty( $retained_params ) )
						{
								$query = '?'.implode( $retained_params, '&' );
						}
				}

				// use port if non default
				$port =
								isset( $parts['port'] ) &&
								(($protocol === 'http://' && $parts['port'] !== 80) ||
								($protocol === 'https://' && $parts['port'] !== 443)) ? ':'.$parts['port'] : '';

				// rebuild
				return $protocol.$parts['host'].$port.$parts['path'].$query;
		}

		/**
		 * Returns true if and only if the key or key/value pair should
		 * be retained as part of the query string.  This amounts to
		 * a brute-force search of the very small list of Facebook-specific
		 * params that should be stripped out.
		 *
		 * @param string $param A key or key/value pair within a URL's query (e.g.
		 *                     'foo=a', 'foo=', or 'foo'.
		 *
		 * @return boolean
		 */
		protected function shouldRetainParam( $param )
		{
				foreach( self::$DROP_QUERY_PARAMS as $drop_query_param )
				{
						if( strpos( $param, $drop_query_param.'=' ) === 0 )
						{
								return false;
						}
				}

				return true;
		}

		/**
		 * Analyzes the supplied result to see if it was thrown
		 * because the access token is no longer valid.  If that is
		 * the case, then the persistent store is cleared.
		 *
		 * @param $result array A record storing the error message returned
		 *                      by a failed API call.
		 */
		protected function throwAPIException( $result )
		{
				$e = new FacebookApiException( $result );
				switch( $e->getType() )
				{
						// OAuth 2.0 Draft 00 style
						case 'OAuthException':
						// OAuth 2.0 Draft 10 style
						case 'invalid_token':
						// REST server errors are just Exceptions
						case 'Exception':
								$message = $e->getMessage();
								if( (strpos( $message, 'Error validating access token' ) !== false) ||
												(strpos( $message, 'Invalid OAuth access token' ) !== false) )
								{
										$this->setAccessToken( null );
										$this->user = 0;
										$this->clearAllPersistentData();
								}
				}

				throw $e;
		}

		/**
		 * Prints to the error log if you aren't in command line mode.
		 *
		 * @param string $msg Log message
		 */
		protected static function errorLog( $msg )
		{
				// disable error log if we are running in a CLI environment
				// @codeCoverageIgnoreStart
				if( php_sapi_name() != 'cli' )
				{
						error_log( $msg );
				}
				// uncomment this if you want to see the errors on the page
				// print 'error_log: '.$msg."\n";
				// @codeCoverageIgnoreEnd
		}

		/**
		 * Base64 encoding that doesn't need to be urlencode()ed.
		 * Exactly the same as base64_encode except it uses
		 *   - instead of +
		 *   _ instead of /
		 *
		 * @param string $input base64UrlEncoded string
		 * @return string
		 */
		protected static function base64UrlDecode( $input )
		{
				return base64_decode( strtr( $input, '-_', '+/' ) );
		}

		/**
		 * Destroy the current session
		 */
		public function destroySession()
		{
				$this->setAccessToken( null );
				$this->user = 0;
				$this->clearAllPersistentData();
		}

		/**
		 * Each of the following four methods should be overridden in
		 * a concrete subclass, as they are in the provided Facebook class.
		 * The Facebook class uses PHP sessions to provide a primitive
		 * persistent store, but another subclass--one that you implement--
		 * might use a database, memcache, or an in-memory cache.
		 *
		 * @see Facebook
		 */

		/**
		 * Stores the given ($key, $value) pair, so that future calls to
		 * getPersistentData($key) return $value. This call may be in another request.
		 *
		 * @param string $key
		 * @param array $value
		 *
		 * @return void
		 */
		abstract protected function setPersistentData( $key, $value );

		/**
		 * Get the data for $key, persisted by BaseFacebook::setPersistentData()
		 *
		 * @param string $key The key of the data to retrieve
		 * @param boolean $default The default value to return if $key is not found
		 *
		 * @return mixed
		 */
		abstract protected function getPersistentData( $key, $default = false );

		/**
		 * Clear the data with $key from the persistent storage
		 *
		 * @param string $key
		 * @return void
		 */
		abstract protected function clearPersistentData( $key );

		/**
		 * Clear all data from the persistent storage
		 *
		 * @return void
		 */
		abstract protected function clearAllPersistentData();
}


text:
import is from 'is_js'

import Client from './client'
import NodeManager from './managers/nodeManager'
import VirtualMachineManager from './managers/virtualMachineManager'
import ApplicationTemplates from './applicationTemplates'
import Credentials from './credentials'

/* eslint-disable */
if (!global._babelPolyfill) {
  require('babel-polyfill')
}
/* eslint-disable */

const SOLARWINDS_USERNAME = process.env.SOLARWINDS_USERNAME
const SOLARWINDS_PASSWORD = process.env.SOLARWINDS_PASSWORD
const SOLARWINDS_HOSTNAME = process.env.SOLARWINDS_HOSTNAME
const SOLARWINDS_PORT = process.env.SOLARWINDS_PORT || 17778

class Landscape {
  constructor(
    username = SOLARWINDS_USERNAME, password = SOLARWINDS_PASSWORD,
    hostname = SOLARWINDS_HOSTNAME, port = SOLARWINDS_PORT
  ) {
    if (is.undefined(username) || is.empty(username)) throw new Error('Provide username for SolarWinds or env variable SOLARWINDS_USERNAME')
    if (is.undefined(password) || is.empty(password)) throw new Error('Provide password for SolarWinds or env variable SOLARWINDS_PASSWORD')
    if (is.undefined(hostname) || is.empty(hostname)) throw new Error('Provide hostname of SolarWinds API or env variable SOLARWINDS_HOSTNAME')
    if (is.undefined(port) || is.empty(port)) throw new Error('Provide port of SolarWinds API or env variable SOLARWINDS_PORT')

    this.client = new Client(username, password, hostname, port)

    this.nodes = new NodeManager(this.client)
    this.virtualMachines = new VirtualMachineManager(this.client)
    this.applicationTemplates = new ApplicationTemplates(this.client)
    this.credentials = new Credentials(this.client)
  }
}

export default Landscape

redpajama_set_name: RedPajamaGithub


text:
ASIGNACIÓN ACADÉMICA

	<form action="#" class="form-inline">

			Horario del Docente:
			<select id="profesor" name="profesor" class="form-control">
			  	<?php foreach ($profesores as $p) { ?>
                    <option value="<?php echo $p->pro_id;?>"><?php echo $p->pro_paterno.' '.$p->pro_materno.' '.$p->pro_nombre;?></option>
                <?php } ?>
			</select>

	</form>

			Hora
			Lunes
			Martes
			Miércoles
			Jueves
			Viernes

			08:00
09:00

4-A
MAT

<button class="btn btn-default">Editar</button>

3-A
FIS

<button class="btn btn-default">Editar</button>

4-B
MAT

<button class="btn btn-default">Editar</button>

<button class="btn btn-default">Editar</button>

<button class="btn btn-default">Editar</button>

			09:00
10:00

<button class="btn btn-default">Editar</button>

3-B
MAT

<button class="btn btn-default">Editar</button>

4-B
FIS

<button class="btn btn-default">Editar</button>

<button class="btn btn-default">Editar</button>

5-A
MAT

<button class="btn btn-default">Editar</button>

			10:00
11:00

4-B
MAT

<button class="btn btn-default">Editar</button>

<button class="btn btn-default">Editar</button>

4-B
MAT

<button class="btn btn-default">Editar</button>

<button class="btn btn-default">Editar</button>

4-B
MAT

<button class="btn btn-default">Editar</button>

			11:00
12:00

4-B
MAT

<button class="btn btn-default">Editar</button>

<button class="btn btn-default">Editar</button>

<button class="btn btn-default">Editar</button>

<button class="btn btn-default">Editar</button>

4-B
MAT

<button class="btn btn-default">Editar</button>


text:
class SessionController < ApplicationController

  def new
    @user = User.new
  end

  def create
    @user = User.find_by(email: user_params[:email])
    if @user.password == params[:password]
      session[:user_id] = @user.id
      redirect_to root_path
    else
      @messages = ["invalid username or password"]
      redirect_to root_path
    end
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_path
  end

  private

  def user_params
    params.require(:user).permit(:email, :password)
  end
end


text:
import styled from "@emotion/styled"
import React, { FunctionComponent, useEffect, useRef, useState } from "react"
import ReactDOM from "react-dom"
import { useWindowMousePosition } from "../hooks/useWindowMousePosition"
import { useWindowSize } from "../hooks/useWindowSize"

export const TooltipContent = styled.div`
  background: hsla(0, 0%, 0%, 0.75);
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0.5em 1em;
  text-align: center;
`
const Div = styled.div`
  position: absolute;
  pointer-events: none;
  & > * {
    pointer-events: none;
  }
`
// check this in case https://www.joshwcomeau.com/react/the-perils-of-rehydration/
export const DialogPortal: FunctionComponent = ({ children }) => {
  if (typeof window === `undefined`) return null
  const element = document.getElementById("dialog-portal")
  if (!element) return null
  return ReactDOM.createPortal(children, element)
}

export const TooltipPortal: FunctionComponent = ({ children }) => {
  if (typeof window === `undefined`) return null
  const element = document.getElementById("tooltip-portal")
  if (!element) return null
  return ReactDOM.createPortal(children, element)
}

export const MouseToolTip: FunctionComponent = ({ children }) => {
  const { pageX, pageY, clientY, clientX } = useWindowMousePosition()
  const { windowWidth } = useWindowSize()
  const ref = useRef<HTMLDivElement>(null)
  const [width, setWidth] = useState(150) // random width
  const [height, setHeight] = useState(40) // random height

  useEffect(() => {
    setWidth(ref.current?.getBoundingClientRect().width ?? 150)
    setHeight(ref.current?.getBoundingClientRect().height ?? 40)
  }, [children])

  // this is use in combination with tooltip content.
  // we try to find how many elements in the tooltip content so that ew change the
  // offset accordingly (for instance in transport in vietnam page, multiple elements are provided
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  const childrenLength = React.Children.count(children?.props?.children)
  const offset = clientY > 80 ? -30 - 20 * childrenLength : 30
  const offsetLeft = windowWidth - clientX < 130
  const offsetRight = clientX < 130
  return (
    <TooltipPortal>
      <Div
        ref={ref}
        style={{
          ...(offsetLeft
            ? {
                left: `${pageX - width - 30}px`,
                top: `${pageY - height / 2}px`,
              }
            : offsetRight
            ? {
                left: `${pageX + 15}px`,
                top: `${pageY - height / 2}px`,
              }
            : { left: `${pageX - width / 2}px`, top: `${pageY + offset}px` }),
        }}
      >
        {children}
      </Div>
    </TooltipPortal>
  )
}


text:
import {RefCounted} from 'neuroglancer/util/disposable';
import {Memoize} from 'neuroglancer/util/memoize';

export interface GL extends WebGLRenderingContext {
  memoize: Memoize<any, RefCounted>;
  WEBGL_draw_buffers: any;
  maxTextureSize: number;
  maxTextureImageUnits: number;
  tempTextureUnit: number;
}

export const DEBUG_SHADERS = false;

export function initializeWebGL(canvas: HTMLCanvasElement) {
  let options: any = {
    'antialias': false,
    'stencil': true,
  };
  if (DEBUG_SHADERS) {
    console.log('DEBUGGING via preserveDrawingBuffer');
    options['preserveDrawingBuffer'] = true;
  }
  let gl =
      <GL>(canvas.getContext('webgl', options) || canvas.getContext('experimental-webgl', options));
  gl.memoize = new Memoize<any, RefCounted>();
  gl.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  gl.maxTextureImageUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  gl.tempTextureUnit = gl.maxTextureImageUnits - 1;

  // FIXME: verify that we received a stencil buffer
  // var contextAttributes = gl.getContextAttributes();
  // var haveStencilBuffer = contextAttributes.stencil;

  gl.WEBGL_draw_buffers = gl.getExtension('WEBGL_draw_buffers');
  if (!gl.WEBGL_draw_buffers) {
    throw new Error('WEBGL_draw_buffers extension not available');
  }

  for (let extension of ['OES_texture_float', 'OES_element_index_uint']) {
    if (!gl.getExtension(extension)) {
      throw new Error(`${extension} extension not available`);
    }
  }

  return gl;
}


text:
package java.security.cert;

import java.util.Iterator;
import java.util.Set;

/**
 * An immutable valid policy tree node as defined by the PKIX certification
 * path validation algorithm.
 *
 *
One of the outputs of the PKIX certification path validation
 * algorithm is a valid policy tree, which includes the policies that
 * were determined to be valid, how this determination was reached,
 * and any policy qualifiers encountered. This tree is of depth
 * n, where n is the length of the certification
 * path that has been validated.
 *
 *
Most applications will not need to examine the valid policy tree.
 * They can achieve their policy processing goals by setting the
 * policy-related parameters in {@code PKIXParameters}. However,
 * the valid policy tree is available for more sophisticated applications,
 * especially those that process policy qualifiers.
 *
 *
{@link PKIXCertPathValidatorResult#getPolicyTree()
 * PKIXCertPathValidatorResult.getPolicyTree} returns the root node of the
 * valid policy tree. The tree can be traversed using the
 * {@link #getChildren getChildren} and {@link #getParent getParent} methods.
 * Data about a particular node can be retrieved using other methods of
 * {@code PolicyNode}.
 *
 *
Concurrent Access
 *
All {@code PolicyNode} objects must be immutable and
 * thread-safe. Multiple threads may concurrently invoke the methods defined
 * in this class on a single {@code PolicyNode} object (or more than one)
 * with no ill effects. This stipulation applies to all public fields and
 * methods of this class and any added or overridden by subclasses.
 *
 * @since       1.4
 * @author      Sean Mullan
 */
public interface PolicyNode {

    /**
     * Returns the parent of this node, or {@code null} if this is the
     * root node.
     *
     * @return the parent of this node, or {@code null} if this is the
     * root node
     */
    PolicyNode getParent();

    /**
     * Returns an iterator over the children of this node. Any attempts to
     * modify the children of this node through the
     * {@code Iterator}'s remove method must throw an
     * {@code UnsupportedOperationException}.
     *
     * @return an iterator over the children of this node
     */
    Iterator<? extends PolicyNode> getChildren();

    /**
     * Returns the depth of this node in the valid policy tree.
     *
     * @return the depth of this node (0 for the root node, 1 for its
     * children, and so on)
     */
    int getDepth();

    /**
     * Returns the valid policy represented by this node.
     *
     * @return the {@code String} OID of the valid policy
     * represented by this node. For the root node, this method always returns
     * the special anyPolicy OID: "2.5.29.32.0".
     */
    String getValidPolicy();

    /**
     * Returns the set of policy qualifiers associated with the
     * valid policy represented by this node.
     *
     * @return an immutable {@code Set} of
     * {@code PolicyQualifierInfo}s. For the root node, this
     * is always an empty {@code Set}.
     */
    Set<? extends PolicyQualifierInfo> getPolicyQualifiers();

    /**
     * Returns the set of expected policies that would satisfy this
     * node's valid policy in the next certificate to be processed.
     *
     * @return an immutable {@code Set} of expected policy
     * {@code String} OIDs. For the root node, this method
     * always returns a {@code Set} with one element, the
     * special anyPolicy OID: "2.5.29.32.0".
     */
    Set<String> getExpectedPolicies();

    /**
     * Returns the criticality indicator of the certificate policy extension
     * in the most recently processed certificate.
     *
     * @return {@code true} if extension marked critical,
     * {@code false} otherwise. For the root node, {@code false}
     * is always returned.
     */
    boolean isCritical();
}


text:
/**
 * EtsiTs103097ExtensionModule
 * {itu-t(0) identified-organization(4) etsi(0) itsDomain(5) wg5(5) secHeaders(103097) extension(2) version1(1)}
 */
package org.bouncycastle.oer.its.etsi103097.extension;

import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1Sequence;

/**
 * Ieee1609Dot2HeaderInfoContributedExtensions
 * IEEE1609DOT2-HEADERINFO-CONTRIBUTED-EXTENSION ::= {
 * {EtsiOriginatingHeaderInfoExtension IDENTIFIED BY etsiHeaderInfoContributorId},
 * ...
 * }
 */
public class EtsiOriginatingHeaderInfoExtension
    extends Extension
{
    public EtsiOriginatingHeaderInfoExtension(ExtId id, ASN1Encodable content)
    {
        super(id, content);
    }

    private EtsiOriginatingHeaderInfoExtension(ASN1Sequence sequence)
    {
        super(sequence);
    }

    public static EtsiOriginatingHeaderInfoExtension getInstance(Object o)
    {
        if (o instanceof EtsiOriginatingHeaderInfoExtension)
        {
            return (EtsiOriginatingHeaderInfoExtension)o;
        }

        if (o != null)
        {
            return new EtsiOriginatingHeaderInfoExtension(ASN1Sequence.getInstance(o));
        }

        return null;
    }

    public EtsiTs102941CrlRequest getEtsiTs102941CrlRequest()
    {
        return EtsiTs102941CrlRequest.getInstance(getContent());
    }

    public EtsiTs102941DeltaCtlRequest getEtsiTs102941DeltaCtlRequest()
    {
        return EtsiTs102941DeltaCtlRequest.getInstance(getContent());
    }

    public static Builder builder()
    {
        return new Builder();
    }

    public static class Builder
    {
        private ExtId id;
        private ASN1Encodable encodable;

        public Builder setId(ExtId id)
        {
            this.id = id;
            return this;
        }

        public Builder setEncodable(ASN1Encodable encodable)
        {
            this.encodable = encodable;
            return this;
        }

        public Builder setEtsiTs102941CrlRequest(EtsiTs102941CrlRequest value)
        {
            this.id = etsiTs102941CrlRequestId;
            this.encodable = value;
            return this;
        }

        public Builder setEtsiTs102941DeltaCtlRequest(EtsiTs102941DeltaCtlRequest value)
        {
            this.id = etsiTs102941DeltaCtlRequestId;
            this.encodable = value;
            return this;
        }

        public EtsiOriginatingHeaderInfoExtension createEtsiOriginatingHeaderInfoExtension()
        {
            return new EtsiOriginatingHeaderInfoExtension(id, encodable);
        }

    }

}


text:
{% extends "admin/base_site.html" %}
{% load i18n %}
{% load url from future %}

{# TODO note that meta refreshes are deprecated.. but is there a nice clean way to do this otherwise? #}
{% block extrahead %}
<meta http-equiv="refresh" content="5" />
{% endblock %}

{% block content %}
{% block description %}
    {% if report.description %}

{% trans "Description" %}

{{ report.description }}

    {% endif %}
{% endblock %}

{% trans "Please wait while your report is generated..." %}

{% endblock %}

{% block breadcrumbs %}

     {% trans "Home" %} ›
     {% trans "Reports" %} ›
     {{report.verbose_name}} ›
     {% if format %}
     {% trans "Report Result" %} ›
     {{format}}
     {% else %}
     {% trans "Report Result" %}
     {% endif %}

{% endblock %}


text:
<?php

namespace Fungio\GoogleMapBundle\Entity;

use Fungio\GoogleMap\Overlays\Rectangle as BaseRectangle;

/**
 * {@inheritdoc}
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class Rectangle extends BaseRectangle
{
}


text:
#ifndef cocosview_PanelSize_h
#define cocosview_PanelSize_h

#include "cocosview/cocosview.h"

NS_CCV_BEG
class PanelSize
{
	public:
		static const float TOOLPANEL_WIDTH;
		static const float PROPERTIESPANEL_WIDTH;
};
NS_CCV_END

#endif


text:
package org.ovirt.engine.core.bll;

import org.ovirt.engine.core.common.queries.VdcQueryParametersBase;
import org.ovirt.engine.core.dao.VmTemplateDao;

public class GetVmTemplateCountQuery<P extends VdcQueryParametersBase> extends QueriesCommandBase<P> {
    public GetVmTemplateCountQuery(P parameters) {
        super(parameters);
    }

    @Override
    protected void executeQueryCommand() {
        getQueryReturnValue().setReturnValue(getVmTemplateDao().getCount());
    }

    private VmTemplateDao getVmTemplateDao() {
        return getDbFacade().getVmTemplateDao();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee"
  xsi:schemaLocation="
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
     http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd"
  default-lazy-init="true">

  <bean id="logListener" class="com.bskyb.cg.environments.LogListener">
    <constructor-arg ref="logger"/>
    <props>
      <prop> <key="bindAddress">tcp://127.0.0.1:9999</prop>

    </props>
  </bean>
</beans>


text:
/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <stdint.h>
#include <time.h>
#include <debug.h>
#include <nuttx/arch.h>
#include <arch/board/board.h>

#include "nvic.h"
#include "clock/clock.h"
#include "up_internal.h"
#include "up_arch.h"

#include "chip.h"

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

/* The desired timer interrupt frequency is provided by the definition
 * CLK_TCK (see include/time.h).  CLK_TCK defines the desired number of
 * system clock ticks per second.  That value is a user configurable setting
 * that defaults to 100 (100 ticks per second = 10 MS interval).
 *
 * The timer counts at the rate SYSCLK_FREQUENCY as defined in the board.h
 * header file.
 */

#define SYSTICK_RELOAD ((SYSCLK_FREQUENCY / CLK_TCK) - 1)

/* The size of the reload field is 24 bits.  Verify taht the reload value
 * will fit in the reload register.
 */

#if SYSTICK_RELOAD > 0x00ffffff
#  error SYSTICK_RELOAD exceeds the range of the RELOAD register
#endif

/****************************************************************************
 * Private Types
 ****************************************************************************/

/****************************************************************************
 * Private Function Prototypes
 ****************************************************************************/

/****************************************************************************
 * Global Functions
 ****************************************************************************/

/****************************************************************************
 * Function:  up_timerisr
 *
 * Description:
 *   The timer ISR will perform a variety of services for various portions
 *   of the systems.
 *
 ****************************************************************************/

int up_timerisr(int irq, uint32_t *regs)
{
   /* Process timer interrupt */

   sched_process_timer();
   return 0;
}

/****************************************************************************
 * Function:  up_timer_initialize
 *
 * Description:
 *   This function is called during start-up to initialize
 *   the timer interrupt.
 *
 ****************************************************************************/

void up_timer_initialize(void)
{
  uint32_t regval;

  /* Set the SysTick interrupt to the default priority */

  regval = getreg32(NVIC_SYSH12_15_PRIORITY);
  regval &= ~NVIC_SYSH_PRIORITY_PR15_MASK;
  regval |= (NVIC_SYSH_PRIORITY_DEFAULT << NVIC_SYSH_PRIORITY_PR15_SHIFT);
  putreg32(regval, NVIC_SYSH12_15_PRIORITY);

  /* Configure SysTick to interrupt at the requested rate */

  putreg32(SYSTICK_RELOAD, NVIC_SYSTICK_RELOAD);

  /* Attach the timer interrupt vector */

  (void)irq_attach(TIVA_IRQ_SYSTICK, (xcpt_t)up_timerisr);

  /* Enable SysTick interrupts */

  putreg32((NVIC_SYSTICK_CTRL_CLKSOURCE|NVIC_SYSTICK_CTRL_TICKINT|NVIC_SYSTICK_CTRL_ENABLE), NVIC_SYSTICK_CTRL);

  /* And enable the timer interrupt */

  up_enable_irq(TIVA_IRQ_SYSTICK);
}


text:
package org.codehaus.griffon.runtime.logging.logback;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.spi.AppenderAttachable;
import org.slf4j.Marker;
import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MarkerIgnoringBase;
import org.slf4j.helpers.MessageFormatter;
import org.slf4j.spi.LocationAwareLogger;

import java.util.Iterator;

import static ch.qos.logback.classic.Level.*;
import static griffon.util.GriffonExceptionHandler.sanitize;

/**
 * A Logback adapter that produces cleaner, more informative stack traces. Based on org.slf4j.impl.GrailsLog4jLoggerAdapter.
 *
 * @author Graeme Rocher
 * @author Burt Beckwith
 */
public class LogbackLoggerAdapter extends MarkerIgnoringBase implements LocationAwareLogger, AppenderAttachable<ILoggingEvent> {

    private static final long serialVersionUID = 1;

    protected static final String FQCN = LogbackLoggerAdapter.class.getName();

    protected final Logger logbackLogger;

    public LogbackLoggerAdapter(Logger logger) {
        logbackLogger = logger;
        name = logger.getName();
    }

    // interface methods

    public boolean isTraceEnabled() {
        return logbackLogger.isTraceEnabled();
    }

    public void trace(String msg) {
        logMessage(TRACE, msg, null);
    }

    public void trace(String format, Object arg) {
        logMessageFormat(TRACE, format, arg);
    }

    public void trace(String format, Object arg1, Object arg2) {
        logMessageFormat(TRACE, format, arg1, arg2);
    }

    public void trace(String format, Object[] argArray) {
        logMessageFormat(TRACE, format, argArray);
    }

    public void trace(String msg, Throwable t) {
        logMessage(TRACE, msg, t);
    }

    public boolean isDebugEnabled() {
        return logbackLogger.isDebugEnabled();
    }

    public void debug(String msg) {
        logMessage(DEBUG, msg, null);
    }

    public void debug(String format, Object arg) {
        logMessageFormat(DEBUG, format, arg);
    }

    public void debug(String format, Object arg1, Object arg2) {
        logMessageFormat(DEBUG, format, arg1, arg2);
    }

    public void debug(String format, Object[] argArray) {
        logMessageFormat(DEBUG, format, argArray);
    }

    public void debug(String msg, Throwable t) {
        logMessage(DEBUG, msg, t);
    }

    public boolean isInfoEnabled() {
        return logbackLogger.isInfoEnabled();
    }

    public void info(String msg) {
        logMessage(INFO, msg, null);
    }

    public void info(String format, Object arg) {
        logMessageFormat(INFO, format, arg);
    }

    public void info(String format, Object arg1, Object arg2) {
        logMessageFormat(INFO, format, arg1, arg2);
    }

    public void info(String format, Object[] argArray) {
        logMessageFormat(INFO, format, argArray);
    }

    public void info(String msg, Throwable t) {
        logMessage(INFO, msg, t);
    }

    public boolean isWarnEnabled() {
        return logbackLogger.isEnabledFor(WARN);
    }

    public void warn(String msg) {
        logMessage(WARN, msg, null);
    }

    public void warn(String format, Object arg) {
        logMessageFormat(WARN, format, arg);
    }

    public void warn(String format, Object[] argArray) {
        logMessageFormat(WARN, format, argArray);
    }

    public void warn(String format, Object arg1, Object arg2) {
        logMessageFormat(WARN, format, arg1, arg2);
    }

    public void warn(String msg, Throwable t) {
        logMessage(WARN, msg, t);
    }

    public boolean isErrorEnabled() {
        return logbackLogger.isEnabledFor(ERROR);
    }

    public void error(String msg) {
        logMessage(ERROR, msg, null);
    }

    public void error(String format, Object arg) {
        logMessageFormat(ERROR, format, arg);
    }

    public void error(String format, Object arg1, Object arg2) {
        logMessageFormat(ERROR, format, arg1, arg2);
    }

    public void error(String format, Object[] argArray) {
        logMessageFormat(ERROR, format, argArray);
    }

    public void error(String msg, Throwable t) {
        logMessage(ERROR, msg, t);
    }

    public void addAppender(Appender<ILoggingEvent> newAppender) {
        logbackLogger.addAppender(newAppender);
    }

    public Iterator<Appender<ILoggingEvent>> iteratorForAppenders() {
        return logbackLogger.iteratorForAppenders();
    }

    public Appender<ILoggingEvent> getAppender(String appenderName) {
        return logbackLogger.getAppender(appenderName);
    }

    public boolean isAttached(Appender<ILoggingEvent> appender) {
        return logbackLogger.isAttached(appender);
    }

    public void detachAndStopAllAppenders() {
        logbackLogger.detachAndStopAllAppenders();
    }

    public boolean detachAppender(Appender<ILoggingEvent> appender) {
        return logbackLogger.detachAppender(appender);
    }

    public boolean detachAppender(String appenderName) {
        return logbackLogger.detachAppender(appenderName);
    }

    public void log(Marker marker, String fqcn, int levelInt, String message, Object[] argArray, Throwable t) {
        logbackLogger.log(marker, fqcn, levelInt, message, argArray, t);
    }

    // non-interface methods mirrored from real logger

    public boolean isEnabledFor(Level level) {
        return logbackLogger.isEnabledFor(level);
    }

    public Level getEffectiveLevel() {
        return logbackLogger.getEffectiveLevel();
    }

    public Level getLevel() {
        return logbackLogger.getLevel();
    }

    public void setLevel(Level level) {
        logbackLogger.setLevel(level);
    }

    public Iterator<Appender<ILoggingEvent>> getAllAppenders() {
        return iteratorForAppenders();
    }

    public boolean isAdditive() {
        return logbackLogger.isAdditive();
    }

    public void setAdditive(boolean additive) {
        logbackLogger.setAdditive(additive);
    }

    public Logger getNativeLogger() {
        return logbackLogger;
    }

    // private methods

    protected FormattingTuple getMessageFormat(final String format, final Object... args) {
        FormattingTuple ft = MessageFormatter.arrayFormat(format, args);
        cleanIfException(ft.getThrowable());
        return ft;
    }

    protected Throwable cleanIfException(final Throwable t) {
        if (t != null) {
            sanitize(t);
        }
        return t;
    }

    protected void logMessageFormat(final Level level, final String format, final Object... args) {
        if (logbackLogger.isEnabledFor(level)) {
            FormattingTuple ft = getMessageFormat(format, args);
            logbackLogger.log(null, FQCN, toLocationAwareInt(level), ft.getMessage(), args, ft.getThrowable());
        }
    }

    protected void logMessage(final Level level, final String msg, final Throwable t) {
        Throwable filteredTrace = t;
        if (t != null && logbackLogger.isEnabledFor(level)) {
            filteredTrace = cleanIfException(t);
        }
        logbackLogger.log(null, FQCN, toLocationAwareInt(level), msg, null, filteredTrace);
    }

    protected int toLocationAwareInt(Level level) {
        switch (level.levelInt) {
            case Level.TRACE_INT:
                return LocationAwareLogger.TRACE_INT;
            case Level.DEBUG_INT:
                return LocationAwareLogger.DEBUG_INT;
            case Level.INFO_INT:
                return LocationAwareLogger.INFO_INT;
            case Level.WARN_INT:
                return LocationAwareLogger.WARN_INT;
            case Level.ERROR_INT:
                return LocationAwareLogger.ERROR_INT;
            default:
                return LocationAwareLogger.ERROR_INT;
        }
    }
}


text:
var Spider = require("./app/spider.js");
var eventsHandler = require("./module/eventsHandler.js");
var log4js = require('log4js');
log4js.configure("log4js.json");
var logger = log4js.getLogger();

var fs = require("fs");

var codeImg = document.getElementById("codeImg");
var loginBtn = document.getElementById("login-btn");
var ipSelect = document.getElementById("ip-select");
var enterBtn = document.getElementById("enter-btn");
var resultBtns = document.getElementsByClassName("result-btn");
var progressBarInner = document.getElementById("progress-bar-inner");

var loginStatus = false;
var taskStatus = false;

/**
 * 输出提示信息
 */
var outputPush = function () {
  var list = [];
  var list1 = document.getElementById("output-list-1");
  var list2 = document.getElementById("output-list-2");
  var list3 = document.getElementById("output-list-3");
  var setContent = function (container, level, msg) {
    container.innerHTML = msg;
    container.className = "output-list";
    container.classList.add(level);
  }
  return function (level, msg) {
    list.push({
      level: level,
      msg: msg
    });
    setContent(list1, level, msg);
    if (list[list.length - 2]) {
      setContent(list2, list[list.length - 2].level, list[list.length - 2].msg);
      if (list[list.length - 3]) {
        setContent(list3, list[list.length - 3].level, list[list.length - 3].msg);
      }
    }
  }
}();

var spider = new Spider();

getCodeImg();

eventsHandler.addEventHandle({
  info: function (target, msg, data) {
    outputPush("info", target + ":" + msg);
    console.log(target + ":" + msg);
  },
  error: function (target, msg, data) {
    outputPush("error", target + ":" + msg + (data ? ". Error:" + data.toString() : ""));
    console.log(target + ":" + msg);
    logger.error(target + ":" + msg + (data ? ". Error:" + data.toString() : ""));
    if (target == "spider" && taskStatus) {
      taskFinish();
    }
  },
  warn: function (target, msg, data) {
    outputPush("warn", target + ":" + msg);
    console.log(target + ":" + msg);
  },
  progress: function (target, msg, data) {
    progressBarInner.style.width = data + "%";
  },
  finish: function (target, msg, data) {
    outputPush("info", target + ":" + msg);
    console.log(target + ":" + msg);
    taskFinish();
  }
});

codeImg.addEventListener("click", function (e) {
  e.preventDefault();
  getCodeImg();
});
loginBtn.addEventListener("click", function (e) {
  e.preventDefault();
  login();
});
ipSelect.addEventListener("change", function (e) {
  spider.setIp(ipSelect.value);
  getCodeImg();
});
enterBtn.addEventListener("click", function (e) {
  e.preventDefault();
  enter();
});
[].forEach.call(resultBtns, function (ele) {
  ele.addEventListener("click", function (element, type) {
    return function (e) {
      e.preventDefault();
      if (element.classList.contains("disabled") || element.classList.contains("active")) {
        return;
      }
      if (type == -1) {
        logout();
        return;
      }
      taskStart(type);
    }
  }(ele, ele.dataset.type))
});

/**
 *
 * 获取验证码
 */
function getCodeImg() {
  codeImg.src = "";
  window.URL.revokeObjectURL(codeImg.src);
  spider.requestImg(function (status, data) {
    if (status) {
      fs.writeFileSync("img.jpg", data);
      var img = fs.readFileSync("img.jpg");
      var blob = new Blob([img.buffer], {
        type: "image/jpeg"
      });
      codeImg.src = window.URL.createObjectURL(blob);
    } else {
      outputPush("warn", "验证码获取失败");
    }
  });
}

/**
 * 登陆
 *
 * @returns
 */
function login() {
  var username = document.getElementById("username").value;
  var password = document.getElementById("password").value;
  var codetext = document.getElementById("codetext").value;
  if (!codetext) {
    outputPush("warn", "请输入验证码");
    return;
  }
  spider.login(username, password, codetext, function (status) {
    if (status) {
      changeLoginStatus(true);
    } else {
      getCodeImg();
    }
  })
}

/**
 * 直接输入cookie和csrftoken进入
 *
 * @returns
 */
function enter() {
  var cookie = document.getElementById("cookie").value;
  var csrftoken = document.getElementById("csrftoken").value;
  if (!cookie || !csrftoken) {
    outputPush("warn", "请输入cookie和csrftoken");
    return;
  }
  spider.setCookie(cookie);
  spider.setCsrftoken(csrftoken);
  changeLoginStatus(true);
}

function logout() {
  changeLoginStatus(false);
  getCodeImg();
}

function taskStart(type) {
  if (!loginStatus) {
    outputPush("info", "请重新登陆");
    logout();
    return;
  }
  if (type) {
    var filePath = "output/";
    switch (type) {
      case '0':
        filePath += "publsn.json";
        break;
      case '1':
        filePath += "pubrequiredlsn.json";
        break;
      case '2':
        filePath += "planlsn.json";
        break;
      case '-1':
        return;
      default:
        outputPush("info", "请输入正确的类型");
        return;
    }
    spider.start(type, filePath);
  }
  [].forEach.call(resultBtns, function (ele) {
    if (ele.dataset.type != type) {
      ele.classList.add("disabled");
    } else {
      ele.classList.add("active");
    }
  });
  taskStatus = true;
}

function taskFinish() {
  [].forEach.call(resultBtns, function (ele) {
    ele.classList.remove("disabled");
    ele.classList.remove("active");
  });
  progressBarInner.style.width = "0";
  taskStatus = false;
}

function changeLoginStatus(status) {
  if (status) {
    loginStatus = status;
    var main = document.getElementById("main");
    main.classList.add("login-success");
  } else {
    loginStatus = false;
    var main = document.getElementById("main");
    main.classList.remove("login-success");
  }
}


text:
package com.djonique.birdays.utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.widget.Toast;

import com.djonique.birdays.R;
import com.djonique.birdays.alarm.AlarmHelper;
import com.djonique.birdays.database.DbHelper;
import com.djonique.birdays.models.Person;

import java.util.ArrayList;
import java.util.List;

public class ContactsHelper {

    private Activity activity;
    private ContentResolver contentResolver;
    private LoadingContactsListener loadingContactsListener;

    public ContactsHelper(Activity activity, ContentResolver contentResolver) {
        this.activity = activity;
        this.contentResolver = contentResolver;
        loadingContactsListener = (LoadingContactsListener) activity;
    }

    /**
     * Returns name from certain contact
     */
    public String getContactName(ContentResolver contentResolver, String id) {
        String name = "";
        Cursor nameCursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI,
                null,
                ContactsContract.Contacts._ID + " = ?",
                new String[]{id}, null);
        if (nameCursor != null && nameCursor.moveToFirst()) {
            name =
                    nameCursor.getString(nameCursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
        }
        if (nameCursor != null) {
            nameCursor.close();
        }
        return name;
    }

    /**
     * Returns phone number from certain contact
     */
    public String getContactPhoneNumber(ContentResolver contentResolver, String id) {
        String phoneNumber = "";
        Cursor phoneCursor = contentResolver.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                new String[]{id}, null);
        if (phoneCursor != null && phoneCursor.moveToFirst()) {
            phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex
                    (ContactsContract.CommonDataKinds.Phone.NUMBER));
        }
        if (phoneCursor != null) {
            phoneCursor.close();
        }
        return phoneNumber;
    }

    /**
     * Returns email from certain contact
     */
    public String getContactEmail(ContentResolver contentResolver, String id) {
        String email = "";
        Cursor emailCursor = contentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                null,
                ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
                new String[]{id}, null);
        if (emailCursor != null && emailCursor.moveToFirst()) {
            email = emailCursor.getString(
                    emailCursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Email.DATA));
        }
        if (emailCursor != null) {
            emailCursor.close();
        }
        return email;
    }

    /**
     * Returns all contacts with Birthdays
     */
    private List<Person> getAllContactsWithBirthdays(ContentResolver contentResolver) {

        List<Person> contacts = new ArrayList<>();

        Cursor cursor = getContactsCursor(contentResolver);

        while (cursor.moveToNext()) {
            String id = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Event.CONTACT_ID));
            String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
            String dateString = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
            long date;
            try {
                date = Utils.formatDateToLong(dateString);
            } catch (Exception e) {
                continue;
            }
            if (date == 0) continue;

            boolean yearUnknown = Utils.isYearUnknown(dateString);
            String phoneNumber = getContactPhoneNumber(contentResolver, id);
            String email = getContactEmail(contentResolver, id);

            Person person = new Person(name, date, yearUnknown, phoneNumber, email);
            contacts.add(person);
        }
        cursor.close();
        return contacts;
    }

    /**
     * Returns cursor with contacts with specified Birthdays
     */
    private Cursor getContactsCursor(ContentResolver contentResolver) {
        Uri uri = ContactsContract.Data.CONTENT_URI;

       /* String[] projection = new String[]{
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Event.CONTACT_ID,
                ContactsContract.CommonDataKinds.Event.START_DATE,
        };*/

        String where =
                ContactsContract.Data.MIMETYPE
                        + "= ? AND "
                        + ContactsContract.CommonDataKinds.Event.TYPE
                        + "="
                        + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
        String[] selectionArgs = new String[]{ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE};
        return contentResolver.query(uri, null, where, selectionArgs, null);
    }

    /**
     * Loads all persons with Birthdays from Contacts, compares them with persons from Database and
     * saves them into DB, sets alarm for added persons
     */
    public void loadContacts(SharedPreferences preferences) {
        if (PermissionManager.readingContactsPermissionGranted(activity)) {
            try {
                new ContactsAsyncLoading().execute();
                preferences.edit().putBoolean(Constants.CONTACTS_UPLOADED, true).apply();
            } catch (Exception e) {
                preferences.edit().putBoolean(Constants.WRONG_CONTACTS_FORMAT, true).apply();
                Toast.makeText(activity, R.string.loading_contacts_error, Toast.LENGTH_LONG).show();
            }
        } else {
            PermissionManager.requestReadingContactsPermission(activity);
        }
    }

    public interface LoadingContactsListener {
        void onContactsUploaded();
    }

    private class ContactsAsyncLoading extends AsyncTask<Void, Void, Void> {

        ProgressDialogHelper progressDialogHelper = new ProgressDialogHelper(activity);

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialogHelper.startProgressDialog(activity.getString(R.string.loading_contacts));
        }

        @Override
        protected Void doInBackground(Void... params) {
            DbHelper dbHelper = new DbHelper(activity);
            AlarmHelper alarmHelper = new AlarmHelper(activity);

            List<Person> dbPersons = dbHelper.query().getPersons();
            List<Person> contacts = getAllContactsWithBirthdays(contentResolver);

            for (Person person : contacts) {
                if (!Utils.isPersonAlreadyInDb(person, dbPersons)) {
                    dbHelper.addRecord(person);
                    alarmHelper.setAlarms(person);
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progressDialogHelper.dismissProgressDialog();
            loadingContactsListener.onContactsUploaded();
            Utils.notifyWidget(activity);
            Toast.makeText(activity, R.string.contacts_uploaded, Toast.LENGTH_SHORT).show();
        }
    }
}


text:
NSMutableData * buildBody(id);
NSMutableData * bodyToData(NSData *);
NSMutableData * encryptBody(NSData *, NSData *);
NSMutableData * decryptBody(NSData *, NSData *);
NSMutableData * authenticate(NSData *, NSData *, NSData *);
NSMutableData * verify(NSData *, NSData *, NSData *);

@interface Packet ()
@property (nonatomic, strong) NSMutableData *masterKey;
@property (nonatomic, strong) NSMutableData *keyId;
@end

@implementation Packet

- (id)initWithKey:(NSData *)key
{
    self = [super init];
    if (self) {
        self.masterKey = [key mutableCopy];
        self.keyId = [Primitives identify:self.masterKey];
    }
    return self;
}

- (NSString *)pack:(id)object
{
    NSMutableData *body = buildBody(object);
    NSMutableData *encrypted = encryptBody(body, self.masterKey);
    NSMutableData *packet = authenticate(encrypted, self.masterKey, self.keyId);
    NSString *websafe = [Primitives stringify:packet];

    [Primitives zero:body, encrypted, packet, nil];
    return websafe;
}

- (id)unpack:(NSString *)websafe
{
    NSMutableData *packet = [Primitives binify:websafe];
    NSMutableData *cipherdata = verify(packet, self.masterKey, self.keyId);
    NSMutableData *body = nil;
    NSMutableData *data = nil;

    if (cipherdata) {
        body = decryptBody(cipherdata, self.masterKey);
        data = bodyToData(body);
        [Primitives zero:body, cipherdata, nil];
    }

    [Primitives zero:packet, nil];
    return data;
}

@end

NSMutableData * buildBody(id data) {
    NSMutableData *nonce = [Primitives nonce];
    NSData *bindata = [Primitives serialize:data];
    NSMutableData *body = [NSMutableData dataWithCapacity:(nonce.length+bindata.length)];
    [body appendData:nonce];
    [body appendData:bindata];

    [Primitives zero:nonce, bindata, nil];
    return body;
}

NSMutableData * bodyToData(NSData *body) {
    NSMutableData *nonce = [NSMutableData dataWithBytes:body.bytes length:16];
    NSMutableData *bindata = [NSMutableData dataWithBytes:(body.bytes+16) length:(body.length-16)];
    NSMutableData *data = [Primitives deserialize:bindata];

    [Primitives zero:nonce, bindata, nil];
    return data;
}

NSMutableData * encryptBody(NSData *body, NSData *master) {
    NSMutableData *key = [Primitives deriveSenderCipherKeyFromMasterKey:master];
    NSMutableData *cipherdata = [Primitives encryptData:body withKey:master];

    [Primitives zero:key, nil];
    return cipherdata;
}

NSMutableData * decryptBody(NSData *cipherdata, NSData *master) {
    NSMutableData *key = [Primitives deriveSenderCipherKeyFromMasterKey:master];
    NSMutableData *iv = [NSMutableData dataWithBytes:cipherdata.bytes length:16];
    NSMutableData *encrypted = [NSMutableData dataWithBytes:(cipherdata.bytes+16) length:(cipherdata.length-16)];
    NSMutableData *body = [Primitives decryptData:encrypted withKey:key andIV:iv];

    [Primitives zero:key, iv, encrypted, nil];
    return body;
}

NSMutableData * authenticate(NSData *data, NSData *master, NSData *keyId) {
    // Authenticate the (keyId || iv || ciphertext); bundle it all together
    NSMutableData *hmacKey = [Primitives deriveSenderHmacKeyFromMasterKey:master];
    NSMutableData *auth = [NSMutableData dataWithCapacity:(keyId.length+data.length)];
    [auth appendData:keyId];
    [auth appendData:data];
    NSMutableData *mac = [Primitives macForData:auth withKey:hmacKey];
    NSMutableData *packet = [NSMutableData dataWithCapacity:(keyId.length+data.length+mac.length)];
    [packet appendData:keyId];
    [packet appendData:data];
    [packet appendData:mac];

    [Primitives zero:hmacKey, mac, auth];
    return packet;
}

NSMutableData * verify(NSData *packet, NSData *master, NSData *keyId) {
    // Authenticate the (keyId || iv || ciphertext); bundle it all together
    NSMutableData *packetKeyId = [NSMutableData dataWithBytes:packet.bytes length:6];

    if (![Primitives compare:packetKeyId to:keyId]) {
        return nil;
    }

    NSMutableData *auth = [NSMutableData dataWithBytes:packet.bytes length:(packet.length-32)];
    NSMutableData *packetMac = [NSMutableData dataWithBytes:(packet.bytes+packet.length-32) length:32];

    NSMutableData *hmacKey = [Primitives deriveSenderHmacKeyFromMasterKey:master];
    NSMutableData *mac = [Primitives macForData:auth withKey:hmacKey];
    BOOL valid = [Primitives compare:packetMac to:mac];

    NSMutableData *data = valid ? [NSMutableData dataWithBytes:packet.bytes+6 length:(packet.length-32-6)] : nil;

    [Primitives zero:hmacKey, mac, auth, packetKeyId, packetMac, nil];
    return data;
}


text:
import { Session, SessionType } from "../../../server/schema/Session";
import speaker from "../../people/kent-c-dodds";

const talk: Session = {
  people: [speaker],
  title: "",
  description: "",
  type: SessionType.KEYNOTE,
  keywords: [],
};

export default talk;


text:
package org.openxsp.java.session;

import org.vertx.java.core.json.JsonObject;

/**
 * Created by Frank Schulze on 22.04.14.
 * frank.schulze at fokus.fraunhofer.de
 */
public class SessionControlAcceptSessionImpl extends SessionControlMessgeImpl implements SessionControlAcceptSession {

    private String content;
    private String contentType;
    private SessionControlMessageHeader header;

    public SessionControlAcceptSessionImpl(){}

    public SessionControlAcceptSessionImpl(String content, String contentType){
        this.content = content;
        this.contentType = contentType;
    }

    @Override
    public SessionControlMethodEnum getMethod() {
        return SessionControlMethodEnum.ACCEPT;
    }

    @Override
    public void setMethod(SessionControlMethodEnum methodEnum) {
        super.setMethod(methodEnum);
    }

    @Override
    public String getSessionID() {
        return super.getSessionID();
    }

    @Override
    public void setSessionID(String sessionID) {
        super.setSessionID(sessionID);
    }

    @Override
    public String getContent() {
        return this.content;
    }

    @Override
    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String getContentType() {
        return this.contentType;
    }

    @Override
    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    @Override
    public SessionControlMessageHeader getHeader() {
        return this.header;
    }

    @Override
    public void setHeader(SessionControlMessageHeader header) {
        this.header = header;
    }

    @Override
    public SessionControlMessage parse(JsonObject jsonMessage) {
        if (jsonMessage == null)
            return null;
        this.setMethod(SessionControlMethodEnum.ACCEPT);
        super.setSessionID(jsonMessage.getString(SessionControlHeaderField.sessionID.toLowerCase()));
        super.setAddress(jsonMessage.getString(SessionControlHeaderField.address));
        this.setContent(jsonMessage.getString(SessionControlHeaderField.content.toLowerCase()));
        this.setContentType(jsonMessage.getString(SessionControlHeaderField.contentType.toLowerCase()));
        header = new SessionControlMessageHeader();
        header.parse(jsonMessage.getObject(SessionControlHeaderField.header.toLowerCase()));
        return this;
    }

    @Override
    public org.vertx.java.core.json.JsonObject create() {
        JsonObject message = new JsonObject();

        message.putString(SessionControlHeaderField.method, SessionControlMethodEnum.ACCEPT.toString().toLowerCase());

        if (super.getAddress() == null)
            return null;
        else
            message.putString(SessionControlHeaderField.address, super.getAddress());
        if (super.getSessionID() != null)
            message.putString(SessionControlHeaderField.sessionID, super.getSessionID());
        if (this.content != null)
            message.putString(SessionControlHeaderField.content, this.content);
        if (this.contentType != null)
            message.putString(SessionControlHeaderField.contentType, this.contentType);
        if (this.header != null)
            message.putObject(SessionControlHeaderField.header, header.create());

        return message;
    }
}


text:
using System;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Testing;
using osu.Game.Configuration;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;

namespace osu.Game.Tests.Visual
{
    public abstract class PlayerTestScene : RateAdjustedBeatmapTestScene
    {
        /// <summary>
        /// Whether custom test steps are provided. Custom tests should invoke <see cref="CreateTest"/> to create the test steps.
        /// </summary>
        protected virtual bool HasCustomSteps => false;

        protected TestPlayer Player;

        protected OsuConfigManager LocalConfig;

        [BackgroundDependencyLoader]
        private void load()
        {
            Dependencies.Cache(LocalConfig = new OsuConfigManager(LocalStorage));
            LocalConfig.GetBindable<double>(OsuSetting.DimLevel).Value = 1.0;
        }

        [SetUpSteps]
        public override void SetUpSteps()
        {
            base.SetUpSteps();

            if (!HasCustomSteps)
                CreateTest();
        }

        protected void CreateTest([CanBeNull] Action action = null)
        {
            if (action != null && !HasCustomSteps)
                throw new InvalidOperationException($"Cannot add custom test steps without {nameof(HasCustomSteps)} being set.");

            action?.Invoke();

            AddStep($"Load player for {CreatePlayerRuleset().Description}", LoadPlayer);
            AddUntilStep("player loaded", () => Player.IsLoaded && Player.Alpha == 1);
        }

        protected virtual bool AllowFail => false;

        protected virtual bool Autoplay => false;

        protected void LoadPlayer() => LoadPlayer(Array.Empty<Mod>());

        protected void LoadPlayer(Mod[] mods)
        {
            var ruleset = CreatePlayerRuleset();
            Ruleset.Value = ruleset.RulesetInfo;

            var beatmap = CreateBeatmap(ruleset.RulesetInfo);

            Beatmap.Value = CreateWorkingBeatmap(beatmap);

            SelectedMods.Value = mods;

            if (!AllowFail)
            {
                var noFailMod = ruleset.CreateMod<ModNoFail>();
                if (noFailMod != null)
                    SelectedMods.Value = SelectedMods.Value.Append(noFailMod).ToArray();
            }

            if (Autoplay)
            {
                var mod = ruleset.GetAutoplayMod();
                if (mod != null)
                    SelectedMods.Value = SelectedMods.Value.Append(mod).ToArray();
            }

            Player = CreatePlayer(ruleset);
            LoadScreen(Player);
        }

        protected override void Dispose(bool isDisposing)
        {
            LocalConfig?.Dispose();
            base.Dispose(isDisposing);
        }

        /// <summary>
        /// Creates the ruleset for setting up the <see cref="Player"/> component.
        /// </summary>
        [NotNull]
        protected abstract Ruleset CreatePlayerRuleset();

        protected sealed override Ruleset CreateRuleset() => CreatePlayerRuleset();

        protected virtual TestPlayer CreatePlayer(Ruleset ruleset) => new TestPlayer(false, false);
    }
}


text:
package geohash

import "math"

// Encode the point (lat, lng) as a string geohash with the standard 12
// characters of precision.
func Encode(lat, lng float64) string {
	return EncodeWithPrecision(lat, lng, 12)
}

// EncodeWithPrecision encodes the point (lat, lng) as a string geohash with
// the specified number of characters of precision (max 12).
func EncodeWithPrecision(lat, lng float64, chars uint) string {
	bits := 5 * chars
	inthash := EncodeIntWithPrecision(lat, lng, bits)
	enc := base32encoding.Encode(inthash)
	return enc[12-chars:]
}

// EncodeInt encodes the point (lat, lng) to a 64-bit integer geohash.
func EncodeInt(lat, lng float64) uint64 {
	latInt := encodeRange(lat, 90)
	lngInt := encodeRange(lng, 180)
	return interleave(latInt, lngInt)
}

// EncodeIntWithPrecision encodes the point (lat, lng) to an integer with the
// specified number of bits.
func EncodeIntWithPrecision(lat, lng float64, bits uint) uint64 {
	hash := EncodeInt(lat, lng)
	return hash >> (64 - bits)
}

// Box represents a rectangle in latitude/longitude space.
type Box struct {
	MinLat float64
	MaxLat float64
	MinLng float64
	MaxLng float64
}

// Center returns the center of the box.
func (b Box) Center() (lat, lng float64) {
	lat = (b.MinLat + b.MaxLat) / 2.0
	lng = (b.MinLng + b.MaxLng) / 2.0
	return
}

// Contains decides whether (lat, lng) is contained in the box. The
// containment test is inclusive of the edges and corners.
func (b Box) Contains(lat, lng float64) bool {
	return (b.MinLat <= lat && lat <= b.MaxLat &&
		b.MinLng <= lng && lng <= b.MaxLng)
}

// minDecimalPlaces returns the minimum number of decimal places such that
// there must exist an number with that many places within any range of width
// r. This is intended for returning minimal precision coordinates inside a
// box.
func maxDecimalPower(r float64) float64 {
	m := int(math.Floor(math.Log10(r)))
	return math.Pow10(m)
}

// Round returns a point inside the box, making an effort to round to minimal
// precision.
func (b Box) Round() (lat, lng float64) {
	x := maxDecimalPower(b.MaxLat - b.MinLat)
	lat = math.Ceil(b.MinLat/x) * x
	x = maxDecimalPower(b.MaxLng - b.MinLng)
	lng = math.Ceil(b.MinLng/x) * x
	return
}

// errorWithPrecision returns the error range in latitude and longitude for in
// integer geohash with bits of precision.
func errorWithPrecision(bits uint) (latErr, lngErr float64) {
	latBits := bits / 2
	lngBits := bits - latBits
	latErr = 180.0 / math.Exp2(float64(latBits))
	lngErr = 360.0 / math.Exp2(float64(lngBits))
	return
}

// BoundingBox returns the region encoded by the given string geohash.
func BoundingBox(hash string) Box {
	bits := uint(5 * len(hash))
	inthash := base32encoding.Decode(hash)
	return BoundingBoxIntWithPrecision(inthash, bits)
}

// BoundingBoxIntWithPrecision returns the region encoded by the integer
// geohash with the specified precision.
func BoundingBoxIntWithPrecision(hash uint64, bits uint) Box {
	fullHash := hash << (64 - bits)
	latInt, lngInt := deinterleave(fullHash)
	lat := decodeRange(latInt, 90)
	lng := decodeRange(lngInt, 180)
	latErr, lngErr := errorWithPrecision(bits)
	return Box{
		MinLat: lat,
		MaxLat: lat + latErr,
		MinLng: lng,
		MaxLng: lng + lngErr,
	}
}

// BoundingBoxInt returns the region encoded by the given 64-bit integer
// geohash.
func BoundingBoxInt(hash uint64) Box {
	return BoundingBoxIntWithPrecision(hash, 64)
}

// Decode the string geohash to a (lat, lng) point.
func Decode(hash string) (lat, lng float64) {
	box := BoundingBox(hash)
	return box.Round()
}

// DecodeIntWithPrecision decodes the provided integer geohash with bits of
// precision to a (lat, lng) point.
func DecodeIntWithPrecision(hash uint64, bits uint) (lat, lng float64) {
	box := BoundingBoxIntWithPrecision(hash, bits)
	return box.Round()
}

// DecodeInt decodes the provided 64-bit integer geohash to a (lat, lng) point.
func DecodeInt(hash uint64) (lat, lng float64) {
	return DecodeIntWithPrecision(hash, 64)
}

// Neighbors returns a slice of geohash strings that correspond to the provided
// geohash's neighbors.
func Neighbors(hash string) []string {
	box := BoundingBox(hash)
	lat, lng := box.Center()
	latDelta := box.MaxLat - box.MinLat
	lngDelta := box.MaxLng - box.MinLng
	precision := uint(len(hash))
	return []string{
		// N
		EncodeWithPrecision(lat+latDelta, lng, precision),
		// NE,
		EncodeWithPrecision(lat+latDelta, lng+lngDelta, precision),
		// E,
		EncodeWithPrecision(lat, lng+lngDelta, precision),
		// SE,
		EncodeWithPrecision(lat-latDelta, lng+lngDelta, precision),
		// S,
		EncodeWithPrecision(lat-latDelta, lng, precision),
		// SW,
		EncodeWithPrecision(lat-latDelta, lng-lngDelta, precision),
		// W,
		EncodeWithPrecision(lat, lng-lngDelta, precision),
		// NW
		EncodeWithPrecision(lat+latDelta, lng-lngDelta, precision),
	}
}

// NeighborsInt returns a slice of uint64s that correspond to the provided hash's
// neighbors at 64-bit precision.
func NeighborsInt(hash uint64) []uint64 {
	return NeighborsIntWithPrecision(hash, 64)
}

// NeighborsIntWithPrecision returns a slice of uint64s that correspond to the
// provided hash's neighbors at the given precision.
func NeighborsIntWithPrecision(hash uint64, bits uint) []uint64 {
	box := BoundingBoxIntWithPrecision(hash, bits)
	lat, lng := box.Center()
	latDelta := box.MaxLat - box.MinLat
	lngDelta := box.MaxLng - box.MinLng
	return []uint64{
		// N
		EncodeIntWithPrecision(lat+latDelta, lng, bits),
		// NE,
		EncodeIntWithPrecision(lat+latDelta, lng+lngDelta, bits),
		// E,
		EncodeIntWithPrecision(lat, lng+lngDelta, bits),
		// SE,
		EncodeIntWithPrecision(lat-latDelta, lng+lngDelta, bits),
		// S,
		EncodeIntWithPrecision(lat-latDelta, lng, bits),
		// SW,
		EncodeIntWithPrecision(lat-latDelta, lng-lngDelta, bits),
		// W,
		EncodeIntWithPrecision(lat, lng-lngDelta, bits),
		// NW
		EncodeIntWithPrecision(lat+latDelta, lng-lngDelta, bits),
	}
}

// precalculated for performance
var exp232 = math.Exp2(32)

// Encode the position of x within the range -r to +r as a 32-bit integer.
func encodeRange(x, r float64) uint32 {
	p := (x + r) / (2 * r)
	return uint32(p * exp232)
}

// Decode the 32-bit range encoding X back to a value in the range -r to +r.
func decodeRange(X uint32, r float64) float64 {
	p := float64(X) / exp232
	x := 2*r*p - r
	return x
}

// Spread out the 32 bits of x into 64 bits, where the bits of x occupy even
// bit positions.
func spread(x uint32) uint64 {
	X := uint64(x)
	X = (X | (X << 16)) & 0x0000ffff0000ffff
	X = (X | (X << 8)) & 0x00ff00ff00ff00ff
	X = (X | (X << 4)) & 0x0f0f0f0f0f0f0f0f
	X = (X | (X << 2)) & 0x3333333333333333
	X = (X | (X << 1)) & 0x5555555555555555
	return X
}

// Interleave the bits of x and y. In the result, x and y occupy even and odd
// bitlevels, respectively.
func interleave(x, y uint32) uint64 {
	return spread(x) | (spread(y) << 1)
}

// Squash the even bitlevels of X into a 32-bit word. Odd bitlevels of X are
// ignored, and may take any value.
func squash(X uint64) uint32 {
	X &= 0x5555555555555555
	X = (X | (X >> 1)) & 0x3333333333333333
	X = (X | (X >> 2)) & 0x0f0f0f0f0f0f0f0f
	X = (X | (X >> 4)) & 0x00ff00ff00ff00ff
	X = (X | (X >> 8)) & 0x0000ffff0000ffff
	X = (X | (X >> 16)) & 0x00000000ffffffff
	return uint32(X)
}

// Deinterleave the bits of X into 32-bit words containing the even and odd
// bitlevels of X, respectively.
func deinterleave(X uint64) (uint32, uint32) {
	return squash(X), squash(X >> 1)
}