text:
#pragma once
#include <aws/dynamodb/DynamoDB_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/dynamodb/model/ImportStatus.h>
#include <aws/dynamodb/model/S3BucketSource.h>
#include <aws/dynamodb/model/InputFormat.h>
#include <aws/core/utils/DateTime.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace DynamoDB
{
namespace Model
{

  /**
   *
 Summary information about the source file for the import.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_DYNAMODB_API ImportSummary
  {
  public:
    ImportSummary();
    ImportSummary(Aws::Utils::Json::JsonView jsonValue);
    ImportSummary& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
 The Amazon Resource Number (ARN) corresponding to the import request.

     */
    inline const Aws::String& GetImportArn() const{ return m_importArn; }

    /**
     *
 The Amazon Resource Number (ARN) corresponding to the import request.

     */
    inline bool ImportArnHasBeenSet() const { return m_importArnHasBeenSet; }

    /**
     *
 The Amazon Resource Number (ARN) corresponding to the import request.

     */
    inline void SetImportArn(const Aws::String& value) { m_importArnHasBeenSet = true; m_importArn = value; }

    /**
     *
 The Amazon Resource Number (ARN) corresponding to the import request.

     */
    inline void SetImportArn(Aws::String&& value) { m_importArnHasBeenSet = true; m_importArn = std::move(value); }

    /**
     *
 The Amazon Resource Number (ARN) corresponding to the import request.

     */
    inline void SetImportArn(const char* value) { m_importArnHasBeenSet = true; m_importArn.assign(value); }

    /**
     *
 The Amazon Resource Number (ARN) corresponding to the import request.

     */
    inline ImportSummary& WithImportArn(const Aws::String& value) { SetImportArn(value); return *this;}

    /**
     *
 The Amazon Resource Number (ARN) corresponding to the import request.

     */
    inline ImportSummary& WithImportArn(Aws::String&& value) { SetImportArn(std::move(value)); return *this;}

    /**
     *
 The Amazon Resource Number (ARN) corresponding to the import request.

     */
    inline ImportSummary& WithImportArn(const char* value) { SetImportArn(value); return *this;}

    /**
     *
 The status of the import operation.

     */
    inline const ImportStatus& GetImportStatus() const{ return m_importStatus; }

    /**
     *
 The status of the import operation.

     */
    inline bool ImportStatusHasBeenSet() const { return m_importStatusHasBeenSet; }

    /**
     *
 The status of the import operation.

     */
    inline void SetImportStatus(const ImportStatus& value) { m_importStatusHasBeenSet = true; m_importStatus = value; }

    /**
     *
 The status of the import operation.

     */
    inline void SetImportStatus(ImportStatus&& value) { m_importStatusHasBeenSet = true; m_importStatus = std::move(value); }

    /**
     *
 The status of the import operation.

     */
    inline ImportSummary& WithImportStatus(const ImportStatus& value) { SetImportStatus(value); return *this;}

    /**
     *
 The status of the import operation.

     */
    inline ImportSummary& WithImportStatus(ImportStatus&& value) { SetImportStatus(std::move(value)); return *this;}

    /**
     *
 The Amazon Resource Number (ARN) of the table being imported into.

     */
    inline const Aws::String& GetTableArn() const{ return m_tableArn; }

    /**
     *
 The Amazon Resource Number (ARN) of the table being imported into.

     */
    inline bool TableArnHasBeenSet() const { return m_tableArnHasBeenSet; }

    /**
     *
 The Amazon Resource Number (ARN) of the table being imported into.

     */
    inline void SetTableArn(const Aws::String& value) { m_tableArnHasBeenSet = true; m_tableArn = value; }

    /**
     *
 The Amazon Resource Number (ARN) of the table being imported into.

     */
    inline void SetTableArn(Aws::String&& value) { m_tableArnHasBeenSet = true; m_tableArn = std::move(value); }

    /**
     *
 The Amazon Resource Number (ARN) of the table being imported into.

     */
    inline void SetTableArn(const char* value) { m_tableArnHasBeenSet = true; m_tableArn.assign(value); }

    /**
     *
 The Amazon Resource Number (ARN) of the table being imported into.

     */
    inline ImportSummary& WithTableArn(const Aws::String& value) { SetTableArn(value); return *this;}

    /**
     *
 The Amazon Resource Number (ARN) of the table being imported into.

     */
    inline ImportSummary& WithTableArn(Aws::String&& value) { SetTableArn(std::move(value)); return *this;}

    /**
     *
 The Amazon Resource Number (ARN) of the table being imported into.

     */
    inline ImportSummary& WithTableArn(const char* value) { SetTableArn(value); return *this;}

    /**
     *
 The path and S3 bucket of the source file that is being imported. This
     * includes the S3Bucket (required), S3KeyPrefix (optional) and S3BucketOwner
     * (optional if the bucket is owned by the requester).

     */
    inline const S3BucketSource& GetS3BucketSource() const{ return m_s3BucketSource; }

    /**
     *
 The path and S3 bucket of the source file that is being imported. This
     * includes the S3Bucket (required), S3KeyPrefix (optional) and S3BucketOwner
     * (optional if the bucket is owned by the requester).

     */
    inline bool S3BucketSourceHasBeenSet() const { return m_s3BucketSourceHasBeenSet; }

    /**
     *
 The path and S3 bucket of the source file that is being imported. This
     * includes the S3Bucket (required), S3KeyPrefix (optional) and S3BucketOwner
     * (optional if the bucket is owned by the requester).

     */
    inline void SetS3BucketSource(const S3BucketSource& value) { m_s3BucketSourceHasBeenSet = true; m_s3BucketSource = value; }

    /**
     *
 The path and S3 bucket of the source file that is being imported. This
     * includes the S3Bucket (required), S3KeyPrefix (optional) and S3BucketOwner
     * (optional if the bucket is owned by the requester).

     */
    inline void SetS3BucketSource(S3BucketSource&& value) { m_s3BucketSourceHasBeenSet = true; m_s3BucketSource = std::move(value); }

    /**
     *
 The path and S3 bucket of the source file that is being imported. This
     * includes the S3Bucket (required), S3KeyPrefix (optional) and S3BucketOwner
     * (optional if the bucket is owned by the requester).

     */
    inline ImportSummary& WithS3BucketSource(const S3BucketSource& value) { SetS3BucketSource(value); return *this;}

    /**
     *
 The path and S3 bucket of the source file that is being imported. This
     * includes the S3Bucket (required), S3KeyPrefix (optional) and S3BucketOwner
     * (optional if the bucket is owned by the requester).

     */
    inline ImportSummary& WithS3BucketSource(S3BucketSource&& value) { SetS3BucketSource(std::move(value)); return *this;}

    /**
     *
 The Amazon Resource Number (ARN) of the Cloudwatch Log Group associated with
     * this import task.

     */
    inline const Aws::String& GetCloudWatchLogGroupArn() const{ return m_cloudWatchLogGroupArn; }

    /**
     *
 The Amazon Resource Number (ARN) of the Cloudwatch Log Group associated with
     * this import task.

     */
    inline bool CloudWatchLogGroupArnHasBeenSet() const { return m_cloudWatchLogGroupArnHasBeenSet; }

    /**
     *
 The Amazon Resource Number (ARN) of the Cloudwatch Log Group associated with
     * this import task.

     */
    inline void SetCloudWatchLogGroupArn(const Aws::String& value) { m_cloudWatchLogGroupArnHasBeenSet = true; m_cloudWatchLogGroupArn = value; }

    /**
     *
 The Amazon Resource Number (ARN) of the Cloudwatch Log Group associated with
     * this import task.

     */
    inline void SetCloudWatchLogGroupArn(Aws::String&& value) { m_cloudWatchLogGroupArnHasBeenSet = true; m_cloudWatchLogGroupArn = std::move(value); }

    /**
     *
 The Amazon Resource Number (ARN) of the Cloudwatch Log Group associated with
     * this import task.

     */
    inline void SetCloudWatchLogGroupArn(const char* value) { m_cloudWatchLogGroupArnHasBeenSet = true; m_cloudWatchLogGroupArn.assign(value); }

    /**
     *
 The Amazon Resource Number (ARN) of the Cloudwatch Log Group associated with
     * this import task.

     */
    inline ImportSummary& WithCloudWatchLogGroupArn(const Aws::String& value) { SetCloudWatchLogGroupArn(value); return *this;}

    /**
     *
 The Amazon Resource Number (ARN) of the Cloudwatch Log Group associated with
     * this import task.

     */
    inline ImportSummary& WithCloudWatchLogGroupArn(Aws::String&& value) { SetCloudWatchLogGroupArn(std::move(value)); return *this;}

    /**
     *
 The Amazon Resource Number (ARN) of the Cloudwatch Log Group associated with
     * this import task.

     */
    inline ImportSummary& WithCloudWatchLogGroupArn(const char* value) { SetCloudWatchLogGroupArn(value); return *this;}

    /**
     *
 The format of the source data. Valid values are CSV,
     * DYNAMODB_JSON or ION.

     */
    inline const InputFormat& GetInputFormat() const{ return m_inputFormat; }

    /**
     *
 The format of the source data. Valid values are CSV,
     * DYNAMODB_JSON or ION.

     */
    inline bool InputFormatHasBeenSet() const { return m_inputFormatHasBeenSet; }

    /**
     *
 The format of the source data. Valid values are CSV,
     * DYNAMODB_JSON or ION.

     */
    inline void SetInputFormat(const InputFormat& value) { m_inputFormatHasBeenSet = true; m_inputFormat = value; }

    /**
     *
 The format of the source data. Valid values are CSV,
     * DYNAMODB_JSON or ION.

     */
    inline void SetInputFormat(InputFormat&& value) { m_inputFormatHasBeenSet = true; m_inputFormat = std::move(value); }

    /**
     *
 The format of the source data. Valid values are CSV,
     * DYNAMODB_JSON or ION.

     */
    inline ImportSummary& WithInputFormat(const InputFormat& value) { SetInputFormat(value); return *this;}

    /**
     *
 The format of the source data. Valid values are CSV,
     * DYNAMODB_JSON or ION.

     */
    inline ImportSummary& WithInputFormat(InputFormat&& value) { SetInputFormat(std::move(value)); return *this;}

    /**
     *
 The time at which this import task began.

     */
    inline const Aws::Utils::DateTime& GetStartTime() const{ return m_startTime; }

    /**
     *
 The time at which this import task began.

     */
    inline bool StartTimeHasBeenSet() const { return m_startTimeHasBeenSet; }

    /**
     *
 The time at which this import task began.

     */
    inline void SetStartTime(const Aws::Utils::DateTime& value) { m_startTimeHasBeenSet = true; m_startTime = value; }

    /**
     *
 The time at which this import task began.

     */
    inline void SetStartTime(Aws::Utils::DateTime&& value) { m_startTimeHasBeenSet = true; m_startTime = std::move(value); }

    /**
     *
 The time at which this import task began.

     */
    inline ImportSummary& WithStartTime(const Aws::Utils::DateTime& value) { SetStartTime(value); return *this;}

    /**
     *
 The time at which this import task began.

     */
    inline ImportSummary& WithStartTime(Aws::Utils::DateTime&& value) { SetStartTime(std::move(value)); return *this;}

    /**
     *
 The time at which this import task ended. (Does this include the successful
     * complete creation of the table it was imported to?)

     */
    inline const Aws::Utils::DateTime& GetEndTime() const{ return m_endTime; }

    /**
     *
 The time at which this import task ended. (Does this include the successful
     * complete creation of the table it was imported to?)

     */
    inline bool EndTimeHasBeenSet() const { return m_endTimeHasBeenSet; }

    /**
     *
 The time at which this import task ended. (Does this include the successful
     * complete creation of the table it was imported to?)

     */
    inline void SetEndTime(const Aws::Utils::DateTime& value) { m_endTimeHasBeenSet = true; m_endTime = value; }

    /**
     *
 The time at which this import task ended. (Does this include the successful
     * complete creation of the table it was imported to?)

     */
    inline void SetEndTime(Aws::Utils::DateTime&& value) { m_endTimeHasBeenSet = true; m_endTime = std::move(value); }

    /**
     *
 The time at which this import task ended. (Does this include the successful
     * complete creation of the table it was imported to?)

     */
    inline ImportSummary& WithEndTime(const Aws::Utils::DateTime& value) { SetEndTime(value); return *this;}

    /**
     *
 The time at which this import task ended. (Does this include the successful
     * complete creation of the table it was imported to?)

     */
    inline ImportSummary& WithEndTime(Aws::Utils::DateTime&& value) { SetEndTime(std::move(value)); return *this;}

  private:

    Aws::String m_importArn;
    bool m_importArnHasBeenSet = false;

    ImportStatus m_importStatus;
    bool m_importStatusHasBeenSet = false;

    Aws::String m_tableArn;
    bool m_tableArnHasBeenSet = false;

    S3BucketSource m_s3BucketSource;
    bool m_s3BucketSourceHasBeenSet = false;

    Aws::String m_cloudWatchLogGroupArn;
    bool m_cloudWatchLogGroupArnHasBeenSet = false;

    InputFormat m_inputFormat;
    bool m_inputFormatHasBeenSet = false;

    Aws::Utils::DateTime m_startTime;
    bool m_startTimeHasBeenSet = false;

    Aws::Utils::DateTime m_endTime;
    bool m_endTimeHasBeenSet = false;
  };

} // namespace Model
} // namespace DynamoDB
} // namespace Aws


