text:
package io.seata.core.protocol.transaction;

import io.seata.core.model.BranchStatus;
import io.seata.core.model.BranchType;
import io.seata.core.rpc.RpcContext;
import io.seata.core.protocol.MessageType;

/**
 * The type Branch report request.
 *
 * @author slievrly
 */
public class BranchReportRequest extends AbstractTransactionRequestToTC {

    private String xid;

    private long branchId;

    private String resourceId;

    private BranchStatus status;

    private String applicationData;

    private BranchType branchType = BranchType.AT;

    /**
     * Gets xid.
     *
     * @return the xid
     */
    public String getXid() {
        return xid;
    }

    /**
     * Sets xid.
     *
     * @param xid the xid
     */
    public void setXid(String xid) {
        this.xid = xid;
    }

    /**
     * Gets branch id.
     *
     * @return the branch id
     */
    public long getBranchId() {
        return branchId;
    }

    /**
     * Sets branch id.
     *
     * @param branchId the branch id
     */
    public void setBranchId(long branchId) {
        this.branchId = branchId;
    }

    /**
     * Gets resource id.
     *
     * @return the resource id
     */
    public String getResourceId() {
        return resourceId;
    }

    /**
     * Sets resource id.
     *
     * @param resourceId the resource id
     */
    public void setResourceId(String resourceId) {
        this.resourceId = resourceId;
    }

    /**
     * Gets branch type.
     *
     * @return the branch type
     */
    public BranchType getBranchType() {
        return branchType;
    }

    /**
     * Sets branch type.
     *
     * @param branchType the branch type
     */
    public void setBranchType(BranchType branchType) {
        this.branchType = branchType;
    }

    /**
     * Gets status.
     *
     * @return the status
     */
    public BranchStatus getStatus() {
        return status;
    }

    /**
     * Sets status.
     *
     * @param status the status
     */
    public void setStatus(BranchStatus status) {
        this.status = status;
    }

    /**
     * Gets application data.
     *
     * @return the application data
     */
    public String getApplicationData() {
        return applicationData;
    }

    /**
     * Sets application data.
     *
     * @param applicationData the application data
     */
    public void setApplicationData(String applicationData) {
        this.applicationData = applicationData;
    }

    @Override
    public short getTypeCode() {
        return MessageType.TYPE_BRANCH_STATUS_REPORT;
    }

    @Override
    public AbstractTransactionResponse handle(RpcContext rpcContext) {
        return handler.handle(this, rpcContext);
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        result.append("xid=");
        result.append(xid);
        result.append(",");
        result.append("branchId=");
        result.append(branchId);
        result.append(",");
        result.append("resourceId=");
        result.append(resourceId);
        result.append(",");
        result.append("status=");
        result.append(status);
        result.append(",");
        result.append("applicationData=");
        result.append(applicationData);

        return result.toString();
    }
}


text:
var config = require('../config/config.json'),
	io;

module.exports = {
	boot: function() {
		io = require('./io');

		io.on('connection', function(socket) {
			require('./chat')(socket);
			require('./auth')(socket);
		});
	}
};

redpajama_set_name: RedPajamaGithub


text:
<?php
require_once dirname(__FILE__) . '/../config/config.php';
if (!$config) die('Fatal error: Cannot load file config file');
ob_start();
if (!isset($_SESSION['administrator'])) {
    header('Location: login.php');
    exit();
}

?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="<?= $config['general']['site_name'] ?> - Admin panel">
    <meta name="author" content="<?= $config['general']['author'] ?>">
    <meta name="keyword" content="">

    <title><?php echo $config['general']['site_name']; ?> - Admin Panel</title>

    <link rel="shortcut icon" type="image/png" href="../<?php echo $config['path']['favicon']; ?>"/>

    <link href="../files/css/bootstrap/bootstrap.css" rel="stylesheet">

    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="../files/plugins/lineicons/style.css">

    <link href="../files/css/admin.css" rel="stylesheet">
    <link href="../files/css/admin-responsive.css" rel="stylesheet">

        <img src="../<?php echo $config['path']['logo']; ?>" style="height: 30px;">

Logout

                        Dashboard

                        My details

                        System

                        System log

                        Settings


text:
using System.ComponentModel;

namespace OpenLiveWriter.ApplicationFramework.Commands
{
	/// <summary>
	/// Summary description for PrintCommand.
	/// </summary>
	public class CommandPageSetup : Command
	{

		public CommandPageSetup(IContainer container)
		{
			///
			/// Required for Windows.Forms Class Composition Designer support
			///
			InitializeComponent();

		}

		public CommandPageSetup()
		{
			///
			/// Required for Windows.Forms Class Composition Designer support
			///
			InitializeComponent();

		}

		#region Component Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			//
			// CommandPageSetup
			//
			this.Identifier = "MindShare.ApplicationCore.Commands.PageSetup";
			this.MainMenuPath = "&File@0/-Page Set&up...@120";
			this.Text = "Page Setup";

		}
		#endregion
	}
}


text:
package io.grpc.benchmarks;

import static io.grpc.benchmarks.Utils.pickUnusedPort;

import com.google.protobuf.ByteString;
import io.grpc.ManagedChannel;
import io.grpc.Server;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.benchmarks.proto.BenchmarkServiceGrpc;
import io.grpc.benchmarks.proto.Messages.Payload;
import io.grpc.benchmarks.proto.Messages.SimpleRequest;
import io.grpc.benchmarks.proto.Messages.SimpleResponse;
import io.grpc.benchmarks.qps.AsyncServer;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import io.grpc.internal.AbstractManagedChannelImplBuilder;
import io.grpc.internal.AbstractServerImplBuilder;
import io.grpc.netty.NegotiationType;
import io.grpc.netty.NettyChannelBuilder;
import io.grpc.netty.NettyServerBuilder;
import io.grpc.okhttp.OkHttpChannelBuilder;
import io.grpc.stub.StreamObserver;
import io.netty.channel.Channel;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.ServerChannel;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalChannel;
import io.netty.channel.local.LocalServerChannel;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Threads;

/** Some text. */
@State(Scope.Benchmark)
public class TransportBenchmark {
  public enum Transport {
    INPROCESS, NETTY, NETTY_LOCAL, NETTY_EPOLL, OKHTTP
  }

  @Param({"INPROCESS", "NETTY", "OKHTTP"})
  public Transport transport;
  @Param({"true", "false"})
  public boolean direct;

  private ManagedChannel channel;
  private Server server;
  private BenchmarkServiceGrpc.BenchmarkServiceBlockingStub stub;
  private BenchmarkServiceGrpc.BenchmarkServiceStub asyncStub;
  private EventLoopGroup groupToShutdown;

  @Setup
  @SuppressWarnings("LiteralClassName") // Epoll is not available on windows
  public void setUp() throws Exception {
    AbstractServerImplBuilder<?> serverBuilder;
    AbstractManagedChannelImplBuilder<?> channelBuilder;
    switch (transport) {
      case INPROCESS:
      {
        String name = "bench" + Math.random();
        serverBuilder = InProcessServerBuilder.forName(name);
        channelBuilder = InProcessChannelBuilder.forName(name);
        break;
      }
      case NETTY:
      {
        InetSocketAddress address = new InetSocketAddress("localhost", pickUnusedPort());
        serverBuilder = NettyServerBuilder.forAddress(address);
        channelBuilder = NettyChannelBuilder.forAddress(address)
            .negotiationType(NegotiationType.PLAINTEXT);
        break;
      }
      case NETTY_LOCAL:
      {
        String name = "bench" + Math.random();
        LocalAddress address = new LocalAddress(name);
        EventLoopGroup group = new DefaultEventLoopGroup();
        serverBuilder = NettyServerBuilder.forAddress(address)
            .bossEventLoopGroup(group)
            .workerEventLoopGroup(group)
            .channelType(LocalServerChannel.class);
        channelBuilder = NettyChannelBuilder.forAddress(address)
            .eventLoopGroup(group)
            .channelType(LocalChannel.class)
            .negotiationType(NegotiationType.PLAINTEXT);
        groupToShutdown = group;
        break;
      }
      case NETTY_EPOLL:
      {
        InetSocketAddress address = new InetSocketAddress("localhost", pickUnusedPort());

        // Reflection used since they are only available on linux.
        Class<?> groupClass = Class.forName("io.netty.channel.epoll.EpollEventLoopGroup");
        EventLoopGroup group = (EventLoopGroup) groupClass.getConstructor().newInstance();

        @SuppressWarnings("unchecked")
        Class<? extends ServerChannel> serverChannelClass = (Class<? extends ServerChannel>)
            Class.forName("io.netty.channel.epoll.EpollServerSocketChannel");
        serverBuilder = NettyServerBuilder.forAddress(address)
            .bossEventLoopGroup(group)
            .workerEventLoopGroup(group)
            .channelType(serverChannelClass);
        @SuppressWarnings("unchecked")
        Class<? extends Channel> channelClass = (Class<? extends Channel>)
            Class.forName("io.netty.channel.epoll.EpollSocketChannel");
        channelBuilder = NettyChannelBuilder.forAddress(address)
            .eventLoopGroup(group)
            .channelType(channelClass)
            .negotiationType(NegotiationType.PLAINTEXT);
        groupToShutdown = group;
        break;
      }
      case OKHTTP:
      {
        int port = pickUnusedPort();
        InetSocketAddress address = new InetSocketAddress("localhost", port);
        serverBuilder = NettyServerBuilder.forAddress(address);
        channelBuilder = OkHttpChannelBuilder.forAddress("localhost", port).usePlaintext();
        break;
      }
      default:
        throw new Exception("Unknown transport: " + transport);
    }

    if (direct) {
      serverBuilder.directExecutor();
      // Because blocking stubs avoid the executor, this doesn't do much.
      channelBuilder.directExecutor();
    }

    server = serverBuilder
        .addService(new AsyncServer.BenchmarkServiceImpl())
        .build();
    server.start();
    channel = channelBuilder.build();
    stub = BenchmarkServiceGrpc.newBlockingStub(channel);
    asyncStub = BenchmarkServiceGrpc.newStub(channel);
    // Wait for channel to start
    stub.unaryCall(SimpleRequest.getDefaultInstance());
  }

  @TearDown
  public void tearDown() throws Exception {
    channel.shutdown();
    server.shutdown();
    channel.awaitTermination(1, TimeUnit.SECONDS);
    server.awaitTermination(1, TimeUnit.SECONDS);
    if (!channel.isTerminated()) {
      throw new Exception("failed to shut down channel");
    }
    if (!server.isTerminated()) {
      throw new Exception("failed to shut down server");
    }
    if (groupToShutdown != null) {
      Future<?> unused = groupToShutdown.shutdownGracefully(0, 1, TimeUnit.SECONDS);
      groupToShutdown.awaitTermination(1, TimeUnit.SECONDS);
      if (!groupToShutdown.isTerminated()) {
        throw new Exception("failed to shut down event loop group.");
      }
    }
  }

