text:
define([
    'streamhub-sdk/view',
    'inherits',
    'hgn!streamhub-metrics/templates/metric'],
function (View, inherits, SimpleMetricTemplate) {

    var MetricView = function (opts) {
        opts = opts || {};
        this.metric = opts.metric;
        View.call(this, opts);
    };

    inherits(MetricView, View);

    MetricView.prototype.elClass = 'hub-metric';

    MetricView.prototype.template = SimpleMetricTemplate;

    MetricView.prototype.setElement = function (element) {
        View.prototype.setElement.apply(this, arguments);
        this.$el.addClass(this.elClass);

        var self = this;
        this.$el.on('click', function () {
            self.$el.trigger('focusMetric.hub', {
                metric: self.metric,
                view: self
            });
        });
    };

    MetricView.prototype.render = function () {
        if (typeof this.template === 'function') {
            this.$el.html(this.template(this.metric));
        }
    };

    return MetricView;
});


text:
using System.Collections.Generic;

namespace Syntaxiom.Symbols
{
    public class SymbolComparer : IComparer<ISymbol>
    {
        private readonly IEvaluationContext _context;

        public SymbolComparer(IEvaluationContext context)
        {
            _context = context;
        }

        public int Compare(ISymbol x, ISymbol y)
        {
            if (x == null)
                return y == null ? 0 : -1;

            return x.ResolveCompareTo(_context, y);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "mkldnn.hpp"
#include "paddle/fluid/operators/batch_norm_op.h"
#include "paddle/fluid/platform/mkldnn_reuse.h"

namespace paddle {
namespace operators {

using batch_norm_bwd = mkldnn::batch_normalization_backward;
using batch_norm_fwd = mkldnn::batch_normalization_forward;
using mkldnn::memory;
using mkldnn::primitive;
using mkldnn::reorder;
using mkldnn::stream;
using paddle::platform::MKLDNNDeviceContext;
using paddle::platform::MKLDNNMemDesc;
using platform::to_void_cast;

namespace {
template <typename T>
struct bn_type_traits {
  using op_type = T;
  using op_desc = typename op_type::desc;
  using op_prim = typename op_type::primitive_desc;
};

class BatchNormMKLDNNHandler : public platform::MKLDNNHandler {
 public:
  BatchNormMKLDNNHandler(
      std::shared_ptr<batch_norm_fwd::primitive_desc> batch_norm_pd,
      const platform::MKLDNNDeviceContext &dev_ctx, mkldnn::engine engine,
      const std::string &base_key)
      : platform::MKLDNNHandler(dev_ctx, engine, base_key) {
    batch_norm_pd_ = batch_norm_pd;
  }

  std::shared_ptr<memory> AcquireScaleshiftMemoryFromPrimitive(void *ptr) {
    return this->AcquireMemoryFromPrimitive(
        batch_norm_pd_->weights_primitive_desc(), ptr, "@scaleshift_mem_p");
  }

  std::shared_ptr<memory> AcquireMeanMemoryFromPrimitive(void *ptr) {
    return this->AcquireMemoryFromPrimitive(
        batch_norm_pd_->mean_primitive_desc(), ptr, "@mean_mem_p");
  }

  std::shared_ptr<memory> AcquireVarianceMemoryFromPrimitive(void *ptr) {
    return this->AcquireMemoryFromPrimitive(
        batch_norm_pd_->variance_primitive_desc(), ptr, "@variance_mem_p");
  }

  std::shared_ptr<batch_norm_fwd> AcquireTestTrainingBatchNormFwd(
      std::shared_ptr<memory> src_memory,
      std::shared_ptr<memory> scaleshift_memory,
      std::shared_ptr<memory> dst_memory, std::shared_ptr<memory> mean_memory,
      std::shared_ptr<memory> variance_memory, bool is_test) {
    auto prim_key = key_ + "@batch_norm_p";
    auto batch_norm_p =
        std::static_pointer_cast<batch_norm_fwd>(dev_ctx_.GetBlob(prim_key));

    PADDLE_ENFORCE((batch_norm_p != nullptr) || !is_reusing_,
                   "Fail to find batch norm primitive in device context");

    if (batch_norm_p == nullptr) {
      if (is_test) {
        batch_norm_p = std::make_shared<batch_norm_fwd>(
            *batch_norm_pd_, *src_memory,
            (const mkldnn::primitive::at &)*mean_memory,
            (const mkldnn::primitive::at &)*variance_memory, *scaleshift_memory,
            *dst_memory);
      } else {
        batch_norm_p = std::make_shared<batch_norm_fwd>(
            *batch_norm_pd_, *src_memory, *scaleshift_memory, *dst_memory,
            *mean_memory, *variance_memory);
      }

      dev_ctx_.SetBlob(prim_key, batch_norm_p);
    } else {
      is_reusing_ = true;
    }

    return batch_norm_p;
  }

  static std::string GetHash(const memory::dims &input_dims, float epsilon,
                             unsigned flag, bool is_test, memory::format format,
                             const std::string &suffix = "") {
    auto dims2str = [](const memory::dims &operand_dims) {
      std::string dstr = "";
      for (size_t i = 0; i < operand_dims.size(); ++i) {
        dstr += std::to_string(operand_dims[i]) + "-";
      }
      return dstr;
    };
    return dims2str(input_dims) + std::to_string(epsilon) +
           std::to_string(flag) + std::to_string(is_test) +
           std::to_string(format) + suffix;
  }

 private:
  std::shared_ptr<batch_norm_fwd::primitive_desc> batch_norm_pd_;
};

std::shared_ptr<memory> UpdateMemoryData(
    const platform::MKLDNNDeviceContext &dev_ctx, const std::string &key,
    void *new_ptr) {
  auto mem = std::static_pointer_cast<memory>(dev_ctx.GetBlob(key));
  PADDLE_ENFORCE(
      mem != nullptr,
      (std::string("Fail to find memory in device context [key: ") + key + "]")
          .c_str());
  mem->set_data_handle(new_ptr);
  return mem;
}

template <typename T, typename Container>
void copy_to_weights(T scale_begin, T scale_end, T shift_begin, T shift_end,
                     Container *c) {
  auto it = std::begin(*c);

  std::copy(scale_begin, scale_end, std::inserter(*c, it));
  std::copy(
      shift_begin, shift_end,
      std::inserter(*c, std::next(it, std::distance(scale_begin, scale_end))));
}

}  // namespace

template <typename T>
class BatchNormMKLDNNOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    const float epsilon = ctx.Attr<float>("epsilon");
    const float momentum = ctx.Attr<float>("momentum");
    const bool is_test = ctx.Attr<bool>("is_test");
    const bool use_global_stats = ctx.Attr<bool>("use_global_stats");
    const bool fuse_with_relu = ctx.Attr<bool>("fuse_with_relu");
    bool global_stats = is_test || use_global_stats;

    const auto *x = ctx.Input<Tensor>("X");
    const auto *mean = ctx.Input<Tensor>("Mean");
    const auto *variance = ctx.Input<Tensor>("Variance");

    auto &dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
    auto mkldnn_engine = dev_ctx.GetEngine();

    auto *y = ctx.Output<Tensor>("Y");
    auto *mean_out = ctx.Output<Tensor>("MeanOut");
    auto *variance_out = ctx.Output<Tensor>("VarianceOut");
    auto *batch_mean = ctx.Output<Tensor>("SavedMean");
    auto *batch_variance = ctx.Output<Tensor>("SavedVariance");

    const auto *scale = ctx.Input<Tensor>("Scale");
    const auto *shift = ctx.Input<Tensor>("Bias");

    PADDLE_ENFORCE(x->layout() == DataLayout::kMKLDNN &&
                       x->format() != memory::format::format_undef,
                   "Wrong layout/format set for Input x tensor");

    const T *x_data = x->data<T>();
    const T *mean_data = mean->data<T>();
    const T *variance_data = variance->data<T>();
    T *y_data = y->mutable_data<T>(ctx.GetPlace());
    T *mean_out_data = mean_out->mutable_data<T>(ctx.GetPlace());
    T *variance_out_data = variance_out->mutable_data<T>(ctx.GetPlace());
    T *batch_mean_data = nullptr;
    T *batch_variance_data = nullptr;

    if (!global_stats) {
      batch_mean_data = batch_mean->mutable_data<T>(ctx.GetPlace());
      batch_variance_data = batch_variance->mutable_data<T>(ctx.GetPlace());
    }

    auto propagation = global_stats == true
                           ? mkldnn::prop_kind::forward_scoring
                           : mkldnn::prop_kind::forward_training;

    auto src_tz = paddle::framework::vectorize2int(x->dims());
    auto scale_tz = paddle::framework::vectorize2int(scale->dims());
    PADDLE_ENFORCE(scale_tz.size() == 1, "Dims of scale tensor is NOT 1");
    const unsigned int ic = scale_tz[0];

    // MKLDNN requires a single piece of memory for scale and shift/bias data
    const size_t scaleshift_size = 2 * ic;
    std::vector<T> scaleshift_data;
    scaleshift_data.reserve(scaleshift_size);

    copy_to_weights(scale->data<T>(), scale->data<T>() + ic, shift->data<T>(),
                    shift->data<T>() + ic, &scaleshift_data);

    unsigned flags = mkldnn::use_scale_shift;
    if (global_stats) flags |= mkldnn::use_global_stats;
    if (fuse_with_relu) flags |= mkldnn::fuse_bn_relu;

    // create mkldnn memory from input x tensor
    mkldnn::memory::format input_format =
        platform::MKLDNNFormatForSize(src_tz.size(), x->format());

    // keys for backward pass
    const std::string key = BatchNormMKLDNNHandler::GetHash(
        src_tz, epsilon, flags, global_stats, input_format,
        ctx.op().Output("SavedMean"));
    const std::string key_batch_norm_fwd_pd = key + "@bn_fwd_pd";

    auto user_src_md = platform::MKLDNNMemDesc(
        {src_tz}, platform::MKLDNNGetDataType<T>(), input_format);

    // create primitive descriptor for batch norm forward
    using bn_fwd_types = bn_type_traits<mkldnn::batch_normalization_forward>;
    auto batch_norm_fwd_desc =
        bn_fwd_types::op_desc{propagation, user_src_md, epsilon, flags};
    auto batch_norm_fwd_pd = std::make_shared<batch_norm_fwd::primitive_desc>(
        batch_norm_fwd_desc, mkldnn_engine);
    // Save conv_pd/src_memory/weights_memory for backward pass
    dev_ctx.SetBlob(key_batch_norm_fwd_pd, batch_norm_fwd_pd);

    BatchNormMKLDNNHandler handler(batch_norm_fwd_pd, dev_ctx, mkldnn_engine,
                                   key);

    auto src_memory =
        handler.AcquireSrcMemory(user_src_md, to_void_cast(x_data));

    // crate mkldnn memory for weights(scale/shift)
    auto scaleshift_memory =
        handler.AcquireScaleshiftMemoryFromPrimitive(scaleshift_data.data());

    // create mkldnn memory for output y tensor
    auto dst_memory = handler.AcquireDstMemory(
        batch_norm_fwd_pd->dst_primitive_desc().desc(), y_data);

    std::shared_ptr<batch_norm_fwd> batch_norm_p;
    if (global_stats) {
      // create mkldnn memory for stats (as input)
      std::shared_ptr<memory> mean_memory =
          handler.AcquireMeanMemoryFromPrimitive(to_void_cast(mean_data));
      std::shared_ptr<memory> variance_memory =
          handler.AcquireVarianceMemoryFromPrimitive(
              to_void_cast(variance_data));

      batch_norm_p = handler.AcquireTestTrainingBatchNormFwd(
          src_memory, scaleshift_memory, dst_memory, mean_memory,
          variance_memory, true);
    } else {
      // create mkldnn memory for stats (as output)
      std::shared_ptr<memory> mean_memory =
          handler.AcquireMeanMemoryFromPrimitive(batch_mean_data);
      std::shared_ptr<memory> variance_memory =
          handler.AcquireVarianceMemoryFromPrimitive(batch_variance_data);

      batch_norm_p = handler.AcquireTestTrainingBatchNormFwd(
          src_memory, scaleshift_memory, dst_memory, mean_memory,
          variance_memory, false);
    }

    y->set_layout(DataLayout::kMKLDNN);
    y->set_format(platform::GetMKLDNNFormat(*dst_memory));

    std::vector<mkldnn::primitive> pipeline;
    pipeline.push_back(*batch_norm_p);
    mkldnn::stream(mkldnn::stream::kind::eager).submit(pipeline).wait();

    if (!global_stats) {
      // mkldnn only compute stats for current batch
      // so we need compute momentum stats via Eigen lib
      EigenVectorArrayMap<T> batch_mean_e(batch_mean_data, ic);
      EigenVectorArrayMap<T> batch_variance_e(batch_variance_data, ic);
      ConstEigenVectorArrayMap<T> mean_e(mean_data, ic);
      ConstEigenVectorArrayMap<T> variance_e{variance_data, ic};

      EigenVectorArrayMap<T> running_mean_e(mean_out_data, ic);
      EigenVectorArrayMap<T> running_variance_e(variance_out_data, ic);

      auto one_minus_momentum = 1. - momentum;
      running_mean_e = mean_e * momentum + batch_mean_e * one_minus_momentum;
      running_variance_e =
          variance_e * momentum + batch_variance_e * one_minus_momentum;
    }
  }
};

template <typename T>
class BatchNormMKLDNNGradOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext &ctx) const override {
    auto &dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
    auto mkldnn_engine = dev_ctx.GetEngine();

