text:
/**
 * @file fastmks_test.cpp
 * @author Ryan Curtin
 *
 * Ensure that fast max-kernel search is correct.
 */
#include <mlpack/core.hpp>
#include <mlpack/methods/fastmks/fastmks.hpp>
#include <mlpack/methods/fastmks/fastmks_model.hpp>

#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
#include "serialization.hpp"

using namespace mlpack;
using namespace mlpack::tree;
using namespace mlpack::fastmks;
using namespace mlpack::kernel;
using namespace mlpack::metric;

BOOST_AUTO_TEST_SUITE(FastMKSTest);

/**
 * Compare single-tree and naive.
 */
BOOST_AUTO_TEST_CASE(SingleTreeVsNaive)
{
  // First create a random dataset.
  arma::mat data;
  data.randn(5, 1000);
  LinearKernel lk;

  // Now run FastMKS naively.
  FastMKS<LinearKernel> naive(data, lk, false, true);

  arma::Mat<size_t> naiveIndices;
  arma::mat naiveProducts;
  naive.Search(10, naiveIndices, naiveProducts);

  // Now run it in single-tree mode.
  FastMKS<LinearKernel> single(data, lk, true);

  arma::Mat<size_t> singleIndices;
  arma::mat singleProducts;
  single.Search(10, singleIndices, singleProducts);

  // Compare the results.
  for (size_t q = 0; q < singleIndices.n_cols; ++q)
  {
    for (size_t r = 0; r < singleIndices.n_rows; ++r)
    {
      BOOST_REQUIRE_EQUAL(singleIndices(r, q), naiveIndices(r, q));
      BOOST_REQUIRE_CLOSE(singleProducts(r, q), naiveProducts(r, q), 1e-5);
    }
  }
}

/**
 * Compare dual-tree and naive.
 */
BOOST_AUTO_TEST_CASE(DualTreeVsNaive)
{
  // First create a random dataset.
  arma::mat data;
  data.randn(10, 5000);
  LinearKernel lk;

  // Now run FastMKS naively.
  FastMKS<LinearKernel> naive(data, lk, false, true);

  arma::Mat<size_t> naiveIndices;
  arma::mat naiveProducts;
  naive.Search(10, naiveIndices, naiveProducts);

  // Now run it in dual-tree mode.
  FastMKS<LinearKernel> tree(data, lk);

  arma::Mat<size_t> treeIndices;
  arma::mat treeProducts;
  tree.Search(10, treeIndices, treeProducts);

  for (size_t q = 0; q < treeIndices.n_cols; ++q)
  {
    for (size_t r = 0; r < treeIndices.n_rows; ++r)
    {
      BOOST_REQUIRE_EQUAL(treeIndices(r, q), naiveIndices(r, q));
      BOOST_REQUIRE_CLOSE(treeProducts(r, q), naiveProducts(r, q), 1e-5);
    }
  }
}

/**
 * Compare dual-tree and single-tree on a larger dataset.
 */
BOOST_AUTO_TEST_CASE(DualTreeVsSingleTree)
{
  // First create a random dataset.
  arma::mat data;
  data.randu(8, 5000);
  PolynomialKernel pk(5.0, 2.5);

  FastMKS<PolynomialKernel> single(data, pk, true);

  arma::Mat<size_t> singleIndices;
  arma::mat singleProducts;
  single.Search(10, singleIndices, singleProducts);

  // Now run it in dual-tree mode.
  FastMKS<PolynomialKernel> tree(data, pk);

  arma::Mat<size_t> treeIndices;
  arma::mat treeProducts;
  tree.Search(10, treeIndices, treeProducts);

  for (size_t q = 0; q < treeIndices.n_cols; ++q)
  {
    for (size_t r = 0; r < treeIndices.n_rows; ++r)
    {
      BOOST_REQUIRE_EQUAL(treeIndices(r, q), singleIndices(r, q));
      BOOST_REQUIRE_CLOSE(treeProducts(r, q), singleProducts(r, q), 1e-5);
    }
  }
}

/**
 * Test sparse FastMKS (how useful is this, I'm not sure).
 */
BOOST_AUTO_TEST_CASE(SparseFastMKSTest)
{
  // First create a random sparse dataset.
  arma::sp_mat dataset;
  dataset.sprandu(10, 100, 0.3);

  FastMKS<LinearKernel, arma::sp_mat> sparsemks(dataset);

  arma::mat denseset(dataset);
  FastMKS<LinearKernel> densemks(denseset);

  // Store the results in these.
  arma::Mat<size_t> sparseIndices, denseIndices;
  arma::mat sparseKernels, denseKernels;

  // Do the searches.
  sparsemks.Search(3, sparseIndices, sparseKernels);
  densemks.Search(3, denseIndices, denseKernels);

  // Make sure the results are the same.
  for (size_t i = 0; i < sparseIndices.n_cols; ++i)
  {
    for (size_t j = 0; j < sparseIndices.n_rows; ++j)
    {
      if (std::abs(sparseKernels(j, i)) > 1e-15)
        BOOST_REQUIRE_CLOSE(sparseKernels(j, i), denseKernels(j, i), 1e-5);
      else
        BOOST_REQUIRE_SMALL(denseKernels(j, i), 1e-15);
      BOOST_REQUIRE_EQUAL(sparseIndices(j, i), denseIndices(j, i));
    }
  }
}

BOOST_AUTO_TEST_CASE(SparsePolynomialFastMKSTest)
{
  // Do it again with the polynomial kernel, just to be sure.
  arma::sp_mat dataset;
  dataset.sprandu(10, 100, 0.3);
  arma::mat denseset(dataset);

  PolynomialKernel pk(3);

  for (size_t i = 0; i < 100; ++i)
    for (size_t j = 0; j < 100; ++j)
      if (std::abs(pk.Evaluate(dataset.col(i), dataset.col(j))) < 1e-10)
        BOOST_REQUIRE_SMALL(pk.Evaluate(denseset.col(i), denseset.col(j)), 1e-10);
      else
        BOOST_REQUIRE_CLOSE(pk.Evaluate(dataset.col(i), dataset.col(j)),
                            pk.Evaluate(denseset.col(i), denseset.col(j)),
                            1e-5);

  FastMKS<PolynomialKernel, arma::sp_mat> sparsepoly(dataset);
  FastMKS<PolynomialKernel> densepoly(denseset);

  // Store the results in these.
  arma::Mat<size_t> sparseIndices, denseIndices;
  arma::mat sparseKernels, denseKernels;

  // Do the searches.
  sparsepoly.Search(3, sparseIndices, sparseKernels);
  densepoly.Search(3, denseIndices, denseKernels);

  // Make sure the results are the same.
  for (size_t i = 0; i < sparseIndices.n_cols; ++i)
  {
    for (size_t j = 0; j < sparseIndices.n_rows; ++j)
    {
      if (std::abs(sparseKernels(j, i)) > 1e-15)
        BOOST_REQUIRE_CLOSE(sparseKernels(j, i), denseKernels(j, i), 1e-5);
      else
        BOOST_REQUIRE_SMALL(denseKernels(j, i), 1e-15);
      BOOST_REQUIRE_EQUAL(sparseIndices(j, i), denseIndices(j, i));
    }
  }
}

// Make sure the empty constructor works.
BOOST_AUTO_TEST_CASE(EmptyConstructorTest)
{
  FastMKS<LinearKernel> f;

  arma::mat queryData = arma::randu<arma::mat>(5, 100);
  arma::Mat<size_t> indices;
  arma::mat products;
  BOOST_REQUIRE_THROW(f.Search(queryData, 3, indices, products),
      std::invalid_argument);
}

// Make sure the simplest overload of Train() works.
BOOST_AUTO_TEST_CASE(SimpleTrainTest)
{
  arma::mat referenceSet = arma::randu<arma::mat>(5, 100);

  FastMKS<LinearKernel> f(referenceSet);
  FastMKS<LinearKernel> f2;
  f2.Train(referenceSet);

  arma::Mat<size_t> indices, indices2;
  arma::mat products, products2;

  arma::mat querySet = arma::randu<arma::mat>(5, 20);

  f.Search(querySet, 3, indices, products);
  f2.Search(querySet, 3, indices2, products2);

  BOOST_REQUIRE_EQUAL(indices.n_rows, indices2.n_rows);
  BOOST_REQUIRE_EQUAL(products.n_rows, products2.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_cols, indices2.n_cols);
  BOOST_REQUIRE_EQUAL(products.n_cols, products2.n_cols);

  for (size_t i = 0; i < products.n_elem; ++i)
  {
    if (std::abs(products[i]) < 1e-5)
      BOOST_REQUIRE_SMALL(products2[i], 1e-5);
    else
      BOOST_REQUIRE_CLOSE(products[i], products2[i], 1e-5);

    BOOST_REQUIRE_EQUAL(indices[i], indices2[i]);
  }
}

// Test the Train() overload that takes a kernel too.
BOOST_AUTO_TEST_CASE(SimpleTrainKernelTest)
{
  arma::mat referenceSet = arma::randu<arma::mat>(5, 100);
  GaussianKernel gk(2.0);

  FastMKS<GaussianKernel> f(referenceSet, gk);
  FastMKS<GaussianKernel> f2;
  f2.Train(referenceSet, gk);

  arma::Mat<size_t> indices, indices2;
  arma::mat products, products2;

  arma::mat querySet = arma::randu<arma::mat>(5, 20);

  f.Search(querySet, 3, indices, products);
  f2.Search(querySet, 3, indices2, products2);

  BOOST_REQUIRE_EQUAL(indices.n_rows, indices2.n_rows);
  BOOST_REQUIRE_EQUAL(products.n_rows, products2.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_cols, indices2.n_cols);
  BOOST_REQUIRE_EQUAL(products.n_cols, products2.n_cols);

  for (size_t i = 0; i < products.n_elem; ++i)
  {
    if (std::abs(products[i]) < 1e-5)
      BOOST_REQUIRE_SMALL(products2[i], 1e-5);
    else
      BOOST_REQUIRE_CLOSE(products[i], products2[i], 1e-5);

    BOOST_REQUIRE_EQUAL(indices[i], indices2[i]);
  }
}

BOOST_AUTO_TEST_CASE(SerializationTest)
{
  arma::mat dataset = arma::randu<arma::mat>(5, 200);

  FastMKS<LinearKernel> f(dataset);

  FastMKS<LinearKernel> fXml, fText, fBinary;
  arma::mat otherDataset = arma::randu<arma::mat>(3, 10);
  fBinary.Train(otherDataset);

  SerializeObjectAll(f, fXml, fText, fBinary);

  arma::mat kernels, xmlKernels, textKernels, binaryKernels;
  arma::Mat<size_t> indices, xmlIndices, textIndices, binaryIndices;

  arma::mat querySet = arma::randu<arma::mat>(5, 100);

  f.Search(querySet, 5, indices, kernels);
  fXml.Search(querySet, 5, xmlIndices, xmlKernels);
  fText.Search(querySet, 5, textIndices, textKernels);
  fBinary.Search(querySet, 5, binaryIndices, binaryKernels);

  CheckMatrices(indices, xmlIndices, textIndices, binaryIndices);
  CheckMatrices(kernels, xmlKernels, textKernels, binaryKernels);
}

