text:
// Ops for operating with sets. They are not checked in
// to TensorFlow because we would first like to demonstrate successful
// end-to-end use of these ops in eval and polish the api a bit like taking two
// SparseTensor rather than on edense and one sparse.

#define EIGEN_USE_THREADS

#include <algorithm>
#include <numeric>
#include <string>
#include <utility>
#include <vector>

#include "absl/container/btree_set.h"
#include "absl/container/flat_hash_set.h"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_util.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/util/sparse/sparse_tensor.h"

namespace tensorflow {

using ShapeArray = sparse::SparseTensor::ShapeArray;
using VarDimArray = sparse::SparseTensor::VarDimArray;

// Validate rank >= 2.
void CheckRankAtLeast2(OpKernelContext* ctx, const TensorShape& shape) {
  const auto rank = shape.dims();
  OP_REQUIRES(ctx, rank >= 2,
              errors::InvalidArgument("Invalid rank ", rank, "."));
}

// Return group shape, which is the 1st n-1 dimensions of shape.
Status GroupShape(const VarDimArray& input_shape, ShapeArray* grouped_shape) {
  if (input_shape.size() < 2) {
    // TODO(irving): Why can't 2 be 1 here?
    return errors::InvalidArgument("Shape [", absl::StrJoin(input_shape, ","),
                                   "] has rank ", input_shape.size(), " < 2");
  }
  // grouped_shape is input_shape[:-1]
  *grouped_shape = ShapeArray(input_shape.begin(), input_shape.end() - 1);
  return Status::OK();
}

// Build `SparseTensor` from indices, values, and shape in inputs
// [base_index, base_index + 3), and validate its rank and indices.
Status SparseTensorFromContext(OpKernelContext* ctx, const int32_t base_index,
                               const bool validate_indices,
                               sparse::SparseTensor* tensor) {
  // Assume row-major order.
  TensorShape shape;
  TF_RETURN_IF_ERROR(TensorShape::BuildTensorShape(
      ctx->input(base_index + 2).vec<int64_t>(), &shape));
  CheckRankAtLeast2(ctx, shape);
  std::vector<int64_t> order(shape.dims());
  std::iota(order.begin(), order.end(), 0);

  Status status = sparse::SparseTensor::Create(
      ctx->input(base_index), ctx->input(base_index + 1), shape, order, tensor);

  if (!validate_indices || !status.ok()) return status;
  return tensor->IndicesValid();
}

// TODO(ptucker): CheckGroup is just a sanity check on the result of
// SparseTensor.group, consider removing.
// `sparse_tensor_shape` is the shape of the `SparseTensor` from which group
// was created, and is used to sanity check the indices in `group'.
template <typename T>
void CheckGroup(OpKernelContext* ctx, const sparse::Group& group,
                const VarDimArray& sparse_tensor_shape) {
  const auto& indices = group.indices();
  const auto& values = group.values<T>();

  // Sanity check: group is non-empty, and indices and values are same size.
  const auto num_values = values.dimension(0);
  OP_REQUIRES(ctx, indices.size() > 0, errors::Internal("Empty group."));
  OP_REQUIRES(
      ctx, indices.dimension(0) == num_values,
      errors::Internal("shape[0] of group indices ", indices.dimension(0),
                       " != values ", num_values, "."));

  // Sanity check: valid indices.
  const auto group_rank = indices.dimension(1);
  const auto expected_rank = sparse_tensor_shape.size();
  OP_REQUIRES(ctx, expected_rank == group_rank,
              errors::Internal("Rank expected ", expected_rank, ", got ",
                               group_rank, "."));
  for (int32_t j = 0; j < expected_rank; ++j) {
    const auto dim_size = sparse_tensor_shape[j];
    OP_REQUIRES(
        ctx, dim_size > 0,
        errors::Internal("Invalid dim_size[", j, "] = ", dim_size, "."));
    for (int64_t i = 0; i < num_values; ++i) {
      const auto index = indices(i, j);
      OP_REQUIRES(ctx, dim_size > index,
                  errors::Internal("indices[", i, ", ", j, "] expected < ",
                                   dim_size, ", got ", index, "."));
    }
  }
}

// This lets us calculate the row-major index into flattened output.
const ShapeArray Strides(const VarDimArray& shape) {
  ShapeArray result(shape.size());
  int64_t product = 1;
  for (int i = shape.size() - 1; i >= 0; --i) {
    result[i] = product;
    product *= shape[i];
  }
  return result;
}

// TODO(ptucker): If memory becomes an issue, consider a 2-pass approach to
// eliminate the intermediate `values` data structure - iterate once to
// determine `num_values`, allocate output tensors, then write results directly
// to output tensors.

// TODO(ptucker): Consider sharding work across multiple threads. See
// SparseCrossOp for an example.

// Output `SparseTensor` of shape `output_shape`. `sets` contains pairs of
// group indices (i.e., values for all but the last dimension of `output_shape`)
// and set values, each of which will occupy the last dimension of
// `output_shape`. `sets` should be sorted in ascending order by group indices.
template <typename T>
void OutputSparseTensor(
    OpKernelContext* ctx, const TensorShape& output_shape,
    const int64_t num_values,
    const std::vector<std::pair<std::vector<int64_t>, absl::btree_set<T>>>&
        sets) {
  // Allocate 3 output tensors for sparse data.
  Tensor *out_indices_t, *out_values_t, *out_shape_t;
  OP_REQUIRES_OK(ctx, ctx->allocate_output(
                          0, TensorShape({num_values, output_shape.dims()}),
                          &out_indices_t));
  OP_REQUIRES_OK(
      ctx, ctx->allocate_output(1, TensorShape({num_values}), &out_values_t));
  OP_REQUIRES_OK(ctx, ctx->allocate_output(
                          2, TensorShape({output_shape.dims()}), &out_shape_t));
  auto out_indices_mat = out_indices_t->matrix<int64_t>();
  auto out_values_flat = out_values_t->vec<T>();

  // For each set, write its indices and values to output tensors.
  int64_t value_index = 0;
  for (auto it = sets.begin(); it != sets.end(); ++it) {
    const auto& group_indices = it->first;
    OP_REQUIRES(
        ctx, group_indices.size() == output_shape.dims() - 1,
        errors::Internal("Invalid number of indices ", group_indices.size(),
                         ", expected ", output_shape.dims() - 1, "."));
    const auto& set = it->second;

    // For each set item, write its indices and value to output tensors.
    int64_t group_value_index = 0;
    for (auto value = set.begin(); value != set.end();
         ++value, ++value_index, ++group_value_index) {
      // First n-1 dimensions are the group, last dimension is the position in
      // the set.
      for (int32_t i = 0; i < group_indices.size(); ++i) {
        out_indices_mat(value_index, i) = group_indices[i];
      }
      out_indices_mat(value_index, group_indices.size()) = group_value_index;

      out_values_flat(value_index) = *value;
    }
  }

  // Write output shape.
  auto out_shape_flat = out_shape_t->vec<int64_t>();
  for (int32_t i = 0; i < output_shape.dims(); ++i) {
    out_shape_flat(i) = output_shape.dim_size(i);
  }
}

bool ValidateIndicesFromContext(OpKernelConstruction* ctx) {
  bool result;
  if (ctx->GetAttr("validate_indices", &result).ok()) {
    return result;
  }
  return true;
}

// Populate `result` set from group in `tensor`. "Group" is defined by
// `group_indices`, which are values for the first n-1 dimensions of
// `input_tensor`. `input_strides` is provided to avoid recalculating it
// multiple times, and is used to calculate the flat index into `input_tensor`
// values.
template <typename T>
void PopulateFromDenseGroup(OpKernelContext* ctx, const Tensor& input_tensor,
                            const VarDimArray& input_strides,
                            const std::vector<int64_t>& group_indices,
                            absl::flat_hash_set<T>* result) {
  OP_REQUIRES(ctx, group_indices.size() == input_strides.size() - 1,
              errors::Internal("group_indices.size ", group_indices.size(),
                               ", !=  input_strides.size-1 ",
                               input_strides.size() - 1, "."));
  result->clear();
  auto input_flat = input_tensor.flat<T>();
  const auto start = std::inner_product(
      group_indices.begin(), group_indices.end(), input_strides.begin(), 0LL);
  const TensorShape& input_shape = input_tensor.shape();
  const auto end = start + input_shape.dim_size(input_shape.dims() - 1);
  for (int64_t i = start; i < end; ++i) {
    result->insert(input_flat(i));
  }
}

// Populate `result` set from `group`. `sparse_tensor_shape` is the shape of the
// `SparseTensor` from which group was created, and is used to sanity check the
// indices in `group'.
template <typename T>
void PopulateFromSparseGroup(OpKernelContext* ctx, const sparse::Group& group,
                             const VarDimArray& sparse_tensor_shape,
                             absl::flat_hash_set<T>* result) {
  CheckGroup<T>(ctx, group, sparse_tensor_shape);
  result->clear();
  const auto& group_values = group.values<T>();
  for (int64_t i = 0; i < group_values.size(); ++i) {
    result->insert(group_values(i));
  }
}

template <typename T>
class SetSizeOp : public OpKernel {
 public:
  explicit SetSizeOp(OpKernelConstruction* ctx)
      : OpKernel(ctx), validate_indices_(ValidateIndicesFromContext(ctx)) {}

  void Compute(OpKernelContext* ctx) override;

