text:
<?php

/*
 * 新浪微博 OAuth 认证类(OAuth2)
 *
 * 授权机制说明请大家参考微博开放平台文档:{@link http://open.weibo.com/wiki/Oauth2}
 *
 * @package sae
 * @author Elmer Zhang
 * @version 1.0
 */

namespace Lo\UserBundle\Util\Lib\Weibo;

use Lo\UserBundle\Util\Lib\Weibo\OAuthException;

class Oauth {

    /**
     * @ignore
     */
    public $client_id;

    /**
     * @ignore
     */
    public $client_secret;

    /**
     * @ignore
     */
    public $access_token;

    /**
     * @ignore
     */
    public $refresh_token;

    /**
     * Contains the last HTTP status code returned.
     *
     * @ignore
     */
    public $http_code;

    /**
     * Contains the last API call.
     *
     * @ignore
     */
    public $url;

    /**
     * Set up the API root URL.
     *
     * @ignore
     */
    public $host = "https://api.weibo.com/2/";

    /**
     * Set timeout default.
     *
     * @ignore
     */
    public $timeout = 30;

    /**
     * Set connect timeout.
     *
     * @ignore
     */
    public $connecttimeout = 30;

    /**
     * Verify SSL Cert.
     *
     * @ignore
     */
    public $ssl_verifypeer = FALSE;

    /**
     * Respons format.
     *
     * @ignore
     */
    public $format = 'json';

    /**
     * Decode returned json data.
     *
     * @ignore
     */
    public $decode_json = TRUE;

    /**
     * Contains the last HTTP headers returned.
     *
     * @ignore
     */
    public $http_info;

    /**
     * Set the useragnet.
     *
     * @ignore
     */
    public $useragent = 'Sae T OAuth2 v0.1';

    /**
     * print the debug info
     *
     * @ignore
     */
    public $debug = FALSE;

    /**
     * boundary of multipart
     * @ignore
     */
    public static $boundary = '';

    /**
     * Set API URLS
     */

    /**
     * @ignore
     */
    function accessTokenURL() {
        return 'https://api.weibo.com/oauth2/access_token';
    }

    /**
     * @ignore
     */
    function authorizeURL() {
        return 'https://api.weibo.com/oauth2/authorize';
    }

    /**
     * construct WeiboOAuth object
     */
    function __construct($client_id, $client_secret, $access_token = NULL, $refresh_token = NULL) {
        $this->client_id = $client_id;
        $this->client_secret = $client_secret;
        $this->access_token = $access_token;
        $this->refresh_token = $refresh_token;
    }

    /**
     * authorize接口
     *
     * 对应API:{@link http://open.weibo.com/wiki/Oauth2/authorize Oauth2/authorize}
     *
     * @param string $url 授权后的回调地址,站外应用需与回调地址一致,站内应用需要填写canvas page的地址
     * @param string $response_type 支持的值包括 code 和token 默认值为code
     * @param string $state 用于保持请求和回调的状态。在回调时,会在Query Parameter中回传该参数
     * @param string $display 授权页面类型 可选范围:
     *  - default		默认授权页面
     *  - mobile		支持html5的手机
     *  - wap1.2		wap1.2页面
     *  - wap2.0		wap2.0页面
     *  - apponweibo	站内应用专用,站内应用不传display参数,并且response_type为token时,默认使用改display.授权后不会返回access_token,只是输出js刷新站内应用父框架
     * @param bool $forcelogin 是否强制用户重新登录,true:是,false:否。默认false。
     * @param string $language 授权页语言,缺省为中文简体版,en为英文版。英文版测试中,开发者任何意见可反馈至 @微博API
     * @return array
     */
    function getAuthorizeURL($url, $response_type = 'code', $state = NULL, $display = NULL, $forcelogin = NULL, $language = NULL) {
        $params = array();
        $params['client_id'] = $this->client_id;
        $params['redirect_uri'] = $url;
        $params['response_type'] = $response_type;
        $params['state'] = $state;
        $params['display'] = $display;
        $params['forcelogin'] = $forcelogin;
        $params['language'] = $language;
        return $this->authorizeURL() . "?" . http_build_query($params);
    }

    /**
     * access_token接口
     *
     * 对应API:{@link http://open.weibo.com/wiki/OAuth2/access_token OAuth2/access_token}
     *
     * @param string $type 请求的类型,可以为:code, password, token
     * @param array $keys 其他参数:
     *  - 当$type为code时: array('code'=>..., 'redirect_uri'=>...)
     *  - 当$type为password时: array('username'=>..., 'password'=>...)
     *  - 当$type为token时: array('refresh_token'=>...)
     * @return array
     */
    function getAccessToken($type = 'code', $keys) {
        $params = array();
        $params['client_id'] = $this->client_id;
        $params['client_secret'] = $this->client_secret;
        if ($type === 'token') {
            $params['grant_type'] = 'refresh_token';
            $params['refresh_token'] = $keys['refresh_token'];
        } elseif ($type === 'code') {
            $params['grant_type'] = 'authorization_code';
            $params['code'] = $keys['code'];
            $params['redirect_uri'] = $keys['redirect_uri'];
        } elseif ($type === 'password') {
            $params['grant_type'] = 'password';
            $params['username'] = $keys['username'];
            $params['password'] = $keys['password'];
        } else {
            throw new OAuthException("wrong auth type");
        }

        $response = $this->oAuthRequest($this->accessTokenURL(), 'POST', $params);
        $token = json_decode($response, true);
        if (is_array($token) && !isset($token['error'])) {
            $this->access_token = $token['access_token'];
            if (isset($token['refresh_token'])) {
                $this->refresh_token = $token['refresh_token'];
            } else {
                $this->refresh_token = '';
            }
        } else {
            throw new OAuthException("get access token failed." . $token['error']);
        }
        return $token;
    }

    /**
     * 解析 signed_request
     *
     * @param string $signed_request 应用框架在加载iframe时会通过向Canvas URL post的参数signed_request
     *
     * @return array
     */
    function parseSignedRequest($signed_request) {
        list($encoded_sig, $payload) = explode('.', $signed_request, 2);
        $sig = self::base64decode($encoded_sig);
        $data = json_decode(self::base64decode($payload), true);
        if (strtoupper($data['algorithm']) !== 'HMAC-SHA256')
            return '-1';
        $expected_sig = hash_hmac('sha256', $payload, $this->client_secret, true);
        return ($sig !== $expected_sig) ? '-2' : $data;
    }

    /**
     * @ignore
     */
    function base64decode($str) {
        return base64_decode(strtr($str . str_repeat('=', (4 - strlen($str) % 4)), '-_', '+/'));
    }