// Make sure that we get an exception if we try to build the wrong FastMKSModel.
BOOST_AUTO_TEST_CASE(FastMKSModelWrongModelTest)
{
  PolynomialKernel pk(2.0);
  arma::mat data = arma::randu<arma::mat>(5, 5);

  FastMKSModel m(FastMKSModel::LINEAR_KERNEL);
  BOOST_REQUIRE_THROW(m.BuildModel(data, pk, false, false, 2.0),
      std::invalid_argument);
}

// Test the linear kernel mode of the FastMKSModel.
BOOST_AUTO_TEST_CASE(FastMKSModelLinearTest)
{
  LinearKernel lk;
  arma::mat referenceData = arma::randu<arma::mat>(10, 100);

  FastMKS<LinearKernel> f(referenceData, lk);

  FastMKSModel m(FastMKSModel::LINEAR_KERNEL);
  FastMKSModel mNaive(FastMKSModel::LINEAR_KERNEL);
  FastMKSModel mSingle(FastMKSModel::LINEAR_KERNEL);

  m.BuildModel(referenceData, lk, false, false, 2.0);
  mNaive.BuildModel(referenceData, lk, false, true, 2.0);
  mSingle.BuildModel(referenceData, lk, true, false, 2.0);

  // Now search, first monochromatically.
  arma::Mat<size_t> indices, mIndices, mNaiveIndices, mSingleIndices;
  arma::mat kernels, mKernels, mNaiveKernels, mSingleKernels;

  f.Search(3, indices, kernels);
  m.Search(3, mIndices, mKernels);
  mNaive.Search(3, mNaiveIndices, mNaiveKernels);
  mSingle.Search(3, mSingleIndices, mSingleKernels);

  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);

  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);

  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);

  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);

  for (size_t i = 0; i < indices.n_elem; ++i)
  {
    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);

    if (std::abs(kernels[i]) < 1e-5)
    {
      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);
    }
    else
    {
      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);
    }
  }

  // Now test with a different query set.
  arma::mat querySet = arma::randu<arma::mat>(10, 50);

  f.Search(querySet, 3, indices, kernels);
  m.Search(querySet, 3, mIndices, mKernels, 2.0);
  mNaive.Search(querySet, 3, mNaiveIndices, mNaiveKernels, 2.0);
  mSingle.Search(querySet, 3, mSingleIndices, mSingleKernels, 2.0);

  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);

  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);

  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);

  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);

  for (size_t i = 0; i < indices.n_elem; ++i)
  {
    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);

    if (std::abs(kernels[i]) < 1e-5)
    {
      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);
    }
    else
    {
      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);
    }
  }
}

// Test the polynomial kernel mode of the FastMKSModel.
BOOST_AUTO_TEST_CASE(FastMKSModelPolynomialTest)
{
  PolynomialKernel pk(2.0);
  arma::mat referenceData = arma::randu<arma::mat>(10, 100);

  FastMKS<PolynomialKernel> f(referenceData, pk);

  FastMKSModel m(FastMKSModel::POLYNOMIAL_KERNEL);
  FastMKSModel mNaive(FastMKSModel::POLYNOMIAL_KERNEL);
  FastMKSModel mSingle(FastMKSModel::POLYNOMIAL_KERNEL);

  m.BuildModel(referenceData, pk, false, false, 2.0);
  mNaive.BuildModel(referenceData, pk, false, true, 2.0);
  mSingle.BuildModel(referenceData, pk, true, false, 2.0);

  // Now search, first monochromatically.
  arma::Mat<size_t> indices, mIndices, mNaiveIndices, mSingleIndices;
  arma::mat kernels, mKernels, mNaiveKernels, mSingleKernels;

  f.Search(3, indices, kernels);
  m.Search(3, mIndices, mKernels);
  mNaive.Search(3, mNaiveIndices, mNaiveKernels);
  mSingle.Search(3, mSingleIndices, mSingleKernels);

  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);

  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);

  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);

  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);

  for (size_t i = 0; i < indices.n_elem; ++i)
  {
    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);

    if (std::abs(kernels[i]) < 1e-5)
    {
      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);
    }
    else
    {
      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);
    }
  }

  // Now test with a different query set.
  arma::mat querySet = arma::randu<arma::mat>(10, 50);

  f.Search(querySet, 3, indices, kernels);
  m.Search(querySet, 3, mIndices, mKernels, 2.0);
  mNaive.Search(querySet, 3, mNaiveIndices, mNaiveKernels, 2.0);
  mSingle.Search(querySet, 3, mSingleIndices, mSingleKernels, 2.0);

  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);

  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);

  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);

  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);

  for (size_t i = 0; i < indices.n_elem; ++i)
  {
    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);

    if (std::abs(kernels[i]) < 1e-5)
    {
      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);
    }
    else
    {
      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);
    }
  }
}

// Test the cosine distance mode of the FastMKSModel.
BOOST_AUTO_TEST_CASE(FastMKSModelCosineTest)
{
  CosineDistance ck;
  arma::mat referenceData = arma::randu<arma::mat>(10, 100);

  FastMKS<CosineDistance> f(referenceData, ck);

  FastMKSModel m(FastMKSModel::COSINE_DISTANCE);
  FastMKSModel mNaive(FastMKSModel::COSINE_DISTANCE);
  FastMKSModel mSingle(FastMKSModel::COSINE_DISTANCE);

  m.BuildModel(referenceData, ck, false, false, 2.0);
  mNaive.BuildModel(referenceData, ck, false, true, 2.0);
  mSingle.BuildModel(referenceData, ck, true, false, 2.0);

  // Now search, first monochromatically.
  arma::Mat<size_t> indices, mIndices, mNaiveIndices, mSingleIndices;
  arma::mat kernels, mKernels, mNaiveKernels, mSingleKernels;

  f.Search(3, indices, kernels);
  m.Search(3, mIndices, mKernels);
  mNaive.Search(3, mNaiveIndices, mNaiveKernels);
  mSingle.Search(3, mSingleIndices, mSingleKernels);

  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);

  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);

  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);

  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);

  for (size_t i = 0; i < indices.n_elem; ++i)
  {
    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);

    if (std::abs(kernels[i]) < 1e-5)
    {
      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);
    }
    else
    {
      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);
    }
  }

  // Now test with a different query set.
  arma::mat querySet = arma::randu<arma::mat>(10, 50);

  f.Search(querySet, 3, indices, kernels);
  m.Search(querySet, 3, mIndices, mKernels, 2.0);
  mNaive.Search(querySet, 3, mNaiveIndices, mNaiveKernels, 2.0);
  mSingle.Search(querySet, 3, mSingleIndices, mSingleKernels, 2.0);

  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);

  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);

  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);

  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);

  for (size_t i = 0; i < indices.n_elem; ++i)
  {
    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);

    if (std::abs(kernels[i]) < 1e-5)
    {
      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);
    }
    else
    {
      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);
    }
  }
}

// Test the Gaussian kernel mode of the FastMKSModel.
BOOST_AUTO_TEST_CASE(FastMKSModelGaussianTest)
{
  GaussianKernel gk(1.5);
  arma::mat referenceData = arma::randu<arma::mat>(10, 100);

  FastMKS<GaussianKernel> f(referenceData, gk);

  FastMKSModel m(FastMKSModel::GAUSSIAN_KERNEL);
  FastMKSModel mNaive(FastMKSModel::GAUSSIAN_KERNEL);
  FastMKSModel mSingle(FastMKSModel::GAUSSIAN_KERNEL);

  m.BuildModel(referenceData, gk, false, false, 2.0);
  mNaive.BuildModel(referenceData, gk, false, true, 2.0);
  mSingle.BuildModel(referenceData, gk, true, false, 2.0);

  // Now search, first monochromatically.
  arma::Mat<size_t> indices, mIndices, mNaiveIndices, mSingleIndices;
  arma::mat kernels, mKernels, mNaiveKernels, mSingleKernels;

  f.Search(3, indices, kernels);
  m.Search(3, mIndices, mKernels);
  mNaive.Search(3, mNaiveIndices, mNaiveKernels);
  mSingle.Search(3, mSingleIndices, mSingleKernels);

  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);

  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);

  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);

  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);

  for (size_t i = 0; i < indices.n_elem; ++i)
  {
    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);

    if (std::abs(kernels[i]) < 1e-5)
    {
      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);
    }
    else
    {
      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);
    }
  }

  // Now test with a different query set.
  arma::mat querySet = arma::randu<arma::mat>(10, 50);

  f.Search(querySet, 3, indices, kernels);
  m.Search(querySet, 3, mIndices, mKernels, 2.0);
  mNaive.Search(querySet, 3, mNaiveIndices, mNaiveKernels, 2.0);
  mSingle.Search(querySet, 3, mSingleIndices, mSingleKernels, 2.0);

  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);

  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);

  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);

  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);

  for (size_t i = 0; i < indices.n_elem; ++i)
  {
    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);

    if (std::abs(kernels[i]) < 1e-5)
    {
      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);
    }
    else
    {
      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);
    }
  }
}

// Test the Epanechnikov kernel mode of the FastMKSModel.
BOOST_AUTO_TEST_CASE(FastMKSModelEpanTest)
{
  EpanechnikovKernel ek(2.5);
  arma::mat referenceData = arma::randu<arma::mat>(10, 100);

  FastMKS<EpanechnikovKernel> f(referenceData, ek);

  FastMKSModel m(FastMKSModel::EPANECHNIKOV_KERNEL);
  FastMKSModel mNaive(FastMKSModel::EPANECHNIKOV_KERNEL);
  FastMKSModel mSingle(FastMKSModel::EPANECHNIKOV_KERNEL);

  m.BuildModel(referenceData, ek, false, false, 2.0);
  mNaive.BuildModel(referenceData, ek, false, true, 2.0);
  mSingle.BuildModel(referenceData, ek, true, false, 2.0);

  // Now search, first monochromatically.
  arma::Mat<size_t> indices, mIndices, mNaiveIndices, mSingleIndices;
  arma::mat kernels, mKernels, mNaiveKernels, mSingleKernels;

  f.Search(3, indices, kernels);
  m.Search(3, mIndices, mKernels);
  mNaive.Search(3, mNaiveIndices, mNaiveKernels);
  mSingle.Search(3, mSingleIndices, mSingleKernels);

  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);

  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);

  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);

  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);

  for (size_t i = 0; i < indices.n_elem; ++i)
  {
    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);

    if (std::abs(kernels[i]) < 1e-5)
    {
      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);
    }
    else
    {
      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);
    }
  }

  // Now test with a different query set.
  arma::mat querySet = arma::randu<arma::mat>(10, 50);

  f.Search(querySet, 3, indices, kernels);
  m.Search(querySet, 3, mIndices, mKernels, 2.0);
  mNaive.Search(querySet, 3, mNaiveIndices, mNaiveKernels, 2.0);
  mSingle.Search(querySet, 3, mSingleIndices, mSingleKernels, 2.0);

  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);

  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);

  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);

  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);

  for (size_t i = 0; i < indices.n_elem; ++i)
  {
    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);

    if (std::abs(kernels[i]) < 1e-5)
    {
      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);
    }
    else
    {
      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);
    }
  }
}

