text:
"""Stateless random ops which take seed as a tensor input."""

import enum
import numpy as np

from tensorflow.python.compat import compat
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import bitwise_ops
from tensorflow.python.ops import gen_stateless_random_ops
from tensorflow.python.ops import gen_stateless_random_ops_v2
from tensorflow.python.ops import math_ops
from tensorflow.python.util import deprecation
from tensorflow.python.util import dispatch
from tensorflow.python.util.tf_export import tf_export

ops.NotDifferentiable("StatelessMultinomial")
ops.NotDifferentiable("StatelessRandomBinomial")
ops.NotDifferentiable("StatelessRandomNormal")
ops.NotDifferentiable("StatelessRandomPoisson")
ops.NotDifferentiable("StatelessRandomUniform")
ops.NotDifferentiable("StatelessRandomUniformInt")
ops.NotDifferentiable("StatelessRandomUniformFullInt")
ops.NotDifferentiable("StatelessTruncatedNormal")

ops.NotDifferentiable("StatelessRandomNormalV2")
ops.NotDifferentiable("StatelessRandomUniformV2")
ops.NotDifferentiable("StatelessRandomUniformIntV2")
ops.NotDifferentiable("StatelessRandomUniformFullIntV2")
ops.NotDifferentiable("StatelessTruncatedNormalV2")

@tf_export("random.Algorithm", "random.experimental.Algorithm")
class Algorithm(enum.Enum):
  # The numbers here must match framework/rng_alg.h
  PHILOX = 1
  THREEFRY = 2
  AUTO_SELECT = 3

def convert_alg_to_int(alg):
  """Converts algorithm to an integer.

  Args:
    alg: can be one of these types: integer, Algorithm, Tensor, string. Allowed
      strings are "philox" and "threefry".

  Returns:
    An integer, unless the input is a Tensor in which case a Tensor is returned.
  """
  if isinstance(alg, int):
    return alg
  if isinstance(alg, Algorithm):
    return alg.value
  if isinstance(alg, ops.Tensor):
    return alg
  if isinstance(alg, str):
    if alg == "philox":
      return Algorithm.PHILOX.value
    elif alg in ("threefry", "three-fry", "three_fry"):
      return Algorithm.THREEFRY.value
    elif alg in ("autoselect", "auto-select", "auto_select"):
      return Algorithm.AUTO_SELECT.value
    else:
      raise ValueError(
          f"Argument `alg` got unsupported string value {alg}. Supported "
          f"string values are 'philox' for the Philox algorithm, 'threefry' "
          f"for the ThreeFry algorithm, and 'auto_select' for auto-selection.")
  else:
    raise TypeError(
        f"Can't convert argument `alg` (of value {alg} and type {type(alg)}) "
        f"to int.")

def _resolve_alg(alg):
  if alg == Algorithm.AUTO_SELECT.value:
    return gen_stateless_random_ops_v2.stateless_random_get_alg()
  return alg

def _get_key_counter(seed, alg):
  """Calculates the key and counter to pass to raw RNG ops.

  This function calculates the key and counter that will be passed to
  the raw RNG ops like `StatelessRandomUniformV2`. Depending on the
  input `alg`, the key and counter may be scrambled or copied from
  `seed`. If `alg` is `"auto_select"`, the key and counter will be
  determined at runtime based on device type.

  Args:
    seed: An integer tensor of shape [2]. The seed to calculate the
      key and counter from.
    alg: The RNG algorithm. See `tf.random.stateless_uniform` for an
      explanation.

  Returns:
    A pair (key, counter) suitable for V2 stateless RNG ops like
    `StatelessRandomUniformV2`.
  """
  if alg == Algorithm.AUTO_SELECT.value:
    key, counter = gen_stateless_random_ops_v2.stateless_random_get_key_counter(
        seed)
  elif alg == Algorithm.PHILOX.value:
    key, counter = _philox_scramble_seed(seed)
  elif alg == Algorithm.THREEFRY.value:
    key = array_ops.reshape(
        uint32s_to_uint64(math_ops.cast(seed, dtypes.uint32)), [1])
    counter = array_ops.zeros([1], dtypes.uint64)
  else:
    raise ValueError(
        f"Argument `alg` got unsupported value {alg}. Supported values are "
        f"{Algorithm.PHILOX.value} for the Philox algorithm, "
        f"{Algorithm.THREEFRY.value} for the ThreeFry algorithm, and "
        f"{Algorithm.AUTO_SELECT.value} for auto-selection.")
  return key, counter

def _get_key_counter_alg(seed, alg):
  if alg is None:
    alg = Algorithm.AUTO_SELECT.value
  alg = convert_alg_to_int(alg)
  key, counter = _get_key_counter(seed, alg)
  if compat.forward_compatible(2021, 8, 11):
    return key, counter, alg
  else:
    return key, counter, _resolve_alg(alg)

def _philox_scramble_seed(seed):
  # the same scrambling procedure as core/kernels/stateless_random_ops.cc
  key = constant_op.constant([0x02461e293ec8f720], dtypes.uint64)
  counter = math_ops.cast(seed, dtypes.uint64)
  mix = gen_stateless_random_ops_v2.stateless_random_uniform_full_int_v2(
      [4], key=key, counter=counter, dtype=dtypes.uint32,
      alg=Algorithm.PHILOX.value)
  key = array_ops.reshape(uint32s_to_uint64(mix[:2]), [1])
  counter = array_ops.stack([0, uint32s_to_uint64(mix[2:])], axis=0)
  return key, counter

def uint32s_to_uint64(x):
  return bitwise_ops.bitwise_or(
      math_ops.cast(x[0], dtypes.uint64),
      bitwise_ops.left_shift(math_ops.cast(x[1], dtypes.uint64),
                             constant_op.constant(32, dtypes.uint64)))

@tf_export("random.experimental.stateless_split")
@dispatch.add_dispatch_support
def split(seed, num=2, alg="auto_select"):
  """Splits an RNG seed into `num` new seeds by adding a leading axis.

  Example:

  >>> seed = [1, 2]
  >>> new_seeds = tf.random.experimental.stateless_split(seed, num=3)
  >>> print(new_seeds)
  tf.Tensor(
  [[1105988140 1738052849]
   [-335576002  370444179]
   [  10670227 -246211131]], shape=(3, 2), dtype=int32)
  >>> tf.random.stateless_normal(shape=[3], seed=new_seeds[0, :])
  <tf.Tensor: shape=(3,), dtype=float32, numpy=array([-0.59835213, -0.9578608 ,
  0.9002807 ], dtype=float32)>

  Args:
    seed: an RNG seed (a tensor with shape [2] and dtype `int32` or
      `int64`). (When using XLA, only `int32` is allowed.)
    num: optional, a positive integer or scalar tensor indicating the number of
      seeds to produce (default 2).
    alg: The RNG algorithm used to generate the random numbers. See
      `tf.random.stateless_uniform` for a detailed explanation.

  Returns:
    A tensor with shape [num, 2] representing `num` new seeds. It will have the
    same dtype as `seed` (if `seed` doesn't have an explict dtype, the dtype
    will be determined by `tf.convert_to_tensor`).
  """
  seed = ops.convert_to_tensor(seed)
  return stateless_random_uniform(shape=[num, 2], seed=seed, dtype=seed.dtype,
                                  minval=None, maxval=None, alg=alg)

@tf_export("random.experimental.stateless_fold_in")
@dispatch.add_dispatch_support
def fold_in(seed, data, alg="auto_select"):
  """Folds in data to an RNG seed to form a new RNG seed.

  For example, in a distributed-training setting, suppose we have a master seed
  and a replica ID. We want to fold the replica ID into the master seed to
  form a "replica seed" to be used by that replica later on, so that different
  replicas will generate different random numbers but the reproducibility of the
  whole system can still be controlled by the master seed:

  >>> master_seed = [1, 2]
  >>> replica_id = 3
  >>> replica_seed = tf.random.experimental.stateless_fold_in(
  ...   master_seed, replica_id)
  >>> print(replica_seed)
  tf.Tensor([1105988140          3], shape=(2,), dtype=int32)
  >>> tf.random.stateless_normal(shape=[3], seed=replica_seed)
  <tf.Tensor: shape=(3,), dtype=float32, numpy=array([0.03197195, 0.8979765 ,
  0.13253039], dtype=float32)>

  Args:
    seed: an RNG seed (a tensor with shape [2] and dtype `int32` or
      `int64`). (When using XLA, only `int32` is allowed.)
    data: an `int32` or `int64` scalar representing data to be folded in to the
      seed.
    alg: The RNG algorithm used to generate the random numbers. See
      `tf.random.stateless_uniform` for a detailed explanation.

  Returns:
    A new RNG seed that is a deterministic function of the inputs and is
    statistically safe for producing a stream of new pseudo-random values. It
    will have the same dtype as `data` (if `data` doesn't have an explict dtype,
    the dtype will be determined by `tf.convert_to_tensor`).
  """
  data = ops.convert_to_tensor(data)
  seed1 = stateless_random_uniform(shape=[], seed=seed, dtype=data.dtype,
                                   minval=None, maxval=None, alg=alg)
  return array_ops.stack([seed1, data])

@tf_export("random.stateless_uniform")
@dispatch.add_dispatch_support
def stateless_random_uniform(shape,
                             seed,
                             minval=0,
                             maxval=None,
                             dtype=dtypes.float32,
                             name=None,
                             alg="auto_select"):
  """Outputs deterministic pseudorandom values from a uniform distribution.

  This is a stateless version of `tf.random.uniform`: if run twice with the
  same seeds and shapes, it will produce the same pseudorandom numbers.  The
  output is consistent across multiple runs on the same hardware (and between
  CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU
  hardware.

  The generated values follow a uniform distribution in the range
  `[minval, maxval)`. The lower bound `minval` is included in the range, while
  the upper bound `maxval` is excluded.

  For floats, the default range is `[0, 1)`.  For ints, at least `maxval` must
  be specified explicitly.

  In the integer case, the random integers are slightly biased unless
  `maxval - minval` is an exact power of two.  The bias is small for values of
  `maxval - minval` significantly smaller than the range of the output (either
  `2**32` or `2**64`).

  For full-range (i.e. inclusive of both max and min) random integers, pass
  `minval=None` and `maxval=None` with an integer `dtype`. For an integer dtype
  either both `minval` and `maxval` must be `None` or neither may be `None`. For
  example:
  ```python
  ints = tf.random.stateless_uniform(
      [10], seed=(2, 3), minval=None, maxval=None, dtype=tf.int32)
  ```

  Args:
    shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
    seed: A shape [2] Tensor, the seed to the random number generator. Must have
      dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.)
    minval: A Tensor or Python value of type `dtype`, broadcastable with
      `shape` (for integer types, broadcasting is not supported, so it needs to
      be a scalar). The lower bound on the range of random values to
      generate. Pass `None` for full-range integers.  Defaults to 0.
    maxval: A Tensor or Python value of type `dtype`, broadcastable with
      `shape` (for integer types, broadcasting is not supported, so it needs to
      be a scalar). The upper bound on the range of random values to generate.
      Defaults to 1 if `dtype` is floating point. Pass `None` for full-range
      integers.
    dtype: The type of the output: `float16`, `bfloat16`, `float32`, `float64`,
      `int32`, or `int64`. For unbounded uniform ints (`minval`, `maxval` both
      `None`), `uint32` and `uint64` may be used. Defaults to `float32`.
    name: A name for the operation (optional).
    alg: The RNG algorithm used to generate the random numbers. Valid
      choices are `"philox"` for [the Philox
      algorithm](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf),
      `"threefry"` for [the ThreeFry
      algorithm](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf),
      and `"auto_select"` (default) for the system to automatically
      select an algorithm based the device type. Values of
      `tf.random.Algorithm` can also be used. Note that with
      `"auto_select"`, the outputs of this function may change when
      it is running on a different device.

  Returns:
    A tensor of the specified shape filled with random uniform values.

  Raises:
    ValueError: If `dtype` is integral and only one of `minval` or `maxval` is
      specified.
  """
  dtype = dtypes.as_dtype(dtype)
  accepted_dtypes = (dtypes.float16, dtypes.bfloat16, dtypes.float32,
                     dtypes.float64, dtypes.int32, dtypes.int64, dtypes.uint32,
                     dtypes.uint64)
  if dtype not in accepted_dtypes:
    raise ValueError(
        f"Argument `dtype` got invalid value {dtype}. Accepted dtypes are "
        f"{accepted_dtypes}.")
  if dtype.is_integer:
    if (minval is None) != (maxval is None):
      raise ValueError(
          f"For integer `dtype` argument {dtype}, argument `minval` and "
          f"`maxval` must be both None or not None. Got `minval`={minval} and "
          f"`maxval`={maxval}.")
    if minval is not None and dtype in (dtypes.uint32, dtypes.uint64):
      raise ValueError(
          f"Argument `dtype` got invalid value {dtype} when argument `minval` "
          f"is not None. Please don't use unsigned integers in this case.")
  elif maxval is None:
    maxval = 1
  with ops.name_scope(name, "stateless_random_uniform",
                      [shape, seed, minval, maxval]) as name:
    shape = tensor_util.shape_tensor(shape)
    if dtype.is_integer and minval is None:
      key, counter, alg = _get_key_counter_alg(seed, alg)
      result = (
          gen_stateless_random_ops_v2.stateless_random_uniform_full_int_v2(
              shape, key=key, counter=counter, dtype=dtype, alg=alg, name=name))
    else:
      minval = ops.convert_to_tensor(minval, dtype=dtype, name="min")
      maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max")
      if dtype.is_integer:
        key, counter, alg = _get_key_counter_alg(seed, alg)
        result = gen_stateless_random_ops_v2.stateless_random_uniform_int_v2(
            shape,
            key=key,
            counter=counter,
            minval=minval,
            maxval=maxval,
            alg=alg,
            name=name)
      else:
        key, counter, alg = _get_key_counter_alg(seed, alg)
        rnd = gen_stateless_random_ops_v2.stateless_random_uniform_v2(
            shape, key=key, counter=counter, dtype=dtype, alg=alg)
        result = math_ops.add(rnd * (maxval - minval), minval, name=name)
    tensor_util.maybe_set_static_shape(result, shape)
    return result

