text:
<?php

namespace Taco\Console;

use PHPUnit_Framework_TestCase;

/**
 * prog one two three
 * prog one two three -p
 * prog one two three --pro
 * prog one two three -p abc
 * prog one two three --pro abc
 * prog one two three --pro abc four five
 * prog one two three --pro abc --pro def
 *
 * Jsou dvě skupiny parametrů:
 * - argumenty: které jsou poziční, ale pomocí jména je možné je vyjmout z pořadí.
 * - optiony:   které jsou mimo pozicy.
 *
 * @call phpunit OptionSignatureTest.php
 */
class OptionSignatureTest extends PHPUnit_Framework_TestCase
{

	/**
	 * Vyžadované parametry jsou poziční. Mohou se zadat bez uvedení jména, a nebo s uvedením jména a tím pořadí přeskočit.
	 */
	function _testRequiredArgument1()
	{
		$sig = new OptionSignature();
		$sig->addArgument('name|n', $sig::TYPE_TEXT, '...');
		$sig->addArgumentDefault('age|a', $sig::TYPE_INT, 42, '...');
		$sig->addOption('sex', $sig::TYPE_ENUM(['male','female']), 'male', '...');

		$this->assertEquals(array('name', 'age', 'sex'), $sig->getOptionNames(), 'List of option names.');
		$this->assertEqualsOption('name', $sig::TYPE_TEXT, $sig->getOptionAt(0));
		$this->assertEqualsOption('age', $sig::TYPE_INT, $sig->getOptionAt(1));
		$this->assertEquals(array('age' => 42, 'sex' => 'male'), $sig->getDefaultValues(), 'List of option names.');
	}

	/**
	 * Vyžadované parametry jsou poziční. Mohou se zadat bez uvedení jména, a nebo s uvedením jména a tím pořadí přeskočit.
	 */
	function testRequiredArgument()
	{
		$sig = new OptionSignature();
		$sig->addArgument('name|n', $sig::TYPE_TEXT, 'Use name');
		$sig->addArgument('age', $sig::TYPE_INT, 'Use age');

		$this->assertEquals(array('name', 'age'), $sig->getOptionNames(), 'List of option names.');
		$this->assertEqualsOption('name', $sig::TYPE_TEXT, $sig->getOption('name'));
		$this->assertEqualsOption('name', $sig::TYPE_TEXT, $sig->getOption('--name'));
		$this->assertEqualsOption('name', $sig::TYPE_TEXT, $sig->getOption(' --name'));
		$this->assertEquals('n', $sig->getOption('name')->getShortname());
		$this->assertEquals($sig->getOption('n'), $sig->getOption('name'));
		$this->assertEqualsOption('age', $sig::TYPE_INT, $sig->getOption(' age'));
		$this->assertNull($sig->getOption('age')->getShortname());
		//$this->assertFalse($sig->hasPositional());
	}

	/**
	 * Volitelné parametry musí být vždy uvedeny jménem.
	 */
	function testOptionalArgument()
	{
		$sig = new OptionSignature();
		//~ $sig->addOptional('show|s', True, $sig::TYPE_BOOL, 'Zobrazit volitelně.');
		$sig->addOption('show|s', $sig::TYPE_BOOL, True, 'Zobrazit volitelně.');
		$sig->addOption('size', $sig::TYPE_INT, 42, 'Use age');

		$this->assertEquals(array('show', 'size'), $sig->getOptionNames(), 'List of option names.');
		$this->assertEqualsOption('show', $sig::TYPE_BOOL, $sig->getOption('show'));
		$this->assertEqualsOption('size', $sig::TYPE_INT, $sig->getOption('size'));
		$this->assertEquals('s', $sig->getOption('show')->getShortname());
		$this->assertEquals($sig->getOption('s'), $sig->getOption('show'));
	}

	/**
	 * shortcut for $sig->addOptional('show|s', True, $sig::TYPE_BOOL, 'Zobrazit volitelně.');
	 */
	function testFlagArgument()
	{
		$sig = new OptionSignature();
		$sig->addFlag('show|s', 'Zobrazit volitelně.');
		$sig->addFlag('size', 'Use age');

		$this->assertEquals(array('show', 'size'), $sig->getOptionNames(), 'List of option names.');
		$this->assertEqualsOption('show', $sig::TYPE_BOOL, $sig->getOption('show'));
		$this->assertEqualsOption('size', $sig::TYPE_BOOL, $sig->getOption('size'));
		$this->assertEquals('s', $sig->getOption('show')->getShortname());
		$this->assertEquals($sig->getOption('s'), $sig->getOption('show'));
	}

	function testHelpFlag()
	{
		$sig = new OptionSignature();
		$sig->addFlag('help|h', 'Help command');

		$this->assertEquals(['help'], $sig->getOptionNames());
		$this->assertEquals('h', $sig->getOption('help')->getShortname());
	}

	function testComplex()
	{
		$sig = new OptionSignature();
		$sig->addOption('working-dir', $sig::TYPE_TEXT, '.', 'Cesta k pracovnímu adresáři');
		$sig->addOption('config', $sig::TYPE_TEXT, 'config.ini', 'Jméno configu.');
		$sig->addFlag('show|s', 'Zobrazit volitelně.');
		$sig->addArgument('name', $sig::TYPE_TEXT, 'poziční');
		$sig->addArgument('surname', $sig::TYPE_TEXT, 'poziční');
		$sig->addArgumentDefault('size', $sig::TYPE_INT, 42, 'Use age');

		$this->assertEquals(array('name', 'surname', 'size', 'working-dir', 'config', 'show'), $sig->getOptionNames());
		$this->assertEqualsOption('show', $sig::TYPE_BOOL, $sig->getOption('show'));
		$this->assertEqualsOption('name', $sig::TYPE_TEXT, $sig->getOptionAt(0));
		$this->assertEqualsOption('surname', $sig::TYPE_TEXT, $sig->getOptionAt(1));
		$this->assertEqualsOption('size', $sig::TYPE_INT, $sig->getOption('size'));
	}

	function testMergeSignature()
	{
		$a = new OptionSignature();
		$a->addArgument('a1', $a::TYPE_TEXT, '..');
		$a->addArgumentDefault('a2', $a::TYPE_INT, 42, '..');
		$a->addOption('a3', $a::TYPE_TEXT, 'config.ini', '...');

		$b = new OptionSignature();
		$b->addArgument('b1', $b::TYPE_TEXT, '..');
		$b->addArgumentDefault('b2|x', $b::TYPE_INT, 42, '..');
		$b->addOption('b3|y', $b::TYPE_TEXT, 'config.ini', '...');

		$a->merge($b);
		$this->assertEquals(array('a1', 'a2', 'b1', 'b2', 'a3', 'b3'), $a->getOptionNames());
		$this->assertEqualsOption('a1', $a::TYPE_TEXT, $a->getOptionAt(0));
		$this->assertEqualsOption('a2', $a::TYPE_INT, $a->getOptionAt(1));
		$this->assertEqualsOption('b1', $a::TYPE_TEXT, $a->getOptionAt(2));
		$this->assertEqualsOption('b2', $a::TYPE_INT, $a->getOptionAt(3));
		$this->assertEquals('x', $a->getOptionAt(3)->getShortname());
		$this->assertEquals('y', $a->getOption('b3')->getShortname());
	}

	private function assertEqualsOption($name, $type, $item)
	{
		$this->assertEquals($name, $item->getName());
		$this->assertEquals($type, $item->getType());
	}

}


text:
import assert from 'assert';

export function testMethodProperty(object, key, options) {
  let desc = Object.getOwnPropertyDescriptor(object, key);
  let { enumerable = false, configurable = false, writable = false, length } = options;

  assert.ok(desc, `Property ${ key.toString() } exists`);

  if (options.get || options.set) {
    if (options.get) {
      assert.equal(typeof desc.get, 'function', 'Getter is a function');
      assert.equal(desc.get.length, 0, 'Getter length is 0');
    } else {
      assert.equal(desc.get, undefined, 'Getter is undefined');
    }

    if (options.set) {
      assert.equal(typeof desc.set, 'function', 'Setter is a function');
      assert.equal(desc.set.length, 1, 'Setter length is 1');
    } else {
      assert.equal(desc.set, undefined, 'Setter is undefined');
    }
  } else {
    assert.equal(typeof desc.value, 'function', 'Value is a function');
    assert.equal(desc.value.length, length, `Function length is ${ length }`);
    assert.equal(desc.writable, writable, `Writable property is correct ${ writable }`);
  }

  assert.equal(desc.enumerable, enumerable, `Enumerable property is ${ enumerable }`);
  assert.equal(desc.configurable, configurable, `Configurable property is ${ configurable }`);
}

redpajama_set_name: RedPajamaGithub


text:
package io.agrest.runtime.constraints;