// Test the triangular kernel mode of the FastMKSModel.
BOOST_AUTO_TEST_CASE(FastMKSModelTriangularTest)
{
  TriangularKernel tk(2.0);
  arma::mat referenceData = arma::randu<arma::mat>(10, 100);

  FastMKS<TriangularKernel> f(referenceData, tk);

  FastMKSModel m(FastMKSModel::TRIANGULAR_KERNEL);
  FastMKSModel mNaive(FastMKSModel::TRIANGULAR_KERNEL);
  FastMKSModel mSingle(FastMKSModel::TRIANGULAR_KERNEL);

  m.BuildModel(referenceData, tk, false, false, 2.0);
  mNaive.BuildModel(referenceData, tk, false, true, 2.0);
  mSingle.BuildModel(referenceData, tk, true, false, 2.0);

  // Now search, first monochromatically.
  arma::Mat<size_t> indices, mIndices, mNaiveIndices, mSingleIndices;
  arma::mat kernels, mKernels, mNaiveKernels, mSingleKernels;

  f.Search(3, indices, kernels);
  m.Search(3, mIndices, mKernels);
  mNaive.Search(3, mNaiveIndices, mNaiveKernels);
  mSingle.Search(3, mSingleIndices, mSingleKernels);

  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);

  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);

  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);

  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);

  for (size_t i = 0; i < indices.n_elem; ++i)
  {
    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);

    if (std::abs(kernels[i]) < 1e-5)
    {
      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);
    }
    else
    {
      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);
    }
  }

  // Now test with a different query set.
  arma::mat querySet = arma::randu<arma::mat>(10, 50);

  f.Search(querySet, 3, indices, kernels);
  m.Search(querySet, 3, mIndices, mKernels, 2.0);
  mNaive.Search(querySet, 3, mNaiveIndices, mNaiveKernels, 2.0);
  mSingle.Search(querySet, 3, mSingleIndices, mSingleKernels, 2.0);

  BOOST_REQUIRE_EQUAL(indices.n_cols, mIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mNaiveIndices.n_cols);
  BOOST_REQUIRE_EQUAL(indices.n_cols, mSingleIndices.n_cols);

  BOOST_REQUIRE_EQUAL(indices.n_rows, mIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mNaiveIndices.n_rows);
  BOOST_REQUIRE_EQUAL(indices.n_rows, mSingleIndices.n_rows);

  BOOST_REQUIRE_EQUAL(kernels.n_cols, mKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mNaiveKernels.n_cols);
  BOOST_REQUIRE_EQUAL(kernels.n_cols, mSingleKernels.n_cols);

  BOOST_REQUIRE_EQUAL(kernels.n_rows, mKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mNaiveKernels.n_rows);
  BOOST_REQUIRE_EQUAL(kernels.n_rows, mSingleKernels.n_rows);

  for (size_t i = 0; i < indices.n_elem; ++i)
  {
    BOOST_REQUIRE_EQUAL(indices[i], mIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mNaiveIndices[i]);
    BOOST_REQUIRE_EQUAL(indices[i], mSingleIndices[i]);

    if (std::abs(kernels[i]) < 1e-5)
    {
      BOOST_REQUIRE_SMALL(mKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_SMALL(mSingleKernels[i], 1e-5);
    }
    else
    {
      BOOST_REQUIRE_CLOSE(kernels[i], mKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mNaiveKernels[i], 1e-5);
      BOOST_REQUIRE_CLOSE(kernels[i], mSingleKernels[i], 1e-5);
    }
  }
}

BOOST_AUTO_TEST_SUITE_END();


text:
package elasta.orm.query.read.builder.ex;

/**
 * Created by Jango on 17/02/13.
 */
final public class ObjectReaderException extends RuntimeException {
    public ObjectReaderException(String msg) {
        super(msg);
    }
}

redpajama_set_name: RedPajamaGithub


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

<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
LineEntity
</TITLE>

<META NAME="date" CONTENT="2014-04-02">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

cn.limc.androidcharts.entity

Class LineEntity<T>

java.lang.Object
  cn.limc.androidcharts.entity.LineEntity<T>

public class LineEntity<T>
extends java.lang.Object

 Entity data which is use for display a single line in LineChart

 LineChartの線表示用データです。単線です。

 保存线图表示用单个线的对象、多条线的时候请使用相应的数据结构保存数据

Version:

v1.0 2011/05/29 12:24:49

Author:

limc

Constructor Summary

LineEntity()

 Constructor of LineEntity

LineEntity(java.util.List<T> lineData,
           java.lang.String title,
           int lineColor)

 Constructor of LineEntity

Method Summary

 int
getLineColor()

 java.util.List<T>
getLineData()

 java.lang.String
getTitle()

 boolean
isDisplay()

 void
put(T value)

 void
setDisplay(boolean display)

 void
setLineColor(int lineColor)

 void
setLineData(java.util.List<T> lineData)

 void
setTitle(java.lang.String title)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

LineEntity

public LineEntity()

 Constructor of LineEntity

 LineEntity类对象的构造函数

 LineEntityのコンストラクター

LineEntity

public LineEntity(java.util.List<T> lineData,
                  java.lang.String title,
                  int lineColor)

 Constructor of LineEntity

 LineEntity类对象的构造函数

 LineEntityのコンストラクター

Parameters:
lineData -

            Data for draw this line

            ラインを表示用データ

            线表示数据

title -

            Title for this line

            ラインの表示タイトル

            线的标题,用于标识别这条线

lineColor -

            Line Color

            ラインの色

            线的颜色

Method Detail

put

public void put(T value)

Parameters:
value -

getLineData

public java.util.List<T> getLineData()

Returns:
the lineData

setLineData

public void setLineData(java.util.List<T> lineData)

Parameters:
lineData - the lineData to set

getTitle

public java.lang.String getTitle()

Returns:
the title

setTitle

public void setTitle(java.lang.String title)

Parameters:
title - the title to set

getLineColor

public int getLineColor()

Returns:
the lineColor

setLineColor

public void setLineColor(int lineColor)

Parameters:
lineColor - the lineColor to set

isDisplay

public boolean isDisplay()

Returns:
the display

setDisplay

public void setDisplay(boolean display)

Parameters:
display - the display to set

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
using System.Reflection;
using System.Runtime.CompilerServices;

[assembly: AssemblyTitle("FluentSecurity")]
[assembly: InternalsVisibleTo("FluentSecurity.Specification")]
[assembly: InternalsVisibleTo("FluentSecurity.TestHelper")]
[assembly: InternalsVisibleTo("FluentSecurity.TestHelper.Specification")]


text:
from unittest import mock

from oslo_config import cfg

from ironic_inspector import node_cache
from ironic_inspector.plugins import base
from ironic_inspector.plugins import capabilities
from ironic_inspector.test import base as test_base

CONF = cfg.CONF

@mock.patch.object(node_cache.NodeInfo, 'update_capabilities', autospec=True)
class TestCapabilitiesHook(test_base.NodeTest):
    hook = capabilities.CapabilitiesHook()

    def test_loadable_by_name(self, mock_caps):
        base.CONF.set_override('processing_hooks', 'capabilities',
                               'processing')
        ext = base.processing_hooks_manager()['capabilities']
        self.assertIsInstance(ext.obj, capabilities.CapabilitiesHook)

    def test_no_data(self, mock_caps):
        self.hook.before_update(self.data, self.node_info)
        self.assertFalse(mock_caps.called)

    def test_boot_mode(self, mock_caps):
        CONF.set_override('boot_mode', True, 'capabilities')
        self.inventory['boot'] = {'current_boot_mode': 'uefi'}

        self.hook.before_update(self.data, self.node_info)
        mock_caps.assert_called_once_with(self.node_info, boot_mode='uefi')

    def test_boot_mode_disabled(self, mock_caps):
        self.inventory['boot'] = {'current_boot_mode': 'uefi'}

        self.hook.before_update(self.data, self.node_info)
        self.assertFalse(mock_caps.called)

    def test_cpu_flags(self, mock_caps):
        self.inventory['cpu']['flags'] = ['fpu', 'vmx', 'aes', 'pse', 'smx']

        self.hook.before_update(self.data, self.node_info)
        mock_caps.assert_called_once_with(self.node_info,
                                          cpu_vt='true',
                                          cpu_hugepages='true',
                                          cpu_txt='true',
                                          cpu_aes='true')

    def test_cpu_no_known_flags(self, mock_caps):
        self.inventory['cpu']['flags'] = ['fpu']

        self.hook.before_update(self.data, self.node_info)
        self.assertFalse(mock_caps.called)

    def test_cpu_flags_custom(self, mock_caps):
        CONF.set_override('cpu_flags', {'fpu': 'new_cap'},
                          'capabilities')
        self.inventory['cpu']['flags'] = ['fpu', 'vmx', 'aes', 'pse']

        self.hook.before_update(self.data, self.node_info)
        mock_caps.assert_called_once_with(self.node_info,
                                          new_cap='true')


text: Nothing to see here, move along.