@tf_export("random.stateless_binomial")
@dispatch.add_dispatch_support
def stateless_random_binomial(shape,
                              seed,
                              counts,
                              probs,
                              output_dtype=dtypes.int32,
                              name=None):
  """Outputs deterministic pseudorandom values from a binomial distribution.

  The generated values follow a binomial distribution with specified count and
  probability of success parameters.

  This is a stateless version of `tf.random.Generator.binomial`: if run twice
  with the same seeds and shapes, it will produce the same pseudorandom numbers.
  The output is consistent across multiple runs on the same hardware (and
  between CPU and GPU), but may change between versions of TensorFlow or on
  non-CPU/GPU hardware.

  Example:

  ```python
  counts = [10., 20.]
  # Probability of success.
  probs = [0.8]

  binomial_samples = tf.random.stateless_binomial(
      shape=[2], seed=[123, 456], counts=counts, probs=probs)

  counts = ... # Shape [3, 1, 2]
  probs = ...  # Shape [1, 4, 2]
  shape = [3, 4, 3, 4, 2]
  # Sample shape will be [3, 4, 3, 4, 2]
  binomial_samples = tf.random.stateless_binomial(
      shape=shape, seed=[123, 456], counts=counts, probs=probs)
  ```

  Args:
    shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
    seed: A shape [2] Tensor, the seed to the random number generator. Must have
      dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.)
    counts: Tensor. The counts of the binomial distribution. Must be
      broadcastable with `probs`, and broadcastable with the rightmost
      dimensions of `shape`.
    probs: Tensor. The probability of success for the binomial distribution.
      Must be broadcastable with `counts` and broadcastable with the rightmost
      dimensions of `shape`.
    output_dtype: The type of the output. Default: tf.int32
    name: A name for the operation (optional).

  Returns:
    samples: A Tensor of the specified shape filled with random binomial
      values.  For each i, each samples[..., i] is an independent draw from
      the binomial distribution on counts[i] trials with probability of
      success probs[i].

  """
  with ops.name_scope(name, "stateless_random_binomial",
                      [shape, seed, counts, probs]) as name:
    shape = tensor_util.shape_tensor(shape)
    probs = ops.convert_to_tensor(
        probs, dtype_hint=dtypes.float32, name="probs")
    counts = ops.convert_to_tensor(
        counts, dtype_hint=probs.dtype, name="counts")
    result = gen_stateless_random_ops.stateless_random_binomial(
        shape=shape, seed=seed, counts=counts, probs=probs, dtype=output_dtype)
    tensor_util.maybe_set_static_shape(result, shape)
    return result

@tf_export("random.stateless_gamma")
@dispatch.add_dispatch_support
def stateless_random_gamma(shape,
                           seed,
                           alpha,
                           beta=None,
                           dtype=dtypes.float32,
                           name=None):
  """Outputs deterministic pseudorandom values from a gamma distribution.

  The generated values follow a gamma distribution with specified concentration
  (`alpha`) and inverse scale (`beta`) parameters.

  This is a stateless version of `tf.random.gamma`: if run twice with the same
  seeds and shapes, it will produce the same pseudorandom numbers. The output is
  consistent across multiple runs on the same hardware (and between CPU and
  GPU),
  but may change between versions of TensorFlow or on non-CPU/GPU hardware.

  A slight difference exists in the interpretation of the `shape` parameter
  between `stateless_gamma` and `gamma`: in `gamma`, the `shape` is always
  prepended to the shape of the broadcast of `alpha` with `beta`; whereas in
  `stateless_gamma` the `shape` parameter must always encompass the shapes of
  each of `alpha` and `beta` (which must broadcast together to match the
  trailing dimensions of `shape`).

  Note: Because internal calculations are done using `float64` and casting has
  `floor` semantics, we must manually map zero outcomes to the smallest
  possible positive floating-point value, i.e., `np.finfo(dtype).tiny`.  This
  means that `np.finfo(dtype).tiny` occurs more frequently than it otherwise
  should.  This bias can only happen for small values of `alpha`, i.e.,
  `alpha << 1` or large values of `beta`, i.e., `beta >> 1`.

  The samples are differentiable w.r.t. alpha and beta.
  The derivatives are computed using the approach described in
  (Figurnov et al., 2018).

  Example:

  ```python
  samples = tf.random.stateless_gamma([10, 2], seed=[12, 34], alpha=[0.5, 1.5])
  # samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents
  # the samples drawn from each distribution

  samples = tf.random.stateless_gamma([7, 5, 2], seed=[12, 34], alpha=[.5, 1.5])
  # samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1]
  # represents the 7x5 samples drawn from each of the two distributions

  alpha = tf.constant([[1.], [3.], [5.]])
  beta = tf.constant([[3., 4.]])
  samples = tf.random.stateless_gamma(
      [30, 3, 2], seed=[12, 34], alpha=alpha, beta=beta)
  # samples has shape [30, 3, 2], with 30 samples each of 3x2 distributions.

  with tf.GradientTape() as tape:
    tape.watch([alpha, beta])
    loss = tf.reduce_mean(tf.square(tf.random.stateless_gamma(
        [30, 3, 2], seed=[12, 34], alpha=alpha, beta=beta)))
  dloss_dalpha, dloss_dbeta = tape.gradient(loss, [alpha, beta])
  # unbiased stochastic derivatives of the loss function
  alpha.shape == dloss_dalpha.shape  # True
  beta.shape == dloss_dbeta.shape  # True
  ```

  Args:
    shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
    seed: A shape [2] Tensor, the seed to the random number generator. Must have
      dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.)
    alpha: Tensor. The concentration parameter of the gamma distribution. Must
      be broadcastable with `beta`, and broadcastable with the rightmost
      dimensions of `shape`.
    beta: Tensor. The inverse scale parameter of the gamma distribution. Must be
      broadcastable with `alpha` and broadcastable with the rightmost dimensions
      of `shape`.
    dtype: Floating point dtype of `alpha`, `beta`, and the output.
    name: A name for the operation (optional).

  Returns:
    samples: A Tensor of the specified shape filled with random gamma values.
      For each i, each `samples[..., i] is an independent draw from the gamma
      distribution with concentration alpha[i] and scale beta[i].

  """
  with ops.name_scope(name, "stateless_random_gamma",
                      [shape, seed, alpha, beta]) as name:
    shape = tensor_util.shape_tensor(shape)
    alpha = ops.convert_to_tensor(alpha, dtype=dtype, name="alpha")
    beta = ops.convert_to_tensor(
        beta if beta is not None else 1, name="beta", dtype=dtype)
    broadcast_shape = array_ops.broadcast_dynamic_shape(
        array_ops.shape(alpha), array_ops.shape(beta))
    alpha_broadcast = array_ops.broadcast_to(alpha, broadcast_shape)
    result = math_ops.maximum(
        np.finfo(alpha.dtype.as_numpy_dtype).tiny,
        gen_stateless_random_ops.stateless_random_gamma_v2(
            shape, seed=seed, alpha=alpha_broadcast) / beta)
    tensor_util.maybe_set_static_shape(result, shape)
    return result

@tf_export("random.stateless_poisson")
@dispatch.add_dispatch_support
def stateless_random_poisson(shape,
                             seed,
                             lam,
                             dtype=dtypes.int32,
                             name=None):
  """Outputs deterministic pseudorandom values from a Poisson distribution.

  The generated values follow a Poisson distribution with specified rate
  parameter.

  This is a stateless version of `tf.random.poisson`: if run twice with the same
  seeds and shapes, it will produce the same pseudorandom numbers. The output is
  consistent across multiple runs on the same hardware, but may change between
  versions of TensorFlow or on non-CPU/GPU hardware.

  A slight difference exists in the interpretation of the `shape` parameter
  between `stateless_poisson` and `poisson`: in `poisson`, the `shape` is always
  prepended to the shape of `lam`; whereas in `stateless_poisson` the shape of
  `lam` must match the trailing dimensions of `shape`.

  Example:

  ```python
  samples = tf.random.stateless_poisson([10, 2], seed=[12, 34], lam=[5, 15])
  # samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents
  # the samples drawn from each distribution

  samples = tf.random.stateless_poisson([7, 5, 2], seed=[12, 34], lam=[5, 15])
  # samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1]
  # represents the 7x5 samples drawn from each of the two distributions

  rate = tf.constant([[1.], [3.], [5.]])
  samples = tf.random.stateless_poisson([30, 3, 1], seed=[12, 34], lam=rate)
  # samples has shape [30, 3, 1], with 30 samples each of 3x1 distributions.
  ```

  Args:
    shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
    seed: A shape [2] Tensor, the seed to the random number generator. Must have
      dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.)
    lam: Tensor. The rate parameter "lambda" of the Poisson distribution. Shape
      must match the rightmost dimensions of `shape`.
    dtype: Dtype of the samples (int or float dtypes are permissible, as samples
      are discrete). Default: int32.
    name: A name for the operation (optional).

  Returns:
    samples: A Tensor of the specified shape filled with random Poisson values.
      For each i, each `samples[..., i]` is an independent draw from the Poisson
      distribution with rate `lam[i]`.

  """
  with ops.name_scope(name, "stateless_random_poisson",
                      [shape, seed, lam]) as name:
    shape = tensor_util.shape_tensor(shape)
    result = gen_stateless_random_ops.stateless_random_poisson(
        shape, seed=seed, lam=lam, dtype=dtype)
    tensor_util.maybe_set_static_shape(result, shape)
    return result