    /**
     * 读取jssdk授权信息,用于和jssdk的同步登录
     *
     * @return array 成功返回array('access_token'=>'value', 'refresh_token'=>'value'); 失败返回false
     */
    function getTokenFromJSSDK() {
        $key = "weibojs_" . $this->client_id;
        if (isset($_COOKIE[$key]) && $cookie = $_COOKIE[$key]) {
            parse_str($cookie, $token);
            if (isset($token['access_token']) && isset($token['refresh_token'])) {
                $this->access_token = $token['access_token'];
                $this->refresh_token = $token['refresh_token'];
                return $token;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 从数组中读取access_token和refresh_token
     * 常用于从Session或Cookie中读取token,或通过Session/Cookie中是否存有token判断登录状态。
     *
     * @param array $arr 存有access_token和secret_token的数组
     * @return array 成功返回array('access_token'=>'value', 'refresh_token'=>'value'); 失败返回false
     */
    function getTokenFromArray($arr) {
        if (isset($arr['access_token']) && $arr['access_token']) {
            $token = array();
            $this->access_token = $token['access_token'] = $arr['access_token'];
            if (isset($arr['refresh_token']) && $arr['refresh_token']) {
                $this->refresh_token = $token['refresh_token'] = $arr['refresh_token'];
            }

            return $token;
        } else {
            return false;
        }
    }

    /**
     * GET wrappwer for oAuthRequest.
     *
     * @return mixed
     */
    function get($url, $parameters = array()) {
        $response = $this->oAuthRequest($url, 'GET', $parameters);
        if ($this->format === 'json' && $this->decode_json) {
            return json_decode($response, true);
        }
        return $response;
    }

    /**
     * POST wreapper for oAuthRequest.
     *
     * @return mixed
     */
    function post($url, $parameters = array(), $multi = false) {
        $response = $this->oAuthRequest($url, 'POST', $parameters, $multi);
        if ($this->format === 'json' && $this->decode_json) {
            return json_decode($response, true);
        }
        return $response;
    }

    /**
     * DELTE wrapper for oAuthReqeust.
     *
     * @return mixed
     */
    function delete($url, $parameters = array()) {
        $response = $this->oAuthRequest($url, 'DELETE', $parameters);
        if ($this->format === 'json' && $this->decode_json) {
            return json_decode($response, true);
        }
        return $response;
    }

    /**
     * Format and sign an OAuth / API request
     *
     * @return string
     * @ignore
     */
    function oAuthRequest($url, $method, $parameters, $multi = false) {

        if (strrpos($url, 'http://') !== 0 && strrpos($url, 'https://') !== 0) {
            $url = "{$this->host}{$url}.{$this->format}";
        }

        switch ($method) {
            case 'GET':
                $url = $url . '?' . http_build_query($parameters);
                return $this->http($url, 'GET');
            default:
                $headers = array();
                if (!$multi && (is_array($parameters) || is_object($parameters))) {
                    $body = http_build_query($parameters);
                } else {
                    $body = self::build_http_query_multi($parameters);
                    $headers[] = "Content-Type: multipart/form-data; boundary=" . self::$boundary;
                }
                return $this->http($url, $method, $body, $headers);
        }
    }

    /**
     * Make an HTTP request
     *
     * @return string API results
     * @ignore
     */
    function http($url, $method, $postfields = NULL, $headers = array()) {
        $this->http_info = array();
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
        curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ci, CURLOPT_ENCODING, "");
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
        //curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, 1);
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
        curl_setopt($ci, CURLOPT_HEADER, FALSE);

        switch ($method) {
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, TRUE);
                if (!empty($postfields)) {
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
                    $this->postdata = $postfields;
                }
                break;
            case 'DELETE':
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
                if (!empty($postfields)) {
                    $url = "{$url}?{$postfields}";
                }
        }

        if (isset($this->access_token) && $this->access_token)
            $headers[] = "Authorization: OAuth2 " . $this->access_token;

        if (!empty($this->remote_ip)) {
            if (defined('SAE_ACCESSKEY')) {
                $headers[] = "SaeRemoteIP: " . $this->remote_ip;
            } else {
                $headers[] = "API-RemoteIP: " . $this->remote_ip;
            }
        } else {
            if (!defined('SAE_ACCESSKEY')) {
                $headers[] = "API-RemoteIP: " . $_SERVER['REMOTE_ADDR'];
            }
        }
        curl_setopt($ci, CURLOPT_URL, $url);
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE);

        $response = curl_exec($ci);
        $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
        $this->url = $url;

        if ($this->debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);

            echo "=====headers======\r\n";
            print_r($headers);

            echo '=====request info=====' . "\r\n";
            print_r(curl_getinfo($ci));

            echo '=====response=====' . "\r\n";
            print_r($response);
        }
        curl_close($ci);
        return $response;
    }

    /**
     * 开启调试信息
     *
     * 开启调试信息后,SDK会将每次请求微博API所发送的POST Data、Headers以及请求信息、返回内容输出出来。
     *
     * @access public
     * @param bool $enable 是否开启调试信息
     * @return void
     */
    function set_debug($enable) {
        $this->debug = $enable;
    }

    /**
     * Get the header info to store.
     *
     * @return int
     * @ignore
     */
    function getHeader($ch, $header) {
        $i = strpos($header, ':');
        if (!empty($i)) {
            $key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
            $value = trim(substr($header, $i + 2));
            $this->http_header[$key] = $value;
        }
        return strlen($header);
    }

    /**
     * @ignore
     */
    public static function build_http_query_multi($params) {
        if (!$params)
            return '';

        uksort($params, 'strcmp');

        $pairs = array();

        self::$boundary = $boundary = uniqid('------------------');
        $MPboundary = '--' . $boundary;
        $endMPboundary = $MPboundary . '--';
        $multipartbody = '';

        foreach ($params as $parameter => $value) {

            if (in_array($parameter, array('pic', 'image')) && $value{0} == '@') {
                $url = ltrim($value, '@');
                $content = file_get_contents($url);
                $array = explode('?', basename($url));
                $filename = $array[0];

                $multipartbody .= $MPboundary . "\r\n";
                $multipartbody .= 'Content-Disposition: form-data; name="' . $parameter . '"; filename="' . $filename . '"' . "\r\n";
                $multipartbody .= "Content-Type: image/unknown\r\n\r\n";
                $multipartbody .= $content . "\r\n";
            } else {
                $multipartbody .= $MPboundary . "\r\n";
                $multipartbody .= 'content-disposition: form-data; name="' . $parameter . "\"\r\n\r\n";
                $multipartbody .= $value . "\r\n";
            }
        }

        $multipartbody .= $endMPboundary;
        return $multipartbody;
    }

}


text:
PushToPulsar
============
Is a little project to help people use Pulsar plugin for XBMC/Kodi from their android devices

For more info see: https://github.com/steeve/plugin.video.pulsar and https://github.com/steeve/plugin.video.pulsar/releases for downloads

Image icon taken from: http://svs.gsfc.nasa.gov/cgi-bin/details.cgi?aid=11609
All credits goes to: NASA's Goddard Space Flight Center

The application includes libraries from:
Apache commons: commons-code-1.9.jar (included for Base32 parse)
http://commons.apache.org/proper/commons-codec/ attributed to http://www.apache.org/ and collaborators.
Released under Apache 2.0 License
http://www.apache.org/licenses/LICENSE-2.0

Bee-encode: bee-encode-0.2.jar (included for reading bencoded torrent files)
https://code.google.com/p/bee-encode/ attributed to Roger Kapsi
Released under Apache 2.0 License
http://www.apache.org/licenses/LICENSE-2.0

redpajama_set_name: RedPajamaGithub


text:
class CouchConsole
  def init
    puts "** initialize all_documents"
    @commands << {
      :regexp => /documents|all_docs/,
      :method => :allDocuments,
      :documentation => [
        ["documents", "Show the document with id"],
        ["_all_docs", "Same as documents"]
      ]
    }
  end

  def allDocuments
    all = @db.documents
    puts "#{all["total_rows"]} documents :"
    all["rows"].each do |doc|
      puts "  id : #{doc["id"]} - rev : #{doc["value"]["rev"]}"
    end
  end