 private:
  const bool validate_indices_;
};

template <typename T>
void SetSizeOp<T>::Compute(OpKernelContext* ctx) {
  sparse::SparseTensor set_st;
  OP_REQUIRES_OK(ctx,
                 SparseTensorFromContext(ctx, 0, validate_indices_, &set_st));

  // Output shape is same as input except for last dimension, which reduces
  // to the set size of values along that dimension.
  ShapeArray output_shape;
  OP_REQUIRES_OK(ctx, GroupShape(set_st.shape(), &output_shape));
  const auto output_strides = Strides(output_shape);

  TensorShape output_shape_ts;
  OP_REQUIRES_OK(ctx,
                 TensorShapeUtils::MakeShape(output_shape, &output_shape_ts));
  Tensor* out_t;
  OP_REQUIRES_OK(ctx, ctx->allocate_output(0, output_shape_ts, &out_t));
  auto out = out_t->flat<int32>();
  out.device(ctx->eigen_cpu_device()) = out.constant(static_cast<int32>(0.0));

  // Group by all but last dimension, create a set of group values, and add set
  // size to output.
  VarDimArray group_ix = set_st.order().subspan(0, set_st.order().size() - 1);
  absl::flat_hash_set<T> group_set;
  for (const auto& group : set_st.group(group_ix)) {
    PopulateFromSparseGroup<T>(ctx, group, set_st.shape(), &group_set);

    const auto group_key = group.group();
    const auto output_index = std::inner_product(
        group_key.begin(), group_key.end(), output_strides.begin(), 0LL);
    out(output_index) = group_set.size();
  }
}

#define _SET_SIZE_REGISTER_KERNEL_BUILDER(T)                     \
  REGISTER_KERNEL_BUILDER(                                       \
      Name("SetSize").Device(DEVICE_CPU).TypeConstraint<T>("T"), \
      SetSizeOp<T>);
_SET_SIZE_REGISTER_KERNEL_BUILDER(int8);
_SET_SIZE_REGISTER_KERNEL_BUILDER(int16);
_SET_SIZE_REGISTER_KERNEL_BUILDER(int32);
_SET_SIZE_REGISTER_KERNEL_BUILDER(int64_t);
_SET_SIZE_REGISTER_KERNEL_BUILDER(uint8);
_SET_SIZE_REGISTER_KERNEL_BUILDER(uint16);
_SET_SIZE_REGISTER_KERNEL_BUILDER(tstring);
#undef _SET_SIZE_REGISTER_KERNEL_BUILDER

enum InputTypes {
  DENSE_DENSE = 0,
  DENSE_SPARSE = 1,
  SPARSE_SPARSE = 2,
};

enum SetOperation { A_MINUS_B = 0, B_MINUS_A = 1, INTERSECTION = 2, UNION = 3 };

SetOperation SetOperationFromContext(OpKernelConstruction* ctx) {
  string set_operation_str;
  if (!ctx->GetAttr("set_operation", &set_operation_str).ok()) {
    ctx->CtxFailure(errors::InvalidArgument("Missing set_operation."));
  } else {
    std::transform(set_operation_str.begin(), set_operation_str.end(),
                   set_operation_str.begin(), ::tolower);
    if ("a-b" == set_operation_str) {
      return A_MINUS_B;
    }
    if ("b-a" == set_operation_str) {
      return B_MINUS_A;
    }
    if ("intersection" == set_operation_str) {
      return INTERSECTION;
    }
    if ("union" != set_operation_str) {
      ctx->CtxFailure(errors::InvalidArgument("Invalid set_operation ",
                                              set_operation_str, "."));
    }
  }
  // NOTE: This is not the default, this function fails if no 'set_operation'
  // attribute is provided.
  return UNION;
}

// Abstract base class for performing set operations across the last dimension
// of 2 input tensors.
template <typename T>
class SetOperationOp : public OpKernel {
 public:
  SetOperationOp(OpKernelConstruction* ctx, InputTypes input_types)
      : OpKernel(ctx),
        set_operation_(SetOperationFromContext(ctx)),
        validate_indices_(ValidateIndicesFromContext(ctx)),
        input_types_(input_types) {}

  void Compute(OpKernelContext* ctx) override;

 private:
  void ApplySetOperation(const absl::flat_hash_set<T>& set1,
                         const absl::flat_hash_set<T>& set2,
                         absl::btree_set<T>* result) const;
  void ComputeDenseToDense(OpKernelContext* ctx) const;
  void ComputeDenseToSparse(OpKernelContext* ctx) const;
  void ComputeSparseToSparse(OpKernelContext* ctx) const;
  const SetOperation set_operation_;
  const bool validate_indices_;
  const InputTypes input_types_;
};

template <typename T>
void SetDifference(const absl::flat_hash_set<T>& set1,
                   const absl::flat_hash_set<T>& set2,
                   absl::btree_set<T>* result) {
  for (const T& elem : set1) {
    if (!set2.contains(elem)) result->insert(elem);
  }
}

template <typename T>
void SetIntersection(const absl::flat_hash_set<T>& set1,
                     const absl::flat_hash_set<T>& set2,
                     absl::btree_set<T>* result) {
  if (set1.size() <= set2.size()) {
    for (const T& elem : set1) {
      if (set2.contains(elem)) result->insert(elem);
    }
  } else {
    for (const T& elem : set2) {
      if (set1.contains(elem)) result->insert(elem);
    }
  }
}

template <typename T>
void SetUnion(const absl::flat_hash_set<T>& set1,
              const absl::flat_hash_set<T>& set2, absl::btree_set<T>* result) {
  result->insert(set1.begin(), set1.end());
  result->insert(set2.begin(), set2.end());
}

template <typename T>
void SetOperationOp<T>::ApplySetOperation(const absl::flat_hash_set<T>& set1,
                                          const absl::flat_hash_set<T>& set2,
                                          absl::btree_set<T>* result) const {
  switch (set_operation_) {
    case A_MINUS_B:
      SetDifference<T>(set1, set2, result);
      break;
    case B_MINUS_A:
      SetDifference<T>(set2, set1, result);
      break;
    case INTERSECTION:
      SetIntersection<T>(set1, set2, result);
      break;
    case UNION:
      SetUnion<T>(set1, set2, result);
      break;
  }
}

// Validate shapes have the same dimensions.
Status CheckShapesMatch(VarDimArray shape1, VarDimArray shape2) {
  if (shape1 != shape2) {
    return errors::InvalidArgument("Mismatched shapes [",
                                   absl::StrJoin(shape1, ","), "] vs [",
                                   absl::StrJoin(shape2, ","), "]");
  }
  return Status::OK();
}

// Validate ranks are the same, and all but last dimension are the same.
// Return GroupShape.
Status GroupShapeFromInputs(VarDimArray shape1, VarDimArray shape2,
                            ShapeArray* group_shape) {
  ShapeArray group_shape_1;
  TF_RETURN_IF_ERROR(GroupShape(shape1, &group_shape_1));
  ShapeArray group_shape_2;
  TF_RETURN_IF_ERROR(GroupShape(shape2, &group_shape_2));
  TF_RETURN_IF_ERROR(CheckShapesMatch(group_shape_1, group_shape_2));
  *group_shape = group_shape_1;
  return Status::OK();
}

// Split `flat_group_index` into separate dimensions based on `group_shape`.
void PopulateGroupIndices(const int64_t flat_group_index,
                          VarDimArray group_shape,
                          std::vector<int64_t>* group_indices) {
  group_indices->clear();
  int64_t running_flat_group_index = flat_group_index;
  for (int group_dim_index = group_shape.size() - 1; group_dim_index >= 0;
       --group_dim_index) {
    const auto group_dim = group_shape[group_dim_index];
    group_indices->insert(group_indices->begin(),
                          running_flat_group_index % group_dim);
    running_flat_group_index /= group_dim;
  }
}

ShapeArray TensorShapeToArray(const TensorShape& t) {
  ShapeArray vec(t.dims());
  for (int i = 0; i < t.dims(); ++i) vec[i] = t.dim_size(i);
  return vec;
}

// `ctx` contains set1 and set2 dense tensors.
// Iterate over groups in set1 and set2, applying `ApplySetOperation` to each,
// and outputting the result `SparseTensor`. A "group" is a collection of values
// with the same first n-1 dimensions in set1 and set2.
template <typename T>
void SetOperationOp<T>::ComputeDenseToDense(OpKernelContext* ctx) const {
  const Tensor& set1_t = ctx->input(0);
  const Tensor& set2_t = ctx->input(1);
  // The following should stay in sync with `_dense_to_dense_shape` shape
  // assertions in python/ops/set_ops.py, and `SetShapeFn` for
  // `DenseToDenseSetOperation` in ops/set_ops.cc.
  ShapeArray group_shape;
  const auto shape1 = TensorShapeToArray(set1_t.shape());
  const auto shape2 = TensorShapeToArray(set2_t.shape());
  OP_REQUIRES_OK(ctx, GroupShapeFromInputs(shape1, shape2, &group_shape));

  const auto set1_strides = Strides(shape1);
  const auto set2_strides = Strides(shape2);

  std::vector<std::pair<std::vector<int64_t>, absl::btree_set<T>>> group_sets;
  int64_t num_result_values = 0;
  int64_t max_set_size = 0;

  absl::flat_hash_set<T> set1_group_set;
  absl::flat_hash_set<T> set2_group_set;
  std::vector<int64_t> group_indices;
  int64_t num_elements;
  OP_REQUIRES_OK(ctx,
                 TensorShapeUtils::NumElements(group_shape, &num_elements));
  for (int64_t flat_group_index = 0; flat_group_index < num_elements;
       ++flat_group_index) {
    PopulateGroupIndices(flat_group_index, group_shape, &group_indices);
    PopulateFromDenseGroup<T>(ctx, set1_t, set1_strides, group_indices,
                              &set1_group_set);
    PopulateFromDenseGroup<T>(ctx, set2_t, set2_strides, group_indices,
                              &set2_group_set);

    absl::btree_set<T> group_set;
    ApplySetOperation(set1_group_set, set2_group_set, &group_set);
    if (!group_set.empty()) {
      const auto set_size = group_set.size();
      if (set_size > max_set_size) {
        max_set_size = set_size;
      }
      num_result_values += set_size;
      group_sets.push_back({group_indices, std::move(group_set)});
    }
  }

  TensorShape output_shape;
  OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(group_shape, &output_shape));
  output_shape.AddDim(max_set_size);
  OutputSparseTensor<T>(ctx, output_shape, num_result_values, group_sets);
}