import io.agrest.EntityConstraint;
import io.agrest.ResourceEntity;
import io.agrest.constraints.Constraint;
import io.agrest.it.fixture.cayenne.E1;
import io.agrest.it.fixture.cayenne.E2;
import io.agrest.meta.AgPersistentEntity;
import io.agrest.unit.TestWithCayenneMapping;
import org.apache.cayenne.map.ObjEntity;
import org.junit.Before;
import org.junit.Test;

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

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ConstraintsHandlerWithDefaultsTest extends TestWithCayenneMapping {

	private ConstraintsHandler constraintHandler;
	private AgPersistentEntity<E1> age1;
	private AgPersistentEntity<E2> age2;

	@SuppressWarnings("unchecked")
	@Before
	public void before() {

		List<EntityConstraint> r = new ArrayList<>();
		r.add(new DefaultEntityConstraint("E1", true, false, Collections.singleton(E1.AGE.getName()),
				Collections.<String> emptySet()));

		List<EntityConstraint> w = new ArrayList<>();
		w.add(new DefaultEntityConstraint("E2", false, false, Collections.singleton(E2.ADDRESS.getName()),
				Collections.<String> emptySet()));

		ObjEntity e1 = runtime.getChannel().getEntityResolver().getObjEntity(E1.class);
		ObjEntity e2 = runtime.getChannel().getEntityResolver().getObjEntity(E2.class);

		age1 = mock(AgPersistentEntity.class);
		when(age1.getObjEntity()).thenReturn(e1);
		when(age1.getType()).thenReturn(E1.class);
		when(age1.getName()).thenReturn(e1.getName());

		age2 = mock(AgPersistentEntity.class);
		when(age2.getObjEntity()).thenReturn(e2);
		when(age2.getType()).thenReturn(E2.class);
		when(age2.getName()).thenReturn(e2.getName());

		this.constraintHandler = new ConstraintsHandler(r, w);
	}

	@Test
	public void testConstrainResponse_PerRequest() {

		Constraint<E1> tc1 = Constraint.excludeAll(E1.class).attributes(E1.DESCRIPTION);

		ResourceEntity<E1> te1 = new ResourceEntity<>(age1);
		appendAttribute(te1, E1.AGE, Integer.class);
		appendAttribute(te1, E1.DESCRIPTION, String.class);

		constraintHandler.constrainResponse(te1, null, tc1);
		assertEquals(1, te1.getAttributes().size());
		assertTrue(te1.getAttributes().containsKey(E1.DESCRIPTION.getName()));
		assertTrue(te1.getChildren().isEmpty());
	}

	@Test
	public void testConstrainResponse_Default() {

		ResourceEntity<E1> te1 = new ResourceEntity<>(age1);
		appendAttribute(te1, E1.AGE, Integer.class);
		appendAttribute(te1, E1.DESCRIPTION, String.class);

		constraintHandler.constrainResponse(te1, null, null);
		assertEquals(1, te1.getAttributes().size());
		assertTrue(te1.getAttributes().containsKey(E1.AGE.getName()));
		assertTrue(te1.getChildren().isEmpty());
	}

	@Test
	public void testConstrainResponse_None() {

		ResourceEntity<E2> te1 = new ResourceEntity<>(age2);
		appendAttribute(te1, E2.ADDRESS, String.class);
		appendAttribute(te1, E2.NAME, String.class);

		constraintHandler.constrainResponse(te1, null, null);
		assertEquals(2, te1.getAttributes().size());
		assertTrue(te1.getAttributes().containsKey(E2.ADDRESS.getName()));
		assertTrue(te1.getAttributes().containsKey(E2.NAME.getName()));

		assertTrue(te1.getChildren().isEmpty());
	}

}


text:
require 'payrollee_cz/version'

require 'bigdecimal'
require 'payrollee_cz/core/payroll_period'
require 'payrollee_cz/core_items/tag_refer'
require 'payrollee_cz/core_items/code_name_refer'
require 'payrollee_cz/core_items/payroll_tag'
require 'payrollee_cz/core_items/payroll_concept'
require 'payrollee_cz/core_items/payroll_result'
require 'payrollee_cz/concepts/unknown_concept'
require 'payrollee_cz/core/pay_concept_gateway'
require 'payrollee_cz/pay_tags/unknown_tag'
require 'payrollee_cz/core/pay_tag_gateway'
require 'payrollee_cz/core/payroll_process'


text:
<?php
/**
 * The contents of this file was generated using the WSDLs as provided by eBay.
 *
 * DO NOT EDIT THIS FILE!
 */

namespace DTS\eBaySDK\BusinessPoliciesManagement\Types;

/**
 *
 * @property string[] $shipToLocation
 * @property string $shippingService
 * @property integer $sortOrderId
 * @property boolean $freeShipping
 * @property \DTS\eBaySDK\BusinessPoliciesManagement\Types\Amount $codFee
 * @property boolean $fastShipping
 * @property \DTS\eBaySDK\BusinessPoliciesManagement\Types\Amount $shippingServiceAdditionalCost
 * @property \DTS\eBaySDK\BusinessPoliciesManagement\Types\Amount $shippingServiceCost
 * @property \DTS\eBaySDK\BusinessPoliciesManagement\Types\Amount $shippingSurcharge
 * @property boolean $buyerResponsibleForShipping
 * @property boolean $buyerResponsibleForPickup
 */
class ShippingPolicyInfoService extends \DTS\eBaySDK\Types\BaseType
{
    /**
     * @var array Properties belonging to objects of this class.
     */
    private static $propertyTypes = [
        'shipToLocation' => [
            'type' => 'string',
            'repeatable' => true,
            'attribute' => false,
            'elementName' => 'shipToLocation'
        ],
        'shippingService' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'shippingService'
        ],
        'sortOrderId' => [
            'type' => 'integer',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'sortOrderId'
        ],
        'freeShipping' => [
            'type' => 'boolean',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'freeShipping'
        ],
        'codFee' => [
            'type' => 'DTS\eBaySDK\BusinessPoliciesManagement\Types\Amount',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'codFee'
        ],
        'fastShipping' => [
            'type' => 'boolean',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'fastShipping'
        ],
        'shippingServiceAdditionalCost' => [
            'type' => 'DTS\eBaySDK\BusinessPoliciesManagement\Types\Amount',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'shippingServiceAdditionalCost'
        ],
        'shippingServiceCost' => [
            'type' => 'DTS\eBaySDK\BusinessPoliciesManagement\Types\Amount',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'shippingServiceCost'
        ],
        'shippingSurcharge' => [
            'type' => 'DTS\eBaySDK\BusinessPoliciesManagement\Types\Amount',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'shippingSurcharge'
        ],
        'buyerResponsibleForShipping' => [
            'type' => 'boolean',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'buyerResponsibleForShipping'
        ],
        'buyerResponsibleForPickup' => [
            'type' => 'boolean',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'buyerResponsibleForPickup'
        ]
    ];

    /**
     * @param array $values Optional properties and values to assign to the object.
     */
    public function __construct(array $values = [])
    {
        list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);

        parent::__construct($parentValues);

        if (!array_key_exists(__CLASS__, self::$properties)) {
            self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
        }

        if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
            self::$xmlNamespaces[__CLASS__] = 'xmlns="http://www.ebay.com/marketplace/selling/v1/services"';
        }

        $this->setValues(__CLASS__, $childValues);
    }
}


text:
"""Describe logbook events."""
from homeassistant.components.logbook import LazyEventPartialState
from homeassistant.components.logbook.const import (
    LOGBOOK_ENTRY_CONTEXT_ID,
    LOGBOOK_ENTRY_ENTITY_ID,
    LOGBOOK_ENTRY_MESSAGE,
    LOGBOOK_ENTRY_NAME,
    LOGBOOK_ENTRY_SOURCE,
)
from homeassistant.const import ATTR_ENTITY_ID, ATTR_NAME
from homeassistant.core import HomeAssistant, callback

from . import ATTR_SOURCE, EVENT_AUTOMATION_TRIGGERED
from .const import DOMAIN

@callback
def async_describe_events(hass: HomeAssistant, async_describe_event):  # type: ignore[no-untyped-def]
    """Describe logbook events."""

    @callback
    def async_describe_logbook_event(event: LazyEventPartialState):  # type: ignore[no-untyped-def]
        """Describe a logbook event."""
        data = event.data
        message = "triggered"
        if ATTR_SOURCE in data:
            message = f"{message} by {data[ATTR_SOURCE]}"

        return {
            LOGBOOK_ENTRY_NAME: data.get(ATTR_NAME),
            LOGBOOK_ENTRY_MESSAGE: message,
            LOGBOOK_ENTRY_SOURCE: data.get(ATTR_SOURCE),
            LOGBOOK_ENTRY_ENTITY_ID: data.get(ATTR_ENTITY_ID),
            LOGBOOK_ENTRY_CONTEXT_ID: event.context_id,
        }

    async_describe_event(
        DOMAIN, EVENT_AUTOMATION_TRIGGERED, async_describe_logbook_event
    )


text:
<include file="Frame:header"/>

<link rel="stylesheet" href="tpl/Agent/Common/js/formCheck/theme/grey/formcheck.css" type="text/css" media="screen" />
<link href="tpl/Agent/Common/style/calendar.css" type="text/css" rel="stylesheet">

修改资料

   <form method="post" action="?g=Agent&m=Site&a=index" id="myform">

          需要审核
          <input type="radio" name="needcheckuser" value="true" <php>if($thisAgent['needcheckuser']==1)echo checked;</php> /> 注册时无需要审核 <input type="radio" name="needcheckuser" value="false" <php>if($thisAgent['needcheckuser']!=1)echo checked;</php> /> 注册时需要审核

          注册填写手机号
          <input type="radio" name="regneedmp" value="true" <php>if($thisAgent['regneedmp']==1)echo checked;</php> /> 需要填写手机号 <input type="radio" name="regneedmp" value="false" <php>if($thisAgent['regneedmp']==0)echo checked;</php> /> 不需要填写手机号

          注册后等级
          <select name="reggid">
      <Saivilist array="groups" foreach="g">
      <option value="{Saivi:$g.id}" <if condition="$thisAgent['reggid'] eq $g['id']">selected</if>>{Saivi:$g.name}</option>
      </Saivilist>
      </select>
         仅注册不需要审核的时候有效

          注册后免费天数
          <input type="text" name="regvaliddays" style="width:100px;" class="validate['required','digit'] colorblur" value="{Saivi:$thisAgent.regvaliddays}" />

            <input type="submit" name="doSubmit" value="提交" class="button"/>

        <input type="hidden" value="<?php echo $_SERVER['HTTP_REFERER'];?>" name="referer" />
</form>
<include file="Frame:footer"/>


text:
class CommandsChannel < ApplicationCable::Channel
  def subscribed
    stream_from "commands_#{current_user.id}"
  end
end


text:
package net.i2p.router.tunnel.pool;

import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

