text:
//-------------------------------------------------------------------
// Query Peer - read the ledger / channel
//-------------------------------------------------------------------
var path = require('path');
const _ = require('lodash');

module.exports = function (logger) {
	var common = require(path.join(__dirname, './common.js'))(logger);
	var Peer = require('fabric-client/lib/Peer.js');
	var query_peer = {};

	//-------------------------------------------------------------------
	// Get Block
	//-------------------------------------------------------------------
	/*
		options: {
					block_id: integer - block number
		}
	*/
	query_peer.query_block = function (obj, options, cb) {
		logger.debug('[fcw] Querying Block: ' + options.block_id);
		var channel = obj.channel;

		// send proposal to peer
		channel.queryBlock(Number(options.block_id)).then(
			function (block_resp) {
				if (cb) return cb(null, format_block(block_resp));
			}
		).catch(
			function (err) {
				logger.error('[fcw] Error in query block', typeof err, err);
				var formatted = common.format_error_msg(err);

				if (cb) return cb(formatted, null);
				else return;
			}
			);
	};

	//-------------------------------------------------------------------
	// Get Channel Stats
	//-------------------------------------------------------------------
	/*
		options: {}
	*/
	query_peer.query_channel = function (obj, options, cb) {
		logger.debug('[fcw] Querying Channel Stats');
		var channel = obj.channel;

		// send proposal to peer
		channel.queryInfo().then(
			function (chain_resp) {
				chain_resp.currentBlockHash = buffer2hexStr(chain_resp.currentBlockHash.buffer);
				chain_resp.previousBlockHash = buffer2hexStr(chain_resp.previousBlockHash.buffer);
				if (cb) return cb(null, chain_resp);
			}
		).catch(
			function (err) {
				logger.error('[fcw] Error in query block', typeof err, err);
				var formatted = common.format_error_msg(err);

				if (cb) return cb(formatted, null);
				else return;
			}
			);
	};

	//-------------------------------------------------------------------
	// Get Channel Members
	//-------------------------------------------------------------------
	/*
		options: {}
	*/
	query_peer.query_channel_members = function (obj, options, cb) {
		console.log('');
		logger.debug('[fcw] Querying Channel Members');
		var channel = obj.channel;

		channel.initialize().then(() => {
			let orgs = channel.getOrganizationUnits();
			if (cb) return cb(null, orgs);
		}).catch(function (err) {
			var formatted = common.format_error_msg(err);
			logger.error('failed to get members', formatted);
			if (cb) return cb(formatted, null);
			else return;
		});
	};

	//-------------------------------------------------------------------
	// Get List of Channels on Peer
	//-------------------------------------------------------------------
	/*
		options: {
			peer_urls: ['array of peer grpc urls'],
			peer_tls_opts: {
				pem: 'complete tls certificate',									<required if using ssl>
				ssl-target-name-override: 'common name used in pem certificate' 	<required if using ssl>
				grpc.keepalive_time_ms: <integer in milliseconds>,					<optional>
				grpc.keepalive_timeout_ms: <integer in milliseconds>				<optional>
			}
		}
	*/
	query_peer.query_list_channels = function (obj, options, cb) {
		console.log('');
		logger.debug('List Channels:', options);
		var client = obj.client;

		// send proposal to peer
		client.queryChannels(
			new Peer(options.peer_urls[0], options.peer_tls_opts)
		).then(function (resp) {
			resp.channels = _.sortBy(resp.channels, [channel => channel.channel_id]);
			if (cb) return cb(null, resp);
		}).catch(function (err) {
			logger.error('[fcw] Error in query block', typeof err, err);

			if (cb) return cb(err, null);
			else return;
		});
	};

	//format from byte array to hex string
	function buffer2hexStr(byteArray) {
		return byteArray.map(function (byte) {
			return ('0' + byte.toString(16)).slice(-2);
		}).join('');
	}

	// Format the Block
	// I don't have the slightest idea if this will hold up, seems ok for marbles =/
	function format_block(data, blockNumber) {
		var ret = {
			parsed: {
				block_id: data.header.number.low,
				data_count: data.data.data.length,
				metadata_count: data.metadata.metadata.length,
				txs: []
			},
			orig_data: data
		};
		data.blockNumber = blockNumber;								//copy it

		try {
			var tx = '';

			// -- move though the block data! -- //
			for (var i in ret.orig_data.data.data) {				//iter through transactions
				try {
					tx = {
						tx_id: ret.orig_data.data.data[i].payload.header.channel_header.tx_id,
						instantiate: parse_if_instantiate(ret.orig_data.data.data[i].payload.data),
						channel_id: ret.orig_data.data.data[i].payload.header.channel_header.channel_id,
						chaincode_id: parse_4_chaincode_id(ret.orig_data.data.data[i].payload.data),
						timestamp: Date.parse(ret.orig_data.data.data[i].payload.header.channel_header.timestamp),
						creator_msp_id: parse_4_msp_id(ret.orig_data.data.data[i].payload.data),
						endorsements: parse_4_endorsements(ret.orig_data.data.data[i].payload.data),
						write_set: parse_4_write_set(ret.orig_data.data.data[i].payload.data),
					};
				}
				catch (e) {
					logger.warn('error in removing buffers - this does not matter', e);
				}

				// -- parse for parameters -- //
				var temp = stupid_parse(ret.orig_data.data.data[i].payload.data, tx.chaincode_id);
				tx.params = temp.parameters;
				tx.params_debug = temp.debug;
				ret.parsed.txs.push(tx);
			}
		}
		catch (e) {
			logger.warn('error in parsing data - this may matter', e);
		}

		// -- DONE -- //
		delete ret.orig_data;
		return ret;
	}

	// get msp id from header.creator
	function parse_4_msp_id(data) {
		try {
			return data.actions[0].header.creator.Mspid;
		} catch (e) {
			if (data.blockNumber >= 0) logger.warn('could not find msp id in tx payload', e);		//don't worry about genesis block
			return '-';
		}
	}

	// get chaincode id from rwset
	function parse_if_instantiate(data) {
		try {
			for (var i in data.actions[0].payload.action.proposal_response_payload.extension.results.ns_rwset) {
				if (data.actions[0].payload.action.proposal_response_payload.extension.results.ns_rwset[i].namespace === 'lscc') {	//skip system chaincode
					if (data.actions[0].payload.action.proposal_response_payload.extension.results.ns_rwset[i].rwset.reads[0].version) {
						return false;
					} else {
						return true;
					}
				}
			}
		} catch (e) {
			return false;
		}
	}

	// get chaincode id from rwset
	function parse_4_chaincode_id(data) {
		try {
			for (var i in data.actions[0].payload.action.proposal_response_payload.extension.results.ns_rwset) {
				if (data.actions[0].payload.action.proposal_response_payload.extension.results.ns_rwset[i].namespace !== 'lscc') {	//skip system chaincode
					return data.actions[0].payload.action.proposal_response_payload.extension.results.ns_rwset[i].namespace;
				}
			}
		} catch (e) {
			if (data.blockNumber >= 0) logger.warn('could not find chaincode id in tx payload', e);
			return '-';
		}
	}

	// get array of endorsements for transaction
	function parse_4_endorsements(data) {
		var msp_ids = [];
		try {
			for (var i in data.actions[0].payload.action.endorsements) {
				msp_ids.push(data.actions[0].payload.action.endorsements[i].endorser.Mspid);
			}
		} catch (e) {
			if (data.blockNumber >= 0) logger.warn('could not find endorsements for tx', e);
		}
		return msp_ids;
	}

	// get the chaincode's write set to the ledger
	function parse_4_write_set(data) {
		try {
			for (var i in data.actions[0].payload.action.proposal_response_payload.extension.results.ns_rwset) {
				if (data.actions[0].payload.action.proposal_response_payload.extension.results.ns_rwset[i].namespace !== 'lscc') {	//skip system chaincode
					return data.actions[0].payload.action.proposal_response_payload.extension.results.ns_rwset[i].rwset.writes;
				}
			}
		} catch (e) {
			if (data.blockNumber >= 0) logger.warn('could not find chaincode id in tx payload', e);
			return [];
		}
	}

	// parse the block object to format for humans - get input parameters for tx
	function stupid_parse(data, chaincodeId) {
		var ret = { debug: {}, parameters: [] };
		var str = null;

		try {
			str = data.actions[0].payload.chaincode_proposal_payload.input.toString();
			ret.debug.original = str;
		} catch (e) {
			logger.warn('no tx data to parse for this block... might be okay');
			return ret;
		}

		// break up string
		try {
			ret.debug.startPos = str.indexOf(chaincodeId);						//dumb detection
			ret.debug.str = str.substr(ret.debug.startPos + chaincodeId.length);
			ret.debug.stopPos = ret.debug.str.indexOf('\u0012');				//this is likely to break
			if (ret.debug.stopPos > 0) ret.debug.finalStr = ret.debug.str.substr(0, ret.debug.stopPos);
			else ret.debug.finalStr = ret.debug.str;
		} catch (e) {
			logger.warn('error parsing string in stupid parse...', e);
		}

		var word = '';
		if (!ret.debug.finalStr) {
			logger.error('parsing block data finalStr is undefined...');
			ret.parameters.push('undefined');
		}
		else if (ret.debug.finalStr.length > 5000) {						//if its suspiciously long, don't process, self preservation
			logger.warn('parsing block data finalStr is too large, skipping', ret.debug.finalStr.length);
			ret.parameters.push('too long to show');
		} else {
			for (var i in ret.debug.finalStr) {								//filter out gibberish
				if (ret.debug.finalStr.charCodeAt(i) >= 32 && ret.debug.finalStr.charCodeAt(i) <= 126) {
					word += ret.debug.finalStr[i];
				}
				else {
					if (word.length > 0) {									//end of word, push it
						ret.parameters.push(word);
					}
					word = '';
				}
			}
			if (word.length > 0) {											//end of word (also its the last word), push it
				ret.parameters.push(word);
			}
		}

		return ret;
	}

	//-------------------------------------------------------------------
	// Get Installed Chaincodes
	//-------------------------------------------------------------------
	/*
		options: {
					peer_urls: [array of peer urls],
					peer_tls_opts: {
						pem: 'complete tls certificate',									<required if using ssl>
						ssl-target-name-override: 'common name used in pem certificate' 	<required if using ssl>
						grpc.keepalive_time_ms: <integer in milliseconds>,					<optional>
						grpc.keepalive_timeout_ms: <integer in milliseconds>				<optional>
					}
		}
	*/
	query_peer.query_installed_cc = function (obj, options, cb) {
		logger.debug('[fcw] Querying Installed Chaincodes\n');
		var channel = obj.channel;

		// send proposal to peer
		channel.queryInstalledChaincodes(
			new Peer(options.peer_urls[0], options.peer_tls_opts)
		).then(function (resp) {
			if (cb) return cb(null, resp);
		}).catch(function (err) {
			logger.error('[fcw] Error in query installed chaincode', typeof err, err);
			var formatted = common.format_error_msg(err);

			if (cb) return cb(formatted, null);
			else return;
		});
	};

	//-------------------------------------------------------------------
	// Get Instantiated Chaincodes
	//-------------------------------------------------------------------
	/*
		options: {}
	*/
	query_peer.query_instantiated_cc = function (obj, options, cb) {
		logger.debug('[fcw] Querying Instantiated Chaincodes\n');
		var channel = obj.channel;

		// send proposal to peer
		channel.queryInstantiatedChaincodes().then(function (resp) {
			if (cb) return cb(null, resp);
		}).catch(function (err) {
			logger.error('[fcw] Error in query instantiated chaincodes', typeof err, err);
			var formatted = common.format_error_msg(err);

			if (cb) return cb(formatted, null);
			else return;
		});
	};

	return query_peer;
};


text:
class UsersController < ApplicationController
  def index
    @user = User.find(user_params)
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)

    if @user.save
      log_in(@user)
      redirect_to @user
    else
    end
  end

  def show
  end

end

private
def user_params
  params.require(:user).permit(:username, :password, :email, :name) #d