text:
# Authentication

 - [Custom Middleware](#middleware)

SleepingOwl Admin uses Laravel authentication by `middleware`.

In your app you should run artisan command: (See https://laravel.com/docs/5.2/authentication#authentication-quickstart)
```bash
$ php artisan make:auth
```

And after add middleware `auth` to `config/sleeping_owl.php`

**Example**
```php
/*
 | ...
 | see https://laravel.com/docs/5.2/authentication#authentication-quickstart
 |
 */
'middleware' => ['web', 'auth'],
...
```

---

## Custom Middleware

You cat create custom middleware class< for example `App\Http\Middleware\AdminAuthenticate`

```php
<?php

namespace App\Http\Middleware;

use App\User;
use Closure;
use Illuminate\Support\Facades\Auth;
class AdminAuthenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param  string|null $guard
     *
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        $auth = Auth::guard($guard);

        if (Auth::guard($guard)->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('login');
            }
        }

        if (! $auth->user()->isAdmin()) {
            return response('Access denied.', 401);
        }

        return $next($request);
    }
}
```

And register this middleware in `App\Http\Kernel`

```php
 ...
 protected $routeMiddleware = [
     ...
     'admin' => \App\Http\Middleware\AdminAuthenticate::class,
     ...
 ];
 ...
```

And add this middleware `admin` to `config\sleeoping_owl.php`

```php
...
'middleware' => ['web', 'admin'],
...
```


text:
/**
 *
 */
package com.ebay.jetstream.messaging.messagetype;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.List;

/**
 *
 * This Advisory Message is used for Messaging Applications to signal advisory messages notifying App Specific
 * Failures to a remote message listener.
 *
 * @author varavindan
 *
 */
public class ApplicationStatusAdvisory extends JetstreamMessage implements Externalizable {

  /**
   * Holds the Failure Conditions which will be notified by the App
   *
   * @author varavindan
   *
   */
  public enum FaultEnum {
    DB_ACCESS_FAILURE, GENERIC_FAILURE
  }

  private String m_eventType = null;

  /**
   * Holds the message origin source/app
   */
  private String m_msgEventSource;

  /**
   * Holds the splitNumber which was either got marked up or marked down
   */
  private List<Integer> m_splitNumber;

  /**
   * Holds the core failure cause observed in the app
   */
  private FaultEnum m_faultDetail;

  /**
   * Indicates whether a reported failure got resolved
   */
  private boolean m_isResolved;

  private long m_advisoryWriteTime;

  /**
   * Holds meaningful failure description for logging purposes
   */
  private String m_faultString;

  public static final String FAULT_REASON = "Reason";

  public static final String SPILIT_NUMBER = "Split_No";

  public static final String RESOLVED_STATUS = "Resolved_Status";

  public static final String EVENT_TYPE = "EventType";

  public static final String EVENT_SOURCE = "EventSource";

  private String forwardingTopic;

  /**
   *
   */
  public ApplicationStatusAdvisory() {

  }

  /**
   * @param eflEventSource
   * @param splitNumber
   * @param faultDetail
   * @param isResolved
   * @param faultString
   */
  public ApplicationStatusAdvisory(String eflEventSource, List<Integer> splitNumber, FaultEnum faultDetail,
      boolean isResolved, String faultString, String eventType) throws Exception {

    super();
    m_msgEventSource = eflEventSource;
    m_splitNumber = splitNumber;
    m_faultDetail = faultDetail;
    m_isResolved = isResolved;
    m_faultString = faultString;
    m_eventType = eventType;
  }

  /**
   * @return the advisoryWriteTime
   */
  public long getAdvisoryWriteTime() {
    return m_advisoryWriteTime;
  }

  /**
   * @return the eflEventSource
   */
  public String getEflEventSource() {
    return m_msgEventSource;
  }

  /**
   * @return the eventType
   */
  public String getEventType() {
    return m_eventType;
  }

  /**
   * @return the faultDetail
   */
  public FaultEnum getFaultDetail() {
    return m_faultDetail;
  }

  /**
   * @return the faultString
   */
  public String getFaultString() {
    return m_faultString;
  }

  public String getForwardingTopic() {
    return forwardingTopic;
  }

  /**
   * @return the msgEventSource
   */
  public String getMsgEventSource() {
    return m_msgEventSource;
  }

  /**
   * @return the splitNumber
   */
  public List<Integer> getSplitNumber() {
    return m_splitNumber;
  }

  /**
   * @return the isResolved
   */
  public boolean isResolved() {
    return m_isResolved;
  }

  /*
   * (non-Javadoc)
   *
   * @see java.io.Externalizable#readExternal(java.io.ObjectInput)
   */
  @Override
  public void readExternal(ObjectInput in) throws IOException {
    try {
      m_splitNumber = (List<Integer>) in.readObject();
      m_eventType = (String) in.readObject();
      m_faultDetail = (FaultEnum) in.readObject();
      m_faultString = (String) in.readObject();
      m_isResolved = in.readBoolean();
      m_msgEventSource = (String) in.readObject();
      forwardingTopic = (String) in.readObject();
      m_advisoryWriteTime = in.readLong();
    }
    catch (ClassNotFoundException c) {

    }
    super.readExternal(in);
  }

  /**
   * @param advisoryWriteTime
   *          the advisoryWriteTime to set
   */
  public void setAdvisoryWriteTime(long advisoryWriteTime) {
    m_advisoryWriteTime = advisoryWriteTime;
  }

  /**
   * @param eventType
   *          the eventType to set
   */
  public void setEventType(String eventType) {
    m_eventType = eventType;
  }

  /**
   * @param faultDetail
   *          the faultDetail to set
   */
  public void setFaultDetail(FaultEnum faultDetail) {
    m_faultDetail = faultDetail;
  }

  /**
   * @param faultString
   *          the faultString to set
   */
  public void setFaultString(String faultString) {
    m_faultString = faultString;
  }

  public void setForwardingTopic(String forwardingTopic) {
    this.forwardingTopic = forwardingTopic;
  }

  /**
   * @param msgEventSource
   *          the msgEventSource to set
   */
  public void setMsgEventSource(String msgEventSource) {
    m_msgEventSource = msgEventSource;
  }

  /**
   * @param isResolved
   *          the isResolved to set
   */
  public void setResolved(boolean isResolved) {
    m_isResolved = isResolved;
  }

  /**
   * @param splitNumber
   *          the splitNumber to set
   */
  public void setSplitNumber(List<Integer> splitNumber) {
    m_splitNumber = splitNumber;
  }

  /*
   * (non-Javadoc)
   *
   * @see com.ebay.jetstream.messaging.JetstreamMessage#toString()
   */
  @Override
  public String toString() {
    StringBuffer sb = new StringBuffer();
    sb.append(this.getClass().getSimpleName()).append(": ").append(EVENT_SOURCE).append("=").append(m_msgEventSource)
        .append(",").append(EVENT_TYPE).append("=").append(m_eventType).append(",").append(SPILIT_NUMBER).append("=")
        .append(m_splitNumber).append(",").append(RESOLVED_STATUS).append("=").append(m_isResolved).append(",")
        .append(FAULT_REASON).append("=").append(m_faultDetail).append(":").append(m_faultString).append(", Topics=")
        .append(getTopic()).append(", ForwardingTopic=").append(forwardingTopic);
    return sb.toString();
  }

  /*
   * (non-Javadoc)
   *
   * @see java.io.Externalizable#writeExternal(java.io.ObjectOutput)
   */
  @Override
  public void writeExternal(ObjectOutput out) throws IOException {
    out.writeObject(m_splitNumber);
    out.writeObject(m_eventType);
    out.writeObject(m_faultDetail);
    out.writeObject(m_faultString);
    out.writeBoolean(m_isResolved);
    out.writeObject(m_msgEventSource);
    out.writeObject(forwardingTopic);
    out.writeLong(m_advisoryWriteTime);

    super.writeExternal(out);
  }

}


text:
A list/map of tech spaces in London. The website is a fork of the great [hack-spot](https://github.com/jlord/hack-spots).

The data is stored in this [google spreadsheet](https://docs.google.com/spreadsheet/ccc?key=0AmK8OoJsMrtedGVxQW82NmRiU18tZnkyVHpjSE5fdnc&usp=drive_web#gid=0),
courtesy of joshr.
I've then copied the spreadsheet and added Lat/Long and adjusted few things.

## How does it work?

A Google Spreadsheet holds all the data and it is connected to this website using the goodies in [sheetsee.js](http://www.github.com/jlord/sheetsee.js). Everytime you visit the website, you'll have the most up to date data that has been entered into the spreadsheet.


text:
"""
Copyright 2016 Deepgram

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import logging
import contextlib
import sys

###############################################################################
def redirect_stderr(x):
	""" Redirects stderr to another file-like object.

		This is some compatibility code to support Python 3.4.
	"""
	if hasattr(contextlib, 'redirect_stderr'):
		result = contextlib.redirect_stderr
	else:
		@contextlib.contextmanager
		def result(x):
			""" Stand-in for Python 3.5's `redirect_stderr`.

				Notes: Non-reentrant, non-threadsafe
			"""
			old_stderr = sys.stderr
			sys.stderr = x
			yield
			sys.stder = old_stderr

	return result(x)

###############################################################################
class DisableLogging:				# pylint: disable=too-few-public-methods
	""" Context manager that disables logging temporarily.
	"""

	###########################################################################
	def __init__(self, level=logging.DEBUG):
		""" Suppresses all logging at `level` and below.
		"""
		self.level = level

	###########################################################################
	def __enter__(self):
		""" Start suppression.
		"""
		logging.disable(self.level)

	###########################################################################
	def __exit__(self, exc_type, exc_val, exc_tb):
		""" Resume regular logging.
		"""
		logging.disable(logging.NOTSET)

### EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF


text:
var dataURL = 'loremIpsum.txt';
// https://raw.githubusercontent.com/ProgressBG-WWW-Courses/JavaScript-Advanced/gh-pages/downloads/products.json

var getByJQuery = function(cb){
	$(".getDataBtn").click(function(){
		$.get(dataURL, function(data, status){
			// do something with data:
			// $(".output").html(data);
			cb(data);
		});
	});
}

var loadByJQuery = function(){
	$(".getDataBtn").click(function(){
	    $(".output").load(dataURL);
	});
}

var productData;
var parseData = function(str) {
	// var res = JSON.parse(str);
	render(str);
}
var render = function(data){
	$(".output").html(data);
}
getByJQuery(render);


text:
package org.apereo.cas.gauth.token;

import org.apereo.cas.config.CasCoreAuthenticationConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationHandlersConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationMetadataConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationPolicyConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationPrincipalConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationServiceSelectionStrategyConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationSupportConfiguration;
import org.apereo.cas.config.CasCoreConfiguration;
import org.apereo.cas.config.CasCoreHttpConfiguration;
import org.apereo.cas.config.CasCoreMultifactorAuthenticationConfiguration;
import org.apereo.cas.config.CasCoreServicesAuthenticationConfiguration;
import org.apereo.cas.config.CasCoreServicesConfiguration;
import org.apereo.cas.config.CasCoreTicketCatalogConfiguration;
import org.apereo.cas.config.CasCoreTicketIdGeneratorsConfiguration;
import org.apereo.cas.config.CasCoreTicketsConfiguration;
import org.apereo.cas.config.CasCoreUtilConfiguration;
import org.apereo.cas.config.CasCoreWebConfiguration;
import org.apereo.cas.config.CasPersonDirectoryConfiguration;
import org.apereo.cas.config.GoogleAuthenticatorMongoDbConfiguration;
import org.apereo.cas.config.support.CasWebApplicationServiceFactoryConfiguration;
import org.apereo.cas.config.support.authentication.GoogleAuthenticatorAuthenticationEventExecutionPlanConfiguration;
import org.apereo.cas.config.support.authentication.GoogleAuthenticatorAuthenticationMultifactorProviderBypassConfiguration;
import org.apereo.cas.gauth.credential.MongoDbGoogleAuthenticatorTokenCredentialRepositoryTests;
import org.apereo.cas.logout.config.CasCoreLogoutConfiguration;
import org.apereo.cas.util.SchedulingUtils;
import org.apereo.cas.util.junit.EnabledIfPortOpen;
import org.apereo.cas.web.config.CasCookieConfiguration;
import org.apereo.cas.web.flow.config.CasCoreWebflowConfiguration;
import org.apereo.cas.web.flow.config.CasMultifactorAuthenticationWebflowConfiguration;
import org.apereo.cas.web.flow.config.CasWebflowContextConfiguration;

import lombok.Getter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.aop.AopAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * This is {@link GoogleAuthenticatorMongoDbTokenRepositoryTests}.
 *
 * @author Misagh Moayyed
 * @since 5.2.0
 */
@Tag("MongoDb")
@SpringBootTest(classes = {
    MongoDbGoogleAuthenticatorTokenCredentialRepositoryTests.MongoTestConfiguration.class,
    GoogleAuthenticatorMongoDbConfiguration.class,
    CasCoreMultifactorAuthenticationConfiguration.class,
    CasMultifactorAuthenticationWebflowConfiguration.class,
    CasCoreTicketsConfiguration.class,
    CasCoreTicketIdGeneratorsConfiguration.class,
    CasCoreTicketCatalogConfiguration.class,
    CasCoreLogoutConfiguration.class,
    CasCoreHttpConfiguration.class,
    CasCookieConfiguration.class,
    CasCoreServicesConfiguration.class,
    CasWebApplicationServiceFactoryConfiguration.class,
    CasCoreAuthenticationConfiguration.class,
    CasCoreServicesAuthenticationConfiguration.class,
    CasCoreAuthenticationMetadataConfiguration.class,
    CasCoreAuthenticationPolicyConfiguration.class,
    CasCoreAuthenticationPrincipalConfiguration.class,
    CasCoreAuthenticationHandlersConfiguration.class,
    CasCoreAuthenticationSupportConfiguration.class,
    CasPersonDirectoryConfiguration.class,
    GoogleAuthenticatorAuthenticationMultifactorProviderBypassConfiguration.class,
    GoogleAuthenticatorAuthenticationEventExecutionPlanConfiguration.class,
    AopAutoConfiguration.class,
    CasCoreConfiguration.class,
    CasCoreAuthenticationServiceSelectionStrategyConfiguration.class,
    CasCoreUtilConfiguration.class,
    CasCoreWebflowConfiguration.class,
    CasWebflowContextConfiguration.class,
    RefreshAutoConfiguration.class,
    CasCoreWebConfiguration.class},
    properties = {
        "cas.authn.mfa.gauth.mongo.userId=root",
        "cas.authn.mfa.gauth.mongo.password=secret",
        "cas.authn.mfa.gauth.mongo.host=localhost",
        "cas.authn.mfa.gauth.mongo.port=27017",
        "cas.authn.mfa.gauth.mongo.authenticationDatabaseName=admin",
        "cas.authn.mfa.gauth.mongo.dropCollection=true",
        "cas.authn.mfa.gauth.mongo.databaseName=gauth-token",
        "cas.authn.mfa.gauth.crypto.enabled=false"
    })
@EnableTransactionManagement(proxyTargetClass = true)
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableScheduling
@Getter
@EnabledIfPortOpen(port = 27017)
public class GoogleAuthenticatorMongoDbTokenRepositoryTests extends BaseOneTimeTokenRepositoryTests {

    @BeforeEach
    public void initialize() {
        oneTimeTokenAuthenticatorTokenRepository.getObject().removeAll();
    }

    @TestConfiguration("MongoTestConfiguration")
    public static class MongoTestConfiguration implements InitializingBean {
        @Autowired
        protected ApplicationContext applicationContext;

        @Override
        public void afterPropertiesSet() {
            SchedulingUtils.prepScheduledAnnotationBeanPostProcessor(applicationContext);
        }
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient
        android:type="linear"
        android:startColor="#ff08ddff"
        android:centerColor="#ff17c9ff"
        android:endColor="#ff0e95ff"
        android:angle="270"/>
    <corners android:radius="10dp" />
    <stroke android:width="1dp" android:color="#5e7974" />
</shape>


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid android:color="#DDDDDD" />

    <corners
        android:bottomLeftRadius="3dp"
        android:bottomRightRadius="3dp"
        android:topLeftRadius="3dp"
        android:topRightRadius="3dp" />

    <!-- 描边 -->
    <stroke
        android:width="1dp"
        android:color="#C4C4C4" />

</shape>


text:
<!DOCTYPE html>

Text


text:
FROM gliderlabs/alpine
MAINTAINER Tim Kropp <timkropp77@gmail.com>
ENV VAULT_VERSION 0.6.0

ADD https://releases.hashicorp.com/vault/${VAULT_VERSION}/vault_${VAULT_VERSION}_linux_amd64.zip /tmp/vault.zip
RUN cd /bin && unzip /tmp/vault.zip && chmod +x /bin/vault && rm /tmp/vault.zip

COPY vaultconfig.hcl /opt/vault/vaultconfig.hcl

EXPOSE 8200
ENV VAULT_ADDR "http://127.0.0.1:8200"

ENTRYPOINT ["/bin/vault"]
CMD ["server"]


text:
// Copyright 2018 Stefan Negritoiu (FreeBusy) and contributors. See LICENSE file for more information.

using System;
using System.IO;
using AlexaSkillsKit.Authentication;
using AlexaSkillsKit.Json;
using Xunit;

namespace AlexaSkillsKit.Tests.Helpers
{
    public class DateTimeHelpersTests
    {
        [Fact]
        public void RequestWithIso8601TimestampTest() {
            const string TestDataFile = @"TestData\RequestWithIso8601Timestamp.json";

            SpeechletRequestValidationResult validationResult = SpeechletRequestValidationResult.OK;
            SpeechletRequestEnvelope alexaRequest = null;
            var alexaContent = File.ReadAllText(TestDataFile);

            try {
                alexaRequest = SpeechletRequestEnvelope.FromJson(alexaContent);
            }
            catch (Exception ex)
            when (ex is Newtonsoft.Json.JsonReaderException || ex is InvalidCastException || ex is FormatException) {
                validationResult = validationResult | SpeechletRequestValidationResult.InvalidJson;
            }

            Assert.True(validationResult == SpeechletRequestValidationResult.OK);
        }

        [Fact]
        public void RequestWithUnixTimeTimestampTest() {
            const string TestDataFile = @"TestData\RequestWithUnixTimeTimestamp.json";

            SpeechletRequestValidationResult validationResult = SpeechletRequestValidationResult.OK;
            SpeechletRequestEnvelope alexaRequest = null;
            var alexaContent = File.ReadAllText(TestDataFile);

            try {
                alexaRequest = SpeechletRequestEnvelope.FromJson(alexaContent);
            }
            catch (Exception ex)
            when (ex is Newtonsoft.Json.JsonReaderException || ex is InvalidCastException || ex is FormatException) {
                validationResult = validationResult | SpeechletRequestValidationResult.InvalidJson;
            }

            Assert.True(validationResult == SpeechletRequestValidationResult.OK);
        }

        [Fact]
        public void RequestWithInvalidTimestampTest(){
            const string TestDataFile = @"TestData\RequestWithInvalidTimestamp.json";

            SpeechletRequestValidationResult validationResult = SpeechletRequestValidationResult.OK;
            SpeechletRequestEnvelope alexaRequest = null;
            var alexaContent = File.ReadAllText(TestDataFile);

            try {
                alexaRequest = SpeechletRequestEnvelope.FromJson(alexaContent);
            }
            catch (Exception ex)
            when (ex is Newtonsoft.Json.JsonReaderException || ex is InvalidCastException || ex is FormatException) {
                validationResult = validationResult | SpeechletRequestValidationResult.InvalidJson;
            }

            Assert.True(validationResult == SpeechletRequestValidationResult.InvalidJson);
        }
    }
}


text:
require_relative 'abstractstrategy.rb'

module SysstatsPluginModule
  class TcpNetworkResultStrategy < AbstractStrategy
    attr_accessor :average_metric_list,:detailed_metric_list

    def self.metric_description
      {
        "active/s" => "The number of times TCP connections have made a direct transition to the SYN-SENT state from the CLOSED state per second [tcpActiveOpens].",
        "passive/s" => "The number of times TCP connections have made a direct transition to the SYN-RCVD state from the LISTEN state per second [tcpPassiveOpens].",
        "iseg/s" => "The total number of segments received per second, including those received in error [tcpInSegs].  This count includes segments received on currently established connections.",
        "oseg/s" => "The total number of segments sent per second, including those on current connections but excluding those containing only retransmitted octets [tcpOutSegs]."
      }
    end

    def initialize(db, fs_ip, application, name, test_type, id, metric_id)
      @average_metric_list = {
        "active/s" => [],
        "passive/s" => [],
        "iseg/s" => [],
        "oseg/s" => []
      }

      @detailed_metric_list = {
        "active/s" => [],
        "passive/s" => [],
        "iseg/s" => [],
        "oseg/s" => []
      }
      super(db, fs_ip, application, name, test_type, id, metric_id)
    end

    def populate_metric(entry, name, id, start, stop)
      open(entry).readlines.each do |result|
        result.scan(/Average:\s+(\d+\.?\d*?)\s+(\d+\.?\d*?)\s+(\d+\.?\d*?)\s+(\d+\.?\d*?)$/).map do |actives, passives, isegs, osegs|
          #get device name and then time
          #only use time that's between start and end (in the 24 hour period the time has to be between those 2)
          dev = File.basename(entry)
          initialize_metric(@average_metric_list,"active/s",dev)
          @average_metric_list["active/s"].find {|key_data| key_data[:dev_name] == dev}[:results] = actives
          initialize_metric(@average_metric_list,"passive/s",dev)
          @average_metric_list["passive/s"].find {|key_data| key_data[:dev_name] == dev}[:results] = passives
          initialize_metric(@average_metric_list,"iseg/s",dev)
          @average_metric_list["iseg/s"].find {|key_data| key_data[:dev_name] == dev}[:results] = isegs
          initialize_metric(@average_metric_list,"oseg/s",dev)
          @average_metric_list["oseg/s"].find {|key_data| key_data[:dev_name] == dev}[:results] = osegs
        end
        result.scan(/(\d+:\d+:\d+ \S+)\s+(\d+\.?\d*?)\s+(\d+\.?\d*?)\s+(\d+\.?\d*?)\s+(\d+\.?\d*?)$/).map do |time,actives, passives, isegs, osegs|
          #get device name and then time
          #only use time that's between start and end (in the 24 hour period the time has to be between those 2)
          dev = File.basename(entry)
          initialize_metric(@detailed_metric_list,"active/s",dev)
          @detailed_metric_list["active/s"].find {|key_data| key_data[:dev_name] == dev}[:results] << {:time => time, :value => actives}
          initialize_metric(@detailed_metric_list,"passive/s",dev)
          @detailed_metric_list["passive/s"].find {|key_data| key_data[:dev_name] == dev}[:results] << {:time => time, :value => passives}
          initialize_metric(@detailed_metric_list,"iseg/s",dev)
          @detailed_metric_list["iseg/s"].find {|key_data| key_data[:dev_name] == dev}[:results] << {:time => time, :value => isegs}
          initialize_metric(@detailed_metric_list,"oseg/s",dev)
          @detailed_metric_list["oseg/s"].find {|key_data| key_data[:dev_name] == dev}[:results] << {:time => time, :value => osegs}
        end
      end
    end
  end
end


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.Resources.Models
{
    /// <summary> The custom resource function definition. </summary>
    public partial class DataManifestCustomResourceFunctionDefinition
    {
        /// <summary> Initializes a new instance of DataManifestCustomResourceFunctionDefinition. </summary>
        internal DataManifestCustomResourceFunctionDefinition()
        {
            DefaultProperties = new ChangeTrackingList<string>();
        }

        /// <summary> Initializes a new instance of DataManifestCustomResourceFunctionDefinition. </summary>
        /// <param name="name"> The function name as it will appear in the policy rule. eg - 'vault'. </param>
        /// <param name="fullyQualifiedResourceType"> The fully qualified control plane resource type that this function represents. eg - 'Microsoft.KeyVault/vaults'. </param>
        /// <param name="defaultProperties"> The top-level properties that can be selected on the function's output. eg - [ "name", "location" ] if vault().name and vault().location are supported. </param>
        /// <param name="allowCustomProperties"> A value indicating whether the custom properties within the property bag are allowed. Needs api-version to be specified in the policy rule eg - vault('2019-06-01'). </param>
        internal DataManifestCustomResourceFunctionDefinition(string name, ResourceType? fullyQualifiedResourceType, IReadOnlyList<string> defaultProperties, bool? allowCustomProperties)
        {
            Name = name;
            FullyQualifiedResourceType = fullyQualifiedResourceType;
            DefaultProperties = defaultProperties;
            AllowCustomProperties = allowCustomProperties;
        }

        /// <summary> The function name as it will appear in the policy rule. eg - 'vault'. </summary>
        public string Name { get; }
        /// <summary> The fully qualified control plane resource type that this function represents. eg - 'Microsoft.KeyVault/vaults'. </summary>
        public ResourceType? FullyQualifiedResourceType { get; }
        /// <summary> The top-level properties that can be selected on the function's output. eg - [ "name", "location" ] if vault().name and vault().location are supported. </summary>
        public IReadOnlyList<string> DefaultProperties { get; }
        /// <summary> A value indicating whether the custom properties within the property bag are allowed. Needs api-version to be specified in the policy rule eg - vault('2019-06-01'). </summary>
        public bool? AllowCustomProperties { get; }
    }
}


text:
package cn.remex.contrib.appbeans;

import cn.remex.core.exception.ServiceCode;
import cn.remex.db.DbRvo;
import cn.remex.web.service.BsRvo;

import java.util.List;

/**
 * Created by LIU on 15/12/14.
 */
public class DataRvo extends BsRvo {
    private static final long serialVersionUID = 7623706753751877136L;
    private List<?> datas;

    private int rowCount;
    private int pagination;
    private int pageCount;
    private int recordCount;
    private int effectRowCount;
    private String pk;

    public DataRvo(){
    }
    public DataRvo(DbRvo dbRvo) {
        super(dbRvo.getStatus()? ServiceCode.SUCCESS: ServiceCode.RSQL_FAIL, dbRvo.getMsg());
        this.datas = dbRvo.obtainObjects();
        this.rowCount = dbRvo.getRowCount();
        this.pagination = dbRvo.getPagination() == 0 ? 1 : dbRvo.getPagination();
        this.recordCount = dbRvo.getRecordCount();
        if (dbRvo.getRowCount() != 0) {
            double b = (getRecordCount() * 1.00) / getRowCount();
            this.pageCount = ((int) Math.ceil(b));
        }
        effectRowCount = dbRvo.getEffectRowCount();
        pk = dbRvo.getId();
    }
    public DataRvo(String code, String msg, List<?> datas) {
        super(code, msg);
        this.datas = datas;
        this.rowCount = datas.size();
        this.pagination = 1;
        this.recordCount = rowCount;
        this.pageCount = 1;
    }

    public int getRowCount() {
        return rowCount;
    }
    public void setRowCount(int rowCount) {
        this.rowCount = rowCount;
    }
    public int getPagination() {
        return pagination;
    }
    public void setPagination(int pagination) {
        this.pagination = pagination;
    }
    public int getRecordCount() {
        return recordCount;
    }
    public void setRecordCount(int recordCount) {
        this.recordCount = recordCount;
    }
    public int getPageCount() {
        return pageCount;
    }
    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }
    public List<?> getDatas() {
        return datas;
    }
    public void setDatas(List<?> datas) {
        this.datas = datas;
    }

    public int getEffectRowCount() {
        return effectRowCount;
    }

    public void setEffectRowCount(int effectRowCount) {
        this.effectRowCount = effectRowCount;
    }

    public String getPk() {
        return pk;
    }

    public void setPk(String pk) {
        this.pk = pk;
    }
}


text:
<use name="roofit"/> <!--- For Graphics related libraries --->
<use name="boost"/>
<use name="ManagerUtils/SysUtils"/>
<flags CXXFLAGS="-g"/>

<export>
   <lib name="1"/>
</export>


text:
package api

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/zenazn/goji/graceful"
	"github.com/zenazn/goji/web"

	"github.com/jeffpierce/cassabon/config"
	"github.com/jeffpierce/cassabon/logging"
)

type CassabonAPI struct {
	wg       *sync.WaitGroup
	server   *web.Mux
	hostPort string
}

func (api *CassabonAPI) Start(wg *sync.WaitGroup) {
	// Add to waitgroup and run go routine.
	api.hostPort = config.G.API.Listen
	api.wg = wg
	api.wg.Add(1)
	go api.run()
}

func (api *CassabonAPI) Stop() {
	config.G.Log.System.LogInfo("API received Stop command, gracefully shutting down.")
	graceful.Shutdown()
	api.wg.Done()
}

func (api *CassabonAPI) run() {
	// Initialize API server
	api.server = web.New()

	// Define routes
	api.server.Get("/", api.rootHandler)
	api.server.Get("/paths", api.getPathHandler)
	api.server.Get("/metrics", api.getMetricHandler)
	api.server.Get("/healthcheck", api.healthHandler)
	api.server.Delete("/paths", api.deletePathHandler)
	api.server.Delete("/metrics", api.deleteMetricHandler)
	api.server.NotFound(api.notFoundHandler)

	api.server.Use(requestLogger)

	config.G.Log.System.LogInfo("API initialized, serving!")
	graceful.ListenAndServe(api.hostPort, api.server)
}

// notFoundHandler is the global 404 handler, used by Goji.
func (api *CassabonAPI) notFoundHandler(w http.ResponseWriter, r *http.Request) {
	api.sendErrorResponse(w, http.StatusNotFound, "not found", r.RequestURI)
}

// healthHandler responds with either ALIVE or DEAD, for use by the load balancer.
func (api *CassabonAPI) healthHandler(w http.ResponseWriter, r *http.Request) {

	// We are alive, unless the healthcheck file says we are dead.
	var alive bool = true

	if health, err := ioutil.ReadFile(config.G.API.HealthCheckFile); err == nil {
		if strings.ToUpper(strings.TrimSpace(string(health))) == "DEAD" {
			alive = false
		}
	}

	if alive {
		fmt.Fprint(w, "ALIVE")
	} else {
		fmt.Fprint(w, "DEAD")
	}
}

// rootHandler provides information about the application, served from "/".
func (api *CassabonAPI) rootHandler(w http.ResponseWriter, r *http.Request) {

	resp := struct {
		Message string `json:"message"`
		Github  string `json:"github"`
		Version string `json:"version"`
	}{}
	resp.Message = "Cassabon.  You know, for stats!"
	resp.Github = "https://github.com/jeffpierce/cassabon"
	resp.Version = config.Version
	jsonText, _ := json.Marshal(resp)
	w.Write(jsonText)
}

// getPathHandler processes requests like "GET /paths?query=foo".
func (api *CassabonAPI) getPathHandler(w http.ResponseWriter, r *http.Request) {

	// Create the channel on which the response will be received.
	ch := make(chan config.APIQueryResponse)

	// Extract the query from the request URI.
	_ = r.ParseForm()
	q := config.IndexQuery{r.Method, r.Form.Get("query"), ch}
	config.G.Log.System.LogDebug("Received paths query: %s %s", q.Method, q.Query)

	// Forward the query.
	select {
	case config.G.Channels.IndexRequest <- q:
	default:
		config.G.Log.System.LogWarn(
			"Index query discarded, IndexRequest channel is full (max %d entries)",
			config.G.Channels.IndexRequestChanLen)
		logging.Statsd.Client.Inc("api.err.path.get", 1, 1.0)
	}

	// Send the response to the client.
	api.sendResponse(w, ch, config.G.API.Timeouts.GetIndex)
}

// deletePathHandler removes paths from the index store.
func (api *CassabonAPI) deletePathHandler(c web.C, w http.ResponseWriter, r *http.Request) {

	// Create the channel on which the response will be received.
	ch := make(chan config.APIQueryResponse)

	// Extract the query from the request URI.
	_ = r.ParseForm()
	q := config.IndexQuery{r.Method, r.Form.Get("query"), ch}
	config.G.Log.System.LogDebug("Received paths query: %s %s", q.Method, q.Query)

	// Forward the query.
	select {
	case config.G.Channels.IndexRequest <- q:
	default:
		config.G.Log.System.LogWarn(
			"Index DELETE query discarded, IndexRequest channel is full (max %d entries)",
			config.G.Channels.IndexRequestChanLen)
		logging.Statsd.Client.Inc("api.err.path.delete", 1, 1.0)
	}

	// Send the response to the client.
	api.sendResponse(w, ch, config.G.API.Timeouts.DeleteIndex)
}

// getMetricHandler processes requests like "GET /metrics?query=foo".
func (api *CassabonAPI) getMetricHandler(w http.ResponseWriter, r *http.Request) {

	// Create the channel on which the response will be received.
	ch := make(chan config.APIQueryResponse)

	// Extract the query from the request URI.
	_ = r.ParseForm()
	from, _ := strconv.Atoi(r.Form.Get("from"))
	to, _ := strconv.Atoi(r.Form.Get("to"))
	q := config.MetricQuery{r.Method, r.Form["path"], int64(from), int64(to), false, ch}
	config.G.Log.System.LogDebug("Received metrics query: %s %v %d %d", q.Method, q.Query, q.From, q.To)

	// Forward the query.
	select {
	case config.G.Channels.MetricRequest <- q:
	default:
		config.G.Log.System.LogWarn(
			"Metrics query discarded, MetricRequest channel is full (max %d entries)",
			config.G.Channels.MetricRequestChanLen)
		logging.Statsd.Client.Inc("api.err.metrics.get", 1, 1.0)
	}

	// Send the response to the client.
	api.sendResponse(w, ch, config.G.API.Timeouts.GetMetric)
}

// deleteMetricHandler removes data from the metrics store.
func (api *CassabonAPI) deleteMetricHandler(c web.C, w http.ResponseWriter, r *http.Request) {

	// Create the channel on which the response will be received.
	ch := make(chan config.APIQueryResponse)

	// Extract the query from the request URI.
	_ = r.ParseForm()
	metric := r.Form["path"]
	from, _ := strconv.Atoi(r.Form.Get("from"))
	to, _ := strconv.Atoi(r.Form.Get("to"))
	dryrunText := r.Form.Get("dryrun")
	dryrun := true
	if strings.ToLower(dryrunText) == "false" || strings.ToLower(dryrunText) == "no" {
		dryrun = false
	}
	q := config.MetricQuery{r.Method, metric, int64(from), int64(to), dryrun, ch}
	config.G.Log.System.LogDebug("Received metrics query: %s %v %d %d %v", q.Method, q.Query, q.From, q.To, dryrun)

	// Forward the query.
	select {
	case config.G.Channels.MetricRequest <- q:
	default:
		config.G.Log.System.LogWarn(
			"Metric DELETE query discarded, IndexRequest channel is full (max %d entries)",
			config.G.Channels.IndexRequestChanLen)
		logging.Statsd.Client.Inc("api.err.metrics.delete", 1, 1.0)
	}

	// Send the response to the client.
	api.sendResponse(w, ch, config.G.API.Timeouts.DeleteMetric)
}

func (api *CassabonAPI) sendResponse(w http.ResponseWriter, ch chan config.APIQueryResponse, timeout time.Duration) {

	// Read the response.
	var resp config.APIQueryResponse
	select {
	case resp = <-ch:
		// Nothing, we have our response.
	case <-time.After(timeout):
		// The query died or wedged; simulate a timeout response.
		resp = config.APIQueryResponse{config.AQS_ERROR, fmt.Sprintf("query timed out after %v", timeout), []byte{}}
	}
	close(ch)

	// Inspect the response status, and send appropriate response headers/data to client.
	switch resp.Status {
	case config.AQS_OK:
		if len(resp.Payload) > 0 {
			w.Write(resp.Payload)
		} else {
			w.WriteHeader(http.StatusNoContent)
		}
	case config.AQS_NOTFOUND:
		api.sendErrorResponse(w, http.StatusNotFound, "not found", resp.Message)
	case config.AQS_BADREQUEST:
		api.sendErrorResponse(w, http.StatusBadRequest, "bad request", resp.Message)
	case config.AQS_ERROR:
		api.sendErrorResponse(w, http.StatusInternalServerError, "internal error", resp.Message)
	}
}

func (api *CassabonAPI) sendErrorResponse(w http.ResponseWriter, status int, text string, message string) {

	resp := struct {
		Status     int    `json:"status"`
		StatusText string `json:"statustext"`
		Message    string `json:"message"`
	}{}

	resp.Status = status
	resp.StatusText = text
	resp.Message = message
	jsonText, _ := json.Marshal(resp)

	w.WriteHeader(status)
	w.Write(jsonText)
}


text:
package alluxio.worker.keyvalue;

import alluxio.Constants;
import alluxio.thrift.KeyValueWorkerClientService;
import alluxio.util.ThreadFactoryUtils;
import alluxio.worker.AbstractWorker;
import alluxio.worker.block.BlockWorker;

import com.google.common.base.Preconditions;
import org.apache.thrift.TProcessor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;

import javax.annotation.concurrent.ThreadSafe;

/**
 * A worker serving key-value queries.
 */
@ThreadSafe
public final class KeyValueWorker extends AbstractWorker {
  /** BlockWorker handle for access block info. */
  private final BlockWorker mBlockWorker;
  /** Logic for handling key-value RPC requests. */
  private final KeyValueWorkerClientServiceHandler mKeyValueServiceHandler;

  /**
   * Constructor of {@link KeyValueWorker}.
   *
   * @param blockWorker handler to the {@link BlockWorker}
   */
  public KeyValueWorker(BlockWorker blockWorker) {
    // TODO(binfan): figure out do we really need thread pool for key-value worker (and for what)
    super(Executors.newFixedThreadPool(1,
        ThreadFactoryUtils.build("keyvalue-worker-heartbeat-%d", true)));
    mBlockWorker = Preconditions.checkNotNull(blockWorker);
    mKeyValueServiceHandler = new KeyValueWorkerClientServiceHandler(mBlockWorker);
  }

  @Override
  public Map<String, TProcessor> getServices() {
    Map<String, TProcessor> services = new HashMap<>();
    services.put(Constants.KEY_VALUE_WORKER_CLIENT_SERVICE_NAME,
        new KeyValueWorkerClientService.Processor<>(mKeyValueServiceHandler));
    return services;
  }

  @Override
  public void start() throws IOException {
    // No heartbeat thread to start
    // Thrift service is multiplexed with other services and will be started together with others
  }

  @Override
  public void stop() throws IOException {
    // No heartbeat thread to stop
    // Thrift service is multiplexed with other services and will be stopped together with others
  }
}


text:
<?php

namespace Yeomi\PostBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

/**
 * Post
 *
 * @ORM\Table(name="post")
 * @ORM\Entity(repositoryClass="Yeomi\PostBundle\Repository\PostRepository")
 * @ORM\HasLifecycleCallbacks
 */
class Post
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Yeomi\PostBundle\Entity\Category", inversedBy="posts")
     * @Assert\NotBlank(message="Vous devez choisir une catégorie")
     */
    private $categories;

    /**
     * @var ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="Yeomi\PostBundle\Entity\Image", mappedBy="post", cascade={"persist", "remove"})
     * @Assert\Valid()
     */
    private $images;

    /**
     * @var \Yeomi\PostBundle\Entity\Video
     *
     * @ORM\OneToOne(targetEntity="Yeomi\PostBundle\Entity\Video", inversedBy="post", cascade={"persist", "remove"})
     * @Assert\Valid()
     */
    private $video;
    /**
     * @var ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="Yeomi\PostBundle\Entity\Comment", mappedBy="post", cascade={"remove"})
     */
    private $comments;

    /**
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="Yeomi\PostBundle\Entity\Vote", mappedBy="post", cascade={"remove"})
     */
    private $votes;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=255, nullable=true)
     */
    private $title;

    /**
     * @var string
     *
     * @ORM\Column(name="link", type="string", length=255, nullable=true)
     */
    private $link;

    /**
     * @var string
     *
     * @ORM\Column(name="content", type="text")
     * @Assert\NotBlank(message="Vous devez écrire un texte")
     * @Assert\Length(
     *      min = "10",
     *      max = "4000",
     *      minMessage = "Votre texte est trop court !",
     *      maxMessage = "Votre texte ne doit pas dépasser {{ limit }} caractères"
     * )
     */
    private $content;

    /**
     * @var \Yeomi\PostBundle\Entity\Type
     *
     * @ORM\ManyToOne(targetEntity="Yeomi\PostBundle\Entity\Type", inversedBy="posts")
     */
    private $type;

    /**
     * @var \Yeomi\UserBundle\Entity\User
     *
     * @ORM\ManyToOne(targetEntity="Yeomi\UserBundle\Entity\User", inversedBy="posts")
     */
    private $user;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created", type="datetime")
     */
    private $created;

    /**
     * @var boolean
     *
     * @ORM\Column(name="published", type="boolean", nullable=true)
     */
    private $published;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="last_action", type="datetime", nullable=true)
     */
    private $lastAction;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->images = new \Doctrine\Common\Collections\ArrayCollection();
        $this->setCreated(new \DateTime());
        $this->setPublished(true);
        $this->setLastAction(new \DateTime());

    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return Post
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set content
     *
     * @param string $content
     * @return Post
     */
    public function setContent($content)
    {
        $this->content = $content;

        return $this;
    }

    /**
     * Get content
     *
     * @return string
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Set created
     *
     * @param \DateTime $created
     * @return Post
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

    /**
     * Get created
     *
     * @return \DateTime
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Set published
     *
     * @param boolean $published
     * @return Post
     */
    public function setPublished($published)
    {
        $this->published = $published;

        return $this;
    }

    /**
     * Get published
     *
     * @return boolean
     */
    public function getPublished()
    {
        return $this->published;
    }

    /**
     * Add categories
     *
     * @param \Yeomi\PostBundle\Entity\Category $categories
     * @return Post
     */
    public function addCategory(\Yeomi\PostBundle\Entity\Category $category)
    {
        $this->categories[] = $category;
        return $this;
    }

    /**
     * Remove categories
     *
     * @param \Yeomi\PostBundle\Entity\Category $categories
     */
    public function removeCategory(\Yeomi\PostBundle\Entity\Category $category)
    {
        $this->categories->removeElement($category);
    }

    /**
     * Get categories
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getCategories()
    {
        return $this->categories;
    }

    /**
     * Set categories
     * @param \Doctrine\Common\Collections\Collection $categories
     *
     * @return Post
     */
    public function setCategories($categories)
    {

        if(!is_array($categories))
        {
            $categories = array($categories);
        }
        $this->categories = $categories;

        return $this;
    }

    /**
     * Add images
     *
     * @param \Yeomi\PostBundle\Entity\Image $images
     * @return Post
     */
    public function addImage(\Yeomi\PostBundle\Entity\Image $images)
    {
        $this->images[] = $images;
        $images->setPost($this);

        return $this;
    }

    /**
     * Remove images
     *
     * @param \Yeomi\PostBundle\Entity\Image $images
     */
    public function removeImage(\Yeomi\PostBundle\Entity\Image $images)
    {
        $this->images->removeElement($images);
    }

    /**
     * Get images
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getImages()
    {
        return $this->images;
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function deleteEmptyImage() {

        foreach ($this->getImages() as $image) {
            if($image->getFile()) {
            } else {
                $this->removeImage($image);
            }
        }
    }

    /**
     * Set type
     *
     * @param \Yeomi\PostBundle\Entity\Type $type
     * @return Post
     */
    public function setType(\Yeomi\PostBundle\Entity\Type $type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * Get type
     *
     * @return \Yeomi\PostBundle\Entity\Type
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Add comments
     *
     * @param \Yeomi\PostBundle\Entity\Comment $comments
     * @return Post
     */
    public function addComment(\Yeomi\PostBundle\Entity\Comment $comments)
    {
        $this->comments[] = $comments;

        return $this;
    }

    /**
     * Remove comments
     *
     * @param \Yeomi\PostBundle\Entity\Comment $comments
     */
    public function removeComment(\Yeomi\PostBundle\Entity\Comment $comments)
    {
        $this->comments->removeElement($comments);
    }

    /**
     * Get comments
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getComments()
    {
        return $this->comments;
    }

    /**
     * Set user
     *
     * @param \Yeomi\UserBundle\Entity\User $user
     * @return Post
     */
    public function setUser(\Yeomi\UserBundle\Entity\User $user = null)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \Yeomi\UserBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * Add votes
     *
     * @param \Yeomi\PostBundle\Entity\Vote $votes
     * @return Post
     */
    public function addVote(\Yeomi\PostBundle\Entity\Vote $votes)
    {
        $this->votes[] = $votes;

        return $this;
    }

    /**
     * Remove votes
     *
     * @param \Yeomi\PostBundle\Entity\Vote $votes
     */
    public function removeVote(\Yeomi\PostBundle\Entity\Vote $votes)
    {
        $this->votes->removeElement($votes);
    }

    /**
     * Get votes
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getVotes()
    {
        return $this->votes;
    }

    /**
     * Get likes
     *
     * @return Array
     */
    public function getLikes()
    {
        $positives = 0;
        $negatives = 0;
        foreach($this->votes as $vote) {
            if ($vote->getPositive()) {
                $positives++;
            } elseif ($vote->getNegative()) {
                $negatives++;
            }
        }

        return array(
            "positives" => $positives,
            "negatives" => $negatives,
        );
    }

    /**
     * Set lastAction
     *
     * @param \DateTime $lastAction
     * @return Post
     */
    public function setLastAction($lastAction)
    {
        $this->lastAction = $lastAction;

        return $this;
    }

    /**
     * Get lastAction
     *
     * @return \DateTime
     */
    public function getLastAction()
    {
        return $this->lastAction;
    }

    /**
     * Set video
     *
     * @param \Yeomi\PostBundle\Entity\Video $video
     * @return Post
     */
    public function setVideo(\Yeomi\PostBundle\Entity\Video $video = null)
    {
        $this->video = $video;

        return $this;
    }

    /**
     * Get video
     *
     * @return \Yeomi\PostBundle\Entity\Video
     */
    public function getVideo()
    {
        return $this->video;
    }

    /**
     * @Assert\Callback
     */
    public function validate(ExecutionContextInterface $context)
    {
        $content = $this->getContent();

        if(strpos($content, 'viagra') !== false) {
            $context->buildViolation('Merci de respecter la charte d\'utilisation')
                ->atPath('content')
                ->addViolation();
        }
        if(strpos($content, '</a>') !== false) {
            $context->buildViolation('Merci de respecter la charte d\'utilisation')
                ->atPath('content')
                ->addViolation();
        }
    }

    /**
     * Set link
     *
     * @param string $link
     *
     * @return Post
     */
    public function setLink($link)
    {
        $this->link = $link;

        return $this;
    }

    /**
     * Get link
     *
     * @return string
     */
    public function getLink()
    {
        return $this->link;
    }
}


text:
package p

func _[T interface{~map[string]int}](x T) {
	_ = x == nil
}

// simplified test case from issue

type PathParamsConstraint interface {
        ~map[string]string | ~[]struct{key, value string}
}

type PathParams[T PathParamsConstraint] struct {
	t T
}

func (pp *PathParams[T]) IsNil() bool {
	return pp.t == nil // this must succeed
}


text:
package edu.mit.ll.em.api.dataaccess;

import java.io.Serializable;

import edu.mit.ll.em.api.util.APILogger;

public class ICSDatastoreException extends Exception implements Serializable {

	private static final long serialVersionUID = 6198179929211261881L;

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

	public static void handle(String cname, String msg, Exception e) throws ICSDatastoreException {
		StringBuilder sb = new StringBuilder();
		if (msg != null) {
			sb.append(msg);
		}
		Throwable c = e.getCause();
		if (c != null) {
			String m = c.getMessage();
			if (m != null) {
				sb.append(" - CauseMsg: ").append(m);
			}
		}
		String m = e.getMessage();
		if (m != null) {
			sb.append(" - ExceptionMsg: ").append(m);
		}
		handle(cname, sb.toString());
	}

	public static void handle(String cname, String msg) throws ICSDatastoreException {
		APILogger.getInstance().e(cname, msg);
		throw new ICSDatastoreException(msg);
	}

	public static void logIt(String cname, String msg, Exception e) {
		StringBuilder sb = new StringBuilder();
		if (msg != null) {
			sb.append(msg);
		}
		Throwable c = e.getCause();
		if (c != null) {
			String m = c.getMessage();
			if (m != null) {
				sb.append(" - CauseMsg: ").append(m);
			}
		}
		String m = e.getMessage();
		if (m != null) {
			sb.append(" - ExceptionMsg: ").append(m);
		}
		APILogger.getInstance().e(cname, sb.toString());
	}
}


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <winpr/io.h>

#ifndef _WIN32

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#include <time.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>

#include <fcntl.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <sys/socket.h>

#include <winpr/crt.h>

#include "../handle/handle.h"

#include "../pipe/pipe.h"

BOOL GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped, LPDWORD lpNumberOfBytesTransferred, BOOL bWait)
{
	ULONG Type;
	PVOID Object;

	if (!winpr_Handle_GetInfo(hFile, &Type, &Object))
		return FALSE;

	else if (Type == HANDLE_TYPE_NAMED_PIPE)
	{
		int status = -1;
		DWORD request;
		PVOID lpBuffer;
		DWORD nNumberOfBytes;
		WINPR_NAMED_PIPE* pipe;

		pipe = (WINPR_NAMED_PIPE*) Object;

		if (!(pipe->dwFlagsAndAttributes & FILE_FLAG_OVERLAPPED))
			return FALSE;

		lpBuffer = lpOverlapped->Pointer;
		request = (DWORD) lpOverlapped->Internal;
		nNumberOfBytes = (DWORD) lpOverlapped->InternalHigh;

		if (request == 0)
		{
			if (pipe->clientfd == -1)
				return FALSE;

			status = read(pipe->clientfd, lpBuffer, nNumberOfBytes);
		}
		else if (request == 1)
		{
			if (pipe->clientfd == -1)
				return FALSE;

			status = write(pipe->clientfd, lpBuffer, nNumberOfBytes);
		}
		else if (request == 2)
		{
			socklen_t length;
			struct sockaddr_un s;

			if (pipe->serverfd == -1)
				return FALSE;

			length = sizeof(struct sockaddr_un);
			ZeroMemory(&s, sizeof(struct sockaddr_un));

			status = accept(pipe->serverfd, (struct sockaddr*) &s, &length);

			if (status < 0)
				return FALSE;

			pipe->clientfd = status;
			pipe->ServerMode = FALSE;

			status = 0;
		}

		if (status < 0)
		{
			*lpNumberOfBytesTransferred = 0;
			return FALSE;
		}

		*lpNumberOfBytesTransferred = status;
	}

	return TRUE;
}

BOOL GetOverlappedResultEx(HANDLE hFile, LPOVERLAPPED lpOverlapped, LPDWORD lpNumberOfBytesTransferred, DWORD dwMilliseconds, BOOL bAlertable)
{
	return TRUE;
}

BOOL DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode, LPVOID lpInBuffer, DWORD nInBufferSize,
		LPVOID lpOutBuffer, DWORD nOutBufferSize, LPDWORD lpBytesReturned, LPOVERLAPPED lpOverlapped)
{
	return TRUE;
}

HANDLE CreateIoCompletionPort(HANDLE FileHandle, HANDLE ExistingCompletionPort, ULONG_PTR CompletionKey, DWORD NumberOfConcurrentThreads)
{
	return NULL;
}

BOOL GetQueuedCompletionStatus(HANDLE CompletionPort, LPDWORD lpNumberOfBytesTransferred,
		PULONG_PTR lpCompletionKey, LPOVERLAPPED* lpOverlapped, DWORD dwMilliseconds)
{
	return TRUE;
}

BOOL GetQueuedCompletionStatusEx(HANDLE CompletionPort, LPOVERLAPPED_ENTRY lpCompletionPortEntries,
		ULONG ulCount, PULONG ulNumEntriesRemoved, DWORD dwMilliseconds, BOOL fAlertable)
{
	return TRUE;
}

BOOL PostQueuedCompletionStatus(HANDLE CompletionPort, DWORD dwNumberOfBytesTransferred, ULONG_PTR dwCompletionKey, LPOVERLAPPED lpOverlapped)
{
	return TRUE;
}

BOOL CancelIo(HANDLE hFile)
{
	return TRUE;
}

BOOL CancelIoEx(HANDLE hFile, LPOVERLAPPED lpOverlapped)
{
	return TRUE;
}

BOOL CancelSynchronousIo(HANDLE hThread)
{
	return TRUE;
}

#endif


text:
layout: archive
lang: en
ref: bioloid-beginner
read_time: true
share: true
author_profile: false
permalink: /docs/en/edu/bioloid/beginner/
sidebar:
  title: BIOLOID Beginner
  nav: "bioloid-beginner"
---

# [Introduction](#introduction)

Robots of 4 DOF can be built with Beginner Kit.  This kit is recommended for people who meet robots for the first time.

- Learning the principle of robot building
  - You can build up 14 example robots with Bioloid Beginner Kit and learn the principle of robot building.
  - From a simple barrier bar of 1 DOF to an automobile or walking droid of 4 DOF, it is possible to build the robot and edit the example programs. It will help increasing your understanding for robot programming.
  - Purchasing 4 more AX-12+ for Bioloid Beginner Kit, you can build intermediate-level robots of 8 DOF.
  - Also, purchasing 14 additional AX-12+ for Bioloid Beginner Kit and frame set for Comprehensive Kit, you can build intermediate-level robots and advanced-level robots of 18 DOF.
  - You can also create your one and only robot by designing, assembling and programming it by yourself.

**WARNING** : ROBOTIS BIOLOID Beginner has been discontinued.
{: .notice--warning}

# [Getting Started](#getting-started)

## [Part List](#part-list)

![](/assets/images/edu/bioloid/entry_partlist_en.png)

- [CM-5]
- [AX-12]
- [AX-S1]

## [Preparation](#preparation)

{% include en/edu/bioloid/preparation.md %}

## [Operating](#operating)

{% include en/edu/bioloid/operating.md %}

## [Charging CM-5](#charging-cm-5)

{% include en/parts/controller/charging_cm5.md %}

# [Tutorial](#tutorial)

## [Screen Output](#screen-output)

{% include en/edu/bioloid/screen_output.md %}

## [Button & LED](#button--led)

{% include en/edu/bioloid/button_led.md %}

## [Attacking Duck](#attacking-duck)

{% include en/edu/bioloid/attacking_duck.md %}

## [Obstacle Detecting Car](#obstacle-detecting-car)

{% include en/edu/bioloid/obstacle_detecting_car.md %}

## [Walking Droid 1](#walking-droid-1)

{% include en/edu/bioloid/walking_droid_1.md %}

## [Walking Droid 2](#walking-droid-2)

{% include en/edu/bioloid/walking_droid_2.md %}

## [Walking Droid 3](#walking-droid-3)

{% include en/edu/bioloid/walking_droid_3.md %}

## [Converting .bpg to .tsk](#converting-bpg-to-tsk)

{% include en/edu/bioloid/convert_bpg_tsk.md %}

# [Download](#download)

The following robots have less than 4 joints and the robots can be built with Beginner kit or Comprehensive Kit. Please refer to the assembly manual for Bioloid Beginner Kit and Comprehensive kit about how to assemble.
{: .notice}

## [Download Task Code](#download-task-code)

{% include en/edu/bioloid/download_task.md %}

## [Download Motion File](#download-motion-file)

{% include en/edu/bioloid/download_motion.md %}

## [Examples](#examples)

### Beginner Level

{% include en/edu/bioloid/example_beginner.md %}

# [References](#references)

## [Replacing Fuse(CM-5)](#replacing-fuse-cm-5)

{% include en/parts/controller/fuse_cm_5.md %}

## [DYNAMIXEL Management](#dynamixel-management)

{% include en/edu/bioloid/dynamixel_management.md %}

{% include en/parts/communication/zigbee_control.md %}

## [Control Multiple Robots](#control-multiple-robots)

{% include en/edu/bioloid/control_multirobot.md %}

[CM-5]: /docs/en/parts/controller/cm-5/
[AX-12]: /docs/en/dxl/ax/ax-12a/
[AX-S1]: /docs/en/parts/sensor/ax-s1/


text:
#import <IDEInterfaceBuilderKit/IBDocumentArchivingSchemaEnumeration.h>

@interface IBDocumentArchivingSchemaEnumerationNSUserInterfaceLayoutDirection : IBDocumentArchivingSchemaEnumeration
{
}

+ (id)sharedInstance;

@end