text:
/*!
 * \file dnnl_fc.cc
 * \brief DNNL (Quantized) FullyConnected operator based on subgraph
 * \author Ciyong Chen
 */

#if MXNET_USE_ONEDNN == 1

#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#include "operator/nn/dnnl/dnnl_act-inl.h"
#include "operator/nn/dnnl/dnnl_base-inl.h"
#include "operator/nn/dnnl/dnnl_fully_connected-inl.h"
#include "operator/nn/dnnl/dnnl_ops-inl.h"
#include "operator/quantization/quantization_utils.h"
#include "operator/tensor/matrix_op-inl.h"
#include "operator/subgraph/common.h"
#include "dnnl_common.h"
#include "dnnl_fc-inl.h"

namespace mxnet {
namespace op {

class SgDNNLFCOp {
 public:
  explicit SgDNNLFCOp(const nnvm::NodeAttrs& attrs)
      : subgraph_sym_(*attrs.subgraphs[0]), full_param_(nnvm::get<DNNLFCFullParam>(attrs.parsed)) {}

  void Forward(const OpContext& ctx,
               const std::vector<NDArray>& inputs,
               const std::vector<OpReqType>& req,
               const std::vector<NDArray>& outputs);

  void Backward(const OpContext& ctx,
                const std::vector<NDArray>& inputs,
                const std::vector<OpReqType>& req,
                const std::vector<NDArray>& outputs) {
    LOG(FATAL) << "Not implemented: subgraph oneDNN fully connected only supports "
                  "inference computation.";
  }