  private static final SimpleRequest UNARY_CALL_1024_REQUEST = SimpleRequest.newBuilder()
      .setResponseSize(1024)
      .setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[1024])))
      .build();

  @Benchmark
  @BenchmarkMode(Mode.SampleTime)
  @OutputTimeUnit(TimeUnit.NANOSECONDS)
  public SimpleResponse unaryCall1024Latency() {
    return stub.unaryCall(UNARY_CALL_1024_REQUEST);
  }

  private static final int BYTE_THROUGHPUT_RESPONSE_SIZE = 1048576;
  private static final SimpleRequest BYTE_THROUGHPUT_REQUEST = SimpleRequest.newBuilder()
      .setResponseSize(BYTE_THROUGHPUT_RESPONSE_SIZE)
      .build();

  @Benchmark
  @BenchmarkMode(Mode.Throughput)
  @OperationsPerInvocation(BYTE_THROUGHPUT_RESPONSE_SIZE)
  @Threads(10)
  public SimpleResponse unaryCallsByteThroughput() {
    return stub.unaryCall(BYTE_THROUGHPUT_REQUEST);
  }

  private static final Throwable OK_THROWABLE = new RuntimeException("OK");

  @State(Scope.Thread)
  public static class PingPongStreamState {
    private final ThreadlessExecutor executor = new ThreadlessExecutor();
    private StreamObserver<SimpleRequest> requestObserver;
    private SimpleResponse response;
    private Throwable status;

    @Setup
    public void setUp(TransportBenchmark bench) {
      requestObserver = bench.asyncStub
          .withExecutor(executor)
          .streamingCall(new StreamObserver<SimpleResponse>() {
            @Override public void onNext(SimpleResponse next) {
              assert response == null;
              response = next;
            }

            @Override public void onError(Throwable t) {
              status = t;
            }

            @Override public void onCompleted() {
              status = OK_THROWABLE;
            }
          });
    }

    /** Issues request and waits for response. */
    public SimpleResponse pingPong(SimpleRequest request) throws InterruptedException {
      requestObserver.onNext(request);
      while (true) {
        executor.waitAndDrain();
        if (response != null) {
          SimpleResponse savedResponse = response;
          response = null;
          return savedResponse;
        }
        if (status != null) {
          throw new RuntimeException("Unexpected stream termination", status);
        }
      }
    }

    @TearDown
    public void tearDown() throws InterruptedException {
      requestObserver.onCompleted();
      while (status == null) {
        executor.waitAndDrain();
      }
      if (status != OK_THROWABLE) {
        throw new RuntimeException("Non-graceful stream shutdown", status);
      }
    }
  }

  @Benchmark
  @BenchmarkMode(Mode.Throughput)
  @OperationsPerInvocation(BYTE_THROUGHPUT_RESPONSE_SIZE)
  @Threads(10)
  public SimpleResponse streamingCallsByteThroughput(PingPongStreamState state)
      throws InterruptedException {
    return state.pingPong(BYTE_THROUGHPUT_REQUEST);
  }

  @State(Scope.Thread)
  public static class InfiniteStreamState {
    private final CancellableInterceptor cancellableInterceptor = new CancellableInterceptor();
    private Iterator<SimpleResponse> iter;

    @Setup
    public void setUp(TransportBenchmark bench) {
      iter = bench.stub
          .withInterceptors(cancellableInterceptor)
          .streamingFromServer(SimpleRequest.getDefaultInstance());
    }

    public SimpleResponse recv() throws InterruptedException {
      return iter.next();
    }

    @TearDown
    public void tearDown() throws InterruptedException {
      cancellableInterceptor.cancel("Normal tear-down", null);
      try {
        // Need to drain the queue
        while (iter.hasNext()) {
          iter.next();
        }
      } catch (StatusRuntimeException ex) {
        if (!Status.Code.CANCELLED.equals(ex.getStatus().getCode())) {
          throw ex;
        }
      }
    }
  }

  // NOTE: Causes OOM with NETTY_LOCAL. Probably a flow control problem in NETTY_LOCAL, but we
  // aren't too concerned.
  @Benchmark
  @BenchmarkMode(Mode.Throughput)
  @Threads(10)
  public SimpleResponse streamingCallsMessageThroughput(InfiniteStreamState state)
      throws InterruptedException {
    return state.recv();
  }
}


text:
LANDSTEAD

Land and property registry

      LEARN HOW IT WORKS

              "Landstead - Land and property registry on NEM is one of the best proposal I've seen in this competition, it shows how the creator of the system has a wholestic view of things."

Landstead uses NEM blockchain technology to create a registry of land and property, allowing government and citizens to co-create an open blockchain system that can be trusted and consulted by interested parties.

        NEM provides the perfect foundation for this project, offering payments, messaging, asset management, multi-user accounts and a naming system implemented with an outstanding core blockchain technology.

The Process

Submit a citizen account

As a Citizen, initiate the registration process by submitting an account for government validation.

Validate an account

As a Civil Servant, validate a citizen account after verifications, such as the citizen ID.

Register a Property

As a Cadastral Service, register a property based on its unique identification, together with additional information about the property.

Register property ownership

As a Cadastral Service, register the ownership of a property, linking it to the account of the owner(s).

Verify your account

As a Citizen, open an account and verify registered ownership of properties.

Transfer property

As a Notary, transfer a property from previous owner(s) to new owner(s).

The Benefits of using Nem Blockchain

Security

Built on a secure blockchain environment, the Landstead platform puts security first with NEM at its core.

Control

Governments are the axis of the platform, managing user privileges as well as land and property data. Through notaries and government servants we manage veracity via the blockchain.

Social

We give the citizen the capacity to manage and visualize the properties they have, emphasising their prominent role on the Landstead platform.

Scalability

Created to manage high quantities of simultaneous users without loss of performance.

Efficiency

The Landstead platform is created specifically to offer users the flexibility to operate whenever they choose.

Auditable

Users are able to review any transaction and registration on the NEM blockchain, providing transparancy and veracity.

            Archives

Github Source Code

Video Demo

White Paper

            About

NEM

Atraura

Atraura Blockchain

Landstead is an Open Source project under The MIT License (MIT)

          Albert Castellana Council Member of nem.io Foundation - Owner at Atraura Blockchain - VD of Innovation at COEINF

          David García - COO at Atraura

          Alvaro Llobet - CCO at Atraura

          Jeff McDonald - Vice President of nem.io Foundation

          Erik Van Himbergen - Sr. Business Analyst at Digipolis


text: Plataforma de crowdfounding para la reconstruccion del ecuador luego del terremo de Abril 2016


text:
using Xunit;

namespace Carbon.Color.Tests
{
    public class RelativeLuminanceTests
    {
        [Fact]
        public void A()
        {
            Assert.Equal(1,     RelativeLuminance.Calculate(NamedColor.White), 3);
            Assert.Equal(0.213, RelativeLuminance.Calculate(NamedColor.Red),   3);
            Assert.Equal(0.715, RelativeLuminance.Calculate(NamedColor.Green), 3);
            Assert.Equal(0.072, RelativeLuminance.Calculate(NamedColor.Blue), 3);
            Assert.Equal(0,     RelativeLuminance.Calculate(NamedColor.Black), 3);
        }
    }
}


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

#include "net/http/http_server_properties_manager.h"

#include "base/basictypes.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/message_loop/message_loop.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/testing_pref_service.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/test/test_simple_task_runner.h"
#include "base/thread_task_runner_handle.h"
#include "base/values.h"
#include "net/base/ip_address_number.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"

namespace net {

namespace {

using base::StringPrintf;
using ::testing::_;
using ::testing::Invoke;
using ::testing::Mock;
using ::testing::StrictMock;

const char kTestHttpServerProperties[] = "TestHttpServerProperties";

class TestingHttpServerPropertiesManager : public HttpServerPropertiesManager {
 public:
  TestingHttpServerPropertiesManager(
      PrefService* pref_service,
      const char* pref_path,
      scoped_refptr<base::SingleThreadTaskRunner> io_task_runner)
      : HttpServerPropertiesManager(pref_service, pref_path, io_task_runner) {
    InitializeOnNetworkThread();
  }

  ~TestingHttpServerPropertiesManager() override {}

  // Make these methods public for testing.
  using HttpServerPropertiesManager::ScheduleUpdateCacheOnPrefThread;

  // Post tasks without a delay during tests.
  void StartPrefsUpdateTimerOnNetworkThread(base::TimeDelta delay) override {
    HttpServerPropertiesManager::StartPrefsUpdateTimerOnNetworkThread(
        base::TimeDelta());
  }

  void UpdateCacheFromPrefsOnUIConcrete() {
    HttpServerPropertiesManager::UpdateCacheFromPrefsOnPrefThread();
  }

  // Post tasks without a delay during tests.
  void StartCacheUpdateTimerOnPrefThread(base::TimeDelta delay) override {
    HttpServerPropertiesManager::StartCacheUpdateTimerOnPrefThread(
        base::TimeDelta());
  }

  void UpdatePrefsFromCacheOnNetworkThreadConcrete(
      const base::Closure& callback) {
    HttpServerPropertiesManager::UpdatePrefsFromCacheOnNetworkThread(callback);
  }

  void ScheduleUpdatePrefsOnNetworkThreadConcrete(Location location) {
    HttpServerPropertiesManager::ScheduleUpdatePrefsOnNetworkThread(location);
  }

  void ScheduleUpdatePrefsOnNetworkThread() {
    // Picked a random Location as caller.
    HttpServerPropertiesManager::ScheduleUpdatePrefsOnNetworkThread(
        DETECTED_CORRUPTED_PREFS);
  }

  MOCK_METHOD0(UpdateCacheFromPrefsOnPrefThread, void());
  MOCK_METHOD1(UpdatePrefsFromCacheOnNetworkThread, void(const base::Closure&));
  MOCK_METHOD1(ScheduleUpdatePrefsOnNetworkThread, void(Location location));
  MOCK_METHOD7(UpdateCacheFromPrefsOnNetworkThread,
               void(std::vector<std::string>* spdy_servers,
                    SpdySettingsMap* spdy_settings_map,
                    AlternativeServiceMap* alternative_service_map,
                    IPAddressNumber* last_quic_address,
                    ServerNetworkStatsMap* server_network_stats_map,
                    QuicServerInfoMap* quic_server_info_map,
                    bool detected_corrupted_prefs));
  MOCK_METHOD7(UpdatePrefsOnPrefThread,
               void(base::ListValue* spdy_server_list,
                    SpdySettingsMap* spdy_settings_map,
                    AlternativeServiceMap* alternative_service_map,
                    IPAddressNumber* last_quic_address,
                    ServerNetworkStatsMap* server_network_stats_map,
                    QuicServerInfoMap* quic_server_info_map,
                    const base::Closure& completion));

 private:
  DISALLOW_COPY_AND_ASSIGN(TestingHttpServerPropertiesManager);
};

}  // namespace

class HttpServerPropertiesManagerTest : public testing::Test {
 protected:
  HttpServerPropertiesManagerTest() {}

  void SetUp() override {
    one_day_from_now_ = base::Time::Now() + base::TimeDelta::FromDays(1);
    pref_service_.registry()->RegisterDictionaryPref(kTestHttpServerProperties);
    http_server_props_manager_.reset(
        new StrictMock<TestingHttpServerPropertiesManager>(
            &pref_service_, kTestHttpServerProperties,
            base::ThreadTaskRunnerHandle::Get()));
    ExpectCacheUpdate();
    base::RunLoop().RunUntilIdle();
  }

  void TearDown() override {
    if (http_server_props_manager_.get())
      http_server_props_manager_->ShutdownOnPrefThread();
    base::RunLoop().RunUntilIdle();
    http_server_props_manager_.reset();
  }

  void ExpectCacheUpdate() {
    EXPECT_CALL(*http_server_props_manager_, UpdateCacheFromPrefsOnPrefThread())
        .WillOnce(Invoke(http_server_props_manager_.get(),
                         &TestingHttpServerPropertiesManager::
                             UpdateCacheFromPrefsOnUIConcrete));
  }

  void ExpectScheduleUpdatePrefsOnNetworkThread() {
    EXPECT_CALL(*http_server_props_manager_,
                ScheduleUpdatePrefsOnNetworkThread(_))
        .WillOnce(Invoke(http_server_props_manager_.get(),
                         &TestingHttpServerPropertiesManager::
                             ScheduleUpdatePrefsOnNetworkThreadConcrete));
  }

  void ExpectScheduleUpdatePrefsOnNetworkThreadRepeatedly() {
    EXPECT_CALL(*http_server_props_manager_,
                ScheduleUpdatePrefsOnNetworkThread(_))
        .WillRepeatedly(Invoke(http_server_props_manager_.get(),
                               &TestingHttpServerPropertiesManager::
                                   ScheduleUpdatePrefsOnNetworkThreadConcrete));
  }

  void ExpectPrefsUpdate() {
    EXPECT_CALL(*http_server_props_manager_,
                UpdatePrefsFromCacheOnNetworkThread(_))
        .WillOnce(Invoke(http_server_props_manager_.get(),
                         &TestingHttpServerPropertiesManager::
                             UpdatePrefsFromCacheOnNetworkThreadConcrete));
  }

  void ExpectPrefsUpdateRepeatedly() {
    EXPECT_CALL(*http_server_props_manager_,
                UpdatePrefsFromCacheOnNetworkThread(_))
        .WillRepeatedly(
            Invoke(http_server_props_manager_.get(),
                   &TestingHttpServerPropertiesManager::
                       UpdatePrefsFromCacheOnNetworkThreadConcrete));
  }

  bool HasAlternativeService(const HostPortPair& server) {
    const AlternativeServiceVector alternative_service_vector =
        http_server_props_manager_->GetAlternativeServices(server);
    return !alternative_service_vector.empty();
  }