import net.i2p.data.Base64;
import net.i2p.data.ByteArray;
import net.i2p.data.DataHelper;
import net.i2p.data.Hash;
import net.i2p.data.RouterIdentity;
import net.i2p.data.RouterInfo;
import net.i2p.data.TunnelId;
import net.i2p.data.i2np.BuildRequestRecord;
import net.i2p.data.i2np.BuildResponseRecord;
import net.i2p.data.i2np.I2NPMessage;
import net.i2p.data.i2np.TunnelBuildMessage;
import net.i2p.data.i2np.TunnelBuildReplyMessage;
import net.i2p.data.i2np.TunnelGatewayMessage;
import net.i2p.data.i2np.VariableTunnelBuildMessage;
import net.i2p.data.i2np.VariableTunnelBuildReplyMessage;
import net.i2p.router.HandlerJobBuilder;
import net.i2p.router.Job;
import net.i2p.router.JobImpl;
import net.i2p.router.OutNetMessage;
import net.i2p.router.RouterContext;
import net.i2p.router.peermanager.TunnelHistory;
import net.i2p.router.tunnel.BuildMessageProcessor;
import net.i2p.router.tunnel.BuildReplyHandler;
import net.i2p.router.tunnel.HopConfig;
import net.i2p.router.tunnel.TunnelDispatcher;
import net.i2p.router.util.CDQEntry;
import net.i2p.router.util.CoDelBlockingQueue;
import net.i2p.stat.Rate;
import net.i2p.stat.RateStat;
import net.i2p.util.Log;

/**
 * Handle the received tunnel build message requests and replies,
 * including sending responsses to requests, updating the
 * lists of our tunnels and participating tunnels,
 * and updating stats.
 *
 * Replies are handled immediately on reception; requests are queued.
 * As of 0.8.11 the request queue is handled in a separate thread,
 * it used to be called from the BuildExecutor thread loop.
 *
 * Note that 10 minute tunnel expiration is hardcoded in here.
 */
class BuildHandler implements Runnable {
    private final RouterContext _context;
    private final Log _log;
    private final TunnelPoolManager _manager;
    private final BuildExecutor _exec;
    private final Job _buildMessageHandlerJob;
    private final Job _buildReplyMessageHandlerJob;
    private final BlockingQueue<BuildMessageState> _inboundBuildMessages;
    private final BuildMessageProcessor _processor;
    private final RequestThrottler _requestThrottler;
    private final ParticipatingThrottler _throttler;
    private final BuildReplyHandler _buildReplyHandler;
    private final AtomicInteger _currentLookups = new AtomicInteger();
    private volatile boolean _isRunning;

    /** TODO these may be too high, review and adjust */
    private static final int MIN_QUEUE = 18;
    private static final int MAX_QUEUE = 192;

    private static final int NEXT_HOP_LOOKUP_TIMEOUT = 15*1000;
    private static final int PRIORITY = OutNetMessage.PRIORITY_BUILD_REPLY;

    /** limits on concurrent next-hop RI lookup */
    private static final int MIN_LOOKUP_LIMIT = 10;
    private static final int MAX_LOOKUP_LIMIT = 100;
    /** limit lookups to this % of current participating tunnels */
    private static final int PERCENT_LOOKUP_LIMIT = 3;

    /**
     *  This must be high, as if we timeout the send we remove the tunnel from
     *  participating via OnFailedSendJob.
     *  If them msg actually got through then we will be dropping
     *  all the traffic in TunnelDispatcher.dispatch(TunnelDataMessage msg, Hash recvFrom).
     *  10s was not enough.
     */
    private static final int NEXT_HOP_SEND_TIMEOUT = 25*1000;

    public BuildHandler(RouterContext ctx, TunnelPoolManager manager, BuildExecutor exec) {
        _context = ctx;
        _log = ctx.logManager().getLog(getClass());
        _manager = manager;
        _exec = exec;
        // Queue size = 12 * share BW / 48K
        int sz = Math.min(MAX_QUEUE, Math.max(MIN_QUEUE, TunnelDispatcher.getShareBandwidth(ctx) * MIN_QUEUE / 48));
        //_inboundBuildMessages = new CoDelBlockingQueue(ctx, "BuildHandler", sz);
        _inboundBuildMessages = new LinkedBlockingQueue<BuildMessageState>(sz);

        _context.statManager().createRateStat("tunnel.reject.10", "How often we reject a tunnel probabalistically", "Tunnels", new long[] { 60*1000, 10*60*1000 });
        _context.statManager().createRateStat("tunnel.reject.20", "How often we reject a tunnel because of transient overload", "Tunnels", new long[] { 60*1000, 10*60*1000 });
        _context.statManager().createRateStat("tunnel.reject.30", "How often we reject a tunnel because of bandwidth overload", "Tunnels", new long[] { 60*1000, 10*60*1000 });
        _context.statManager().createRateStat("tunnel.reject.50", "How often we reject a tunnel because of a critical issue (shutdown, etc)", "Tunnels", new long[] { 60*1000, 10*60*1000 });

        _context.statManager().createRequiredRateStat("tunnel.decryptRequestTime", "Time to decrypt a build request (ms)", "Tunnels", new long[] { 60*1000, 10*60*1000 });
        _context.statManager().createRequiredRateStat("tunnel.rejectTimeout", "Reject tunnel count (unknown next hop)", "Tunnels", new long[] { 60*1000, 10*60*1000 });
        _context.statManager().createRequiredRateStat("tunnel.rejectTimeout2", "Reject tunnel count (can't contact next hop)", "Tunnels", new long[] { 60*1000, 10*60*1000 });
        _context.statManager().createRequiredRateStat("tunnel.rejectDupID", "Part. tunnel dup ID", "Tunnels", new long[] { 24*60*60*1000 });
        _context.statManager().createRequiredRateStat("tunnel.ownDupID", "Our tunnel dup. ID", "Tunnels", new long[] { 24*60*60*1000 });
        _context.statManager().createRequiredRateStat("tunnel.rejectHostile", "Reject malicious tunnel", "Tunnels", new long[] { 24*60*60*1000 });
        _context.statManager().createRequiredRateStat("tunnel.rejectHopThrottle", "Reject per-hop limit", "Tunnels", new long[] { 60*60*1000 });
        _context.statManager().createRequiredRateStat("tunnel.dropReqThrottle", "Drop per-hop limit", "Tunnels", new long[] { 60*60*1000 });
        _context.statManager().createRequiredRateStat("tunnel.dropLookupThrottle", "Drop next hop lookup", "Tunnels", new long[] { 60*60*1000 });

        _context.statManager().createRequiredRateStat("tunnel.rejectOverloaded", "Delay to process rejected request (ms)", "Tunnels", new long[] { 60*1000, 10*60*1000 });
        _context.statManager().createRequiredRateStat("tunnel.acceptLoad", "Delay to process accepted request (ms)", "Tunnels", new long[] { 60*1000, 10*60*1000 });
        _context.statManager().createRateStat("tunnel.dropConnLimits", "Drop instead of reject due to conn limits", "Tunnels", new long[] { 10*60*1000 });
        _context.statManager().createRateStat("tunnel.rejectConnLimits", "Reject due to conn limits", "Tunnels", new long[] { 10*60*1000 });
        _context.statManager().createRequiredRateStat("tunnel.dropLoad", "Delay before dropping request (ms)?", "Tunnels", new long[] { 60*1000, 10*60*1000 });
        _context.statManager().createRequiredRateStat("tunnel.dropLoadDelay", "Delay before abandoning request (ms)", "Tunnels", new long[] { 60*1000, 10*60*1000 });
        _context.statManager().createRequiredRateStat("tunnel.dropLoadBacklog", "Pending request count when dropped", "Tunnels", new long[] { 60*1000, 10*60*1000 });
        _context.statManager().createRequiredRateStat("tunnel.dropLoadProactive", "Delay estimate when dropped (ms)", "Tunnels", new long[] { 60*1000, 10*60*1000 });
        _context.statManager().createRequiredRateStat("tunnel.dropLoadProactiveAbort", "Allowed requests during load", "Tunnels", new long[] { 60*1000, 10*60*1000 });
        //_context.statManager().createRateStat("tunnel.handleRemaining", "How many pending inbound requests were left on the queue after one pass?", "Tunnels", new long[] { 60*1000, 10*60*1000 });
        _context.statManager().createRateStat("tunnel.buildReplyTooSlow", "How often a tunnel build reply came back after we had given up waiting for it?", "Tunnels", new long[] { 60*1000, 10*60*1000 });

        _context.statManager().createRateStat("tunnel.receiveRejectionProbabalistic", "How often we are rejected probabalistically?", "Tunnels", new long[] { 10*60*1000l, 60*60*1000l, 24*60*60*1000l });
        _context.statManager().createRateStat("tunnel.receiveRejectionTransient", "How often we are rejected due to transient overload?", "Tunnels", new long[] { 10*60*1000l, 60*60*1000l, 24*60*60*1000l });
        _context.statManager().createRateStat("tunnel.receiveRejectionBandwidth", "How often we are rejected due to bandwidth overload?", "Tunnels", new long[] { 10*60*1000l, 60*60*1000l, 24*60*60*1000l });
        _context.statManager().createRateStat("tunnel.receiveRejectionCritical", "How often we are rejected due to critical failure?", "Tunnels", new long[] { 10*60*1000l, 60*60*1000l, 24*60*60*1000l });

        _context.statManager().createRateStat("tunnel.corruptBuildReply", "", "Tunnels", new long[] { 24*60*60*1000l });
        ctx.statManager().createRateStat("tunnel.buildLookupSuccess", "Was a deferred lookup successful?", "Tunnels", new long[] { 60*60*1000 });

        _processor = new BuildMessageProcessor(ctx);
        // used for previous hop, for all requests
        _requestThrottler = new RequestThrottler(ctx);
        // used for previous and next hops, for successful builds only
        _throttler = new ParticipatingThrottler(ctx);
        _buildReplyHandler = new BuildReplyHandler(ctx);
        _buildMessageHandlerJob = new TunnelBuildMessageHandlerJob(ctx);
        _buildReplyMessageHandlerJob = new TunnelBuildReplyMessageHandlerJob(ctx);
        TunnelBuildMessageHandlerJobBuilder tbmhjb = new TunnelBuildMessageHandlerJobBuilder();
        TunnelBuildReplyMessageHandlerJobBuilder tbrmhjb = new TunnelBuildReplyMessageHandlerJobBuilder();
        ctx.inNetMessagePool().registerHandlerJobBuilder(TunnelBuildMessage.MESSAGE_TYPE, tbmhjb);
        ctx.inNetMessagePool().registerHandlerJobBuilder(TunnelBuildReplyMessage.MESSAGE_TYPE, tbrmhjb);
        ctx.inNetMessagePool().registerHandlerJobBuilder(VariableTunnelBuildMessage.MESSAGE_TYPE, tbmhjb);
        ctx.inNetMessagePool().registerHandlerJobBuilder(VariableTunnelBuildReplyMessage.MESSAGE_TYPE, tbrmhjb);
    }