@tf_export("random.stateless_normal")
@dispatch.add_dispatch_support
def stateless_random_normal(shape,
                            seed,
                            mean=0.0,
                            stddev=1.0,
                            dtype=dtypes.float32,
                            name=None,
                            alg="auto_select"):
  """Outputs deterministic pseudorandom values from a normal distribution.

  This is a stateless version of `tf.random.normal`: if run twice with the
  same seeds and shapes, it will produce the same pseudorandom numbers.  The
  output is consistent across multiple runs on the same hardware (and between
  CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU
  hardware.

  Args:
    shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
    seed: A shape [2] Tensor, the seed to the random number generator. Must have
      dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.)
    mean: A 0-D Tensor or Python value of type `dtype`. The mean of the normal
      distribution.
    stddev: A 0-D Tensor or Python value of type `dtype`. The standard deviation
      of the normal distribution.
    dtype: The float type of the output: `float16`, `bfloat16`, `float32`,
      `float64`. Defaults to `float32`.
    name: A name for the operation (optional).
    alg: The RNG algorithm used to generate the random numbers. See
      `tf.random.stateless_uniform` for a detailed explanation.

  Returns:
    A tensor of the specified shape filled with random normal values.
  """
  with ops.name_scope(name, "stateless_random_normal",
                      [shape, seed, mean, stddev]) as name:
    shape = tensor_util.shape_tensor(shape)
    mean = ops.convert_to_tensor(mean, dtype=dtype, name="mean")
    stddev = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev")
    key, counter, alg = _get_key_counter_alg(seed, alg)
    rnd = gen_stateless_random_ops_v2.stateless_random_normal_v2(
        shape, key=key, counter=counter, dtype=dtype, alg=alg)
    result = math_ops.add(rnd * stddev, mean, name=name)
    tensor_util.maybe_set_static_shape(result, shape)
    return result

@tf_export("random.stateless_truncated_normal")
@dispatch.add_dispatch_support
def stateless_truncated_normal(shape,
                               seed,
                               mean=0.0,
                               stddev=1.0,
                               dtype=dtypes.float32,
                               name=None,
                               alg="auto_select"):
  """Outputs deterministic pseudorandom values, truncated normally distributed.

  This is a stateless version of `tf.random.truncated_normal`: if run twice with
  the same seeds and shapes, it will produce the same pseudorandom numbers.  The
  output is consistent across multiple runs on the same hardware (and between
  CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU
  hardware.

  The generated values follow a normal distribution with specified mean and
  standard deviation, except that values whose magnitude is more than 2 standard
  deviations from the mean are dropped and re-picked.

  Args:
    shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
    seed: A shape [2] Tensor, the seed to the random number generator. Must have
      dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.)
    mean: A 0-D Tensor or Python value of type `dtype`. The mean of the
      truncated normal distribution.
    stddev: A 0-D Tensor or Python value of type `dtype`. The standard deviation
      of the normal distribution, before truncation.
    dtype: The type of the output.
    name: A name for the operation (optional).
    alg: The RNG algorithm used to generate the random numbers. See
      `tf.random.stateless_uniform` for a detailed explanation.

  Returns:
    A tensor of the specified shape filled with random truncated normal values.
  """
  with ops.name_scope(name, "stateless_truncated_normal",
                      [shape, seed, mean, stddev]) as name:
    shape = tensor_util.shape_tensor(shape)
    mean = ops.convert_to_tensor(mean, dtype=dtype, name="mean")
    stddev = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev")
    key, counter, alg = _get_key_counter_alg(seed, alg)
    rnd = gen_stateless_random_ops_v2.stateless_truncated_normal_v2(
        shape, key=key, counter=counter, dtype=dtype, alg=alg)
    result = math_ops.add(rnd * stddev, mean, name=name)
    tensor_util.maybe_set_static_shape(result, shape)
    return result

@tf_export(v1=["random.stateless_multinomial"])
@dispatch.add_dispatch_support
@deprecation.deprecated(
    date=None, instructions="Use `tf.random.stateless_categorical` instead.")
def stateless_multinomial(logits,
                          num_samples,
                          seed,
                          output_dtype=dtypes.int64,
                          name=None):
  """Draws deterministic pseudorandom samples from a multinomial distribution.

  This is a stateless version of `tf.random.categorical`: if run twice with the
  same seeds and shapes, it will produce the same pseudorandom numbers.  The
  output is consistent across multiple runs on the same hardware (and between
  CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU
  hardware.

  Example:

  ```python
  # samples has shape [1, 5], where each value is either 0 or 1 with equal
  # probability.
  samples = tf.random.stateless_categorical(
      tf.math.log([[0.5, 0.5]]), 5, seed=[7, 17])
  ```

  Args:
    logits: 2-D Tensor with shape `[batch_size, num_classes]`.  Each slice
      `[i, :]` represents the unnormalized log-probabilities for all classes.
    num_samples: 0-D.  Number of independent samples to draw for each row slice.
    seed: A shape [2] Tensor, the seed to the random number generator. Must have
      dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.)
    output_dtype: The integer type of the output: `int32` or `int64`. Defaults
      to `int64`.
    name: Optional name for the operation.

  Returns:
    The drawn samples of shape `[batch_size, num_samples]`.
  """
  with ops.name_scope(name, "stateless_multinomial", [logits, seed]):
    return stateless_multinomial_categorical_impl(logits, num_samples,
                                                  output_dtype, seed)

@tf_export("random.stateless_categorical")
@dispatch.add_dispatch_support
def stateless_categorical(logits,
                          num_samples,
                          seed,
                          dtype=dtypes.int64,
                          name=None):
  """Draws deterministic pseudorandom samples from a categorical distribution.

  This is a stateless version of `tf.categorical`: if run twice with the
  same seeds and shapes, it will produce the same pseudorandom numbers.  The
  output is consistent across multiple runs on the same hardware (and between
  CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU
  hardware.

  Example:

  ```python
  # samples has shape [1, 5], where each value is either 0 or 1 with equal
  # probability.
  samples = tf.random.stateless_categorical(
      tf.math.log([[0.5, 0.5]]), 5, seed=[7, 17])
  ```

  Args:
    logits: 2-D Tensor with shape `[batch_size, num_classes]`.  Each slice
      `[i, :]` represents the unnormalized log-probabilities for all classes.
    num_samples: 0-D.  Number of independent samples to draw for each row slice.
    seed: A shape [2] Tensor, the seed to the random number generator. Must have
      dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.)
    dtype: The integer type of the output: `int32` or `int64`. Defaults to
      `int64`.
    name: Optional name for the operation.

  Returns:
    The drawn samples of shape `[batch_size, num_samples]`.
  """
  with ops.name_scope(name, "stateless_categorical", [logits, seed]):
    return stateless_multinomial_categorical_impl(logits, num_samples, dtype,
                                                  seed)

def stateless_multinomial_categorical_impl(logits, num_samples, dtype, seed):
  """Implementation for stateless multinomial/categorical ops (v1/v2)."""
  logits = ops.convert_to_tensor(logits, name="logits")
  dtype = dtypes.as_dtype(dtype) if dtype else dtypes.int64
  accepted_dtypes = (dtypes.int32, dtypes.int64)
  if dtype not in accepted_dtypes:
    raise ValueError(
        f"Argument `dtype` got invalid value {dtype}. Accepted dtypes are "
        f"{accepted_dtypes}.")
  return gen_stateless_random_ops.stateless_multinomial(
      logits, num_samples, seed, output_dtype=dtype)

@dispatch.add_dispatch_support
@tf_export("random.stateless_parameterized_truncated_normal")
def stateless_parameterized_truncated_normal(shape,
                                             seed,
                                             means=0.0,
                                             stddevs=1.0,
                                             minvals=-2.0,
                                             maxvals=2.0,
                                             name=None):
  """Outputs random values from a truncated normal distribution.

  The generated values follow a normal distribution with specified mean and
  standard deviation, except that values whose magnitude is more than 2 standard
  deviations from the mean are dropped and re-picked.

  Examples:

  Sample from a Truncated normal, with deferring shape parameters that
  broadcast.

  >>> means = 0.
  >>> stddevs = tf.math.exp(tf.random.uniform(shape=[2, 3]))
  >>> minvals = [-1., -2., -1000.]
  >>> maxvals = [[10000.], [1.]]
  >>> y = tf.random.stateless_parameterized_truncated_normal(
  ...   shape=[10, 2, 3], seed=[7, 17],
  ...   means=means, stddevs=stddevs, minvals=minvals, maxvals=maxvals)
  >>> y.shape
  TensorShape([10, 2, 3])

  Args:
    shape: A 1-D integer `Tensor` or Python array. The shape of the output
      tensor.
    seed: A shape [2] Tensor, the seed to the random number generator. Must have
      dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.)
    means: A `Tensor` or Python value of type `dtype`. The mean of the truncated
      normal distribution. This must broadcast with `stddevs`, `minvals` and
      `maxvals`, and the broadcasted shape must be dominated by `shape`.
    stddevs: A `Tensor` or Python value of type `dtype`. The standard deviation
      of the truncated normal distribution. This must broadcast with `means`,
      `minvals` and `maxvals`, and the broadcasted shape must be dominated by
      `shape`.
    minvals: A `Tensor` or Python value of type `dtype`. The minimum value of
      the truncated normal distribution. This must broadcast with `means`,
      `stddevs` and `maxvals`, and the broadcasted shape must be dominated by
      `shape`.
    maxvals: A `Tensor` or Python value of type `dtype`. The maximum value of
      the truncated normal distribution. This must broadcast with `means`,
      `stddevs` and `minvals`, and the broadcasted shape must be dominated by
      `shape`.
    name: A name for the operation (optional).

  Returns:
    A tensor of the specified shape filled with random truncated normal values.
  """
  with ops.name_scope(name, "stateless_parameterized_truncated_normal",
                      [shape, means, stddevs, minvals, maxvals]) as name:
    shape_tensor = tensor_util.shape_tensor(shape)
    means_tensor = ops.convert_to_tensor(means, name="means")
    stddevs_tensor = ops.convert_to_tensor(stddevs, name="stddevs")
    minvals_tensor = ops.convert_to_tensor(minvals, name="minvals")
    maxvals_tensor = ops.convert_to_tensor(maxvals, name="maxvals")
    rnd = gen_stateless_random_ops.stateless_parameterized_truncated_normal(
        shape_tensor, seed, means_tensor, stddevs_tensor, minvals_tensor,
        maxvals_tensor)
    tensor_util.maybe_set_static_shape(rnd, shape)
    return rnd


text:
<?php

namespace Austinw\Pdfdf;

use Illuminate\Support\Facades\Facade;

/**
 * Facade for Pdfdf
 *
 * @author Austin White <austingym@gmail.com>
 */
class PdfdfFacade extends Facade
{
    /**
    * Get the registered name of the component.
    *
    * @return string
    */
    protected static function getFacadeAccessor()
    {
        return 'pdfdf';
    }
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import
import paho.mqtt.client as mqtt
import uuid
from . import cbLogs

# This function strips the scheme and the port (if they exist) off the given url
def parse_url(url):
    s = url.split(":")
    if len(s) == 3:  # we've got http and a port. get rid of them
        return s[1][2:]
    elif len(s) == 2:  # we've either got a port or an http
        try:
            int(s[1])  # if it's a port, we'll be able to convert to int
        except ValueError:
            return s[1][2:]
        else:
            return s[0]
    elif len(s) > 3:
        cbLogs.error("Couldn't parse this url:", url)
        exit(-1)
    else:
        return s[0]

class Messaging:
    def __init__(self, user=None, port=1883, keepalive=30, url="", client_id="", use_tls=False):
        # mqtt client
        self.__mqttc = (client_id != "" and mqtt.Client(client_id=client_id)) or mqtt.Client(client_id=uuid.uuid4().hex)
        self.__mqttc.username_pw_set(user.token, user.system.systemKey)

        # default callback functions
        # these are wrappers for the user defined callbacks
        # we do it this way so we can log debug info and errors
        # and still allow users to update them without calling a function
        self.__mqttc.on_connect = self.__connect_cb
        self.__mqttc.on_disconnect = self.__disconnect_cb
        self.__mqttc.on_subscribe = self.__subscribe_cb
        self.__mqttc.on_unsubscribe = self.__unsubscribe_cb
        self.__mqttc.on_publish = self.__publish_cb
        self.__mqttc.on_message = self.__message_cb
        self.__mqttc.on_log = self.__log_cb

