text:
"""Keras layers of XLNet model in TF 2.0."""

from __future__ import absolute_import
from __future__ import division
# from __future__ import google_type_annotations
from __future__ import print_function

import copy
import numpy as np

import tensorflow as tf
from official.nlp.xlnet import data_utils

def gelu(x):
  """Gaussian Error Linear Unit.

  This is a smoother version of the RELU.
  Original paper: https://arxiv.org/abs/1606.08415
  Args:
    x: float Tensor to perform activation.

  Returns:
    `x` with the GELU activation applied.
  """
  cdf = 0.5 * (1.0 + tf.tanh(
      (np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3)))))
  return x * cdf

def rel_shift(x, klen=-1):
  """Performs relative shift to form the relative attention score."""
  x_size = tf.shape(x)

  x = tf.reshape(x, [x_size[1], x_size[0], x_size[2], x_size[3]])
  x = tf.slice(x, [1, 0, 0, 0], [-1, -1, -1, -1])
  x = tf.reshape(x, [x_size[0], x_size[1] - 1, x_size[2], x_size[3]])
  x = tf.slice(x, [0, 0, 0, 0], [-1, klen, -1, -1])

  return x

def _get_initializer(flags):
  """Get variable intializer."""
  if flags.init_method == 'uniform':
    initializer = tf.keras.initializers.RandomUniform(
        minval=-flags.init_range, maxval=flags.init_range)
  elif flags.init_method == 'normal':
    initializer = tf.keras.initializers.RandomNormal(stddev=flags.init_std)
  else:
    raise ValueError('Initializer {} not supported'.format(flags.init_method))
  return initializer

def _create_mask(qlen, mlen, dtype=tf.float32, same_length=False):
  """Creates attention mask when single-side context allowed only."""
  attn_mask = tf.ones([qlen, qlen], dtype=dtype)
  mask_u = tf.linalg.band_part(attn_mask, 0, -1)
  mask_dia = tf.linalg.band_part(attn_mask, 0, 0)
  attn_mask_pad = tf.zeros([qlen, mlen], dtype=dtype)
  ret = tf.concat([attn_mask_pad, mask_u - mask_dia], 1)
  if same_length:
    mask_l = tf.linalg.band_part(attn_mask, -1, 0)
    ret = tf.concat([ret[:, :qlen] + mask_l - mask_dia, ret[:, qlen:]], 1)

  return ret

def _cache_mem(curr_out, prev_mem, mem_len, reuse_len=None):
  """cache hidden states into memory."""

  if mem_len is None or mem_len == 0:
    return None
  else:
    if reuse_len is not None and reuse_len > 0:
      curr_out = curr_out[:reuse_len]

    if prev_mem is None:
      new_mem = curr_out[-mem_len:]
    else:
      new_mem = tf.concat([prev_mem, curr_out], 0)[-mem_len:]

  return tf.keras.backend.stop_gradient(new_mem)

def is_special_none_tensor(tensor):
  """Checks if a tensor is a special None Tensor."""
  return tensor.shape.ndims == 0 and tensor.dtype == tf.int32

class PositionalEmbedding(tf.keras.layers.Layer):
  """Generates relative positional embeddings used in Transformer-XL and XLNet."""

  def __init__(self, dim, **kwargs):
    super(PositionalEmbedding, self).__init__(**kwargs)
    self.dim = dim

  def build(self, unused_input_shapes):
    """Constructs inversed frequency vector for positional embedding layer."""
    self.inv_freq = 1.0 / (10000.0**(tf.range(0, self.dim, 2.0) / self.dim))
    super(PositionalEmbedding, self).build(unused_input_shapes)

  def call(self, pos_seq, batch_size):
    """Implements call() for the layer."""
    sinusoid_inp = tf.einsum('i,d->id', pos_seq, self.inv_freq)
    pos_emb = tf.concat([tf.sin(sinusoid_inp), tf.cos(sinusoid_inp)], -1)
    pos_emb = pos_emb[:, None, :]

    if batch_size is not None:
      pos_emb = tf.tile(pos_emb, [1, batch_size, 1])

    return pos_emb

class RelativeAttention(tf.keras.layers.Layer):
  """Core calculations for relative attention."""

  def __init__(self, dropout_att, scale):
    super(RelativeAttention, self).__init__()
    self.scale = scale
    self.dropout_att = dropout_att

  def build(self, unused_input_shapes):
    """Implements build() for the layer."""

    self.attention_probs_dropout = tf.keras.layers.Dropout(
        rate=self.dropout_att)

    super(RelativeAttention, self).build(unused_input_shapes)

  def call(self, q_head, k_head_h, v_head_h, k_head_r, seg_embed, seg_mat,
           r_w_bias, r_r_bias, r_s_bias, attn_mask):
    """Implements call() for the layer."""

    # content based attention score
    ac = tf.einsum('ibnd,jbnd->ijbn', q_head + r_w_bias, k_head_h)

    # position based attention score
    bd = tf.einsum('ibnd,jbnd->ijbn', q_head + r_r_bias, k_head_r)
    bd = rel_shift(bd, klen=tf.shape(ac)[1])

    # segment-based attention score
    if seg_mat is None:
      ef = 0
    else:
      ef = tf.einsum('ibnd,snd->isbn', q_head + r_s_bias, seg_embed)
      tgt_shape = tf.shape(bd)
      ef = tf.where(
          tf.broadcast_to(tf.expand_dims(seg_mat, 3), tgt_shape),
          tf.broadcast_to(ef[:, 1:, :, :], tgt_shape),
          tf.broadcast_to(ef[:, :1, :, :], tgt_shape))

    # merges attention scores and performs masking
    attn_score = (ac + bd + ef) * self.scale
    if attn_mask is not None:
      attn_score = attn_score - 1e30 * attn_mask

    # attention probability
    attn_prob = tf.nn.softmax(attn_score, 1)
    attn_prob = self.attention_probs_dropout(attn_prob)

    # attention output
    attn_vec = tf.einsum('ijbn,jbnd->ibnd', attn_prob, v_head_h)

    return attn_vec

class PositionwiseFF(tf.keras.layers.Layer):
  """Positionwise feed-forward layer."""

  def __init__(self, d_model, d_inner, dropout, kernel_initializer,
               activation_type, **kwargs):
    super(PositionwiseFF, self).__init__(**kwargs)
    self.d_model = d_model
    self.d_inner = d_inner
    self.dropout = dropout
    self.activation_type = activation_type
    self.kernel_initializer = kernel_initializer

  def build(self, unused_input_shapes):
    """Implements build() for the layer."""
    if self.activation_type == 'relu':
      activation = tf.nn.relu
    elif self.activation_type == 'gelu':
      activation = gelu
    else:
      raise (ValueError('Unsupported activation type {}'.format(
          self.activation_type)))
    self.inner_projection_layer = (
        tf.keras.layers.Dense(
            units=self.d_inner,
            activation=activation,
            kernel_initializer=self.kernel_initializer,
            name='layer_1'))
    self.output_projection_layer = (
        tf.keras.layers.Dense(
            units=self.d_model,
            kernel_initializer=self.kernel_initializer,
            name='layer_2'))
    self.output_dropout = tf.keras.layers.Dropout(
        rate=self.dropout, name='drop_2')
    self.output_layer_norm = (
        tf.keras.layers.LayerNormalization(
            name='LayerNorm', axis=-1, epsilon=1e-12))
    super(PositionwiseFF, self).build(unused_input_shapes)

  def call(self, inp):
    """Implements call() for the layer."""

    output = self.inner_projection_layer(inp)
    output = self.output_projection_layer(output)
    output = self.output_dropout(output)
    output = self.output_layer_norm(output + inp)
    return output

class EmbeddingLookup(tf.keras.layers.Layer):
  """Looks up words embeddings for id tensor."""

  def __init__(self, n_token, d_embed, initializer, **kwargs):
    super(EmbeddingLookup, self).__init__(**kwargs)
    self.n_token = n_token
    self.d_embed = d_embed
    self.initializer = initializer

  def build(self, unused_input_shapes):
    """Implements build() for the layer."""
    self.lookup_table = self.add_weight(
        'lookup_table',
        shape=[self.n_token, self.d_embed],
        initializer=self.initializer,
        dtype=self.dtype)

    super(EmbeddingLookup, self).build(unused_input_shapes)

  def call(self, inputs):
    return tf.nn.embedding_lookup(self.lookup_table, inputs)

class RelativeMultiheadAttention(tf.keras.layers.Layer):
  """Multi-head attention with relative embedding."""

  def __init__(self, d_model, n_head, d_head, dropout, dropout_att,
               kernel_initializer, **kwargs):
    super(RelativeMultiheadAttention, self).__init__(**kwargs)
    self.d_model = d_model
    self.n_head = n_head
    self.d_head = d_head
    self.dropout = dropout
    self.dropout_att = dropout_att
    self.initializer = kernel_initializer

  def build(self, unused_input_shapes):
    """Implements build() for the layer."""
    self.scale = 1.0 / (self.d_head**0.5)

    self.output_layer_norm = tf.keras.layers.LayerNormalization(
        name='LayerNorm', axis=-1, epsilon=1e-12)

    self.kh_projection_layer = self.add_weight(
        'k/kernel',
        shape=[self.d_model, self.n_head, self.d_head],
        initializer=self.initializer)
    self.vh_projection_layer = self.add_weight(
        'v/kernel',
        shape=[self.d_model, self.n_head, self.d_head],
        initializer=self.initializer)
    self.kr_projection_layer = self.add_weight(
        'r/kernel',
        shape=[self.d_model, self.n_head, self.d_head],
        initializer=self.initializer)
    self.qh_projection_layer = self.add_weight(
        'q/kernel',
        shape=[self.d_model, self.n_head, self.d_head],
        initializer=self.initializer)

    self.relative_attention_layer = RelativeAttention(
        dropout_att=self.dropout_att, scale=self.scale)

    self.proj_o = self.add_weight(
        'o/kernel',
        shape=[self.d_model, self.n_head, self.d_head],
        initializer=self.initializer)

    self.attention_dropout = tf.keras.layers.Dropout(rate=self.dropout)

    super(RelativeMultiheadAttention, self).build(unused_input_shapes)

  def call(self, h, g, r, r_w_bias, r_r_bias, seg_mat, r_s_bias, seg_embed,
           attn_mask_h, attn_mask_g, mems, target_mapping):
    """Implements call() for the layer."""

    if mems is not None and mems.shape.ndims > 1:
      cat = tf.concat([mems, h], 0)
    else:
      cat = h

    # content heads
    q_head_h = tf.einsum('ibh,hnd->ibnd', h, self.qh_projection_layer)
    k_head_h = tf.einsum('ibh,hnd->ibnd', cat, self.kh_projection_layer)
    v_head_h = tf.einsum('ibh,hnd->ibnd', cat, self.vh_projection_layer)

    # positional heads
    k_head_r = tf.einsum('ibh,hnd->ibnd', r, self.kr_projection_layer)

    # core attention ops
    attn_vec_h = self.relative_attention_layer(q_head_h, k_head_h, v_head_h,
                                               k_head_r, seg_embed, seg_mat,
                                               r_w_bias, r_r_bias, r_s_bias,
                                               attn_mask_h)

    # post processing
    output_h = tf.einsum('ibnd,hnd->ibh', attn_vec_h, self.proj_o)
    output_h = self.attention_dropout(output_h)
    output_h = self.output_layer_norm(output_h + h)

    output_g = None
    if g is not None:  # enable two-stream attention
      # g-stream
      q_head_g = tf.einsum('ibh,hnd->ibnd', g, self.qh_projection_layer)
      if target_mapping is not None:
        q_head_g = tf.einsum('mbnd,mlb->lbnd', q_head_g, target_mapping)
        attn_vec_g = self.relative_attention_layer(q_head_g, k_head_h, v_head_h,
                                                   k_head_r, seg_embed, seg_mat,
                                                   r_w_bias, r_r_bias, r_s_bias,
                                                   attn_mask_g)
        attn_vec_g = tf.einsum('lbnd,mlb->mbnd', attn_vec_g, target_mapping)

      else:
        attn_vec_g = self.relative_attention_layer(q_head_g, k_head_h, v_head_h,
                                                   k_head_r, seg_embed, seg_mat,
                                                   r_w_bias, r_r_bias, r_s_bias,
                                                   attn_mask_g)

      # post processing
      output_g = tf.einsum('ibnd,hnd->ibh', attn_vec_g, self.proj_o)
      output_g = self.attention_dropout(output_g)
      output_g = self.output_layer_norm(output_g + g)

    return (output_h, output_g)