// `ctx` contains dense set1 and sparse set2 tensors.
// Iterate over groups in set1 and set2, applying `ApplySetOperation` to each,
// and outputing the result `SparseTensor`. A "group" is a collection of values
// with the same first n-1 dimensions in set1 and set2.
template <typename T>
void SetOperationOp<T>::ComputeDenseToSparse(OpKernelContext* ctx) const {
  const Tensor& set1_t = ctx->input(0);
  sparse::SparseTensor set2_st;
  OP_REQUIRES_OK(ctx,
                 SparseTensorFromContext(ctx, 1, validate_indices_, &set2_st));
  // The following should stay in sync with `_dense_to_sparse_shape` shape
  // assertions in python/ops/set_ops.py, and `SetShapeFn` for
  // `DenseToSparseSetOperation` in ops/set_ops.cc.
  ShapeArray group_shape;
  OP_REQUIRES_OK(ctx, GroupShapeFromInputs(TensorShapeToArray(set1_t.shape()),
                                           set2_st.shape(), &group_shape));

  const ShapeArray set1_strides = Strides(TensorShapeToArray(set1_t.shape()));

  std::vector<std::pair<std::vector<int64_t>, absl::btree_set<T>>> group_sets;
  int64_t num_result_values = 0;
  int64_t max_set_size = 0;

  absl::flat_hash_set<T> set1_group_set;
  absl::flat_hash_set<T> set2_group_set;
  auto set2_grouper =
      set2_st.group(set2_st.order().subspan(0, set2_st.order().size() - 1));
  auto set2_group_it = set2_grouper.begin();
  std::vector<int64_t> group_indices;
  int64_t num_elements;
  OP_REQUIRES_OK(ctx,
                 TensorShapeUtils::NumElements(group_shape, &num_elements));
  for (int64_t flat_group_index = 0; flat_group_index < num_elements;
       ++flat_group_index) {
    PopulateGroupIndices(flat_group_index, group_shape, &group_indices);

    // Get values from set1.
    PopulateFromDenseGroup<T>(ctx, set1_t, set1_strides, group_indices,
                              &set1_group_set);

    // Get values from set2, if applicable.
    set2_group_set.clear();
    if (set2_group_it != set2_grouper.end()) {
      const auto& group = *set2_group_it;
      const auto set2_group_indices = group.group();
      OP_REQUIRES(
          ctx, set2_group_indices.size() == group_indices.size(),
          errors::InvalidArgument("Invalid number of group indices ",
                                  set2_group_indices.size(), ", expected ",
                                  group_indices.size(), "."));
      bool group_match = true;
      for (int32_t i = 0; group_match && (i < set2_group_indices.size()); ++i) {
        if (set2_group_indices[i] != group_indices[i]) {
          group_match = false;
        }
      }
      if (group_match) {
        PopulateFromSparseGroup<T>(ctx, group, set2_st.shape(),
                                   &set2_group_set);
        ++set2_group_it;
      }
    }

    absl::btree_set<T> group_set;
    ApplySetOperation(set1_group_set, set2_group_set, &group_set);
    if (!group_set.empty()) {
      const auto set_size = group_set.size();
      if (set_size > max_set_size) {
        max_set_size = set_size;
      }
      num_result_values += set_size;
      group_sets.push_back({group_indices, std::move(group_set)});
    }
  }

  TensorShape output_shape;
  OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(group_shape, &output_shape));
  output_shape.AddDim(max_set_size);
  OutputSparseTensor<T>(ctx, output_shape, num_result_values, group_sets);
}

// This is used to determine which group iterator is less than the other, based
// on row-major ordering of indices.
// An empty index list indicates end of iteration, which is interpreted as "max"
// for the purposes of comparison; i.e., non-empty < empty.
// Return 0 if both groups are empty, or both non-empty with the same values.
// Return <0 if set1 <= set2, or set2 is empty.
// Return >0 if set2 <= set1, or set1 is empty.
void CompareGroups(OpKernelContext* ctx,
                   const std::vector<int64_t>& set1_group_indices,
                   const std::vector<int64_t>& set2_group_indices,
                   int64_t* result) {
  if (set1_group_indices.empty()) {
    *result = set2_group_indices.empty() ? 0 : 1;
    return;
  }
  if (set2_group_indices.empty()) {
    *result = set1_group_indices.empty() ? 0 : -1;
    return;
  }
  OP_REQUIRES(ctx, set1_group_indices.size() == set2_group_indices.size(),
              errors::InvalidArgument("Mismatched group dims ",
                                      set1_group_indices.size(), " vs ",
                                      set2_group_indices.size(), "."));
  for (int32_t i = 0; i < set1_group_indices.size(); ++i) {
    *result = set1_group_indices[i] - set2_group_indices[i];
    if (*result != 0) {
      return;
    }
  }
}

// `ctx` contains set1 and set2 sparse tensors.
// Iterate over groups in set1 and set2, applying `ApplySetOperation` to each,
// and outputing the result `SparseTensor`. A "group" is a collection of values
// with the same first n-1 dimensions in set1 and set2.
template <typename T>
void SetOperationOp<T>::ComputeSparseToSparse(OpKernelContext* ctx) const {
  sparse::SparseTensor set1_st;
  OP_REQUIRES_OK(ctx,
                 SparseTensorFromContext(ctx, 0, validate_indices_, &set1_st));

  sparse::SparseTensor set2_st;
  OP_REQUIRES_OK(ctx,
                 SparseTensorFromContext(ctx, 3, validate_indices_, &set2_st));

  // The following should stay in sync with `_sparse_to_sparse_shape` shape
  // assertions in python/ops/set_ops.py, and `SetShapeFn` for
  // `SparseToSparseSetOperation` in ops/set_ops.cc.
  ShapeArray group_shape;
  OP_REQUIRES_OK(ctx, GroupShapeFromInputs(set1_st.shape(), set2_st.shape(),
                                           &group_shape));

  std::vector<std::pair<std::vector<int64_t>, absl::btree_set<T>>> group_sets;
  int64_t num_result_values = 0;
  int64_t max_set_size = 0;

  absl::flat_hash_set<T> set1_group_set;
  absl::flat_hash_set<T> set2_group_set;
  auto set1_grouper =
      set1_st.group(set1_st.order().subspan(0, set1_st.order().size() - 1));
  auto set1_group_it = set1_grouper.begin();
  auto set2_grouper =
      set2_st.group(set2_st.order().subspan(0, set2_st.order().size() - 1));
  auto set2_group_it = set2_grouper.begin();

  // Empty indices vector represents iteration end in `CompareGroups`.
  const std::vector<int64_t> group_iter_end;
  // Group by rows, and iterate over rows of both sets in parallel, creating a
  // set for each row.
  while ((set1_group_it != set1_grouper.end()) ||
         (set2_group_it != set2_grouper.end())) {
    const std::vector<int64_t>& set1_group_indices =
        (set1_group_it == set1_grouper.end()) ? group_iter_end
                                              : (*set1_group_it).group();
    const std::vector<int64_t>& set2_group_indices =
        (set2_group_it == set2_grouper.end()) ? group_iter_end
                                              : (*set2_group_it).group();

    int64_t compare_groups;
    CompareGroups(ctx, set1_group_indices, set2_group_indices, &compare_groups);
    const std::vector<int64_t>* group_indices = nullptr;

    // Get values from set1, if applicable.
    set1_group_set.clear();
    if (compare_groups <= 0) {
      PopulateFromSparseGroup<T>(ctx, *set1_group_it, set1_st.shape(),
                                 &set1_group_set);
      ++set1_group_it;
      group_indices = &set1_group_indices;
    }

    // Get values from set2, if applicable.
    set2_group_set.clear();
    if (compare_groups >= 0) {
      PopulateFromSparseGroup<T>(ctx, *set2_group_it, set2_st.shape(),
                                 &set2_group_set);
      ++set2_group_it;
      group_indices = &set2_group_indices;
    }

    absl::btree_set<T> group_set;
    ApplySetOperation(set1_group_set, set2_group_set, &group_set);
    if (!group_set.empty()) {
      const auto set_size = group_set.size();
      if (set_size > max_set_size) {
        max_set_size = set_size;
      }
      num_result_values += set_size;
      group_sets.push_back({*group_indices, std::move(group_set)});
    }
  }

  TensorShape output_shape;
  OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(group_shape, &output_shape));
  output_shape.AddDim(max_set_size);
  OutputSparseTensor<T>(ctx, output_shape, num_result_values, group_sets);
}

// Given set1 of shape [b, n1] and data_2 of shape [b, n2], populate result
// sparse tensor with [b, n3] values, where each row `i` contains the result of
// the set operation on elements from set1[i] and set2[i]. `n3` is the number
// of elements in that result row.
template <typename T>
void SetOperationOp<T>::Compute(OpKernelContext* ctx) {
  switch (input_types_) {
    case DENSE_DENSE:
      ComputeDenseToDense(ctx);
      break;
    case DENSE_SPARSE:
      ComputeDenseToSparse(ctx);
      break;
    case SPARSE_SPARSE:
      ComputeSparseToSparse(ctx);
      break;
  }
}

template <typename T>
class DenseToDenseSetOperationOp : public SetOperationOp<T> {
 public:
  explicit DenseToDenseSetOperationOp(OpKernelConstruction* ctx)
      : SetOperationOp<T>(ctx, DENSE_DENSE) {}
};

