text:
# Neural Network

Note: Functions taking `Tensor` arguments can also take anything accepted by
[`tf.convert_to_tensor`](../../api_docs/python/framework.md#convert_to_tensor).

## Contents
### [Neural Network](#AUTOGENERATED-neural-network)
* [Activation Functions](#AUTOGENERATED-activation-functions)
  * [`tf.nn.relu(features, name=None)`](#relu)
  * [`tf.nn.relu6(features, name=None)`](#relu6)
  * [`tf.nn.softplus(features, name=None)`](#softplus)
  * [`tf.nn.dropout(x, keep_prob, noise_shape=None, seed=None, name=None)`](#dropout)
  * [`tf.nn.bias_add(value, bias, name=None)`](#bias_add)
  * [`tf.sigmoid(x, name=None)`](#sigmoid)
  * [`tf.tanh(x, name=None)`](#tanh)
* [Convolution](#AUTOGENERATED-convolution)
  * [`tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None)`](#conv2d)
  * [`tf.nn.depthwise_conv2d(input, filter, strides, padding, name=None)`](#depthwise_conv2d)
  * [`tf.nn.separable_conv2d(input, depthwise_filter, pointwise_filter, strides, padding, name=None)`](#separable_conv2d)
* [Pooling](#AUTOGENERATED-pooling)
  * [`tf.nn.avg_pool(value, ksize, strides, padding, name=None)`](#avg_pool)
  * [`tf.nn.max_pool(value, ksize, strides, padding, name=None)`](#max_pool)
  * [`tf.nn.max_pool_with_argmax(input, ksize, strides, padding, Targmax=None, name=None)`](#max_pool_with_argmax)
* [Normalization](#AUTOGENERATED-normalization)
  * [`tf.nn.l2_normalize(x, dim, epsilon=1e-12, name=None)`](#l2_normalize)
  * [`tf.nn.local_response_normalization(input, depth_radius=None, bias=None, alpha=None, beta=None, name=None)`](#local_response_normalization)
  * [`tf.nn.moments(x, axes, name=None)`](#moments)
* [Losses](#AUTOGENERATED-losses)
  * [`tf.nn.l2_loss(t, name=None)`](#l2_loss)
* [Classification](#AUTOGENERATED-classification)
  * [`tf.nn.sigmoid_cross_entropy_with_logits(logits, targets, name=None)`](#sigmoid_cross_entropy_with_logits)
  * [`tf.nn.softmax(logits, name=None)`](#softmax)
  * [`tf.nn.softmax_cross_entropy_with_logits(logits, labels, name=None)`](#softmax_cross_entropy_with_logits)
* [Embeddings](#AUTOGENERATED-embeddings)
  * [`tf.nn.embedding_lookup(params, ids, name=None)`](#embedding_lookup)
* [Evaluation](#AUTOGENERATED-evaluation)
  * [`tf.nn.top_k(input, k, name=None)`](#top_k)
  * [`tf.nn.in_top_k(predictions, targets, k, name=None)`](#in_top_k)
* [Candidate Sampling](#AUTOGENERATED-candidate-sampling)
  * [Sampled Loss Functions](#AUTOGENERATED-sampled-loss-functions)
  * [`tf.nn.nce_loss(weights, biases, inputs, labels, num_sampled, num_classes, num_true=1, sampled_values=None, remove_accidental_hits=False, name='nce_loss')`](#nce_loss)
  * [`tf.nn.sampled_softmax_loss(weights, biases, inputs, labels, num_sampled, num_classes, num_true=1, sampled_values=None, remove_accidental_hits=True, name='sampled_softmax_loss')`](#sampled_softmax_loss)
  * [Candidate Samplers](#AUTOGENERATED-candidate-samplers)
  * [`tf.nn.uniform_candidate_sampler(true_classes, num_true, num_sampled, unique, range_max, seed=None, name=None)`](#uniform_candidate_sampler)
  * [`tf.nn.log_uniform_candidate_sampler(true_classes, num_true, num_sampled, unique, range_max, seed=None, name=None)`](#log_uniform_candidate_sampler)
  * [`tf.nn.learned_unigram_candidate_sampler(true_classes, num_true, num_sampled, unique, range_max, seed=None, name=None)`](#learned_unigram_candidate_sampler)
  * [`tf.nn.fixed_unigram_candidate_sampler(true_classes, num_true, num_sampled, unique, range_max, vocab_file='', distortion=0.0, num_reserved_ids=0, num_shards=1, shard=0, unigrams=[], seed=None, name=None)`](#fixed_unigram_candidate_sampler)
  * [Miscellaneous candidate sampling utilities](#AUTOGENERATED-miscellaneous-candidate-sampling-utilities)
  * [`tf.nn.compute_accidental_hits(true_classes, sampled_candidates, num_true, seed=None, name=None)`](#compute_accidental_hits)

## Activation Functions

The activation ops provide different types of nonlinearities for use in
neural networks.  These include smooth nonlinearities (`sigmoid`,
`tanh`, and `softplus`), continuous but not everywhere differentiable
functions (`relu`, `relu6`, and `relu_x`), and random regularization
(`dropout`).

All activation ops apply componentwise, and produce a tensor of the same
shape as the input tensor.

- - -

### `tf.nn.relu(features, name=None)`

Computes rectified linear: `max(features, 0)`.

##### Args:

*  `features`: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `int64`, `uint8`, `int16`, `int8`.
*  `name`: A name for the operation (optional).

##### Returns:

  A `Tensor`. Has the same type as `features`.

- - -

### `tf.nn.relu6(features, name=None)`

Computes Rectified Linear 6: `min(max(features, 0), 6)`.

##### Args:

*  `features`: A `Tensor` with type `float`, `double`, `int32`, `int64`, `uint8`,
    `int16`, or `int8`.
*  `name`: A name for the operation (optional).

##### Returns:

  A `Tensor` with the same type as `features`.

- - -

### `tf.nn.softplus(features, name=None)`

Computes softplus: `log(exp(features) + 1)`.

##### Args:

*  `features`: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `int64`, `uint8`, `int16`, `int8`.
*  `name`: A name for the operation (optional).

##### Returns:

  A `Tensor`. Has the same type as `features`.

- - -

### `tf.nn.dropout(x, keep_prob, noise_shape=None, seed=None, name=None)`

Computes dropout.

With probability `keep_prob`, outputs the input element scaled up by
`1 / keep_prob`, otherwise outputs `0`.  The scaling is so that the expected
sum is unchanged.

By default, each element is kept or dropped independently.  If `noise_shape`
is specified, it must be
[broadcastable](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
to the shape of `x`, and only dimensions with `noise_shape[i] == shape(x)[i]`
will make independent decisions.  For example, if `shape(x) = [k, l, m, n]`
and `noise_shape = [k, 1, 1, n]`, each batch and channel component will be
kept independently and each row and column will be kept or not kept together.

##### Args:

*  `x`: A tensor.
*  `keep_prob`: A scalar `Tensor` with the same type as x. The probability
    that each element is kept.
*  `noise_shape`: A 1-D `Tensor` of type `int32`, representing the
    shape for randomly generated keep/drop flags.
*  `seed`: A Python integer. Used to create random seeds. See
    [`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed)
    for behavior.
*  `name`: A name for this operation (optional).

##### Returns:

  A Tensor of the same shape of `x`.

##### Raises:

*  `ValueError`: If `keep_prob` is not in `(0, 1]`.

- - -

### `tf.nn.bias_add(value, bias, name=None)`

Adds `bias` to `value`.

This is (mostly) a special case of `tf.add` where `bias` is restricted to 1-D.
Broadcasting is supported, so `value` may have any number of dimensions.
Unlike `tf.add`, the type of `bias` is allowed to differ from `value` in the
case where both types are quantized.

##### Args:

*  `value`: A `Tensor` with type `float`, `double`, `int64`, `int32`, `uint8`,
    `int16`, `int8`, or `complex64`.
*  `bias`: A 1-D `Tensor` with size matching the last dimension of `value`.
    Must be the same type as `value` unless `value` is a quantized type,
    in which case a different quantized type may be used.
*  `name`: A name for the operation (optional).

##### Returns:

  A `Tensor` with the same type as `value`.

- - -

### `tf.sigmoid(x, name=None)`

Computes sigmoid of `x` element-wise.

Specifically, `y = 1 / (1 + exp(-x))`.

##### Args:

*  `x`: A Tensor with type `float`, `double`, `int32`, `complex64`, `int64`,
    or `qint32`.
*  `name`: A name for the operation (optional).

##### Returns:

  A Tensor with the same type as `x` if `x.dtype != qint32`
    otherwise the return type is `quint8`.

- - -

### `tf.tanh(x, name=None)`

Computes hyperbolic tangent of `x` element-wise.

##### Args:

*  `x`: A Tensor with type `float`, `double`, `int32`, `complex64`, `int64`,
    or `qint32`.
*  `name`: A name for the operation (optional).

##### Returns:

  A Tensor with the same type as `x` if `x.dtype != qint32` otherwise
    the return type is `quint8`.

## Convolution

The convolution ops sweep a 2-D filter over a batch of images, applying the
filter to each window of each image of the appropriate size.  The different
ops trade off between generic vs. specific filters:

* `conv2d`: Arbitrary filters that can mix channels together.
* `depthwise_conv2d`: Filters that operate on each channel independently.
* `separable_conv2d`: A depthwise spatial filter followed by a pointwise filter.

Note that although these ops are called "convolution", they are strictly
speaking "cross-correlation" since the filter is combined with an input window
without reversing the filter.  For details, see [the properties of
cross-correlation](https://en.wikipedia.org/wiki/Cross-correlation#Properties).

The filter is applied to image patches of the same size as the filter and
strided according to the `strides` argument.  `strides = [1, 1, 1, 1]` applies
the filter to a patch at every offset, `strides = [1, 2, 2, 1]` applies the
filter to every other image patch in each dimension, etc.

Ignoring channels for the moment, the spatial semantics of the convolution ops
are as follows.  If the 4-D `input` has shape
`[batch, in_height, in_width, ...]` and the 4-D `filter` has shape
`[filter_height, filter_width, ...]`, then

    shape(output) = [batch,
                     (in_height - filter_height + 1) / strides[1],
                     (in_width - filter_width + 1) / strides[2],
                     ...]

    output[b, i, j, :] =
        sum_{di, dj} input[b, strides[1] * i + di, strides[2] * j + dj, ...] *
                     filter[di, dj, ...]

Since `input` is 4-D, each `input[b, i, j, :]` is a vector.  For `conv2d`, these
vectors are multiplied by the `filter[di, dj, :, :]` matrices to produce new
vectors.  For `depthwise_conv_2d`, each scalar component `input[b, i, j, k]`
is multiplied by a vector `filter[di, dj, k]`, and all the vectors are
concatenated.

In the formula for `shape(output)`, the rounding direction depends on padding:

* `padding = 'SAME'`: Round down (only full size windows are considered).
* `padding = 'VALID'`: Round up (partial windows are included).

- - -

### `tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None)`

Computes a 2-D convolution given 4-D `input` and `filter` tensors.

Given an input tensor of shape `[batch, in_height, in_width, in_channels]`
and a filter / kernel tensor of shape
`[filter_height, filter_width, in_channels, out_channels]`, this op
performs the following:

1. Flattens the filter to a 2-D matrix with shape
   `[filter_height * filter_width * in_channels, output_channels]`.
2. Extracts image patches from the the input tensor to form a *virtual*
   tensor of shape `[batch, out_height, out_width,
   filter_height * filter_width * in_channels]`.
3. For each patch, right-multiplies the filter matrix and the image patch
   vector.

In detail,

    output[b, i, j, k] =
        sum_{di, dj, q} input[b, strides[1] * i + di, strides[2] * j + dj, q] *
                        filter[di, dj, q, k]

Must have `strides[0] = strides[3] = 1`.  For the most common case of the same
horizontal and vertices strides, `strides = [1, stride, stride, 1]`.

##### Args:

*  `input`: A `Tensor`. Must be one of the following types: `float32`, `float64`.
*  `filter`: A `Tensor`. Must have the same type as `input`.
*  `strides`: A list of `ints`.
    1-D of length 4.  The stride of the sliding window for each dimension
    of `input`.
*  `padding`: A `string` from: `"SAME", "VALID"`.
    The type of padding algorithm to use.
*  `use_cudnn_on_gpu`: An optional `bool`. Defaults to `True`.
*  `name`: A name for the operation (optional).

##### Returns:

  A `Tensor`. Has the same type as `input`.

- - -

### `tf.nn.depthwise_conv2d(input, filter, strides, padding, name=None)`

Depthwise 2-D convolution.

Given an input tensor of shape `[batch, in_height, in_width, in_channels]`
and a filter tensor of shape
`[filter_height, filter_width, in_channels, channel_multiplier]`
containing `in_channels` convolutional filters of depth 1, `depthwise_conv2d`
applies a different filter to each input channel (expanding from 1 channel
to `channel_multiplier` channels for each), then concatenates the results
together.  The output has `in_channels * channel_multiplier` channels.

In detail,

    output[b, i, j, k * channel_multiplier + q] =
        sum_{di, dj} input[b, strides[1] * i + di, strides[2] * j + dj, k] *
                     filter[di, dj, k, q]

Must have `strides[0] = strides[3] = 1`.  For the most common case of the
same horizontal and vertical strides, `strides = [1, stride, stride, 1]`.

##### Args:

*  `input`: 4-D with shape `[batch, in_height, in_width, in_channels]`.
*  `filter`: 4-D with shape
    `[filter_height, filter_width, in_channels, channel_multiplier]`.
*  `strides`: 1-D of size 4.  The stride of the sliding window for each
    dimension of `input`.
*  `padding`: A string, either `'VALID'` or `'SAME'`.  The padding algorithm.
*  `name`: A name for this operation (optional).

##### Returns:

  A 4-D `Tensor` of shape
  `[batch, out_height, out_width, in_channels * channel_multiplier].`

- - -

### `tf.nn.separable_conv2d(input, depthwise_filter, pointwise_filter, strides, padding, name=None)`

2-D convolution with separable filters.

Performs a depthwise convolution that acts separately on channels followed by
a pointwise convolution that mixes channels.  Note that this is separability
between dimensions `[1, 2]` and `3`, not spatial separability between
dimensions `1` and `2`.

In detail,

    output[b, i, j, k] = sum_{di, dj, q, r]
        input[b, strides[1] * i + di, strides[2] * j + dj, q] *
        depthwise_filter[di, dj, q, r] *
        pointwise_filter[0, 0, q * channel_multiplier + r, k]

`strides` controls the strides for the depthwise convolution only, since
the pointwise convolution has implicit strides of `[1, 1, 1, 1]`.  Must have
`strides[0] = strides[3] = 1`.  For the most common case of the same
horizontal and vertical strides, `strides = [1, stride, stride, 1]`.

##### Args:

*  `input`: 4-D `Tensor` with shape `[batch, in_height, in_width, in_channels]`.
*  `depthwise_filter`: 4-D `Tensor` with shape
    `[filter_height, filter_width, in_channels, channel_multiplier]`.
    Contains `in_channels` convolutional filters of depth 1.
*  `pointwise_filter`: 4-D `Tensor` with shape
    `[1, 1, channel_multiplier * in_channels, out_channels]`.  Pointwise
    filter to mix channels after `depthwise_filter` has convolved spatially.
*  `strides`: 1-D of size 4.  The strides for the depthwise convolution for
    each dimension of `input`.
*  `padding`: A string, either `'VALID'` or `'SAME'`.  The padding algorithm.
*  `name`: A name for this operation (optional).

##### Returns:

  A 4-D `Tensor` of shape `[batch, out_height, out_width, out_channels]`.

## Pooling

The pooling ops sweep a rectangular window over the input tensor, computing a
reduction operation for each window (average, max, or max with argmax).  Each
pooling op uses rectangular windows of size `ksize` separated by offset
`strides`.  For example, if `strides` is all ones every window is used, if
`strides` is all twos every other window is used in each dimension, etc.

In detail, the output is

    output[i] = reduce(value[strides * i:strides * i + ksize])

for each tuple of indices `i`.  The output shape is

    shape(output) = (shape(value) - ksize + 1) / strides

where the rounding direction depends on padding:

* `padding = 'SAME'`: Round down (only full size windows are considered).
* `padding = 'VALID'`: Round up (partial windows are included).

- - -

### `tf.nn.avg_pool(value, ksize, strides, padding, name=None)`

Performs the average pooling on the input.

Each entry in `output` is the mean of the corresponding size `ksize`
window in `value`.

##### Args:

*  `value`: A 4-D `Tensor` of shape `[batch, height, width, channels]` and type
    `float32`, `float64`, `qint8`, `quint8`, or `qint32`.
*  `ksize`: A list of ints that has length >= 4.
    The size of the window for each dimension of the input tensor.
*  `strides`: A list of ints that has length >= 4.
    The stride of the sliding window for each dimension of the
    input tensor.
*  `padding`: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
*  `name`: Optional name for the operation.

##### Returns:

  A `Tensor` with the same type as `value`.  The average pooled output tensor.

- - -

### `tf.nn.max_pool(value, ksize, strides, padding, name=None)`

Performs the max pooling on the input.

##### Args:

*  `value`: A 4-D `Tensor` with shape `[batch, height, width, channels]` and
    type `float32`, `float64`, `qint8`, `quint8`, `qint32`.
*  `ksize`: A list of ints that has length >= 4.  The size of the window for
    each dimension of the input tensor.
*  `strides`: A list of ints that has length >= 4.  The stride of the sliding
    window for each dimension of the input tensor.
*  `padding`: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
*  `name`: Optional name for the operation.

##### Returns:

  A `Tensor` with the same type as `value`.  The max pooled output tensor.

- - -

### `tf.nn.max_pool_with_argmax(input, ksize, strides, padding, Targmax=None, name=None)`

Performs max pooling on the input and outputs both max values and indices.

The indices in `argmax` are flattened, so that a maximum value at position
`[b, y, x, c]` becomes flattened index
`((b * height + y) * width + x) * channels + c`.

##### Args:

*  `input`: A `Tensor` of type `float32`.
    4-D with shape `[batch, height, width, channels]`.  Input to pool over.
*  `ksize`: A list of `ints` that has length `>= 4`.
    The size of the window for each dimension of the input tensor.
*  `strides`: A list of `ints` that has length `>= 4`.
    The stride of the sliding window for each dimension of the
    input tensor.
*  `padding`: A `string` from: `"SAME", "VALID"`.
    The type of padding algorithm to use.
*  `Targmax`: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int64`.
*  `name`: A name for the operation (optional).

##### Returns:

  A tuple of `Tensor` objects (output, argmax).

*  `output`: A `Tensor` of type `float32`. The max pooled output tensor.
*  `argmax`: A `Tensor` of type `Targmax`. 4-D.  The flattened indices of the max values chosen for each output.

## Normalization

Normalization is useful to prevent neurons from saturating when inputs may
have varying scale, and to aid generalization.

- - -

### `tf.nn.l2_normalize(x, dim, epsilon=1e-12, name=None)`

Normalizes along dimension `dim` using an L2 norm.

For a 1-D tensor with `dim = 0`, computes

    output = x / sqrt(max(sum(x**2), epsilon))

For `x` with more dimensions, independently normalizes each 1-D slice along
dimension `dim`.

##### Args:

*  `x`: A `Tensor`.
*  `dim`: Dimension along which to normalize.
*  `epsilon`: A lower bound value for the norm. Will use `sqrt(epsilon)` as the
    divisor if `norm < sqrt(epsilon)`.
*  `name`: A name for this operation (optional).

##### Returns:

  A `Tensor` with the same shape as `x`.

- - -

### `tf.nn.local_response_normalization(input, depth_radius=None, bias=None, alpha=None, beta=None, name=None)`

Local Response Normalization.

The 4-D `input` tensor is treated as a 3-D array of 1-D vectors (along the last
dimension), and each vector is normalized independently.  Within a given vector,
each component is divided by the weighted, squared sum of inputs within
`depth_radius`.  In detail,

    sqr_sum[a, b, c, d] =
        sum(input[a, b, c, d - depth_radius : d + depth_radius + 1] ** 2)
    output = input / (bias + alpha * sqr_sum ** beta)

For details, see [Krizhevsky et al., ImageNet classification with deep
convolutional neural networks (NIPS 2012)]
(http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks).

##### Args:

*  `input`: A `Tensor` of type `float32`. 4-D.
*  `depth_radius`: An optional `int`. Defaults to `5`.
    0-D.  Half-width of the 1-D normalization window.
*  `bias`: An optional `float`. Defaults to `1`.
    An offset (usually positive to avoid dividing by 0).
*  `alpha`: An optional `float`. Defaults to `1`.
    A scale factor, usually positive.
*  `beta`: An optional `float`. Defaults to `0.5`. An exponent.
*  `name`: A name for the operation (optional).

##### Returns:

  A `Tensor` of type `float32`.

- - -

### `tf.nn.moments(x, axes, name=None)`

Calculate the mean and variance of `x`.

The mean and variance are calculated by aggregating the contents of `x`
across `axes`.  If `x` is 1-D and `axes = [0]` this is just the mean
and variance of a vector.

For so-called "global normalization" needed for convolutional filters pass
`axes=[0, 1, 2]` (batch, height, width).  For batch normalization pass
`axes=[0]` (batch).

##### Args:

*  `x`: A `Tensor`.
*  `axes`: array of ints.  Axes along which to compute mean and
    variance.
*  `name`: Name used to scope the operations that compute the moments.

##### Returns:

  Two `Tensor` objects: `mean` and `variance`.

## Losses

The loss ops measure error between two tensors, or between a tensor and zero.
These can be used for measuring accuracy of a network in a regression task
or for regularization purposes (weight decay).

- - -

### `tf.nn.l2_loss(t, name=None)`

L2 Loss.

Computes half the L2 norm of a tensor without the `sqrt`:

    output = sum(t ** 2) / 2

##### Args:

*  `t`: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `qint8`, `quint8`, `qint32`.
    Typically 2-D, but may have any dimensions.
*  `name`: A name for the operation (optional).

##### Returns:

  A `Tensor`. Has the same type as `t`. 0-D.

## Classification

TensorFlow provides several operations that help you perform classification.

- - -

### `tf.nn.sigmoid_cross_entropy_with_logits(logits, targets, name=None)`

Computes sigmoid cross entropy given `logits`.

Measures the probability error in discrete classification tasks in which each
class is independent and not mutually exclusive.  For instance, one could
perform multilabel classification where a picture can contain both an elephant
and a dog at the same time.

For brevity, let `x = logits`, `z = targets`.  The logistic loss is

    x - x * z + log(1 + exp(-x))

To ensure stability and avoid overflow, the implementation uses

    max(x, 0) - x * z + log(1 + exp(-abs(x)))

`logits` and `targets` must have the same type and shape.

##### Args:

*  `logits`: A `Tensor` of type `float32` or `float64`.
*  `targets`: A `Tensor` of the same type and shape as `logits`.
*  `name`: A name for the operation (optional).

##### Returns:

  A `Tensor` of the same shape as `logits` with the componentwise
  logistic losses.

- - -

### `tf.nn.softmax(logits, name=None)`

Computes softmax activations.

For each batch `i` and class `j` we have

    softmax[i, j] = exp(logits[i, j]) / sum(exp(logits[i]))

##### Args:

*  `logits`: A `Tensor`. Must be one of the following types: `float32`, `float64`.
    2-D with shape `[batch_size, num_classes]`.
*  `name`: A name for the operation (optional).

##### Returns:

  A `Tensor`. Has the same type as `logits`. Same shape as `logits`.

- - -

### `tf.nn.softmax_cross_entropy_with_logits(logits, labels, name=None)`

Computes softmax cross entropy between `logits` and `labels`.

Measures the probability error in discrete classification tasks in which the
classes are mutually exclusive (each entry is in exactly one class).  For
example, each CIFAR-10 image is labeled with one and only one label: an image
can be a dog or a truck, but not both.

**WARNING:** This op expects unscaled logits, since it performs a `softmax`
on `logits` internally for efficiency.  Do not call this op with the
output of `softmax`, as it will produce incorrect results.

`logits` and `labels` must have the same shape `[batch_size, num_classes]`
and the same dtype (either `float32` or `float64`).

##### Args:

*  `logits`: Unscaled log probabilities.
*  `labels`: Each row `labels[i]` must be a valid probability distribution.
*  `name`: A name for the operation (optional).

##### Returns:

  A 1-D `Tensor` of length `batch_size` of the same type as `logits` with the
  softmax cross entropy loss.

## Embeddings

TensorFlow provides library support for looking up values in embedding
tensors.

- - -

### `tf.nn.embedding_lookup(params, ids, name=None)`

Looks up `ids` in a list of embedding tensors.

This function is used to perform parallel lookups on the list of
tensors in `params`.  It is a generalization of
[`tf.gather()`](../../api_docs/python/array_ops.md#gather), where `params` is
interpreted as a partition of a larger embedding tensor.

If `len(params) > 1`, each element `id` of `ids` is partitioned between
the elements of `params` by computing `p = id % len(params)`, and is
then used to look up the slice `params[p][id // len(params), ...]`.

The results of the lookup are then concatenated into a dense
tensor. The returned tensor has shape `shape(ids) + shape(params)[1:]`.

##### Args:

*  `params`: A list of tensors with the same shape and type.
*  `ids`: A `Tensor` with type `int32` containing the ids to be looked
    up in `params`.
*  `name`: A name for the operation (optional).

##### Returns:

  A `Tensor` with the same type as the tensors in `params`.

##### Raises:

*  `ValueError`: If `params` is empty.

## Evaluation

The evaluation ops are useful for measuring the performance of a network.
Since they are nondifferentiable, they are typically used at evaluation time.

- - -

### `tf.nn.top_k(input, k, name=None)`

Returns the values and indices of the k largest elements for each row.

\\(values_{i, j}\\) represents the j-th largest element in \\(input_i\\).

\\(indices_{i, j}\\) gives the column index of the corresponding element,
such that \\(input_{i, indices_{i, j}} = values_{i, j}\\). If two
elements are equal, the lower-index element appears first.

##### Args:

*  `input`: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `int64`, `uint8`, `int16`, `int8`.
    A batch_size x classes tensor
*  `k`: An `int` that is `>= 1`.
    Number of top elements to look for within each row
*  `name`: A name for the operation (optional).

##### Returns:

  A tuple of `Tensor` objects (values, indices).

*  `values`: A `Tensor`. Has the same type as `input`. A batch_size x k tensor with the k largest elements for each row,
    sorted in descending order
*  `indices`: A `Tensor` of type `int32`. A batch_size x k tensor with the index of each value within each row

- - -

### `tf.nn.in_top_k(predictions, targets, k, name=None)`

Says whether the targets are in the top K predictions.

This outputs a batch_size bool array, an entry out[i] is true if the
prediction for the target class is among the top k predictions among
all predictions for example i. Note that the behavior of InTopK differs
from the TopK op in its handling of ties; if multiple classes have the
same prediction value and straddle the top-k boundary, all of those
classes are considered to be in the top k.

More formally, let

  \\(predictions_i\\) be the predictions for all classes for example i,
  \\(targets_i\\) be the target class for example i,
  \\(out_i\\) be the output for example i,

$$out_i = predictions_{i, targets_i} \in TopKIncludingTies(predictions_i)$$

##### Args:

*  `predictions`: A `Tensor` of type `float32`. A batch_size x classes tensor
*  `targets`: A `Tensor` of type `int32`. A batch_size vector of class ids
*  `k`: An `int`. Number of top elements to look at for computing precision
*  `name`: A name for the operation (optional).

##### Returns:

  A `Tensor` of type `bool`. Computed Precision at k as a bool Tensor

## Candidate Sampling

Do you want to train a multiclass or multilabel model with thousands
or millions of output classes (for example, a language model with a
large vocabulary)?  Training with a full Softmax is slow in this case,
since all of the classes are evaluated for every training example.
Candidate Sampling training algorithms can speed up your step times by
only considering a small randomly-chosen subset of contrastive classes
(called candidates) for each batch of training examples.

See our [Candidate Sampling Algorithms Reference]
(../../extras/candidate_sampling.pdf)

### Sampled Loss Functions

TensorFlow provides the following sampled loss functions for faster training.

- - -

### `tf.nn.nce_loss(weights, biases, inputs, labels, num_sampled, num_classes, num_true=1, sampled_values=None, remove_accidental_hits=False, name='nce_loss')`

Computes and returns the noise-contrastive estimation training loss.

See [Noise-contrastive estimation: A new estimation principle for
unnormalized statistical models]
(http://www.jmlr.org/proceedings/papers/v9/gutmann10a/gutmann10a.pdf).
Also see our [Candidate Sampling Algorithms Reference]
(http://www.tensorflow.org/extras/candidate_sampling.pdf)

Note: In the case where num_true > 1, we assign to each target class
the target probability 1 / num_true so that the target probabilities
sum to 1 per-example.

Note: It would be useful to allow a variable number of target classes per
example.  We hope to provide this functionality in a future release.
For now, if you have a variable number of target classes, you can pad them
out to a constant number by either repeating them or by padding
with an otherwise unused class.

##### Args:

*  `weights`: A `Tensor` of shape [num_classes, dim].  The class embeddings.
*  `biases`: A `Tensor` of shape [num_classes].  The class biases.
*  `inputs`: A `Tensor` of shape [batch_size, dim].  The forward
      activations of the input network.
*  `labels`: A `Tensor` of type `int64` and shape `[batch_size,
    num_true]`. The target classes.
*  `num_sampled`: An `int`.  The number of classes to randomly sample per batch.
*  `num_classes`: An `int`. The number of possible classes.
*  `num_true`: An `int`.  The number of target classes per training example.
*  `sampled_values`: a tuple of `(sampled_candidates, true_expected_count,
      sampled_expected_count)` returned by a *_candidate_sampler function.
      (if None, we default to LogUniformCandidateSampler)
*  `remove_accidental_hits`: A `bool`.  Whether to remove "accidental hits"
      where a sampled class equals one of the target classes.  If set to
      `True`, this is a "Sampled Logistic" loss instead of NCE, and we are
      learning to generate log-odds instead of log probabilities.  See
      our [Candidate Sampling Algorithms Reference]
      (http://www.tensorflow.org/extras/candidate_sampling.pdf).
      Default is False.
*  `name`: A name for the operation (optional).

##### Returns:

  A batch_size 1-D tensor of per-example NCE losses.

- - -

### `tf.nn.sampled_softmax_loss(weights, biases, inputs, labels, num_sampled, num_classes, num_true=1, sampled_values=None, remove_accidental_hits=True, name='sampled_softmax_loss')`

Computes and returns the sampled softmax training loss.

This is a faster way to train a softmax classifier over a huge number of
classes.

This operation is for training only.  It is generally an underestimate of
the full softmax loss.

At inference time, you can compute full softmax probabilities with the
expression `tf.nn.softmax(tf.matmul(inputs, weights) + biases)`.

See our [Candidate Sampling Algorithms Reference]
(http://www.tensorflow.org/extras/candidate_sampling.pdf)

Also see Section 3 of http://arxiv.org/abs/1412.2007 for the math.

##### Args:

*  `weights`: A `Tensor` of shape [num_classes, dim].  The class embeddings.
*  `biases`: A `Tensor` of shape [num_classes].  The class biases.
*  `inputs`: A `Tensor` of shape [batch_size, dim].  The forward
      activations of the input network.
*  `labels`: A `Tensor` of type `int64` and shape `[batch_size,
    num_true]`. The target classes.  Note that this format differs from
    the `labels` argument of `nn.softmax_cross_entropy_with_logits`.
*  `num_sampled`: An `int`.  The number of classes to randomly sample per batch.
*  `num_classes`: An `int`. The number of possible classes.
*  `num_true`: An `int`.  The number of target classes per training example.
*  `sampled_values`: a tuple of `(sampled_candidates, true_expected_count,
      sampled_expected_count)` returned by a *_candidate_sampler function.
      (if None, we default to LogUniformCandidateSampler)
*  `remove_accidental_hits`: A `bool`.  whether to remove "accidental hits"
      where a sampled class equals one of the target classes.  Default is
      True.
*  `name`: A name for the operation (optional).

##### Returns:

  A batch_size 1-D tensor of per-example sampled softmax losses.

### Candidate Samplers

TensorFlow provides the following samplers for randomly sampling candidate
classes when using one of the sampled loss functions above.

- - -

### `tf.nn.uniform_candidate_sampler(true_classes, num_true, num_sampled, unique, range_max, seed=None, name=None)`

Samples a set of classes using a uniform base distribution.

This operation randomly samples a tensor of sampled classes
(`sampled_candidates`) from the range of integers `[0, range_max]`.

The elements of `sampled_candidates` are drawn without replacement
(if `unique=True`) or with replacement (if `unique=False`) from
the base distribution.

The base distribution for this operation is the uniform distribution
over the range of integers `[0, range_max]`.

In addition, this operation returns tensors `true_expected_count`
and `sampled_expected_count` representing the number of times each
of the target classes (`true_classes`) and the sampled
classes (`sampled_candidates`) is expected to occur in an average
tensor of sampled classes.  These values correspond to `Q(y|x)`
defined in [this
document](http://www.tensorflow.org/extras/candidate_sampling.pdf).
If `unique=True`, then these are post-rejection probabilities and we
compute them approximately.

##### Args:

*  `true_classes`: A `Tensor` of type `int64` and shape `[batch_size,
    num_true]`. The target classes.
*  `num_true`: An `int`.  The number of target classes per training example.
*  `num_sampled`: An `int`.  The number of classes to randomly sample per batch.
*  `unique`: A `bool`. Determines whether all sampled classes in a batch are
    unique.
*  `range_max`: An `int`. The number of possible classes.
*  `seed`: An `int`. An operation-specific seed. Default is 0.
*  `name`: A name for the operation (optional).

##### Returns:

*  `sampled_candidates`: A tensor of type `int64` and shape `[num_sampled]`.
    The sampled classes.
*  `true_expected_count`: A tensor of type `float`.  Same shape as
    `true_classes`. The expected counts under the sampling distribution
    of each of `true_classes`.
*  `sampled_expected_count`: A tensor of type `float`. Same shape as
    `sampled_candidates`. The expected counts under the sampling distribution
    of each of `sampled_candidates`.

- - -

### `tf.nn.log_uniform_candidate_sampler(true_classes, num_true, num_sampled, unique, range_max, seed=None, name=None)`

Samples a set of classes using a log-uniform (Zipfian) base distribution.

This operation randomly samples a tensor of sampled classes
(`sampled_candidates`) from the range of integers `[0, range_max]`.

The elements of `sampled_candidates` are drawn without replacement
(if `unique=True`) or with replacement (if `unique=False`) from
the base distribution.

The base distribution for this operation is an approximately log-uniform
or Zipfian distribution:

`P(class) = (log(class + 2) - log(class + 1)) / log(range_max + 1)`

This sampler is useful when the target classes approximately follow such
a distribution - for example, if the classes represent words in a lexicon
sorted in decreasing order of frequency. If your classes are not ordered by
decreasing frequency, do not use this op.

In addition, this operation returns tensors `true_expected_count`
and `sampled_expected_count` representing the number of times each
of the target classes (`true_classes`) and the sampled
classes (`sampled_candidates`) is expected to occur in an average
tensor of sampled classes.  These values correspond to `Q(y|x)`
defined in [this
document](http://www.tensorflow.org/extras/candidate_sampling.pdf).
If `unique=True`, then these are post-rejection probabilities and we
compute them approximately.

##### Args:

*  `true_classes`: A `Tensor` of type `int64` and shape `[batch_size,
    num_true]`. The target classes.
*  `num_true`: An `int`.  The number of target classes per training example.
*  `num_sampled`: An `int`.  The number of classes to randomly sample per batch.
*  `unique`: A `bool`. Determines whether all sampled classes in a batch are
    unique.
*  `range_max`: An `int`. The number of possible classes.
*  `seed`: An `int`. An operation-specific seed. Default is 0.
*  `name`: A name for the operation (optional).

##### Returns:

*  `sampled_candidates`: A tensor of type `int64` and shape `[num_sampled]`.
    The sampled classes.
*  `true_expected_count`: A tensor of type `float`.  Same shape as
    `true_classes`. The expected counts under the sampling distribution
    of each of `true_classes`.
*  `sampled_expected_count`: A tensor of type `float`. Same shape as
    `sampled_candidates`. The expected counts under the sampling distribution
    of each of `sampled_candidates`.

- - -

### `tf.nn.learned_unigram_candidate_sampler(true_classes, num_true, num_sampled, unique, range_max, seed=None, name=None)`

Samples a set of classes from a distribution learned during training.

This operation randomly samples a tensor of sampled classes
(`sampled_candidates`) from the range of integers `[0, range_max]`.

The elements of `sampled_candidates` are drawn without replacement
(if `unique=True`) or with replacement (if `unique=False`) from
the base distribution.

The base distribution for this operation is constructed on the fly
during training.  It is a unigram distribution over the target
classes seen so far during training.  Every integer in `[0, range_max]`
begins with a weight of 1, and is incremented by 1 each time it is
seen as a target class.  The base distribution is not saved to checkpoints,
so it is reset when the model is reloaded.

In addition, this operation returns tensors `true_expected_count`
and `sampled_expected_count` representing the number of times each
of the target classes (`true_classes`) and the sampled
classes (`sampled_candidates`) is expected to occur in an average
tensor of sampled classes.  These values correspond to `Q(y|x)`
defined in [this
document](http://www.tensorflow.org/extras/candidate_sampling.pdf).
If `unique=True`, then these are post-rejection probabilities and we
compute them approximately.

##### Args:

*  `true_classes`: A `Tensor` of type `int64` and shape `[batch_size,
    num_true]`. The target classes.
*  `num_true`: An `int`.  The number of target classes per training example.
*  `num_sampled`: An `int`.  The number of classes to randomly sample per batch.
*  `unique`: A `bool`. Determines whether all sampled classes in a batch are
    unique.
*  `range_max`: An `int`. The number of possible classes.
*  `seed`: An `int`. An operation-specific seed. Default is 0.
*  `name`: A name for the operation (optional).

##### Returns:

*  `sampled_candidates`: A tensor of type `int64` and shape `[num_sampled]`.
    The sampled classes.
*  `true_expected_count`: A tensor of type `float`.  Same shape as
    `true_classes`. The expected counts under the sampling distribution
    of each of `true_classes`.
*  `sampled_expected_count`: A tensor of type `float`. Same shape as
    `sampled_candidates`. The expected counts under the sampling distribution
    of each of `sampled_candidates`.

- - -

### `tf.nn.fixed_unigram_candidate_sampler(true_classes, num_true, num_sampled, unique, range_max, vocab_file='', distortion=0.0, num_reserved_ids=0, num_shards=1, shard=0, unigrams=[], seed=None, name=None)`

Samples a set of classes using the provided (fixed) base distribution.

This operation randomly samples a tensor of sampled classes
(`sampled_candidates`) from the range of integers `[0, range_max]`.

The elements of `sampled_candidates` are drawn without replacement
(if `unique=True`) or with replacement (if `unique=False`) from
the base distribution.

The base distribution is read from a file or passed in as an
in-memory array. There is also an option to skew the distribution by
applying a distortion power to the weights.

In addition, this operation returns tensors `true_expected_count`
and `sampled_expected_count` representing the number of times each
of the target classes (`true_classes`) and the sampled
classes (`sampled_candidates`) is expected to occur in an average
tensor of sampled classes.  These values correspond to `Q(y|x)`
defined in [this
document](http://www.tensorflow.org/extras/candidate_sampling.pdf).
If `unique=True`, then these are post-rejection probabilities and we
compute them approximately.

##### Args:

*  `true_classes`: A `Tensor` of type `int64` and shape `[batch_size,
    num_true]`. The target classes.
*  `num_true`: An `int`.  The number of target classes per training example.
*  `num_sampled`: An `int`.  The number of classes to randomly sample per batch.
*  `unique`: A `bool`. Determines whether all sampled classes in a batch are
    unique.
*  `range_max`: An `int`. The number of possible classes.
*  `vocab_file`: Each valid line in this file (which should have a CSV-like
    format) corresponds to a valid word ID. IDs are in sequential order,
    starting from num_reserved_ids. The last entry in each line is expected
    to be a value corresponding to the count or relative probability. Exactly
    one of `vocab_file` and `unigrams` needs to be passed to this operation.
*  `distortion`: The distortion is used to skew the unigram probability
    distribution.  Each weight is first raised to the distortion's power
    before adding to the internal unigram distribution. As a result,
    `distortion = 1.0` gives regular unigram sampling (as defined by the vocab
    file), and `distortion = 0.0` gives a uniform distribution.
*  `num_reserved_ids`: Optionally some reserved IDs can be added in the range
    `[0, num_reserved_ids]` by the users. One use case is that a special
    unknown word token is used as ID 0. These IDs will have a sampling
    probability of 0.
*  `num_shards`: A sampler can be used to sample from a subset of the original
    range in order to speed up the whole computation through parallelism. This
    parameter (together with `shard`) indicates the number of partitions that
    are being used in the overall computation.
*  `shard`: A sampler can be used to sample from a subset of the original range
    in order to speed up the whole computation through parallelism. This
    parameter (together with `num_shards`) indicates the particular partition
    number of the operation, when partitioning is being used.
*  `unigrams`: A list of unigram counts or probabilities, one per ID in
    sequential order. Exactly one of `vocab_file` and `unigrams` should be
    passed to this operation.
*  `seed`: An `int`. An operation-specific seed. Default is 0.
*  `name`: A name for the operation (optional).

##### Returns:

*  `sampled_candidates`: A tensor of type `int64` and shape `[num_sampled]`.
    The sampled classes.
*  `true_expected_count`: A tensor of type `float`.  Same shape as
    `true_classes`. The expected counts under the sampling distribution
    of each of `true_classes`.
*  `sampled_expected_count`: A tensor of type `float`. Same shape as
    `sampled_candidates`. The expected counts under the sampling distribution
    of each of `sampled_candidates`.

### Miscellaneous candidate sampling utilities

- - -

### `tf.nn.compute_accidental_hits(true_classes, sampled_candidates, num_true, seed=None, name=None)`

Compute the ids of positions in sampled_candidates matching true_classes.

In Candidate Sampling, this operation facilitates virtually removing
sampled classes which happen to match target classes.  This is done
in Sampled Softmax and Sampled Logistic.

See our [Candidate Sampling Algorithms
Reference](http://www.tensorflow.org/extras/candidate_sampling.pdf).

We presuppose that the `sampled_candidates` are unique.

We call it an 'accidental hit' when one of the target classes
matches one of the sampled classes.  This operation reports
accidental hits as triples `(index, id, weight)`, where `index`
represents the row number in `true_classes`, `id` represents the
position in `sampled_candidates`, and weight is `-FLOAT_MAX`.

The result of this op should be passed through a `sparse_to_dense`
operation, then added to the logits of the sampled classes. This
removes the contradictory effect of accidentally sampling the true
target classes as noise classes for the same example.

##### Args:

*  `true_classes`: A `Tensor` of type `int64` and shape `[batch_size,
    num_true]`. The target classes.
*  `sampled_candidates`: A tensor of type `int64` and shape `[num_sampled]`.
    The sampled_candidates output of CandidateSampler.
*  `num_true`: An `int`.  The number of target classes per training example.
*  `seed`: An `int`. An operation-specific seed. Default is 0.
*  `name`: A name for the operation (optional).

##### Returns:

*  `indices`: A `Tensor` of type `int32` and shape `[num_accidental_hits]`.
    Values indicate rows in `true_classes`.
*  `ids`: A `Tensor` of type `int64` and shape `[num_accidental_hits]`.
    Values indicate positions in `sampled_candidates`.
*  `weights`: A `Tensor` of type `float` and shape `[num_accidental_hits]`.
    Each value is `-FLOAT_MAX`.


text:
(function(){
    'use strict';
    angular.module('gantt').directive('ganttHeaderColumns', ['GanttDirectiveBuilder', function(Builder) {
        var builder = new Builder('ganttHeaderColumns');
        builder.controller = function($scope, $element) {
            $scope.gantt.header.columns.$element = $element;
            $scope.gantt.header.columns.$scope = $scope;
        };
        return builder.build();
    }]);
}());

redpajama_set_name: RedPajamaGithub


text:
module.exports = {
	name: 'select2',
	extends: 'select',
	wrapper: ['validation', 'horizontalBootstrapLabel', 'bootstrapHasError']
};


text:
require 'spec_helper'
require 'generator_spec'

describe RailsDynamicErrors::InstallGenerator do
  destination File.expand_path("../../../../dummy/tmp/", __FILE__)

  before(:each) do
    prepare_destination
    config_dir = File.expand_path("../../../../dummy/tmp/config/", __FILE__)
    FileUtils.mkdir(config_dir)
    @config_application_file = File.join(config_dir, 'application.rb')
    config_routes_file = File.join(config_dir, 'routes.rb')
    File.open(@config_application_file, 'w') { |f| f.write("module Dummy\n  class Application < Rails::Application\n  end\nend") }
    File.open(config_routes_file, 'w') { |f| f.write("Rails.application.routes.draw do\nend") }
    run_generator
  end

  it "inserts options into config/application.rb" do
    text = <<-INSERTION
    # config.rails_dynamic_errors.http_error_status_codes_to_handle = [404, 422]
    INSERTION
    File.read(@config_application_file).should include(text)
  end

  it "mounts the engine in config/routes.rb" do
    assert_file "config/routes.rb", /mount RailsDynamicErrors::Engine/
  end

  it "mounts the engine in config/routes.rb at the 'errors' path" do
    assert_file "config/routes.rb", /mount RailsDynamicErrors::Engine, at: '#{RailsDynamicErrors::DEFAULT_MOUNT_PATH}'/
  end
end


text:
"""Dependencies represent the flow of data explicitly, with reference to the source model
output and sink model input.

A Dependency is an edge in the model process graph. No processing happens on dependency edges,
only on the Model nodes.

A Dependency can have a timestep specified - by default this is the current timestep, but a
system-of-systems model may also want to specify that data should be provided from the previous
timestep or a base timestep.
"""
from smif.metadata import RelativeTimestep

class Dependency(object):
    """Link a model input to a data source

    Arguments
    ---------
    source_model : smif.model.Model
        The source model object
    source : smif.metadata.Spec
        The source output description
    sink_model : smif.model.Model
        The sink model object
    sink : smif.metadata.Spec
        The sink input description
    timestep : smif.metadata.RelativeTimestep, optional
        The relative timestep of the dependency, defaults to CURRENT
    """
    def __init__(self, source_model, source, sink_model, sink,
                 timestep=RelativeTimestep.CURRENT):
        # Insist on identical metadata - conversions must be explicit
        if source != sink:
            diff = ""
            if source.dtype != sink.dtype:
                diff += "dtype(%s!=%s) " % (source.dtype, sink.dtype)
            if source.dims != sink.dims:
                diff += "dims(%s!=%s) " % (source.dims, sink.dims)
            if source.coords != sink.coords:
                diff += "coords do not match "
            if source.unit != sink.unit:
                diff += "unit(%s!=%s) " % (source.unit, sink.unit)
            msg = "Dependencies must connect identical metadata (up to variable name). " + \
                "Connecting %s:%s->%s:%s with mismatched %s"
            raise ValueError(
                msg % (source_model.name, source.name, sink_model.name, sink.name, diff))

        self.source_model = source_model
        self.source = source
        self.sink_model = sink_model
        self.sink = sink
        self.timestep = timestep

    def as_dict(self):
        """Serialise to dictionary representation
        """
        config = {
            'source': self.source_model.name,
            'source_output': self.source.name,
            'sink': self.sink_model.name,
            'sink_input': self.sink.name
        }
        try:
            config['timestep'] = self.timestep.value
        except AttributeError:
            config['timestep'] = self.timestep
        return config

    def __repr__(self):
        return "<Dependency({}, {}, {}, {}, {})>".format(
            self.source_model, self.source, self.sink_model, self.sink, self.timestep)

    def __eq__(self, other):
        return self.source_model == other.source_model \
            and self.source == other.source \
            and self.sink_model == other.sink_model \
            and self.sink == other.sink \
            and self.timestep == other.timestep


text:
package com.pearson.entech.elasticsearch.search.facet.approx.date.collectors;

import static com.google.common.collect.Maps.newHashMap;

import java.io.IOException;
import java.util.Map;

import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.CacheRecycler;
import org.elasticsearch.common.joda.TimeZoneRounding;
import org.elasticsearch.common.trove.ExtTLongObjectHashMap;
import org.elasticsearch.common.trove.list.array.TIntArrayList;
import org.elasticsearch.index.fielddata.AtomicFieldData;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.fielddata.ScriptDocValues;
import org.elasticsearch.index.fielddata.plain.LongArrayIndexFieldData;
import org.elasticsearch.search.facet.InternalFacet;

import com.pearson.entech.elasticsearch.search.facet.approx.date.internal.DistinctCountPayload;
import com.pearson.entech.elasticsearch.search.facet.approx.date.internal.InternalDistinctFacet;

/**
 * A Collector for distinct date facets.
 *
 * @param <V> the field data type of the optional value field (use NullFieldData if you aren't using the value field)
 * @param <D> the field data type of the distinct field
 */
public class DistinctCollector<V extends AtomicFieldData<? extends ScriptDocValues>, D extends AtomicFieldData<? extends ScriptDocValues>>
        extends TimestampFirstCollector<V> {

    /**
     * The number of exact distinct field values to record before tipping into approximate counting.
     */
    private final int _exactThreshold;

    /**
     * A map from distinct field values to lists of timestamps.
     */
    private Map<BytesRef, TIntArrayList> _occurrences;

    /**
     * Iterator over the values of the distinct field.
     */
    private final BytesFieldIterator<AtomicFieldData<? extends ScriptDocValues>> _distinctFieldIter;

    /**
     * Create a new collector.
     *
     * @param keyFieldData the key field (datetime) data
     * @param distinctFieldData the distinct field data
     * @param tzRounding the timezone rounding to apply
     * @param exactThreshold The number of exact distinct field values to record before tipping into approximate counting
     */
    public DistinctCollector(final LongArrayIndexFieldData keyFieldData,
            final IndexFieldData<D> distinctFieldData,
            final TimeZoneRounding tzRounding,
            final int exactThreshold) {
        super(keyFieldData, tzRounding);
        _distinctFieldIter = new BytesFieldIterator(distinctFieldData); // TODO type safety?
        _exactThreshold = exactThreshold;
        _occurrences = newHashMap();
    }

    @Override
    public void setNextReader(final AtomicReaderContext context) throws IOException {
        super.setNextReader(context);
        _distinctFieldIter.setNextReader(context);
    }

    @Override
    public void collect(final int doc) throws IOException {
        _distinctFieldIter.collect(doc);

        // Exit as early as possible in order to avoid unnecessary lookups/conversions
        super.collect(doc);
        if(!hasNextTimestamp())
            return;

        // Strategy: compile a map from distinct field values to timestamps where those values occur.
        // Later, at build time, we invert this into a map from timestamps to DistinctCountPayloads.
        // This avoids having to read, copy and store multiple BytesRefs containing the same distinct field values.

        while(_distinctFieldIter.hasNext()) {
            // TODO this causes two conversions if the field's numeric
            final BytesRef unsafe = _distinctFieldIter.next();
            TIntArrayList timestampList = _occurrences.get(unsafe);
            if(timestampList == null) {
                final BytesRef safe = BytesRef.deepCopyOf(unsafe);
                timestampList = new TIntArrayList();
                _occurrences.put(safe, timestampList);
            }

            // To reduce memory usage, we store all timestamps at second resolution for now
            while(hasNextTimestamp()) {
                final long time = nextTimestamp();
                timestampList.add((int) (time / 1000));
            }

            // Reset timestamp iterator for this doc
            // TODO make this a standalone CollectableIterator like _distinctFieldIter
            super.collect(doc);
        }
    }

    @Override
    public void postCollection() {
        super.postCollection();
        _distinctFieldIter.postCollection();
    }

    @Override
    public InternalFacet build(final String facetName) {
        // This is where we invert the distinct value->timestamp map to build the actual facet object
        final ExtTLongObjectHashMap<DistinctCountPayload> counts = CacheRecycler.popLongObjectMap();
        for(final BytesRef fieldVal : _occurrences.keySet()) {
            final TIntArrayList timestampList = _occurrences.get(fieldVal);
            final int timestampCount = timestampList.size();
            for(int i = 0; i < timestampCount; i++) {
                final long timestampSecs = timestampList.get(i);
                // Convert back to milliseconds resolution
                final long timestamp = timestampSecs * 1000;
                DistinctCountPayload payload = counts.get(timestamp);
                if(payload == null) {
                    payload = new DistinctCountPayload(_exactThreshold);
                    counts.put(timestamp, payload);
                }
                payload.update(fieldVal);
            }
            _occurrences.put(fieldVal, null); // Free this up for GC immediately
        }

        _occurrences = null;
        final InternalFacet facet = new InternalDistinctFacet(facetName, counts);
        return facet;
    }

}


text: <ng-include src="'./app/manipulate_author/author_form.template.html'"></ng-include>


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="bootstrap/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false">
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory suffix="Test.php">./tests/</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist>
            <directory suffix=".php">./app/</directory>
            <exclude>
                <directory>./app/Interfaces/</directory>
                <directory>./app/Providers/</directory>
                <directory>./app/Http/Requests</directory>
                <file>./app/Console/Commands/Inspire.php</file>
                <file>./app/Console/Kernel.php</file>
                <file>./app/Exceptions/Handler.php</file>
                <file>./app/Http/Kernel.php</file>
                <file>./app/Http/Controllers/Controller.php</file>
                <file>./app/Http/Middleware/EncryptCookies.php</file>
                <file>./app/Http/Middleware/VerifyCsrfToken.php</file>
                <file>./app/Jobs/Job.php</file>
                <file>./app/Events/Event.php</file>
            </exclude>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
        <env name="DB_CONNECTION" value="travis" />
    </php>
    <logging>
        <log type="coverage-text" target="php://stdout" showUncoveredFiles="false" />
        <log type="coverage-clover" target="tests/build/clover.xml"/>
    </logging>
</phpunit>


text:
import Config from './Config';

var Utility = {};

Utility.scrollToTop = function() {
    window.scrollTo(0, 0);
};

Utility.setTitle = function(title) {
    document.title = title + " | " + Config.server_name + " - MapleStory Private Server";
    this.scrollToTop();
};

export default Utility


text:
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Threading;
using Abp.Localization.Dictionaries;

namespace Abp.Localization.Sources
{
    /// <summary>
    /// This class is used to build a localization source
    /// which works on memory based dictionaries to find strings.
    /// </summary>
    public class DictionaryBasedLocalizationSource : IDictionaryBasedLocalizationSource
    {
        /// <summary>
        /// Unique Name of the source.
        /// </summary>
        public string Name { get; private set; }

        /// <summary>
        /// List of all dictionaries in this source.
        /// Key: Culture-name
        /// Value: Dictionary.
        /// </summary>
        private readonly Dictionary<string, ILocalizationDictionary> _dictionaries;

        /// <summary>
        /// Default directory is used when requested string can not found in specified culture.
        /// </summary>
        private ILocalizationDictionary _defaultDictionary;

        private readonly ILocalizationDictionaryProvider _dictionaryProvider;

        /// <summary>
        ///
        /// </summary>
        /// <param name="name"></param>
        /// <param name="dictionaryProvider"></param>
        public DictionaryBasedLocalizationSource(string name, ILocalizationDictionaryProvider dictionaryProvider)
        {
            Name = name;
            _dictionaries = new Dictionary<string, ILocalizationDictionary>();
            _dictionaryProvider = dictionaryProvider;
        }

        /// <inheritdoc/>
        public virtual void Initialize()
        {
            if (_dictionaryProvider == null)
            {
                return;
            }

            var defaultProvided = false;
            foreach (var dictionaryInfo in _dictionaryProvider.GetDictionaries(Name))
            {
                _dictionaries[dictionaryInfo.Dictionary.CultureInfo.Name] = dictionaryInfo.Dictionary;
                if (dictionaryInfo.IsDefault)
                {
                    if (defaultProvided)
                    {
                        throw new AbpInitializationException("Only one default localization dictionary can be for source: " + Name);
                    }

                    _defaultDictionary = dictionaryInfo.Dictionary;
                    defaultProvided = true;
                }
            }

            if (!defaultProvided)
            {
                throw new AbpInitializationException("There should be a default localization dictionary for source: " + Name);
            }
        }

        /// <inheritdoc/>
        public string GetString(string name)
        {
            return GetString(name, Thread.CurrentThread.CurrentUICulture);
        }

        /// <inheritdoc/>
        public string GetString(string name, CultureInfo culture)
        {
            var cultureCode = culture.Name;

            //Try to get from original dictionary
            ILocalizationDictionary originalDictionary;
            if (_dictionaries.TryGetValue(cultureCode, out originalDictionary))
            {
                var strOriginal = originalDictionary.GetOrNull(name);
                if (strOriginal != null)
                {
                    return strOriginal.Value;
                }
            }

            //Try to get from same language dictionary
            if (cultureCode.Length == 5) //Example: "tr-TR" (length=5)
            {
                var langCode = cultureCode.Substring(0, 2);
                ILocalizationDictionary langDictionary;
                if (_dictionaries.TryGetValue(langCode, out langDictionary))
                {
                    var strLang = langDictionary.GetOrNull(name);
                    if (strLang != null)
                    {
                        return strLang.Value;
                    }
                }
            }

            //Try to get from default language
            if (_defaultDictionary == null)
            {
                throw new AbpException("Can not find '" + name + "' and no default language is defined!");
            }

            var strDefault = _defaultDictionary.GetOrNull(name);
            if (strDefault != null)
            {
                return strDefault.Value;
            }

            throw new AbpException("Can not find a localized string for '" + name + "' in source '" + Name + "'!");
        }

        /// <inheritdoc/>
        public IReadOnlyList<LocalizedString> GetAllStrings()
        {
            return GetAllStrings(Thread.CurrentThread.CurrentUICulture);
        }

        /// <inheritdoc/>
        public IReadOnlyList<LocalizedString> GetAllStrings(CultureInfo culture)
        {
            if (_defaultDictionary == null)
            {
                throw new AbpException("No default dictionary is defined!");
            }

            //Create a temp dictionary to build
            var dict = new Dictionary<string, LocalizedString>();

            //Fill all strings from default dictionary
            foreach (var defaultDictString in _defaultDictionary.GetAllStrings())
            {
                dict[defaultDictString.Name] = defaultDictString;
            }

            //Overwrite all strings from the language based on country culture
            if (culture.Name.Length == 5)
            {
                ILocalizationDictionary langDictionary;
                if (_dictionaries.TryGetValue(culture.Name.Substring(0, 2), out langDictionary))
                {
                    foreach (var langString in langDictionary.GetAllStrings())
                    {
                        dict[langString.Name] = langString;
                    }
                }
            }

            //Overwrite all strings from the original dictionary
            ILocalizationDictionary originalDictionary;
            if (_dictionaries.TryGetValue(culture.Name, out originalDictionary))
            {
                foreach (var originalLangString in originalDictionary.GetAllStrings())
                {
                    dict[originalLangString.Name] = originalLangString;
                }
            }

            return dict.Values.ToImmutableList();
        }

        /// <summary>
        /// Extends the source with given dictionary.
        /// </summary>
        /// <param name="dictionary">Dictionary to extend the source</param>
        public void Extend(ILocalizationDictionary dictionary)
        {
            //Add
            ILocalizationDictionary existingDictionary;
            if (!_dictionaries.TryGetValue(dictionary.CultureInfo.Name, out existingDictionary))
            {
                _dictionaries[dictionary.CultureInfo.Name] = dictionary;
                return;
            }

            //Override
            var localizedStrings = dictionary.GetAllStrings();
            foreach (var localizedString in localizedStrings)
            {
                existingDictionary[localizedString.Name] = localizedString.Value;
            }
        }
    }
}


text:
require "initializer_helpers/version"

module InitializerHelpers
  module_function

  def skip_console_rake_generators &block
    skip(console? || generators? || rake?, &block)
  end

  def skip_rake_generators &block
    skip(generators? || rake?, &block)
  end

  def skip_generators &block
    skip(generators?, &block)
  end

  def skip_console &block
    skip(console?, &block)
  end

  def skip_rake_generators_include_jobs_work &block
    skip(generators? || (rake? && !rake_jobs_work?), &block)
  end

  def rake?
    File.basename($0) == 'rake'
  end

  def rake_jobs_work?
    Rake.application.top_level_tasks.include?('jobs:work')
  end

  def console?
    defined? Rails::Console
  end

  def generators?
    defined? Rails::Generators
  end

  private
  module_function

  def skip(condition, &block)
    raise ArgumentError, 'no block given' if block.blank?
    yield unless condition
  end
end


text:
<?php

//Reference Documentation: http://support.chargify.com/faqs/api/api-subscriptions

class ChargifyCreditCard extends ChargifyConnector
{
  private $card_type;
  private $expiration_month;
  private $expiration_year;
  private $first_name;
  private $last_name;
  private $masked_card_number;

  public function __construct(SimpleXMLElement $cc_xml_node)
  {
    //Load object dynamically and convert SimpleXMLElements into strings
    foreach($cc_xml_node as $key => $element) { $this->$key = (string)$element; }
  }

  /* Getters */

  public function getCardType() { return $this->card_type; }

  public function getExpirationMonth() { return $this->expiration_month; }

  public function getExpirationYear() { return $this->expiration_year; }

  public function getFirstName() { return $this->first_name; }

  public function getLastName() { return $this->last_name; }

  public function getMaskedCardNumber() { return $this->masked_card_number; }
}

?>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.eclipse.emf.cdo.common.id.CDOIDReference (CDO Model Repository Documentation)</title>
<meta name="date" content="">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.eclipse.emf.cdo.common.id.CDOIDReference

Packages that use CDOIDReference

Package
Description

org.eclipse.emf.cdo.common.protocol

Common concepts for dealing with protocols and CDO-specific I/O.

org.eclipse.emf.cdo.server

Server concepts for dealing with repositories and stores.

org.eclipse.emf.cdo.spi.common.protocol

Common base implementations for dealing with I/O of CDO data structures.

Uses of CDOIDReference in org.eclipse.emf.cdo.common.protocol

Methods in org.eclipse.emf.cdo.common.protocol that return CDOIDReference

Modifier and Type
Method and Description

CDOIDReference
CDODataInput.readCDOIDReference()

Methods in org.eclipse.emf.cdo.common.protocol with parameters of type CDOIDReference

Modifier and Type
Method and Description

void
CDODataOutput.writeCDOIDReference(CDOIDReference idReference)

Uses of CDOIDReference in org.eclipse.emf.cdo.server

Methods in org.eclipse.emf.cdo.server that return types with arguments of type CDOIDReference

Modifier and Type
Method and Description

List<CDOIDReference>
IStoreAccessor.CommitContext.getXRefs()

Uses of CDOIDReference in org.eclipse.emf.cdo.spi.common.protocol

Methods in org.eclipse.emf.cdo.spi.common.protocol that return CDOIDReference

Modifier and Type
Method and Description

CDOIDReference
CDODataInputImpl.readCDOIDReference()

Methods in org.eclipse.emf.cdo.spi.common.protocol with parameters of type CDOIDReference

Modifier and Type
Method and Description

void
CDODataOutputImpl.writeCDOIDReference(CDOIDReference idReference)

Skip navigation links

Overview

Package

Class

Use

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright (c) 2011-2015 Eike Stepper (Berlin, Germany) and others.


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ccsu.cs407.creational;

/**
 *
 * @author cw1491
 */
public interface MazeFactoryInterface {
  public Wall makeWall();
  public Door makeDoor();
  public Room makeRoom();
}


text:
/* $Id$ */

package org.apache.fop.render;

// Java
import java.io.IOException;
import java.io.OutputStream;

import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.area.LineArea;
import org.apache.fop.area.OffDocumentItem;
import org.apache.fop.area.PageSequence;
import org.apache.fop.area.PageViewport;
import org.apache.fop.fonts.FontInfo;

/**
 * Interface implemented by all renderers. This interface is used to control
 * the rendering of pages and to let block and inline level areas call the
 * appropriate method to render themselves.

 *
 * A Renderer implementation takes areas/spaces and produces output in some
 * format.

 *
 * Typically, most renderers are subclassed from FOP's abstract implementations
 * ({@link AbstractRenderer}, {@link PrintRenderer}) which already handle a lot
 * of things letting you concentrate on the details of the output format.
 */
public interface Renderer {

    /**
     * Role constant for Avalon.
     */
    String ROLE = Renderer.class.getName();

    /**
     * Get the MIME type of the renderer.
     *
     * @return The MIME type of the renderer, may return null if not applicable.
     */
    String getMimeType();

        /**
     * Initiates the rendering phase.
     * This must only be called once for a rendering. If
     * stopRenderer is called then this may be called again
     * for a new document rendering.
     *
     * @param outputStream     The OutputStream to use for output
     * @exception IOException  If an I/O error occurs
     */
    void startRenderer(OutputStream outputStream)
        throws IOException;

    /**
     * Signals the end of the rendering phase.
     * The renderer should reset to an initial state and dispose of
     * any resources for the completed rendering.
     *
     * @exception IOException  If an I/O error occurs
     */
    void stopRenderer()
        throws IOException;

    /**
     * Set the User Agent.
     *
     * @param agent  The User Agent
     */
    void setUserAgent(FOUserAgent agent);

    /**
     * Returns the associated user agent.
     * @return the user agent
     */
    FOUserAgent getUserAgent();

    /**
     * Set up the given FontInfo.
     *
     * @param fontInfo  The font information
     * @throws FOPException if an error occurs while setting up the font info object
     */
    void setupFontInfo(FontInfo fontInfo) throws FOPException;

    /**
     * Reports if out of order rendering is supported.

     *
     * Normally, all pages of a document are rendered in their natural order
     * (page 1, page 2, page 3 etc.). Some output formats (such as PDF) allow
     * pages to be output in random order. This is helpful to reduce resource
     * strain on the system because a page that cannot be fully resolved
     * doesn't block subsequent pages that are already fully resolved.

     *
     * @return   True if this renderer supports out of order rendering.
     */
    boolean supportsOutOfOrder();

    /**
     * Tells the renderer to process an item not explicitly placed on the
     * document (e.g., PDF bookmarks).  Note - not all renderers will process
     * all off-document items.
     *
     * @param odi  The off-document item to be rendered
     */
    void processOffDocumentItem(OffDocumentItem odi);

    /**
     * @return the adapter for painting Java2D images (or null if not supported)
     */
    Graphics2DAdapter getGraphics2DAdapter();

    /**
     * @return the adapter for painting RenderedImages (or null if not supported)
     */
    ImageAdapter getImageAdapter();

    /**
     * This is called if the renderer supports out of order rendering. The
     * renderer should prepare the page so that a page further on in the set of
     * pages can be rendered. The body of the page should not be rendered. The
     * page will be rendered at a later time by the call to {@link
     * #renderPage(PageViewport)}.
     *
     * @param page  The page viewport to use
     */
    void preparePage(PageViewport page);

    /**
     * Tells the renderer that a new page sequence starts.
     *
     * @param seqTitle  The title of the page sequence
     * @deprecated Use {@link #startPageSequence(PageSequence)} instead
     */
    void startPageSequence(LineArea seqTitle);

    /**
     * Tells the renderer that a new page sequence starts.
     *
     * @param pageSequence the page sequence
     */
    void startPageSequence(PageSequence pageSequence);

    /**
     * Tells the renderer to render a particular page. A renderer typically
     * responds by packing up the current page and writing it immediately to the
     * output device.
     *
     * @param page              The page to be rendered
     * @exception IOException   if an I/O error occurs
     * @exception FOPException  if a FOP interal error occurs.
     */
    void renderPage(PageViewport page)
        throws IOException, FOPException;

}


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

namespace AH.INVMS.MODEL
{
    public class PurchaseOrder
    {
        public string ID { set; get; }
        public string TransactionType { set; get; }
        public string POType { set; get; }
        public DateTime PODate { set; get; }
        public DateTime DeliveryDate { set; get; }
        public string DeliveryNote { set; get; }
        public string CompleteFlag { set; get; }
        public string Remarks { set; get; }
        public string PurchaseBy { set; get; }
        public string POString { set; get; }
        public string TermsDetails { set; get; }
        public float PendingReqQty { set; get; }
        public float PrevPO { set; get; }
        public ItemOrder ItemOrder { set; get; }
        public StoreLocation StoreLocation { set; get; }
        public Warehouse Warehouse { set; get; }
        public StoreTypeSCM StoreType { set; get; }
        public PurchaseRequisition PurchaseRequisition { set; get; }
        public Supplier Supplier { set; get; }
        public EntryParameter EntryParameter { set; get; }

    }
}


text:
<?php

namespace app\models;

use Yii;

use app\models\general\GeneralLabel;
use app\models\general\GeneralMessage;

/**
 * This is the model class for table "tbl_anugerah_ahli_jawantankuasa_pemilihan".
 *
 * @property integer $anugerah_ahli_jawantankuasa_pemilihan_id
 * @property string $perwakilan
 * @property string $nama
 * @property string $jawatan
 * @property integer $created_by
 * @property integer $updated_by
 * @property string $created
 * @property string $updated
 */
class AnugerahAhliJawantankuasaPemilihan extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbl_anugerah_ahli_jawantankuasa_pemilihan';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['tahun'], 'required'],
            [['created_by', 'updated_by', 'tahun'], 'integer'],
            [['created', 'updated'], 'safe'],
            [['perwakilan', 'nama', 'jawatan'], 'string', 'max' => 80, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['perwakilan', 'nama', 'jawatan'], function ($attribute, $params) {
                if (!\common\models\general\GeneralFunction::validateXSS($this->$attribute)) {
                    $this->addError($attribute, GeneralMessage::yii_validation_xss);
                }
            }],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'anugerah_ahli_jawantankuasa_pemilihan_id' => 'Anugerah Ahli Jawantankuasa Pemilihan ID',
            'perwakilan' => GeneralLabel::perwakilan,  //'Perwakilan',
            'nama' => GeneralLabel::nama,  //'Nama',
            'jawatan' => GeneralLabel::jawatan,  //'Jawatan',
            'tahun' => GeneralLabel::tahun,
            'created_by' => 'Created By',
            'updated_by' => 'Updated By',
            'created' => 'Created',
            'updated' => 'Updated',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRefPerwakilan(){
        return $this->hasOne(RefPerwakilan::className(), ['id' => 'perwakilan']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRefJawatanJawatankuasaPemilihan(){
        return $this->hasOne(RefJawatanJawatankuasaPemilihan::className(), ['id' => 'jawatan']);
    }
}


text:
set EnableNuGetPackageRestore=true
call .\packages\psake.4.3.2\tools\psake.cmd buildSigned.ps1 %*

pause


text:
<?php

namespace PHPExiftool\Driver\Tag\DICOM;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class ControlPoint3DPosition extends AbstractTag
{

    protected $Id = '300A,02D4';

    protected $Name = 'ControlPoint3DPosition';

    protected $FullName = 'DICOM::Main';

    protected $GroupName = 'DICOM';

    protected $g0 = 'DICOM';

    protected $g1 = 'DICOM';

    protected $g2 = 'Image';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Control Point 3D Position';
}


text:
// $Id: server_loggerd.cpp 81978 2008-06-16 16:57:12Z sowayaa $
// server_loggerd.cpp,v 4.29 2003/12/30 23:18:59 shuston Exp

// This server daemon collects, formats, and displays logging
// information forwarded from client daemons running on other hosts in
// the network.  In addition, this example illustrates how to use the
// ACE_Reactor, ACE_Acceptor, ACE_Singleton, and the ACE_Test_and_Set
// components.

#include "ace/OS_NS_string.h"
#include "ace/Get_Opt.h"
#include "ace/Acceptor.h"
#include "ace/Null_Mutex.h"
#include "ace/SOCK_Acceptor.h"
#include "ace/Singleton.h"
#include "ace/CDR_Stream.h"
#include "ace/Auto_Ptr.h"
#include "ace/Test_and_Set.h"

// FUZZ: disable check_for_streams_include
#include "ace/streams.h"

#include "ace/Log_Record.h"
#include "ace/Test_and_Set.h"

#include "server_loggerd.h"

ACE_RCSID(Acceptor_server, server_loggerd, "$Id: server_loggerd.cpp 81978 2008-06-16 16:57:12Z sowayaa $")

// ----------------------------------------

// Return the port number.

u_short
Options::port (void)
{
  return this->port_;
}

// Parse the command-line options.

void
Options::parse_args (int argc, ACE_TCHAR *argv[])
{
  this->port_ = ACE_DEFAULT_SERVER_PORT;

  ACE_Get_Opt get_opt (argc, argv, ACE_TEXT ("p:"));

  for (int c; (c = get_opt ()) != -1; )
    switch (c)
      {
      case 'p':
        this->port_ = ACE_OS::atoi (get_opt.opt_arg ());
        break;
      default:
        break;
      }
}

// ----------------------------------------

// Our Reactor Singleton.
typedef ACE_Singleton<ACE_Reactor, ACE_Null_Mutex>
REACTOR;

// Our Options Singleton.
typedef ACE_Singleton<Options, ACE_Null_Mutex>
OPTIONS;

// Our ACE_Test_and_Set Singleton.
typedef ACE_Singleton<ACE_Test_and_Set <ACE_Null_Mutex, sig_atomic_t>, ACE_Null_Mutex>
QUIT_HANDLER;

// ----------------------------------------

// Specialize a Logging Acceptor.
typedef ACE_Acceptor <Logging_Handler, ACE_SOCK_ACCEPTOR>
Logging_Acceptor;

// Default constructor.

Logging_Handler::Logging_Handler (void)
{
}

int
Logging_Handler::handle_timeout (const ACE_Time_Value &,
                                 const void *arg)
{
#if defined (ACE_NDEBUG)
  ACE_UNUSED_ARG (arg);
#endif /* ACE_NDEBUG */

  ACE_ASSERT (arg == this);
  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%P|%t) handling timeout from this = %@\n"), this));
  return 0;
}

// Perform the logging record receive.

int
Logging_Handler::handle_input (ACE_HANDLE)
{
  ACE_Log_Record log_record;

  // We need to use the old two-read trick here since TCP sockets
  // don't support framing natively.  Allocate a message block for the
  // payload; initially at least large enough to hold the header, but
  // needs some room for alignment.
  ACE_Message_Block *payload_p = 0;
  ACE_Message_Block *header_p = 0;
  ACE_NEW_RETURN (header_p,
                  ACE_Message_Block (ACE_DEFAULT_CDR_BUFSIZE),
                  -1);

  auto_ptr <ACE_Message_Block> header (header_p);

  // Align the Message Block for a CDR stream
  ACE_CDR::mb_align (header.get ());

  ACE_CDR::Boolean byte_order;
  ACE_CDR::ULong length;

  ssize_t count = ACE::recv_n (this->peer ().get_handle (),
                               header->wr_ptr (),
                               8);
  switch (count)
    {
      // Handle shutdown and error cases.
    default:
    case -1:
    case 0:

      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("server logging daemon closing down\n")));

      return -1;
      /* NOTREACHED */

    case 8:
      // Just fall through in this case..
      break;
    }

  header->wr_ptr (8); // Reflect addition of 8 bytes.

  // Create a CDR stream to parse the 8-byte header.
  ACE_InputCDR header_cdr (header.get ());

  // Extract the byte-order and use helper methods to disambiguate
  // octet, booleans, and chars.
  header_cdr >> ACE_InputCDR::to_boolean (byte_order);

  // Set the byte-order on the stream...
  header_cdr.reset_byte_order (byte_order);

  // Extract the length
  header_cdr >> length;

  ACE_NEW_RETURN (payload_p,
                  ACE_Message_Block (length),
                  -1);
  auto_ptr <ACE_Message_Block> payload (payload_p);

  // Ensure there's sufficient room for log record payload.
  ACE_CDR::grow (payload.get (), 8 + ACE_CDR::MAX_ALIGNMENT + length);

  // Use <recv_n> to obtain the contents.
  if (ACE::recv_n (this->peer ().get_handle (),
                   payload->wr_ptr (),
                   length) <= 0)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("%p\n"),
                  ACE_TEXT ("recv_n()")));
      return -1;
    }

  payload->wr_ptr (length);   // Reflect additional bytes

  ACE_InputCDR payload_cdr (payload.get ());
  payload_cdr.reset_byte_order (byte_order);
  payload_cdr >> log_record;  // Finally extract the <ACE_log_record>.

  log_record.length (length);

  log_record.print (ACE_TEXT_CHAR_TO_TCHAR (this->peer_name_), 1, stderr);

  return 0;
}

int
Logging_Handler::open (void *)
{
  ACE_INET_Addr addr;

  if (this->peer ().get_remote_addr (addr) == -1)
    return -1;
  else
    {
      ACE_OS::strncpy (this->peer_name_,
                       addr.get_host_name (),
                       MAXHOSTNAMELEN + 1);

      if (REACTOR::instance ()->register_handler (this, READ_MASK) == -1)
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT ("(%P|%t) can't register with reactor\n")),
                          -1);
      else if (REACTOR::instance ()->schedule_timer
               (this,
                (const void *) this,
                ACE_Time_Value (2),
                ACE_Time_Value (2)) == -1)
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT ("(%P|%t) can't register with reactor\n")),
                          -1);
      else
        ACE_DEBUG ((LM_DEBUG,
                    ACE_TEXT ("(%P|%t) connected with %C\n"),
                    this->peer_name_));
      return 0;
    }
}

int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  // Acceptor factory.
  Logging_Acceptor peer_acceptor;

  OPTIONS::instance ()->parse_args (argc, argv);

  // We need to pass in REACTOR::instance () here so that we don't use
  // the default ACE_Reactor::instance ().

  if (peer_acceptor.open
      (ACE_INET_Addr (OPTIONS::instance ()->port ()),
       REACTOR::instance ()) == -1)
    ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("open")), -1);

  // Register QUIT_HANDLER to receive SIGINT commands.  When received,
  // QUIT_HANDLER becomes "set" and thus, the event loop below will
  // exit.
  else if (REACTOR::instance ()->register_handler
           (SIGINT, QUIT_HANDLER::instance ()) == -1)
    ACE_ERROR_RETURN ((LM_ERROR,
                       ACE_TEXT ("registering service with ACE_Reactor\n")),
                      -1);

  // Run forever, performing logging service.

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%P|%t) starting up server logging daemon\n")));

  // Perform logging service until QUIT_HANDLER receives SIGINT.
  while (QUIT_HANDLER::instance ()->is_set () == 0)
    REACTOR::instance ()->handle_events ();

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%P|%t) shutting down server logging daemon\n")));

  return 0;
}

#if defined (ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION)
template ACE_Singleton<ACE_Reactor, ACE_Null_Mutex> *
  ACE_Singleton<ACE_Reactor, ACE_Null_Mutex>::singleton_;
template ACE_Singleton<Options, ACE_Null_Mutex> *
  ACE_Singleton<Options, ACE_Null_Mutex>::singleton_;
template ACE_Singleton<ACE_Test_and_Set <ACE_Null_Mutex, sig_atomic_t>, ACE_Null_Mutex> *
  ACE_Singleton<ACE_Test_and_Set <ACE_Null_Mutex, sig_atomic_t>, ACE_Null_Mutex>::singleton_;
#endif /* ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION */


text:
<?php

namespace Phobetor\RabbitMqSupervisorBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * @license MIT
 */
class RabbitMqSupervisorBundle extends Bundle
{
}


text:
module.exports = {
    'secret': 'learnRestApiwithNickjs', // used when we create and verify JSON Web Tokens
    'database': 'mongodb://localhost:27017/runoob' // 填写本地自己 mongodb 连接地址,xxx为数据表名
};


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:layout_gravity="center"
    android:weightSum="1"
    style="f">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
    />

</LinearLayout>


text:
<?php

namespace Plop;

/**
 * \brief
 *      This exception is thrown by Plop whenever
 *      a problem is detected.
 *
 * @codeCoverageIgnore
 */
class Exception extends \Exception
{
}


text:
title: "Community Round-up #11"
author: Vjeux
---

This round-up is the proof that React has taken off from its Facebook's root: it features three in-depth presentations of React done by external people. This is awesome, keep them coming!

## Super VanJS 2013 Talk

[Steve Luscher](https://github.com/steveluscher) working at [LeanPub](https://leanpub.com/) made a 30 min talk at [Super VanJS](https://twitter.com/vanjs). He does a remarkable job at explaining why React is so fast with very exciting demos using the HTML5 Audio API.

## React Tips

[Connor McSheffrey](http://connormcsheffrey.com/) and [Cheng Lou](https://github.com/chenglou) added a new section to the documentation. It's a list of small tips that you will probably find useful while working on React. Since each article is very small and focused, we [encourage you to contribute](/react/tips/introduction.html)!

- [Inline Styles](/react/tips/inline-styles.html)
- [If-Else in JSX](/react/tips/if-else-in-JSX.html)
- [Self-Closing Tag](/react/tips/self-closing-tag.html)
- [Maximum Number of JSX Root Nodes](/react/tips/maximum-number-of-jsx-root-nodes.html)
- [Shorthand for Specifying Pixel Values in style props](/react/tips/style-props-value-px.html)
- [Type of the Children props](/react/tips/children-props-type.html)
- [Value of null for Controlled Input](/react/tips/controlled-input-null-value.html)
- [`componentWillReceiveProps` Not Triggered After Mounting](/react/tips/componentWillReceiveProps-not-triggered-after-mounting.html)
- [Props in getInitialState Is an Anti-Pattern](/react/tips/props-in-getInitialState-as-anti-pattern.html)
- [DOM Event Listeners in a Component](/react/tips/dom-event-listeners.html)
- [Load Initial Data via AJAX](/react/tips/initial-ajax.html)
- [False in JSX](/react/tips/false-in-jsx.html)

## Intro to the React Framework

[Pavan Podila](http://blog.pixelingene.com/) wrote an in-depth introduction to React on TutsPlus. This is definitively worth reading.

> Within a component-tree, data should always flow down. A parent-component should set the props of a child-component to pass any data from the parent to the child. This is termed as the Owner-Owned pair. On the other hand user-events (mouse, keyboard, touches) will always bubble up from the child all the way to the root component, unless handled in between.

[![](/react/img/blog/tutsplus.png)](http://dev.tutsplus.com/tutorials/intro-to-the-react-framework--net-35660)

>
> [Read the full article ...](http://dev.tutsplus.com/tutorials/intro-to-the-react-framework--net-35660)

## 140-characters textarea

[Brian Kim](https://github.com/brainkim) wrote a small textarea component that gradually turns red as you reach the 140-characters limit. Because he only changes the background color, React is smart enough not to mess with the text selection.

See the Pen FECGb by Brian Kim (@brainkim) on CodePen

## Genesis Skeleton

[Eric Clemmons](https://ericclemmons.github.io/) is working on a "Modern, opinionated, full-stack starter kit for rapid, streamlined application development". The version 0.4.0 has just been released and has first-class support for React.

[![](/react/img/blog/genesis_skeleton.png)](http://genesis-skeleton.com/)

## AgFlow Talk

[Robert Zaremba](http://rz.scale-it.pl/) working on [AgFlow](http://www.agflow.com/) recently talked in Poland about React.

> In a nutshell, I presented why we chose React among other available options (ember.js, angular, backbone ...) in AgFlow, where I'm leading an application development.
>
> During the talk a wanted to highlight that React is not about implementing a Model, but a way to construct visible components with some state. React is simple. It is super simple, you can learn it in 1h. On the other hand what is model? Which functionality it should provide? React does one thing and does it the best (for me)!
>
> [Read the full article...](http://rz.scale-it.pl/2013/10/20/frontend_components_in_react.html)

## JSX

[Todd Kennedy](http://tck.io/) working at Condé Nast wrote [JSXHint](https://github.com/CondeNast/JSXHint) and explains in a blog post his perspective on JSX.

> Lets start with the elephant in the room: JSX?
> Is this some sort of template language? Specifically no. This might have been the first big stumbling block. What looks like to be a templating language is actually an in-line DSL that gets transpiled directly into JavaScript by the JSX transpiler.
>
> Creating elements in memory is quick -- copying those elements into the DOM is where the slowness occurs. This is due to a variety of issues, most namely reflow/paint. Changing the items in the DOM causes the browser to re-paint the display, apply styles, etc. We want to keep those operations to an absolute minimum, especially if we're dealing with something that needs to update the DOM frequently.
>
> [Read the full article...](http://tck.io/posts/jsxhint_and_react.html)

## Photo Gallery

[Maykel Loomans](http://miekd.com/), designer at Instagram, wrote a gallery for photos he shot using React.

[![](/react/img/blog/xoxo2013.png)](http://photos.miekd.com/xoxo2013/)

## Random Tweet

I think this reversed gif of Steve Urkel best describes my changing emotions towards the React Lib http://t.co/JoX0XqSXX3
— Ryan Seddon (@ryanseddon) November 7, 2013


text:
#ifndef _CHAT_H
#define _CHAT_H

#include <deque>
#include <string>

class User;

class Chat
{
public:
  enum MessageTarget
  {
    ALL,
    USER,
    OTHERS,
    ADMINS,
    OPS,
    GUESTS
  };

  Chat();
  ~Chat();

  bool handleMsg(User* user, std::string msg);
  void handleServerMsg(User* user, std::string msg, const std::string& timeStamp);
  void handleAdminChatMsg(User* user, std::string msg, const std::string& timeStamp);
  void handleChatMsg(User* user, std::string msg, const std::string& timeStamp);

  bool sendMsg(User* user, std::string msg, MessageTarget action = ALL);
  bool sendUserlist(User* user);
  void sendHelp(User* user, std::deque<std::string> args);

  void handleCommand(User* user, std::string msg, const std::string& timeStamp);

private:
  std::deque<std::string> parseCmd(std::string cmd);
  std::string adminPassword;
};

#endif


text:
/*-------------------------------------------------------------------------
 *
 * lmgr.h
 *	  POSTGRES lock manager definitions.
 *
 *
 * Portions Copyright (c) 2006-2008, Greenplum inc
 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 * $PostgreSQL: pgsql/src/include/storage/lmgr.h,v 1.56 2006/08/18 16:09:13 tgl Exp $
 *
 *-------------------------------------------------------------------------
 */
#ifndef LMGR_H
#define LMGR_H

#include "lib/stringinfo.h"
#include "storage/itemptr.h"
#include "storage/lock.h"
#include "utils/rel.h"

extern void RelationInitLockInfo(Relation relation);

/* Lock a relation */
extern void LockRelationOid(Oid relid, LOCKMODE lockmode);
extern bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode);
extern void UnlockRelationId(LockRelId *relid, LOCKMODE lockmode);
extern void UnlockRelationOid(Oid relid, LOCKMODE lockmode);

extern void LockRelation(Relation relation, LOCKMODE lockmode);
extern bool ConditionalLockRelation(Relation relation, LOCKMODE lockmode);
extern void UnlockRelation(Relation relation, LOCKMODE lockmode);

extern void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode);
extern void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode);

/* Lock a relation for extension */
extern void LockRelationForExtension(Relation relation, LOCKMODE lockmode);
extern void UnlockRelationForExtension(Relation relation, LOCKMODE lockmode);
extern void LockRelationForResyncExtension(RelFileNode *relFileNode, LOCKMODE lockmode);
extern void UnlockRelationForResyncExtension(RelFileNode *relFileNode, LOCKMODE lockmode);

/* Lock a relation for Append-Only segment files. */
extern LockAcquireResult LockRelationAppendOnlySegmentFile(RelFileNode *relFileNode, int32 segno, LOCKMODE lockmode, bool dontWait);
extern void UnlockRelationAppendOnlySegmentFile(RelFileNode *relFileNode, int32 segno, LOCKMODE lockmode, int32 contentid);

/* Lock a page (currently only used within indexes) */
extern void LockPage(Relation relation, BlockNumber blkno, LOCKMODE lockmode);
extern bool ConditionalLockPage(Relation relation, BlockNumber blkno, LOCKMODE lockmode);
extern void UnlockPage(Relation relation, BlockNumber blkno, LOCKMODE lockmode);

/* Lock a tuple (see heap_lock_tuple before assuming you understand this) */
extern void LockTuple(Relation relation, ItemPointer tid, LOCKMODE lockmode);
extern bool ConditionalLockTuple(Relation relation, ItemPointer tid,
					 LOCKMODE lockmode);
extern void UnlockTuple(Relation relation, ItemPointer tid, LOCKMODE lockmode);

/* Lock an XID (used to wait for a transaction to finish) */
extern void XactLockTableInsert(TransactionId xid);
extern void XactLockTableDelete(TransactionId xid);
extern void XactLockTableWait(TransactionId xid);
extern bool ConditionalXactLockTableWait(TransactionId xid);

/* Lock a general object (other than a relation) of the current database */
extern void LockDatabaseObject(Oid classid, Oid objid, uint16 objsubid,
				   LOCKMODE lockmode);
extern void UnlockDatabaseObject(Oid classid, Oid objid, uint16 objsubid,
					 LOCKMODE lockmode);

/* Lock a shared-across-databases object (other than a relation) */
extern void LockSharedObject(Oid classid, Oid objid, uint16 objsubid,
				 LOCKMODE lockmode);
extern void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid,
				   LOCKMODE lockmode);
/* Knowledge about which locktags describe temp objects */
extern bool LockTagIsTemp(const LOCKTAG *tag);

#endif   /* LMGR_H */


text:
import Event from "app/models/Event";
import type {Position} from "app/models/Matrix";

export default class MoveEvent extends Event {
    position: Position;
    newPosition: Position;

    constructor(position: Position, newPosition: Position) {
        super();
        this.position = position;
        this.newPosition = newPosition;
    }
}