    /**
     *  @since 0.9
     */
    public void restart() {
        _inboundBuildMessages.clear();
    }

    /**
     *  Cannot be restarted.
     *  @param numThreads the number of threads to be shut down
     *  @since 0.9
     */
    public synchronized void shutdown(int numThreads) {
        _isRunning = false;
        _inboundBuildMessages.clear();
        BuildMessageState poison = new BuildMessageState(_context, null, null, null);
        for (int i = 0; i < numThreads; i++) {
            _inboundBuildMessages.offer(poison);
        }
    }

    /**
     * Thread to handle inbound requests
     * @since 0.8.11
     */
    public void run() {
        _isRunning = true;
        while (_isRunning && !_manager.isShutdown()) {
            try {
                handleInboundRequest();
            } catch (Exception e) {
                _log.log(Log.CRIT, "B0rked in the tunnel handler", e);
            }
        }
        if (_log.shouldLog(Log.WARN))
            _log.warn("Done handling");
        _isRunning = false;
    }

    /**
     * Blocking call to handle a single inbound request
     */
    private void handleInboundRequest() {
        BuildMessageState state = null;

            try {
                state = _inboundBuildMessages.take();
            } catch (InterruptedException ie) {
                return;
            }

            // check for poison
            if (state.msg == null) {
                _isRunning = false;
                return;
            }

            long now = _context.clock().now();
            long dropBefore = now - (BuildRequestor.REQUEST_TIMEOUT/4);
            if (state.recvTime <= dropBefore) {
                if (_log.shouldLog(Log.WARN))
                    _log.warn("Not even trying to handle/decrypt the request " + state.msg.getUniqueId()
                              + ", since we received it a long time ago: " + (now - state.recvTime));
                _context.statManager().addRateData("tunnel.dropLoadDelay", now - state.recvTime);
                _context.throttle().setTunnelStatus(_x("Dropping tunnel requests: Too slow"));
                return;
            }
            handleRequest(state);

        //int remaining = _inboundBuildMessages.size();
        //if (remaining > 0)
        //    _context.statManager().addRateData("tunnel.handleRemaining", remaining, 0);
        //return remaining;
    }

    /**
     * Blocking call to handle a single inbound reply
     */
    private void handleReply(BuildReplyMessageState state) {
        // search through the tunnels for a reply
        long replyMessageId = state.msg.getUniqueId();
        PooledTunnelCreatorConfig cfg = _exec.removeFromBuilding(replyMessageId);
        if (cfg == null) {
            // cannot handle - not pending... took too long?
            if (_log.shouldLog(Log.WARN))
                _log.warn("The reply " + replyMessageId + " did not match any pending tunnels");
            _context.statManager().addRateData("tunnel.buildReplyTooSlow", 1);
        } else {
            handleReply(state.msg, cfg, System.currentTimeMillis()-state.recvTime);
        }
    }

    /**
     * Blocking call to handle a single inbound reply
     */
    private void handleReply(TunnelBuildReplyMessage msg, PooledTunnelCreatorConfig cfg, long delay) {
        long requestedOn = cfg.getExpiration() - 10*60*1000;
        long rtt = _context.clock().now() - requestedOn;
        if (_log.shouldLog(Log.INFO))
            _log.info(msg.getUniqueId() + ": Handling the reply after " + rtt + ", delayed " + delay + " waiting for " + cfg);

        List<Integer> order = cfg.getReplyOrder();
        int statuses[] = _buildReplyHandler.decrypt(msg, cfg, order);
        if (statuses != null) {
            boolean allAgree = true;
            // For each peer in the tunnel
            for (int i = 0; i < cfg.getLength(); i++) {
                Hash peer = cfg.getPeer(i);
                // If this tunnel member is us, skip this record, don't update profile or stats
                // for ourselves, we always agree
                // Why must we save a slot for ourselves anyway?
                if (peer.equals(_context.routerHash()))
                    continue;

                int record = order.indexOf(Integer.valueOf(i));
                if (record < 0) {
                    _log.error("Bad status index " + i);
                    // don't leak
                    _exec.buildComplete(cfg, cfg.getTunnelPool());
                    return;
                }

                int howBad = statuses[record];

                    // Look up routerInfo
                    RouterInfo ri = _context.netDb().lookupRouterInfoLocally(peer);
                    // Default and detect bandwidth tier
                    String bwTier = "Unknown";
                    if (ri != null) bwTier = ri.getBandwidthTier(); // Returns "Unknown" if none recognized
                        else if (_log.shouldLog(Log.WARN)) _log.warn("Failed detecting bwTier, null routerInfo for: " + peer);
                    // Record that a peer of the given tier agreed or rejected
                    if (howBad == 0) {
                        _context.statManager().addRateData("tunnel.tierAgree" + bwTier, 1);
                    } else {
                        _context.statManager().addRateData("tunnel.tierReject" + bwTier, 1);
                    }
                    if (_log.shouldLog(Log.INFO))
                        _log.info(msg.getUniqueId() + ": Peer " + peer + " replied with status " + howBad);

                if (howBad == 0) {
                    // w3wt
                    _context.profileManager().tunnelJoined(peer, rtt);
                } else {
                    allAgree = false;
                    switch (howBad) {
                        case TunnelHistory.TUNNEL_REJECT_BANDWIDTH:
                            _context.statManager().addRateData("tunnel.receiveRejectionBandwidth", 1);
                            break;
                        case TunnelHistory.TUNNEL_REJECT_TRANSIENT_OVERLOAD:
                            _context.statManager().addRateData("tunnel.receiveRejectionTransient", 1);
                            break;
                        case TunnelHistory.TUNNEL_REJECT_PROBABALISTIC_REJECT:
                            _context.statManager().addRateData("tunnel.receiveRejectionProbabalistic", 1);
                            break;
                        case TunnelHistory.TUNNEL_REJECT_CRIT:
                        default:
                            _context.statManager().addRateData("tunnel.receiveRejectionCritical", 1);
                    }
                    // penalize peer based on their bitchiness level
                    _context.profileManager().tunnelRejected(peer, rtt, howBad);
                    _context.messageHistory().tunnelParticipantRejected(peer, "peer rejected after " + rtt + " with " + howBad + ": " + cfg.toString());
                }
            }

            if (allAgree) {
                // wikked, completely build
                boolean success;
                if (cfg.isInbound())
                    success = _context.tunnelDispatcher().joinInbound(cfg);
                else
                    success = _context.tunnelDispatcher().joinOutbound(cfg);
                if (!success) {
                    // This will happen very rarely. We check for dups when
                    // creating the config, but we don't track IDs for builds in progress.
                    _context.statManager().addRateData("tunnel.ownDupID", 1);
                    _exec.buildComplete(cfg, cfg.getTunnelPool());
                    if (_log.shouldLog(Log.WARN))
                        _log.warn("Dup ID for our own tunnel " + cfg);
                    return;
                }
                cfg.getTunnelPool().addTunnel(cfg); // self.self.self.foo!
                // call buildComplete() after addTunnel() so we don't try another build.
                _exec.buildComplete(cfg, cfg.getTunnelPool());
                _exec.buildSuccessful(cfg);

                ExpireJob expireJob = new ExpireJob(_context, cfg, cfg.getTunnelPool());
                cfg.setExpireJob(expireJob);
                _context.jobQueue().addJob(expireJob);
                if (cfg.getDestination() == null)
                    _context.statManager().addRateData("tunnel.buildExploratorySuccess", rtt);
                else
                    _context.statManager().addRateData("tunnel.buildClientSuccess", rtt);
            } else {
                // someone is no fun
                _exec.buildComplete(cfg, cfg.getTunnelPool());
                if (cfg.getDestination() == null)
                    _context.statManager().addRateData("tunnel.buildExploratoryReject", rtt);
                else
                    _context.statManager().addRateData("tunnel.buildClientReject", rtt);
            }
        } else {
            if (_log.shouldLog(Log.WARN))
                _log.warn(msg.getUniqueId() + ": Tunnel reply could not be decrypted for tunnel " + cfg);
            _context.statManager().addRateData("tunnel.corruptBuildReply", 1);
            // don't leak
            _exec.buildComplete(cfg, cfg.getTunnelPool());
        }
    }