  //base::RunLoop loop_;
  TestingPrefServiceSimple pref_service_;
  scoped_ptr<TestingHttpServerPropertiesManager> http_server_props_manager_;
  base::Time one_day_from_now_;

 private:
  DISALLOW_COPY_AND_ASSIGN(HttpServerPropertiesManagerTest);
};

TEST_F(HttpServerPropertiesManagerTest,
       SingleUpdateForTwoSpdyServerPrefChanges) {
  ExpectCacheUpdate();

  // Set up the prefs for www.google.com:80 and mail.google.com:80 and then set
  // it twice. Only expect a single cache update.

  base::DictionaryValue* server_pref_dict = new base::DictionaryValue;
  HostPortPair google_server("www.google.com", 80);
  HostPortPair mail_server("mail.google.com", 80);

  // Set supports_spdy for www.google.com:80.
  server_pref_dict->SetBoolean("supports_spdy", true);

  // Set up alternative_services for www.google.com:80.
  base::DictionaryValue* alternative_service_dict0 = new base::DictionaryValue;
  alternative_service_dict0->SetInteger("port", 443);
  alternative_service_dict0->SetString("protocol_str", "npn-h2");
  base::DictionaryValue* alternative_service_dict1 = new base::DictionaryValue;
  alternative_service_dict1->SetInteger("port", 1234);
  alternative_service_dict1->SetString("protocol_str", "quic");
  base::ListValue* alternative_service_list = new base::ListValue;
  alternative_service_list->Append(alternative_service_dict0);
  alternative_service_list->Append(alternative_service_dict1);
  server_pref_dict->SetWithoutPathExpansion("alternative_service",
                                            alternative_service_list);

  // Set up ServerNetworkStats for www.google.com:80.
  base::DictionaryValue* stats = new base::DictionaryValue;
  stats->SetInteger("srtt", 10);
  server_pref_dict->SetWithoutPathExpansion("network_stats", stats);

  // Set the server preference for www.google.com:80.
  base::DictionaryValue* servers_dict = new base::DictionaryValue;
  servers_dict->SetWithoutPathExpansion("www.google.com:80", server_pref_dict);

  // Set the preference for mail.google.com server.
  base::DictionaryValue* server_pref_dict1 = new base::DictionaryValue;

  // Set supports_spdy for mail.google.com:80
  server_pref_dict1->SetBoolean("supports_spdy", true);

  // Set up alternate_protocol for mail.google.com:80 to test migration to
  // alternative_service.
  base::DictionaryValue* alternate_protocol_dict = new base::DictionaryValue;
  alternate_protocol_dict->SetString("protocol_str", "npn-spdy/3.1");
  alternate_protocol_dict->SetInteger("port", 444);
  server_pref_dict1->SetWithoutPathExpansion("alternate_protocol",
                                             alternate_protocol_dict);

  // Set up ServerNetworkStats for mail.google.com:80.
  base::DictionaryValue* stats1 = new base::DictionaryValue;
  stats1->SetInteger("srtt", 20);
  server_pref_dict1->SetWithoutPathExpansion("network_stats", stats1);
  // Set the server preference for mail.google.com:80.
  servers_dict->SetWithoutPathExpansion("mail.google.com:80",
                                        server_pref_dict1);

  base::DictionaryValue* http_server_properties_dict =
      new base::DictionaryValue;
  HttpServerPropertiesManager::SetVersion(http_server_properties_dict, -1);
  http_server_properties_dict->SetWithoutPathExpansion("servers", servers_dict);
  base::DictionaryValue* supports_quic = new base::DictionaryValue;
  supports_quic->SetBoolean("used_quic", true);
  supports_quic->SetString("address", "127.0.0.1");
  http_server_properties_dict->SetWithoutPathExpansion("supports_quic",
                                                       supports_quic);

  // Set quic_server_info for www.google.com:80 and mail.google.com:80.
  base::DictionaryValue* quic_servers_dict = new base::DictionaryValue;
  base::DictionaryValue* quic_server_pref_dict1 = new base::DictionaryValue;
  std::string quic_server_info1("quic_server_info1");
  quic_server_pref_dict1->SetStringWithoutPathExpansion("server_info",
                                                        quic_server_info1);
  base::DictionaryValue* quic_server_pref_dict2 = new base::DictionaryValue;
  std::string quic_server_info2("quic_server_info2");
  quic_server_pref_dict2->SetStringWithoutPathExpansion("server_info",
                                                        quic_server_info2);
  // Set the quic_server_info1 for www.google.com server.
  QuicServerId google_quic_server_id("www.google.com", 80);
  quic_servers_dict->SetWithoutPathExpansion(google_quic_server_id.ToString(),
                                             quic_server_pref_dict1);
  // Set the quic_server_info2 for mail.google.com server.
  QuicServerId mail_quic_server_id("mail.google.com", 80);
  quic_servers_dict->SetWithoutPathExpansion(mail_quic_server_id.ToString(),
                                             quic_server_pref_dict2);
  http_server_properties_dict->SetWithoutPathExpansion("quic_servers",
                                                       quic_servers_dict);

  // Set the same value for kHttpServerProperties multiple times.
  pref_service_.SetManagedPref(kTestHttpServerProperties,
                               http_server_properties_dict);
  base::DictionaryValue* http_server_properties_dict2 =
      http_server_properties_dict->DeepCopy();
  pref_service_.SetManagedPref(kTestHttpServerProperties,
                               http_server_properties_dict2);

  base::RunLoop().RunUntilIdle();
  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());

  // Verify SupportsSpdy.
  EXPECT_TRUE(
      http_server_props_manager_->SupportsRequestPriority(google_server));
  EXPECT_TRUE(http_server_props_manager_->SupportsRequestPriority(mail_server));
  EXPECT_FALSE(http_server_props_manager_->SupportsRequestPriority(
      HostPortPair::FromString("foo.google.com:1337")));

  // Verify alternative service.
  const AlternativeServiceMap& map =
      http_server_props_manager_->alternative_service_map();
  ASSERT_EQ(2u, map.size());
  AlternativeServiceMap::const_iterator map_it = map.begin();
  EXPECT_EQ("www.google.com", map_it->first.host());
  ASSERT_EQ(2u, map_it->second.size());
  EXPECT_EQ(NPN_HTTP_2, map_it->second[0].alternative_service.protocol);
  EXPECT_TRUE(map_it->second[0].alternative_service.host.empty());
  EXPECT_EQ(443, map_it->second[0].alternative_service.port);
  EXPECT_EQ(QUIC, map_it->second[1].alternative_service.protocol);
  EXPECT_TRUE(map_it->second[1].alternative_service.host.empty());
  EXPECT_EQ(1234, map_it->second[1].alternative_service.port);
  ++map_it;
  EXPECT_EQ("mail.google.com", map_it->first.host());
  ASSERT_EQ(1u, map_it->second.size());
  EXPECT_EQ(NPN_SPDY_3_1, map_it->second[0].alternative_service.protocol);
  EXPECT_TRUE(map_it->second[0].alternative_service.host.empty());
  EXPECT_EQ(444, map_it->second[0].alternative_service.port);

  // Verify SupportsQuic.
  IPAddressNumber last_address;
  EXPECT_TRUE(http_server_props_manager_->GetSupportsQuic(&last_address));
  EXPECT_EQ("127.0.0.1", IPAddressToString(last_address));

  // Verify ServerNetworkStats.
  const ServerNetworkStats* stats2 =
      http_server_props_manager_->GetServerNetworkStats(google_server);
  EXPECT_EQ(10, stats2->srtt.ToInternalValue());
  const ServerNetworkStats* stats3 =
      http_server_props_manager_->GetServerNetworkStats(mail_server);
  EXPECT_EQ(20, stats3->srtt.ToInternalValue());

  // Verify QuicServerInfo.
  EXPECT_EQ(quic_server_info1, *http_server_props_manager_->GetQuicServerInfo(
                                   google_quic_server_id));
  EXPECT_EQ(quic_server_info2, *http_server_props_manager_->GetQuicServerInfo(
                                   mail_quic_server_id));
}

TEST_F(HttpServerPropertiesManagerTest, BadCachedHostPortPair) {
  ExpectCacheUpdate();
  // The prefs are automaticalls updated in the case corruption is detected.
  ExpectPrefsUpdate();
  ExpectScheduleUpdatePrefsOnNetworkThread();

  base::DictionaryValue* server_pref_dict = new base::DictionaryValue;

  // Set supports_spdy for www.google.com:65536.
  server_pref_dict->SetBoolean("supports_spdy", true);

  // Set up alternative_service for www.google.com:65536.
  base::DictionaryValue* alternative_service_dict = new base::DictionaryValue;
  alternative_service_dict->SetString("protocol_str", "npn-h2");
  alternative_service_dict->SetInteger("port", 80);
  base::ListValue* alternative_service_list = new base::ListValue;
  alternative_service_list->Append(alternative_service_dict);
  server_pref_dict->SetWithoutPathExpansion("alternative_service",
                                            alternative_service_list);

  // Set up ServerNetworkStats for www.google.com:65536.
  base::DictionaryValue* stats = new base::DictionaryValue;
  stats->SetInteger("srtt", 10);
  server_pref_dict->SetWithoutPathExpansion("network_stats", stats);

  // Set the server preference for www.google.com:65536.
  base::DictionaryValue* servers_dict = new base::DictionaryValue;
  servers_dict->SetWithoutPathExpansion("www.google.com:65536",
                                        server_pref_dict);

  // Set quic_server_info for www.google.com:65536.
  base::DictionaryValue* quic_servers_dict = new base::DictionaryValue;
  base::DictionaryValue* quic_server_pref_dict1 = new base::DictionaryValue;
  quic_server_pref_dict1->SetStringWithoutPathExpansion("server_info",
                                                        "quic_server_info1");
  quic_servers_dict->SetWithoutPathExpansion("http://mail.google.com:65536",
                                             quic_server_pref_dict1);

  base::DictionaryValue* http_server_properties_dict =
      new base::DictionaryValue;
  HttpServerPropertiesManager::SetVersion(http_server_properties_dict, -1);
  http_server_properties_dict->SetWithoutPathExpansion("servers", servers_dict);
  http_server_properties_dict->SetWithoutPathExpansion("quic_servers",
                                                       quic_servers_dict);

  // Set up the pref.
  pref_service_.SetManagedPref(kTestHttpServerProperties,
                               http_server_properties_dict);

  base::RunLoop().RunUntilIdle();
  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());

  // Verify that nothing is set.
  EXPECT_FALSE(http_server_props_manager_->SupportsRequestPriority(
      HostPortPair::FromString("www.google.com:65536")));
  EXPECT_FALSE(
      HasAlternativeService(HostPortPair::FromString("www.google.com:65536")));
  const ServerNetworkStats* stats1 =
      http_server_props_manager_->GetServerNetworkStats(
          HostPortPair::FromString("www.google.com:65536"));
  EXPECT_EQ(NULL, stats1);
  EXPECT_EQ(0u, http_server_props_manager_->quic_server_info_map().size());
}

TEST_F(HttpServerPropertiesManagerTest, BadCachedAltProtocolPort) {
  ExpectCacheUpdate();
  // The prefs are automaticalls updated in the case corruption is detected.
  ExpectPrefsUpdate();
  ExpectScheduleUpdatePrefsOnNetworkThread();

  base::DictionaryValue* server_pref_dict = new base::DictionaryValue;

  // Set supports_spdy for www.google.com:80.
  server_pref_dict->SetBoolean("supports_spdy", true);

  // Set up alternative_service for www.google.com:80.
  base::DictionaryValue* alternative_service_dict = new base::DictionaryValue;
  alternative_service_dict->SetString("protocol_str", "npn-h2");
  alternative_service_dict->SetInteger("port", 65536);
  base::ListValue* alternative_service_list = new base::ListValue;
  alternative_service_list->Append(alternative_service_dict);
  server_pref_dict->SetWithoutPathExpansion("alternative_service",
                                            alternative_service_list);

  // Set the server preference for www.google.com:80.
  base::DictionaryValue* servers_dict = new base::DictionaryValue;
  servers_dict->SetWithoutPathExpansion("www.google.com:80", server_pref_dict);

  base::DictionaryValue* http_server_properties_dict =
      new base::DictionaryValue;
  HttpServerPropertiesManager::SetVersion(http_server_properties_dict, -1);
  http_server_properties_dict->SetWithoutPathExpansion("servers", servers_dict);

  // Set up the pref.
  pref_service_.SetManagedPref(kTestHttpServerProperties,
                               http_server_properties_dict);

  base::RunLoop().RunUntilIdle();
  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());

  // Verify alternative service is not set.
  EXPECT_FALSE(
      HasAlternativeService(HostPortPair::FromString("www.google.com:80")));
}