end

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe Banzai::ObjectRenderer do
  let(:project) { create(:empty_project) }
  let(:user) { project.owner }
  let(:renderer) { described_class.new(project, user, custom_value: 'value') }
  let(:object) { Note.new(note: 'hello', note_html: '
hello
', cached_markdown_version: CacheMarkdownField::CACHE_VERSION) }

  describe '#render' do
    it 'renders and redacts an Array of objects' do
      renderer.render([object], :note)

      expect(object.redacted_note_html).to eq '
hello
'
      expect(object.user_visible_reference_count).to eq 0
    end

    it 'calls Banzai::Redactor to perform redaction' do
      expect_any_instance_of(Banzai::Redactor).to receive(:redact).and_call_original

      renderer.render([object], :note)
    end

    it 'retrieves field content using Banzai.render_field' do
      expect(Banzai).to receive(:render_field).with(object, :note).and_call_original

      renderer.render([object], :note)
    end

    it 'passes context to PostProcessPipeline' do
      another_user = create(:user)
      another_project = create(:empty_project)
      object = Note.new(
        note: 'hello',
        note_html: 'hello',
        author: another_user,
        project: another_project
      )

      expect(Banzai::Pipeline::PostProcessPipeline).to receive(:to_document).with(
        anything,
        hash_including(
          skip_redaction: true,
          current_user: user,
          project: another_project,
          author: another_user,
          custom_value: 'value'
        )
      ).and_call_original

      renderer.render([object], :note)
    end
  end
end


text:
require 'polisher/upstream'

include Polisher

puts Upstream.parse("spec/data/Gemfile")               # => #<Polisher::Gemfile>
puts Upstream.parse("spec/data/rspec-2.12.0.gem")      # => #<Polisher::Gem>
puts Upstream.parse("spec/data/mysql-2.9.1.gemspec")   # => #<Polisher::Gem>

puts Polisher::Gem.local_versions_for('rails')         # => [3.2.13] (corresponding to locally installed versions)


text:
package org.asynchttpclient.providers.grizzly.filters;

import org.asynchttpclient.providers.grizzly.filters.events.SSLSwitchingEvent;
import org.glassfish.grizzly.Connection;
import org.glassfish.grizzly.EmptyCompletionHandler;
import org.glassfish.grizzly.Grizzly;
import org.glassfish.grizzly.IOEvent;
import org.glassfish.grizzly.attributes.Attribute;
import org.glassfish.grizzly.filterchain.FilterChain;
import org.glassfish.grizzly.filterchain.FilterChainContext;
import org.glassfish.grizzly.filterchain.FilterChainEvent;
import org.glassfish.grizzly.filterchain.NextAction;
import org.glassfish.grizzly.ssl.SSLEngineConfigurator;
import org.glassfish.grizzly.ssl.SSLFilter;

import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * SSL Filter that may be present within the FilterChain and may be
 * enabled/disabled by sending the appropriate {@link SSLSwitchingEvent}.
 *
 * @since 2.0
 * @author The Grizzly Team
 */
public final class SwitchingSSLFilter extends SSLFilter {

    private static final Attribute<Boolean> CONNECTION_IS_SECURE =
        Grizzly.DEFAULT_ATTRIBUTE_BUILDER.createAttribute(SwitchingSSLFilter.class.getName());
    private static final Attribute<Throwable> HANDSHAKE_ERROR =
        Grizzly.DEFAULT_ATTRIBUTE_BUILDER.createAttribute(SwitchingSSLFilter.class.getName() + "-HANDSHAKE-ERROR");

    // ------------------------------------------------------------ Constructors

    public SwitchingSSLFilter(final SSLEngineConfigurator clientConfig) {

        super(null, clientConfig);
        addHandshakeListener(new ProtocolHandshakeListener());
    }

    // -------------------------------------------------- Methods from SSLFilter

    @Override
    protected void notifyHandshakeFailed(Connection connection, Throwable t) {
        setError(connection, t);
    }

    @Override
    public NextAction handleConnect(final FilterChainContext ctx) throws IOException {
        // Suspend further handleConnect processing.  We do this to ensure that
        // the SSL handshake has been completed before returning the connection
        // for use in processing user requests.  Additionally, this allows us
        // to determine if a connection is SPDY or HTTP as early as possible.
        ctx.suspend();
        final Connection c = ctx.getConnection();
        handshake(ctx.getConnection(),
                  new EmptyCompletionHandler<SSLEngine>() {
                      @Override
                      public void completed(SSLEngine result) {
                          // Handshake was successful.  Resume the handleConnect
                          // processing.  We pass in Invoke Action so the filter
                          // chain will call handleConnect on the next filter.
                          ctx.resume(ctx.getInvokeAction());
                      }

                      @Override
                      public void cancelled() {
                          // Handshake was cancelled.  Stop the handleConnect
                          // processing.  The exception will be checked and
                          // passed to the user later.
                          setError(c, new SSLHandshakeException(
                                  "Handshake canceled."));
                          ctx.resume(ctx.getStopAction());
                      }

                      @Override
                      public void failed(Throwable throwable) {
                          // Handshake failed.  Stop the handleConnect
                          // processing.  The exception will be checked and
                          // passed to the user later.
                          setError(c, throwable);
                          ctx.resume(ctx.getStopAction());
                      }
                  });

        // This typically isn't advised, however, we need to be able to
        // read the response from the proxy and OP_READ isn't typically
        // enabled on the connection until all of the handleConnect()
        // processing is complete.
        enableRead(c);

        // Tell the FilterChain that we're suspending further handleConnect
        // processing.
        return ctx.getSuspendAction();
    }

    @Override
    public NextAction handleEvent(final FilterChainContext ctx,
                                  final FilterChainEvent event) throws IOException {

        if (event.type() == SSLSwitchingEvent.class) {
            final SSLSwitchingEvent se = (SSLSwitchingEvent) event;
            setSecureStatus(se.getConnection(), se.isSecure());
            return ctx.getStopAction();
        }
        return ctx.getInvokeAction();

    }

    @Override
    public NextAction handleRead(final FilterChainContext ctx) throws IOException {

        if (isSecure(ctx.getConnection())) {
            return super.handleRead(ctx);
        }
        return ctx.getInvokeAction();

    }

    @Override
    public NextAction handleWrite(final FilterChainContext ctx) throws IOException {

        if (isSecure(ctx.getConnection())) {
            return super.handleWrite(ctx);
        }
        return ctx.getInvokeAction();

    }

    @Override
    public void onFilterChainChanged(final FilterChain filterChain) {
        // no-op
    }

    public static Throwable getHandshakeError(final Connection c) {
        return HANDSHAKE_ERROR.remove(c);
    }

    // --------------------------------------------------------- Private Methods

    private static boolean isSecure(final Connection c) {
        Boolean secStatus = CONNECTION_IS_SECURE.get(c);
        return (secStatus == null ? true : secStatus);
    }

    private static void setSecureStatus(final Connection c, final boolean secure) {
        CONNECTION_IS_SECURE.set(c, secure);
    }

    private static void setError(final Connection c, Throwable t) {
        HANDSHAKE_ERROR.set(c, t);
    }

    private static void enableRead(final Connection c) throws IOException {
        c.enableIOEvent(IOEvent.READ);
    }

    // ---------------------------------------------------------- Nested Classes

    private static interface HandshakeCompleteListener {
            void complete();
    }

    private static final class ProtocolHandshakeListener implements HandshakeListener {

        static final ConcurrentHashMap<Connection,HandshakeCompleteListener> listeners =
                new ConcurrentHashMap<Connection,HandshakeCompleteListener>();

        // --------------------------------------- Method from HandshakeListener

        @Override
        public void onStart(Connection connection) {
            // no-op
        }

        @Override
        public void onComplete(Connection connection) {
            final HandshakeCompleteListener listener = listeners.get(connection);
            if (listener != null) {
                removeListener(connection);
                listener.complete();
            }
        }

        // --------------------------------------------- Package Private Methods

        public static void addListener(final Connection c,
                                       final HandshakeCompleteListener listener) {
            listeners.putIfAbsent(c, listener);
        }

        static void removeListener(final Connection c) {
            listeners.remove(c);
        }
    }

}


text:
chrome.browserAction.onClicked.addListener(function(tab) {
    // No tabs or host permissions needed!
    console.log('Crawling ' + tab.url + '...');

    chrome.tabs.executeScript(null, {
        file: "lib/jquery-2.1.1.min.js"
    }, function() {
        chrome.tabs.executeScript(null, {
            file: 'script.js'
        });
    });

});


text:
__author__ = 'dsc'
from bottle import request
import requests
from bin.urlparse import ParseUrl
from bin.protocols import Web
from json import dumps
from bin.orm import Source, SourceFile
from bin.crawler import WebCrawl
from bin.dataobjects import DataObjectManipulation, Debug

class Api():
    def __init__(self, cfg):
        self._uri = 'post'
        self._cfg = cfg

    def postd(self):
        return request.forms

    def post_get(self, name, default=''):
        return request.POST.get(name, default).strip()

    def handle_post(self, data, db=None, database=None):
        if not 'cmd' in data:
            return None

        data = data.dict

        if data['cmd'][0] == 'detecturl' and 'url' in data:
            url = data['url'][0]

            if url.startswith('http') or url.startswith('https') or url.startswith('HTTP') or url.startswith('HTTPS'):

                try:
                    url = ParseUrl(url)
                except:
                    return dumps({'detecturl': 'Could not parse location.'})
                try:
                    res = requests.head(url=url.reluri,verify=False, timeout=2, allow_redirects=False, headers={'User-Agent': self._cfg.get('Crawler', 'default_ua')})
                except Exception as e:
                    return dumps({
                        'detecturl':{
                            'status': 'Status: Error',
                            'auth': '',
                            'textcolor': 'red'
                        }
                    })

                auth = ''
                status = []

                if 'www-authenticate' in res.headers:
                    auth = res.headers['www-authenticate']
                    auth = 'DIGEST' if auth.lower().startswith('digest') else 'BASIC'
                    status.append('Requires: %s' % auth)

                if res.status_code == 200 or res.status_code == 401:
                    status.append('Status: OK')

                    return dumps({
                        'detecturl':{
                            'status': ' - '.join(status),
                            'auth': auth,
                            'textcolor': 'green'
                        }
                    })
                elif res.status_code == 301:
                    return dumps({
                        'detecturl':{
                            'status': 'Status: HTTP redirect encountered (301)',
                            'auth': auth,
                            'textcolor': 'red'
                        }
                    })

        elif data['cmd'][0] == 'get_source_details':
            if not 'source_name' in data:
                return None

            sources = Sources(db, self._cfg)
            sources.get_sources()

            for source in sources.list:
                if source.name == data['source_name'][0]:
                    dom = DataObjectManipulation()
                    source = dom.humanize(source, humansizes=True, humandates=True)
                    source_info = dom.dictionize(source)

                    return {'get_source_details': source_info}

        elif data['cmd'][0] == 'crawlnow' and 'source_name' in data:
            source_name = data['source_name'][0]
            source = db.query(Source).filter_by(name=source_name).first()

            if source:
                webcrawl = WebCrawl(
                    name=source_name,
                    cfg=self._cfg,

                    url = source.crawl_url,
                    ua = source.crawl_useragent,
                    auth_type=source.crawl_authtype,
                    auth_username=source.crawl_username,
                    auth_password=source.crawl_password,
                    crawl_wait=source.crawl_wait,
                    ssl_verify=source.crawl_verifyssl
                )
                res = webcrawl.http()
                if isinstance(res, Debug):
                    return Debug

                database.bulk_add(db, res, source_name)

            return dumps({'crawlnow': {
                'status': 'busy'
            }})
            pass

        return None


text:
using Serilog;
using System;
using VaraniumSharp.Attributes;
using VaraniumSharp.Enumerations;
using VaraniumSharp.Monolith.Interfaces;
using VaraniumSharp.Monolith.Interfaces.Notifications;
using VaraniumSharp.Monolith.Interfaces.Wrappers;

namespace VaraniumSharp.Monolith.Notifications
{
    /// <summary>
    /// Provides ability to easily send Pushover notifications
    /// </summary>
    [AutomaticContainerRegistration(typeof(IPushoverNotifier), ServiceReuse.Singleton)]
    public class PushoverNotifier : IPushoverNotifier
    {
        #region Constructor

        /// <summary>
        /// Parameterless Constructor
        /// </summary>
        public PushoverNotifier(IPushoverWrapper pushoverWrapper)
        {
            _configuration = pushoverWrapper.Configuration;
            IsEnabled = _configuration.IsEnabled;
            _log = Log.Logger.ForContext<PushoverNotifier>();

            if (!_configuration.IsEnabled)
            {
                return;
            }

            _log.Information("Setting up Pushover client");
            _client = pushoverWrapper;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Indicate if the Pushover notifier is enabled
        /// </summary>
        public bool IsEnabled { get; }

        #endregion

        #region Public Methods

        /// <summary>
        /// Send a Pushover notification.
        /// This method will only send a Push if a default send key is provided, if no key is provided the message will be silently dropped and an warning logged
        /// </summary>
        /// <param name="title">Title of the Push</param>
        /// <param name="message">Body text of the Push</param>
        public void SendNotification(string title, string message)
        {
            if (string.IsNullOrEmpty(_configuration.DefaultSendKey))
            {
                _log.Warning("DefaultSendKey is not provided and no send key was provided. Cannot send Push");
                return;
            }
            SendNotification(title, message, string.Empty);
        }

        /// <summary>
        /// Send a Pusover notification.
        /// </summary>
        /// <param name="title">Title of the Push</param>
        /// <param name="message">Body text of the Push</param>
        /// <param name="sendKey">Key of the user or group to send to</param>
        public void SendNotification(string title, string message, string sendKey)
        {
            if (!_configuration.IsEnabled)
            {
                _log.Verbose("Cannot send Push, Pushover is disabled");
                return;
            }

            try
            {
                _client.Push(title, message, sendKey);
                _log.Debug("Push sent");
            }
            catch (Exception exception)
            {
                _log.Error(exception, "An error occured while trying to send a Push");
            }
        }

        #endregion

        #region Variables

        private readonly IPushoverWrapper _client;
        private readonly IPushoverConfiguration _configuration;
        private readonly ILogger _log;

        #endregion
    }
}


text:
/**
 * Provides XML schema implementations of XEP-0084: User Avatar (metadata).
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSchema(namespace = AvatarMetadata.NAMESPACE, elementFormDefault = XmlNsForm.QUALIFIED) package rocks.xmpp.extensions.avatar.model.metadata;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;


text:
package death

import (
	"errors"
	log "github.com/cihub/seelog"
	. "github.com/smartystreets/goconvey/convey"
	"os"
	"syscall"
	"testing"
	"time"
)

type Unhashable map[string]interface{}

func (u Unhashable) Close() error {
	return nil
}

func TestDeath(t *testing.T) {
	defer log.Flush()

	Convey("Validate death handles unhashable types", t, func() {
		u := make(Unhashable)
		death := NewDeath(syscall.SIGTERM)
		syscall.Kill(os.Getpid(), syscall.SIGTERM)
		death.WaitForDeath(u)
	})

	Convey("Validate death happens cleanly", t, func() {
		death := NewDeath(syscall.SIGTERM)
		syscall.Kill(os.Getpid(), syscall.SIGTERM)
		death.WaitForDeath()

	})

	Convey("Validate death happens with other signals", t, func() {
		death := NewDeath(syscall.SIGHUP)
		closeMe := &CloseMe{}
		syscall.Kill(os.Getpid(), syscall.SIGHUP)
		death.WaitForDeath(closeMe)
		So(closeMe.Closed, ShouldEqual, 1)
	})

	Convey("Validate death gives up after timeout", t, func() {
		death := NewDeath(syscall.SIGHUP)
		death.SetTimeout(10 * time.Millisecond)
		neverClose := &neverClose{}
		syscall.Kill(os.Getpid(), syscall.SIGHUP)
		death.WaitForDeath(neverClose)

	})

	Convey("Validate death uses new logger", t, func() {
		death := NewDeath(syscall.SIGHUP)
		closeMe := &CloseMe{}
		logger := &MockLogger{}
		death.SetLogger(logger)

		syscall.Kill(os.Getpid(), syscall.SIGHUP)
		death.WaitForDeath(closeMe)
		So(closeMe.Closed, ShouldEqual, 1)
		So(logger.Logs, ShouldNotBeEmpty)
	})

	Convey("Close multiple things with one that fails the timer", t, func() {
		death := NewDeath(syscall.SIGHUP)
		death.SetTimeout(10 * time.Millisecond)
		neverClose := &neverClose{}
		closeMe := &CloseMe{}
		syscall.Kill(os.Getpid(), syscall.SIGHUP)
		death.WaitForDeath(neverClose, closeMe)
		So(closeMe.Closed, ShouldEqual, 1)
	})

}

type MockLogger struct {
	Logs []interface{}
}

func (l *MockLogger) Info(v ...interface{}) {
	for _, log := range v {
		l.Logs = append(l.Logs, log)
	}
}

func (l *MockLogger) Debug(v ...interface{}) {
	for _, log := range v {
		l.Logs = append(l.Logs, log)
	}
}

func (l *MockLogger) Error(v ...interface{}) error {
	for _, log := range v {
		l.Logs = append(l.Logs, log)
	}
	return nil
}

func (l *MockLogger) Warn(v ...interface{}) error {
	for _, log := range v {
		l.Logs = append(l.Logs, log)
	}
	return nil
}

type neverClose struct {
}

func (n *neverClose) Close() error {
	time.Sleep(2 * time.Minute)
	return nil
}

type CloseMe struct {
	Closed int
}

func (c *CloseMe) Close() error {
	c.Closed++
	return errors.New("I've been closed!")
}


text:
#region Disclaimer/Info

///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at subtext@googlegroups.com
//
// This project is licensed under the BSD license.  See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////

#endregion

using System;
using System.Collections.Generic;

namespace Subtext.Framework.Services.SearchEngine
{
    public class SearchEngineEntry
    {
        public int EntryId { get; set; }
        public string EntryName { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
        public string Tags { get; set; }
        public int BlogId { get; set; }
        public bool IsPublished { get; set; }
        public DateTime PublishDate { get; set; }
        public string BlogName { get; set; }
        public int GroupId { get; set; }
    }
}


text:
package executor

import (
	"context"
	"encoding/base64"
	"fmt"
	"math/rand"
	"sort"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/pingcap/log"
	"github.com/pingcap/parser/ast"
	"github.com/pingcap/parser/mysql"
	"github.com/pingcap/tidb/expression"
	"github.com/pingcap/tidb/expression/aggregation"
	"github.com/pingcap/tidb/planner/core"
	"github.com/pingcap/tidb/planner/property"
	"github.com/pingcap/tidb/planner/util"
	"github.com/pingcap/tidb/sessionctx"
	"github.com/pingcap/tidb/sessionctx/variable"
	"github.com/pingcap/tidb/types"
	"github.com/pingcap/tidb/util/chunk"
	"github.com/pingcap/tidb/util/disk"
	"github.com/pingcap/tidb/util/memory"
	"github.com/pingcap/tidb/util/mock"
	"github.com/pingcap/tidb/util/stringutil"
	"go.uber.org/zap/zapcore"
)

var (
	_          Executor          = &mockDataSource{}
	_          core.PhysicalPlan = &mockDataPhysicalPlan{}
	wideString                   = strings.Repeat("x", 5*1024)
)

type mockDataSourceParameters struct {
	schema      *expression.Schema
	genDataFunc func(row int, typ *types.FieldType) interface{}
	ndvs        []int  // number of distinct values on columns[i] and zero represents no limit
	orders      []bool // columns[i] should be ordered if orders[i] is true
	rows        int    // number of rows the DataSource should output
	ctx         sessionctx.Context
}

type mockDataSource struct {
	baseExecutor
	p        mockDataSourceParameters
	genData  []*chunk.Chunk
	chunks   []*chunk.Chunk
	chunkPtr int
}

type mockDataPhysicalPlan struct {
	MockPhysicalPlan
	schema *expression.Schema
	exec   Executor
}

func (mp *mockDataPhysicalPlan) GetExecutor() Executor {
	return mp.exec
}

func (mp *mockDataPhysicalPlan) Schema() *expression.Schema {
	return mp.schema
}

func (mp *mockDataPhysicalPlan) ExplainID() fmt.Stringer {
	return stringutil.MemoizeStr(func() string {
		return "mockData_0"
	})
}

func (mp *mockDataPhysicalPlan) Stats() *property.StatsInfo {
	return nil
}

func (mp *mockDataPhysicalPlan) SelectBlockOffset() int {
	return 0
}

func (mds *mockDataSource) genColDatums(col int) (results []interface{}) {
	typ := mds.retFieldTypes[col]
	order := false
	if col < len(mds.p.orders) {
		order = mds.p.orders[col]
	}
	rows := mds.p.rows
	NDV := 0
	if col < len(mds.p.ndvs) {
		NDV = mds.p.ndvs[col]
	}
	results = make([]interface{}, 0, rows)
	if NDV == 0 {
		if mds.p.genDataFunc == nil {
			for i := 0; i < rows; i++ {
				results = append(results, mds.randDatum(typ))
			}
		} else {
			for i := 0; i < rows; i++ {
				results = append(results, mds.p.genDataFunc(i, typ))
			}
		}
	} else {
		datumSet := make(map[string]bool, NDV)
		datums := make([]interface{}, 0, NDV)
		for len(datums) < NDV {
			d := mds.randDatum(typ)
			str := fmt.Sprintf("%v", d)
			if datumSet[str] {
				continue
			}
			datumSet[str] = true
			datums = append(datums, d)
		}

		for i := 0; i < rows; i++ {
			results = append(results, datums[rand.Intn(NDV)])
		}
	}

	if order {
		sort.Slice(results, func(i, j int) bool {
			switch typ.Tp {
			case mysql.TypeLong, mysql.TypeLonglong:
				return results[i].(int64) < results[j].(int64)
			case mysql.TypeDouble:
				return results[i].(float64) < results[j].(float64)
			case mysql.TypeVarString:
				return results[i].(string) < results[j].(string)
			default:
				panic("not implement")
			}
		})
	}

	return
}

func (mds *mockDataSource) randDatum(typ *types.FieldType) interface{} {
	switch typ.Tp {
	case mysql.TypeLong, mysql.TypeLonglong:
		return int64(rand.Int())
	case mysql.TypeDouble, mysql.TypeFloat:
		return rand.Float64()
	case mysql.TypeNewDecimal:
		var d types.MyDecimal
		return d.FromInt(int64(rand.Int()))
	case mysql.TypeVarString:
		buff := make([]byte, 10)
		rand.Read(buff)
		return base64.RawURLEncoding.EncodeToString(buff)
	default:
		panic("not implement")
	}
}

func (mds *mockDataSource) prepareChunks() {
	mds.chunks = make([]*chunk.Chunk, len(mds.genData))
	for i := range mds.chunks {
		mds.chunks[i] = mds.genData[i].CopyConstruct()
	}
	mds.chunkPtr = 0
}

func (mds *mockDataSource) Next(ctx context.Context, req *chunk.Chunk) error {
	if mds.chunkPtr >= len(mds.chunks) {
		req.Reset()
		return nil
	}
	dataChk := mds.chunks[mds.chunkPtr]
	dataChk.SwapColumns(req)
	mds.chunkPtr++
	return nil
}

func buildMockDataSource(opt mockDataSourceParameters) *mockDataSource {
	baseExec := newBaseExecutor(opt.ctx, opt.schema, 0)
	m := &mockDataSource{baseExec, opt, nil, nil, 0}
	rTypes := retTypes(m)
	colData := make([][]interface{}, len(rTypes))
	for i := 0; i < len(rTypes); i++ {
		colData[i] = m.genColDatums(i)
	}

	m.genData = make([]*chunk.Chunk, (m.p.rows+m.maxChunkSize-1)/m.maxChunkSize)
	for i := range m.genData {
		m.genData[i] = chunk.NewChunkWithCapacity(retTypes(m), m.maxChunkSize)
	}

	for i := 0; i < m.p.rows; i++ {
		idx := i / m.maxChunkSize
		retTypes := retTypes(m)
		for colIdx := 0; colIdx < len(rTypes); colIdx++ {
			switch retTypes[colIdx].Tp {
			case mysql.TypeLong, mysql.TypeLonglong:
				m.genData[idx].AppendInt64(colIdx, colData[colIdx][i].(int64))
			case mysql.TypeDouble, mysql.TypeFloat:
				m.genData[idx].AppendFloat64(colIdx, colData[colIdx][i].(float64))
			case mysql.TypeNewDecimal:
				m.genData[idx].AppendMyDecimal(colIdx, colData[colIdx][i].(*types.MyDecimal))
			case mysql.TypeVarString:
				m.genData[idx].AppendString(colIdx, colData[colIdx][i].(string))
			default:
				panic("not implement")
			}
		}
	}
	return m
}

func buildMockDataSourceWithIndex(opt mockDataSourceParameters, index []int) *mockDataSource {
	opt.orders = make([]bool, len(opt.schema.Columns))
	for _, idx := range index {
		opt.orders[idx] = true
	}
	return buildMockDataSource(opt)
}

// aggTestCase has a fixed schema (aggCol Double, groupBy LongLong).
type aggTestCase struct {
	execType    string // "hash" or "stream"
	aggFunc     string // sum, avg, count ....
	groupByNDV  int    // the number of distinct group-by keys
	hasDistinct bool
	rows        int
	concurrency int
	ctx         sessionctx.Context
}

func (a aggTestCase) columns() []*expression.Column {
	return []*expression.Column{
		{Index: 0, RetType: types.NewFieldType(mysql.TypeDouble)},
		{Index: 1, RetType: types.NewFieldType(mysql.TypeLonglong)},
	}
}

func (a aggTestCase) String() string {
	return fmt.Sprintf("(execType:%v, aggFunc:%v, ndv:%v, hasDistinct:%v, rows:%v, concurrency:%v)",
		a.execType, a.aggFunc, a.groupByNDV, a.hasDistinct, a.rows, a.concurrency)
}

func defaultAggTestCase(exec string) *aggTestCase {
	ctx := mock.NewContext()
	ctx.GetSessionVars().InitChunkSize = variable.DefInitChunkSize
	ctx.GetSessionVars().MaxChunkSize = variable.DefMaxChunkSize
	return &aggTestCase{exec, ast.AggFuncSum, 1000, false, 10000000, 4, ctx}
}

func buildHashAggExecutor(ctx sessionctx.Context, src Executor, schema *expression.Schema,
	aggFuncs []*aggregation.AggFuncDesc, groupItems []expression.Expression) Executor {
	plan := new(core.PhysicalHashAgg)
	plan.AggFuncs = aggFuncs
	plan.GroupByItems = groupItems
	plan.SetSchema(schema)
	plan.Init(ctx, nil, 0)
	plan.SetChildren(nil)
	b := newExecutorBuilder(ctx, nil)
	exec := b.build(plan)
	hashAgg := exec.(*HashAggExec)
	hashAgg.children[0] = src
	return exec
}

func buildStreamAggExecutor(ctx sessionctx.Context, src Executor, schema *expression.Schema,
	aggFuncs []*aggregation.AggFuncDesc, groupItems []expression.Expression) Executor {
	plan := new(core.PhysicalStreamAgg)
	plan.AggFuncs = aggFuncs
	plan.GroupByItems = groupItems
	plan.SetSchema(schema)
	plan.Init(ctx, nil, 0)
	plan.SetChildren(nil)
	b := newExecutorBuilder(ctx, nil)
	exec := b.build(plan)
	streamAgg := exec.(*StreamAggExec)
	streamAgg.children[0] = src
	return exec
}

func buildAggExecutor(b *testing.B, testCase *aggTestCase, child Executor) Executor {
	ctx := testCase.ctx
	if err := ctx.GetSessionVars().SetSystemVar(variable.TiDBHashAggFinalConcurrency, fmt.Sprintf("%v", testCase.concurrency)); err != nil {
		b.Fatal(err)
	}
	if err := ctx.GetSessionVars().SetSystemVar(variable.TiDBHashAggPartialConcurrency, fmt.Sprintf("%v", testCase.concurrency)); err != nil {
		b.Fatal(err)
	}

	childCols := testCase.columns()
	schema := expression.NewSchema(childCols...)
	groupBy := []expression.Expression{childCols[1]}
	aggFunc, err := aggregation.NewAggFuncDesc(testCase.ctx, testCase.aggFunc, []expression.Expression{childCols[0]}, testCase.hasDistinct)
	if err != nil {
		b.Fatal(err)
	}
	aggFuncs := []*aggregation.AggFuncDesc{aggFunc}

	var aggExec Executor
	switch testCase.execType {
	case "hash":
		aggExec = buildHashAggExecutor(testCase.ctx, child, schema, aggFuncs, groupBy)
	case "stream":
		aggExec = buildStreamAggExecutor(testCase.ctx, child, schema, aggFuncs, groupBy)
	default:
		b.Fatal("not implement")
	}
	return aggExec
}

func benchmarkAggExecWithCase(b *testing.B, casTest *aggTestCase) {
	cols := casTest.columns()
	orders := []bool{false, casTest.execType == "stream"}
	dataSource := buildMockDataSource(mockDataSourceParameters{
		schema: expression.NewSchema(cols...),
		ndvs:   []int{0, casTest.groupByNDV},
		orders: orders,
		rows:   casTest.rows,
		ctx:    casTest.ctx,
	})

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		b.StopTimer() // prepare a new agg-executor
		aggExec := buildAggExecutor(b, casTest, dataSource)
		tmpCtx := context.Background()
		chk := newFirstChunk(aggExec)
		dataSource.prepareChunks()

		b.StartTimer()
		if err := aggExec.Open(tmpCtx); err != nil {
			b.Fatal(err)
		}
		for {
			if err := aggExec.Next(tmpCtx, chk); err != nil {
				b.Fatal(b)
			}
			if chk.NumRows() == 0 {
				break
			}
		}

		if err := aggExec.Close(); err != nil {
			b.Fatal(err)
		}
		b.StopTimer()
	}
}

func BenchmarkAggRows(b *testing.B) {
	rows := []int{100000, 1000000, 10000000}
	concurrencies := []int{1, 4, 8, 15, 20, 30, 40}
	for _, row := range rows {
		for _, con := range concurrencies {
			for _, exec := range []string{"hash", "stream"} {
				if exec == "stream" && con > 1 {
					continue
				}
				cas := defaultAggTestCase(exec)
				cas.rows = row
				cas.concurrency = con
				b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
					benchmarkAggExecWithCase(b, cas)
				})
			}
		}
	}
}

func BenchmarkAggGroupByNDV(b *testing.B) {
	NDVs := []int{10, 100, 1000, 10000, 100000, 1000000, 10000000}
	for _, NDV := range NDVs {
		for _, exec := range []string{"hash", "stream"} {
			cas := defaultAggTestCase(exec)
			cas.groupByNDV = NDV
			b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
				benchmarkAggExecWithCase(b, cas)
			})
		}
	}
}

func BenchmarkAggConcurrency(b *testing.B) {
	concs := []int{1, 4, 8, 15, 20, 30, 40}
	for _, con := range concs {
		for _, exec := range []string{"hash", "stream"} {
			if exec == "stream" && con > 1 {
				continue
			}
			cas := defaultAggTestCase(exec)
			cas.concurrency = con
			b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
				benchmarkAggExecWithCase(b, cas)
			})
		}
	}
}

func BenchmarkAggDistinct(b *testing.B) {
	rows := []int{100000, 1000000, 10000000}
	distincts := []bool{false, true}
	for _, row := range rows {
		for _, exec := range []string{"hash", "stream"} {
			for _, distinct := range distincts {
				cas := defaultAggTestCase(exec)
				cas.rows = row
				cas.hasDistinct = distinct
				b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
					benchmarkAggExecWithCase(b, cas)
				})
			}
		}
	}
}

func buildWindowExecutor(ctx sessionctx.Context, windowFunc string, funcs int, frame *core.WindowFrame, srcExec Executor, schema *expression.Schema, partitionBy []*expression.Column, concurrency int, dataSourceSorted bool) Executor {
	src := &mockDataPhysicalPlan{
		schema: srcExec.Schema(),
		exec:   srcExec,
	}

	win := new(core.PhysicalWindow)
	win.WindowFuncDescs = make([]*aggregation.WindowFuncDesc, 0)
	winSchema := schema.Clone()
	for i := 0; i < funcs; i++ {
		var args []expression.Expression
		switch windowFunc {
		case ast.WindowFuncNtile:
			args = append(args, &expression.Constant{Value: types.NewUintDatum(2)})
		case ast.WindowFuncNthValue:
			args = append(args, partitionBy[0], &expression.Constant{Value: types.NewUintDatum(2)})
		case ast.AggFuncSum:
			args = append(args, src.Schema().Columns[0])
		case ast.AggFuncAvg:
			args = append(args, src.Schema().Columns[0])
		case ast.AggFuncBitXor:
			args = append(args, src.Schema().Columns[0])
		case ast.AggFuncMax, ast.AggFuncMin:
			args = append(args, src.Schema().Columns[0])
		default:
			args = append(args, partitionBy[0])
		}
		desc, _ := aggregation.NewWindowFuncDesc(ctx, windowFunc, args)

		win.WindowFuncDescs = append(win.WindowFuncDescs, desc)
		winSchema.Append(&expression.Column{
			UniqueID: 10 + (int64)(i),
			RetType:  types.NewFieldType(mysql.TypeLonglong),
		})
	}
	for _, col := range partitionBy {
		win.PartitionBy = append(win.PartitionBy, property.SortItem{Col: col})
	}
	win.Frame = frame
	win.OrderBy = nil

	win.SetSchema(winSchema)
	win.Init(ctx, nil, 0)

	var tail core.PhysicalPlan = win
	if !dataSourceSorted {
		byItems := make([]*util.ByItems, 0, len(partitionBy))
		for _, col := range partitionBy {
			byItems = append(byItems, &util.ByItems{Expr: col, Desc: false})
		}
		sort := &core.PhysicalSort{ByItems: byItems}
		sort.SetChildren(src)
		win.SetChildren(sort)
		tail = sort
	} else {
		win.SetChildren(src)
	}

	var plan core.PhysicalPlan
	if concurrency > 1 {
		byItems := make([]expression.Expression, 0, len(win.PartitionBy))
		for _, item := range win.PartitionBy {
			byItems = append(byItems, item.Col)
		}

		plan = core.PhysicalShuffle{
			Concurrency:  concurrency,
			Tail:         tail,
			DataSource:   src,
			SplitterType: core.PartitionHashSplitterType,
			HashByItems:  byItems,
		}.Init(ctx, nil, 0)
		plan.SetChildren(win)
	} else {
		plan = win
	}

	b := newExecutorBuilder(ctx, nil)
	exec := b.build(plan)
	return exec
}

// windowTestCase has a fixed schema (col Double, partitionBy LongLong, rawData VarString(16), col LongLong).
type windowTestCase struct {
	windowFunc       string
	numFunc          int // The number of windowFuncs. Default: 1.
	frame            *core.WindowFrame
	ndv              int // the number of distinct group-by keys
	rows             int
	concurrency      int
	dataSourceSorted bool
	ctx              sessionctx.Context
	rawDataSmall     string
	columns          []*expression.Column // the columns of mock schema
}

func (a windowTestCase) String() string {
	return fmt.Sprintf("(func:%v, aggColType:%s, numFunc:%v, ndv:%v, rows:%v, sorted:%v, concurrency:%v)",
		a.windowFunc, a.columns[0].RetType, a.numFunc, a.ndv, a.rows, a.dataSourceSorted, a.concurrency)
}

func defaultWindowTestCase() *windowTestCase {
	ctx := mock.NewContext()
	ctx.GetSessionVars().InitChunkSize = variable.DefInitChunkSize
	ctx.GetSessionVars().MaxChunkSize = variable.DefMaxChunkSize
	return &windowTestCase{ast.WindowFuncRowNumber, 1, nil, 1000, 10000000, 1, true, ctx, strings.Repeat("x", 16),
		[]*expression.Column{
			{Index: 0, RetType: types.NewFieldType(mysql.TypeDouble)},
			{Index: 1, RetType: types.NewFieldType(mysql.TypeLonglong)},
			{Index: 2, RetType: types.NewFieldType(mysql.TypeVarString)},
			{Index: 3, RetType: types.NewFieldType(mysql.TypeLonglong)},
		}}
}

func benchmarkWindowExecWithCase(b *testing.B, casTest *windowTestCase) {
	ctx := casTest.ctx
	if err := ctx.GetSessionVars().SetSystemVar(variable.TiDBWindowConcurrency, fmt.Sprintf("%v", casTest.concurrency)); err != nil {
		b.Fatal(err)
	}

	cols := casTest.columns
	dataSource := buildMockDataSource(mockDataSourceParameters{
		schema: expression.NewSchema(cols...),
		ndvs:   []int{0, casTest.ndv, 0, 0},
		orders: []bool{false, casTest.dataSourceSorted, false, false},
		rows:   casTest.rows,
		ctx:    casTest.ctx,
	})

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		b.StopTimer() // prepare a new window-executor
		childCols := casTest.columns
		schema := expression.NewSchema(childCols...)
		windowExec := buildWindowExecutor(casTest.ctx, casTest.windowFunc, casTest.numFunc, casTest.frame, dataSource, schema, childCols[1:2], casTest.concurrency, casTest.dataSourceSorted)
		tmpCtx := context.Background()
		chk := newFirstChunk(windowExec)
		dataSource.prepareChunks()

		b.StartTimer()
		if err := windowExec.Open(tmpCtx); err != nil {
			b.Fatal(err)
		}
		for {
			if err := windowExec.Next(tmpCtx, chk); err != nil {
				b.Fatal(b)
			}
			if chk.NumRows() == 0 {
				break
			}
		}

		if err := windowExec.Close(); err != nil {
			b.Fatal(err)
		}
		b.StopTimer()
	}
}

func BenchmarkWindowRows(b *testing.B) {
	b.ReportAllocs()
	rows := []int{1000, 100000}
	ndvs := []int{10, 1000}
	concs := []int{1, 2, 4}
	for _, row := range rows {
		for _, ndv := range ndvs {
			for _, con := range concs {
				cas := defaultWindowTestCase()
				cas.rows = row
				cas.ndv = ndv
				cas.concurrency = con
				cas.dataSourceSorted = false
				cas.windowFunc = ast.WindowFuncRowNumber // cheapest
				b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
					benchmarkWindowExecWithCase(b, cas)
				})
			}
		}
	}
}

func BenchmarkWindowFunctions(b *testing.B) {
	b.ReportAllocs()
	windowFuncs := []string{
		ast.WindowFuncRowNumber,
		ast.WindowFuncRank,
		ast.WindowFuncDenseRank,
		ast.WindowFuncCumeDist,
		ast.WindowFuncPercentRank,
		ast.WindowFuncNtile,
		ast.WindowFuncLead,
		ast.WindowFuncLag,
		ast.WindowFuncFirstValue,
		ast.WindowFuncLastValue,
		ast.WindowFuncNthValue,
	}
	concs := []int{1, 4}
	for _, windowFunc := range windowFuncs {
		for _, con := range concs {
			cas := defaultWindowTestCase()
			cas.rows = 100000
			cas.ndv = 1000
			cas.concurrency = con
			cas.dataSourceSorted = false
			cas.windowFunc = windowFunc
			b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
				benchmarkWindowExecWithCase(b, cas)
			})
		}
	}
}

func BenchmarkWindowFunctionsWithFrame(b *testing.B) {
	b.ReportAllocs()
	windowFuncs := []string{
		ast.WindowFuncRowNumber,
		ast.AggFuncBitXor,
	}
	numFuncs := []int{1, 5}
	frames := []*core.WindowFrame{
		{Type: ast.Rows, Start: &core.FrameBound{UnBounded: true}, End: &core.FrameBound{Type: ast.CurrentRow}},
	}
	sortTypes := []bool{false, true}
	concs := []int{1, 2, 3, 4, 5, 6}
	for i, windowFunc := range windowFuncs {
		for _, sorted := range sortTypes {
			for _, numFunc := range numFuncs {
				for _, con := range concs {
					cas := defaultWindowTestCase()
					cas.rows = 100000
					cas.ndv = 1000
					cas.concurrency = con
					cas.dataSourceSorted = sorted
					cas.windowFunc = windowFunc
					cas.numFunc = numFunc
					if i < len(frames) {
						cas.frame = frames[i]
					}
					b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
						benchmarkWindowExecWithCase(b, cas)
					})
				}
			}
		}
	}
}

func BenchmarkWindowFunctionsAggWindowProcessorAboutFrame(b *testing.B) {
	b.ReportAllocs()
	windowFunc := ast.AggFuncMax
	frame := &core.WindowFrame{Type: ast.Rows, Start: &core.FrameBound{UnBounded: true}, End: &core.FrameBound{UnBounded: true}}
	cas := defaultWindowTestCase()
	cas.rows = 10000
	cas.ndv = 10
	cas.concurrency = 1
	cas.dataSourceSorted = false
	cas.windowFunc = windowFunc
	cas.numFunc = 1
	cas.frame = frame
	b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
		benchmarkWindowExecWithCase(b, cas)
	})
}

func baseBenchmarkWindowFunctionsWithSlidingWindow(b *testing.B, frameType ast.FrameType) {
	b.ReportAllocs()
	windowFuncs := []struct {
		aggFunc     string
		aggColTypes byte
	}{
		{ast.AggFuncSum, mysql.TypeFloat},
		{ast.AggFuncSum, mysql.TypeNewDecimal},
		{ast.AggFuncCount, mysql.TypeLong},
		{ast.AggFuncAvg, mysql.TypeFloat},
		{ast.AggFuncAvg, mysql.TypeNewDecimal},
		{ast.AggFuncBitXor, mysql.TypeLong},
		{ast.AggFuncMax, mysql.TypeLong},
		{ast.AggFuncMax, mysql.TypeFloat},
		{ast.AggFuncMin, mysql.TypeLong},
		{ast.AggFuncMin, mysql.TypeFloat},
	}
	row := 100000
	ndv := 100
	frame := &core.WindowFrame{
		Type:  frameType,
		Start: &core.FrameBound{Type: ast.Preceding, Num: 10},
		End:   &core.FrameBound{Type: ast.Following, Num: 10},
	}
	for _, windowFunc := range windowFuncs {
		cas := defaultWindowTestCase()
		cas.ctx.GetSessionVars().WindowingUseHighPrecision = false
		cas.rows = row
		cas.ndv = ndv
		cas.windowFunc = windowFunc.aggFunc
		cas.frame = frame
		cas.columns[0].RetType.Tp = windowFunc.aggColTypes
		b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
			benchmarkWindowExecWithCase(b, cas)
		})
	}
}

func BenchmarkWindowFunctionsWithSlidingWindow(b *testing.B) {
	baseBenchmarkWindowFunctionsWithSlidingWindow(b, ast.Rows)
	baseBenchmarkWindowFunctionsWithSlidingWindow(b, ast.Ranges)
}

type hashJoinTestCase struct {
	rows               int
	cols               []*types.FieldType
	concurrency        int
	ctx                sessionctx.Context
	keyIdx             []int
	joinType           core.JoinType
	disk               bool
	useOuterToBuild    bool
	rawData            string
	childrenUsedSchema [][]bool
}

func (tc hashJoinTestCase) columns() []*expression.Column {
	ret := make([]*expression.Column, 0)
	for i, t := range tc.cols {
		column := &expression.Column{Index: i, RetType: t, UniqueID: tc.ctx.GetSessionVars().AllocPlanColumnID()}
		ret = append(ret, column)
	}
	return ret
}

func (tc hashJoinTestCase) String() string {
	return fmt.Sprintf("(rows:%v, cols:%v, concurency:%v, joinKeyIdx: %v, disk:%v)",
		tc.rows, tc.cols, tc.concurrency, tc.keyIdx, tc.disk)
}

func defaultHashJoinTestCase(cols []*types.FieldType, joinType core.JoinType, useOuterToBuild bool) *hashJoinTestCase {
	ctx := mock.NewContext()
	ctx.GetSessionVars().InitChunkSize = variable.DefInitChunkSize
	ctx.GetSessionVars().MaxChunkSize = variable.DefMaxChunkSize
	ctx.GetSessionVars().StmtCtx.MemTracker = memory.NewTracker(-1, -1)
	ctx.GetSessionVars().StmtCtx.DiskTracker = disk.NewTracker(-1, -1)
	ctx.GetSessionVars().SetIndexLookupJoinConcurrency(4)
	tc := &hashJoinTestCase{rows: 100000, concurrency: 4, ctx: ctx, keyIdx: []int{0, 1}, rawData: wideString}
	tc.cols = cols
	tc.useOuterToBuild = useOuterToBuild
	tc.joinType = joinType
	return tc
}

func prepare4HashJoin(testCase *hashJoinTestCase, innerExec, outerExec Executor) *HashJoinExec {
	if testCase.useOuterToBuild {
		innerExec, outerExec = outerExec, innerExec
	}
	cols0 := innerExec.Schema().Columns
	cols1 := outerExec.Schema().Columns

	joinSchema := expression.NewSchema()
	if testCase.childrenUsedSchema != nil {
		for i, used := range testCase.childrenUsedSchema[0] {
			if used {
				joinSchema.Append(cols0[i])
			}
		}
		for i, used := range testCase.childrenUsedSchema[1] {
			if used {
				joinSchema.Append(cols1[i])
			}
		}
	} else {
		joinSchema.Append(cols0...)
		joinSchema.Append(cols1...)
	}

	joinKeys := make([]*expression.Column, 0, len(testCase.keyIdx))
	for _, keyIdx := range testCase.keyIdx {
		joinKeys = append(joinKeys, cols0[keyIdx])
	}
	probeKeys := make([]*expression.Column, 0, len(testCase.keyIdx))
	for _, keyIdx := range testCase.keyIdx {
		probeKeys = append(probeKeys, cols1[keyIdx])
	}
	e := &HashJoinExec{
		baseExecutor:      newBaseExecutor(testCase.ctx, joinSchema, 5, innerExec, outerExec),
		concurrency:       uint(testCase.concurrency),
		joinType:          testCase.joinType, // 0 for InnerJoin, 1 for LeftOutersJoin, 2 for RightOuterJoin
		isOuterJoin:       false,
		buildKeys:         joinKeys,
		probeKeys:         probeKeys,
		buildSideExec:     innerExec,
		probeSideExec:     outerExec,
		buildSideEstCount: float64(testCase.rows),
		useOuterToBuild:   testCase.useOuterToBuild,
	}

	childrenUsedSchema := markChildrenUsedCols(e.Schema(), e.children[0].Schema(), e.children[1].Schema())
	defaultValues := make([]types.Datum, e.buildSideExec.Schema().Len())
	lhsTypes, rhsTypes := retTypes(innerExec), retTypes(outerExec)
	e.joiners = make([]joiner, e.concurrency)
	for i := uint(0); i < e.concurrency; i++ {
		e.joiners[i] = newJoiner(testCase.ctx, e.joinType, true, defaultValues,
			nil, lhsTypes, rhsTypes, childrenUsedSchema)
	}
	memLimit := int64(-1)
	if testCase.disk {
		memLimit = 1
	}
	t := memory.NewTracker(-1, memLimit)
	t.SetActionOnExceed(nil)
	t2 := disk.NewTracker(-1, -1)
	e.ctx.GetSessionVars().StmtCtx.MemTracker = t
	e.ctx.GetSessionVars().StmtCtx.DiskTracker = t2
	return e
}

func benchmarkHashJoinExecWithCase(b *testing.B, casTest *hashJoinTestCase) {
	opt1 := mockDataSourceParameters{
		rows: casTest.rows,
		ctx:  casTest.ctx,
		genDataFunc: func(row int, typ *types.FieldType) interface{} {
			switch typ.Tp {
			case mysql.TypeLong, mysql.TypeLonglong:
				return int64(row)
			case mysql.TypeVarString:
				return casTest.rawData
			case mysql.TypeDouble:
				return float64(row)
			default:
				panic("not implement")
			}
		},
	}
	opt2 := opt1
	opt1.schema = expression.NewSchema(casTest.columns()...)
	opt2.schema = expression.NewSchema(casTest.columns()...)
	dataSource1 := buildMockDataSource(opt1)
	dataSource2 := buildMockDataSource(opt2)
	// Test spill result.
	benchmarkHashJoinExec(b, casTest, dataSource1, dataSource2, true)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		benchmarkHashJoinExec(b, casTest, dataSource1, dataSource2, false)
	}
}

func benchmarkHashJoinExec(b *testing.B, casTest *hashJoinTestCase, opt1, opt2 *mockDataSource, testResult bool) {
	b.StopTimer()
	exec := prepare4HashJoin(casTest, opt1, opt2)
	tmpCtx := context.Background()
	chk := newFirstChunk(exec)
	opt1.prepareChunks()
	opt2.prepareChunks()

	totalRow := 0
	b.StartTimer()
	if err := exec.Open(tmpCtx); err != nil {
		b.Fatal(err)
	}
	for {
		if err := exec.Next(tmpCtx, chk); err != nil {
			b.Fatal(err)
		}
		if chk.NumRows() == 0 {
			break
		}
		totalRow += chk.NumRows()
	}

	if testResult {
		time.Sleep(200 * time.Millisecond)
		if spilled := exec.rowContainer.alreadySpilledSafeForTest(); spilled != casTest.disk {
			b.Fatal("wrong usage with disk:", spilled, casTest.disk)
		}
	}

	if err := exec.Close(); err != nil {
		b.Fatal(err)
	}
	b.StopTimer()
	if totalRow == 0 {
		b.Fatal("totalRow == 0")
	}
}

func BenchmarkHashJoinInlineProjection(b *testing.B) {
	cols := []*types.FieldType{
		types.NewFieldType(mysql.TypeLonglong),
		types.NewFieldType(mysql.TypeVarString),
	}

	b.ReportAllocs()

	{
		cas := defaultHashJoinTestCase(cols, 0, false)
		cas.keyIdx = []int{0}
		cas.childrenUsedSchema = [][]bool{
			{false, true},
			{false, false},
		}
		b.Run("InlineProjection:ON", func(b *testing.B) {
			benchmarkHashJoinExecWithCase(b, cas)
		})
	}

	{
		cas := defaultHashJoinTestCase(cols, 0, false)
		cas.keyIdx = []int{0}
		b.Run("InlineProjection:OFF", func(b *testing.B) {
			benchmarkHashJoinExecWithCase(b, cas)
		})
	}
}

func BenchmarkHashJoinExec(b *testing.B) {
	lvl := log.GetLevel()
	log.SetLevel(zapcore.ErrorLevel)
	defer log.SetLevel(lvl)

	cols := []*types.FieldType{
		types.NewFieldType(mysql.TypeLonglong),
		types.NewFieldType(mysql.TypeVarString),
	}

	b.ReportAllocs()
	cas := defaultHashJoinTestCase(cols, 0, false)
	b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
		benchmarkHashJoinExecWithCase(b, cas)
	})

	cas.keyIdx = []int{0}
	b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
		benchmarkHashJoinExecWithCase(b, cas)
	})

	cas.keyIdx = []int{0}
	cas.disk = true
	b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
		benchmarkHashJoinExecWithCase(b, cas)
	})

	// Replace the wide string column with double column
	cols = []*types.FieldType{
		types.NewFieldType(mysql.TypeLonglong),
		types.NewFieldType(mysql.TypeDouble),
	}

	cas = defaultHashJoinTestCase(cols, 0, false)
	cas.keyIdx = []int{0}
	cas.rows = 5
	b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
		benchmarkHashJoinExecWithCase(b, cas)
	})

	cas = defaultHashJoinTestCase(cols, 0, false)
	b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
		benchmarkHashJoinExecWithCase(b, cas)
	})

	cas.keyIdx = []int{0}
	b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
		benchmarkHashJoinExecWithCase(b, cas)
	})
}

func BenchmarkOuterHashJoinExec(b *testing.B) {
	lvl := log.GetLevel()
	log.SetLevel(zapcore.ErrorLevel)
	defer log.SetLevel(lvl)

	cols := []*types.FieldType{
		types.NewFieldType(mysql.TypeLonglong),
		types.NewFieldType(mysql.TypeVarString),
	}

	b.ReportAllocs()
	cas := defaultHashJoinTestCase(cols, 2, true)
	b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
		benchmarkHashJoinExecWithCase(b, cas)
	})

	cas.keyIdx = []int{0}
	b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
		benchmarkHashJoinExecWithCase(b, cas)
	})

	cas.keyIdx = []int{0}
	cas.disk = true
	b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
		benchmarkHashJoinExecWithCase(b, cas)
	})

	// Replace the wide string column with double column
	cols = []*types.FieldType{
		types.NewFieldType(mysql.TypeLonglong),
		types.NewFieldType(mysql.TypeDouble),
	}

	cas = defaultHashJoinTestCase(cols, 2, true)
	cas.keyIdx = []int{0}
	cas.rows = 5
	b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
		benchmarkHashJoinExecWithCase(b, cas)
	})

	cas = defaultHashJoinTestCase(cols, 2, true)
	b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
		benchmarkHashJoinExecWithCase(b, cas)
	})

	cas.keyIdx = []int{0}
	b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
		benchmarkHashJoinExecWithCase(b, cas)
	})
}

func benchmarkBuildHashTableForList(b *testing.B, casTest *hashJoinTestCase) {
	opt := mockDataSourceParameters{
		schema: expression.NewSchema(casTest.columns()...),
		rows:   casTest.rows,
		ctx:    casTest.ctx,
		genDataFunc: func(row int, typ *types.FieldType) interface{} {
			switch typ.Tp {
			case mysql.TypeLong, mysql.TypeLonglong:
				return int64(row)
			case mysql.TypeVarString:
				return casTest.rawData
			default:
				panic("not implement")
			}
		},
	}
	dataSource1 := buildMockDataSource(opt)
	dataSource2 := buildMockDataSource(opt)

	dataSource1.prepareChunks()
	benchmarkBuildHashTable(b, casTest, dataSource1, dataSource2, true)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		benchmarkBuildHashTable(b, casTest, dataSource1, dataSource2, false)
	}
}

func benchmarkBuildHashTable(b *testing.B, casTest *hashJoinTestCase, dataSource1, dataSource2 *mockDataSource, testResult bool) {
	b.StopTimer()
	exec := prepare4HashJoin(casTest, dataSource1, dataSource2)
	tmpCtx := context.Background()
	if err := exec.Open(tmpCtx); err != nil {
		b.Fatal(err)
	}
	exec.prepared = true

	innerResultCh := make(chan *chunk.Chunk, len(dataSource1.chunks))
	for _, chk := range dataSource1.chunks {
		innerResultCh <- chk
	}
	close(innerResultCh)

	b.StartTimer()
	if err := exec.buildHashTableForList(innerResultCh); err != nil {
		b.Fatal(err)
	}

	if testResult {
		time.Sleep(200 * time.Millisecond)
		if exec.rowContainer.alreadySpilledSafeForTest() != casTest.disk {
			b.Fatal("wrong usage with disk")
		}
	}

	if err := exec.Close(); err != nil {
		b.Fatal(err)
	}
	b.StopTimer()
}

func BenchmarkBuildHashTableForList(b *testing.B) {
	lvl := log.GetLevel()
	log.SetLevel(zapcore.ErrorLevel)
	defer log.SetLevel(lvl)

	cols := []*types.FieldType{
		types.NewFieldType(mysql.TypeLonglong),
		types.NewFieldType(mysql.TypeVarString),
	}

	b.ReportAllocs()
	cas := defaultHashJoinTestCase(cols, 0, false)
	rows := []int{10, 100000}
	keyIdxs := [][]int{{0, 1}, {0}}
	disks := []bool{false, true}
	for _, row := range rows {
		for _, keyIdx := range keyIdxs {
			for _, disk := range disks {
				cas.rows = row
				cas.keyIdx = keyIdx
				cas.disk = disk
				b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
					benchmarkBuildHashTableForList(b, cas)
				})
			}
		}
	}
}

type indexJoinTestCase struct {
	outerRows       int
	innerRows       int
	concurrency     int
	ctx             sessionctx.Context
	outerJoinKeyIdx []int
	innerJoinKeyIdx []int
	innerIdx        []int
	needOuterSort   bool
	rawData         string
}

func (tc indexJoinTestCase) columns() []*expression.Column {
	return []*expression.Column{
		{Index: 0, RetType: types.NewFieldType(mysql.TypeLonglong)},
		{Index: 1, RetType: types.NewFieldType(mysql.TypeDouble)},
		{Index: 2, RetType: types.NewFieldType(mysql.TypeVarString)},
	}
}

func defaultIndexJoinTestCase() *indexJoinTestCase {
	ctx := mock.NewContext()
	ctx.GetSessionVars().InitChunkSize = variable.DefInitChunkSize
	ctx.GetSessionVars().MaxChunkSize = variable.DefMaxChunkSize
	ctx.GetSessionVars().SnapshotTS = 1
	ctx.GetSessionVars().StmtCtx.MemTracker = memory.NewTracker(-1, -1)
	ctx.GetSessionVars().StmtCtx.DiskTracker = disk.NewTracker(-1, -1)
	tc := &indexJoinTestCase{
		outerRows:       100000,
		innerRows:       variable.DefMaxChunkSize * 100,
		concurrency:     4,
		ctx:             ctx,
		outerJoinKeyIdx: []int{0, 1},
		innerJoinKeyIdx: []int{0, 1},
		innerIdx:        []int{0, 1},
		rawData:         wideString,
	}
	return tc
}

func (tc indexJoinTestCase) String() string {
	return fmt.Sprintf("(outerRows:%v, innerRows:%v, concurency:%v, outerJoinKeyIdx: %v, innerJoinKeyIdx: %v, NeedOuterSort:%v)",
		tc.outerRows, tc.innerRows, tc.concurrency, tc.outerJoinKeyIdx, tc.innerJoinKeyIdx, tc.needOuterSort)
}
func (tc indexJoinTestCase) getMockDataSourceOptByRows(rows int) mockDataSourceParameters {
	return mockDataSourceParameters{
		schema: expression.NewSchema(tc.columns()...),
		rows:   rows,
		ctx:    tc.ctx,
		genDataFunc: func(row int, typ *types.FieldType) interface{} {
			switch typ.Tp {
			case mysql.TypeLong, mysql.TypeLonglong:
				return int64(row)
			case mysql.TypeDouble:
				return float64(row)
			case mysql.TypeVarString:
				return tc.rawData
			default:
				panic("not implement")
			}
		},
	}
}

func prepare4IndexInnerHashJoin(tc *indexJoinTestCase, outerDS *mockDataSource, innerDS *mockDataSource) Executor {
	outerCols, innerCols := tc.columns(), tc.columns()
	joinSchema := expression.NewSchema(outerCols...)
	joinSchema.Append(innerCols...)
	leftTypes, rightTypes := retTypes(outerDS), retTypes(innerDS)
	defaultValues := make([]types.Datum, len(innerCols))
	colLens := make([]int, len(innerCols))
	for i := range colLens {
		colLens[i] = types.UnspecifiedLength
	}
	keyOff2IdxOff := make([]int, len(tc.outerJoinKeyIdx))
	for i := range keyOff2IdxOff {
		keyOff2IdxOff[i] = i
	}
	e := &IndexLookUpJoin{
		baseExecutor: newBaseExecutor(tc.ctx, joinSchema, 1, outerDS),
		outerCtx: outerCtx{
			rowTypes: leftTypes,
			keyCols:  tc.outerJoinKeyIdx,
		},
		innerCtx: innerCtx{
			readerBuilder: &dataReaderBuilder{Plan: &mockPhysicalIndexReader{e: innerDS}, executorBuilder: newExecutorBuilder(tc.ctx, nil)},
			rowTypes:      rightTypes,
			colLens:       colLens,
			keyCols:       tc.innerJoinKeyIdx,
		},
		workerWg:      new(sync.WaitGroup),
		joiner:        newJoiner(tc.ctx, 0, false, defaultValues, nil, leftTypes, rightTypes, nil),
		isOuterJoin:   false,
		keyOff2IdxOff: keyOff2IdxOff,
		lastColHelper: nil,
	}
	e.joinResult = newFirstChunk(e)
	return e
}

func prepare4IndexOuterHashJoin(tc *indexJoinTestCase, outerDS *mockDataSource, innerDS *mockDataSource) Executor {
	e := prepare4IndexInnerHashJoin(tc, outerDS, innerDS).(*IndexLookUpJoin)
	idxHash := &IndexNestedLoopHashJoin{IndexLookUpJoin: *e}
	concurrency := tc.concurrency
	idxHash.joiners = make([]joiner, concurrency)
	for i := 0; i < concurrency; i++ {
		idxHash.joiners[i] = e.joiner.Clone()
	}
	return idxHash
}

func prepare4IndexMergeJoin(tc *indexJoinTestCase, outerDS *mockDataSource, innerDS *mockDataSource) Executor {
	outerCols, innerCols := tc.columns(), tc.columns()
	joinSchema := expression.NewSchema(outerCols...)
	joinSchema.Append(innerCols...)
	outerJoinKeys := make([]*expression.Column, 0, len(tc.outerJoinKeyIdx))
	innerJoinKeys := make([]*expression.Column, 0, len(tc.innerJoinKeyIdx))
	for _, keyIdx := range tc.outerJoinKeyIdx {
		outerJoinKeys = append(outerJoinKeys, outerCols[keyIdx])
	}
	for _, keyIdx := range tc.innerJoinKeyIdx {
		innerJoinKeys = append(innerJoinKeys, innerCols[keyIdx])
	}
	leftTypes, rightTypes := retTypes(outerDS), retTypes(innerDS)
	defaultValues := make([]types.Datum, len(innerCols))
	colLens := make([]int, len(innerCols))
	for i := range colLens {
		colLens[i] = types.UnspecifiedLength
	}
	keyOff2IdxOff := make([]int, len(outerJoinKeys))
	for i := range keyOff2IdxOff {
		keyOff2IdxOff[i] = i
	}

	compareFuncs := make([]expression.CompareFunc, 0, len(outerJoinKeys))
	outerCompareFuncs := make([]expression.CompareFunc, 0, len(outerJoinKeys))
	for i := range outerJoinKeys {
		compareFuncs = append(compareFuncs, expression.GetCmpFunction(nil, outerJoinKeys[i], innerJoinKeys[i]))
		outerCompareFuncs = append(outerCompareFuncs, expression.GetCmpFunction(nil, outerJoinKeys[i], outerJoinKeys[i]))
	}
	e := &IndexLookUpMergeJoin{
		baseExecutor: newBaseExecutor(tc.ctx, joinSchema, 2, outerDS),
		outerMergeCtx: outerMergeCtx{
			rowTypes:      leftTypes,
			keyCols:       tc.outerJoinKeyIdx,
			joinKeys:      outerJoinKeys,
			needOuterSort: tc.needOuterSort,
			compareFuncs:  outerCompareFuncs,
		},
		innerMergeCtx: innerMergeCtx{
			readerBuilder: &dataReaderBuilder{Plan: &mockPhysicalIndexReader{e: innerDS}, executorBuilder: newExecutorBuilder(tc.ctx, nil)},
			rowTypes:      rightTypes,
			joinKeys:      innerJoinKeys,
			colLens:       colLens,
			keyCols:       tc.innerJoinKeyIdx,
			compareFuncs:  compareFuncs,
		},
		workerWg:      new(sync.WaitGroup),
		isOuterJoin:   false,
		keyOff2IdxOff: keyOff2IdxOff,
		lastColHelper: nil,
	}
	concurrency := e.ctx.GetSessionVars().IndexLookupJoinConcurrency()
	joiners := make([]joiner, concurrency)
	for i := 0; i < concurrency; i++ {
		joiners[i] = newJoiner(tc.ctx, 0, false, defaultValues, nil, leftTypes, rightTypes, nil)
	}
	e.joiners = joiners
	return e
}

type indexJoinType int8

const (
	indexInnerHashJoin indexJoinType = iota
	indexOuterHashJoin
	indexMergeJoin
)

func benchmarkIndexJoinExecWithCase(
	b *testing.B,
	tc *indexJoinTestCase,
	outerDS *mockDataSource,
	innerDS *mockDataSource,
	execType indexJoinType,
) {
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		b.StopTimer()
		var exec Executor
		switch execType {
		case indexInnerHashJoin:
			exec = prepare4IndexInnerHashJoin(tc, outerDS, innerDS)
		case indexOuterHashJoin:
			exec = prepare4IndexOuterHashJoin(tc, outerDS, innerDS)
		case indexMergeJoin:
			exec = prepare4IndexMergeJoin(tc, outerDS, innerDS)
		}

		tmpCtx := context.Background()
		chk := newFirstChunk(exec)
		outerDS.prepareChunks()
		innerDS.prepareChunks()

		b.StartTimer()
		if err := exec.Open(tmpCtx); err != nil {
			b.Fatal(err)
		}
		for {
			if err := exec.Next(tmpCtx, chk); err != nil {
				b.Fatal(err)
			}
			if chk.NumRows() == 0 {
				break
			}
		}

		if err := exec.Close(); err != nil {
			b.Fatal(err)
		}
		b.StopTimer()
	}
}

func BenchmarkIndexJoinExec(b *testing.B) {
	lvl := log.GetLevel()
	log.SetLevel(zapcore.ErrorLevel)
	defer log.SetLevel(lvl)

	b.ReportAllocs()
	tc := defaultIndexJoinTestCase()
	outerOpt := tc.getMockDataSourceOptByRows(tc.outerRows)
	innerOpt := tc.getMockDataSourceOptByRows(tc.innerRows)
	outerDS := buildMockDataSourceWithIndex(outerOpt, tc.innerIdx)
	innerDS := buildMockDataSourceWithIndex(innerOpt, tc.innerIdx)

	tc.needOuterSort = true
	b.Run(fmt.Sprintf("index merge join need outer sort %v", tc), func(b *testing.B) {
		benchmarkIndexJoinExecWithCase(b, tc, outerDS, innerDS, indexMergeJoin)
	})

	tc.needOuterSort = false
	b.Run(fmt.Sprintf("index merge join %v", tc), func(b *testing.B) {
		benchmarkIndexJoinExecWithCase(b, tc, outerDS, innerDS, indexMergeJoin)
	})

	b.Run(fmt.Sprintf("index inner hash join %v", tc), func(b *testing.B) {
		benchmarkIndexJoinExecWithCase(b, tc, outerDS, innerDS, indexInnerHashJoin)
	})

	b.Run(fmt.Sprintf("index outer hash join %v", tc), func(b *testing.B) {
		benchmarkIndexJoinExecWithCase(b, tc, outerDS, innerDS, indexOuterHashJoin)
	})
}

type mergeJoinTestCase struct {
	indexJoinTestCase
	childrenUsedSchema [][]bool
}

func prepare4MergeJoin(tc *mergeJoinTestCase, leftExec, rightExec *mockDataSource) *MergeJoinExec {
	outerCols, innerCols := tc.columns(), tc.columns()

	joinSchema := expression.NewSchema()
	if tc.childrenUsedSchema != nil {
		for i, used := range tc.childrenUsedSchema[0] {
			if used {
				joinSchema.Append(outerCols[i])
			}
		}
		for i, used := range tc.childrenUsedSchema[1] {
			if used {
				joinSchema.Append(innerCols[i])
			}
		}
	} else {
		joinSchema.Append(outerCols...)
		joinSchema.Append(innerCols...)
	}

	outerJoinKeys := make([]*expression.Column, 0, len(tc.outerJoinKeyIdx))
	innerJoinKeys := make([]*expression.Column, 0, len(tc.innerJoinKeyIdx))
	for _, keyIdx := range tc.outerJoinKeyIdx {
		outerJoinKeys = append(outerJoinKeys, outerCols[keyIdx])
	}
	for _, keyIdx := range tc.innerJoinKeyIdx {
		innerJoinKeys = append(innerJoinKeys, innerCols[keyIdx])
	}
	compareFuncs := make([]expression.CompareFunc, 0, len(outerJoinKeys))
	outerCompareFuncs := make([]expression.CompareFunc, 0, len(outerJoinKeys))
	for i := range outerJoinKeys {
		compareFuncs = append(compareFuncs, expression.GetCmpFunction(nil, outerJoinKeys[i], innerJoinKeys[i]))
		outerCompareFuncs = append(outerCompareFuncs, expression.GetCmpFunction(nil, outerJoinKeys[i], outerJoinKeys[i]))
	}

	defaultValues := make([]types.Datum, len(innerCols))

	// only benchmark inner join
	e := &MergeJoinExec{
		stmtCtx:      tc.ctx.GetSessionVars().StmtCtx,
		baseExecutor: newBaseExecutor(tc.ctx, joinSchema, 3, leftExec, rightExec),
		compareFuncs: compareFuncs,
		isOuterJoin:  false,
	}

	e.joiner = newJoiner(
		tc.ctx,
		0,
		false,
		defaultValues,
		nil,
		retTypes(leftExec),
		retTypes(rightExec),
		tc.childrenUsedSchema,
	)

	e.innerTable = &mergeJoinTable{
		isInner:    true,
		childIndex: 1,
		joinKeys:   innerJoinKeys,
	}

	e.outerTable = &mergeJoinTable{
		childIndex: 0,
		filters:    nil,
		joinKeys:   outerJoinKeys,
	}

	return e
}

func defaultMergeJoinTestCase() *mergeJoinTestCase {
	return &mergeJoinTestCase{*defaultIndexJoinTestCase(), nil}
}

func newMergeJoinBenchmark(numOuterRows, numInnerDup, numInnerRedundant int) (tc *mergeJoinTestCase, innerDS, outerDS *mockDataSource) {
	ctx := mock.NewContext()
	ctx.GetSessionVars().InitChunkSize = variable.DefInitChunkSize
	ctx.GetSessionVars().MaxChunkSize = variable.DefMaxChunkSize
	ctx.GetSessionVars().SnapshotTS = 1
	ctx.GetSessionVars().StmtCtx.MemTracker = memory.NewTracker(-1, -1)
	ctx.GetSessionVars().StmtCtx.DiskTracker = disk.NewTracker(-1, -1)

	numInnerRows := numOuterRows*numInnerDup + numInnerRedundant
	itc := &indexJoinTestCase{
		outerRows:       numOuterRows,
		innerRows:       numInnerRows,
		concurrency:     4,
		ctx:             ctx,
		outerJoinKeyIdx: []int{0, 1},
		innerJoinKeyIdx: []int{0, 1},
		innerIdx:        []int{0, 1},
		rawData:         wideString,
	}
	tc = &mergeJoinTestCase{*itc, nil}
	outerOpt := mockDataSourceParameters{
		schema: expression.NewSchema(tc.columns()...),
		rows:   numOuterRows,
		ctx:    tc.ctx,
		genDataFunc: func(row int, typ *types.FieldType) interface{} {
			switch typ.Tp {
			case mysql.TypeLong, mysql.TypeLonglong:
				return int64(row)
			case mysql.TypeDouble:
				return float64(row)
			case mysql.TypeVarString:
				return tc.rawData
			default:
				panic("not implement")
			}
		},
	}

	innerOpt := mockDataSourceParameters{
		schema: expression.NewSchema(tc.columns()...),
		rows:   numInnerRows,
		ctx:    tc.ctx,
		genDataFunc: func(row int, typ *types.FieldType) interface{} {
			row = row / numInnerDup
			switch typ.Tp {
			case mysql.TypeLong, mysql.TypeLonglong:
				return int64(row)
			case mysql.TypeDouble:
				return float64(row)
			case mysql.TypeVarString:
				return tc.rawData
			default:
				panic("not implement")
			}
		},
	}

	innerDS = buildMockDataSource(innerOpt)
	outerDS = buildMockDataSource(outerOpt)

	return
}

type mergeJoinType int8

const (
	innerMergeJoin mergeJoinType = iota
)

func benchmarkMergeJoinExecWithCase(b *testing.B, tc *mergeJoinTestCase, innerDS, outerDS *mockDataSource, joinType mergeJoinType) {
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		b.StopTimer()
		var exec Executor
		switch joinType {
		case innerMergeJoin:
			exec = prepare4MergeJoin(tc, innerDS, outerDS)
		}

		tmpCtx := context.Background()
		chk := newFirstChunk(exec)
		outerDS.prepareChunks()
		innerDS.prepareChunks()

		b.StartTimer()
		if err := exec.Open(tmpCtx); err != nil {
			b.Fatal(err)
		}
		for {
			if err := exec.Next(tmpCtx, chk); err != nil {
				b.Fatal(err)
			}
			if chk.NumRows() == 0 {
				break
			}
		}

		if err := exec.Close(); err != nil {
			b.Fatal(err)
		}
		b.StopTimer()
	}
}

func BenchmarkMergeJoinExec(b *testing.B) {
	lvl := log.GetLevel()
	log.SetLevel(zapcore.ErrorLevel)
	defer log.SetLevel(lvl)
	b.ReportAllocs()

	totalRows := 300000

	innerDupAndRedundant := [][]int{
		{1, 0},
		{100, 0},
		{10000, 0},
		{1, 30000},
	}

	childrenUsedSchemas := [][][]bool{
		nil,
		{
			{true, false, false},
			{false, true, false},
		},
	}

	for _, params := range innerDupAndRedundant {
		numInnerDup, numInnerRedundant := params[0], params[1]
		for _, childrenUsedSchema := range childrenUsedSchemas {
			tc, innerDS, outerDS := newMergeJoinBenchmark(totalRows/numInnerDup, numInnerDup, numInnerRedundant)
			inlineProj := false
			if childrenUsedSchema != nil {
				inlineProj = true
				tc.childrenUsedSchema = childrenUsedSchema
			}

			b.Run(fmt.Sprintf("merge join %v InlineProj:%v", tc, inlineProj), func(b *testing.B) {
				benchmarkMergeJoinExecWithCase(b, tc, outerDS, innerDS, innerMergeJoin)
			})
		}
	}
}

type sortCase struct {
	rows       int
	orderByIdx []int
	ndvs       []int
	ctx        sessionctx.Context
}

func (tc sortCase) columns() []*expression.Column {
	return []*expression.Column{
		{Index: 0, RetType: types.NewFieldType(mysql.TypeLonglong)},
		{Index: 1, RetType: types.NewFieldType(mysql.TypeLonglong)},
	}
}

func (tc sortCase) String() string {
	return fmt.Sprintf("(rows:%v, orderBy:%v, ndvs: %v)", tc.rows, tc.orderByIdx, tc.ndvs)
}

func defaultSortTestCase() *sortCase {
	ctx := mock.NewContext()
	ctx.GetSessionVars().InitChunkSize = variable.DefInitChunkSize
	ctx.GetSessionVars().MaxChunkSize = variable.DefMaxChunkSize
	ctx.GetSessionVars().StmtCtx.MemTracker = memory.NewTracker(-1, -1)
	tc := &sortCase{rows: 300000, orderByIdx: []int{0, 1}, ndvs: []int{0, 0}, ctx: ctx}
	return tc
}

func benchmarkSortExec(b *testing.B, cas *sortCase) {
	opt := mockDataSourceParameters{
		schema: expression.NewSchema(cas.columns()...),
		rows:   cas.rows,
		ctx:    cas.ctx,
		ndvs:   cas.ndvs,
	}
	dataSource := buildMockDataSource(opt)
	exec := &SortExec{
		baseExecutor: newBaseExecutor(cas.ctx, dataSource.schema, 4, dataSource),
		ByItems:      make([]*util.ByItems, 0, len(cas.orderByIdx)),
		schema:       dataSource.schema,
	}
	for _, idx := range cas.orderByIdx {
		exec.ByItems = append(exec.ByItems, &util.ByItems{Expr: cas.columns()[idx]})
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		b.StopTimer()
		tmpCtx := context.Background()
		chk := newFirstChunk(exec)
		dataSource.prepareChunks()

		b.StartTimer()
		if err := exec.Open(tmpCtx); err != nil {
			b.Fatal(err)
		}
		for {
			if err := exec.Next(tmpCtx, chk); err != nil {
				b.Fatal(err)
			}
			if chk.NumRows() == 0 {
				break
			}
		}

		if err := exec.Close(); err != nil {
			b.Fatal(err)
		}
		b.StopTimer()
	}
}

func BenchmarkSortExec(b *testing.B) {
	b.ReportAllocs()
	cas := defaultSortTestCase()
	// all random data
	cas.ndvs = []int{0, 0}
	cas.orderByIdx = []int{0, 1}
	b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
		benchmarkSortExec(b, cas)
	})

	ndvs := []int{1, 10000}
	for _, ndv := range ndvs {
		cas.ndvs = []int{ndv, 0}
		cas.orderByIdx = []int{0, 1}
		b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
			benchmarkSortExec(b, cas)
		})

		cas.ndvs = []int{ndv, 0}
		cas.orderByIdx = []int{0}
		b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
			benchmarkSortExec(b, cas)
		})

		cas.ndvs = []int{ndv, 0}
		cas.orderByIdx = []int{1}
		b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
			benchmarkSortExec(b, cas)
		})
	}
}

type limitCase struct {
	rows                  int
	offset                int
	count                 int
	childUsedSchema       []bool
	usingInlineProjection bool
	ctx                   sessionctx.Context
}

func (tc limitCase) columns() []*expression.Column {
	return []*expression.Column{
		{Index: 0, RetType: types.NewFieldType(mysql.TypeLonglong)},
		{Index: 1, RetType: types.NewFieldType(mysql.TypeLonglong)},
	}
}

func (tc limitCase) String() string {
	return fmt.Sprintf("(rows:%v, offset:%v, count:%v, inline_projection:%v)",
		tc.rows, tc.offset, tc.count, tc.usingInlineProjection)
}

func defaultLimitTestCase() *limitCase {
	ctx := mock.NewContext()
	ctx.GetSessionVars().InitChunkSize = variable.DefInitChunkSize
	ctx.GetSessionVars().MaxChunkSize = variable.DefMaxChunkSize
	ctx.GetSessionVars().StmtCtx.MemTracker = memory.NewTracker(-1, -1)
	tc := &limitCase{
		rows:                  30000,
		offset:                10000,
		count:                 10000,
		childUsedSchema:       []bool{false, true},
		usingInlineProjection: false,
		ctx:                   ctx,
	}
	return tc
}

func benchmarkLimitExec(b *testing.B, cas *limitCase) {
	opt := mockDataSourceParameters{
		schema: expression.NewSchema(cas.columns()...),
		rows:   cas.rows,
		ctx:    cas.ctx,
	}
	dataSource := buildMockDataSource(opt)
	var exec Executor
	limit := &LimitExec{
		baseExecutor: newBaseExecutor(cas.ctx, dataSource.schema, 4, dataSource),
		begin:        uint64(cas.offset),
		end:          uint64(cas.offset + cas.count),
	}
	if cas.usingInlineProjection {
		if len(cas.childUsedSchema) > 0 {
			limit.columnIdxsUsedByChild = make([]int, 0, len(cas.childUsedSchema))
			for i, used := range cas.childUsedSchema {
				if used {
					limit.columnIdxsUsedByChild = append(limit.columnIdxsUsedByChild, i)
				}
			}
		}
		exec = limit
	} else {
		columns := cas.columns()
		usedCols := make([]*expression.Column, 0, len(columns))
		exprs := make([]expression.Expression, 0, len(columns))
		for i, used := range cas.childUsedSchema {
			if used {
				usedCols = append(usedCols, columns[i])
				exprs = append(exprs, columns[i])
			}
		}
		proj := &ProjectionExec{
			baseExecutor:  newBaseExecutor(cas.ctx, expression.NewSchema(usedCols...), 0, limit),
			numWorkers:    1,
			evaluatorSuit: expression.NewEvaluatorSuite(exprs, false),
		}
		exec = proj
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		b.StopTimer()
		tmpCtx := context.Background()
		chk := newFirstChunk(exec)
		dataSource.prepareChunks()

		b.StartTimer()
		if err := exec.Open(tmpCtx); err != nil {
			b.Fatal(err)
		}
		for {
			if err := exec.Next(tmpCtx, chk); err != nil {
				b.Fatal(err)
			}
			if chk.NumRows() == 0 {
				break
			}
		}

		if err := exec.Close(); err != nil {
			b.Fatal(err)
		}
		b.StopTimer()
	}
}

func BenchmarkLimitExec(b *testing.B) {
	b.ReportAllocs()
	cas := defaultLimitTestCase()
	usingInlineProjection := []bool{false, true}
	for _, inlineProjection := range usingInlineProjection {
		cas.usingInlineProjection = inlineProjection
		b.Run(fmt.Sprintf("%v", cas), func(b *testing.B) {
			benchmarkLimitExec(b, cas)
		})
	}
}


text:
config.baseTitle = 'Revel framework'
config.siteName = 'Revel framework'
config.siteDes = 'A high productivity, full-stack web framework for the Go language.'
config.siteKey = 'revel-framework'
config.assetBasePath = '/'

// https://github.com/youzan/php-co-koa
config.docProject = 'revel/revel.github.io'
config.project = 'revel/revel'

config.authorPage = 'https://github.com/revel'
config.authorName = 'revel'

config.theme = 'yeti'
config.codeTheme = 'github'
// config.catelogPage = 'SUMMARY.md'
config.catelogPage = '/books/revel/catelog.md'
config.defaultPage = 'tutorial/index.md'
config.makeTOC = true
config.emptyData = 'No content to display!'

config.onContentWrited = function (contentDom) {
  contentDom.find('h2').first().remove()
  // contentDom.find('h1').first().prevAll().remove()
}


text:
package io.takari.bpm.api;

import java.util.Map;
import java.util.Set;

/**
 * The execution context. Provides access to the process variables.
 */
public interface ExecutionContext {

    /**
     * Key of latest handled @{BpmnError}. Can be accessed with @{code #getVariable(LAST_ERROR_KEY}.
     */
    String LAST_ERROR_KEY = "lastError";

    String PROCESS_BUSINESS_KEY = "__processBusinessKey";

    String CURRENT_FLOW_NAME_KEY = "__currentFlow";

    Object getVariable(String key);

    Map<String, Object> getVariables();

    void setVariable(String key, Object value);

    boolean hasVariable(String key);

    void removeVariable(String key);

    Set<String> getVariableNames();

    <T> T eval(String expr, Class<T> type);

    Map<String, Object> toMap();

    Object interpolate(Object v);

    void suspend(String messageRef);

    void suspend(String messageRef, Object payload, boolean resumeFromSameStep);

    String getProcessDefinitionId();

    String getElementId();
}


text:
//
//  LoginViewController.m
//  DeliciousMenu
//
//  Created by scjy on 16/3/8.
//  Copyright © 2016年 刘海艳. All rights reserved.
//

#import "LoginViewController.h"
#import "UIViewController+Comment.h"
#import "ResignViewController.h"
#import <BmobSDK/Bmob.h>
#import "ProgressHUD.h"
#import "ViewController.h"
@interface LoginViewController ()

@property(nonatomic, strong) UITextField *resignTF;
@property(nonatomic, strong) UITextField *resignPass;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"登录";
    [self showBackButtonWithImage:@"btn_left"];

    self.resignTF = [[UITextField alloc] initWithFrame:CGRectMake(kWidth/8, kHeight/6, kWidth*3/4, 45)];
    self.resignTF.placeholder = @"请输入用户名";
    self.resignTF.textAlignment = NSTextAlignmentCenter;
    self.resignTF.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.resignTF];

    self.resignPass = [[UITextField alloc] initWithFrame:CGRectMake(kWidth/8, kHeight/6+50, kWidth*3/4, 45)];
    self.resignPass.placeholder = @"请输入密码";
    self.resignPass.textAlignment = NSTextAlignmentCenter;
    self.resignPass.borderStyle = UITextBorderStyleRoundedRect;
    self.resignPass.secureTextEntry = YES;
    [self.view addSubview:self.resignPass];

    //QQ登录按钮
    UIButton *QQfinish = [UIButton buttonWithType:UIButtonTypeCustom];
    QQfinish.frame = CGRectMake(kWidth/8, kHeight/6 + 200, kWidth/4, 45);
    UIImageView *qq = [[UIImageView alloc] initWithFrame:CGRectMake(0, 10, 30, 30)];

    qq.image = [UIImage imageNamed:@"485c77cc7"];
    [QQfinish setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];

    [QQfinish addSubview:qq];
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(45,0, QQfinish.frame.size.width*3/4, 45)];
    lable.text = @"QQ登录";
    lable.tintColor = [UIColor grayColor];
    [QQfinish addSubview:lable];
    [self.view addSubview:QQfinish];

    //登录按钮
    UIButton *Loginfinish = [UIButton buttonWithType:UIButtonTypeCustom];
    [Loginfinish setTitle:@"登录" forState:UIControlStateNormal];
    [Loginfinish setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [Loginfinish addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    Loginfinish.frame = CGRectMake(kWidth/8, kHeight/6+100, kWidth/4, 45);
    [self.view addSubview:Loginfinish];

    //注册
    UIButton *resignLfinish = [UIButton buttonWithType:UIButtonTypeCustom];
    [resignLfinish setTitle:@"注册" forState:UIControlStateNormal];
    [resignLfinish setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    resignLfinish.frame = CGRectMake(kWidth/8, kHeight/6+150, kWidth/4, 45);
    [resignLfinish addTarget:self action:@selector(pushResignVC) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:resignLfinish];

}

-(void)login{

    [ProgressHUD show:@"正在登录"];

    [BmobUser loginWithUsernameInBackground:@"小明"password:@"123456"];

    [BmobUser loginWithUsernameInBackground:self.resignTF.text password:self.resignPass.text block:^(BmobUser *user, NSError *error) {
        if (user) {
            YiralLog(@"%@",self.resignTF.text);
        }

    }];
    [ProgressHUD showSuccess:@"恭喜您,登录成功"];

    ViewController *VC = [[ViewController alloc] init];
    [self.navigationController pushViewController:VC animated:YES];

}
//在视图即将消失的时候,收起第三方菊花

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    [ProgressHUD dismiss];

}

-(void)pushResignVC{

    ResignViewController *resign = [[ResignViewController alloc] init];
    [self.navigationController pushViewController:resign animated:YES];

}

//点击右下角回收键盘;
-(BOOL)textFieldShouldReturn:(UITextField *)textField{

    [textField resignFirstResponder];

    return YES;

}

//点击空白处回收键盘;
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //两种方法回收键盘;
    [self.view endEditing:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/first_party_sets/first_party_sets_overrides_policy_handler.h"

#include <stdlib.h>
#include <iostream>

#include "base/at_exit.h"
#include "base/i18n/icu_util.h"
#include "base/json/json_reader.h"
#include "components/policy/core/browser/policy_error_map.h"
#include "components/policy/core/common/chrome_schema.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/policy_constants.h"
#include "testing/libfuzzer/proto/json.pb.h"
#include "testing/libfuzzer/proto/json_proto_converter.h"
#include "testing/libfuzzer/proto/lpm_interface.h"

namespace first_party_sets {

struct IcuEnvironment {
  IcuEnvironment() { CHECK(base::i18n::InitializeICU()); }

  // used by ICU integration.
  base::AtExitManager at_exit_manager;
};

IcuEnvironment* test_case = new IcuEnvironment();

DEFINE_PROTO_FUZZER(const json_proto::JsonValue& json_value) {
  json_proto::JsonProtoConverter converter;
  std::string native_input = converter.Convert(json_value);
  FirstPartySetsOverridesPolicyHandler handler(policy::GetChromeSchema());

  if (getenv("LPM_DUMP_NATIVE_INPUT"))
    std::cout << native_input << std::endl;

  policy::PolicyMap policy_map;
  policy_map.Set(policy::key::kFirstPartySetsOverrides,
                 policy::PolicyLevel::POLICY_LEVEL_MANDATORY,
                 policy::PolicyScope::POLICY_SCOPE_MACHINE,
                 policy::PolicySource::POLICY_SOURCE_ENTERPRISE_DEFAULT,
                 base::JSONReader::Read(native_input),
                 /*external_data_fetcher=*/nullptr);
  policy::PolicyErrorMap errors;
  handler.CheckPolicySettings(policy_map, &errors);
}

}  // namespace first_party_sets


text:
package me.magicall.game;

import me.magicall.game.io.OutputSource;
import me.magicall.game.player.Player;

/**
 * 游戏启动器。builder模式。
 *
 * @author MaGiCalL
 */
public interface GameLauncher extends OutputSource {

	/**
	 * 启动一个游戏
	 */
	Game launch(Player mainPlayer);

}


text:
#include "CCPUOnEmissionObserverTranslator.h"
#include "extensions/Particle3D/PU/CCPUParticleSystem3D.h"
#include "extensions/Particle3D/PU/CCPUDynamicAttribute.h"
#include "extensions/Particle3D/PU/CCPUDynamicAttributeTranslator.h"

NS_CC_BEGIN

PUOnEmissionObserverTranslator::PUOnEmissionObserverTranslator()
{
}
//-------------------------------------------------------------------------
bool PUOnEmissionObserverTranslator::translateChildProperty( PUScriptCompiler* /*compiler*/, PUAbstractNode* /*node*/ )
{
    return false;
}

bool PUOnEmissionObserverTranslator::translateChildObject( PUScriptCompiler* /*compiler*/, PUAbstractNode* /*node*/ )
{
    // No objects
    return false;
}

NS_CC_END


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="button_and_edit">45dp</dimen>
</resources>


text:
@implementation ChangePasswordStatus

@end


text:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { MetadataComponent } from './metadata.component';

const routes: Routes = [
  { path: 'metadata',  component: MetadataComponent },
  // { path: 'oauth', component: OAuthComponent, outlet: 'popup' }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class MetadataRoutingModule { }


text:
function changeMenuStyle(obj,new_style) {
  obj.className = new_style
}

function showCursor() {
    document.body.style.cursor = "hand"
}

function hideCursor() {
    document.body.style.cursor = "default"
}

function confirmDelete() {
    if (confirm("Are you sure you want to delete?"))
        return true
    return false
}

function setUrl ( url, target ) {
  if ( target == '_self' ) {
    document.location.href = url;
  } else {
    open(url,target);
  }
}

function spawn(url,winw,winh) {
  var w = window.open(url, "_blank",
      "screenX=0,screenY=0,status=yes,toolbar=yes,menubar=yes,location=yes,width=" + winw + ",height=" + winh +
      ",scrollbars=yes,resizable=yes");
}

function spawnX(url,winw,winh) {
  var w = window.open(url, "_blank",
      "screenX=0,screenY=0,status=no,toolbar=yes,menubar=no,location=no,width=" + winw + ",height=" + winh +
      ",scrollbars=yes,resizable=yes");
}

function showWindow(imgscr) {
       myWind = window.open(imgscr,"subWindow","HEIGHT=520,WIDTH=520,resizable");
       myWind.focus()
}

function URLencode(sStr) {
    return escape(sStr).replace(/\+/g, '%2C').replace(/\"/g,'%22').replace(/\'/g, '%27')
}

// *********************** Begin URL encode javascript function from CMAP **********************

var active = 'false';
var NS6 = (document.getElementById && !document.all) ? true : false;

function ifenter(e,form) {
  if (!active) return;

  var keycode;
  if (window.event)         // IE
    keycode = window.event.keyCode;
  else
  if (e) {                  // NS
    if (NS6)
      keycode = e.keyCode;  // NS6: this shows bksp, enter ...
    else
      keycode = e.which;    // NS6: real   NS4: all keys
  }
  else return true;

  if (NS6) {
    if (keycode == 13) {
      Search(form);
      e.cancelBubble = true;
      return false;
    }
    else
      return true;
  }
  else if (keycode == 13) {
    Search(form);
    return false;
  }
  else
    return true;
}

function Search(form) {

    var searchTerm1 = document.SiteSearch.term.value;
    var searchTerm = searchTerm1.replace(/ /g, "%20");

    if ( ( searchTerm == null ) || ( searchTerm == "" ) || ( searchTerm == " ") ) {
        alert("Please enter a search term.");
    } else {
        location = '/NCICB/ZopeSearch?start:int=0&term=' + searchTerm;
    }

}

function setSize() {
 if(!document.layers) {
   document.forms[0].term.size=15;
  }
}


text:
AppBook
=======

An app that show you the rank list of Apple App Store.

1. most using Swift code.
2. fast scolling with image async rendering and label async rendering.


text:
using System;
using System.Security.Cryptography.X509Certificates;

namespace ConDep.Dsl
{
    public interface IOfferIisWebSiteOptions
    {
        /// <summary>
        /// Sets the physical path of the Web Site.
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        IOfferIisWebSiteOptions PhysicalPath(string path);

        /// <summary>
        /// Adds a Http Binding to the Web Site.
        /// </summary>
        /// <param name="httpBindingOptions">At least one of the options must be specified for the binding to be valid.</param>
        /// <returns></returns>
        IOfferIisWebSiteOptions AddHttpBinding(Action<IOfferBindingOptions> httpBindingOptions);

        /// <summary>
        /// Finds certifcate in local certificate store and copies certificate to server and adds to binding.
        /// </summary>
        /// <param name="findType">Type of certificate attribute to search in.</param>
        /// <param name="findName">Value of certificate attribute.</param>
        /// <param name="bindingOptions">Binding options for setting port, ip and host name.</param>
        /// <returns></returns>
        IOfferIisWebSiteOptions AddHttpsBinding(X509FindType findType, string findName, Action<IOfferBindingOptions> bindingOptions);

        /// <summary>
        /// Associate application pool with Web Site. To create an Application Pool, use the IISAppPool operation (e.g. require.IISAppPool)
        /// </summary>
        /// <param name="appPoolName"></param>
        /// <returns></returns>
        IOfferIisWebSiteOptions ApplicationPool(string appPoolName);

        /// <summary>
        /// Adds an empty Web Application to the Web Site
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        IOfferIisWebSiteOptions WebApp(string name);

        /// <summary>
        /// Adds an empty Web Application with defined options to the Web Site.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        IOfferIisWebSiteOptions WebApp(string name, Action<IOfferIisWebAppOptions> options);

        /// <summary>
        /// Sets the log directory for the Web Site.
        /// </summary>
        /// <param name="logDirectory"></param>
        /// <returns></returns>
        IOfferIisWebSiteOptions LogDirectory(string logDirectory);
    }
}