#define _DENSE_TO_DENSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(T) \
  REGISTER_KERNEL_BUILDER(Name("DenseToDenseSetOperation")       \
                              .Device(DEVICE_CPU)                \
                              .TypeConstraint<T>("T"),           \
                          DenseToDenseSetOperationOp<T>);
_DENSE_TO_DENSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(int8);
_DENSE_TO_DENSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(int16);
_DENSE_TO_DENSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(int32);
_DENSE_TO_DENSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(int64_t);
_DENSE_TO_DENSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(uint8);
_DENSE_TO_DENSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(uint16);
_DENSE_TO_DENSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(tstring);
#undef _DENSE_TO_DENSE_SET_OPERATION_REGISTER_KERNEL_BUILDER

template <typename T>
class DenseToSparseSetOperationOp : public SetOperationOp<T> {
 public:
  explicit DenseToSparseSetOperationOp(OpKernelConstruction* ctx)
      : SetOperationOp<T>(ctx, DENSE_SPARSE) {}
};

#define _DENSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(T) \
  REGISTER_KERNEL_BUILDER(Name("DenseToSparseSetOperation")       \
                              .Device(DEVICE_CPU)                 \
                              .TypeConstraint<T>("T"),            \
                          DenseToSparseSetOperationOp<T>);
_DENSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(int8);
_DENSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(int16);
_DENSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(int32);
_DENSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(int64_t);
_DENSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(uint8);
_DENSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(uint16);
_DENSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(tstring);
#undef _DENSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER

template <typename T>
class SparseToSparseSetOperationOp : public SetOperationOp<T> {
 public:
  explicit SparseToSparseSetOperationOp(OpKernelConstruction* ctx)
      : SetOperationOp<T>(ctx, SPARSE_SPARSE) {}
};

#define _SPARSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(T) \
  REGISTER_KERNEL_BUILDER(Name("SparseToSparseSetOperation")       \
                              .Device(DEVICE_CPU)                  \
                              .TypeConstraint<T>("T"),             \
                          SparseToSparseSetOperationOp<T>);
_SPARSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(int8);
_SPARSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(int16);
_SPARSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(int32);
_SPARSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(int64_t);
_SPARSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(uint8);
_SPARSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(uint16);
_SPARSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER(tstring);
#undef _SPARSE_TO_SPARSE_SET_OPERATION_REGISTER_KERNEL_BUILDER

}  // namespace tensorflow


text:
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                Toggle navigation

            </button>
            Project name

Home

About

Contact

            <form ng-controller="calendarController as calendar" class="navbar-form navbar-right" role="form">

                    <select ng-model="produtor.id" class="form-control">
                        <option ng-repeat="value in produtor.produtores" value="{{value.id}}">
                            {{value.nome}}
                        </option>
                    </select>
                    <button type="button" ng-click="calendar.getData(produtor)" class="btn btn-default btn-sm">Selecionar</button>

            </form>

redpajama_set_name: RedPajamaGithub


text:
#include "environment.h"

namespace rocksample {

using namespace std;

// Environment

Environment::Environment(int num_locs, int num_rocks, const vector<int> &rock_locs) : num_locs_(num_locs), num_rocks_(num_rocks), rock_locs_(rock_locs) {}

int Environment::GetNumLocs() const {
  return num_locs_;
}

int Environment::GetNumRocks() const {
  return num_rocks_;
}

const std::vector<int>& Environment::GetRockLocs() const {
  return rock_locs_;
}

int Environment::GetRockX(int rock) const {
  return rock_locs_[rock * 2];
}

int Environment::GetRockY(int rock) const {
  return rock_locs_[(rock * 2) + 1];
}

// returns rock number if there is a rock at this location, otherwise -1
int Environment::GetRock(int x, int y) const {
  for (int rock = 0; rock < num_rocks_; ++rock) {
    if ((rock_locs_[rock * 2] == x) && (rock_locs_[(rock * 2) + 1] == y)) {
      return rock;
    }
  }
  return -1;
}

} // namespace rocksample


text:
from __future__ import (
    absolute_import, division, print_function, unicode_literals)

import googleapiclient.discovery

from . import schema

SHEETS_API_DISCOVERY_URL = (
    'https://sheets.googleapis.com/$discovery/rest?version=v4')

class API(object):

    def __init__(self, http, discovery):
        if discovery:
            self.sheets = googleapiclient.discovery.build(
                'sheets', 'v4', http=http,
                discoveryServiceUrl=SHEETS_API_DISCOVERY_URL)
            self.drive = googleapiclient.discovery.build(
                'drive', 'v2', http=http)
        else:
            self.sheets = googleapiclient.discovery.build_from_document(
                schema.SHEETS_V4, http=http)
            self.drive = googleapiclient.discovery.build_from_document(
                schema.DRIVE_V2, http=http)


text:
from msrest.pipeline import ClientRawResponse
from .. import models