    /**
     *  Decrypt the request, lookup the RI locally,
     *  and call handleReq() if found or queue a lookup job.
     *
     *  @return handle time or -1 if it wasn't completely handled
     */
    private long handleRequest(BuildMessageState state) {
        long timeSinceReceived = _context.clock().now()-state.recvTime;
        if (_log.shouldLog(Log.DEBUG))
            _log.debug(state.msg.getUniqueId() + ": handling request after " + timeSinceReceived);

        if (timeSinceReceived > (BuildRequestor.REQUEST_TIMEOUT*3)) {
            // don't even bother, since we are so overloaded locally
            _context.throttle().setTunnelStatus(_x("Dropping tunnel requests: Overloaded"));
            if (_log.shouldLog(Log.WARN))
                _log.warn("Not even trying to handle/decrypt the request " + state.msg.getUniqueId()
                           + ", since we received it a long time ago: " + timeSinceReceived);
            _context.statManager().addRateData("tunnel.dropLoadDelay", timeSinceReceived);
            return -1;
        }
        // ok, this is not our own tunnel, so we need to do some heavy lifting
        // this not only decrypts the current hop's record, but encrypts the other records
        // with the enclosed reply key
        long beforeDecrypt = System.currentTimeMillis();
        BuildRequestRecord req = _processor.decrypt(_context, state.msg, _context.routerHash(), _context.keyManager().getPrivateKey());
        long decryptTime = System.currentTimeMillis() - beforeDecrypt;
        _context.statManager().addRateData("tunnel.decryptRequestTime", decryptTime);
        if (decryptTime > 500 && _log.shouldLog(Log.WARN))
            _log.warn("Took too long to decrypt the request: " + decryptTime + " for message " + state.msg.getUniqueId() + " received " + (timeSinceReceived+decryptTime) + " ago");
        if (req == null) {
            // no records matched, or the decryption failed.  bah
            if (_log.shouldLog(Log.WARN))
                _log.warn("The request " + state.msg.getUniqueId() + " could not be decrypted");
            return -1;
        }

        long beforeLookup = System.currentTimeMillis();
        Hash nextPeer = req.readNextIdentity();
        long readPeerTime = System.currentTimeMillis()-beforeLookup;
        RouterInfo nextPeerInfo = _context.netDb().lookupRouterInfoLocally(nextPeer);
        long lookupTime = System.currentTimeMillis()-beforeLookup;
        if (lookupTime > 500 && _log.shouldLog(Log.WARN))
            _log.warn("Took too long to lookup the request: " + lookupTime + "/" + readPeerTime + " for message " + state.msg.getUniqueId() + " received " + (timeSinceReceived+decryptTime) + " ago");
        if (nextPeerInfo == null) {
            // limit concurrent next-hop lookups to prevent job queue overload attacks
            int numTunnels = _context.tunnelManager().getParticipatingCount();
            int limit = Math.max(MIN_LOOKUP_LIMIT, Math.min(MAX_LOOKUP_LIMIT, numTunnels * PERCENT_LOOKUP_LIMIT / 100));
            int current = _currentLookups.incrementAndGet();
            if (current <= limit) {
                if (_log.shouldLog(Log.DEBUG))
                    _log.debug("Request " + state.msg.getUniqueId() + '/' + req.readReceiveTunnelId() + '/' + req.readNextTunnelId()
                               + " handled, lookup next peer " + nextPeer
                               + " lookups: " + current + '/' + limit);
                _context.netDb().lookupRouterInfo(nextPeer, new HandleReq(_context, state, req, nextPeer),
                                              new TimeoutReq(_context, state, req, nextPeer), NEXT_HOP_LOOKUP_TIMEOUT);
            } else {
                _currentLookups.decrementAndGet();
                if (_log.shouldLog(Log.WARN))
                    _log.warn("Drop next hop lookup, limit " + limit);
                _context.statManager().addRateData("tunnel.dropLookupThrottle", 1);
            }
            return -1;
        } else {
            long beforeHandle = System.currentTimeMillis();
            handleReq(nextPeerInfo, state, req, nextPeer);
            long handleTime = System.currentTimeMillis() - beforeHandle;
            if (_log.shouldLog(Log.DEBUG))
                _log.debug("Request " + state.msg.getUniqueId() + " handled and we know the next peer "
                           + nextPeer + " after " + handleTime
                           + "/" + decryptTime + "/" + lookupTime + "/" + timeSinceReceived);
            return handleTime;
        }
    }

    /**
     * This request is actually a reply, process it as such
     */
    private void handleRequestAsInboundEndpoint(BuildEndMessageState state) {
        int records = state.msg.getRecordCount();
        TunnelBuildReplyMessage msg;
        if (records == TunnelBuildMessage.MAX_RECORD_COUNT)
            msg = new TunnelBuildReplyMessage(_context);
        else
            msg = new VariableTunnelBuildReplyMessage(_context, records);
        for (int i = 0; i < records; i++)
            msg.setRecord(i, state.msg.getRecord(i));
        msg.setUniqueId(state.msg.getUniqueId());
        handleReply(msg, state.cfg, System.currentTimeMillis() - state.recvTime);
    }

    private class HandleReq extends JobImpl {
        private final BuildMessageState _state;
        private final BuildRequestRecord _req;
        private final Hash _nextPeer;

        HandleReq(RouterContext ctx, BuildMessageState state, BuildRequestRecord req, Hash nextPeer) {
            super(ctx);
            _state = state;
            _req = req;
            _nextPeer = nextPeer;
        }

        public String getName() { return "Deferred tunnel join processing"; }

        public void runJob() {
            // decrement in-progress counter
            _currentLookups.decrementAndGet();
            if (_log.shouldLog(Log.DEBUG))
                _log.debug("Request " + _state.msg.getUniqueId() + " handled with a successful deferred lookup for the next peer " + _nextPeer);

            RouterInfo ri = getContext().netDb().lookupRouterInfoLocally(_nextPeer);
            if (ri != null) {
                handleReq(ri, _state, _req, _nextPeer);
                getContext().statManager().addRateData("tunnel.buildLookupSuccess", 1);
            } else {
                if (_log.shouldLog(Log.WARN))
                    _log.warn("Deferred successfully, but we couldnt find " + _nextPeer);
                getContext().statManager().addRateData("tunnel.buildLookupSuccess", 0);
            }
        }
    }

    private class TimeoutReq extends JobImpl {
        private final BuildMessageState _state;
        private final BuildRequestRecord _req;
        private final Hash _nextPeer;

        TimeoutReq(RouterContext ctx, BuildMessageState state, BuildRequestRecord req, Hash nextPeer) {
            super(ctx);
            _state = state;
            _req = req;
            _nextPeer = nextPeer;
        }

        public String getName() { return "Timeout looking for next peer for tunnel join"; }

        public void runJob() {
            // decrement in-progress counter
            _currentLookups.decrementAndGet();
            getContext().statManager().addRateData("tunnel.rejectTimeout", 1);
            getContext().statManager().addRateData("tunnel.buildLookupSuccess", 0);
            // logging commented out so class can be static
            //if (_log.shouldLog(Log.WARN))
            //    _log.warn("Request " + _state.msg.getUniqueId()
            //              + " could no be satisfied, as the next peer could not be found: " + _nextPeer.toBase64());

            // ???  should we blame the peer here?   getContext().profileManager().tunnelTimedOut(_nextPeer);
            getContext().messageHistory().tunnelRejected(_state.fromHash, new TunnelId(_req.readReceiveTunnelId()), _nextPeer,
                                                         "rejected because we couldn't find " + _nextPeer + ": " +
                                                         _state.msg.getUniqueId() + "/" + _req.readNextTunnelId());
        }
    }

    /**
     * If we are dropping lots of requests before even trying to handle them,
     * I suppose you could call us "overloaded"
     */
/**** unused, see handleReq() below
    private final static int MAX_PROACTIVE_DROPS = 240;

    private int countProactiveDrops() {
        int dropped = 0;
        dropped += countEvents("tunnel.dropLoadProactive", 60*1000);
        dropped += countEvents("tunnel.dropLoad", 60*1000);
        dropped += countEvents("tunnel.dropLoadBacklog", 60*1000);
        dropped += countEvents("tunnel.dropLoadDelay", 60*1000);
        return dropped;
    }

    private int countEvents(String stat, long period) {
        RateStat rs = _context.statManager().getRate(stat);
        if (rs != null) {
            Rate r = rs.getRate(period);
            if (r != null)
                return (int)r.getCurrentEventCount();
        }
        return 0;
    }
****/