text:
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './components/App';
import Login from './components/Login';
import CreateWallet from './components/CreateWallet';
import Send from './components/Send';
import Dashboard from './containers/Dashboard';

export default (
	<Route path="/" component={App}>
		<IndexRoute component={Login} />
		<Route path="/dashboard" component={Dashboard} />
		<Route path="/create" component={CreateWallet} />
		<Route path="/send" component={Send} />
	</Route>
);

redpajama_set_name: RedPajamaGithub


text:
//
//  MyLabel.m
//  美团
//
//  Created by 陈受恩 on 15/12/14.
//  Copyright © 2015年 chenshouen. All rights reserved.
//

#import "MyLabel.h"

@implementation MyLabel

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.*/

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];

    //获取上下文CGContextRef +设置画线起点画线终点+渲染到屏幕
    CGContextRef context=UIGraphicsGetCurrentContext();
    CGContextMoveToPoint(context, 0, rect.size.height/2);
    CGContextAddLineToPoint(context, rect.size.width, rect.size.height/2);
    CGContextStrokePath(context);

}

@end


text:
using LiteGuard;

namespace Savvy.Services.Authentication
{
    /// <summary>
    /// This event is fired if the user logged in.
    /// </summary>
    public sealed class UserLoggedInEvent
    {
    }
}


text:
package org.apache.hadoop.hbase.replication;

import static org.junit.Assert.fail;

import java.io.IOException;

import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.ipc.RpcServer;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.apache.hadoop.hbase.testclassification.ReplicationTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.JVMClusterUtil;
import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Category({ ReplicationTests.class, LargeTests.class })
public class TestReplicationDroppedTables extends TestReplicationBase {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
      HBaseClassTestRule.forClass(TestReplicationDroppedTables.class);

  private static final Logger LOG = LoggerFactory.getLogger(TestReplicationDroppedTables.class);
  private static final int ROWS_COUNT = 1000;

  @Before
  public void setUpBase() throws Exception {
    // Starting and stopping replication can make us miss new logs,
    // rolling like this makes sure the most recent one gets added to the queue
    for (JVMClusterUtil.RegionServerThread r : UTIL1.getHBaseCluster()
        .getRegionServerThreads()) {
      UTIL1.getAdmin().rollWALWriter(r.getRegionServer().getServerName());
    }
    // Initialize the peer after wal rolling, so that we will abandon the stuck WALs.
    super.setUpBase();
    int rowCount = UTIL1.countRows(tableName);
    UTIL1.deleteTableData(tableName);
    // truncating the table will send one Delete per row to the slave cluster
    // in an async fashion, which is why we cannot just call deleteTableData on
    // utility2 since late writes could make it to the slave in some way.
    // Instead, we truncate the first table and wait for all the Deletes to
    // make it to the slave.
    Scan scan = new Scan();
    int lastCount = 0;
    for (int i = 0; i < NB_RETRIES; i++) {
      if (i == NB_RETRIES - 1) {
        fail("Waited too much time for truncate");
      }
      ResultScanner scanner = htable2.getScanner(scan);
      Result[] res = scanner.next(rowCount);
      scanner.close();
      if (res.length != 0) {
        if (res.length < lastCount) {
          i--; // Don't increment timeout if we make progress
        }
        lastCount = res.length;
        LOG.info("Still got " + res.length + " rows");
        Thread.sleep(SLEEP_TIME);
      } else {
        break;
      }
    }
    // Set the max request size to a tiny 10K for dividing the replication WAL entries into multiple
    // batches. the default max request size is 256M, so all replication entries are in a batch, but
    // when replicate at sink side, it'll apply to rs group by table name, so the WAL of test table
    // may apply first, and then test_dropped table, and we will believe that the replication is not
    // got stuck (HBASE-20475).
    CONF1.setInt(RpcServer.MAX_REQUEST_SIZE, 10 * 1024);
  }

  @Test
  public void testEditsStuckBehindDroppedTable() throws Exception {
    // Sanity check Make sure by default edits for dropped tables stall the replication queue, even
    // when the table(s) in question have been deleted on both ends.
    testEditsBehindDroppedTable(false, "test_dropped");
  }

  @Test
  public void testEditsDroppedWithDroppedTable() throws Exception {
    // Make sure by default edits for dropped tables are themselves dropped when the
    // table(s) in question have been deleted on both ends.
    testEditsBehindDroppedTable(true, "test_dropped");
  }

  @Test
  public void testEditsDroppedWithDroppedTableNS() throws Exception {
    // also try with a namespace
    UTIL1.getAdmin().createNamespace(NamespaceDescriptor.create("NS").build());
    UTIL2.getAdmin().createNamespace(NamespaceDescriptor.create("NS").build());
    try {
      testEditsBehindDroppedTable(true, "NS:test_dropped");
    } finally {
      UTIL1.getAdmin().deleteNamespace("NS");
      UTIL2.getAdmin().deleteNamespace("NS");
    }
  }

  private byte[] generateRowKey(int id) {
    return Bytes.toBytes(String.format("NormalPut%03d", id));
  }

  private void testEditsBehindDroppedTable(boolean allowProceeding, String tName) throws Exception {
    CONF1.setBoolean(HConstants.REPLICATION_DROP_ON_DELETED_TABLE_KEY, allowProceeding);
    CONF1.setInt(HConstants.REPLICATION_SOURCE_MAXTHREADS_KEY, 1);

    // make sure we have a single region server only, so that all
    // edits for all tables go there
    restartSourceCluster(1);

    TableName tablename = TableName.valueOf(tName);
    byte[] familyName = Bytes.toBytes("fam");
    byte[] row = Bytes.toBytes("row");

    TableDescriptor table =
        TableDescriptorBuilder
            .newBuilder(tablename).setColumnFamily(ColumnFamilyDescriptorBuilder
                .newBuilder(familyName).setScope(HConstants.REPLICATION_SCOPE_GLOBAL).build())
            .build();

    Connection connection1 = ConnectionFactory.createConnection(UTIL1.getConfiguration());
    Connection connection2 = ConnectionFactory.createConnection(UTIL2.getConfiguration());
    try (Admin admin1 = connection1.getAdmin()) {
      admin1.createTable(table);
    }
    try (Admin admin2 = connection2.getAdmin()) {
      admin2.createTable(table);
    }
    UTIL1.waitUntilAllRegionsAssigned(tablename);
    UTIL2.waitUntilAllRegionsAssigned(tablename);

    // now suspend replication
    try (Admin admin1 = connection1.getAdmin()) {
      admin1.disableReplicationPeer(PEER_ID2);
    }

    // put some data (lead with 0 so the edit gets sorted before the other table's edits
    // in the replication batch) write a bunch of edits, making sure we fill a batch
    try (Table droppedTable = connection1.getTable(tablename)) {
      byte[] rowKey = Bytes.toBytes(0 + " put on table to be dropped");
      Put put = new Put(rowKey);
      put.addColumn(familyName, row, row);
      droppedTable.put(put);
    }

    try (Table table1 = connection1.getTable(tableName)) {
      for (int i = 0; i < ROWS_COUNT; i++) {
        Put put = new Put(generateRowKey(i)).addColumn(famName, row, row);
        table1.put(put);
      }
    }

    try (Admin admin1 = connection1.getAdmin()) {
      admin1.disableTable(tablename);
      admin1.deleteTable(tablename);
    }
    try (Admin admin2 = connection2.getAdmin()) {
      admin2.disableTable(tablename);
      admin2.deleteTable(tablename);
    }

    try (Admin admin1 = connection1.getAdmin()) {
      admin1.enableReplicationPeer(PEER_ID2);
    }

    if (allowProceeding) {
      // in this we'd expect the key to make it over
      verifyReplicationProceeded();
    } else {
      verifyReplicationStuck();
    }
    // just to be safe
    CONF1.setBoolean(HConstants.REPLICATION_DROP_ON_DELETED_TABLE_KEY, false);
  }

  @Test
  public void testEditsBehindDroppedTableTiming() throws Exception {
    CONF1.setBoolean(HConstants.REPLICATION_DROP_ON_DELETED_TABLE_KEY, true);
    CONF1.setInt(HConstants.REPLICATION_SOURCE_MAXTHREADS_KEY, 1);

    // make sure we have a single region server only, so that all
    // edits for all tables go there
    restartSourceCluster(1);

    TableName tablename = TableName.valueOf("testdroppedtimed");
    byte[] familyName = Bytes.toBytes("fam");
    byte[] row = Bytes.toBytes("row");

    TableDescriptor table =
        TableDescriptorBuilder
            .newBuilder(tablename).setColumnFamily(ColumnFamilyDescriptorBuilder
                .newBuilder(familyName).setScope(HConstants.REPLICATION_SCOPE_GLOBAL).build())
            .build();

    Connection connection1 = ConnectionFactory.createConnection(CONF1);
    Connection connection2 = ConnectionFactory.createConnection(CONF2);
    try (Admin admin1 = connection1.getAdmin()) {
      admin1.createTable(table);
    }
    try (Admin admin2 = connection2.getAdmin()) {
      admin2.createTable(table);
    }
    UTIL1.waitUntilAllRegionsAssigned(tablename);
    UTIL2.waitUntilAllRegionsAssigned(tablename);

    // now suspend replication
    try (Admin admin1 = connection1.getAdmin()) {
      admin1.disableReplicationPeer(PEER_ID2);
    }

    // put some data (lead with 0 so the edit gets sorted before the other table's edits
    // in the replication batch) write a bunch of edits, making sure we fill a batch
    try (Table droppedTable = connection1.getTable(tablename)) {
      byte[] rowKey = Bytes.toBytes(0 + " put on table to be dropped");
      Put put = new Put(rowKey);
      put.addColumn(familyName, row, row);
      droppedTable.put(put);
    }

    try (Table table1 = connection1.getTable(tableName)) {
      for (int i = 0; i < ROWS_COUNT; i++) {
        Put put = new Put(generateRowKey(i)).addColumn(famName, row, row);
        table1.put(put);
      }
    }

    try (Admin admin2 = connection2.getAdmin()) {
      admin2.disableTable(tablename);
      admin2.deleteTable(tablename);
    }

    // edit should still be stuck
    try (Admin admin1 = connection1.getAdmin()) {
      // enable the replication peer.
      admin1.enableReplicationPeer(PEER_ID2);
      // the source table still exists, replication should be stalled
      verifyReplicationStuck();

      admin1.disableTable(tablename);
      // still stuck, source table still exists
      verifyReplicationStuck();

      admin1.deleteTable(tablename);
      // now the source table is gone, replication should proceed, the
      // offending edits be dropped
      verifyReplicationProceeded();
    }
    // just to be safe
    CONF1.setBoolean(HConstants.REPLICATION_DROP_ON_DELETED_TABLE_KEY, false);
  }

