text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="IE=Edge" http-equiv="X-UA-Compatible"/>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>twilio.rest.events.v1.sink package — twilio-python 7.15.3 documentation</title>
<link href="../../../_static/alabaster.css" rel="stylesheet" type="text/css"/>
<link href="../../../_static/pygments.css" rel="stylesheet" type="text/css"/>

<link href="../../../genindex.html" rel="index" title="Index"/>
<link href="../../../search.html" rel="search" title="Search"/>
<link href="twilio.rest.events.v1.subscription.html" rel="next" title="twilio.rest.events.v1.subscription package"/>
<link href="twilio.rest.events.v1.schema.html" rel="prev" title="twilio.rest.events.v1.schema package"/>
<link href="../../../_static/custom.css" rel="stylesheet" type="text/css"/>
<meta content="width=device-width, initial-scale=0.9, maximum-scale=0.9" name="viewport"/>

twilio.rest.events.v1.sink package¶

Submodules¶

twilio.rest.events.v1.sink.sink_test module¶

This code was generated by
/ _    _  _|   _  _

(_)/(_)(_|/| |(/_  v1.0.0
/       /

class twilio.rest.events.v1.sink.sink_test.SinkTestInstance(version, payload, sid)[source]¶

Bases: twilio.base.instance_resource.InstanceResource

PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution.

result¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	Feedback indicating whether the test event was generated.

Return type:	unicode

class twilio.rest.events.v1.sink.sink_test.SinkTestList(version, sid)[source]¶

Bases: twilio.base.list_resource.ListResource

PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution.

create()[source]¶

Create the SinkTestInstance

<col class="field-name"/>
<col class="field-body"/>

Returns:	The created SinkTestInstance

Return type:	twilio.rest.events.v1.sink.sink_test.SinkTestInstance

class twilio.rest.events.v1.sink.sink_test.SinkTestPage(version, response, solution)[source]¶

Bases: twilio.base.page.Page

PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution.

get_instance(payload)[source]¶

Build an instance of SinkTestInstance

<col class="field-name"/>
<col class="field-body"/>

Parameters:	payload (dict) – Payload response from the API

Returns:	twilio.rest.events.v1.sink.sink_test.SinkTestInstance

Return type:	twilio.rest.events.v1.sink.sink_test.SinkTestInstance

twilio.rest.events.v1.sink.sink_validate module¶

This code was generated by
/ _    _  _|   _  _

(_)/(_)(_|/| |(/_  v1.0.0
/       /

class twilio.rest.events.v1.sink.sink_validate.SinkValidateInstance(version, payload, sid)[source]¶

Bases: twilio.base.instance_resource.InstanceResource

PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution.

result¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	Feedback indicating whether the given Sink was validated.

Return type:	unicode

class twilio.rest.events.v1.sink.sink_validate.SinkValidateList(version, sid)[source]¶

Bases: twilio.base.list_resource.ListResource

PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution.

create(test_id)[source]¶

Create the SinkValidateInstance

<col class="field-name"/>
<col class="field-body"/>

Parameters:	test_id (unicode) – A string that uniquely identifies the test event for a Sink being validated.

Returns:	The created SinkValidateInstance

Return type:	twilio.rest.events.v1.sink.sink_validate.SinkValidateInstance

class twilio.rest.events.v1.sink.sink_validate.SinkValidatePage(version, response, solution)[source]¶

Bases: twilio.base.page.Page

PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution.

get_instance(payload)[source]¶

Build an instance of SinkValidateInstance

<col class="field-name"/>
<col class="field-body"/>

Parameters:	payload (dict) – Payload response from the API

Returns:	twilio.rest.events.v1.sink.sink_validate.SinkValidateInstance

Return type:	twilio.rest.events.v1.sink.sink_validate.SinkValidateInstance

Module contents¶

This code was generated by
/ _    _  _|   _  _

(_)/(_)(_|/| |(/_  v1.0.0
/       /

class twilio.rest.events.v1.sink.SinkContext(version, sid)[source]¶

Bases: twilio.base.instance_context.InstanceContext

PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution.

delete()[source]¶

Deletes the SinkInstance

<col class="field-name"/>
<col class="field-body"/>

Returns:	True if delete succeeds, False otherwise

Return type:	bool

fetch()[source]¶

Fetch the SinkInstance

<col class="field-name"/>
<col class="field-body"/>

Returns:	The fetched SinkInstance

Return type:	twilio.rest.events.v1.sink.SinkInstance

sink_test¶

Access the sink_test

<col class="field-name"/>
<col class="field-body"/>

Returns:	twilio.rest.events.v1.sink.sink_test.SinkTestList

Return type:	twilio.rest.events.v1.sink.sink_test.SinkTestList

sink_validate¶

Access the sink_validate

<col class="field-name"/>
<col class="field-body"/>

Returns:	twilio.rest.events.v1.sink.sink_validate.SinkValidateList

Return type:	twilio.rest.events.v1.sink.sink_validate.SinkValidateList

update(description)[source]¶

Update the SinkInstance

<col class="field-name"/>
<col class="field-body"/>

Parameters:	description (unicode) – Sink Description

Returns:	The updated SinkInstance

Return type:	twilio.rest.events.v1.sink.SinkInstance

class twilio.rest.events.v1.sink.SinkInstance(version, payload, sid=None)[source]¶

Bases: twilio.base.instance_resource.InstanceResource

PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution.

class SinkType[source]¶

Bases: object

KINESIS = 'kinesis'¶

SEGMENT = 'segment'¶

WEBHOOK = 'webhook'¶

class Status[source]¶

Bases: object

ACTIVE = 'active'¶

FAILED = 'failed'¶

INITIALIZED = 'initialized'¶

VALIDATING = 'validating'¶

date_created¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	The date this Sink was created

Return type:	datetime

date_updated¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	The date this Sink was updated

Return type:	datetime

delete()[source]¶

Deletes the SinkInstance

<col class="field-name"/>
<col class="field-body"/>

Returns:	True if delete succeeds, False otherwise

Return type:	bool

description¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	Sink Description

Return type:	unicode

fetch()[source]¶

Fetch the SinkInstance

<col class="field-name"/>
<col class="field-body"/>

Returns:	The fetched SinkInstance

Return type:	twilio.rest.events.v1.sink.SinkInstance

links¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	Nested resource URLs.

Return type:	unicode

sid¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	A string that uniquely identifies this Sink.

Return type:	unicode

sink_configuration¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	JSON Sink configuration.

Return type:	dict

sink_test¶

Access the sink_test

<col class="field-name"/>
<col class="field-body"/>

Returns:	twilio.rest.events.v1.sink.sink_test.SinkTestList

Return type:	twilio.rest.events.v1.sink.sink_test.SinkTestList

sink_type¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	Sink type.

Return type:	SinkInstance.SinkType

sink_validate¶

Access the sink_validate

<col class="field-name"/>
<col class="field-body"/>

Returns:	twilio.rest.events.v1.sink.sink_validate.SinkValidateList

Return type:	twilio.rest.events.v1.sink.sink_validate.SinkValidateList

status¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	The Status of this Sink

Return type:	SinkInstance.Status

update(description)[source]¶

Update the SinkInstance

<col class="field-name"/>
<col class="field-body"/>

Parameters:	description (unicode) – Sink Description

Returns:	The updated SinkInstance

Return type:	twilio.rest.events.v1.sink.SinkInstance

url¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	The URL of this resource.

Return type:	unicode

class twilio.rest.events.v1.sink.SinkList(version)[source]¶

Bases: twilio.base.list_resource.ListResource

PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution.

create(description, sink_configuration, sink_type)[source]¶

Create the SinkInstance

<col class="field-name"/>
<col class="field-body"/>

Parameters:

description (unicode) – Sink Description.

sink_configuration (dict) – JSON Sink configuration.

sink_type (SinkInstance.SinkType) – Sink type.

Returns:
The created SinkInstance

Return type:
twilio.rest.events.v1.sink.SinkInstance

get(sid)[source]¶

Constructs a SinkContext

<col class="field-name"/>
<col class="field-body"/>

Parameters:	sid – A string that uniquely identifies this Sink.

Returns:	twilio.rest.events.v1.sink.SinkContext

Return type:	twilio.rest.events.v1.sink.SinkContext

get_page(target_url)[source]¶

Retrieve a specific page of SinkInstance records from the API.
Request is executed immediately

<col class="field-name"/>
<col class="field-body"/>

Parameters:	target_url (str) – API-generated URL for the requested results page

Returns:	Page of SinkInstance

Return type:	twilio.rest.events.v1.sink.SinkPage

list(in_use=<object object>, status=<object object>, limit=None, page_size=None)[source]¶

Lists SinkInstance records from the API as a list.
Unlike stream(), this operation is eager and will load limit records into
memory before returning.

<col class="field-name"/>
<col class="field-body"/>

Parameters:

in_use (bool) – A boolean to return sinks used/not used by a subscription.

status (unicode) – A string to filter sinks by status.

limit (int) – Upper limit for the number of records to return. list() guarantees
never to return more than limit.  Default is no limit

page_size (int) – Number of records to fetch per request, when not set will use
the default value of 50 records.  If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)

Returns:
Generator that will yield up to limit results

Return type:
list[twilio.rest.events.v1.sink.SinkInstance]

page(in_use=<object object>, status=<object object>, page_token=<object object>, page_number=<object object>, page_size=<object object>)[source]¶

Retrieve a single page of SinkInstance records from the API.
Request is executed immediately

<col class="field-name"/>
<col class="field-body"/>

Parameters:

in_use (bool) – A boolean to return sinks used/not used by a subscription.

status (unicode) – A string to filter sinks by status.

page_token (str) – PageToken provided by the API

page_number (int) – Page Number, this value is simply for client state

page_size (int) – Number of records to return, defaults to 50

Returns:
Page of SinkInstance

Return type:
twilio.rest.events.v1.sink.SinkPage

stream(in_use=<object object>, status=<object object>, limit=None, page_size=None)[source]¶

Streams SinkInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.

<col class="field-name"/>
<col class="field-body"/>

Parameters:

in_use (bool) – A boolean to return sinks used/not used by a subscription.

status (unicode) – A string to filter sinks by status.

limit (int) – Upper limit for the number of records to return. stream()
guarantees to never return more than limit.  Default is no limit

page_size (int) – Number of records to fetch per request, when not set will use
the default value of 50 records.  If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)

Returns:
Generator that will yield up to limit results

Return type:
list[twilio.rest.events.v1.sink.SinkInstance]

class twilio.rest.events.v1.sink.SinkPage(version, response, solution)[source]¶

Bases: twilio.base.page.Page

PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution.

get_instance(payload)[source]¶

Build an instance of SinkInstance

<col class="field-name"/>
<col class="field-body"/>

Parameters:	payload (dict) – Payload response from the API

Returns:	twilio.rest.events.v1.sink.SinkInstance

Return type:	twilio.rest.events.v1.sink.SinkInstance

About twilio-python

    A Python module for communicating with the Twilio API and generating TwiML.

Useful Links

Twilio's Python Helper Library Docs

twilio @ PyPI

twilio-python @ GitHub

Table of Contents

twilio.rest.events.v1.sink package

Submodules

twilio.rest.events.v1.sink.sink_test module

twilio.rest.events.v1.sink.sink_validate module

Module contents

Related Topics

Documentation overview

twilio

twilio package

twilio.rest package

twilio.rest.events package

twilio.rest.events.v1 package

Previous: twilio.rest.events.v1.schema package

Next: twilio.rest.events.v1.subscription package

This Page

Show Source

Quick search

<form action="../../../search.html" class="search" method="get">
<input name="q" type="text"/>
<input type="submit" value="Go"/>
<input name="check_keywords" type="hidden" value="yes"/>
<input name="area" type="hidden" value="default"/>
</form>

      ©2019, Twilio.

      |
      Powered by Sphinx 1.8.0
      & Alabaster 0.7.12

      |
      Page source


text:
var Model = require('derby/node_modules/racer/lib/Model/Model');

croc.Class.define('croc.data.chain.From', {
    extend: croc.data.chain.Atom,

    statics: {
        resolve: function(source) {
            if (source && source instanceof Model && croc.Interface.check(source.get(), 'croc.data.chain.IList')) {
                return source.get();
            }
            return croc.Interface.check(source, 'croc.data.chain.IList') ? source :
                new croc.data.chain.From({source: source});
        }
    },

    options: {
        /**
         * @type {Array|Derby.Model}
         */
        source: {}
    },
    construct: function(options) {
        if (Array.isArray(options.source)) {
            this.__items = options.source;
        }
        else {
            this.__items = options.source.get() || [];
            options.source.on('all', function() {
                this.setItems(options.source.get() || []);
            }.bind(this));
        }

        croc.data.chain.From.superclass.construct.apply(this, arguments);
    },
    members: {
        getItems: function() {
            return this.__items;
        },
        setItems: function(items) {
            var old = this.__items;
            this.__items = items;
            this.fireEvent('change', this.__items, old);
        }
    }
});

redpajama_set_name: RedPajamaGithub


text:
package controllers.errors

import itutil.ControllerISpec
import play.api.test.Helpers._

class EmailPasscodesMaxAttemptsExceededControllerISpec extends ControllerISpec {

  "show" must {
    "return an OK" in new Setup {
      given()
        .user.isAuthorised()

      insertCurrentProfileIntoDb(currentProfile, sessionId)

      val res = await(buildClient(routes.EmailPasscodesMaxAttemptsExceededController.show.url).get())

      res.status mustBe OK
    }
  }

}


text:
// locally_connected_impl.h is the templated implementation of the
// locally_connected.h file.

#ifndef CAFFE2_OPERATORS_LOCALLY_CONNECTED_OP_IMPL_H_
#define CAFFE2_OPERATORS_LOCALLY_CONNECTED_OP_IMPL_H_

#include <vector>

#include "caffe2/core/context.h"
#include "caffe2/core/flags.h"
#include "caffe2/core/logging.h"
#include "caffe2/core/operator.h"
#include "caffe2/operators/conv_pool_op_base.h"
#include "caffe2/operators/locally_connected_op.h"
#include "caffe2/utils/math.h"

namespace caffe2 {

template <typename T, class Context>
bool LocallyConnectedOp<T, Context>::RunOnDeviceWithOrderNCHW() {
  const auto& X = Input(INPUT);
  const auto& filter = Input(FILTER);
  auto* Y = Output(0);
  const int image_ndim = X.ndim() - 2;
  CAFFE_ENFORCE_EQ(X.ndim() + image_ndim, filter.ndim());
  lc_op_util::ShapeParams shape;
  shape.N = X.dim32(0);
  shape.C = X.dim32(1);
  shape.M = filter.dim32(image_ndim);
  CAFFE_ENFORCE(
      shape.C == filter.dim32(image_ndim + 1) * group_,
      "Locally Connected op: input channels does not match: "
      "# of input channels ",
      shape.C,
      " is not equal to kernel channels * group:",
      filter.dim32(image_ndim + 1),
      "*",
      group_);
  CAFFE_ENFORCE(
      shape.M % group_ == 0,
      "The number of output channels is not divisible by group.");

  ConvPoolOpBase<Context>::SetOutputSize(X, Y, shape.M);
  shape.input_image_size = GetDimsSize(X);
  shape.output_image_size = GetDimsSize(*Y);
  const std::vector<int> output_image_dims = GetDims(*Y);
  for (int i = 0; i < image_ndim; ++i) {
    CAFFE_ENFORCE(output_image_dims[i] == filter.dim32(i));
  }

  int kernel_dims_size = 1;
  for (std::size_t i = 0; i < kernel_.size(); ++i) {
    CAFFE_ENFORCE_EQ(filter.dim32(i + image_ndim + 2), kernel_[i]);
    kernel_dims_size *= kernel_[i];
  }

  shape.input_image_dims = GetDims(X);
  const std::vector<int> input_dims(X.dims().cbegin() + 1, X.dims().cend());
  SetDeviceTensor(input_dims, &X_dims_device_);
  shape.kernel_dim = shape.C / group_ * kernel_dims_size;

  const std::vector<int> Y_dims(Y->dims().cbegin(), Y->dims().cend());
  SetColumnBufferShape(
      shape.N,
      shape.C,
      shape.kernel_dim,
      output_image_dims,
      &shape.column_dims,
      &shape.column_transposed_dims);
  SetYTranposedBufferShape(Y_dims, &shape.Y_transposed_dims);

  const T* X_data = X.template data<T>();
  const T* filter_data = filter.template data<T>();
  const T* bias_data = nullptr;
  if (InputSize() == 3) {
    const auto& bias = Input(BIAS);
    CAFFE_ENFORCE(bias.ndim() == image_ndim + 1);
    for (int i = 0; i < image_ndim; ++i) {
      CAFFE_ENFORCE(bias.dim32(i) == output_image_dims[i]);
    }
    CAFFE_ENFORCE(bias.dim32(image_ndim) == shape.M);
    bias_data = bias.template data<T>();
    ConvPoolOpBase<Context>::template SetBiasMultiplier<T>(
        shape.N, &bias_multiplier_);
  }
  T* Y_data = Y->template mutable_data<T>();

  RunOnDeviceWithOrderNCHWImpl(
      shape,
      X_data,
      filter_data,
      bias_data,
      Y_data,
      &column_buffer_,
      &column_transposed_buffer_,
      &Y_transposed_buffer_);

  return true;
}

template <typename T, class Context>
bool LocallyConnectedOp<T, Context>::RunOnDeviceWithOrderNHWC() {
  const auto& X = Input(INPUT);
  const auto& filter = Input(FILTER);
  auto* Y = Output(0);
  CAFFE_ENFORCE_EQ(
      kernel_.size(),
      2,
      "Only 2d locally connected op is supported for NHWC storage type.");
  const int image_ndim = X.ndim() - 2;
  CAFFE_ENFORCE_EQ(X.ndim() + image_ndim, filter.ndim());
  lc_op_util::ShapeParams shape;
  shape.N = X.dim32(0);
  shape.C = X.dim32(3);
  shape.input_image_dims = {X.dim32(1), X.dim32(2)};
  shape.M = filter.dim32(image_ndim);
  CAFFE_ENFORCE(filter.dim32(image_ndim + 1) == kernel_h());
  CAFFE_ENFORCE(filter.dim32(image_ndim + 2) == kernel_w());
  CAFFE_ENFORCE(filter.dim32(image_ndim + 3) == shape.C);
  ConvPoolOpBase<Context>::SetOutputSize(X, Y, shape.M);

  shape.input_image_size = GetDimsSize(X);
  shape.output_image_size = GetDimsSize(*Y);
  const std::vector<int> output_image_dims = GetDims(*Y);
  for (int i = 0; i < image_ndim; ++i) {
    CAFFE_ENFORCE(output_image_dims[i] == filter.dim32(i));
  }

  shape.kernel_dim = kernel_h() * kernel_w() * shape.C;
  const std::vector<int> Y_dims(Y->dims().cbegin(), Y->dims().cend());
  SetColumnBufferShape(
      shape.N,
      shape.C,
      shape.kernel_dim,
      output_image_dims,
      &shape.column_dims,
      &shape.column_transposed_dims);
  SetYTranposedBufferShape(Y_dims, &shape.Y_transposed_dims);

  const T* X_data = X.template data<T>();
  const T* filter_data = filter.template data<T>();
  const T* bias_data = nullptr;
  if (InputSize() == 3) {
    const auto& bias = Input(BIAS);
    CAFFE_ENFORCE(bias.ndim() == image_ndim + 1);
    for (int i = 0; i < image_ndim; ++i) {
      CAFFE_ENFORCE(bias.dim32(i) == output_image_dims[i]);
    }
    CAFFE_ENFORCE(bias.dim32(image_ndim) == shape.M);
    bias_data = bias.template data<T>();
    ConvPoolOpBase<Context>::template SetBiasMultiplier<T>(
        shape.N, &bias_multiplier_);
  }
  T* Y_data = Y->template mutable_data<T>();

  RunOnDeviceWithOrderNHWCImpl(
      shape,
      X_data,
      filter_data,
      bias_data,
      Y_data,
      &column_buffer_,
      &column_transposed_buffer_,
      &Y_transposed_buffer_);

  return true;
}

template <typename T, class Context>
void LocallyConnectedOp<T, Context>::RunOnDeviceWithOrderNCHWImpl(
    const lc_op_util::ShapeParams& shape,
    const T* X_data,
    const T* filter_data,
    const T* bias_data,
    T* Y_data,
    Tensor<Context>* column_buffer,
    Tensor<Context>* column_transposed_buffer,
    Tensor<Context>* Y_transposed_buffer) {
  const int input_stride = shape.C / group_ * shape.input_image_size;
  const int column_stride = shape.kernel_dim * shape.output_image_size;
  column_buffer->Resize(shape.column_dims);
  column_transposed_buffer->Resize(shape.column_transposed_dims);
  Y_transposed_buffer->Resize(shape.Y_transposed_dims);
  T* column_buffer_data = column_buffer->template mutable_data<T>();
  T* Y_transposed_buffer_data = Y_transposed_buffer->template mutable_data<T>();

  for (int image_id = 0; image_id < shape.N; ++image_id) {
    for (int group_id = 0; group_id < group_; ++group_id) {
      if (kernel_.size() == 2) {
        math::Im2col<T, Context, StorageOrder::NCHW>(
            X_data + group_id * input_stride,
            shape.C / group_,
            shape.input_image_dims[0],
            shape.input_image_dims[1],
            kernel_h(),
            kernel_w(),
            dilation_h(),
            dilation_w(),
            pad_t(),
            pad_l(),
            pad_b(),
            pad_r(),
            stride_h(),
            stride_w(),
            column_buffer_data + group_id * column_stride,
            &context_);
      } else {
        math::Im2colNd<T, Context, StorageOrder::NCHW>(
            X_data + group_id * input_stride,
            X_dims_device_.template data<int>(),
            column_dims_device_.template data<int>() + 1,
            shape.C * shape.input_image_size,
            column_stride,
            kernel_device_.template data<int>(),
            stride_device_.template data<int>(),
            dilation_device_.template data<int>(),
            pads_device_.template data<int>(),
            kernel_.size(),
            column_buffer_data + group_id * column_stride,
            &context_);
      }
    }
    X_data += input_stride * group_;
    column_buffer_data += column_stride * group_;
  }
  math::Transpose(
      shape.column_dims.size(),
      column_dims_device_.template data<int>(),
      column_transposed_dims_device_.template data<int>(),
      column_axes_device_.template data<int>(),
      column_buffer->size(),
      column_buffer->template data<T>(),
      column_transposed_buffer->template mutable_data<T>(),
      &context_);
  math::GemmBatched(
      CblasNoTrans,
      CblasNoTrans,
      shape.output_image_size * group_,
      shape.M / group_,
      shape.N,
      shape.kernel_dim,
      1.0f,
      filter_data,
      column_transposed_buffer->template data<T>(),
      0.0f,
      Y_transposed_buffer_data,
      &context_);
  if (bias_data != nullptr) {
    math::Gemm<T, Context>(
        CblasNoTrans,
        CblasNoTrans,
        shape.output_image_size * shape.M,
        shape.N,
        1,
        1.0,
        bias_data,
        bias_multiplier_.template data<T>(),
        1.0,
        Y_transposed_buffer_data,
        &context_);
  }
  math::Transpose(
      shape.Y_transposed_dims.size(),
      Y_transposed_dims_device_.template data<int>(),
      Y_dims_device_.template data<int>(),
      Y_transposed_axes_device_.template data<int>(),
      Y_transposed_buffer->size(),
      Y_transposed_buffer_data,
      Y_data,
      &context_);
}

template <typename T, class Context>
void LocallyConnectedOp<T, Context>::RunOnDeviceWithOrderNHWCImpl(
    const lc_op_util::ShapeParams& shape,
    const T* X_data,
    const T* filter_data,
    const T* bias_data,
    T* Y_data,
    Tensor<Context>* column_buffer,
    Tensor<Context>* column_transposed_buffer,
    Tensor<Context>* Y_transposed_buffer) {
  const int input_stride = shape.C * shape.input_image_size;
  const int column_stride = shape.kernel_dim * shape.output_image_size;
  column_buffer->Resize(shape.column_dims);
  column_transposed_buffer->Resize(shape.column_transposed_dims);
  Y_transposed_buffer->Resize(shape.Y_transposed_dims);
  T* column_buffer_data = column_buffer->template mutable_data<T>();
  T* Y_transposed_buffer_data = Y_transposed_buffer->template mutable_data<T>();
  for (int image_id = 0; image_id < shape.N; ++image_id) {
    math::Im2col<T, Context, StorageOrder::NHWC>(
        X_data + image_id * input_stride,
        shape.C,
        shape.input_image_dims[0],
        shape.input_image_dims[1],
        kernel_h(),
        kernel_w(),
        dilation_h(),
        dilation_w(),
        pad_t(),
        pad_l(),
        pad_b(),
        pad_r(),
        stride_h(),
        stride_w(),
        column_buffer_data + image_id * column_stride,
        &context_);
  }
  math::Transpose(
      shape.column_dims.size(),
      column_dims_device_.template data<int>(),
      column_transposed_dims_device_.template data<int>(),
      column_axes_device_.template data<int>(),
      column_buffer->size(),
      column_buffer->template data<T>(),
      column_transposed_buffer->template mutable_data<T>(),
      &context_);
  math::GemmBatched(
      CblasNoTrans,
      CblasTrans,
      shape.output_image_size,
      shape.N,
      shape.M,
      shape.kernel_dim,
      1.0f,
      column_transposed_buffer->template data<T>(),
      filter_data,
      0.0f,
      Y_transposed_buffer_data,
      &context_);
  math::Transpose(
      shape.Y_transposed_dims.size(),
      Y_transposed_dims_device_.template data<int>(),
      Y_dims_device_.template data<int>(),
      Y_transposed_axes_device_.template data<int>(),
      Y_transposed_buffer->size(),
      Y_transposed_buffer_data,
      Y_data,
      &context_);
  if (bias_data != nullptr) {
    math::Gemm<T, Context>(
        CblasNoTrans,
        CblasNoTrans,
        shape.N,
        shape.output_image_size * shape.M,
        1,
        1.0f,
        bias_multiplier_.template data<T>(),
        bias_data,
        1.0f,
        Y_data,
        &context_);
  }
}

template <typename T, class Context>
void LocallyConnectedOp<T, Context>::SetColumnBufferShape(
    const int N,
    const int C,
    const int kernel_dim,
    const std::vector<int>& output_image_dims,
    std::vector<int>* column_dims,
    std::vector<int>* column_transposed_dims) {
  std::vector<int> column_axes;
  lc_op_util::SetColumnBufferShapeImpl(
      N,
      kernel_dim,
      order_,
      output_image_dims,
      column_dims,
      column_transposed_dims,
      &column_axes,
      nullptr);
  SetDeviceTensor(*column_dims, &column_dims_device_);
  SetDeviceTensor(*column_transposed_dims, &column_transposed_dims_device_);
  SetDeviceTensor(column_axes, &column_axes_device_);
}

template <typename T, class Context>
void LocallyConnectedOp<T, Context>::SetYTranposedBufferShape(
    const std::vector<int>& Y_dims,
    std::vector<int>* Y_transposed_dims) {
  const int n_Y_dims = Y_dims.size();
  Y_transposed_dims->resize(n_Y_dims);
  std::vector<int> Y_transposed_axes(n_Y_dims);
  if (order_ == StorageOrder::NCHW) {
    for (int i = 0; i < n_Y_dims - 2; ++i) {
      Y_transposed_dims->at(i) = Y_dims[i + 2];
      Y_transposed_axes[i + 2] = i;
    }
    Y_transposed_dims->at(n_Y_dims - 2) = Y_dims[1];
    Y_transposed_dims->at(n_Y_dims - 1) = Y_dims[0];
    Y_transposed_axes[1] = n_Y_dims - 2;
    Y_transposed_axes[0] = n_Y_dims - 1;
  } else {
    for (int i = 0; i < n_Y_dims - 2; ++i) {
      Y_transposed_dims->at(i) = Y_dims[i + 1];
      Y_transposed_axes[i + 1] = i;
    }
    Y_transposed_dims->at(n_Y_dims - 2) = Y_dims[0];
    Y_transposed_dims->at(n_Y_dims - 1) = Y_dims[n_Y_dims - 1];
    Y_transposed_axes[0] = n_Y_dims - 2;
    Y_transposed_axes[n_Y_dims - 1] = n_Y_dims - 1;
  }
  SetDeviceTensor(Y_dims, &Y_dims_device_);
  SetDeviceTensor(*Y_transposed_dims, &Y_transposed_dims_device_);
  SetDeviceTensor(Y_transposed_axes, &Y_transposed_axes_device_);
}

template <typename T, class Context>
bool LocallyConnectedGradientOp<T, Context>::RunOnDeviceWithOrderNCHW() {
  const auto& X = Input(INPUT);
  const auto& filter = Input(FILTER);
  const auto& dY = Input(OUTPUT_GRAD);
  auto* dfilter = Output(FILTER_GRAD);
  const int image_ndim = X.ndim() - 2;
  CAFFE_ENFORCE_EQ(X.ndim() + image_ndim, filter.ndim());

  lc_op_util::ShapeParams shape;
  shape.N = X.dim32(0);
  shape.C = X.dim32(1);
  shape.M = filter.dim32(image_ndim);
  CAFFE_ENFORCE(filter.dim32(image_ndim + 1) * group_ == shape.C);
  CAFFE_ENFORCE(shape.M % group_ == 0);

  shape.input_image_dims = GetDims(X);
  shape.input_image_size = GetDimsSize(X);
  const std::vector<int> output_image_dims = GetDims(dY);
  shape.output_image_size = GetDimsSize(dY);
  for (int i = 0; i < image_ndim; ++i) {
    CAFFE_ENFORCE(output_image_dims[i] == filter.dim32(i));
  }
  ConvPoolOpBase<Context>::ComputePads(shape.input_image_dims);

  int kernel_dims_size = 1;
  for (std::size_t i = 0; i < kernel_.size(); ++i) {
    CAFFE_ENFORCE_EQ(filter.dim32(i + image_ndim + 2), kernel_[i]);
    kernel_dims_size *= kernel_[i];
  }

  const std::vector<int> X_dims(X.dims().cbegin() + 1, X.dims().cend());
  SetDeviceTensor(X_dims, &X_dims_device_);
  shape.kernel_dim = shape.C / group_ * kernel_dims_size;

  const std::vector<int> dY_dims(dY.dims().cbegin(), dY.dims().cend());
  SetColumnBufferShape(
      shape.N,
      shape.C,
      shape.kernel_dim,
      output_image_dims,
      &shape.column_dims,
      &shape.column_transposed_dims);
  SetDYTranposedBufferShape(dY_dims, &shape.Y_transposed_dims);

  dfilter->ResizeLike(filter);
  const T* X_data = X.template data<T>();
  const T* filter_data = filter.template data<T>();
  const T* dY_data = dY.template data<T>();
  T* dfilter_data = dfilter->template mutable_data<T>();
  T* dX_data = nullptr;
  T* dbias_data = nullptr;
  if (OutputSize() == 3 || (no_bias_ && OutputSize() == 2)) {
    auto* dX = Output(no_bias_ ? BIAS_OR_INPUT_GRAD : INPUT_GRAD);
    dX->ResizeLike(X);
    dX_data = dX->template mutable_data<T>();
  }
  if (!no_bias_) {
    auto* dbias = Output(BIAS_OR_INPUT_GRAD);
    std::vector<int> dbias_dims = output_image_dims;
    dbias_dims.push_back(shape.M);
    dbias->Resize(dbias_dims);
    ConvPoolOpBase<Context>::template SetBiasMultiplier<T>(
        shape.N, &bias_multiplier_);
    dbias_data = dbias->template mutable_data<T>();
  }
  RunOnDeviceWithOrderNCHWImpl(
      shape,
      X_data,
      filter_data,
      dY_data,
      dfilter_data,
      dX_data,
      dbias_data,
      &column_buffer_,
      &column_transposed_buffer_,
      &dY_transposed_buffer_);

  return true;
}

template <typename T, class Context>
bool LocallyConnectedGradientOp<T, Context>::RunOnDeviceWithOrderNHWC() {
  const auto& X = Input(INPUT);
  const auto& filter = Input(FILTER);
  const auto& dY = Input(OUTPUT_GRAD);
  auto* dfilter = Output(FILTER_GRAD);
  CAFFE_ENFORCE_EQ(
      kernel_.size(),
      2,
      "Only 2d locally connected op is supported for NHWC storage type.");
  const int image_ndim = X.ndim() - 2;
  CAFFE_ENFORCE_EQ(X.ndim() + image_ndim, filter.ndim());
  lc_op_util::ShapeParams shape;
  shape.N = X.dim32(0);
  shape.C = X.dim32(3);
  shape.input_image_dims = {X.dim32(1), X.dim32(2)};
  shape.M = filter.dim32(image_ndim);
  CAFFE_ENFORCE(filter.dim32(image_ndim + 1) == kernel_h());
  CAFFE_ENFORCE(filter.dim32(image_ndim + 2) == kernel_w());
  CAFFE_ENFORCE(filter.dim32(image_ndim + 3) == shape.C);
  ConvPoolOpBase<Context>::ComputePads(shape.input_image_dims);

  shape.input_image_size = GetDimsSize(X);
  shape.output_image_size = GetDimsSize(dY);
  const std::vector<int> output_image_dims = GetDims(dY);
  for (int i = 0; i < image_ndim; ++i) {
    CAFFE_ENFORCE(output_image_dims[i] == filter.dim32(i));
  }

  shape.kernel_dim = kernel_h() * kernel_w() * shape.C;
  const std::vector<int> dY_dims(dY.dims().cbegin(), dY.dims().cend());
  SetColumnBufferShape(
      shape.N,
      shape.C,
      shape.kernel_dim,
      output_image_dims,
      &shape.column_dims,
      &shape.column_transposed_dims);
  SetDYTranposedBufferShape(dY_dims, &shape.Y_transposed_dims);

  dfilter->ResizeLike(filter);
  const T* X_data = X.template data<T>();
  const T* filter_data = filter.template data<T>();
  const T* dY_data = dY.template data<T>();
  T* dfilter_data = dfilter->template mutable_data<T>();
  T* dX_data = nullptr;
  T* dbias_data = nullptr;
  if (OutputSize() == 3 || (no_bias_ && OutputSize() == 2)) {
    auto* dX = Output(no_bias_ ? BIAS_OR_INPUT_GRAD : INPUT_GRAD);
    dX->ResizeLike(X);
    dX_data = dX->template mutable_data<T>();
  }
  if (!no_bias_) {
    auto* dbias = Output(BIAS_OR_INPUT_GRAD);
    std::vector<int> dbias_dims = output_image_dims;
    dbias_dims.push_back(shape.M);
    dbias->Resize(dbias_dims);
    ConvPoolOpBase<Context>::template SetBiasMultiplier<T>(
        shape.N, &bias_multiplier_);
    dbias_data = dbias->template mutable_data<T>();
  }
  RunOnDeviceWithOrderNHWCImpl(
      shape,
      X_data,
      filter_data,
      dY_data,
      dfilter_data,
      dX_data,
      dbias_data,
      &column_buffer_,
      &column_transposed_buffer_,
      &dY_transposed_buffer_);

  return true;
}

template <typename T, class Context>
void LocallyConnectedGradientOp<T, Context>::RunOnDeviceWithOrderNCHWImpl(
    const lc_op_util::ShapeParams& shape,
    const T* X_data,
    const T* filter_data,
    const T* dY_data,
    T* dfilter_data,
    T* dX_data,
    T* dbias_data,
    Tensor<Context>* column_buffer,
    Tensor<Context>* column_transposed_buffer,
    Tensor<Context>* dY_transposed_buffer) {
  const int input_stride = shape.C * shape.input_image_size;
  const int column_stride = shape.kernel_dim * shape.output_image_size;
  column_buffer->Resize(shape.column_dims);
  column_transposed_buffer->Resize(shape.column_transposed_dims);
  dY_transposed_buffer->Resize(shape.Y_transposed_dims);
  T* column_buffer_data = column_buffer->template mutable_data<T>();
  T* dY_transposed_buffer_data =
      dY_transposed_buffer->template mutable_data<T>();

  for (int image_id = 0; image_id < shape.N; ++image_id) {
    for (int group_id = 0; group_id < group_; ++group_id) {
      if (kernel_.size() == 2) {
        math::Im2col<T, Context, StorageOrder::NCHW>(
            X_data + group_id * input_stride,
            shape.C / group_,
            shape.input_image_dims[0],
            shape.input_image_dims[1],
            kernel_h(),
            kernel_w(),
            dilation_h(),
            dilation_w(),
            pad_t(),
            pad_l(),
            pad_b(),
            pad_r(),
            stride_h(),
            stride_w(),
            column_buffer_data + group_id * column_stride,
            &context_);
      } else {
        math::Im2colNd<T, Context, StorageOrder::NCHW>(
            X_data + group_id * input_stride,
            X_dims_device_.template data<int>(),
            column_dims_device_.template data<int>() + 1,
            shape.C * shape.input_image_size,
            column_stride,
            kernel_device_.template data<int>(),
            stride_device_.template data<int>(),
            dilation_device_.template data<int>(),
            pads_device_.template data<int>(),
            kernel_.size(),
            column_buffer_data + group_id * column_stride,
            &context_);
      }
    }
    X_data += input_stride * group_;
    column_buffer_data += column_stride * group_;
  }
  math::Transpose(
      shape.column_dims.size(),
      column_dims_device_.template data<int>(),
      column_transposed_dims_device_.template data<int>(),
      column_axes_device_.template data<int>(),
      column_buffer->size(),
      column_buffer->template data<T>(),
      column_transposed_buffer->template mutable_data<T>(),
      &context_);

  math::Transpose(
      shape.Y_transposed_dims.size(),
      dY_dims_device_.template data<int>(),
      dY_transposed_dims_device_.template data<int>(),
      dY_axes_device_.template data<int>(),
      dY_transposed_buffer->size(),
      dY_data,
      dY_transposed_buffer_data,
      &context_);

  // Gradient respect to filter.
  math::GemmBatched(
      CblasNoTrans,
      CblasTrans,
      shape.output_image_size * group_,
      shape.M / group_,
      shape.kernel_dim,
      shape.N,
      1.0f,
      dY_transposed_buffer_data,
      column_transposed_buffer->template data<T>(),
      0.0f,
      dfilter_data,
      &context_);

  if (dbias_data != nullptr) {
    // Gradient respect to bias.
    math::Gemv<T, Context>(
        CblasNoTrans,
        shape.output_image_size * shape.M,
        shape.N,
        1.0f,
        dY_transposed_buffer_data,
        bias_multiplier_.template data<T>(),
        0.0f,
        dbias_data,
        &context_);
  }

  if (dX_data != nullptr) {
    // Gradient respect to X.
    math::GemmBatched(
        CblasTrans,
        CblasNoTrans,
        shape.output_image_size * group_,
        shape.kernel_dim,
        shape.N,
        shape.M / group_,
        1.0f,
        filter_data,
        dY_transposed_buffer_data,
        0.0f,
        column_transposed_buffer->template mutable_data<T>(),
        &context_);
    math::Transpose(
        shape.column_dims.size(),
        column_transposed_dims_device_.template data<int>(),
        column_dims_device_.template data<int>(),
        column_transposed_axes_device_.template data<int>(),
        column_transposed_buffer->size(),
        column_transposed_buffer->template data<T>(),
        column_buffer->template mutable_data<T>(),
        &context_);
    const T* const_column_buffer_data = column_buffer->template data<T>();
    for (int image_id = 0; image_id < shape.N; ++image_id) {
      for (int group_id = 0; group_id < group_; ++group_id) {
        if (kernel_.size() == 2) {
          math::Col2im<T, Context, StorageOrder::NCHW>(
              const_column_buffer_data + group_id * column_stride,
              shape.C / group_,
              shape.input_image_dims[0],
              shape.input_image_dims[1],
              kernel_h(),
              kernel_w(),
              dilation_h(),
              dilation_w(),
              pad_t(),
              pad_l(),
              pad_b(),
              pad_r(),
              stride_h(),
              stride_w(),
              dX_data + group_id * input_stride,
              &context_);
        } else {
          math::Col2imNd<T, Context, StorageOrder::NCHW>(
              const_column_buffer_data + group_id * column_stride,
              X_dims_device_.template data<int>(),
              column_dims_device_.template data<int>() + 1,
              shape.C * shape.input_image_size,
              column_stride,
              kernel_device_.template data<int>(),
              stride_device_.template data<int>(),
              dilation_device_.template data<int>(),
              pads_device_.template data<int>(),
              kernel_.size(),
              dX_data + group_id * input_stride,
              &context_);
        }
      }
      dX_data += input_stride * group_;
      const_column_buffer_data += column_stride * group_;
    }
  }
}

template <typename T, class Context>
void LocallyConnectedGradientOp<T, Context>::RunOnDeviceWithOrderNHWCImpl(
    const lc_op_util::ShapeParams& shape,
    const T* X_data,
    const T* filter_data,
    const T* dY_data,
    T* dfilter_data,
    T* dX_data,
    T* dbias_data,
    Tensor<Context>* column_buffer,
    Tensor<Context>* column_transposed_buffer,
    Tensor<Context>* dY_transposed_buffer) {
  const int input_stride = shape.C * shape.input_image_size;
  const int column_stride = shape.kernel_dim * shape.output_image_size;
  column_buffer->Resize(shape.column_dims);
  column_transposed_buffer->Resize(shape.column_transposed_dims);
  dY_transposed_buffer->Resize(shape.Y_transposed_dims);
  T* column_buffer_data = column_buffer->template mutable_data<T>();
  T* dY_transposed_buffer_data =
      dY_transposed_buffer->template mutable_data<T>();
  for (int image_id = 0; image_id < shape.N; ++image_id) {
    math::Im2col<T, Context, StorageOrder::NHWC>(
        X_data + image_id * input_stride,
        shape.C,
        shape.input_image_dims[0],
        shape.input_image_dims[1],
        kernel_h(),
        kernel_w(),
        dilation_h(),
        dilation_w(),
        pad_t(),
        pad_l(),
        pad_b(),
        pad_r(),
        stride_h(),
        stride_w(),
        column_buffer_data + image_id * column_stride,
        &context_);
  }
  math::Transpose(
      shape.column_dims.size(),
      column_dims_device_.template data<int>(),
      column_transposed_dims_device_.template data<int>(),
      column_axes_device_.template data<int>(),
      column_buffer->size(),
      column_buffer->template data<T>(),
      column_transposed_buffer->template mutable_data<T>(),
      &context_);

  math::Transpose(
      shape.Y_transposed_dims.size(),
      dY_dims_device_.template data<int>(),
      dY_transposed_dims_device_.template data<int>(),
      dY_axes_device_.template data<int>(),
      dY_transposed_buffer->size(),
      dY_data,
      dY_transposed_buffer_data,
      &context_);

  // Gradient respect to filter.
  math::GemmBatched(
      CblasTrans,
      CblasNoTrans,
      shape.output_image_size,
      shape.M,
      shape.kernel_dim,
      shape.N,
      1.0f,
      dY_transposed_buffer_data,
      column_transposed_buffer->template data<T>(),
      0.0f,
      dfilter_data,
      &context_);

  if (dbias_data != nullptr) {
    // Gradient respect to bias.
    math::Gemv<T, Context>(
        CblasTrans,
        shape.N,
        shape.output_image_size * shape.M,
        1.0f,
        dY_data,
        bias_multiplier_.template data<T>(),
        0.0f,
        dbias_data,
        &context_);
  }

  if (dX_data != nullptr) {
    // Gradient respect to X.
    math::GemmBatched(
        CblasNoTrans,
        CblasNoTrans,
        shape.output_image_size,
        shape.N,
        shape.kernel_dim,
        shape.M,
        1.0f,
        dY_transposed_buffer_data,
        filter_data,
        0.0f,
        column_transposed_buffer->template mutable_data<T>(),
        &context_);
    math::Transpose(
        shape.column_dims.size(),
        column_transposed_dims_device_.template data<int>(),
        column_dims_device_.template data<int>(),
        column_transposed_axes_device_.template data<int>(),
        column_transposed_buffer->size(),
        column_transposed_buffer->template data<T>(),
        column_buffer->template mutable_data<T>(),
        &context_);
    const T* const_column_buffer_data = column_buffer->template data<T>();
    for (int image_id = 0; image_id < shape.N; ++image_id) {
      math::Col2im<T, Context, StorageOrder::NHWC>(
          const_column_buffer_data,
          shape.C,
          shape.input_image_dims[0],
          shape.input_image_dims[1],
          kernel_h(),
          kernel_w(),
          dilation_h(),
          dilation_w(),
          pad_t(),
          pad_l(),
          pad_b(),
          pad_r(),
          stride_h(),
          stride_w(),
          dX_data,
          &context_);
      dX_data += input_stride;
      const_column_buffer_data += column_stride;
    }
  }
}

template <typename T, class Context>
void LocallyConnectedGradientOp<T, Context>::SetColumnBufferShape(
    const int N,
    const int C,
    const int kernel_dim,
    const std::vector<int>& output_image_dims,
    std::vector<int>* column_dims,
    std::vector<int>* column_transposed_dims) {
  std::vector<int> column_axes;
  std::vector<int> column_transposed_axes;
  lc_op_util::SetColumnBufferShapeImpl(
      N,
      kernel_dim,
      order_,
      output_image_dims,
      column_dims,
      column_transposed_dims,
      &column_axes,
      &column_transposed_axes);
  SetDeviceTensor(*column_dims, &column_dims_device_);
  SetDeviceTensor(*column_transposed_dims, &column_transposed_dims_device_);
  SetDeviceTensor(column_axes, &column_axes_device_);
  SetDeviceTensor(column_transposed_axes, &column_transposed_axes_device_);
}

template <typename T, class Context>
void LocallyConnectedGradientOp<T, Context>::SetDYTranposedBufferShape(
    const std::vector<int>& dY_dims,
    std::vector<int>* dY_transposed_dims) {
  const int n_dY_dims = dY_dims.size();
  dY_transposed_dims->resize(n_dY_dims);
  std::vector<int> dY_axes(n_dY_dims);
  if (order_ == StorageOrder::NCHW) {
    for (int i = 0; i < n_dY_dims - 2; ++i) {
      dY_transposed_dims->at(i) = dY_dims[i + 2];
      dY_axes[i] = i + 2;
    }
    dY_transposed_dims->at(n_dY_dims - 2) = dY_dims[1];
    dY_transposed_dims->at(n_dY_dims - 1) = dY_dims[0];
    dY_axes[n_dY_dims - 2] = 1;
    dY_axes[n_dY_dims - 1] = 0;
  } else {
    for (int i = 0; i < n_dY_dims - 2; ++i) {
      dY_transposed_dims->at(i) = dY_dims[i + 1];
      dY_axes[i] = i + 1;
    }
    dY_transposed_dims->at(n_dY_dims - 2) = dY_dims[0];
    dY_transposed_dims->at(n_dY_dims - 1) = dY_dims[n_dY_dims - 1];
    dY_axes[n_dY_dims - 2] = 0;
    dY_axes[n_dY_dims - 1] = n_dY_dims - 1;
  }
  SetDeviceTensor(dY_dims, &dY_dims_device_);
  SetDeviceTensor(*dY_transposed_dims, &dY_transposed_dims_device_);
  SetDeviceTensor(dY_axes, &dY_axes_device_);
}

} // namespace caffe2

#endif // CAFFE2_OPERATORS_LOCALLY_CONNECTED_OP_IMPL_H_


text:
package com.opengamma.master;

import java.util.Map;

import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectBean;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;

import com.opengamma.util.PublicSPI;
import org.joda.beans.Property;
import org.joda.beans.impl.direct.DirectMetaProperty;

/**
 * Request for meta-data about a single master.
 * <p>
 * Some user interfaces require meta-data in order to operate, such as
 * a drop-down list of valid entries to select from. This abstract class
 * provides the basic ability to request such meta-data.
 */
@PublicSPI
@BeanDefinition
public abstract class AbstractMetaDataRequest extends DirectBean {

  /**
   * The uniqueIdScheme of the underlying master to search. Wildcards are not allowed.
   */
  @PropertyDefinition
  private String _uniqueIdScheme;

  /**
   * Creates an instance.
   */
  public AbstractMetaDataRequest() {
  }

  //------------------------- AUTOGENERATED START -------------------------
  ///CLOVER:OFF
  /**
   * The meta-bean for {@code AbstractMetaDataRequest}.
   * @return the meta-bean, not null
   */
  public static AbstractMetaDataRequest.Meta meta() {
    return AbstractMetaDataRequest.Meta.INSTANCE;
  }

  static {
    JodaBeanUtils.registerMetaBean(AbstractMetaDataRequest.Meta.INSTANCE);
  }

  @Override
  public AbstractMetaDataRequest.Meta metaBean() {
    return AbstractMetaDataRequest.Meta.INSTANCE;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the uniqueIdScheme of the underlying master to search. Wildcards are not allowed.
   * @return the value of the property
   */
  public String getUniqueIdScheme() {
    return _uniqueIdScheme;
  }

  /**
   * Sets the uniqueIdScheme of the underlying master to search. Wildcards are not allowed.
   * @param uniqueIdScheme  the new value of the property
   */
  public void setUniqueIdScheme(String uniqueIdScheme) {
    this._uniqueIdScheme = uniqueIdScheme;
  }

  /**
   * Gets the the {@code uniqueIdScheme} property.
   * @return the property, not null
   */
  public final Property<String> uniqueIdScheme() {
    return metaBean().uniqueIdScheme().createProperty(this);
  }

  //-----------------------------------------------------------------------
  @Override
  public AbstractMetaDataRequest clone() {
    return JodaBeanUtils.cloneAlways(this);
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj != null && obj.getClass() == this.getClass()) {
      AbstractMetaDataRequest other = (AbstractMetaDataRequest) obj;
      return JodaBeanUtils.equal(getUniqueIdScheme(), other.getUniqueIdScheme());
    }
    return false;
  }

  @Override
  public int hashCode() {
    int hash = getClass().hashCode();
    hash = hash * 31 + JodaBeanUtils.hashCode(getUniqueIdScheme());
    return hash;
  }

  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder(64);
    buf.append("AbstractMetaDataRequest{");
    int len = buf.length();
    toString(buf);
    if (buf.length() > len) {
      buf.setLength(buf.length() - 2);
    }
    buf.append('}');
    return buf.toString();
  }

  protected void toString(StringBuilder buf) {
    buf.append("uniqueIdScheme").append('=').append(JodaBeanUtils.toString(getUniqueIdScheme())).append(',').append(' ');
  }

  //-----------------------------------------------------------------------
  /**
   * The meta-bean for {@code AbstractMetaDataRequest}.
   */
  public static class Meta extends DirectMetaBean {
    /**
     * The singleton instance of the meta-bean.
     */
    static final Meta INSTANCE = new Meta();

    /**
     * The meta-property for the {@code uniqueIdScheme} property.
     */
    private final MetaProperty<String> _uniqueIdScheme = DirectMetaProperty.ofReadWrite(
        this, "uniqueIdScheme", AbstractMetaDataRequest.class, String.class);
    /**
     * The meta-properties.
     */
    private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
        this, null,
        "uniqueIdScheme");

    /**
     * Restricted constructor.
     */
    protected Meta() {
    }

    @Override
    protected MetaProperty<?> metaPropertyGet(String propertyName) {
      switch (propertyName.hashCode()) {
        case -1737146991:  // uniqueIdScheme
          return _uniqueIdScheme;
      }
      return super.metaPropertyGet(propertyName);
    }

    @Override
    public BeanBuilder<? extends AbstractMetaDataRequest> builder() {
      throw new UnsupportedOperationException("AbstractMetaDataRequest is an abstract class");
    }

    @Override
    public Class<? extends AbstractMetaDataRequest> beanType() {
      return AbstractMetaDataRequest.class;
    }

    @Override
    public Map<String, MetaProperty<?>> metaPropertyMap() {
      return _metaPropertyMap$;
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-property for the {@code uniqueIdScheme} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<String> uniqueIdScheme() {
      return _uniqueIdScheme;
    }

    //-----------------------------------------------------------------------
    @Override
    protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
      switch (propertyName.hashCode()) {
        case -1737146991:  // uniqueIdScheme
          return ((AbstractMetaDataRequest) bean).getUniqueIdScheme();
      }
      return super.propertyGet(bean, propertyName, quiet);
    }

    @Override
    protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
      switch (propertyName.hashCode()) {
        case -1737146991:  // uniqueIdScheme
          ((AbstractMetaDataRequest) bean).setUniqueIdScheme((String) newValue);
          return;
      }
      super.propertySet(bean, propertyName, newValue, quiet);
    }

  }

  ///CLOVER:ON
  //-------------------------- AUTOGENERATED END --------------------------
}


text:
package com.marcelmika.lims.persistence.generated.service.base;

import com.marcelmika.lims.persistence.generated.service.PanelLocalServiceUtil;

import java.util.Arrays;

/**
 * @author Brian Wing Shun Chan
 * @generated
 */
public class PanelLocalServiceClpInvoker {
	public PanelLocalServiceClpInvoker() {
		_methodName0 = "addPanel";

		_methodParameterTypes0 = new String[] {
				"com.marcelmika.lims.persistence.generated.model.Panel"
			};

		_methodName1 = "createPanel";

		_methodParameterTypes1 = new String[] { "long" };

		_methodName2 = "deletePanel";

		_methodParameterTypes2 = new String[] { "long" };

		_methodName3 = "deletePanel";

		_methodParameterTypes3 = new String[] {
				"com.marcelmika.lims.persistence.generated.model.Panel"
			};

		_methodName4 = "dynamicQuery";

		_methodParameterTypes4 = new String[] {  };

		_methodName5 = "dynamicQuery";

		_methodParameterTypes5 = new String[] {
				"com.liferay.portal.kernel.dao.orm.DynamicQuery"
			};

		_methodName6 = "dynamicQuery";

		_methodParameterTypes6 = new String[] {
				"com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int"
			};

		_methodName7 = "dynamicQuery";

		_methodParameterTypes7 = new String[] {
				"com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int",
				"com.liferay.portal.kernel.util.OrderByComparator"
			};

		_methodName8 = "dynamicQueryCount";

		_methodParameterTypes8 = new String[] {
				"com.liferay.portal.kernel.dao.orm.DynamicQuery"
			};

		_methodName9 = "dynamicQueryCount";

		_methodParameterTypes9 = new String[] {
				"com.liferay.portal.kernel.dao.orm.DynamicQuery",
				"com.liferay.portal.kernel.dao.orm.Projection"
			};

		_methodName10 = "fetchPanel";

		_methodParameterTypes10 = new String[] { "long" };

		_methodName11 = "getPanel";

		_methodParameterTypes11 = new String[] { "long" };

		_methodName12 = "getPersistedModel";

		_methodParameterTypes12 = new String[] { "java.io.Serializable" };

		_methodName13 = "getPanels";

		_methodParameterTypes13 = new String[] { "int", "int" };

		_methodName14 = "getPanelsCount";

		_methodParameterTypes14 = new String[] {  };

		_methodName15 = "updatePanel";

		_methodParameterTypes15 = new String[] {
				"com.marcelmika.lims.persistence.generated.model.Panel"
			};

		_methodName50 = "getBeanIdentifier";

		_methodParameterTypes50 = new String[] {  };

		_methodName51 = "setBeanIdentifier";

		_methodParameterTypes51 = new String[] { "java.lang.String" };

		_methodName56 = "getPanelByUser";

		_methodParameterTypes56 = new String[] { "long" };

		_methodName57 = "updateActivePanel";

		_methodParameterTypes57 = new String[] { "long", "java.lang.String" };
	}

	public Object invokeMethod(String name, String[] parameterTypes,
		Object[] arguments) throws Throwable {
		if (_methodName0.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes0, parameterTypes)) {
			return PanelLocalServiceUtil.addPanel((com.marcelmika.lims.persistence.generated.model.Panel)arguments[0]);
		}

		if (_methodName1.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes1, parameterTypes)) {
			return PanelLocalServiceUtil.createPanel(((Long)arguments[0]).longValue());
		}

		if (_methodName2.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes2, parameterTypes)) {
			return PanelLocalServiceUtil.deletePanel(((Long)arguments[0]).longValue());
		}

		if (_methodName3.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes3, parameterTypes)) {
			return PanelLocalServiceUtil.deletePanel((com.marcelmika.lims.persistence.generated.model.Panel)arguments[0]);
		}

		if (_methodName4.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes4, parameterTypes)) {
			return PanelLocalServiceUtil.dynamicQuery();
		}

		if (_methodName5.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes5, parameterTypes)) {
			return PanelLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0]);
		}

		if (_methodName6.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes6, parameterTypes)) {
			return PanelLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0],
				((Integer)arguments[1]).intValue(),
				((Integer)arguments[2]).intValue());
		}

		if (_methodName7.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes7, parameterTypes)) {
			return PanelLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0],
				((Integer)arguments[1]).intValue(),
				((Integer)arguments[2]).intValue(),
				(com.liferay.portal.kernel.util.OrderByComparator)arguments[3]);
		}

		if (_methodName8.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes8, parameterTypes)) {
			return PanelLocalServiceUtil.dynamicQueryCount((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0]);
		}

		if (_methodName9.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes9, parameterTypes)) {
			return PanelLocalServiceUtil.dynamicQueryCount((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0],
				(com.liferay.portal.kernel.dao.orm.Projection)arguments[1]);
		}

		if (_methodName10.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes10, parameterTypes)) {
			return PanelLocalServiceUtil.fetchPanel(((Long)arguments[0]).longValue());
		}

		if (_methodName11.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes11, parameterTypes)) {
			return PanelLocalServiceUtil.getPanel(((Long)arguments[0]).longValue());
		}

		if (_methodName12.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes12, parameterTypes)) {
			return PanelLocalServiceUtil.getPersistedModel((java.io.Serializable)arguments[0]);
		}

		if (_methodName13.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes13, parameterTypes)) {
			return PanelLocalServiceUtil.getPanels(((Integer)arguments[0]).intValue(),
				((Integer)arguments[1]).intValue());
		}

		if (_methodName14.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes14, parameterTypes)) {
			return PanelLocalServiceUtil.getPanelsCount();
		}

		if (_methodName15.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes15, parameterTypes)) {
			return PanelLocalServiceUtil.updatePanel((com.marcelmika.lims.persistence.generated.model.Panel)arguments[0]);
		}

		if (_methodName50.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes50, parameterTypes)) {
			return PanelLocalServiceUtil.getBeanIdentifier();
		}

		if (_methodName51.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes51, parameterTypes)) {
			PanelLocalServiceUtil.setBeanIdentifier((java.lang.String)arguments[0]);

			return null;
		}

		if (_methodName56.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes56, parameterTypes)) {
			return PanelLocalServiceUtil.getPanelByUser(((Long)arguments[0]).longValue());
		}

		if (_methodName57.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes57, parameterTypes)) {
			PanelLocalServiceUtil.updateActivePanel(((Long)arguments[0]).longValue(),
				(java.lang.String)arguments[1]);

			return null;
		}

		throw new UnsupportedOperationException();
	}

	private String _methodName0;
	private String[] _methodParameterTypes0;
	private String _methodName1;
	private String[] _methodParameterTypes1;
	private String _methodName2;
	private String[] _methodParameterTypes2;
	private String _methodName3;
	private String[] _methodParameterTypes3;
	private String _methodName4;
	private String[] _methodParameterTypes4;
	private String _methodName5;
	private String[] _methodParameterTypes5;
	private String _methodName6;
	private String[] _methodParameterTypes6;
	private String _methodName7;
	private String[] _methodParameterTypes7;
	private String _methodName8;
	private String[] _methodParameterTypes8;
	private String _methodName9;
	private String[] _methodParameterTypes9;
	private String _methodName10;
	private String[] _methodParameterTypes10;
	private String _methodName11;
	private String[] _methodParameterTypes11;
	private String _methodName12;
	private String[] _methodParameterTypes12;
	private String _methodName13;
	private String[] _methodParameterTypes13;
	private String _methodName14;
	private String[] _methodParameterTypes14;
	private String _methodName15;
	private String[] _methodParameterTypes15;
	private String _methodName50;
	private String[] _methodParameterTypes50;
	private String _methodName51;
	private String[] _methodParameterTypes51;
	private String _methodName56;
	private String[] _methodParameterTypes56;
	private String _methodName57;
	private String[] _methodParameterTypes57;
}