    /**
     *  Actually process the request and send the reply.
     *
     *  Todo: Replies are not subject to RED for bandwidth reasons,
     *  and the bandwidth is not credited to any tunnel.
     *  If we did credit the reply to the tunnel, it would
     *  prevent the classification of the tunnel as 'inactive' on tunnels.jsp.
     */
    private void handleReq(RouterInfo nextPeerInfo, BuildMessageState state, BuildRequestRecord req, Hash nextPeer) {
        long ourId = req.readReceiveTunnelId();
        long nextId = req.readNextTunnelId();
        boolean isInGW = req.readIsInboundGateway();
        boolean isOutEnd = req.readIsOutboundEndpoint();

        if (isInGW && isOutEnd) {
            _context.statManager().addRateData("tunnel.rejectHostile", 1);
            _log.error("Dropping build request, IBGW+OBEP");
            return;
        }

        // Loop checks
        if ((!isOutEnd) && _context.routerHash().equals(nextPeer)) {
            _context.statManager().addRateData("tunnel.rejectHostile", 1);
            // We are 2 hops in a row? Drop it without a reply.
            // No way to recognize if we are every other hop, but see below
            _log.error("Dropping build request, we the next hop");
            return;
        }
        // previous test should be sufficient to keep it from getting here but maybe not?
        if (!isInGW) {
            Hash from = state.fromHash;
            if (from == null)
                from = state.from.calculateHash();
            if (_context.routerHash().equals(from)) {
                _context.statManager().addRateData("tunnel.rejectHostile", 1);
                _log.error("Dropping build request, we are the previous hop");
                return;
            }
        }
        if ((!isOutEnd) && (!isInGW)) {
            Hash from = state.fromHash;
            if (from == null)
                from = state.from.calculateHash();
            // Previous and next hop the same? Don't help somebody be evil. Drop it without a reply.
            // A-B-C-A is not preventable
            if (nextPeer.equals(from)) {
                _context.statManager().addRateData("tunnel.rejectHostile", 1);
                _log.error("Dropping build request with the same previous and next hop");
                return;
            }
        }

        // time is in hours, and only for log below - what's the point?
        // tunnel-alt-creation.html specifies that this is enforced +/- 1 hour but it is not.
        long time = req.readRequestTime();
        long now = (_context.clock().now() / (60l*60l*1000l)) * (60*60*1000);
        int ourSlot = -1;

        int response = _context.throttle().acceptTunnelRequest();

        // This only checked OUR tunnels, so the log message was wrong.
        // Now checked by TunnelDispatcher.joinXXX()
        // and returned as success value, checked below.
        //if (_context.tunnelManager().getTunnelInfo(new TunnelId(ourId)) != null) {
        //    if (_log.shouldLog(Log.ERROR))
        //        _log.error("Already participating in a tunnel with the given Id (" + ourId + "), so gotta reject");
        //    if (response == 0)
        //        response = TunnelHistory.TUNNEL_REJECT_PROBABALISTIC_REJECT;
        //}

        //if ( (response == 0) && (_context.random().nextInt(50) <= 1) )
        //    response = TunnelHistory.TUNNEL_REJECT_PROBABALISTIC_REJECT;

        long recvDelay = _context.clock().now()-state.recvTime;
        if (response == 0) {
            // unused
            //int proactiveDrops = countProactiveDrops();
            float pDrop = ((float) recvDelay) / (float) (BuildRequestor.REQUEST_TIMEOUT*3);
            pDrop = (float)Math.pow(pDrop, 16);
            if (_context.random().nextFloat() < pDrop) { // || (proactiveDrops > MAX_PROACTIVE_DROPS) ) ) {
                _context.statManager().addRateData("tunnel.rejectOverloaded", recvDelay);
                _context.throttle().setTunnelStatus(_x("Rejecting tunnels: Request overload"));
                //if (true || (proactiveDrops < MAX_PROACTIVE_DROPS*2))
                    response = TunnelHistory.TUNNEL_REJECT_TRANSIENT_OVERLOAD;
                //else
                //    response = TunnelHistory.TUNNEL_REJECT_BANDWIDTH;
            } else {
                _context.statManager().addRateData("tunnel.acceptLoad", recvDelay);
            }
        }

        /*
         * Being a IBGW or OBEP generally leads to more connections, so if we are
         * approaching our connection limit (i.e. !haveCapacity()),
         * reject this request.
         *
         * Don't do this for class N or O, under the assumption that they are already talking
         * to most of the routers, so there's no reason to reject. This may drive them
         * to their conn. limits, but it's hopefully a temporary solution to the
         * tunnel build congestion. As the net grows this will have to be revisited.
         */
        RouterInfo ri = _context.router().getRouterInfo();
        if (response == 0) {
            if (ri == null) {
                // ?? We should always have a RI
                response = TunnelHistory.TUNNEL_REJECT_BANDWIDTH;
            } else {
                char bw = ri.getBandwidthTier().charAt(0);
                if (bw != 'O' && bw != 'N' &&
                    ((isInGW && ! _context.commSystem().haveInboundCapacity(87)) ||
                     (isOutEnd && ! _context.commSystem().haveOutboundCapacity(87)))) {
                        _context.statManager().addRateData("tunnel.rejectConnLimits", 1);
                        _context.throttle().setTunnelStatus(_x("Rejecting tunnels: Connection limit"));
                        response = TunnelHistory.TUNNEL_REJECT_BANDWIDTH;
                }
            }
        }

        // Check participating throttle counters for previous and next hops
        // This is at the end as it compares to a percentage of created tunnels.
        // We may need another counter above for requests.
        if (response == 0 && !isInGW) {
            Hash from = state.fromHash;
            if (from == null)
                from = state.from.calculateHash();
            if (from != null && _throttler.shouldThrottle(from)) {
                if (_log.shouldLog(Log.WARN))
                    _log.warn("Rejecting tunnel (hop throttle), previous hop: " + from);
                // no setTunnelStatus() indication
                _context.statManager().addRateData("tunnel.rejectHopThrottle", 1);
                response = TunnelHistory.TUNNEL_REJECT_BANDWIDTH;
            }
        }
        if (response == 0 && (!isOutEnd) &&
            _throttler.shouldThrottle(nextPeer)) {
            if (_log.shouldLog(Log.WARN))
                _log.warn("Rejecting tunnel (hop throttle), next hop: " + nextPeer);
            _context.statManager().addRateData("tunnel.rejectHopThrottle", 1);
            // no setTunnelStatus() indication
            response = TunnelHistory.TUNNEL_REJECT_BANDWIDTH;
        }

        if (_log.shouldLog(Log.DEBUG))
            _log.debug("Responding to " + state.msg.getUniqueId() + "/" + ourId
                       + " after " + recvDelay + " with " + response
                       + " from " + (state.fromHash != null ? state.fromHash :
                                     state.from != null ? state.from.calculateHash() : "tunnel"));

        HopConfig cfg = null;
        if (response == 0) {
            cfg = new HopConfig();
            cfg.setCreation(_context.clock().now());
            cfg.setExpiration(_context.clock().now() + 10*60*1000);
            cfg.setIVKey(req.readIVKey());
            cfg.setLayerKey(req.readLayerKey());
            if (isInGW) {
                cfg.setReceiveFrom(null);
            } else {
                if (state.fromHash != null) {
                    cfg.setReceiveFrom(state.fromHash);
                } else if (state.from != null) {
                    cfg.setReceiveFrom(state.from.calculateHash());
                } else {
                    // b0rk
                    return;
                }
            }
            cfg.setReceiveTunnelId(DataHelper.toLong(4, ourId));
            if (isOutEnd) {
                cfg.setSendTo(null);
                cfg.setSendTunnelId(null);
            } else {
                cfg.setSendTo(nextPeer);
                cfg.setSendTunnelId(DataHelper.toLong(4, nextId));
            }

            // now "actually" join
            boolean success;
            if (isOutEnd)
                success = _context.tunnelDispatcher().joinOutboundEndpoint(cfg);
            else if (isInGW)
                success = _context.tunnelDispatcher().joinInboundGateway(cfg);
            else
                success = _context.tunnelDispatcher().joinParticipant(cfg);
            if (success) {
                if (_log.shouldLog(Log.DEBUG))
                    _log.debug("Joining " + state.msg.getUniqueId() + "/" + cfg.getReceiveTunnel() + "/" + recvDelay + " as " + (isOutEnd ? "outbound endpoint" : isInGW ? "inbound gw" : "participant"));
            } else {
                // Dup Tunnel ID. This can definitely happen (birthday paradox).
                // Probability in 11 minutes (per hop type):
                // 0.1% for 2900 tunnels; 1% for 9300 tunnels
                response = TunnelHistory.TUNNEL_REJECT_BANDWIDTH;
                _context.statManager().addRateData("tunnel.rejectDupID", 1);
                if (_log.shouldLog(Log.WARN))
                    _log.warn("DUP ID failure " + state.msg.getUniqueId() + "/" + cfg.getReceiveTunnel() + " as " + (isOutEnd ? "outbound endpoint" : isInGW ? "inbound gw" : "participant"));
            }
        }
        if (response != 0) {
            _context.statManager().addRateData("tunnel.reject." + response, 1);
            _context.messageHistory().tunnelRejected(state.fromHash, new TunnelId(ourId), nextPeer,
                                                     "rejecting for " + response + ": " +
                                                     state.msg.getUniqueId() + "/" + ourId + "/" + req.readNextTunnelId() + " delay " +
                                                     recvDelay + " as " +
                                                     (isOutEnd ? "outbound endpoint" : isInGW ? "inbound gw" : "participant"));
        }

        // Connection congestion control:
        // If we rejected the request, are near our conn limits, and aren't connected to the next hop,
        // just drop it.
        // 81% = between 75% control measures in Transports and 87% rejection above
        if (response != 0 &&
            (! _context.routerHash().equals(nextPeer)) &&
            (! _context.commSystem().haveOutboundCapacity(81)) &&
            (! _context.commSystem().isEstablished(nextPeer))) {
            _context.statManager().addRateData("tunnel.dropConnLimits", 1);
            if (_log.shouldLog(Log.WARN))
                _log.warn("Not sending rejection due to conn limits");
            return;
        }

        byte reply[] = BuildResponseRecord.create(_context, response, req.readReplyKey(), req.readReplyIV(), state.msg.getUniqueId());
        int records = state.msg.getRecordCount();
        for (int j = 0; j < records; j++) {
            if (state.msg.getRecord(j) == null) {
                ourSlot = j;
                state.msg.setRecord(j, new ByteArray(reply));
                //if (_log.shouldLog(Log.DEBUG))
                //    _log.debug("Full reply record for slot " + ourSlot + "/" + ourId + "/" + nextId + "/" + req.readReplyMessageId()
                //               + ": " + Base64.encode(reply));
                break;
            }
        }

        if (_log.shouldLog(Log.DEBUG))
            _log.debug("Read slot " + ourSlot + " containing our hop @ " + _context.routerHash()
                      + " accepted? " + response + " receiving on " + ourId
                      + " sending to " + nextId
                      + " on " + nextPeer
                      + " inGW? " + isInGW + " outEnd? " + isOutEnd + " time difference " + (now-time)
                      + " recvDelay " + recvDelay + " replyMessage " + req.readReplyMessageId()
                      + " replyKey " + req.readReplyKey() + " replyIV " + Base64.encode(req.readReplyIV()));

        // now actually send the response
        if (!isOutEnd) {
            state.msg.setUniqueId(req.readReplyMessageId());
            state.msg.setMessageExpiration(_context.clock().now() + NEXT_HOP_SEND_TIMEOUT);
            OutNetMessage msg = new OutNetMessage(_context, state.msg, state.msg.getMessageExpiration(), PRIORITY, nextPeerInfo);
            if (response == 0)
                msg.setOnFailedSendJob(new TunnelBuildNextHopFailJob(_context, cfg));
            _context.outNetMessagePool().add(msg);
        } else {
            // We are the OBEP.
            // send it to the reply tunnel on the reply peer within a new TunnelBuildReplyMessage
            // (enough layers jrandom?)
            TunnelBuildReplyMessage replyMsg;
            if (records == TunnelBuildMessage.MAX_RECORD_COUNT)
                replyMsg = new TunnelBuildReplyMessage(_context);
            else
                replyMsg = new VariableTunnelBuildReplyMessage(_context, records);
            for (int i = 0; i < records; i++)
                replyMsg.setRecord(i, state.msg.getRecord(i));
            replyMsg.setUniqueId(req.readReplyMessageId());
            replyMsg.setMessageExpiration(_context.clock().now() + NEXT_HOP_SEND_TIMEOUT);
            TunnelGatewayMessage m = new TunnelGatewayMessage(_context);
            m.setMessage(replyMsg);
            m.setMessageExpiration(replyMsg.getMessageExpiration());
            m.setTunnelId(new TunnelId(nextId));
            if (_context.routerHash().equals(nextPeer)) {
                // ok, we are the gateway, so inject it
                if (_log.shouldLog(Log.DEBUG))
                    _log.debug("We are the reply gateway for " + nextId
                              + " when replying to replyMessage " + req.readReplyMessageId());
                _context.tunnelDispatcher().dispatch(m);
            } else {
                // ok, the gateway is some other peer, shove 'er across
                OutNetMessage outMsg = new OutNetMessage(_context, m, m.getMessageExpiration(), PRIORITY, nextPeerInfo);
                if (response == 0)
                    outMsg.setOnFailedSendJob(new TunnelBuildNextHopFailJob(_context, cfg));
                _context.outNetMessagePool().add(outMsg);
            }
        }
    }