  private boolean peerHasAllNormalRows() throws IOException {
    try (ResultScanner scanner = htable2.getScanner(new Scan())) {
      Result[] results = scanner.next(ROWS_COUNT);
      if (results.length != ROWS_COUNT) {
        return false;
      }
      for (int i = 0; i < results.length; i++) {
        Assert.assertArrayEquals(generateRowKey(i), results[i].getRow());
      }
      return true;
    }
  }

  private void verifyReplicationProceeded() throws Exception {
    for (int i = 0; i < NB_RETRIES; i++) {
      if (i == NB_RETRIES - 1) {
        fail("Waited too much time for put replication");
      }
      if (!peerHasAllNormalRows()) {
        LOG.info("Row not available");
        Thread.sleep(SLEEP_TIME);
      } else {
        break;
      }
    }
  }

  private void verifyReplicationStuck() throws Exception {
    for (int i = 0; i < NB_RETRIES; i++) {
      if (peerHasAllNormalRows()) {
        fail("Edit should have been stuck behind dropped tables");
      } else {
        LOG.info("Row not replicated, let's wait a bit more...");
        Thread.sleep(SLEEP_TIME);
      }
    }
  }
}


text:
package utils

import (
	"net/url"
	"strings"
)

// HostnameFromAddr determines the hostname in an address string
func HostnameFromAddr(addr string) (string, error) {
	p, err := url.Parse(addr)
	if err != nil {
		return "", err
	}
	h := p.Host

	// copied from https://golang.org/src/net/http/transport.go
	if hasPort(h) {
		h = h[:strings.LastIndex(h, ":")]
	}

	return h, nil
}

// copied from https://golang.org/src/net/http/http.go
func hasPort(s string) bool {
	return strings.LastIndex(s, ":") > strings.LastIndex(s, "]")
}


text:
package com.google.cloud.hadoop.gcsio;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.common.util.concurrent.MoreExecutors;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * The unittest version of {@code GoogleCloudStorageFileSystemIntegrationTest}; the external
 * GoogleCloudStorage dependency is replaced by an in-memory version which mimics the same
 * bucket/object semantics.
 */
@RunWith(JUnit4.class)
public class GoogleCloudStorageFileSystemTest
    extends GoogleCloudStorageFileSystemIntegrationTest {

  @BeforeClass
  public static void beforeAllTests()
      throws IOException {
    // Disable logging.
    Logger.getRootLogger().setLevel(Level.OFF);

    if (gcsfs == null) {
      // TODO(user): Maybe switch to
      // new CacheSupplementedGoogleCloudStorage(new InMemoryGoogleCloudStorage()).
      gcsfs = new GoogleCloudStorageFileSystem(new InMemoryGoogleCloudStorage(),
          GoogleCloudStorageFileSystemOptions
              .newBuilder()
              .setShouldIncludeInTimestampUpdatesPredicate(INCLUDE_SUBSTRINGS_PREDICATE)
              .build());
      gcsfs.setUpdateTimestampsExecutor(MoreExecutors.sameThreadExecutor());
      GoogleCloudStorageFileSystemIntegrationTest.postCreateInit();
    }
  }

  @AfterClass
  public static void afterAllTests()
      throws IOException {
    GoogleCloudStorageFileSystemIntegrationTest.afterAllTests();
  }

  /**
   * Helper to fill out some default valid options after which the caller may want to reset a few
   * invalid options for individual items for particular tests.
   */
  private static void setDefaultValidOptions(
      GoogleCloudStorageFileSystemOptions.Builder optionsBuilder) {
    optionsBuilder
        .setIsMetadataCacheEnabled(true)
        .setCacheMaxEntryAgeMillis(12345L)
        .setCacheMaxInfoAgeMillis(42L)
        .getCloudStorageOptionsBuilder()
            .setAppName("appName")
            .setProjectId("projectId")
            .getWriteChannelOptionsBuilder()
                .setFileSizeLimitedTo250Gb(GCS_FILE_SIZE_LIMIT_250GB_DEFAULT)
                .setUploadBufferSize(WRITE_BUFFERSIZE_DEFAULT);
  }

  /**
   * Validates constructor.
   */
  @Test
  public void testConstructor() throws IOException {
    GoogleCredential cred = new GoogleCredential();
    GoogleCloudStorageFileSystemOptions.Builder optionsBuilder =
        GoogleCloudStorageFileSystemOptions.newBuilder();

    setDefaultValidOptions(optionsBuilder);

    // Verify that projectId == null or empty throws IllegalArgumentException.
    optionsBuilder.getCloudStorageOptionsBuilder().setProjectId(null);
    try {
      new GoogleCloudStorageFileSystem(cred, optionsBuilder.build());
      Assert.fail("Expected IllegalArgumentException");
    } catch (IllegalArgumentException iae) {
      // Expected.
    }

    optionsBuilder.getCloudStorageOptionsBuilder().setProjectId("");
    try {
      new GoogleCloudStorageFileSystem(cred, optionsBuilder.build());
      Assert.fail("Expected IllegalArgumentException");
    } catch (IllegalArgumentException iae) {
      // Expected.
    }

    optionsBuilder.getCloudStorageOptionsBuilder().setProjectId("projectId");

    // Verify that appName == null or empty throws IllegalArgumentException.

    optionsBuilder.getCloudStorageOptionsBuilder().setAppName(null);
    try {
      new GoogleCloudStorageFileSystem(cred, optionsBuilder.build());
      Assert.fail("Expected IllegalArgumentException");
    } catch (IllegalArgumentException iae) {
      // Expected.
    }

    optionsBuilder.getCloudStorageOptionsBuilder().setAppName("");
    try {
      new GoogleCloudStorageFileSystem(cred, optionsBuilder.build());
      Assert.fail("Expected IllegalArgumentException");
    } catch (IllegalArgumentException iae) {
      // Expected.
    }

    optionsBuilder.getCloudStorageOptionsBuilder().setAppName("appName");

    // Verify that credential == null throws IllegalArgumentException.
    try {
      new GoogleCloudStorageFileSystem((Credential) null, optionsBuilder.build());
      Assert.fail("Expected IllegalArgumentException");
    } catch (IllegalArgumentException iae) {
      // Expected.
    }

    // Verify that fake projectId/appName and empty cred does not throw.
    setDefaultValidOptions(optionsBuilder);

    GoogleCloudStorageFileSystem tmpGcsFs =
        new GoogleCloudStorageFileSystem(cred, optionsBuilder.build());

    // White-box testing; check a few internal outcomes of our options.
    Assert.assertTrue(tmpGcsFs.getGcs() instanceof CacheSupplementedGoogleCloudStorage);
    CacheSupplementedGoogleCloudStorage cacheGcs =
        (CacheSupplementedGoogleCloudStorage) tmpGcsFs.getGcs();
    Assert.assertEquals(
        12345L, cacheGcs.getResourceCache().getMutableConfig().getMaxEntryAgeMillis());
    Assert.assertEquals(
        42L, cacheGcs.getResourceCache().getMutableConfig().getMaxInfoAgeMillis());
  }

  /**
   * Verify that pathComparator produces correct sorting order.
   */
  @Test
  public void testPathComparator()
      throws URISyntaxException {
    String[] paths = {
      "gs://aa",
      "gs://abcdefghij",
      "gs://aaa",
      "gs:/",
      "gs://aa/f",
      "gs://aaa/f",
      "gs://aa/bb/f",
      "gs://ab",
      "gs://aa/bb/",
      "gs://aa",
    };

    String[] expectedAfterSort = {
      "gs:/",
      "gs://aa",
      "gs://aa",
      "gs://ab",
      "gs://aaa",
      "gs://aa/f",
      "gs://aaa/f",
      "gs://aa/bb/",
      "gs://aa/bb/f",
      "gs://abcdefghij",
    };

    // Prepare URI lists from their string equivalents.
    List<URI> pathUris = new ArrayList<>();
    List<URI> expectedUris = new ArrayList<>();

    for (String path : paths) {
      pathUris.add(new URI(path));
    }

    for (String path : expectedAfterSort) {
      expectedUris.add(new URI(path));
    }

    // Sanity check for input data using "natural-ordering" sorting.
    List<URI> pathUrisNaturalSorted = new ArrayList<>(pathUris);
    Collections.sort(pathUrisNaturalSorted);
    List<URI> expectedUrisNaturalSorted = new ArrayList<>(expectedUris);
    Collections.sort(expectedUrisNaturalSorted);
    Assert.assertArrayEquals(expectedUrisNaturalSorted.toArray(), pathUrisNaturalSorted.toArray());

    // Sort the paths with the GCSFS-supplied pathComparator and verify.
    Collections.sort(pathUris, GoogleCloudStorageFileSystem.pathComparator);
    Assert.assertArrayEquals(expectedUris.toArray(), pathUris.toArray());
  }

  /**
   * Verify that we cannot pass invalid path to GoogleCloudStorageFileSystem.
   */
  @Test
  public void testInvalidPath()
      throws IOException, URISyntaxException {
    String[] invalidPaths = {

      // Path with a scheme other than gs.
      "foo://bucket/object",

      // Path with empty object name.
      "gs://bucket/",
      "gs://bucket",

      // Path with consecutive / chars in the path component.
      "gs://bucket//obj",
      "gs://bucket/obj//foo/bar",
    };

    for (String invalidPath : invalidPaths) {
      try {
        GoogleCloudStorageFileSystem.validatePathAndGetId(new URI(invalidPath), false);
        Assert.fail(String.format("Expected path to be invalid: %s", invalidPath));
      } catch (IllegalArgumentException expected) {
        // Expected.
      }
    }

    String[] validPaths = {
      "gs:/",
      "gs://bucket/obj",
      "gs://bucket/obj/",
      "gs://bucket/obj/bar",
    };

    for (String validPath : validPaths) {
      try {
        GoogleCloudStorageFileSystem.validatePathAndGetId(new URI(validPath), false);
      } catch (IllegalArgumentException expected) {
        Assert.fail(String.format("Expected path to be valid: %s", validPath));
      }
    }

    try {
      // To verify the behavior when the GCSFS is the one creating an invalid URI, we must call
      // through directly to GCSFS.getPath instead of GCSFS.validatePathAndGetId like above;
      // there's no way to create the invalid URI beforehand to pass through to GCSFS.
      String invalidBucketName = "bucket-name-has-invalid-char^";
      GoogleCloudStorageFileSystem.getPath(invalidBucketName, null, true);
      Assert.fail(String.format("Expected getPath to be invalid: gs://%s", invalidBucketName));
    } catch (IllegalArgumentException expected) {
      // Expected.
    }
  }

  /**
   * Verify getItemName().
   */
  @Test
  public void testGetItemName()
      throws URISyntaxException {
    // Trailing slashes are effectively stripped for returned bucket names, but not for object
    // names.
    String[] inputPaths = {
      "gs:/",
      "gs://my-bucket",
      "gs://my-bucket/",
      "gs://my-bucket/foo",
      "gs://my-bucket/foo/",
      "gs://my-bucket/foo/bar",
      "gs://my-bucket/foo/bar/",
    };

    String[] expectedNames = {
      null,
      "my-bucket",
      "my-bucket",
      "foo",
      "foo/",
      "bar",
      "bar/",
    };

    List<String> actualNames = new ArrayList<>();
    for (String inputPath : inputPaths) {
      actualNames.add(GoogleCloudStorageFileSystem.getItemName(new URI(inputPath)));
    }
    Assert.assertArrayEquals(expectedNames, actualNames.toArray(new String[0]));
  }

  /**
   * Verify getParentPath().
   */
  @Test
  public void testGetParentPathEdgeCases()
      throws URISyntaxException {
    URI[] inputPaths = {
      new URI("gs:/"),
      new URI("gs://my-bucket"),
      new URI("gs://my-bucket/"),
      new URI("gs://my-bucket/foo"),
      new URI("gs://my-bucket/foo/"),
      new URI("gs://my-bucket/foo/bar"),
      new URI("gs://my-bucket/foo/bar/"),
    };

    URI[] expectedPaths = {
      null,
      new URI("gs:/"),
      new URI("gs:/"),
      new URI("gs://my-bucket/"),
      new URI("gs://my-bucket/"),
      new URI("gs://my-bucket/foo/"),
      new URI("gs://my-bucket/foo/"),
    };

    List<URI> actualPaths = new ArrayList<>();
    for (URI inputPath : inputPaths) {
      actualPaths.add(GoogleCloudStorageFileSystem.getParentPath(inputPath));
    }
    Assert.assertArrayEquals(expectedPaths, actualPaths.toArray(new URI[0]));
  }

  /**
   * Verify validateBucketName().
   */
  @Test
  public void testValidateBucketName() {
    String[] invalidBucketNames = {

      // Empty or null.
      null,
      "",

      // With a '/' character in it.
      "foo/bar",
      "/bar",
    };

    for (String bucketName : invalidBucketNames) {
      try {
        GoogleCloudStorageFileSystem.validateBucketName(bucketName);
        Assert.fail(String.format("Expected bucket name to be invalid: %s", bucketName));
      } catch (IllegalArgumentException expected) {
        // Expected.
      }
    }

    String[] validBucketNames = {
      "foo",
      "foo/",
    };

    for (String bucketName : validBucketNames) {
      try {
        GoogleCloudStorageFileSystem.validateBucketName(bucketName);
      } catch (IllegalArgumentException expected) {
        Assert.fail(String.format("Expected bucket name to be valid: %s", bucketName));
      }
    }
  }

  /**
   * Verify validateObjectName().
   */
  @Test
  public void testValidateObjectName() {
    String[] invalidObjectNames = {

      // Empty or null.
      null,
      "",

      // With consecutive '/' characters in it.
      "//",
      "///",
      "foo//bar",
      "foo/bar//",
      "//foo/bar",
      "foo////bar",

      // other cases
      "/",
    };

    for (String objectName : invalidObjectNames) {
      try {
        GoogleCloudStorageFileSystem.validateObjectName(objectName, false);
        Assert.fail(String.format("Expected object name to be invalid: %s", objectName));
      } catch (IllegalArgumentException expected) {
        // Expected.
      }
    }

    // Verify that an empty object name is allowed when explicitly allowed.
    GoogleCloudStorageFileSystem.validateObjectName(null, true);
    GoogleCloudStorageFileSystem.validateObjectName("", true);

    String[] validObjectNames = {
      "foo",
      "foo/bar",
      "foo/bar/",
    };

    for (String objectName : validObjectNames) {
      try {
        GoogleCloudStorageFileSystem.validateObjectName(objectName, false);
      } catch (IllegalArgumentException expected) {
        Assert.fail(String.format("Expected object name to be valid: %s", objectName));
      }
    }
  }

  /**
   * Verify misc cases for FileInfo.
   */
  @Test
  public void testFileInfo()
      throws IOException {
    Assert.assertEquals(
        GoogleCloudStorageFileSystem.GCS_ROOT,
        gcsfs.getFileInfo(GoogleCloudStorageFileSystem.GCS_ROOT).getPath());
    Assert.assertEquals(
        GoogleCloudStorageItemInfo.ROOT_INFO,
        gcsfs.getFileInfo(GoogleCloudStorageFileSystem.GCS_ROOT).getItemInfo());
  }

  /**
   * Verify misc cases for create/open.
   */
  @Test
  public void testMiscCreateAndOpen()
      throws URISyntaxException, IOException {
    URI dirPath = new URI("gs://foo/bar/");
    try {
      gcsfs.create(dirPath);
      Assert.fail(String.format("Writing to directory should not be allowed: %s", dirPath));
    } catch (IllegalArgumentException expected) {
      // Expected.
    }

    try {
      gcsfs.open(dirPath);
      Assert.fail(String.format("Reading from directory should not be allowed: %s", dirPath));
    } catch (IllegalArgumentException expected) {
      // Expected.
    }
  }
}