        # user defined callback functions
        self.on_connect = None
        self.on_disconnect = None
        self.on_subscribe = None
        self.on_unsubscribe = None
        self.on_publish = None
        self.on_message = None
        self.on_log = None

        # internal variables
        if url:
            self.__url = parse_url(url)
        else:
            self.__url = parse_url(user.system.url)
        self.__port = port
        self.__keepalive = keepalive
        self.__qos = 0
        self.__use_tls = use_tls

    def __connect_cb(self, client, userdata, flags, rc):
        if rc == 0:
            cbLogs.info("Connected to MQTT broker at", self.__url, "port", str(self.__port) + ".")
        elif rc == 1:
            cbLogs.error("MQTT connection to", self.__url, "port", str(self.__port) + ".", "refused. Incorrect protocol version.")  # I should probably fix this
            exit(-1)
        elif rc == 2:
            cbLogs.error("MQTT connection to", self.__url, "port", str(self.__port) + ".", "refused. Invalid client identifier.")
            exit(-1)
        elif rc == 3:
            cbLogs.error("MQTT connection to", self.__url, "port", str(self.__port) + ".", "refused. Server unavailable.")
            exit(-1)
        elif rc == 4:
            cbLogs.error("MQTT connection to", self.__url, "port", str(self.__port) + ".", "refused. Bad username or password.")
            exit(-1)
        elif rc == 5:
            cbLogs.error("MQTT connection to", self.__url, "port", str(self.__port) + ".", "refused. Not authorized.")
            exit(-1)
        else:
            cbLogs.error("MQTT connection to", self.__url, "port", str(self.__port) + ".", "refused. Tell ClearBlade to update their SDK for this case. rc=" + rc)
            exit(-1)
        if self.on_connect:
            self.on_connect(client, userdata, flags, rc)

    def __disconnect_cb(self, client, userdata, rc):
        if rc == 0:
            cbLogs.info("Disconnected from MQTT broker at", self.__url, "port", str(self.__port) + ".")
        else:
            cbLogs.error("Unexpected disconnect from MQTT broker at", self.__url, "port", str(self.__port) + ". Check your network.")
        if self.on_disconnect:
            self.on_disconnect(client, userdata, rc)

    def __subscribe_cb(self, client, userdata, mid, granted_qos):
        if self.on_subscribe:
            self.on_subscribe(client, userdata, mid, granted_qos)

    def __unsubscribe_cb(self, client, userdata, mid):
        if self.on_unsubscribe:
            self.on_unsubscribe(client, userdata, mid)

    def __publish_cb(self, client, userdata, mid):
        if self.on_publish:
            self.on_publish(client, userdata, mid)

    def __message_cb(self, client, userdata, message):
        if self.on_message:
            self.on_message(client, userdata, message)

    def __log_cb(self, client, userdata, level, buf):
        cbLogs.mqtt(level, buf)
        if self.on_log:
            self.on_log(client, userdata, level, buf)

    def connect(self):
        cbLogs.info("Connecting to MQTT.")
        if self.__use_tls:
            self.__mqttc.tls_set()
        self.__mqttc.connect(self.__url, self.__port, self.__keepalive)
        self.__mqttc.loop_start()

    def disconnect(self):
        cbLogs.info("Disconnecting from MQTT.")
        self.__mqttc.loop_stop()
        self.__mqttc.disconnect()

    def subscribe(self, channel):
        cbLogs.info("Subscribing to:", channel)
        self.__mqttc.subscribe(channel, self.__qos)

    def unsubscribe(self, channel):
        cbLogs.info("Unsubscribing from:", channel)
        self.__mqttc.unsubscribe(channel)

    def publish(self, channel, message, qos=0):
        cbLogs.info("Publishing", message, "to", channel, ".")
        self.__mqttc.publish(channel, message, qos)


text:
class RenameDisplayNameVisibilityToDisplayLayout < ActiveRecord::Migration[5.0]
  def change
    rename_column :variables, :display_name_visibility, :display_layout
  end
end


text:
package syncme.app;

import syncme.app.logic.Constants;
import syncme.app.ui.AppSectionsPagerAdapter;
import syncme.app.utils.CommonUtils;

import com.example.syncme.R;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity implements ActionBar.TabListener{

	AppSectionsPagerAdapter mAppSectionsPagerAdapter;
	ViewPager mViewPager;

	private String TAG = getClass().getName();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

//
//		Intent intent = new Intent(this, SignUpActivity.class);
//		startActivity(intent);

		// Create the adapter that will return a fragment for each of the three primary sections
		// of the app.
		mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());

		// Set up the action bar.
		 ActionBar actionBar = getActionBar();

		// Specify that the Home/Up button should not be enabled, since there is no hierarchical
		// parent.
		//actionBar.setHomeButtonEnabled(false);

		// Specify that we will be displaying tabs in the action bar.
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		// Set up the ViewPager, attaching the adapter and setting up a listener for when the
        // user swipes between sections.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mAppSectionsPagerAdapter);

        mViewPager.setOnPageChangeListener(onPageSelected(actionBar));

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by the adapter.
            // Also specify this Activity object, which implements the TabListener interface, as the
            // listener for when this tab is selected.
            actionBar.addTab(
                    actionBar.newTab()
                            .setText(mAppSectionsPagerAdapter.getPageTitle(i))
                            .setTabListener(this));
        }
	}

	private ViewPager.SimpleOnPageChangeListener onPageSelected(final ActionBar actionBar){
		return new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // When swiping between different app sections, select the corresponding tab.
                // We can also use ActionBar.Tab#select() to do this if we have a reference to the
                // Tab.
                actionBar.setSelectedNavigationItem(position);
            }
        };
	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
		CommonUtils.LogError(TAG , "onTabReselected", Constants.UNIMPLEMENTED_MSG);
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		 // When the given tab is selected, switch to the corresponding page in the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
		CommonUtils.LogError(TAG , "onTabSelected", Constants.UNIMPLEMENTED_MSG);
	}

}


text:
using namespace std;

int main()
{
   int set[8] = {5, 10, 15, 20, 25, 30, 35, 40};
   int *nums = set;     // Make nums point to set

   // Display the numbers in the array.
   cout << "The numbers in set are:\n";
   cout << *nums << " ";   // Display first element
   while (nums < &set[7])
   {
      // Advance nums to point to the next element.
      nums++;
      // Display the value pointed to by nums.
      cout << *nums << " ";
   }

   // Display the numbers in reverse order.
   cout << "\nThe numbers in set backward are:\n";
   cout << *nums << " ";   // Display first element
   while (nums > set)
   {
      // Move backward to the previous element.
      nums--;
      // Display the value pointed to by nums.
      cout << *nums << " ";
   }
   return 0;
}


text:
import React from 'react'
import Enzyme, { mount } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import { BriefDownloadResponses } from './BriefDownloadResponses'

Enzyme.configure({ adapter: new Adapter() })

jest.mock('shared/Icon/_getIcons')

const brief = {
  id: 1,
  title: 'Test Brief',
  lot: 'digital-professionals',
  responsesZipFilesize: null
}

const responses = [{}, {}]

test('Component mounts with a download button and a filesize in KB when file is < 1MB in size', () => {
  brief.responsesZipFilesize = 1024
  const component = mount(<BriefDownloadResponses brief={brief} briefResponses={responses} />)
  const button = component.find('a')
  expect(button.at(0).text()).toEqual('Download responses 1.00KB zip')
})

test('Component mounts with a download button and a filesize in MB when file is >= 1MB in size', () => {
  brief.responsesZipFilesize = 1024 * 1024 * 10
  const component = mount(<BriefDownloadResponses brief={brief} briefResponses={responses} />)
  const button = component.find('a')
  expect(button.at(0).text()).toEqual('Download responses 10.00MB zip')
})

test('Component mounts without a download button when there are no responses', () => {
  const component = mount(<BriefDownloadResponses brief={brief} briefResponses={[]} />)
  const button = component.find('a')
  expect(button.length).toEqual(1)
})

test('Component mounts without a download button when the filesize is 0', () => {
  brief.responsesZipFilesize = 0
  const component = mount(<BriefDownloadResponses brief={brief} briefResponses={[]} />)
  const button = component.find('a')
  expect(button.length).toEqual(1)
})

test('Component mounts with singular "response" in heading when there is 1 response', () => {
  brief.responsesZipFilesize = 1024
  const component = mount(<BriefDownloadResponses brief={brief} briefResponses={[{}]} />)
  const heading = component.find('h1')
  expect(heading.at(0).text()).toEqual("You've had 1 response to your opportunity.Test Brief")
})

test('Component mounts with plural "responses" in heading when there is more than 1 response', () => {
  brief.responsesZipFilesize = 1024
  const component = mount(<BriefDownloadResponses brief={brief} briefResponses={responses} />)
  const heading = component.find('h1')
  expect(heading.at(0).text()).toEqual("You've had 2 responses to your opportunity.Test Brief")
})

test('Component mounts with plural "candidates" when there are at least 2 responses', () => {
  brief.responsesZipFilesize = 1024
  brief.lot = 'specialist'
  const component = mount(<BriefDownloadResponses brief={brief} briefResponses={responses} />)
  const heading = component.find('h1')
  expect(heading.at(0).text()).toEqual('2 candidates have responded to your opportunity.Test Brief')
})

test('Component mounts with singular "candidate" when there is 1 response', () => {
  brief.responsesZipFilesize = 1024
  brief.lot = 'specialist'
  const component = mount(<BriefDownloadResponses brief={brief} briefResponses={[{}]} />)
  const heading = component.find('h1')
  expect(heading.at(0).text()).toEqual('1 candidate has responded to your opportunity.Test Brief')
})

test('Component mounts with a download button with csv file type for outcome briefs', () => {
  brief.lot = 'digital-outcome'
  const component = mount(<BriefDownloadResponses brief={brief} briefResponses={responses} />)
  const button = component.find('a')
  expect(button.at(0).text()).toEqual('Download responses csv')
})


text:
/**************************************************************************************************
 *** This file was autogenerated from GrTiledGradientEffect.fp; do not modify.
 **************************************************************************************************/
#ifndef GrTiledGradientEffect_DEFINED
#  define GrTiledGradientEffect_DEFINED
#  include "include/core/SkTypes.h"
#  include "src/gpu/GrCoordTransform.h"
#  include "src/gpu/GrFragmentProcessor.h"
class GrTiledGradientEffect : public GrFragmentProcessor
{
public:
  static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> colorizer, std::unique_ptr<GrFragmentProcessor> gradLayout, bool mirror, bool makePremul, bool colorsAreOpaque)
  {
    return std::unique_ptr<GrFragmentProcessor>(new GrTiledGradientEffect(std::move(colorizer), std::move(gradLayout), mirror, makePremul, colorsAreOpaque));
  }
  GrTiledGradientEffect(const GrTiledGradientEffect& src);
  std::unique_ptr<GrFragmentProcessor> clone() const override;
  const char* name() const override
  {
    return "TiledGradientEffect";
  }
  int colorizer_index = -1;
  int gradLayout_index = -1;
  bool mirror;
  bool makePremul;
  bool colorsAreOpaque;
private:
  GrTiledGradientEffect(std::unique_ptr<GrFragmentProcessor> colorizer, std::unique_ptr<GrFragmentProcessor> gradLayout, bool mirror, bool makePremul, bool colorsAreOpaque)
    : INHERITED(kGrTiledGradientEffect_ClassID, (OptimizationFlags) kCompatibleWithCoverageAsAlpha_OptimizationFlag | (colorsAreOpaque && gradLayout->preservesOpaqueInput() ? kPreservesOpaqueInput_OptimizationFlag : kNone_OptimizationFlags))
    , mirror(mirror)
    , makePremul(makePremul)
    , colorsAreOpaque(colorsAreOpaque)
  {
    SkASSERT(colorizer);
    colorizer_index = this->numChildProcessors();
    this->registerChildProcessor(std::move(colorizer));
    SkASSERT(gradLayout);
    gradLayout_index = this->numChildProcessors();
    this->registerChildProcessor(std::move(gradLayout));
  }
  GrGLSLFragmentProcessor* onCreateGLSLInstance() const override;
  void onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const override;
  bool onIsEqual(const GrFragmentProcessor&) const override;
  GR_DECLARE_FRAGMENT_PROCESSOR_TEST
  typedef GrFragmentProcessor INHERITED;
};
#endif