    public int getInboundBuildQueueSize() {
            return _inboundBuildMessages.size();
    }

    /**
     *  Handle incoming Tunnel Build Messages, which are generally requests to us,
     *  but could also be the reply where we are the IBEP.
     */
    private class TunnelBuildMessageHandlerJobBuilder implements HandlerJobBuilder {
        public Job createJob(I2NPMessage receivedMessage, RouterIdentity from, Hash fromHash) {
            // need to figure out if this is a reply to an inbound tunnel request (where we are the
            // endpoint, receiving the request at the last hop)
            long reqId = receivedMessage.getUniqueId();
            PooledTunnelCreatorConfig cfg = _exec.removeFromBuilding(reqId);
            if (_log.shouldLog(Log.DEBUG))
                _log.debug("Receive tunnel build message " + reqId + " from "
                           + (from != null ? from.calculateHash() : fromHash != null ? fromHash : "tunnels")
                           + ", found matching tunnel? " + (cfg != null));
            if (cfg != null) {
                if (!cfg.isInbound()) {
                    // shouldnt happen - should we put it back?
                    _log.error("received it, but its not inbound? " + cfg);
                }
                BuildEndMessageState state = new BuildEndMessageState(cfg, receivedMessage);
                handleRequestAsInboundEndpoint(state);
            } else {
                if (_exec.wasRecentlyBuilding(reqId)) {
                    // we are the IBEP but we already gave up?
                    if (_log.shouldLog(Log.WARN))
                        _log.warn("Dropping the reply " + reqId + ", as we used to be building that");
                    _context.statManager().addRateData("tunnel.buildReplyTooSlow", 1);
                } else {
                    int sz = _inboundBuildMessages.size();
                    // Can probably remove this check, since CoDel is in use
                    BuildMessageState cur = _inboundBuildMessages.peek();
                    boolean accept = true;
                    if (cur != null) {
                        long age = _context.clock().now() - cur.recvTime;
                        if (age >= BuildRequestor.REQUEST_TIMEOUT/4) {
                            _context.statManager().addRateData("tunnel.dropLoad", age, sz);
                            _context.throttle().setTunnelStatus(_x("Dropping tunnel requests: High load"));
                            // if the queue is backlogged, stop adding new messages
                            accept = false;
                        }
                    }
                    if (accept) {
                        // early request throttle check, before queueing and decryption
                        Hash fh = fromHash;
                        if (fh == null && from != null)
                            fh = from.calculateHash();
                        if (fh != null && _requestThrottler.shouldThrottle(fh)) {
                            if (_log.shouldLog(Log.WARN))
                                _log.warn("Dropping tunnel request (from throttle), previous hop: " + from);
                            _context.statManager().addRateData("tunnel.dropReqThrottle", 1);
                            accept = false;
                        }
                    }
                    if (accept) {
                        // This is expensive and rarely seen, use CoDel instead
                        //int queueTime = estimateQueueTime(sz);
                        //float pDrop = queueTime/((float)BuildRequestor.REQUEST_TIMEOUT*3);
                        //pDrop = (float)Math.pow(pDrop, 16); // steeeep
                        //float f = _context.random().nextFloat();
                        //if ( (pDrop > f) && (allowProactiveDrop()) ) {
                        //if (pDrop > f) {
                        //    _context.throttle().setTunnelStatus(_x("Dropping tunnel requests: Queue time"));
                        //    _context.statManager().addRateData("tunnel.dropLoadProactive", queueTime, sz);
                        //} else {
                            accept = _inboundBuildMessages.offer(new BuildMessageState(_context, receivedMessage, from, fromHash));
                            if (accept) {
                                // wake up the Executor to call handleInboundRequests()
                                _exec.repoll();
                            } else {
                                _context.throttle().setTunnelStatus(_x("Dropping tunnel requests: High load"));
                                _context.statManager().addRateData("tunnel.dropLoadBacklog", sz);
                            }
                        //}
                    }
                }
            }
            return _buildMessageHandlerJob;
        }
    }

/****
    private boolean allowProactiveDrop() {
        boolean rv = _context.getBooleanPropertyDefaultTrue("router.allowProactiveDrop");
        if (!rv)
            _context.statManager().addRateData("tunnel.dropLoadProactiveAbort", 1, 0);
        return rv;
    }
****/

/****
    private int estimateQueueTime(int numPendingMessages) {
        int decryptTime = 200;
        RateStat rs = _context.statManager().getRate("tunnel.decryptRequestTime");
        if (rs != null) {
            Rate r = rs.getRate(60*1000);
            double avg = 0;
            if (r != null)
                avg = r.getAverageValue();
            if (avg > 0) {
                decryptTime = (int)avg;
            } else {
                avg = rs.getLifetimeAverageValue();
                if (avg > 0)
                    decryptTime = (int)avg;
            }
        }
        float estimatedQueueTime = numPendingMessages * decryptTime;
        estimatedQueueTime *= 1.2f; // lets leave some cpu to spare, 'eh?
        return (int)estimatedQueueTime;
    }
****/

    /** */
    private class TunnelBuildReplyMessageHandlerJobBuilder implements HandlerJobBuilder {
        public Job createJob(I2NPMessage receivedMessage, RouterIdentity from, Hash fromHash) {
            if (_log.shouldLog(Log.DEBUG))
                _log.debug("Receive tunnel build reply message " + receivedMessage.getUniqueId() + " from "
                           + (fromHash != null ? fromHash : from != null ? from.calculateHash() : "a tunnel"));
            handleReply(new BuildReplyMessageState(receivedMessage));
            return _buildReplyMessageHandlerJob;
        }
    }

    /** normal inbound requests from other people */
    private static class BuildMessageState implements CDQEntry {
        private final RouterContext _ctx;
        final TunnelBuildMessage msg;
        final RouterIdentity from;
        final Hash fromHash;
        final long recvTime;

        public BuildMessageState(RouterContext ctx, I2NPMessage m, RouterIdentity f, Hash h) {
            _ctx = ctx;
            msg = (TunnelBuildMessage)m;
            from = f;
            fromHash = h;
            recvTime = ctx.clock().now();
        }

        public void setEnqueueTime(long time) {
            // set at instantiation, which is just before enqueueing
        }

        public long getEnqueueTime() {
            return recvTime;
        }

        public void drop() {
            _ctx.throttle().setTunnelStatus(_x("Dropping tunnel requests: Queue time"));
            _ctx.statManager().addRateData("tunnel.dropLoadProactive", _ctx.clock().now() - recvTime);
        }
    }

    /** replies for outbound tunnels that we have created */
    private static class BuildReplyMessageState {
        final TunnelBuildReplyMessage msg;
        final long recvTime;
        public BuildReplyMessageState(I2NPMessage m) {
            msg = (TunnelBuildReplyMessage)m;
            recvTime = System.currentTimeMillis();
        }
    }

    /** replies for inbound tunnels we have created */
    private static class BuildEndMessageState {
        final TunnelBuildMessage msg;
        final PooledTunnelCreatorConfig cfg;
        final long recvTime;
        public BuildEndMessageState(PooledTunnelCreatorConfig c, I2NPMessage m) {
            cfg = c;
            msg = (TunnelBuildMessage)m;
            recvTime = System.currentTimeMillis();
        }
    }

    /** noop */
    private static class TunnelBuildMessageHandlerJob extends JobImpl {
        private TunnelBuildMessageHandlerJob(RouterContext ctx) { super(ctx); }
        public void runJob() {}
        public String getName() { return "Receive tunnel build message"; }
    }

    /** noop */
    private static class TunnelBuildReplyMessageHandlerJob extends JobImpl {
        private TunnelBuildReplyMessageHandlerJob(RouterContext ctx) { super(ctx); }
        public void runJob() {}
        public String getName() { return "Receive tunnel build reply message"; }
    }

    /**
     *  Remove the participating tunnel if we can't contact the next hop
     *  Not strictly necessary, as the entry doesn't use that much space,
     *  but it affects capacity calculations
     */
    private static class TunnelBuildNextHopFailJob extends JobImpl {
        private final HopConfig _cfg;

        private TunnelBuildNextHopFailJob(RouterContext ctx, HopConfig cfg) {
            super(ctx);
            _cfg = cfg;
        }

        public String getName() { return "Timeout contacting next peer for tunnel join"; }

        public void runJob() {
            getContext().tunnelDispatcher().remove(_cfg);
            getContext().statManager().addRateData("tunnel.rejectTimeout2", 1);
            Log log = getContext().logManager().getLog(BuildHandler.class);
            if (log.shouldLog(Log.WARN))
                log.warn("Timeout contacting next hop for " + _cfg);
        }
    }

    /**
     *  Mark a string for extraction by xgettext and translation.
     *  Use this only in static initializers.
     *  It does not translate!
     *  @return s
     */
    private static final String _x(String s) {
        return s;
    }
}


text:
namespace CARLsim_PTI {
    class Experiment {
    public:
        virtual void run(const ParameterInstances &parameters, std::ostream &outputStream) const = 0;
    };
}

#endif // EXPERIMENT_H


text:
package org.springframework.core.test.tools;

/**
 * Assertion methods for {@code ResourceFile} instances.
 *
 * @author Phillip Webb
 * @since 6.0
 */