 private:
  bool initialized_{false};
  bool reorder_data_{false};
  bool inplace_{false};
  nnvm::Symbol subgraph_sym_;
  DNNLFCFullParam full_param_;
  dnnl_args_map_t args_;
  std::shared_ptr<DNNLFullyConnectedForward> fwd_;
  std::shared_ptr<dnnl::memory> cached_data_mem_;
  std::shared_ptr<dnnl::memory> cached_out_mem_;
  NDArray cached_weight_;
  NDArray cached_bias_;
  float cached_data_min_;
  float cached_data_max_;
  float cached_weight_min_;
  float cached_weight_max_;
  float cached_sum_min_;
  float cached_sum_max_;
  float cached_bias_min_;
  float cached_bias_max_;
  size_t weight_ver_;
  size_t bias_ver_;
  float cached_output_min_;
  float cached_output_max_;
  float data_scale_{0.0f};
  std::vector<float> weight_scales_;
};

void SgDNNLFCOp::Forward(const OpContext& ctx,
                         const std::vector<NDArray>& in_data,
                         const std::vector<OpReqType>& req,
                         const std::vector<NDArray>& out_data) {
  auto& dnnl_param         = full_param_.dnnl_param;
  auto& default_param      = full_param_.default_param;
  const bool has_bias      = !default_param.no_bias;
  const bool quantized     = dnnl_param.quantized;
  const bool out_quantized = dnnl_param.quantized && !dnnl_param.enable_float_output;
  const bool channel_wise  = quantized && dnnl_param.channel_wise_quantize.has_value() &&
                            dnnl_param.channel_wise_quantize.value();

  const FCInputIndex idx(full_param_);

  CHECK_EQ(in_data.size(), idx.GetTotal());

  int index               = 0;
  const int out_index     = index++;
  const int out_min_index = out_quantized ? index++ : 0;
  const int out_max_index = out_quantized ? index++ : 0;
  CHECK_EQ(out_data.size(), index);  // index is equal to total number of outputs

  float data_min   = 0.0f;
  float data_max   = 0.0f;
  float weight_min = 0.0f;
  float weight_max = 0.0f;
  float bias_min   = 0.0f;
  float bias_max   = 0.0f;

  const float sum_min   = idx.sum_min ? in_data[idx.sum_min].data().dptr<float>()[0] : 0.0;
  const float sum_max   = idx.sum_max ? in_data[idx.sum_max].data().dptr<float>()[0] : 0.0;
  NDArray data          = in_data[idx.data];
  const NDArray& weight = in_data[idx.weight];
  NDArray output;

  if (dnnl_param.with_sum) {
    if (!initialized_) {
      // TODO(zhennan): Currently, dnnl fallback mechanism will break inplace option,
      // which make check (req[out_index] == kWriteInplace) useless.
      auto in_dnnl_mem  = static_cast<const dnnl::memory*>(in_data[idx.sum].GetDNNLData());
      auto out_dnnl_mem = static_cast<const dnnl::memory*>(out_data[out_index].GetDNNLData());
      if (in_dnnl_mem->get_data_handle() == out_dnnl_mem->get_data_handle()) {
        inplace_ = true;
      }
    }
    if (inplace_) {
      output = in_data[idx.sum];
    } else {
      // Not in place: copy in_data[idx.sum] into outputs[out_index].
      auto in_dnnl_mem  = static_cast<const dnnl::memory*>(in_data[idx.sum].GetDNNLData());
      auto out_dnnl_mem = static_cast<const dnnl::memory*>(out_data[out_index].GetDNNLData());
      if (out_data[out_index].dtype() == mshadow::kInt32) {
        auto mem_desc           = in_dnnl_mem->get_desc();
        auto this_dtype         = get_dnnl_type(mshadow::kInt32);
        mem_desc.data.data_type = static_cast<dnnl_data_type_t>(this_dtype);
        dnnl_mem_ptr tmp_mem(new dnnl::memory(
            mem_desc, CpuEngine::Get()->get_engine(), out_dnnl_mem->get_data_handle()));
        DNNLStream::Get()->RegisterMem(tmp_mem);
        DNNLStream::Get()->RegisterPrimArgs(
            dnnl::reorder(*in_dnnl_mem, *tmp_mem),
            {{DNNL_ARG_FROM, *in_dnnl_mem}, {DNNL_ARG_TO, *tmp_mem}});
        output = NDArray(tmp_mem);
      } else {
        dnnl_mem_ptr tmp_mem(new dnnl::memory(in_dnnl_mem->get_desc(),
                                              CpuEngine::Get()->get_engine(),
                                              out_dnnl_mem->get_data_handle()));
        DNNLStream::Get()->RegisterMem(tmp_mem);
        DNNLMemoryCopy(*in_dnnl_mem, tmp_mem.get());
        output = NDArray(tmp_mem);
      }
    }
  } else {
    output = out_data[out_index];
  }

  if (dnnl_param.quantized) {
    if (!channel_wise) {
      weight_min = in_data[idx.weight_min].data().dptr<float>()[0];
      weight_max = in_data[idx.weight_max].data().dptr<float>()[0];
      if (has_bias) {
        bias_min = in_data[idx.bias_min].data().dptr<float>()[0];
        bias_max = in_data[idx.bias_max].data().dptr<float>()[0];
      }
    }
    data_min = in_data[idx.data_min].data().dptr<float>()[0];
    data_max = in_data[idx.data_max].data().dptr<float>()[0];
  }

  if (initialized_ && dnnl_param.quantized && dmlc::GetEnv("MXNET_ONEDNN_QFC_DYNAMIC_PARAMS", 0)) {
    if (channel_wise) {
      if (cached_data_min_ != data_min || cached_data_max_ != data_max ||
          cached_sum_min_ != sum_min || cached_sum_max_ != sum_max ||
          weight_ver_ != weight.version() ||
          (has_bias && (bias_ver_ != in_data[idx.bias].version()))) {
        initialized_ = false;
      }
    } else {
      if (cached_data_min_ != data_min || cached_data_max_ != data_max ||
          cached_sum_min_ != sum_min || cached_sum_max_ != sum_max ||
          cached_weight_min_ != weight_min || cached_weight_max_ != weight_max ||
          (has_bias && (cached_bias_min_ != bias_min || cached_bias_max_ != bias_max))) {
        initialized_ = false;
      }
    }
  }

  if (!initialized_) {
    const auto nthreads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount();
    const auto engine   = CpuEngine::Get()->get_engine();
    cached_data_min_    = data_min;
    cached_data_max_    = data_max;
    cached_weight_min_  = weight_min;
    cached_weight_max_  = weight_max;
    weight_ver_         = weight.version();
    cached_weight_      = weight;
    cached_sum_min_     = sum_min;
    cached_sum_max_     = sum_max;
    if (has_bias) {
      cached_bias_min_ = bias_min;
      cached_bias_max_ = bias_max;
      bias_ver_        = in_data[idx.bias].version();
      cached_bias_     = in_data[idx.bias];
    } else {
      cached_bias_ = NDArray();
    }
    const mxnet::TShape ishape = data.shape();
    const auto data_ndim       = ishape.ndim();
    if (data.IsDNNLData()) {
      reorder_data_ = true;
      data          = data.Reorder2Default();
    }
    if (data_ndim != 2) {
      if (!default_param.flatten) {
        data =
            data.DNNLDataReshape(Shape2(ishape.ProdShape(0, data_ndim - 1), ishape[data_ndim - 1]));
      } else {
        data = data.DNNLDataReshape(Shape2(ishape[0], ishape.ProdShape(1, data_ndim)));
      }
    }

    // create cached out_md
    const mxnet::TShape oshape = output.shape();
    dnnl::memory::dims out_dims(2);
    if (oshape.ndim() == 2) {
      out_dims[0] = static_cast<int>(oshape[0]);
      out_dims[1] = static_cast<int>(oshape[1]);
    } else {
      if (!default_param.flatten) {
        out_dims[0] = static_cast<int>(oshape.ProdShape(0, oshape.ndim() - 1));
        out_dims[1] = static_cast<int>(oshape[oshape.ndim() - 1]);
      } else {
        out_dims[0] = static_cast<int>(static_cast<int>(oshape[0]));
        out_dims[1] = static_cast<int>(oshape.ProdShape(1, oshape.ndim()));
      }
    }
    dnnl::memory::desc out_md =
        dnnl::memory::desc(out_dims,
                           get_dnnl_type(output.dtype()),
                           static_cast<dnnl::memory::format_tag>(GetDefaultFormat(2)));
    cached_out_mem_ = std::make_shared<dnnl::memory>(out_md, engine);

    bool support_channelwise_scale = false;
    if (dnnl_param.quantized) {
      CHECK(data.dtype() == mshadow::kInt8 || data.dtype() == mshadow::kUint8);
      data_scale_ = GetQuantizeScale(data.dtype(), cached_data_min_, cached_data_max_);

      bool fuse_requantize = false;
      // Channelwise scaling is only supported when fusion is enabled (requantize or dequantize).
      if (dnnl_param.min_calib_range.has_value() && dnnl_param.max_calib_range.has_value()) {
        cached_output_min_        = dnnl_param.min_calib_range.value();
        cached_output_max_        = dnnl_param.max_calib_range.value();
        support_channelwise_scale = true;
        fuse_requantize           = true;
      }
      if (dnnl_param.enable_float_output) {
        support_channelwise_scale = true;
      }
      // channel_wise  support_channelwise_scale  result
      // True          True                       True
      // True          False                      Error
      // False         True/False                 False
      if (channel_wise && !support_channelwise_scale) {
        LOG(FATAL)
            << "Currently, channel-wise quantization requires fuse requantize or dequantize."
            << " Please make sure the `min_calib_range` and `max_calib_range` are set when only"
            << " fuse requantize (outputs of FullyConnected are collected during calibration "
               "phase),"
            << " or the env var of `MXNET_DISABLE_ONEDNN_QFC_FLOAT_OUTPUT` and "
            << " `MXNET_DISABLE_ONEDNN_QFC_FUSE_ALL` are not set to true (default is false)";
      }
      support_channelwise_scale = support_channelwise_scale && channel_wise;

      if (support_channelwise_scale) {
        MSHADOW_REAL_TYPE_SWITCH(cached_weight_.dtype(), DType, {
          weight_scales_ = GetWeightScales<DType>(cached_weight_,
                                                  has_bias ? &cached_bias_ : nullptr,
                                                  data_scale_,
                                                  support_channelwise_scale);
        });
      } else {
        weight_scales_.resize(1);
        weight_scales_[0] =
            GetQuantizeScale(cached_weight_.dtype(), cached_weight_min_, cached_weight_max_);
        if (has_bias) {
          if (cached_bias_.dtype() == mshadow::kInt8) {
            float bias_scale = GetQuantizeScale(mshadow::kInt8, cached_bias_min_, cached_bias_max_);

            float bias_int32_rescale = data_scale_ * weight_scales_[0] / bias_scale;
            // TODO(zhennan): dnnl has bug to handle INT_MAX in bias, so set
            // the maximum value of bias to INT_MAX / 2.
            float bias_max_rescale =
                MaxValue<int32_t>() / 2 / MaxAbs(cached_bias_min_, cached_bias_max_) / bias_scale;
            if (bias_int32_rescale > bias_max_rescale) {
              // avoid overflow on bias
              bias_int32_rescale = bias_max_rescale;
              float weight_rescale =
                  bias_int32_rescale * bias_scale / data_scale_ / weight_scales_[0];
              int8_t* weight_ptr = weight.data().dptr<int8_t>();
              size_t weight_size = weight.shape().Size();
#pragma omp parallel for num_threads(nthreads)
              for (index_t i = 0; i < static_cast<index_t>(weight_size); ++i) {
                weight_ptr[i] = std::round(weight_ptr[i] * weight_rescale);
              }
              weight_scales_[0] *= weight_rescale;
            }
            NDArray bias = in_data[fullc::kBias];
            cached_bias_ =
                NDArray(bias.storage_type(), bias.shape(), bias.ctx(), true, mshadow::kInt32);
            int8_t* bias_ptr            = bias.data().dptr<int8_t>();
            int32_t* quantized_bias_ptr = cached_bias_.data().dptr<int32_t>();
            size_t bias_size            = bias.shape().Size();

#pragma omp parallel for num_threads(nthreads)
            for (index_t i = 0; i < static_cast<index_t>(bias_size); ++i) {
              quantized_bias_ptr[i] = std::round(bias_ptr[i] * bias_int32_rescale);
            }
          }
        }
      }

      size_t num_channel = cached_weight_.shape()[0];
      float out_scale    = 1.0f;
      if (fuse_requantize || dnnl_param.enable_float_output) {
        float tmp_scale_ = 1.0f;
        if (fuse_requantize) {
          if (dnnl_param.with_eltwise) {
            tmp_scale_ = 1.0 / data_scale_;
            full_param_.eltwise_param.scale =
                GetQuantizeScale(output.dtype(), cached_output_min_, cached_output_max_);
          } else {
            out_scale  = GetQuantizeScale(output.dtype(), cached_output_min_, cached_output_max_);
            tmp_scale_ = out_scale / data_scale_;
          }
        } else {
          tmp_scale_ = 1.0 / data_scale_;
        }

        if (support_channelwise_scale) {
          full_param_.output_scales.resize(num_channel);
#pragma omp parallel for num_threads(nthreads)
          for (index_t i = 0; i < static_cast<index_t>(num_channel); ++i) {
            full_param_.output_scales[i] = tmp_scale_ / weight_scales_[i];
          }
        } else {
          full_param_.output_scales.resize(1);
          full_param_.output_scales[0] = tmp_scale_ / weight_scales_[0];
        }
      } else {
        Stream<cpu>* s = ctx.get_stream<cpu>();
        if (data.dtype() == mshadow::kInt8) {
          mxnet_op::Kernel<QuantizationRangeForS8S8MultiplicationStruct, cpu>::Launch(
              s,
              1,
              &cached_output_min_,
              &cached_output_max_,
              &data_min,
              &data_max,
              &weight_min,
              &weight_max);
        } else {
          mxnet_op::Kernel<QuantizationRangeForS8U8MultiplicationStruct, cpu>::Launch(
              s,
              1,
              &cached_output_min_,
              &cached_output_max_,
              &data_min,
              &data_max,
              &weight_min,
              &weight_max);
        }
        full_param_.output_scales.resize(0);
        out_scale = data_scale_ * weight_scales_[0];
      }

      if (dnnl_param.with_sum && !dnnl_param.enable_float_output) {
        float sum_in_scale =
            GetQuantizeScale(in_data[idx.sum].dtype(), cached_sum_min_, cached_sum_max_);
        full_param_.sum_scale = out_scale / sum_in_scale;
      }
    }  // if (dnnl_param.quantized)

    fwd_.reset(new DNNLFullyConnectedForward(full_param_,
                                             ctx.is_train,
                                             data,
                                             cached_weight_,
                                             (has_bias ? &cached_bias_ : nullptr),
                                             out_md));

    // convert weight and bias to the format that DNNL requires
    if (!dnnl_param.quantized || support_channelwise_scale) {
      dnnl::memory::desc bias_md;
      if (has_bias)
        bias_md = fwd_->fwd_pd.bias_desc();
      ConvertWeightBias2DNNL(&cached_weight_,
                             &cached_bias_,
                             has_bias,
                             fwd_->fwd_pd.weights_desc(),
                             has_bias ? &bias_md : nullptr,
                             1,
                             data_scale_,
                             weight_scales_,
                             false);
    } else {
      const auto def_weight_mem = static_cast<const dnnl::memory*>(weight.GetDNNLData());
      if (def_weight_mem->get_desc() != fwd_->fwd_pd.weights_desc()) {
        auto weight_desc       = fwd_->fwd_pd.weights_desc();
        cached_weight_         = NDArray(weight_desc);
        auto cached_weight_mem = static_cast<const dnnl::memory*>(cached_weight_.GetDNNLData());
        std::unordered_map<int, dnnl::memory> args(
            {{DNNL_ARG_FROM, *def_weight_mem}, {DNNL_ARG_TO, *cached_weight_mem}});
        DNNLStream::Get()->RegisterPrimArgs(dnnl::reorder(*def_weight_mem, *cached_weight_mem),
                                            args);
      }
    }

    const auto data_mem = static_cast<const dnnl::memory*>(data.GetDNNLData());
    cached_data_mem_    = std::make_shared<dnnl::memory>(data_mem->get_desc(), engine);

    args_[DNNL_ARG_SRC]     = *cached_data_mem_;
    args_[DNNL_ARG_WEIGHTS] = *static_cast<const dnnl::memory*>(cached_weight_.GetDNNLData());
    if (has_bias)
      args_[DNNL_ARG_BIAS] = *static_cast<const dnnl::memory*>(cached_bias_.GetDNNLData());
    args_[DNNL_ARG_DST] = *cached_out_mem_;
    initialized_        = true;
  }

  if (dnnl_param.with_sum) {
    const auto& output_mem   = output.GetDNNLData();
    const auto& out_mem_desc = output_mem->get_desc();
    auto dst_mem_desc        = fwd_->fwd_pd.dst_desc();
    if (out_mem_desc != dst_mem_desc) {
      auto tmp_out_mem            = output.GetDNNLDataReorder(dst_mem_desc);
      dst_mem_desc.data.data_type = out_mem_desc.data.data_type;
      dnnl_mem_ptr new_out_mem(new dnnl::memory(
          dst_mem_desc, CpuEngine::Get()->get_engine(), output_mem->get_data_handle()));
      DNNLStream::Get()->RegisterMem(new_out_mem);
      DNNLMemoryCopy(*tmp_out_mem, new_out_mem.get());
      output = NDArray(new_out_mem);
    }
  }

  if (reorder_data_) {
    data = data.Reorder2Default();
  }
  MSHADOW_TYPE_SWITCH(data.dtype(), DType, {
    cached_data_mem_->set_data_handle(reinterpret_cast<void*>(data.data().dptr<DType>()));
  });
  MSHADOW_TYPE_SWITCH(output.dtype(), DType, {
    cached_out_mem_->set_data_handle(reinterpret_cast<void*>(output.data().dptr<DType>()));
  });
  DNNLStream::Get()->RegisterPrimArgs(fwd_->GetFwd(), args_);
  DNNLStream::Get()->Submit();

  if (dnnl_param.quantized && !dnnl_param.enable_float_output) {
    float* output_min_ptr = out_data[out_min_index].data().dptr<float>();
    float* output_max_ptr = out_data[out_max_index].data().dptr<float>();

    *output_min_ptr = cached_output_min_;
    *output_max_ptr = cached_output_max_;
  }
}

static void SgDNNLFCParamParser(nnvm::NodeAttrs* attrs) {
  // For backward compatible, with_relu->with_eltwise
  auto legacy = attrs->dict.find("with_relu");
  if (legacy != attrs->dict.end()) {
    attrs->dict["with_eltwise"] = attrs->dict["with_relu"];
    attrs->dict.erase(legacy);
  }

  DNNLFCFullParam full_param;
  try {
    full_param.dnnl_param.Init(attrs->dict);
  } catch (const dmlc::ParamError& e) {
    std::ostringstream os;
    os << e.what();
    os << ", in operator " << attrs->op->name << "("
       << "name=\"" << attrs->name << "\"";
    for (const auto& k : attrs->dict) {
      os << ", " << k.first << "=\"" << k.second << "\"";
    }
    os << ")";
    throw dmlc::ParamError(os.str());
  }
  auto subgraph_sym = attrs->subgraphs[0];
  DFSVisit(subgraph_sym->outputs, [&](const nnvm::ObjectPtr& node) {
    if (node->is_variable())
      return;
    auto& op_name = node->op()->name;
    if (op_name == "FullyConnected") {
      full_param.default_param = nnvm::get<FullyConnectedParam>(node->attrs.parsed);
    } else if (SupportDNNLFCEltwiseFusion(op_name)) {
      if (op_name == "Activation") {
        const ActivationParam act_param = nnvm::get<ActivationParam>(node->attrs.parsed);
        full_param.eltwise_param.alg    = GetDNNLActAlgo(act_param);
      } else if (op_name == "LeakyReLU") {
        const auto act_param           = nnvm::get<LeakyReLUParam>(node->attrs.parsed);
        full_param.eltwise_param.alpha = act_param.slope;
        full_param.eltwise_param.alg   = GetDNNLActAlgo(act_param);
      } else if (op_name == "clip") {
        const ClipParam clip_param     = nnvm::get<ClipParam>(node->attrs.parsed);
        full_param.eltwise_param.alg   = dnnl::algorithm::eltwise_bounded_relu;
        full_param.eltwise_param.alpha = clip_param.a_max;
      } else {
        full_param.eltwise_param.alg = GetDNNLEltwiseAlgo(op_name);
      }
    }
  });
  attrs->parsed = std::move(full_param);
}

static std::vector<std::string> SgDNNLFCListInputNames(const NodeAttrs& attrs) {
  auto const& full_param               = nnvm::get<DNNLFCFullParam>(attrs.parsed);
  auto const& dnnl_param               = full_param.dnnl_param;
  std::vector<std::string> input_names = DefaultSubgraphOpListInputs(attrs);
  if (dnnl_param.quantized) {
    const bool channel_wise =
        dnnl_param.channel_wise_quantize.has_value() && dnnl_param.channel_wise_quantize;
    input_names.emplace_back("data_min");
    input_names.emplace_back("data_max");
    if (!channel_wise) {
      input_names.emplace_back("weight_min");
      input_names.emplace_back("weight_max");
      if (!full_param.default_param.no_bias) {
        input_names.emplace_back("bias_min");
        input_names.emplace_back("bias_max");
      }
    }
    if (dnnl_param.with_sum && !dnnl_param.enable_float_output) {
      input_names.emplace_back("sum_min");
      input_names.emplace_back("sum_max");
    }
  }
  return input_names;
}

static std::vector<std::string> SgDNNLFCListOutputNames(const NodeAttrs& attrs) {
  auto const& full_param = nnvm::get<DNNLFCFullParam>(attrs.parsed);
  if (full_param.dnnl_param.quantized) {
    if (full_param.dnnl_param.enable_float_output)
      return std::vector<std::string>{"output"};
    else
      return std::vector<std::string>{"output", "output_min", "output_max"};
  } else {
    return std::vector<std::string>{"output"};
  }
}

template <typename T>
static inline void FillBaseInputOutputInfo(const DNNLFCFullParam& param,
                                           std::vector<T>* base_in_attrs,
                                           std::vector<T>* base_out_attrs,
                                           std::vector<T>* in_attrs,
                                           std::vector<T>* out_attrs) {
  auto base_num_inputs = FCInputIndex(param).GetBase();

  base_out_attrs->push_back(out_attrs->at(0));
  for (int i = 0; i < base_num_inputs; ++i) {
    base_in_attrs->push_back(in_attrs->at(i));
  }
}

static bool SgDNNLFCInferShape(const nnvm::NodeAttrs& attrs,
                               mxnet::ShapeVector* in_shapes,
                               mxnet::ShapeVector* out_shapes) {
  auto const& full_param = nnvm::get<DNNLFCFullParam>(attrs.parsed);
  if (full_param.dnnl_param.quantized) {
    mxnet::ShapeVector base_in_shapes;
    mxnet::ShapeVector base_out_shapes;
    FillBaseInputOutputInfo(full_param, &base_in_shapes, &base_out_shapes, in_shapes, out_shapes);
    bool ret = DefaultSubgraphOpShape(attrs, &base_in_shapes, &base_out_shapes);

    for (size_t i = 0; i < in_shapes->size(); ++i) {
      if (i < base_in_shapes.size())
        in_shapes->at(i) = base_in_shapes[i];
      else
        SHAPE_ASSIGN_CHECK(*in_shapes, i, Shape1(1));
    }

    out_shapes->at(0) = base_out_shapes[0];
    if (!full_param.dnnl_param.enable_float_output) {
      SHAPE_ASSIGN_CHECK(*out_shapes, 1, Shape1(1));
      SHAPE_ASSIGN_CHECK(*out_shapes, 2, Shape1(1));
    }
    return ret;
  } else {
    return DefaultSubgraphOpShape(attrs, in_shapes, out_shapes);
  }
}

static bool SgDNNLFCInferType(const nnvm::NodeAttrs& attrs,
                              std::vector<int>* in_types,
                              std::vector<int>* out_types) {
  auto const& full_param = nnvm::get<DNNLFCFullParam>(attrs.parsed);
  if (full_param.dnnl_param.quantized) {
    const bool channel_wise = full_param.dnnl_param.channel_wise_quantize.has_value() &&
                              full_param.dnnl_param.channel_wise_quantize;
    const FCInputIndex idx(full_param);

    CHECK(in_types->at(idx.data) == mshadow::kInt8 || in_types->at(idx.data) == mshadow::kUint8)
        << "QuantizedFullyConnected  data input only supports int8/uint8, while "
        << in_types->at(idx.data) << " is given.";
    if (channel_wise) {
      TYPE_ASSIGN_CHECK(*in_types, idx.weight, mshadow::kFloat32);
      if (idx.IsBiasExist()) {
        TYPE_ASSIGN_CHECK(*in_types, idx.bias, mshadow::kFloat32);
      }
    } else {
      TYPE_ASSIGN_CHECK(*in_types, idx.weight, mshadow::kInt8);
      if (idx.IsBiasExist()) {
        if (in_types->at(idx.bias) == -1) {
          TYPE_ASSIGN_CHECK(*in_types, idx.bias, mshadow::kInt32);
        } else {
          CHECK(in_types->at(idx.bias) == mshadow::kInt8 ||
                in_types->at(idx.bias) == mshadow::kInt32)
              << "QuantizedFullyConnected bias input only supports int8/int32, while "
              << in_types->at(idx.bias) << " is given.";
        }
      }
    }
    if (idx.IsSumExist()) {
      if (full_param.dnnl_param.enable_float_output) {
        TYPE_ASSIGN_CHECK(*in_types, idx.sum, mshadow::kFloat32);
      } else {
        CHECK(in_types->at(idx.sum) == mshadow::kInt8 || in_types->at(idx.sum) == mshadow::kUint8)
            << "QuantizedFullyConnected sum input only supports int8/uint8, while "
            << in_types->at(idx.sum) << " is given.";
      }
    }
    for (size_t i = idx.data_min; i < in_types->size(); ++i) {
      TYPE_ASSIGN_CHECK(*in_types, i, mshadow::kFloat32);
    }

    if (full_param.dnnl_param.enable_float_output) {
      TYPE_ASSIGN_CHECK(*out_types, 0, mshadow::kFloat32);
    } else {
      if (full_param.dnnl_param.min_calib_range.has_value() &&
          full_param.dnnl_param.max_calib_range.has_value()) {
        if (IsOutputUint8(full_param)) {
          TYPE_ASSIGN_CHECK(*out_types, 0, mshadow::kUint8);
        } else {
          TYPE_ASSIGN_CHECK(*out_types, 0, mshadow::kInt8);
        }
      } else {
        TYPE_ASSIGN_CHECK(*out_types, 0, mshadow::kInt32);
      }
      TYPE_ASSIGN_CHECK(*out_types, 1, mshadow::kFloat32);
      TYPE_ASSIGN_CHECK(*out_types, 2, mshadow::kFloat32);
    }
    return true;
  } else {
    return DefaultSubgraphOpType(attrs, in_types, out_types);
  }
}

static bool SgDNNLFCStorageType(const nnvm::NodeAttrs& attrs,
                                const int dev_mask,
                                DispatchMode* dispatch_mode,
                                std::vector<int>* in_attrs,
                                std::vector<int>* out_attrs) {
  auto const& full_param = nnvm::get<DNNLFCFullParam>(attrs.parsed);
  if (full_param.dnnl_param.quantized) {
    std::vector<int> base_in_attrs;
    std::vector<int> base_out_attrs;
    FillBaseInputOutputInfo(full_param, &base_in_attrs, &base_out_attrs, in_attrs, out_attrs);
    bool ret = DefaultSubgraphOpStorageType(
        attrs, dev_mask, dispatch_mode, &base_in_attrs, &base_out_attrs);

    for (size_t i = 0; i < in_attrs->size(); ++i) {
      if (i < base_in_attrs.size())
        in_attrs->at(i) = base_in_attrs[i];
      else
        type_assign(&in_attrs->at(i), mxnet::kDefaultStorage);
    }

    out_attrs->at(0) = base_out_attrs[0];
    if (!full_param.dnnl_param.enable_float_output) {
      type_assign(&out_attrs->at(1), mxnet::kDefaultStorage);
      type_assign(&out_attrs->at(2), mxnet::kDefaultStorage);
    }
    return ret;
  } else {
    return DefaultSubgraphOpStorageType(attrs, dev_mask, dispatch_mode, in_attrs, out_attrs);
  }
}

std::vector<std::pair<int, int>> SgDNNLFCInplaceOption(const NodeAttrs& attrs) {
  auto const& param = nnvm::get<DNNLFCFullParam>(attrs.parsed);
  if (param.dnnl_param.with_sum) {
    return std::vector<std::pair<int, int>>{{FCInputIndex(param).sum, 0}};
  } else {
    return std::vector<std::pair<int, int>>();
  }
}

static OpStatePtr CreateSgDNNLFCState(const nnvm::NodeAttrs& attrs,
                                      Context ctx,
                                      const mxnet::ShapeVector& in_shapes,
                                      const std::vector<int>& in_types) {
  return OpStatePtr::Create<SgDNNLFCOp>(attrs);
}

static void SgDNNLFCForward(const OpStatePtr& state_pointer,
                            const OpContext& ctx,
                            const std::vector<NDArray>& inputs,
                            const std::vector<OpReqType>& req,
                            const std::vector<NDArray>& outputs) {
  SgDNNLFCOp& op = state_pointer.get_state<SgDNNLFCOp>();
  op.Forward(ctx, inputs, req, outputs);
}

nnvm::ObjectPtr SgDNNLFCQuantizedOp(const NodeAttrs& attrs) {
  nnvm::ObjectPtr node          = nnvm::Node::Create();
  node->attrs.op                = Op::Get("_sg_onednn_fully_connected");
  node->attrs.name              = "quantized_" + attrs.name;
  node->attrs.dict              = attrs.dict;
  node->attrs.dict["quantized"] = "True";
  node->attrs.subgraphs.reserve(attrs.subgraphs.size());
  for (auto sub : attrs.subgraphs) {
    node->attrs.subgraphs.push_back(sub);
  }
  node->op()->attr_parser(&(node->attrs));
  return node;
}

static bool SgDNNLAvoidFCQuantizeInput(const NodeAttrs& attrs,
                                       const size_t index_to_check,
                                       const std::string quantize_granularity) {
  auto const& full_param = nnvm::get<DNNLFCFullParam>(attrs.parsed);
  std::unordered_set<size_t> avoid_indexes;
  FCInputIndex idx(full_param);
  if (quantize_granularity == "channel-wise") {
    avoid_indexes.insert(fullc::kWeight);  // weight
    if (!full_param.default_param.no_bias) {
      avoid_indexes.insert(fullc::kBias);  // bias
    }
  }
  if (idx.IsSumInputFloat()) {
    avoid_indexes.insert(idx.sum);
  }
  return avoid_indexes.count(index_to_check);
}

NNVM_REGISTER_OP(_sg_onednn_fully_connected)
    .add_alias("_sg_mkldnn_fully_connected")
    .describe(R"code(_sg_onednn_fully_connected)code" ADD_FILELINE)
    .set_num_inputs([](const NodeAttrs& attrs) {
      auto const& full_param = nnvm::get<DNNLFCFullParam>(attrs.parsed);
      return FCInputIndex(full_param).GetTotal();
    })
    .set_num_outputs([](const NodeAttrs& attrs) {
      auto const& full_param = nnvm::get<DNNLFCFullParam>(attrs.parsed);
      return (full_param.dnnl_param.quantized && !full_param.dnnl_param.enable_float_output) ? 3 :
                                                                                1;
    })
    .set_attr_parser(SgDNNLFCParamParser)
    .set_attr<nnvm::FListInputNames>("FListInputNames", SgDNNLFCListInputNames)
    .set_attr<nnvm::FListOutputNames>("FListOutputNames", SgDNNLFCListOutputNames)
    .set_attr<mxnet::FInferShape>("FInferShape", SgDNNLFCInferShape)
    .set_attr<nnvm::FInferType>("FInferType", SgDNNLFCInferType)
    .set_attr<FInferStorageType>("FInferStorageType", SgDNNLFCStorageType)
    .set_attr<FCreateOpState>("FCreateOpState", CreateSgDNNLFCState)
    .set_attr<FStatefulComputeEx>("FStatefulComputeEx<cpu>", SgDNNLFCForward)
    .set_attr<bool>("TIsDNNL", true)
    // TODO(Xinyu): a temp solution to enable GluonCV INT8 flow,
    // will be reverted after the improvement of CachedOP is done.
    .set_attr<nnvm::FGradient>("FGradient", MakeZeroGradNodes)
    .set_attr<FResourceRequest>("FResourceRequest",
                                [](const NodeAttrs& n) {
                                  return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
                                })
    .set_attr<nnvm::FMutateInputs>("FMutateInputs", DefaultSubgraphOpMutableInputs)
    .set_attr<std::string>("key_var_num_args", "num_args")
    .set_attr<nnvm::FInplaceOption>("FInplaceOption", SgDNNLFCInplaceOption)
    .set_attr<FQuantizable>("FQuantizable",
                            [](const NodeAttrs& attrs) { return QuantizeType::kMust; })
    .set_attr<FQuantizedOp>("FQuantizedOp", SgDNNLFCQuantizedOp)
    .set_attr<FNeedRequantize>("FNeedRequantize", [](const NodeAttrs& attrs) { return true; })
    .set_attr<FAvoidQuantizeInput>("FAvoidQuantizeInput", SgDNNLAvoidFCQuantizeInput);

}  // namespace op
}  // namespace mxnet