text:
package org.apache.shardingsphere.elasticjob.executor;

import lombok.SneakyThrows;
import org.apache.shardingsphere.elasticjob.api.JobConfiguration;
import org.apache.shardingsphere.elasticjob.executor.fixture.executor.ClassedFooJobExecutor;
import org.apache.shardingsphere.elasticjob.executor.fixture.job.FooJob;
import org.apache.shardingsphere.elasticjob.infra.exception.JobExecutionEnvironmentException;
import org.apache.shardingsphere.elasticjob.infra.exception.JobSystemException;
import org.apache.shardingsphere.elasticjob.infra.listener.ShardingContexts;
import org.apache.shardingsphere.elasticjob.tracing.event.JobStatusTraceEvent.State;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public final class ElasticJobExecutorTest {

    @Mock
    private FooJob fooJob;

    private JobConfiguration jobConfig;

    @Mock
    private JobFacade jobFacade;

    @Mock
    private ClassedFooJobExecutor jobItemExecutor;

    private ElasticJobExecutor elasticJobExecutor;

    @Before
    public void setUp() {
        jobConfig = createJobConfiguration();
        when(jobFacade.loadJobConfiguration(anyBoolean())).thenReturn(jobConfig);
        elasticJobExecutor = new ElasticJobExecutor(fooJob, jobConfig, jobFacade);
        setJobItemExecutor();
    }

    private JobConfiguration createJobConfiguration() {
        return JobConfiguration.newBuilder("test_job", 3)
                .cron("0/1 * * * * ?").shardingItemParameters("0=A,1=B,2=C").jobParameter("param").failover(true).misfire(false).jobErrorHandlerType("THROW").description("desc").build();
    }

    @SneakyThrows
    private void setJobItemExecutor() {
        Field field = ElasticJobExecutor.class.getDeclaredField("jobItemExecutor");
        field.setAccessible(true);
        field.set(elasticJobExecutor, jobItemExecutor);
    }

    @Test(expected = JobSystemException.class)
    public void assertExecuteWhenCheckMaxTimeDiffSecondsIntolerable() throws JobExecutionEnvironmentException {
        doThrow(JobExecutionEnvironmentException.class).when(jobFacade).checkJobExecutionEnvironment();
        try {
            elasticJobExecutor.execute();
        } finally {
            verify(jobItemExecutor, times(0)).process(eq(fooJob), eq(jobConfig), eq(jobFacade), any());
        }
    }

    @Test
    public void assertExecuteWhenPreviousJobStillRunning() {
        ShardingContexts shardingContexts = new ShardingContexts("fake_task_id", "test_job", 3, "", Collections.emptyMap());
        when(jobFacade.getShardingContexts()).thenReturn(shardingContexts);
        when(jobFacade.misfireIfRunning(shardingContexts.getShardingItemParameters().keySet())).thenReturn(true);
        elasticJobExecutor.execute();
        verify(jobFacade).postJobStatusTraceEvent(shardingContexts.getTaskId(), State.TASK_STAGING, "Job 'test_job' execute begin.");
        verify(jobFacade).postJobStatusTraceEvent(shardingContexts.getTaskId(), State.TASK_FINISHED,
                "Previous job 'test_job' - shardingItems '[]' is still running, misfired job will start after previous job completed.");
        verify(jobItemExecutor, times(0)).process(eq(fooJob), eq(jobConfig), eq(jobFacade), any());
    }

    @Test
    public void assertExecuteWhenShardingItemsIsEmpty() {
        ShardingContexts shardingContexts = new ShardingContexts("fake_task_id", "test_job", 3, "", Collections.emptyMap());
        prepareForIsNotMisfire(jobFacade, shardingContexts);
        elasticJobExecutor.execute();
        verify(jobFacade).postJobStatusTraceEvent(shardingContexts.getTaskId(), State.TASK_STAGING, "Job 'test_job' execute begin.");
        verify(jobFacade).postJobStatusTraceEvent(shardingContexts.getTaskId(), State.TASK_FINISHED, "Sharding item for job 'test_job' is empty.");
        verify(jobItemExecutor, times(0)).process(eq(fooJob), eq(jobConfig), eq(jobFacade), any());
    }

    @Test(expected = JobSystemException.class)
    public void assertExecuteFailureWhenThrowExceptionForSingleShardingItem() {
        assertExecuteFailureWhenThrowException(createSingleShardingContexts());
    }

    @Test
    public void assertExecuteFailureWhenThrowExceptionForMultipleShardingItems() {
        assertExecuteFailureWhenThrowException(createMultipleShardingContexts());
    }

    private void assertExecuteFailureWhenThrowException(final ShardingContexts shardingContexts) {
        prepareForIsNotMisfire(jobFacade, shardingContexts);
        doThrow(RuntimeException.class).when(jobItemExecutor).process(eq(fooJob), eq(jobConfig), eq(jobFacade), any());
        try {
            elasticJobExecutor.execute();
        } finally {
            verify(jobFacade).postJobStatusTraceEvent(shardingContexts.getTaskId(), State.TASK_STAGING, "Job 'test_job' execute begin.");
            verify(jobFacade).postJobStatusTraceEvent(shardingContexts.getTaskId(), State.TASK_RUNNING, "");
            verify(jobFacade).postJobStatusTraceEvent(shardingContexts.getTaskId(), State.TASK_ERROR, getErrorMessage(shardingContexts));
            verify(jobFacade).registerJobBegin(shardingContexts);
            verify(jobItemExecutor, times(shardingContexts.getShardingTotalCount())).process(eq(fooJob), eq(jobConfig), eq(jobFacade), any());
            verify(jobFacade).registerJobCompleted(shardingContexts);
        }
    }

    private String getErrorMessage(final ShardingContexts shardingContexts) {
        return 1 == shardingContexts.getShardingItemParameters().size()
                ? "{0=java.lang.RuntimeException" + System.lineSeparator() + "}"
                : "{0=java.lang.RuntimeException" + System.lineSeparator() + ", 1=java.lang.RuntimeException" + System.lineSeparator() + "}";
    }

    @Test
    public void assertExecuteSuccessForSingleShardingItems() {
        assertExecuteSuccess(createSingleShardingContexts());
    }

    @Test
    public void assertExecuteSuccessForMultipleShardingItems() {
        assertExecuteSuccess(createMultipleShardingContexts());
    }

    private void assertExecuteSuccess(final ShardingContexts shardingContexts) {
        prepareForIsNotMisfire(jobFacade, shardingContexts);
        elasticJobExecutor.execute();
        verify(jobFacade).postJobStatusTraceEvent(shardingContexts.getTaskId(), State.TASK_STAGING, "Job 'test_job' execute begin.");
        verify(jobFacade).postJobStatusTraceEvent(shardingContexts.getTaskId(), State.TASK_FINISHED, "");
        verifyForIsNotMisfire(jobFacade, shardingContexts);
        verify(jobItemExecutor, times(shardingContexts.getShardingTotalCount())).process(eq(fooJob), eq(jobConfig), eq(jobFacade), any());
    }

    @Test
    public void assertExecuteWithMisfireIsEmpty() {
        ShardingContexts shardingContexts = createMultipleShardingContexts();
        when(jobFacade.getShardingContexts()).thenReturn(shardingContexts);
        elasticJobExecutor.execute();
        verifyForIsNotMisfire(jobFacade, shardingContexts);
        verify(jobItemExecutor, times(2)).process(eq(fooJob), eq(jobConfig), eq(jobFacade), any());
    }

    @Test
    public void assertExecuteWithMisfireIsNotEmptyButIsNotEligibleForJobRunning() {
        ShardingContexts shardingContexts = createMultipleShardingContexts();
        when(jobFacade.getShardingContexts()).thenReturn(shardingContexts);
        elasticJobExecutor.execute();
        verifyForIsNotMisfire(jobFacade, shardingContexts);
        verify(jobItemExecutor, times(2)).process(eq(fooJob), eq(jobConfig), eq(jobFacade), any());
        verify(jobFacade, times(0)).clearMisfire(shardingContexts.getShardingItemParameters().keySet());
    }

    @Test
    public void assertExecuteWithMisfire() {
        ShardingContexts shardingContexts = createMultipleShardingContexts();
        when(jobFacade.getShardingContexts()).thenReturn(shardingContexts);
        when(jobFacade.isExecuteMisfired(shardingContexts.getShardingItemParameters().keySet())).thenReturn(true, false);
        elasticJobExecutor.execute();
        verify(jobFacade).postJobStatusTraceEvent(shardingContexts.getTaskId(), State.TASK_STAGING, "Job 'test_job' execute begin.");
        verify(jobFacade, times(2)).postJobStatusTraceEvent(shardingContexts.getTaskId(), State.TASK_RUNNING, "");
        verify(jobFacade).misfireIfRunning(shardingContexts.getShardingItemParameters().keySet());
        verify(jobFacade, times(2)).registerJobBegin(shardingContexts);
        verify(jobItemExecutor, times(4)).process(eq(fooJob), eq(jobConfig), eq(jobFacade), any());
        verify(jobFacade, times(2)).registerJobCompleted(shardingContexts);
    }

    @Test(expected = JobSystemException.class)
    public void assertBeforeJobExecutedFailure() {
        ShardingContexts shardingContexts = createMultipleShardingContexts();
        when(jobFacade.getShardingContexts()).thenReturn(shardingContexts);
        doThrow(RuntimeException.class).when(jobFacade).beforeJobExecuted(shardingContexts);
        try {
            elasticJobExecutor.execute();
        } finally {
            verify(jobItemExecutor, times(0)).process(eq(fooJob), eq(jobConfig), eq(jobFacade), any());
        }
    }

    @Test(expected = JobSystemException.class)
    public void assertAfterJobExecutedFailure() {
        ShardingContexts shardingContexts = createMultipleShardingContexts();
        when(jobFacade.getShardingContexts()).thenReturn(shardingContexts);
        doThrow(RuntimeException.class).when(jobFacade).afterJobExecuted(shardingContexts);
        try {
            elasticJobExecutor.execute();
        } finally {
            verify(jobItemExecutor, times(2)).process(eq(fooJob), eq(jobConfig), eq(jobFacade), any());
        }
    }

    private ShardingContexts createSingleShardingContexts() {
        Map<Integer, String> map = new HashMap<>(1, 1);
        map.put(0, "A");
        return new ShardingContexts("fake_task_id", "test_job", 1, "", map);
    }

    private ShardingContexts createMultipleShardingContexts() {
        Map<Integer, String> map = new HashMap<>(2, 1);
        map.put(0, "A");
        map.put(1, "B");
        return new ShardingContexts("fake_task_id", "test_job", 2, "", map);
    }

    private void prepareForIsNotMisfire(final JobFacade jobFacade, final ShardingContexts shardingContexts) {
        when(jobFacade.getShardingContexts()).thenReturn(shardingContexts);
        when(jobFacade.misfireIfRunning(shardingContexts.getShardingItemParameters().keySet())).thenReturn(false);
        when(jobFacade.isExecuteMisfired(shardingContexts.getShardingItemParameters().keySet())).thenReturn(false);
    }

    private void verifyForIsNotMisfire(final JobFacade jobFacade, final ShardingContexts shardingContexts) {
        try {
            verify(jobFacade).checkJobExecutionEnvironment();
        } catch (final JobExecutionEnvironmentException ex) {
            throw new RuntimeException(ex);
        }
        verify(jobFacade).postJobStatusTraceEvent(shardingContexts.getTaskId(), State.TASK_STAGING, "Job 'test_job' execute begin.");
        verify(jobFacade).beforeJobExecuted(shardingContexts);
        verify(jobFacade).registerJobBegin(shardingContexts);
        verify(jobFacade).registerJobCompleted(shardingContexts);
        verify(jobFacade).afterJobExecuted(shardingContexts);
    }
}