end


text:
// Code generated by github.com/actgardner/gogen-avro/v8. DO NOT EDIT.
/*
 * SOURCE:
 *     schema.avsc
 */
package avro

import (
	"io"

	"github.com/actgardner/gogen-avro/v8/vm"
	"github.com/actgardner/gogen-avro/v8/vm/types"
)

func writeArrayString(r []string, w io.Writer) error {
	err := vm.WriteLong(int64(len(r)), w)
	if err != nil || len(r) == 0 {
		return err
	}
	for _, e := range r {
		err = vm.WriteString(e, w)
		if err != nil {
			return err
		}
	}
	return vm.WriteLong(0, w)
}

type ArrayStringWrapper struct {
	Target *[]string
}

func (_ *ArrayStringWrapper) SetBoolean(v bool)                { panic("Unsupported operation") }
func (_ *ArrayStringWrapper) SetInt(v int32)                   { panic("Unsupported operation") }
func (_ *ArrayStringWrapper) SetLong(v int64)                  { panic("Unsupported operation") }
func (_ *ArrayStringWrapper) SetFloat(v float32)               { panic("Unsupported operation") }
func (_ *ArrayStringWrapper) SetDouble(v float64)              { panic("Unsupported operation") }
func (_ *ArrayStringWrapper) SetBytes(v []byte)                { panic("Unsupported operation") }
func (_ *ArrayStringWrapper) SetString(v string)               { panic("Unsupported operation") }
func (_ *ArrayStringWrapper) SetUnionElem(v int64)             { panic("Unsupported operation") }
func (_ *ArrayStringWrapper) Get(i int) types.Field            { panic("Unsupported operation") }
func (_ *ArrayStringWrapper) AppendMap(key string) types.Field { panic("Unsupported operation") }
func (_ *ArrayStringWrapper) Finalize()                        {}
func (_ *ArrayStringWrapper) SetDefault(i int)                 { panic("Unsupported operation") }
func (r *ArrayStringWrapper) NullField(i int) {
	panic("Unsupported operation")
}

func (r *ArrayStringWrapper) AppendArray() types.Field {
	var v string

	*r.Target = append(*r.Target, v)
	return &types.String{Target: &(*r.Target)[len(*r.Target)-1]}
}


text:
PEGASUS_USING_STD;

PEGASUS_NAMESPACE_BEGIN

////////////////////////////////////////////////////////////////////////////////
//
// CGIQueryString:
//   This file provides the methods for the CIGQuery String class that
//   parse a CGI query string of the following form:
//
//     NameSpace=root%2Fcimv2&ClassName=&LocalOnly=true
//
////////////////////////////////////////////////////////////////////////////////

static void _ExpandCGIQueryValue(char* value)
{
    // Look for '%' characters followed by hex codes:

    for (char* p = value; *p; p++)
    {
	if (*p == '%')
	{
	    char hexString[3];
	    sprintf(hexString, "%*.*s", 2, 2, p + 1);
	    char* end = 0;
	    long tmp = strtol(hexString, &end, 16);

	    if (*end)
		throw BadlyFormedCGIQueryString();

            *p = char(tmp);
#ifdef PEGASUS_HAVE_EBCDIC
            __atoe_l(p,1);
#endif
            p++;
	    memcpy(p, p + 2, strlen(p) - 2 + 1);
	    // CORRECTION, KS. Add decrement. corrects problem with succesive
	    //             % sequences
	    p--;

	}
	else if (*p == '+')
	    *p = ' ';
    }
}

void CGIQueryString::_parseCGIQueryString(
    char* queryString,
    Array<CGIQueryStringEntry>& entries)
{
    // First split about the '&' characters:

#if defined(PEGASUS_OS_SOLARIS) || \
    defined(PEGASUS_OS_HPUX) || \
    defined(PEGASUS_OS_LINUX)
    char *last;
    for (char* p = strtok_r(queryString, "&", &last); p;
         p = strtok_r(NULL, "&", &last))
#else
    for (char* p = strtok(queryString, "&"); p; p = strtok(NULL, "&"))
#endif
    {
	char* name = p;

	// Find equal sign:
	char* equalChar = strchr(p, '=');

	if (!equalChar)
	    throw BadlyFormedCGIQueryString();

	*equalChar++ = '\0';

	char* value = equalChar;

	_ExpandCGIQueryValue(value);

	// cout << "name=[" << name << "]" << endl;
	// cout << "value=[" << value << "]" << endl;

	CGIQueryStringEntry entry = { name, value };
	entries.append(entry);
    }
}

CGIQueryString::CGIQueryString(char* queryString)
{
    _parseCGIQueryString(queryString, _entries);
}

const char* CGIQueryString::findValue(const char* name) const
{
    for (Uint32 i = 0, n = _entries.size(); i < n; i++)
    {
	if (strcmp(_entries[i].name, name) == 0)
	    return _entries[i].value;
    }

    return 0;
}

PEGASUS_NAMESPACE_END


text:
class Countdown {
public:
    Countdown();

	void setup();
	void update();
	void draw();
    void start(float duration);
    void stop();

    bool isComplete();

    float progress;
    ofEvent<int> countdownCompleteEvent;
    float startTime;
    float countdownDuration;

protected:
    bool enabled;
    ofxTween tween;
    ofxEasingLinear easinglinear;

private:

};


text:
package BehaviorTests;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

class TestUtils {
    public static File getImageFile() {
        return rezFile("/image.jpg");
    }