#endif  // if MXNET_USE_ONEDNN == 1


text:
using DevCamp.WebApp.Utils;
using DevCamp.WebApp.ViewModels;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace DevCamp.WebApp.Controllers
{
    //BASED ON THE SAMPLE https://azure.microsoft.com/en-us/documentation/articles/active-directory-v2-devquickstarts-dotnet-web/
    //AND https://github.com/microsoftgraph/aspnet-connect-rest-sample
    //AND https://github.com/microsoftgraph/aspnet-connect-sample <--DO NOT USE Uses MSAL Preview

    public class ProfileController : Controller
    {
        //Add telemetry
        private TelemetryClient telemetryClient = new TelemetryClient();

        // The URL that auth should redirect to after a successful login.
        Uri loginRedirectUri => new Uri(Url.Action(nameof(Index), "Profile", null, Request.Url.Scheme));
        // The URL to redirect to after a logout.
        Uri logoutRedirectUri => new Uri(Url.Action(nameof(Index), "Profile", null, Request.Url.Scheme));

        public void SignIn()
        {
            telemetryClient.TrackEvent("Sign in");

            if (!Request.IsAuthenticated)
            {
                // Signal OWIN to send an authorization request to Azure
                HttpContext.GetOwinContext().Authentication.Challenge(
                  new AuthenticationProperties { RedirectUri = "/" },
                  OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }
        }

        public void SignOut()
        {
            telemetryClient.TrackEvent("Sign out");

            if (Request.IsAuthenticated)
            {
                // Get the user's token cache and clear it
                string userObjId = System.Security.Claims.ClaimsPrincipal.Current
                  .FindFirst(Settings.AAD_OBJECTID_CLAIMTYPE).Value;

                SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);
                tokenCache.Clear();
            }
            // Send an OpenID Connect sign-out request.
            HttpContext.GetOwinContext().Authentication.SignOut(
              CookieAuthenticationDefaults.AuthenticationType);
            Response.Redirect("/");
        }

        [Authorize]
        //
        // GET: /UserProfile/
        public async Task<ActionResult> Index()
        {
            UserProfileViewModel userProfile = new UserProfileViewModel();
            try
            {
                string userObjId = System.Security.Claims.ClaimsPrincipal.Current.FindFirst(Settings.AAD_OBJECTID_CLAIMTYPE).Value;
                SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);

                string tenantId = System.Security.Claims.ClaimsPrincipal.Current.FindFirst(Settings.AAD_TENANTID_CLAIMTYPE).Value;
                string authority = string.Format(Settings.AAD_INSTANCE, tenantId, "");
                AuthHelper authHelper = new AuthHelper(authority, Settings.AAD_APP_ID, Settings.AAD_APP_SECRET, tokenCache);
                string accessToken = await authHelper.GetUserAccessToken(Url.Action("Index", "Home", null, Request.Url.Scheme));

                //#### TRACK A CUSTOM EVENT ####
                var profileProperties = new Dictionary<string, string> {{"userid", userObjId}, {"tenantid", tenantId}};
                telemetryClient.TrackEvent("View Profile", profileProperties);
                //#### TRACK A CUSTOM EVENT ####

                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    // New code:
                    HttpResponseMessage response = await client.GetAsync(Settings.GRAPH_CURRENT_USER_URL);
                    if (response.IsSuccessStatusCode)
                    {
                        string resultString = await response.Content.ReadAsStringAsync();

                        userProfile = JsonConvert.DeserializeObject<UserProfileViewModel>(resultString);
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.Error = "An error has occurred. Details: " + ex.Message;
                return View();
            }

            return View(userProfile);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace Leak.Networking.Core
{
    public interface NetworkConnection
    {
        long Identifier { get; }

        NetworkAddress Remote { get; }

        NetworkDirection Direction { get; }

        void Receive(NetworkIncomingMessageHandler handler);

        void Send(NetworkOutgoingMessage message);

        void Terminate();
    }
}


text:
package org.apache.bookkeeper.tools.cli.commands.bookie;

import com.beust.jcommander.Parameter;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.apache.bookkeeper.bookie.Bookie;
import org.apache.bookkeeper.bookie.BookieShell;
import org.apache.bookkeeper.client.BKException;
import org.apache.bookkeeper.client.BookKeeper;
import org.apache.bookkeeper.client.BookKeeperAdmin;
import org.apache.bookkeeper.client.UpdateLedgerOp;
import org.apache.bookkeeper.conf.ClientConfiguration;
import org.apache.bookkeeper.conf.ServerConfiguration;
import org.apache.bookkeeper.net.BookieSocketAddress;
import org.apache.bookkeeper.tools.cli.helpers.BookieCommand;
import org.apache.bookkeeper.tools.framework.CliFlags;
import org.apache.bookkeeper.tools.framework.CliSpec;
import org.apache.bookkeeper.util.MathUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Command to update ledger command.
 */
public class FlipBookieIdCommand extends BookieCommand<FlipBookieIdCommand.FlipBookieIdFlags> {

    static final Logger LOG = LoggerFactory.getLogger(FlipBookieIdCommand.class);

    private static final String NAME = "flip-bookie-id";
    private static final String DESC = "Update bookie id in ledgers (this may take a long time).";

    public FlipBookieIdCommand() {
        this(new FlipBookieIdFlags());
    }

    private FlipBookieIdCommand(FlipBookieIdFlags flags) {
        super(CliSpec.<FlipBookieIdFlags>newBuilder()
                  .withName(NAME)
                  .withDescription(DESC)
                  .withFlags(flags)
                  .build());
    }

    /**
     * Flags for update ledger command.
     */
    @Accessors(fluent = true)
    @Setter
    public static class FlipBookieIdFlags extends CliFlags {

        @Parameter(names = { "-host", "--hostname" },
            description = "Expects configuration useHostNameAsBookieID=true as the option value (default: ip address)")
        private boolean hostname;

        @Parameter(names = { "-s", "--updatepersec" },
            description = "Number of ledgers updating per second (default: 5 per sec)")
        private int updatePerSec = 5;

        @Parameter(names = {"-l", "--limit"},
            description = "Maximum number of ledgers of ledgers to update (default: no limit)")
        private int limit = Integer.MIN_VALUE;

        @Parameter(names = { "-v", "--verbose" }, description = "Print status of the ledger updation (default: false)")
        private boolean verbose;

        @Parameter(names = { "-p", "--printprogress" },
            description = "Print messages on every configured seconds if verbose turned on (default: 10 secs)")
        private long printProgress = 10;
    }

    @Override
    public boolean apply(ServerConfiguration conf, FlipBookieIdFlags cmdFlags) {
        try {
            return updateLedger(conf, cmdFlags);
        } catch (Exception e) {
            throw new UncheckedExecutionException(e.getMessage(), e);
        }
    }

    private boolean updateLedger(ServerConfiguration conf, FlipBookieIdFlags flags)
        throws InterruptedException, BKException, IOException {

        if (!conf.getUseHostNameAsBookieID() && flags.hostname) {
            LOG.error("Expects configuration useHostNameAsBookieID=true as the option value");
            return false;
        } else if (conf.getUseHostNameAsBookieID() && !flags.hostname) {
            LOG.error("Expects configuration useHostNameAsBookieID=false as the option value'");
            return false;
        }

        final int rate = flags.updatePerSec;
        if (rate <= 0) {
            LOG.error("Invalid updatespersec {}, should be > 0", rate);
            return false;
        }

        final int limit = flags.limit;
        if (limit <= 0 && limit != Integer.MIN_VALUE) {
            LOG.error("Invalid limit {}, should be > 0", limit);
            return false;
        }

        final long printProgress;
        if (flags.verbose) {
            printProgress = 10;
        } else {
            printProgress = flags.printProgress;
        }

        final ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.addConfiguration(conf);
        final BookKeeper bk = new BookKeeper(clientConfiguration);
        final BookKeeperAdmin admin = new BookKeeperAdmin(bk);
        final UpdateLedgerOp updateLedgerOp = new UpdateLedgerOp(bk, admin);
        final ServerConfiguration serverConfiguration = new ServerConfiguration(conf);
        final BookieSocketAddress newBookieId = Bookie.getBookieAddress(serverConfiguration);
        serverConfiguration.setUseHostNameAsBookieID(!flags.hostname);
        final BookieSocketAddress oldBookieId = Bookie.getBookieAddress(serverConfiguration);

        BookieShell.UpdateLedgerNotifier progressable = new BookieShell.UpdateLedgerNotifier() {
            long lastReport = System.nanoTime();

            @Override
            public void progress(long updated, long issued) {
                if (printProgress <= 0) {
                    return; // disabled
                }
                if (TimeUnit.MILLISECONDS.toSeconds(MathUtils.elapsedMSec(lastReport)) >= printProgress) {
                    LOG.info("Number of ledgers issued={}, updated={}", issued, updated);
                    lastReport = MathUtils.nowInNano();
                }
            }
        };

        try {
            updateLedgerOp.updateBookieIdInLedgers(oldBookieId, newBookieId, rate, limit, progressable);
        } catch (IOException e) {
            LOG.error("Failed to update ledger metadata", e);
            return false;
        }

        return true;
    }
}


text:
set -e
case $CIRCLE_NODE_INDEX in
0) docker run --rm -e NOTARY_BUILDTAGS=pkcs11 --env-file buildscripts/env.list --user notary notary_client bash -c "make ci && codecov"
   ;;
1) docker run --rm -e NOTARY_BUILDTAGS=none --env-file buildscripts/env.list --user notary notary_client bash -c "make ci && codecov"
   ;;
2) SKIPENVCHECK=1 make TESTDB=mysql integration
   ;;