text:
export default {
  onSelect({LocalState}, keyTab) {
    return LocalState.set('SELECT_TAB', keyTab);
  },
  clearState({LocalState}) {
    return LocalState.set('SELECT_TAB', null);
  }
};


text:
#include "fmo.h"
#include "memory_align.h"

namespace WelsDec {

/*!
 * \brief	Generate MB allocated map for interleaved slice group (TYPE 0)
 *
 * \param	pFmo	fmo context
 * \param	pPps	pps context
 *
 * \return	0 - successful; none 0 - failed
 */
static inline int32_t FmoGenerateMbAllocMapType0 (PFmo pFmo, PPps pPps) {
  uint32_t uiNumSliceGroups = 0;
  int32_t iMbNum = 0;
  int32_t i = 0;

  WELS_VERIFY_RETURN_IF (1, (NULL == pFmo || NULL == pPps))
  uiNumSliceGroups = pPps->uiNumSliceGroups;
  iMbNum = pFmo->iCountMbNum;
  WELS_VERIFY_RETURN_IF (1, (NULL == pFmo->pMbAllocMap || iMbNum <= 0 || uiNumSliceGroups >= MAX_SLICEGROUP_IDS))

  do {
    uint8_t uiGroup = 0;
    do {
      const int32_t kiRunIdx = pPps->uiRunLength[uiGroup];
      int32_t j = 0;
      do {
        pFmo->pMbAllocMap[i + j] = uiGroup;
        ++ j;
      } while (j < kiRunIdx && i + j < iMbNum);
      i += kiRunIdx;
      ++ uiGroup;
    } while (uiGroup < uiNumSliceGroups && i < iMbNum);
  } while (i < iMbNum);

  return 0; // well here
}

/*!
 * \brief	Generate MB allocated map for dispersed slice group (TYPE 1)
 *
 * \param	pFmo	fmo context
 * \param	pPps	pps context
 * \param	iMbWidth	MB width
 *
 * \return	0 - successful; none 0 - failed
 */
static inline int32_t FmoGenerateMbAllocMapType1 (PFmo pFmo, PPps pPps, const int32_t kiMbWidth) {
  uint32_t uiNumSliceGroups = 0;
  int32_t iMbNum = 0;
  int32_t i = 0;
  WELS_VERIFY_RETURN_IF (1, (NULL == pFmo || NULL == pPps))
  uiNumSliceGroups = pPps->uiNumSliceGroups;
  iMbNum			 = pFmo->iCountMbNum;
  WELS_VERIFY_RETURN_IF (1, (NULL == pFmo->pMbAllocMap || iMbNum <= 0 || kiMbWidth == 0
                             || uiNumSliceGroups >= MAX_SLICEGROUP_IDS))

  do {
    pFmo->pMbAllocMap[i] = (uint8_t) (((i % kiMbWidth) + (((i / kiMbWidth) * uiNumSliceGroups) >> 1)) % uiNumSliceGroups);
    ++ i;
  } while (i < iMbNum);

  return 0; // well here
}

/*!
 * \brief	Generate MB allocated map for various type of slice group cases (TYPE 0, .., 6)
 *
 * \param	pFmo		fmo context
 * \param	pPps		pps context
 * \param	kiMbWidth	MB width
 * \param	kiMbHeight	MB height
 *
 * \return	0 - successful; none 0 - failed
 */
static inline int32_t FmoGenerateSliceGroup (PFmo pFmo, const PPps kpPps, const int32_t kiMbWidth,
    const int32_t kiMbHeight) {
  int32_t iNumMb	= 0;
  int32_t iErr		= 0;
  bool	bResolutionChanged = false;

  // the cases we would not like
  WELS_VERIFY_RETURN_IF (1, (NULL == pFmo || NULL == kpPps))

  iNumMb	= pFmo->iCountMbNum;

  iNumMb = kiMbWidth * kiMbHeight;

  if (0 == iNumMb)
    return 1;

  WelsFree (pFmo->pMbAllocMap, "_fmo->pMbAllocMap");
  pFmo->pMbAllocMap	= (uint8_t*)WelsMallocz (iNumMb * sizeof (uint8_t), "_fmo->pMbAllocMap");
  WELS_VERIFY_RETURN_IF (1, (NULL == pFmo->pMbAllocMap))	// out of memory

  pFmo->iCountMbNum	= iNumMb;

  if (kpPps->uiNumSliceGroups < 2 && iNumMb > 0) { // only one slice group, exactly it is single slice based
    memset (pFmo->pMbAllocMap, 0,  iNumMb * sizeof (int8_t));	// for safe

    pFmo->iSliceGroupCount		= 1;

    return 0;
  }

  if (bResolutionChanged || ((int32_t)kpPps->uiSliceGroupMapType != pFmo->iSliceGroupType)
      || ((int32_t)kpPps->uiNumSliceGroups != pFmo->iSliceGroupCount)) {
    switch (kpPps->uiSliceGroupMapType) {
    case 0:
      iErr	= FmoGenerateMbAllocMapType0 (pFmo, kpPps);
      break;
    case 1:
      iErr = FmoGenerateMbAllocMapType1 (pFmo, kpPps, kiMbWidth);
      break;
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
      // Reserve for others slice group type
      iErr	= 1;
      break;
    default:
      return 1;
    }
  }

  if (0 == iErr) {	// well now
    pFmo->iSliceGroupCount	= kpPps->uiNumSliceGroups;
    pFmo->iSliceGroupType	= kpPps->uiSliceGroupMapType;
  }

  return iErr;
}

/*!
 * \brief	Initialize Wels Flexible Macroblock Ordering (FMO)
 *
 * \param	pFmo		Wels fmo to be initialized
 * \param	pPps	pps argument
 * \param	kiMbWidth	mb width
 * \param	kiMbHeight	mb height
 *
 * \return	0 - successful; none 0 - failed;
 */
int32_t	InitFmo (PFmo pFmo, PPps pPps, const int32_t kiMbWidth, const int32_t kiMbHeight) {
  return FmoGenerateSliceGroup (pFmo, pPps, kiMbWidth, kiMbHeight);
}

/*!
 * \brief	Uninitialize Wels Flexible Macroblock Ordering (FMO) list
 *
 * \param	pFmo		Wels base fmo ptr to be uninitialized
 * \param	kiCnt		count number of PPS per list
 * \param	kiAvail		count available number of PPS in list
 *
 * \return	NONE
 */
void UninitFmoList (PFmo pFmo, const int32_t kiCnt, const int32_t kiAvail) {
  PFmo pIter = pFmo;
  int32_t i = 0;
  int32_t iFreeNodes = 0;

  if (NULL == pIter || kiAvail <= 0 || kiCnt < kiAvail)
    return;

  while (i < kiCnt) {
    if (pIter != NULL && pIter->bActiveFlag) {
      if (NULL != pIter->pMbAllocMap) {
        WelsFree (pIter->pMbAllocMap, "pIter->pMbAllocMap");

        pIter->pMbAllocMap	= NULL;
      }
      pIter->iSliceGroupCount	= 0;
      pIter->iSliceGroupType	= -1;
      pIter->iCountMbNum		= 0;
      pIter->bActiveFlag		= false;
      ++ iFreeNodes;
      if (iFreeNodes >= kiAvail)
        break;
    }
    ++ pIter;
    ++ i;
  }
}

/*!
 * \brief	detect parameter sets are changed or not
 *
 * \param	pFmo				fmo context
 * \param	kiCountNumMb		(iMbWidth * iMbHeight) in Sps
 * \param	iSliceGroupType	slice group type if fmo is exactly enabled
 * \param	iSliceGroupCount	slice group count if fmo is exactly enabled
 *
 * \return	true - changed or not initialized yet; false - not change at all
 */
bool FmoParamSetsChanged (PFmo pFmo, const int32_t kiCountNumMb, const int32_t kiSliceGroupType,
                          const int32_t kiSliceGroupCount) {
  WELS_VERIFY_RETURN_IF (false, (NULL == pFmo))

  return ((!pFmo->bActiveFlag)
          || (kiCountNumMb != pFmo->iCountMbNum)
          || (kiSliceGroupType != pFmo->iSliceGroupType)
          || (kiSliceGroupCount != pFmo->iSliceGroupCount));
}

/*!
 * \brief	update/insert FMO parameter unit
 *
 * \param	_fmo	FMO context
 * \param	_sps	PSps
 * \param	_pps	PPps
 * \param	pActiveFmoNum	int32_t* [in/out]
 *
 * \return	true - update/insert successfully; false - failed;
 */
bool FmoParamUpdate (PFmo pFmo, PSps pSps, PPps pPps, int32_t* pActiveFmoNum) {
  const uint32_t kuiMbWidth = pSps->iMbWidth;
  const uint32_t kuiMbHeight = pSps->iMbHeight;

  if (FmoParamSetsChanged (pFmo,
                           kuiMbWidth * kuiMbHeight,
                           pPps->uiSliceGroupMapType,
                           pPps->uiNumSliceGroups)) {

    if (InitFmo (pFmo, pPps, kuiMbWidth, kuiMbHeight)) {
      return false;
    } else {
      if (!pFmo->bActiveFlag && *pActiveFmoNum < MAX_PPS_COUNT) {
        ++ (*pActiveFmoNum);
        pFmo->bActiveFlag	= true;
      }
    }
  }

  return true;
}

/*!
 * \brief	Convert kMbXy to slice group idc correspondingly
 *
 * \param	pFmo		Wels fmo context
 * \param	kMbXy		kMbXy to be converted
 *
 * \return	slice group idc - successful; -1 - failed;
 */
int32_t FmoMbToSliceGroup (PFmo pFmo, const MB_XY_T kiMbXy) {
  const int32_t kiMbNum	= pFmo->iCountMbNum;
  const uint8_t* kpMbMap	= pFmo->pMbAllocMap;

  if (kiMbXy < 0 || kiMbXy >= kiMbNum || kpMbMap == NULL)
    return -1;

  return kpMbMap[ kiMbXy ];
}

/*!
 * \brief	Get successive mb to be processed with given current kMbXy
 *
 * \param	pFmo			Wels fmo context
 * \param	kMbXy			current kMbXy
 *
 * \return	iNextMb - successful; -1 - failed;
 */
MB_XY_T FmoNextMb (PFmo pFmo, const MB_XY_T kiMbXy) {
  const int32_t kiTotalMb			= pFmo->iCountMbNum;
  const uint8_t* kpMbMap			= pFmo->pMbAllocMap;
  MB_XY_T iNextMb					= kiMbXy;
  const uint8_t kuiSliceGroupIdc	= (uint8_t)FmoMbToSliceGroup (pFmo, kiMbXy);

  if (kuiSliceGroupIdc == (uint8_t) (-1))
    return -1;

  do {
    ++ iNextMb;
    if (iNextMb >= kiTotalMb) {
      iNextMb	= -1;
      break;
    }
    if (kpMbMap[iNextMb] == kuiSliceGroupIdc) {
      break;
    }
  } while (1);

  // -1: No further MB in this slice (could be end of picture)
  return iNextMb;
}

} // namespace WelsDec


text:
layout: post
title: MP PSC District Public Prosecution Officer recruitment last date 13th Feb-2016
date: 2016-01-03 04:15
comments: true
tags:  District Law MP Officer Online Prosecution PSC
archive: false
---
Recruitment of Assistant District Public Prosecution Officer in Madhya Pradesh (MP) Home (Police) Department

Online Applications are invited from Indian Nationals for the following vacancy in the MP Government Home Department by MPPSC  :

- Assistant District Public Prosecution Officer : 251 posts, Pay Scale : Rs. 9300-34800 Grade Pay Rs. 3600, Age : 24-30 years as on 01/01/2016 , Qualification : Graduate in Law or equivalent.