public class ResourceFileAssert
		extends DynamicFileAssert<ResourceFileAssert, ResourceFile> {

	ResourceFileAssert(ResourceFile actual) {
		super(actual, ResourceFileAssert.class);
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Jard. bot. État Brux. 19: 336 (1949)

#### Original name
Pestalotia sonsensis Henn.

### Remarks
null


text:
/**
 * @format
 * @flow
 */

import {foo1, foo2} from './foo';

(foo1: empty);
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
// intentionally empty line
(foo2: empty);


text:
<?php

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \common\modules\user\models\SignupForm */

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

$this->title = Yii::t('common', 'Signup');
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

            <?php $form = ActiveForm::begin(['id' => 'form-signup', 'enableAjaxValidation' => true]); ?>

                <?= $form->field($model, 'username') ?>

                <?= $form->field($model, 'email') ?>

                <?= $form->field($model, 'password')->passwordInput() ?>

                    <?= Html::submitButton('注册', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>

                    <?= Html::a('去登录', ['/user/security/login'], ['class' => 'btn btn-warning']) ?>

            <?php ActiveForm::end(); ?>


text: Distribute spider


text:
package org.arakhne.afc.attrs.attr;

/**
 * This exception is generated each time something wrong append
 * with attributes.
 *
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 */
public class AttributeError extends RuntimeException {

	private static final long serialVersionUID = 3139198792703646207L;

	/** Construct the exception.
	 */
	public AttributeError() {
		//
	}

	/** Construct the exception.
	 * @param name is the name of the attribute on which something wrong appended.
	 */
	public AttributeError(String name) {
		super(name);
	}

	/** Construct the exception.
	 * @param cause is the exception to forward.
	 */
	public AttributeError(Throwable cause) {
		super(cause);
	}

}


text:
package software.amazon.awssdk.http.nio.netty.internal.http2.utils;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2FrameLogger;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.logging.LogLevel;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey;

public final class Http2TestUtils {
    public static final int INITIAL_WINDOW_SIZE = 1_048_576;

    public static EmbeddedChannel newHttp2Channel() {
        return newHttp2Channel(new NoOpHandler());
    }

    public static EmbeddedChannel newHttp2Channel(ChannelHandler channelHandler) {
        Http2FrameCodec http2FrameCodec = Http2FrameCodecBuilder.forClient().initialSettings(
            Http2Settings.defaultSettings().initialWindowSize(INITIAL_WINDOW_SIZE))
                                                                .frameLogger(new Http2FrameLogger(LogLevel.DEBUG)).build();
        EmbeddedChannel channel = new EmbeddedChannel(http2FrameCodec,
                                                      new Http2MultiplexHandler(channelHandler));

        channel.attr(ChannelAttributeKey.HTTP2_CONNECTION).set(http2FrameCodec.connection());
        channel.attr(ChannelAttributeKey.HTTP2_INITIAL_WINDOW_SIZE).set(INITIAL_WINDOW_SIZE);
        channel.attr(ChannelAttributeKey.PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP2));
        return channel;
    }

    private static class NoOpHandler extends ChannelInitializer<Channel> {
        @Override
        protected void initChannel(Channel ch) {
        }
    }
}


text:
var lessc_helper = {

    //Stylize a string
    stylize : function(str, style) {
        var styles = {
            'reset'     : [0,   0],
            'bold'      : [1,  22],
            'inverse'   : [7,  27],
            'underline' : [4,  24],
            'yellow'    : [33, 39],
            'green'     : [32, 39],
            'red'       : [31, 39],
            'grey'      : [90, 39]
        };
        return '\033[' + styles[style][0] + 'm' + str +
               '\033[' + styles[style][1] + 'm';
    },

    //Print command line options
    printUsage: function() {
        console.log("usage: lessc [option option=parameter ...] <source> [destination]");
        console.log("");
        console.log("If source is set to `-' (dash or hyphen-minus), input is read from stdin.");
        console.log("");
        console.log("options:");
        console.log("  -h, --help              Print help (this message) and exit.");
        console.log("  --include-path=PATHS    Set include paths. Separated by `:'. Use `;' on Windows.");
        console.log("  -M, --depends           Output a makefile import dependency list to stdout");
        console.log("  --no-color              Disable colorized output.");
        console.log("  --no-ie-compat          Disable IE compatibility checks.");
        console.log("  --no-js                 Disable JavaScript in less files");
        console.log("  -l, --lint              Syntax check only (lint).");
        console.log("  -s, --silent            Suppress output of error messages.");
        console.log("  --strict-imports        Force evaluation of imports.");
        console.log("  --insecure              Allow imports from insecure https hosts.");
        console.log("  --verbose               Be verbose.");
        console.log("  -v, --version           Print version number and exit.");
        console.log("  -x, --compress          Compress output by removing some whitespaces.");
        console.log("  --clean-css             Compress output using clean-css");
        console.log("  -O0, -O1, -O2           Set the parser's optimization level. The lower");
        console.log("                          the number, the less nodes it will create in the");
        console.log("                          tree. This could matter for debugging, or if you");
        console.log("                          want to access the individual nodes in the tree.");
        console.log("  --line-numbers=TYPE     Outputs filename and line numbers.");
        console.log("                          TYPE can be either 'comments', which will output");
        console.log("                          the debug info within comments, 'mediaquery'");
        console.log("                          that will output the information within a fake");
        console.log("                          media query which is compatible with the SASS");
        console.log("                          format, and 'all' which will do both.");
        console.log("  --source-map[=FILENAME] Outputs a v3 sourcemap to the filename (or output filename.map)");
        console.log("  --source-map-rootpath=X adds this path onto the sourcemap filename and less file paths");
        console.log("  --source-map-basepath=X Sets sourcemap base path, defaults to current working directory.");
        console.log("  --source-map-inline     puts the less files into the map instead of referencing them");
        console.log("  -rp, --rootpath=URL     Set rootpath for url rewriting in relative imports and urls.");
        console.log("                          Works with or without the relative-urls option.");
        console.log("  -ru, --relative-urls    re-write relative urls to the base less file.");
        console.log("  -sm=on|off              Turn on or off strict math, where in strict mode, math");
        console.log("  --strict-math=on|off    requires brackets. This option may default to on and then");
        console.log("                          be removed in the future.");
        console.log("  -su=on|off              Allow mixed units, e.g. 1px+1em or 1px*1px which have units");
        console.log("  --strict-units=on|off   that cannot be represented.");
        console.log("");
        console.log("Report bugs to: http://github.com/less/less.js/issues");
        console.log("Home page: <http://lesscss.org/>");
    }
};

// Exports helper functions
for (var h in lessc_helper) { exports[h] = lessc_helper[h]; }


text:
exports["test date"] = require("./date.test.js");

if (module == require.main) require('test').run(exports);


text:
<!DOCTYPE html>
<title>Credential Manager: request() basics.</title>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<script>
function stubResolverChecker(c) {
    assert_equals(c, undefined, "FIXME: We're currently always returning 'undefined'.");
    this.done();
}

function stubRejectionChecker(reason) {
    assert_unreached("request() should not reject, but did: " + reason.name);
}

(function() {
    var t = async_test("Verify the basics of request().");
    t.step(function () {
        navigator.credentials.request().then(
            t.step_func(stubResolverChecker.bind(t)),
            t.step_func(stubRejectionChecker.bind(t)));
    });
}());

(function() {
    var t = async_test("Verify the basics of request({}).");
    t.step(function () {
        navigator.credentials.request({}).then(
            t.step_func(stubResolverChecker.bind(t)),
            t.step_func(stubRejectionChecker.bind(t)));
    });
}());

(function() {
    var t = async_test("Verify the basics of request().");
    t.step(function () {
        navigator.credentials.request({
            federations: [ 'https://example.com/' ]
        }).then(
            t.step_func(stubResolverChecker.bind(t)),
            t.step_func(stubRejectionChecker.bind(t)));
    });
}());

(function() {
    var t = async_test("Verify the basics of request().");
    t.step(function () {
        navigator.credentials.request({
            federations: [ 'https://example.com/' ],
            zeroClickOnly: true
        }).then(
            t.step_func(stubResolverChecker.bind(t)),
            t.step_func(stubRejectionChecker.bind(t)));
    });
}());

(function() {
    var t = async_test("Verify the basics of request().");
    t.step(function () {
        navigator.credentials.request({
            zeroClickOnly: true
        }).then(
            t.step_func(stubResolverChecker.bind(t)),
            t.step_func(stubRejectionChecker.bind(t)));
    });
}());

(function() {
    var t = async_test("Verify the basics of request().");
    t.step(function () {
        navigator.credentials.request({
            notValid: 'yay!'
        }).then(
            t.step_func(stubResolverChecker.bind(t)),
            t.step_func(stubRejectionChecker.bind(t)));
    });
}());
</script>


text:
layout: post
title: Benchmarks for golang standard string library vs customized version
publish: true
---

# Benchmarks for 2 string libraries

It was fun reading K&R once again. Out of curiosity i set out to
implement a substring search function in go. It wasn't an easy task for a
newbie programmer like me. Due to multiple frustrations i decided to
peek at the go standard string library to see how it is done.

The standard strings library has a method called "Contains" that does what i need:

e.g

strings.Contains(str, subs) –> returns bool

However, i noticed that strings.Contains() calls another funciton
called Index():
     func Index(s, sep string) int

I immediately noticed that this function made the len(s) call 3
times. I curiosly added the following code:

m := len(s)

and replaced all 3 len(s) called with m.

Committed code can be found here:
<https://github.com/mesb/go/commit/5a56f4ea49b14f2251f64d7e38fbd8f892e13ac1>

Thanks to some hospitable people on the #go-nuts IRC channel, i
learned to do benchmarks on such experiments.

Here is the test directory:
<https://github.com/mesb/tests>

and below are the benchmark results

## Test Results

<colgroup>
<col  class="right" />

<col  class="right" />
</colgroup>

ns/op customized string lib
ns/op std string lib

1308
1639

1295
1663

1307
1726

1290
1748

1246
1617

1286
1617

1261
1673

1241
1651

1312
1633

1284
1747

## Average ns/op

<colgroup>
<col  class="right" />

<col  class="right" />
</colgroup>

customized lib
standard lib

1283
1671.4

In effect, the golang len(string) has to be made faster.

![img]({{ site.url }}/images/benchmarks.gif "Benchmarks for custmoized string liv vs the go standard string library")