3) SKIPENVCHECK=1 make TESTDB=rethink integration
   ;;
4) docker run --rm -e NOTARY_BUILDTAGS=pkcs11 notary_client make vet lint fmt misspell
   ;;
esac


text:
package de.gishmo.mvp4g.example.multipresenterwithhistorie.client.ui.toolbar;

import com.google.inject.Inject;
import com.mvp4g.client.annotation.Presenter;
import com.mvp4g.client.presenter.BasePresenter;

import de.gishmo.mvp4g.example.multipresenterwithhistorie.client.Mvp4gMultiPresenterWithHistorieEventBus;
import de.gishmo.mvp4g.example.multipresenterwithhistorie.client.model.ApplicationContext;

@Presenter(view = IToolbarView.class)
public final class ToolbarPresenter
  extends BasePresenter<IToolbarView, Mvp4gMultiPresenterWithHistorieEventBus>
  implements IToolbarView.Presenter {

  @Inject
  private ApplicationContext applicationContext;

  @Override
  public void bind() {
    eventBus.setToolbar(view.asWidget());
  }

  @Override
  public void doAdd() {
    eventBus.newPerson();
  }
}


text:
FROM openjdk
MAINTAINER Ryan Ratcliff <ryan.ratcliff@ryanratcliff.net>
ENV refreshed_at 2019-02-06

RUN mkdir /opt/dynamodb_local
RUN mkdir /var/dynamodb_data
RUN wget -q -O - https://s3-us-west-2.amazonaws.com/dynamodb-local/dynamodb_local_2019-02-04.tar.gz | tar -xzf - -C /opt/dynamodb_local

WORKDIR /opt/dynamodb_local
VOLUME ["/var/dynamodb_data"]
EXPOSE 8000

ENTRYPOINT ["/usr/bin/java", "-Djava.library.path=/opt/dynamodb_local/DynamoDBLocal_lib", "-jar", "DynamoDBLocal.jar", "-sharedDb", "-dbPath", "/var/dynamodb_data"]


text:
#import "DVTSourceModel.h"

@interface DVTSourceModel (IBDVTSourceModelAdditions)
- (id)sourceModelInfoForSourceModelItem:(id)arg1 matchingSourceModelItemContextMask:(unsigned long long)arg2;
- (id)sourceModelInfoForBindingObjCPropertyContextItem:(id)arg1;
- (id)sourceModelInfoForBindingObjCInstanceVariableContextItem:(id)arg1;
- (id)firstSourceModelItemOccurringBeforeRange:(struct _NSRange)arg1 fromSourceModelItem:(id)arg2;
- (id)extendedTypeNameFromSourceModelItem:(id)arg1 range:(struct _NSRange *)arg2;
- (id)sourceModelInfoForObjCInstanceVariableOutletContextItem:(id)arg1;
- (id)sourceModelInfoForObjCPropertyOutletContextItem:(id)arg1;
- (id)sourceModelInfoForObjCInstanceVariableOutletCollectionContextItem:(id)arg1;
- (id)sourceModelInfoForObjCPropertyOutletCollectionContextItem:(id)arg1;
- (id)sourceModelInfoForActionContextItem:(id)arg1 languageSpecification:(id)arg2;
- (BOOL)sourceModelItemHasDescendantIBActionItem:(id)arg1;
@end


text:
import {Injectable} from "@angular/core";

