text:
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
// =============================================================================

#include "dragnn/components/util/bulk_feature_extractor.h"
#include "dragnn/core/compute_session_pool.h"
#include "dragnn/core/resource_container.h"
#include "dragnn/core/test/mock_compute_session.h"

#include <gmock/gmock.h>
#include "tensorflow/core/framework/fake_input.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/kernels/ops_testutil.h"

namespace syntaxnet {
namespace dragnn {

using tensorflow::AllocatorAttributes;
using tensorflow::DT_FLOAT;
using tensorflow::DT_STRING;
using tensorflow::FrameAndIter;
using tensorflow::NodeDefBuilder;
using tensorflow::OpKernelContext;
using tensorflow::ResourceMgr;
using tensorflow::ScopedStepContainer;
using tensorflow::Status;
using tensorflow::TensorShape;
using tensorflow::checkpoint::TensorSliceReaderCacheWrapper;
using tensorflow::test::SetOutputAttrs;

using testing::Return;
using testing::_;

typedef ResourceContainer<ComputeSession> ComputeSessionResource;
typedef ResourceContainer<ComputeSessionPool> ComputeSessionPoolResource;

class DragnnBulkOpKernelsTest : public tensorflow::OpsTestBase {
 public:
  static const int kEmbeddingSize = 2;
  static const int kNumActions = 3;
  static const int kNumChannels = 2;
  static const int kNumIds = 8;
  static const int kNumItems = 3;
  static const int kNumSteps = 3;
  const string kComponentName = "TESTING_COMPONENT_NAME";

  MockComputeSession *GetMockSession() {
    TF_CHECK_OK(InitOp());

    // Set the input data.
    const string container_string = "container_str";
    const string id_string = "id_str";
    AddInputFromList<string>(TensorShape({2}), {container_string, id_string});

    // Reset the test context to ensure it's clean.
    ResetOpKernelContext();

    // Create a MockComputeSession and set expectations.
    std::unique_ptr<MockComputeSession> mock_session(new MockComputeSession());
    MockComputeSession *mock_session_ptr = mock_session.get();

    // Wrap the ComputeSessionResource and put it into the resource manager.
    TF_CHECK_OK(resource_mgr()->Create<ComputeSessionResource>(
        container_string, id_string,
        new ComputeSessionResource(std::move(mock_session))));
    return mock_session_ptr;
  }

  void ResetOpKernelContext() {
    params_.reset(new OpKernelContext::Params);
    params_->device = device_.get();
    params_->frame_iter = FrameAndIter(0, 0);
    params_->inputs = &inputs_;
    params_->op_kernel = kernel_.get();
    step_container_.reset(new ScopedStepContainer(0, [](const string &) {}));
    params_->step_container = step_container_.get();
    attrs_.clear();
    SetOutputAttrs(params_.get(), &attrs_);
    TensorSliceReaderCacheWrapper slice_reader_cache_wrapper;
    params_->slice_reader_cache = &slice_reader_cache_wrapper;
    params_->resource_manager = device_->resource_manager();
    context_.reset(new OpKernelContext(params_.get()));
  }

  Status RunOpKernelWithContext() {
    device_->Compute(kernel_.get(), context_.get());
    return context_->status();
  }