TEST_F(HttpServerPropertiesManagerTest, SupportsSpdy) {
  ExpectPrefsUpdate();
  ExpectScheduleUpdatePrefsOnNetworkThread();

  // Post an update task to the network thread. SetSupportsSpdy calls
  // ScheduleUpdatePrefsOnNetworkThread.

  // Add mail.google.com:443 as a supporting spdy server.
  HostPortPair spdy_server_mail("mail.google.com", 443);
  EXPECT_FALSE(
      http_server_props_manager_->SupportsRequestPriority(spdy_server_mail));
  http_server_props_manager_->SetSupportsSpdy(spdy_server_mail, true);
  // ExpectScheduleUpdatePrefsOnNetworkThread() should be called only once.
  http_server_props_manager_->SetSupportsSpdy(spdy_server_mail, true);

  // Run the task.
  base::RunLoop().RunUntilIdle();

  EXPECT_TRUE(
      http_server_props_manager_->SupportsRequestPriority(spdy_server_mail));
  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
}

TEST_F(HttpServerPropertiesManagerTest, SetSpdySetting) {
  ExpectPrefsUpdate();
  ExpectScheduleUpdatePrefsOnNetworkThread();

  // Add SpdySetting for mail.google.com:443.
  HostPortPair spdy_server_mail("mail.google.com", 443);
  const SpdySettingsIds id1 = SETTINGS_UPLOAD_BANDWIDTH;
  const SpdySettingsFlags flags1 = SETTINGS_FLAG_PLEASE_PERSIST;
  const uint32 value1 = 31337;
  http_server_props_manager_->SetSpdySetting(
      spdy_server_mail, id1, flags1, value1);

  // Run the task.
  base::RunLoop().RunUntilIdle();

  const SettingsMap& settings_map1_ret =
      http_server_props_manager_->GetSpdySettings(spdy_server_mail);
  ASSERT_EQ(1U, settings_map1_ret.size());
  SettingsMap::const_iterator it1_ret = settings_map1_ret.find(id1);
  EXPECT_TRUE(it1_ret != settings_map1_ret.end());
  SettingsFlagsAndValue flags_and_value1_ret = it1_ret->second;
  EXPECT_EQ(SETTINGS_FLAG_PERSISTED, flags_and_value1_ret.first);
  EXPECT_EQ(value1, flags_and_value1_ret.second);

  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
}

TEST_F(HttpServerPropertiesManagerTest, ClearSpdySetting) {
  ExpectPrefsUpdateRepeatedly();
  ExpectScheduleUpdatePrefsOnNetworkThreadRepeatedly();

  // Add SpdySetting for mail.google.com:443.
  HostPortPair spdy_server_mail("mail.google.com", 443);
  const SpdySettingsIds id1 = SETTINGS_UPLOAD_BANDWIDTH;
  const SpdySettingsFlags flags1 = SETTINGS_FLAG_PLEASE_PERSIST;
  const uint32 value1 = 31337;
  http_server_props_manager_->SetSpdySetting(
      spdy_server_mail, id1, flags1, value1);

  // Run the task.
  base::RunLoop().RunUntilIdle();

  const SettingsMap& settings_map1_ret =
      http_server_props_manager_->GetSpdySettings(spdy_server_mail);
  ASSERT_EQ(1U, settings_map1_ret.size());
  SettingsMap::const_iterator it1_ret = settings_map1_ret.find(id1);
  EXPECT_TRUE(it1_ret != settings_map1_ret.end());
  SettingsFlagsAndValue flags_and_value1_ret = it1_ret->second;
  EXPECT_EQ(SETTINGS_FLAG_PERSISTED, flags_and_value1_ret.first);
  EXPECT_EQ(value1, flags_and_value1_ret.second);

  // Clear SpdySetting for mail.google.com:443.
  http_server_props_manager_->ClearSpdySettings(spdy_server_mail);

  // Run the task.
  base::RunLoop().RunUntilIdle();

  // Verify that there are no entries in the settings map for
  // mail.google.com:443.
  const SettingsMap& settings_map2_ret =
      http_server_props_manager_->GetSpdySettings(spdy_server_mail);
  ASSERT_EQ(0U, settings_map2_ret.size());

  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
}

TEST_F(HttpServerPropertiesManagerTest, ClearAllSpdySetting) {
  ExpectPrefsUpdateRepeatedly();
  ExpectScheduleUpdatePrefsOnNetworkThreadRepeatedly();

  // Add SpdySetting for mail.google.com:443.
  HostPortPair spdy_server_mail("mail.google.com", 443);
  const SpdySettingsIds id1 = SETTINGS_UPLOAD_BANDWIDTH;
  const SpdySettingsFlags flags1 = SETTINGS_FLAG_PLEASE_PERSIST;
  const uint32 value1 = 31337;
  http_server_props_manager_->SetSpdySetting(
      spdy_server_mail, id1, flags1, value1);

  // Run the task.
  base::RunLoop().RunUntilIdle();

  const SettingsMap& settings_map1_ret =
      http_server_props_manager_->GetSpdySettings(spdy_server_mail);
  ASSERT_EQ(1U, settings_map1_ret.size());
  SettingsMap::const_iterator it1_ret = settings_map1_ret.find(id1);
  EXPECT_TRUE(it1_ret != settings_map1_ret.end());
  SettingsFlagsAndValue flags_and_value1_ret = it1_ret->second;
  EXPECT_EQ(SETTINGS_FLAG_PERSISTED, flags_and_value1_ret.first);
  EXPECT_EQ(value1, flags_and_value1_ret.second);

  // Clear All SpdySettings.
  http_server_props_manager_->ClearAllSpdySettings();

  // Run the task.
  base::RunLoop().RunUntilIdle();

  // Verify that there are no entries in the settings map.
  const SpdySettingsMap& spdy_settings_map2_ret =
      http_server_props_manager_->spdy_settings_map();
  ASSERT_EQ(0U, spdy_settings_map2_ret.size());

  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
}

TEST_F(HttpServerPropertiesManagerTest, GetAlternativeServices) {
  ExpectPrefsUpdate();
  ExpectScheduleUpdatePrefsOnNetworkThread();

  HostPortPair spdy_server_mail("mail.google.com", 80);
  EXPECT_FALSE(HasAlternativeService(spdy_server_mail));
  const AlternativeService alternative_service(NPN_HTTP_2, "mail.google.com",
                                               443);
  http_server_props_manager_->SetAlternativeService(
      spdy_server_mail, alternative_service, 1.0, one_day_from_now_);
  // ExpectScheduleUpdatePrefsOnNetworkThread() should be called only once.
  http_server_props_manager_->SetAlternativeService(
      spdy_server_mail, alternative_service, 1.0, one_day_from_now_);

  // Run the task.
  base::RunLoop().RunUntilIdle();
  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());

  AlternativeServiceVector alternative_service_vector =
      http_server_props_manager_->GetAlternativeServices(spdy_server_mail);
  ASSERT_EQ(1u, alternative_service_vector.size());
  EXPECT_EQ(alternative_service, alternative_service_vector[0]);
}

TEST_F(HttpServerPropertiesManagerTest, SetAlternativeServices) {
  ExpectPrefsUpdate();
  ExpectScheduleUpdatePrefsOnNetworkThread();

  HostPortPair spdy_server_mail("mail.google.com", 80);
  EXPECT_FALSE(HasAlternativeService(spdy_server_mail));
  AlternativeServiceInfoVector alternative_service_info_vector;
  const AlternativeService alternative_service1(NPN_HTTP_2, "mail.google.com",
                                                443);
  alternative_service_info_vector.push_back(
      AlternativeServiceInfo(alternative_service1, 1.0, one_day_from_now_));
  const AlternativeService alternative_service2(QUIC, "mail.google.com", 1234);
  alternative_service_info_vector.push_back(
      AlternativeServiceInfo(alternative_service2, 1.0, one_day_from_now_));
  http_server_props_manager_->SetAlternativeServices(
      spdy_server_mail, alternative_service_info_vector);
  // ExpectScheduleUpdatePrefsOnNetworkThread() should be called only once.
  http_server_props_manager_->SetAlternativeServices(
      spdy_server_mail, alternative_service_info_vector);

  // Run the task.
  base::RunLoop().RunUntilIdle();
  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());

  AlternativeServiceVector alternative_service_vector =
      http_server_props_manager_->GetAlternativeServices(spdy_server_mail);
  ASSERT_EQ(2u, alternative_service_vector.size());
  EXPECT_EQ(alternative_service1, alternative_service_vector[0]);
  EXPECT_EQ(alternative_service2, alternative_service_vector[1]);
}

TEST_F(HttpServerPropertiesManagerTest, SetAlternativeServicesEmpty) {
  HostPortPair spdy_server_mail("mail.google.com", 80);
  EXPECT_FALSE(HasAlternativeService(spdy_server_mail));
  const AlternativeService alternative_service(NPN_HTTP_2, "mail.google.com",
                                               443);
  http_server_props_manager_->SetAlternativeServices(
      spdy_server_mail, AlternativeServiceInfoVector());
  // ExpectScheduleUpdatePrefsOnNetworkThread() should not be called.

  // Run the task.
  base::RunLoop().RunUntilIdle();
  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());

  EXPECT_FALSE(HasAlternativeService(spdy_server_mail));
}

TEST_F(HttpServerPropertiesManagerTest, ClearAlternativeServices) {
  ExpectPrefsUpdate();
  ExpectScheduleUpdatePrefsOnNetworkThread();

  HostPortPair spdy_server_mail("mail.google.com", 80);
  EXPECT_FALSE(HasAlternativeService(spdy_server_mail));
  AlternativeService alternative_service(NPN_HTTP_2, "mail.google.com", 443);
  http_server_props_manager_->SetAlternativeService(
      spdy_server_mail, alternative_service, 1.0, one_day_from_now_);
  ExpectScheduleUpdatePrefsOnNetworkThread();
  http_server_props_manager_->ClearAlternativeServices(spdy_server_mail);
  // ExpectScheduleUpdatePrefsOnNetworkThread() should be called only once.
  http_server_props_manager_->ClearAlternativeServices(spdy_server_mail);

  // Run the task.
  base::RunLoop().RunUntilIdle();
  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());

  EXPECT_FALSE(HasAlternativeService(spdy_server_mail));
}

TEST_F(HttpServerPropertiesManagerTest, ConfirmAlternativeService) {
  ExpectPrefsUpdate();

  HostPortPair spdy_server_mail("mail.google.com", 80);
  EXPECT_FALSE(HasAlternativeService(spdy_server_mail));
  AlternativeService alternative_service(NPN_HTTP_2, "mail.google.com", 443);

  ExpectScheduleUpdatePrefsOnNetworkThread();
  http_server_props_manager_->SetAlternativeService(
      spdy_server_mail, alternative_service, 1.0, one_day_from_now_);

  EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken(
      alternative_service));
  EXPECT_FALSE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken(
      alternative_service));

  ExpectScheduleUpdatePrefsOnNetworkThread();
  http_server_props_manager_->MarkAlternativeServiceBroken(alternative_service);
  EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken(
      alternative_service));
  EXPECT_TRUE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken(
      alternative_service));

  ExpectScheduleUpdatePrefsOnNetworkThread();
  http_server_props_manager_->ConfirmAlternativeService(alternative_service);
  EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken(
      alternative_service));
  EXPECT_FALSE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken(
      alternative_service));
  // ExpectScheduleUpdatePrefsOnNetworkThread() should be called only once.
  http_server_props_manager_->ConfirmAlternativeService(alternative_service);
  EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken(
      alternative_service));
  EXPECT_FALSE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken(
      alternative_service));

  // Run the task.
  base::RunLoop().RunUntilIdle();
  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());

  EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken(
      alternative_service));
  EXPECT_FALSE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken(
      alternative_service));
}