    const float epsilon = ctx.Attr<float>("epsilon");

    const auto *x = ctx.Input<Tensor>("X");
    const auto *scale = ctx.Input<Tensor>("Scale");
    const auto *shift = ctx.Input<Tensor>("Bias");
    const auto *batch_mean = ctx.Input<Tensor>("SavedMean");
    const auto *batch_variance = ctx.Input<Tensor>("SavedVariance");

    const auto *diff_y = ctx.Input<Tensor>(framework::GradVarName("Y"));
    auto *diff_x = ctx.Output<Tensor>(framework::GradVarName("X"));
    auto *diff_scale = ctx.Output<Tensor>(framework::GradVarName("Scale"));
    auto *diff_shift = ctx.Output<Tensor>(framework::GradVarName("Bias"));

    PADDLE_ENFORCE(diff_y->layout() == DataLayout::kMKLDNN &&
                       diff_y->format() != memory::format::format_undef,
                   "Wrong layout/format set for Input diff_y tensor");

    const T *x_data = x->data<T>();
    const T *diff_y_data = diff_y->data<T>();
    const T *batch_mean_data = batch_mean->data<T>();
    const T *batch_variance_data = batch_variance->data<T>();
    const T *scale_data = scale->data<T>();
    const T *shift_data = shift->data<T>();
    T *diff_x_data = diff_x->mutable_data<T>(ctx.GetPlace());
    T *diff_scale_data = diff_scale->mutable_data<T>(ctx.GetPlace());
    T *diff_shift_data = diff_shift->mutable_data<T>(ctx.GetPlace());

    auto src_tz = paddle::framework::vectorize2int(x->dims());
    auto diff_src_tz = src_tz;
    auto dst_tz = src_tz;
    auto diff_dst_tz = dst_tz;
    auto scale_tz = paddle::framework::vectorize2int(scale->dims());
    PADDLE_ENFORCE(scale_tz.size() == 1, "Dims of scale tensor is NOT 1");

    const unsigned int ic = scale_tz[0];

    using bn_bwd_types = bn_type_traits<mkldnn::batch_normalization_backward>;

    mkldnn::memory::format dst_format =
        platform::MKLDNNFormatForSize(src_tz.size(), diff_y->format());

    mkldnn::memory::format input_format =
        platform::MKLDNNFormatForSize(src_tz.size(), x->format());

    unsigned flags = mkldnn::use_scale_shift;

    // keys from forward pass
    const std::string key = BatchNormMKLDNNHandler::GetHash(
        src_tz, epsilon, flags, false, input_format,
        ctx.op().Input("SavedMean"));
    const std::string key_batch_norm_fwd_pd = key + "@bn_fwd_pd";

    // keys for primitives reuse
    const std::string key_with_hash =
        key + BatchNormMKLDNNHandler::GetHash(src_tz, epsilon, flags, false,
                                              input_format);
    const std::string key_batch_norm_bwd_p =
        key_with_hash + "@batch_norm_bwd_p";
    const std::string key_batch_norm_src_mem_p =
        key_with_hash + "@batch_norm_bwd_src_mem_p";
    const std::string key_batch_norm_mean_mem_p =
        key_with_hash + "@batch_norm_bwd_mean_mem_p";
    const std::string key_batch_norm_variance_mem_p =
        key_with_hash + "@batch_norm_bwd_variance_mem_p";
    const std::string key_batch_norm_scaleshift_mem_p =
        key_with_hash + "@batch_norm_bwd_scaleshift_mem_p";
    const std::string key_batch_norm_diff_scaleshift_mem_p =
        key_with_hash + "@batch_norm_bwd_diff_scaleshift_mem_p";
    const std::string key_batch_norm_diff_src_mem_p =
        key_with_hash + "@batch_norm_bwd_diff_src_mem_p";
    const std::string key_batch_norm_diff_dst_mem_p =
        key_with_hash + "@batch_norm_bwd_diff_dst_mem_p";

    primitive reorder_diff_dst;
    bool is_diff_dst_reordered = false;
    auto user_diff_dst_memory = memory(
        {{{diff_dst_tz}, memory::data_type::f32, dst_format}, mkldnn_engine},
        to_void_cast(diff_y_data));

    // MKLDNN requires a single piece of memory for scale and shift/bias data
    const size_t scaleshift_size = 2 * ic;

    std::vector<T> scaleshift_data;
    scaleshift_data.reserve(scaleshift_size);
    copy_to_weights(scale_data, scale_data + ic, shift_data, shift_data + ic,
                    &scaleshift_data);

    std::vector<T> diff_scaleshift_data;
    diff_scaleshift_data.reserve(scaleshift_size);

    auto batch_norm_fwd_pd =
        std::static_pointer_cast<batch_norm_fwd::primitive_desc>(
            dev_ctx.GetBlob(key_batch_norm_fwd_pd));
    PADDLE_ENFORCE(batch_norm_fwd_pd != nullptr,
                   "Fail to find batch_norm_fwd_pd in device context");

    auto batch_norm_bwd_p = std::static_pointer_cast<batch_norm_bwd>(
        dev_ctx.GetBlob(key_batch_norm_bwd_p));