  // Accessor for the underlying resource manager.
  ResourceMgr *resource_mgr() { return params_->resource_manager; }
  /*
  // Returns a vector with dimensions: channel x batch x step.
  // For each item we return features for three steps:
  //   feature step 0: (5, 1)
  //   feature step 1: (5, 0.5), (6, 0.7)
  //   feature step 2: (3, 0.1), (7, [empty]) <- Default weight is 1.0.
  void ExpectFeatures(MockComputeSession *mock_session) {
    vector<FixedFeatures> feature_step_zero, feature_step_one, feature_step_two;
    for (int item = 0; item < kNumItems; ++item) {
      feature_step_zero.emplace_back();
      feature_step_zero.back().add_id(5);
      feature_step_zero.back().add_weight(1.0);
      feature_step_one.emplace_back();
      feature_step_one.back().add_id(5);
      feature_step_one.back().add_weight(0.5);
      feature_step_one.back().add_id(6);
      feature_step_one.back().add_weight(0.7);
      feature_step_two.emplace_back();
      feature_step_two.back().add_id(3);
      feature_step_two.back().add_weight(0.1);
      feature_step_two.back().add_id(7);
    }
    for (int channel = 0; channel < kNumChannels; ++channel) {
      EXPECT_CALL(*mock_session, GetInputFeatures(kComponentName, channel))
          .Times(3)
          .WillOnce(Return(feature_step_zero))
          .WillOnce(Return(feature_step_one))
          .WillOnce(Return(feature_step_two));
    }
  }

  // Returns a vector with dimensions: channel x batch x step.
  // For each item we return features for three steps with ids only:
  //   feature step 0: id=5
  //   feature step 1: id=6
  //   feature step 2: id=3
  void ExpectFeatureIds(MockComputeSession *mock_session) {
    vector<FixedFeatures> feature_step_zero, feature_step_one, feature_step_two;
    for (int item = 0; item < kNumItems; ++item) {
      feature_step_zero.emplace_back();
      feature_step_zero.back().add_id(5);
      feature_step_one.emplace_back();
      feature_step_one.back().add_id(6);
      feature_step_two.emplace_back();
      feature_step_two.back().add_id(3);
    }
    for (int channel = 0; channel < kNumChannels; ++channel) {
      EXPECT_CALL(*mock_session, GetInputFeatures(kComponentName, channel))
          .Times(3)
          .WillOnce(Return(feature_step_zero))
          .WillOnce(Return(feature_step_one))
          .WillOnce(Return(feature_step_two));
    }
  }
  */
  // This needs to maintain its existence throughout the compute call.
  std::vector<AllocatorAttributes> attrs_;
};

const int DragnnBulkOpKernelsTest::kEmbeddingSize;
const int DragnnBulkOpKernelsTest::kNumActions;
const int DragnnBulkOpKernelsTest::kNumChannels;
const int DragnnBulkOpKernelsTest::kNumIds;
const int DragnnBulkOpKernelsTest::kNumItems;
const int DragnnBulkOpKernelsTest::kNumSteps;

// The ExtractFixedFeatures op should return a set of fixed feature vectors
// as described below.
TEST_F(DragnnBulkOpKernelsTest, BulkFixedFeatures) {
  // Create and initialize the kernel under test.
  TF_ASSERT_OK(
      NodeDefBuilder("BulkFixedFeatures", "BulkFixedFeatures")
          .Attr("component", kComponentName)
          .Attr("num_channels", kNumChannels)
          .Input(FakeInput(DT_STRING))  // The handle for the ComputeSession.
          .Finalize(node_def()));

  MockComputeSession *mock_session = GetMockSession();
  const std::vector<int> expected_indices({0, 2, 1, 0, 1});
  const std::vector<int> expected_ids({5, 5, 6, 3, 7});
  const std::vector<float> expected_weights({1.0, 0.5, 0.7, 0.1, 1.0});

  // This function takes the allocator functions passed into GetBulkFF, uses
  // them to allocate a tensor, then fills that tensor based on channel.
  auto assigner_function = [=](string, const BulkFeatureExtractor &extractor) {
    constexpr int kFeatureCount = 3;
    constexpr int kTotalFeatures = 5;
    constexpr int kNumSteps = 3;
    for (int i = 0; i < kNumChannels; ++i) {
      // Allocate a new tensor set for every channel.
      int32 *indices =
          extractor.AllocateIndexMemory(i, kTotalFeatures * kNumSteps);
      int64 *ids = extractor.AllocateIdMemory(i, kTotalFeatures * kNumSteps);
      float *weights =
          extractor.AllocateWeightMemory(i, kTotalFeatures * kNumSteps);

      // Fill the tensor.
      int array_index = 0;
      for (int step = 0; step < kNumSteps; step++) {
        for (int j = 0; j < kTotalFeatures; ++j) {
          int offset = i + 1;
          indices[array_index] =
              (expected_indices[j] + step * kFeatureCount) * offset;
          ids[array_index] = expected_ids[j] * offset;
          weights[array_index] = expected_weights[j] * offset;
          ++array_index;
        }
      }
    }
    return kNumSteps;
  };

  EXPECT_CALL(*mock_session, BulkGetInputFeatures(kComponentName, _))
      .WillOnce(testing::Invoke(assigner_function));

  // Run the kernel.
  TF_EXPECT_OK(RunOpKernelWithContext());

  // Validate the outputs.
  // In this case, for every channel we should have:
  //   indices = [0  , 2  , 1  , 0  , 1  ]
  //             [3  , 5  , 4  , 3  , 4  ]
  //             [6  , 8  , 7  , 6  , 7  ]
  //   ids =     [5  , 5  , 6  , 3  , 7  ]
  //             [5  , 5  , 6  , 3  , 7  ]
  //             [5  , 5  , 6  , 3  , 7  ]
  //   weights = [1.0, 0.5, 0.7, 0.1, 1.0]
  //             [1.0, 0.5, 0.7, 0.1, 1.0]
  //             [1.0, 0.5, 0.7, 0.1, 1.0]

  for (int i = 0; i < kNumChannels * 3; ++i) {
    EXPECT_EQ(expected_indices.size() * kNumSteps,
              GetOutput(i + 1)->NumElements());
  }
  for (int channel = 0; channel < kNumChannels; ++channel) {
    LOG(INFO) << "Channel " << channel;
    for (int step = 0; step < kNumSteps; ++step) {
      for (int i = 0; i < expected_indices.size(); ++i) {
        const int j = i + step * expected_indices.size();

        // Note that the expectation on the indices changes per step, unlike the
        // expectation for ids and weights.
        int offset = channel + 1;
        EXPECT_EQ((expected_indices[i] + step * kNumItems) * offset,
                  GetOutput(channel + 1)->vec<int32>()(j));
        EXPECT_EQ(expected_ids[i] * offset,
                  GetOutput(kNumChannels + channel + 1)->vec<int64>()(j));
        EXPECT_EQ(expected_weights[i] * offset,
                  GetOutput(2 * kNumChannels + channel + 1)->vec<float>()(j));
      }
    }
  }
  EXPECT_EQ(kNumSteps, GetOutput(3 * kNumChannels + 1)->scalar<int32>()());
}

TEST_F(DragnnBulkOpKernelsTest, BulkFixedEmbeddings) {
  // Create and initialize the kernel under test.
  TF_ASSERT_OK(
      NodeDefBuilder("BulkFixedEmbeddings", "BulkFixedEmbeddings")
          .Attr("component", kComponentName)
          .Attr("num_channels", kNumChannels)
          .Input(FakeInput(DT_STRING))  // The handle for the ComputeSession.
          .Input(FakeInput(DT_FLOAT))   // Embedding matrices.
          .Finalize(node_def()));
  MockComputeSession *mock_session = GetMockSession();
  ComponentSpec spec;
  spec.set_name(kComponentName);
  auto chan0_spec = spec.add_fixed_feature();
  chan0_spec->set_size(2);
  auto chan1_spec = spec.add_fixed_feature();
  chan1_spec->set_size(1);
  EXPECT_CALL(*mock_session, Spec(kComponentName))
      .WillOnce(testing::ReturnRef(spec));

  EXPECT_CALL(*mock_session, BatchSize(kComponentName))
      .WillOnce(Return(kNumItems));

  const std::vector<int> feature_step_1({0, 1, 2, 1, 2, 2, 1, 0, 1, 0});
  const std::vector<int> feature_index_1({0, 0, 0, 0, 0, 1, 1, 1, 1, 1});
  const std::vector<int> feature_ids_1({5, 6, 3, 5, 7, 5, 6, 3, 5, 7});
  const std::vector<float> feature_weights_1(
      {1.0, 0.7, 0.1, 0.5, 1.0, 10, 7, 1, 5, 10});

  const std::vector<int> feature_step_2({0, 1, 2, 1, 2});
  const std::vector<int> feature_index_2({0, 0, 0, 0, 0});
  const std::vector<int> feature_ids_2({5, 6, 3, 5, 7});
  const std::vector<float> feature_weights_2({1.0, 0.7, 0.1, 0.5, 1.0});

  const std::vector<std::vector<int>> feature_steps_by_channel(
      {feature_step_1, feature_step_2});
  const std::vector<std::vector<int>> feature_index_by_channel(
      {feature_index_1, feature_index_2});
  const std::vector<std::vector<int>> feature_ids_by_channel(
      {feature_ids_1, feature_ids_2});
  const std::vector<std::vector<float>> feature_weights_by_channel(
      {feature_weights_1, feature_weights_2});

  // This function takes the allocator functions passed into GetBulkFF, uses
  // them to allocate a tensor, then fills that tensor based on channel.
  auto assigner_function = [=](string, const BulkFeatureExtractor &extractor) {
    constexpr int kNumElements = 3;
    constexpr int kNumSteps = 3;
    for (int i = 0; i < kNumChannels; ++i) {
      auto feature_step = feature_steps_by_channel.at(i);
      auto feature_index = feature_index_by_channel.at(i);
      auto feature_ids = feature_ids_by_channel.at(i);
      auto feature_weights = feature_weights_by_channel.at(i);

      // Allocate a new tensor set for every channel.
      int32 *indices =
          extractor.AllocateIndexMemory(i, kNumElements * feature_step.size());
      int64 *ids =
          extractor.AllocateIdMemory(i, kNumElements * feature_step.size());
      float *weights =
          extractor.AllocateWeightMemory(i, kNumElements * feature_step.size());

      // Fill the tensor.
      int array_index = 0;

      for (int element = 0; element < kNumElements; ++element) {
        for (int feature = 0; feature < feature_step.size(); ++feature) {
          indices[array_index] = extractor.GetIndex(
              kNumSteps, kNumElements, feature_index[feature], element,
              feature_step[feature]);
          ids[array_index] = feature_ids[feature];
          weights[array_index] = feature_weights[feature];
          ++array_index;
        }
      }
    }
    return kNumSteps;
  };

  EXPECT_CALL(*mock_session, BulkGetInputFeatures(kComponentName, _))
      .WillOnce(testing::Invoke(assigner_function));

  // Embedding matrices as additional inputs.
  // For channel 0, the embeddings are [id, 0].
  // For channel 1, the embeddings are [0, id].
  vector<float> embedding_matrix_a;
  vector<float> embedding_matrix_b;
  for (int id = 0; id < kNumIds; ++id) {
    embedding_matrix_a.push_back(id);
    embedding_matrix_a.push_back(0);
    embedding_matrix_b.push_back(0);
    embedding_matrix_b.push_back(id);
  }
  AddInputFromArray<float>(TensorShape({8, 2}), embedding_matrix_a);
  AddInputFromArray<float>(TensorShape({8, 2}), embedding_matrix_b);

  // Run the kernel.
  TF_EXPECT_OK(RunOpKernelWithContext());

  // Validate the outputs.
  // In this case we should have, for every item, these three steps:
  const vector<vector<float>> expected_embeddings = {{5.0, 0, 73, 0, 0, 5.0},
                                                     {6.7, 0, 67, 0, 0, 6.7},
                                                     {7.3, 0, 50, 0, 0, 7.3}};
  EXPECT_EQ(kNumSteps * kNumItems, GetOutput(1)->shape().dim_size(0));
  constexpr int kNumFeatures = 3;
  EXPECT_EQ(kNumFeatures * kEmbeddingSize, GetOutput(1)->shape().dim_size(1));
  for (int item = 0; item < kNumItems; ++item) {
    for (int step = 0; step < kNumSteps; ++step) {
      for (int col = 0; col < kNumChannels * kEmbeddingSize; ++col) {
        const int row = item * kNumSteps + step;
        EXPECT_EQ(expected_embeddings[step][col],
                  GetOutput(1)->matrix<float>()(row, col))
            << "step: " << step << ", row: " << row << ", col: " << col;
      }
    }
  }

  EXPECT_EQ(kNumSteps, GetOutput(2)->scalar<int32>()());
}

TEST_F(DragnnBulkOpKernelsTest, BulkEmbedFixedFeatures) {
  // Create and initialize the kernel under test.
  constexpr int kBatchPad = 7;
  constexpr int kStepPad = 5;
  constexpr int kMaxBeamSize = 3;
  TF_ASSERT_OK(
      NodeDefBuilder("BulkEmbedFixedFeatures", "BulkEmbedFixedFeatures")
          .Attr("component", kComponentName)
          .Attr("num_channels", kNumChannels)
          .Attr("pad_to_batch", kBatchPad)
          .Attr("pad_to_steps", kStepPad)
          .Input(FakeInput(DT_STRING))  // The handle for the ComputeSession.
          .Input(FakeInput(DT_FLOAT))   // Embedding matrices.
          .Finalize(node_def()));
  MockComputeSession *mock_session = GetMockSession();
  ComponentSpec spec;
  spec.set_name(kComponentName);
  auto chan0_spec = spec.add_fixed_feature();
  constexpr int kChan0FeatureCount = 2;
  chan0_spec->set_size(kChan0FeatureCount);
  auto chan1_spec = spec.add_fixed_feature();
  constexpr int kChan1FeatureCount = 1;
  chan1_spec->set_size(kChan1FeatureCount);
  EXPECT_CALL(*mock_session, Spec(kComponentName))
      .WillOnce(testing::ReturnRef(spec));
  EXPECT_CALL(*mock_session, BeamSize(kComponentName))
      .WillOnce(testing::Return(kMaxBeamSize));

  // Embedding matrices as additional inputs.
  // For channel 0, the embeddings are [id, id, id].
  // For channel 1, the embeddings are [id^2, id^2, id^2, ... ,id^2].
  vector<float> embedding_matrix_0;
  constexpr int kEmbedding0Size = 3;
  vector<float> embedding_matrix_1;
  constexpr int kEmbedding1Size = 9;
  for (int id = 0; id < kNumIds; ++id) {
    for (int i = 0; i < kEmbedding0Size; ++i) {
      embedding_matrix_0.push_back(id);
      LOG(INFO) << embedding_matrix_0.back();
    }
    for (int i = 0; i < kEmbedding1Size; ++i) {
      embedding_matrix_1.push_back(id * id);
      LOG(INFO) << embedding_matrix_0.back();
    }
  }

  AddInputFromArray<float>(TensorShape({kNumIds, kEmbedding0Size}),
                           embedding_matrix_0);
  AddInputFromArray<float>(TensorShape({kNumIds, kEmbedding1Size}),
                           embedding_matrix_1);

  constexpr int kExpectedEmbeddingSize = kChan0FeatureCount * kEmbedding0Size +
                                         kChan1FeatureCount * kEmbedding1Size;
  constexpr int kExpectedOutputSize =
      kExpectedEmbeddingSize * kBatchPad * kStepPad * kMaxBeamSize;

  // This function takes the allocator functions passed into GetBulkFF, uses
  // them to allocate a tensor, then fills that tensor based on channel.
  auto eval_function = [=](const string &component_name, int batch_size_padding,
                           int num_steps_padding, int output_array_size,
                           const vector<const float *> &per_channel_embeddings,
                           float *embedding_output) {
    // Validate the control variables.
    EXPECT_EQ(batch_size_padding, kBatchPad);
    EXPECT_EQ(num_steps_padding, kStepPad);
    EXPECT_EQ(output_array_size, kExpectedOutputSize);

    // Validate the passed embeddings.
    for (int i = 0; i < kNumIds; ++i) {
      for (int j = 0; j < kEmbedding0Size; ++j) {
        float ch0_embedding =
            per_channel_embeddings.at(0)[i * kEmbedding0Size + j];
        EXPECT_FLOAT_EQ(ch0_embedding, i)
            << "Failed match at " << i << "," << j;
      }
      for (int j = 0; j < kEmbedding1Size; ++j) {
        float ch1_embedding =
            per_channel_embeddings.at(1)[i * kEmbedding1Size + j];
        EXPECT_FLOAT_EQ(ch1_embedding, i * i)
            << "Failed match at " << i << "," << j;
      }
    }

    // Fill the output matrix to the expected size. This will trigger msan
    // if the allocation wasn't big enough.
    for (int i = 0; i < kExpectedOutputSize; ++i) {
      embedding_output[i] = i;
    }
  };

  EXPECT_CALL(*mock_session,
              BulkEmbedFixedFeatures(kComponentName, _, _, _, _, _))
      .WillOnce(testing::Invoke(eval_function));

  // Run the kernel.
  TF_EXPECT_OK(RunOpKernelWithContext());

  // Validate outputs.
  EXPECT_EQ(kBatchPad * kStepPad * kMaxBeamSize,
            GetOutput(1)->shape().dim_size(0));
  EXPECT_EQ(kExpectedEmbeddingSize, GetOutput(1)->shape().dim_size(1));
  auto output_data = GetOutput(1)->flat<float>();
  for (int i = 0; i < kExpectedOutputSize; ++i) {
    EXPECT_FLOAT_EQ(i, output_data(i));
  }
  EXPECT_EQ(kStepPad, GetOutput(2)->scalar<int32>()());
}

TEST_F(DragnnBulkOpKernelsTest, BulkFixedEmbeddingsWithPadding) {
  // Create and initialize the kernel under test.
  constexpr int kPaddedNumSteps = 5;
  constexpr int kPaddedBatchSize = 4;
  TF_ASSERT_OK(
      NodeDefBuilder("BulkFixedEmbeddings", "BulkFixedEmbeddings")
          .Attr("component", kComponentName)
          .Attr("num_channels", kNumChannels)
          .Attr("pad_to_steps", kPaddedNumSteps)
          .Attr("pad_to_batch", kPaddedBatchSize)
          .Input(FakeInput(DT_STRING))  // The handle for the ComputeSession.
          .Input(FakeInput(DT_FLOAT))   // Embedding matrices.
          .Finalize(node_def()));
  MockComputeSession *mock_session = GetMockSession();
  ComponentSpec spec;
  spec.set_name(kComponentName);
  auto chan0_spec = spec.add_fixed_feature();
  chan0_spec->set_size(2);
  auto chan1_spec = spec.add_fixed_feature();
  chan1_spec->set_size(1);
  EXPECT_CALL(*mock_session, Spec(kComponentName))
      .WillOnce(testing::ReturnRef(spec));

  EXPECT_CALL(*mock_session, BatchSize(kComponentName))
      .WillOnce(Return(kNumItems));

  const std::vector<int> feature_step_1({0, 1, 2, 1, 2, 2, 1, 0, 1, 0});
  const std::vector<int> feature_index_1({0, 0, 0, 0, 0, 1, 1, 1, 1, 1});
  const std::vector<int> feature_ids_1({5, 6, 3, 5, 7, 5, 6, 3, 5, 7});
  const std::vector<float> feature_weights_1(
      {1.0, 0.7, 0.1, 0.5, 1.0, 10, 7, 1, 5, 10});

  const std::vector<int> feature_step_2({0, 1, 2, 1, 2});
  const std::vector<int> feature_index_2({0, 0, 0, 0, 0});
  const std::vector<int> feature_ids_2({5, 6, 3, 5, 7});
  const std::vector<float> feature_weights_2({1.0, 0.7, 0.1, 0.5, 1.0});

  const std::vector<std::vector<int>> feature_steps_by_channel(
      {feature_step_1, feature_step_2});
  const std::vector<std::vector<int>> feature_index_by_channel(
      {feature_index_1, feature_index_2});
  const std::vector<std::vector<int>> feature_ids_by_channel(
      {feature_ids_1, feature_ids_2});
  const std::vector<std::vector<float>> feature_weights_by_channel(
      {feature_weights_1, feature_weights_2});

  // This function takes the allocator functions passed into GetBulkFF, uses
  // them to allocate a tensor, then fills that tensor based on channel.
  auto assigner_function = [=](string, const BulkFeatureExtractor &extractor) {
    constexpr int kNumElements = 3;
    constexpr int kNumSteps = 3;
    for (int i = 0; i < kNumChannels; ++i) {
      auto feature_step = feature_steps_by_channel.at(i);
      auto feature_index = feature_index_by_channel.at(i);
      auto feature_ids = feature_ids_by_channel.at(i);
      auto feature_weights = feature_weights_by_channel.at(i);

      // Allocate a new tensor set for every channel.
      int32 *indices =
          extractor.AllocateIndexMemory(i, kNumElements * feature_step.size());
      int64 *ids =
          extractor.AllocateIdMemory(i, kNumElements * feature_step.size());
      float *weights =
          extractor.AllocateWeightMemory(i, kNumElements * feature_step.size());

      // Fill the tensor.
      int array_index = 0;

      for (int element = 0; element < kNumElements; ++element) {
        for (int feature = 0; feature < feature_step.size(); ++feature) {
          indices[array_index] = extractor.GetIndex(
              kNumSteps, kNumElements, feature_index[feature], element,
              feature_step[feature]);
          ids[array_index] = feature_ids[feature];
          weights[array_index] = feature_weights[feature];
          ++array_index;
        }
      }
    }
    return kNumSteps;
  };

  EXPECT_CALL(*mock_session, BulkGetInputFeatures(kComponentName, _))
      .WillOnce(testing::Invoke(assigner_function));

  // Embedding matrices as additional inputs.
  // For channel 0, the embeddings are [id, 0].
  // For channel 1, the embeddings are [0, id].
  vector<float> embedding_matrix_a;
  vector<float> embedding_matrix_b;
  for (int id = 0; id < kNumIds; ++id) {
    embedding_matrix_a.push_back(id);
    embedding_matrix_a.push_back(0);
    embedding_matrix_b.push_back(0);
    embedding_matrix_b.push_back(id);
  }
  AddInputFromArray<float>(TensorShape({8, 2}), embedding_matrix_a);
  AddInputFromArray<float>(TensorShape({8, 2}), embedding_matrix_b);

  // Run the kernel.
  TF_EXPECT_OK(RunOpKernelWithContext());

  // Validate the outputs.
  // In this case we should have, for every item, these three steps:
  const vector<vector<float>> expected_embeddings = {{5.0, 0, 73, 0, 0, 5.0},
                                                     {6.7, 0, 67, 0, 0, 6.7},
                                                     {7.3, 0, 50, 0, 0, 7.3}};
  EXPECT_EQ(kPaddedNumSteps * kPaddedBatchSize,
            GetOutput(1)->shape().dim_size(0));

  constexpr int kNumFeatures = 3;
  EXPECT_EQ(kNumFeatures * kEmbeddingSize, GetOutput(1)->shape().dim_size(1));
  for (int item = 0; item < kNumItems; ++item) {
    for (int step = 0; step < kNumSteps; ++step) {
      for (int col = 0; col < kNumChannels * kEmbeddingSize; ++col) {
        const int row = item * kPaddedNumSteps + step;
        EXPECT_EQ(expected_embeddings[step][col],
                  GetOutput(1)->matrix<float>()(row, col))
            << "step: " << step << ", row: " << row << ", col: " << col;
      }
    }
  }

  EXPECT_EQ(kNumSteps, GetOutput(2)->scalar<int32>()());
}

TEST_F(DragnnBulkOpKernelsTest, BulkAdvanceFromOracle) {
  // Create and initialize the kernel under test.
  TF_ASSERT_OK(
      NodeDefBuilder("BulkAdvanceFromOracle", "BulkAdvanceFromOracle")
          .Attr("component", kComponentName)
          .Input(FakeInput(DT_STRING))  // The handle for the ComputeSession.
          .Finalize(node_def()));
  MockComputeSession *mock_session = GetMockSession();
  EXPECT_CALL(*mock_session, IsTerminal(kComponentName))
      .WillOnce(Return(false))
      .WillOnce(Return(false))
      .WillOnce(Return(false))
      .WillOnce(Return(true));
  EXPECT_CALL(*mock_session, AdvanceFromOracle(kComponentName))
      .Times(kNumSteps);
  const vector<vector<vector<int32>>> gold = {
      {{1}, {1}, {1}}, {{2}, {2}, {2}}, {{3}, {3}, {3}},
  };
  EXPECT_CALL(*mock_session, EmitOracleLabels(kComponentName))
      .WillOnce(Return(gold[0]))
      .WillOnce(Return(gold[1]))
      .WillOnce(Return(gold[2]));
  EXPECT_CALL(*mock_session, BeamSize(kComponentName)).WillOnce(Return(1));
  EXPECT_CALL(*mock_session, BatchSize(kComponentName))
      .WillOnce(Return(kNumItems));

  // Run the kernel.
  TF_EXPECT_OK(RunOpKernelWithContext());

  // Validate the outputs.
  // For every item we should have:
  const vector<int32> expected_gold = {1, 2, 3};
  EXPECT_EQ(kNumSteps * kNumItems, GetOutput(1)->NumElements());
  for (int item = 0; item < kNumItems; ++item) {
    for (int step = 0; step < kNumSteps; ++step) {
      EXPECT_EQ(expected_gold[step],
                GetOutput(1)->vec<int32>()(step + item * kNumSteps));
    }
  }
}

string ArrayToString(const float *array, const int size) {
  string str = "[ ";
  for (int i = 0; i < size; ++i) {
    str += tensorflow::strings::Printf("%.1f ", array[i]);
  }
  return str + "]";
}

MATCHER(CheckScoresAreConsecutiveIntegersDivTen, "") {
  const int size =
      DragnnBulkOpKernelsTest::kNumItems * DragnnBulkOpKernelsTest::kNumActions;
  for (int i(0), score(arg[0] * 10); i < size; ++i, ++score) {
    EXPECT_NEAR(score / 10.0f, arg[i], 1e-4)
        << "i: " << i << ", scores: " << ArrayToString(arg, size);
  }
  return true;
}

TEST_F(DragnnBulkOpKernelsTest, BulkAdvanceFromPrediction) {
  // Create and initialize the kernel under test.
  TF_ASSERT_OK(
      NodeDefBuilder("BulkAdvanceFromPrediction", "BulkAdvanceFromPrediction")
          .Attr("component", kComponentName)
          .Input(FakeInput(DT_STRING))  // The handle for the ComputeSession.
          .Input(FakeInput(DT_FLOAT))   // Prediction scores for advancing.
          .Finalize(node_def()));
  MockComputeSession *mock_session = GetMockSession();

  // Creates an input tensor such that each step will see a list of consecutive
  // integers divided by 10 as scores.
  vector<float> scores(kNumItems * kNumSteps * kNumActions);
  for (int step(0), cnt(0); step < kNumSteps; ++step) {
    for (int item = 0; item < kNumItems; ++item) {
      for (int action = 0; action < kNumActions; ++action, ++cnt) {
        scores[action + kNumActions * (step + item * kNumSteps)] = cnt / 10.0f;
      }
    }
  }
  AddInputFromArray<float>(TensorShape({kNumItems * kNumSteps, kNumActions}),
                           scores);

  EXPECT_CALL(*mock_session, BeamSize(kComponentName)).WillOnce(Return(1));
  EXPECT_CALL(*mock_session, BatchSize(kComponentName))
      .WillOnce(Return(kNumItems));
  EXPECT_CALL(*mock_session, IsTerminal(kComponentName))
      .Times(kNumSteps)
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*mock_session,
              AdvanceFromPrediction(kComponentName,
                                    CheckScoresAreConsecutiveIntegersDivTen(),
                                    kNumItems, kNumActions))
      .Times(kNumSteps)
      .WillRepeatedly(Return(true));