    public static File rezFile(String name) {
        try {
            return new File(MockServer.class.getResource(name).toURI());
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] getFileBytes(String s) {
        try {
            final InputStream stream = new FileInputStream(rezFile(s));
            final byte[] bytes = new byte[stream.available()];
            stream.read(bytes);
            stream.close();
            return bytes;
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

    public static <K, V> Map<K, V> mapOf(Object... keyValues) {
        Map<K, V> map = new HashMap<>();

        K key = null;
        for (int index = 0; index < keyValues.length; index++) {
            if (index % 2 == 0) {
                key = (K)keyValues[index];
            }
            else {
                map.put(key, (V)keyValues[index]);
            }
        }

        return map;
    }
}


text:
<?php

/**
 * Monolog error handler
 *
 * A facility to enable logging of runtime errors, exceptions and fatal errors.
 *
 * Quick setup: ErrorHandler::register($logger);
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class Monolog_ErrorHandler
{
    private $logger;

    private $previousExceptionHandler;
    private $uncaughtExceptionLevel;

    private $previousErrorHandler;
    private $errorLevelMap;

    private $fatalLevel;
    private $reservedMemory;
    private static $fatalErrors = array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR);

    public function __construct(Monolog_Psr_LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * Registers a new ErrorHandler for a given Logger
     *
     * By default it will handle errors, exceptions and fatal errors
     *
     * @param  Monolog_Psr_LoggerInterface $logger
     * @param  array|false                 $errorLevelMap  an array of E_* constant to LogLevel::* constant mapping, or false to disable error handling
     * @param  int|false                   $exceptionLevel a LogLevel::* constant, or false to disable exception handling
     * @param  int|false                   $fatalLevel     a LogLevel::* constant, or false to disable fatal error handling
     *
     * @return Monolog_ErrorHandler
     */
    public static function register(Monolog_Psr_LoggerInterface $logger, $errorLevelMap = array(), $exceptionLevel = null, $fatalLevel = null)
    {
        $handler = new self($logger);
        if ($errorLevelMap !== false) {
            $handler->registerErrorHandler($errorLevelMap);
        }
        if ($exceptionLevel !== false) {
            $handler->registerExceptionHandler($exceptionLevel);
        }
        if ($fatalLevel !== false) {
            $handler->registerFatalHandler($fatalLevel);
        }

        return $handler;
    }

    public function registerExceptionHandler($level = null, $callPrevious = true)
    {
        $prev                         = set_exception_handler(array($this, 'handleException'));
        $this->uncaughtExceptionLevel = $level;
        if ($callPrevious && $prev) {
            $this->previousExceptionHandler = $prev;
        }
    }

    public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
    {
        $prev                = set_error_handler(array($this, 'handleError'), $errorTypes);
        $this->errorLevelMap = $this->arrayReplace($this->defaultErrorLevelMap(), $levelMap);
        if ($callPrevious) {
            $this->previousErrorHandler = $prev ? $prev : true;
        }
    }

    /**
     * Backport of PHP >=5.3 function array_replace
     *
     * @link http://www.php.net/manual/en/function.array-replace.php#94458
     */
    private function arrayReplace(array $array, array $array1)
    {
        $args  = func_get_args();
        $count = func_num_args();

        for ($i = 0; $i < $count; ++$i) {
            if (is_array($args[$i])) {
                foreach ($args[$i] as $key => $val) {
                    $array[$key] = $val;
                }
            } else {
                trigger_error(
                  __FUNCTION__.'(): Argument #'.($i + 1).' is not an array',
                  E_USER_WARNING
                );

                return null;
            }
        }

        return $array;
    }

    public function registerFatalHandler($level = null, $reservedMemorySize = 20)
    {
        register_shutdown_function(array($this, 'handleFatalError'));

        $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
        $this->fatalLevel     = $level;
    }

    protected function defaultErrorLevelMap()
    {
        $map = array(
            E_ERROR             => Monolog_Psr_LogLevel::CRITICAL,
            E_WARNING           => Monolog_Psr_LogLevel::WARNING,
            E_PARSE             => Monolog_Psr_LogLevel::ALERT,
            E_NOTICE            => Monolog_Psr_LogLevel::NOTICE,
            E_CORE_ERROR        => Monolog_Psr_LogLevel::CRITICAL,
            E_CORE_WARNING      => Monolog_Psr_LogLevel::WARNING,
            E_COMPILE_ERROR     => Monolog_Psr_LogLevel::ALERT,
            E_COMPILE_WARNING   => Monolog_Psr_LogLevel::WARNING,
            E_USER_ERROR        => Monolog_Psr_LogLevel::ERROR,
            E_USER_WARNING      => Monolog_Psr_LogLevel::WARNING,
            E_USER_NOTICE       => Monolog_Psr_LogLevel::NOTICE,
            E_STRICT            => Monolog_Psr_LogLevel::NOTICE,
            E_RECOVERABLE_ERROR => Monolog_Psr_LogLevel::ERROR,
        );

        if (version_compare(PHP_VERSION, '5.3', '>=')) {
            $map[E_USER_DEPRECATED] = Monolog_Psr_LogLevel::NOTICE;
            $map[E_DEPRECATED]      = Monolog_Psr_LogLevel::NOTICE;
        }

        return $map;
    }

    /**
     * @private
     */
    public function handleException(Exception $e)
    {
        $this->logger->log(
          $this->uncaughtExceptionLevel === null ? Monolog_Psr_LogLevel::ERROR : $this->uncaughtExceptionLevel,
          'Uncaught exception',
          array('exception' => $e)
        );

        if ($this->previousExceptionHandler) {
            call_user_func($this->previousExceptionHandler, $e);
        }
    }

    /**
     * @private
     */
    public function handleError($code, $message, $file = '', $line = 0, $context = array())
    {
        if (!(error_reporting() & $code)) {
            return;
        }

        $level = isset($this->errorLevelMap[$code]) ? $this->errorLevelMap[$code] : Monolog_Psr_LogLevel::CRITICAL;
        $this->logger->log($level, self::codeToString($code).': '.$message, array('file' => $file, 'line' => $line));

        if ($this->previousErrorHandler === true) {
            return false;
        } elseif ($this->previousErrorHandler) {
            return call_user_func($this->previousErrorHandler, $code, $message, $file, $line, $context);
        }
    }

    /**
     * @private
     */
    public function handleFatalError()
    {
        $this->reservedMemory = null;

        $lastError = error_get_last();
        if ($lastError && in_array($lastError['type'], self::$fatalErrors)) {
            $this->logger->log(
              $this->fatalLevel === null ? Monolog_Psr_LogLevel::ALERT : $this->fatalLevel,
              'Fatal Error ('.self::codeToString($lastError['type']).'): '.$lastError['message'],
              array('file' => $lastError['file'], 'line' => $lastError['line'])
            );
        }
    }

    private static function codeToString($code)
    {
        switch ($code) {
            case E_ERROR:
                return 'E_ERROR';
            case E_WARNING:
                return 'E_WARNING';
            case E_PARSE:
                return 'E_PARSE';
            case E_NOTICE:
                return 'E_NOTICE';
            case E_CORE_ERROR:
                return 'E_CORE_ERROR';
            case E_CORE_WARNING:
                return 'E_CORE_WARNING';
            case E_COMPILE_ERROR:
                return 'E_COMPILE_ERROR';
            case E_COMPILE_WARNING:
                return 'E_COMPILE_WARNING';
            case E_USER_ERROR:
                return 'E_USER_ERROR';
            case E_USER_WARNING:
                return 'E_USER_WARNING';
            case E_USER_NOTICE:
                return 'E_USER_NOTICE';
            case E_STRICT:
                return 'E_STRICT';
            case E_RECOVERABLE_ERROR:
                return 'E_RECOVERABLE_ERROR';
            case E_DEPRECATED:
                return 'E_DEPRECATED';
            case E_USER_DEPRECATED:
                return 'E_USER_DEPRECATED';
        }

        if (version_compare(PHP_VERSION, '5.3', '>=')) {
            switch ($code) {
                case E_DEPRECATED:
                    return 'E_DEPRECATED';
                case E_USER_DEPRECATED:
                    return 'E_USER_DEPRECATED';
            }
        }

        return 'Unknown PHP error';
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/topLayout"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true">
    <WalletMobile.Droid.CameraSourcePreview
        android:id="@+id/preview"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <WalletMobile.Droid.GraphicOverlay
            android:id="@+id/faceOverlay"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </WalletMobile.Droid.CameraSourcePreview>
</LinearLayout>


text:
struct spi_context;

int spi_read(spi_context*);
int spi_write(spi_context*, int);
spi_context* spi_open(const char*, uint8_t, uint8_t, uint32_t, uint16_t);
void spi_close(spi_context*);

#endif


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

{% block navigation %}

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle naviation Menu
            </button>
            Home

                    Healthy Alternatives

                    Restaurants

{% endblock %}

{% block header %}

Welcome To A New Lifestyle!

Enter a meal below

            <form class="form-inline" style="width: 100%;">

                        <input type="text" class="form-control" id="recipe-entry" placeholder="Meal">

                        <input type="text" style="height: 58px;" class="form-control" id="location-entry" placeholder="Location">

            </form>
            Tell Me More

{% endblock %}

{% block healthy %}

Healthy Alternatives

{% endblock %}

{% block restaurant %}

Restaurants

{% endblock %}

{% block recipe_modal %}

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

Modal title

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

{% endblock %}


text:
package com.angcyo.uiview.net;

import android.os.Environment;

import com.angcyo.github.utilcode.utils.NetworkUtils;
import com.angcyo.library.utils.L;
import com.angcyo.uiview.RApplication;
import com.angcyo.uiview.RCrashHandler;
import com.angcyo.uiview.Root;
import com.angcyo.uiview.net.cookie.CookieJarImpl;
import com.angcyo.uiview.net.cookie.store.PersistentCookieStore;
import com.angcyo.uiview.receiver.NetworkStateReceiver;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Call;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * Created by angcyo on 2016-03-20 23:53.
 */
public class RRetrofit {
    public static final String SERVICE_URL = "http://service.klgwl.com/";
    /**
     * 默认超时时间
     */
    public static final int DEFAULT_TIMEOUT = 20;
    public static String DEBUG_URL = "http://192.168.1.35/";
    public static String RELEASE_URL = "http://api.klgwl.com/";
    public static String BASE_URL = RELEASE_URL;

    //    //切换服务器, 1外网 -1内网
//    public static void switchHttp(int type) {
//        if (type >= 1) {
//            BASE = "http://zan.eeniao.com/";
//            DEBUG_URL = "http://zan.eeniao.com/app/";
//            BASE_IMAGE_URL = "http://zan.eeniao.com/upload/";
//            BASE_LOGO_URL = "http://zan.eeniao.com/static/images/reglogo.png";
//        } else if (type <= -1) {
//            BASE = "http://192.168.1.156:8081/";
//            DEBUG_URL = "http://192.168.1.156:8081/app/";
//            BASE_IMAGE_URL = "http://192.168.1.156:8081/upload/";
//            BASE_LOGO_URL = "http://192.168.1.156:8081/static/images/reglogo.png";
//        }
//        HnUrl.SERVER = DEBUG_URL;
//        HnUrl.FILE_UPLOAD_API = BASE_IMAGE_URL + "index.php";
//    }
    public static boolean DEBUG = L.LOG_DEBUG;

    static {
//        if (DEBUG) {
//            BASE_URL = DEBUG_URL;
//        } else {
//            BASE_URL = RELEASE_URL;
//        }
    }

    public static <T> T create(final Class<T> cls) {
        return create(cls, CacheType.NO_CACHE);
    }

    public static <T> T create(final Class<T> cls, String baseUrl) {
        return create(cls, CacheType.NO_CACHE, baseUrl);
    }

    public static <T> T create(final Class<T> cls, CacheType cacheType) {
        return create(cls, cacheType, BASE_URL);
    }

    public static <T> T create(final Class<T> cls, CacheType cacheType, String baseUrl) {
        Converter.Factory factory = getFactory();

        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(defaultClient(cacheType))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create());

        if (factory != null) {
            builder.addConverterFactory(factory);
        }

//        builder.addConverterFactory(ScalarsConverterFactory.create());

        try {
            saveToSDCard(cls.getSimpleName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        Retrofit retrofit = builder.build();
        return retrofit.create(cls);
    }

    private static Converter.Factory getFactory() {
        Converter.Factory gsonFactory = checkFactory("retrofit2.converter.gson.GsonConverterFactory");
        Converter.Factory jacksonFactory = checkFactory("retrofit2.converter.jackson.JacksonConverterFactory");

        //优先使用jackson
        if (jacksonFactory != null) {
            return jacksonFactory;
        }
        return gsonFactory;
    }

    private static Converter.Factory checkFactory(String className) {
        Converter.Factory factory = null;
        try {
            final Class<?> factoryName = Class.forName(className);
            final Method create = factoryName.getMethod("create");
            factory = (Converter.Factory) create.invoke(null);
        } catch (Exception e) {
        }
        return factory;
    }

    private static OkHttpClient defaultClient(CacheType cacheType) {
        // create an instance of OkLogInterceptor using a builder()
//        OkLogInterceptor okLogInterceptor;
//        OkLogInterceptor.Builder builder = OkLogInterceptor.builder();

//        builder.setBaseUrl(DEBUG_URL);
//        builder.useAndroidLog(false);

//        if (DEBUG) {
//            okLogInterceptor = builder.withAllLogData().build();
//        } else {
//            okLogInterceptor = builder.withNoLogData().build();
//        }

        // create an instance of OkHttpClient builder
        OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();

        //缓存支持,okhttp只会对get请求进行缓存,post请求是不会进行缓存
        okHttpBuilder
                .addInterceptor(new CacheInterceptor(false))
                .addNetworkInterceptor(new CacheInterceptor(DEBUG, cacheType))
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .cache(new Cache(new File(RApplication.getApp().getCacheDir(), "ok_cache"), 10240 * 1024))
        ;

        // add OkLogInterceptor to OkHttpClient's application interceptors
        // okHttpBuilder.addInterceptor(okLogInterceptor);

        okHttpBuilder.cookieJar(new CookieJarImpl(new PersistentCookieStore(RApplication.getApp())));

        //okHttpBuilder.cache()
        // build
        OkHttpClient okHttpClient = okHttpBuilder.build();

        return okHttpClient;
    }

    public static void cancelTag(Object tag) {
        for (Call call : defaultClient(CacheType.NO_CACHE).dispatcher().queuedCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
        for (Call call : defaultClient(CacheType.NO_CACHE).dispatcher().runningCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
    }

    /**
     * 追加数据到文件
     */
    public static void saveToSDCard(String data) throws Exception {
        String saveFolder = Environment.getExternalStorageDirectory().getAbsoluteFile() +
                File.separator + Root.APP_FOLDER + File.separator + "log";
        File folder = new File(saveFolder);
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                return;
            }
        }
        String dataTime = RCrashHandler.getDataTime("yyyy-MM-dd_HH-mm-ss-SSS");
        File file = new File(saveFolder, /*dataTime + */"RRetrofit.log");
        boolean append = true;
        if (file.length() > 1024 * 1024 * 10 /*大于10MB重写*/) {
            append = false;
        }
        PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file, append)));
        pw.print(dataTime);
        pw.print(":");
        pw.print(data);
        // 导出手机信息
        pw.println();
        pw.close();
    }

    public enum CacheType {
        /**
         * 在OKHttp开发中我们常见到的有下面几个:
         * max-age     缓存多长时间, 超过时间才请求
         * no-cache
         * max-stale   在这个时长之内的请求, 使用缓存.
         */
        NO_CACHE, MAX_AGE, MAX_STALE
    }

    /**
     * 如果服务器返回的Response不包含Header:Cache-Control, max-age=xxx,缓存控制, 就需要手动修改
     * <p>
     * max-age:这个参数告诉浏览器将页面缓存多长时间,超过这个时间后才再次向服务器发起请求检查页面是否有更新。对于静态的页面,比如图片、CSS、Javascript,一般都不大变更,因此通常我们将存储这些内容的时间设置为较长的时间,这样浏览器会不会向浏览器反复发起请求,也不会去检查是否更新了。
     * s-maxage:这个参数告诉缓存服务器(proxy,如Squid)的缓存页面的时间。如果不单独指定,缓存服务器将使用max-age。对于动态内容(比如文档的查看页面),我们可告诉浏览器很快就过时了(max-age=0),并告诉缓存服务器(Squid)保留内容一段时间(比如,s-maxage=7200)。一旦我们更新文档,我们将告诉Squid清除老的缓存版本。
     * must-revalidate:这告诉浏览器,一旦缓存的内容过期,一定要向服务器询问是否有新版本。
     * proxy-revalidate:proxy上的缓存一旦过期,一定要向服务器询问是否有新版本。
     * no-cache:不做缓存。
     * no-store:数据不在硬盘中临时保存,这对需要保密的内容比较重要。
     * public:告诉缓存服务器, 即便是对于不该缓存的内容也缓存起来,比如当用户已经认证的时候。所有的静态内容(图片、Javascript、CSS等)应该是public的。
     * private:告诉proxy不要缓存,但是浏览器可使用private cache进行缓存。一般登录后的个性化页面是private的。
     * no-transform: 告诉proxy不进行转换,比如告诉手机浏览器不要下载某些图片。
     * max-stale指示客户机可以接收超出超时期间的响应消息。如果指定max-stale消息的值,那么客户机可以接收超出超时期指定值之内的响应消息。
     */
    public static class CacheInterceptor implements Interceptor {

        boolean log;
        CacheType mCacheType;

        public CacheInterceptor(boolean log) {
            this(log, CacheType.NO_CACHE);
        }

        public CacheInterceptor(boolean log, CacheType cacheType) {
            this.log = log;
            mCacheType = cacheType;
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
//            Request request = chain.request();
//            Response response = chain.proceed(request);
//            Response newResponse = response.newBuilder()
//                    .removeHeader("Pragma")
//                    .removeHeader("Cache-Control")
//                    //cache for 30 days
//                    .header("Cache-Control", "public, max-age=" + 3600 * 24 * 30)
//                    .build();
//            if (DEBUG) {
//                L.i("请求URL:" + request.url().url().toString());
//            }

            Request request = chain.request();

            String data = "请求URL:" + request.method() + ":" + request.url().url().toString();
            if (log) {
                L.d(data);
            }

//            if ("GET" == request.method() || "POST" == request.method()) {
//                L.e("开始拦截:" + request.url().url().toString());
//                Response.Builder builder = new Response.Builder();
//                builder.body(ResponseBody.create(MediaType.parse("application/json"), "测试拦截数据"));
//                builder.code(200);
//                builder.message("测试的Message字段");
//                builder.request(request);
//                builder.protocol(Protocol.HTTP_1_1);
//                return builder.build();
//            }

            try {
                saveToSDCard(data);
            } catch (Exception e) {
                e.printStackTrace();
            }

            Request.Builder builder = request.newBuilder();
            if (NetworkStateReceiver.getNetType().value() <=
                    NetworkUtils.NetworkType.NETWORK_NO.value()) {
                //没网络,强制使用缓存
                request = builder
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
                //request = builder.cacheControl(new CacheControl.Builder().noCache().build()).build();
            } else {
                //有网的情况下
                /**
                 * 在OKHttp开发中我们常见到的有下面几个:
                 * max-age     缓存多长时间, 超过时间才请求
                 * no-cache
                 * max-stale   在这个时长之内的请求, 使用缓存.
                 * */
                CacheControl.Builder cacheBuild = new CacheControl.Builder();
                switch (mCacheType) {
                    case MAX_AGE:
                        cacheBuild.maxAge(1, TimeUnit.HOURS);
                        break;
                    case MAX_STALE:
                        cacheBuild.maxAge(1, TimeUnit.MINUTES);
                        break;
                    case NO_CACHE:
                    default:
                        cacheBuild.noCache();
                        break;

                }
                request = builder
                        .cacheControl(cacheBuild.build())
                        .build();
            }

            Response originalResponse = chain.proceed(request);
            if (NetworkStateReceiver.getNetType().value() > NetworkUtils.NetworkType.NETWORK_UNKNOWN.value()) {
                //有网的时候读接口上的@Headers里的配置,你可以在这里进行统一的设置
                String cacheControl = request.cacheControl().toString();
                return originalResponse.newBuilder()
                        .header("Cache-Control", cacheControl)
                        .removeHeader("Pragma")
                        .build();
            } else {
                return originalResponse.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale=2419200")
                        .removeHeader("Pragma")
                        .build();
            }
        }
    }
}


text:
{{<govuk_template}}

{{$pageTitle}}
  GOV.UK prototyping kit
{{/pageTitle}}

{{$head}}
  {{>includes/head}}
  <link href="/public/stylesheets/alphagov-static.css" media="screen" rel="stylesheet" type="text/css" />
  <link href="/public/vendor/leaflet/leaflet.css" media="screen" rel="stylesheet" type="text/css" />
  <link href="/public/stylesheets/property-page-v0.css" media="screen" rel="stylesheet" type="text/css" />
{{/head}}

{{$insideHeader}}
  Search

  <form id="search" class="site-search" action="/search" method="get" role="search">

      Search
      <input type="search" name="q" id="site-search-text" title="Search" class="js-search-focus">
      <input class="submit" type="submit" value="Search" />

  </form>
{{/insideHeader}}

{{$content}}

  {{>digital-register/includes/banner}}

Home

Property and land

Search results

Property details

Property details

            3a Mandela Way

          Southampton

          SO15 5RZ

Property type

Flat

Tenure

Leasehold

Price paid

£188,000 on 3 October 2012

Local council

Southampton City Council

Further information about this property

The Land Registry may have detailed information on this property held in a register of title, including

who the owner is

maps and title plan

rights and restrictions that affect it

View the register of title for 3a Mandela Way

Related properties

3 Mandela Way, terraced house, freehold

        What are related properties?

Related properties are properties contained by, or containing, the property on this page.

For example a leasehold flat is likely to be part of a freehold building which contains other leasehold flats.

{{/content}}

{{$footerTop}}
  {{>property-page/prototype-v1/includes/footer-top}}
{{/footerTop}}

{{$footerSupportLinks}}
  {{>property-page/prototype-v1/includes/footer-support-links}}
{{/footerSupportLinks}}

{{$bodyEnd}}
  {{>includes/scripts}}

{{/bodyEnd}}

{{/govuk_template}}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>PKIXRevocationChecker.Option (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<meta name="keywords" content="java.security.cert.PKIXRevocationChecker.Option class">
<meta name="keywords" content="values()">
<meta name="keywords" content="valueOf()">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

compact1, compact2, compact3

java.security.cert

Enum PKIXRevocationChecker.Option

java.lang.Object

java.lang.Enum<PKIXRevocationChecker.Option>

java.security.cert.PKIXRevocationChecker.Option

All Implemented Interfaces:

Serializable, Comparable<PKIXRevocationChecker.Option>

Enclosing class:

PKIXRevocationChecker

public static enum PKIXRevocationChecker.Option
extends Enum<PKIXRevocationChecker.Option>

Various revocation options that can be specified for the revocation
 checking mechanism.

Enum Constant Summary

Enum Constants

Enum Constant and Description

NO_FALLBACK

Disable the fallback mechanism.

ONLY_END_ENTITY

Only check the revocation status of end-entity certificates.

PREFER_CRLS

Prefer CRLs to OSCP.

SOFT_FAIL

Allow revocation check to succeed if the revocation status cannot be
 determined for one of the following reasons:

  The CRL or OCSP response cannot be obtained because of a
      network error.

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static PKIXRevocationChecker.Option
valueOf(String name)

Returns the enum constant of this type with the specified name.

static PKIXRevocationChecker.Option[]
values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

ONLY_END_ENTITY

public static final PKIXRevocationChecker.Option ONLY_END_ENTITY

Only check the revocation status of end-entity certificates.

PREFER_CRLS

public static final PKIXRevocationChecker.Option PREFER_CRLS

Prefer CRLs to OSCP. The default behavior is to prefer OCSP. Each
 PKIX implementation should document further details of their
 specific preference rules and fallback policies.

NO_FALLBACK

public static final PKIXRevocationChecker.Option NO_FALLBACK

Disable the fallback mechanism.

SOFT_FAIL

public static final PKIXRevocationChecker.Option SOFT_FAIL

Allow revocation check to succeed if the revocation status cannot be
 determined for one of the following reasons:

The CRL or OCSP response cannot be obtained because of a
      network error.

The OCSP responder returns one of the following errors
      specified in section 2.3 of RFC 2560: internalError or tryLater.

 Note that these conditions apply to both OCSP and CRLs, and unless
 the NO_FALLBACK option is set, the revocation check is
 allowed to succeed only if both mechanisms fail under one of the
 conditions as stated above.
 Exceptions that cause the network errors are ignored but can be
 later retrieved by calling the
 getSoftFailExceptions method.

Method Detail

values

public static PKIXRevocationChecker.Option[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (PKIXRevocationChecker.Option c : PKIXRevocationChecker.Option.values())
    System.out.println(c);

Returns:

an array containing the constants of this enum type, in the order they are declared

valueOf

public static PKIXRevocationChecker.Option valueOf(String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:

name - the name of the enum constant to be returned.

Returns:

the enum constant with the specified name

Throws:

IllegalArgumentException - if this enum type has no constant with the specified name

NullPointerException - if the argument is null

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
assassins
=========

Simulate a game of Assassins--inspired by a recent game at an int'l school.

    bundle install
    ruby ./assassins.rb

Options:
* --die, -d:   Whether to die after init
* --count, -c [i]:   The number of players (default: 8)
* --path, -p [s]:   The path to the names file (default: ./assassins.txt)
* --shuffle-factor, -s [i]:   The chance of a random re-matchup (default: 10)
* --brightness, -b [f]:   The brightness of the name colors (default: 1.5)
* --no-color, -n:   If your eyes are bleeding enough
* --help, -h:   Show this message

(Thanks, Trollop.)


text:
PYTHONIC_NS_BEGIN

namespace operator_
{
  template <class A, class B>
  auto imax(A &&a, B &&b) -> typename std::enable_if<
      std::is_const<A>::value || !std::is_assignable<A, B>::value,
      decltype(numpy::functor::maximum{}(std::forward<A>(a),
                                         std::forward<B>(b)))>::type;

  template <class A, class B>
  auto imax(A &&a, B &&b) -> typename std::enable_if<
      !std::is_const<A>::value && std::is_assignable<A, B>::value,
      decltype(a = numpy::functor::maximum{}(std::forward<A>(a),
                                             std::forward<B>(b)))>::type;

  DEFINE_FUNCTOR(pythonic::operator_, imax);
}
PYTHONIC_NS_END

#endif


text:
import * as assert from 'assert';
import * as dom from 'vs/base/browser/dom';
import { generateUuid } from 'vs/base/common/uuid';
import { appendStylizedStringToContainer, handleANSIOutput } from 'vs/workbench/contrib/debug/browser/debugANSIHandling';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { workbenchInstantiationService } from 'vs/workbench/test/workbenchTestServices';
import { LinkDetector } from 'vs/workbench/contrib/debug/browser/linkDetector';

suite('Debug - ANSI Handling', () => {

	let linkDetector: LinkDetector;

	/**
	 * Instantiate a {@link LinkDetector} for use by the functions being tested.
	 */
	setup(() => {
		const instantiationService: TestInstantiationService = <TestInstantiationService>workbenchInstantiationService();
		linkDetector = instantiationService.createInstance(LinkDetector);
	});

	test('appendStylizedStringToContainer', () => {
		const root: HTMLSpanElement = document.createElement('span');
		let child: Node;

		assert.equal(0, root.children.length);

		appendStylizedStringToContainer(root, 'content1', ['class1', 'class2'], linkDetector);
		appendStylizedStringToContainer(root, 'content2', ['class2', 'class3'], linkDetector);

		assert.equal(2, root.children.length);

		child = root.firstChild!;
		if (child instanceof HTMLSpanElement) {
			assert.equal('content1', child.textContent);
			assert(dom.hasClass(child, 'class1'));
			assert(dom.hasClass(child, 'class2'));
		} else {
			assert.fail('Unexpected assertion error');
		}

		child = root.lastChild!;
		if (child instanceof HTMLSpanElement) {
			assert.equal('content2', child.textContent);
			assert(dom.hasClass(child, 'class2'));
			assert(dom.hasClass(child, 'class3'));
		} else {
			assert.fail('Unexpected assertion error');
		}
	});

	/**
	 * Apply an ANSI sequence to {@link #getSequenceOutput}.
	 *
	 * @param sequence The ANSI sequence to stylize.
	 * @returns An {@link HTMLSpanElement} that contains the stylized text.
	 */
	function getSequenceOutput(sequence: string): HTMLSpanElement {
		const root: HTMLSpanElement = handleANSIOutput(sequence, linkDetector);
		assert.equal(1, root.children.length);
		const child: Node = root.lastChild!;
		if (child instanceof HTMLSpanElement) {
			return child;
		} else {
			assert.fail('Unexpected assertion error');
			return null!;
		}
	}

	/**
	 * Assert that a given ANSI sequence maintains added content following the ANSI code, and that
	 * the provided {@param assertion} passes.
	 *
	 * @param sequence The ANSI sequence to verify. The provided sequence should contain ANSI codes
	 * only, and should not include actual text content as it is provided by this function.
	 * @param assertion The function used to verify the output.
	 */
	function assertSingleSequenceElement(sequence: string, assertion: (child: HTMLSpanElement) => void): void {
		const child: HTMLSpanElement = getSequenceOutput(sequence + 'content');
		assert.equal('content', child.textContent);
		assertion(child);
	}

	test('Expected single sequence operation', () => {

		// Bold code
		assertSingleSequenceElement('\x1b[1m', (child) => {
			assert(dom.hasClass(child, 'code-bold'));
		});

		// Underline code
		assertSingleSequenceElement('\x1b[4m', (child) => {
			assert(dom.hasClass(child, 'code-underline'));
		});

		for (let i = 30; i <= 37; i++) {
			const style: string = 'code-foreground-' + i;

			// Foreground colour codes
			assertSingleSequenceElement('\x1b[' + i + 'm', (child) => {
				assert(dom.hasClass(child, style));
			});

			// Cancellation code removes colour code
			assertSingleSequenceElement('\x1b[' + i + ';39m', (child) => {
				assert(dom.hasClass(child, style) === false);
			});
		}

		for (let i = 40; i <= 47; i++) {
			const style: string = 'code-background-' + i;

			// Foreground colour codes
			assertSingleSequenceElement('\x1b[' + i + 'm', (child) => {
				assert(dom.hasClass(child, style));
			});

			// Cancellation code removes colour code
			assertSingleSequenceElement('\x1b[' + i + ';49m', (child) => {
				assert(dom.hasClass(child, style) === false);
			});
		}

		// Codes do not interfere
		assertSingleSequenceElement('\x1b[1;4;30;31;32;33;34;35;36;37m', (child) => {
			assert.equal(10, child.classList.length);

			assert(dom.hasClass(child, 'code-bold'));
			assert(dom.hasClass(child, 'code-underline'));
			for (let i = 30; i <= 37; i++) {
				assert(dom.hasClass(child, 'code-foreground-' + i));
			}
		});

		// Duplicate codes do not change output
		assertSingleSequenceElement('\x1b[1;1;4;1;4;4;1;4m', (child) => {
			assert(dom.hasClass(child, 'code-bold'));
			assert(dom.hasClass(child, 'code-underline'));
		});

		// Extra terminating semicolon does not change output
		assertSingleSequenceElement('\x1b[1;4;m', (child) => {
			assert(dom.hasClass(child, 'code-bold'));
			assert(dom.hasClass(child, 'code-underline'));
		});

		// Cancellation code removes multiple codes
		assertSingleSequenceElement('\x1b[1;4;30;41;32;43;34;45;36;47;0m', (child) => {
			assert.equal(0, child.classList.length);
		});

	});

	/**
	 * Assert that a given ANSI sequence produces the expected number of {@link HTMLSpanElement} children. For
	 * each child, run the provided assertion.
	 *
	 * @param sequence The ANSI sequence to verify.
	 * @param assertions A set of assertions to run on the resulting children.
	 */
	function assertMultipleSequenceElements(sequence: string, assertions: Array<(child: HTMLSpanElement) => void>): void {
		const root: HTMLSpanElement = handleANSIOutput(sequence, linkDetector);
		assert.equal(assertions.length, root.children.length);
		for (let i = 0; i < assertions.length; i++) {
			const child: Node = root.children[i];
			if (child instanceof HTMLSpanElement) {
				assertions[i](child);
			} else {
				assert.fail('Unexpected assertion error');
			}
		}
	}

	test('Expected multiple sequence operation', () => {

		// Multiple codes affect the same text
		assertSingleSequenceElement('\x1b[1m\x1b[4m\x1b[32m', (child) => {
			assert(dom.hasClass(child, 'code-bold'));
			assert(dom.hasClass(child, 'code-underline'));
			assert(dom.hasClass(child, 'code-foreground-32'));
		});

		// Consecutive codes do not affect previous ones
		assertMultipleSequenceElements('\x1b[1mbold\x1b[32mgreen\x1b[4munderline\x1b[0mnothing', [
			(bold) => {
				assert.equal(1, bold.classList.length);
				assert(dom.hasClass(bold, 'code-bold'));
			},
			(green) => {
				assert.equal(2, green.classList.length);
				assert(dom.hasClass(green, 'code-bold'));
				assert(dom.hasClass(green, 'code-foreground-32'));
			},
			(underline) => {
				assert.equal(3, underline.classList.length);
				assert(dom.hasClass(underline, 'code-bold'));
				assert(dom.hasClass(underline, 'code-foreground-32'));
				assert(dom.hasClass(underline, 'code-underline'));
			},
			(nothing) => {
				assert.equal(0, nothing.classList.length);
			},
		]);

	});

	/**
	 * Assert that the provided ANSI sequence exactly matches the text content of the resulting
	 * {@link HTMLSpanElement}.
	 *
	 * @param sequence The ANSI sequence to verify.
	 */
	function assertSequenceEqualToContent(sequence: string): void {
		const child: HTMLSpanElement = getSequenceOutput(sequence);
		assert(child.textContent === sequence);
	}

	test('Invalid codes treated as regular text', () => {

		// Individual components of ANSI code start are printed
		assertSequenceEqualToContent('\x1b');
		assertSequenceEqualToContent('[');

		// Unsupported sequence prints both characters
		assertSequenceEqualToContent('\x1b[');

		// Random strings are displayed properly
		for (let i = 0; i < 50; i++) {
			const uuid: string = generateUuid();
			assertSequenceEqualToContent(uuid);
		}

	});

	/**
	 * Assert that a given ANSI sequence maintains added content following the ANSI code, and that
	 * the expression itself is thrown away.
	 *
	 * @param sequence The ANSI sequence to verify. The provided sequence should contain ANSI codes
	 * only, and should not include actual text content as it is provided by this function.
	 */
	function assertEmptyOutput(sequence: string) {
		const child: HTMLSpanElement = getSequenceOutput(sequence + 'content');
		assert.equal('content', child.textContent);
		assert.equal(0, child.classList.length);
	}

	test('Empty sequence output', () => {

		const sequences: string[] = [
			// No colour codes
			'',
			'\x1b[;m',
			'\x1b[1;;m',
			'\x1b[m',
			// Unsupported colour codes
			'\x1b[30;50m',
			'\x1b[99m'
		];

		sequences.forEach(sequence => {
			assertEmptyOutput(sequence);
		});

		// Check other possible ANSI terminators
		const terminators: string[] = 'ABCDHIJKfhmpsu'.split('');

		terminators.forEach(terminator => {
			assertEmptyOutput('\x1b[content' + terminator);
		});

	});

});


text:
btwb-specs
==========

Beyond The Whiteboard Specifications


text:
namespace crosapi {

StructuredMetricsServiceAsh::StructuredMetricsServiceAsh() = default;
StructuredMetricsServiceAsh::~StructuredMetricsServiceAsh() = default;

void StructuredMetricsServiceAsh::BindReceiver(
    mojo::PendingReceiver<mojom::StructuredMetricsService> receiver) {
  receivers_.Add(this, std::move(receiver));
}

void StructuredMetricsServiceAsh::Record(
    const std::vector<::metrics::structured::Event>& events) {
  for (const auto& event : events) {
    auto event_base = metrics::structured::EventBase::FromEvent(event);

    // Only record the event if it is valid.
    if (event_base.has_value()) {
      metrics::structured::Recorder::GetInstance()->Record(
          std::move(event_base.value()));
    } else {
      metrics::structured::LogInternalError(
          metrics::structured::StructuredMetricsError::kInvalidEventParsed);
    }
  }
}

}  // namespace crosapi


text:
package com.schemast;

public class SchemastException extends RuntimeException {

    public SchemastException(String msg) {
        super(msg);
    }

    public SchemastException(Throwable t) {
        super(t);
    }
}


text:
<?php declare(strict_types=1);

namespace GraphQL\Validator\Rules;

use GraphQL\Error\Error;
use GraphQL\Language\AST\NodeKind;
use GraphQL\Language\AST\OperationDefinitionNode;
use GraphQL\Language\Visitor;
use GraphQL\Language\VisitorOperation;
use GraphQL\Validator\QueryValidationContext;

class SingleFieldSubscription extends ValidationRule
{
    /**
     * @return array<string, callable>
     */
    public function getVisitor(QueryValidationContext $context): array
    {
        return [
            NodeKind::OPERATION_DEFINITION => static function (OperationDefinitionNode $node) use ($context): VisitorOperation {
                if ($node->operation === 'subscription') {
                    $selections = $node->selectionSet->selections;

                    if (\count($selections) > 1) {
                        $offendingSelections = $selections->splice(1, \count($selections));

                        $context->reportError(new Error(
                            static::multipleFieldsInOperation($node->name->value ?? null),
                            $offendingSelections
                        ));
                    }
                }

                return Visitor::skipNode();
            },
        ];
    }

    public static function multipleFieldsInOperation(?string $operationName): string
    {
        if ($operationName === null) {
            return 'Anonymous Subscription must select only one top level field.';
        }

        return "Subscription \"{$operationName}\" must select only one top level field.";
    }
}