text:
| **Master** | **Develop** |
|   :---:    |    :---:    |
|  |  |

# Wiki-Editor
A React/Slate WYSIWYG editor

## Current Plugins

### Alignment
Supports `align: left|right|justify` and `float: left|right`

### Anchor
Allows editing of `a` tags via Markdown syntax: `[text](href)`. Whenever the cursor enters a hyperlink, it will be automatically converted to Markdown. As soon as the cursor leaves this Markdown, it automatically converts back into a hyperlink.

### AutoReplacers
Supports case-insensitive, automatic conversion of:
* `(c)` to ©
* `(r)` to ®
* `(tm)` to ™
* `--` to `<hr />` (2+ `-` on a single line, converted on pressing `Enter` at the end of the line)
* `#{1,6}` to `<h1>` through `<h6>` (start a new line with `#`'s, and press `Space`)

### Header
Supports a toolbar dropdown menu for converting the current line from `<p>` to `<h1>` to `<h6>`

### HorizontalRule
Supports keyboard navigation around `<hr />` tags

### Paragraph
Supports basic `<p>` tag rendering, compatible with the **Alignment** plugin

### Table
Provides keyboard navigation, toolbar support, and hotkeys for editing `<table>`s and their children. All hotkeys use `⌘+Shift` _and_ `Ctrl+Shift` plus the keystroke below.
* Add Table
* Clear Cell Contents: Hotkey+`Delete`
* Insert Column to Left: Hotkey+`Left`
* Insert Column to Right: Hotkey+`Right`
* Insert Row Above: Hotkey+`Up`
* Insert Row Below: Hotkey+`Down`
* Toggle `TD`/`TH`: Hotkey+`H`
* Delete Table

### TextDecorators
* Toggle Bold: `Ctrl` or `⌘` + `b`
* Toggle Italic: `Ctrl` or `⌘` + `i`
* Toggle Strike: `Ctrl` or `⌘` + `d`
* Toggle Underline: `Ctrl` or `⌘` + `u`
* Toggle Superscript: `Ctrl` or `⌘` + `Up`
* Toggle Subscript: `Ctrl` or `⌘` + `Down`


text:
namespace MineAPI.Editor.Item.WizardNewItemMeta
{
    /// <summary>
    ///
    /// </summary>
    partial class AddItemMetaPage1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #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()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AddItemMetaPage1));
            this.lblSubItemName = new System.Windows.Forms.Label();
            this.txtSubItemName = new System.Windows.Forms.TextBox();
            this.txtSubItemNameReal = new System.Windows.Forms.TextBox();
            this.lblSubItemNameReal = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // lblSubItemName
            //
            this.lblSubItemName.Location = new System.Drawing.Point(35, 69);
            this.lblSubItemName.Name = "lblSubItemName";
            this.lblSubItemName.Size = new System.Drawing.Size(525, 85);
            this.lblSubItemName.TabIndex = 19;
            this.lblSubItemName.Text = resources.GetString("lblSubItemName.Text");
            //
            // txtSubItemName
            //
            this.txtSubItemName.Location = new System.Drawing.Point(35, 157);
            this.txtSubItemName.Name = "txtSubItemName";
            this.txtSubItemName.Size = new System.Drawing.Size(525, 20);
            this.txtSubItemName.TabIndex = 16;
            this.txtSubItemName.TextChanged += new System.EventHandler(this.txtSubItemName_TextChanged);
            //
            // txtSubItemNameReal
            //
            this.txtSubItemNameReal.Location = new System.Drawing.Point(35, 251);
            this.txtSubItemNameReal.Name = "txtSubItemNameReal";
            this.txtSubItemNameReal.ReadOnly = true;
            this.txtSubItemNameReal.Size = new System.Drawing.Size(525, 20);
            this.txtSubItemNameReal.TabIndex = 18;
            //
            // lblSubItemNameReal
            //
            this.lblSubItemNameReal.Location = new System.Drawing.Point(35, 230);
            this.lblSubItemNameReal.Name = "lblSubItemNameReal";
            this.lblSubItemNameReal.Size = new System.Drawing.Size(525, 18);
            this.lblSubItemNameReal.TabIndex = 17;
            this.lblSubItemNameReal.Text = "Shows what your sub-item name will actually look like after processing...";
            //
            // AddItemMetaPage1
            //
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
            this.Controls.Add(this.lblSubItemName);
            this.Controls.Add(this.txtSubItemName);
            this.Controls.Add(this.txtSubItemNameReal);
            this.Controls.Add(this.lblSubItemNameReal);
            this.MinimumSize = new System.Drawing.Size(594, 412);
            this.Name = "AddItemMetaPage1";
            this.Size = new System.Drawing.Size(594, 412);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label lblSubItemName;
        private System.Windows.Forms.TextBox txtSubItemName;
        private System.Windows.Forms.TextBox txtSubItemNameReal;
        private System.Windows.Forms.Label lblSubItemNameReal;
    }
}


text:
It's nothing more than a simple version of grep command in linux system. The purpose of this project is to make easier for the user to search a word or multpile words from the give path.

## SetUp

Download the project from the github using https or git clone command,

    https://github.com/ashokkumar-dhanavel/python-proj.git

                     or
    git clone git@github.com:ashokkumar-dhanavel/python-proj.git

## Pre-requisites for testing the project

The following python packages are required for testing the project

1) nose

command to install nose package "pip install nose"

## Project Installation

After downloading the project from the github location setup the project using the command,

python setup.py install

## Logfind command usage

usage: logfind.py [-h] p s

Find the String from the log files

positional arguments:
  p           directory path
  s           keyword to find from the log files. Accept multiple words
              example 'Hello world'

optional arguments:
  -h, --help  show this help message and exit


text:
package org.springframework.core.convert;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.junit.Test;

import org.springframework.core.MethodParameter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

/**
 * Tests for {@link TypeDescriptor}.
 *
 * @author Keith Donald
 * @author Andy Clement
 * @author Phillip Webb
 */
@SuppressWarnings("rawtypes")
public class TypeDescriptorTests {

	public List<String> listOfString;

	public List<List<String>> listOfListOfString = new ArrayList<List<String>>();

	public List<List> listOfListOfUnknown = new ArrayList<List>();

	public int[] intArray;

	public List<String>[] arrayOfListOfString;

	public List<Integer> listField = new ArrayList<Integer>();

	public Map<String, Integer> mapField = new HashMap<String, Integer>();

	public Map<String, List<Integer>> nestedMapField = new HashMap<String, List<Integer>>();

	@Test
	public void parameterPrimitive() throws Exception {
		TypeDescriptor desc = new TypeDescriptor(new MethodParameter(getClass().getMethod("testParameterPrimitive", int.class), 0));
		assertEquals(int.class, desc.getType());
		assertEquals(Integer.class, desc.getObjectType());
		assertEquals("int", desc.getName());
		assertEquals("int", desc.toString());
		assertTrue(desc.isPrimitive());
		assertEquals(0, desc.getAnnotations().length);
		assertFalse(desc.isCollection());
		assertFalse(desc.isMap());
	}

	public void testParameterPrimitive(int primitive) {

	}

	@Test
	public void parameterScalar() throws Exception {
		TypeDescriptor desc = new TypeDescriptor(new MethodParameter(getClass().getMethod("testParameterScalar", String.class), 0));
		assertEquals(String.class, desc.getType());
		assertEquals(String.class, desc.getObjectType());
		assertEquals("java.lang.String", desc.getName());
		assertEquals("java.lang.String", desc.toString());
		assertTrue(!desc.isPrimitive());
		assertEquals(0, desc.getAnnotations().length);
		assertFalse(desc.isCollection());
		assertFalse(desc.isArray());
		assertFalse(desc.isMap());
	}

	public void testParameterScalar(String value) {

	}