  // Run the kernel.
  TF_EXPECT_OK(RunOpKernelWithContext());
}

TEST_F(DragnnBulkOpKernelsTest, BulkAdvanceFromPredictionFailsIfAdvanceFails) {
  // Create and initialize the kernel under test.
  TF_ASSERT_OK(
      NodeDefBuilder("BulkAdvanceFromPrediction", "BulkAdvanceFromPrediction")
          .Attr("component", kComponentName)
          .Input(FakeInput(DT_STRING))  // The handle for the ComputeSession.
          .Input(FakeInput(DT_FLOAT))   // Prediction scores for advancing.
          .Finalize(node_def()));
  MockComputeSession *mock_session = GetMockSession();

  // Creates an input tensor such that each step will see a list of consecutive
  // integers divided by 10 as scores.
  vector<float> scores(kNumItems * kNumSteps * kNumActions);
  for (int step(0), cnt(0); step < kNumSteps; ++step) {
    for (int item = 0; item < kNumItems; ++item) {
      for (int action = 0; action < kNumActions; ++action, ++cnt) {
        scores[action + kNumActions * (step + item * kNumSteps)] = cnt / 10.0f;
      }
    }
  }
  AddInputFromArray<float>(TensorShape({kNumItems * kNumSteps, kNumActions}),
                           scores);

  EXPECT_CALL(*mock_session, BeamSize(kComponentName)).WillOnce(Return(1));
  EXPECT_CALL(*mock_session, BatchSize(kComponentName))
      .WillOnce(Return(kNumItems));
  EXPECT_CALL(*mock_session, IsTerminal(kComponentName))
      .Times(2)
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*mock_session,
              AdvanceFromPrediction(kComponentName,
                                    CheckScoresAreConsecutiveIntegersDivTen(),
                                    kNumItems, kNumActions))
      .WillOnce(Return(true))
      .WillOnce(Return(false));

  // Run the kernel.
  auto result = RunOpKernelWithContext();
  EXPECT_FALSE(result.ok());
}

}  // namespace dragnn
}  // namespace syntaxnet


text:
/**
 * cc.PhysicsDebugNode's rendering objects of WebGL
 */
(function () {
    cc.PhysicsDebugNode.WebGLRenderCmd = function (renderableObject) {
        this._rootCtor(renderableObject);
        this._needDraw = true;
        this._matrix = new cc.math.Matrix4();
        this._matrix.identity();
    };

    cc.PhysicsDebugNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
    cc.PhysicsDebugNode.WebGLRenderCmd.prototype.constructor = cc.PhysicsDebugNode.WebGLRenderCmd;

    cc.PhysicsDebugNode.WebGLRenderCmd.prototype.rendering = function (ctx) {
        var node = this._node;
        if (!node._space)
            return;

        node._space.eachShape(cc.DrawShape.bind(node));
        node._space.eachConstraint(cc.DrawConstraint.bind(node));

        var wt = this._worldTransform;
        this._matrix.mat[0] = wt.a;
        this._matrix.mat[4] = wt.c;
        this._matrix.mat[12] = wt.tx;
        this._matrix.mat[1] = wt.b;
        this._matrix.mat[5] = wt.d;
        this._matrix.mat[13] = wt.ty;

        //cc.DrawNode.prototype.draw.call(node);
        cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst);
        this._shaderProgram.use();
        this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix);
        node._render();

        node.clear();
    };
})();