import "rxjs/add/operator/catch";
import "rxjs/add/operator/map";

import {HttpOAuthService} from "../shared/http-oauth.service";
import {CrudService} from "./base/crud.service";
import {ImportModel} from "../model/full/import-model";
import {ImportBriefModel} from "../model/brief/import-brief-model";

@Injectable()
export class ImportService extends CrudService<ImportModel, ImportBriefModel> {

    constructor(http: HttpOAuthService) {
        super(http, '/api/import');
    }
}


text:
What is ClassNet Web App
###################

ClassNet Web App is a web enviroment that pull out information from the Class.Net system(developed by Infospeed) into a Web App accessible by a simple web-login.

###################
Under Development
###################


text:
<?xml version="1.0" encoding="UTF-8"?>
<deploy
 date="2018.01.09.14:30:02"
 outputDirectory="/home/tianzhao/quartus_17_fringe_ref/a10_soc_devkit_ghrd/ip/ghrd_10as066n2/ghrd_10as066n2_ILC/">
 <perimeter>
  <parameter
     name="AUTO_GENERATION_ID"
     type="Integer"
     defaultValue="0"
     onHdl="0"
     affectsHdl="1" />
  <parameter
     name="AUTO_UNIQUE_ID"
     type="String"
     defaultValue=""
     onHdl="0"
     affectsHdl="1" />
  <parameter
     name="AUTO_DEVICE_FAMILY"
     type="String"
     defaultValue="Arria 10"
     onHdl="0"
     affectsHdl="1" />
  <parameter
     name="AUTO_DEVICE"
     type="String"
     defaultValue="10AS066N3F40E2SG"
     onHdl="0"
     affectsHdl="1" />
  <parameter
     name="AUTO_DEVICE_SPEEDGRADE"
     type="String"
     defaultValue="2"
     onHdl="0"
     affectsHdl="1" />
  <parameter
     name="AUTO_CLK_CLOCK_RATE"
     type="Long"
     defaultValue="-1"
     onHdl="0"
     affectsHdl="1" />
  <parameter
     name="AUTO_CLK_CLOCK_DOMAIN"
     type="Integer"
     defaultValue="-1"
     onHdl="0"
     affectsHdl="1" />
  <parameter
     name="AUTO_CLK_RESET_DOMAIN"
     type="Integer"
     defaultValue="-1"
     onHdl="0"
     affectsHdl="1" />
  <parameter
     name="AUTO_IRQ_INTERRUPTS_USED"
     type="BigInteger"
     defaultValue="-1"
     onHdl="0"
     affectsHdl="1" />
  <interface name="avalon_slave" kind="avalon" start="0">
   <property name="addressAlignment" value="DYNAMIC" />
   <property name="addressGroup" value="0" />
   <property name="addressSpan" value="256" />
   <property name="addressUnits" value="WORDS" />
   <property name="alwaysBurstMaxBurst" value="false" />
   <property name="associatedClock" value="clk" />
   <property name="associatedReset" value="reset_n" />
   <property name="bitsPerSymbol" value="8" />
   <property name="bridgedAddressOffset" value="0" />
   <property name="bridgesToMaster" value="" />
   <property name="burstOnBurstBoundariesOnly" value="false" />
   <property name="burstcountUnits" value="WORDS" />
   <property name="constantBurstBehavior" value="false" />
   <property name="explicitAddressSpan" value="0" />
   <property name="holdTime" value="0" />
   <property name="interleaveBursts" value="false" />
   <property name="isBigEndian" value="false" />
   <property name="isFlash" value="false" />
   <property name="isMemoryDevice" value="false" />
   <property name="isNonVolatileStorage" value="false" />
   <property name="linewrapBursts" value="false" />
   <property name="maximumPendingReadTransactions" value="0" />
   <property name="maximumPendingWriteTransactions" value="0" />
   <property name="minimumReadLatency" value="1" />
   <property name="minimumResponseLatency" value="1" />
   <property name="minimumUninterruptedRunLength" value="1" />
   <property name="prSafe" value="false" />
   <property name="printableDevice" value="false" />
   <property name="readLatency" value="1" />
   <property name="readWaitStates" value="0" />
   <property name="readWaitTime" value="0" />
   <property name="registerIncomingSignals" value="false" />
   <property name="registerOutgoingSignals" value="false" />
   <property name="setupTime" value="0" />
   <property name="timingUnits" value="Cycles" />
   <property name="transparentBridge" value="false" />
   <property name="waitrequestAllowance" value="0" />
   <property name="wellBehavedWaitrequest" value="false" />
   <property name="writeLatency" value="0" />
   <property name="writeWaitStates" value="0" />
   <property name="writeWaitTime" value="0" />
   <port name="avmm_addr" direction="input" role="address" width="6" />
   <port name="avmm_wrdata" direction="input" role="writedata" width="32" />
   <port name="avmm_write" direction="input" role="write" width="1" />
   <port name="avmm_read" direction="input" role="read" width="1" />
   <port name="avmm_rddata" direction="output" role="readdata" width="32" />
  </interface>
  <interface name="clk" kind="clock" start="0">
   <property name="clockRate" value="0" />
   <property name="externallyDriven" value="false" />
   <property name="ptfSchematicName" value="" />
   <port name="clk" direction="input" role="clk" width="1" />
  </interface>
  <interface name="irq" kind="interrupt" start="1">
   <property name="associatedAddressablePoint" value="" />
   <property name="associatedClock" value="clk" />
   <property name="associatedReset" value="reset_n" />
   <property name="irqMap" value="" />
   <property name="irqScheme" value="INDIVIDUAL_REQUESTS" />
   <port name="irq" direction="input" role="irq" width="2" />
  </interface>
  <interface name="reset_n" kind="reset" start="0">
   <property name="associatedClock" value="clk" />
   <property name="synchronousEdges" value="DEASSERT" />
   <port name="reset_n" direction="input" role="reset_n" width="1" />
  </interface>
 </perimeter>
 <entity kind="ghrd_10as066n2_ILC" version="1.0" name="ghrd_10as066n2_ILC">
  <parameter name="AUTO_CLK_CLOCK_RATE" value="-1" />
  <parameter name="AUTO_IRQ_INTERRUPTS_USED" value="-1" />
  <parameter name="AUTO_GENERATION_ID" value="0" />
  <parameter name="AUTO_DEVICE" value="10AS066N3F40E2SG" />
  <parameter name="AUTO_DEVICE_FAMILY" value="Arria 10" />
  <parameter name="AUTO_CLK_RESET_DOMAIN" value="-1" />
  <parameter name="AUTO_CLK_CLOCK_DOMAIN" value="-1" />
  <parameter name="AUTO_UNIQUE_ID" value="" />
  <parameter name="AUTO_DEVICE_SPEEDGRADE" value="2" />
  <generatedFiles>
   <file
       path="/home/tianzhao/quartus_17_fringe_ref/a10_soc_devkit_ghrd/ip/ghrd_10as066n2/ghrd_10as066n2_ILC/synth/ghrd_10as066n2_ILC.v"
       attributes="CONTAINS_INLINE_CONFIGURATION" />
  </generatedFiles>
  <childGeneratedFiles>
   <file
       path="/home/tianzhao/quartus_17_fringe_ref/a10_soc_devkit_ghrd/ip/ghrd_10as066n2/ghrd_10as066n2_ILC/synth/ghrd_10as066n2_ILC.v"
       attributes="CONTAINS_INLINE_CONFIGURATION" />
  </childGeneratedFiles>
  <sourceFiles>
   <file
       path="/home/tianzhao/quartus_17_fringe_ref/a10_soc_devkit_ghrd/ip/ghrd_10as066n2/ghrd_10as066n2_ILC.ip" />
  </sourceFiles>
  <childSourceFiles>
   <file
       path="/opt/intelFPGA_pro/17.1/ip/altera/altera_interrupt_latency_calculator/interrupt_latency_counter_hw.tcl" />
  </childSourceFiles>
  <messages>
   <message level="Info" culprit="ghrd_10as066n2_ILC">"Generating: ghrd_10as066n2_ILC"</message>
   <message level="Info" culprit="ghrd_10as066n2_ILC">"Generating: interrupt_latency_counter"</message>
  </messages>
 </entity>
 <entity
   kind="interrupt_latency_counter"
   version="17.1"
   name="interrupt_latency_counter">
  <parameter name="CLOCK_RATE" value="100000000" />
  <parameter name="INTR_TYPE" value="0" />
  <parameter name="IRQ_PORT_CNT" value="2" />
  <generatedFiles>
   <file
       path="/home/tianzhao/quartus_17_fringe_ref/a10_soc_devkit_ghrd/ip/ghrd_10as066n2/ghrd_10as066n2_ILC/interrupt_latency_counter_171/synth/interrupt_latency_counter.v"
       attributes="TOP_LEVEL_FILE" />
   <file
       path="/home/tianzhao/quartus_17_fringe_ref/a10_soc_devkit_ghrd/ip/ghrd_10as066n2/ghrd_10as066n2_ILC/interrupt_latency_counter_171/synth/irq_detector.v"
       attributes="" />
   <file
       path="/home/tianzhao/quartus_17_fringe_ref/a10_soc_devkit_ghrd/ip/ghrd_10as066n2/ghrd_10as066n2_ILC/interrupt_latency_counter_171/synth/state_machine_counter.v"
       attributes="" />
  </generatedFiles>
  <childGeneratedFiles>
   <file
       path="/home/tianzhao/quartus_17_fringe_ref/a10_soc_devkit_ghrd/ip/ghrd_10as066n2/ghrd_10as066n2_ILC/interrupt_latency_counter_171/synth/interrupt_latency_counter.v"
       attributes="TOP_LEVEL_FILE" />
   <file
       path="/home/tianzhao/quartus_17_fringe_ref/a10_soc_devkit_ghrd/ip/ghrd_10as066n2/ghrd_10as066n2_ILC/interrupt_latency_counter_171/synth/irq_detector.v"
       attributes="" />
   <file
       path="/home/tianzhao/quartus_17_fringe_ref/a10_soc_devkit_ghrd/ip/ghrd_10as066n2/ghrd_10as066n2_ILC/interrupt_latency_counter_171/synth/state_machine_counter.v"
       attributes="" />
  </childGeneratedFiles>
  <sourceFiles>
   <file
       path="/opt/intelFPGA_pro/17.1/ip/altera/altera_interrupt_latency_calculator/interrupt_latency_counter_hw.tcl" />
  </sourceFiles>
  <childSourceFiles/>
  <instantiator instantiator="ghrd_10as066n2_ILC" as="ILC" />
  <messages>
   <message level="Info" culprit="ghrd_10as066n2_ILC">"Generating: interrupt_latency_counter"</message>
  </messages>
 </entity>
</deploy>


text:
<TITLE>Review for Railway Children, The (1970)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Railway Children, The (1970)

reviewed by
Shane Burridge

                              THE RAILWAY CHILDREN
                       A film review by Shane R. Burridge
                        Copyright 1996 Shane R. Burridge

The Railway Children (1970) 108m.

Heartwarming film written and directed by character actor Lionel
Jeffries from E. Nesbitt's novel.  It may remind you in spirit of
Julio Cortazar's beautiful short story `The End of the Game'.  Set at
the turn of the century, story relates adventures of three Edwardian
children who move to a country house in Yorkshire after their father
is mysteriously taken away by police.  As their mother refuses to
inform the children of the exact nature of their circumstances, the
country retreat, with its stone cottages and buttercup fields, becomes
a kind of balmy, nostalgic limbo.  It's an inbetween world where the
children must while away the hours until their father's return - if,
in fact, he will return.  Reason this classic is so popular must
surely be because of its prewar innocence that yet manages to capture
elements of what it was like for urban and suburban Britons during the
Blitz:  there are children being relocated into the country by
railway; a father absent from home on "government business"; a brave
mother making do; a family playing at "being poor".  This strong sense
of reminiscence is established right from frame one - in the first few
minutes of the film we see the camera pan lovingly over mementoes and
trinkets; we see a photograph being taken, a Christmas dinner, a
spinning zoetrope, a panto performance of Peter Pan - and while it is
all rather sentimental, it never becomes mawkish.