class SpellCheckClientOperationsMixin(object):

    def spell_checker(
            self, text, accept_language=None, pragma=None, user_agent=None, client_id=None, client_ip=None, location=None, action_type=None, app_name=None, country_code=None, client_machine_name=None, doc_id=None, market=None, session_id=None, set_lang=None, user_id=None, mode=None, pre_context_text=None, post_context_text=None, custom_headers=None, raw=False, **operation_config):
        """The Bing Spell Check API lets you perform contextual grammar and spell
        checking. Bing has developed a web-based spell-checker that leverages
        machine learning and statistical machine translation to dynamically
        train a constantly evolving and highly contextual algorithm. The
        spell-checker is based on a massive corpus of web searches and
        documents.

        :param text: The text string to check for spelling and grammar errors.
         The combined length of the text string, preContextText string, and
         postContextText string may not exceed 10,000 characters. You may
         specify this parameter in the query string of a GET request or in the
         body of a POST request. Because of the query string length limit,
         you'll typically use a POST request unless you're checking only short
         strings.
        :type text: str
        :param accept_language: A comma-delimited list of one or more
         languages to use for user interface strings. The list is in decreasing
         order of preference. For additional information, including expected
         format, see
         [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
         This header and the setLang query parameter are mutually exclusive; do
         not specify both. If you set this header, you must also specify the cc
         query parameter. Bing will use the first supported language it finds
         from the list, and combine that language with the cc parameter value
         to determine the market to return results for. If the list does not
         include a supported language, Bing will find the closest language and
         market that supports the request, and may use an aggregated or default
         market for the results instead of a specified one. You should use this
         header and the cc query parameter only if you specify multiple
         languages; otherwise, you should use the mkt and setLang query
         parameters. A user interface string is a string that's used as a label
         in a user interface. There are very few user interface strings in the
         JSON response objects. Any links in the response objects to Bing.com
         properties will apply the specified language.
        :type accept_language: str
        :param pragma: By default, Bing returns cached content, if available.
         To prevent Bing from returning cached content, set the Pragma header
         to no-cache (for example, Pragma: no-cache).
        :type pragma: str
        :param user_agent: The user agent originating the request. Bing uses
         the user agent to provide mobile users with an optimized experience.
         Although optional, you are strongly encouraged to always specify this
         header. The user-agent should be the same string that any commonly
         used browser would send. For information about user agents, see [RFC
         2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
        :type user_agent: str
        :param client_id: Bing uses this header to provide users with
         consistent behavior across Bing API calls. Bing often flights new
         features and improvements, and it uses the client ID as a key for
         assigning traffic on different flights. If you do not use the same
         client ID for a user across multiple requests, then Bing may assign
         the user to multiple conflicting flights. Being assigned to multiple
         conflicting flights can lead to an inconsistent user experience. For
         example, if the second request has a different flight assignment than
         the first, the experience may be unexpected. Also, Bing can use the
         client ID to tailor web results to that client ID's search history,
         providing a richer experience for the user. Bing also uses this header
         to help improve result rankings by analyzing the activity generated by
         a client ID. The relevance improvements help with better quality of
         results delivered by Bing APIs and in turn enables higher
         click-through rates for the API consumer. IMPORTANT: Although
         optional, you should consider this header required. Persisting the
         client ID across multiple requests for the same end user and device
         combination enables 1) the API consumer to receive a consistent user
         experience, and 2) higher click-through rates via better quality of
         results from the Bing APIs. Each user that uses your application on
         the device must have a unique, Bing generated client ID. If you do not
         include this header in the request, Bing generates an ID and returns
         it in the X-MSEdge-ClientID response header. The only time that you
         should NOT include this header in a request is the first time the user
         uses your app on that device. Use the client ID for each Bing API
         request that your app makes for this user on the device. Persist the
         client ID. To persist the ID in a browser app, use a persistent HTTP
         cookie to ensure the ID is used across all sessions. Do not use a
         session cookie. For other apps such as mobile apps, use the device's
         persistent storage to persist the ID. The next time the user uses your
         app on that device, get the client ID that you persisted. Bing
         responses may or may not include this header. If the response includes
         this header, capture the client ID and use it for all subsequent Bing
         requests for the user on that device. If you include the
         X-MSEdge-ClientID, you must not include cookies in the request.
        :type client_id: str
        :param client_ip: The IPv4 or IPv6 address of the client device. The
         IP address is used to discover the user's location. Bing uses the
         location information to determine safe search behavior. Although
         optional, you are encouraged to always specify this header and the
         X-Search-Location header. Do not obfuscate the address (for example,
         by changing the last octet to 0). Obfuscating the address results in
         the location not being anywhere near the device's actual location,
         which may result in Bing serving erroneous results.
        :type client_ip: str
        :param location: A semicolon-delimited list of key/value pairs that
         describe the client's geographical location. Bing uses the location
         information to determine safe search behavior and to return relevant
         local content. Specify the key/value pair as <key>:<value>. The
         following are the keys that you use to specify the user's location.
         lat (required): The latitude of the client's location, in degrees. The
         latitude must be greater than or equal to -90.0 and less than or equal
         to +90.0. Negative values indicate southern latitudes and positive
         values indicate northern latitudes. long (required): The longitude of
         the client's location, in degrees. The longitude must be greater than
         or equal to -180.0 and less than or equal to +180.0. Negative values
         indicate western longitudes and positive values indicate eastern
         longitudes. re (required): The radius, in meters, which specifies the
         horizontal accuracy of the coordinates. Pass the value returned by the
         device's location service. Typical values might be 22m for GPS/Wi-Fi,
         380m for cell tower triangulation, and 18,000m for reverse IP lookup.
         ts (optional): The UTC UNIX timestamp of when the client was at the
         location. (The UNIX timestamp is the number of seconds since January
         1, 1970.) head (optional): The client's relative heading or direction
         of travel. Specify the direction of travel as degrees from 0 through
         360, counting clockwise relative to true north. Specify this key only
         if the sp key is nonzero. sp (optional): The horizontal velocity
         (speed), in meters per second, that the client device is traveling.
         alt (optional): The altitude of the client device, in meters. are
         (optional): The radius, in meters, that specifies the vertical
         accuracy of the coordinates. Specify this key only if you specify the
         alt key. Although many of the keys are optional, the more information
         that you provide, the more accurate the location results are. Although
         optional, you are encouraged to always specify the user's geographical
         location. Providing the location is especially important if the
         client's IP address does not accurately reflect the user's physical
         location (for example, if the client uses VPN). For optimal results,
         you should include this header and the  X-Search-ClientIP header, but
         at a minimum, you should include this header.
        :type location: str
        :param action_type: A string that's used by logging to determine
         whether the request is coming from an interactive session or a page
         load. The following are the possible values. 1) Edit—The request is
         from an interactive session 2) Load—The request is from a page load.
         Possible values include: 'Edit', 'Load'
        :type action_type: str or
         ~azure.cognitiveservices.language.spellcheck.models.ActionType
        :param app_name: The unique name of your app. The name must be known
         by Bing. Do not include this parameter unless you have previously
         contacted Bing to get a unique app name. To get a unique name, contact
         your Bing Business Development manager.
        :type app_name: str
        :param country_code: A 2-character country code of the country where
         the results come from. This API supports only the United States
         market. If you specify this query parameter, it must be set to us. If
         you set this parameter, you must also specify the Accept-Language
         header. Bing uses the first supported language it finds from the
         languages list, and combine that language with the country code that
         you specify to determine the market to return results for. If the
         languages list does not include a supported language, Bing finds the
         closest language and market that supports the request, or it may use
         an aggregated or default market for the results instead of a specified
         one. You should use this query parameter and the Accept-Language query
         parameter only if you specify multiple languages; otherwise, you
         should use the mkt and setLang query parameters. This parameter and
         the mkt query parameter are mutually exclusive—do not specify both.
        :type country_code: str
        :param client_machine_name: A unique name of the device that the
         request is being made from. Generate a unique value for each device
         (the value is unimportant). The service uses the ID to help debug
         issues and improve the quality of corrections.
        :type client_machine_name: str
        :param doc_id: A unique ID that identifies the document that the text
         belongs to. Generate a unique value for each document (the value is
         unimportant). The service uses the ID to help debug issues and improve
         the quality of corrections.
        :type doc_id: str
        :param market: The market where the results come from. You are
         strongly encouraged to always specify the market, if known. Specifying
         the market helps Bing route the request and return an appropriate and
         optimal response. This parameter and the cc query parameter are
         mutually exclusive—do not specify both.
        :type market: str
        :param session_id: A unique ID that identifies this user session.
         Generate a unique value for each user session (the value is
         unimportant). The service uses the ID to help debug issues and improve
         the quality of corrections
        :type session_id: str
        :param set_lang: The language to use for user interface strings.
         Specify the language using the ISO 639-1 2-letter language code. For
         example, the language code for English is EN. The default is EN
         (English). Although optional, you should always specify the language.
         Typically, you set setLang to the same language specified by mkt
         unless the user wants the user interface strings displayed in a
         different language. This parameter and the Accept-Language header are
         mutually exclusive—do not specify both. A user interface string is a
         string that's used as a label in a user interface. There are few user
         interface strings in the JSON response objects. Also, any links to
         Bing.com properties in the response objects apply the specified
         language.
        :type set_lang: str
        :param user_id: A unique ID that identifies the user. Generate a
         unique value for each user (the value is unimportant). The service
         uses the ID to help debug issues and improve the quality of
         corrections.
        :type user_id: str
        :param mode: The type of spelling and grammar checks to perform. The
         following are the possible values (the values are case insensitive).
         The default is Proof. 1) Proof—Finds most spelling and grammar
         mistakes. 2) Spell—Finds most spelling mistakes but does not find some
         of the grammar errors that Proof catches (for example, capitalization
         and repeated words). Possible values include: 'proof', 'spell'
        :type mode: str or
         ~azure.cognitiveservices.language.spellcheck.models.Mode
        :param pre_context_text: A string that gives context to the text
         string. For example, the text string petal is valid. However, if you
         set preContextText to bike, the context changes and the text string
         becomes not valid. In this case, the API suggests that you change
         petal to pedal (as in bike pedal). This text is not checked for
         grammar or spelling errors. The combined length of the text string,
         preContextText string, and postContextText string may not exceed
         10,000 characters. You may specify this parameter in the query string
         of a GET request or in the body of a POST request.
        :type pre_context_text: str
        :param post_context_text: A string that gives context to the text
         string. For example, the text string read is valid. However, if you
         set postContextText to carpet, the context changes and the text string
         becomes not valid. In this case, the API suggests that you change read
         to red (as in red carpet). This text is not checked for grammar or
         spelling errors. The combined length of the text string,
         preContextText string, and postContextText string may not exceed
         10,000 characters. You may specify this parameter in the query string
         of a GET request or in the body of a POST request.
        :type post_context_text: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: SpellCheck or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.language.spellcheck.models.SpellCheck
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.language.spellcheck.models.ErrorResponseException>`
        """
        x_bing_apis_sdk = "true"

        # Construct URL
        url = self.spell_checker.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if action_type is not None:
            query_parameters['ActionType'] = self._serialize.query("action_type", action_type, 'str')
        if app_name is not None:
            query_parameters['AppName'] = self._serialize.query("app_name", app_name, 'str')
        if country_code is not None:
            query_parameters['cc'] = self._serialize.query("country_code", country_code, 'str')
        if client_machine_name is not None:
            query_parameters['ClientMachineName'] = self._serialize.query("client_machine_name", client_machine_name, 'str')
        if doc_id is not None:
            query_parameters['DocId'] = self._serialize.query("doc_id", doc_id, 'str')
        if market is not None:
            query_parameters['mkt'] = self._serialize.query("market", market, 'str')
        if session_id is not None:
            query_parameters['SessionId'] = self._serialize.query("session_id", session_id, 'str')
        if set_lang is not None:
            query_parameters['SetLang'] = self._serialize.query("set_lang", set_lang, 'str')
        if user_id is not None:
            query_parameters['UserId'] = self._serialize.query("user_id", user_id, 'str')
        if mode is not None:
            query_parameters['Mode'] = self._serialize.query("mode", mode, 'str')
        if pre_context_text is not None:
            query_parameters['PreContextText'] = self._serialize.query("pre_context_text", pre_context_text, 'str')
        if post_context_text is not None:
            query_parameters['PostContextText'] = self._serialize.query("post_context_text", post_context_text, 'str')
        query_parameters['Text'] = self._serialize.query("text", text, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)
        header_parameters['X-BingApis-SDK'] = self._serialize.header("x_bing_apis_sdk", x_bing_apis_sdk, 'str')
        if accept_language is not None:
            header_parameters['Accept-Language'] = self._serialize.header("accept_language", accept_language, 'str')
        if pragma is not None:
            header_parameters['Pragma'] = self._serialize.header("pragma", pragma, 'str')
        if user_agent is not None:
            header_parameters['User-Agent'] = self._serialize.header("user_agent", user_agent, 'str')
        if client_id is not None:
            header_parameters['X-MSEdge-ClientID'] = self._serialize.header("client_id", client_id, 'str')
        if client_ip is not None:
            header_parameters['X-MSEdge-ClientIP'] = self._serialize.header("client_ip", client_ip, 'str')
        if location is not None:
            header_parameters['X-Search-Location'] = self._serialize.header("location", location, 'str')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None
        if response.status_code == 200:
            deserialized = self._deserialize('SpellCheck', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    spell_checker.metadata = {'url': '/spellcheck'}


text:
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
   <extension
         point="com.b2international.snowowl.core.bootstrapFragments">
      <bootstrapFragment
            class="com.b2international.snowowl.identity.IdentityBootstrap">
      </bootstrapFragment>
   </extension>

</plugin>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Blender
{
	/// <summary>
	/// This class contains a pair of value and its type, and access methods to value.
	/// </summary>
	/// <remarks>
	/// The implementation of each access method is provided by sub class which is defined by IBlendType.
	/// </remarks>
	public class BlendValueCapsule
	{
		#region properties

		private IBlendType m_type;
		public IBlendType Type
		{
			get
			{
				return m_type;
			}

		}

		#endregion // properties

		public BlendValueCapsule(IBlendType type, object value)
		{
			m_type = type;
			m_rawValue = value;
		}

		virtual public BlendValueCapsule GetAt(int index)
		{
			throw new BlenderException("BlendValue.GetAt() is not implemented");
		}

		virtual public BlendValueCapsule GetAt(int index1, int index2)
		{
			throw new BlenderException("BlendValue.GetAt() is not implemented");
		}

		virtual public BlendValueCapsule GetMember(string name)
		{
			throw new BlenderException("BlendValue.GetMember() is not implemented");
		}

		virtual public IEnumerable<object> GetAllValue()
		{
			yield return m_rawValue;
		}

		public string GetAllValueAsString()
		{
			return (string)GetAllValue().First();
		}

		public Type GetRawValue<Type>()
		{
			return (Type)m_rawValue;
		}

		public object GetRawValue()
		{
			return m_rawValue;
		}

		#region properties

		private object m_rawValue;

		#endregion // prorperties
	}
}


text: var regex = /\p{Script_Extensions=Wancho}/u;


text:
//
//  RunEverywhereXcodePlugin.m
//  RunEverywhereXcodePlugin
//
//  Created by Eric Mika on 3/19/14.
//  Copyright (c) 2014 Kitschpatrol. All rights reserved.
//

#import "KPRunEverywhereXcodePlugin.h"

static KPRunEverywhereXcodePlugin *sharedPlugin;

@interface KPRunEverywhereXcodePlugin ()

@property (nonatomic, strong) NSBundle *bundle;

@property (nonatomic, strong) NSString *initiallySelectedDestinationTitle;
@property (nonatomic, strong) NSMutableArray *destinationTitlesToBuild;

// Guards prevent multiple builds on redundant notifications
@property (nonatomic) BOOL waitingForBuild;
@property (nonatomic) BOOL waitingForRun;
@property (nonatomic) BOOL waitingForStop;

@end

@implementation KPRunEverywhereXcodePlugin

+ (void)pluginDidLoad:(NSBundle *)plugin {
  static id sharedPlugin = nil;
  static dispatch_once_t onceToken;
  NSString *currentApplicationName = [[NSBundle mainBundle] infoDictionary][@"CFBundleName"];
  if ([currentApplicationName isEqual:@"Xcode"]) {
    dispatch_once(&onceToken, ^{
      sharedPlugin = [[self alloc] initWithBundle:plugin];
    });
  }
}

- (id)initWithBundle:(NSBundle *)plugin {
  if (self = [super init]) {
    // Reference to plugin's bundle, for resource acccess
    self.bundle = plugin;

    _waitingForBuild = NO;
    _waitingForRun = NO;
    _waitingForStop = NO;
    _destinationTitlesToBuild = nil;

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationDidFinishLaunching:)
                                                 name:NSApplicationDidFinishLaunchingNotification
                                               object:nil];

    // Watch notifications
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationListener:) name:nil object:nil];
  }
  return self;
}