text:
package mqtt

import (
	"fmt"
	"reflect"
	"regexp"

	"github.com/LoRaWanSoFa/ttn/core/types"
)

// DeviceTopicType represents the type of a device topic
type DeviceTopicType string

const (
	// Activations of devices
	Activations DeviceTopicType = "activations"
	// Uplink data from devices
	Uplink DeviceTopicType = "up"
	// Downlink data to devices
	Downlink DeviceTopicType = "down"
)

const wildcard = "+"

// DeviceTopic represents an MQTT topic for application devices
// If the DevEUI is an empty []byte{}, it is considered to be a wildcard
type DeviceTopic struct {
	AppEUI types.AppEUI
	DevEUI types.DevEUI
	Type   DeviceTopicType
}

// ParseDeviceTopic parses an MQTT device topic string to a DeviceTopic struct
func ParseDeviceTopic(topic string) (*DeviceTopic, error) {
	var err error
	pattern := regexp.MustCompile("([0-9A-F]{16}|\\+)/(devices)/([0-9A-F]{16}|\\+)/(activations|up|down)")
	matches := pattern.FindStringSubmatch(topic)
	if len(matches) < 4 {
		return nil, fmt.Errorf("Invalid topic format")
	}
	var appEUI types.AppEUI
	if matches[1] != wildcard {
		appEUI, err = types.ParseAppEUI(matches[1])
		if err != nil {
			return nil, err
		}
	}
	var devEUI types.DevEUI
	if matches[1] != wildcard {
		devEUI, err = types.ParseDevEUI(matches[3])
		if err != nil {
			return nil, err
		}
	}
	topicType := DeviceTopicType(matches[4])
	return &DeviceTopic{appEUI, devEUI, topicType}, nil
}