redpajama_set_name: RedPajamaGithub


text:
namespace logging
{
    struct Message
    {
        std::string text;
        bool isError;
        boost::posix_time::ptime time;

        Message(const char *msg, bool error) : text(msg), isError(error)
        {
            time = boost::posix_time::second_clock::local_time();
        }
    };

    std::queue<Message> messages;
    std::condition_variable loggerCondition;
    std::mutex loggerMutex;
    bool loggerClose = false;

    void syncLog(const Message &msg)
    {
        using namespace std;
        using namespace boost;
#ifndef XCODE
        static ofstream debug;

        if (!debug.is_open()) {
            debug.open(std::getenv("FCGI_DEBUG_LOG"), ios_base::out | ios_base::app);
            debug.imbue(locale(debug.getloc(), new posix_time::time_facet()));
        }
#else
        auto &debug = std::cerr;
#endif

        debug << (msg.isError ? "E " : "D ") << '[' << msg.time << "] " << msg.text << endl;
    }

    void asyncLogger()
    {
        while (!loggerClose) {
            std::unique_lock<std::mutex> locker(loggerMutex);
            loggerCondition.wait(locker, []{ return loggerClose || !messages.empty(); });

            while (!messages.empty()) {
                syncLog(messages.front());
                messages.pop();
            }
        }
    }

    void logSync(const char *msg, bool isError)
    {
        std::unique_lock<std::mutex> locker(loggerMutex);
        syncLog(Message(msg, isError));
    }

    void logAsync(const char *msg, bool isError)
    {
        std::unique_lock<std::mutex> locker(loggerMutex);
        messages.push(Message(msg, isError));
        loggerCondition.notify_one();
    }

    void closeAsync()
    {
        std::unique_lock<std::mutex> locker(loggerMutex);
        loggerClose = true;
        loggerCondition.notify_one();
    }

    class Logger
    {
        std::thread loggerThread;

    public:
        Logger() : loggerThread(asyncLogger) { }

        ~Logger()
        {
            closeAsync();
            loggerThread.join();
        }
    };

    static Logger logger;
}

void error_log(const char* msg)
{
    logging::logSync(msg, true);
}

void debug_log(const char* msg)
{
    #ifdef DEBUG
    logging::logAsync(msg, false);
    #endif
}

#endif


text:
extern "C" {
#include <sys/types.h>

#include <signal.h>
#include <unistd.h>
}

#include <cstdlib>
#include <cstring>
#include <set>

#include "utils/logging/macros.hpp"
#include "utils/process/operations.hpp"
#include "utils/sanity.hpp"
#include "utils/signals/exceptions.hpp"
#include "utils/signals/programmer.hpp"

namespace signals = utils::signals;
namespace process = utils::process;

namespace {

/// The interrupt signal that fired, or -1 if none.
static volatile int fired_signal = -1;

/// Collection of PIDs.
typedef std::set< pid_t > pids_set;

/// List of processes to kill upon reception of a signal.
static pids_set pids_to_kill;

/// Programmer status for the SIGHUP signal.
static std::auto_ptr< signals::programmer > sighup_handler;
/// Programmer status for the SIGINT signal.
static std::auto_ptr< signals::programmer > sigint_handler;
/// Programmer status for the SIGTERM signal.
static std::auto_ptr< signals::programmer > sigterm_handler;

/// Signal mask to restore after exiting a signal inhibited section.
static sigset_t global_old_sigmask;

/// Whether there is an interrupts_handler object in existence or not.
static bool interrupts_handler_active = false;

/// Whether there is an interrupts_inhibiter object in existence or not.
static std::size_t interrupts_inhibiter_active = 0;

/// Generic handler to capture interrupt signals.
///
/// From this handler, we record that an interrupt has happened so that
/// check_interrupt() can know whether there execution has to be stopped or not.
/// We also terminate any of our child processes (started by the
/// utils::process::children class) so that any ongoing wait(2) system calls
/// terminate.
///
/// \param signo The signal that caused this handler to be called.
static void
signal_handler(const int signo)
{
    static const char* message = "[-- Signal caught; please wait for "
        "cleanup --]\n";
    if (::write(STDERR_FILENO, message, std::strlen(message)) == -1) {
        // We are exiting: the message printed here is only for informational
        // purposes.  If we fail to print it (which probably means something
        // is really bad), there is not much we can do within the signal
        // handler, so just ignore this.
    }

    fired_signal = signo;

    for (pids_set::const_iterator iter = pids_to_kill.begin();
        iter != pids_to_kill.end(); ++iter) {
        process::terminate_group(*iter);
    }
}

/// Installs signal handlers for potential interrupts.
///
/// \pre Must not have been called before.
/// \post The various sig*_handler global variables are atomically updated.
static void
setup_handlers(void)
{
    PRE(sighup_handler.get() == NULL);
    PRE(sigint_handler.get() == NULL);
    PRE(sigterm_handler.get() == NULL);

    // Create the handlers on the stack first so that, if any of them fails, the
    // stack unwinding cleans things up.
    std::auto_ptr< signals::programmer > tmp_sighup_handler(
        new signals::programmer(SIGHUP, signal_handler));
    std::auto_ptr< signals::programmer > tmp_sigint_handler(
        new signals::programmer(SIGINT, signal_handler));
    std::auto_ptr< signals::programmer > tmp_sigterm_handler(
        new signals::programmer(SIGTERM, signal_handler));

    // Now, update the global pointers, which is an operation that cannot fail.
    sighup_handler = tmp_sighup_handler;
    sigint_handler = tmp_sigint_handler;
    sigterm_handler = tmp_sigterm_handler;
}

/// Uninstalls the signal handlers installed by setup_handlers().
static void
cleanup_handlers(void)
{
    sighup_handler->unprogram(); sighup_handler.reset(NULL);
    sigint_handler->unprogram(); sigint_handler.reset(NULL);
    sigterm_handler->unprogram(); sigterm_handler.reset(NULL);
}

/// Masks the signals installed by setup_handlers().
static void
mask_signals(sigset_t* old_sigmask)
{
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGALRM);
    sigaddset(&mask, SIGHUP);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGTERM);
    const int ret = ::sigprocmask(SIG_BLOCK, &mask, old_sigmask);
    INV(ret != -1);
}

/// Resets the signal masking put in place by mask_signals().
static void
unmask_signals(sigset_t* old_sigmask)
{
    const int ret = ::sigprocmask(SIG_SETMASK, old_sigmask, NULL);
    INV(ret != -1);
}

}  // anonymous namespace

/// Constructor that sets up the signal handlers.
signals::interrupts_handler::interrupts_handler(void) :
    _programmed(false)
{
    PRE(!interrupts_handler_active);
    setup_handlers();
    _programmed = true;
    interrupts_handler_active = true;
}

/// Destructor that removes the signal handlers.
///
/// Given that this is a destructor and it can't report errors back to the
/// caller, the caller must attempt to call unprogram() on its own.
signals::interrupts_handler::~interrupts_handler(void)
{
    if (_programmed) {
        LW("Destroying still-programmed signals::interrupts_handler object");
        try {
            unprogram();
        } catch (const error& e) {
            UNREACHABLE;
        }
    }
}

/// Unprograms all signals captured by the interrupts handler.
///
/// \throw system_error If the unprogramming of any signal fails.
void
signals::interrupts_handler::unprogram(void)
{
    PRE(_programmed);

    // Modify the control variables first before unprogramming the handlers.  If
    // we fail to do the latter, we do not want to try again because we will not
    // succeed (and we'll cause a crash due to failed preconditions).
    _programmed = false;
    interrupts_handler_active = false;

    cleanup_handlers();
    fired_signal = -1;
}

/// Constructor that sets up signal masking.
signals::interrupts_inhibiter::interrupts_inhibiter(void)
{
    sigset_t old_sigmask;
    mask_signals(&old_sigmask);
    if (interrupts_inhibiter_active == 0) {
        global_old_sigmask = old_sigmask;
    }
    ++interrupts_inhibiter_active;
}

/// Destructor that removes signal masking.
signals::interrupts_inhibiter::~interrupts_inhibiter(void)
{
    if (interrupts_inhibiter_active > 1) {
        --interrupts_inhibiter_active;
    } else {
        interrupts_inhibiter_active = false;
        unmask_signals(&global_old_sigmask);
    }
}

/// Checks if an interrupt has fired.
///
/// Calls to this function should be sprinkled in strategic places through the
/// code protected by an interrupts_handler object.
///
/// Only one call to this function will raise an exception per signal received.
/// This is to allow executing cleanup actions without reraising interrupt
/// exceptions unless the user has fired another interrupt.
///
/// \throw interrupted_error If there has been an interrupt.
void
signals::check_interrupt(void)
{
    if (fired_signal != -1) {
        const int original_fired_signal = fired_signal;
        fired_signal = -1;
        throw interrupted_error(original_fired_signal);
    }
}

/// Registers a child process to be killed upon reception of an interrupt.
///
/// \pre Must be called with interrupts being inhibited.  The caller must ensure
/// that the call call to fork() and the addition of the PID happen atomically.
///
/// \param pid The PID of the child process.  Must not have been yet regsitered.
void
signals::add_pid_to_kill(const pid_t pid)
{
    PRE(interrupts_inhibiter_active);
    PRE(pids_to_kill.find(pid) == pids_to_kill.end());
    pids_to_kill.insert(pid);
}

/// Unregisters a child process previously registered via add_pid_to_kill().
///
/// \pre Must be called with interrupts being inhibited.  This is not necessary,
/// but pushing this to the caller simplifies our logic and provides consistency
/// with the add_pid_to_kill() call.
///
/// \param pid The PID of the child process.  Must have been registered
///     previously, and the process must have already been awaited for.
void
signals::remove_pid_to_kill(const pid_t pid)
{
    PRE(interrupts_inhibiter_active);
    PRE(pids_to_kill.find(pid) != pids_to_kill.end());
    pids_to_kill.erase(pid);
}


text:
//
//  BaseViewController.m
//
//
//  Created by Ankit Jain on 27/06/15.
//
//

#import "BaseViewController.h"
#import "InitialViewController.h"
#import "MessagesViewController.h"
#import "JuneViewController.h"
#import "JulyViewController.h"
#import "ImpDatesViewController.h"
#import "AppDelegate.h"
#import "AugustViewController.h"

@interface BaseViewController () <BlurMenuDelegate>

@end

@implementation BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSDate *)getDate {
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    return delegate.date;
}

-(void)updateDate{
//    NSString *month = [[NSUserDefaults standardUserDefaults] valueForKey:@"GET_DATE"];
//    NSInteger monthInt = [month integerValue] + 1;
//
//    [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%ld", (long)monthInt] forKey:@"GET_DATE"];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//
//    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
//    [delegate getNextMonthDate];

}

#pragma - Menu