- (void)applicationDidFinishLaunching:(NSNotification *)notification {
  // Set up menu items
  NSMenuItem *productMenuItem = [[NSApp mainMenu] itemWithTitle:@"Product"];
  if (productMenuItem) {
    // Run everywhere item
    NSMenuItem *runEverywhereMenuItem = [[NSMenuItem alloc] initWithTitle:@"Run Everywhere" action:@selector(doRunEverywhereMenuAction) keyEquivalent:@"r"];
    [runEverywhereMenuItem setKeyEquivalentModifierMask:NSCommandKeyMask | NSControlKeyMask | NSAlternateKeyMask];
    [runEverywhereMenuItem setAlternate:NO];
    [runEverywhereMenuItem setTarget:self];

    // Add it to the product menu
    NSInteger runMenuItemIndex = [[productMenuItem submenu] indexOfItemWithTitle:@"Run"];
    [[productMenuItem submenu] insertItem:runEverywhereMenuItem atIndex:runMenuItemIndex + 2]; // Deal with hidden alternate "Run..." menu item.

    // Stop everywhere item
    NSMenuItem *stopEverywhereMenuItem = [[NSMenuItem alloc] initWithTitle:@"Stop Everywhere" action:@selector(doStopEverywhereMenuAction) keyEquivalent:@"."];
    [stopEverywhereMenuItem setKeyEquivalentModifierMask:NSCommandKeyMask | NSControlKeyMask | NSAlternateKeyMask];
    [stopEverywhereMenuItem setAlternate:NO];
    [stopEverywhereMenuItem setTarget:self];

    // Add it to the product menu
    NSInteger stopMenuItemIndex = [[productMenuItem submenu] indexOfItemWithTitle:@"Stop"];
    [[productMenuItem submenu] insertItem:stopEverywhereMenuItem atIndex:stopMenuItemIndex + 1];
  }

  [[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationDidFinishLaunchingNotification object:nil];
}

- (void)notificationListener:(NSNotification *)notification {
  /*
   // Log notifications if you like
   if ([[notification name] length] >= 2 && ([[[notification name] substringWithRange:NSMakeRange(0, 2)] isEqualTo:@"NS"] || [[[notification name]
   substringWithRange:NSMakeRange(0, 2)] isEqualTo:@"_N"])) {
   // It's a system-level notification
   }
   else {
   // It's a Xcode-level notification
   NSLog(@"%@", notification.name);
   }
   */

  // This seems like quite a mess, but the notification-driven approach avoids waiting for
  // indeterminate amounts of time for building / running to get far enough along to avoid crashes.

  // Finished building
  if ([[notification name] isEqualToString:@"IDEBuildOperationDidGenerateOutputFilesNotification"]) {
    if (self.waitingForBuild) {
      self.waitingForBuild = NO;
      [self runSelected];

      // Clean up if it's the end of the list
      if (self.destinationTitlesToBuild.count == 0) {
        self.destinationTitlesToBuild = nil;
        self.waitingForBuild = NO;
        self.waitingForRun = NO;
        [self performActionForMenuItemWithTitle:self.initiallySelectedDestinationTitle];
      }
    }
  }

  // Finished launching
  if ([[notification name] isEqualToString:@"DVTDeviceShouldIgnoreChangesDidEndNotification"]) {
    if (self.waitingForRun) {
      self.waitingForRun = NO;
      [self buildNextDestination];
    }
  }

  // Finished stopping
  if ([[notification name] isEqualToString:@"CurrentExecutionTrackerCompletedNotification"]) {
    if (self.waitingForStop) {
      // Keep stopping
      self.waitingForStop = NO;
      [self doStopEverywhereMenuAction];
    }
  }
}

#pragma mark - Menu Callbacks

- (void)doStopEverywhereMenuAction {
  [self updateMenus];
  self.waitingForStop = NO;

  NSMenuItem *productMenuItem = [[NSApp mainMenu] itemWithTitle:@"Product"];
  NSMenuItem *stopMenuItem = [[productMenuItem submenu] itemWithTitle:@"Stop"];
  [[productMenuItem submenu] update];

  if ([stopMenuItem isEnabled]) {
    self.waitingForStop = YES;
    [self performActionForMenuItem:stopMenuItem];
  }
}

// Sample Action, for menu item:
- (void)doRunEverywhereMenuAction {
  self.waitingForBuild = NO;
  self.waitingForRun = NO;

  self.destinationTitlesToBuild = [NSMutableArray arrayWithArray:[self getDestinationMenuItemTitles]];

  // TODO stop everything
  // Save initially selected item
  self.initiallySelectedDestinationTitle = nil;
  for (NSString *destinationTitle in self.destinationTitlesToBuild) {
    NSMenuItem *destinationMenuItem = [self getDestinationMenuByTitle:destinationTitle];
    if (destinationMenuItem.state == NSOnState) {
      self.initiallySelectedDestinationTitle = destinationMenuItem.title;
      break;
    }
  }

  [self buildNextDestination];
  // Notifications kick off the rest
}

#pragma mark - Logic

- (void)buildNextDestination {
  if (self.destinationTitlesToBuild) {
    if (self.destinationTitlesToBuild.count > 0) {
      // Run next
      NSString *destinationToBuildTitle = [self.destinationTitlesToBuild lastObject];
      [self.destinationTitlesToBuild removeLastObject];

      // Select destination
      [self performActionForMenuItemWithTitle:destinationToBuildTitle];
      [self buildSelected];
    }
  }
}

- (void)buildSelected {
  self.waitingForBuild = YES;
  NSMenuItem *buildMenuItem;
  NSMenuItem *productMenuItem = [[NSApp mainMenu] itemWithTitle:@"Product"];
  if ([productMenuItem hasSubmenu]) {
    buildMenuItem = [[productMenuItem submenu] itemWithTitle:@"Build"];
  }

  [self performActionForMenuItem:buildMenuItem];
}

- (void)runSelected {
  self.waitingForRun = YES;
  // Run it
  NSMenuItem *runMenuItem;
  NSMenuItem *productMenuItem = [[NSApp mainMenu] itemWithTitle:@"Product"];
  if ([productMenuItem hasSubmenu]) {
    runMenuItem = [[productMenuItem submenu] itemWithTitle:@"Run"];
  }
  [self performActionForMenuItem:runMenuItem];
}

- (void)performActionForMenuItemWithTitle:(NSString *)title {
  // Run UI stuff on the main thread
  dispatch_async(dispatch_get_main_queue(), ^{
    [self updateMenus];
    @try {
        NSMenuItem *menuItem = [self getDestinationMenuByTitle:title];
        [[menuItem menu] performActionForItemAtIndex:[[menuItem menu] indexOfItem:menuItem]];
    }
    @catch (NSException *exception) {

    }
  });
}

- (void)performActionForMenuItem:(NSMenuItem *)menuItem {
  // Run UI stuff on the main thread
  dispatch_async(dispatch_get_main_queue(), ^{
    [[menuItem menu] performActionForItemAtIndex:[[menuItem menu] indexOfItem:menuItem]];
  });
}

#pragma mark - Helpers

- (NSMenuItem *)getDestinationMenuByTitle:(NSString *)title {
  NSMenuItem *productMenuItem = [[NSApp mainMenu] itemWithTitle:@"Product"];
  if ([productMenuItem hasSubmenu]) {
    NSMenuItem *destinationMenuItem = [[productMenuItem submenu] itemWithTitle:@"Destination"];
    if ([destinationMenuItem hasSubmenu]) {
      return [[destinationMenuItem submenu] itemWithTitle:title];
    }
  }
  return nil;
}

- (void)updateMenus {
  // According to dtrace the destinations list is generated lazily when the menu is opened
  // This ensures the list is populated before we scan for destinations
  [[[NSApp mainMenu] delegate] menuNeedsUpdate:[NSApp mainMenu]];

  NSMenuItem *productMenuItem = [[NSApp mainMenu] itemWithTitle:@"Product"];
  // NSMenu *productMenu = [productMenuItem submenu];
  //[[productMenu delegate] menuNeedsUpdate:productMenu];

  if ([productMenuItem hasSubmenu]) {
    NSMenuItem *destinationMenuItem = [[productMenuItem submenu] itemWithTitle:@"Destination"];
    if ([destinationMenuItem hasSubmenu]) {
      NSMenu *destinationMenu = [destinationMenuItem submenu];
      [[destinationMenu delegate] menuNeedsUpdate:destinationMenu];
    }
  }
}

- (NSArray *)getDestinationMenuItemTitles {
  // Fish out the destination menu items
  NSMutableArray *destinationItems = [NSMutableArray array];

  [self updateMenus];

  NSMenuItem *productMenuItem = [[NSApp mainMenu] itemWithTitle:@"Product"];

  if ([productMenuItem hasSubmenu]) {
    NSMenuItem *destinationMenuItem = [[productMenuItem submenu] itemWithTitle:@"Destination"];

    if ([destinationMenuItem hasSubmenu]) {
      BOOL foundFirstSeparator = NO;

      for (NSMenuItem *menuItem in [[destinationMenuItem submenu] itemArray]) {
        // Grab everything after first separator, and before second separator or end of the menu
        if ([menuItem isSeparatorItem]) {
          if (!foundFirstSeparator) {
            foundFirstSeparator = YES;
          } else {
            break;
          }
        } else if (foundFirstSeparator) {
          [destinationItems addObject:menuItem.title];
        }
      }
    }
  }

  return [destinationItems copy];
}

- (void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end


text:
<?php
namespace tests\Reprint;

use Reprint\Utilities;

/**
 * @coversDefaultClass \Reprint\Utilities
 */
class UtilitiesTest extends \PHPUnit_Framework_TestCase {
	protected static $classname	= '\\Reprint\\Utilities';

	/**
	 * @covers ::stringToSlug
	 * @covers ::<!public>
	 * @dataProvider getStringToSlugData
	 */
	public function testStringToSlug($expected, $string, $message = null){
		$this->assertEquals($expected, Utilities::stringToSlug($string), $message);
	}

	public function getStringToSlugData(){
		return array(
			array('example-string', 'Example String', 'Slugs should be generated from basic strings'),
			array('an-example-string-slug', '"An Example" String Slug', 'Non-alphanumeric characters should be removed from slugs'),
			array('cant-keep-apostrophes', 'Can\'t keep apostrophes', 'Apostrophes should be removed'),
			array('example-string', ' (Example)  &   "String" ', 'Multiple consecutive non-whitespace characters should be reduced to one'),
		);
	}

	/**
	 * @covers ::escape
	 * @covers ::<!public>
	 * @dataProvider getEscapeData
	 */
	public function testEscape($expected, $string, $message = null){
		$this->assertEquals($expected, Utilities::escape($string), $message);
	}

	public function getEscapeData(){
		return array(
			array('Text then a <tag>', 'Text then a <tag>', 'HTML should be correctly escaped'),
			array(''Text' with "quotes"', '\'Text\' with "quotes"', 'Quotes should be correctly escaped'),
		);
	}

	/**
	 * @covers ::renderTemplate
	 * @covers ::<!public>
	 * @dataProvider getRenderTemplateData
	 */
	public function testRenderTemplate($expected, $content, array $args = null, $message = null){
		$this->assertEquals($expected, Utilities::renderTemplate($content, $args), $message);
	}

	public function getRenderTemplateData(){
		return array(
			array(
				'An example {{template}}',
				'An example {{template}}',
				null,
				'Argument-less template should not be modified',
			),
			array(
				'An example template',
				'An example {{type}}',
				array(
					'type'	=> 'template',
				),
				'Template tags should be replaced',
			),
			array(
				'An example template with {{something}}',
				'An example {{type}} with {{something}}',
				array(
					'type'	=> 'template',
				),
				'Unknown tags should not be modified',
			),
		);
	}
}


text:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".NewVisitActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/label_place_name" />

        <EditText
            android:id="@+id/newVisitPlace"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="@string/hint_filter_visits"
            android:inputType="textNoSuggestions" >
        </EditText>

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/label_visit_date" />

        <DatePicker
            android:id="@+id/newVisitDate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:calendarViewShown="false" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/label_visit_friends" />

        <MultiAutoCompleteTextView
            android:id="@+id/newVisitFriends"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10" />

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/label_visit_rating" />

        <RatingBar
            android:id="@+id/newVisitRating"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/newVisitSubmit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:text="@string/submit"
            android:onClick="addNewActivity" />
    </LinearLayout>

</ScrollView>


text:
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import vm

vm_ops = None

def test():
    global vm_ops
    vm_ops = vm.VM()
    vm_ops.create_vm(provisioning=u'厚置备', data_size='2 GB')
    vm_ops.create_vm(provisioning=u'精简置备', data_size='2 GB', view='list')
    vm_ops.check_browser_console_log()
    test_util.test_pass('Create VM with Data Volume Successful')

def env_recover():
    global vm_ops
    vm_ops.delete_vm(corner_btn=False, del_vol=True)
    vm_ops.close()

#Will be called only if exception happens in test().
def error_cleanup():
    global vm_ops
    try:
        vm_ops.delete_vm(corner_btn=False)
        vm_ops.close()
    except:
        pass


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Kabaddi Scheduler</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/normalize.css">
    <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/main.css">
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="app.css">

Kabaddi Scheduler (Le Panga!!!)

Add Team


text:
//  (C) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000.
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).
//
//  See http://www.boost.org/libs/type_traits for most recent version including documentation.

#ifndef BOOST_TT_IS_INTEGRAL_HPP_INCLUDED
#define BOOST_TT_IS_INTEGRAL_HPP_INCLUDED

#include <boost/config.hpp>

// should be the last #include
#include <boost/type_traits/detail/bool_trait_def.hpp>

namespace boost {

//* is a type T an [cv-qualified-] integral type described in the standard (3.9.1p3)
// as an extention we include long long, as this is likely to be added to the
// standard at a later date
#if defined( __CODEGEARC__ )
BOOST_TT_AUX_BOOL_TRAIT_DEF1(is_integral,T,__is_integral(T))
#else
BOOST_TT_AUX_BOOL_TRAIT_DEF1(is_integral,T,false)

BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,unsigned char,true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,unsigned short,true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,unsigned int,true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,unsigned long,true)

BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,signed char,true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,signed short,true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,signed int,true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,signed long,true)

BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,bool,true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,char,true)

#ifndef BOOST_NO_INTRINSIC_WCHAR_T
// If the following line fails to compile and you're using the Intel
// compiler, see http://lists.boost.org/MailArchives/boost-users/msg06567.php,
// and define BOOST_NO_INTRINSIC_WCHAR_T on the command line.
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,wchar_t,true)
#endif

// Same set of integral types as in boost/type_traits/integral_promotion.hpp.
// Please, keep in sync. -- Alexander Nasonov
#if (defined(BOOST_MSVC) && (BOOST_MSVC < 1300)) \
    || (defined(BOOST_INTEL_CXX_VERSION) && defined(_MSC_VER) && (BOOST_INTEL_CXX_VERSION <= 600)) \
    || (defined(__BORLANDC__) && (__BORLANDC__ == 0x600) && (_MSC_VER < 1300))
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,unsigned __int8,true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,__int8,true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,unsigned __int16,true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,__int16,true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,unsigned __int32,true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,__int32,true)
#ifdef __BORLANDC__
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,unsigned __int64,true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,__int64,true)
#endif
#endif

# if defined(BOOST_HAS_LONG_LONG)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral, ::boost::ulong_long_type,true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral, ::boost::long_long_type,true)
#elif defined(BOOST_HAS_MS_INT64)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,unsigned __int64,true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_integral,__int64,true)
#endif

#endif  // non-CodeGear implementation

} // namespace boost

#include <boost/type_traits/detail/bool_trait_undef.hpp>

#endif // BOOST_TT_IS_INTEGRAL_HPP_INCLUDED