	@Test
	public void parameterList() throws Exception {
		MethodParameter methodParameter = new MethodParameter(getClass().getMethod("testParameterList", List.class), 0);
		TypeDescriptor desc = new TypeDescriptor(methodParameter);
		assertEquals(List.class, desc.getType());
		assertEquals(List.class, desc.getObjectType());
		assertEquals("java.util.List", desc.getName());
		assertEquals("java.util.List<java.util.List<java.util.Map<java.lang.Integer, java.lang.Enum<?>>>>", desc.toString());
		assertTrue(!desc.isPrimitive());
		assertEquals(0, desc.getAnnotations().length);
		assertTrue(desc.isCollection());
		assertFalse(desc.isArray());
		assertEquals(List.class, desc.getElementTypeDescriptor().getType());
		assertEquals(TypeDescriptor.nested(methodParameter, 1), desc.getElementTypeDescriptor());
		assertEquals(TypeDescriptor.nested(methodParameter, 2), desc.getElementTypeDescriptor().getElementTypeDescriptor());
		assertEquals(TypeDescriptor.nested(methodParameter, 3), desc.getElementTypeDescriptor().getElementTypeDescriptor().getMapValueTypeDescriptor());
		assertEquals(Integer.class, desc.getElementTypeDescriptor().getElementTypeDescriptor().getMapKeyTypeDescriptor().getType());
		assertEquals(Enum.class, desc.getElementTypeDescriptor().getElementTypeDescriptor().getMapValueTypeDescriptor().getType());
		assertFalse(desc.isMap());
	}

	public void testParameterList(List<List<Map<Integer, Enum<?>>>> list) {

	}

	@Test
	public void parameterListNoParamTypes() throws Exception {
		MethodParameter methodParameter = new MethodParameter(getClass().getMethod("testParameterListNoParamTypes", List.class), 0);
		TypeDescriptor desc = new TypeDescriptor(methodParameter);
		assertEquals(List.class, desc.getType());
		assertEquals(List.class, desc.getObjectType());
		assertEquals("java.util.List", desc.getName());
		assertEquals("java.util.List<?>", desc.toString());
		assertTrue(!desc.isPrimitive());
		assertEquals(0, desc.getAnnotations().length);
		assertTrue(desc.isCollection());
		assertFalse(desc.isArray());
		assertNull(desc.getElementTypeDescriptor());
		assertFalse(desc.isMap());
	}

	public void testParameterListNoParamTypes(List list) {

	}

	@Test
	public void parameterArray() throws Exception {
		MethodParameter methodParameter = new MethodParameter(getClass().getMethod("testParameterArray", Integer[].class), 0);
		TypeDescriptor desc = new TypeDescriptor(methodParameter);
		assertEquals(Integer[].class, desc.getType());
		assertEquals(Integer[].class, desc.getObjectType());
		assertEquals("java.lang.Integer[]", desc.getName());
		assertEquals("java.lang.Integer[]", desc.toString());
		assertTrue(!desc.isPrimitive());
		assertEquals(0, desc.getAnnotations().length);
		assertFalse(desc.isCollection());
		assertTrue(desc.isArray());
		assertEquals(Integer.class, desc.getElementTypeDescriptor().getType());
		assertEquals(TypeDescriptor.valueOf(Integer.class), desc.getElementTypeDescriptor());
		assertFalse(desc.isMap());
	}

	public void testParameterArray(Integer[] array) {

	}

	@Test
	public void parameterMap() throws Exception {
		MethodParameter methodParameter = new MethodParameter(getClass().getMethod("testParameterMap", Map.class), 0);
		TypeDescriptor desc = new TypeDescriptor(methodParameter);
		assertEquals(Map.class, desc.getType());
		assertEquals(Map.class, desc.getObjectType());
		assertEquals("java.util.Map", desc.getName());
		assertEquals("java.util.Map<java.lang.Integer, java.util.List<java.lang.String>>", desc.toString());
		assertTrue(!desc.isPrimitive());
		assertEquals(0, desc.getAnnotations().length);
		assertFalse(desc.isCollection());
		assertFalse(desc.isArray());
		assertTrue(desc.isMap());
		assertEquals(TypeDescriptor.nested(methodParameter, 1), desc.getMapValueTypeDescriptor());
		assertEquals(TypeDescriptor.nested(methodParameter, 2), desc.getMapValueTypeDescriptor().getElementTypeDescriptor());
		assertEquals(Integer.class, desc.getMapKeyTypeDescriptor().getType());
		assertEquals(List.class, desc.getMapValueTypeDescriptor().getType());
		assertEquals(String.class, desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType());
	}

	public void testParameterMap(Map<Integer, List<String>> map) {

	}

	@Test
	public void parameterAnnotated() throws Exception {
		TypeDescriptor t1 = new TypeDescriptor(new MethodParameter(getClass().getMethod("testAnnotatedMethod", String.class), 0));
		assertEquals(String.class, t1.getType());
		assertEquals(1, t1.getAnnotations().length);
		assertNotNull(t1.getAnnotation(ParameterAnnotation.class));
		assertTrue(t1.hasAnnotation(ParameterAnnotation.class));
		assertEquals(123, t1.getAnnotation(ParameterAnnotation.class).value());
	}

	@Target({ElementType.PARAMETER})
	@Retention(RetentionPolicy.RUNTIME)
	public @interface ParameterAnnotation {
		int value();
	}

	public void testAnnotatedMethod(@ParameterAnnotation(123) String parameter) {

	}

	@Test
	public void propertyComplex() throws Exception {
		Property property = new Property(getClass(), getClass().getMethod("getComplexProperty"), getClass().getMethod("setComplexProperty", Map.class));
		TypeDescriptor desc = new TypeDescriptor(property);
		assertEquals(String.class, desc.getMapKeyTypeDescriptor().getType());
		assertEquals(Integer.class, desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getElementTypeDescriptor().getType());
	}

	public Map<String, List<List<Integer>>> getComplexProperty() {
		return null;
	}

	public void setComplexProperty(Map<String, List<List<Integer>>> complexProperty) {

	}

	@Test
	public void propertyGenericType() throws Exception {
		GenericType<Integer> genericBean = new IntegerType();
		Property property = new Property(getClass(), genericBean.getClass().getMethod("getProperty"), genericBean.getClass().getMethod("setProperty", Integer.class));
		TypeDescriptor desc = new TypeDescriptor(property);
		assertEquals(Integer.class, desc.getType());
	}

	@Test
	public void propertyTypeCovariance() throws Exception {
		GenericType<Number> genericBean = new NumberType();
		Property property = new Property(getClass(), genericBean.getClass().getMethod("getProperty"), genericBean.getClass().getMethod("setProperty", Number.class));
		TypeDescriptor desc = new TypeDescriptor(property);
		assertEquals(Integer.class, desc.getType());
	}

	@Test
	public void propertyGenericTypeList() throws Exception {
		GenericType<Integer> genericBean = new IntegerType();
		Property property = new Property(getClass(), genericBean.getClass().getMethod("getListProperty"), genericBean.getClass().getMethod("setListProperty", List.class));
		TypeDescriptor desc = new TypeDescriptor(property);
		assertEquals(List.class, desc.getType());
		assertEquals(Integer.class, desc.getElementTypeDescriptor().getType());
	}

	public interface GenericType<T> {
		T getProperty();

		void setProperty(T t);

		List<T> getListProperty();

		void setListProperty(List<T> t);

 	}

	public class IntegerType implements GenericType<Integer> {

		@Override
		public Integer getProperty() {
			return null;
		}

		@Override
		public void setProperty(Integer t) {
		}

		@Override
		public List<Integer> getListProperty() {
			return null;
		}

		@Override
		public void setListProperty(List<Integer> t) {
		}
	}

	public class NumberType implements GenericType<Number> {

		@Override
		public Integer getProperty() {
			return null;
		}

		@Override
		public void setProperty(Number t) {
		}

		@Override
		public List<Number> getListProperty() {
			return null;
		}

		@Override
		public void setListProperty(List<Number> t) {
		}
	}

	@Test
	public void propertyGenericClassList() throws Exception {
		IntegerClass genericBean = new IntegerClass();
		Property property = new Property(genericBean.getClass(), genericBean.getClass().getMethod("getListProperty"), genericBean.getClass().getMethod("setListProperty", List.class));
		TypeDescriptor desc = new TypeDescriptor(property);
		assertEquals(List.class, desc.getType());
		assertEquals(Integer.class, desc.getElementTypeDescriptor().getType());
		assertNotNull(desc.getAnnotation(MethodAnnotation1.class));
		assertTrue(desc.hasAnnotation(MethodAnnotation1.class));
	}

	public static class GenericClass<T> {

		public T getProperty() {
			return null;
		}

		public void setProperty(T t) {
		}

		@MethodAnnotation1
		public List<T> getListProperty() {
			return null;
		}

		public void setListProperty(List<T> t) {
		}

	}

	public static class IntegerClass extends GenericClass<Integer> {

	}

	@Test
	public void property() throws Exception {
		Property property = new Property(getClass(), getClass().getMethod("getProperty"), getClass().getMethod("setProperty", Map.class));
		TypeDescriptor desc = new TypeDescriptor(property);
		assertEquals(Map.class, desc.getType());
		assertEquals(Integer.class, desc.getMapKeyTypeDescriptor().getElementTypeDescriptor().getType());
		assertEquals(Long.class, desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType());
		assertNotNull(desc.getAnnotation(MethodAnnotation1.class));
		assertNotNull(desc.getAnnotation(MethodAnnotation2.class));
		assertNotNull(desc.getAnnotation(MethodAnnotation3.class));
	}

	@MethodAnnotation1
	public Map<List<Integer>, List<Long>> getProperty() {
		return property;
	}

	@MethodAnnotation2
	public void setProperty(Map<List<Integer>, List<Long>> property) {
		this.property = property;
	}

	@MethodAnnotation3
	private Map<List<Integer>, List<Long>> property;

	@Target({ElementType.METHOD})
	@Retention(RetentionPolicy.RUNTIME)
	public @interface MethodAnnotation1 {

	}

	@Target({ElementType.METHOD})
	@Retention(RetentionPolicy.RUNTIME)
	public @interface MethodAnnotation2 {

	}

	@Target({ElementType.FIELD})
	@Retention(RetentionPolicy.RUNTIME)
	public @interface MethodAnnotation3 {

	}

	@Test
	public void fieldScalar() throws Exception {
		TypeDescriptor typeDescriptor = new TypeDescriptor(getClass().getField("fieldScalar"));
		assertFalse(typeDescriptor.isPrimitive());
		assertFalse(typeDescriptor.isArray());
		assertFalse(typeDescriptor.isCollection());
		assertFalse(typeDescriptor.isMap());
		assertEquals(Integer.class, typeDescriptor.getType());
		assertEquals(Integer.class, typeDescriptor.getObjectType());
	}

	public Integer fieldScalar;