// String implements the Stringer interface
func (t DeviceTopic) String() string {
	appEUI := wildcard
	if !reflect.DeepEqual(t.AppEUI, types.AppEUI{}) {
		appEUI = t.AppEUI.String()
	}
	devEUI := wildcard
	if !reflect.DeepEqual(t.DevEUI, types.DevEUI{}) {
		devEUI = t.DevEUI.String()
	}
	return fmt.Sprintf("%s/%s/%s/%s", appEUI, "devices", devEUI, t.Type)
}


text:
package com.yanzhenjie.album.widget.divider;

import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.annotation.ColorInt;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;

/**
 *
The implementation of divider does not add dividers around the list.

 * Created by YanZhenjie on 2017/8/14.
 */
public class Api20ItemDivider extends Divider {

    private final int mWidth;
    private final int mHeight;
    private final Drawer mDrawer;

    /**
     * @param color divider line color.
     */
    public Api20ItemDivider(@ColorInt int color) {
        this(color, 4, 4);
    }

    /**
     * @param color  line color.
     * @param width  line width.
     * @param height line height.
     */
    public Api20ItemDivider(@ColorInt int color, int width, int height) {
        this.mWidth = Math.round(width / 2F);
        this.mHeight = Math.round(height / 2F);
        this.mDrawer = new ColorDrawer(color, mWidth, mHeight);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof LinearLayoutManager) {
            int orientation = getOrientation(layoutManager);
            int position = parent.getChildLayoutPosition(view);
            int spanCount = getSpanCount(layoutManager);
            int childCount = layoutManager.getItemCount();

            if (orientation == RecyclerView.VERTICAL) {
                offsetVertical(outRect, position, spanCount, childCount);
            } else {
                offsetHorizontal(outRect, position, spanCount, childCount);
            }
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            outRect.set(mWidth, mHeight, mWidth, mHeight); // |-|-
        }
    }

    private void offsetHorizontal(Rect outRect, int position, int spanCount, int childCount) {
        boolean firstRaw = isFirstRaw(RecyclerView.HORIZONTAL, position, spanCount, childCount);
        boolean lastRaw = isLastRaw(RecyclerView.HORIZONTAL, position, spanCount, childCount);
        boolean firstColumn = isFirstColumn(RecyclerView.HORIZONTAL, position, spanCount, childCount);
        boolean lastColumn = isLastColumn(RecyclerView.HORIZONTAL, position, spanCount, childCount);

        if (spanCount == 1) {
            if (firstColumn && lastColumn) { // xxxx
                outRect.set(0, 0, 0, 0);
            } else if (firstColumn) { // xx|x
                outRect.set(0, 0, mWidth, 0);
            } else if (lastColumn) { // |xxx
                outRect.set(mWidth, 0, 0, 0);
            } else { // |x|x
                outRect.set(mWidth, 0, mWidth, 0);
            }
        } else {
            if (firstColumn && firstRaw) { // xx|-
                outRect.set(0, 0, mWidth, mHeight);
            } else if (firstColumn && lastRaw) { // x-|x
                outRect.set(0, mHeight, mWidth, 0);
            } else if (lastColumn && firstRaw) { // |xx-
                outRect.set(mWidth, 0, 0, mHeight);
            } else if (lastColumn && lastRaw) { // |-xx
                outRect.set(mWidth, mHeight, 0, 0);
            } else if (firstColumn) { // x-|-
                outRect.set(0, mHeight, mWidth, mHeight);
            } else if (lastColumn) { // |-x-
                outRect.set(mWidth, mHeight, 0, mHeight);
            } else if (firstRaw) { // |x|-
                outRect.set(mWidth, 0, mWidth, mHeight);
            } else if (lastRaw) { // |-|x
                outRect.set(mWidth, mHeight, mWidth, 0);
            } else { // |-|-
                outRect.set(mWidth, mHeight, mWidth, mHeight);
            }
        }
    }

    private void offsetVertical(Rect outRect, int position, int spanCount, int childCount) {
        boolean firstRaw = isFirstRaw(RecyclerView.VERTICAL, position, spanCount, childCount);
        boolean lastRaw = isLastRaw(RecyclerView.VERTICAL, position, spanCount, childCount);
        boolean firstColumn = isFirstColumn(RecyclerView.VERTICAL, position, spanCount, childCount);
        boolean lastColumn = isLastColumn(RecyclerView.VERTICAL, position, spanCount, childCount);

        if (spanCount == 1) {
            if (firstRaw && lastRaw) { // xxxx
                outRect.set(0, 0, 0, 0);
            } else if (firstRaw) { // xxx-
                outRect.set(0, 0, 0, mHeight);
            } else if (lastRaw) { // x-xx
                outRect.set(0, mHeight, 0, 0);
            } else { // x-x-
                outRect.set(0, mHeight, 0, mHeight);
            }
        } else {
            if (firstRaw && firstColumn) { // xx|-
                outRect.set(0, 0, mWidth, mHeight);
            } else if (firstRaw && lastColumn) { // |xx-
                outRect.set(mWidth, 0, 0, mHeight);
            } else if (lastRaw && firstColumn) { // x-|x
                outRect.set(0, mHeight, mWidth, 0);
            } else if (lastRaw && lastColumn) { // |-xx
                outRect.set(mWidth, mHeight, 0, 0);
            } else if (firstRaw) { // |x|-
                outRect.set(mWidth, 0, mWidth, mHeight);
            } else if (lastRaw) { // |-|x
                outRect.set(mWidth, mHeight, mWidth, 0);
            } else if (firstColumn) { // x-|-
                outRect.set(0, mHeight, mWidth, mHeight);
            } else if (lastColumn) { // |-x-
                outRect.set(mWidth, mHeight, 0, mHeight);
            } else { // |-|-
                outRect.set(mWidth, mHeight, mWidth, mHeight);
            }
        }
    }

    private int getOrientation(RecyclerView.LayoutManager layoutManager) {
        if (layoutManager instanceof LinearLayoutManager) {
            return ((LinearLayoutManager) layoutManager).getOrientation();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            return ((StaggeredGridLayoutManager) layoutManager).getOrientation();
        }
        return RecyclerView.VERTICAL;
    }

    private int getSpanCount(RecyclerView.LayoutManager layoutManager) {
        if (layoutManager instanceof GridLayoutManager) {
            return ((GridLayoutManager) layoutManager).getSpanCount();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            return ((StaggeredGridLayoutManager) layoutManager).getSpanCount();
        }
        return 1;
    }

    private boolean isFirstRaw(int orientation, int position, int columnCount, int childCount) {
        if (orientation == RecyclerView.VERTICAL) {
            return position < columnCount;
        } else {
            if (columnCount == 1) return true;
            return position % columnCount == 0;
        }
    }

    private boolean isLastRaw(int orientation, int position, int columnCount, int childCount) {
        if (orientation == RecyclerView.VERTICAL) {
            if (columnCount == 1) {
                return position + 1 == childCount;
            } else {
                int lastRawItemCount = childCount % columnCount;
                int rawCount = (childCount - lastRawItemCount) / columnCount + (lastRawItemCount > 0 ? 1 : 0);

                int rawPositionJudge = (position + 1) % columnCount;
                if (rawPositionJudge == 0) {
                    int positionRaw = (position + 1) / columnCount;
                    return rawCount == positionRaw;
                } else {
                    int rawPosition = (position + 1 - rawPositionJudge) / columnCount + 1;
                    return rawCount == rawPosition;
                }
            }
        } else {
            if (columnCount == 1) return true;
            return (position + 1) % columnCount == 0;
        }
    }

    private boolean isFirstColumn(int orientation, int position, int columnCount, int childCount) {
        if (orientation == RecyclerView.VERTICAL) {
            if (columnCount == 1) return true;
            return position % columnCount == 0;
        } else {
            return position < columnCount;
        }
    }

    private boolean isLastColumn(int orientation, int position, int columnCount, int childCount) {
        if (orientation == RecyclerView.VERTICAL) {
            if (columnCount == 1) return true;
            return (position + 1) % columnCount == 0;
        } else {
            if (columnCount == 1) {
                return position + 1 == childCount;
            } else {
                int lastRawItemCount = childCount % columnCount;
                int rawCount = (childCount - lastRawItemCount) / columnCount + (lastRawItemCount > 0 ? 1 : 0);

                int rawPositionJudge = (position + 1) % columnCount;
                if (rawPositionJudge == 0) {
                    int positionRaw = (position + 1) / columnCount;
                    return rawCount == positionRaw;
                } else {
                    int rawPosition = (position + 1 - rawPositionJudge) / columnCount + 1;
                    return rawCount == rawPosition;
                }
            }
        }
    }

    @Override
    public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        int orientation = getOrientation(layoutManager);
        int spanCount = getSpanCount(layoutManager);
        int childCount = layoutManager.getChildCount();

        if (layoutManager instanceof LinearLayoutManager) {
            canvas.save();
            for (int i = 0; i < childCount; i++) {
                View view = layoutManager.getChildAt(i);
                int position = parent.getChildLayoutPosition(view);

                if (orientation == RecyclerView.VERTICAL) {
                    drawVertical(canvas, view, position, spanCount, childCount);
                } else {
                    drawHorizontal(canvas, view, position, spanCount, childCount);
                }
            }
            canvas.restore();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            canvas.save();
            for (int i = 0; i < childCount; i++) {
                View view = layoutManager.getChildAt(i);
                mDrawer.drawLeft(view, canvas);
                mDrawer.drawTop(view, canvas);
                mDrawer.drawRight(view, canvas);
                mDrawer.drawBottom(view, canvas);
            }
            canvas.restore();
        }
    }

    private void drawHorizontal(Canvas canvas, View view, int position, int spanCount, int childCount) {
        boolean firstRaw = isFirstRaw(RecyclerView.HORIZONTAL, position, spanCount, childCount);
        boolean lastRaw = isLastRaw(RecyclerView.HORIZONTAL, position, spanCount, childCount);
        boolean firstColumn = isFirstColumn(RecyclerView.HORIZONTAL, position, spanCount, childCount);
        boolean lastColumn = isLastColumn(RecyclerView.HORIZONTAL, position, spanCount, childCount);

        if (spanCount == 1) {
            if (firstRaw && lastColumn) { // xxxx
                // Nothing.
            } else if (firstColumn) { // xx|x
                mDrawer.drawRight(view, canvas);
            } else if (lastColumn) { // |xxx
                mDrawer.drawLeft(view, canvas);
            } else { // |x|x
                mDrawer.drawLeft(view, canvas);
                mDrawer.drawRight(view, canvas);
            }
        } else {
            if (firstColumn && firstRaw) { // xx|-
                mDrawer.drawRight(view, canvas);
                mDrawer.drawBottom(view, canvas);
            } else if (firstColumn && lastRaw) { // x-|x
                mDrawer.drawTop(view, canvas);
                mDrawer.drawRight(view, canvas);
            } else if (lastColumn && firstRaw) { // |xx-
                mDrawer.drawLeft(view, canvas);
                mDrawer.drawBottom(view, canvas);
            } else if (lastColumn && lastRaw) { // |-xx
                mDrawer.drawLeft(view, canvas);
                mDrawer.drawTop(view, canvas);
            } else if (firstColumn) { // x-|-
                mDrawer.drawTop(view, canvas);
                mDrawer.drawRight(view, canvas);
                mDrawer.drawBottom(view, canvas);
            } else if (lastColumn) { // |-x-
                mDrawer.drawLeft(view, canvas);
                mDrawer.drawTop(view, canvas);
                mDrawer.drawBottom(view, canvas);
            } else if (firstRaw) { // |x|-
                mDrawer.drawLeft(view, canvas);
                mDrawer.drawRight(view, canvas);
                mDrawer.drawBottom(view, canvas);
            } else if (lastRaw) { // |-|x
                mDrawer.drawLeft(view, canvas);
                mDrawer.drawTop(view, canvas);
                mDrawer.drawRight(view, canvas);
            } else { // |-|-
                mDrawer.drawLeft(view, canvas);
                mDrawer.drawTop(view, canvas);
                mDrawer.drawRight(view, canvas);
                mDrawer.drawBottom(view, canvas);
            }
        }
    }

    private void drawVertical(Canvas canvas, View view, int position, int spanCount, int childCount) {
        boolean firstRaw = isFirstRaw(RecyclerView.VERTICAL, position, spanCount, childCount);
        boolean lastRaw = isLastRaw(RecyclerView.VERTICAL, position, spanCount, childCount);
        boolean firstColumn = isFirstColumn(RecyclerView.VERTICAL, position, spanCount, childCount);
        boolean lastColumn = isLastColumn(RecyclerView.VERTICAL, position, spanCount, childCount);

        if (spanCount == 1) {
            if (firstRaw && lastRaw) { // xxxx
                // Nothing.
            } else if (firstRaw) { // xxx-
                mDrawer.drawBottom(view, canvas);
            } else if (lastRaw) { // x-xx
                mDrawer.drawTop(view, canvas);
            } else { // x-x-
                mDrawer.drawTop(view, canvas);
                mDrawer.drawBottom(view, canvas);
            }
        } else {
            if (firstRaw && firstColumn) { // xx|-
                mDrawer.drawRight(view, canvas);
                mDrawer.drawBottom(view, canvas);
            } else if (firstRaw && lastColumn) { // |xx-
                mDrawer.drawLeft(view, canvas);
                mDrawer.drawBottom(view, canvas);
            } else if (lastRaw && firstColumn) { // x-|x
                mDrawer.drawTop(view, canvas);
                mDrawer.drawRight(view, canvas);
            } else if (lastRaw && lastColumn) { // |-xx
                mDrawer.drawLeft(view, canvas);
                mDrawer.drawTop(view, canvas);
            } else if (firstRaw) { // |x|-
                mDrawer.drawLeft(view, canvas);
                mDrawer.drawRight(view, canvas);
                mDrawer.drawBottom(view, canvas);
            } else if (lastRaw) { // |-|x
                mDrawer.drawLeft(view, canvas);
                mDrawer.drawTop(view, canvas);
                mDrawer.drawRight(view, canvas);
            } else if (firstColumn) { // x-|-
                mDrawer.drawTop(view, canvas);
                mDrawer.drawRight(view, canvas);
                mDrawer.drawBottom(view, canvas);
            } else if (lastColumn) { // |-x-
                mDrawer.drawLeft(view, canvas);
                mDrawer.drawTop(view, canvas);
                mDrawer.drawBottom(view, canvas);
            } else { // |-|-
                mDrawer.drawLeft(view, canvas);
                mDrawer.drawTop(view, canvas);
                mDrawer.drawRight(view, canvas);
                mDrawer.drawBottom(view, canvas);
            }
        }
    }

    @Override
    public int getHeight() {
        return mHeight;
    }

    @Override
    public int getWidth() {
        return mWidth;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;

namespace VirtualScene.DataComponents.Common.DataAdapters.FileSystem.Archive
{
    internal class XmlSerializerPool
    {
        private readonly Dictionary<Type, XmlSerializer> _xmlSerializers = new Dictionary<Type, XmlSerializer>();

        public XmlSerializer GetSerializerBy<TObject>(TObject obj)
        {
            return GetSerializerByType(obj.GetType());
        }

        public XmlSerializer GetSerializer<TObject>()
        {
            return GetSerializerByType(typeof(TObject));
        }

        public XmlSerializer GetSerializerByType(Type type)
        {
            if (!_xmlSerializers.ContainsKey(type))
                _xmlSerializers.Add(type, new XmlSerializer(type));
            return _xmlSerializers[type];
        }

    }
}


text:
#pragma once
#include <aws/swf/SWF_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace SWF
{
namespace Model
{
  /*

Used to filter the workflow executions in visibility APIs by their workflowId.

  */
  class AWS_SWF_API WorkflowExecutionFilter
  {
  public:
    WorkflowExecutionFilter();
    WorkflowExecutionFilter(const Aws::Utils::Json::JsonValue& jsonValue);
    WorkflowExecutionFilter& operator=(const Aws::Utils::Json::JsonValue& jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /*

The workflowId to pass of match the criteria of this filter.

    */
    inline const Aws::String& GetWorkflowId() const{ return m_workflowId; }

    /*

The workflowId to pass of match the criteria of this filter.

    */
    inline void SetWorkflowId(const Aws::String& value) { m_workflowIdHasBeenSet = true; m_workflowId = value; }

    /*

The workflowId to pass of match the criteria of this filter.

    */
    inline void SetWorkflowId(Aws::String&& value) { m_workflowIdHasBeenSet = true; m_workflowId = value; }

    /*

The workflowId to pass of match the criteria of this filter.

    */
    inline void SetWorkflowId(const char* value) { m_workflowIdHasBeenSet = true; m_workflowId.assign(value); }

    /*

The workflowId to pass of match the criteria of this filter.

    */
    inline WorkflowExecutionFilter& WithWorkflowId(const Aws::String& value) { SetWorkflowId(value); return *this;}

    /*

The workflowId to pass of match the criteria of this filter.

    */
    inline WorkflowExecutionFilter& WithWorkflowId(Aws::String&& value) { SetWorkflowId(value); return *this;}

    /*

The workflowId to pass of match the criteria of this filter.

    */
    inline WorkflowExecutionFilter& WithWorkflowId(const char* value) { SetWorkflowId(value); return *this;}

  private:
    Aws::String m_workflowId;
    bool m_workflowIdHasBeenSet;
  };

} // namespace Model
} // namespace SWF
} // namespace Aws


text:
hs.win.Result = Ext.extend (Ext.Window, {
    constructor: function (node, config) {
	var perm = 0;
	var text;
	var urlText;
	var urlPanel;

	var result_id = node.id;
	var title = node.name;

	var pubURL = 'Public URL: ' + window.location.host + '/app/tool/result/load?id=' + result_id;

	function togglePerm  () {
	    if (perm) {
		text = 'Make Result Private';
		perm = 0;
		urlText = pubURL;
	    }
	    else {
		text = 'Make Result Public';
		perm = 1;
		urlText = ' ';
	    }
	};
	togglePerm ();

	var publicButton = new Ext.Button ({
	    text: text,
	    handler: function (b, e) {
		Ext.Ajax.request ({
		    method: 'GET',
		    url: '/' + hs.application + '/tool/result/publish',
		    params: {
			id: result_id,
			perm: perm,
		    },
		});
		togglePerm ();
		urlPanel.update (urlText);
		b.setText (text);
	    },
	});

	var exportButton = new Ext.Button ({
	    text: 'Export',
	    handler: function (b, e) {
		Ext.Ajax.request ({
		    method: 'GET',
		    url: hs.url ('tool', 'result', ['export_available']),
		    params: {
			id: result_id,
		    },
		    success: function  (data) {
			var types = JSON.parse (data.responseText);
			var selections = [];
			for (var i = 0; i < types.length; i ++) {
			    selections.push ({
				inputValue: types[i].id,
				boxLabel: types[i].name,
				name: 'export_mode',
			    });
			}
			var radio = new Ext.form.RadioGroup  ({
			    items: selections,
			    width: 200,
			});

			var input = new Ext.form.TextField ({
			    emptyText: 'Filename',
			    width: 200,
			});

			var win = new Ext.Window ({
			    title: 'Export Result',
			    width: 200,
			    items: [
				radio,
				input,
			    ],
			    buttons: [
				new Ext.Button ({
				    text: 'Export',
				    handler: function (b, e) {
					window.location = hs.url ('tool', 'result', ['export'], {
					    id: result_id,
					    mode: radio.getValue ().inputValue,
					    filename: input.getValue (),
					});
				    },
				}),
			    ],
			});
			win.show ()
		    },
		});
	    },
	});

	var result = new hs.util.IFramePanel ({
	    region: 'center',
	}, '/' + hs.application + '/tool/result/load?id=' + result_id);

	urlPanel = new Ext.Panel ({
	    region: 'south',
	    height: 'autoHeight',
	    padding: 10,
	    html: ' ',
	    //hidden: (perm == 1),
	});

	Ext.apply (config, {
	    layout: 'border',
	    width: 800,
	    height: 600,
	    hideBorders: true,
	    title: title,
	    items: [
		result,
		urlPanel,
	    ],
	    buttons: [
		exportButton,
		publicButton,
	    ],
	});
	hs.win.Result.superclass.constructor.call(this,  config);
    },
});


text:
<?php include 'functions.php';?><!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Eureka Media Browser</title>
        <meta name="description" content="HTML-first crack at a Flexible Media Browser">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="assets/css/eureka.0.0.0.css?nc=<?php echo time() ?>">

        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" async>

        <form>

Media Source

                                        <select id="media-browser_0__mediasource-select" title="Choose a Media Source to browse">

                                            <option value='0' selected>Filesystem</option>
                                            <option value='1'>Assets</option>
                                            <option value='2'>Amazon S3</option>
                                        </select>

Browse Parent Directory

                                                assets

                                                    assets/images

                                            uploads

                                        <form action="#">
                                            <input type="hidden" name="mediasource" value="0">
                                            <input type="hidden" name="mediapath" value="assets/images">
                                            <button type="submit" class="nued create-new" title="Create a new directory in assets/images">

Create a new directory in assets/images

                                            </button>
                                        </form>
                                        <form action="#">
                                            <input type="hidden" name="mediasource" value="0">
                                            <input type="hidden" name="mediapath" value="assets/images">
                                            <button type="submit" class="nued upload-files" title="Upload media to assets/images">

Upload media to assets/images

                                            </button>
                                        </form>

Media Content

                                            <form>

                                                <input id="media-browser_0__filter-images" disabled js-enabled type="search" placeholder="Please enable JavaScript" asyncronous-placeholder="Filter images" autocomplete="off">
                                            </form>

                                                Browsing:
                                                <form aciton="#" id="media-browser_0__browsing">
                                                    <select name="media-browser_0__browsing">

                                                        <optgroup label="Filesystem" data-source="0">
                                                            <option>assets</option>
                                                            <option>assets/images</option>
                                                        </optgroup>
                                                        <optgroup label="Assets" data-source="1">
                                                            <option selected>assets</option>
                                                            <option value="">assets/images</option>
                                                        </optgroup>
                                                        <optgroup label="Amazon S3" data-source="2">
                                                            <option>uploads</option>
                                                        </optgroup>
                                                    </select>

                                                        <button type="submit" class="nued">Go </button>

                                                </form>

                                                Upload:
                                                <form action="#" id="media-browser_0__upload-form">
                                                    <input id="media-browser_0__upload-input" multiple="multiple" name="uploadFiles" type="file">
                                                </form>

                                                        Tabular Layout displays image thumbnails along with Name, Description, File Size and Edited On columns

                                                        Thumbnail layout displays a grid of medium sized thumbnails

                                                        Grid View displays images a grid of large images

                                                Name
                                                Dimensions
                                                File Size
                                                Edited On

                                                        <input only-syncronous type="radio" name="file">

                                                    DSC02396.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02396.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02398.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02398.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02532.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02532.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02399.jpg

                                                    600x600

                                                    1.0mb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02399.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02404.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02404.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02405.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02405.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02434.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02434.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02436.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02436.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02441.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02441.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02469.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02469.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02472.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02472.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02487.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02487.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02472.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02472.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02489.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02489.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02491.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02491.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02493.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02493.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02503.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02503.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02514.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02514.jpg'); ?>

<input only-syncronous type="radio" name="file">

                                                    DSC02525.jpg

                                                    600x600

                                                    400kb

                                                    <time>Jan 3, 2015</time>

                                            <?php contextual_row('DSC02525.jpg'); ?>

                            <button class="muted clickable cancel">Cancel</button>
                            <button class="btn clickable cta" id="media-browser_0__choose-btn" type="submit" js-disabled>Choose</button>

        </form>


text:
from django.contrib import admin

import autocomplete_light

from models import *

class BookAdmin(admin.ModelAdmin):
    form = autocomplete_light.modelform_factory(Book)

admin.site.register(Author)
admin.site.register(Book, BookAdmin)
admin.site.register(Publisher)


text:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace TrackableEntities.Client.Tests.Entities.NorthwindModels
{
    [JsonObject(IsReference = true)]
    public class CustomerSetting : EntityBase
    {
        private string _customerId;
        public string CustomerId
        {
            get { return _customerId; }
            set
            {
                if (value == _customerId) return;
                _customerId = value;
                NotifyPropertyChanged(() => CustomerId);
            }
        }

        private string _setting;
        public string Setting
        {
            get { return _setting; }
            set
            {
                if (value == _setting) return;
                _setting = value;
                NotifyPropertyChanged(() => Setting);
            }
        }

        private Customer _customer;
        public Customer Customer
        {
            get { return _customer; }
            set
            {
                if (value == _customer) return;
                _customer = value;
                CustomerChangeTracker = _customer == null ? null
                    : new ChangeTrackingCollection<Customer> { _customer };
                NotifyPropertyChanged(() => Customer);
            }
        }
        private ChangeTrackingCollection<Customer> CustomerChangeTracker { get; set; }
    }
}