text:
package com.amazonaws.services.databasemigrationservice.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * The task assessment report in JSON format.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ReplicationTaskAssessmentResult implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The replication task identifier of the task on which the task assessment was run.
     *

     */
    private String replicationTaskIdentifier;
    /**
     *

     * The Amazon Resource Name (ARN) of the replication task.
     *

     */
    private String replicationTaskArn;
    /**
     *

     * The date the task assessment was completed.
     *

     */
    private java.util.Date replicationTaskLastAssessmentDate;
    /**
     *

     * The status of the task assessment.
     *

     */
    private String assessmentStatus;
    /**
     *

     * The file containing the results of the task assessment.
     *

     */
    private String assessmentResultsFile;
    /**
     *

     * The task assessment results in JSON format.
     *

     */
    private String assessmentResults;
    /**
     *

     * The URL of the S3 object containing the task assessment results.
     *

     */
    private String s3ObjectUrl;

    /**
     *

     * The replication task identifier of the task on which the task assessment was run.
     *

     *
     * @param replicationTaskIdentifier
     *        The replication task identifier of the task on which the task assessment was run.
     */

    public void setReplicationTaskIdentifier(String replicationTaskIdentifier) {
        this.replicationTaskIdentifier = replicationTaskIdentifier;
    }

    /**
     *

     * The replication task identifier of the task on which the task assessment was run.
     *

     *
     * @return The replication task identifier of the task on which the task assessment was run.
     */

    public String getReplicationTaskIdentifier() {
        return this.replicationTaskIdentifier;
    }

    /**
     *

     * The replication task identifier of the task on which the task assessment was run.
     *

     *
     * @param replicationTaskIdentifier
     *        The replication task identifier of the task on which the task assessment was run.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ReplicationTaskAssessmentResult withReplicationTaskIdentifier(String replicationTaskIdentifier) {
        setReplicationTaskIdentifier(replicationTaskIdentifier);
        return this;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the replication task.
     *

     *
     * @param replicationTaskArn
     *        The Amazon Resource Name (ARN) of the replication task.
     */

    public void setReplicationTaskArn(String replicationTaskArn) {
        this.replicationTaskArn = replicationTaskArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the replication task.
     *

     *
     * @return The Amazon Resource Name (ARN) of the replication task.
     */

    public String getReplicationTaskArn() {
        return this.replicationTaskArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the replication task.
     *

     *
     * @param replicationTaskArn
     *        The Amazon Resource Name (ARN) of the replication task.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ReplicationTaskAssessmentResult withReplicationTaskArn(String replicationTaskArn) {
        setReplicationTaskArn(replicationTaskArn);
        return this;
    }

    /**
     *

     * The date the task assessment was completed.
     *

     *
     * @param replicationTaskLastAssessmentDate
     *        The date the task assessment was completed.
     */

    public void setReplicationTaskLastAssessmentDate(java.util.Date replicationTaskLastAssessmentDate) {
        this.replicationTaskLastAssessmentDate = replicationTaskLastAssessmentDate;
    }

    /**
     *

     * The date the task assessment was completed.
     *

     *
     * @return The date the task assessment was completed.
     */

    public java.util.Date getReplicationTaskLastAssessmentDate() {
        return this.replicationTaskLastAssessmentDate;
    }

    /**
     *

     * The date the task assessment was completed.
     *

     *
     * @param replicationTaskLastAssessmentDate
     *        The date the task assessment was completed.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ReplicationTaskAssessmentResult withReplicationTaskLastAssessmentDate(java.util.Date replicationTaskLastAssessmentDate) {
        setReplicationTaskLastAssessmentDate(replicationTaskLastAssessmentDate);
        return this;
    }

    /**
     *

     * The status of the task assessment.
     *

     *
     * @param assessmentStatus
     *        The status of the task assessment.
     */

    public void setAssessmentStatus(String assessmentStatus) {
        this.assessmentStatus = assessmentStatus;
    }

    /**
     *

     * The status of the task assessment.
     *

     *
     * @return The status of the task assessment.
     */

    public String getAssessmentStatus() {
        return this.assessmentStatus;
    }

    /**
     *

     * The status of the task assessment.
     *

     *
     * @param assessmentStatus
     *        The status of the task assessment.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ReplicationTaskAssessmentResult withAssessmentStatus(String assessmentStatus) {
        setAssessmentStatus(assessmentStatus);
        return this;
    }

    /**
     *

     * The file containing the results of the task assessment.
     *

     *
     * @param assessmentResultsFile
     *        The file containing the results of the task assessment.
     */

    public void setAssessmentResultsFile(String assessmentResultsFile) {
        this.assessmentResultsFile = assessmentResultsFile;
    }

    /**
     *

     * The file containing the results of the task assessment.
     *

     *
     * @return The file containing the results of the task assessment.
     */

    public String getAssessmentResultsFile() {
        return this.assessmentResultsFile;
    }

    /**
     *

     * The file containing the results of the task assessment.
     *

     *
     * @param assessmentResultsFile
     *        The file containing the results of the task assessment.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ReplicationTaskAssessmentResult withAssessmentResultsFile(String assessmentResultsFile) {
        setAssessmentResultsFile(assessmentResultsFile);
        return this;
    }

    /**
     *

     * The task assessment results in JSON format.
     *

     *
     * @param assessmentResults
     *        The task assessment results in JSON format.
     */

    public void setAssessmentResults(String assessmentResults) {
        this.assessmentResults = assessmentResults;
    }

    /**
     *

     * The task assessment results in JSON format.
     *

     *
     * @return The task assessment results in JSON format.
     */

    public String getAssessmentResults() {
        return this.assessmentResults;
    }

    /**
     *

     * The task assessment results in JSON format.
     *

     *
     * @param assessmentResults
     *        The task assessment results in JSON format.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ReplicationTaskAssessmentResult withAssessmentResults(String assessmentResults) {
        setAssessmentResults(assessmentResults);
        return this;
    }

    /**
     *

     * The URL of the S3 object containing the task assessment results.
     *

     *
     * @param s3ObjectUrl
     *        The URL of the S3 object containing the task assessment results.
     */

    public void setS3ObjectUrl(String s3ObjectUrl) {
        this.s3ObjectUrl = s3ObjectUrl;
    }

    /**
     *

     * The URL of the S3 object containing the task assessment results.
     *

     *
     * @return The URL of the S3 object containing the task assessment results.
     */

    public String getS3ObjectUrl() {
        return this.s3ObjectUrl;
    }

    /**
     *

     * The URL of the S3 object containing the task assessment results.
     *

     *
     * @param s3ObjectUrl
     *        The URL of the S3 object containing the task assessment results.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ReplicationTaskAssessmentResult withS3ObjectUrl(String s3ObjectUrl) {
        setS3ObjectUrl(s3ObjectUrl);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getReplicationTaskIdentifier() != null)
            sb.append("ReplicationTaskIdentifier: ").append(getReplicationTaskIdentifier()).append(",");
        if (getReplicationTaskArn() != null)
            sb.append("ReplicationTaskArn: ").append(getReplicationTaskArn()).append(",");
        if (getReplicationTaskLastAssessmentDate() != null)
            sb.append("ReplicationTaskLastAssessmentDate: ").append(getReplicationTaskLastAssessmentDate()).append(",");
        if (getAssessmentStatus() != null)
            sb.append("AssessmentStatus: ").append(getAssessmentStatus()).append(",");
        if (getAssessmentResultsFile() != null)
            sb.append("AssessmentResultsFile: ").append(getAssessmentResultsFile()).append(",");
        if (getAssessmentResults() != null)
            sb.append("AssessmentResults: ").append(getAssessmentResults()).append(",");
        if (getS3ObjectUrl() != null)
            sb.append("S3ObjectUrl: ").append(getS3ObjectUrl());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ReplicationTaskAssessmentResult == false)
            return false;
        ReplicationTaskAssessmentResult other = (ReplicationTaskAssessmentResult) obj;
        if (other.getReplicationTaskIdentifier() == null ^ this.getReplicationTaskIdentifier() == null)
            return false;
        if (other.getReplicationTaskIdentifier() != null && other.getReplicationTaskIdentifier().equals(this.getReplicationTaskIdentifier()) == false)
            return false;
        if (other.getReplicationTaskArn() == null ^ this.getReplicationTaskArn() == null)
            return false;
        if (other.getReplicationTaskArn() != null && other.getReplicationTaskArn().equals(this.getReplicationTaskArn()) == false)
            return false;
        if (other.getReplicationTaskLastAssessmentDate() == null ^ this.getReplicationTaskLastAssessmentDate() == null)
            return false;
        if (other.getReplicationTaskLastAssessmentDate() != null
                && other.getReplicationTaskLastAssessmentDate().equals(this.getReplicationTaskLastAssessmentDate()) == false)
            return false;
        if (other.getAssessmentStatus() == null ^ this.getAssessmentStatus() == null)
            return false;
        if (other.getAssessmentStatus() != null && other.getAssessmentStatus().equals(this.getAssessmentStatus()) == false)
            return false;
        if (other.getAssessmentResultsFile() == null ^ this.getAssessmentResultsFile() == null)
            return false;
        if (other.getAssessmentResultsFile() != null && other.getAssessmentResultsFile().equals(this.getAssessmentResultsFile()) == false)
            return false;
        if (other.getAssessmentResults() == null ^ this.getAssessmentResults() == null)
            return false;
        if (other.getAssessmentResults() != null && other.getAssessmentResults().equals(this.getAssessmentResults()) == false)
            return false;
        if (other.getS3ObjectUrl() == null ^ this.getS3ObjectUrl() == null)
            return false;
        if (other.getS3ObjectUrl() != null && other.getS3ObjectUrl().equals(this.getS3ObjectUrl()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getReplicationTaskIdentifier() == null) ? 0 : getReplicationTaskIdentifier().hashCode());
        hashCode = prime * hashCode + ((getReplicationTaskArn() == null) ? 0 : getReplicationTaskArn().hashCode());
        hashCode = prime * hashCode + ((getReplicationTaskLastAssessmentDate() == null) ? 0 : getReplicationTaskLastAssessmentDate().hashCode());
        hashCode = prime * hashCode + ((getAssessmentStatus() == null) ? 0 : getAssessmentStatus().hashCode());
        hashCode = prime * hashCode + ((getAssessmentResultsFile() == null) ? 0 : getAssessmentResultsFile().hashCode());
        hashCode = prime * hashCode + ((getAssessmentResults() == null) ? 0 : getAssessmentResults().hashCode());
        hashCode = prime * hashCode + ((getS3ObjectUrl() == null) ? 0 : getS3ObjectUrl().hashCode());
        return hashCode;
    }

    @Override
    public ReplicationTaskAssessmentResult clone() {
        try {
            return (ReplicationTaskAssessmentResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.databasemigrationservice.model.transform.ReplicationTaskAssessmentResultMarshaller.getInstance().marshall(this,
                protocolMarshaller);
    }
}


text:
@interface ColorInverterView : UIView {
#if __has_feature(objc_arc) == 1
    __strong ANImageBitmapRep * image;
#else
    ANImageBitmapRep * image;
#endif
}

- (IBAction)invert:(id)sender;

@end