It's wonderful how Jeffries creates an idyllic world that is entirely
plausible, a world where strangers are kind and one good deed always
deserves another.  His splendid work is more than matched by a
sterling cast.  You'll really want to spend more time with these
children and share their adventures - from the older sister Bobby
(Jenny Agutter, who has as much poise at 16 in a middy blouse or a
pinafore than she would as an adult), the younger sister Phyllis (A
cheerful, brunette Sally Thomsett, who would later find fame as the
dippy blonde Jo in the sitcom MAN ABOUT THE HOUSE, and was actually
older than Agutter), and brother Peter (Gary Warren, who starred in
the cult children's BBC serial CATWEAZLE).  Their performances are
matched equally by the adults Dinah Sheridan and most notably Bernard
Cribbins as a humble-yet-proud stationmaster.

This film has such a generous, humane spirit to it that you may feel
your eyes mist over during several occasions.  The finale is a
guaranteed tearjerker, but I always get a lump in my throat at the
very end when Agutter softly tells the audience "Goodbye", knowing
that she could not realize she was well on the way to becoming a
celebrated and popular actress in the film industry.  THE RAILWAY
CHILDREN probably works even better now than it did then in 1970, as
the nostalgia it evokes for those times works in tandem with the
nostaliga of the story itself.  They don't make films like this
anymore.  William Mervyn, as a train-travelling old gentlemen, sums it
up in one word.  "Charming....charming!"   Footnote:  Agutter,
Thomsett, and their screen father Iain Cuthbertson were reunited a
quarter-century later when the British Film Institute brought them
back together to a cheering crowd at the Yorkshire Station, whereupon
their film was commemorated with a special plaque.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
=begin

=end
require "optparse"
require_relative 'yadisk_api'

class YadiskCli
  def initialize login, pass, location
    @yadisk = YadiskApi.new login, pass, location
    @cli = {}

    @global = OptionParser.new do |opts|
      opts.banner = "Command-line tool for working with Yandex.Disk\n"
      opts.banner += "Copyright (c) 2014 Zhussupov Zhassulan zhzhussupovkz@gmail.com\n"
      opts.banner += "Commonly used command are:\n
      upload : Upload file to the Yandex.Disk\n
      download : Download file from the Yandex.Disk\n
      create: Create directory in the Yandex.Disk\n
      del: Delete file or directory from the Yandex.Disk\n
      copy: Copy file or directory on the Yandex.Disk\n
      move: Move file or directory on the Yandex.Disk\n
      space: Get free and available space on the Yandex.Disk\n
      list: List of files on the Yandex.Disk\n
      share: Share file or directory from the Yandex.Disk\n
      private: Set private file or directory from the Yandex.Disk\n
      preview: Get image preview from the Yandex.Disk\n
      See 'run.rb COMMAND --help' for more information on a specific command.\n"
    end

    @commands = {

      #download files from server
      'download' =>  OptionParser.new do |opts|
        opts.banner = "Download file from Yandex.Disk\n"

        opts.on('-h', '--help', "help page") do
          puts opts
          exit
        end

        opts.on('-i', '--input FILENAME', "Filename from Yandex.Disk") do |o|
          cli[:file] = o
        end

        opts.on('-o', '--output FILENAME', "Output filename Yandex.Disk") do |o|
          cli[:output] = o
        end
      end,

      #upload files to the server
      'upload' =>  OptionParser.new do |opts|
        opts.banner = "Upload file to the Yandex.Disk\n"

        opts.on('-h', '--help', "help page") do
          puts opts
          exit
        end

        opts.on('-f', '--file FILENAME', "Local file name Yandex.Disk") do |o|
          cli[:file] = o
        end

        opts.on('-d', '--dir FILENAME', "Directory name from the Yandex.Disk") do |o|
          cli[:dir] = o
        end
      end,

      #create directory in the server
      'create' =>  OptionParser.new do |opts|
        opts.banner = "Create directory in the Yandex.Disk\n"

        opts.on('-h', '--help', "help page") do
          puts opts
          exit
        end

        opts.on('-d', '--dir DIRECTORY', "Directory name for create in Yandex.Disk") do |o|
          cli[:dir] = o
        end
      end,

      #delete directory from the server
      'del' =>  OptionParser.new do |opts|
        opts.banner = "Delete directory or file from the Yandex.Disk\n"

        opts.on('-h', '--help', "help page") do
          puts opts
          exit
        end

        opts.on('-d', '--dir DIRECTORY', "Directory name for delete in Yandex.Disk") do |o|
          cli[:dir] = o
        end
      end,

      #copy files and directories in the server
      'copy' =>  OptionParser.new do |opts|
        opts.banner = "Copy directory or file in the Yandex.Disk\n"

        opts.on('-h', '--help', "help page") do
          puts opts
          exit
        end

        opts.on('-f', '--from FILENAME', "File or directory name from Yandex.Disk") do |o|
          cli[:from] = o
        end

        opts.on('-t', '--to FILENAME', "Destination filename Yandex.Disk") do |o|
          cli[:to] = o
        end
      end,

      #move files and directories in the server
      'move' =>  OptionParser.new do |opts|
        opts.banner = "Move directory or file in the Yandex.Disk\n"

        opts.on('-h', '--help', "help page") do
          puts opts
          exit
        end

        opts.on('-f', '--from FILENAME', "File or directory name from Yandex.Disk") do |o|
          cli[:from] = o
        end

        opts.on('-t', '--to FILENAME', "Destination filename Yandex.Disk") do |o|
          cli[:to] = o
        end
      end,

      #list of files and directories
      'list' =>  OptionParser.new do |opts|
        opts.banner = "List of files and directories from the Yandex.Disk\n"

        opts.on('-h', '--help', "help page") do
          puts opts
          exit
        end

        opts.on('-d', '--dir FILENAME', "File or directory name from Yandex.Disk") do |o|
          cli[:dir] = o
        end

        opts.on('-a', '--amount INT', "Amount parameter for pagination list Yandex.Disk") do |o|
          cli[:amount] = o
        end

        opts.on('-o', '--offset INT', "Offset parameter for pagination list Yandex.Disk") do |o|
          cli[:offset] = o
        end
      end,

      #share folder or file from the server
      'share' =>  OptionParser.new do |opts|
        opts.banner = "Share directory of file from the Yandex.Disk\n"

        opts.on('-h', '--help', "help page") do
          puts opts
          exit
        end

        opts.on('-d', '--dir DIRECTORY', "Directory or file name for share in Yandex.Disk") do |o|
          cli[:dir] = o
        end
      end,

      #set private folder or file from the server
      'private' =>  OptionParser.new do |opts|
        opts.banner = "Set private directory of file from the Yandex.Disk\n"

        opts.on('-h', '--help', "help page") do
          puts opts
          exit
        end

        opts.on('-d', '--dir DIRECTORY', "Directory or file name for setting private in Yandex.Disk") do |o|
          cli[:dir] = o
        end
      end,

      #get image preview from the server
      'preview' =>  OptionParser.new do |opts|
        opts.banner = "Get image preview and download from the Yandex.Disk\n"

        opts.on('-h', '--help', "help page") do
          puts opts
          exit
        end

        opts.on('-f', '--file FILENAME', "Filename for preview from Yandex.Disk. For images only.") do |o|
          cli[:file] = o
        end

        opts.on('-s', '--size SIZE', "Image size from Yandex.Disk") do |o|
          cli[:size] = o
        end
      end
    }
    global.order!
  end

  attr_accessor :cli, :commands, :global
  attr_reader :yadisk, :main

  #rum cli tool
  def run
    cmd = ARGV.shift
    if cmd.nil?
      puts global
      exit
    end
    commands[cmd].order!
    case cmd
    when 'upload'
      yadisk.upload_file options = cli
    when 'download'
      yadisk.download_file cli
    when 'create'
      yadisk.mkdir options = cli
    when 'del'
      yadisk.rm cli
    when 'copy'
      yadisk.copy cli
    when 'move'
      yadisk.move cli
    when 'space'
      yadisk.get_space
    when 'list'
      dir = cli[:dir] || '/'
      cli.delete(:dir)
      yadisk.get_list dir, cli
    when 'share'
      yadisk.share cli
    when 'private'
      yadisk.set_private cli
    when 'preview'
      yadisk.image_preview options = cli
    end
  end

end


text:
"""
Test 'destroy'.
"""

# isort: FIRSTPARTY
from dbus_client_gen import DbusClientUniqueResultError

# isort: LOCAL
from stratis_cli import StratisCliErrorCodes
from stratis_cli._errors import StratisCliEngineError

from .._misc import RUNNER, TEST_RUNNER, SimTestCase, device_name_list

_DEVICE_STRATEGY = device_name_list(1)
_ERROR = StratisCliErrorCodes.ERROR

class Destroy1TestCase(SimTestCase):
    """
    Test 'destroy' on empty database.

    'destroy' should always fail if pool is missing.
    """

    _MENU = ["--propagate", "pool", "destroy"]
    _POOLNAME = "deadpool"

    def test_execution(self):
        """
        Destroy should fail because there is no object path for the pool.
        """
        command_line = self._MENU + [self._POOLNAME]
        self.check_error(DbusClientUniqueResultError, command_line, _ERROR)

class Destroy2TestCase(SimTestCase):
    """
    Test 'destroy' on database which contains the given pool.
    """

    _MENU = ["--propagate", "pool", "destroy"]
    _POOLNAME = "deadpool"

    def setUp(self):
        """
        Start the stratisd daemon with the simulator.
        """
        super().setUp()
        command_line = ["pool", "create", self._POOLNAME] + _DEVICE_STRATEGY()
        RUNNER(command_line)

    def test_execution(self):
        """
        The pool was just created, so must be destroyable.
        """
        command_line = self._MENU + [self._POOLNAME]
        TEST_RUNNER(command_line)

class Destroy3TestCase(SimTestCase):
    """
    Test 'destroy' on database which contains the given pool with a volume.
    """

    _MENU = ["--propagate", "pool", "destroy"]
    _POOLNAME = "deadpool"
    _VOLNAME = "vol"

    def setUp(self):
        """
        Start the stratisd daemon with the simulator.
        """
        super().setUp()
        command_line = ["pool", "create", self._POOLNAME] + _DEVICE_STRATEGY()
        RUNNER(command_line)

        command_line = ["filesystem", "create", self._POOLNAME, self._VOLNAME]
        RUNNER(command_line)

    def test_execution(self):
        """
        This should fail since it has a filesystem.
        """
        command_line = self._MENU + [self._POOLNAME]
        self.check_error(StratisCliEngineError, command_line, _ERROR)

    def test_with_filesystem_removed(self):
        """
        This should succeed since the filesystem is removed first.
        """
        command_line = ["filesystem", "destroy", self._POOLNAME, self._VOLNAME]
        RUNNER(command_line)
        command_line = self._MENU + [self._POOLNAME]
        TEST_RUNNER(command_line)


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mém. Soc. Émul. Montbéliard, Sér. 2 5: 123 (1872)

#### Original name
Agaricus hiascens Fr., 1821

### Remarks
null


text:
package org.vastness.bukkit.teclp.embedded;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.vastness.bukkit.teclp.teclp;
import org.vastness.bukkit.teclp.tectonicus.TectonicusConfig;

public class WorldDataServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private final teclp plugin;
    public WorldDataServlet(final teclp plugin){
        this.plugin = plugin;
    }

    protected void doGet (final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException
    {
       final String world = request.getParameter("world");
       final String json = createJson(world);

       response.setContentType("text/javascript");
       response.setStatus(HttpServletResponse.SC_OK);
       response.getWriter().print(json);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    private String createJson(String worldName){
        World world = null;
        if (worldName == null){
            world = plugin.getServer().getWorlds().get(0);
            worldName = world.getName();
        }else{

            world = plugin.getServer().getWorld(worldName);
            if (world == null){
                world = plugin.getServer().getWorlds().get(0);
                worldName = world.getName();
            }
        }
        final Map jsonObj = new LinkedHashMap();
        jsonObj.put("worlds", getWorlds() );
        jsonObj.put("name", worldName);
        jsonObj.put("spawn", getSpawn(world));
        jsonObj.put("tectonicus", getTectonicusConf());
        jsonObj.put("time", new Long(world.getTime()));
        jsonObj.put("players", getPlayers(world));
        jsonObj.put("specialplaces", getSpecialPlaces());
        jsonObj.put("wgregions", getWgRegions(worldName));
        return JSONValue.toJSONString(jsonObj);

    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    private Map getTectonicusConf() {
        final Map data = new LinkedHashMap();
        final TectonicusConfig tecConfig = TectonicusConfig.getInstance();
        data.put("tiletype", tecConfig.getTileType());
        data.put("showspawn", tecConfig.isShowSpawn());
        data.put("maxzoom", new Integer(tecConfig.getMaxZoom()));
        data.put("signsinitiallyvisible", new Boolean(tecConfig.isSignsInitiallyVisible()));
        data.put("playersinitiallyvisible", new Boolean(tecConfig.isPlayersInitiallyVisible()));
        data.put("placesinitiallyvisible", new Boolean(tecConfig.isPlacesInitiallyVisible()));
        data.put("pybukkitwebenabled", new Boolean(tecConfig.isPyBukkitWebEnabled()));
        data.put("chatenabled", new Boolean(tecConfig.isChatEnabled()));
        data.put("regionssinitiallyvisible", new Boolean(tecConfig.isRegionsInitiallyVisible()));
        return data;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    private Map getSpawn(final World world) {
        final Map data = new LinkedHashMap();
        final Location loc = world.getSpawnLocation();
        data.put("x", new Integer(loc.getBlockX()));
        data.put("y", new Integer(loc.getBlockY()));
        data.put("z", new Integer(loc.getBlockZ()));
        return data;
    }

    @SuppressWarnings("rawtypes")
    private Map getWgRegions(final String worldName) {
        final JSONParser json = new JSONParser();
        Map data;
        try{
            data = (Map) json.parse(new FileReader(new File("plugins/WorldGuard/"+worldName+".regions.json")));
        } catch (final Exception e){
            data = new LinkedHashMap();
            //TODO
        }
        return data;
    }

    @SuppressWarnings({ "rawtypes" })
    private Map getSpecialPlaces() {
        final Map data = new LinkedHashMap();
        return data;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    private Map getPlayers(World world) {
        List<Player> players =world.getPlayers();
        Map data = new LinkedHashMap();
        for (Player player : players){
            data.put(player.getName(), getPlayer(player));
        }
        return data;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    private Map getPlayer(Player player) {
        Map data = new LinkedHashMap();
        data.put("health", new Integer(player.getHealth()));
        data.put("air", new Integer(player.getRemainingAir()));
        data.put("money", new Double(0.0)); //TODO

        final Location loc = player.getLocation();
        final Map positionMap = new LinkedHashMap<String, Integer>();
        positionMap.put("x", new Integer(loc.getBlockX()));
        positionMap.put("y", new Integer(loc.getBlockY()));
        positionMap.put("z", new Integer(loc.getBlockZ()));

        data.put("position", positionMap);

        final Map inventory = new LinkedHashMap<String, Integer>();
        final PlayerInventory pInv = player.getInventory();
        final ItemStack[] stack = pInv.getContents();
        for(int i = 0; i < stack.length; i++){
            inventory.put(new Integer(stack[i].getTypeId()).toString(), new Integer(stack[i].getAmount()));
        }

        data.put("inventory", inventory);
        data.put("permissions", null);//TODO
        return data;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    private Map getWorlds() {
        final List<World> worldList = plugin.getServer().getWorlds();
        final Map data = new LinkedHashMap<String, Integer>();
        for (final World world : worldList ){
            data.put(world.getName(), new Integer(worldList.indexOf(world)));
        }
        return data;
    }

}


text:
#pragma once
#include <aws/wafv2/WAFV2_EXPORTS.h>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace WAFV2
{
namespace Model
{
  class AWS_WAFV2_API DisassociateWebACLResult
  {
  public:
    DisassociateWebACLResult();
    DisassociateWebACLResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    DisassociateWebACLResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

  };

} // namespace Model
} // namespace WAFV2
} // namespace Aws


text:
<?php
namespace AuthorBooks\Model;

require_once __DIR__ . '/BookSchemaProxy.php';
use Maghead\Schema\SchemaLoader;
use Maghead\Result;
use Maghead\Inflator;
use Magsql\Bind;
use Magsql\ArgumentArray;
use PDO;
use Magsql\Universal\Query\InsertQuery;
use Maghead\Runtime\Repo;

class BookRepo extends Repo
{
    const SCHEMA_CLASS = 'AuthorBooks\\Model\\BookSchema';
    const SCHEMA_PROXY_CLASS = 'AuthorBooks\\Model\\BookSchemaProxy';
    const COLLECTION_CLASS = 'AuthorBooks\\Model\\BookCollection';
    const MODEL_CLASS = 'AuthorBooks\\Model\\Book';
    const TABLE = 'books';
    const READ_SOURCE_ID = 'default';
    const WRITE_SOURCE_ID = 'default';
    const PRIMARY_KEY = 'id';
    const TABLE_ALIAS = 'm';
    const FIND_BY_PRIMARY_KEY_SQL = 'SELECT * FROM books WHERE id = ? LIMIT 1';
    const DELETE_BY_PRIMARY_KEY_SQL = 'DELETE FROM books WHERE id = ?';
    public static $columnNames = array(
      0 => 'id',
      1 => 'title',
      2 => 'subtitle',
      3 => 'isbn',
      4 => 'description',
      5 => 'view',
      6 => 'published',
      7 => 'publisher_id',
      8 => 'published_at',
      9 => 'is_hot',
      10 => 'is_selled',
    );
    public static $columnHash = array(
      'id' => 1,
      'title' => 1,
      'subtitle' => 1,
      'isbn' => 1,
      'description' => 1,
      'view' => 1,
      'published' => 1,
      'publisher_id' => 1,
      'published_at' => 1,
      'is_hot' => 1,
      'is_selled' => 1,
    );
    public static $mixinClasses = array(
    );
    protected $table = 'books';
    protected $findStm;
    protected $deleteStm;
    protected $findByIsbnStm;
    public static function getSchema()
    {
        static $schema;
        if ($schema) {
            return $schema;
        }
        return $schema = new \AuthorBooks\Model\BookSchemaProxy;
    }
    public function find($pkId)
    {
        if (!$this->findStm) {
            $this->findStm = $this->read->prepare(self::FIND_BY_PRIMARY_KEY_SQL);
            $this->findStm->setFetchMode(PDO::FETCH_CLASS, 'AuthorBooks\Model\Book');
        }
        return static::_stmFetch($this->findStm, [$pkId]);
    }
    public function findByIsbn($value)
    {
        if (!isset($this->findByIsbnStm)) {
            $this->findByIsbnStm = $this->read->prepare('SELECT * FROM books WHERE isbn = :isbn LIMIT 1');
            $this->findByIsbnStm->setFetchMode(PDO::FETCH_CLASS, \AuthorBooks\Model\Book);
        }
        return static::_stmFetch($this->findByIsbnStm, [':isbn' => $value ]);
    }
    public function deleteByPrimaryKey($pkId)
    {
        if (!$this->deleteStm) {
            $this->deleteStm = $this->write->prepare(self::DELETE_BY_PRIMARY_KEY_SQL);
        }
        return $this->deleteStm->execute([$pkId]);
    }
}


text:
<mat-card>

    <mat-card-content>

        <ng-template [tdLoading]="loadName" tdLoadingStrategy="overlay">

        <form #editform="ngForm"  id="editform" flex (ngSubmit)="editform.submitted && editform.valid && submitForm(editform)" novalidate>
            <input type="submit" #btnSubmit hidden id="btnSubmit" name="btnSubmit" value="" />

            <mat-form-field>
              <input matInput #name flex name="name" [(ngModel)]="itemEdit.name" required placeholder="Name" maxlength="150" />
              <mat-hint align="end">{{name.value.length}} / 150</mat-hint>
            </mat-form-field>
            <mat-form-field>
              <input matInput #description flex name="description" [(ngModel)]="itemEdit.description" required placeholder="Description"
                maxlength="150">
              <mat-hint align="end">{{description.value.length}} / 150</mat-hint>
            </mat-form-field>
            <mat-form-field>
              <input matInput #rootFolder flex name="rootFolder" [(ngModel)]="itemEdit.rootFolder" required placeholder="Root Folder name"
                maxlength="150">
              <mat-hint align="end">{{rootFolder.value.length}} / 150</mat-hint>
            </mat-form-field>

      </form>

       0" label="Status assigned" flex [expand]="true" >
          <crm-opptypestatus [idtype]="itemEdit.id" ></crm-opptypestatus>

   <ng-template tdLoading="items.load">

          <ng-template tdDataTableTemplate="name" let-value="value" let-row="row"  let-column="column">

              <button mat-button (click)="editEntity(row.id)">{{value}}</button>

          </ng-template>
          <ng-template tdDataTableTemplate="tActions" let-value="value" let-row="row" let-column="column">

              <button mat-icon-button (click)="confirmDelete( row)">
              <mat-icon>delete</mat-icon>
            </button>

          </ng-template>

Rows per page:

{{pagingBarPageSize.range}} of {{pagingBarPageSize.total}}

              </ng-template>

    </ng-template>
    </mat-card-content>
  </mat-card>


text:
#include "tensorflow/core/common_runtime/kernel_benchmark_testlib.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"

namespace tensorflow {

// Creates a Graph which applies a unary "func" on a 3D float tensor
// of "num" elements.
static Graph* Unary(const string& func, int num) {
  Graph* g = new Graph(OpRegistry::Global());
  Tensor data(DT_FLOAT, TensorShape({64, 64, num / (64 * 64)}));
  CHECK_GT(data.NumElements(), 0);
  data.flat<float>().setRandom();
  test::graph::Unary(g, func, test::graph::Constant(g, data), 0);
  return g;
}

static int kRows = 100000;

static int RowsAndColsArg(int r, int c) { return r * kRows + c; }
static int RowsFromArg(int arg) { return (arg / kRows); }
static int ColsFromArg(int arg) { return (arg % kRows); }

#define BM_UNARY(DEVICE, FUNC)                              \
  static void BM_##DEVICE##_##FUNC(int iters, int num) {    \
    const int64 tot = static_cast<int64>(iters) * num;      \
    testing::ItemsProcessed(tot);                           \
    testing::BytesProcessed(tot * sizeof(float));           \
    test::Benchmark(#DEVICE, Unary(#FUNC, num)).Run(iters); \
  }                                                         \
  BENCHMARK(BM_##DEVICE##_##FUNC)->Range(4 << 10, 1 << 20);

BM_UNARY(cpu, Floor);
BM_UNARY(gpu, Floor);

// data func scalar.
static Graph* BinaryScalar(int num, const string& func) {
  Graph* g = new Graph(OpRegistry::Global());
  Tensor lhs(DT_FLOAT, TensorShape({64, 64, num / (64 * 64)}));
  lhs.flat<float>().setRandom();
  Tensor rhs(DT_FLOAT, TensorShape({}));
  rhs.flat<float>().setRandom();
  test::graph::Binary(g, func, test::graph::Constant(g, lhs),
                      test::graph::Constant(g, rhs));
  return g;
}

#define BM_BINARY_SCALAR(DEVICE, FUNC)                             \
  static void BM_##DEVICE##_##FUNC##_scalar(int iters, int num) {  \
    const int64 tot = static_cast<int64>(iters) * num;             \
    testing::ItemsProcessed(tot);                                  \
    testing::BytesProcessed(tot * sizeof(float));                  \
    test::Benchmark(#DEVICE, BinaryScalar(num, #FUNC)).Run(iters); \
  }                                                                \
  BENCHMARK(BM_##DEVICE##_##FUNC##_scalar)                         \
      ->Arg(4096) /* must >= 4096 */                               \
      ->Arg(32768)                                                 \
      ->Arg(131072)                                                \
      ->Arg(1048576);

BM_BINARY_SCALAR(cpu, Less);
BM_BINARY_SCALAR(gpu, Less);
BM_BINARY_SCALAR(cpu, Add);
BM_BINARY_SCALAR(gpu, Add);
#undef BM_BINARY_SCALAR

static Graph* BiasAdd(int rows, int cols) {
  Graph* g = new Graph(OpRegistry::Global());
  Tensor lhs(DT_FLOAT, TensorShape({rows, cols}));
  lhs.flat<float>().setRandom();
  TensorShape rhs_shape;
  rhs_shape = TensorShape({cols});
  Tensor rhs(DT_FLOAT, rhs_shape);
  rhs.flat<float>().setRandom();
  test::graph::Binary(g, "BiasAdd", test::graph::Constant(g, lhs),
                      test::graph::Constant(g, rhs));
  return g;
}

#define BM_BIAS_ADD(DEVICE, R, C)                                     \
  static void BM_##DEVICE##_BiasAdd_R##R##_C##C(int iters, int arg) { \
    const int rows = RowsFromArg(arg);                                \
    const int cols = ColsFromArg(arg);                                \
    const int64 tot = static_cast<int64>(iters) * rows * cols;        \
    testing::ItemsProcessed(tot);                                     \
    testing::BytesProcessed(tot * sizeof(float));                     \
    test::Benchmark(#DEVICE, BiasAdd(rows, cols)).Run(iters);         \
  }                                                                   \
  BENCHMARK(BM_##DEVICE##_BiasAdd_R##R##_C##C)->Arg(RowsAndColsArg(R, C));

#define BM_BIAS_ADD_ALL(DEVICE)   \
  BM_BIAS_ADD(DEVICE, 512, 2048); \
  BM_BIAS_ADD(DEVICE, 512, 4096); \
  BM_BIAS_ADD(DEVICE, 2048, 512); \
  BM_BIAS_ADD(DEVICE, 4096, 512);

BM_BIAS_ADD_ALL(cpu);
BM_BIAS_ADD_ALL(gpu);
#undef BM_BIAS_ADD_ALL
#undef BM_BIAS_ADD

static Graph* BiasAddGrad(int rows, int cols) {
  Graph* g = new Graph(OpRegistry::Global());
  TensorShape lhs_shape;
  lhs_shape = TensorShape({rows, cols});
  Tensor lhs(DT_FLOAT, lhs_shape);
  lhs.template flat<float>().setRandom();
  Node* n;
  TF_CHECK_OK(NodeBuilder(g->NewName("n"), "BiasAddGrad")
                  .Input(test::graph::Constant(g, lhs), /*index=*/0)
                  .Finalize(g, &n));
  return g;
}

#define BM_BIAS_ADD_GRAD(DEVICE, R, C)                                    \
  static void BM_##DEVICE##_BiasAddGrad_R##R##_C##C(int iters, int arg) { \
    const int rows = RowsFromArg(arg);                                    \
    const int cols = ColsFromArg(arg);                                    \
    const int64 tot = static_cast<int64>(iters) * rows * cols;            \
    testing::ItemsProcessed(tot);                                         \
    testing::BytesProcessed(tot * sizeof(float));                         \
    test::Benchmark(#DEVICE, BiasAddGrad(rows, cols)).Run(iters);         \
  }                                                                       \
  BENCHMARK(BM_##DEVICE##_BiasAddGrad_R##R##_C##C)->Arg(RowsAndColsArg(R, C));

#define BM_BIAS_ADD_GRAD_ALL(DEVICE)   \
  BM_BIAS_ADD_GRAD(DEVICE, 512, 2048); \
  BM_BIAS_ADD_GRAD(DEVICE, 512, 4096); \
  BM_BIAS_ADD_GRAD(DEVICE, 2048, 512); \
  BM_BIAS_ADD_GRAD(DEVICE, 4096, 512);

BM_BIAS_ADD_GRAD_ALL(cpu);
BM_BIAS_ADD_GRAD_ALL(gpu);
#undef BM_BIAS_ADD_GRAD_ALL
#undef BM_BIAS_ADD_GRAD

static Graph* BcastAdd(int rows, int cols, int dim) {
  Graph* g = new Graph(OpRegistry::Global());
  Tensor lhs(DT_FLOAT, TensorShape({rows, cols}));
  lhs.flat<float>().setRandom();
  TensorShape rhs_shape;
  if (dim == 0) {
    rhs_shape = TensorShape({rows, 1});
  } else {
    rhs_shape = TensorShape({cols});
  }
  Tensor rhs(DT_FLOAT, rhs_shape);
  rhs.flat<float>().setRandom();
  test::graph::Binary(g, "Add", test::graph::Constant(g, lhs),
                      test::graph::Constant(g, rhs));
  return g;
}

#define BM_BCAST_ADD_ROW(DEVICE, R, C)                                    \
  static void BM_##DEVICE##_BcastAddRow_R##R##_C##C(int iters, int arg) { \
    const int rows = RowsFromArg(arg);                                    \
    const int cols = ColsFromArg(arg);                                    \
    const int64 tot = static_cast<int64>(iters) * rows * cols;            \
    testing::ItemsProcessed(tot);                                         \
    testing::BytesProcessed(tot * sizeof(float));                         \
    test::Benchmark(#DEVICE, BcastAdd(rows, cols, 0)).Run(iters);         \
  }                                                                       \
  BENCHMARK(BM_##DEVICE##_BcastAddRow_R##R##_C##C)->Arg(RowsAndColsArg(R, C));

#define BM_BCAST_ADD_ROW_ALL(DEVICE)   \
  BM_BCAST_ADD_ROW(DEVICE, 512, 2048); \
  BM_BCAST_ADD_ROW(DEVICE, 512, 4096); \
  BM_BCAST_ADD_ROW(DEVICE, 2048, 512); \
  BM_BCAST_ADD_ROW(DEVICE, 4096, 512);
BM_BCAST_ADD_ROW_ALL(cpu);
BM_BCAST_ADD_ROW_ALL(gpu);
#undef BM_BCAST_ADD_ROW_ALL
#undef BM_BCAST_ADD_ROW

#define BM_BCAST_ADD_COL(DEVICE, R, C)                                    \
  static void BM_##DEVICE##_BcastAddCol_R##R##_C##C(int iters, int arg) { \
    const int rows = RowsFromArg(arg);                                    \
    const int cols = ColsFromArg(arg);                                    \
    const int64 tot = static_cast<int64>(iters) * rows * cols;            \
    testing::ItemsProcessed(tot);                                         \
    testing::BytesProcessed(tot * sizeof(float));                         \
    test::Benchmark(#DEVICE, BcastAdd(rows, cols, 1)).Run(iters);         \
  }                                                                       \
  BENCHMARK(BM_##DEVICE##_BcastAddCol_R##R##_C##C)->Arg(RowsAndColsArg(R, C));

#define BM_BCAST_ADD_COL_ALL(DEVICE)   \
  BM_BCAST_ADD_COL(DEVICE, 512, 2048); \
  BM_BCAST_ADD_COL(DEVICE, 512, 4096); \
  BM_BCAST_ADD_COL(DEVICE, 2048, 512); \
  BM_BCAST_ADD_COL(DEVICE, 4096, 512);
BM_BCAST_ADD_COL_ALL(cpu);
BM_BCAST_ADD_COL_ALL(gpu);
#undef BM_BCAST_ADD_COL_ALL
#undef BM_BCAST_ADD_COL

}  // end namespace tensorflow


text:
namespace prerender {

using WebKit::WebPrerender;
using WebKit::WebPrerenderingSupport;

PrerenderDispatcher::PrerenderDispatcher() {
  WebPrerenderingSupport::initialize(this);
}

PrerenderDispatcher::~PrerenderDispatcher() {
  WebPrerenderingSupport::shutdown();
}

bool PrerenderDispatcher::IsPrerenderURL(const GURL& url) const {
  return running_prerender_urls_.count(url) >= 1;
}

void PrerenderDispatcher::OnPrerenderStart(int prerender_id) {
  DCHECK_NE(0u, prerenders_.count(prerender_id));
  std::map<int, WebPrerender>::iterator it = prerenders_.find(prerender_id);

  WebPrerender& prerender = it->second;

  // The prerender should only be null in unit tests.
  if (prerender.isNull())
    return;

  prerender.didStartPrerender();
}

void PrerenderDispatcher::OnPrerenderStopLoading(int prerender_id) {
  DCHECK_NE(0u, prerenders_.count(prerender_id));
  std::map<int, WebPrerender>::iterator it = prerenders_.find(prerender_id);

  WebPrerender& prerender = it->second;
  DCHECK(!prerender.isNull())
      << "OnPrerenderStopLoading shouldn't be called from a unit test, the only"
      << "context in which a WebPrerender in the dispatcher can be null.";

  prerender.didSendLoadForPrerender();
}

void PrerenderDispatcher::OnPrerenderAddAlias(const GURL& alias) {
  running_prerender_urls_.insert(alias);
}

void PrerenderDispatcher::OnPrerenderRemoveAliases(
    const std::vector<GURL>& aliases) {
  for (size_t i = 0; i < aliases.size(); ++i) {
    std::multiset<GURL>::iterator it = running_prerender_urls_.find(aliases[i]);
    if (it != running_prerender_urls_.end()) {
      running_prerender_urls_.erase(it);
    }
  }
}

void PrerenderDispatcher::OnPrerenderStop(int prerender_id) {
  DCHECK_NE(0u, prerenders_.count(prerender_id));
  WebPrerender& prerender = prerenders_[prerender_id];

  // The prerender should only be null in unit tests.
  if (!prerender.isNull())
    prerender.didStopPrerender();

  // TODO(cbentzel): We'd also want to send the map of active prerenders when
  // creating a new render process, so the Add/Remove go relative to that.
  // This may not be that big of a deal in practice, since the newly created tab
  // is unlikely to go to the prerendered page.
  prerenders_.erase(prerender_id);
}

bool PrerenderDispatcher::OnControlMessageReceived(
    const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(PrerenderDispatcher, message)
    IPC_MESSAGE_HANDLER(PrerenderMsg_OnPrerenderStart, OnPrerenderStart)
    IPC_MESSAGE_HANDLER(PrerenderMsg_OnPrerenderStopLoading,
                        OnPrerenderStopLoading)
    IPC_MESSAGE_HANDLER(PrerenderMsg_OnPrerenderAddAlias, OnPrerenderAddAlias)
    IPC_MESSAGE_HANDLER(PrerenderMsg_OnPrerenderRemoveAliases,
                        OnPrerenderRemoveAliases)
    IPC_MESSAGE_HANDLER(PrerenderMsg_OnPrerenderStop, OnPrerenderStop)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  return handled;
}

void PrerenderDispatcher::add(const WebPrerender& prerender) {
  const PrerenderExtraData& extra_data =
      PrerenderExtraData::FromPrerender(prerender);
  if (prerenders_.count(extra_data.prerender_id()) != 0) {
    // TODO(gavinp): Determine why these apparently duplicate adds occur.
    return;
  }

  prerenders_[extra_data.prerender_id()] = prerender;

  content::RenderThread::Get()->Send(new PrerenderHostMsg_AddLinkRelPrerender(
      extra_data.prerender_id(), GURL(prerender.url()),
      content::Referrer(GURL(prerender.referrer()),
                        prerender.referrerPolicy()),
      extra_data.size(), extra_data.render_view_route_id()));
}

void PrerenderDispatcher::cancel(const WebPrerender& prerender) {
  const PrerenderExtraData& extra_data =
      PrerenderExtraData::FromPrerender(prerender);
  content::RenderThread::Get()->Send(
      new PrerenderHostMsg_CancelLinkRelPrerender(extra_data.prerender_id()));
}

void PrerenderDispatcher::abandon(const WebPrerender& prerender) {
  const PrerenderExtraData& extra_data =
      PrerenderExtraData::FromPrerender(prerender);
  content::RenderThread::Get()->Send(
      new PrerenderHostMsg_AbandonLinkRelPrerender(extra_data.prerender_id()));
}

}  // namespace prerender


text:
var mongoose = require('mongoose');

var PostSchema = new mongoose.Schema({
  title: String,
  link: String,
  upvotes: {type: Number, default: 0},
  comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});

PostSchema.methods.upvote = function(cb) {
  this.upvotes += 1;
  this.save(cb);
};

mongoose.model('Post', PostSchema);