text:
#ifdef INTEL_MKL
#include "tensorflow/cc/ops/const_op.h"
#include "tensorflow/cc/ops/image_ops.h"
#include "tensorflow/cc/ops/nn_ops.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/common_runtime/kernel_benchmark_testlib.h"
#include "tensorflow/core/framework/fake_input.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/kernels/conv_ops_gpu.h"
#include "tensorflow/core/kernels/ops_testutil.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session.h"

namespace tensorflow {

// Helper class for converting MKL tensors to TF tensors and comparing to
// expected values

static const uint8 dummy_tensor[] = {0, 0, 0, 0, 0, 0, 0, 0};
static const TensorShape dummy_shape({8});

using BiasAddGraphRunner =
    std::function<void(const Tensor& input_data, const Tensor& filter_data,
                       const Tensor& bias_data, Tensor* out)>;

using FusedGraphRunner =
    std::function<void(const Tensor& input_data, const Tensor& filter_data,
                       const Tensor& bias_data,
                       const std::vector<string>& fused_ops, Tensor* out)>;

template <typename T>
class CommonTestUtilities : public OpsTestBase {
 public:
  void PerformConversion(DataType dtype, const Tensor& tensor,
                         const Tensor& mkl_meta_tensor, Tensor* output) {
    // Create an MKL to TF conversion node and execute it
    TF_EXPECT_OK(NodeDefBuilder("mkl_to_tf_op", "_MklToTf")
                     .Input(FakeInput(dtype))     // Input
                     .Input(FakeInput(DT_UINT8))  // Mkl second tensor
                     .Attr("T", dtype)
                     .Attr("_kernel", "MklLayoutDependentOp")
                     .Finalize(node_def()));
    TF_EXPECT_OK(InitOp());
    AddInputFromArray<T>(tensor.shape(), tensor.flat<T>());
    AddInputFromArray<uint8>(mkl_meta_tensor.shape(),
                             mkl_meta_tensor.flat<uint8>());
    TF_ASSERT_OK(RunOpKernel());

    *output = *GetOutput(0);
  }

  // Runs a Tensorflow graph defined by the root scope, and fetches the result
  // of 'fetch' node into the output Tensor.
  static void RunAndFetch(const tensorflow::Scope& root, const string& fetch,
                          Tensor* output) {
    tensorflow::GraphDef graph;
    TF_ASSERT_OK(root.ToGraphDef(&graph));

    std::unique_ptr<tensorflow::Session> session(
        tensorflow::NewSession(tensorflow::SessionOptions()));
    TF_ASSERT_OK(session->Create(graph));

    std::vector<Tensor> unfused_tensors;
    TF_ASSERT_OK(session->Run({}, {fetch}, {}, &unfused_tensors));

    *output = unfused_tensors[0];
  }

  void ConvertAndCompare(DataType dtype, const Tensor& tensor,
                         const Tensor& mkl_meta_tensor,
                         const Tensor& expected) {
    Tensor output;
    PerformConversion(dtype, tensor, mkl_meta_tensor, &output);
    test::ExpectTensorNear<T>(expected, output, 1e-5);
  }
  void TestBody() {}

  static void VerifyBiasAddTensorsClose(int depth, int image_width,
                                        int image_height, int image_batch_count,
                                        int filter_size, int filter_count,
                                        const BiasAddGraphRunner& run_default,
                                        const BiasAddGraphRunner& run_fused) {
    DataType dtype = DataTypeToEnum<T>::v();

    Tensor image(dtype, {image_batch_count, image_height, image_width, depth});
    image.flat<T>() = image.flat<T>().setRandom();

    Tensor filter(dtype, {filter_size, filter_size, depth, filter_count});
    filter.flat<T>() = filter.flat<T>().setRandom();

    const int bias_size = filter_count;
    Tensor bias(dtype, {bias_size});
    bias.flat<T>() = bias.flat<T>().setRandom();

    Tensor conv_2d;
    Tensor fused_conv_2d;

    run_default(image, filter, bias, &conv_2d);
    run_fused(image, filter, bias, &fused_conv_2d);

    ASSERT_EQ(conv_2d.dtype(), fused_conv_2d.dtype());
    ASSERT_EQ(conv_2d.shape(), fused_conv_2d.shape());

    test::ExpectClose(conv_2d, fused_conv_2d, 1e-5);
  }

  static void VerifyFusedTensorsClose(int depth, int image_width,
                                      int image_height, int image_batch_count,
                                      int filter_size, int filter_count,
                                      const std::vector<string>& fused_ops,
                                      const FusedGraphRunner& run_default,
                                      const FusedGraphRunner& run_fused) {
    DataType dtype = DataTypeToEnum<T>::v();

    Tensor image(dtype, {image_batch_count, image_height, image_width, depth});
    image.flat<T>() = image.flat<T>().setRandom();

    Tensor filter(dtype, {filter_size, filter_size, depth, filter_count});
    filter.flat<T>() = filter.flat<T>().setRandom();

    const int bias_size = filter_count;
    Tensor bias(dtype, {bias_size});
    bias.flat<T>() = bias.flat<T>().setRandom();

    Tensor conv_2d;
    Tensor fused_conv_2d;

    run_default(image, filter, bias, fused_ops, &conv_2d);
    run_fused(image, filter, bias, fused_ops, &fused_conv_2d);

    ASSERT_EQ(conv_2d.dtype(), fused_conv_2d.dtype());
    ASSERT_EQ(conv_2d.shape(), fused_conv_2d.shape());

    test::ExpectClose(conv_2d, fused_conv_2d, 1e-5);
  }
};

// Testing MKL's fused convolution ops

template <typename T>
class MklFusedConv2DOpTest : public OpsTestBase {
 protected:
  static constexpr int kDepth = 3;
  static constexpr int kImageWidth = 32;
  static constexpr int kImageHeight = 32;
  static constexpr int kImageBatchCount = 8;

  void RunConv2DUnfused(const Tensor& input_data, const Tensor& filter_data,
                        const Tensor& bias_data,
                        const std::vector<string>& fused_ops, Tensor* output,
                        int stride = 1) {
    auto root = tensorflow::Scope::NewRootScope();
    auto input_data_op =
        ops::Const(root.WithOpName("input"), Input::Initializer(input_data));
    Output next_op = ops::Conv2D(
        root.WithOpName("conv"), input_data_op,
        ops::Const(root.WithOpName("filter"), Input::Initializer(filter_data)),
        {1, stride, stride, 1}, "SAME");

    string last_op = "";
    if (std::find(fused_ops.begin(), fused_ops.end(), "BiasAdd") !=
        fused_ops.end()) {
      last_op = "with_bias";
      next_op = ops::BiasAdd(
          root.WithOpName(last_op), next_op,
          ops::Const(root.WithOpName("bias"), Input::Initializer(bias_data)));
    }

    if (std::find(fused_ops.begin(), fused_ops.end(), "Add") !=
        fused_ops.end()) {
      last_op = "with_add";
      next_op = ops::AddN(root.WithOpName("with_add"),
                          std::initializer_list<Input>{next_op, input_data_op});
    }

    if (std::find(fused_ops.begin(), fused_ops.end(), "Relu") !=
        fused_ops.end()) {
      last_op = "with_relu";
      next_op = ops::Relu(root.WithOpName(last_op), next_op);
    }

    if (std::find(fused_ops.begin(), fused_ops.end(), "Relu6") !=
        fused_ops.end()) {
      last_op = "with_relu6";
      next_op = ops::Relu6(root.WithOpName(last_op), next_op);
    }

    if (std::find(fused_ops.begin(), fused_ops.end(), "Elu") !=
        fused_ops.end()) {
      last_op = "with_elu";
      next_op = ops::Relu(root.WithOpName(last_op), next_op);
    }

    CommonTestUtilities<T>::RunAndFetch(root, last_op, output);
  }

  void RunMklFusedConv2DOp(const Tensor& image, const Tensor& filter,
                           const std::vector<Tensor>& args,
                           const std::vector<string>& fused_ops, Tensor* output,
                           int stride = 1) {
    DataType dtype = DataTypeToEnum<T>::v();
    int num_args = static_cast<int>(args.size());

    TF_EXPECT_OK(NodeDefBuilder("fused_conv_op", "_MklFusedConv2D")
                     .Input(FakeInput(dtype))
                     .Input(FakeInput(dtype))
                     .Input(FakeInput(num_args, dtype))
                     .Input(FakeInput(DT_UINT8))
                     .Input(FakeInput(DT_UINT8))
                     .Input(FakeInput(num_args, DT_UINT8))
                     .Attr("T", dtype)
                     .Attr("num_args", num_args)
                     .Attr("strides", {1, stride, stride, 1})
                     .Attr("padding", "SAME")
                     .Attr("fused_ops", fused_ops)
                     .Attr("_kernel", "MklLayoutDependentOp")
                     .Finalize(node_def()));

    TF_EXPECT_OK(InitOp());

    AddInputFromArray<T>(image.shape(), image.flat<T>());
    AddInputFromArray<T>(filter.shape(), filter.flat<T>());
    for (const Tensor& arg : args)
      AddInputFromArray<T>(arg.shape(), arg.flat<T>());
    AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
    AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
    for (const Tensor& arg : args)
      AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
    TF_ASSERT_OK(RunOpKernel());

    // Compare output to expected results
    const Tensor& output_tensor = *GetOutput(0);
    // Index 2 will need to be changed if the number of outputs produced
    // by MklConv2D change.
    const Tensor& output_meta_tensor = *GetOutput(2);
    CommonTestUtilities<T> test_util;
    test_util.PerformConversion(dtype, output_tensor, output_meta_tensor,
                                output);
  }

  // Verifies computing unfused ops in a graph is identical to FusedConv2D.
  void VerifyFusedConv2D(int filter_size, int filter_count,
                         const std::vector<string>& fused_ops,
                         int depth = kDepth, int image_width = kImageWidth,
                         int image_height = kImageHeight,
                         int image_batch_count = kImageBatchCount) {
    const FusedGraphRunner run_default =
        [this](const Tensor& input_data, const Tensor& filter_data,
               const Tensor& bias_data, const std::vector<string>& fused_ops,
               Tensor* out) {
          RunConv2DUnfused(input_data, filter_data, bias_data, fused_ops, out);
        };

    const FusedGraphRunner run_fused =
        [this](const Tensor& input_data, const Tensor& filter_data,
               const Tensor& bias_data, const std::vector<string>& fused_ops,
               Tensor* out) {
          std::vector<Tensor> fused_input = {bias_data};
          if (std::find(fused_ops.begin(), fused_ops.end(), "Add") !=
              fused_ops.end()) {
            fused_input.push_back(input_data);
          }
          RunMklFusedConv2DOp(input_data, filter_data, fused_input, fused_ops,
                              out);
        };

    CommonTestUtilities<T>::VerifyFusedTensorsClose(
        depth, image_width, image_height, image_batch_count, filter_size,
        filter_count, fused_ops, run_default, run_fused);
  }
};

template <typename T>
class MklFusedConv2DWithBiasOpTest : public MklFusedConv2DOpTest<T> {};

TYPED_TEST_CASE_P(MklFusedConv2DWithBiasOpTest);

// -------------------------------------------------------------------------- //
// Conv2D + BiasAdd + {Activation}                                            //
// -------------------------------------------------------------------------- //

TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, OneByOneConvolution) {
  const int kFilterSize = 1;
  const int kFilterCount = 12;
  this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd"});
}

TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, SpatialConvolution) {
  const int kFilterSize = 3;
  const int kFilterCount = 12;
  this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd"});
}

TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, OneByOneConvolutionAndRelu) {
  const int kFilterSize = 1;
  const int kFilterCount = 12;
  this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Relu"});
}

TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, SpatialConvolutionAndRelu) {
  const int kFilterSize = 3;
  const int kFilterCount = 12;
  this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Relu"});
}

TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, OneByOneConvolutionAndRelu6) {
  const int kFilterSize = 1;
  const int kFilterCount = 12;
  this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Relu6"});
}

TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, SpatialConvolutionAndRelu6) {
  const int kFilterSize = 3;
  const int kFilterCount = 12;
  this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Relu6"});
}

TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, OneByOneConvolutionAndElu) {
  const int kFilterSize = 1;
  const int kFilterCount = 12;
  this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Elu"});
}

TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, SpatialConvolutionAndElu) {
  const int kFilterSize = 3;
  const int kFilterCount = 12;
  this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Elu"});
}

TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, OneByOneConvolutionAndAdd) {
  const int kFilterSize = 1;
  const int kFilterCount = 3;
  this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Add"});
}

TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, SpatialConvolutionAndAdd) {
  const int kFilterSize = 3;
  const int kFilterCount = 3;
  this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Add"});
}

TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, OneByOneConvolutionAndAddRelu) {
  const int kFilterSize = 1;
  const int kFilterCount = 3;
  this->VerifyFusedConv2D(kFilterSize, kFilterCount,
                          {"BiasAdd", "Add", "Relu"});
}

TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, SpatialConvolutionAndAddRelu) {
  const int kFilterSize = 3;
  const int kFilterCount = 3;
  this->VerifyFusedConv2D(kFilterSize, kFilterCount,
                          {"BiasAdd", "Add", "Relu"});
}

TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, OneByOneConvolutionAndAddRelu6) {
  const int kFilterSize = 1;
  const int kFilterCount = 3;
  this->VerifyFusedConv2D(kFilterSize, kFilterCount,
                          {"BiasAdd", "Add", "Relu6"});
}

TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, SpatialConvolutionAndAddRelu6) {
  const int kFilterSize = 3;
  const int kFilterCount = 3;
  this->VerifyFusedConv2D(kFilterSize, kFilterCount,
                          {"BiasAdd", "Add", "Relu6"});
}

TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, OneByOneConvolutionAndAddElu) {
  const int kFilterSize = 1;
  const int kFilterCount = 3;
  this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Add", "Elu"});
}

TYPED_TEST_P(MklFusedConv2DWithBiasOpTest, SpatialConvolutionAndAddElu) {
  const int kFilterSize = 3;
  const int kFilterCount = 3;
  this->VerifyFusedConv2D(kFilterSize, kFilterCount, {"BiasAdd", "Add", "Elu"});
}

REGISTER_TYPED_TEST_CASE_P(
    MklFusedConv2DWithBiasOpTest, OneByOneConvolution, SpatialConvolution,
    OneByOneConvolutionAndRelu, SpatialConvolutionAndRelu,
    OneByOneConvolutionAndRelu6, SpatialConvolutionAndRelu6,
    OneByOneConvolutionAndElu, SpatialConvolutionAndElu,
    OneByOneConvolutionAndAdd, SpatialConvolutionAndAdd,
    OneByOneConvolutionAndAddRelu, SpatialConvolutionAndAddRelu,
    OneByOneConvolutionAndAddRelu6, SpatialConvolutionAndAddRelu6,
    OneByOneConvolutionAndAddElu, SpatialConvolutionAndAddElu);

using MklFusedBiasAddDataTypes = ::testing::Types<float>;
INSTANTIATE_TYPED_TEST_CASE_P(Test, MklFusedConv2DWithBiasOpTest,
                              MklFusedBiasAddDataTypes);
// Testing fusion of pad and convolution

class FusedPadConvOpTest : public OpsTestBase {
 public:
  template <typename T>
  void Run(DataType dtype, Tensor& image, Tensor& filter, Tensor& padding,
           Tensor& expected, const string data_format) {
    const int stride = 1;

    // Create a fused pad+conv2d node
    TF_EXPECT_OK(NodeDefBuilder("fused_pad_conv_op", "_MklPadWithConv2D")
                     .Input(FakeInput(dtype))     // Input
                     .Input(FakeInput(dtype))     // Filter
                     .Input(FakeInput(DT_INT32))  // Padding
                     .Input(FakeInput(DT_UINT8))  // MKl second tensor
                     .Input(FakeInput(DT_UINT8))  // MKl second tensor
                     .Input(FakeInput(DT_UINT8))  // MKl second tensor
                     .Attr("padding", "VALID")
                     .Attr("data_format", data_format)
                     .Attr("T", dtype)
                     .Attr("strides", {1, stride, stride, 1})
                     .Attr("_kernel", "MklLayoutDependentOp")
                     .Finalize(node_def()));
    TF_EXPECT_OK(InitOp());

    // Setting up inputs and execute
    AddInputFromArray<T>(image.shape(), image.flat<T>());
    AddInputFromArray<T>(filter.shape(), filter.flat<T>());
    AddInputFromArray<int32>(padding.shape(), padding.flat<int32>());
    AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
    AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
    AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
    TF_ASSERT_OK(RunOpKernel());

    // Compare output to expected results
    const Tensor& first = *GetOutput(0);
    const Tensor& second = *GetOutput(2);
    CommonTestUtilities<T> test_util;
    test_util.ConvertAndCompare(dtype, first, second, expected);
  }
};

TEST_F(FusedPadConvOpTest, PaddingConvTest) {
  const int depth = 1;
  const int image_width = 4;
  const int image_height = 3;
  const int image_batch_count = 1;
  Tensor image(DT_FLOAT, {image_batch_count, image_height, image_width, depth});
  test::FillValues<float>(&image, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12});

  const int kFilterSize = 3;
  const int kFilterCount = 1;
  Tensor filter(DT_FLOAT, {kFilterSize, kFilterSize, depth, kFilterCount});
  test::FillValues<float>(&filter, {1, 4, 7, 2, 5, 8, 3, 6, 9});

  const int padding_height = 4;
  const int padding_width = 2;
  Tensor padding(DT_INT32, {padding_height, padding_width});
  test::FillValues<int32>(&padding, {0, 0, 3, 4, 1, 2, 0, 0});

  Tensor expected(DT_FLOAT, TensorShape({1, 8, 5, 1}));
  test::FillValues<float>(
      &expected,
      {0,  0,   0,   0,   0,   24, 42,  60,  33,  12,  105, 150, 183, 95,
       32, 235, 312, 357, 178, 56, 187, 234, 261, 121, 32,  106, 126, 138,
       59, 12,  0,   0,   0,   0,  0,   0,   0,   0,   0,   0});

  Run<float>(DT_FLOAT, image, filter, padding, expected, "NHWC");
}

TEST_F(FusedPadConvOpTest, PaddingConvTestNchw) {
  const int depth = 1;
  const int image_width = 4;
  const int image_height = 3;
  const int image_batch_count = 1;
  Tensor image(DT_FLOAT, {image_batch_count, depth, image_height, image_width});
  test::FillValues<float>(&image, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12});

  const int kFilterSize = 3;
  const int kFilterCount = 1;
  Tensor filter(DT_FLOAT, {kFilterSize, kFilterSize, depth, kFilterCount});
  test::FillValues<float>(&filter, {1, 4, 7, 2, 5, 8, 3, 6, 9});

  const int padding_height = 4;
  const int padding_width = 2;
  Tensor padding(DT_INT32, {padding_height, padding_width});
  test::FillValues<int32>(&padding, {0, 0, 0, 0, 3, 4, 1, 2});

  Tensor expected(DT_FLOAT, TensorShape({1, 1, 8, 5}));
  test::FillValues<float>(
      &expected,
      {0,  0,   0,   0,   0,   24, 42,  60,  33,  12,  105, 150, 183, 95,
       32, 235, 312, 357, 178, 56, 187, 234, 261, 121, 32,  106, 126, 138,
       59, 12,  0,   0,   0,   0,  0,   0,   0,   0,   0,   0});

  Run<float>(DT_FLOAT, image, filter, padding, expected, "NCHW");
}

class FilterCacheTest : public OpsTestBase {
 public:
  template <typename T>
  void Run(DataType dtype, Tensor& image, Tensor& filter, Tensor& expected,
           const bool is_filter_const) {
    const int stride = 1;

    TF_EXPECT_OK(NodeDefBuilder("conv2d_filter_cache", "_MklConv2D")
                     .Input(FakeInput(dtype))     // Input
                     .Input(FakeInput(dtype))     // Filter
                     .Input(FakeInput(DT_UINT8))  // MKl second tensor
                     .Input(FakeInput(DT_UINT8))  // MKl second tensor
                     .Attr("padding", "VALID")
                     .Attr("data_format", "NHWC")
                     .Attr("is_filter_const", is_filter_const)
                     .Attr("T", dtype)
                     .Attr("strides", {1, stride, stride, 1})
                     .Attr("_kernel", "MklLayoutDependentOp")
                     .Finalize(node_def()));
    TF_EXPECT_OK(InitOp());

    // Setting up inputs and execute
    AddInputFromArray<T>(image.shape(), image.flat<T>());
    AddInputFromArray<T>(filter.shape(), filter.flat<T>());
    AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
    AddInputFromArray<uint8>(dummy_shape, dummy_tensor);

    TF_ASSERT_OK(RunOpKernel());

    // Compare outputs to expected results
    const Tensor& output = *GetOutput(0);
    const Tensor& output_layout = *GetOutput(2);
    CommonTestUtilities<T> conv_comp;
    conv_comp.ConvertAndCompare(dtype, output, output_layout, expected);

    // TODO(bhavanis): For now, we rely on internal performance tests to
    // determine if filter data is being cached and reused.
    // However, we still need to add a check here to determine if this is
    // still the case by inspecting the contents of the persistent tensor.
    TF_ASSERT_OK(RunOpKernel());

    // Compare output to expected results
    const Tensor& output_new = *GetOutput(0);
    const Tensor& output_layout_new = *GetOutput(2);
    CommonTestUtilities<T> conv_comp_new;
    conv_comp_new.ConvertAndCompare(dtype, output_new, output_layout_new,
                                    expected);
  }
};