Selection Procedure : Written test on 05/06/2016 followed by interview for selected candidates.

Application Fee :  Rs.1200/- (Rs.600/- for SC/ST/OBC/PWD) plus Rs.35/- as portal fee, can be paid online by Credit Card/ Debit Card or can be deposite in the prscribed bank account by net banking.

**How to Apply** : Apply Online only from 14/01/2016  12.00 noon to 13/02/2016 upto 12.00 midnight on the websites http://www.mppscdemo.gov.in and/or http://www.mppsc.nic.in/ and/or http://www.mppsc.com/ .

Please see document  <http://mpinfo.org/MPinfoStatic/rojgar/2015/2812/vac04.pdf>  for details.


text:
layout: post
title: "Project proposal in Machine Learning/Continuous Optimization"
description: "Gradient Descent optimisation using Neural Network proxies"
comments: true
categories: Research
keywords: "dummy content, lorem ipsum"
---

### Gradient Descent optimisation using Neural Network proxies

##### Presentation

Many practical continuous minimization problems are not amenable to standard optimization methods
because gradients can not be computed directly. Recent results obtained in our lab suggest
that it is possible to train a Neural Network regressor as a proxy to the initial function. We then optimise the proxy function via Gradient-Descent.
However, during the optimisation process, the optimiser might explore regions of the space where the model of the proxy is wrong. It is then necessary to resample the space around the current optimisation point and retrain the Neural Net using these new samples. The goal of this project is to find out the best way to do it, taking into account the cost of getting a new sample.

##### Outcomes of the project
A principled and efficient approach to the problem of efficient resampling during optmisation would have an important impact from a theoretical and a industrial perspective.

##### Researched profile
* Knowledge of Machine Learning and Optimisation Theory
* Experience using Python
* Taste for experimentation and/or theory in CS

##### Gained knowledge
* Learn how to use correctly a Deep-Learning framework (TensorFlow)
* Gain expertise in the field of Active Learning
* Understand how to use Machine Learning out of the boundaries of usual applications

##### Dates
At least 3 Months, anytime.

##### Contact
Please contact me pierre.baque(at)epfl.ch for any further information.


text:
FOUNDATION_EXPORT double UIImageEffectsVersionNumber;
FOUNDATION_EXPORT const unsigned char UIImageEffectsVersionString[];


text:
@interface NSString (SP_String)

-(NSURL *)SP_UrlString;
@end


text:
if node[:pdepend][:install_dir] != ""
    pdepend_dir = node[:pdepend][:install_dir]
else
    pdepend_dir = "#{Chef::Config[:file_cache_path]}/pdepend"
end

directory "#{pdepend_dir}" do
    owner "root"
    group "root"
    mode "0755"
    action :create
end

remote_file "#{pdepend_dir}/pdepend.phar" do
    source node[:pdepend][:phar_url]
    mode "0755"
end


text:
var Demo = Demo || {};
Demo.Player = Demo.Player || {};

/**
 * @namespace  Camera initialization
 * @class Creates cameras for the scene.
 */
Demo.Player.User = function ( params ) {

    this.manager = params.context;

    this.name = params.name || "Player 1";

    this.uid = Demo.Util.generateUUID();

    this.cssColor = params.cssColor || "#0000FF";

    this.myTurn = true;

    this.isHuman = true;

};

Demo.Player.User.prototype = {

  /**
   * User takes a turn.  Called from the Player Manager
   * @return {[type]} [description]
   */
  takeTurn: function () {
    this.enableClick();
  },

  /**
   * Enables the click function.  Keeps interaction minimized when it isn't the user's turn.
   * @return {[type]} [description]
   */
  enableClick: function () {
    var me = this;
    $(document).bind("userClick", function (mouse){
      me.selectCube(mouse.message);
    });
  },

  /**
   * Unbind the disableClick
   */
  disableClick: function () {
    $(document).unbind("userClick");
  },

  /**
   * Cast a ray and select a cube if not already selected.
   * @param  {[type]} event Event information including mouse coordinates.
   * @return {[type]}       [description]
   */
  selectCube: function (mouseInfo){

    var mouse = {},
      leftOffset,
      topOffset,
      vector,
      ray,
      intersected;

    vector = new THREE.Vector3(mouseInfo.x, mouseInfo.y, 1);
    this.manager.context.projector.unprojectVector(vector, this.manager.context.cameras.liveCam);

    ray = new THREE.Raycaster(this.manager.context.cameras.liveCam.position, vector.sub(this.manager.context.cameras.liveCam.position).normalize());

    // Casting a ray to find if there is an intersection.
    intersected = ray.intersectObjects( this.manager.context.collisions );

    // only change the first (closest) intersected object.
    if(intersected.length > 0) {

      if(intersected[0].object.ttt === null) {
        Demo.Util.selectCube(intersected[0].object, {color: this.cssColor, name: this.name });

        this.manager.checkForTTT();
        this.disableClick();

        if(!this.manager.gameOver) {
            // after a short pause, execute user code.
            $.event.trigger({
              type: "nextTurn",
            });
        }
      }
    }
  },
};


text:
/* $Id: COMDefs.cpp $ */
/** @file
 * VBox Qt GUI - CInterface implementation.
 */

/*
 * Copyright (C) 2006-2012 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */

#ifdef VBOX_WITH_PRECOMPILED_HEADERS
# include <precomp.h>
#else  /* !VBOX_WITH_PRECOMPILED_HEADERS */

/* Qt includes: */
# include <QSocketNotifier>

/* GUI includes: */
# include "COMDefs.h"

/* COM includes: */
# include "CVirtualBoxErrorInfo.h"

#endif /* !VBOX_WITH_PRECOMPILED_HEADERS */

/* VirtualBox interface declarations: */
#ifndef VBOX_WITH_XPCOM
# include "VirtualBox.h"
#else /* !VBOX_WITH_XPCOM */
# include "VirtualBox_XPCOM.h"
#endif /* VBOX_WITH_XPCOM */

/* Other VBox includes: */
#include <iprt/log.h>

#ifdef VBOX_WITH_XPCOM

/* Other VBox includes: */
# include <iprt/env.h>
# include <iprt/err.h>
# include <iprt/path.h>
# include <iprt/param.h>
# include <nsEventQueueUtils.h>
# include <nsIEventQueue.h>
# include <nsIExceptionService.h>

/* Mac OS X (Carbon mode) and OS/2 will notify the native queue
   internally in plevent.c. Because moc doesn't seems to respect
   #ifdefs, we still have to include the definition of the class.
   very silly. */
# if !defined (Q_OS_MAC)  && !defined (Q_OS_OS2)
XPCOMEventQSocketListener *COMBase::sSocketListener = 0;

# endif

/**
 *  Internal class to asynchronously handle IPC events on the GUI thread
 *  using the event queue socket FD and QSocketNotifier.
 */
class XPCOMEventQSocketListener : public QObject
{
    Q_OBJECT

public:

    XPCOMEventQSocketListener (nsIEventQueue *eq)
    {
        mEventQ = eq;
        mNotifier = new QSocketNotifier (mEventQ->GetEventQueueSelectFD(),
                                         QSocketNotifier::Read, this);
        QObject::connect (mNotifier, SIGNAL (activated (int)),
                          this, SLOT (processEvents()));
    }

    virtual ~XPCOMEventQSocketListener()
    {
        delete mNotifier;
    }

public slots:

    void processEvents() { mEventQ->ProcessPendingEvents(); }

private:

    QSocketNotifier *mNotifier;
    nsCOMPtr <nsIEventQueue> mEventQ;
};

#endif /* !defined (VBOX_WITH_XPCOM) */

/**
 *  Initializes COM/XPCOM.
 */
HRESULT COMBase::InitializeCOM(bool fGui)
{
    LogFlowFuncEnter();

    HRESULT rc = com::Initialize(fGui);

#if defined (VBOX_WITH_XPCOM)

# if !defined (RT_OS_DARWIN) && !defined (RT_OS_OS2)

    if (NS_SUCCEEDED (rc))
    {
        nsCOMPtr <nsIEventQueue> eventQ;
        rc = NS_GetMainEventQ (getter_AddRefs (eventQ));
        if (NS_SUCCEEDED (rc))
        {
#  ifdef DEBUG
            BOOL isNative = FALSE;
            eventQ->IsQueueNative (&isNative);
            AssertMsg (isNative, ("The event queue must be native"));
#  endif
            BOOL isOnMainThread = FALSE;
            rc = eventQ->IsOnCurrentThread (&isOnMainThread);
            if (NS_SUCCEEDED (rc) && isOnMainThread)
            {
                sSocketListener = new XPCOMEventQSocketListener (eventQ);
            }
        }
    }

# endif /* !defined (RT_OS_DARWIN) && !defined (RT_OS_OS) */

#endif /* defined (VBOX_WITH_XPCOM) */

    if (FAILED (rc))
        CleanupCOM();

    AssertComRC (rc);

    LogFlowFunc (("rc=%08X\n", rc));
    LogFlowFuncLeave();
    return rc;

}

/**
 *  Cleans up COM/XPCOM.
 */
HRESULT COMBase::CleanupCOM()
{
    LogFlowFuncEnter();

    HRESULT rc = S_OK;

#if defined (VBOX_WITH_XPCOM)

    /* scope the code to make smart references are released before calling
     * com::Shutdown() */
    {
        nsCOMPtr <nsIEventQueue> eventQ;
        rc = NS_GetMainEventQ (getter_AddRefs (eventQ));
        if (NS_SUCCEEDED (rc))
        {
            BOOL isOnMainThread = FALSE;
            rc = eventQ->IsOnCurrentThread (&isOnMainThread);
            if (NS_SUCCEEDED (rc) && isOnMainThread)
            {
# if !defined (RT_OS_DARWIN) && !defined (RT_OS_OS2)
                if (sSocketListener)
                {
                    delete sSocketListener;
                    sSocketListener = NULL;
                }
# endif
            }
        }
    }

#endif /* defined (VBOX_WITH_XPCOM) */

    HRESULT rc2 = com::Shutdown();
    if (SUCCEEDED (rc))
        rc = rc2;

    AssertComRC (rc);

    LogFlowFunc (("rc=%08X\n", rc));
    LogFlowFuncLeave();
    return rc;
}

/* static */
void COMBase::ToSafeArray (const QVector <QString> &aVec,
                           com::SafeArray <BSTR> &aArr)
{
    aArr.reset (aVec.size());
    for (int i = 0; i < aVec.size(); ++ i)
        aArr [i] = SysAllocString ((const OLECHAR *)
            (aVec.at (i).isNull() ? 0 : aVec.at (i).utf16()));
}

/* static */
void COMBase::FromSafeArray (const com::SafeArray <BSTR> &aArr,
                             QVector <QString> &aVec)
{
    aVec.resize (static_cast <int> (aArr.size()));
    for (int i = 0; i < aVec.size(); ++ i)
        aVec [i] = QString::fromUtf16 (aArr [i]);
}

/* static */
void COMBase::ToSafeArray (const QVector <QUuid> &aVec,
                           com::SafeGUIDArray &aArr)
{
    AssertCompileSize (GUID, sizeof (QUuid));
    aArr.reset (aVec.size());
    for (int i = 0; i < aVec.size(); ++ i)
        aArr [i] = *(GUID*) &aVec [i];
}

/* static */
void COMBase::FromSafeArray (const com::SafeGUIDArray &aArr,
                             QVector <QUuid> &aVec)
{
    AssertCompileSize (GUID, sizeof (QUuid));
    aVec.resize (static_cast <int> (aArr.size()));
    for (int i = 0; i < aVec.size(); ++ i)
        aVec [i] = *(QUuid*) &aArr [i];
}

////////////////////////////////////////////////////////////////////////////////