TEST_F(HttpServerPropertiesManagerTest, SupportsQuic) {
  ExpectPrefsUpdate();
  ExpectScheduleUpdatePrefsOnNetworkThread();

  IPAddressNumber address;
  EXPECT_FALSE(http_server_props_manager_->GetSupportsQuic(&address));

  IPAddressNumber actual_address;
  CHECK(ParseIPLiteralToNumber("127.0.0.1", &actual_address));
  http_server_props_manager_->SetSupportsQuic(true, actual_address);
  // ExpectScheduleUpdatePrefsOnNetworkThread() should be called only once.
  http_server_props_manager_->SetSupportsQuic(true, actual_address);

  // Run the task.
  base::RunLoop().RunUntilIdle();
  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());

  EXPECT_TRUE(http_server_props_manager_->GetSupportsQuic(&address));
  EXPECT_EQ(actual_address, address);
}

TEST_F(HttpServerPropertiesManagerTest, ServerNetworkStats) {
  ExpectPrefsUpdate();
  ExpectScheduleUpdatePrefsOnNetworkThread();

  HostPortPair mail_server("mail.google.com", 80);
  const ServerNetworkStats* stats =
      http_server_props_manager_->GetServerNetworkStats(mail_server);
  EXPECT_EQ(NULL, stats);
  ServerNetworkStats stats1;
  stats1.srtt = base::TimeDelta::FromMicroseconds(10);
  http_server_props_manager_->SetServerNetworkStats(mail_server, stats1);
  // ExpectScheduleUpdatePrefsOnNetworkThread() should be called only once.
  http_server_props_manager_->SetServerNetworkStats(mail_server, stats1);

  // Run the task.
  base::RunLoop().RunUntilIdle();
  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());

  const ServerNetworkStats* stats2 =
      http_server_props_manager_->GetServerNetworkStats(mail_server);
  EXPECT_EQ(10, stats2->srtt.ToInternalValue());
}

TEST_F(HttpServerPropertiesManagerTest, QuicServerInfo) {
  ExpectPrefsUpdate();
  ExpectScheduleUpdatePrefsOnNetworkThread();

  QuicServerId mail_quic_server_id("mail.google.com", 80);
  EXPECT_EQ(nullptr,
            http_server_props_manager_->GetQuicServerInfo(mail_quic_server_id));
  std::string quic_server_info1("quic_server_info1");
  http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id,
                                                quic_server_info1);
  // ExpectScheduleUpdatePrefsOnNetworkThread() should be called only once.
  http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id,
                                                quic_server_info1);

  // Run the task.
  base::RunLoop().RunUntilIdle();
  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());

  EXPECT_EQ(quic_server_info1, *http_server_props_manager_->GetQuicServerInfo(
                                   mail_quic_server_id));
}

TEST_F(HttpServerPropertiesManagerTest, Clear) {
  ExpectPrefsUpdate();
  ExpectScheduleUpdatePrefsOnNetworkThreadRepeatedly();

  HostPortPair spdy_server_mail("mail.google.com", 443);
  http_server_props_manager_->SetSupportsSpdy(spdy_server_mail, true);
  AlternativeService alternative_service(NPN_HTTP_2, "mail.google.com", 1234);
  http_server_props_manager_->SetAlternativeService(
      spdy_server_mail, alternative_service, 1.0, one_day_from_now_);
  IPAddressNumber actual_address;
  CHECK(ParseIPLiteralToNumber("127.0.0.1", &actual_address));
  http_server_props_manager_->SetSupportsQuic(true, actual_address);
  ServerNetworkStats stats;
  stats.srtt = base::TimeDelta::FromMicroseconds(10);
  http_server_props_manager_->SetServerNetworkStats(spdy_server_mail, stats);

  QuicServerId mail_quic_server_id("mail.google.com", 80);
  std::string quic_server_info1("quic_server_info1");
  http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id,
                                                quic_server_info1);

  const SpdySettingsIds id1 = SETTINGS_UPLOAD_BANDWIDTH;
  const SpdySettingsFlags flags1 = SETTINGS_FLAG_PLEASE_PERSIST;
  const uint32 value1 = 31337;
  http_server_props_manager_->SetSpdySetting(spdy_server_mail, id1, flags1,
                                             value1);

  // Run the task.
  base::RunLoop().RunUntilIdle();

  EXPECT_TRUE(
      http_server_props_manager_->SupportsRequestPriority(spdy_server_mail));
  EXPECT_TRUE(HasAlternativeService(spdy_server_mail));
  IPAddressNumber address;
  EXPECT_TRUE(http_server_props_manager_->GetSupportsQuic(&address));
  EXPECT_EQ(actual_address, address);
  const ServerNetworkStats* stats1 =
      http_server_props_manager_->GetServerNetworkStats(spdy_server_mail);
  EXPECT_EQ(10, stats1->srtt.ToInternalValue());
  EXPECT_EQ(quic_server_info1, *http_server_props_manager_->GetQuicServerInfo(
                                   mail_quic_server_id));

  // Check SPDY settings values.
  const SettingsMap& settings_map1_ret =
      http_server_props_manager_->GetSpdySettings(spdy_server_mail);
  ASSERT_EQ(1U, settings_map1_ret.size());
  SettingsMap::const_iterator it1_ret = settings_map1_ret.find(id1);
  EXPECT_TRUE(it1_ret != settings_map1_ret.end());
  SettingsFlagsAndValue flags_and_value1_ret = it1_ret->second;
  EXPECT_EQ(SETTINGS_FLAG_PERSISTED, flags_and_value1_ret.first);
  EXPECT_EQ(value1, flags_and_value1_ret.second);

  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());

  ExpectPrefsUpdate();

  // Clear http server data, time out if we do not get a completion callback.
  http_server_props_manager_->Clear(base::MessageLoop::QuitWhenIdleClosure());
  base::RunLoop().Run();

  EXPECT_FALSE(
      http_server_props_manager_->SupportsRequestPriority(spdy_server_mail));
  EXPECT_FALSE(HasAlternativeService(spdy_server_mail));
  EXPECT_FALSE(http_server_props_manager_->GetSupportsQuic(&address));
  const ServerNetworkStats* stats2 =
      http_server_props_manager_->GetServerNetworkStats(spdy_server_mail);
  EXPECT_EQ(NULL, stats2);
  EXPECT_EQ(nullptr,
            http_server_props_manager_->GetQuicServerInfo(mail_quic_server_id));

  const SettingsMap& settings_map2_ret =
      http_server_props_manager_->GetSpdySettings(spdy_server_mail);
  EXPECT_EQ(0U, settings_map2_ret.size());

  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
}

// https://crbug.com/444956: Add 200 alternative_service servers followed by
// supports_quic and verify we have read supports_quic from prefs.
TEST_F(HttpServerPropertiesManagerTest, BadSupportsQuic) {
  ExpectCacheUpdate();

  base::DictionaryValue* servers_dict = new base::DictionaryValue;

  for (int i = 0; i < 200; ++i) {
    // Set up alternative_service for www.google.com:i.
    base::DictionaryValue* alternative_service_dict = new base::DictionaryValue;
    alternative_service_dict->SetString("protocol_str", "quic");
    alternative_service_dict->SetInteger("port", i);
    base::ListValue* alternative_service_list = new base::ListValue;
    alternative_service_list->Append(alternative_service_dict);
    base::DictionaryValue* server_pref_dict = new base::DictionaryValue;
    server_pref_dict->SetWithoutPathExpansion("alternative_service",
                                              alternative_service_list);
    servers_dict->SetWithoutPathExpansion(StringPrintf("www.google.com:%d", i),
                                          server_pref_dict);
  }

  // Set the preference for mail.google.com server.
  base::DictionaryValue* server_pref_dict1 = new base::DictionaryValue;

  // Set the server preference for mail.google.com:80.
  servers_dict->SetWithoutPathExpansion("mail.google.com:80",
                                        server_pref_dict1);

  base::DictionaryValue* http_server_properties_dict =
      new base::DictionaryValue;
  HttpServerPropertiesManager::SetVersion(http_server_properties_dict, -1);
  http_server_properties_dict->SetWithoutPathExpansion("servers", servers_dict);

  // Set up SupportsQuic for 127.0.0.1
  base::DictionaryValue* supports_quic = new base::DictionaryValue;
  supports_quic->SetBoolean("used_quic", true);
  supports_quic->SetString("address", "127.0.0.1");
  http_server_properties_dict->SetWithoutPathExpansion("supports_quic",
                                                       supports_quic);

  // Set up the pref.
  pref_service_.SetManagedPref(kTestHttpServerProperties,
                               http_server_properties_dict);

  base::RunLoop().RunUntilIdle();
  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());

  // Verify alternative service.
  for (int i = 0; i < 200; ++i) {
    std::string server = StringPrintf("www.google.com:%d", i);
    AlternativeServiceVector alternative_service_vector =
        http_server_props_manager_->GetAlternativeServices(
            HostPortPair::FromString(server));
    ASSERT_EQ(1u, alternative_service_vector.size());
    EXPECT_EQ(QUIC, alternative_service_vector[0].protocol);
    EXPECT_EQ(i, alternative_service_vector[0].port);
  }

  // Verify SupportsQuic.
  IPAddressNumber address;
  ASSERT_TRUE(http_server_props_manager_->GetSupportsQuic(&address));
  EXPECT_EQ("127.0.0.1", IPAddressToString(address));
}

TEST_F(HttpServerPropertiesManagerTest, UpdateCacheWithPrefs) {
  ExpectScheduleUpdatePrefsOnNetworkThreadRepeatedly();

  const HostPortPair server_www("www.google.com", 80);
  const HostPortPair server_mail("mail.google.com", 80);

  // Set alternate protocol.
  AlternativeServiceInfoVector alternative_service_info_vector;
  AlternativeService www_alternative_service1(NPN_HTTP_2, "", 443);
  base::Time expiration1;
  ASSERT_TRUE(base::Time::FromUTCString("2036-12-01 10:00:00", &expiration1));
  alternative_service_info_vector.push_back(
      AlternativeServiceInfo(www_alternative_service1, 1.0, expiration1));
  AlternativeService www_alternative_service2(NPN_HTTP_2, "www.google.com",
                                              1234);
  base::Time expiration2;
  ASSERT_TRUE(base::Time::FromUTCString("2036-12-31 10:00:00", &expiration2));
  alternative_service_info_vector.push_back(
      AlternativeServiceInfo(www_alternative_service2, 0.7, expiration2));
  http_server_props_manager_->SetAlternativeServices(
      server_www, alternative_service_info_vector);

  AlternativeService mail_alternative_service(NPN_SPDY_3_1, "foo.google.com",
                                              444);
  base::Time expiration3 = base::Time::Max();
  http_server_props_manager_->SetAlternativeService(
      server_mail, mail_alternative_service, 0.2, expiration3);

  // Set ServerNetworkStats.
  ServerNetworkStats stats;
  stats.srtt = base::TimeDelta::FromInternalValue(42);
  http_server_props_manager_->SetServerNetworkStats(server_mail, stats);

  // Set quic_server_info string.
  QuicServerId mail_quic_server_id("mail.google.com", 80);
  std::string quic_server_info1("quic_server_info1");
  http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id,
                                                quic_server_info1);

  // Set SupportsQuic.
  IPAddressNumber actual_address;
  CHECK(ParseIPLiteralToNumber("127.0.0.1", &actual_address));
  http_server_props_manager_->SetSupportsQuic(true, actual_address);

  // Update cache.
  ExpectPrefsUpdate();
  ExpectCacheUpdate();
  http_server_props_manager_->ScheduleUpdateCacheOnPrefThread();
  base::RunLoop().RunUntilIdle();

  // Verify preferences.
  const char expected_json[] =
      "{\"quic_servers\":{\"https://"
      "mail.google.com:80\":{\"server_info\":\"quic_server_info1\"}},"
      "\"servers\":{\"mail.google.com:80\":{\"alternative_service\":[{"
      "\"expiration\":\"9223372036854775807\",\"host\":\"foo.google.com\","
      "\"port\":444,\"probability\":0.2,\"protocol_str\":\"npn-spdy/3.1\"}],"
      "\"network_stats\":{\"srtt\":42}},\"www.google.com:80\":{"
      "\"alternative_service\":[{\"expiration\":\"13756212000000000\","
      "\"port\":443,\"probability\":1.0,\"protocol_str\":\"npn-h2\"},"
      "{\"expiration\":\"13758804000000000\",\"host\":\"www.google.com\","
      "\"port\":1234,\"probability\":0.7,\"protocol_str\":\"npn-h2\"}]}},"
      "\"supports_quic\":{\"address\":\"127.0.0.1\",\"used_quic\":true},"
      "\"version\":3}";

  const base::Value* http_server_properties =
      pref_service_.GetUserPref(kTestHttpServerProperties);
  ASSERT_NE(nullptr, http_server_properties);
  std::string preferences_json;
  EXPECT_TRUE(
      base::JSONWriter::Write(*http_server_properties, &preferences_json));
  EXPECT_EQ(expected_json, preferences_json);
}

