text:
"""Spatial transformation ops like RoIAlign, CropAndResize."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf

def _coordinate_vector_1d(start, end, size, align_endpoints):
  """Generates uniformly spaced coordinate vector.

  Args:
    start: A float tensor of shape [batch, num_boxes] indicating start values.
    end: A float tensor of shape [batch, num_boxes] indicating end values.
    size: Number of points in coordinate vector.
    align_endpoints: Whether to align first and last points exactly to
      endpoints.

  Returns:
    A 3D float tensor of shape [batch, num_boxes, size] containing grid
    coordinates.
  """
  start = tf.expand_dims(start, -1)
  end = tf.expand_dims(end, -1)
  length = end - start
  if align_endpoints:
    relative_grid_spacing = tf.linspace(0.0, 1.0, size)
    offset = 0 if size > 1 else length / 2
  else:
    relative_grid_spacing = tf.linspace(0.0, 1.0, size + 1)[:-1]
    offset = length / (2 * size)
  relative_grid_spacing = tf.reshape(relative_grid_spacing, [1, 1, size])
  relative_grid_spacing = tf.cast(relative_grid_spacing, dtype=start.dtype)
  absolute_grid = start + offset + relative_grid_spacing * length
  return absolute_grid

def box_grid_coordinate_vectors(boxes, size_y, size_x, align_corners=False):
  """Generates coordinate vectors for a `size x size` grid in boxes.

  Each box is subdivided uniformly into a grid consisting of size x size
  rectangular cells. This function returns coordinate vectors describing
  the center of each cell.

  If `align_corners` is true, grid points are uniformly spread such that the
  corner points on the grid exactly overlap corners of the boxes.

  Note that output coordinates are expressed in the same coordinate frame as
  input boxes.

  Args:
    boxes: A float tensor of shape [batch, num_boxes, 4] containing boxes of the
      form [ymin, xmin, ymax, xmax].
    size_y: Size of the grid in y axis.
    size_x: Size of the grid in x axis.
    align_corners: Whether to align the corner grid points exactly with box
      corners.

  Returns:
    box_grid_y: A float tensor of shape [batch, num_boxes, size_y] containing y
      coordinates for grid points.
    box_grid_x: A float tensor of shape [batch, num_boxes, size_x] containing x
      coordinates for grid points.
  """
  ymin, xmin, ymax, xmax = tf.unstack(boxes, axis=-1)
  box_grid_y = _coordinate_vector_1d(ymin, ymax, size_y, align_corners)
  box_grid_x = _coordinate_vector_1d(xmin, xmax, size_x, align_corners)
  return box_grid_y, box_grid_x

def feature_grid_coordinate_vectors(box_grid_y, box_grid_x):
  """Returns feature grid point coordinate vectors for bilinear interpolation.

  Box grid is specified in absolute coordinate system with origin at left top
  (0, 0). The returned coordinate vectors contain 0-based feature point indices.

  This function snaps each point in the box grid to nearest 4 points on the
  feature map.

  In this function we also follow the convention of treating feature pixels as
  point objects with no spatial extent.

  Args:
    box_grid_y: A float tensor of shape [batch, num_boxes, size] containing y
      coordinate vector of the box grid.
    box_grid_x: A float tensor of shape [batch, num_boxes, size] containing x
      coordinate vector of the box grid.

  Returns:
    feature_grid_y0: An int32 tensor of shape [batch, num_boxes, size]
      containing y coordinate vector for the top neighbors.
    feature_grid_x0: A int32 tensor of shape [batch, num_boxes, size]
      containing x coordinate vector for the left neighbors.
    feature_grid_y1: A int32 tensor of shape [batch, num_boxes, size]
      containing y coordinate vector for the bottom neighbors.
    feature_grid_x1: A int32 tensor of shape [batch, num_boxes, size]
      containing x coordinate vector for the right neighbors.
  """
  feature_grid_y0 = tf.floor(box_grid_y)
  feature_grid_x0 = tf.floor(box_grid_x)
  feature_grid_y1 = tf.floor(box_grid_y + 1)
  feature_grid_x1 = tf.floor(box_grid_x + 1)
  feature_grid_y0 = tf.cast(feature_grid_y0, dtype=tf.int32)
  feature_grid_y1 = tf.cast(feature_grid_y1, dtype=tf.int32)
  feature_grid_x0 = tf.cast(feature_grid_x0, dtype=tf.int32)
  feature_grid_x1 = tf.cast(feature_grid_x1, dtype=tf.int32)
  return (feature_grid_y0, feature_grid_x0, feature_grid_y1, feature_grid_x1)

def _valid_indicator(feature_grid_y, feature_grid_x, true_feature_shapes):
  """Computes a indicator vector for valid indices.

  Computes an indicator vector which is true for points on feature map and
  false for points off feature map.

  Args:
    feature_grid_y: An int32 tensor of shape [batch, num_boxes, size_y]
      containing y coordinate vector.
    feature_grid_x: An int32 tensor of shape [batch, num_boxes, size_x]
      containing x coordinate vector.
    true_feature_shapes: A int32 tensor of shape [batch, num_boxes, 2]
      containing valid height and width of feature maps. Feature maps are
      assumed to be aligned to the left top corner.

  Returns:
    indices: A 1D bool tensor indicating valid feature indices.
  """
  height = tf.cast(true_feature_shapes[:, :, 0:1], dtype=feature_grid_y.dtype)
  width = tf.cast(true_feature_shapes[:, :, 1:2], dtype=feature_grid_x.dtype)
  valid_indicator = tf.logical_and(
      tf.expand_dims(
          tf.logical_and(feature_grid_y >= 0, tf.less(feature_grid_y, height)),
          3),
      tf.expand_dims(
          tf.logical_and(feature_grid_x >= 0, tf.less(feature_grid_x, width)),
          2))
  return tf.reshape(valid_indicator, [-1])

def ravel_indices(feature_grid_y, feature_grid_x, num_levels, height, width,
                  box_levels):
  """Returns grid indices in a flattened feature map of shape [-1, channels].

  The returned 1-D array can be used to gather feature grid points from a
  feature map that has been flattened from [batch, num_levels, max_height,
  max_width, channels] to [batch * num_levels * max_height * max_width,
  channels].

  Args:
    feature_grid_y: An int32 tensor of shape [batch, num_boxes, size_y]
      containing y coordinate vector.
    feature_grid_x: An int32 tensor of shape [batch, num_boxes, size_x]
      containing x coordinate vector.
    num_levels: Number of feature levels.
    height: An integer indicating the padded height of feature maps.
    width: An integer indicating the padded width of feature maps.
    box_levels: An int32 tensor of shape [batch, num_boxes] indicating
      feature level assigned to each box.

  Returns:
    indices: A 1D int32 tensor containing feature point indices in a flattened
      feature grid.
  """
  num_boxes = tf.shape(feature_grid_y)[1]
  batch_size = tf.shape(feature_grid_y)[0]
  size_y = tf.shape(feature_grid_y)[2]
  size_x = tf.shape(feature_grid_x)[2]
  height_dim_offset = width
  level_dim_offset = height * height_dim_offset
  batch_dim_offset = num_levels * level_dim_offset

  batch_dim_indices = (
      tf.reshape(
          tf.range(batch_size) * batch_dim_offset, [batch_size, 1, 1, 1]) *
      tf.ones([1, num_boxes, size_y, size_x], dtype=tf.int32))
  box_level_indices = (
      tf.reshape(box_levels * level_dim_offset, [batch_size, num_boxes, 1, 1]) *
      tf.ones([1, 1, size_y, size_x], dtype=tf.int32))
  height_indices = (
      tf.reshape(feature_grid_y * height_dim_offset,
                 [batch_size, num_boxes, size_y, 1]) *
      tf.ones([1, 1, 1, size_x], dtype=tf.int32))
  width_indices = (
      tf.reshape(feature_grid_x, [batch_size, num_boxes, 1, size_x])
      * tf.ones([1, 1, size_y, 1], dtype=tf.int32))
  indices = (
      batch_dim_indices + box_level_indices + height_indices + width_indices)
  flattened_indices = tf.reshape(indices, [-1])
  return flattened_indices

def pad_to_max_size(features):
  """Pads features to max height and max width and stacks them up.

  Args:
    features: A list of num_levels 4D float tensors of shape [batch, height_i,
      width_i, channels] containing feature maps.

  Returns:
    stacked_features: A 5D float tensor of shape [batch, num_levels, max_height,
      max_width, channels] containing stacked features.
    true_feature_shapes: A 2D int32 tensor of shape [num_levels, 2] containing
      height and width of the feature maps before padding.
  """
  heights = [tf.shape(feature)[1] for feature in features]
  widths = [tf.shape(feature)[2] for feature in features]
  max_height = tf.reduce_max(heights)
  max_width = tf.reduce_max(widths)

  features_all = [
      tf.image.pad_to_bounding_box(feature, 0, 0, max_height,
                                   max_width) for feature in features
  ]
  features_all = tf.stack(features_all, axis=1)
  true_feature_shapes = tf.stack([tf.shape(feature)[1:3]
                                  for feature in features])
  return features_all, true_feature_shapes

def _gather_valid_indices(tensor, indices, padding_value=0.0):
  """Gather values for valid indices.

  TODO(rathodv): We can't use ops.gather_with_padding_values due to cyclic
  dependency. Start using it after migrating all users of spatial ops to import
  this module directly rather than util/ops.py

  Args:
    tensor: A tensor to gather valid values from.
    indices: A 1-D int32 tensor containing indices along axis 0 of `tensor`.
      Invalid indices must be marked with -1.
    padding_value: Value to return for invalid indices.

  Returns:
    A tensor sliced based on indices. For indices that are equal to -1, returns
    rows of padding value.
  """
  padded_tensor = tf.concat(
      [
          padding_value *
          tf.ones([1, tf.shape(tensor)[-1]], dtype=tensor.dtype), tensor
      ],
      axis=0,
  )
  # tf.concat gradient op uses tf.where(condition) (which is not
  # supported on TPU) when the inputs to it are tf.IndexedSlices instead of
  # tf.Tensor. Since gradient op for tf.gather returns tf.IndexedSlices,
  # we add a dummy op inbetween tf.concat and tf.gather to ensure tf.concat
  # gradient function gets tf.Tensor inputs and not tf.IndexedSlices.
  padded_tensor *= 1.0
  return tf.gather(padded_tensor, indices + 1)

def multilevel_roi_align(features, boxes, box_levels, output_size,
                         num_samples_per_cell_y=1, num_samples_per_cell_x=1,
                         align_corners=False, extrapolation_value=0.0,
                         scope=None):
  """Applies RoI Align op and returns feature for boxes.

  Given multiple features maps indexed by different levels, and a set of boxes
  where each box is mapped to a certain level, this function selectively crops
  and resizes boxes from the corresponding feature maps.

  We follow the RoI Align technique in https://arxiv.org/pdf/1703.06870.pdf
  figure 3. Specifically, each box is subdivided uniformly into a grid
  consisting of output_size[0] x output_size[1] rectangular cells. Within each
  cell we select `num_points` points uniformly and compute feature values using
  bilinear interpolation. Finally, we average pool the interpolated values in
  each cell to obtain a [output_size[0], output_size[1], channels] feature.

  If `align_corners` is true, sampling points are uniformly spread such that
  corner points exactly overlap corners of the boxes.

  In this function we also follow the convention of treating feature pixels as
  point objects with no spatial extent.

  Args:
    features: A list of 4D float tensors of shape [batch_size, max_height,
      max_width, channels] containing features. Note that each feature map must
      have the same number of channels.
    boxes: A 3D float tensor of shape [batch_size, num_boxes, 4] containing
      boxes of the form [ymin, xmin, ymax, xmax] in normalized coordinates.
    box_levels: A 3D int32 tensor of shape [batch_size, num_boxes]
      representing the feature level index for each box.
    output_size: An list of two integers [size_y, size_x] indicating the output
      feature size for each box.
    num_samples_per_cell_y: Number of grid points to sample along y axis in each
      cell.
    num_samples_per_cell_x: Number of grid points to sample along x axis in each
      cell.
    align_corners: Whether to align the corner grid points exactly with box
      corners.
    extrapolation_value: a float value to use for extrapolation.
    scope: Scope name to use for this op.

  Returns:
    A 5D float tensor of shape [batch_size, num_boxes, output_size[0],
    output_size[1], channels] representing the cropped features.
  """
  with tf.name_scope(scope, 'MultiLevelRoIAlign'):
    features, true_feature_shapes = pad_to_max_size(features)
    batch_size = tf.shape(features)[0]
    num_levels = features.get_shape().as_list()[1]
    max_feature_height = tf.shape(features)[2]
    max_feature_width = tf.shape(features)[3]
    num_filters = features.get_shape().as_list()[4]
    num_boxes = tf.shape(boxes)[1]

    # Convert boxes to absolute co-ordinates.
    true_feature_shapes = tf.cast(true_feature_shapes, dtype=boxes.dtype)
    true_feature_shapes = tf.gather(true_feature_shapes, box_levels)
    boxes *= tf.concat([true_feature_shapes - 1] * 2, axis=-1)

    size_y = output_size[0] * num_samples_per_cell_y
    size_x = output_size[1] * num_samples_per_cell_x
    box_grid_y, box_grid_x = box_grid_coordinate_vectors(
        boxes, size_y=size_y, size_x=size_x, align_corners=align_corners)
    (feature_grid_y0, feature_grid_x0, feature_grid_y1,
     feature_grid_x1) = feature_grid_coordinate_vectors(box_grid_y, box_grid_x)
    feature_grid_y = tf.reshape(
        tf.stack([feature_grid_y0, feature_grid_y1], axis=3),
        [batch_size, num_boxes, -1])
    feature_grid_x = tf.reshape(
        tf.stack([feature_grid_x0, feature_grid_x1], axis=3),
        [batch_size, num_boxes, -1])
    feature_coordinates = ravel_indices(feature_grid_y, feature_grid_x,
                                        num_levels, max_feature_height,
                                        max_feature_width, box_levels)
    valid_indices = _valid_indicator(feature_grid_y, feature_grid_x,
                                     true_feature_shapes)
    feature_coordinates = tf.where(valid_indices, feature_coordinates,
                                   -1 * tf.ones_like(feature_coordinates))
    flattened_features = tf.reshape(features, [-1, num_filters])
    flattened_feature_values = _gather_valid_indices(flattened_features,
                                                     feature_coordinates,
                                                     extrapolation_value)
    features_per_box = tf.reshape(
        flattened_feature_values,
        [batch_size, num_boxes, size_y * 2, size_x * 2, num_filters])

    # Cast tensors into dtype of features.
    box_grid_y = tf.cast(box_grid_y, dtype=features_per_box.dtype)
    box_grid_x = tf.cast(box_grid_x, dtype=features_per_box.dtype)
    feature_grid_y0 = tf.cast(feature_grid_y0, dtype=features_per_box.dtype)
    feature_grid_x0 = tf.cast(feature_grid_x0, dtype=features_per_box.dtype)

    # RoI Align operation is a bilinear interpolation of four
    # neighboring feature points f0, f1, f2, and f3 onto point y, x given by
    # f(y, x) = [hy, ly] * [[f00, f01], * [hx, lx]^T
    #                       [f10, f11]]
    #
    # Unrolling the matrix multiplies gives us:
    # f(y, x) = (hy * hx) f00 + (hy * lx) f01 + (ly * hx) f10 + (lx * ly) f11
    # f(y, x) = w00 * f00 + w01 * f01 + w10 * f10 + w11 * f11
    #
    # This can be computed by applying pointwise multiplication and sum_pool in
    # a 2x2 window.
    ly = box_grid_y - feature_grid_y0
    lx = box_grid_x - feature_grid_x0
    hy = 1.0 - ly
    hx = 1.0 - lx

    kernel_y = tf.reshape(
        tf.stack([hy, ly], axis=3), [batch_size, num_boxes, size_y * 2, 1])

    kernel_x = tf.reshape(
        tf.stack([hx, lx], axis=3), [batch_size, num_boxes, 1, size_x * 2])

    # Multiplier 4 is to make tf.nn.avg_pool behave like sum_pool.
    interpolation_kernel = kernel_y * kernel_x * 4

    # Interpolate the gathered features with computed interpolation kernels.
    features_per_box *= tf.expand_dims(interpolation_kernel, axis=4),
    features_per_box = tf.reshape(
        features_per_box,
        [batch_size * num_boxes, size_y * 2, size_x * 2, num_filters])

    # This combines the two pooling operations - sum_pool to perform bilinear
    # interpolation and avg_pool to pool the values in each bin.
    features_per_box = tf.nn.avg_pool(
        features_per_box,
        [1, num_samples_per_cell_y * 2, num_samples_per_cell_x * 2, 1],
        [1, num_samples_per_cell_y * 2, num_samples_per_cell_x * 2, 1], 'VALID')
    features_per_box = tf.reshape(
        features_per_box,
        [batch_size, num_boxes, output_size[0], output_size[1], num_filters])

    return features_per_box

def native_crop_and_resize(image, boxes, crop_size, scope=None):
  """Same as `matmul_crop_and_resize` but uses tf.image.crop_and_resize."""
  def get_box_inds(proposals):
    proposals_shape = proposals.get_shape().as_list()
    if any(dim is None for dim in proposals_shape):
      proposals_shape = tf.shape(proposals)
    ones_mat = tf.ones(proposals_shape[:2], dtype=tf.int32)
    multiplier = tf.expand_dims(
        tf.range(start=0, limit=proposals_shape[0]), 1)
    return tf.reshape(ones_mat * multiplier, [-1])

  with tf.name_scope(scope, 'CropAndResize'):
    cropped_regions = tf.image.crop_and_resize(
        image, tf.reshape(boxes, [-1] + boxes.shape.as_list()[2:]),
        get_box_inds(boxes), crop_size)
    final_shape = tf.concat([tf.shape(boxes)[:2],
                             tf.shape(cropped_regions)[1:]], axis=0)
    return tf.reshape(cropped_regions, final_shape)

def matmul_crop_and_resize(image, boxes, crop_size, extrapolation_value=0.0,
                           scope=None):
  """Matrix multiplication based implementation of the crop and resize op.

  Extracts crops from the input image tensor and bilinearly resizes them
  (possibly with aspect ratio change) to a common output size specified by
  crop_size. This is more general than the crop_to_bounding_box op which
  extracts a fixed size slice from the input image and does not allow
  resizing or aspect ratio change.

  Returns a tensor with crops from the input image at positions defined at
  the bounding box locations in boxes. The cropped boxes are all resized
  (with bilinear interpolation) to a fixed size = `[crop_height, crop_width]`.
  The result is a 5-D tensor `[batch, num_boxes, crop_height, crop_width,
  depth]`.

  Note that this operation is meant to replicate the behavior of the standard
  tf.image.crop_and_resize operation but there are a few differences.
  Specifically:
    1) There is no `box_indices` argument --- to run this op on multiple images,
      one must currently call this op independently on each image.
    2) The `crop_size` parameter is assumed to be statically defined.
      Moreover, the number of boxes must be strictly nonzero.

  Args:
    image: A `Tensor`. Must be one of the following types: `uint8`, `int8`,
      `int16`, `int32`, `int64`, `half`, 'bfloat16', `float32`, `float64`.
      A 4-D tensor of shape `[batch, image_height, image_width, depth]`.
      Both `image_height` and `image_width` need to be positive.
    boxes: A `Tensor` of type `float32` or 'bfloat16'.
      A 3-D tensor of shape `[batch, num_boxes, 4]`. The boxes are specified in
      normalized coordinates and are of the form `[y1, x1, y2, x2]`. A
      normalized coordinate value of `y` is mapped to the image coordinate at
      `y * (image_height - 1)`, so as the `[0, 1]` interval of normalized image
      height is mapped to `[0, image_height - 1] in image height coordinates.
      We do allow y1 > y2, in which case the sampled crop is an up-down flipped
      version of the original image. The width dimension is treated similarly.
      Normalized coordinates outside the `[0, 1]` range are allowed, in which
      case we use `extrapolation_value` to extrapolate the input image values.
    crop_size: A list of two integers `[crop_height, crop_width]`. All
      cropped image patches are resized to this size. The aspect ratio of the
      image content is not preserved. Both `crop_height` and `crop_width` need
      to be positive.
    extrapolation_value: a float value to use for extrapolation.
    scope: A name for the operation (optional).

  Returns:
    A 5-D tensor of shape `[batch, num_boxes, crop_height, crop_width, depth]`
  """
  with tf.name_scope(scope, 'MatMulCropAndResize'):
    box_levels = tf.zeros(tf.shape(boxes)[:2], dtype=tf.int32)
    return multilevel_roi_align([image],
                                boxes,
                                box_levels,
                                crop_size,
                                align_corners=True,
                                extrapolation_value=extrapolation_value)


text:
require 'wlang/dialect/dispatching'
require 'wlang/dialect/evaluation'
require 'wlang/dialect/tags'
module WLang
  class Dialect
    include Dialect::Dispatching
    include Dialect::Evaluation
    include Dialect::Tags

    class << self

      def factor(options = {})
        new(default_options.merge(options))
      end

      def default_options(options = {})
        @default_options ||= (superclass.default_options.dup rescue {})
        @default_options.merge!(options)
      end

      def compiler(options = {})
        factor(options).compiler
      end

      def compile(source, options = {})
        compiler(options).compile(source)
      end

      def to_ruby_code(source, options = {})
        compiler(options).to_ruby_code(source)
      end

      def render(source, scope = {}, buffer = "")
        compile(source).call(scope, buffer)
      end

    end

    default_options :braces      => WLang::BRACES,
                    :autospacing => false

    attr_reader :options
    def braces; options[:braces]; end

    attr_reader :compiler

    def initialize(options = {})
      @options  = options
      @compiler = WLang::Compiler.new(self)
    end

  end # class Dialect
end # module WLang

redpajama_set_name: RedPajamaGithub


text:
/*
 * JStackAlloc (c) 2008 Martin Dvorak <jezek2@advel.cz>
 * JStackAlloc (c) 2016 Danke Xie <danke.xie@gmail.com>
 *     Modified for Android following http://ameblo.jp/guojia/theme-10051299279.html
 *     Fixed raw types
 *
 * This software is provided 'as-is', without any express or implied warranty.
 * In no event will the authors be held liable for any damages arising from
 * the use of this software.
 *
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you must not
 *    claim that you wrote the original software. If you use this software
 *    in a product, an acknowledgment in the product documentation would be
 *    appreciated but is not required.
 * 2. Altered source versions must be plainly marked as such, and must not be
 *    misrepresented as being the original software.
 * 3. This notice may not be removed or altered from any source distribution.
 */

package org.gearvrf.bulletphysics.stack;

import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Support for stack allocation of "value" objects. The only requirements for "value"
 * objects is that they must have public zero argument constructor and set
 * method with one argument of the same type (or superclass) which copies data from
 * given instance.

 *
 * Example usage:
 *

 * public static Vector3f average(Vector3f v1, Vector3f v2, Vector3f out) {
 *     out.add(v1, v2);
 *     out.scale(0.5f);
 *     return out;
 * }
 *
 * public static void test() {
 *     Vector3f v1 = Stack.alloc(Vector3f.class);
 *     v1.set(0f, 1f, 2f);
 *
 *     Vector3f v2 = Stack.alloc(v1);
 *     v2.x = 10f;
 *
 *     Vector3f avg = average(v1, v2, Stack.alloc(Vector3f.class));
 * }
 *

 * which is transformed into something like the following code. The actual
 * generated code has mangled names for unique type identification and can have
 * other minor differences.
 *

 * public static void test() {
 *     $Stack stack = $Stack.get();
 *     stack.pushVector3f();
 *     try {
 *         Vector3f v1 = stack.getVector3f();
 *         v1.set(0f, 1f, 2f);
 *
 *         Vector3f v2 = stack.getVector3f(v1);
 *         v2.x = 10f;
 *
 *         Vector3f avg = average(v1, v2, stack.getVector3f());
 *     }
 *     finally {
 *         stack.popVector3f();
 *     }
 * }
 *

 *
 * Rules:
 *

 *
classes needs to be instrumented by provided InstrumentationTask for ANT, otherwise
 *     error is throwed in runtime

 *
stack is pushed only once per method, do not use stack allocation in loops

 *
returning of stack allocated objects is not supported, use output parameter instead (like in the
 *     example)

 *
working with stack is thread-safe, the data are separate for each thread

 *
combining different libraries works fine, each must have their stack stored
 *     in different package, so you'll just end up with multiple stacks in final application,
 *     which is fine, because the values are used between them without problem
 *
when creating and destroying threads you must be aware that the implementation
 *     uses ThreadLocal to persist stack instances between method calls, it's advisable
 *     to call cleanCurrentThread method on thread just before destroying
 *

 *

 *
 * @author jezek2, danke-sra
 */
public class Stack {
	private static List<WeakReference<ThreadLocal<?>>> threadLocalList = new ArrayList<WeakReference<ThreadLocal<?>>>();

	private Stack() {
	}

	/**
	 * インスタンスを作る人
	 * @param <T> The type parameter.
	 *
	 * @param cls The class to be allocated.
	 * @return An instance of the class.
	 *
	 */
	//  See http://ameblo.jp/guojia/theme-10051299279.html
	public static <T> T alloc(Class<T> cls) {
	    try {
	        return cls.newInstance();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }

	    return null;
	}

	/**
	 * コピーを作る人
	 * @param <T> The type parameter.
	 *
	 * @param obj The object to be cloned.
	 * @return The cloned object.
	 */
	@SuppressWarnings("unchecked")
	public static <T> T alloc(T obj) {
	    Constructor<T> constructor;
	    try {
	        // コピーコンストラクタがある事大前提(良い子は真似しないでね?)
	        constructor = (Constructor<T>) obj.getClass().getConstructor(obj.getClass());
	        return (T) constructor.newInstance(obj);
	    } catch (Exception e) {
	        e.printStackTrace();
	        return null;
	    }
	}

	/**
	 * Used internally.
	 */
	public static synchronized void internalRegisterThreadLocal(ThreadLocal<?> local) {
		threadLocalList.add(new WeakReference<ThreadLocal<?>>(local));
	}

	/**
	 * Removes all cached stack instances for current thread.
	 */
	public static synchronized void cleanCurrentThread() {
		for (Iterator<WeakReference<ThreadLocal<?>>> it = threadLocalList.iterator(); it.hasNext(); ) {
			WeakReference<ThreadLocal<?>> ref = it.next();
			ThreadLocal<?> local = ref.get();
			if (local != null) {
				local.remove();
			}
			else {
				it.remove();
			}
		}
	}

	/**
	 * Removes all cached stack instances for current thread in current library.

	 *
	 * Requires instrumentation of your classes in order to work.
	 */
	public static void libraryCleanCurrentThread() {
		throw new Error("not instrumented");
	}

}


text:
package grpccmd

import (
	"encoding/json"
	"fmt"
	"reflect"

	"github.com/golang/protobuf/proto"
	"github.com/spf13/cobra"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

var rootCmd = &cobra.Command{}

var addr = new(string)
var input = new(string)

func init() {
	rootCmd.PersistentFlags().StringVar(addr, "addr", "", "gRPC server address.")
	rootCmd.PersistentFlags().StringVar(input, "input", "", "JSON representation of the input data for the method.")
}

func SetCmdInfo(name, short, long string) {
	rootCmd.Use = fmt.Sprintf("%s [command]", name)
	rootCmd.Short = short
	rootCmd.Long = long
}

func RegisterServiceCmd(cmd *cobra.Command) {
	rootCmd.AddCommand(cmd)
}

func Execute() error {
	return rootCmd.Execute()
}

func RunE(
	method,
	inT string,
	newClient func(*grpc.ClientConn) interface{},
) func(*cobra.Command, []string) error {
	return func(cmd *cobra.Command, args []string) error {
		conn, err := dial(*addr)
		if err != nil {
			return err
		}
		defer conn.Close()
		c := newClient(conn)
		cv := reflect.ValueOf(c)
		method := cv.MethodByName(method)
		if method.IsValid() {

			in := reflect.New(proto.MessageType(inT).Elem()).Interface()
			if len(*input) > 0 {
				if err := json.Unmarshal([]byte(*input), in); err != nil {
					return err
				}
			}

			result := method.Call([]reflect.Value{
				reflect.ValueOf(context.Background()),
				reflect.ValueOf(in),
			})
			if len(result) != 2 {
				panic("service methods should always return 2 values")
			}
			if !result[1].IsNil() {
				return result[1].Interface().(error)
			}
			out := result[0].Interface()
			data, err := json.MarshalIndent(out, "", "    ")
			if err != nil {
				return err
			}
			fmt.Println(string(data))
		}

		return nil
	}
}

func dial(addr string) (*grpc.ClientConn, error) {
	var opts []grpc.DialOption
	opts = append(opts, grpc.WithInsecure())
	return grpc.Dial(addr, opts...)
}


text:
require 'active_support/concern'

module Caprese
  class Serializer < ActiveModel::Serializer
    module Links
      extend ActiveSupport::Concern

      included do
        # Add a links[:self] to this resource
        #
        # @example
        #   object = Order<@token='asd27h'>
        #   links = { self: '/api/v1/orders/asd27hß' }
        unless self._links[:self]
          link :self do
            if object.persisted? && (url = serializer.class.route_for(object))
              serializer.url_helpers.send(
                url,
                object.read_attribute(Caprese.config.resource_primary_key),
                host: serializer.class.send(:caprese_default_url_options_host)
              )
            end
          end
        end
      end

      module ClassMethods
        # Fetches the host from Caprese.config.default_url_options or fails if it is not set
        # @note default_url_options[:host] is used to render the host in links that are serialized in the response
        def caprese_default_url_options_host
          Caprese.config.default_url_options.fetch(:host) do
            fail 'Caprese requires that config.default_url_options[:host] be set when rendering links.'
          end
        end
      end
    end
  end
end


text:
<?php

declare(strict_types=1);

namespace ApiPlatform\Core\Tests\Documentation\Action;

use ApiPlatform\Core\Api\FormatsProviderInterface;
use ApiPlatform\Core\Documentation\Action\DocumentationAction;
use ApiPlatform\Core\Documentation\Documentation;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\ResourceNameCollection;
use ApiPlatform\Core\OpenApi\Factory\OpenApiFactoryInterface;
use ApiPlatform\Core\OpenApi\Model\Info;
use ApiPlatform\Core\OpenApi\Model\Paths;
use ApiPlatform\Core\OpenApi\OpenApi;
use ApiPlatform\Core\Tests\ProphecyTrait;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;

/**
 * @author Amrouche Hamza <hamza.simperfit@gmail.com>
 */
class DocumentationActionTest extends TestCase
{
    use ProphecyTrait;

    /**
     * @group legacy
     * @expectedDeprecation Not passing an instance of "ApiPlatform\Core\OpenApi\Factory\OpenApiFactoryInterface" as 7th parameter of the constructor of "ApiPlatform\Core\Documentation\Action\DocumentationAction" is deprecated since API Platform 2.6
     */
    public function testDocumentationAction(): void
    {
        $requestProphecy = $this->prophesize(Request::class);
        $attributesProphecy = $this->prophesize(ParameterBagInterface::class);
        $queryProphecy = $this->prophesize(ParameterBag::class);
        $resourceNameCollectionFactoryProphecy = $this->prophesize(ResourceNameCollectionFactoryInterface::class);
        $resourceNameCollectionFactoryProphecy->create()->willReturn(new ResourceNameCollection(['dummies']));
        $requestProphecy->attributes = $attributesProphecy->reveal();
        $requestProphecy->query = $queryProphecy->reveal();
        $requestProphecy->getBaseUrl()->willReturn('/api')->shouldBeCalledTimes(1);
        $queryProphecy->getBoolean('api_gateway')->willReturn(true)->shouldBeCalledTimes(1);
        $queryProphecy->getInt('spec_version', 2)->willReturn(2)->shouldBeCalledTimes(1);
        $attributesProphecy->all()->willReturn(['_api_normalization_context' => ['foo' => 'bar', 'base_url' => '/api', 'api_gateway' => true, 'spec_version' => 2]])->shouldBeCalledTimes(1);
        $attributesProphecy->get('_api_normalization_context', [])->willReturn(['foo' => 'bar'])->shouldBeCalledTimes(1);
        $attributesProphecy->set('_api_normalization_context', ['foo' => 'bar', 'base_url' => '/api', 'api_gateway' => true, 'spec_version' => 2])->shouldBeCalledTimes(1);

        $documentation = new DocumentationAction($resourceNameCollectionFactoryProphecy->reveal(), 'My happy hippie api', 'lots of chocolate', '1.0.0');
        $this->assertEquals(new Documentation(new ResourceNameCollection(['dummies']), 'My happy hippie api', 'lots of chocolate', '1.0.0'), $documentation($requestProphecy->reveal()));
    }

    public function testLegacyDocumentationAction(): void
    {
        $requestProphecy = $this->prophesize(Request::class);
        $attributesProphecy = $this->prophesize(ParameterBagInterface::class);
        $queryProphecy = $this->prophesize(ParameterBag::class);
        $resourceNameCollectionFactoryProphecy = $this->prophesize(ResourceNameCollectionFactoryInterface::class);
        $resourceNameCollectionFactoryProphecy->create()->willReturn(new ResourceNameCollection(['dummies']));
        $requestProphecy->attributes = $attributesProphecy->reveal();
        $requestProphecy->query = $queryProphecy->reveal();
        $requestProphecy->getBaseUrl()->willReturn('/api')->shouldBeCalledTimes(1);
        $queryProphecy->getBoolean('api_gateway')->willReturn(true)->shouldBeCalledTimes(1);
        $queryProphecy->getInt('spec_version', 2)->willReturn(2)->shouldBeCalledTimes(1);
        $attributesProphecy->all()->willReturn(['_api_normalization_context' => ['foo' => 'bar', 'base_url' => '/api', 'api_gateway' => true, 'spec_version' => 2]])->shouldBeCalledTimes(1);
        $attributesProphecy->get('_api_normalization_context', [])->willReturn(['foo' => 'bar'])->shouldBeCalledTimes(1);
        $attributesProphecy->set('_api_normalization_context', ['foo' => 'bar', 'base_url' => '/api', 'api_gateway' => true, 'spec_version' => 2])->shouldBeCalledTimes(1);
        $formatsProviderProphecy = $this->prophesize(FormatsProviderInterface::class);
        $formatsProviderProphecy->getFormatsFromAttributes(Argument::type('array'))->willReturn(['formats' => ['jsonld' => 'application/ld+json']])->shouldBeCalled();

        $documentation = new DocumentationAction($resourceNameCollectionFactoryProphecy->reveal(), 'My happy hippie api', 'lots of chocolate', '1.0.0', $formatsProviderProphecy->reveal());
        $this->assertEquals(new Documentation(new ResourceNameCollection(['dummies']), 'My happy hippie api', 'lots of chocolate', '1.0.0', ['formats' => ['jsonld' => 'application/ld+json']]), $documentation($requestProphecy->reveal()));
    }

    /**
     * @group legacy
     * @expectedDeprecation Passing an array or an instance of "ApiPlatform\Core\Api\FormatsProviderInterface" as 5th parameter of the constructor of "ApiPlatform\Core\Documentation\Action\DocumentationAction" is deprecated since API Platform 2.5
     */
    public function testDocumentationActionFormatDeprecation()
    {
        $resourceNameCollectionFactoryProphecy = $this->prophesize(ResourceNameCollectionFactoryInterface::class);
        $resourceNameCollectionFactoryProphecy->create()->willReturn(new ResourceNameCollection(['dummies']));
        new DocumentationAction($resourceNameCollectionFactoryProphecy->reveal(), '', '', '', ['formats' => ['jsonld' => 'application/ld+json']]);
    }

    public function testDocumentationActionV2(): void
    {
        $openApiFactoryProphecy = $this->prophesize(OpenApiFactoryInterface::class);
        $requestProphecy = $this->prophesize(Request::class);
        $attributesProphecy = $this->prophesize(ParameterBagInterface::class);
        $queryProphecy = $this->prophesize(ParameterBag::class);
        $resourceNameCollectionFactoryProphecy = $this->prophesize(ResourceNameCollectionFactoryInterface::class);
        $resourceNameCollectionFactoryProphecy->create()->willReturn(new ResourceNameCollection(['dummies']));
        $requestProphecy->attributes = $attributesProphecy->reveal();
        $requestProphecy->query = $queryProphecy->reveal();
        $requestProphecy->getBaseUrl()->willReturn('/api')->shouldBeCalledTimes(1);
        $queryProphecy->getBoolean('api_gateway')->willReturn(true)->shouldBeCalledTimes(1);
        $queryProphecy->getInt('spec_version', 2)->willReturn(2)->shouldBeCalledTimes(1);
        $attributesProphecy->all()->willReturn(['_api_normalization_context' => ['foo' => 'bar', 'base_url' => '/api', 'api_gateway' => true, 'spec_version' => 2]])->shouldBeCalledTimes(1);
        $attributesProphecy->get('_api_normalization_context', [])->willReturn(['foo' => 'bar'])->shouldBeCalledTimes(1);
        $attributesProphecy->set('_api_normalization_context', ['foo' => 'bar', 'base_url' => '/api', 'api_gateway' => true, 'spec_version' => 2])->shouldBeCalledTimes(1);

        $documentation = new DocumentationAction($resourceNameCollectionFactoryProphecy->reveal(), 'My happy hippie api', 'lots of chocolate', '1.0.0', null, [2, 3], $openApiFactoryProphecy->reveal());
        $this->assertEquals(new Documentation(new ResourceNameCollection(['dummies']), 'My happy hippie api', 'lots of chocolate', '1.0.0'), $documentation($requestProphecy->reveal()));
    }

    public function testDocumentationActionV3(): void
    {
        $openApi = new OpenApi(new Info('my api', '1.0.0'), [], new Paths());
        $openApiFactoryProphecy = $this->prophesize(OpenApiFactoryInterface::class);
        $openApiFactoryProphecy->__invoke(Argument::any())->shouldBeCalled()->willReturn($openApi);
        $requestProphecy = $this->prophesize(Request::class);
        $attributesProphecy = $this->prophesize(ParameterBagInterface::class);
        $queryProphecy = $this->prophesize(ParameterBag::class);
        $resourceNameCollectionFactoryProphecy = $this->prophesize(ResourceNameCollectionFactoryInterface::class);
        $resourceNameCollectionFactoryProphecy->create()->willReturn(new ResourceNameCollection(['dummies']));
        $requestProphecy->attributes = $attributesProphecy->reveal();
        $requestProphecy->query = $queryProphecy->reveal();
        $requestProphecy->getBaseUrl()->willReturn('/api')->shouldBeCalledTimes(1);
        $queryProphecy->getBoolean('api_gateway')->willReturn(true)->shouldBeCalledTimes(1);
        $queryProphecy->getInt('spec_version', 2)->willReturn(3)->shouldBeCalledTimes(1);
        $attributesProphecy->all()->willReturn(['_api_normalization_context' => ['foo' => 'bar', 'base_url' => '/api', 'api_gateway' => true, 'spec_version' => 3]])->shouldBeCalledTimes(1);
        $attributesProphecy->get('_api_normalization_context', [])->willReturn(['foo' => 'bar'])->shouldBeCalledTimes(1);
        $attributesProphecy->set('_api_normalization_context', ['foo' => 'bar', 'base_url' => '/api', 'api_gateway' => true, 'spec_version' => 3])->shouldBeCalledTimes(1);

        $documentation = new DocumentationAction($resourceNameCollectionFactoryProphecy->reveal(), 'My happy hippie api', 'lots of chocolate', '1.0.0', null, [2, 3], $openApiFactoryProphecy->reveal());
        $this->assertInstanceOf(OpenApi::class, $documentation($requestProphecy->reveal()));
    }
}


text:
package com.gauravbytes.gkart.service.exception;

/**
 *
 * @author Gaurav Rai Mazra
 * Catch me
 */
public class GenericServiceException extends RuntimeException {

	/**
	 *
	 */
	private static final long serialVersionUID = -3681636607322599994L;

	public GenericServiceException(String message) {
		super(message);
	}
}


text:
package com.adobe.acs.commons.quickly.impl;

import com.adobe.acs.commons.quickly.Command;
import com.adobe.acs.commons.quickly.QuicklyEngine;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.commons.json.JSONException;

import javax.servlet.ServletException;
import java.io.IOException;

@SlingServlet(
        label = "ACS AEM Commons - Quickly - Servlet End-point",
        paths = "/bin/quickly.json"
)
public class QuicklyServlet extends SlingSafeMethodsServlet {

    @Reference
    private QuicklyEngine quicklyEngine;

    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
            throws ServletException, IOException {
        final Command cmd = new Command(request);

        response.setHeader("Content-Type", " application/json; charset=UTF-8");

        try {
            response.getWriter().append(quicklyEngine.execute(request, response, cmd).toString());
        } catch (JSONException e) {
            response.sendError(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().print("{\"status:\": \"error\"}");
        }
    }
}


text:
package net.coding.program.common;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by chaochen on 14-10-25.
 */
public class HtmlContent {

    private static final String REGX_PHOTO = "(?:
)? ?(?:
)? ?";
    private static final String REGX_PHOTO_OLD = "

";
    private static final String REPLACE_PHOTO = "[图片]";

    private static final String REGX_MONKEY = "";
    private static final String REGX_EMOJI = "";

    private static final String REGX_NET_PHOTO = "";

    private static final String REGX_CODE = "(
)?<code(.*\\n)*(
)?";

    private static final String REPLACE_CODE = "[代码]";

    private static final String REGX_HTML = "<([A-Za-z][A-Za-z0-9]*)[^>]*>(.*?)</\\1>";

    public static Global.MessageParse parseMaopao(String s) {
        return createMessageParse(s, REGX_PHOTO);
    }

    public static Global.MessageParse parseMessage(String s) {
        Global.MessageParse parse = createMessageParse(s, REGX_PHOTO_OLD);
        if (parse.uris.size() > 0) {
            return parse;
        } else {
            return parseMaopao(s);
        }
    }

    public static String parseDynamic(String s) {
//        Global.MessageParse parse = new Global.MessageParse();

//        String replaceImage = s.replaceAll(HtmlContent.REGX_PHOTO, REPLACE_PHOTO);
//
//        replaceImage = replaceImage.replaceAll(REGX_MONKEY, "");
//
//        parse.text = replaceAllSpace(replaceImage);

        return parseToText(s);
    }

    public static Global.MessageParse parseReplacePhoto(String s) {
        Global.MessageParse parse = new Global.MessageParse();

        String replaceImage = s.replaceAll(HtmlContent.REGX_PHOTO, REPLACE_PHOTO);

        replaceImage = replaceImage.replaceAll(REGX_MONKEY, "");

        parse.text = replaceAllSpace(replaceImage);

        return parse;
    }

    public static String parseReplacePhotoEmoji(String s) {
        String replaceImage = s.replaceAll(HtmlContent.REGX_PHOTO, REPLACE_PHOTO);

        return replaceImage.replaceAll(REGX_MONKEY, ":$1:")
                .replaceAll(REGX_EMOJI, ":$1:");
    }

    public static String parseReplacePhotoMonkey(String s) {
        String replaceImage = s.replaceAll(REGX_MONKEY, REPLACE_PHOTO);
        replaceImage = replaceImage.replaceAll(REGX_PHOTO, REPLACE_PHOTO);
        replaceImage = replaceImage.replaceAll(REGX_PHOTO_OLD, REPLACE_PHOTO);
        replaceImage = replaceImage.replaceAll(REGX_NET_PHOTO, REPLACE_PHOTO);
        return replaceImage;
        //return s.replaceAll(HtmlContent.REGX_MONKEY, REPLACE_PHOTO).replaceAll(REGX_PHOTO, REPLACE_PHOTO)
        //      .replaceAll(REGX_PHOTO_OLD, REPLACE_PHOTO);
    }

    public static String parseToText(String s) {
        return s.replaceAll(REGX_MONKEY, "[$1]")
                .replaceAll(REGX_PHOTO, REPLACE_PHOTO)
                .replaceAll(REGX_PHOTO_OLD, REPLACE_PHOTO)
                .replaceAll(REGX_CODE, REPLACE_CODE)
                .replaceAll(REGX_HTML, "$2")
                .replace("", "");
    }

    public static String parseToShareText(String s) {
        return s.replaceAll(REGX_MONKEY, "[$1]")
                .replaceAll(REGX_PHOTO, REPLACE_PHOTO)
                .replaceAll(REGX_PHOTO_OLD, REPLACE_PHOTO)
                .replaceAll(REGX_CODE, REPLACE_CODE)
                .replaceAll(REGX_HTML, "$2")
                .replace("", "")
                .replaceAll("<(.*?)>", "");
    }

    private static Global.MessageParse createMessageParse(String s, String regx) {
        Global.MessageParse parse = new Global.MessageParse();

        // emoji 有时候会是类似于 image 的形式
        String emojiSrc = "";
        String emojiDesc = "";
        s = s.replaceAll(emojiSrc, emojiDesc);

        Pattern pattern = Pattern.compile(regx);
        Matcher matcher = pattern.matcher(s);
        while (matcher.find()) {
            parse.uris.add(matcher.group(1));
        }

        String replaceImage = s.replaceAll(regx, "");
        parse.text = replaceAllSpace(replaceImage);

        return parse;
    }

    private static String replaceAllSpace(String s) {
        final String br = "
";
        s = s.replaceAll("
", "").replaceAll("
", br);
        if (s.endsWith(br)) {
            s = s.substring(0, s.length() - br.length());
        }

        if (s.startsWith(br)) {
            s = s.substring(br.length(), s.length());
        }

        String temp = s.replaceAll("
", "").replaceAll(" ", "").replaceAll("\n", "");
        if (temp.isEmpty()) {
            return "";
        }

//        s = s.replaceAll("( ?
 ?)+", "
").replaceAll("( ?(
)? ?\n?)+$", "")
//                .replaceAll("^( ?(
)? ?\n?)+", "");

        s = s.replaceAll("( ?
 ?)+", "
").replaceAll("( ?
 ?\n?)+$", "").replaceAll("^( ?
 ?\n?)+", "");
        return s;
    }

    public static String createUserHtml(String globalKey, String name) {
        final String format = "%s";
        return String.format(format, globalKey, name);
    }
}


text:
'use strict';

//region Imports

import DataType from './data-type.js';
import Boolean from './boolean.js';
import Text from './text.js';
import Email from './email.js';
import Integer from './integer.js';
import Decimal from './decimal.js';
import Enum from './enum.js';
import DateTime from './date-time.js';

//endregion

/**
 * Contains data type components and definitions.
 *
 * @namespace bo.dataTypes
 *
 * @property {function} DataType - {@link bo.dataTypes.DataType Data type} constructor to create new definitions.
 * @property {object} Boolean - Data type instance that defines {@link bo.dataTypes.Boolean Boolean} data.
 * @property {object} Text - Data type instance that defines {@link bo.dataTypes.Text Text} data.
 * @property {object} Email - Data type instance that defines {@link bo.dataTypes.Email Email} data.
 * @property {object} Integer - Data type instance that defines {@link bo.dataTypes.Integer Integer} data.
 * @property {object} Decimal - Data type instance that defines {@link bo.dataTypes.Decimal Decimal} data.
 * @property {function} Enum - {@link bo.dataTypes.Enum Enum} constructor to create new enumeration data type.
 * @property {object} DateTime - Data type instance that defines {@link bo.dataTypes.DateTime DateTime} data.
 */
const index = {
  DataType: DataType,
  Boolean: new Boolean(),
  Text: new Text(),
  Email: new Email(),
  Integer: new Integer(),
  Decimal: new Decimal(),
  Enum: Enum,
  DateTime: new DateTime()
};

// Immutable object.
Object.freeze( index );

export default index;


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.bazaarvoice.emodb</groupId>
        <artifactId>emodb-parent</artifactId>
        <version>5.7.9-SNAPSHOT</version>
        <relativePath>../parent/pom.xml</relativePath>
    </parent>

    <artifactId>emodb-rpms</artifactId>
    <packaging>pom</packaging>

    <name>EmoDB Yum RPM Deployer</name>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <descriptor>dep.xml</descriptor>
                    <finalName>emodb-${project.version}</finalName>
                </configuration>
                <executions>
                    <execution>
                        <id>create-package</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>yum-deploy</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>com.bazaarvoice.maven.plugins</groupId>
                        <artifactId>s3repo-maven-plugin</artifactId>
                        <executions>
                            <execution>
                                <phase>deploy</phase>
                                <goals>
                                    <goal>create-update</goal>
                                </goals>
                                <configuration>
                                    <s3RepositoryPath>${yumrepo.s3RepositoryPath}</s3RepositoryPath>
                                    <artifactItems>
                                        <artifactItem>
                                            <groupId>${project.groupId}</groupId>
                                            <artifactId>${yumArtifactId}</artifactId>
                                            <version>${project.version}</version>
                                            <type>rpm</type>
                                            <targetBaseName>${yumArtifactName}</targetBaseName>
                                            <targetExtension>noarch.rpm</targetExtension>
                                        </artifactItem>
                                    </artifactItems>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</project>


text:
/*Initialisation des différents élements JQuery*/

const srcGame = {'tictactoo' : '/img/morpion.jpg'};
$("#toutes").click(function () { typeGame("Toutes"); recuperationPartie("Toutes"); }); // The value of the selected option
$("#attente").click(function () { typeGame("En attente"); recuperationPartie("En attente"); }); // The value of the selected option
$("#cours").click(function () { typeGame("En cours"); recuperationPartie("En cours") }); // The value of the selected option

$("#reload").click(function ()
{
	typeGame("Toutes");
	recuperationPartie("Toutes");
});

$("#dropdown-type-game").dropdown();

$(document).ready(function() {
	$('select').material_select();
});
$('select').material_select('destroy');

function typeGame(type) {
	if(document.getElementById("value-type")){
		document.getElementById("value-type").innerHTML = type;
	}
	else{
		let valueType = document.createElement("strong");
		valueType.setAttribute("id", "value-type");
	}
}

function showForm(){
	if(!$("#form-ajout").hasClass("scale-out")){
		document.getElementById("add-partie").innerHTML = "add";
		$("#form-ajout").addClass("scale-out");
	}
	else{
		document.getElementById("add-partie").innerHTML = "remove";

		$("#form-ajout").removeClass("scale-out");
	}
}

function addIndeter(){
	$("#listGame").append("
" +
		"
" +
		"
" +
		"

" +
		"
" +
		"
" +
		"

" +
		"
" +
		"
" +
		"

" +
		"
" +
		"
" +
		"
");
}

function removeIndeter() {
	$("#inder").remove();
}
function init() {
	typeGame("Toutes");
	recuperationPartie("Toutes");
}


text:
/**
 * guy
 * 一个占位符和两个icon和一行数 组成的一行listitem
 *
 * Created by GUY on 2015/9/15.
 * @class BI.BlankIconTextIconItem
 * @extends BI.BasicButton
 */
BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, {

    _defaultConfig: function () {
        var conf = BI.BlankIconTextIconItem.superclass._defaultConfig.apply(this, arguments);
        return BI.extend(conf, {
            baseCls: (conf.baseCls || "") + " bi-blank-icon-text-icon-item",
            logic: {
                dynamic: false
            },
            iconCls1: "",
            iconCls2: "",
            blankWidth: 0,
            iconHeight: null,
            iconWidth: null,
            textHgap: 0,
            textVgap: 0,
            textLgap: 0,
            textRgap: 0
        });
    },

    render: function () {
        var self = this, o = this.options;

        return {
            type: "bi.vertical_adapt",
            columnSize: [o.blankWidth, o.leftIconWrapperWidth || o.height, "fill", o.rightIconWrapperWidth || o.height],
            items: [{
                type: "bi.layout",
                width: o.blankWidth
            }, {
                type: "bi.icon_label",
                cls: o.iconCls1,
                width: o.leftIconWrapperWidth || o.height,
                height: o.height,
                iconWidth: o.iconWidth,
                iconHeight: o.iconHeight
            }, {
                el: {
                    type: "bi.label",
                    ref: function (_ref) {
                        self.text = _ref;
                    },
                    textAlign: "left",
                    hgap: o.textHgap,
                    vgap: o.textVgap,
                    lgap: o.textLgap,
                    rgap: o.textRgap,
                    text: o.text,
                    value: o.value,
                    keyword: o.keyword,
                    height: o.height
                }
            }, {
                type: "bi.icon_label",
                cls: o.iconCls2,
                width: o.rightIconWrapperWidth || o.height,
                height: o.height,
                iconWidth: o.iconWidth,
                iconHeight: o.iconHeight
            }]
        };
    },

    doClick: function () {
        BI.BlankIconTextIconItem.superclass.doClick.apply(this, arguments);
        if (this.isValid()) {
            this.fireEvent(BI.BlankIconTextIconItem.EVENT_CHANGE, this.getValue(), this);
        }
    },

    doRedMark: function () {
        this.text.doRedMark.apply(this.text, arguments);
    },

    unRedMark: function () {
        this.text.unRedMark.apply(this.text, arguments);
    },

    doHighLight: function () {
        this.text.doHighLight.apply(this.text, arguments);
    },

    unHighLight: function () {
        this.text.unHighLight.apply(this.text, arguments);
    },

    setValue: function () {
        if (!this.isReadOnly()) {
            this.text.setValue.apply(this.text, arguments);
        }
    },

    getValue: function () {
        return this.text.getValue();
    },

    setText: function () {
        this.text.setText.apply(this.text, arguments);
    },

    getText: function () {
        return this.text.getText();
    }
});
BI.BlankIconTextIconItem.EVENT_CHANGE = "EVENT_CHANGE";
BI.shortcut("bi.blank_icon_text_icon_item", BI.BlankIconTextIconItem);


text:
/// Interfaces for WinJS

export interface ValueCallback {
	(value:any):any;
}

export interface EventCallback {
	(value:any):void;
}

export interface ErrorCallback {
	(error:any):any;
}

export interface ProgressCallback {
	(progress:any):any;
}

export declare class Promise {
	constructor(init:(complete:ValueCallback, error:ErrorCallback, progress:ProgressCallback)=>void, oncancel?: any);

	// commented out to speed up adoption of TPromise
	// static as(value:any):Promise;

	static join(promises:{[name:string]:Promise;}):Promise;
	static join(promises:Promise[]):Promise;
	static any(promises:Promise[]):Promise;

	// commented out to speed up adoption of TPromise
	// static timeout(delay:number):Promise;

	static wrapError(error:any):Promise;
	static is(value: any): boolean;
	static addEventListener(type:string, fn:EventCallback):void;

	public then(success?:ValueCallback, error?:ErrorCallback, progress?:ProgressCallback):Promise;
	public then<U>(success?:ValueCallback, error?:ErrorCallback, progress?:ProgressCallback):TPromise<U>;
	public done(success?:ValueCallback, error?:ErrorCallback, progress?:ProgressCallback):void;
	public cancel():void;
}

export interface IXHROptions {
	type?:string;
	url?:string;
	user?:string;
	password?:string;
	responseType?:string;
	headers?:any;
	customRequestInitializer?:(req:any)=>void;
	data?:any;
}

export declare function xhr(options:IXHROptions):TPromise<XMLHttpRequest>;
export declare function decoratePromise(promise:Promise, successCallback?:ValueCallback, errorCallback?:ErrorCallback):Promise;
export declare function decoratePromise<T>(promise:TPromise<T>, successCallback?:TValueCallback<T>, errorCallback?:ErrorCallback):TPromise<T>;

// --- Generic promise
export interface TValueCallback<T> {
	(value:T):void;
}

export interface TValueCallback<T> {
	(value:T):void;
}

export interface TProgressCallback<T> {
	(progress:T):void;
}

export declare class TPromise<V> {

	constructor(init:(complete: TValueCallback<V>, error:(err:any)=>void, progress:ProgressCallback)=>void, oncancel?: any);

	public then<U>(success?: (value:V)=>TPromise<U>, error?: (err:any)=>TPromise<U>, progress?:ProgressCallback): TPromise<U>;
	public then<U>(success?: (value:V)=>TPromise<U>, error?: (err:any)=>TPromise<U>|U, progress?:ProgressCallback): TPromise<U>;
	public then<U>(success?: (value:V)=>TPromise<U>, error?: (err:any)=>U, progress?:ProgressCallback): TPromise<U>;
	public then<U>(success?: (value:V)=>TPromise<U>, error?: (err:any)=>void, progress?:ProgressCallback): TPromise<U>;
	public then<U>(success?: (value:V)=>TPromise<U>|U, error?: (err:any)=>TPromise<U>, progress?:ProgressCallback): TPromise<U>;
	public then<U>(success?: (value:V)=>TPromise<U>|U, error?: (err:any)=>TPromise<U>|U, progress?:ProgressCallback): TPromise<U>;
	public then<U>(success?: (value:V)=>TPromise<U>|U, error?: (err:any)=>U, progress?:ProgressCallback): TPromise<U>;
	public then<U>(success?: (value:V)=>TPromise<U>|U, error?: (err:any)=>void, progress?:ProgressCallback): TPromise<U>;
	public then<U>(success?: (value:V)=>U, error?: (err:any)=>TPromise<U>, progress?:ProgressCallback): TPromise<U>;
	public then<U>(success?: (value:V)=>U, error?: (err:any)=>TPromise<U>|U, progress?:ProgressCallback): TPromise<U>;
	public then<U>(success?: (value:V)=>U, error?: (err:any)=>U, progress?:ProgressCallback): TPromise<U>;
	public then<U>(success?: (value:V)=>U, error?: (err:any)=>void, progress?:ProgressCallback): TPromise<U>;

	public done(success?: (value:V)=>void, error?: (err:any)=>any, progress?:ProgressCallback): void;
	public cancel():void;

	public static as<ValueType>(value:ValueType):TPromise<ValueType>;
	public static is(value: any): value is TPromise<any>;
	public static timeout(delay:number):TPromise<void>;
	public static join<ValueType>(promises:TPromise<ValueType>[]):TPromise<ValueType[]>;
	public static join<ValueType>(promises:Thenable<ValueType>[]):Thenable<ValueType[]>;
	public static join<ValueType>(promises: {[n:string]:TPromise<ValueType>}):TPromise<{[n:string]:ValueType}>;
	public static any<ValueType>(promises:TPromise<ValueType>[]):TPromise<{ key:string; value:TPromise<ValueType>;}>;
	public static wrapError<ValueType>(error:any):TPromise<ValueType>;
}

// --- Generic promise with generic progress value
export declare class PPromise<C,P> extends TPromise<C> {

	constructor(init:(complete: TValueCallback<C>, error:(err:any)=>void, progress: TProgressCallback<P>)=>void, oncancel?: any);

	public then<U>(success?: (value:C)=>PPromise<U,P>, error?: (err:any)=>PPromise<U,P>, progress?:(value:P)=>void): PPromise<U,P>;
	public then<U>(success?: (value:C)=>PPromise<U,P>, error?: (err:any)=>U, progress?:(value:P)=>void): PPromise<U,P>;
	public then<U>(success?: (value:C)=>PPromise<U,P>, error?: (err:any)=>void, progress?:(value:P)=>void): PPromise<U,P>;
	public then<U>(success?: (value:C)=>U, error?: (err:any)=>PPromise<C,P>, progress?:(value:P)=>void): PPromise<U,P>;
	public then<U>(success?: (value:C)=>U, error?: (err:any)=>U, progress?:(value:P)=>void): PPromise<U,P>;
	public then<U>(success?: (value:C)=>U, error?: (err:any)=>void, progress?:(value:P)=>void): PPromise<U,P>;

	public done(success?: (value:C)=>void, error?: (err:any)=>any, progress?:(value:P)=>void): void;
	public cancel():void;

	public static as<V>(value:V):TPromise<V>;
	public static timeout(delay:number):PPromise<void, void>;
	public static join<C,P>(promises:PPromise<C,P>[]):PPromise<C,P[]>;
	public static join<C,P>(promises: {[n:string]:PPromise<C,P>}):PPromise<{[n:string]:C},P>;
	public static any<C,P>(promises:PPromise<C,P>[]):PPromise<{ key:string; value:PPromise<C,P>;},P>;
	public static wrapError<V>(error:any):TPromise<V>;
}


text:
namespace OneCloudNet.Client
{
    using System;
    using System.Net;
    using OneCloudNet.Exceptions;
    using OneCloudNet.Helpers;
    using RestSharp;
    using RestSharp.Serialization.Json;

    /// <summary>
    /// The main 1Cloud API client interface.
    /// </summary>
    public partial class OneCloudNetClient : IOneCloudNetClient
    {
        /// <summary>
        /// Base URL for API requests.
        /// </summary>
        private const string ApiBaseUrl = "https://api.1cloud.ru";

        /// <summary>
        /// Unique private API token for authorization.
        /// </summary>
        private readonly string _token;

        /// <summary>
        /// Client for REST-communications.
        /// </summary>
        private RestClient _restClient;

        /// <summary>
        /// Helper for creating REST-requests.
        /// </summary>
        private RequestHelper _requestHelper;

        /// <summary>
        /// Initializes a new instance of the <see cref="OneCloudNetClient" /> class.
        /// </summary>
        /// <param name="token">The token to use for the 1Cloud Requests</param>
        /// <param name="proxy">The proxy to use for web requests</param>
        public OneCloudNetClient(string token, IWebProxy proxy = null)
        {
            Proxy = proxy;
            _token = token;
            LoadClient();
        }

        /// <summary>
        /// Proxy settings.
        /// </summary>
        public IWebProxy Proxy { get; set; }

        private void LoadClient()
        {
            _restClient = new RestClient(ApiBaseUrl);
            _restClient.Proxy = Proxy;
            _restClient.ClearHandlers();
            _restClient.AddHandler("*", new JsonDeserializer());

            _requestHelper = new RequestHelper(_token);
        }

        private T Execute<T>(IRestRequest request)
            where T : new()
        {
            var response = _restClient.Execute<T>(request);

            if (response.StatusCode != HttpStatusCode.OK &&
                response.StatusCode != HttpStatusCode.Created)
            {
                throw new OneCloudRestException(response, HttpStatusCode.OK);
            }

            return response.Data;
        }

        private IRestResponse Execute(IRestRequest request)
        {
            var response = _restClient.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK &&
                response.StatusCode != HttpStatusCode.Created)
            {
                throw new OneCloudRestException(response, HttpStatusCode.OK);
            }

            return response;
        }

        private void ExecuteAsync(IRestRequest request, Action<IRestResponse> success, Action<OneCloudException> failure)
        {
            _restClient.ExecuteAsync(
                request,
                (response, asynchandle) =>
                {
                    if (response.StatusCode != HttpStatusCode.OK &&
                        response.StatusCode != HttpStatusCode.Created)
                    {
                        failure(new OneCloudRestException(response, HttpStatusCode.OK));
                    }
                    else
                    {
                        success(response);
                    }
                });
        }

        private void ExecuteAsync<T>(IRestRequest request, Action<T> success, Action<OneCloudException> failure)
        {
            _restClient.ExecuteAsync<T>(
                request,
                (response, asynchandle) =>
                {
                    if (response.StatusCode != HttpStatusCode.OK &&
                        response.StatusCode != HttpStatusCode.Created)
                    {
                        failure(new OneCloudRestException(response, HttpStatusCode.OK));
                    }
                    else
                    {
                        success(response.Data);
                    }
                });
        }
    }
}


text:
define :db_postgres_connect_app, :template => "db_connection_example.erb", :cookbook => "db_postgres", :database => nil do

  template params[:name] do
    source params[:template]
    cookbook params[:cookbook]
    mode 0440
    owner params[:owner]
    group params[:group]
    backup false
    variables(
      :user => node[:db][:application][:user],
      :password => node[:db][:application][:password],
      :fqdn => node[:db][:dns][:master][:fqdn],
      :socket => node[:db_postgres][:socket],
      :database => params[:database]
    )
  end

end


text:
<?php

namespace Seller\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Http\PhpEnvironment\Request;
use Seller\Model\Seller;
use Seller\Form\SellerForm;
use Seller\Form\UploadForm;
use Seller\Form\EmailForm;
use Zend\Mail\Message;
use Zend\Mail\Transport\Sendmail;

class SellerController extends AbstractActionController {

    public function indexAction() {
        $form = new UploadForm('upload-form');

        if ($this->getRequest()->isPost()) {
            // Make certain to merge the files info!
            $post = array_merge_recursive(
                    $this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray()
            );

            $form->setData($post);

            $seller = new Seller();
            //$form->setInputFilter($seller->getInputFilter());

            if ($form->isValid()) {
                $data = $form->getData();

                $property_image = substr(($data['image-file']['tmp_name']), -24);

                $data['property_image'] = $property_image;

                $seller = new Seller();

                $seller->exchangeArray($data);
                $this->getSellerTable()->saveProperty($seller);

                // Form is valid, save the form!
                return $this->redirect()->toRoute('seller');
            }
        }

        return array('form' => $form);
    }

    public function getSellerTable() {
//        if (!$this->sellerTable) {
        $sm = $this->getServiceLocator();
        $this->sellerTable = $sm->get('Seller\Model\SellerTable');
//        }
        return $this->sellerTable;
    }

    /*     * ************************************************* */

    public function uploadFormAction() {
        $form = new UploadForm('upload-form');
        $tempFile = null;

        $prg = $this->fileprg($form);
        if ($prg instanceof \Zend\Http\PhpEnvironment\Response) {
            return $prg; // Return PRG redirect response
        } elseif (is_array($prg)) {
            if ($form->isValid()) {
                $data = $form->getData();
                // Form is valid, save the form!
                return $this->redirect()->toRoute('upload-form/success');
            } else {
                // Form not valid, but file uploads might be valid...
                // Get the temporary file information to show the user in the view
                $fileErrors = $form->get('image-file')->getMessages();
                if (empty($fileErrors)) {
                    $tempFile = $form->get('image-file')->getValue();
                }
            }
        }

        return array(
            'form' => $form,
            'tempFile' => $tempFile,
        );
    }

    public function detailsAction() {

       $id = (int)$this->params('id');

       if($id!=0)
       {
       $property_details = $this->getSellerTable()->getProperty($id);
       }

        $emailForm = new EmailForm('email-form');

       $request = $this->getRequest();

        if ($this->getRequest()->isPost()) {

           $data = $request->getPost();

          $email = $data->user_email;

            $message = new Message();

            $message->addFrom($email)
                    ->addTo("iqbal.wdz@gmail.com")
                    ->setSubject("Sending an email from Property Details Page");
            $message->setBody("This is the message body.");

            $transport = new Mail\Transport\Sendmail();
            $transport->send($message);

            return $this->redirect()->toRoute('application');

        }

        return array('form' => $emailForm,'property_details'=>$property_details);
    }

    public function propertyAction(){

    }

}


text:
package com.akjava.gwt.html5.client.file.ui;

import com.akjava.gwt.html5.client.file.File;
import com.akjava.gwt.html5.client.file.FileUtils;
import com.akjava.gwt.html5.client.file.webkit.DirectoryCallback;
import com.akjava.gwt.html5.client.file.webkit.FileEntry;
import com.akjava.gwt.html5.client.file.webkit.FilePathCallback;
import com.akjava.gwt.html5.client.file.webkit.Item;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.dom.client.DragLeaveEvent;
import com.google.gwt.event.dom.client.DragLeaveHandler;
import com.google.gwt.event.dom.client.DragOverEvent;
import com.google.gwt.event.dom.client.DragOverHandler;
import com.google.gwt.event.dom.client.DropEvent;
import com.google.gwt.event.dom.client.DropHandler;

/**
 * TODO
 * how to know drop end?
 * @author aki
 *
 */
public abstract class AbstractVerticalDropPanel extends DropVerticalPanelBase {

	public abstract void dropStart();
	//public abstract void dropEnd();
	public abstract void dropFile(File file,String parent);
	public AbstractVerticalDropPanel(){
		this.addDropHandler(new DropHandler() {

			@Override
			public void onDrop(DropEvent event) {
				event.preventDefault();

				dropStart();

				final JsArray<Item> items = FileUtils.transferToItem(event
						.getNativeEvent());
				final FilePathCallback callback = new FilePathCallback() {
					@Override
					public void callback(File file, String parent) {
						if(file!=null){
						dropFile(file,parent);
						}
					}

				};

				for(int i=0;i<items.length();i++){
					FileEntry entry = items.get(i).webkitGetAsEntry();
					entryCallback(entry,callback,"");
				}

			}
		});
		this.addDragOverHandler(new DragOverHandler() {
			@Override
			public void onDragOver(DragOverEvent event) {
				event.preventDefault();
				dragOver();

			}
		});

		this.addDragLeaveHandler(new DragLeaveHandler() {

			@Override
			public void onDragLeave(DragLeaveEvent event) {
				event.preventDefault();
				dragLeave();
			}
		});
	}
	public abstract void dragLeave() ;
	public abstract void dragOver() ;
	private void entryCallback(final FileEntry entry,final FilePathCallback callback,String path){
		if(entry==null){
			return;
		}
		if (entry.isFile()) {
			entry.file(callback,path);
		} else if (entry.isDirectory()) {
			entry.getReader().readEntries(
					new DirectoryCallback() {
						@Override
						public void callback(
								JsArray<FileEntry> entries) {
							callback.callback(null, entry.getFullPath());
							for (int j = 0; j < entries
									.length(); j++) {
								entryCallback(entries.get(j),callback,entry.getFullPath());
							}
						}
					});
		}
	}

}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import oscar_vat_moss.fields

class Migration(migrations.Migration):

    dependencies = [
        ('partner', '0003_auto_20150604_1450'),
    ]

    operations = [
        migrations.AddField(
            model_name='partneraddress',
            name='vatin',
            field=oscar_vat_moss.fields.VATINField(help_text='Required if you are associated with a business registered for VAT in the European Union.', verbose_name='VAT Identification Number (VATIN)', blank=True),
        ),
    ]


text:
import base64

import requests
from allauth.account.utils import user_email, user_field, user_username
from allauth.exceptions import ImmediateHttpResponse
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
                                                          OAuth2CallbackView,
                                                          OAuth2LoginView)
from allauth.utils import valid_email_or_none
from django.contrib.auth import get_user_model
from django.urls import reverse_lazy
from django.views.generic.base import TemplateView
from django.shortcuts import redirect

from osf_oauth2_adapter.provider import OSFProvider

from .apps import OsfOauth2AdapterConfig

class OSFOAuth2Adapter(OAuth2Adapter, DefaultSocialAccountAdapter):
    provider_id = OSFProvider.id
    base_url = '{}oauth2/{}'.format(OsfOauth2AdapterConfig.osf_accounts_url, '{}')
    access_token_url = base_url.format('token')
    authorize_url = base_url.format('authorize')
    profile_url = '{}v2/users/me/'.format(OsfOauth2AdapterConfig.osf_api_url)

    def get_base64_gravatar(self, url):
        resp = requests.get(url)
        return "data:" + resp.headers['Content-Type'] + ";" + "base64," + str(base64.b64encode(resp.content).decode("utf-8"))

    def pre_social_login(self, request, sociallogin):
        User = get_user_model()
        if User.objects.filter(username=sociallogin.user.username, is_researcher=False).exists():
            raise ImmediateHttpResponse(redirect(reverse_lazy('local-user-already-exists')))
        return super().pre_social_login(request, sociallogin)

    def populate_user(self, request, sociallogin, data):
        """
        Hook that can be used to further populate the user instance.

        For convenience, we populate several common fields.

        Note that the user instance being populated represents a
        suggested User instance that represents the social user that is
        in the process of being logged in.

        The User instance need not be completely valid and conflict
        free. For example, verifying whether or not the username
        already exists, is not a responsibility.
        """
        username = data.get('username')
        first_name = data.get('first_name')
        last_name = data.get('last_name')
        email = username
        time_zone = data.get('time_zone')
        locale = data.get('locale')
        gravatar = data.get('profile_image_url')
        user = sociallogin.user
        user_username(user, username or '')
        user_email(user, valid_email_or_none(email) or '')
        user_field(user, 'given_name', first_name or '')
        user.is_active = True
        user.is_researcher = True
        user_field(user, 'family_name', last_name or '')
        user_field(user, 'time_zone', time_zone)
        user_field(user, 'locale', locale)
        user_field(user, '_identicon', self.get_base64_gravatar(gravatar))

        return user

    def complete_login(self, request, app, access_token, **kwargs):
        extra_data = requests.get(self.profile_url, headers={
            'Authorization': 'Bearer {}'.format(access_token.token)
        })
        return self.get_provider().sociallogin_from_response(
            request,
            extra_data.json()
        )

oauth2_login = OAuth2LoginView.adapter_view(OSFOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(OSFOAuth2Adapter)

class LoginErroredCancelledView(TemplateView):
    template_name = ("account/login_errored_cancelled.html")

login_errored_cancelled = LoginErroredCancelledView.as_view()

class LocalUserAlreadyExistsView(TemplateView):
    template_name = 'account/local_user_exists.html'


text:
% FOLD {{{
% Comment
\RequirePackage[shortlabels,inline]{enumitem}
% }}}