    if (batch_norm_bwd_p == nullptr) {
      auto src_memory = std::shared_ptr<memory>(new memory(
          {{{src_tz}, memory::data_type::f32, input_format}, mkldnn_engine},
          to_void_cast(x_data)));

      // for diff_dst, try to use same format as dst in forward pass
      auto diff_dst_pd = batch_norm_fwd_pd.get()->dst_primitive_desc();
      auto diff_dst_md = diff_dst_pd.desc();

      // create primitive descriptor for batch norm backward
      auto batch_norm_bwd_desc = bn_bwd_types::op_desc{
          mkldnn::prop_kind::backward, diff_dst_md,
          src_memory->get_primitive_desc().desc(), epsilon, flags};
      auto batch_norm_bwd_pd = bn_bwd_types::op_prim{
          batch_norm_bwd_desc, mkldnn_engine, *batch_norm_fwd_pd};

      // reorder user_diff_dst if it's not in preferred format
      auto diff_dst_memory = std::make_shared<memory>(user_diff_dst_memory);
      if (diff_dst_pd != user_diff_dst_memory.get_primitive_desc()) {
        diff_dst_memory = std::make_shared<memory>(diff_dst_pd);
        reorder_diff_dst = reorder(user_diff_dst_memory, *diff_dst_memory);
        is_diff_dst_reordered = true;
      }

      // create mkldnn memory for input tensors (src/mean/variance)
      auto mean_memory =
          std::make_shared<memory>(batch_norm_bwd_pd.mean_primitive_desc(),
                                   to_void_cast(batch_mean_data));
      auto variance_memory =
          std::make_shared<memory>(batch_norm_bwd_pd.variance_primitive_desc(),
                                   to_void_cast(batch_variance_data));

      // create mkldnn memory for input tensors (scale/shift)
      auto scaleshift_memory = std::make_shared<memory>(
          batch_norm_bwd_pd.weights_primitive_desc(), scaleshift_data.data());

      // create mkldnn memory for output diff weights (combined scale/shift)
      auto diff_scaleshift_memory = std::make_shared<memory>(
          batch_norm_bwd_pd.diff_weights_primitive_desc(),
          diff_scaleshift_data.data());

      // here assume diff_src is in the same format of src
      auto diff_src_memory = std::make_shared<memory>(
          src_memory->get_primitive_desc(), diff_x_data);

      // finally create batch_norm backward primitive
      batch_norm_bwd_p = std::make_shared<batch_norm_bwd>(
          batch_norm_bwd_pd, *src_memory, *mean_memory, *variance_memory,
          *diff_dst_memory, *scaleshift_memory, *diff_src_memory,
          *diff_scaleshift_memory);

      dev_ctx.SetBlob(key_batch_norm_bwd_p, batch_norm_bwd_p);
      dev_ctx.SetBlob(key_batch_norm_src_mem_p, src_memory);
      dev_ctx.SetBlob(key_batch_norm_mean_mem_p, mean_memory);
      dev_ctx.SetBlob(key_batch_norm_variance_mem_p, variance_memory);
      dev_ctx.SetBlob(key_batch_norm_scaleshift_mem_p, scaleshift_memory);
      dev_ctx.SetBlob(key_batch_norm_diff_scaleshift_mem_p,
                      diff_scaleshift_memory);
      dev_ctx.SetBlob(key_batch_norm_diff_src_mem_p, diff_src_memory);
      dev_ctx.SetBlob(key_batch_norm_diff_dst_mem_p, diff_dst_memory);

      // set layout/format of output tensors
      diff_x->set_layout(DataLayout::kMKLDNN);
      diff_x->set_format((memory::format)diff_src_memory->get_primitive_desc()
                             .desc()
                             .data.format);
    } else {
      // primitives already exist
      UpdateMemoryData(dev_ctx, key_batch_norm_src_mem_p, to_void_cast(x_data));
      UpdateMemoryData(dev_ctx, key_batch_norm_mean_mem_p,
                       to_void_cast(batch_mean_data));
      UpdateMemoryData(dev_ctx, key_batch_norm_variance_mem_p,
                       to_void_cast(batch_variance_data));
      UpdateMemoryData(dev_ctx, key_batch_norm_scaleshift_mem_p,
                       scaleshift_data.data());
      UpdateMemoryData(dev_ctx, key_batch_norm_diff_scaleshift_mem_p,
                       diff_scaleshift_data.data());
      auto diff_src_memory = UpdateMemoryData(
          dev_ctx, key_batch_norm_diff_src_mem_p, to_void_cast(diff_x_data));
      auto diff_dst_memory = UpdateMemoryData(
          dev_ctx, key_batch_norm_diff_dst_mem_p, to_void_cast(diff_y_data));

      // reorder user_diff_dst if it's not in preferred format
      if (diff_dst_memory->get_primitive_desc() !=
          user_diff_dst_memory.get_primitive_desc()) {
        reorder_diff_dst = reorder(user_diff_dst_memory, *diff_dst_memory);
        is_diff_dst_reordered = true;
      }

      // set layout/format of output tensors
      diff_x->set_layout(DataLayout::kMKLDNN);
      diff_x->set_format((memory::format)diff_src_memory->get_primitive_desc()
                             .desc()
                             .data.format);
    }

    // execute optional reorder and batch_norm backward primitive
    std::vector<primitive> pipeline;
    if (is_diff_dst_reordered) pipeline.push_back(reorder_diff_dst);
    pipeline.push_back(*batch_norm_bwd_p);
    stream(stream::kind::eager).submit(pipeline).wait();

    // copy back diff sacle/shift to output tensors (diff scale/shift)
    diff_scaleshift_data.resize(scaleshift_size);
    auto it = std::begin(diff_scaleshift_data);
    std::copy(it, std::next(it, ic), diff_scale_data);
    std::copy(std::next(it, ic), std::end(diff_scaleshift_data),
              diff_shift_data);
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OP_KERNEL(batch_norm, MKLDNN, ::paddle::platform::CPUPlace,
                   ops::BatchNormMKLDNNOpKernel<float>);
REGISTER_OP_KERNEL(batch_norm_grad, MKLDNN, ::paddle::platform::CPUPlace,
                   ops::BatchNormMKLDNNGradOpKernel<float>);


text:
;------------------------------------------------------------------------------
;
; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution.  The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php.
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;
; Module Name:
;
;   WriteCr2.Asm
;
; Abstract:
;
;   AsmWriteCr2 function
;
; Notes:
;
;------------------------------------------------------------------------------

    .code

;------------------------------------------------------------------------------
; UINTN
; EFIAPI
; AsmWriteCr2 (
;   UINTN  Cr2
;   );
;------------------------------------------------------------------------------
AsmWriteCr2 PROC
    mov     cr2, rcx
    mov     rax, rcx
    ret
AsmWriteCr2 ENDP

    END


text:
// from MIT-Mobile-for-iPhone v3.0
#import "IconGrid.h"

GridPadding GridPaddingMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right) {
    GridPadding padding = {top, left, bottom, right};
    return padding;
}

GridSpacing GridSpacingMake(CGFloat width, CGFloat height) {
    return (GridSpacing)CGSizeMake(width, height);
}

const GridPadding GridPaddingZero = {0, 0, 0, 0};
const GridSpacing GridSpacingZero = {0, 0};

@interface IconGrid (Private)

- (void)layoutRow:(NSArray *)rowIcons yOrigin:(CGFloat)yOrigin width:(CGFloat)rowWidth;

@end

@implementation IconGrid

@synthesize delegate, padding, spacing, maxColumns, alignment, icons;

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        padding = GridPaddingZero;
        spacing = GridSpacingZero;
        maxColumns = 0;
        alignment = GridIconAlignmentLeft;
    }
    return self;
}

- (CGFloat)topPadding { return padding.top; }
- (CGFloat)rightPadding { return padding.right; }
- (CGFloat)bottomPadding { return padding.bottom; }
- (CGFloat)leftPadding { return padding.left; }

- (void)setTopPadding:(CGFloat)value { padding.top = value; }
- (void)setRightPadding:(CGFloat)value { padding.right = value; }
- (void)setBottomPadding:(CGFloat)value { padding.bottom = value; }
- (void)setLeftPadding:(CGFloat)value { padding.left = value; }

- (void)layoutSubviews {
    // modified here b/c we haven't incorporated -removeAllSubviews from UIKit+MITAdditions
    for (UIView *aView in self.subviews) {
        [aView removeFromSuperview];
    }
    [super layoutSubviews];

    CGFloat availableWidth = self.frame.size.width - self.leftPadding - self.rightPadding;
    if (availableWidth <= 0)
        return;

    CGFloat yOrigin = self.topPadding;

    NSMutableArray *iconsInCurrentRow = [NSMutableArray array];
    CGFloat currentRowWidth = 0;

    for (UIView *aView in self.icons) {

        CGFloat nextWidthNeeded = currentRowWidth + self.spacing.width + aView.frame.size.width;
        CGFloat iconCount = iconsInCurrentRow.count;
        // if we have a full row or are at the end, layout icons and flush the icons buffer
        if ((iconCount && nextWidthNeeded > availableWidth) || (self.maxColumns && iconCount >= self.maxColumns))
        {
            [self layoutRow:iconsInCurrentRow yOrigin:yOrigin width:currentRowWidth];

            CGFloat maxHeightInRow = 0;
            for (UIView *rowView in iconsInCurrentRow) {
                if (rowView.frame.size.height > maxHeightInRow)
                    maxHeightInRow = rowView.frame.size.height;
            }
            yOrigin += maxHeightInRow + spacing.height;

            [iconsInCurrentRow removeAllObjects];
            currentRowWidth = 0;
        }

        // add our view to the queue, which may or may not be emtpy(ied)
        [iconsInCurrentRow addObject:aView];
        currentRowWidth += aView.frame.size.width;
        if ([iconsInCurrentRow count] > 1) {
            currentRowWidth += spacing.width;
        }
    }
    // finish the loop
    [self layoutRow:iconsInCurrentRow yOrigin:yOrigin width:currentRowWidth];

    // resize our frame if it is too short to fit all icons.
    CGFloat maxHeight = 0;
    for (UIView *anIcon in iconsInCurrentRow) {
        if (maxHeight < anIcon.frame.size.height)
            maxHeight = anIcon.frame.size.height;
    }
    if (self.frame.size.height < maxHeight + yOrigin + self.bottomPadding) {
        CGRect frame = self.frame;
        frame.size.height = maxHeight + yOrigin + self.bottomPadding;
        self.frame = frame;

		if ([delegate respondsToSelector:@selector(iconGridFrameDidChange:)]) {
			[delegate iconGridFrameDidChange:self];
		}
    }
}