	@Test
	public void fieldList() throws Exception {
		TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("listOfString"));
		assertFalse(typeDescriptor.isArray());
		assertEquals(List.class, typeDescriptor.getType());
		assertEquals(String.class, typeDescriptor.getElementTypeDescriptor().getType());
		assertEquals("java.util.List<java.lang.String>", typeDescriptor.toString());
	}

	@Test
	public void fieldListOfListOfString() throws Exception {
		TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("listOfListOfString"));
		assertFalse(typeDescriptor.isArray());
		assertEquals(List.class, typeDescriptor.getType());
		assertEquals(List.class, typeDescriptor.getElementTypeDescriptor().getType());
		assertEquals(String.class, typeDescriptor.getElementTypeDescriptor().getElementTypeDescriptor().getType());
		assertEquals("java.util.List<java.util.List<java.lang.String>>", typeDescriptor.toString());
	}

	@Test
	public void fieldListOfListUnknown() throws Exception {
		TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("listOfListOfUnknown"));
		assertFalse(typeDescriptor.isArray());
		assertEquals(List.class, typeDescriptor.getType());
		assertEquals(List.class, typeDescriptor.getElementTypeDescriptor().getType());
		assertNull(typeDescriptor.getElementTypeDescriptor().getElementTypeDescriptor());
		assertEquals("java.util.List<java.util.List<?>>", typeDescriptor.toString());
	}

	@Test
	public void fieldArray() throws Exception {
		TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("intArray"));
		assertTrue(typeDescriptor.isArray());
		assertEquals(Integer.TYPE,typeDescriptor.getElementTypeDescriptor().getType());
		assertEquals("int[]",typeDescriptor.toString());
	}

	@Test
	public void fieldComplexTypeDescriptor() throws Exception {
		TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("arrayOfListOfString"));
		assertTrue(typeDescriptor.isArray());
		assertEquals(List.class,typeDescriptor.getElementTypeDescriptor().getType());
		assertEquals(String.class, typeDescriptor.getElementTypeDescriptor().getElementTypeDescriptor().getType());
		assertEquals("java.util.List<java.lang.String>[]",typeDescriptor.toString());
	}

	@Test
	public void fieldComplexTypeDescriptor2() throws Exception {
		TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("nestedMapField"));
		assertTrue(typeDescriptor.isMap());
		assertEquals(String.class,typeDescriptor.getMapKeyTypeDescriptor().getType());
		assertEquals(List.class, typeDescriptor.getMapValueTypeDescriptor().getType());
		assertEquals(Integer.class, typeDescriptor.getMapValueTypeDescriptor().getElementTypeDescriptor().getType());
		assertEquals("java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>", typeDescriptor.toString());
	}

	@Test
	public void fieldMap() throws Exception {
		TypeDescriptor desc = new TypeDescriptor(TypeDescriptorTests.class.getField("fieldMap"));
		assertTrue(desc.isMap());
		assertEquals(Integer.class, desc.getMapKeyTypeDescriptor().getElementTypeDescriptor().getType());
		assertEquals(Long.class, desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType());
	}

	public Map<List<Integer>, List<Long>> fieldMap;

	@Test
	public void fieldAnnotated() throws Exception {
		TypeDescriptor typeDescriptor = new TypeDescriptor(getClass().getField("fieldAnnotated"));
		assertEquals(1, typeDescriptor.getAnnotations().length);
		assertNotNull(typeDescriptor.getAnnotation(FieldAnnotation.class));
	}

	@FieldAnnotation
	public List<String> fieldAnnotated;

	@Target({ElementType.FIELD})
	@Retention(RetentionPolicy.RUNTIME)
	public @interface FieldAnnotation {

	}

	@Test
	public void valueOfScalar() {
		TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(Integer.class);
		assertFalse(typeDescriptor.isPrimitive());
		assertFalse(typeDescriptor.isArray());
		assertFalse(typeDescriptor.isCollection());
		assertFalse(typeDescriptor.isMap());
		assertEquals(Integer.class, typeDescriptor.getType());
		assertEquals(Integer.class, typeDescriptor.getObjectType());
	}

	@Test
	public void valueOfPrimitive() {
		TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(int.class);
		assertTrue(typeDescriptor.isPrimitive());
		assertFalse(typeDescriptor.isArray());
		assertFalse(typeDescriptor.isCollection());
		assertFalse(typeDescriptor.isMap());
		assertEquals(Integer.TYPE, typeDescriptor.getType());
		assertEquals(Integer.class, typeDescriptor.getObjectType());
	}

	@Test
	public void valueOfArray() throws Exception {
		TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(int[].class);
		assertTrue(typeDescriptor.isArray());
		assertFalse(typeDescriptor.isCollection());
		assertFalse(typeDescriptor.isMap());
		assertEquals(Integer.TYPE, typeDescriptor.getElementTypeDescriptor().getType());
	}

	@Test
	public void valueOfCollection() throws Exception {
		TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(Collection.class);
		assertTrue(typeDescriptor.isCollection());
		assertFalse(typeDescriptor.isArray());
		assertFalse(typeDescriptor.isMap());
		assertNull(typeDescriptor.getElementTypeDescriptor());
	}

	@Test
	public void forObject() {
		TypeDescriptor desc = TypeDescriptor.forObject("3");
		assertEquals(String.class, desc.getType());
	}

	@Test
	public void forObjectNullTypeDescriptor() {
		TypeDescriptor desc = TypeDescriptor.forObject(null);
		assertNull(desc);
	}

	@Test
	public void nestedMethodParameterType2Levels() throws Exception {
		TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test2", List.class), 0), 2);
		assertEquals(String.class, t1.getType());
	}

	@Test
	public void nestedMethodParameterTypeMap() throws Exception {
		TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test3", Map.class), 0), 1);
		assertEquals(String.class, t1.getType());
	}

	@Test
	public void nestedMethodParameterTypeMapTwoLevels() throws Exception {
		TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test4", List.class), 0), 2);
		assertEquals(String.class, t1.getType());
	}

	@Test(expected=IllegalArgumentException.class)
	public void nestedMethodParameterNot1NestedLevel() throws Exception {
		TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test4", List.class), 0, 2), 2);
	}

	@Test
	public void nestedTooManyLevels() throws Exception {
		TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test4", List.class), 0), 3);
		assertNull(t1);
	}

	@Test
	public void nestedMethodParameterTypeNotNestable() throws Exception {
		TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test5", String.class), 0), 2);
		assertNull(t1);
	}

	@Test(expected=IllegalArgumentException.class)
	public void nestedMethodParameterTypeInvalidNestingLevel() throws Exception {
		TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test5", String.class), 0, 2), 2);
	}

	public void test1(List<String> param1) {

	}

	public void test2(List<List<String>> param1) {

	}

	public void test3(Map<Integer, String> param1) {

	}

	public void test4(List<Map<Integer, String>> param1) {

	}

	public void test5(String param1) {

	}

	@Test
	public void nestedNotParameterized() throws Exception {
		TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test6", List.class), 0), 1);
		assertEquals(List.class,t1.getType());
		assertEquals("java.util.List<?>", t1.toString());
		TypeDescriptor t2 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test6", List.class), 0), 2);
		assertNull(t2);
	}

	public void test6(List<List> param1) {

	}

	@Test
	public void nestedFieldTypeMapTwoLevels() throws Exception {
		TypeDescriptor t1 = TypeDescriptor.nested(getClass().getField("test4"), 2);
		assertEquals(String.class, t1.getType());
	}

	public List<Map<Integer, String>> test4;

	@Test
	public void nestedPropertyTypeMapTwoLevels() throws Exception {
		Property property = new Property(getClass(), getClass().getMethod("getTest4"), getClass().getMethod("setTest4", List.class));
		TypeDescriptor t1 = TypeDescriptor.nested(property, 2);
		assertEquals(String.class, t1.getType());
	}

	public List<Map<Integer, String>> getTest4() {
		return null;
	}

	public void setTest4(List<Map<Integer, String>> test4) {

	}

	@Test
	public void collection() {
		TypeDescriptor desc = TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(Integer.class));
		assertEquals(List.class, desc.getType());
		assertEquals(List.class, desc.getObjectType());
		assertEquals("java.util.List", desc.getName());
		assertEquals("java.util.List<java.lang.Integer>", desc.toString());
		assertTrue(!desc.isPrimitive());
		assertEquals(0, desc.getAnnotations().length);
		assertTrue(desc.isCollection());
		assertFalse(desc.isArray());
		assertEquals(Integer.class, desc.getElementTypeDescriptor().getType());
		assertEquals(TypeDescriptor.valueOf(Integer.class), desc.getElementTypeDescriptor());
		assertFalse(desc.isMap());
	}

	@Test
	public void collectionNested() {
		TypeDescriptor desc = TypeDescriptor.collection(List.class, TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(Integer.class)));
		assertEquals(List.class, desc.getType());
		assertEquals(List.class, desc.getObjectType());
		assertEquals("java.util.List", desc.getName());
		assertEquals("java.util.List<java.util.List<java.lang.Integer>>", desc.toString());
		assertTrue(!desc.isPrimitive());
		assertEquals(0, desc.getAnnotations().length);
		assertTrue(desc.isCollection());
		assertFalse(desc.isArray());
		assertEquals(List.class, desc.getElementTypeDescriptor().getType());
		assertEquals(TypeDescriptor.valueOf(Integer.class), desc.getElementTypeDescriptor().getElementTypeDescriptor());
		assertFalse(desc.isMap());
	}

	@Test
	public void map() {
		TypeDescriptor desc = TypeDescriptor.map(Map.class, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class));
		assertEquals(Map.class, desc.getType());
		assertEquals(Map.class, desc.getObjectType());
		assertEquals("java.util.Map", desc.getName());
		assertEquals("java.util.Map<java.lang.String, java.lang.Integer>", desc.toString());
		assertTrue(!desc.isPrimitive());
		assertEquals(0, desc.getAnnotations().length);
		assertFalse(desc.isCollection());
		assertFalse(desc.isArray());
		assertTrue(desc.isMap());
		assertEquals(String.class, desc.getMapKeyTypeDescriptor().getType());
		assertEquals(Integer.class, desc.getMapValueTypeDescriptor().getType());
	}

	@Test
	public void mapNested() {
		TypeDescriptor desc = TypeDescriptor.map(Map.class, TypeDescriptor.valueOf(String.class),
				TypeDescriptor.map(Map.class, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class)));
		assertEquals(Map.class, desc.getType());
		assertEquals(Map.class, desc.getObjectType());
		assertEquals("java.util.Map", desc.getName());
		assertEquals("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.lang.Integer>>", desc.toString());
		assertTrue(!desc.isPrimitive());
		assertEquals(0, desc.getAnnotations().length);
		assertFalse(desc.isCollection());
		assertFalse(desc.isArray());
		assertTrue(desc.isMap());
		assertEquals(String.class, desc.getMapKeyTypeDescriptor().getType());
		assertEquals(String.class, desc.getMapValueTypeDescriptor().getMapKeyTypeDescriptor().getType());
		assertEquals(Integer.class, desc.getMapValueTypeDescriptor().getMapValueTypeDescriptor().getType());
	}

	@Test
	public void narrow() {
		TypeDescriptor desc = TypeDescriptor.valueOf(Number.class);
		Integer value = new Integer(3);
		desc = desc.narrow(value);
		assertEquals(Integer.class, desc.getType());
	}

	@Test
	public void elementType() {
		TypeDescriptor desc = TypeDescriptor.valueOf(List.class);
		Integer value = new Integer(3);
		desc = desc.elementTypeDescriptor(value);
		assertEquals(Integer.class, desc.getType());
	}

	@Test
	public void elementTypePreserveContext() throws Exception {
		TypeDescriptor desc = new TypeDescriptor(getClass().getField("listPreserveContext"));
		assertEquals(Integer.class, desc.getElementTypeDescriptor().getElementTypeDescriptor().getType());
		List<Integer> value = new ArrayList<Integer>(3);
		desc = desc.elementTypeDescriptor(value);
		assertEquals(Integer.class, desc.getElementTypeDescriptor().getType());
		assertNotNull(desc.getAnnotation(FieldAnnotation.class));
	}

	@FieldAnnotation
	public List<List<Integer>> listPreserveContext;

	@Test
	public void mapKeyType() {
		TypeDescriptor desc = TypeDescriptor.valueOf(Map.class);
		Integer value = new Integer(3);
		desc = desc.getMapKeyTypeDescriptor(value);
		assertEquals(Integer.class, desc.getType());
	}

	@Test
	public void mapKeyTypePreserveContext() throws Exception {
		TypeDescriptor desc = new TypeDescriptor(getClass().getField("mapPreserveContext"));
		assertEquals(Integer.class, desc.getMapKeyTypeDescriptor().getElementTypeDescriptor().getType());
		List<Integer> value = new ArrayList<Integer>(3);
		desc = desc.getMapKeyTypeDescriptor(value);
		assertEquals(Integer.class, desc.getElementTypeDescriptor().getType());
		assertNotNull(desc.getAnnotation(FieldAnnotation.class));
	}

	@FieldAnnotation
	public Map<List<Integer>, List<Integer>> mapPreserveContext;

	@Test
	public void mapValueType() {
		TypeDescriptor desc = TypeDescriptor.valueOf(Map.class);
		Integer value = new Integer(3);
		desc = desc.getMapValueTypeDescriptor(value);
		assertEquals(Integer.class, desc.getType());
	}

	@Test
	public void mapValueTypePreserveContext() throws Exception {
		TypeDescriptor desc = new TypeDescriptor(getClass().getField("mapPreserveContext"));
		assertEquals(Integer.class, desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType());
		List<Integer> value = new ArrayList<Integer>(3);
		desc = desc.getMapValueTypeDescriptor(value);
		assertEquals(Integer.class, desc.getElementTypeDescriptor().getType());
		assertNotNull(desc.getAnnotation(FieldAnnotation.class));
	}

	@Test
	public void equals() throws Exception {
		TypeDescriptor t1 = TypeDescriptor.valueOf(String.class);
		TypeDescriptor t2 = TypeDescriptor.valueOf(String.class);
		TypeDescriptor t3 = TypeDescriptor.valueOf(Date.class);
		TypeDescriptor t4 = TypeDescriptor.valueOf(Date.class);
		TypeDescriptor t5 = TypeDescriptor.valueOf(List.class);
		TypeDescriptor t6 = TypeDescriptor.valueOf(List.class);
		TypeDescriptor t7 = TypeDescriptor.valueOf(Map.class);
		TypeDescriptor t8 = TypeDescriptor.valueOf(Map.class);
		assertEquals(t1, t2);
		assertEquals(t3, t4);
		assertEquals(t5, t6);
		assertEquals(t7, t8);

		TypeDescriptor t9 = new TypeDescriptor(getClass().getField("listField"));
		TypeDescriptor t10 = new TypeDescriptor(getClass().getField("listField"));
		assertEquals(t9, t10);

		TypeDescriptor t11 = new TypeDescriptor(getClass().getField("mapField"));
		TypeDescriptor t12 = new TypeDescriptor(getClass().getField("mapField"));
		assertEquals(t11, t12);
	}

	@Test
	public void isAssignableTypes() {
		assertTrue(TypeDescriptor.valueOf(Integer.class).isAssignableTo(TypeDescriptor.valueOf(Number.class)));
		assertFalse(TypeDescriptor.valueOf(Number.class).isAssignableTo(TypeDescriptor.valueOf(Integer.class)));
		assertFalse(TypeDescriptor.valueOf(String.class).isAssignableTo(TypeDescriptor.valueOf(String[].class)));
	}

	@Test
	public void isAssignableElementTypes() throws Exception {
		assertTrue(new TypeDescriptor(getClass().getField("listField")).isAssignableTo(new TypeDescriptor(getClass().getField("listField"))));
		assertTrue(new TypeDescriptor(getClass().getField("notGenericList")).isAssignableTo(new TypeDescriptor(getClass().getField("listField"))));
		assertTrue(new TypeDescriptor(getClass().getField("listField")).isAssignableTo(new TypeDescriptor(getClass().getField("notGenericList"))));
		assertFalse(new TypeDescriptor(getClass().getField("isAssignableElementTypes")).isAssignableTo(new TypeDescriptor(getClass().getField("listField"))));
		assertTrue(TypeDescriptor.valueOf(List.class).isAssignableTo(new TypeDescriptor(getClass().getField("listField"))));
	}

	public List notGenericList;

	public List<Number> isAssignableElementTypes;

	@Test
	public void isAssignableMapKeyValueTypes() throws Exception {
		assertTrue(new TypeDescriptor(getClass().getField("mapField")).isAssignableTo(new TypeDescriptor(getClass().getField("mapField"))));
		assertTrue(new TypeDescriptor(getClass().getField("notGenericMap")).isAssignableTo(new TypeDescriptor(getClass().getField("mapField"))));
		assertTrue(new TypeDescriptor(getClass().getField("mapField")).isAssignableTo(new TypeDescriptor(getClass().getField("notGenericMap"))));
		assertFalse(new TypeDescriptor(getClass().getField("isAssignableMapKeyValueTypes")).isAssignableTo(new TypeDescriptor(getClass().getField("mapField"))));
		assertTrue(TypeDescriptor.valueOf(Map.class).isAssignableTo(new TypeDescriptor(getClass().getField("mapField"))));
	}

	public Map notGenericMap;

	public Map<CharSequence, Number> isAssignableMapKeyValueTypes;

	@Test
	public void multiValueMap() throws Exception {
		TypeDescriptor td = new TypeDescriptor(getClass().getField("multiValueMap"));
		assertTrue(td.isMap());
		assertEquals(String.class, td.getMapKeyTypeDescriptor().getType());
		assertEquals(List.class, td.getMapValueTypeDescriptor().getType());
		assertEquals(Integer.class,
				td.getMapValueTypeDescriptor().getElementTypeDescriptor().getType());
	}

	public MultiValueMap<String, Integer> multiValueMap = new LinkedMultiValueMap<String, Integer>();

	@Test
	public void passDownGeneric() throws Exception {
		TypeDescriptor td = new TypeDescriptor(getClass().getField("passDownGeneric"));
		assertEquals(List.class, td.getElementTypeDescriptor().getType());
		assertEquals(Set.class, td.getElementTypeDescriptor().getElementTypeDescriptor().getType());
		assertEquals(Integer.class, td.getElementTypeDescriptor().getElementTypeDescriptor().getElementTypeDescriptor().getType());
	}

	public PassDownGeneric<Integer> passDownGeneric = new PassDownGeneric<Integer>();

	@SuppressWarnings("serial")
	public static class PassDownGeneric<T> extends ArrayList<List<Set<T>>> {
	}

	@Test
	public void testUpCast() throws Exception {
		Property property = new Property(getClass(), getClass().getMethod("getProperty"),
				getClass().getMethod("setProperty", Map.class));
		TypeDescriptor typeDescriptor = new TypeDescriptor(property);
		TypeDescriptor upCast = typeDescriptor.upcast(Object.class);
		assertTrue(upCast.getAnnotation(MethodAnnotation1.class) != null);
	}

	@Test
	public void testUpCastNotSuper() throws Exception {
		Property property = new Property(getClass(), getClass().getMethod("getProperty"),
				getClass().getMethod("setProperty", Map.class));
		TypeDescriptor typeDescriptor = new TypeDescriptor(property);
		try {
			typeDescriptor.upcast(Collection.class);
			fail("Did not throw");
		} catch(IllegalArgumentException e) {
			assertEquals("interface java.util.Map is not assignable to interface java.util.Collection", e.getMessage());
		}
	}

	@Test
	public void elementTypeForCollectionSubclass() throws Exception {
		@SuppressWarnings("serial")
		class CustomSet extends HashSet<String> {
		}

		assertEquals(TypeDescriptor.valueOf(CustomSet.class).getElementTypeDescriptor(), TypeDescriptor.valueOf(String.class));
		assertEquals(TypeDescriptor.forObject(new CustomSet()).getElementTypeDescriptor(), TypeDescriptor.valueOf(String.class));
	}

	@Test
	public void elementTypeForMapSubclass() throws Exception {
		@SuppressWarnings("serial")
		class CustomMap extends HashMap<String, Integer> {
		}

		assertEquals(TypeDescriptor.valueOf(CustomMap.class).getMapKeyTypeDescriptor(), TypeDescriptor.valueOf(String.class));
		assertEquals(TypeDescriptor.valueOf(CustomMap.class).getMapValueTypeDescriptor(), TypeDescriptor.valueOf(Integer.class));
		assertEquals(TypeDescriptor.forObject(new CustomMap()).getMapKeyTypeDescriptor(), TypeDescriptor.valueOf(String.class));
		assertEquals(TypeDescriptor.forObject(new CustomMap()).getMapValueTypeDescriptor(), TypeDescriptor.valueOf(Integer.class));
	}

	@Test
	public void createMapArray() throws Exception {
		TypeDescriptor mapType = TypeDescriptor.map(LinkedHashMap.class, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class));
		TypeDescriptor arrayType = TypeDescriptor.array(mapType);
		assertEquals(arrayType.getType(), LinkedHashMap[].class);
		assertEquals(arrayType.getElementTypeDescriptor(), mapType);
	}

	@Test
	public void createStringArray() throws Exception {
		TypeDescriptor arrayType = TypeDescriptor.array(TypeDescriptor.valueOf(String.class));
		assertEquals(arrayType, TypeDescriptor.valueOf(String[].class));
	}

	@Test
	public void createNullArray() throws Exception {
		assertNull(TypeDescriptor.array(null));
	}

	@Test
	public void serializable() throws Exception {
		TypeDescriptor typeDescriptor = TypeDescriptor.forObject("");
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ObjectOutputStream outputStream = new ObjectOutputStream(out);
		outputStream.writeObject(typeDescriptor);
		ObjectInputStream inputStream = new ObjectInputStream(new ByteArrayInputStream(
				out.toByteArray()));
		TypeDescriptor readObject = (TypeDescriptor) inputStream.readObject();
		assertThat(readObject, equalTo(typeDescriptor));
	}

	@Test
	public void createCollectionWithNullElement() throws Exception {
		TypeDescriptor typeDescriptor = TypeDescriptor.collection(List.class, null);
		assertThat(typeDescriptor.getElementTypeDescriptor(), nullValue());
	}

	@Test
	public void createMapWithNullElements() throws Exception {
		TypeDescriptor typeDescriptor = TypeDescriptor.map(LinkedHashMap.class, null, null);
		assertThat(typeDescriptor.getMapKeyTypeDescriptor(), nullValue());
		assertThat(typeDescriptor.getMapValueTypeDescriptor(), nullValue());
	}

	@Test
	public void getSource() throws Exception {
		Field field = getClass().getField("fieldScalar");
		MethodParameter methodParameter = new MethodParameter(getClass().getMethod("testParameterPrimitive", int.class), 0);
		assertThat(new TypeDescriptor(field).getSource(), equalTo((Object) field));
		assertThat(new TypeDescriptor(methodParameter).getSource(), equalTo((Object) methodParameter));
		assertThat(TypeDescriptor.valueOf(Integer.class).getSource(), equalTo((Object) Integer.class));
	}

}