- (IBAction)showMenu:(id)sender {
    NSArray *items = [[NSArray alloc] initWithObjects:@"Anniversary Countdown", @"Imp Dates", @"Love Quotes", @"June", @"July", @"August", nil];
    BlurMenu *menu = [[BlurMenu alloc] initWithItems:items parentView:self.view delegate:self];
    [menu show];
}

- (void)menuDidShow {

}

- (void)menuDidHide {

}

- (void)selectedItemAtIndex:(NSInteger)index {
    BOOL animated = NO;
    if (index == 0) {
        InitialViewController *initialVC = [self.storyboard instantiateViewControllerWithIdentifier:@"InitialViewController"];
        [self.navigationController pushViewController:initialVC animated:animated];
    } else if (index == 1) {
        ImpDatesViewController *impVC = [self.storyboard instantiateViewControllerWithIdentifier:@"ImpDatesViewController"];
        [self.navigationController pushViewController:impVC animated:animated];
    } else if (index == 2) {
        MessagesViewController *messageVC = [self.storyboard instantiateViewControllerWithIdentifier:@"MessagesViewController"];
        [self.navigationController pushViewController:messageVC animated:animated];
    } else if (index == 3) {
        JuneViewController *juneVC = [self.storyboard instantiateViewControllerWithIdentifier:@"JuneViewController"];
        [self.navigationController pushViewController:juneVC animated:animated];
    } else if (index == 4) {
        JulyViewController *julyVC = [self.storyboard instantiateViewControllerWithIdentifier:@"JulyViewController"];
        [self.navigationController pushViewController:julyVC animated:animated];
    } else if (index == 5) {
        AugustViewController *augustVC = [self.storyboard instantiateViewControllerWithIdentifier:@"AugustViewController"];
        [self.navigationController pushViewController:augustVC animated:animated];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
module Codewars.Kata.Catenation where

charConcat :: String -> String
charConcat word = foldr (\i str  -> word !! (i - 1) : word !! (length word - i) : show i ++ str) "" [1..length word `div` 2]


text:
declare module 'mod1' {
    class Foo {
        private n;
    }
}
declare module 'mod2' {
    class Foo {
        private n;
    }
}

//// [propertyIdentityWithPrivacyMismatch_1.ts]
///<reference path='propertyIdentityWithPrivacyMismatch_0.ts'/>
import m1 = require('mod1');
import m2 = require('mod2');
var x: m1.Foo;
var x: m2.Foo; // Should be error (mod1.Foo !== mod2.Foo)
class Foo1 {
    private n;
}
class Foo2 {
    private n;
}
var y: Foo1;
var y: Foo2;

//// [propertyIdentityWithPrivacyMismatch_0.js]
//// [propertyIdentityWithPrivacyMismatch_1.js]
define(["require", "exports"], function (require, exports) {
    var x;
    var x; // Should be error (mod1.Foo !== mod2.Foo)
    var Foo1 = (function () {
        function Foo1() {
        }
        return Foo1;
    })();
    var Foo2 = (function () {
        function Foo2() {
        }
        return Foo2;
    })();
    var y;
    var y;
});


text:
title:  Åndens kærlighed
date:   24/04/2018
---

Helligånden er næsten lige så misforstået som Faderen. Nogle teologer har opfattet Ånden som kærligheden mellem Faderen og Sønnen. Med andre ord ser de blot Ånden som et følelsesmæssigt bånd mellem Faderen og Sønnen. Dermed bliver han begrænset til forholdet mellem de to andre medlemmer of guddommen og ikke selv et medlem.
Skriften beviser imidlertid, at Ånden er en person. Kristne døbes i hans navn sammen med Faderens og Sønnens (Matt 28,19). Ånden herliggør Kristus (Joh 16,4). Ånden overbeviser mennesker (Joh
16,8). Han kan bedrøves (Ef 4,30). Han er en "anden talsmand" (Joh 14,16), et ord, der også kan oversættes med hjælper eller trøster.
Han underviser (Luk 12,12), går i forbøn (Rom 8,26), og helliger (1 Pet 1,2). Kristus udtalte, at Ånden vejleder mennesker i hele sandheden (Joh 16,13). Kort sagt, Helligånden er Gud, ligesom Faderen og Sønnen er det. Sammen er de én Gud.

`Læs Luk 12,12; Joh 16,8-13 og ApG 13,2. Alt, hvad Helligånden gør, åbenbarer guddommelig kærlighed. Nævn nogle af dem.`

Det største bevis for, at Helligånden er Gud, er Kristi inkarnation. Jesus blev født af Helligånden (Matt 1,20). Kun Gud kunne "skabe" på den måde.

Helligånden er i stand til at udrette to modsatte mirakler for Kristus. Først bragte han den allestedsnærværende Kristus ind i Marias skød. Kristus steg til himlen i et menneskeligt legeme med dette legemes begrænsninger. For det andet bringer Helligånden os Kristus, bundet af sin menneskelighed, og gør ham gennem endnu et uforklarligt mirakel nærværende for kristne i hele verden.

På denne måde arbejder Helligånden sammen med Faderen og Sønnen på vore vegne. "Guddommen blev rørt af medlidenhed for den menneskelige race, og Faderen, Sønnen og Helligånden viede sig selv til en plan for at frelse menneskeheden." (Ellen White, Counsels on Health, s. 222).

Faderen, Sønnen og Helligånden elsker os lige højt og arbejder på at frelse os til Guds evige rige. Hvordan kan vi da ignorere så stor en frelse?

**Til at tænke over**

`Hvilken trøst kan vi finde i det faktum, at Faderen, Sønnen og Helligånden sammen arbejder for vores evige lykke?`


text:
typedef struct
{
    SDL_Window *win;
    SDL_Renderer *render;
    TTF_Font *font;
    SDL_Color font_colour;
}
Display;

//  PROTOTYPES  //////////////////////////////////////////////////////

result init_display(Display *disp, Scene *scene);
void quit_display(Display *disp);

result draw_scene(Display *disp, Scene *scene);
result draw_text(Display *disp, const char *text, int x, int y);

SDL_Texture *load_image(Display *disp, const char *filename);

#endif


text:
import warnings
import numpy as np
import scipy.sparse as sp

from .base import BaseEstimator, ClassifierMixin, RegressorMixin
from .base import MultiOutputMixin
from .utils import check_random_state
from .utils.validation import _num_samples
from .utils.validation import check_array
from .utils.validation import check_consistent_length
from .utils.validation import check_is_fitted
from .utils.random import random_choice_csc
from .utils.stats import _weighted_percentile
from .utils.multiclass import class_distribution

class DummyClassifier(BaseEstimator, ClassifierMixin, MultiOutputMixin):
    """
    DummyClassifier is a classifier that makes predictions using simple rules.

    This classifier is useful as a simple baseline to compare with other
    (real) classifiers. Do not use it for real problems.

    Read more in the :ref:`User Guide <dummy_estimators>`.

    Parameters
    ----------
    strategy : str, default="stratified"
        Strategy to use to generate predictions.

        * "stratified": generates predictions by respecting the training
          set's class distribution.
        * "most_frequent": always predicts the most frequent label in the
          training set.
        * "prior": always predicts the class that maximizes the class prior
          (like "most_frequent") and ``predict_proba`` returns the class prior.
        * "uniform": generates predictions uniformly at random.
        * "constant": always predicts a constant label that is provided by
          the user. This is useful for metrics that evaluate a non-majority
          class

          .. versionadded:: 0.17
             Dummy Classifier now supports prior fitting strategy using
             parameter *prior*.

    random_state : int, RandomState instance or None, optional, default=None
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    constant : int or str or array of shape = [n_outputs]
        The explicit constant as predicted by the "constant" strategy. This
        parameter is useful only for the "constant" strategy.

    Attributes
    ----------
    classes_ : array or list of array of shape = [n_classes]
        Class labels for each output.

    n_classes_ : array or list of array of shape = [n_classes]
        Number of label for each output.

    class_prior_ : array or list of array of shape = [n_classes]
        Probability of each class for each output.

    n_outputs_ : int,
        Number of outputs.

    sparse_output_ : bool,
        True if the array returned from predict is to be in sparse CSC format.
        Is automatically set to True if the input y is passed in sparse format.
    """

    def __init__(self, strategy="stratified", random_state=None,
                 constant=None):
        self.strategy = strategy
        self.random_state = random_state
        self.constant = constant

    def fit(self, X, y, sample_weight=None):
        """Fit the random classifier.

        Parameters
        ----------
        X : {array-like, object with finite length or shape}
            Training data, requires length = n_samples

        y : array-like, shape = [n_samples] or [n_samples, n_outputs]
            Target values.

        sample_weight : array-like of shape = [n_samples], optional
            Sample weights.

        Returns
        -------
        self : object
        """
        allowed_strategies = ("most_frequent", "stratified", "uniform",
                              "constant", "prior")
        if self.strategy not in allowed_strategies:
            raise ValueError("Unknown strategy type: %s, expected one of %s."
                             % (self.strategy, allowed_strategies))

        if self.strategy == "uniform" and sp.issparse(y):
            y = y.toarray()
            warnings.warn('A local copy of the target data has been converted '
                          'to a numpy array. Predicting on sparse target data '
                          'with the uniform strategy would not save memory '
                          'and would be slower.',
                          UserWarning)

        self.sparse_output_ = sp.issparse(y)

        if not self.sparse_output_:
            y = np.atleast_1d(y)

        self.output_2d_ = y.ndim == 2 and y.shape[1] > 1

        if y.ndim == 1:
            y = np.reshape(y, (-1, 1))

        self.n_outputs_ = y.shape[1]

        check_consistent_length(X, y, sample_weight)

        if self.strategy == "constant":
            if self.constant is None:
                raise ValueError("Constant target value has to be specified "
                                 "when the constant strategy is used.")
            else:
                constant = np.reshape(np.atleast_1d(self.constant), (-1, 1))
                if constant.shape[0] != self.n_outputs_:
                    raise ValueError("Constant target value should have "
                                     "shape (%d, 1)." % self.n_outputs_)

        (self.classes_,
         self.n_classes_,
         self.class_prior_) = class_distribution(y, sample_weight)

        if (self.strategy == "constant" and
                any(constant[k] not in self.classes_[k]
                    for k in range(self.n_outputs_))):
            # Checking in case of constant strategy if the constant
            # provided by the user is in y.
            raise ValueError("The constant target value must be "
                             "present in training data")

        if self.n_outputs_ == 1 and not self.output_2d_:
            self.n_classes_ = self.n_classes_[0]
            self.classes_ = self.classes_[0]
            self.class_prior_ = self.class_prior_[0]

        return self

    def predict(self, X):
        """Perform classification on test vectors X.

        Parameters
        ----------
        X : {array-like, object with finite length or shape}
            Training data, requires length = n_samples

        Returns
        -------
        y : array, shape = [n_samples] or [n_samples, n_outputs]
            Predicted target values for X.
        """
        check_is_fitted(self, 'classes_')

        # numpy random_state expects Python int and not long as size argument
        # under Windows
        n_samples = _num_samples(X)
        rs = check_random_state(self.random_state)

        n_classes_ = self.n_classes_
        classes_ = self.classes_
        class_prior_ = self.class_prior_
        constant = self.constant
        if self.n_outputs_ == 1 and not self.output_2d_:
            # Get same type even for self.n_outputs_ == 1
            n_classes_ = [n_classes_]
            classes_ = [classes_]
            class_prior_ = [class_prior_]
            constant = [constant]
        # Compute probability only once
        if self.strategy == "stratified":
            proba = self.predict_proba(X)
            if self.n_outputs_ == 1 and not self.output_2d_:
                proba = [proba]

        if self.sparse_output_:
            class_prob = None
            if self.strategy in ("most_frequent", "prior"):
                classes_ = [np.array([cp.argmax()]) for cp in class_prior_]

            elif self.strategy == "stratified":
                class_prob = class_prior_

            elif self.strategy == "uniform":
                raise ValueError("Sparse target prediction is not "
                                 "supported with the uniform strategy")

            elif self.strategy == "constant":
                classes_ = [np.array([c]) for c in constant]

            y = random_choice_csc(n_samples, classes_, class_prob,
                                  self.random_state)
        else:
            if self.strategy in ("most_frequent", "prior"):
                y = np.tile([classes_[k][class_prior_[k].argmax()] for
                             k in range(self.n_outputs_)], [n_samples, 1])

            elif self.strategy == "stratified":
                y = np.vstack([classes_[k][proba[k].argmax(axis=1)] for
                               k in range(self.n_outputs_)]).T

            elif self.strategy == "uniform":
                ret = [classes_[k][rs.randint(n_classes_[k], size=n_samples)]
                       for k in range(self.n_outputs_)]
                y = np.vstack(ret).T

            elif self.strategy == "constant":
                y = np.tile(self.constant, (n_samples, 1))

            if self.n_outputs_ == 1 and not self.output_2d_:
                y = np.ravel(y)

        return y

    def predict_proba(self, X):
        """
        Return probability estimates for the test vectors X.

        Parameters
        ----------
        X : {array-like, object with finite length or shape}
            Training data, requires length = n_samples

        Returns
        -------
        P : array-like or list of array-lke of shape = [n_samples, n_classes]
            Returns the probability of the sample for each class in
            the model, where classes are ordered arithmetically, for each
            output.
        """
        check_is_fitted(self, 'classes_')

        # numpy random_state expects Python int and not long as size argument
        # under Windows
        n_samples = _num_samples(X)
        rs = check_random_state(self.random_state)

        n_classes_ = self.n_classes_
        classes_ = self.classes_
        class_prior_ = self.class_prior_
        constant = self.constant
        if self.n_outputs_ == 1 and not self.output_2d_:
            # Get same type even for self.n_outputs_ == 1
            n_classes_ = [n_classes_]
            classes_ = [classes_]
            class_prior_ = [class_prior_]
            constant = [constant]

        P = []
        for k in range(self.n_outputs_):
            if self.strategy == "most_frequent":
                ind = class_prior_[k].argmax()
                out = np.zeros((n_samples, n_classes_[k]), dtype=np.float64)
                out[:, ind] = 1.0
            elif self.strategy == "prior":
                out = np.ones((n_samples, 1)) * class_prior_[k]

            elif self.strategy == "stratified":
                out = rs.multinomial(1, class_prior_[k], size=n_samples)
                out = out.astype(np.float64)

            elif self.strategy == "uniform":
                out = np.ones((n_samples, n_classes_[k]), dtype=np.float64)
                out /= n_classes_[k]

            elif self.strategy == "constant":
                ind = np.where(classes_[k] == constant[k])
                out = np.zeros((n_samples, n_classes_[k]), dtype=np.float64)
                out[:, ind] = 1.0

            P.append(out)

        if self.n_outputs_ == 1 and not self.output_2d_:
            P = P[0]

        return P

    def predict_log_proba(self, X):
        """
        Return log probability estimates for the test vectors X.

        Parameters
        ----------
        X : {array-like, object with finite length or shape}
            Training data, requires length = n_samples

        Returns
        -------
        P : array-like or list of array-like of shape = [n_samples, n_classes]
            Returns the log probability of the sample for each class in
            the model, where classes are ordered arithmetically for each
            output.
        """
        proba = self.predict_proba(X)
        if self.n_outputs_ == 1:
            return np.log(proba)
        else:
            return [np.log(p) for p in proba]

    def _more_tags(self):
        return {'poor_score': True, 'no_validation': True}

    def score(self, X, y, sample_weight=None):
        """Returns the mean accuracy on the given test data and labels.

        In multi-label classification, this is the subset accuracy
        which is a harsh metric since you require for each sample that
        each label set be correctly predicted.

        Parameters
        ----------
        X : {array-like, None}
            Test samples with shape = (n_samples, n_features) or
            None. Passing None as test samples gives the same result
            as passing real test samples, since DummyClassifier
            operates independently of the sampled observations.

        y : array-like, shape = (n_samples) or (n_samples, n_outputs)
            True labels for X.

        sample_weight : array-like, shape = [n_samples], optional
            Sample weights.

        Returns
        -------
        score : float
            Mean accuracy of self.predict(X) wrt. y.

        """
        if X is None:
            X = np.zeros(shape=(len(y), 1))
        return super().score(X, y, sample_weight)

class DummyRegressor(BaseEstimator, RegressorMixin, MultiOutputMixin):
    """
    DummyRegressor is a regressor that makes predictions using
    simple rules.

    This regressor is useful as a simple baseline to compare with other
    (real) regressors. Do not use it for real problems.

    Read more in the :ref:`User Guide <dummy_estimators>`.

    Parameters
    ----------
    strategy : str
        Strategy to use to generate predictions.

        * "mean": always predicts the mean of the training set
        * "median": always predicts the median of the training set
        * "quantile": always predicts a specified quantile of the training set,
          provided with the quantile parameter.
        * "constant": always predicts a constant value that is provided by
          the user.

    constant : int or float or array of shape = [n_outputs]
        The explicit constant as predicted by the "constant" strategy. This
        parameter is useful only for the "constant" strategy.

    quantile : float in [0.0, 1.0]
        The quantile to predict using the "quantile" strategy. A quantile of
        0.5 corresponds to the median, while 0.0 to the minimum and 1.0 to the
        maximum.

    Attributes
    ----------
    constant_ : array, shape (1, n_outputs)
        Mean or median or quantile of the training targets or constant value
        given by the user.

    n_outputs_ : int,
        Number of outputs.
    """

    def __init__(self, strategy="mean", constant=None, quantile=None):
        self.strategy = strategy
        self.constant = constant
        self.quantile = quantile

    def fit(self, X, y, sample_weight=None):
        """Fit the random regressor.

        Parameters
        ----------
        X : {array-like, object with finite length or shape}
            Training data, requires length = n_samples

        y : array-like, shape = [n_samples] or [n_samples, n_outputs]
            Target values.

        sample_weight : array-like of shape = [n_samples], optional
            Sample weights.

        Returns
        -------
        self : object
        """
        allowed_strategies = ("mean", "median", "quantile", "constant")
        if self.strategy not in allowed_strategies:
            raise ValueError("Unknown strategy type: %s, expected one of %s."
                             % (self.strategy, allowed_strategies))

        y = check_array(y, ensure_2d=False)
        if len(y) == 0:
            raise ValueError("y must not be empty.")

        self.output_2d_ = y.ndim == 2 and y.shape[1] > 1

        if y.ndim == 1:
            y = np.reshape(y, (-1, 1))
        self.n_outputs_ = y.shape[1]

        check_consistent_length(X, y, sample_weight)

        if self.strategy == "mean":
            self.constant_ = np.average(y, axis=0, weights=sample_weight)

        elif self.strategy == "median":
            if sample_weight is None:
                self.constant_ = np.median(y, axis=0)
            else:
                self.constant_ = [_weighted_percentile(y[:, k], sample_weight,
                                                       percentile=50.)
                                  for k in range(self.n_outputs_)]

        elif self.strategy == "quantile":
            if self.quantile is None or not np.isscalar(self.quantile):
                raise ValueError("Quantile must be a scalar in the range "
                                 "[0.0, 1.0], but got %s." % self.quantile)

            percentile = self.quantile * 100.0
            if sample_weight is None:
                self.constant_ = np.percentile(y, axis=0, q=percentile)
            else:
                self.constant_ = [_weighted_percentile(y[:, k], sample_weight,
                                                       percentile=percentile)
                                  for k in range(self.n_outputs_)]

        elif self.strategy == "constant":
            if self.constant is None:
                raise TypeError("Constant target value has to be specified "
                                "when the constant strategy is used.")

            self.constant = check_array(self.constant,
                                        accept_sparse=['csr', 'csc', 'coo'],
                                        ensure_2d=False, ensure_min_samples=0)

            if self.output_2d_ and self.constant.shape[0] != y.shape[1]:
                raise ValueError(
                    "Constant target value should have "
                    "shape (%d, 1)." % y.shape[1])

            self.constant_ = self.constant

        self.constant_ = np.reshape(self.constant_, (1, -1))
        return self

    def predict(self, X, return_std=False):
        """
        Perform classification on test vectors X.

        Parameters
        ----------
        X : {array-like, object with finite length or shape}
            Training data, requires length = n_samples

        return_std : boolean, optional
            Whether to return the standard deviation of posterior prediction.
            All zeros in this case.

        Returns
        -------
        y : array, shape = [n_samples] or [n_samples, n_outputs]
            Predicted target values for X.

        y_std : array, shape = [n_samples] or [n_samples, n_outputs]
            Standard deviation of predictive distribution of query points.
        """
        check_is_fitted(self, "constant_")
        n_samples = _num_samples(X)

        y = np.full((n_samples, self.n_outputs_), self.constant_,
                    dtype=np.array(self.constant_).dtype)
        y_std = np.zeros((n_samples, self.n_outputs_))

        if self.n_outputs_ == 1 and not self.output_2d_:
            y = np.ravel(y)
            y_std = np.ravel(y_std)

        return (y, y_std) if return_std else y

    def _more_tags(self):
        return {'poor_score': True, 'no_validation': True}

    def score(self, X, y, sample_weight=None):
        """Returns the coefficient of determination R^2 of the prediction.

        The coefficient R^2 is defined as (1 - u/v), where u is the residual
        sum of squares ((y_true - y_pred) ** 2).sum() and v is the total
        sum of squares ((y_true - y_true.mean()) ** 2).sum().
        The best possible score is 1.0 and it can be negative (because the
        model can be arbitrarily worse). A constant model that always
        predicts the expected value of y, disregarding the input features,
        would get a R^2 score of 0.0.

        Parameters
        ----------
        X : {array-like, None}
            Test samples with shape = (n_samples, n_features) or None.
            For some estimators this may be a
            precomputed kernel matrix instead, shape = (n_samples,
            n_samples_fitted], where n_samples_fitted is the number of
            samples used in the fitting for the estimator.
            Passing None as test samples gives the same result
            as passing real test samples, since DummyRegressor
            operates independently of the sampled observations.

        y : array-like, shape = (n_samples) or (n_samples, n_outputs)
            True values for X.

        sample_weight : array-like, shape = [n_samples], optional
            Sample weights.

        Returns
        -------
        score : float
            R^2 of self.predict(X) wrt. y.
        """
        if X is None:
            X = np.zeros(shape=(len(y), 1))
        return super().score(X, y, sample_weight)


text:
package de.fau.cs.mad.yasme.android.ui.fragments;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import de.fau.cs.mad.yasme.android.EditTextWithImage;
import de.fau.cs.mad.yasme.android.R;
import de.fau.cs.mad.yasme.android.asyncTasks.database.GetNewMessagesForChatTask;
import de.fau.cs.mad.yasme.android.asyncTasks.server.GetMessageTask;
import de.fau.cs.mad.yasme.android.asyncTasks.server.SendMessageTask;
import de.fau.cs.mad.yasme.android.controller.FragmentObservable;
import de.fau.cs.mad.yasme.android.controller.Log;
import de.fau.cs.mad.yasme.android.controller.NotifiableFragment;
import de.fau.cs.mad.yasme.android.controller.ObservableRegistry;
import de.fau.cs.mad.yasme.android.controller.Toaster;
import de.fau.cs.mad.yasme.android.encryption.MessageEncryption;
import de.fau.cs.mad.yasme.android.entities.Chat;
import de.fau.cs.mad.yasme.android.entities.Message;
import de.fau.cs.mad.yasme.android.entities.User;
import de.fau.cs.mad.yasme.android.storage.DatabaseManager;
import de.fau.cs.mad.yasme.android.storage.PictureManager;
import de.fau.cs.mad.yasme.android.ui.AbstractYasmeActivity;
import de.fau.cs.mad.yasme.android.ui.ChatAdapter;
import de.fau.cs.mad.yasme.android.ui.activities.ChatActivity;
import de.fau.cs.mad.yasme.android.ui.activities.ChatSettingsActivity;

/**
 * Created by Martin Sturm <martin.sturm@fau.de> on 21.06.2014.
 */
public class ChatFragment extends Fragment implements NotifiableFragment<List<Message>> {
    public static final String RESTORE_LATEST_MESSAGE_ON_DISPLAY = "LATEST_MESSAGE_ON_DISPLAY";
    public static final String RESTORE_CHAT_ID = "CHAT_ID";
    public static final String RESTORE_IMAGE_URI = "imageUri";

    private ChatAdapter mAdapter;
    private Chat chat;
    private AtomicLong latestMessageOnDisplay;
    private Context mContext;

    //UI references
    private Button imageCancel;
    private ImageView imageView;
    private EditText editMessage;
    private ListView list;

    private static final int RESULT_LOAD_IMAGE = 100;
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 200;

    private Uri imageUri;
    private Bitmap bitmap;

    public ChatFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Retrain instance variables!
        // setRetainInstance(true);

        ChatActivity activity = (ChatActivity) getActivity();
        mContext = DatabaseManager.INSTANCE.getContext();

        Intent intent = activity.getIntent();
        long chatId = intent.getLongExtra(AbstractYasmeActivity.CHAT_ID, -1);
        if (chatId <= 0) {
            throw new ExceptionInInitializerError("chatId <= 0");
        }

        //add the fragments own menu items
        setHasOptionsMenu(true);

        //trying to get chat with chatId from local DB
        try {
            chat = DatabaseManager.INSTANCE.getChatDAO().get(chatId);
            // Assuming that the messages are sorted by id
            latestMessageOnDisplay = new AtomicLong(0);
        } catch (NullPointerException e) {
            // Occurs when new chat has been generated, but id hasn't been returned by the server yet
            chat = null;
            Log.e(this.getClass().getSimpleName(), "get chat from DB failed");
        }
        if (chat == null) {
            Toaster.getInstance().toast(R.string.unable_open_chat, Toast.LENGTH_SHORT);
            activity.finish();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_chat, container, false);

        // Restore saved state if member variables are null
        // These lines would better fit to onRestoreView but this method requires a higher API level
        if (null != savedInstanceState) {
            if (null == latestMessageOnDisplay) {
                long latestMessageOnDisplayId = savedInstanceState.getLong(RESTORE_LATEST_MESSAGE_ON_DISPLAY);
                latestMessageOnDisplay = new AtomicLong(latestMessageOnDisplayId);
            }
            if (null == chat) {
                long chatId = savedInstanceState.getLong(RESTORE_CHAT_ID);
                chat = DatabaseManager.INSTANCE.getChatDAO().get(chatId);
                if (null == chat) {
                    Log.e(this.getClass().getSimpleName(), "Oh no, looks like this chat has been deleted in the meantime");
                    return rootView;
                }
            }
            // Restore the image uri if the device is rotated while capturing an image
            if (null == imageUri && savedInstanceState.containsKey(RESTORE_IMAGE_URI)) {
                imageUri = Uri.fromFile(new File(savedInstanceState.getString(RESTORE_IMAGE_URI)));
            }
        }

        list = (ListView) rootView.findViewById(R.id.chat_messageList);
        imageCancel = (Button) rootView.findViewById(R.id.button_cancel_image);
        imageCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageView.setImageResource(android.R.color.transparent);
                imageCancel.setVisibility(View.GONE);
                imageView.setVisibility(View.GONE);
                editMessage.setVisibility(View.VISIBLE);
                editMessage.requestFocus();
            }
        });

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        LinearLayout layoutTextView = (LinearLayout) rootView.findViewById(R.id.text_view_layout);
        final EditTextWithImage ownEdit = new EditTextWithImage(DatabaseManager.INSTANCE.getContext());
        editMessage = ownEdit.getEditText();
        imageView = ownEdit.getImageView();
        imageView.setMinimumHeight(256);
        imageView.setMinimumWidth(256);
        imageView.setMaxHeight(256);
        imageView.setMaxWidth(256);
        imageView.setVisibility(View.GONE);

        editMessage.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (editMessage.getCompoundDrawables()[2] == null) {
                    return false;
                }
                if (motionEvent.getAction() != MotionEvent.ACTION_UP) {
                    return false;
                }
                if (motionEvent.getX() > editMessage.getWidth() - editMessage.getPaddingRight()
                        - ownEdit.getIntrinsicWidth()) {
                    Log.d(this.getClass().getSimpleName(), "picture-button pressed");
                    //button pressed
                    showSelectionDialog();
                }
                return false;
            }
        });
        layoutTextView.addView(imageView, 0, params);
        layoutTextView.addView(editMessage, 0, params);

        Button buttonSend = (Button) rootView.findViewById(R.id.button_send);
        buttonSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                send(v);
            }
        });

        AbstractYasmeActivity activity = (AbstractYasmeActivity) getActivity();
        mAdapter = new ChatAdapter(activity, R.layout.chat_item_other, new ArrayList<Message>());
        list.setAdapter(mAdapter);
        mAdapter.setNotifyOnChange(true);
        notifyFragment(chat.getMessages());

        ((ChatActivity) getActivity()).setActionBarTitle(chat.getName(), chat.getStatus());

        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
        //Register at observer
        Log.d(this.getClass().getSimpleName(), "Try to get ChatListObservableInstance");
        FragmentObservable<ChatFragment, List<Message>> obs = ObservableRegistry.getObservable(ChatFragment.class);
        Log.d(this.getClass().getSimpleName(), "... successful");

        obs.register(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(getClass().getSimpleName(), "Update Chat");
        // Ask server for new messages
        Log.d(getClass().getSimpleName(), "GetMessageTask started from ChatFragment");
        new GetMessageTask(this.getClass()).execute();
    }

    @Override
    public void onStop() {
        super.onStop();
        FragmentObservable<ChatFragment, List<Message>> obs = ObservableRegistry.
                getObservable(ChatFragment.class);
        Log.d(this.getClass().getSimpleName(), "Remove from observer");
        obs.remove(this);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);

        // Save states
        savedInstanceState.putLong(RESTORE_LATEST_MESSAGE_ON_DISPLAY, latestMessageOnDisplay.get());
        savedInstanceState.putLong(RESTORE_CHAT_ID, chat.getId());
        if (null != imageUri) {
            savedInstanceState.putString(RESTORE_IMAGE_URI, imageUri.getPath());
        }
    }

    private void showSelectionDialog() {
        AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
        alert.setTitle(getString(R.string.select_image_source_title));
        alert.setMessage(getString(R.string.select_image_source_message));
        if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            alert.setNeutralButton(R.string.select_camera, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    // create Intent to take a picture and return control to the calling application
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    //create temp file
                    File file = null;
                    try {
                        file = PictureManager.getOutputMediaFilePath();
                    } catch (IOException e) {
                        Log.e(this.getClass().getSimpleName(), "Error during creating the file");
                        return;
                    }
                    imageUri = Uri.fromFile(file);

                    try {
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                        intent.putExtra("data", true);
                        // start the image capture Intent
                        startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
                    } catch (Exception e) {
                        Log.e(this.getClass().getSimpleName(), "Error during capturing an image");
                    }
                }
            });
        }
        alert.setPositiveButton(R.string.select_gallery, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, RESULT_LOAD_IMAGE);
            }
        });
        alert.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
            }
        });
        Log.d(this.getClass().getSimpleName(), "show selection dialog");
        alert.show();
    }

    @Override
    public void notifyFragment(List<Message> messages) {
        Log.d(super.getClass().getSimpleName(), "I have been notified. Yeeha!");
        if (messages == null) {
            // Notified from GetMessageTask, new Messages are stored in the DB
            // Note that retrieved messages will be ordered ascending by id
            new GetNewMessagesForChatTask(latestMessageOnDisplay.get(), chat.getId(), this.getClass())
                    .execute(this.getClass().getName());
            // And don't stop the progress bar
            return;
        } else {
            //Notified from GetNewMessageForChatTask
            updateViews(messages);
        }
        Log.d(this.getClass().getSimpleName(), "Received " + messages.size() + " messages");
    }

    public Chat getChat() {
        return chat;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && null != data && resultCode == Activity.RESULT_OK) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = mContext.getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            User user = new User();
            user.setProfilePicture(picturePath);
            bitmap = PictureManager.INSTANCE.getPicture(user, 256, 256);

            if (bitmap != null) {
                editMessage.setVisibility(View.GONE);
                imageCancel.setVisibility(View.VISIBLE);
                imageView.setVisibility(View.VISIBLE);
                imageView.setImageBitmap(ThumbnailUtils.extractThumbnail(bitmap, 128, 128));
            }
        }
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            String path = imageUri.getPath();

            User user = new User();
            user.setProfilePicture(path);
            bitmap = PictureManager.INSTANCE.getPicture(user, 256, 256);
        }
        if (bitmap != null) {
            editMessage.setVisibility(View.GONE);
            imageCancel.setVisibility(View.VISIBLE);
            imageView.setVisibility(View.VISIBLE);
            imageView.setImageBitmap(ThumbnailUtils.extractThumbnail(bitmap, 128, 128));
        }
    }

    public void send(View view) {
        if (editMessage.getVisibility() != View.GONE) {
            //case message
            String msgText = editMessage.getText().toString();
            if (msgText.isEmpty()) {
                Log.d(this.getClass().getSimpleName(), "Nichts eingegeben");
                return;
            }
            if (msgText.length() > 10000) {
                Toaster.getInstance().toast(R.string.text_to_long, Toast.LENGTH_LONG);
                return;
            }

            // Send trimmed message without whitespaces and get new messages afterwards
            AbstractYasmeActivity activity = (AbstractYasmeActivity) getActivity();
            Log.d(getClass().getSimpleName(), "GetMessageTask started from ChatFragment (send)");
            new SendMessageTask(chat, activity.getSelfUser(),
                    new GetMessageTask(this.getClass()), SendMessageTask.Mime.PLAIN).execute(msgText.trim());

            Log.d(this.getClass().getSimpleName(), "Send message in bg");
            // Empty the input field after send button was pressed
            editMessage.setText("");
        } else {
            // case picture
            AbstractYasmeActivity activity = (AbstractYasmeActivity) getActivity();
            imageView.setImageResource(android.R.color.transparent);
            imageView.setVisibility(View.GONE);
            imageCancel.setVisibility(View.GONE);
            editMessage.setVisibility(View.VISIBLE);
            editMessage.requestFocus();

            String imageMessage = PictureManager.INSTANCE.bitMapToString(bitmap);
            new SendMessageTask(chat, activity.getSelfUser(), new GetMessageTask(this.getClass()),
                    SendMessageTask.Mime.IMAGE).execute(imageMessage);
        }
    }

    public void updateViews(List<Message> messages) {
        if (messages == null) {
            Log.d(this.getClass().getSimpleName(), "Keine Nachrichten zum Ausgeben");
            return;
        }

        List<Message> newMessages = new ArrayList<>();

        // Even if this fragment will be notified with same messages several times, it should not display them more than once
        // Synchronize the write access on latestMessageOnDisplay in case the fragment can be notified by more than one thread
        synchronized (this) {
            long newLatestMessageOnDisplay = latestMessageOnDisplay.get();
            for (Message msg : messages) {
                // Ignore messages which were not meant for this chat
                if (msg.getChat().getId() == chat.getId() && msg.getId() > latestMessageOnDisplay.get()) {
                    newMessages.add(msg);
                    newLatestMessageOnDisplay = Math.max(newLatestMessageOnDisplay, msg.getId());
                }
            }
            latestMessageOnDisplay.set(newLatestMessageOnDisplay);
        }

        int count = 0;
        ArrayList<Message> newNewMessages = new ArrayList<>();
        for (int i = 0; i < newMessages.size(); i++) {
            Message msg = newMessages.get(i);
            if (msg.getErrorId() == MessageEncryption.ErrorType.DECRYPTION_FAILED) {
                count++;
                if (i >= newMessages.size() - 1 || newMessages.get(i + 1).getErrorId() != MessageEncryption.ErrorType.DECRYPTION_FAILED) {
                    msg.setMessage(String.valueOf(count) + " " + getResources().getString(R.string.decryption_failed));
                    msg.setErrorId(0);
                    newNewMessages.add(msg);
                }
            } else {
                newNewMessages.add(msg);
            }
        }

        mAdapter.addAll(newNewMessages);
        editMessage.requestFocus();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int itemId = item.getItemId();
        if (itemId == R.id.action_chat_settings) {
            Intent intent = new Intent(getActivity(), ChatSettingsActivity.class);
            intent.putExtra(ChatSettingsActivity.CHAT_ID, chat.getId());
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
package com.clicktravel.infrastructure.messaging.aws.sqs;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.policy.Policy;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.model.*;

/**
 * Represents an actual AWS SQS queue that exists in the AWS environment. Provides some convenience methods for working
 * with the actual AWS SQS queue.
 */
public class SqsQueueResource {

    private static final String AWS_POLICY_ATTRIBUTE = QueueAttributeName.Policy.toString();
    private static final String SQS_QUEUE_ARN_ATTRIBUTE = QueueAttributeName.QueueArn.toString();

    private final Logger logger = LoggerFactory.getLogger(getClass());
    private final String queueName;
    private final AmazonSQS amazonSqsClient;
    private final String queueUrl;
    private String queueArn; // lazily initialised

    public SqsQueueResource(final String queueName, final String queueUrl, final AmazonSQS amazonSqsClient) {
        this.queueName = queueName;
        this.queueUrl = queueUrl;
        this.amazonSqsClient = amazonSqsClient;
    }

    /**
     * Sends a message to the AWS SQS queue
     * @param messageBody Body of the message to send
     */
    public void sendMessage(final String messageBody) throws AmazonClientException {
        final SendMessageRequest sendMessageRequest = new SendMessageRequest(queueUrl, messageBody);
        doSendRequest(sendMessageRequest);
    }

    /**
     * Sends a delayed message to the AWS SQS queue
     * @param messageBody Body of the message to send
     * @param delaySeconds Number of seconds to delay visibility of the sent message
     */
    public void sendDelayedMessage(final String messageBody, final int delaySeconds) throws AmazonClientException {
        final SendMessageRequest sendMessageRequest = new SendMessageRequest(queueUrl, messageBody)
                .withDelaySeconds(delaySeconds);
        doSendRequest(sendMessageRequest);
    }

    private void doSendRequest(final SendMessageRequest sendMessageRequest) throws AmazonClientException {
        amazonSqsClient.sendMessage(sendMessageRequest);
        logger.trace("Successfully sent message: Payload=" + sendMessageRequest.getMessageBody() + "] to SQS queue: ["
                + queueName + "]");
    }

    /**
     * Receive up to 10 messages from the AWS SQS queue, using short polling. If an error occurs performing the SQS
     * ReceiveMessageRequest, the request is retried until it succeeds.
     * @return {@code List<com.amazonaws.services.sqs.model.Message>} received messages
     * @throws InterruptedException
     */
    public List<Message> receiveMessages() throws AmazonClientException {
        return doReceiveRequest(new ReceiveMessageRequest(queueUrl));
    }

    /**
     * Receive up to the given number of messages from the AWS SQS queue, waiting the specified time for messages to
     * appear.
     * @param waitTimeSeconds Number of seconds to wait for messages to appear
     * @param maxMessages Maximum number of messages returned, may be up to 10.
     * @return {@code List<com.amazonaws.services.sqs.model.Message>} received messages
     * @throws InterruptedException
     */
    public List<Message> receiveMessages(final int waitTimeSeconds, final int maxMessages) throws AmazonClientException {
        final ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(queueUrl).withWaitTimeSeconds(
                waitTimeSeconds).withMaxNumberOfMessages(maxMessages);
        return doReceiveRequest(receiveMessageRequest);
    }

    private List<Message> doReceiveRequest(final ReceiveMessageRequest receiveMessageRequest)
            throws AmazonClientException {
        return amazonSqsClient.receiveMessage(receiveMessageRequest).getMessages();
    }

    /**
     * Delete a previously received message from the AWS SQS queue. Up to {@link #MAX_SQS_DELETE_MESSAGE_ATTEMPTS}
     * attempts are made to perform the SQS {@link DeleteMessageRequest}.
     * @param receiptHandle Identifier of message to delete, given with receipt of the message
     */
    public void deleteMessage(final String receiptHandle) throws AmazonClientException {
        final DeleteMessageRequest deleteMessageRequest = new DeleteMessageRequest(queueUrl, receiptHandle);
        amazonSqsClient.deleteMessage(deleteMessageRequest);
    }

    /**
     * Sets the {@link Policy} of the AWS SQS queue
     * @param policy {@link Policy} to set
     */
    public void setPolicy(final Policy policy) throws AmazonClientException {
        final Map<String, String> queueAttributes = Collections.singletonMap(AWS_POLICY_ATTRIBUTE, policy.toJson());
        amazonSqsClient.setQueueAttributes(new SetQueueAttributesRequest(queueUrl, queueAttributes));
    }

    /**
     * @return The ARN of the AWS SQS queue
     */
    public String queueArn() throws AmazonClientException {
        if (queueArn == null) {
            final GetQueueAttributesRequest request = new GetQueueAttributesRequest(queueUrl)
                    .withAttributeNames(SQS_QUEUE_ARN_ATTRIBUTE);
            final GetQueueAttributesResult getQueueAttributesResult = amazonSqsClient.getQueueAttributes(request);
            queueArn = getQueueAttributesResult.getAttributes().get(SQS_QUEUE_ARN_ATTRIBUTE);
        }
        return queueArn;
    }

    /**
     * @return The AWS SQS queue name
     */
    public String getQueueName() {
        return queueName;
    }
}


text:
namespace ProductiveRage.Immutable
{
	/// <summary>
	/// This implementation varies from the Bridge one because the GetMethod method signatures supported by Bridge are different to .NET and the easiest
	/// thing to do is to trim out that logic from this 'non-BridgeBuild'
	/// </summary>
	public static class ObjectLiteralSupportingEquality
	{
		public static bool AreEqual(object x, object y)
		{
			if ((x == null) && (y == null))
				return true;
			else if ((x == null) || (y == null))
				return false;
			return x.Equals(y);
		}
	}
}


text:
          Source Code

Join in: Get the Sources for this guide.

        Download as .zip
        or checkout the corresponding tag with Git.

      In addition to this guide, the source code of the example project is also available on
      GitHub.
      You can directly download
      the whole project or clone it with git:

git clone https://github.com/camunda/{{ .Get "repo" }}.git

      To follow this guide, download
      the initial state or checkout the tag in the git repository:

git checkout -f Start

      or every step in between:

git checkout -f Step-X

      After every section in this guide you will find a box which contains a download link to the current
      state of the project and git instructions to checkout the current version of the repository.


text:
class FlyingMob : public Mob
{
public:
	FlyingMob(BlockSource &);
	virtual ~FlyingMob();
	virtual void causeFallDamage(float);
	virtual void onLadder();
	virtual void travel(float, float);
};


text:
using SQLite;

namespace DAL
{
    public class Distribution
    {
        public Distribution() { }

        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }

        [Unique]
        public string Name { get; set; }

        public string Website { get; set; }

        public byte ReleaseModel { get; set; }

        public enum ReleaseModels
        {
            Fixed = 1,
            Rolling = 2
        }
    }
}


text:
package org.basex.query.func.file;

import static org.basex.query.QueryError.*;

import java.io.*;
import java.nio.file.*;

import org.basex.query.*;
import org.basex.query.value.item.*;

/**
 * Function implementation.
 *
 * @author BaseX Team 2005-15, BSD License
 * @author Christian Gruen
 */
public class FileCopy extends FileFn {
  @Override
  public Item item(final QueryContext qc) throws IOException, QueryException {
    return relocate(true, qc);
  }

  /**
   * Transfers a file path, given a source and a target.
   * @param copy copy flag (no move)
   * @param qc query context
   * @return result
   * @throws QueryException query exception
   * @throws IOException I/O exception
   */
  final synchronized Item relocate(final boolean copy, final QueryContext qc)
      throws QueryException, IOException {

    final Path source = toPath(0, qc);
    if(!Files.exists(source)) throw FILE_NOT_FOUND_X.get(info, source);
    final Path src = absolute(source);
    Path trg = absolute(toPath(1, qc));

    if(Files.isDirectory(trg)) {
      // target is a directory: attach file name
      trg = trg.resolve(src.getFileName());
      if(Files.isDirectory(trg)) throw FILE_IS_DIR_X.get(info, trg);
    } else if(!Files.exists(trg)) {
      // target does not exist: ensure that parent exists
      if(!Files.isDirectory(trg.getParent())) throw FILE_NO_DIR_X.get(info, trg);
    } else if(Files.isDirectory(src)) {
      // if target is file, source cannot be a directory
      throw FILE_IS_DIR_X.get(info, src);
    }

    // ignore operations on identical, canonical source and target path
    relocate(src, trg, copy);
    return null;
  }

  /**
   * Recursively copies files.
   * @param src source path
   * @param trg target path
   * @param copy copy flag
   * @throws IOException I/O exception
   */
  private synchronized void relocate(final Path src, final Path trg, final boolean copy)
      throws IOException {

    if(Files.isDirectory(src)) {
      Files.createDirectory(trg);
      try(DirectoryStream<Path> paths = Files.newDirectoryStream(src)) {
        for(final Path p : paths) relocate(p, trg.resolve(p.getFileName()), copy);
      }
      if(!copy) Files.delete(src);
    } else if(copy) {
      Files.copy(src, trg, StandardCopyOption.REPLACE_EXISTING);
    } else {
      Files.move(src, trg, StandardCopyOption.REPLACE_EXISTING);
    }
  }
}