TEST_F(HttpServerPropertiesManagerTest, AddToAlternativeServiceMap) {
  scoped_ptr<base::Value> server_value = base::JSONReader::Read(
      "{\"alternative_service\":[{\"port\":443,\"protocol_str\":\"npn-h2\"},"
      "{\"port\":123,\"protocol_str\":\"quic\",\"probability\":0.7,"
      "\"expiration\":\"9223372036854775807\"},{\"host\":\"example.org\","
      "\"port\":1234,\"protocol_str\":\"npn-h2\",\"probability\":0.2,"
      "\"expiration\":\"13758804000000000\"}]}");
  ASSERT_TRUE(server_value);
  base::DictionaryValue* server_dict;
  ASSERT_TRUE(server_value->GetAsDictionary(&server_dict));

  const HostPortPair host_port_pair("example.com", 443);
  AlternativeServiceMap alternative_service_map(/*max_size=*/5);
  EXPECT_TRUE(http_server_props_manager_->AddToAlternativeServiceMap(
      host_port_pair, *server_dict, &alternative_service_map));

  AlternativeServiceMap::iterator it =
      alternative_service_map.Get(host_port_pair);
  ASSERT_NE(alternative_service_map.end(), it);
  AlternativeServiceInfoVector alternative_service_info_vector = it->second;
  ASSERT_EQ(3u, alternative_service_info_vector.size());

  EXPECT_EQ(NPN_HTTP_2,
            alternative_service_info_vector[0].alternative_service.protocol);
  EXPECT_EQ("", alternative_service_info_vector[0].alternative_service.host);
  EXPECT_EQ(443, alternative_service_info_vector[0].alternative_service.port);
  // Probability defaults to 1.0.
  EXPECT_DOUBLE_EQ(1.0, alternative_service_info_vector[0].probability);
  // Expiration defaults to one day from now, testing with tolerance.
  const base::Time now = base::Time::Now();
  const base::Time expiration = alternative_service_info_vector[0].expiration;
  EXPECT_LE(now + base::TimeDelta::FromHours(23), expiration);
  EXPECT_GE(now + base::TimeDelta::FromDays(1), expiration);

  EXPECT_EQ(QUIC,
            alternative_service_info_vector[1].alternative_service.protocol);
  EXPECT_EQ("", alternative_service_info_vector[1].alternative_service.host);
  EXPECT_EQ(123, alternative_service_info_vector[1].alternative_service.port);
  EXPECT_DOUBLE_EQ(0.7, alternative_service_info_vector[1].probability);
  // numeric_limits<int64>::max() represents base::Time::Max().
  EXPECT_EQ(base::Time::Max(), alternative_service_info_vector[1].expiration);

  EXPECT_EQ(NPN_HTTP_2,
            alternative_service_info_vector[2].alternative_service.protocol);
  EXPECT_EQ("example.org",
            alternative_service_info_vector[2].alternative_service.host);
  EXPECT_EQ(1234, alternative_service_info_vector[2].alternative_service.port);
  EXPECT_DOUBLE_EQ(0.2, alternative_service_info_vector[2].probability);
  base::Time expected_expiration;
  ASSERT_TRUE(
      base::Time::FromUTCString("2036-12-31 10:00:00", &expected_expiration));
  EXPECT_EQ(expected_expiration, alternative_service_info_vector[2].expiration);
}

// Early release 46 Dev and Canary builds serialized alternative service
// expiration as double.  Test that they are properly parsed.
// TODO(bnc) Remove this test around 2015-10-01,
// and remove corresponding FRIEND macro from header file.
TEST_F(HttpServerPropertiesManagerTest, AlternativeServiceExpirationDouble) {
  scoped_ptr<base::Value> server_value = base::JSONReader::Read(
      "{\"alternative_service\":[{\"port\":443,\"protocol_str\":\"npn-h2\","
      "\"expiration\":1234567890.0}]}");
  ASSERT_TRUE(server_value);
  base::DictionaryValue* server_dict;
  ASSERT_TRUE(server_value->GetAsDictionary(&server_dict));

  const HostPortPair host_port_pair("example.com", 443);
  AlternativeServiceMap alternative_service_map(/*max_size=*/5);
  EXPECT_TRUE(http_server_props_manager_->AddToAlternativeServiceMap(
      host_port_pair, *server_dict, &alternative_service_map));

  AlternativeServiceMap::iterator it =
      alternative_service_map.Get(host_port_pair);
  ASSERT_NE(alternative_service_map.end(), it);
  AlternativeServiceInfoVector alternative_service_info_vector = it->second;
  ASSERT_EQ(1u, alternative_service_info_vector.size());

  EXPECT_EQ(NPN_HTTP_2,
            alternative_service_info_vector[0].alternative_service.protocol);
  EXPECT_EQ("", alternative_service_info_vector[0].alternative_service.host);
  EXPECT_EQ(443, alternative_service_info_vector[0].alternative_service.port);
  // Probability defaults to 1.0.
  EXPECT_DOUBLE_EQ(1.0, alternative_service_info_vector[0].probability);
  base::Time expected_expiration;
  ASSERT_TRUE(
      base::Time::FromUTCString("2009-02-13 23:31:30", &expected_expiration));
  EXPECT_EQ(expected_expiration, alternative_service_info_vector[0].expiration);
}

TEST_F(HttpServerPropertiesManagerTest, ShutdownWithPendingUpdateCache0) {
  // Post an update task to the UI thread.
  http_server_props_manager_->ScheduleUpdateCacheOnPrefThread();
  // Shutdown comes before the task is executed.
  http_server_props_manager_->ShutdownOnPrefThread();
  http_server_props_manager_.reset();
  // Run the task after shutdown and deletion.
  base::RunLoop().RunUntilIdle();
}

TEST_F(HttpServerPropertiesManagerTest, ShutdownWithPendingUpdateCache1) {
  // Post an update task.
  http_server_props_manager_->ScheduleUpdateCacheOnPrefThread();
  // Shutdown comes before the task is executed.
  http_server_props_manager_->ShutdownOnPrefThread();
  // Run the task after shutdown, but before deletion.
  base::RunLoop().RunUntilIdle();
  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
  http_server_props_manager_.reset();
  base::RunLoop().RunUntilIdle();
}

TEST_F(HttpServerPropertiesManagerTest, ShutdownWithPendingUpdateCache2) {
  http_server_props_manager_->UpdateCacheFromPrefsOnUIConcrete();
  // Shutdown comes before the task is executed.
  http_server_props_manager_->ShutdownOnPrefThread();
  // Run the task after shutdown, but before deletion.
  base::RunLoop().RunUntilIdle();
  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
  http_server_props_manager_.reset();
  base::RunLoop().RunUntilIdle();
}

//
// Tests for shutdown when updating prefs.
//
TEST_F(HttpServerPropertiesManagerTest, ShutdownWithPendingUpdatePrefs0) {
  // Post an update task to the IO thread.
  http_server_props_manager_->ScheduleUpdatePrefsOnNetworkThread();
  // Shutdown comes before the task is executed.
  http_server_props_manager_->ShutdownOnPrefThread();
  http_server_props_manager_.reset();
  // Run the task after shutdown and deletion.
  base::RunLoop().RunUntilIdle();
}

TEST_F(HttpServerPropertiesManagerTest, ShutdownWithPendingUpdatePrefs1) {
  ExpectPrefsUpdate();
  // Post an update task.
  http_server_props_manager_->ScheduleUpdatePrefsOnNetworkThread();
  // Shutdown comes before the task is executed.
  http_server_props_manager_->ShutdownOnPrefThread();
  // Run the task after shutdown, but before deletion.
  base::RunLoop().RunUntilIdle();
  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
  http_server_props_manager_.reset();
  base::RunLoop().RunUntilIdle();
}

TEST_F(HttpServerPropertiesManagerTest, ShutdownWithPendingUpdatePrefs2) {
  // This posts a task to the UI thread.
  http_server_props_manager_->UpdatePrefsFromCacheOnNetworkThreadConcrete(
      base::Closure());
  // Shutdown comes before the task is executed.
  http_server_props_manager_->ShutdownOnPrefThread();
  // Run the task after shutdown, but before deletion.
  base::RunLoop().RunUntilIdle();
  Mock::VerifyAndClearExpectations(http_server_props_manager_.get());
  http_server_props_manager_.reset();
  base::RunLoop().RunUntilIdle();
}

}  // namespace net


text:
package org.codegist.crest.annotate;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 *
Binds a deserializer for the annotated method response type, overriding the default deserialization process.

 *
When set at interface level, it will applies to all methods where it is not already specified

 * @author laurent.gilles@codegist.org
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface Deserializer {

    /**
     * Defines the deserializer to use to deserialize the annotated method response type
     */
    Class<? extends org.codegist.crest.serializer.Deserializer> value();

}


text:
#ifndef VISUAL_CHANNELS_H_
#define VISUAL_CHANNELS_H_

#include <string>
#include <map>
#include <vector>

namespace cocos3d
{

class C3DModel;
class C3DParticleRender;

/**
 * This is the base class for the primitives drawn by the visual channels.
 */
class ChannelDrawItem
{
public:
	/**
	 * Constructor & Destructor
	 */
	ChannelDrawItem();
	virtual ~ChannelDrawItem();

	/**
	 * draw this item
	 */
	void draw();

	/**
	 * init & fini item
	 */
	void init( float distance, C3DModel* model );
	void fini();

	/**
	 * get item distance
	 */
	float distance() const { return _distance; }

private:

	void drawSorted();
	void drawUnsorted();

	// properties
	bool	_sortInternal;	// always true currently
	float	_distance;//distance to camera
	C3DModel*  _model;      // model to draw

};

/**
 * This class is the base class and the manager for the visual channels. A
 * channel is essentially a bucket of objects with similar rendering rules.
 * The channels are traversed fixed global order, and within each channel items
 * are drawn, possibly in a sorted order.
 */
class C3DRenderChannel
{
public:
	/**
	 * Constructor & Destructor
	 */
	C3DRenderChannel(){};
	virtual ~C3DRenderChannel(){};

	/**
	 * add draw item
	 */
	virtual void addItem( float zDistance, C3DModel* model ){};
	/**
	 * clear
	 */
	virtual void clear(){};
	/**
	 * draw routine
	 */
	virtual void draw(bool clear=false){};

	/**
	 * get channel name
	 */
    virtual const char* getName() { return ""; }

};

/**
 * This class implements the sorted channel, sorted objects are rendered after
 * the main scene and the shimmer.
 */
class SortedChannel : public C3DRenderChannel
{
public:
    enum SortType
    {
        Greater,
        Less,
    };
	/**
	 * Constructor & Destructor
	 */
	SortedChannel(SortType type = Greater);
	virtual ~SortedChannel();

	/**
	 * add draw item
	 */
	void addItem( float zDistance, C3DModel* model );
	/**
	 * clear items
	 */
	void clear();
	/**
	 * draw
	 */
	void draw(bool clear=false);
	/**
	 * channe name
	 */
    virtual const char* getName() { return "sorted"; }

private:
	std::vector< ChannelDrawItem* >		_drawItems;

    SortType _type;

    bool (*compare)( const ChannelDrawItem* a, const ChannelDrawItem* b );
};

class ParticleRenderChannel : public C3DRenderChannel
{
public:
    ParticleRenderChannel();
    virtual ~ParticleRenderChannel()
    {

    }