text:
title: Co-Working Session
text: Come work on your coding projects with us, and feel free to ask for help and feedback! All languages, disciplines and skill levels welcome.
location: Koerner Library, Room 153
link: https://github.com/minisciencegirl/studyGroup/issues/114
date: 2016-08-26
startTime: '13:00'
endTime: '14:00'
---


text:
namespace ErlSharp.Tests.Language
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using ErlSharp.Expressions;
    using ErlSharp.Language;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class FunctionTests
    {
        [TestMethod]
        public void EvaluateConstantBody()
        {
            Function function = new Function(null, new object[] { }, new ConstantExpression(1));

            Assert.AreEqual(1, function.Evaluate(null));
        }

        [TestMethod]
        public void EvaluateExpressionBody()
        {
            Function function = new Function(null, new object[] { }, new AddExpression(new VariableExpression(new Variable("X")), new VariableExpression(new Variable("Y"))));
            Context context = new Context();
            context.SetValue("X", 1);
            context.SetValue("Y", 2);

            Assert.AreEqual(3, function.Evaluate(context));
        }

        [TestMethod]
        public void MakeContextAndEvaluateExpressionBody()
        {
            Function function = new Function(null, new object[] { new Variable("X"), new Variable("Y") }, new AddExpression(new VariableExpression(new Variable("X")), new VariableExpression(new Variable("Y"))));

            Context context = function.MakeContext(new object[] { 1, 2 });

            Assert.IsNotNull(context);
            Assert.AreEqual(1, context.GetValue("X"));
            Assert.AreEqual(2, context.GetValue("Y"));

            Assert.AreEqual(3, function.Evaluate(context));
        }

        [TestMethod]
        public void CannotMakeContextByArity()
        {
            Function function = new Function(null, new object[] { new Variable("X"), new Variable("Y") }, new AddExpression(new VariableExpression(new Variable("X")), new VariableExpression(new Variable("Y"))));

            Context context = function.MakeContext(new object[] { 1, 2, 3 });

            Assert.IsNull(context);
        }

        [TestMethod]
        public void CannotMakeContextByNoMatch()
        {
            Function function = new Function(null, new object[] { new Variable("X"), new Variable("X") }, new AddExpression(new VariableExpression(new Variable("X")), new VariableExpression(new Variable("X"))));

            Context context = function.MakeContext(new object[] { 1, 2 });

            Assert.IsNull(context);
        }
    }
}


text:
/*
 Erica Sadun, http://ericasadun.com
 iPhone Developer's Cookbook, 3.0 Edition
 BSD License, Use at your own risk
 */

//获取物理设备的高度
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
//获取物理设备的宽度
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ScreenViewHeight (ScreenHeight-64)

#import <UIKit/UIKit.h>

CGPoint CGRectGetCenter(CGRect rect);
CGRect  CGRectMoveToCenter(CGRect rect, CGPoint center);