class TransformerXLModel(tf.keras.layers.Layer):
  """Defines a Transformer-XL computation graph with additional support for XLNet."""

  def __init__(self,
               n_token,
               n_layer,
               d_model,
               n_head,
               d_head,
               d_inner,
               dropout,
               dropout_att,
               attn_type,
               bi_data,
               is_training,
               initializer,
               mem_len=None,
               same_length=False,
               clamp_len=-1,
               untie_r=False,
               use_tpu=True,
               reuse_len=None,
               ff_activation='relu',
               use_cls_mask=False,
               **kwargs):
    """Initializes TransformerXLModel.

    Args:
      n_token: int, the number of tokens in vocabulary.
      n_layer: int, the number of layers.
      d_model: int, the hidden size.
      n_head: int, the number of attention heads.
      d_head: int, the dimension size of each attention head.
      d_inner: int, the hidden size in feed-forward layers.
      dropout: float, dropout rate.
      dropout_att: float, dropout rate on attention probabilities.
      attn_type: str, "uni" or "bi".
      bi_data: bool, whether to use bidirectional input pipeline. Usually set to
        True during pretraining and False during finetuning.
      is_training: bool, whether in training mode.
      initializer: A tf initializer.
      mem_len: int, the number of tokens to cache.
      same_length: bool, whether to use the same attention length for each
        token.
      clamp_len: int, clamp all relative distances larger than clamp_len. -1
        means no clamping.
      untie_r: bool, whether to untie the biases in attention.
      use_tpu: bool, whether TPUs are used.
      reuse_len: int, the number of tokens in the currect batch to be cached and
        reused in the future.
      ff_activation: str, "relu" or "gelu".
      use_cls_mask: bool, whether to introduce cls mask.
      **kwargs: Other parameters.
    """

    super(TransformerXLModel, self).__init__(**kwargs)

    self.n_token = n_token
    self.initializer = initializer
    self.attn_type = attn_type
    self.n_layer = n_layer
    self.d_model = d_model
    self.n_head = n_head
    self.d_head = d_head
    self.d_inner = d_inner
    self.ff_activation = ff_activation
    self.untie_r = untie_r
    self.use_tpu = use_tpu
    self.dropout = dropout
    self.dropout_att = dropout_att

    self.mem_len = mem_len
    self.reuse_len = reuse_len
    self.bi_data = bi_data
    self.clamp_len = clamp_len
    self.same_length = same_length
    self.use_cls_mask = use_cls_mask

  def build(self, unused_input_shapes):
    """Implements build() for the layer."""
    self.tf_float = tf.float32

    self.embedding_lookup = EmbeddingLookup(
        n_token=self.n_token,
        d_embed=self.d_model,
        initializer=self.initializer,
        dtype=self.tf_float,
        name='word_embedding')

    self.h_dropout = tf.keras.layers.Dropout(rate=self.dropout)
    self.g_dropout = tf.keras.layers.Dropout(rate=self.dropout)

    if self.untie_r:
      self.r_w_bias = (
          self.add_weight(
              'r_w_bias',
              shape=[self.n_layer, self.n_head, self.d_head],
              dtype=self.tf_float,
              initializer=self.initializer))
      self.r_r_bias = (
          self.add_weight(
              'r_r_bias',
              shape=[self.n_layer, self.n_head, self.d_head],
              dtype=self.tf_float,
              initializer=self.initializer))
      self.r_s_bias = (
          self.add_weight(
              'r_s_bias',
              shape=[self.n_layer, self.n_head, self.d_head],
              dtype=self.tf_float,
              initializer=self.initializer))
    else:
      self.r_w_bias = (
          self.add_weight(
              'r_w_bias',
              shape=[self.n_head, self.d_head],
              dtype=self.tf_float,
              initializer=self.initializer))
      self.r_r_bias = (
          self.add_weight(
              'r_r_bias',
              shape=[self.n_head, self.d_head],
              dtype=self.tf_float,
              initializer=self.initializer))
      self.r_s_bias = (
          self.add_weight(
              'r_s_bias', [self.n_head, self.d_head],
              dtype=self.tf_float,
              initializer=self.initializer))

    self.seg_embed = self.add_weight(
        'seg_embed', [self.n_layer, 2, self.n_head, self.d_head],
        dtype=self.tf_float,
        initializer=self.initializer)

    self.mask_emb = self.add_weight(
        'mask_emb/mask_emb', shape=[1, 1, self.d_model], dtype=self.tf_float)

    self.emb_dropout = tf.keras.layers.Dropout(rate=self.dropout)
    self.fwd_position_embedding = PositionalEmbedding(self.d_model)
    self.bwd_position_embedding = PositionalEmbedding(self.d_model)

    self.rel_multihead_layers = []
    self.h_positionwise_ffn_layers = []
    for i in range(self.n_layer):
      self.rel_multihead_layers.append(
          RelativeMultiheadAttention(
              d_model=self.d_model,
              dropout=self.dropout,
              n_head=self.n_head,
              d_head=self.d_head,
              dropout_att=self.dropout_att,
              kernel_initializer=self.initializer,
              name='layer_%d/rel_attn' % (i)))
      self.h_positionwise_ffn_layers.append(
          PositionwiseFF(
              d_model=self.d_model,
              d_inner=self.d_inner,
              dropout=self.dropout,
              kernel_initializer=self.initializer,
              activation_type=self.ff_activation,
              name='layer_%d/ff' % (i)))

    self.output_dropout = tf.keras.layers.Dropout(rate=self.dropout)

    super(TransformerXLModel, self).build(unused_input_shapes)

  def __call__(self,
               inp_k,
               seg_id=None,
               input_mask=None,
               mems=None,
               perm_mask=None,
               target_mapping=None,
               inp_q=None,
               **kwargs):
    # Uses dict to feed inputs into call() in order to keep mems as a python
    # list.
    inputs = {
        'inp_k': inp_k,
        'seg_id': seg_id,
        'input_mask': input_mask,
        'mems': mems,
        'perm_mask': perm_mask,
        'target_mapping': target_mapping,
        'inp_q': inp_q
    }
    return super(TransformerXLModel, self).__call__(inputs, **kwargs)

  def call(self, inputs):
    """Implements call() for the layer."""
    inp_k = inputs['inp_k']
    seg_id = inputs['seg_id']
    input_mask = inputs['input_mask']
    mems = inputs['mems']
    perm_mask = inputs['perm_mask']
    target_mapping = inputs['target_mapping']
    inp_q = inputs['inp_q']

    new_mems = []

    bsz = tf.shape(inp_k)[1]

    qlen = inp_k.shape.as_list()[0]

    mlen = mems[0].shape.as_list()[0] if mems is not None else 0
    klen = mlen + qlen

    ##### Attention mask
    # causal attention mask
    if self.attn_type == 'uni':
      attn_mask = _create_mask(qlen, mlen, self.tf_float, self.same_length)
      # pylint: enable=protected-access
      attn_mask = attn_mask[:, :, None, None]
    elif self.attn_type == 'bi':
      attn_mask = None
    else:
      raise ValueError('Unsupported attention type: {}'.format(self.attn_type))

    # data mask: input mask & perm mask
    if input_mask is not None and perm_mask is not None:
      data_mask = input_mask[None] + perm_mask

    elif input_mask is not None and perm_mask is None:
      data_mask = input_mask[None]
    elif input_mask is None and perm_mask is not None:
      data_mask = perm_mask
    else:
      data_mask = None

    if data_mask is not None:
      # all mems can be attended to
      mems_mask = tf.zeros([tf.shape(data_mask)[0], mlen, bsz],
                           dtype=self.tf_float)
      data_mask = tf.concat([mems_mask, data_mask], 1)
      if attn_mask is None:
        attn_mask = data_mask[:, :, :, None]
      else:
        attn_mask += data_mask[:, :, :, None]

    if attn_mask is not None:
      attn_mask = tf.cast(attn_mask > 0, dtype=self.tf_float)

    if attn_mask is not None:
      non_tgt_mask = -tf.eye(qlen, dtype=self.tf_float)
      non_tgt_mask = tf.concat(
          [tf.zeros([qlen, mlen], dtype=self.tf_float), non_tgt_mask], axis=-1)
      non_tgt_mask = tf.cast(
          (attn_mask + non_tgt_mask[:, :, None, None]) > 0, dtype=self.tf_float)
    else:
      non_tgt_mask = None

    word_emb_k = self.embedding_lookup(inp_k)

    if inp_q is not None:
      if target_mapping is not None:
        word_emb_q = tf.tile(self.mask_emb,
                             [tf.shape(target_mapping)[0], bsz, 1])
      else:
        inp_q_ext = inp_q[:, :, None]
        word_emb_q = inp_q_ext * self.mask_emb + (1 - inp_q_ext) * word_emb_k

    output_h = self.h_dropout(word_emb_k)
    output_g = None
    if inp_q is not None:
      output_g = self.g_dropout(word_emb_q)

    ##### Segment embedding
    if seg_id is not None:

      # Convert `seg_id` to one-hot `seg_mat`

      mem_pad = tf.zeros([mlen, bsz], dtype=tf.int32)

      cat_id = tf.concat([mem_pad, seg_id], 0)

      if self.use_cls_mask:
        # `1` indicates not in the same segment [qlen x klen x bsz]
        # seg_id: [qlen x bsz] & cat_id: [klen x bsz]
        cls_mat = tf.logical_or(
            tf.equal(seg_id, tf.constant([data_utils.SEG_ID_CLS]))[:, None],
            tf.equal(cat_id, tf.constant([data_utils.SEG_ID_CLS]))[None, :])
        seg_mat = tf.equal(seg_id[:, None], cat_id[None, :])
        seg_mat = tf.logical_or(cls_mat, seg_mat)
      else:
        seg_mat = tf.logical_not(tf.equal(seg_id[:, None], cat_id[None, :]))
    else:
      seg_mat = None

    dtype = self.tf_float
    freq_seq = tf.range(0, self.d_model, 2.0)
    if dtype is not None and dtype != tf.float32:
      freq_seq = tf.cast(freq_seq, dtype=self.dtype)

    if self.attn_type == 'bi':
      beg, end = klen, -qlen
    elif self.attn_type == 'uni':
      beg, end = klen, -1
    else:
      raise ValueError('Unknown `attn_type` {}.'.format(self.attn_type))

    if self.bi_data:
      fwd_pos_seq = tf.range(beg, end, -1.0)
      bwd_pos_seq = tf.range(-beg, -end, 1.0)

      if dtype is not None and dtype != tf.float32:
        fwd_pos_seq = tf.cast(fwd_pos_seq, dtype=dtype)
        bwd_pos_seq = tf.cast(bwd_pos_seq, dtype=dtype)

      if self.clamp_len > 0:
        fwd_pos_seq = tf.clip_by_value(fwd_pos_seq, -self.clamp_len,
                                       self.clamp_len)
        bwd_pos_seq = tf.clip_by_value(bwd_pos_seq, -self.clamp_len,
                                       self.clamp_len)

      if bsz is not None:
        fwd_pos_emb = self.fwd_position_embedding(fwd_pos_seq, bsz // 2)
        bwd_pos_emb = self.bwd_position_embedding(bwd_pos_seq, bsz // 2)
      else:
        fwd_pos_emb = self.fwd_position_embedding(fwd_pos_seq, None)
        bwd_pos_emb = self.bwd_position_embedding(bwd_pos_seq, None)

      pos_emb = tf.concat([fwd_pos_emb, bwd_pos_emb], axis=1)
    else:
      fwd_pos_seq = tf.range(beg, end, -1.0)
      if dtype is not None and dtype != tf.float32:
        fwd_pos_seq = tf.cast(fwd_pos_seq, dtype=dtype)
      if self.clamp_len > 0:
        fwd_pos_seq = tf.clip_by_value(fwd_pos_seq, -self.clamp_len,
                                       self.lamp_len)

      pos_emb = self.fwd_position_embedding(fwd_pos_seq, bsz)

    pos_emb = self.emb_dropout(pos_emb)

    if mems is None:
      mems = [None] * self.n_layer
    for i in range(self.n_layer):
      # cache new mems
      new_mems.append(
          _cache_mem(output_h, mems[i], self.mem_len, self.reuse_len))
      # pylint: enable=protected-access

      # segment bias
      if seg_id is None:
        r_s_bias_i = None
        seg_embed_i = None
      else:
        r_s_bias_i = self.r_s_bias if not self.untie_r else self.r_s_bias[i]
        seg_embed_i = self.seg_embed[i]

      ffn_layer = self.h_positionwise_ffn_layers[i]
      attention_layer = self.rel_multihead_layers[i]
      output_h, output_g = attention_layer(
          h=output_h,
          g=output_g,
          r=pos_emb,
          r_w_bias=self.r_w_bias if not self.untie_r else self.r_w_bias[i],
          r_r_bias=self.r_r_bias if not self.untie_r else self.r_r_bias[i],
          seg_mat=seg_mat,
          r_s_bias=r_s_bias_i,
          seg_embed=seg_embed_i,
          attn_mask_h=non_tgt_mask,
          attn_mask_g=attn_mask,
          mems=mems[i],
          target_mapping=target_mapping)
      output_h = ffn_layer(output_h)
      if output_g is not None:
        output_g = ffn_layer(output_g)

    if inp_q is not None:
      output = output_g
    else:
      output = output_h

    return output, new_mems, None

class PretrainingXLNetModel(tf.keras.Model):
  """XLNet keras model combined with pretraining LM loss layer.

  See the original paper: https://arxiv.org/pdf/1906.08237.pdf

  """

  def __init__(self, use_proj, xlnet_config, run_config, **kwargs):
    super(PretrainingXLNetModel, self).__init__(**kwargs)
    self.run_config = run_config
    self.initializer = _get_initializer(run_config)
    self.xlnet_config = copy.deepcopy(xlnet_config)

    self.transformerxl_model = TransformerXLModel(
        n_token=self.xlnet_config.n_token,
        initializer=self.initializer,
        attn_type='bi',
        n_layer=self.xlnet_config.n_layer,
        d_model=self.xlnet_config.d_model,
        n_head=self.xlnet_config.n_head,
        d_head=self.xlnet_config.d_head,
        d_inner=self.xlnet_config.d_inner,
        ff_activation=self.xlnet_config.ff_activation,
        untie_r=self.xlnet_config.untie_r,
        is_training=self.run_config.is_training,
        use_tpu=self.run_config.use_tpu,
        dropout=self.run_config.dropout,
        dropout_att=self.run_config.dropout_att,
        mem_len=self.run_config.mem_len,
        reuse_len=self.run_config.reuse_len,
        bi_data=self.run_config.bi_data,
        clamp_len=self.run_config.clamp_len,
        same_length=self.run_config.same_length,
        use_cls_mask=self.run_config.use_cls_mask,
        name='transformer')
    self.lmloss_layer = LMLossLayer(
        n_token=self.xlnet_config.n_token,
        d_model=self.xlnet_config.d_model,
        initializer=self.initializer,
        tie_weight=True,
        bi_data=self.run_config.bi_data,
        use_tpu=self.run_config.use_tpu,
        use_proj=use_proj,
        name='lm_loss')

  def call(self, features):
    """Implements call() for the layer."""

    input_ids = tf.transpose(features['input_k'], [1, 0])
    inp_q = tf.transpose(features['input_q'], [1, 0])

    seg_ids = tf.transpose(features['seg_id'], [1, 0])

    perm_mask = tf.transpose(features['perm_mask'], [1, 2, 0])

    target_mapping = tf.transpose(features['target_mapping'], [1, 2, 0])

    # target for LM loss
    target = tf.transpose(features['target'], [1, 0])

    # target mask for LM loss
    tgt_mask = tf.transpose(features['target_mask'], [1, 0])

    mems = features.get('mems', None)

    transformerxl_output, self.new_mems, self.lookup_table = self.transformerxl_model(
        input_ids,
        seg_id=seg_ids,
        input_mask=None,
        mems=mems,
        perm_mask=perm_mask,
        target_mapping=target_mapping,
        inp_q=inp_q)
    lm_loss, _ = self.lmloss_layer(
        hidden=transformerxl_output,
        target=target,
        lookup_table=self.transformerxl_model.embedding_lookup.lookup_table,
        target_mask=tgt_mask)
    self.add_loss(lm_loss)
    return self.new_mems, transformerxl_output

class ClassificationXLNetModel(tf.keras.Model):
  """XLNet keras model combined with classification loss layer.

  See the original paper: https://arxiv.org/pdf/1906.08237.pdf

  """

  def __init__(self, xlnet_config, run_config, n_class, summary_type, **kwargs):
    super(ClassificationXLNetModel, self).__init__(**kwargs)
    self.run_config = run_config
    self.initializer = _get_initializer(run_config)
    self.xlnet_config = copy.deepcopy(xlnet_config)

    self.transformerxl_model = TransformerXLModel(
        n_token=self.xlnet_config.n_token,
        initializer=self.initializer,
        attn_type='bi',
        n_layer=self.xlnet_config.n_layer,
        d_model=self.xlnet_config.d_model,
        n_head=self.xlnet_config.n_head,
        d_head=self.xlnet_config.d_head,
        d_inner=self.xlnet_config.d_inner,
        ff_activation=self.xlnet_config.ff_activation,
        untie_r=self.xlnet_config.untie_r,
        is_training=self.run_config.is_training,
        use_tpu=self.run_config.use_tpu,
        dropout=self.run_config.dropout,
        dropout_att=self.run_config.dropout_att,
        mem_len=self.run_config.mem_len,
        reuse_len=self.run_config.reuse_len,
        bi_data=self.run_config.bi_data,
        clamp_len=self.run_config.clamp_len,
        same_length=self.run_config.same_length,
        name='transformer')

    self.summarization_layer = Summarization(
        d_model=self.xlnet_config.d_model,
        n_head=self.xlnet_config.n_head,
        d_head=self.xlnet_config.d_head,
        dropout=self.run_config.dropout,
        dropout_att=self.run_config.dropout_att,
        initializer=self.initializer,
        use_proj=True,
        summary_type=summary_type,
        name='sequence_summary')

    self.cl_loss_layer = ClassificationLossLayer(
        n_class=n_class, initializer=self.initializer, name='classification')

  def call(self, features):
    """Implements call() for the layer."""
    bsz_per_core = tf.shape(features['input_ids'])[0]

    input_ids = tf.transpose(features['input_ids'], [1, 0])
    seg_ids = tf.transpose(features['segment_ids'], [1, 0])
    input_mask = tf.transpose(features['input_mask'], [1, 0])

    label = tf.reshape(features['label_ids'], [bsz_per_core])

    mems = features.get('mems', None)

    transformerxl_output, new_mems, self.lookup_table = (
        self.transformerxl_model(input_ids, seg_ids, input_mask, mems))

    summary = self.summarization_layer(transformerxl_output)
    per_example_loss, logits = self.cl_loss_layer(hidden=summary, labels=label)
    self.add_loss(tf.keras.backend.mean(per_example_loss))
    return new_mems, logits

class LMLossLayer(tf.keras.layers.Layer):
  """Layer computing cross entropy loss for language modeling."""

  def __init__(self,
               n_token,
               d_model,
               initializer,
               tie_weight=False,
               bi_data=True,
               use_tpu=False,
               use_proj=False,
               **kwargs):
    """Constructs LMLoss layer.

    Args:
      n_token: Number of tokens in vocabulary.
      d_model: The dimension of model hidden state.
      initializer: Initializer used for parameters.
      tie_weight: Whether to share weights between embedding lookup layer and
        next-token prediction layer.
      bi_data: Whether to use bidirectional input pipeline. Usually set to True
        during pretraining and False during finetuning.
      use_tpu: bool, whether to use TPU.
      use_proj: bool, whether to add a projection layer before LM prediction.
      **kwargs: Other parameters.
    """
    super(LMLossLayer, self).__init__(**kwargs)
    self.n_token = n_token
    self.d_model = d_model
    self.initializer = initializer

    self.tie_weight = tie_weight
    self.bi_data = bi_data
    self.use_tpu = use_tpu
    self.use_proj = use_proj

  def build(self, unused_input_shapes):
    """Implements build() for the layer."""
    if self.use_proj:
      self.proj_layer = tf.keras.layers.Dense(
          units=self.d_model,
          kernel_initializer=self.initializer,
          activation=gelu,
          name='lm_projection/dense')
      self.proj_layer_norm = tf.keras.layers.LayerNormalization(
          axis=-1, epsilon=1e-12, name='lm_projection/LayerNorm')
    if not self.tie_weight:
      self.softmax_w = self.add_weight(
          'weight',
          shape=[self.n_token, self.d_model],
          initializer=self.initializer)

    self.softmax_b = self.add_weight(
        'bias', shape=[self.n_token], initializer=tf.zeros_initializer())

    super(LMLossLayer, self).build(unused_input_shapes)

  def call(self, hidden, target, lookup_table, target_mask):
    """Implements call() for the layer."""
    if self.use_proj:
      hidden = self.proj_layer_norm(self.proj_layer(hidden))
    if self.tie_weight:
      logits = tf.einsum('ibd,nd->ibn', hidden, lookup_table) + self.softmax_b
    else:
      logits = tf.einsum('ibd,nd->ibn', hidden, self.softmax_w) + self.softmax_b

    if self.use_tpu:
      one_hot_target = tf.one_hot(target, self.n_token, dtype=logits.dtype)
      loss = -tf.reduce_sum(tf.nn.log_softmax(logits) * one_hot_target, -1)
    else:
      loss = tf.nn.sparse_softmax_cross_entropy_with_logits(
          labels=target, logits=logits)

    total_loss = tf.reduce_sum(loss * target_mask) / tf.reduce_sum(target_mask)

    return total_loss, logits

class Summarization(tf.keras.layers.Layer):
  """The layer to pool the output from XLNet model into a vector."""

  def __init__(self,
               d_model,
               n_head,
               d_head,
               dropout,
               dropout_att,
               initializer,
               use_proj=True,
               summary_type='last',
               **kwargs):
    """Constructs Summarization layer.

    Args:
      d_model: int, the dimension of model hidden state.
      n_head: int, the number of attention heads.
      d_head: int, the dimension size of each attention head.
      dropout: float, dropout rate.
      dropout_att: float, dropout rate on attention probabilities.
      initializer: Initializer used for parameters.
      use_proj: bool, whether to use projection layer for summarization.
      summary_type: Method used to summarize a sequence into a compact vector.
      **kwargs: Other parameters.
    """
    super(Summarization, self).__init__(**kwargs)
    self.d_model = d_model
    self.n_head = n_head
    self.d_head = d_head
    self.initializer = initializer

    self.dropout = dropout
    self.dropout_att = dropout_att
    self.use_proj = use_proj
    self.summary_type = summary_type

  def build(self, unused_input_shapes):
    """Implements build() for the layer."""
    if self.use_proj:
      self.proj_layer = tf.keras.layers.Dense(
          units=self.d_model,
          kernel_initializer=self.initializer,
          activation=tf.nn.tanh,
          name='summary')
    self.dropout_layer = tf.keras.layers.Dropout(rate=self.dropout)

    super(Summarization, self).build(unused_input_shapes)

  def call(self, inputs):
    """Implements call() for the layer."""
    if self.summary_type == 'last':
      summary = inputs[-1]
    elif self.summary_type == 'first':
      summary = inputs[0]
    else:
      raise ValueError('Invalid summary type provided: %s' % self.summary_type)
    summary = self.proj_layer(summary)
    summary = self.dropout_layer(summary)
    return summary

class ClassificationLossLayer(tf.keras.layers.Layer):
  """Layer computing cross entropy loss for classification task."""

  def __init__(self, n_class, initializer, **kwargs):
    """Constructs Summarization layer.

    Args:
      n_class: Number of tokens in vocabulary.
      initializer: Initializer used for parameters.
      **kwargs: Other parameters.
    """
    super(ClassificationLossLayer, self).__init__(**kwargs)

    self.n_class = n_class
    self.initializer = initializer

  def build(self, unused_input_shapes):
    """Implements build() for the layer."""
    self.proj_layer = tf.keras.layers.Dense(
        units=self.n_class, kernel_initializer=self.initializer, name='logit')

    super(ClassificationLossLayer, self).build(unused_input_shapes)

  def call(self, hidden, labels):
    """Implements call() for the layer."""

    logits = self.proj_layer(hidden)
    one_hot_target = tf.one_hot(labels, self.n_class, dtype=hidden.dtype)  # pytype: disable=attribute-error
    loss = -tf.reduce_sum(tf.nn.log_softmax(logits) * one_hot_target, -1)

    return loss, logits

class QAXLNetModel(tf.keras.Model):
  """XLNet keras model combined with question answering loss layer.

  See the original paper: https://arxiv.org/pdf/1906.08237.pdf

  """

  def __init__(self, xlnet_config, run_config, start_n_top, end_n_top,
               **kwargs):
    super(QAXLNetModel, self).__init__(**kwargs)
    self.run_config = run_config
    self.initializer = _get_initializer(run_config)
    self.xlnet_config = copy.deepcopy(xlnet_config)

    self.transformerxl_model = TransformerXLModel(
        n_token=self.xlnet_config.n_token,
        initializer=self.initializer,
        attn_type='bi',
        n_layer=self.xlnet_config.n_layer,
        d_model=self.xlnet_config.d_model,
        n_head=self.xlnet_config.n_head,
        d_head=self.xlnet_config.d_head,
        d_inner=self.xlnet_config.d_inner,
        ff_activation=self.xlnet_config.ff_activation,
        untie_r=self.xlnet_config.untie_r,
        is_training=self.run_config.is_training,
        use_tpu=self.run_config.use_tpu,
        dropout=self.run_config.dropout,
        dropout_att=self.run_config.dropout_att,
        mem_len=self.run_config.mem_len,
        reuse_len=self.run_config.reuse_len,
        bi_data=self.run_config.bi_data,
        clamp_len=self.run_config.clamp_len,
        same_length=self.run_config.same_length,
        name='transformer')

    self.qa_loss_layer = QALossLayer(
        d_model=self.xlnet_config.d_model,
        start_n_top=start_n_top,
        end_n_top=end_n_top,
        initializer=self.initializer,
        dropout=self.run_config.dropout)

  def call(self, features, training=False):
    """Implements call() for the layer."""

    input_ids = tf.transpose(features['input_ids'], [1, 0])
    seg_ids = tf.transpose(features['segment_ids'], [1, 0])
    input_mask = tf.transpose(features['input_mask'], [1, 0])

    cls_index = tf.reshape(features['cls_index'], [-1])
    p_mask = features['p_mask']

    transformerxl_output, new_mems, self.lookup_table = (
        self.transformerxl_model(input_ids, seg_ids, input_mask))

    if training:
      loss, logits = self.qa_loss_layer(
          hidden=transformerxl_output,
          p_mask=p_mask,
          cls_index=cls_index,
          start_positions=features['start_positions'],
          end_positions=features['end_positions'],
          is_impossible=features['is_impossible'])
      self.add_loss(loss)
      return new_mems, logits
    else:
      results = self.qa_loss_layer(
          hidden=transformerxl_output, p_mask=p_mask, cls_index=cls_index)
      return results

class QALossLayer(tf.keras.layers.Layer):
  """Layer computing position and regression loss for question answering task."""

  def __init__(self, d_model, start_n_top, end_n_top, initializer, dropout,
               **kwargs):
    """Constructs Summarization layer.

    Args:
      d_model: Int, the hidden size.
      start_n_top: Beam size for span start.
      end_n_top: Beam size for span end.
      initializer: Initializer used for parameters.
      dropout: float, dropout rate.
      **kwargs: Other parameters.
    """
    super(QALossLayer, self).__init__(**kwargs)
    self.d_model = d_model
    self.start_n_top = start_n_top
    self.end_n_top = end_n_top
    self.initializer = initializer
    self.dropout = dropout

  def build(self, unused_input_shapes):
    """Implements build() for the layer."""
    self.start_logits_proj_layer = tf.keras.layers.Dense(
        units=1, kernel_initializer=self.initializer, name='start_logits/dense')
    self.end_logits_proj_layer0 = tf.keras.layers.Dense(
        units=self.d_model,
        kernel_initializer=self.initializer,
        activation=tf.nn.tanh,
        name='end_logits/dense_0')
    self.end_logits_proj_layer1 = tf.keras.layers.Dense(
        units=1, kernel_initializer=self.initializer, name='end_logits/dense_1')
    self.end_logits_layer_norm = tf.keras.layers.LayerNormalization(
        axis=-1, epsilon=1e-12, name='end_logits/LayerNorm')
    self.answer_class_proj_layer0 = tf.keras.layers.Dense(
        units=self.d_model,
        kernel_initializer=self.initializer,
        activation=tf.nn.tanh,
        name='answer_class/dense_0')
    self.answer_class_proj_layer1 = tf.keras.layers.Dense(
        units=1,
        kernel_initializer=self.initializer,
        use_bias=False,
        name='answer_class/dense_1')
    self.ans_feature_dropout = tf.keras.layers.Dropout(rate=self.dropout)
    super(QALossLayer, self).build(unused_input_shapes)

  def __call__(self, hidden, p_mask, cls_index, **kwargs):
    return super(QALossLayer, self).__call__(
        (hidden, p_mask, cls_index, kwargs))

  def call(self, inputs, training=False):
    """Implements call() for the layer."""
    hidden, p_mask, cls_index, kwargs = inputs
    return_dict = {}
    seq_len = tf.shape(hidden)[0]

    start_logits = self.start_logits_proj_layer(hidden)
    start_logits = tf.transpose(tf.squeeze(start_logits, -1), [1, 0])
    start_logits_masked = start_logits * (1 - p_mask) - 1e30 * p_mask
    start_log_probs = tf.nn.log_softmax(start_logits_masked, -1)
    if training:
      start_positions = kwargs['start_positions']
      end_positions = kwargs['end_positions']
      is_impossible = kwargs['is_impossible']
      start_positions = tf.reshape(start_positions, [-1])
      start_index = tf.one_hot(
          start_positions, depth=seq_len, axis=-1, dtype=tf.float32)
      start_features = tf.einsum('lbh,bl->bh', hidden, start_index)
      start_features = tf.tile(start_features[None], [seq_len, 1, 1])
      end_logits = self.end_logits_proj_layer0(
          tf.concat([hidden, start_features], axis=-1))

      end_logits = self.end_logits_layer_norm(end_logits)

      end_logits = self.end_logits_proj_layer1(end_logits)
      end_logits = tf.transpose(tf.squeeze(end_logits, -1), [1, 0])
      end_logits_masked = end_logits * (1 - p_mask) - 1e30 * p_mask
      end_log_probs = tf.nn.log_softmax(end_logits_masked, -1)
    else:
      # during inference, compute the end logits based on beam search

      start_top_log_probs, start_top_index = tf.nn.top_k(
          start_log_probs, k=self.start_n_top)
      start_index = tf.one_hot(
          start_top_index, depth=seq_len, axis=-1, dtype=tf.float32)
      start_features = tf.einsum('lbh,bkl->bkh', hidden, start_index)
      end_input = tf.tile(hidden[:, :, None], [1, 1, self.start_n_top, 1])
      start_features = tf.tile(start_features[None], [seq_len, 1, 1, 1])
      end_input = tf.concat([end_input, start_features], axis=-1)
      end_logits = self.end_logits_proj_layer0(end_input)
      end_logits = tf.reshape(end_logits, [seq_len, -1, self.d_model])
      end_logits = self.end_logits_layer_norm(end_logits)

      end_logits = tf.reshape(end_logits,
                              [seq_len, -1, self.start_n_top, self.d_model])

      end_logits = self.end_logits_proj_layer1(end_logits)
      end_logits = tf.reshape(end_logits, [seq_len, -1, self.start_n_top])
      end_logits = tf.transpose(end_logits, [1, 2, 0])
      end_logits_masked = end_logits * (
          1 - p_mask[:, None]) - 1e30 * p_mask[:, None]
      end_log_probs = tf.nn.log_softmax(end_logits_masked, -1)
      end_top_log_probs, end_top_index = tf.nn.top_k(
          end_log_probs, k=self.end_n_top)
      end_top_log_probs = tf.reshape(end_top_log_probs,
                                     [-1, self.start_n_top * self.end_n_top])
      end_top_index = tf.reshape(end_top_index,
                                 [-1, self.start_n_top * self.end_n_top])

    if training:
      return_dict['start_log_probs'] = start_log_probs
      return_dict['end_log_probs'] = end_log_probs
    else:
      return_dict['start_top_log_probs'] = start_top_log_probs
      return_dict['start_top_index'] = start_top_index
      return_dict['end_top_log_probs'] = end_top_log_probs
      return_dict['end_top_index'] = end_top_index
    # an additional layer to predict answerability

    # get the representation of CLS
    cls_index = tf.one_hot(cls_index, seq_len, axis=-1, dtype=tf.float32)
    cls_feature = tf.einsum('lbh,bl->bh', hidden, cls_index)

    # get the representation of START
    start_p = tf.nn.softmax(start_logits_masked, axis=-1, name='softmax_start')
    start_feature = tf.einsum('lbh,bl->bh', hidden, start_p)

    ans_feature = tf.concat([start_feature, cls_feature], -1)
    ans_feature = self.answer_class_proj_layer0(ans_feature)
    ans_feature = self.ans_feature_dropout(ans_feature)
    cls_logits = self.answer_class_proj_layer1(ans_feature)
    cls_logits = tf.squeeze(cls_logits, -1)
    return_dict['cls_logits'] = cls_logits

    if not training:
      return return_dict

    def compute_loss(log_probs, positions):
      one_hot_positions = tf.one_hot(positions, depth=seq_len, dtype=tf.float32)

      loss = -tf.reduce_sum(one_hot_positions * log_probs, axis=-1)
      loss = tf.reduce_mean(loss)
      return loss

    start_loss = compute_loss(start_log_probs, start_positions)
    end_loss = compute_loss(end_log_probs, end_positions)

    total_loss = (start_loss + end_loss) * 0.5

    is_impossible = tf.reshape(is_impossible, [-1])
    regression_loss = tf.nn.sigmoid_cross_entropy_with_logits(
        labels=is_impossible, logits=cls_logits)
    regression_loss = tf.reduce_mean(regression_loss)

    total_loss += regression_loss * 0.5
    return total_loss, cls_logits


text:
#pragma once

#include "../oomodel_api.h"
#include "Type.h"

namespace OOModel {

class OOMODEL_API ReferenceType : public Type {
	public:
		ReferenceType(Type* baseType, bool isValueType);
		ReferenceType(const ReferenceType& other);
		virtual ~ReferenceType();

		virtual bool equals(const Type* other) const override;
		virtual ReferenceType* clone() const override;

		const Type* baseType() const;

	private:
		Type* baseType_;
};

inline const Type* ReferenceType::baseType() const { return baseType_; }
} /* namespace OOModel */

redpajama_set_name: RedPajamaGithub


text:
"use strict"

var colorSchemes = {
	standard: { front: "blue", back: "green", up: "orange", down: "red", left: "white", right: "yellow" },
	ad8: { front: "#009", back: "#111", up: "#999", down: "#990", left: "#900", right: "#090" },
	bright: { front: "#F00", back: "#0FF", up: "#0F0", down: "#F0F", left: "#00F", right: "#FF0" },
	dark: { front: "#600", back: "#066", up: "#060", down: "#606", left: "#006", right: "#660" },
	grayscale: { front: "#111", back: "#333", up: "#666", down: "#999", left: "#CCC", right: "#FFF" }
}
var cube = {
	SIDE_NAMES: ['front', 'back', 'left', 'right', 'up', 'down'],

	DIRS: { CW: 0, CCW: 1, TW: 2 },
	oppositeDirection: function(direction){
		var oppdir = direction;
		if(direction == this.DIRS.CW) oppdir = this.DIRS.CCW;
		else if(direction == this.DIRS.CCW) oppdir = this.DIRS.CW;
		return oppdir;
	},

	colors: colorSchemes.standard,

	size: 1,
	setSize: function(s){
		Can.can.width = Can.can.width; //clears the canvas
		this.size = s < 1 ? 1 : s;
		this.init();
		if(btnControls.visible) btnControls.show();;
	},

	focusedDepth: 1,
	setDepth: function(d){
		if(d < 1 || d > this.size-1) d = 1;
		this.focusedDepth = d;
		this.setWidth(this.turnWidth);
		depthView.draw();
	},

	turnWidth: 1,
	setWidth: function(w){
		w = w > this.focusedDepth ? this.focusedDepth : w
		w = w < 1 ? 1 : w;
		this.turnWidth = w;
		depthView.draw();
	},

	drawCube: function(clearCanvas){
		if(clearCanvas) Can.can.width = Can.can.width;
		unfoldedView.draw();
		cornerView.draw();
		if(timerSetting.isOn) timer.draw();
	},

	makeSide: function(color){
		var side = []
		for(var i = 0; i < this.size; i++){
			var row=[]
			for(var j = 0; j < this.size; j++){
				row[j] = color;
			}
			side[i] = row;
		}
		return side;
	},

	init: function(){
		this.SIDE_NAMES.forEach(function(s){ cube[s] = cube.makeSide(s); });
		this.drawCube();
		this.setDepth(1);
		this.wasScrambled = false;
		if(timerSetting.isOn) timer.reset();
	},

	/**** Rotations ****/
	/* rotations explained:
		rotatePoint will determine where a given x,y coordinate's resulting position if rotated (used for face rotations)
			translate to (0,0) in the center, coord is x+yi, multiply by i for CW, -i for CCW, or -1 for half turn.
			(x,y) => ((x-1) + (y-1)i) * i = (y-1) - (x-1)i => (y, 1-(x-1)) = (y, 2-x)
			(x,y) => ((x-1) + (y-1)i) * -i = -(y-1) + (x-1)i => (1-(y-1), x) = (2-y, x)
		rotateFace will turn elemnts of any given face in a given direction
			it will not rotate attached pieces within the layer (this is accomplished with rotateLayer)
			rotateFace should not be used directly; instead is called by full rotations and rotateLayer
		rotateFull[Up,Down,Left,Right] will turn the entire cube in the named direction, changing which face is "front"
		rotateLayer will perform a turn on the cube at cube.focusedDepth
			a depth of 1 will result in the face being turned. larger depths result in manipulation of inner layers
			rotateLayer will only operate on the front layer at any depth < cube.size
			combined with full rotations, any layer can be manipulated
		rotate[F,B,U,D,R,L] will rotate the named layer in the given direction at the focused depth
	*/
	rotatePoint: function(x, y, direction){
		switch(direction){
			case this.DIRS.CW:
				return { x: y, y: this.size-1-x };
				break;
			case this.DIRS.CCW:
				return { x: this.size-1-y, y: x };
				break;
			case this.DIRS.TW:
				return { x: this.size-1-x, y: this.size-1-y };
				break;
		}
	},

	rotateFace: function(side, direction){
		//copy existing face values
		var sideBak = [];
		side.forEach(function(col){ sideBak.push(col.slice(0)); });
		//translate to new positions
		for(var i = 0; i < this.size; i++){
			for(var j = 0; j < this.size; j++){
				var newPt = this.rotatePoint(j, i, direction);
				side[newPt.x][newPt.y] = sideBak[j][i]
			}
		}
	},

	rotateLayer: function(depth, direction, skipDraw){
		if(depth == 1) this.rotateFace(this.front, direction);
		if(depth == cube.size) this.rotateFace(this.back, this.oppositeDirection(direction));
		var tmp = this.up[this.size-depth].slice(0);
		for(var i = 0; i < this.size; i++){
			var end_i = this.size - i - 1; //index from end
			switch(direction){
				case this.DIRS.CW:
					this.up[this.size-depth][i] = this.left[end_i][this.size-depth];
					this.left[end_i][this.size-depth] = this.down[depth-1][end_i];
					this.down[depth-1][end_i] = this.right[i][depth-1];
					this.right[i][depth-1] = tmp[i];
					break;
				case this.DIRS.CCW:
					this.up[this.size-depth][i] = this.right[i][depth-1];
					this.right[i][depth-1] = this.down[depth-1][end_i];
					this.down[depth-1][end_i] = this.left[end_i][this.size-depth];
					this.left[end_i][this.size-depth] = tmp[i];
					break;
				/* TODO: this.DIRS.TW */
			}
		}
		if(!skipDraw) this.drawCube();
	},

	/**** Full Cube Rotations ****/
	rotateFullLeft: function(skipDraw){
		var tmp = this.front;
		this.front = this.right;
		this.right = this.back;
		this.back = this.left;
		this.left = tmp;
		this.rotateFace(this.up, this.DIRS.CW);
		this.rotateFace(this.down, this.DIRS.CCW);
		if(!skipDraw) this.drawCube();
	},
	rotateFullRight: function(skipDraw){
		var tmp = this.front;
		this.front = this.left;
		this.left = this.back;
		this.back = this.right;
		this.right = tmp;
		this.rotateFace(this.down, this.DIRS.CW);
		this.rotateFace(this.up, this.DIRS.CCW);
		if(!skipDraw) this.drawCube();
	},
	rotateFullUp: function(skipDraw){
		var tmp = this.front;
		this.front = this.down;
		this.down = this.back;
		this.back = this.up;
		this.up = tmp;
		this.rotateFace(this.down, this.DIRS.TW);
		this.rotateFace(this.back, this.DIRS.TW);
		this.rotateFace(this.right, this.DIRS.CW);
		this.rotateFace(this.left, this.DIRS.CCW);
		if(!skipDraw) this.drawCube();
	},
	rotateFullDown: function(skipDraw){
		var tmp = this.front;
		this.front = this.up;
		this.up = this.back;
		this.back = this.down;
		this.down = tmp;
		this.rotateFace(this.up, this.DIRS.TW);
		this.rotateFace(this.back, this.DIRS.TW);
		this.rotateFace(this.left, this.DIRS.CW);
		this.rotateFace(this.right, this.DIRS.CCW);
		if(!skipDraw) this.drawCube();
	},
	rotateFullCCW: function(skipDraw){
		for(var i = 1; i <= this.size; i++){
			this.rotateLayer(i, this.DIRS.CCW, true);
		}
		if(!skipDraw) this.drawCube();
	},
	rotateFullCW: function(skipDraw){
		for(var i = 1; i <= this.size; i++){
			this.rotateLayer(i, this.DIRS.CW, true);
		}
		if(!skipDraw) this.drawCube();
	},

	/**** Normal Moves ****/
	rotateF: function(direction, skipDraw){
		for(var i = 0; i < this.turnWidth; i++){
			var effectiveDepth = this.focusedDepth - i;
			if(effectiveDepth < 1) break;
			this.rotateLayer(effectiveDepth, direction, skipDraw);
		}
		var solved = this.isSolved();
		if(this.wasScrambled && solved) ga('send', 'event', 'cube'+this.size, 'solved', timerSetting.isOn ? timer.elapsedAsString() : 'untimed');
		if(this.wasScrambled && timerSetting.isOn){
			if(solved){
				timer.stop();
				this.wasScrambled = false;
			}else if(!timer.isStarted()){
				timer.start();
			}
		}
	},
	rotateB: function(direction, skipDraw){
		this.rotateFullLeft(true);
		this.rotateFullLeft(true);
		this.rotateF(direction, true);
		this.rotateFullLeft(true);
		this.rotateFullLeft(skipDraw);
	},
	rotateU: function(direction, skipDraw){
		this.rotateFullDown(true);
		this.rotateF(direction, true);
		this.rotateFullUp(skipDraw);
	},
	rotateD: function(direction, skipDraw){
		this.rotateFullUp(true);
		this.rotateF(direction, true);
		this.rotateFullDown(skipDraw);
	},
	rotateL: function (direction, skipDraw){
		this.rotateFullRight(true);
		this.rotateF(direction, true);
		this.rotateFullLeft(skipDraw);
	},
	rotateR: function (direction, skipDraw){
		this.rotateFullLeft(true);
		this.rotateF(direction, true);
		this.rotateFullRight(skipDraw);
	},
	wasScrambled: false,
	scramble: function(){
		var minimumTurns = 22;
		var depthRange = Math.floor(this.size/2);
		var turnCount = this.size*this.size*this.size;
		if(turnCount < minimumTurns) turnCount = minimumTurns;
		for(var i = 0; i < turnCount; i++){
			this.setDepth(Math.floor(Math.random()*depthRange)+1);
			var dir = Math.floor(Math.random()*2) == 0 ? this.DIRS.CW : this.DIRS.CCW;
			switch(Math.floor(Math.random()*6)){
				case 0:
					this.rotateF(dir, true);
					break;
				case 1:
					this.rotateB(dir, true);
					break;
				case 2:
					this.rotateL(dir, true);
					break;
				case 3:
					this.rotateR(dir, true);
					break;
				case 4:
					this.rotateU(dir, true);
					break;
				case 5:
					this.rotateD(dir, true);
					break;
			}
		}
		if(timerSetting.isOn) timer.reset();
		this.setDepth(1);
		this.drawCube();
		this.wasScrambled = true;
		ga('send', 'event', 'cube'+this.size, 'scrambled');
	},
	isSolved: function(){
		for(var i = 0; i < this.size; i++){
			for(var j = 0; j < this.size; j++){
				for(var k = 0; k < this.SIDE_NAMES.length; k++){
					if(this[this.SIDE_NAMES[k]][i][j] != this[this.SIDE_NAMES[k]][0][0]) return false;
				}
			}
		}
		return true;
	}
};

cube.setSize(5);


text:
using System.IO;
using System.Text;
using Dune.Utility;

namespace Dune.Packets.Impl
{
    public class TusUserAreaWriteRequestHeader : PacketBase
    {
        public override PacketType Type
        {
            get { return PacketType.TusUserAreaWriteRequestHeader; }
        }

        public int DataLength { get; set; }
        public string User { get; set; }

        public override void ParsePayload(byte[] payload)
        {
            var reader = new BigEndianBinaryReader(new MemoryStream(payload));
            ushort dataLength = reader.ReadUInt16();
            User = Encoding.ASCII.GetString(reader.ReadBytes(dataLength));
        }

        protected override byte[] SerializePayload()
        {
            byte[] user = Encoding.ASCII.GetBytes(User);
            byte[] payload = new byte[sizeof(int) + sizeof(ushort) + user.Length];
            var writer = new BigEndianBinaryWriter(new MemoryStream(payload));

            writer.Write(DataLength);
            writer.Write((ushort)user.Length);
            writer.Write(user);

            return payload;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/transparent_red">

    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        android:layout_margin="@dimen/spacing_small"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/logTypeIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginStart="@dimen/spacing_small"
        android:layout_marginTop="@dimen/spacing_very_small"
        app:layout_constraintBottom_toTopOf="@+id/geocacheName"
        app:layout_constraintStart_toEndOf="@+id/checkbox"
        app:layout_constraintTop_toTopOf="parent"
        tools:src="@drawable/ic_found"
        tools:tint="@color/green" />

    <TextView
        android:id="@+id/logType"
        style="@style/Text.Primary.Small"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        android:layout_marginStart="@dimen/spacing_very_small"
        app:layout_constraintBottom_toTopOf="@+id/geocacheName"
        app:layout_constraintStart_toEndOf="@+id/logTypeIcon"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="@string/found" />

    <TextView
        android:id="@+id/logDate"
        style="@style/Text.Primary.VerySmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/spacing_very_small"
        app:layout_constraintBottom_toBottomOf="@+id/logType"
        app:layout_constraintStart_toEndOf="@+id/logType"
        app:layout_constraintTop_toTopOf="@+id/logType"
        tools:text="2017-06-12" />

    <TextView
        android:id="@+id/logTime"
        style="@style/Text.Secondary.Tiny"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_marginStart="@dimen/spacing_very_small"
        app:layout_constraintBottom_toBottomOf="@+id/logDate"
        app:layout_constraintStart_toEndOf="@+id/logDate"
        app:layout_constraintTop_toTopOf="@+id/logDate"
        tools:text="16:28" />

    <ImageView
        android:id="@+id/recommendationIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginStart="@dimen/spacing_very_small"
        android:src="@drawable/ic_star"
        android:tint="@color/darkGreen"
        app:layout_constraintBottom_toBottomOf="@+id/logTime"
        app:layout_constraintStart_toEndOf="@+id/logTime"
        app:layout_constraintTop_toTopOf="@+id/logTime"/>

    <ImageView
        android:id="@+id/passwordIcon"
        android:layout_width="18dp"
        android:layout_height="18dp"
        android:layout_marginEnd="@dimen/spacing_small"
        android:src="@drawable/ic_password_lock"
        android:tint="@color/gray_hint"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/rateIcon"
        app:layout_constraintBottom_toTopOf="@+id/geocacheName" />

    <ImageView
        android:id="@+id/rateIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="@dimen/spacing_small"
        android:src="@drawable/ic_face"
        android:tint="@color/gray_hint"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/commentIcon"
        app:layout_constraintBottom_toTopOf="@+id/geocacheName" />

    <ImageView
        android:id="@+id/commentIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="@dimen/spacing_small"
        android:src="@drawable/ic_comment"
        android:tint="@color/gray_hint"
        android:layout_marginTop="@dimen/spacing_very_small"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/moreIcon"
        app:layout_constraintBottom_toTopOf="@+id/geocacheName"/>

    <TextView
        android:id="@+id/geocacheName"
        style="@style/Text.Primary.Small"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:layout_marginEnd="@dimen/spacing_small"
        android:layout_marginTop="@dimen/spacing_very_small"
        app:layout_constraintBottom_toTopOf="@+id/separator"
        app:layout_constraintStart_toStartOf="@+id/logDate"
        app:layout_constraintTop_toBottomOf="@+id/logTypeIcon"
        app:layout_constraintEnd_toStartOf="@+id/moreIcon"
        tools:text="Krosno Airport" />

    <ImageView
        android:id="@+id/moreIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/spacing_small"
        android:src="@drawable/ic_more"
        android:tint="@color/colorPrimaryDark"
        android:layout_marginEnd="@dimen/spacing_small"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <View
        android:id="@+id/separator"
        android:layout_width="0dp"
        android:layout_height="1dp"
        android:background="@color/accent_gray"
        android:layout_marginTop="@dimen/spacing_very_small"
        app:layout_constraintTop_toBottomOf="@+id/geocacheName"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/geocacheName"/>

</android.support.constraint.ConstraintLayout>


text:
The code for my website. It's written in Haskell using Alexander Thiemann's [Spock](https://github.com/agrafix/Spock). It was originally based off of the [funblog](https://github.com/agrafix/funblog) project. Shout out to Michael Snoyman for Hamlet and Persistent.

### License

♬ Don't know much about li-cen-sing ♬

(So I'm just leaving this here. Use the code however you want. Or don't. I don't care. Go away.)

Released under the Apache-2.0 license.


text:
module TDev { export module RT {
    //? A device on the home network
    //@ stem("dev") immutable walltap cap(home) obsolete
    export class Device
        extends RTValue
    {
        private _name : string = undefined;

        constructor() {
            super()
        }

        //? Gets the friendly name of the device
        //@ obsolete
        public name() : string { return this._name; }

        //? Sets the friendly name of the device
        //@ obsolete
        public set_name(name:string) : void { this._name = name; }

        //? Gets the manfacturer name
        //@ stub obsolete
        public manufacturer() : string
        { return undefined; }

        //? Browses to the device control panel
        //@ stub obsolete
        public browse() : void
        { }

        //? Display the device to the wall
        //@ stub obsolete
        public post_to_wall() : void
        { }

        //? Checks if the device is connected
        //@ stub obsolete
        //@ tandre
        public is_connected() : boolean
        { return undefined; }

    }
} }


text:
package core

import (
	"fmt"
	"github.com/bmizerany/assert"
	"testing"
)

func TestUrlGeneration(t *testing.T) {
	expectedUrl := "/Index/Type/Id?op_type=create&parent=Parent&percolate=Percolate&refresh=true&routing=Routing&timeout=Timeout&timestamp=TimeStamp&ttl=10&version=1"
	url, err := GetIndexUrl("Index", "Type", "Id", "Parent", 1, "create", "Routing", "TimeStamp", 10, "Percolate", "Timeout", true)
	assert.T(t, err == nil, t, "err was not nil")
	assert.T(t, url == expectedUrl, fmt.Sprintf("TestUrlGeneration Should get %s, instead got %s", expectedUrl, url))
}

func TestUrlGenerationNoIndex(t *testing.T) {
	_, err := GetIndexUrl("", "Type", "Id", "Parent", 1, "create", "Routing", "TimeStamp", 10, "Percolate", "Timeout", true)
	assert.T(t, err != nil, "err should have been returned")
}

func TestUrlGenerationNoType(t *testing.T) {
	_, err := GetIndexUrl("Index", "", "Id", "Parent", 1, "create", "Routing", "TimeStamp", 10, "Percolate", "Timeout", true)
	assert.T(t, err != nil, "err should have been returned")
}

func TestUrlGenerationNoId(t *testing.T) {
	expectedUrl := "/Index/Type?op_type=create&parent=Parent&percolate=Percolate&refresh=true&routing=Routing&timeout=Timeout&timestamp=TimeStamp&ttl=10&version=1"
	url, err := GetIndexUrl("Index", "Type", "", "Parent", 1, "create", "Routing", "TimeStamp", 10, "Percolate", "Timeout", true)
	assert.T(t, err == nil, t, "err was not nil")
	assert.T(t, url == expectedUrl, t, fmt.Sprintf("TestUrlGenerationNoId Should get %s, instead got %s", expectedUrl, url))
}

// if Id is blank, op_type should default to create
func TestUrlGenerationNoIdAndOpTypeNotCreate(t *testing.T) {
	expectedUrl := "/Index/Type?op_type=create&parent=Parent&percolate=Percolate&refresh=true&routing=Routing&timeout=Timeout&timestamp=TimeStamp&ttl=10&version=1"
	url, err := GetIndexUrl("Index", "Type", "", "Parent", 1, "notcreate", "Routing", "TimeStamp", 10, "Percolate", "Timeout", true)
	assert.T(t, err == nil, "err was not nil")
	assert.T(t, url == expectedUrl,
		fmt.Sprintf("TestUrlGenerationNoId Should get %s, instead got %s", expectedUrl, url))
}

func TestUrlGenerationNoParent(t *testing.T) {
	expectedUrl := "/Index/Type/Id?op_type=create&percolate=Percolate&refresh=true&routing=Routing&timeout=Timeout&timestamp=TimeStamp&ttl=10&version=1"
	url, err := GetIndexUrl("Index", "Type", "Id", "", 1, "create", "Routing", "TimeStamp", 10, "Percolate", "Timeout", true)
	assert.T(t, err == nil, "err was not nil")
	assert.T(t, url == expectedUrl,
		fmt.Sprintf("TestUrlGenerationNoParent Should get %s, instead got %s", expectedUrl, url))
}

func TestUrlGenerationNoVersion(t *testing.T) {
	expectedUrl := "/Index/Type/Id?op_type=create&parent=Parent&percolate=Percolate&refresh=true&routing=Routing&timeout=Timeout&timestamp=TimeStamp&ttl=10"
	url, err := GetIndexUrl("Index", "Type", "Id", "Parent", 0, "create", "Routing", "TimeStamp", 10, "Percolate", "Timeout", true)
	assert.T(t, err == nil, "err was not nil")
	assert.T(t, url == expectedUrl,
		fmt.Sprintf("TestUrlGenerationNoVersion Should get %s, instead got %s", expectedUrl, url))
}

func TestUrlGenerationNoOpType(t *testing.T) {
	expectedUrl := "/Index/Type/Id?parent=Parent&percolate=Percolate&refresh=true&routing=Routing&timeout=Timeout&timestamp=TimeStamp&ttl=10&version=1"
	url, err := GetIndexUrl("Index", "Type", "Id", "Parent", 1, "", "Routing", "TimeStamp", 10, "Percolate", "Timeout", true)
	assert.T(t, err == nil, "err was not nil")
	assert.T(t, url == expectedUrl,
		fmt.Sprintf("TestUrlGenerationNoOpType Should get %s, instead got %s", expectedUrl, url))
}
func TestUrlGenerationNoRouting(t *testing.T) {
	expectedUrl := "/Index/Type/Id?op_type=create&parent=Parent&percolate=Percolate&refresh=true&timeout=Timeout&timestamp=TimeStamp&ttl=10&version=1"
	url, err := GetIndexUrl("Index", "Type", "Id", "Parent", 1, "create", "", "TimeStamp", 10, "Percolate", "Timeout", true)
	assert.T(t, err == nil, t, "err was not nil")
	assert.T(t, url == expectedUrl,
		fmt.Sprintf("TestUrlGenerationNoRouting Should get %s, instead got %s", expectedUrl, url))
}
func TestUrlGenerationNoTimestamp(t *testing.T) {
	expectedUrl := "/Index/Type/Id?op_type=create&parent=Parent&percolate=Percolate&refresh=true&routing=Routing&timeout=Timeout&ttl=10&version=1"
	url, err := GetIndexUrl("Index", "Type", "Id", "Parent", 1, "create", "Routing", "", 10, "Percolate", "Timeout", true)
	assert.T(t, err == nil, t, "err was not nil")
	assert.T(t, url == expectedUrl,
		fmt.Sprintf("TestUrlGenerationNoTimestamp Should get %s, instead got %s", expectedUrl, url))
}
func TestUrlGenerationNoTTL(t *testing.T) {
	expectedUrl := "/Index/Type/Id?op_type=create&parent=Parent&percolate=Percolate&refresh=true&routing=Routing&timeout=Timeout&timestamp=TimeStamp&version=1"
	url, err := GetIndexUrl("Index", "Type", "Id", "Parent", 1, "create", "Routing", "TimeStamp", 0, "Percolate", "Timeout", true)
	assert.T(t, err == nil, t, "err was not nil")
	assert.T(t, url == expectedUrl,
		fmt.Sprintf("TestUrlGenerationNoTTL Should get %s, instead got %s", expectedUrl, url))
}
func TestUrlGenerationNoPercolate(t *testing.T) {
	expectedUrl := "/Index/Type/Id?op_type=create&parent=Parent&refresh=true&routing=Routing&timeout=Timeout&timestamp=TimeStamp&ttl=10&version=1"
	url, err := GetIndexUrl("Index", "Type", "Id", "Parent", 1, "create", "Routing", "TimeStamp", 10, "", "Timeout", true)
	assert.T(t, err == nil, t, "err was not nil")
	assert.T(t, url == expectedUrl,
		fmt.Sprintf("TestUrlGenerationNoPercolate Should get %s, instead got %s", expectedUrl, url))
}
func TestUrlGenerationNoTimeout(t *testing.T) {
	expectedUrl := "/Index/Type/Id?op_type=create&parent=Parent&percolate=Percolate&refresh=true&routing=Routing&timestamp=TimeStamp&ttl=10&version=1"
	url, err := GetIndexUrl("Index", "Type", "Id", "Parent", 1, "create", "Routing", "TimeStamp", 10, "Percolate", "", true)
	assert.T(t, err == nil, t, "err was not nil")
	assert.T(t, url == expectedUrl,
		fmt.Sprintf("TestUrlGenerationNoTimeout Should get %s, instead got %s", expectedUrl, url))
}
func TestUrlGenerationNoRefresh(t *testing.T) {
	expectedUrl := "/Index/Type/Id?op_type=create&parent=Parent&percolate=Percolate&routing=Routing&timeout=Timeout&timestamp=TimeStamp&ttl=10&version=1"
	url, err := GetIndexUrl("Index", "Type", "Id", "Parent", 1, "create", "Routing", "TimeStamp", 10, "Percolate", "Timeout", false)
	assert.T(t, err == nil, t, "err was not nil")
	assert.T(t, url == expectedUrl,
		fmt.Sprintf("TestUrlGenerationNoRefresh Should get %s, instead got %s", expectedUrl, url))
}


text:
import EditorComponent from 'components/editors/editor';
import QuillComponent from 'components/editors/html';
import CodeMirrorComponent from 'components/editors/markdown';
import ShortTextEditorComponent from 'components/editors/short_text';
import TextEditorComponent from 'components/editors/text';
import * as API from 'lib/api';
import * as React from 'react';

interface ContentEditor {
  shouldRender(content: API.Content): boolean;
  render(content: API.Content, ref: React.RefObject<any>): React.ReactElement<any>;
}

const LongHTMLEditor: ContentEditor = {
  shouldRender: (content: API.Content) => content.text != null && content.text.type == 'html',
  render: (content: API.Content, ref: React.RefObject<any>) => (
    <EditorComponent ref={ref} content={content} />
  ),
};

const LongMarkdownEditor: ContentEditor = {
  shouldRender: (content: API.Content) => content.text != null && content.text.type == 'markdown',
  render: (content: API.Content, ref: React.RefObject<any>) => (
    <CodeMirrorComponent ref={ref} content={content} />
  ),
};

const LongTextEditor: ContentEditor = {
  shouldRender: (content: API.Content) => content.text != null && content.text.type == 'text',
  render: (content: API.Content, ref: React.RefObject<any>) => (
    <TextEditorComponent ref={ref} content={content} />
  ),
};

const ShortTextEditor: ContentEditor = {
  shouldRender: (content: API.Content) =>
    content.short != null && (content.short.type == 'text' || content.short.type == 'markdown'),
  render: (content: API.Content, ref: React.RefObject<any>) => (
    <ShortTextEditorComponent ref={ref} content={content} />
  ),
};

const ShortHTMLEditor: ContentEditor = {
  shouldRender: (content: API.Content) => content.short != null && content.short.type == 'html',
  render: (content: API.Content, ref: React.RefObject<any>) => (
    <QuillComponent ref={ref} content={content} />
  ),
};

const editors: ContentEditor[] = [
  LongHTMLEditor,
  LongMarkdownEditor,
  LongTextEditor,
  ShortHTMLEditor,
  ShortTextEditor,
];

interface Props {
  content: API.Content | API.Data;
  hideLabel: boolean;
}

const imageExtensions = ['png', 'jpg', 'jpeg', 'gif'];

export class Editor extends React.PureComponent<Props> {
  editorRef: React.RefObject<any>;

  constructor(props: Props) {
    super(props);
    this.editorRef = React.createRef();
  }

  insertFile(filename: string, url: string) {
    const editor = this.editorRef.current;
    let isImage = imageExtensions.some((v) => filename.substr(-v.length) == v);
    if (isImage) {
      if (editor.insertImage) {
        editor.insertImage(url);
      }
    } else if (editor.insertText) {
      editor.insertText(filename, url);
    }
  }

  render() {
    for (var i = 0; i < editors.length; i++) {
      let editor = editors[i];
      if (editor.shouldRender(this.props.content)) {
        return (

              {this.props.hideLabel ? '' :
{this.props.content.key}
}
              {editor.render(this.props.content, this.editorRef)}

        );
      }
    }
  }
}


text:
search:
   keywords: ['java', 'odatabasedocument', 'isactiveoncurrentthread']
---

# ODatabaseDocument - isActiveOnCurrentThread()

Determines whether the current database is active on the current thread.

## Database Thread

Using this method you can determine whether the current database is active on the current thread in your application.

### Syntax

```
boolean ODatabaseDocument().isActiveOnCurrentThread()
```

#### Return Value

This method returns a `boolean` value indicating whether the current database is active on the current thread.


text:
layout: post
title: "You're fired. Enjoy your summer."
date: 2015-06-20 14:00:00
categories: post
tags: academia management
image: /assets/article_images/summer.jpg

---

Interesting post on the institutional tensions between management and academia. I particularly related to the Heroic model - one based on the individual at the expense of the collective. This quote on the way the current system works:

>diverts resources from collective effort to the Heroic model.

No: let's treat them as isolated demigods, masters of their own fates, regardless of local or wider conditions: educational, financial or emotional.

Source: [You're fired. Enjoy your summer.](http://plashingvole.blogspot.co.uk/2015/06/youre-fired-enjoy-your-summer.html)


text:
/**
 * Manage doors.
 */
function DoorSystem() {
  System.call(this, Position, Door);
}

__extend(DoorSystem, System, {
  a: function onEntityAdded(entity) {
    var position = entity.g(Position);
    AStar.w(position.x / 16 | 0, position.y / 16 | 0, true);
  },
  r: function onEntityRemoved(entity) {
    var position = entity.g(Position);
    AStar.w(position.x / 16 | 0, position.y / 16 | 0, false);
  }
});


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>de.hopmann.msc</groupId>
		<artifactId>repositories</artifactId>
		<version>1.0.0</version>
	</parent>
	<artifactId>repo-commons</artifactId>
	<packaging>jar</packaging>

	<dependencies>

	</dependencies>

	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>


text:
<?php

	namespace apf\iface\acl\os{

		interface User{

			public static function instance($val,$parameters=NULL);
			public static function getCurrent();
			public function isRoot();
			public function setUID($uid);
			public function getGroup();
			public function getGroups($parameters=NULL);

		}

	}


text:
from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)

    def __unicode__(self):
        return u"Q: %s " % self.question

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)

    def __unicode__(self):
        return u"Choice: %s in poll %s" % (self.choice, self.poll)

__test__ = {'API_TESTS':"""
# Regression test for the use of None as a query value. None is interpreted as
# an SQL NULL, but only in __exact queries.
# Set up some initial polls and choices
>>> p1 = Poll(question='Why?')
>>> p1.save()
>>> c1 = Choice(poll=p1, choice='Because.')
>>> c1.save()
>>> c2 = Choice(poll=p1, choice='Why Not?')
>>> c2.save()

# Exact query with value None returns nothing ("is NULL" in sql, but every 'id'
# field has a value).
>>> Choice.objects.filter(choice__exact=None)
[]

Excluding the previous result returns everything.
>>> Choice.objects.exclude(choice=None).order_by('id')
[<Choice: Choice: Because. in poll Q: Why? >, <Choice: Choice: Why Not? in poll Q: Why? >]

# Valid query, but fails because foo isn't a keyword
>>> Choice.objects.filter(foo__exact=None)
Traceback (most recent call last):
...
FieldError: Cannot resolve keyword 'foo' into field. Choices are: choice, id, poll

# Can't use None on anything other than __exact
>>> Choice.objects.filter(id__gt=None)
Traceback (most recent call last):
...
ValueError: Cannot use None as a query value

# Can't use None on anything other than __exact
>>> Choice.objects.filter(foo__gt=None)
Traceback (most recent call last):
...
ValueError: Cannot use None as a query value

# Related managers use __exact=None implicitly if the object hasn't been saved.
>>> p2 = Poll(question="How?")
>>> p2.choice_set.all()
[]

"""}


text:
'use strict';

angular.module('sbAdminApp')
.controller('HeaderCtrl', ['UserService', '$auth', '$rootScope', '$scope', '$state', '$translate', 'ngDialog', 'toaster', function(UserService, $auth, $rootScope, $scope, $state, $translate, ngDialog, toaster) {
	var vm = this;

	vm.changePassword = changePassword;
	vm.prepareChangePassword = prepareChangePassword;
	vm.showPolicy = showPolicy;
	vm.logout = logout;
	vm.init = init;

	vm.init();

	function prepareChangePassword(user) {
		this.password = {};
		this.password_error = false;

		vm.changePasswordDialog = ngDialog.open({
			template: 'change-password-dialog',
			scope: $scope
		});
	}

	function showPolicy() {
		vm.showPolicyDialog = ngDialog.open({
			template: 'policyDialog',
			showClose: false,
			scope: $scope
		});
	}

	function validate(form) {
		if(!form.$valid) return false;

		if (form.newPassword.$modelValue != form.confirmPassword.$modelValue){
			vm.password_error = true;
			return false;
		}

		return true;
	}

	function changePassword(form) {
		if (validate(form)) {
			UserService.changePassword(vm.password).$promise.then(function(response) {
				vm.changePasswordDialog.close();
				toaster.pop('success', 'Senha alterada com sucesso.');
			}, function(err) {
				toaster.pop('error', $translate.instant(err.data ? err.data : err.status));
			});
		}
	}

	function logout() {
		$auth.removeToken();
		delete $rootScope.user;
		$state.go('login');
	};

	function init(){
		vm.user = $rootScope.user;
	}
}]);


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Acta Phytopath. 9: 354 (1974)

#### Original name
Annelloconidiaceae Vörös & Léránth

### Remarks
null


text:
package org.elasticsearch.license;

import org.elasticsearch.action.Action;

public class GetBasicStatusAction extends Action<GetBasicStatusResponse> {

    public static final GetBasicStatusAction INSTANCE = new GetBasicStatusAction();
    public static final String NAME = "cluster:admin/xpack/license/basic_status";

    private GetBasicStatusAction() {
        super(NAME);
    }

    @Override
    public GetBasicStatusResponse newResponse() {
        return new GetBasicStatusResponse();
    }
}


text:
"{{include.quote}}"

        {% include rio-image.html src=include.author-image-src alt=include.author-name class="casestudy__author-image"%}
				{{include.author-name}}
				{{include.author-job-title}}


text:
<?php

namespace App;

use App\Library\Traits\CurrentUserModel;
use Illuminate\Http\Request;
use Illuminate\Notifications\Notifiable;
use Caffeinated\Shinobi\Traits\ShinobiTrait;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use App\Notifications\SentEmailLink as ResetPasswordNotification;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Notifiable, Authenticatable, CanResetPassword, ShinobiTrait, CurrentUserModel;

    /**
     * Type of relations
     *
     * @var string
     */
    const TYPE = 'App\User';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'surname', 'patronymic', 'email', 'password', 'image_id',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * Users can have many roles.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany('\App\Role')->withTimestamps();
    }

    /**
     * Send the password reset notification.
     *
     * @param  string $token
     * @return void
     */
    public function sendPasswordResetNotification($token)
    {
        $this->notify(new ResetPasswordNotification($token));
    }

    /**
     * Get all of the field's.
     */
    public function fields()
    {
        return $this->morphMany('App\Field', 'accessory');
    }

    /**
     * Get all of the requisite's.
     */
    public function requisites()
    {
        return $this->morphMany('App\Requisite', 'relation');
    }

    /**
     * Get all of the requisite's.
     */
    public function oversees()
    {
        return $this->hasMany('App\Client', 'curator', 'id');
    }

    public function subdivisions()
    {
        return $this->hasMany('App\Subdivision', 'id', 'responsible');
    }

    public function stock()
    {
        return $this->hasMany('App\Stock', 'id', 'responsible');
    }

    public function photos()
    {
        return $this->morphMany('App\Image', 'imageable');
    }

    public function image()
    {
        return $this->hasOne('App\Image', 'id', 'image_id');
    }

    public function trades()
    {
        return $this->hasMany('App\Trade', 'id', 'client_id');
    }

    public function completedTrades()
    {
        return $this->hasMany('App\Trade', 'id', 'completed_by_user');
    }

    public function createImage(Request $request, $updateImage = true)
    {
        if (!$request->hasFile('user_image'))
            return false;

        $file = $request->file('user_image');
        $destinationPath = base_path() . '/public/upload/images/';
        $image_name = time() . "_" . $this->table . "_" . $file->getClientOriginalName();
        $userPhoto = $file->move($destinationPath, $image_name);

        $image = Image::create([
            'name' => 'User Image',
            'src' => $image_name,
            'alt' => 'User Image',
            'imageable_id' => $this->id,
            'imageable_type' => self::TYPE,
        ]);

        if ($image instanceof Image) {
            if ($updateImage)
                $this->updateProfileImage($image);
            return true;
        } else {
            unlink($userPhoto->getPath());
            return false;
        }
    }

    public function findAllImages()
    {
        return Image::where('imageable_id', $this->id)->where('imageable_type',self::TYPE)->orderBy('created_at', 'desc')->get();
    }

    /**
     * Is current user
     *
     * @return bool
     */
    public function is_current()
    {
        if ($this->getCurrentUser()->id == $this->id)
            return true;
        return false;
    }

    /**
     * User full name
     *
     * @return string
     */
    public function getFullName()
    {
        return $this->surname . ' ' . $this->name . ' ' . $this->patronymic;
    }

    /**
     * Get current user with all relations or Auth::user()
     */
    public static function getCurrentWithAllRealtionsOrAuthUser()
    {
        $user = \Auth::user();
        $uAllR = self::whereId($user->id)->with([
            'requisites',
            'oversees',
            'subdivisions',
            'stock',
            'photos',
            'image',
            'trades',
            'completedTrades'
        ])->firstOrFail();
        if($uAllR instanceof User)
            return $uAllR;
        return $user;
    }

    /**
     * Update Profile photo
     *
     * @param bool $updateImage
     * @param Image $image
     * @return bool
     */
    public function updateProfileImage(Image $image, $updateImage = true)
    {
        if($this->image_id != $image->id){
            $this->image_id = $image->id;
            if ($this->save()){
                if($this->is_current()){
                    \Session::put('current.image', $image->src);
                    \Session::remove('current.user');
                }
                return true;
            }
        }else {
            if($this->is_current()){
                \Session::put('current.image', $image->src);
                \Session::remove('current.user');
            }
            return true;
        }
        return false;
    }

    public function createRequisite(Request $request)
    {
        $requisite = $this->requisites()->create([
            'relation_id'   => $this->id,
            'relation_type' => self::TYPE,
            'legal_name'    => $request->get('legal_name'),
            'bank'          => $request->get('bank'),
            'iik'           => $request->get('iik'),
            'iin'           => $request->get('iin'),
            'bin'           => $request->get('bin'),
            'cbe'           => $request->get('cbe'),
        ]);
        if ($requisite instanceof Requisite)
            return $requisite;
        return false;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <FrameLayout
        android:id="@+id/container"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="0dp"/>

    <RadioGroup
        android:id="@+id/group"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="50dp">
        <RadioButton
            android:id="@+id/common"
            android:text="Common"
            android:button="@null"
            android:gravity="center"
            android:textColor="@color/white"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent"/>

        <RadioButton
            android:id="@+id/translucent"
            android:text="Translucent"
            android:button="@null"
            android:textColor="@color/white"
            android:gravity="center"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent"/>

        <RadioButton
            android:id="@+id/coordinator"
            android:text="Coordinator"
            android:button="@null"
            android:textColor="@color/white"
            android:gravity="center"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent"/>

        <RadioButton
            android:id="@+id/collapsing_toolbar"
            android:text="Collapsing\nToolbar"
            android:button="@null"
            android:textColor="@color/white"
            android:gravity="center"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent"/>
    </RadioGroup>
</LinearLayout>


text:
package org.apache.shardingsphere.database.protocol.mysql.packet.binlog.row;

import org.apache.shardingsphere.database.protocol.mysql.constant.MySQLBinlogEventType;
import org.apache.shardingsphere.database.protocol.mysql.packet.binlog.AbstractMySQLBinlogEventPacket;
import org.apache.shardingsphere.database.protocol.mysql.packet.binlog.MySQLBinlogEventHeader;
import org.apache.shardingsphere.database.protocol.mysql.packet.binlog.row.column.MySQLBinlogColumnDef;
import org.apache.shardingsphere.database.protocol.mysql.packet.binlog.row.column.value.MySQLBinlogProtocolValueFactory;
import org.apache.shardingsphere.database.protocol.mysql.packet.command.query.binary.execute.MySQLNullBitmap;
import org.apache.shardingsphere.database.protocol.mysql.payload.MySQLPacketPayload;
import lombok.Getter;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

/**
 * MySQL binlog rows event packet.
 *
 * @see ROWS_EVENT
 */
@Getter
public final class MySQLBinlogRowsEventPacket extends AbstractMySQLBinlogEventPacket {

    private final long tableId;

    private final int flags;

    private final int columnNumber;

    private final MySQLNullBitmap columnsPresentBitmap;

    private final MySQLNullBitmap columnsPresentBitmap2;

    private final List<Serializable[]> rows = new LinkedList<>();

    private final List<Serializable[]> rows2 = new LinkedList<>();

    public MySQLBinlogRowsEventPacket(final MySQLBinlogEventHeader binlogEventHeader, final MySQLPacketPayload payload) {
        super(binlogEventHeader);
        tableId = payload.readInt6();
        flags = payload.readInt2();
        skipExtraData(payload);
        columnNumber = (int) payload.readIntLenenc();
        columnsPresentBitmap = new MySQLNullBitmap(columnNumber, payload);
        columnsPresentBitmap2 = readUpdateColumnsPresentBitmap(payload);
    }

    private void skipExtraData(final MySQLPacketPayload payload) {
        if (isRowsEventVersion2(getBinlogEventHeader().getEventType())) {
            int extraDataLength = payload.readInt2() - 2;
            payload.skipReserved(extraDataLength);
        }
    }

    private boolean isRowsEventVersion2(final int eventType) {
        return MySQLBinlogEventType.WRITE_ROWS_EVENTv2.getValue() == eventType || MySQLBinlogEventType.UPDATE_ROWS_EVENTv2.getValue() == eventType
            || MySQLBinlogEventType.DELETE_ROWS_EVENTv2.getValue() == eventType;
    }

    private MySQLNullBitmap readUpdateColumnsPresentBitmap(final MySQLPacketPayload payload) {
        return isUpdateRowsEvent(getBinlogEventHeader().getEventType()) ? new MySQLNullBitmap(columnNumber, payload) : null;
    }

    private boolean isUpdateRowsEvent(final int eventType) {
        return MySQLBinlogEventType.UPDATE_ROWS_EVENTv2.getValue() == eventType || MySQLBinlogEventType.UPDATE_ROWS_EVENTv1.getValue() == eventType;
    }

    /**
     * Read rows in binlog.
     *
     * @param tableMapEventPacket TABLE_MAP_EVENT packet before this ROWS_EVENT
     * @param payload ROWS_EVENT packet payload
     */
    public void readRows(final MySQLBinlogTableMapEventPacket tableMapEventPacket, final MySQLPacketPayload payload) {
        List<MySQLBinlogColumnDef> columnDefs = tableMapEventPacket.getColumnDefs();
        while (hasNextRow(payload)) {
            rows.add(readRow(columnDefs, payload));
            if (isUpdateRowsEvent(getBinlogEventHeader().getEventType())) {
                rows2.add(readRow(columnDefs, payload));
            }
        }
    }

    private boolean hasNextRow(final MySQLPacketPayload payload) {
        return payload.getByteBuf().isReadable();
    }

    private Serializable[] readRow(final List<MySQLBinlogColumnDef> columnDefs, final MySQLPacketPayload payload) {
        MySQLNullBitmap nullBitmap = new MySQLNullBitmap(columnNumber, payload);
        Serializable[] result = new Serializable[columnNumber];
        for (int i = 0; i < columnNumber; i++) {
            MySQLBinlogColumnDef columnDef = columnDefs.get(i);
            result[i] = nullBitmap.isNullParameter(i) ? null : MySQLBinlogProtocolValueFactory.getBinlogProtocolValue(columnDef.getColumnType()).read(columnDef, payload);
        }
        return result;
    }

    @Override
    protected void writeEvent(final MySQLPacketPayload payload) {
        // TODO
    }
}


text:
namespace FIX40
{

  class QuoteRequest : public Message
  {
  public:
    QuoteRequest() : Message(MsgType()) {}
    QuoteRequest(const FIX::Message& m) : Message(m) {}
    QuoteRequest(const Message& m) : Message(m) {}
    QuoteRequest(const QuoteRequest& m) : Message(m) {}
    static FIX::MsgType MsgType() { return FIX::MsgType("R"); }

    QuoteRequest(
      const FIX::QuoteReqID& aQuoteReqID,
      const FIX::Symbol& aSymbol )
    : Message(MsgType())
    {
      set(aQuoteReqID);
      set(aSymbol);
    }

    FIELD_SET(*this, FIX::QuoteReqID);
    FIELD_SET(*this, FIX::Symbol);
    FIELD_SET(*this, FIX::SymbolSfx);
    FIELD_SET(*this, FIX::SecurityID);
    FIELD_SET(*this, FIX::IDSource);
    FIELD_SET(*this, FIX::Issuer);
    FIELD_SET(*this, FIX::SecurityDesc);
    FIELD_SET(*this, FIX::PrevClosePx);
    FIELD_SET(*this, FIX::Side);
    FIELD_SET(*this, FIX::OrderQty);
  };

}

#endif


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

namespace Hyperion.Core.IDAL
{
    using Poseidon.Base.Framework;
    using Hyperion.Core.DL;

    /// <summary>
    /// 设备状态数据访问接口
    /// </summary>
    internal interface IEquipmentStateRepository : IBaseDAL<EquipmentState, long>
    {
    }
}


text:
import {Observable} from '../../Observable';
import {switchMapTo} from '../../operator/switchMapTo';
Observable.prototype.switchMapTo = switchMapTo;

export var _void: void;


text:
const camelCase = require('camelcase');
const path = require('path');
const webpack = require('webpack');
const pkg = require(path.join(process.cwd(), 'package.json'));
const shouldMininimize = process.argv.indexOf('--min') !== -1;
var HtmlWebpackPlugin = require('html-webpack-plugin');

const standardConfig = {
  devtool: 'source-map',
  entry: './src/index.js',
    output: {
      path: './dist',
      filename: 'index.js'
    },
  module: {
    noParse: /node_modules\/knockout\/build\/output\/*.js/,
    loaders: [{
      test: /\.scss$/,
      loaders: ['style', 'css', 'sass']
    }, {
      test: /\.html$/,
      loader: 'html'
    }, {
      test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
      loader: 'file'
    }, {
      test: /\.js$/,
      loader: 'babel',
      query: {
        presets: ['babel-preset-es2015']
      }
    }]
  },
  devServer: {
    port: 8000,
    contentBase: 'src/',
    inline: true
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: 'src/index.html',
      hash:true,
      inject: false
    }),
    new webpack.optimize.UglifyJsPlugin({
      include: /\.min\.js$/,
      minimize: true
    })
  ]
};

if (shouldMininimize) {
  Object.assign(standardConfig.entry, {
    'dist/index.min.js': './src/index.js'
  });
}

module.exports = standardConfig;


text:
#include <aws/elasticache/model/ModifyReplicationGroupRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::ElastiCache::Model;
using namespace Aws::Utils;

ModifyReplicationGroupRequest::ModifyReplicationGroupRequest() :
    m_replicationGroupIdHasBeenSet(false),
    m_replicationGroupDescriptionHasBeenSet(false),
    m_primaryClusterIdHasBeenSet(false),
    m_snapshottingClusterIdHasBeenSet(false),
    m_automaticFailoverEnabled(false),
    m_automaticFailoverEnabledHasBeenSet(false),
    m_cacheSecurityGroupNamesHasBeenSet(false),
    m_securityGroupIdsHasBeenSet(false),
    m_preferredMaintenanceWindowHasBeenSet(false),
    m_notificationTopicArnHasBeenSet(false),
    m_cacheParameterGroupNameHasBeenSet(false),
    m_notificationTopicStatusHasBeenSet(false),
    m_applyImmediately(false),
    m_applyImmediatelyHasBeenSet(false),
    m_engineVersionHasBeenSet(false),
    m_autoMinorVersionUpgrade(false),
    m_autoMinorVersionUpgradeHasBeenSet(false),
    m_snapshotRetentionLimit(0),
    m_snapshotRetentionLimitHasBeenSet(false),
    m_snapshotWindowHasBeenSet(false)
{
}

Aws::String ModifyReplicationGroupRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=ModifyReplicationGroup&";
  if(m_replicationGroupIdHasBeenSet)
  {
    ss << "ReplicationGroupId=" << StringUtils::URLEncode(m_replicationGroupId.c_str()) << "&";
  }
  if(m_replicationGroupDescriptionHasBeenSet)
  {
    ss << "ReplicationGroupDescription=" << StringUtils::URLEncode(m_replicationGroupDescription.c_str()) << "&";
  }
  if(m_primaryClusterIdHasBeenSet)
  {
    ss << "PrimaryClusterId=" << StringUtils::URLEncode(m_primaryClusterId.c_str()) << "&";
  }
  if(m_snapshottingClusterIdHasBeenSet)
  {
    ss << "SnapshottingClusterId=" << StringUtils::URLEncode(m_snapshottingClusterId.c_str()) << "&";
  }
  if(m_automaticFailoverEnabledHasBeenSet)
  {
    ss << "AutomaticFailoverEnabled=" << m_automaticFailoverEnabled << "&";
  }
  if(m_cacheSecurityGroupNamesHasBeenSet)
  {
    unsigned cacheSecurityGroupNamesCount = 1;
    for(auto& item : m_cacheSecurityGroupNames)
    {
      ss << "CacheSecurityGroupNames.member." << cacheSecurityGroupNamesCount << "="
          << StringUtils::URLEncode(item.c_str()) << "&";
      cacheSecurityGroupNamesCount++;
    }
  }
  if(m_securityGroupIdsHasBeenSet)
  {
    unsigned securityGroupIdsCount = 1;
    for(auto& item : m_securityGroupIds)
    {
      ss << "SecurityGroupIds.member." << securityGroupIdsCount << "="
          << StringUtils::URLEncode(item.c_str()) << "&";
      securityGroupIdsCount++;
    }
  }
  if(m_preferredMaintenanceWindowHasBeenSet)
  {
    ss << "PreferredMaintenanceWindow=" << StringUtils::URLEncode(m_preferredMaintenanceWindow.c_str()) << "&";
  }
  if(m_notificationTopicArnHasBeenSet)
  {
    ss << "NotificationTopicArn=" << StringUtils::URLEncode(m_notificationTopicArn.c_str()) << "&";
  }
  if(m_cacheParameterGroupNameHasBeenSet)
  {
    ss << "CacheParameterGroupName=" << StringUtils::URLEncode(m_cacheParameterGroupName.c_str()) << "&";
  }
  if(m_notificationTopicStatusHasBeenSet)
  {
    ss << "NotificationTopicStatus=" << StringUtils::URLEncode(m_notificationTopicStatus.c_str()) << "&";
  }
  if(m_applyImmediatelyHasBeenSet)
  {
    ss << "ApplyImmediately=" << m_applyImmediately << "&";
  }
  if(m_engineVersionHasBeenSet)
  {
    ss << "EngineVersion=" << StringUtils::URLEncode(m_engineVersion.c_str()) << "&";
  }
  if(m_autoMinorVersionUpgradeHasBeenSet)
  {
    ss << "AutoMinorVersionUpgrade=" << m_autoMinorVersionUpgrade << "&";
  }
  if(m_snapshotRetentionLimitHasBeenSet)
  {
    ss << "SnapshotRetentionLimit=" << m_snapshotRetentionLimit << "&";
  }
  if(m_snapshotWindowHasBeenSet)
  {
    ss << "SnapshotWindow=" << StringUtils::URLEncode(m_snapshotWindow.c_str()) << "&";
  }
  ss << "Version=2015-02-02";
  return ss.str();
}