void COMErrorInfo::init(const CVirtualBoxErrorInfo &info)
{
    if (info.isNull())
    {
        mIsNull = true;
        mIsBasicAvailable = false;
        mIsFullAvailable = false;
        mResultCode = S_OK;
        m_pNext = NULL;
        AssertMsgFailedReturnVoid(("error info is NULL!\n"));
    }

    bool gotSomething = false;
    bool gotAll = true;

    mResultCode = info.GetResultCode();
    gotSomething |= info.isOk();
    gotAll &= info.isOk();

    mInterfaceID = info.GetInterfaceID();
    gotSomething |= info.isOk();
    gotAll &= info.isOk();
    if (info.isOk())
        mInterfaceName = getInterfaceNameFromIID (mInterfaceID);

    mComponent = info.GetComponent();
    gotSomething |= info.isOk();
    gotAll &= info.isOk();

    mText = info.GetText();
    gotSomething |= info.isOk();
    gotAll &= info.isOk();

    m_pNext = NULL;

    CVirtualBoxErrorInfo next = info.GetNext();
    if (info.isOk() && !next.isNull())
    {
        m_pNext = new COMErrorInfo(next);
        Assert(m_pNext);
    }

    gotSomething |= info.isOk();
    gotAll &= info.isOk();

    mIsBasicAvailable = gotSomething;
    mIsFullAvailable = gotAll;

    mIsNull = !gotSomething;

    AssertMsg (gotSomething, ("Nothing to fetch!\n"));
}

void COMErrorInfo::copyFrom(const COMErrorInfo &x)
{
    mIsNull = x.mIsNull;
    mIsBasicAvailable = x.mIsBasicAvailable;
    mIsFullAvailable = x.mIsFullAvailable;

    mResultCode = x.mResultCode;
    mInterfaceID = x.mInterfaceID;
    mComponent = x.mComponent;
    mText = x.mText;

    if (x.m_pNext)
        m_pNext = new COMErrorInfo(*x.m_pNext);
    else
        m_pNext = NULL;

    mInterfaceName = x.mInterfaceName;
    mCalleeIID = x.mCalleeIID;
    mCalleeName = x.mCalleeName;
}

void COMErrorInfo::cleanup()
{
    if (m_pNext)
    {
        delete m_pNext;
        m_pNext = NULL;
    }
}

/**
 *  Fetches error info from the current thread.
 *  If callee is NULL, then error info is fetched in "interfaceless"
 *  manner (so calleeIID() and calleeName() will return null).
 *
 *  @param  callee
 *      pointer to the interface whose method returned an error
 *  @param  calleeIID
 *      UUID of the callee's interface. Ignored when callee is NULL
 */
void COMErrorInfo::fetchFromCurrentThread(IUnknown *callee, const GUID *calleeIID)
{
    mIsNull = true;
    mIsFullAvailable = mIsBasicAvailable = false;

    AssertReturn (!callee || calleeIID, (void) 0);

    HRESULT rc = E_FAIL;

#if !defined (VBOX_WITH_XPCOM)

    if (callee)
    {
        CComPtr <IUnknown> iface = callee;
        CComQIPtr <ISupportErrorInfo> serr;
        serr = callee;
        if (!serr)
            return;
        rc = serr->InterfaceSupportsErrorInfo (*calleeIID);
        if (!SUCCEEDED (rc))
            return;
    }

    CComPtr <IErrorInfo> err;
    rc = ::GetErrorInfo (0, &err);
    if (rc == S_OK && err)
    {
        CComPtr <IVirtualBoxErrorInfo> info;
        info = err;
        if (info)
            init (CVirtualBoxErrorInfo (info));

        if (!mIsFullAvailable)
        {
            bool gotSomething = false;

            rc = err->GetGUID (COMBase::GUIDOut (mInterfaceID));
            gotSomething |= SUCCEEDED (rc);
            if (SUCCEEDED (rc))
                mInterfaceName = getInterfaceNameFromIID (mInterfaceID);

            rc = err->GetSource (COMBase::BSTROut (mComponent));
            gotSomething |= SUCCEEDED (rc);

            rc = err->GetDescription (COMBase::BSTROut (mText));
            gotSomething |= SUCCEEDED (rc);

            if (gotSomething)
                mIsBasicAvailable = true;

            mIsNull = !gotSomething;

            AssertMsg (gotSomething, ("Nothing to fetch!\n"));
        }
    }

#else /* !defined (VBOX_WITH_XPCOM) */

    nsCOMPtr <nsIExceptionService> es;
    es = do_GetService (NS_EXCEPTIONSERVICE_CONTRACTID, &rc);
    if (NS_SUCCEEDED (rc))
    {
        nsCOMPtr <nsIExceptionManager> em;
        rc = es->GetCurrentExceptionManager (getter_AddRefs (em));
        if (NS_SUCCEEDED (rc))
        {
            nsCOMPtr <nsIException> ex;
            rc = em->GetCurrentException (getter_AddRefs(ex));
            if (NS_SUCCEEDED (rc) && ex)
            {
                nsCOMPtr <IVirtualBoxErrorInfo> info;
                info = do_QueryInterface (ex, &rc);
                if (NS_SUCCEEDED (rc) && info)
                    init (CVirtualBoxErrorInfo (info));

                if (!mIsFullAvailable)
                {
                    bool gotSomething = false;

                    rc = ex->GetResult (&mResultCode);
                    gotSomething |= NS_SUCCEEDED (rc);

                    char *message = NULL; // utf8
                    rc = ex->GetMessage (&message);
                    gotSomething |= NS_SUCCEEDED (rc);
                    if (NS_SUCCEEDED (rc) && message)
                    {
                        mText = QString::fromUtf8 (message);
                        nsMemory::Free (message);
                    }

                    if (gotSomething)
                        mIsBasicAvailable = true;

                    mIsNull = !gotSomething;

                    AssertMsg (gotSomething, ("Nothing to fetch!\n"));
                }

                // set the exception to NULL (to emulate Win32 behavior)
                em->SetCurrentException (NULL);

                rc = NS_OK;
            }
        }
    }

    AssertComRC (rc);

#endif /* !defined (VBOX_WITH_XPCOM) */

    if (callee && calleeIID && mIsBasicAvailable)
    {
        mCalleeIID = COMBase::ToQUuid (*calleeIID);
        mCalleeName = getInterfaceNameFromIID (mCalleeIID);
    }
}

// static
QString COMErrorInfo::getInterfaceNameFromIID (const QUuid &id)
{
    QString name;

    com::GetInterfaceNameByIID (COMBase::GUIDIn (id), COMBase::BSTROut (name));

    return name;
}

#if defined (VBOX_WITH_XPCOM)
#include "COMDefs.moc"
#endif


text:
module Blogit::Renderers
  require "blogit/renderers/html_with_albino"
end


text:
package com.l000phone.themovietime.shop.shopActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.l000phone.themovietime.BaseActivity;
import com.l000phone.themovietime.R;

public class ShopSerchActivity extends BaseActivity {

    private EditText editText;
    private Editable text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_serch);
        initView();
    }

    private void initView() {
        editText = (EditText) findViewById(R.id.shop_search_edsearch);

    }

    public void search(View view){

        switch (view.getId()){
            case R.id.shop_search_imgBack:
                ShopSerchActivity.this.finish();
                break;

            case R.id.shop_search_search:
                String content = editText.getText().toString();

                if(!TextUtils.isEmpty(content)){
                    Intent intent = new Intent(ShopSerchActivity.this,ShopBuyLotsGridActivity.class);

                    Bundle bundle = new Bundle();

                    bundle.putString("name",content);

                    bundle.putString("categoryId1","0");

                    intent.putExtras(bundle);

                    startActivity(intent);

                    ShopSerchActivity.this.finish();
                }
                break;
        }
    }
}


text:
'use strict';

var memoize    = require('memoizee/plain')
  , ensureType = require('dbjs/valid-dbjs-type');

module.exports = memoize(function (User) {
	var db = ensureType(User).database
	  , UserRoleMeta;

	UserRoleMeta = db.Object.extend('UserRoleMeta', {
		destroy: { type: db.Function, value: function () {
			this.validateDestroy();
			this._destroy();
		} },
		_destroy: { type: db.Function },
		canBeDestroyed: { type: db.Boolean, value: true },
		validateDestroy: { type: db.Function, value: function (ignore) {
			if (!this.canBeDestroyed) {
				throw new Error('Cannot destroy user, role restriction: "' + this.key + '"');
			}
		} }
	});

	User.prototype.defineProperties({
		rolesMeta: { type: db.Object, nested: true },
		canBeDestroyed: { type: db.Boolean, value: function (_observe) {
			return this.roles.every(function (role) {
				if (!this.rolesMeta[role]) return true;
				return _observe(this.rolesMeta[role]._canBeDestroyed);
			}.bind(this));
		} },
		_destroy: { type: db.Function, value: function (ignore) {
			var db = this.database;
			this.roles.forEach(function (role) {
				if (!this.rolesMeta[role]) return;
				this.rolesMeta[role]._destroy();
			}.bind(this));
			db.objects.delete(this);
		} },
		destroy: { type: db.Function, value: function (ignore) {
			this.validateDestroy();
			this._destroy();
		} },
		validateDestroy: { type: db.Function, value: function (ignore) {
			this.roles.forEach(function (role) {
				if (!this.rolesMeta[role]) return;
				this.rolesMeta[role].validateDestroy();
			}.bind(this));
		} }
	});
	User.prototype.rolesMeta._descriptorPrototype_.type = UserRoleMeta;

	User.prototype.rolesMeta.define('user', {
		nested: true
	});

	User.prototype.rolesMeta.get('user').setProperties({
		_destroy: function (ignore) {
			var dbObjects = this.database.objects;
			this.master.initialBusinessProcesses.forEach(function (bp) {
				dbObjects.delete(bp);
			});
		},
		canBeDestroyed: function (_observe) {
			return !_observe(this.master._submittedBusinessProcessesSize);
		}
	});

	return User;
}, { normalizer: require('memoizee/normalizers/get-1')() });


text:
require File.join(File.dirname(__FILE__), 'spec_helper')

describe Neo4j::Transaction, :type => :clean_db do

  it "#run runs the provided block in an transaction" do
    node =  Neo4j::Transaction.run { Neo4j::Node.new }
    node.should exist
  end

  it "#run should rollback the transaction if an exception is raised" do
    node = nil

    expect do
      Neo4j::Transaction.run do
        node = Neo4j::Node.new
        Neo4j::Node.should exist(node)
        raise "oops"
      end
    end.to raise_error

    node.should_not exist
  end

  it "#success, if not called the node will node be updated" do
    a = Neo4j::Transaction.run do
      Neo4j::Node.new :name => 'andreas'
    end
    id = a.neo_id
    tx = Neo4j::Transaction.new
    a2 = Neo4j::Node.load(id)
    a2[:name] = 'kalle'
    a2[:name].should == 'kalle'
    tx.finish
    a2[:name].should == 'andreas'
  end

  it "#failure, if called the node will node be updated, even if #success if called" do
    a = Neo4j::Transaction.run do
      Neo4j::Node.new :name => 'andreas'
    end
    id = a.neo_id
    tx = Neo4j::Transaction.new
    a2 = Neo4j::Node.load(id)
    a2[:name] = 'kalle'
    a2[:name].should == 'kalle'
    tx.success
    tx.failure
    tx.finish
    a2[:name].should == 'andreas'
  end

  it "#new returns a Java Transaction" do
    tx = Neo4j::Transaction.new
    tx.should be_kind_of(org.neo4j.graphdb.Transaction)
    tx.finish
  end

  it "a nested transaction that fails will fail the top transaction" do
    tx1 = Neo4j::Transaction.new
    tx2 = Neo4j::Transaction.new
    node = Neo4j::Node.new

    # when
    tx2.failure
    tx2.finish
    tx1.success

    # then
    expect { tx1.finish }.to raise_error
    node.should_not exist
  end

  it "#finish without a call to #success will not commit the transaction" do
    tx = Neo4j::Transaction.new
    node = Neo4j::Node.new
    tx.finish

    node.should_not exist
  end

  it "#success will commit the transaction" do
    tx = Neo4j::Transaction.new
    node = Neo4j::Node.new
    tx.success
    tx.finish

    node.should exist
  end

end