@interface UIView (ViewFrameGeometry)
@property CGPoint origin;
@property CGSize size;

@property (readonly) CGPoint bottomLeft;
@property (readonly) CGPoint bottomRight;
@property (readonly) CGPoint topRight;

@property CGFloat height;
@property CGFloat width;

@property CGFloat top;
@property CGFloat left;

@property CGFloat bottom;
@property CGFloat right;

- (void) moveBy: (CGPoint) delta;
- (void) scaleBy: (CGFloat) scaleFactor;
- (void) fitInSize: (CGSize) aSize;

-(void)addSeperateLineWithRowCount:(NSInteger)rowCount andIsAlignment:(BOOL)isAlignment;

@end


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace DLINQSearchIndexer
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
    }
}


text:
module Lint
  class Application < Lotus::Application
    configure do
      routes do
        get '/',      to: 'home#index'
        get '/greet', to: 'home#greet'
      end
    end

    load!
  end

  module Controllers::Home
    class Index
      include Lint::Action

      def call(params)
      end
    end

    class Greet
      include Lint::Action

      def call(params)
        self.body = 'Hello'
      end
    end
  end

  module Views::Home
    class Index
      include Lint::View

      def render
        'View'
      end
    end
  end
end


text:
namespace Google.Cloud.Retail.V2.Snippets
{
    // [START retail_v2_generated_CatalogService_SetDefaultBranch_async_flattened_resourceNames]
    using Google.Cloud.Retail.V2;
    using System.Threading.Tasks;

    public sealed partial class GeneratedCatalogServiceClientSnippets
    {
        /// <summary>Snippet for SetDefaultBranchAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task SetDefaultBranchResourceNamesAsync()
        {
            // Create client
            CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync();
            // Initialize request argument(s)
            CatalogName catalog = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]");
            // Make the request
            await catalogServiceClient.SetDefaultBranchAsync(catalog);
        }
    }
    // [END retail_v2_generated_CatalogService_SetDefaultBranch_async_flattened_resourceNames]
}


text:
#ifndef BYTE_STREAM_OUT_NIL_H
#define BYTE_STREAM_OUT_NIL_H

#include "bytestreamout.hpp"

#include <stdio.h>

class ByteStreamOutNil : public ByteStreamOut
{
public:
  ByteStreamOutNil();
/* write a single byte                                       */
  BOOL putByte(U8 byte);
/* write an array of bytes                                   */
  BOOL putBytes(const U8* bytes, U32 num_bytes);
/* write 16 bit low-endian field                             */
  BOOL put16bitsLE(const U8* bytes);
/* write 32 bit low-endian field                             */
  BOOL put32bitsLE(const U8* bytes);
/* write 64 bit low-endian field                             */
  BOOL put64bitsLE(const U8* bytes);
/* write 16 bit big-endian field                             */
  BOOL put16bitsBE(const U8* bytes);
/* write 32 bit big-endian field                             */
  BOOL put32bitsBE(const U8* bytes);
/* write 64 bit big-endian field                             */
  BOOL put64bitsBE(const U8* bytes);
/* is the stream seekable (e.g. standard out is not)         */
  BOOL isSeekable() const;
/* get current position of stream                            */
  I64 tell() const;
/* seek to this position in the stream                       */
  BOOL seek(const I64 position);
/* seek to the end of the file                               */
  BOOL seekEnd();
/* destructor                                                */
  ~ByteStreamOutNil(){};
private:
  I64 num_bytes;
};

inline ByteStreamOutNil::ByteStreamOutNil()
{
  num_bytes = 0;
}

inline BOOL ByteStreamOutNil::putByte(U8 byte)
{
  num_bytes++;
  return TRUE;
}

inline BOOL ByteStreamOutNil::putBytes(const U8* bytes, U32 num_bytes)
{
  this->num_bytes += num_bytes;
  return TRUE;
}

inline BOOL ByteStreamOutNil::put16bitsLE(const U8* bytes)
{
  return putBytes(bytes, 2);
}

inline BOOL ByteStreamOutNil::put32bitsLE(const U8* bytes)
{
  return putBytes(bytes, 4);
}

inline BOOL ByteStreamOutNil::put64bitsLE(const U8* bytes)
{
  return putBytes(bytes, 8);
}

inline BOOL ByteStreamOutNil::put16bitsBE(const U8* bytes)
{
  return putBytes(bytes, 2);
}

inline BOOL ByteStreamOutNil::put32bitsBE(const U8* bytes)
{
  return putBytes(bytes, 4);
}

inline BOOL ByteStreamOutNil::put64bitsBE(const U8* bytes)
{
  return putBytes(bytes, 8);
}

inline BOOL ByteStreamOutNil::isSeekable() const
{
  return TRUE;
}

inline I64 ByteStreamOutNil::tell() const
{
  return num_bytes;
}

inline BOOL ByteStreamOutNil::seek(I64 position)
{
  return TRUE;
}

inline BOOL ByteStreamOutNil::seekEnd()
{
  return TRUE;
}

#endif


text:
@implementation NSString(Path)

- (void) createFilePathStructure
{
    BOOL isDirectory = NO;
    if (![[NSFileManager defaultManager] fileExistsAtPath:self isDirectory:&isDirectory])
    {
        NSError *error = nil;
        [[NSFileManager defaultManager] createDirectoryAtPath:self withIntermediateDirectories:YES attributes:nil error:&error];
        [error release];
    }
}

@end


text:
package com.example.animation.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bm.library.PhotoView;
import com.bumptech.glide.Glide;
import com.example.animation.R;

import java.io.File;
import java.util.List;

/**
 * Created by 刘通 on 2018/3/14.
 */

public class DownloadPageAdapter extends PagerAdapter {

    private List<String> urls;
    private Context context;

    public DownloadPageAdapter(List<String> urls,Context context){
        this.urls = urls;
        this.context = context;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = LayoutInflater.from(container.getContext()).inflate(R.layout.cosplay_image_item,container,false);
        PhotoView photoView = (PhotoView) view.findViewById(R.id.cosplay_image_item_pv);
        photoView.enable();
        Glide.with(context).load(new File(urls.get(position))).into(photoView);
        container.addView(view);
        return view;
    }

    @Override
    public int getCount() {
        return urls.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        View view =(View) object;
        container.removeView(view);
    }
}


text:
namespace Serenity
{
    using jQueryApi;
    using System;
    using System.Html;
    using System.Runtime.CompilerServices;

    public class PopupToolButton : PopupMenuButton
    {
        public PopupToolButton(jQueryObject div, PopupToolButtonOptions opt)
            : base(div, opt)
        {
            div.AddClass("s-PopupToolButton");
            J("<b/>").AppendTo(div.Children(".button-outer").Children("span"));
        }
    }

    [Imported, Serializable]
    public class PopupToolButtonOptions : PopupMenuButtonOptions
    {
    }
}


text:
from markupsafe import escape

def run():
    string = 'Hello World!' * 1000
    escape(string)


text:
import * as builder from 'botbuilder';

/** Options used to configure an IQnAMakerOptions. */
export interface IQnAMakerOptions {
    /** (Optional) minimum score needed to trigger the response. The default value is 0.3 */
    qnaThreshold?: number;

    /** The QnA Maker Knowledge Base ID to query for getting the response. */
    knowledgeBaseId: string;

    /** User's QnA Maker Subscription Key for authorization. */
    subscriptionKey: string;

    /** (Optional) message that is returned when there are no responses above the threshold. The default is 'No match found!'. */
    defaultMessage?: string;

    /** (Optional) maximum number of answers from the QnA Maker service. */
    Top?: number;

    /** And instance of dialog library which includes the feedback flow. This should be set if Top > 1. */
    feedbackLib?: QnAMakerTools;
}

/** Result returned by an QnA Maker recognizer. */
export interface IQnAMakerResult{
    /** Answer text of the matched QnA. */
    answer: string;

    /** Array of questions and alternate phrases of the matched QnA. */
    questions: string[];

    /**  The confidence score from QnA Maker service for the matched QnA. */
    score: number;
}

/** Response returned by QnA Maker recognizer. */
export interface IQnAMakerResult extends builder.IIntentRecognizerResult {
    /** List of top matched QnA with score greater than the specified threshold. */
    answers: IQnAMakerResult[];
}

/**
* QnA Maker recognizer plugin fetches answers for users utterances using [QnA Maker](https://qnamaker.ai)
* @param options used to initialize the recognizer.
*/
export class QnAMakerRecognizer implements builder.IIntentRecognizer {
    /**
    * Constructs a new instance of the recognizer.
    * @param options used to initialize the recognizer.
    */
    constructor(options: IQnAMakerOptions);

    /** Attempts to match a users text utterance and retrieves the best matching answer. */
    public recognize(context: builder.IRecognizeContext, cb: (error: Error, result: IQnAMakerResult) => void): void;

    /**
    * Calls QnA Maker to retrieve answers for users utterances.
    * @param utterance The text to pass to QnA Maker for recognition.
    * @param kbUrl URI for QnA Maker knowledge base hosted on https://qnamaker.ai.
    * @param ocpApimSubscriptionKey The subscription key of the user to access knowledge bases on https://qnamaker.ai.
    * @param callback Callback to invoke with the results of the QnA Maker recognition step.
    * @param callback.err Error that occured during the recognition step.
    * @param callback.result the qna maker result that were recognized.
    */
    static recognize(utterance: string, kbUrl: string, ocpApimSubscriptionKey: string, callback: (error: Error, result?: IQnAMakerResult) => void): void;
}

/** Fetches the best matching answer response from QnA Maker's Knowledge Base. */
export class QnAMakerDialog extends builder.Dialog {
    /**
    * Constructs a new instance of an QnAMakerDialog.
    * @param options used to initialize the dialog.
    */
    constructor(options: IQnAMakerOptions);

    /**
    * Processes messages received from the user. Called by the dialog system.
    * @param session Session object for the current conversation.
    * @param recognizeResult (Optional) recognition results returned from a prior call to the dialogs [recognize()](#recognize) method.
    */
    replyReceived(session: builder.Session, recognizeResult?: builder.IIntentRecognizerResult): void;

    /** Attempts to find an answer to users text utterance from QnA Maker knowledge base. */
    recognize(context: builder.IRecognizeContext, cb: (error: Error, result: IQnAMakerResult) => void): void;

    /**
     * Adds a new recognizer plugin to the QnA Maker dialog.
     * @param plugin The recognizer to add.
     */
    recognizer(plugin: builder.IIntentRecognizer): QnAMakerDialog;

    /**
     *
     * @param session Session object for the current conversation.
     * @param qnaMakerResult QnA Maker response from the service.
     */
    qnaFeedbackStep(session: builder.Session, qnaMakerResult: IQnAMakerResults): void;

    /**
     * Processes the QnA Maker result and returns true when the top answer is very confident
     * @param qnaMakerResult QnA Maker response from the service.
     */
    isConfidentAnswer(qnaMakerResult: IQnAMakerResults): boolean;

    /**
     * Default wait method the service calls after responding to the received text.
     * @param session Session object for the current conversation.
     * @param qnaMakerResult QnA Maker response from the service.
     */
    defaultWaitNextMessage(session: builder.Session, qnaMakerResult: IQnAMakerResults): void;

    /**
     * Sends the message from the bot based on the result from QnA Maker.
     * @param session Session object for the current conversation.
     * @param qnaMakerResult QnA Maker response from the service.
     */
    respondFromQnAMakerResult(session: builder.Session, qnaMakerResult: IQnAMakerResults): void;
}

/**
 * Dialog library which includes the feedback flow when there are more than 1 good match
 * This should be set if Top > 1.
 */
export class QnAMakerTools{
    /**
     * Constructs a new instance of QnAMakerTools
     */
    constructor();

    /**
     * Returns the dialog library including the feedback dialog.
     */
    public createLibrary(): builder.Library;

    /**
     * Starts the new dialog to select the best match from top N QnA Maker responses
     * @param session Session object for the current conversation.
     * @param qnaMakerResult QnA Maker response from the service.
     */
    public answerSelector(session: builder.Session, qnaMakerResult: IQnAMakerResults): void;
}