    /**
     * item drawn by particle channel
     */
    struct ParticleDrawItem
    {
        C3DParticleRender* _render;
        float _distance;
    };
    /**
	 * add draw item
	 */
	void addItem( float zDistance, C3DParticleRender* render );
	/**
	 * clear items
	 */
	void clear();
	/**
	 * draw
	 */
	void draw(bool clear=false);
	/**
	 * channe name
	 */
    virtual const char* getName() { return "particlechannel"; }
private:
	std::vector< ParticleDrawItem>		_drawItems;
    bool                                _sorted;

};

/**
 * This class manage all the render channel.
 */
class RenderChannelManager
{
public:
	/**
	 * Constructor & Destructor
	 */
	RenderChannelManager();
	virtual ~RenderChannelManager();

	/**
	 * get channel by name
	 */
	C3DRenderChannel* getRenderChannel( const std::string& name );

	/**
	 * init & fini channels
	 */
	void initChannels();
	void finiChannels();
	/**
	 * clear channel items
	 */
	void clearChannelItems();

	/**
	 * draw routine
	 */
	void draw();
private:
	/**
	 * add & remove channel
	 */
	void add( const std::string& name, C3DRenderChannel* pChannel );
	void remove( const std::string& name );

private:
	std::map< std::string, C3DRenderChannel* > _RenderChannels;

};

}
#endif // VISUAL_CHANNELS_H


text:
#import <Foundation/Foundation.h>

#ifndef _ZXINGOBJC_

#define _ZXINGOBJC_

#import "ZXingObjCCore.h"

#if defined(ZXINGOBJC_AZTEC) || !defined(ZXINGOBJC_USE_SUBSPECS)
#import "ZXingObjCAztec.h"
#endif
#if defined(ZXINGOBJC_DATAMATRIX) || !defined(ZXINGOBJC_USE_SUBSPECS)
#import "ZXingObjCDataMatrix.h"
#endif
#if defined(ZXINGOBJC_MAXICODE) || !defined(ZXINGOBJC_USE_SUBSPECS)
#import "ZXingObjCMaxiCode.h"
#endif
#if defined(ZXINGOBJC_ONED) || !defined(ZXINGOBJC_USE_SUBSPECS)
#import "ZXingObjCOneD.h"
#endif
#if defined(ZXINGOBJC_PDF417) || !defined(ZXINGOBJC_USE_SUBSPECS)
#import "ZXingObjCPDF417.h"
#endif
#if defined(ZXINGOBJC_QRCODE) || !defined(ZXINGOBJC_USE_SUBSPECS)
#import "ZXingObjCQRCode.h"
#endif

#import "ZXMultiFormatReader.h"
#import "ZXMultiFormatWriter.h"

#endif


text:
#ifndef _MODEL_H_
#define _MODEL_H_

#include <map>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include "mesh.h"
#include "texture.h"

/*
* ´ú±íÒ»¸öÄ£ÐÍ Ä£ÐÍ¿ÉÒÔ°üº¬Ò»¸ö»ò¶à¸öMesh
*/
class Model
{
public:
	void draw(const Shader& shader) const
	{
		for (std::vector<Mesh>::const_iterator it = this->meshes.begin(); this->meshes.end() != it; ++it)
		{
			it->draw(shader);
		}
	}
	bool loadModel(const std::string& filePath)
	{
		Assimp::Importer importer;
		if (filePath.empty())
		{
			std::cerr << "Error:Model::loadModel, empty model file path." << std::endl;
			return false;
		}
		const aiScene* sceneObjPtr = importer.ReadFile(filePath,
			aiProcess_Triangulate
			| aiProcess_FlipUVs
			| aiProcess_GenSmoothNormals
			| aiProcess_CalcTangentSpace);
		if (!sceneObjPtr
			|| sceneObjPtr->mFlags == AI_SCENE_FLAGS_INCOMPLETE
			|| !sceneObjPtr->mRootNode)
		{
			std::cerr << "Error:Model::loadModel, description: "
				<< importer.GetErrorString() << std::endl;
			return false;
		}
		this->modelFileDir = filePath.substr(0, filePath.find_last_of('/'));
		if (!this->processNode(sceneObjPtr->mRootNode, sceneObjPtr))
		{
			std::cerr << "Error:Model::loadModel, process node failed."<< std::endl;
			return false;
		}
		return true;
	}
	~Model()
	{
		for (std::vector<Mesh>::const_iterator it = this->meshes.begin(); this->meshes.end() != it; ++it)
		{
			it->final();
		}
	}
	const std::vector<Mesh>& getMeshes() const { return this->meshes; }
private:
	/*
	* µÝ¹é´¦ÀíÄ£Ð͵Ľáµã
	*/
	bool processNode(const aiNode* node, const aiScene* sceneObjPtr)
	{
		if (!node || !sceneObjPtr)
		{
			return false;
		}
		// ÏÈ´¦Àí×ÔÉí½áµã
		for (size_t i = 0; i < node->mNumMeshes; ++i)
		{
			// ×¢ÒânodeÖеÄmeshÊǶÔsceneObjectÖÐmeshµÄË÷Òý
			const aiMesh* meshPtr = sceneObjPtr->mMeshes[node->mMeshes[i]];
			if (meshPtr)
			{
				Mesh meshObj;
				if (this->processMesh(meshPtr, sceneObjPtr, meshObj))
				{
					this->meshes.push_back(meshObj);
				}
			}
		}
		// ´¦Àíº¢×Ó½áµã
		for (size_t i = 0; i < node->mNumChildren; ++i)
		{
			this->processNode(node->mChildren[i], sceneObjPtr);
		}
		return true;
	}
	bool processMesh(const aiMesh* meshPtr, const aiScene* sceneObjPtr, Mesh& meshObj)
	{
		if (!meshPtr || !sceneObjPtr)
		{
			return false;
		}
		std::vector<Vertex> vertData;
		std::vector<Texture> textures;
		std::vector<GLuint> indices;
		// ´ÓMeshµÃµ½¶¥µãÊý¾Ý¡¢·¨ÏòÁ¿¡¢ÎÆÀíÊý¾Ý
		for (size_t i = 0; i < meshPtr->mNumVertices; ++i)
		{
			Vertex vertex;
			// »ñÈ¡¶¥µãλÖÃ
			if (meshPtr->HasPositions())
			{
				vertex.position.x = meshPtr->mVertices[i].x;
				vertex.position.y = meshPtr->mVertices[i].y;
				vertex.position.z = meshPtr->mVertices[i].z;
			}
			// »ñÈ¡ÎÆÀíÊý¾Ý Ä¿Ç°Ö»´¦Àí0ºÅÎÆÀí
			if (meshPtr->HasTextureCoords(0))
			{
				vertex.texCoords.x = meshPtr->mTextureCoords[0][i].x;
				vertex.texCoords.y = meshPtr->mTextureCoords[0][i].y;
			}
			else
			{
				vertex.texCoords = glm::vec2(0.0f, 0.0f);
			}
			// »ñÈ¡·¨ÏòÁ¿Êý¾Ý
			if (meshPtr->HasNormals())
			{
				vertex.normal.x = meshPtr->mNormals[i].x;
				vertex.normal.y = meshPtr->mNormals[i].y;
				vertex.normal.z = meshPtr->mNormals[i].z;
			}
			// »ñÈ¡tangentÏòÁ¿
			if (meshPtr->HasTangentsAndBitangents())
			{
				glm::vec3 tangent;
				tangent.x = meshPtr->mTangents[i].x;
				tangent.y = meshPtr->mTangents[i].y;
				tangent.z = meshPtr->mTangents[i].z;
				vertex.tangent = tangent;
			}

			vertData.push_back(vertex);
		}
		// »ñÈ¡Ë÷ÒýÊý¾Ý
		for (size_t i = 0; i < meshPtr->mNumFaces; ++i)
		{
			aiFace face = meshPtr->mFaces[i];
			if (face.mNumIndices != 3)
			{
				std::cerr << "Error:Model::processMesh, mesh not transformed to triangle mesh." << std::endl;
				return false;
			}
			for (size_t j = 0; j < face.mNumIndices; ++j)
			{
				indices.push_back(face.mIndices[j]);
			}
		}
		// »ñÈ¡ÎÆÀíÊý¾Ý
		if (meshPtr->mMaterialIndex >= 0)
		{
			const aiMaterial* materialPtr = sceneObjPtr->mMaterials[meshPtr->mMaterialIndex];
			// »ñÈ¡diffuseÀàÐÍ
			std::vector<Texture> diffuseTexture;
			this->processMaterial(materialPtr, sceneObjPtr, aiTextureType_DIFFUSE, diffuseTexture);
			textures.insert(textures.end(), diffuseTexture.begin(), diffuseTexture.end());
			// »ñÈ¡specularÀàÐÍ
			std::vector<Texture> specularTexture;
			this->processMaterial(materialPtr, sceneObjPtr, aiTextureType_SPECULAR, specularTexture);
			textures.insert(textures.end(), specularTexture.begin(), specularTexture.end());
			// »ñÈ¡normal mappingÊý¾Ý
			std::vector<Texture> normalTexture;
			this->processMaterial(materialPtr, sceneObjPtr, aiTextureType_HEIGHT, normalTexture);
			textures.insert(textures.end(), normalTexture.begin(), normalTexture.end());
		}
		meshObj.setData(vertData, textures, indices);
		return true;
	}
	/*
	* »ñÈ¡Ò»¸ö²ÄÖÊÖеÄÎÆÀí
	*/
	bool processMaterial(const aiMaterial* matPtr, const aiScene* sceneObjPtr,
		const aiTextureType textureType, std::vector<Texture>& textures)
	{
		textures.clear();

		if (!matPtr
			|| !sceneObjPtr )
		{
			return false;
		}
		if (matPtr->GetTextureCount(textureType) <= 0)
		{
			return true;
		}
		for (size_t i = 0; i < matPtr->GetTextureCount(textureType); ++i)
		{
			Texture text;
			aiString textPath;
			aiReturn retStatus = matPtr->GetTexture(textureType, i, &textPath);
			if (retStatus != aiReturn_SUCCESS
				|| textPath.length == 0)
			{
				std::cerr << "Warning, load texture type=" << textureType
					<< "index= " << i << " failed with return value= "
					<< retStatus << std::endl;
				continue;
			}
			std::string absolutePath = this->modelFileDir + "/" + textPath.C_Str();
			LoadedTextMapType::const_iterator it = this->loadedTextureMap.find(absolutePath);
			if (it == this->loadedTextureMap.end()) // ¼ì²éÊÇ·ñÒѾ¼ÓÔعýÁË
			{
				GLuint textId = TextureHelper::load2DTexture(absolutePath.c_str());
				text.id = textId;
				text.path = absolutePath;
				text.type = textureType;
				textures.push_back(text);
				loadedTextureMap[absolutePath] = text;
			}
			else
			{
				textures.push_back(it->second);
			}
		}
		return true;
	}
private:
	std::vector<Mesh> meshes; // ±£´æMesh
	std::string modelFileDir; // ±£´æÄ£ÐÍÎļþµÄÎļþ¼Ð·¾¶
	typedef std::map<std::string, Texture> LoadedTextMapType; // key = texture file path
	LoadedTextMapType loadedTextureMap; // ±£´æÒѾ¼ÓÔصÄÎÆÀí
};

#endif


text:
package org.robolectric.shadows;

import android.content.res.AssetManager;
import android.graphics.Typeface;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.annotation.HiddenApi;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.annotation.Resetter;
import org.robolectric.manifest.AndroidManifest;
import org.robolectric.util.ReflectionHelpers;
import org.robolectric.util.ReflectionHelpers.ClassParameter;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static org.robolectric.RuntimeEnvironment.getApiLevel;
import static org.robolectric.Shadows.shadowOf;

/**
 * Shadow for {@link android.graphics.Typeface}.
 */
@Implements(value = Typeface.class, looseSignatures = true)
public class ShadowTypeface {
  private static Map<Long, FontDesc> FONTS = new HashMap<>();
  private static long nextFontId = 1;
  private FontDesc description;
  @RealObject private Typeface realTypeface;

  @HiddenApi
  public void __constructor__(int fontId) {
    description = findById((long) fontId);
  }

  @HiddenApi
  public void __constructor__(long fontId) {
    description = findById(fontId);
  }

  @Implementation
  public static Typeface create(String familyName, int style) {
    return createUnderlyingTypeface(familyName, style);
  }