TEST_F(FilterCacheTest, Conv2DFilterCacheTest) {
  const int depth = 1;
  const int image_width = 4;
  const int image_height = 3;
  const int image_batch_count = 1;
  Tensor image(DT_FLOAT, {image_batch_count, image_height, image_width, depth});
  test::FillValues<float>(&image, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12});

  const int kFilterSize = 3;
  const int kFilterCount = 1;
  Tensor filter(DT_FLOAT, {kFilterSize, kFilterSize, depth, kFilterCount});
  test::FillValues<float>(&filter, {1, 4, 7, 2, 5, 8, 3, 6, 9});

  Tensor expected(DT_FLOAT, TensorShape({1, 1, 2, 1}));
  test::FillValues<float>(&expected, {312, 357});

  Run<float>(DT_FLOAT, image, filter, expected, true);
}

// Testing fusion of pad and fusedconv2d
template <typename T>
class MklPadWithFusedConv2DOpTest : public OpsTestBase {
 protected:
  static constexpr int kDepth = 3;
  static constexpr int kImageWidth = 30;
  static constexpr int kImageHeight = 28;
  static constexpr int kImageBatchCount = 8;

  // 0: top pad, 1: bottom pad, 2: left pad, 3: right pad
  int padding_list_[4];

  // Verifies that computing Pad+Conv2D+BiasAdd in a graph is identical to
  // FusedConv2D.
  void VerifyPadAndConv2DWithBias(int filter_size, int filter_count,
                                  int depth = kDepth,
                                  int image_width = kImageWidth,
                                  int image_height = kImageHeight,
                                  int image_batch_count = kImageBatchCount) {
    const BiasAddGraphRunner run_default = [this](const Tensor& input_data,
                                                  const Tensor& filter_data,
                                                  const Tensor& bias_data,
                                                  Tensor* out) {
      RunMklPadWithFusedConv2DAndBias(input_data, filter_data, bias_data, out);
    };

    const BiasAddGraphRunner run_fused =
        [this](const Tensor& input_data, const Tensor& filter_data,
               const Tensor& bias_data, Tensor* out) {
          RunMklFusedConv2DWithPadOp(input_data, filter_data, {bias_data},
                                     {"BiasAdd"}, out);
        };

    CommonTestUtilities<T>::VerifyBiasAddTensorsClose(
        depth, image_width, image_height, image_batch_count, filter_size,
        filter_count, run_default, run_fused);
  }

  // Verifies that computing Pad+Conv2D+BiasAdd+Relu in a graph is identical to
  // FusedConv2D.
  void VerifyPadAndConv2DWithBiasRelu(
      int filter_size, int filter_count, int depth = kDepth,
      int image_width = kImageWidth, int image_height = kImageHeight,
      int image_batch_count = kImageBatchCount) {
    const BiasAddGraphRunner run_default =
        [this](const Tensor& input_data, const Tensor& filter_data,
               const Tensor& bias_data, Tensor* out) {
          RunMklPadWithFusedConv2DAndBiasRelu(input_data, filter_data,
                                              bias_data, out);
        };

    const BiasAddGraphRunner run_fused =
        [this](const Tensor& input_data, const Tensor& filter_data,
               const Tensor& bias_data, Tensor* out) {
          RunMklFusedConv2DWithPadOp(input_data, filter_data, {bias_data},
                                     {"BiasAdd", "Relu"}, out);
        };

    CommonTestUtilities<T>::VerifyBiasAddTensorsClose(
        depth, image_width, image_height, image_batch_count, filter_size,
        filter_count, run_default, run_fused);
  }

  void RunMklPadWithFusedConv2DAndBias(const Tensor& input_data,
                                       const Tensor& filter_data,
                                       const Tensor& bias_data, Tensor* output,
                                       int stride = 1) {
    auto root = tensorflow::Scope::NewRootScope();

    // FusedConv2D only supports NHWC format so we use NHWC here.
    auto padding = ops::Const(root.WithOpName("padding"),
                              {0, 0, padding_list_[0], padding_list_[1],
                               padding_list_[2], padding_list_[3], 0, 0},
                              {4, 2});
    auto pad = ops::Pad(
        root.WithOpName("pad"),
        ops::Const(root.WithOpName("input"), Input::Initializer(input_data)),
        padding);

    auto conv = ops::Conv2D(
        root.WithOpName("conv"), pad,
        ops::Const(root.WithOpName("filter"), Input::Initializer(filter_data)),
        {1, stride, stride, 1}, "VALID");

    auto with_bias = ops::BiasAdd(
        root.WithOpName("with_bias"), conv,
        ops::Const(root.WithOpName("bias"), Input::Initializer(bias_data)));

    CommonTestUtilities<T>::RunAndFetch(root, "with_bias", output);
  }

  void RunMklPadWithFusedConv2DAndBiasRelu(const Tensor& input_data,
                                           const Tensor& filter_data,
                                           const Tensor& bias_data,
                                           Tensor* output, int stride = 1) {
    auto root = tensorflow::Scope::NewRootScope();

    // FusedConv2D only supports NHWC format so we use NHWC here.
    auto padding = ops::Const(root.WithOpName("padding"),
                              {0, 0, padding_list_[0], padding_list_[1],
                               padding_list_[2], padding_list_[3], 0, 0},
                              {4, 2});
    auto pad = ops::Pad(
        root.WithOpName("pad"),
        ops::Const(root.WithOpName("input"), Input::Initializer(input_data)),
        padding);

    auto conv = ops::Conv2D(
        root.WithOpName("conv"), pad,
        ops::Const(root.WithOpName("filter"), Input::Initializer(filter_data)),
        {1, stride, stride, 1}, "VALID");

    auto with_bias = ops::BiasAdd(
        root.WithOpName("with_bias"), conv,
        ops::Const(root.WithOpName("bias"), Input::Initializer(bias_data)));

    auto with_relu = ops::Relu(root.WithOpName("with_relu"), with_bias);

    CommonTestUtilities<T>::RunAndFetch(root, "with_relu", output);
  }

  void RunMklFusedConv2DWithPadOp(const Tensor& image, const Tensor& filter,
                                  const std::vector<Tensor>& args,
                                  const std::vector<string>& fused_ops,
                                  Tensor* output, int stride = 1) {
    DataType dtype = DataTypeToEnum<T>::v();
    const int num_args = static_cast<int>(args.size());
    Tensor padding(DT_INT32, {4, 2});
    test::FillValues<int32>(
        &padding, {0, 0, padding_list_[0], padding_list_[1], padding_list_[2],
                   padding_list_[3], 0, 0});

    TF_EXPECT_OK(NodeDefBuilder("pad_fused_conv_op", "_MklPadWithFusedConv2D")
                     .Input(FakeInput(dtype))
                     .Input(FakeInput(dtype))
                     .Input(FakeInput(num_args, dtype))
                     .Input(FakeInput(DT_INT32))
                     .Input(FakeInput(DT_UINT8))
                     .Input(FakeInput(DT_UINT8))
                     .Input(FakeInput(num_args, DT_UINT8))
                     .Input(FakeInput(DT_UINT8))
                     .Attr("T", dtype)
                     .Attr("num_args", num_args)
                     .Attr("strides", {1, stride, stride, 1})
                     .Attr("padding", "VALID")
                     .Attr("fused_ops", fused_ops)
                     .Attr("_kernel", "MklLayoutDependentOp")
                     .Finalize(node_def()));

    TF_EXPECT_OK(InitOp());

    AddInputFromArray<T>(image.shape(), image.flat<T>());
    AddInputFromArray<T>(filter.shape(), filter.flat<T>());
    for (const Tensor& arg : args)
      AddInputFromArray<T>(arg.shape(), arg.flat<T>());
    AddInputFromArray<int32>(padding.shape(), padding.flat<int32>());
    // Add MKL meta input for input, filter, pad and agrs.
    for (int i = 0; i < args.size() + 3; ++i)
      AddInputFromArray<uint8>(dummy_shape, dummy_tensor);
    TF_ASSERT_OK(RunOpKernel());

    // Compare output to expected results
    const Tensor& output_tensor = *GetOutput(0);
    // Index 2 will need to be changed if the number of outputs produced
    // by MklConv2D change.
    const Tensor& output_meta_tensor = *GetOutput(2);
    CommonTestUtilities<T> test_util;
    test_util.PerformConversion(dtype, output_tensor, output_meta_tensor,
                                output);
  }

 public:
  void SetPaddingList(int top, int bottom, int left, int right) {
    padding_list_[0] = top;
    padding_list_[1] = bottom;
    padding_list_[2] = left;
    padding_list_[3] = right;
  }
};

TYPED_TEST_CASE_P(MklPadWithFusedConv2DOpTest);

TYPED_TEST_P(MklPadWithFusedConv2DOpTest, WithBiasAndRoundPad) {
  const int kFilterSize = 1;
  const int kFilterCount = 12;
  this->SetPaddingList(2, 2, 1, 1);
  this->VerifyPadAndConv2DWithBias(kFilterSize, kFilterCount);
}

TYPED_TEST_P(MklPadWithFusedConv2DOpTest, WithBiasAndPartialPad) {
  const int kFilterSize = 1;
  const int kFilterCount = 12;
  this->SetPaddingList(4, 0, 2, 0);
  this->VerifyPadAndConv2DWithBias(kFilterSize, kFilterCount);
}

TYPED_TEST_P(MklPadWithFusedConv2DOpTest, WithBiasReluAndRoundPad) {
  const int kFilterSize = 1;
  const int kFilterCount = 12;
  this->SetPaddingList(2, 2, 1, 1);
  this->VerifyPadAndConv2DWithBiasRelu(kFilterSize, kFilterCount);
}

TYPED_TEST_P(MklPadWithFusedConv2DOpTest, WithBiasReluAndPartialPad) {
  const int kFilterSize = 1;
  const int kFilterCount = 12;
  this->SetPaddingList(4, 0, 2, 0);
  this->VerifyPadAndConv2DWithBiasRelu(kFilterSize, kFilterCount);
}

REGISTER_TYPED_TEST_CASE_P(MklPadWithFusedConv2DOpTest,  //
                           WithBiasAndRoundPad,          //
                           WithBiasAndPartialPad,        //
                           WithBiasReluAndRoundPad,      //
                           WithBiasReluAndPartialPad);

using MklPadWithFusedConv2DDataTypes = ::testing::Types<float>;
INSTANTIATE_TYPED_TEST_CASE_P(Test, MklPadWithFusedConv2DOpTest,
                              MklPadWithFusedConv2DDataTypes);

}  // namespace tensorflow
#endif  // INTEL_MKL


text:
/**
 *
 */

package org.opensaml.saml2.core.impl;

import org.opensaml.common.impl.AbstractSAMLObjectMarshaller;
import org.opensaml.saml2.core.NewID;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.io.MarshallingException;
import org.opensaml.xml.util.XMLHelper;
import org.w3c.dom.Element;

/**
 * A thread safe Marshaller for {@link org.opensaml.saml2.core.NewID} objects.
 */
public class NewIDMarshaller extends AbstractSAMLObjectMarshaller {