- (void)layoutRow:(NSArray *)rowIcons yOrigin:(CGFloat)yOrigin width:(CGFloat)rowWidth {
    CGFloat xOrigin;
    switch (alignment) {
        case GridIconAlignmentRight:
            xOrigin = self.frame.size.width - self.rightPadding - rowWidth;
            break;
        case GridIconAlignmentCenter:
            xOrigin = floor((self.frame.size.width - rowWidth) / 2);
            break;
        case GridIconAlignmentLeft:
        default:
            xOrigin = self.leftPadding;
            break;
    }

    CGRect currentFrame;
    for (UIView *rowView in rowIcons) {
        currentFrame = rowView.frame;
        currentFrame.origin.x = xOrigin;
        currentFrame.origin.y = yOrigin;
        rowView.frame = currentFrame;
        [self addSubview:rowView];

        xOrigin += currentFrame.size.width + self.spacing.width;
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)dealloc {
    [super dealloc];
}

@end


text:
FactoryGirl.define do
  factory :tax_rate, class: Spree::TaxRate do
    zone
    amount 0.1
    tax_category
    association(:calculator, factory: :default_tax_calculator)
  end
end


text:
const _ = require('lodash');
const AWS = require('aws-sdk');
const { promisify, retry, wait } = require('./util');

function getInstance(config) {
	return new AWS.DynamoDB(config);
}

function getDocClient(region) {
	return new AWS.DynamoDB.DocumentClient({ region });
}

function getAllTables(instance) {
	return promisify(cb => instance.listTables({}, cb))
		.then(_.property('TableNames'));
}

function createTable(instance, ProvisionedThroughput, TableName, KeySchema, AttributeDefinitions) {
	const params = { TableName, KeySchema, AttributeDefinitions, ProvisionedThroughput };

	return promisify(cb => instance.createTable(params, cb))
		.then(() => waitForTableStatus(instance, TableName));
}

function waitForTableStatus(instance, TableName, desiredStatus = 'ACTIVE', maxWait = 5000, currentWait = 0) {
	const start = new Date().getTime();

	return getTableStatus(instance, TableName)
		.then((currentStatus) => {
			if (currentStatus === desiredStatus) {
				return desiredStatus;
			}
			currentWait += new Date().getTime() - start;
			if (currentWait < maxWait) {
				return wait(1000)
					.then(() => waitForTableStatus(instance, TableName, desiredStatus, maxWait, currentWait));
			}
			throw new Error('timed out');
		});
}

function getTableStatus(instance, TableName) {
	return promisify(cb => instance.describeTable({ TableName }, cb))
		.then(_.property('Table'))
		.then(_.property('TableStatus'))
		.catch((err) => {
			if (err.name === 'ResourceNotFoundException') {
				return 'DELETED';
			}
			return 'ERROR';
		});
}

function dropTable(instance, TableName) {
	return promisify(cb => instance.deleteTable({ TableName }, cb))
			.then(() => waitForTableStatus(instance, TableName, 'DELETED'));
}

const upsertQueue = [];
let upsertPromise;

function upsertItem(docClient, TableName, Item) {
	const fn = () => promisify(cb => docClient.put({ TableName, Item }, cb))
		.then(() => {
			process.stdout.write('.');
		})
		.catch((error) => {
			process.stdout.write('*');
			throw new Error(error);
		});

	upsertQueue.push(fn);

	if (!upsertPromise) {
		upsertPromise = retry(upsertQueue)
			.then((input) => {
				upsertPromise = null;
				return input;
			});
	}

	return upsertPromise;
}

function getItem(docClient, TableName, Key) {
	return promisify(cb => docClient.get({ TableName, Key }, cb));
}

function query(docClient, TableName, keyCondition, attributeNames, attributeValues, projection = '') {
	const params = {
		TableName,
		KeyConditionExpression: keyCondition,
		ExpressionAttributeNames: attributeNames,
		ExpressionAttributeValues: attributeValues,
		ProjectionExpression: projection
	};

	return promisify(cb => docClient.query(params, cb))
		.then(_.property('Items'));
}

function scan(docClient, TableName, filter, attributeNames, attributeValues, projection = '') {
	const params = {
		TableName,
		FilterExpression: filter,
		ExpressionAttributeNames: attributeNames,
		ExpressionAttributeValues: attributeValues,
		ProjectionExpression: projection
	};

	return promisify(cb => docClient.scan(params, cb))
		.then(_.property('Items'));
}

module.exports = {
	getInstance,
	getDocClient,
	createTable,
	dropTable,
	getAllTables,
	upsertItem,
	getTableStatus,
	getItem,
	query,
	scan
};


text:
<TITLE>Review for Newton Boys, The (1998)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Newton Boys, The (1998)

reviewed by
Marty Mapes

The Newton Boys
A film review by Marty Mapes
Copyright 1998 Marty Mapes

**1/2 (out of 4) This is the first Linklater movie that didn't look like one
(no angst-ridden gen-Xers in this one). It's also the first Linklater movie
that I haven't been pleasantly surprised with. I suspect there's a
correlation.

THE NEWTON BOYS is Linklater's most mainstream and conventional effort so
far. It is the self-proclaimed "true story of the most successful bank
robbers in the history of the United States." Starring Matthew McConaughey,
Skeet Ulrich, and Ethan Hawke, this movie also has a pretty high hunk
quotient (about a .675, almost as high as "Young Guns").

Willis Newton (McConaughey) hooks up with a couple of bank robbers who pull
a small job in the middle of nowhere. They ride into town in broad daylight
and make off with very little money before the local sheriff, in a
newfangled horseless carriage, shoots two of the three robbers. After Willis
escapes with his friend Glasscock (Dwight Yoakam, who is proving to be a
capable actor after his impressive debut in SLING BLADE), they talk about
what went wrong.

They agree that the idea of a daylight robbery is just plain stupid. A night
robbery would have been much easier and more successful. They decide to
prove their hypothesis by robbing a bank at night. Willis enlists the aid of
his brothers (Ulrich, Hawke, and Vincent D'Onofrio) and before long, they
are robbing banks left and right.

They are very successful. They rob at night, and they only attack banks they
know have square safes, which are susceptible to nitroglycerine explosives.
They are in and out before anybody can organize a posse.

Their luck runs out in Canada, when a bank that was supposed to have a
square safe has gone to the uncrackable round-fronted kind. Willis,
desperate to make SOMETHING from his trip to Canada, organizes an ambitious
attempt at a daylight robbery. The Newtons prove to be as good at daylight
robberies as Linklater is at mainstream movies. Out of their element, the
robbery goes bad and the boys are lucky to escape unharmed.

Glasscock and the Newtons realize that their bank robbing days are done
because everyone has gone to round safes (largely because of their success).
They are rich enough to retire, but they want one last big score. They
almost pull off a difficult train robbery, but can't quite make it work.
They mistakenly shoot one of their own men, payoffs to the Chicago mob
aren't made in time... before long they are all arrested. The movie ends
with the Newton boys getting light sentences because of their lovable
good-ole-boy demeanors.

Linklater seems very taken with the "real story" of the Newton Boys. At the
end of the film he reveals what really happened to each character after
getting out of prison. Even over the credits he includes documentary footage
of Willis Newton recounting his youth and of Johnny Carson interviewing Joe
Newton on "The Tonight Show." There is so much information on the real
Newton boys that it is distracting.

My first thought was that Linklater should have spent his energy making a
documentary. My second thought was that a more interesting movie might have
been made by someone who wasn't so taken with the real story. An adaptation
farther from the truth might have made a better movie. Here's why:

As interesting as their story is, it doesn't necessarily lend itself to film
- it doesn't have much of an ending. They go to jail, get out, and live to
old age. Not exactly an exciting denouement. It's an interesting fact but it
doesn't really cap the conflict of the rest of the film.

Also, there are too many characters that are too similar. Sure, each Newton
boy has a distinct personality, but their bank robbing careers are so
defining that their differences seem small by comparison. There is a slight
emphasis on Willis' character, but there is no single point of focus for the
film and the result is a movie that seems a little too even, a little too
flat. A bit more contrast might have been farther from the truth, but it
would have made a better movie.

I have no other complaints about THE NEWTON BOYS. There are even a few areas
that I'd praise. Linklater's fabricated and computer-generated prairie town
was surprising in it's realism and insignificance in the landscape. The
music consists of modern recordings of period jazz, an  interesting
approach, well-suited to this film. But overall, the movie failed to capture
my imagination.

Linklater is great at recording the pulse of his generation. He's a natural
with dialogue, self-discovery and angst.THE NEWTON BOYS gives him little
opportunity to do what he's good at. It's the kind of movie most anyone
could have directed, and it's too bad someone else didn't beat him to it.
Still, It looks like THE NEWTON BOYS was a labor of love for him, so perhaps
it's doesn't signal a permanent change in his style. We can only hope that
the director of SLACKER hasn't sold out.

Check out more current movie reviews at http://www.indra.com/~mmapes/

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:
using JsonFx.Json;
using Nancy;
using Nancy.Hosting.Self;
using Nancy.Responses;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace AdhellDaemon
{
    public class Settings
    {
        public static DateTime LatestBuild = new DateTime(2017, 1, 1, 0, 0, 0);
        public static int Port = 54236;
        public static bool Building = false;
        public static string BaseDirectory = @"/root/adhell";

        public static string LastBuildName = "";

        public static string apkToolYml = @"!!brut.androlib.meta.MetaInfo
apkFileName: Adhell.apk
compressionType: false
doNotCompress:
- arsc
isFrameworkApk: false
packageInfo:
  forcedPackageId: '127'
  renameManifestPackage: {0}
sdkInfo:
  minSdkVersion: '16'
  targetSdkVersion: '26'
sharedLibrary: false
unknownFiles:
  publicsuffixes.gz: '0'
  fabric/com.crashlytics.sdk.android.answers.properties: '8'
  fabric/com.crashlytics.sdk.android.beta.properties: '8'
  fabric/com.crashlytics.sdk.android.crashlytics-core.properties: '8'
  fabric/com.crashlytics.sdk.android.crashlytics.properties: '8'
  fabric/io.fabric.sdk.android.fabric.properties: '8'
usesFramework:
  ids:
  - 1
  tag: null
version: 2.2.4
versionInfo:
  versionCode: '1'
  versionName: 1.0.0
";

        public static string smaliHack = @".class public final Lcom/fiendfyre/AdHell2/BuildConfig;
.super Ljava/lang/Object;
.source ""BuildConfig.java""

# static fields
.field public static final APPLICATION_ID:Ljava/lang/String; = ""[!!!!!][0]""

.field public static final BUILD_TYPE:Ljava/lang/String; = ""release""

.field public static final DEBUG:Z = false

.field public static final FLAVOR:Ljava/lang/String; = """"

.field public static final VERSION_CODE:I = 0x1

.field public static final VERSION_NAME:Ljava/lang/String; = ""1.0.0""

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 6
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method
";

        public static string AndroidManifest = @"<?xml version=""1.0"" encoding=""utf-8"" standalone=""no""?><manifest xmlns:android=""http://schemas.android.com/apk/res/android"" package=""[!!!!!][0]"">
    <uses-permission android:name=""android.permission.sec.MDM_FIREWALL""/>
    <uses-permission android:name=""android.permission.sec.MDM_APP_MGMT""/>
    <uses-permission android:name=""android.permission.sec.MDM_APP_PERMISSION_MGMT""/>
    <uses-permission android:name=""com.samsung.android.providers.context.permission.WRITE_USE_APP_FEATURE_SURVEY""/>
    <uses-permission android:name=""android.permission.ACCESS_NETWORK_STATE""/>
    <uses-permission android:name=""android.permission.INTERNET""/>
    <uses-permission android:name=""android.permission.RECEIVE_BOOT_COMPLETED""/>
    <uses-permission android:name=""android.permission.WAKE_LOCK""/>
    <uses-permission android:name=""android.permission.WRITE_EXTERNAL_STORAGE""/>
    <uses-permission android:name=""android.permission.READ_EXTERNAL_STORAGE""/>
    <uses-permission android:name=""com.android.vending.BILLING""/>
    <application android:allowBackup=""true"" android:icon=""@mipmap/ic_launcher"" android:label=""@string/app_name"" android:name=""com.fiendfyre.AdHell2.App"" android:supportsRtl=""true"" android:theme=""@style/AppTheme"">
        <activity android:name=""com.fiendfyre.AdHell2.MainActivity"" android:windowSoftInputMode=""adjustPan"">
            <intent-filter>
                <action android:name=""android.intent.action.MAIN""/>
                <category android:name=""android.intent.category.LAUNCHER""/>
            </intent-filter>
        </activity>
        <service android:exported=""false"" android:name=""com.fiendfyre.AdHell2.service.BlockedDomainService""/>
        <service android:exported=""false"" android:name=""com.fiendfyre.AdHell2.service.HeartbeatIntentService""/>
        <receiver android:description=""@string/app_name"" android:label=""@string/app_name"" android:name=""com.fiendfyre.AdHell2.receiver.CustomDeviceAdminReceiver"" android:permission=""android.permission.BIND_DEVICE_ADMIN"">
            <meta-data android:name=""android.app.device_admin"" android:resource=""@xml/enterprise_device_admin""/>
            <intent-filter>
                <action android:name=""android.app.action.DEVICE_ADMIN_ENABLED""/>
            </intent-filter>
        </receiver>
        <receiver android:name=""com.fiendfyre.AdHell2.receiver.BlockedDomainAlarmReceiver"" android:process="":remote""/>
        <receiver android:name=""com.fiendfyre.AdHell2.receiver.BootBroadcastReceiver"">
            <intent-filter>
                <action android:name=""android.intent.action.BOOT_COMPLETED""/>
            </intent-filter>
        </receiver>
        <receiver android:name=""com.fiendfyre.AdHell2.receiver.AdhellDownloadBroadcastReceiver"">
            <intent-filter>
                <action android:name=""android.intent.action.DOWNLOAD_COMPLETE""/>
            </intent-filter>
        </receiver>
        <receiver android:name=""com.fiendfyre.AdHell2.receiver.ApplicationsListChangedReceiver"">
            <intent-filter>
                <action android:name=""android.intent.action.PACKAGE_ADDED""/>
                <action android:name=""android.intent.action.PACKAGE_REMOVED""/>
                <data android:scheme=""package""/>
            </intent-filter>
        </receiver>
        <meta-data android:name=""android.support.VERSION"" android:value=""26.0.1""/>
        <provider android:authorities=""[!!!!!][0].lifecycle-trojan"" android:exported=""false"" android:multiprocess=""true"" android:name=""android.arch.lifecycle.LifecycleRuntimeTrojanProvider""/>
        <activity android:name=""com.android.billingclient.util.ProxyBillingActivity"" android:theme=""@android:style/Theme.Translucent.NoTitleBar""/>
    </application>
</manifest>";

        public static string Errors = "";
    }

    public class MainModule : NancyModule
    {
        public static string GetUniqueKey(int maxSize)
        {
            char[] chars = new char[26];
            chars = "abcdefghijklmnopqrstuvwxyz".ToCharArray();

            byte[] data = new byte[1];

            using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
            {
                crypto.GetNonZeroBytes(data);
                data = new byte[maxSize];
                crypto.GetNonZeroBytes(data);
            }
            StringBuilder result = new StringBuilder(maxSize);
            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length)]);
            }
            return result.ToString();
        }

        public MainModule()
        {
            Get["/newbuild"] = parameters =>
            {
                if (Settings.Building) return "alreadybuilding";

                if((DateTime.Now - Settings.LatestBuild).TotalMinutes < 2)
                {
                    return "notoldenough";
                }

                Settings.Building = true;

                Task.Run(() =>
                {
                    try
                    {
                        // Modify apktool.yml
                        var appId = "com." + GetUniqueKey(new Random().Next(5, 11)) + "." + GetUniqueKey(new Random().Next(6, 12));

                        var newYml = string.Format(Settings.apkToolYml, appId);
                        File.WriteAllText(Settings.BaseDirectory + "/Adhell/apktool.yml", newYml);

                        var newSmali = Settings.smaliHack.Replace("[!!!!!][0]", appId);
                        File.WriteAllText(Settings.BaseDirectory + "/Adhell/smali/com/fiendfyre/AdHell2/BuildConfig.smali", newSmali);

                        var androidManifest = Settings.AndroidManifest.Replace("[!!!!!][0]", appId);
                        File.WriteAllText(Settings.BaseDirectory + "/Adhell/AndroidManifest.xml", androidManifest);

                        var appSettingsFragPath = Settings.BaseDirectory + "/Adhell/smali/com/fiendfyre/AdHell2/fragments/AppSettingsFragment.smali";

                        if(!File.Exists(appSettingsFragPath + ".bak"))
                        {
                            // Make it!
                            File.Copy(appSettingsFragPath, appSettingsFragPath + ".bak", true);
                        }

                        var appSettingsFrag = File.ReadAllText(appSettingsFragPath + ".bak").Replace("com.fiendfyre.AdHell5", appId);

                        File.WriteAllText(appSettingsFragPath, appSettingsFrag);

                        var lastBuild = DateTime.Now;
                        var outFilename = "Adhell-" + lastBuild.Month + lastBuild.Day + "-" + lastBuild.Hour + lastBuild.Minute + lastBuild.Second + ".apk";

                        Settings.LatestBuild = lastBuild;

                        // Rebuild apk
                        var apkToolStartInfo = new ProcessStartInfo();
                        apkToolStartInfo.FileName = Settings.BaseDirectory + "/apktool";
                        apkToolStartInfo.Arguments = "b Adhell -o " + outFilename;
                        apkToolStartInfo.WorkingDirectory = Settings.BaseDirectory;
                        apkToolStartInfo.CreateNoWindow = true;

                        var apkTool = Process.Start(apkToolStartInfo);
                        apkTool.WaitForExit();

                        // Resign apk
                        var jarSignStartInfo = new ProcessStartInfo();
                        jarSignStartInfo.FileName = @"jarsigner"; // wtf.
                        jarSignStartInfo.Arguments = "-keystore my.keystore -storepass android -keypass android -sigalg SHA1withRSA -digestalg SHA1 " + outFilename + " app";
                        jarSignStartInfo.WorkingDirectory = Settings.BaseDirectory;
                        jarSignStartInfo.CreateNoWindow = true;

                        var jarSign = Process.Start(jarSignStartInfo);
                        jarSign.WaitForExit();

                        try
                        {
                            File.Delete(Settings.BaseDirectory + "/" + Settings.LastBuildName);
                        }
                        catch { }

                        Settings.Building = false;
                        Settings.LastBuildName = outFilename;
                    }
                    catch (Exception ex)
                    {
                        Settings.Errors += "
" + ex + "

";
                    }
                });

                return "working";
            };

            Get["/errors"] = parameters =>
            {
                return Settings.Errors;
            };

            Get["/getlatest"] = parameters =>
            {
                var file = new FileStream(Settings.BaseDirectory + "/" + Settings.LastBuildName, FileMode.Open);
                string fileName = Settings.LastBuildName;

                var response = new StreamResponse(() => file, MimeTypes.GetMimeType(fileName));
                return response.AsAttachment(fileName);
            };

            Get["/isbuilding"] = parameters =>
            {
                return Settings.Building ? "true" : "false";
            };

            Get["/grablatest"] = parameters =>
            {
                if (Settings.Building) return "There's a build in progress right now, hold on.";

                Settings.Building = true;

                try
                {
                    // https://api.github.com/repos/MilanParikh/Adhell2/releases/latest
                    var reader = new JsonReader();
                    var wc = new WebClient();

                    dynamic output = null;

                    try
                    {
                        wc.Headers.Add("User-Agent", "AdhellDaemon/1.0");
                        output = reader.Read(wc.DownloadString("https://api.github.com/repos/MilanParikh/Adhell2/releases/latest"));
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Unable to get the latest version data. " + ex);
                    }

                    var link = (string) output.assets[0].browser_download_url;

                    var outPath = Settings.BaseDirectory + "/Adhell.apk";

                    if (File.Exists(outPath))
                    {
                        File.Delete(outPath);
                    }

                    try
                    {
                        wc.Headers.Add("User-Agent", "AdhellDaemon/1.0");
                        wc.DownloadFile(link, outPath);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Unable to download the latest file. " + ex);
                    }

                if (Directory.Exists(Settings.BaseDirectory + "/Adhell"))
                    {
                        Directory.Delete(Settings.BaseDirectory + "/Adhell", true);
                    }

                    var apkToolStartInfo = new ProcessStartInfo();
                    apkToolStartInfo.FileName = Settings.BaseDirectory + "/apktool";
                    apkToolStartInfo.Arguments = "d Adhell.apk";
                    apkToolStartInfo.WorkingDirectory = Settings.BaseDirectory;
                    apkToolStartInfo.CreateNoWindow = true;

                    var proc = Process.Start(apkToolStartInfo);
                    proc.WaitForExit();

                    Settings.Building = false;

                    return "Seems to be OK...? Try to rebuild!";
                }
                catch(Exception ex)
                {
                    Settings.Building = false;
                    return "Something happened. RIP :(

" + ex + "
";
                }

                return "done";
            };

            After += ctx =>
            {
                if (ctx.Response.ContentType == "text/html")
                {
                    ctx.Response.ContentType = "text/html; charset=utf-8";
                }
            };
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;

            Console.WriteLine("Starting...");

            var url = "http://127.0.0.1:" + Settings.Port;

            using (var host = new NancyHost(new Uri(url)))
            {
                host.Start();

                Console.WriteLine("Started at {0}", url);

                while (true)
                {
                    Console.ReadLine();
                    Console.ReadKey();
                }
            }
        }
    }
}


text:
package org.compass.core.load.simple;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.compass.core.Compass;
import org.compass.core.CompassSession;
import org.compass.core.CompassTransaction;
import org.compass.core.config.CompassConfiguration;

/**
 * @author kimchy
 */
public class ClientLoadTester {

    public static void main(String[] args) throws Exception {
        CompassConfiguration conf = new CompassConfiguration();
        conf.configure("/org/compass/core/load/simple/compass.cfg.xml");
        File testPropsFile = new File("compass.test.properties");
        if (testPropsFile.exists()) {
            Properties testProps = new Properties();
            testProps.load(new FileInputStream(testPropsFile));
            conf.getSettings().addSettings(testProps);
        }
        conf.addClass(A.class);
        Compass compass = conf.buildCompass();

        while (true) {
            CompassSession session = compass.openSession();
            CompassTransaction tr = session.beginTransaction();

            System.out.println("COUNT: " + session.queryBuilder().matchAll().count());

            tr.commit();
            session.close();
        }
    }
}


text:
Meteor.publish("feeds", function(){
	return Feeds.find({userId: this.userId});
});

// Publish the user's articles for this feed.
Meteor.publish("articles", function(){
	return Articles.find({userId: this.userId});
});

Articles.allow({
	update: function(userId, doc, fieldNames, modifier ){
		return doc.userId == userId;
	}
});

Feeds.allow({
	update: function(userId, doc, fieldNames, modifier){
		return doc.userId == userId;
	},
	remove: function(userId, doc){
		return doc.userId == userId;
	}
});

Accounts.onLogin(function(){
	Meteor.call("refreshFeeds");
});


text:
#ifndef __SOT_POOL_HH__
#define __SOT_POOL_HH__

/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */

/* --- STD --- */
#include <map>
#include <sstream>
#include <string>

/* --- SOT --- */
#include <dynamic-graph/pool.h>
#include <dynamic-graph/signal-base.h>

#include <sot/core/exception-factory.hh>

#include "sot/core/api.hh"

/* --------------------------------------------------------------------- */
/* --- CLASS ----------------------------------------------------------- */
/* --------------------------------------------------------------------- */

namespace dynamicgraph {
namespace sot {

// Preliminary declarations
class FeatureAbstract;
class TaskAbstract;

/*! @ingroup factory
  \brief This singleton class keep tracks of all features and tasks.

  Three kinds of objects are handled:
  \li The controllers, i.e. the tasks which inherits from TaskAbstract.
  \li The features, i.e. the information which inherits from FeatureAbstract.

  \li Any object which need to be inside the SoT and which inherits from Entity.

  This class provides the necessary operations to register, unregister each
  instance of thoses classes.
  As tasks and features derived from Entities, they should be registered
  as such.

  \note From the code it is not very clear why we should not unregister
  from the tasks and the features...

  The role of this class is also to look for the object supporting
  a command, and to apply this command.

  It also returns references to signals from their fully-qualified names.
 */
class SOT_CORE_EXPORT PoolStorage {
 public:
  /*! \name Define types to simplify the writing
    @{
   */
  /*! \brief Sorted set of tasks with unique key (name). */
  typedef std::map<std::string, TaskAbstract *> Tasks;

  /*! \brief Sorted set of features with unique key (name). */
  typedef std::map<std::string, FeatureAbstract *> Features;
  /*! @} */

 protected:
  /*! \name Fields of the class to manage the three entities.
    Also the name is singular, those are true sets.
    @{
  */

  /*! \brief Set of controllers */
  Tasks task;

  /*! \brief Set of features */
  Features feature;
  /*! @} */

 public:
  /*! \brief Default destructor */
  ~PoolStorage(void);

  /// \brief Get unique instance of the class
  static PoolStorage *getInstance();

  /// \brief destroy unique instance of the class
  static void destroy();

  /*! \name Methods related to the handling of the features
    @{
   */
  /*! \brief Registering a feature. */
  void registerFeature(const std::string &entname, FeatureAbstract *ent);

  /*! \brief Get a reference to a feature. */
  FeatureAbstract &getFeature(const std::string &name);
  /*! @} */

  /*! \name Methods related to the handling of the tasks
    @{
   */
  /*! \brief Registering a task. */
  void registerTask(const std::string &entname, TaskAbstract *ent);
  /*! \brief Get a reference to a task. */
  TaskAbstract &getTask(const std::string &name);
  /*! @} */

  /*! \brief This method write a graph description on the file named FileName.
   */
  void writeGraph(const std::string &aFileName);
  void writeCompletionList(std::ostream &os);

 private:
  PoolStorage();
  static PoolStorage *instance_;
};

} /* namespace sot */
} /* namespace dynamicgraph */

#endif /* #ifndef __SOT_POOL_HH__ */


text:
package com.cengallut.handlerextension

import scala.ref.WeakReference
import android.os.{Message, Handler}

/**
 * A global event hub that allows different components of
 * the app to communicate without explicit coupling.
 */
object MessageHub {

  /**
   * Subscribe to the global event stream
   */
  case class Subscribe(who: Handler)

  /**
   * Unsubscribe from the global event stream
   */
  case class Unsubscribe(who: Handler)

  def create: Handler with HandlerExt = new MessageHub

}

private final class MessageHub extends Handler with HandlerExt {
  import MessageHub._
  import HandlerExtensionPackage._

  private var subscribers = Set.empty[WeakReference[Handler]]

  override private[handlerextension] def basis: Handler = this

  override def handleMessage(msg: Message): Unit = {
    msg.obj match {
      case Subscribe(who)   => subscribers += new WeakReference[Handler](who)
      case Unsubscribe(who) => purgeSubscribers(who)
      case a: AnyRef        => broadcastEvent(a)
    }
  }

  private def purgeSubscribers(who: Handler): Unit = {
    subscribers = subscribers.filter { handlerRef =>
      handlerRef.get.isDefined && (handlerRef() ne who)
    }
  }

  private def broadcastEvent(event: AnyRef): Unit = {
    for (
      weakRefToHandler <- subscribers;
      maybeHandler     <- weakRefToHandler.get
    ) {
      maybeHandler.send(event)
    }
  }

}


text:
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import PropTypes from 'prop-types';
import { isFragment } from 'react-is';
import clsx from 'clsx';
import { chainPropTypes } from '@material-ui/utils';
import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled';
import experimentalStyled from '../styles/experimentalStyled';
import useThemeProps from '../styles/useThemeProps';
import Avatar from '../Avatar';
import avatarGroupClasses, { getAvatarGroupUtilityClass } from './avatarGroupClasses';
import { jsxs as _jsxs } from "react/jsx-runtime";
var SPACINGS = {
  small: -16,
  medium: null
};

var useUtilityClasses = function useUtilityClasses(styleProps) {
  var classes = styleProps.classes;
  var slots = {
    root: ['root'],
    avatar: ['avatar']
  };
  return composeClasses(slots, getAvatarGroupUtilityClass, classes);
};

var AvatarGroupRoot = experimentalStyled('div', {}, {
  name: 'MuiAvatarGroup',
  slot: 'Root',
  overridesResolver: function overridesResolver(props, styles) {
    return _extends(_defineProperty({}, "& .".concat(avatarGroupClasses.avatar), styles.avatar), styles.root);
  }
})(function (_ref) {
  var _ref2;

  var theme = _ref.theme;
  return _ref2 = {}, _defineProperty(_ref2, "& .MuiAvatar-root", {
    border: "2px solid ".concat(theme.palette.background.default),
    boxSizing: 'content-box',
    marginLeft: -8,
    '&:last-child': {
      marginLeft: 0
    }
  }), _defineProperty(_ref2, "display", 'flex'), _defineProperty(_ref2, "flexDirection", 'row-reverse'), _ref2;
});
var AvatarGroupAvatar = experimentalStyled(Avatar, {}, {
  name: 'MuiAvatarGroup',
  slot: 'Avatar',
  overridesResolver: function overridesResolver(props, styles) {
    return styles.avatar;
  }
})(function (_ref3) {
  var theme = _ref3.theme;
  return {
    border: "2px solid ".concat(theme.palette.background.default),
    boxSizing: 'content-box',
    marginLeft: -8,
    '&:last-child': {
      marginLeft: 0
    }
  };
});
var AvatarGroup = /*#__PURE__*/React.forwardRef(function AvatarGroup(inProps, ref) {
  var props = useThemeProps({
    props: inProps,
    name: 'MuiAvatarGroup'
  });

  var childrenProp = props.children,
      className = props.className,
      _props$max = props.max,
      max = _props$max === void 0 ? 5 : _props$max,
      _props$spacing = props.spacing,
      spacing = _props$spacing === void 0 ? 'medium' : _props$spacing,
      _props$variant = props.variant,
      variant = _props$variant === void 0 ? 'circular' : _props$variant,
      other = _objectWithoutProperties(props, ["children", "className", "max", "spacing", "variant"]);

  var clampedMax = max < 2 ? 2 : max;

  var styleProps = _extends({}, props, {
    max: max,
    spacing: spacing,
    variant: variant
  });

  var classes = useUtilityClasses(styleProps);
  var children = React.Children.toArray(childrenProp).filter(function (child) {
    if (process.env.NODE_ENV !== 'production') {
      if (isFragment(child)) {
        console.error(["Material-UI: The AvatarGroup component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
      }
    }

    return /*#__PURE__*/React.isValidElement(child);
  });
  var extraAvatars = children.length > clampedMax ? children.length - clampedMax + 1 : 0;
  var marginLeft = spacing && SPACINGS[spacing] !== undefined ? SPACINGS[spacing] : -spacing;
  return /*#__PURE__*/_jsxs(AvatarGroupRoot, _extends({
    styleProps: styleProps,
    className: clsx(classes.root, className),
    ref: ref
  }, other, {
    children: [extraAvatars ? /*#__PURE__*/_jsxs(AvatarGroupAvatar, {
      styleProps: styleProps,
      className: classes.avatar,
      style: {
        marginLeft: marginLeft
      },
      variant: variant,
      children: ["+", extraAvatars]
    }) : null, children.slice(0, children.length - extraAvatars).reverse().map(function (child) {
      return /*#__PURE__*/React.cloneElement(child, {
        className: clsx(child.props.className, classes.avatar),
        style: _extends({
          marginLeft: marginLeft
        }, child.props.style),
        variant: child.props.variant || variant
      });
    })]
  }));
});
process.env.NODE_ENV !== "production" ? AvatarGroup.propTypes
/* remove-proptypes */
= {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------

  /**
   * The avatars to stack.
   */
  children: PropTypes.node,

  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,

  /**
   * @ignore
   */
  className: PropTypes.string,

  /**
   * Max avatars to show before +x.
   * @default 5
   */
  max: chainPropTypes(PropTypes.number, function (props) {
    if (props.max < 2) {
      return new Error(['Material-UI: The prop `max` should be equal to 2 or above.', 'A value below is clamped to 2.'].join('\n'));
    }

    return null;
  }),

  /**
   * Spacing between avatars.
   * @default 'medium'
   */
  spacing: PropTypes.oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.number]),

  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.object,

  /**
   * The variant to use.
   * @default 'circular'
   */
  variant: PropTypes
  /* @typescript-to-proptypes-ignore */
  .oneOfType([PropTypes.oneOf(['circular', 'rounded', 'square']), PropTypes.string])
} : void 0;
export default AvatarGroup;


text:
package com.microsoft.bingads.internal;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Encapsulates a row of csv values and the corresponding header mappings for that array
 *
 */
public class RowValues {

    protected String[] columns;
    protected Map<String, Integer> mappings;

    public RowValues(String[] columns, Map<String, Integer> mappings) {
        this.columns = columns;
        this.mappings = mappings;
    }

    public String get(String header) {
        return columns[this.mappings.get(header)];
    }

    public String tryGet(String header) {
        if (!this.mappings.containsKey(header) || this.mappings.get(header) == null) {
            return null;
        }

        return this.get(header);
    }

    public void put(String header, String value) {
        columns[mappings.get(header)] = value;
    }

    public boolean containsHeader(String header) {
        return mappings.containsKey(header);
    }

    public String[] getColumns() {
        return this.columns;
    }

    public Map<String, String> toMap() {
        Map<String, String> values = new HashMap<String, String>();

        for (Entry<String, Integer> entry : this.mappings.entrySet()) {
            String value = this.columns[entry.getValue()];

            values.put(entry.getKey(), value);
        }

        return values;
    }

    public String toDebugString() {
        String result = "";

        for (Entry<String, Integer> entry : this.mappings.entrySet()) {
            String value = this.columns[entry.getValue()];

            result += String.format("%s = '%s'", entry.getKey(), value) + "; ";
        }

        return result;
    }

}


text:
jQuery(document).ready(function() {
	var form = jQuery('form');
	var select = jQuery('select[name = "with-selected"]');
	var option = jQuery('<option value="export">Export</option>');

	if (select.find('optgroup:first').length) {
		option.insertBefore(select.find('optgroup:first'));
	}

	else {
		option.appendTo(select);
	}

	form.bind('submit', function() {
		if (select.val() == 'export') {
			form.attr('action', Symphony.WEBSITE + '/symphony/extension/quickexport/run/');
		}
	});
});


text:
package io.fabric8.maven.docker.service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import io.fabric8.maven.docker.access.DockerAccess;
import io.fabric8.maven.docker.access.DockerAccessException;
import io.fabric8.maven.docker.model.Container;
import io.fabric8.maven.docker.model.Image;
import io.fabric8.maven.docker.model.Network;

/**
 * Query service for getting image and container information from the docker dameon
 *
 */
public class QueryService {

    // Access to docker daemon & logger
    private DockerAccess docker;

    /**
     * Constructor which gets its dependencies as args)
     *  @param docker remote access to docker daemon
     * */
    public QueryService(DockerAccess docker) {
        this.docker = docker;
    }

    /**
     * Get container by id
     *
     * @param containerIdOrName container id or name
     * @return container found
     * @throws DockerAccessException if an error occurs or no container with this id or name exists
     */
    public Container getMandatoryContainer(String containerIdOrName) throws DockerAccessException {
        Container container = getContainer(containerIdOrName);
        if (container == null) {
            throw new DockerAccessException("Cannot find container %s", containerIdOrName);
        }
        return container;
    }

    /**
     * Get a container running for a given container name.
     * @param containerIdOrName name of container to lookup
     * @return the container found or null if no container is available.
     * @throws DockerAccessException in case of an remote error
     */
    public Container getContainer(final String containerIdOrName) throws DockerAccessException {
        return docker.getContainer(containerIdOrName);
    }

    /**
     * Get a network for a given network name.
     * @param networkName name of network to lookup
     * @return the network found or null if no network is available.
     * @throws DockerAccessException in case of an remote error
     */
    public Network getNetworkByName(final String networkName) throws DockerAccessException {
        for (Network el : docker.listNetworks()) {
            if (networkName.equals(el.getName())) {
                return el;
            }
        }
        return null;
    }

    /**
     * Get all networks.
     * @return the network found or null if no network is available.
     * @throws DockerAccessException in case of an remote error
     */
    public Set<Network> getNetworks() throws DockerAccessException {
        return new HashSet<>(docker.listNetworks());
    }

    /**
     * Get name for single container when the id is given
     *
     * @param containerId id of container to lookup
     * @return the name of the container
     * @throws DockerAccessException if access to the docker daemon fails
     */
    public String getContainerName(String containerId) throws DockerAccessException {
        return getMandatoryContainer(containerId).getName();
    }

    /**
     * List all containers on the Docker server.
     *
     * @param all if true, list stopped containers as well as running containers.
     *
     * @return list of Container objects
     * @throws DockerAccessException if the request fails
     */
    public List<Container> listContainers(final boolean all) throws DockerAccessException {
        return docker.listContainers(all);
    }

    /**
     * Get all containers which are build from an image. By default only the last containers are considered but this
     * can be tuned with a global parameters.
     *
     * @param image for which its container are looked up
     * @param all if true, fetch stopped containers as well as running containers.
     * @return list of Container objects
     * @throws DockerAccessException if the request fails
     */
    public List<Container> getContainersForImage(final String image, final boolean all) throws DockerAccessException {
        return docker.getContainersForImage(image, all);
    }

    /**
     * Get all images on the Docker server.
     *
     * @param all if true, fetch untagged images as well as tagged.
     *
     * @return list of Image objects
     * @throws DockerAccessException if the request fails
     */
    public List<Image> listImages(final boolean all) throws DockerAccessException {
        return docker.listImages(all);
    }

    /**
     * Finds the id of an image.
     *
     * @param imageName name of the image.
     * @return the id of the image
     * @throws DockerAccessException if the request fails
     */
    public String getImageId(String imageName) throws DockerAccessException {
        return docker.getImageId(imageName);
    }

    /**
     * Get the id of the latest container started for an image
     *
     * @param image for which its container are looked up
     * @return container or null if no container has been started for this image.
     * @throws DockerAccessException if the request fails
     */
    public Container getLatestContainerForImage(String image) throws DockerAccessException {
        long newest = 0;
        Container result = null;

        for (Container container : getContainersForImage(image, false)) {
            long timestamp = container.getCreated();

            if (timestamp < newest) {
                continue;
            }

            newest = timestamp;
            result = container;
        }

        return result;
    }

    /**
     * Check whether a container with the given name exists
     *
     * @param containerName container name
     * @return true if a container with this name exists, false otherwise.
     * @throws DockerAccessException
     */
    public boolean hasContainer(String containerName) throws DockerAccessException {
        return getContainer(containerName) != null;
    }

    /**
     * Check whether a network with the given name exists
     *
     * @param networkName network name
     * @return true if a network with this name exists, false otherwise.
     * @throws DockerAccessException
     */

    public boolean hasNetwork(String networkName) throws DockerAccessException {
        return getNetworkByName(networkName) != null;
    }

    /**
     * Check whether the given Image is locally available.
     *
     * @param name name of image to check, the image can contain a tag, otherwise 'latest' will be appended
     * @return true if the image is locally available or false if it must be pulled.
     * @throws DockerAccessException if the request fails
     */
    public boolean hasImage(String name) throws DockerAccessException {
        return docker.hasImage(name);
    }

}


text: require('./dist/server/config/env');


text:
namespace net {

namespace {

// Returns true if the certificate verification call was successful (regardless
// of its result), i.e. if |verify_result| was set. Otherwise returns false.
bool VerifyFromAndroidTrustManager(const std::vector<std::string>& cert_bytes,
                                   const std::string& hostname,
                                   CertVerifyResult* verify_result) {
  android::CertVerifyStatusAndroid status;
  std::vector<std::string> verified_chain;

  // TODO(joth): Fetch the authentication type from SSL rather than hardcode.
  android::VerifyX509CertChain(cert_bytes, "RSA", hostname,
                               &status, &verify_result->is_issued_by_known_root,
                               &verified_chain);
  switch (status) {
    case android::CERT_VERIFY_STATUS_ANDROID_FAILED:
      return false;
    case android::CERT_VERIFY_STATUS_ANDROID_OK:
      break;
    case android::CERT_VERIFY_STATUS_ANDROID_NO_TRUSTED_ROOT:
      verify_result->cert_status |= CERT_STATUS_AUTHORITY_INVALID;
      break;
    case android::CERT_VERIFY_STATUS_ANDROID_EXPIRED:
    case android::CERT_VERIFY_STATUS_ANDROID_NOT_YET_VALID:
      verify_result->cert_status |= CERT_STATUS_DATE_INVALID;
      break;
    case android::CERT_VERIFY_STATUS_ANDROID_UNABLE_TO_PARSE:
      verify_result->cert_status |= CERT_STATUS_INVALID;
      break;
    case android::CERT_VERIFY_STATUS_ANDROID_INCORRECT_KEY_USAGE:
      verify_result->cert_status |= CERT_STATUS_INVALID;
      break;
    default:
      NOTREACHED();
      verify_result->cert_status |= CERT_STATUS_INVALID;
      break;
  }

  // Save the verified chain.
  if (!verified_chain.empty()) {
    std::vector<base::StringPiece> verified_chain_pieces(verified_chain.size());
    for (size_t i = 0; i < verified_chain.size(); i++) {
      verified_chain_pieces[i] = base::StringPiece(verified_chain[i]);
    }
    scoped_refptr<X509Certificate> verified_cert =
        X509Certificate::CreateFromDERCertChain(verified_chain_pieces);
    if (verified_cert.get())
      verify_result->verified_cert = verified_cert;
  }

  // Extract the algorithm information from the certs
  X509Certificate::OSCertHandles chain;
  const X509Certificate::OSCertHandles& intermediates =
      verify_result->verified_cert->GetIntermediateCertificates();
  chain.push_back(verify_result->verified_cert->os_cert_handle());
  chain.insert(chain.end(), intermediates.begin(), intermediates.end());

  // If the chain successfully verified, ignore the trust anchor (the last
  // certificate). Otherwise, assume the chain is partial. This is not entirely
  // correct, as a full chain may have been constructed and then failed to
  // validate. However, if that is the case, the more serious error will
  // override any SHA-1 considerations.
  size_t correction_for_root =
      (status == android::CERT_VERIFY_STATUS_ANDROID_OK) ? 1 : 0;
  for (size_t i = 0; i < chain.size() - correction_for_root; ++i) {
    int sig_alg = OBJ_obj2nid(chain[i]->sig_alg->algorithm);
    if (sig_alg == NID_md2WithRSAEncryption) {
      verify_result->has_md2 = true;
    } else if (sig_alg == NID_md4WithRSAEncryption) {
      verify_result->has_md4 = true;
    } else if (sig_alg == NID_md5WithRSAEncryption ||
               sig_alg == NID_md5WithRSA) {
      verify_result->has_md5 = true;
    } else if (sig_alg == NID_sha1WithRSAEncryption ||
               sig_alg == NID_dsaWithSHA || sig_alg == NID_dsaWithSHA1 ||
               sig_alg == NID_dsaWithSHA1_2 || sig_alg == NID_sha1WithRSA ||
               sig_alg == NID_ecdsa_with_SHA1) {
      verify_result->has_sha1 = true;
    }
  }

  // Extract the public key hashes.
  for (size_t i = 0; i < verified_chain.size(); i++) {
    base::StringPiece spki_bytes;
    if (!asn1::ExtractSPKIFromDERCert(verified_chain[i], &spki_bytes))
      continue;

    HashValue sha1(HASH_VALUE_SHA1);
    base::SHA1HashBytes(reinterpret_cast<const uint8*>(spki_bytes.data()),
                        spki_bytes.size(), sha1.data());
    verify_result->public_key_hashes.push_back(sha1);

    HashValue sha256(HASH_VALUE_SHA256);
    crypto::SHA256HashString(spki_bytes, sha256.data(), crypto::kSHA256Length);
    verify_result->public_key_hashes.push_back(sha256);
  }

  return true;
}

bool GetChainDEREncodedBytes(X509Certificate* cert,
                             std::vector<std::string>* chain_bytes) {
  X509Certificate::OSCertHandle cert_handle = cert->os_cert_handle();
  X509Certificate::OSCertHandles cert_handles =
      cert->GetIntermediateCertificates();

  // Make sure the peer's own cert is the first in the chain, if it's not
  // already there.
  if (cert_handles.empty() || cert_handles[0] != cert_handle)
    cert_handles.insert(cert_handles.begin(), cert_handle);

  chain_bytes->reserve(cert_handles.size());
  for (X509Certificate::OSCertHandles::const_iterator it =
       cert_handles.begin(); it != cert_handles.end(); ++it) {
    std::string cert_bytes;
    if(!X509Certificate::GetDEREncoded(*it, &cert_bytes))
      return false;
    chain_bytes->push_back(cert_bytes);
  }
  return true;
}

}  // namespace

CertVerifyProcAndroid::CertVerifyProcAndroid() {}

CertVerifyProcAndroid::~CertVerifyProcAndroid() {}

bool CertVerifyProcAndroid::SupportsAdditionalTrustAnchors() const {
  return false;
}

bool CertVerifyProcAndroid::SupportsOCSPStapling() const {
  return false;
}

int CertVerifyProcAndroid::VerifyInternal(
    X509Certificate* cert,
    const std::string& hostname,
    const std::string& ocsp_response,
    int flags,
    CRLSet* crl_set,
    const CertificateList& additional_trust_anchors,
    CertVerifyResult* verify_result) {
  if (!cert->VerifyNameMatch(hostname,
                             &verify_result->common_name_fallback_used)) {
    verify_result->cert_status |= CERT_STATUS_COMMON_NAME_INVALID;
  }

  std::vector<std::string> cert_bytes;
  if (!GetChainDEREncodedBytes(cert, &cert_bytes))
    return ERR_CERT_INVALID;
  if (!VerifyFromAndroidTrustManager(cert_bytes, hostname, verify_result)) {
    NOTREACHED();
    return ERR_FAILED;
  }
  if (IsCertStatusError(verify_result->cert_status))
    return MapCertStatusToNetError(verify_result->cert_status);

  return OK;
}

}  // namespace net


text:
#import "NDResourceFork.h"
#import "NSString+CarbonUtilities.h"
//#import "NSURL+NDCarbonUtilities.h"

OSErr createResourceFork( NSURL * aURL );

@implementation NDResourceFork

/*
 * resourceForkForReadingAtURL:
 */
+ (id)resourceForkForReadingAtURL:(NSURL *)aURL
{
	return [[[self alloc] initForReadingAtURL:aURL] autorelease];
}

/*
 * resourceForkForWritingAtURL:
 */
+ (id)resourceForkForWritingAtURL:(NSURL *)aURL
{
	return [[[self alloc] initForWritingAtURL:aURL] autorelease];
}

/*
 * resourceForkForReadingAtPath:
 */
+ (id)resourceForkForReadingAtPath:(NSString *)aPath
{
	return [[[self alloc] initForReadingAtPath:aPath] autorelease];
}

/*
 * resourceForkForWritingAtPath:
 */
+ (id)resourceForkForWritingAtPath:(NSString *)aPath
{
	return [[[self alloc] initForWritingAtPath:aPath] autorelease];
}

/*
 * initForReadingAtURL:
 */
- (id)initForReadingAtURL:(NSURL *)aURL
{
	return [self initForPermission:fsRdPerm AtURL:aURL];
}

/*
 * initForWritingAtURL:
 */
- (id)initForWritingAtURL:(NSURL *)aURL
{
	return [self initForPermission:fsWrPerm AtURL:aURL];
}

/*
 * initForPermission:AtURL:
 */
- (id)initForPermission:(char)aPermission AtURL:(NSURL *)aURL
{
	return [self initForPermission:aPermission AtPath:[aURL path]];
}

- (id)initForPermission:(char)aPermission AtPath:(NSString *)aPath
{
	OSErr			theError = !noErr;
	FSRef			theFsRef,
					theParentFsRef;

	if( self = [self init] )
	{
		/*
		 * if write permission then create resource fork
		 */
		if( (aPermission & 0x06) != 0 )		// if write permission
		{
			if ( [[aPath stringByDeletingLastPathComponent] getFSRef:&theParentFsRef] )
			{
				unsigned int	theNameLength;
				unichar 			theUnicodeName[ PATH_MAX ];
				NSString			* theName;

				theName = [aPath lastPathComponent];
				theNameLength = [theName length];

				if( theNameLength <= PATH_MAX )
				{
					[theName getCharacters:theUnicodeName range:NSMakeRange(0,theNameLength)];

					FSCreateResFile( &theParentFsRef, theNameLength, theUnicodeName, 0, NULL, NULL, NULL );		// doesn't replace if already exists

					theError =  ResError( );

					if( theError == noErr || theError == dupFNErr )
					{
						[aPath getFSRef:&theFsRef];
						fileReference = FSOpenResFile ( &theFsRef, aPermission );
						theError = fileReference > 0 ? ResError( ) : !noErr;
					}
				}
				else
					theError = !noErr;
			}
		}
		else		// dont have write permission
		{
			[aPath getFSRef:&theFsRef];
			fileReference = FSOpenResFile ( &theFsRef, aPermission );
			theError = fileReference > 0 ? ResError( ) : !noErr;
		}

	}

	if( noErr != theError && theError != dupFNErr )
	{
		[self release];
		self = nil;
	}

	return self;
}

/*
 * initForReadingAtPath:
 */
- (id)initForReadingAtPath:(NSString *)aPath
{
	if( [[NSFileManager defaultManager] fileExistsAtPath:aPath] )
		return [self initForPermission:fsRdPerm AtURL:[NSURL fileURLWithPath:aPath]];
	else
		return nil;
}

/*
 * initForWritingAtPath:
 */
- (id)initForWritingAtPath:(NSString *)aPath
{
	return [self initForPermission:fsWrPerm AtURL:[NSURL fileURLWithPath:aPath]];
}

/*
 * dealloc
 */
- (void)dealloc
{
	CloseResFile( fileReference );

	[super dealloc];
}

- (BOOL)addData:(NSData *)aData type:(ResType)aType Id:(short)anID name:(NSString *)aName
{
	Handle		theResHandle;

	if( [self removeType:aType Id:anID] )
	{
		short			thePreviousRefNum;

		thePreviousRefNum = CurResFile();	// save current resource
		UseResFile( fileReference );    			// set this resource to be current

		// copy NSData's bytes to a handle
		if ( noErr == PtrToHand ( [aData bytes], &theResHandle, [aData length] ) )
		{
			Str255			thePName;

			CopyCStringToPascal ( [aName lossyCString], thePName );

			HLock( theResHandle );
			AddResource( theResHandle, aType, anID, thePName );
			HUnlock( theResHandle );

			UseResFile( thePreviousRefNum );     		// reset back to resource previously set

//			DisposeHandle( theResHandle );
			return ( ResError( ) == noErr );
		}
	}

	return NO;
}

/*
 * dataForType:Id:
 */
- (NSData *)dataForType:(ResType)aType Id:(short)anID
{
	NSData		* theData = nil;
	Handle		theResHandle;
	short			thePreviousRefNum;

	thePreviousRefNum = CurResFile();	// save current resource

	UseResFile( fileReference );    		// set this resource to be current

	if( noErr ==  ResError( ) )
	{
		theResHandle = Get1Resource( aType, anID );

		if( theResHandle && noErr ==  ResError( ) )
		{
			HLock(theResHandle);
			theData = [NSData dataWithBytes:*theResHandle length:GetHandleSize( theResHandle )];
			HUnlock(theResHandle);
		}

		if ( theResHandle )
			ReleaseResource( theResHandle );
	}

	UseResFile( thePreviousRefNum );     		// reset back to resource previously set

	return theData;
}

/*
 * -addString:type:Id:name:
 *		adds a string to the resource fork as a pascal string
 */
- (BOOL)addString:(NSString *)aString type:(ResType)aType Id:(short)anID name:(NSString *)aName
{
	unsigned int		theLength;

	theLength = [aString length];

	if( theLength < 256 )
	{
		NSMutableData		* theData;

		theData = [NSMutableData dataWithLength:1];
		*((char*)[theData mutableBytes]) = (char)theLength;
		[theData appendData:[aString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
		return [self addData:theData type:aType Id:anID name:aName];
	}
	else
		return NO;
}

/*
 * -stringForType:Id:
 */
- (NSString *)stringForType:(ResType)aType Id:(short)anID
{
	NSData			* theData;

	theData = [self dataForType:aType Id:anID];

	return theData ? [NSString stringWithCString:([theData bytes] + 1) length:[theData length] - 1] : nil;
}

/*
 * removeType: Id:
 */
- (BOOL)removeType:(ResType)aType Id:(short)anID
{
	Handle		theResHandle;
	OSErr			theErr;

	UseResFile( fileReference );    			// set this resource to be current

	theResHandle = Get1Resource( aType, anID );
	theErr = ResError( );
	if( theResHandle && theErr == noErr )
	{
		RemoveResource( theResHandle );		// Disposed of in current resource file
		theErr = ResError( );
	}
	return theErr == noErr;
}

@end