  @Implementation
  public static Typeface create(Typeface family, int style) {
    if (family == null) {
      return createUnderlyingTypeface(null, style);
    } else {
      return createUnderlyingTypeface(shadowOf(family).getFontDescription().getFamilyName(), style);
    }
  }

  @Implementation
  public static Typeface createFromAsset(AssetManager mgr, String path) {
    AndroidManifest appManifest = Shadows.shadowOf(RuntimeEnvironment.application).getAppManifest();
    ArrayList<String> paths = new ArrayList<>();
    paths.add(getAssetsPath(appManifest, path));

    List<AndroidManifest> libraryManifests = appManifest.getLibraryManifests();
    for (AndroidManifest libraryManifest : libraryManifests) {
      paths.add(getAssetsPath(libraryManifest, path));
    }

    for (String assetPath : paths) {
      if (new File(assetPath).exists()) {
        return createUnderlyingTypeface(path, Typeface.NORMAL);
      }
    }

    throw new RuntimeException("Font not found at " + paths);
  }

  @Implementation
  public static Typeface createFromFile(File path) {
    String familyName = path.toPath().getFileName().toString();
    return createUnderlyingTypeface(familyName, Typeface.NORMAL);
  }

  @Implementation
  public static Typeface createFromFile(String path) {
    return createFromFile(new File(path));
  }

  @Implementation
  public int getStyle() {
    return description.getStyle();
  }

  @HiddenApi
  @Implementation(minSdk = LOLLIPOP)
  public static Typeface createFromFamilies(Object /*FontFamily[]*/ families) {
    return null;
  }

  @HiddenApi
  @Implementation(minSdk = LOLLIPOP)
  public static Typeface createFromFamiliesWithDefault(Object /*FontFamily[]*/ families) {
    return null;
  }

  @Resetter
  synchronized public static void reset() {
    FONTS.clear();
  }

  private static Typeface createUnderlyingTypeface(String familyName, int style) {
    long thisFontId = nextFontId++;
    FONTS.put(thisFontId, new FontDesc(familyName, style));
    if (getApiLevel() >= LOLLIPOP) {
      return ReflectionHelpers.callConstructor(Typeface.class, ClassParameter.from(long.class, thisFontId));
    } else {
      return ReflectionHelpers.callConstructor(Typeface.class, ClassParameter.from(int.class, (int) thisFontId));
    }
  }

  private static String getAssetsPath(AndroidManifest appManifest, String fontName) {
    return appManifest.getAssetsDirectory().join(fontName).toString();
  }

  private synchronized static FontDesc findById(long fontId) {
    if (FONTS.containsKey(fontId)) {
      return FONTS.get(fontId);
    }
    throw new RuntimeException("Unknown font id: " + fontId);
  }

  /**
   * Non-Android accessor. Return the font description.
   *
   * @return Font description.
   */
  public FontDesc getFontDescription() {
    return description;
  }

  public static class FontDesc {
    public final String familyName;
    public final int style;

    public FontDesc(String familyName, int style) {
      this.familyName = familyName;
      this.style = style;
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;

      FontDesc fontDesc = (FontDesc) o;

      if (style != fontDesc.style) return false;
      if (familyName != null ? !familyName.equals(fontDesc.familyName) : fontDesc.familyName != null)
        return false;

      return true;
    }

    @Override
    public int hashCode() {
      int result = familyName != null ? familyName.hashCode() : 0;
      result = 31 * result + style;
      return result;
    }

    public String getFamilyName() {
      return familyName;
    }

    public int getStyle() {
      return style;
    }
  }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template FormatterConcept</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../string_algo/reference.html#header.boost.algorithm.string.concept_hpp" title="Header <boost/algorithm/string/concept.hpp>">
<link rel="prev" href="FinderConcept.html" title="Struct template FinderConcept">
<link rel="next" href="token_compress_mode_type.html" title="Type token_compress_mode_type">

Home
Libraries
People
FAQ
More

Struct template FormatterConcept

boost::algorithm::FormatterConcept — Formatter concept.

Synopsis

// In header: <boost/algorithm/string/concept.hpp>

template<typename FormatterT, typename FinderT, typename IteratorT>
struct FormatterConcept {

  // public member functions
  void constraints();
};

Description

Defines the Formatter concept. Formatter is a functor, which takes a result from a finder operation and transforms it in a specific way.

Result must be a container supported by container_traits, or a reference to it.

FormatterConcept public member functions

void constraints();

Copyright © 2002-2004 Pavol Droba
Use, modification and distribution is subject to the Boost
                Software License, Version 1.0. (See accompanying file
                LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package com.talis.hbase.rdf.layout.simple;

import com.talis.hbase.rdf.store.TableDesc;

public class TableDescSimpleCommon extends TableDesc
{
	protected static final String COL_FAMILY_NAME_STR 		= "triples";

	protected static final String CELL_VALUE_SEPARATOR 		= "&&";
	protected static final String TRIPLE_SEPARATOR 			= "~~";

	private final String _COL_FAMILY_NAME_STR ;

	public TableDescSimpleCommon( String tName ) { this( tName, COL_FAMILY_NAME_STR ) ; }

	public TableDescSimpleCommon( String tableName, String colFamily )
	{
		super( tableName, colFamily ) ;
		_COL_FAMILY_NAME_STR = colFamily ;
	}

	public String getColFamilyName() { return _COL_FAMILY_NAME_STR ; }
}


text:
<?php

namespace Black\DDD\DDDinPHP\Application\DTO;

use Black\DDD\DDDinPHP\Domain\Model\Entity;

/**
 * Interface Assembler
 *
 * A DTO assembler is a special service to transform/reverse transform an Entity to a Data Transfer Object.
 * Use this (optional) and not pure-DDD service if you want to centralize the transformation of your Data Transfer
 * Object.
 */
interface Assembler
{
    /**
     * Transform an Entity to a Data Transfer Object
     *
     * @param  Entity $entity
     * @return mixed
     */
    public function transform(Entity $entity);

    /**
     * Transform a Data Transfer Object to an Entity
     *
     * @param  DTO   $dto
     * @return mixed
     */
    public function reverseTransform(DTO $dto);
}


text:
import { deepStrictEqual as equal } from "assert";
import { LegendBuilder } from "../lib/output/plugins/LegendPlugin";

describe("LegendBuilder", function () {
    it("returns empty items when no css classes are registered", function () {
        const builder = new LegendBuilder();
        const results = builder
            .build()
            .map((items) => items.map((item) => item.name));

        equal(results, []);
    });

    it("returns single item list when common css classes are registered", function () {
        const builder = new LegendBuilder();
        builder.registerCssClasses(["tsd-kind-namespace"]);
        const results = builder
            .build()
            .map((items) => items.map((item) => item.name));

        equal(results, [["Namespace"]]);
    });

    it("returns single item list with multiple items when common css classes are registered", function () {
        const builder = new LegendBuilder();
        builder.registerCssClasses(["tsd-kind-namespace"]);
        builder.registerCssClasses(["tsd-kind-function"]);
        const results = builder
            .build()
            .map((items) => items.map((item) => item.name));

        equal(results, [["Namespace", "Function"]]);
    });

    it("returns single item list with multiple items when multiple css classes are registered", function () {
        const builder = new LegendBuilder();
        builder.registerCssClasses(["tsd-kind-namespace"]);
        builder.registerCssClasses(["tsd-kind-function"]);
        builder.registerCssClasses([
            "tsd-kind-function",
            "tsd-has-type-parameter",
        ]);
        const results = builder
            .build()
            .map((items) => items.map((item) => item.name));

        equal(results, [
            ["Namespace", "Function", "Function with type parameter"],
        ]);
    });

    it("returns multiple item list when common css classes are registered from different groups", function () {
        const builder = new LegendBuilder();
        builder.registerCssClasses(["tsd-kind-namespace"]);
        builder.registerCssClasses([
            "tsd-kind-accessor",
            "tsd-parent-kind-class",
            "tsd-is-inherited",
        ]);
        builder.registerCssClasses([
            "tsd-kind-property",
            "tsd-parent-kind-class",
            "tsd-is-private",
        ]);
        builder.registerCssClasses([
            "tsd-kind-accessor",
            "tsd-parent-kind-class",
            "tsd-is-private",
        ]);
        const results = builder
            .build()
            .map((items) => items.map((item) => item.name));

        equal(results, [
            ["Namespace"],
            ["Inherited accessor"],
            ["Private property", "Private accessor"],
        ]);
    });

    it("returns single item when includes ignored classes", function () {
        const builder = new LegendBuilder();
        builder.registerCssClasses([
            "tsd-kind-class",
            "tsd-parent-kind-module",
        ]);
        const results = builder
            .build()
            .map((items) => items.map((item) => item.name));

        equal(results, [["Class"]]);
    });
});


text:
<!doctype html>

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<meta name="viewport" content="width=device-width">
	<title>Videri Concept Project Kickstart with Bootstrap</title>
	<link rel="stylesheet" type="text/css" href="public/css/style.css">
	<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

Brandimage

Navitem

Navitem

Navitem

Navitem

		Heroimage

Website Kickstart

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga, ea error consequatur explicabo consectetur veniam voluptates ad aperiam optio neque. Eius quae quia ab doloribus quos ullam odit maiores repudiandae.
				At, velit aut animi saepe praesentium rerum temporibus veritatis quo voluptatum nostrum nulla fugiat quia? Voluptates, repellat, illum incidunt aliquid aut obcaecati architecto! Corporis, enim reiciendis repellendus officiis dolorum molestias.
				Beatae, nulla magnam id illo iusto. Unde, vero commodi dolore ipsum natus velit minus deleniti rerum itaque error! Repellat, illo quae eius harum maxime esse consequuntur cum mollitia ipsam distinctio!
				Labore, ipsum, et minus eveniet nesciunt laudantium sed blanditiis dignissimos architecto totam officiis provident consequatur ipsam! Impedit, autem veniam inventore enim fugit ea fuga facilis eaque maiores maxime hic id.
				Nobis, numquam aspernatur tenetur eligendi voluptas nesciunt tempora sit assumenda totam soluta. Consectetur, doloribus optio perferendis facere reiciendis eos explicabo sequi illum quibusdam quas error delectus rem minus accusantium autem.

			Copyright © 2014 - All Rights reserved


text:
#import <Foundation/Foundation.h>
#import "QSFormItem.h"

@interface QSSectionHeaderFormItem : QSFormItem {
	NSString * _strText;
}

@property (nonatomic, retain, getter=text, setter=setText:) NSString * _strText;

- (QSSectionHeaderFormItem *)initWithKey:(NSString *)strKey Text:(NSString *)strText;
@end


text:
using System;
class Rectangles
{
    static void Main()
    {
        // * Write an expression that calculates rectangle's perimeter and area by given width and height.

        Console.Write("Width of rectangle: ");
        float width = float.Parse(Console.ReadLine());
        Console.Write("Height of rectangle: ");
        float height = float.Parse(Console.ReadLine());

        float p = width * 2 + height * 2;
        float s = width * height;

        Console.WriteLine("Perimeter = " + p);
        Console.WriteLine("Area = " + s);
    }
}


text:
<resources>
    <string name="app_name">PracticalTest02</string>
    <string name="server">SERVER</string>
    <string name="server_port">Port</string>
    <string name="connect">Connect</string>
    <string name="client">CLIENT</string>
    <string name="client_address">Address</string>
    <string name="client_port">Port</string>
    <string name="get_time">Get Time</string>
</resources>


text:
'use strict';
const meow = require('meow');
const hasha = require('hasha');

const cli = meow(`
	Usage
	  $ hasha <text>
	  $ cat <file> | hasha

	Options
	  --algorithm, -a  Cipher algorithm: md5,sha1,sha256,sha512   [Default: sha512]
	  --encoding, -e   Output encoding: hex,base64,buffer,binary  [Default: hex]

	Example
	  $ hasha unicorn --algorithm=md5
	  1abcb33beeb811dca15f0ac3e47b88d9
`, {
	flags: {
		algorithm: {
			type: 'string',
			alias: 'a'
		},
		encoding: {
			type: 'string',
			alias: 'e'
		}
	}
});

const input = cli.input[0];

if (!input && process.stdin.isTTY) {
	console.log('Specify something to hash');
	process.exit(1);
}

if (input) {
	console.log(hasha(input, cli.flags));
} else {
	process.stdin.pipe(hasha.stream(cli.flags)).pipe(process.stdout);
}