    /** {@inheritDoc} */
    protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException {
        NewID newID = (NewID) samlObject;

        if (newID.getNewID() != null) {
            XMLHelper.appendTextContent(domElement, newID.getNewID());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
select count(*) as count, 'BothProcesses' as description
from experimental_flamegraph
where
  upid_group = (
    select group_concat(distinct upid)
    from perf_sample join thread t using (utid) join process p using (upid)
  )
  and profile_type = 'perf'
  and ts <= 7689491063351
  and size > 0
union all
select count(*) as count, 'FirstProcess' as description
from experimental_flamegraph
  join process using (upid)
where pid = 1728
  and profile_type = 'perf'
  and ts <= 7689491063351
  and size > 0
union all
select count(*) as count, 'SecondProcess' as description
from experimental_flamegraph
  join process using (upid)
where pid = 703
  and profile_type = 'perf'
  and ts <= 7689491063351
  and size > 0;


text:
<?php
namespace HcBackend\Stdlib\Extractor\Request\Payload;

use Zend\Http\PhpEnvironment\Request;
use Zend\Json\Json;
use Zf2Libs\Stdlib\Extractor\ExtractorInterface;
use Zf2Libs\Stdlib\Extractor\Exception\InvalidArgumentException;

class Extractor implements ExtractorInterface
{
    /**
     * @var Json
     */
    protected $jsonService;

    public function __construct(Json $jsonService)
    {
        $this->jsonService = $jsonService;
    }

    /**
     * Extract values from an object
     *
     * @param object $request
     * @throws \Zf2Libs\Stdlib\Extractor\Exception\InvalidArgumentException
     * @internal param object $user
     * @return mixed
     */
    public function extract($request)
    {
        if (!$request instanceof Request) {
            throw new InvalidArgumentException("Expected Request object, invalid object given");
        }

        if (!in_array($request->getMethod(), array('POST', 'PUT', 'PATCH'))) {
            return array();
        }

        if ($request->getHeader('ContentType')->getFieldValue() == 'application/json' &&
            strlen($request->getContent()) > 0) {
            return (array)$this->jsonService->decode($request->getContent());
        } else {
            return $request->getPost()->toArray();
        }
    }
}


text:
(function ($) {
  // register namespace
  $.extend(true, window, {
    "Slick": {
      "CellExternalCopyManager": CellExternalCopyManager
    }
  });

  function CellExternalCopyManager(options) {
    /*
      This manager enables users to copy/paste data from/to an external Spreadsheet application

      Since it is not possible to access directly the clipboard in javascript, the plugin uses
      a trick to do it's job. After detecting the keystroke, we dynamically create a textarea
      where the browser copies/pastes the serialized data.

      options:
        copiedCellStyle : sets the css className used for copied cells. default : "copied"
        copiedCellStyleLayerKey : sets the layer key for setting css values of copied cells. default : "copy-manager"
        dataItemColumnValueExtractor : option to specify a custom column value extractor function
        dataItemColumnValueSetter : option to specify a custom column value setter function
    */
    var _grid;
    var _self = this;
    var _copiedRanges;
    var _options = options || {};
    var _copiedCellStyleLayerKey = _options.copiedCellStyleLayerKey || "copy-manager";
    var _copiedCellStyle = _options.copiedCellStyle || "copied";
    var _clearCopyTI = 0;

    var keyCodes = {
      'C':67,
      'V':86
    }

    function init(grid) {
      _grid = grid;
      _grid.onKeyDown.subscribe(handleKeyDown);

      // we need a cell selection model
      var cellSelectionModel = grid.getSelectionModel();
      if (!cellSelectionModel){
        throw new Error("Selection model is mandatory for this plugin. Please set a selection model on the grid before adding this plugin: grid.setSelectionModel(new Slick.CellSelectionModel())");
      }
      // we give focus on the grid when a selection is done on it.
      // without this, if the user selects a range of cell without giving focus on a particular cell, the grid doesn't get the focus and key stroke handles (ctrl+c) don't work
      cellSelectionModel.onSelectedRangesChanged.subscribe(function(e, args){
        _grid.focus();
      });
    }

    function destroy() {
      _grid.onKeyDown.unsubscribe(handleKeyDown);
    }

    function getDataItemValueForColumn(item, columnDef) {
      if (_options.dataItemColumnValueExtractor) {
        return _options.dataItemColumnValueExtractor(item, columnDef);
      }
      // if a custom getter is not defined, we call serializeValue of the editor to serialize
      var editorArgs = {
        'container':$(document),  // a dummy container
        'column':columnDef
      };
      var editor = new columnDef.editor(editorArgs);
      var retVal = '';
      editor.loadValue(item);
      retVal = editor.serializeValue();
      editor.destroy();

      return retVal;
    }

    function setDataItemValueForColumn(item, columnDef, value) {
      if (_options.dataItemColumnValueSetter) {
        return _options.dataItemColumnValueSetter(item, columnDef, value);
      }
      // if a custom setter is not defined, we call applyValue of the editor to unserialize
      var editorArgs = {
        'container':$(document),  // a dummy container
        'column':columnDef
      };
      var editor = new columnDef.editor(editorArgs);
      editor.loadValue(item);
      editor.applyValue(item, value);
      editor.destroy();
    }

    function _createTextBox(innerText){
      var ta = document.createElement('textarea');
      ta.style.position = 'absolute';
      ta.style.left = '-1000px';
      ta.style.top = '-1000px';
      ta.value = innerText;
      document.body.appendChild(ta);
      ta.focus();

      return ta;
    }

    function _decodeTabularData(_grid, ta){
      var columns = _grid.getColumns();
      var clipText = ta.value;
      var clipRows = clipText.split(/[\n\f\r]/);
      var clippedRange = [];

      document.body.removeChild(ta);

      for (var i=0; i<clipRows.length; i++) {
        if (clipRows[i]!="")
          clippedRange[i] = clipRows[i].split("\t");
      }

      var selectedCell = _grid.getActiveCell();
      var ranges = _grid.getSelectionModel().getSelectedRanges();
      var selectedRange = ranges && ranges.length ? ranges[0] : null;   // pick only one selection
      var activeRow = null;
      var activeCell = null;

      if (selectedRange){
        activeRow = selectedRange.fromRow;
        activeCell = selectedRange.fromCell;
      } else if (selectedCell){
        activeRow = selectedCell.row;
        activeCell = selectedCell.cell;
      } else {
        // we don't know where to paste
        return;
      }

      var oneCellToMultiple = false;
      var destH = clippedRange.length;
      var destW = clippedRange.length ? clippedRange[0].length : 0;
      if (clippedRange.length == 1 && clippedRange[0].length == 1 && selectedRange){
        oneCellToMultiple = true;
        destH = selectedRange.toRow - selectedRange.fromRow +1;
        destW = selectedRange.toCell - selectedRange.fromCell +1;
      }

      var desty = activeRow;
      var destx = activeCell;
      var h = 0;
      var w = 0;

      for (var y = 0; y < destH; y++){
        h++;
        w=0;
        for (var x = 0; x < destW; x++){
          w++;
          var desty = activeRow + y;
          var destx = activeCell + x;

          if (desty < data.length && destx < grid.getColumns().length ) {
            var nd = _grid.getCellNode(desty, destx);
            var dt = _grid.getDataItem(desty);
            if (oneCellToMultiple)
              setDataItemValueForColumn(dt, columns[destx], clippedRange[0][0]);
            else
              setDataItemValueForColumn(dt, columns[destx], clippedRange[y][x]);
            _grid.updateCell(desty, destx);
          }
        }
      }

      var bRange = {
        'fromCell': activeCell,
        'fromRow': activeRow,
        'toCell': activeCell+w-1,
        'toRow': activeRow+h-1
      }

      markCopySelection([bRange]);
      _grid.getSelectionModel().setSelectedRanges([bRange]);
      _self.onPasteCells.notify({ranges: [bRange]});
    }

    function handleKeyDown(e, args) {
      var ranges;
      if (!_grid.getEditorLock().isActive()) {
        if (e.which == frappe.ui.keyCode.ESCAPE) {
          if (_copiedRanges) {
            e.preventDefault();
            clearCopySelection();
            _self.onCopyCancelled.notify({ranges: _copiedRanges});
            _copiedRanges = null;
          }
        }

        if (e.which == keyCodes.C && (e.ctrlKey || e.metaKey)) {    // CTRL + C
          ranges = _grid.getSelectionModel().getSelectedRanges();
          if (ranges.length != 0) {
            _copiedRanges = ranges;
            markCopySelection(ranges);
            _self.onCopyCells.notify({ranges: ranges});

            var columns = _grid.getColumns();
            var clipTextArr = [];

            for (var rg = 0; rg < ranges.length; rg++){
                var range = ranges[rg];
                var clipTextRows = [];
                for (var i=range.fromRow; i< range.toRow+1 ; i++){
                    var clipTextCells = [];
                    var dt = _grid.getDataItem(i);

                    for (var j=range.fromCell; j< range.toCell+1 ; j++){
                        clipTextCells.push(getDataItemValueForColumn(dt, columns[j]));
                    }
                    clipTextRows.push(clipTextCells.join("\t"));
                }
                clipTextArr.push(clipTextRows.join("\r\n"));
            }
            var clipText = clipTextArr.join('');
            var ta = _createTextBox(clipText);
            $(ta).select();

            setTimeout(function(){
                document.body.removeChild(ta);
            }, 100);

            return false;
          }
        }

        if (e.which == keyCodes.V && (e.ctrlKey || e.metaKey)) {    // CTRL + V
            var ta = _createTextBox('');

            setTimeout(function(){
                _decodeTabularData(_grid, ta);
            }, 100);

            return false;
        }
      }
    }

    function markCopySelection(ranges) {
      clearCopySelection();

      var columns = _grid.getColumns();
      var hash = {};
      for (var i = 0; i < ranges.length; i++) {
        for (var j = ranges[i].fromRow; j <= ranges[i].toRow; j++) {
          hash[j] = {};
          for (var k = ranges[i].fromCell; k <= ranges[i].toCell && k<columns.length; k++) {
            hash[j][columns[k].id] = _copiedCellStyle;
          }
        }
      }
      _grid.setCellCssStyles(_copiedCellStyleLayerKey, hash);
      clearTimeout(_clearCopyTI);
      _clearCopyTI = setTimeout(function(){
        _self.clearCopySelection();
      }, 2000);
    }

    function clearCopySelection() {
      _grid.removeCellCssStyles(_copiedCellStyleLayerKey);
    }

    $.extend(this, {
      "init": init,
      "destroy": destroy,
      "clearCopySelection": clearCopySelection,
      "handleKeyDown":handleKeyDown,
      "onCopyCells": new Slick.Event(),
      "onCopyCancelled": new Slick.Event(),
      "onPasteCells": new Slick.Event()
    });
  }
})(jQuery);


text:
/**
 * @file   ProcessManagerTest.cpp
 * @brief  ProcessManager class tester.
 * @author zer0
 * @date   2017-07-29
 */

#include <gtest/gtest.h>
#include <libtbag/log/Log.hpp>
#include <libtbag/uvpp/Loop.hpp>
#include <libtbag/process/ProcessManager.hpp>
#include <libtbag/filesystem/Path.hpp>

#include <atomic>

using namespace libtbag;
using namespace libtbag::process;
using namespace libtbag::uvpp;

TEST(ProcessManagerTest, Default)
{
    log::SeverityGuard guard;

    std::string const EXE_NAME = "tbproc";
    std::string const TEST_OUT = "test_output_string";

    using Path = filesystem::Path;
    Path const PATH = Path::getExeDir() / filesystem::getExecutableName(EXE_NAME);

    int const TEST_COUNT = 10;
    std::atomic_int on_read(0);
    std::atomic_int on_error(0);
    std::atomic_int on_exit(0);

    ProcessManager pm;
    pm.out_read_cb = [&](int pid, char const * buffer, std::size_t size){
        ++on_read;
    };
    pm.err_read_cb = [&](int pid, char const * buffer, std::size_t size){
        ++on_error;
    };
    pm.exit_cb = [&](int pid, int64_t exit_status, int term_signal){
        ++on_exit;
    };

    for (int i = 0; i < TEST_COUNT; ++i) {
        ASSERT_NE(0, pm.exec(PATH.toString(), {"out"}, {}, std::string(), TEST_OUT));
    }
    pm.joinAll();

    ASSERT_EQ(TEST_COUNT, pm.size());
    ASSERT_FALSE(pm.empty());
    auto list = pm.list();
    ASSERT_EQ(TEST_COUNT, list.size());
    for (auto & proc : list) {
        auto shared = pm.get(proc.pid).lock();
        ASSERT_EQ(0, shared->getExitStatus());
        ASSERT_EQ(0, shared->getTermSignal());
    }
    ASSERT_EQ(TEST_COUNT, on_read);
    ASSERT_EQ(0, on_error);
    ASSERT_EQ(TEST_COUNT, on_exit);
}


text:
{% extends "base.html" %}
{% block content %}

About Dance Cat

      Dance Cat just want to dance with you.

      Meow!

    Dance Cat's Github Repository

{% endblock %}


text:
var expect = require('chai').expect;
var DeploymentNotification = require('../../models/deployment_notification');

describe('DeploymentNotification', function() {
    var subject, jsonHash;
    beforeEach(function() {
        jsonHash = {
            "deploymentHref": "http://cicd/deployments/12345"
        }
        subject = DeploymentNotification(jsonHash);
    });
    describe('#constructor(jsonHash)', function() {
        it('returns an instance of DeploymentNotification', function() {
            expect(subject).not.to.be.null;
        });
    });
    describe('#toJSONString()', function() {
        it('gives me the jsonHash i expect', function() {
            expect(subject.toJSONString()).to.equal(JSON.stringify(jsonHash));
        });
    });
});


text:
/*
 * mutex6d.c
 *
 * Tests PTHREAD_MUTEX_DEFAULT mutex type.
 * Thread locks mutex twice (recursive lock).
 * The thread should deadlock.
 *
 * Depends on API functions:
 *      pthread_create()
 *      pthread_mutexattr_init()
 *      pthread_mutexattr_settype()
 *      pthread_mutexattr_gettype()
 *      pthread_mutex_init()
 *	pthread_mutex_lock()
 *	pthread_mutex_unlock()
 */

#include "test.h"

static int lockCount = 0;

static pthread_mutex_t mutex;
static pthread_mutexattr_t mxAttr;

void * locker(void * arg)
{
  assert(pthread_mutex_lock(&mutex) == 0);
  lockCount++;

  /* Should wait here (deadlocked) */
  assert(pthread_mutex_lock(&mutex) == 0);
  lockCount++;
  assert(pthread_mutex_unlock(&mutex) == 0);

  return (void *) 555;
}

int
main()
{
  pthread_t t;
  int mxType = -1;

  assert(pthread_mutexattr_init(&mxAttr) == 0);
  assert(pthread_mutexattr_settype(&mxAttr, PTHREAD_MUTEX_DEFAULT) == 0);
  assert(pthread_mutexattr_gettype(&mxAttr, &mxType) == 0);
  assert(mxType == PTHREAD_MUTEX_NORMAL);

  assert(pthread_mutex_init(&mutex, &mxAttr) == 0);

  assert(pthread_create(&t, NULL, locker, NULL) == 0);

  Sleep(1000);

  assert(lockCount == 1);

  /*
   * Should succeed even though we don't own the lock
   * because FAST mutexes don't check ownership.
   */
  assert(pthread_mutex_unlock(&mutex) == 0);

  Sleep (1000);

  assert(lockCount == 2);

  exit(0);

  /* Never reached */
  return 0;
}


text:
import EventsEmitter from 'EventsEmitter'
import './TransformGizmos'

export default class TransformTool extends EventsEmitter {

  /////////////////////////////////////////////////////////////////
  // Class constructor
  //
  /////////////////////////////////////////////////////////////////
  constructor (viewer) {

    super()

    viewer.toolController.registerTool(this)

    this._viewer = viewer

    this._dbIds = []

    this._hitPoint = null

    this._selectSet = null

    this._isDragging = false

    this._transformMesh = null

    this._modifiedFragIdMap = {}

    this._transformControlTx = null

    this._selectedFragProxyMap = {}

    this.onTxChange =
      this.onTxChange.bind(this)

    this.onAggregateSelectionChanged =
      this.onAggregateSelectionChanged.bind(this)

    this.onCameraChanged =
      this.onCameraChanged.bind(this)

    this.handleSelectionChanged =
      this.handleSelectionChanged.bind(this)
  }

  /////////////////////////////////////////////////////////////////
  //
  //
  /////////////////////////////////////////////////////////////////
  getNames() {

    return ["Viewing.Transform.Tool"]
  }

  /////////////////////////////////////////////////////////////////
  //
  //
  /////////////////////////////////////////////////////////////////
  getName() {

    return "Viewing.Transform.Tool"
  }

  ///////////////////////////////////////////////////////////////////////////
  // Creates a dummy mesh to attach control to
  //
  ///////////////////////////////////////////////////////////////////////////
  createTransformMesh() {

    var material = new THREE.MeshPhongMaterial(
      { color: 0xff0000 })

    this._viewer.impl.matman().addMaterial(
      'transform-tool-material',
      material,
      true)

    var sphere = new THREE.Mesh(
      new THREE.SphereGeometry(0.0001, 5),
      material)

    sphere.position.set(0, 0, 0)

    return sphere
  }

  ///////////////////////////////////////////////////////////////////////////
  // on translation change
  //
  ///////////////////////////////////////////////////////////////////////////
  onTxChange() {

    for(var fragId in this._selectedFragProxyMap) {

      var fragProxy = this._selectedFragProxyMap[fragId]

      var position = new THREE.Vector3(
        this._transformMesh.position.x - fragProxy.offset.x,
        this._transformMesh.position.y - fragProxy.offset.y,
        this._transformMesh.position.z - fragProxy.offset.z)

      fragProxy.position = position

      fragProxy.updateAnimTransform()
    }

    this._viewer.impl.sceneUpdated(true)

    this.emit('transform.TxChange', {
      dbIds: this._dbIds,
      fragIds: Object.keys(this._selectedFragProxyMap)
    })
  }

  ///////////////////////////////////////////////////////////////////////////
  // on camera changed
  //
  ///////////////////////////////////////////////////////////////////////////
  onCameraChanged() {

    if(this._transformControlTx) {

      this._transformControlTx.update()
    }
  }

  ///////////////////////////////////////////////////////////////////////////
  // item selected callback
  //
  ///////////////////////////////////////////////////////////////////////////
  onAggregateSelectionChanged(event) {

    var dbIdArray = []
    var fragIdsArray = []

    if(event.selections && event.selections.length) {

      var selection = event.selections[0]

      dbIdArray = selection.dbIdArray

      fragIdsArray = selection.fragIdsArray
    }

    this.handleSelectionChanged(dbIdArray, fragIdsArray)
  }

  handleSelectionChanged(dbIdArray, fragIdsArray) {

    this._selectedFragProxyMap = {}

    this._dbIds = dbIdArray

    //component unselected

    if(!fragIdsArray.length) {

      this._hitPoint = null

      this._transformControlTx.visible = false

      this._transformControlTx.removeEventListener(
        'change', this.onTxChange)

      this._viewer.removeEventListener(
        Autodesk.Viewing.CAMERA_CHANGE_EVENT,
        this.onCameraChanged)

      this.emit('transform.select', {
        dbIds: this._dbIds
      })

      return
    }

    if (this._hitPoint) {

      this._selectSet = this.emit('transform.select', {
        dbIds: this._dbIds
      })

      if (this._selectSet) {

        if (!this._selectSet.selectable) {
          this._hitPoint = null
          this._viewer.select([])
          return
        }

        if (!this._selectSet.transformable) {
          this._hitPoint = null
          return
        }
      }

      this._transformControlTx.visible = true

      this._transformControlTx.setPosition(
        this._hitPoint)

      this._transformControlTx.addEventListener(
        'change', this.onTxChange)

      this._viewer.addEventListener(
        Autodesk.Viewing.CAMERA_CHANGE_EVENT,
        this.onCameraChanged)

      fragIdsArray.forEach((fragId)=> {

        var fragProxy = this._viewer.impl.getFragmentProxy(
          this._viewer.model,
          fragId)

        fragProxy.getAnimTransform()

        var offset = {

          x: this._hitPoint.x - fragProxy.position.x,
          y: this._hitPoint.y - fragProxy.position.y,
          z: this._hitPoint.z - fragProxy.position.z
        }

        fragProxy.offset = offset

        this._selectedFragProxyMap[fragId] = fragProxy

        this._modifiedFragIdMap[fragId] = {}
      })

      this._hitPoint = null
    }
  }

  ///////////////////////////////////////////////////////////////////////////
  // normalize screen coordinates
  //
  ///////////////////////////////////////////////////////////////////////////
  normalize(screenPoint) {

    var viewport = this._viewer.navigation.getScreenViewport()

    var n = {
      x: (screenPoint.x - viewport.left) / viewport.width,
      y: (screenPoint.y - viewport.top) / viewport.height
    }

    return n
  }

  ///////////////////////////////////////////////////////////////////////////
  // get 3d hit point on mesh
  //
  ///////////////////////////////////////////////////////////////////////////
  getHitPoint(event) {

    var screenPoint = {
      x: event.clientX,
      y: event.clientY
    }

    var n = this.normalize(screenPoint)

    var hitPoint = this._viewer.utilities.getHitPoint(n.x, n.y)

    return hitPoint
  }

  ///////////////////////////////////////////////////////////////////
  //
  //
  ///////////////////////////////////////////////////////////////////
  activate() {

    if (!this.active) {

      console.log(this.getName() + ' activated')

      this.active = true

      this._viewer.select([])

      var bbox = this._viewer.model.getBoundingBox()

      this._viewer.impl.createOverlayScene(
        'TransformToolOverlay')

      this._transformControlTx = new THREE.TransformControls(
        this._viewer.impl.camera,
        this._viewer.impl.canvas,
        "translate")

      this._transformControlTx.setSize(
        bbox.getBoundingSphere().radius * 5)

      this._transformControlTx.visible = false

      this._viewer.impl.addOverlay(
        'TransformToolOverlay',
        this._transformControlTx)

      this._transformMesh = this.createTransformMesh()

      this._transformControlTx.attach(
        this._transformMesh)

      this._viewer.addEventListener(
        Autodesk.Viewing.AGGREGATE_SELECTION_CHANGED_EVENT,
        this.onAggregateSelectionChanged)

      this._viewer.toolController.activateTool(
        this.getName())

      this.emit('activate')
    }
  }

  ///////////////////////////////////////////////////////////////////////////
  // deactivate tool
  //
  ///////////////////////////////////////////////////////////////////////////
  deactivate() {

    if (this.active) {

      console.log(this.getName() + ' deactivated')

      this.active = false

      this.viewer.toolController.deactivateTool(
        this.getName())

      this._viewer.impl.removeOverlay(
        'TransformToolOverlay',
        this._transformControlTx)

      this._transformControlTx.removeEventListener(
        'change',
        this.onTxChange)

      this._transformControlTx = null

      this._viewer.impl.removeOverlayScene(
        'TransformToolOverlay')

      this._viewer.removeEventListener(
        Autodesk.Viewing.CAMERA_CHANGE_EVENT,
        this.onCameraChanged)

      this._viewer.removeEventListener(
        Autodesk.Viewing.AGGREGATE_SELECTION_CHANGED_EVENT,
        this.onAggregateSelectionChanged)

      this.emit('deactivate')
    }
  }

  ///////////////////////////////////////////////////////////////////////////
  //
  //
  ///////////////////////////////////////////////////////////////////////////
  handleButtonDown(event, button) {

    this._hitPoint = this.getHitPoint(event)

    this._isDragging = true

    if (this._transformControlTx.onPointerDown(event))
      return true

    //return _transRotControl.onPointerDown(event)
    return false
  }

  ///////////////////////////////////////////////////////////////////////////
  //
  //
  ///////////////////////////////////////////////////////////////////////////
  handleButtonUp(event, button) {

    this._isDragging = false

    if (this._transformControlTx.onPointerUp(event))
      return true

    //return _transRotControl.onPointerUp(event)
    return false
  }

  ///////////////////////////////////////////////////////////////////////////
  //
  //
  ///////////////////////////////////////////////////////////////////////////
  handleMouseMove(event) {

    if (this._isDragging) {

      if (this._transformControlTx.onPointerMove(event) ) {

        return true
      }

      return false
    }

    if (this._transformControlTx.onPointerHover(event))
      return true

    //return _transRotControl.onPointerHover(event)
    return false
  }
}


text:
/**
 * @module ol/interaction/Translate
 */
import Collection from '../Collection.js';
import {getChangeEventType} from '../Object.js';
import {listen} from '../events.js';
import Event from '../events/Event.js';
import {TRUE} from '../functions.js';
import {includes} from '../array.js';
import PointerInteraction from '../interaction/Pointer.js';
import InteractionProperty from '../interaction/Property.js';

/**
 * @enum {string}
 */
var TranslateEventType = {
  /**
   * Triggered upon feature translation start.
   * @event TranslateEvent#translatestart
   * @api
   */
  TRANSLATESTART: 'translatestart',
  /**
   * Triggered upon feature translation.
   * @event TranslateEvent#translating
   * @api
   */
  TRANSLATING: 'translating',
  /**
   * Triggered upon feature translation end.
   * @event TranslateEvent#translateend
   * @api
   */
  TRANSLATEEND: 'translateend'
};

/**
 * @typedef {Object} Options
 * @property {module:ol/Collection<module:ol/Feature>} [features] Only features contained in this collection will be able to be translated. If
 * not specified, all features on the map will be able to be translated.
 * @property {Array<module:ol/layer/Layer>|function(module:ol/layer/Layer): boolean} [layers] A list of layers from which features should be
 * translated. Alternatively, a filter function can be provided. The
 * function will be called for each layer in the map and should return
 * `true` for layers that you want to be translatable. If the option is
 * absent, all visible layers will be considered translatable.
 * @property {number} [hitTolerance=0] Hit-detection tolerance. Pixels inside the radius around the given position
 * will be checked for features. This only works for the canvas renderer and
 * not for WebGL.
 */

/**
 * @classdesc
 * Events emitted by {@link module:ol/interaction/Translate~Translate} instances
 * are instances of this type.
 */
export var TranslateEvent = (function (Event) {
  function TranslateEvent(type, features, coordinate) {

    Event.call(this, type);

    /**
     * The features being translated.
     * @type {module:ol/Collection<module:ol/Feature>}
     * @api
     */
    this.features = features;

    /**
     * The coordinate of the drag event.
     * @const
     * @type {module:ol/coordinate~Coordinate}
     * @api
     */
    this.coordinate = coordinate;

  }

  if ( Event ) TranslateEvent.__proto__ = Event;
  TranslateEvent.prototype = Object.create( Event && Event.prototype );
  TranslateEvent.prototype.constructor = TranslateEvent;

  return TranslateEvent;
}(Event));

/**
 * @classdesc
 * Interaction for translating (moving) features.
 *
 * @fires module:ol/interaction/Translate~TranslateEvent
 * @api
 */
var Translate = (function (PointerInteraction) {
  function Translate(opt_options) {
    PointerInteraction.call(this, {
      handleDownEvent: handleDownEvent,
      handleDragEvent: handleDragEvent,
      handleMoveEvent: handleMoveEvent,
      handleUpEvent: handleUpEvent
    });

    var options = opt_options ? opt_options : {};

    /**
     * The last position we translated to.
     * @type {module:ol/coordinate~Coordinate}
     * @private
     */
    this.lastCoordinate_ = null;

    /**
     * @type {module:ol/Collection<module:ol/Feature>}
     * @private
     */
    this.features_ = options.features !== undefined ? options.features : null;

    /** @type {function(module:ol/layer/Layer): boolean} */
    var layerFilter;
    if (options.layers) {
      if (typeof options.layers === 'function') {
        layerFilter = options.layers;
      } else {
        var layers = options.layers;
        layerFilter = function(layer) {
          return includes(layers, layer);
        };
      }
    } else {
      layerFilter = TRUE;
    }

    /**
     * @private
     * @type {function(module:ol/layer/Layer): boolean}
     */
    this.layerFilter_ = layerFilter;

    /**
     * @private
     * @type {number}
     */
    this.hitTolerance_ = options.hitTolerance ? options.hitTolerance : 0;

    /**
     * @type {module:ol/Feature}
     * @private
     */
    this.lastFeature_ = null;

    listen(this,
      getChangeEventType(InteractionProperty.ACTIVE),
      this.handleActiveChanged_, this);

  }

  if ( PointerInteraction ) Translate.__proto__ = PointerInteraction;
  Translate.prototype = Object.create( PointerInteraction && PointerInteraction.prototype );
  Translate.prototype.constructor = Translate;

  /**
   * Tests to see if the given coordinates intersects any of our selected
   * features.
   * @param {module:ol/pixel~Pixel} pixel Pixel coordinate to test for intersection.
   * @param {module:ol/PluggableMap} map Map to test the intersection on.
   * @return {module:ol/Feature} Returns the feature found at the specified pixel
   * coordinates.
   * @private
   */
  Translate.prototype.featuresAtPixel_ = function featuresAtPixel_ (pixel, map) {
    return map.forEachFeatureAtPixel(pixel,
      function(feature) {
        if (!this.features_ || includes(this.features_.getArray(), feature)) {
          return feature;
        }
      }.bind(this), {
        layerFilter: this.layerFilter_,
        hitTolerance: this.hitTolerance_
      });
  };

  /**
   * Returns the Hit-detection tolerance.
   * @returns {number} Hit tolerance in pixels.
   * @api
   */
  Translate.prototype.getHitTolerance = function getHitTolerance () {
    return this.hitTolerance_;
  };

  /**
   * Hit-detection tolerance. Pixels inside the radius around the given position
   * will be checked for features. This only works for the canvas renderer and
   * not for WebGL.
   * @param {number} hitTolerance Hit tolerance in pixels.
   * @api
   */
  Translate.prototype.setHitTolerance = function setHitTolerance (hitTolerance) {
    this.hitTolerance_ = hitTolerance;
  };

  /**
   * @inheritDoc
   */
  Translate.prototype.setMap = function setMap (map) {
    var oldMap = this.getMap();
    PointerInteraction.prototype.setMap.call(this, map);
    this.updateState_(oldMap);
  };

  /**
   * @private
   */
  Translate.prototype.handleActiveChanged_ = function handleActiveChanged_ () {
    this.updateState_(null);
  };

  /**
   * @param {module:ol/PluggableMap} oldMap Old map.
   * @private
   */
  Translate.prototype.updateState_ = function updateState_ (oldMap) {
    var map = this.getMap();
    var active = this.getActive();
    if (!map || !active) {
      map = map || oldMap;
      if (map) {
        var elem = map.getViewport();
        elem.classList.remove('ol-grab', 'ol-grabbing');
      }
    }
  };

  return Translate;
}(PointerInteraction));

/**
 * @param {module:ol/MapBrowserPointerEvent} event Event.
 * @return {boolean} Start drag sequence?
 * @this {module:ol/interaction/Translate}
 */
function handleDownEvent(event) {
  this.lastFeature_ = this.featuresAtPixel_(event.pixel, event.map);
  if (!this.lastCoordinate_ && this.lastFeature_) {
    this.lastCoordinate_ = event.coordinate;
    handleMoveEvent.call(this, event);

    var features = this.features_ || new Collection([this.lastFeature_]);

    this.dispatchEvent(
      new TranslateEvent(
        TranslateEventType.TRANSLATESTART, features,
        event.coordinate));
    return true;
  }
  return false;
}

/**
 * @param {module:ol/MapBrowserPointerEvent} event Event.
 * @return {boolean} Stop drag sequence?
 * @this {module:ol/interaction/Translate}
 */
function handleUpEvent(event) {
  if (this.lastCoordinate_) {
    this.lastCoordinate_ = null;
    handleMoveEvent.call(this, event);

    var features = this.features_ || new Collection([this.lastFeature_]);

    this.dispatchEvent(
      new TranslateEvent(
        TranslateEventType.TRANSLATEEND, features,
        event.coordinate));
    return true;
  }
  return false;
}

/**
 * @param {module:ol/MapBrowserPointerEvent} event Event.
 * @this {module:ol/interaction/Translate}
 */
function handleDragEvent(event) {
  if (this.lastCoordinate_) {
    var newCoordinate = event.coordinate;
    var deltaX = newCoordinate[0] - this.lastCoordinate_[0];
    var deltaY = newCoordinate[1] - this.lastCoordinate_[1];

    var features = this.features_ || new Collection([this.lastFeature_]);

    features.forEach(function(feature) {
      var geom = feature.getGeometry();
      geom.translate(deltaX, deltaY);
      feature.setGeometry(geom);
    });

    this.lastCoordinate_ = newCoordinate;
    this.dispatchEvent(
      new TranslateEvent(
        TranslateEventType.TRANSLATING, features,
        newCoordinate));
  }
}

/**
 * @param {module:ol/MapBrowserEvent} event Event.
 * @this {module:ol/interaction/Translate}
 */
function handleMoveEvent(event) {
  var elem = event.map.getViewport();

  // Change the cursor to grab/grabbing if hovering any of the features managed
  // by the interaction
  if (this.featuresAtPixel_(event.pixel, event.map)) {
    elem.classList.remove(this.lastCoordinate_ ? 'ol-grab' : 'ol-grabbing');
    elem.classList.add(this.lastCoordinate_ ? 'ol-grabbing' : 'ol-grab');
  } else {
    elem.classList.remove('ol-grab', 'ol-grabbing');
  }
}

export default Translate;

//# sourceMappingURL=Translate.js.map


text:
FOUNDATION_EXPORT double PulsarKitVersionNumber;

//! Project version string for PulsarKit.
FOUNDATION_EXPORT const unsigned char PulsarKitVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <PulsarKit/PublicHeader.h>


text:
import sys, os

def upcase_first_letter(s):
    return s[0].upper() + s[1:]

scriptPath = os.path.realpath(__file__)
scriptDirPath = os.path.dirname(scriptPath)

arguments = sys.argv

className = str(arguments[1])
className = upcase_first_letter(className)

fileNameObj = scriptDirPath+'/'+className+'.obj'
fileNameMtl = fileNameObj.replace('obj','mtl')

fileObj = open(fileNameObj,'r')

positionList = list()
texCoordList = list()
normalList = list()

facesLinesList = list()

line = fileObj.readline()

while line!='':
        if line.startswith('vn '):
                string = line.replace('vn ','')
                string = string.replace('\n','')
                normalList.append(string)
        elif line.startswith('v '):
                string = line.replace('v ','')
                string = string.replace('\n','')
                positionList.append(string)
        elif line.startswith('f '):
                string = line.replace('f ','')
                string = string.replace('\n','')
                facesLinesList.append(string)
        elif line.startswith('vt '):
                string = line.replace('vt ','')
                string = string.replace('\n','')
                texCoordList.append(string)
        elif line.startswith('mtllib '):
                string = line.replace('mtllib ','')
                string = string.replace('\n','')
        line = fileObj.readline()

fileObj.close()

positionCoordsComponentsList = list()
for line in positionList:
        positionCoordsComponentsList.append(line.split(' '))

textureCoordComponentsList = list()
for line in texCoordList:
        textureCoordComponentsList.append(line.split(' '))

normalCoordsComponentsList = list()
for line in normalList:
        normalCoordsComponentsList.append(line.split(' '))

facesList = list()
for line in facesLinesList:
        list3F = line.split(' ')
        facesList.append(list3F[0].split('/'))
        facesList.append(list3F[1].split('/'))
        facesList.append(list3F[2].split('/'))

numberOfVertices = len(facesList)

swiftFilePath = fileNameObj.replace('obj','swift')
fileSwift = open(swiftFilePath,'w')
fileSwift.write('import UIKit' + '\n\n' + '@objc class ' + className + ': Node {')
fileSwift.write('\n\n    init(baseEffect: BaseEffect)\n    {\n')

fileSwift.write('\n        var verticesArray:Array<Vertex> = []\n')
fileSwift.write('''        let path = NSBundle.mainBundle().pathForResource("''' +className.lower()+'''", ofType: "txt")\n''')
fileSwift.write('            var possibleContent = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)\n\n')
fileSwift.write('            if let content = possibleContent {\n')
fileSwift.write('''            var array = content.componentsSeparatedByString("\\n")\n''')
fileSwift.write('            array.removeLast()\n')
fileSwift.write('            for line in array{\n')
fileSwift.write('                var vertex = Vertex(text: line)\n')
fileSwift.write('                verticesArray.append(vertex)\n')
fileSwift.write('            }\n')
fileSwift.write('        }\n')

fileSwift.write('\n\n')

fileMtl = open(fileNameMtl,'r')
line = fileMtl.readline()

shininess = ''
ambientIntensity = ''
diffuseIntensity = ''
specularIntensity = ''
textureFileName = ''

while line!='':
        if line.startswith('Ns '):
                string = line.replace('Ns ','')
                string = string.replace('\n','')
                shininess = string
        elif line.startswith('Ka '):
                string = line.replace('Ka ','')
                string = string.replace('\n','')
                ambientList = string.split(' ')
                ambientIntensity = str(ambientList[0])
        elif line.startswith('Kd '):
                string = line.replace('Kd ','')
                string = string.replace('\n','')
                diffuseList = string.split(' ')
                diffuseIntensity = str(diffuseList[0])
        elif line.startswith('Ks '):
                string = line.replace('Ks ','')
                string = string.replace('\n','')
                specularList = string.split(' ')
                specularIntensity = str(specularList[0])
        elif line.startswith('map_Kd '):
                string = line.replace('map_Kd ','')
                string = string.replace('\n','')
                textureFileName = string

        line = fileMtl.readline()

fileObj.close()

fileSwift.write('''        super.init(name: "'''+ className +'''", baseEffect: baseEffect, vertices: verticesArray, vertexCount: verticesArray.count, textureName: "'''+textureFileName+'''")''')

fileSwift.write('\n\n')
fileSwift.write('        self.ambientIntensity = '+ambientIntensity+'\n')
fileSwift.write('        self.diffuseIntensity = '+diffuseIntensity+'\n')
fileSwift.write('        self.specularIntensity = '+specularIntensity+'\n')
fileSwift.write('        self.shininess = '+shininess)

fileSwift.write('\n\n    }')
fileSwift.write('\n\n}')

fileSwift.close()

fileTxtName = scriptDirPath+'/'+className.lower()+'.txt'
fileTxt = open(fileTxtName,'w')

for i in range(numberOfVertices):
        face = facesList[i]
        x = str(positionCoordsComponentsList[int(face[0])-1][0])
        y = str(positionCoordsComponentsList[int(face[0])-1][1])
        z = str(positionCoordsComponentsList[int(face[0])-1][2])
        u = str(textureCoordComponentsList[int(face[1])-1][0])
        v = str(textureCoordComponentsList[int(face[1])-1][1])
        nX = str(normalCoordsComponentsList[int(face[2])-1][0])
        nY = str(normalCoordsComponentsList[int(face[2])-1][1])
        nZ = str(normalCoordsComponentsList[int(face[2])-1][2])
        vStr = x+' '+y+' '+z+' '+u+' '+v+' '+nX+' '+nY+' '+nZ+'\n'
        fileTxt.write(vStr)
fileTxt.close()


text:
Article 655
----
La réparation et la reconstruction du mur mitoyen sont à la charge de tous ceux
qui y ont droit, et proportionnellement au droit de chacun.


text:
class GURL;
class Profile;
class WebsiteSettings;

namespace base {
class Value;
};

namespace gfx {
class Image;
}

namespace net {
class X509Certificate;
}

// The class |WebsiteSettingsUI| specifies the platform independent
// interface of the website settings UI. The website settings UI displays
// information and controls for site specific data (local stored objects like
// cookies), site specific permissions (location, popup, plugin, etc.
// permissions) and site specific information (identity, connection status,
// etc.).
class WebsiteSettingsUI {
 public:
  // The Website Settings UI contains several tabs. Each tab is associated with
  // a unique tab id. The enum |TabId| contains all the ids for the tabs.
  enum TabId {
    TAB_ID_PERMISSIONS = 0,
    TAB_ID_CONNECTION,
    NUM_TAB_IDS,
  };

  // The security summary is styled depending on the security state. At the
  // moment, the only styling we apply is color, but it could also include e.g.
  // bolding.
  enum SecuritySummaryStyle { STYLE_UNSTYLED = 0, STYLE_COLOR = 1 << 1 };

  struct SecurityDescription {
    // A one-line summary of the security state.
    base::string16 summary;
    // A short paragraph with more details about the state, and how
    // the user should treat it.
    base::string16 details;
  };

  // |CookieInfo| contains information about the cookies from a specific source.
  // A source can for example be a specific origin or an entire wildcard domain.
  struct CookieInfo {
    CookieInfo();

    // The number of allowed cookies.
    int allowed;
    // The number of blocked cookies.
    int blocked;

    // Whether these cookies are from the current top-level origin as seen by
    // the user, or from third-party origins.
    bool is_first_party;
  };

  // |PermissionInfo| contains information about a single permission |type| for
  // the current website.
  struct PermissionInfo {
    PermissionInfo();
    // Site permission |type|.
    ContentSettingsType type;
    // The current value for the permission |type| (e.g. ALLOW or BLOCK).
    ContentSetting setting;
    // The global default settings for this permission |type|.
    ContentSetting default_setting;
    // The settings source e.g. user, extensions, policy, ... .
    content_settings::SettingSource source;
    // Whether the profile is off the record.
    bool is_incognito;
  };

  // |ChosenObjectInfo| contains information about a single |object| of a
  // chooser |type| that the current website has been granted access to.
  struct ChosenObjectInfo {
    ChosenObjectInfo(const WebsiteSettings::ChooserUIInfo& ui_info,
                     std::unique_ptr<base::DictionaryValue> object);
    ~ChosenObjectInfo();
    // |ui_info| for this chosen object type.
    const WebsiteSettings::ChooserUIInfo& ui_info;
    // The opaque |object| representing the thing the user selected.
    std::unique_ptr<base::DictionaryValue> object;
  };

  // |IdentityInfo| contains information about the site's identity and
  // connection.
  struct IdentityInfo {
    IdentityInfo();
    ~IdentityInfo();

    // The site's identity: the certificate's Organization Name for sites with
    // Extended Validation certificates, or the URL's hostname for all other
    // sites.
    std::string site_identity;
    // Status of the site's identity.
    WebsiteSettings::SiteIdentityStatus identity_status;
    // Helper to get security description info to display to the user.
    std::unique_ptr<SecurityDescription> GetSecurityDescription() const;
    // Textual description of the site's identity status that is displayed to
    // the user.
    std::string identity_status_description;
    // The server certificate if a secure connection.
    scoped_refptr<net::X509Certificate> certificate;
    // Status of the site's connection.
    WebsiteSettings::SiteConnectionStatus connection_status;
    // Textual description of the site's connection status that is displayed to
    // the user.
    std::string connection_status_description;
    // Set when the user has explicitly bypassed an SSL error for this host and
    // has a flag set to remember ssl decisions (explicit flag or in the
    // experimental group).  When |show_ssl_decision_revoke_button| is true, the
    // connection area of the page info will include an option for the user to
    // revoke their decision to bypass the SSL error for this host.
    bool show_ssl_decision_revoke_button;
  };

  using CookieInfoList = std::vector<CookieInfo>;
  using PermissionInfoList = std::vector<PermissionInfo>;
  using ChosenObjectInfoList = std::vector<std::unique_ptr<ChosenObjectInfo>>;

  virtual ~WebsiteSettingsUI();

  // Returns the UI string for the given permission |type|.
  static base::string16 PermissionTypeToUIString(ContentSettingsType type);

  // Returns the UI string for the given permission |value|, used in the
  // permission-changing menu. Generally this will be a verb in the imperative
  // form, e.g. "ask", "allow", "block".
  static base::string16 PermissionValueToUIString(ContentSetting value);

  // Returns the UI string describing the action taken for a permission,
  // including why that action was taken. E.g. "Allowed by you",
  // "Blocked by default".
  static base::string16 PermissionActionToUIString(
      Profile* profile,
      ContentSettingsType type,
      ContentSetting setting,
      ContentSetting default_setting,
      content_settings::SettingSource source);

  // Returns the icon resource ID for the given permission |type| and |setting|.
  static int GetPermissionIconID(ContentSettingsType type,
                                 ContentSetting setting);

  // Returns the icon for the given permissionInfo |info|.  If |info|'s current
  // setting is CONTENT_SETTING_DEFAULT, it will return the icon for |info|'s
  // default setting.
  static const gfx::Image& GetPermissionIcon(const PermissionInfo& info);

  // Returns the UI string describing the given object |info|.
  static base::string16 ChosenObjectToUIString(const ChosenObjectInfo& info);

  // Returns the icon for the given object |info|.
  static const gfx::Image& GetChosenObjectIcon(const ChosenObjectInfo& info,
                                               bool deleted);

  // Returns the identity icon ID for the given identity |status|.
  static int GetIdentityIconID(WebsiteSettings::SiteIdentityStatus status);

  // Returns the identity icon for the given identity |status|.
  static const gfx::Image& GetIdentityIcon(
      WebsiteSettings::SiteIdentityStatus status);

  // Returns the connection icon ID for the given connection |status|.
  static int GetConnectionIconID(
      WebsiteSettings::SiteConnectionStatus status);

  // Returns the connection icon for the given connection |status|.
  static const gfx::Image& GetConnectionIcon(
      WebsiteSettings::SiteConnectionStatus status);

  // Sets cookie information.
  virtual void SetCookieInfo(const CookieInfoList& cookie_info_list) = 0;

  // Sets permission information.
  virtual void SetPermissionInfo(
      const PermissionInfoList& permission_info_list,
      ChosenObjectInfoList chosen_object_info_list) = 0;

  // Sets site identity information.
  virtual void SetIdentityInfo(const IdentityInfo& identity_info) = 0;

  // Selects the tab with the given |tab_id|.
  virtual void SetSelectedTab(TabId tab_id) = 0;
};

typedef WebsiteSettingsUI::CookieInfoList CookieInfoList;
typedef WebsiteSettingsUI::PermissionInfoList PermissionInfoList;
typedef WebsiteSettingsUI::ChosenObjectInfoList ChosenObjectInfoList;

#endif  // CHROME_BROWSER_UI_WEBSITE_SETTINGS_WEBSITE_SETTINGS_UI_H_


text:
(function() {
  'use strict';

  angular
    .module('core')
    .controller('HeaderController', HeaderController);

  HeaderController.$inject = ['$scope', '$state', 'Authentication', 'Menus'];

  function HeaderController($scope, $state, Authentication, Menus) {
    // Expose view variables
    $scope.$state = $state;
    $scope.authentication = Authentication;

    // Get the topbar menu
    $scope.menu = Menus.getMenu('topbar');

    // Get the account menu
    $scope.accountMenu = Menus.getMenu('account').items[0];

    // Toggle the menu items
    $scope.isCollapsed = false;
    $scope.toggleCollapsibleMenu = function () {
      $scope.isCollapsed = !$scope.isCollapsed;
    };

    // Collapsing the menu after navigation
    $scope.$on('$stateChangeSuccess', function () {
      $scope.isCollapsed = false;
    });
  }
})();


text:
package com.github.cchao.touchnews.ui.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.github.cchao.touchnews.ui.fragment.base.BaseFragment;

import java.util.List;

/**
 * Created by cchao on 2016/3/30.
 * E-mail:   cchao1024@163.com
 * Description: 新闻频道 页面Adapter
 */
public class NewsFragmentsPagerAdapter extends FragmentPagerAdapter {
    private List<BaseFragment> mListFragments = null;
    private String[] mTitles = null;

    public NewsFragmentsPagerAdapter(FragmentManager fm, String[] titles, List<BaseFragment> fragments) {
        super(fm);
        mListFragments = fragments;
        mTitles = titles;

    }

    @Override
    public int getCount() {
        if (mListFragments != null) {
            return mListFragments.size();
        } else {
            return 0;
        }
    }

    @Override
    public Fragment getItem(int position) {
        if (mListFragments != null && position >= 0 && position < mListFragments.size()) {
            return mListFragments.get(position);
        } else {
            return null;
        }
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mTitles[position];
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using GameFramework.Cameras;
using GameFramework.Drawing;
using GameFramework.Hexes;
using GameFramework.Layers;
using GameFramework.Scenes;
using GameFramework.Sheets;
using GameFramework.Sprites;
using GameFramework.Tiles;

namespace GameFramework.IO.Repositories
{
    public class XmlRepository
    {
        public void Save(Scene scene, string path)
        {
            var document = new XDocument();

            document.Add(new XElement("Scene",
                new XAttribute("name", scene.Name),
                scene.Children.OfType<ILayer>().Select(XmlRepository.ToXml)));

            // TODO: Fix this
            //document.Save(path);
        }

        public void Save(SheetBase sheetBase, string path)
        {
            var document = new XDocument();

            document.Add(SheetXmlRepository.ToXml(sheetBase));

            // TODO: Fix this
            //document.Save(path);
        }

        public static Scene LoadFrom(GameResourceManager gameResourceManager, string path)
        {
            var document = XDocument.Load(path);

            var sceneElement = document.Element("Scene");
            var scene = new Scene(sceneElement.Attribute("name").Value);

            foreach (var layerElement in sceneElement.Elements())
            {
                switch (layerElement.Name.ToString())
                {
                    case "ImageLayer":
                        scene.Add(ImageXmlRepository.ImageLayerFromXml(gameResourceManager, layerElement));
                        break;
                    case "HexLayer":
                        scene.Add(HexXmlRepository.HexLayerFromXml(gameResourceManager, layerElement));
                        break;
                    case "TileLayer":
                        scene.Add(TileXmlRepository.TileLayerFromXml(gameResourceManager, layerElement));
                        break;
                    case "ColorLayer":
                        scene.Add(ColorXmlRepository.ColorLayerFromXml(layerElement));
                        break;
                    case "SpriteLayer":
                        scene.Add(SpriteXmlRepository.SpriteLayerFromXml(gameResourceManager, layerElement));
                        break;
                    case "DrawingLayer":
                        scene.Add(DrawingXmlRepository.DrawingLayerFromXml(layerElement));
                        break;
                }
            }

            return scene;
        }

        public static XElement ToXml(ILayer layerBase)
        {
            var drawingLayer = layerBase as DrawingLayer;
            if (drawingLayer != null) return DrawingXmlRepository.ToXml(drawingLayer);

            var hexLayer = layerBase as HexLayer;
            if (hexLayer != null) return HexXmlRepository.ToXml(hexLayer);

            var colorLayer = layerBase as ColorLayer;
            if (colorLayer != null) return ColorXmlRepository.ToXml(colorLayer);

            var imageLayer = layerBase as ImageLayer;
            if (imageLayer != null) return ImageXmlRepository.ToXml(imageLayer);

            var spriteLayer = layerBase as SpriteLayer;
            if (spriteLayer != null) return SpriteXmlRepository.ToXml(spriteLayer);

            var tileLayer = layerBase as TileLayer;
            if (tileLayer != null) return TileXmlRepository.ToXml(tileLayer);

            throw new NotSupportedException(layerBase.GetType() + " is not supported");
        }

        internal static IEnumerable<object> LayerBaseToXml(ILayer layerBase)
        {
            yield return new XAttribute("name", layerBase.Name);
            yield return new XAttribute("parallaxScrollingVector", layerBase.ParallaxScrollingVector);
            yield return new XAttribute("offset", layerBase.Offset);
            yield return new XAttribute("cameraMode", layerBase.CameraMode);
        }

        internal static void BaseFromXml(ILayer layerBase, XElement element)
        {
            layerBase.Name = element.Attribute("name").Value;
            layerBase.ParallaxScrollingVector = MathUtil.ParseVector(element.Attribute("parallaxScrollingVector").Value);
            layerBase.Offset = MathUtil.ParseVector(element.Attribute("offset").Value);
            layerBase.CameraMode = (CameraMode)Enum.Parse(typeof(CameraMode), element.Attribute("cameraMode").Value);
        }
    }
}


text:
package org.dashbuilder.dataprovider.backend.sql;

public class SQLQueryDataSetLookupTest extends SQLTableDataSetLookupTest {

    @Override
    public String getExpenseReportsDsetFile() {
        return testSettings.getExpenseReportsQueryDsetFile();
    }
}


text:
'use strict';

var EventEmitter = require('events').EventEmitter;
var emitThen     = require('emit-then');
var Promise      = require('bluebird');
var _            = require('lodash');
var url          = require('url');
var needle       = Promise.promisifyAll(require('needle'));
var utils        = require('./utils');

var internals = {};

internals.options = function (request, options) {
  options = options || {};
  return _.defaults(options, {
    json: (request.method === 'POST' || request.method === 'PUT'),
    query: options.qs || {}
  });
};

internals.query = function (request, options) {
  var parsed = url.parse(request.url, true);
  _.extend(parsed.query, options.query);
  request.url = url.format(parsed);
};

internals.needle = function (request) {
  return needle.requestAsync(
    request.method,
    request.url,
    request.data,
    _.pick(request.options, 'timeout', 'follow', 'proxy', 'agent', 'headers', 'auth', 'json')
  );
};

var Request = function (method, url, data, options) {
  this.method = method;
  this.url = url;
  this.data = data;
  this.options = internals.options(this, options);
  internals.query(this, this.options);
  EventEmitter.call(this);
};

Request.ResponseError = utils.ResponseError;

Request.prototype = Object.create(EventEmitter.prototype);

Request.prototype.emitThen = emitThen;

Request.prototype.send = Promise.method(function () {
  return this
    .emitThen('preRequest', this)
    .bind(this)
    .then(function () {
      var request = internals.needle(this);
      try {
        this.emit('postRequest', _.clone(this));
      } catch (e) {}
      return request;
    })
    .spread(function (response) {
      return response;
    })
    .tap(function (response) {
      this.response = response;
      return this.emitThen('preResponse', this, response);
    })
    .tap(function (response) {
      return utils.catch(response, this.options);
    })
    .then(function (response) {
      return utils.parse(response, this.options);
    })
    .tap(function () {
      return this.emitThen('postResponse', this, this.response);
    });
});

module.exports = Request;