text:
import collections
import os
import sys

import numpy
try:
    from PIL import Image
    available = True
except ImportError as e:
    available = False
    _import_error = e

import chainer
from chainer.dataset.convert import concat_examples
from chainer.dataset import download
from chainer import function
from chainer.functions.activation.relu import relu
from chainer.functions.activation.softmax import softmax
from chainer.functions.array.reshape import reshape
from chainer.functions.math.average import average
from chainer.functions.noise.dropout import dropout
from chainer.functions.normalization.local_response_normalization import (
    local_response_normalization)
from chainer.functions.pooling.average_pooling_2d import average_pooling_2d
from chainer.functions.pooling.max_pooling_2d import max_pooling_2d
from chainer.initializers import constant
from chainer.initializers import uniform
from chainer import link
from chainer.links.connection.convolution_2d import Convolution2D
from chainer.links.connection.inception import Inception
from chainer.links.connection.linear import Linear
from chainer.serializers import npz
from chainer.utils import argument
from chainer.utils import imgproc
from chainer.variable import Variable

class GoogLeNet(link.Chain):

    """A pre-trained GoogLeNet model provided by BVLC.

    When you specify the path of the pre-trained chainer model serialized as
    a ``.npz`` file in the constructor, this chain model automatically
    initializes all the parameters with it.
    This model would be useful when you want to extract a semantic feature
    vector per image, or fine-tune the model on a different dataset.

    If you want to manually convert the pre-trained caffemodel to a chainer
    model that can be specified in the constructor,
    please use ``convert_caffemodel_to_npz`` classmethod instead.

    GoogLeNet, which is also called Inception-v1, is an architecture of
    convolutional neural network proposed in 2014. This model is relatively
    lightweight and requires small memory footprint during training compared
    with modern architectures such as ResNet. Therefore, if you fine-tune your
    network based on a model pre-trained by Imagenet and need to train it with
    large batch size, GoogLeNet may be useful. On the other hand, if you just
    want an off-the-shelf classifier, we recommend you to use ResNet50 or other
    models since they are more accurate than GoogLeNet.

    The original model is provided here:
    `<https://github.com/BVLC/caffe/tree/master/models/bvlc_googlenet>`_

    Args:
        pretrained_model (str): the destination of the pre-trained
            chainer model serialized as a ``.npz`` file.
            If this argument is specified as ``auto``,
            it automatically downloads the caffemodel from the internet.
            Note that in this case the converted chainer model is stored
            on ``$CHAINER_DATASET_ROOT/pfnet/chainer/models`` directory,
            where ``$CHAINER_DATASET_ROOT`` is set as
            ``$HOME/.chainer/dataset`` unless you specify another value
            as a environment variable. The converted chainer model is
            automatically used from the second time.
            If the argument is specified as ``None``, all the parameters
            are not initialized by the pre-trained model, but the default
            initializer used in BVLC, i.e.,
            ``chainer.initializers.LeCunUniform(scale=1.0)``.
            Note that, in Caffe, when weight_filler is specified as
            "xavier" type without variance_norm parameter, the weights are
            initialized by Uniform(-s, s), where
            :math:`s = \\sqrt{\\frac{3}{fan_{in}}}` and :math:`fan_{in}` is the
            number of input units. This corresponds to LeCunUniform in Chainer
            but not GlorotUniform.

    Attributes:
        available_layers (list of str): The list of available layer names
            used by ``forward`` and ``extract`` methods.

    """

    def __init__(self, pretrained_model='auto'):
        super(GoogLeNet, self).__init__()

        if pretrained_model:
            # As a sampling process is time-consuming,
            # we employ a zero initializer for faster computation.
            kwargs = {'initialW': constant.Zero()}
        else:
            # employ default initializers used in BVLC. For more detail, see
            # https://github.com/chainer/chainer/pull/2424#discussion_r109642209
            kwargs = {'initialW': uniform.LeCunUniform(scale=1.0)}

        with self.init_scope():
            self.conv1 = Convolution2D(3, 64, 7, stride=2, pad=3, **kwargs)
            self.conv2_reduce = Convolution2D(64, 64, 1, **kwargs)
            self.conv2 = Convolution2D(64, 192, 3, stride=1, pad=1, **kwargs)
            self.inc3a = Inception(192, 64, 96, 128, 16, 32, 32)
            self.inc3b = Inception(256, 128, 128, 192, 32, 96, 64)
            self.inc4a = Inception(480, 192, 96, 208, 16, 48, 64)
            self.inc4b = Inception(512, 160, 112, 224, 24, 64, 64)
            self.inc4c = Inception(512, 128, 128, 256, 24, 64, 64)
            self.inc4d = Inception(512, 112, 144, 288, 32, 64, 64)
            self.inc4e = Inception(528, 256, 160, 320, 32, 128, 128)
            self.inc5a = Inception(832, 256, 160, 320, 32, 128, 128)
            self.inc5b = Inception(832, 384, 192, 384, 48, 128, 128)
            self.loss3_fc = Linear(1024, 1000, **kwargs)

            self.loss1_conv = Convolution2D(512, 128, 1, **kwargs)
            self.loss1_fc1 = Linear(2048, 1024, **kwargs)
            self.loss1_fc2 = Linear(1024, 1000, **kwargs)

            self.loss2_conv = Convolution2D(528, 128, 1, **kwargs)
            self.loss2_fc1 = Linear(2048, 1024, **kwargs)
            self.loss2_fc2 = Linear(1024, 1000, **kwargs)

        if pretrained_model == 'auto':
            _retrieve(
                'bvlc_googlenet.npz',
                'http://dl.caffe.berkeleyvision.org/bvlc_googlenet.caffemodel',
                self)
        elif pretrained_model:
            npz.load_npz(pretrained_model, self)

    @property
    def functions(self):
        return collections.OrderedDict([
            ('conv1', [self.conv1, relu]),
            ('pool1', [_max_pooling_2d, _local_response_normalization]),
            ('conv2_reduce', [self.conv2_reduce, relu]),
            ('conv2', [self.conv2, relu, _local_response_normalization]),
            ('pool2', [_max_pooling_2d]),
            ('inception_3a', [self.inc3a]),
            ('inception_3b', [self.inc3b]),
            ('pool3', [_max_pooling_2d]),
            ('inception_4a', [self.inc4a]),
            ('inception_4b', [self.inc4b]),
            ('inception_4c', [self.inc4c]),
            ('inception_4d', [self.inc4d]),
            ('inception_4e', [self.inc4e]),
            ('pool4', [_max_pooling_2d]),
            ('inception_5a', [self.inc5a]),
            ('inception_5b', [self.inc5b]),
            ('pool5', [_average_pooling_2d_k7]),
            ('loss3_fc', [_dropout, self.loss3_fc]),
            ('prob', [softmax]),
            # Since usually the following outputs are not used, they are put
            # after 'prob' to be skipped for efficiency.
            ('loss1_fc2', [_average_pooling_2d_k5, self.loss1_conv, relu,
                           self.loss1_fc1, relu, self.loss1_fc2]),
            ('loss2_fc2', [_average_pooling_2d_k5, self.loss2_conv, relu,
                           self.loss2_fc1, relu, self.loss2_fc2])
        ])

    @property
    def available_layers(self):
        return list(self.functions.keys())

    @classmethod
    def convert_caffemodel_to_npz(cls, path_caffemodel, path_npz):
        """Converts a pre-trained caffemodel to a chainer model.

        Args:
            path_caffemodel (str): Path of the pre-trained caffemodel.
            path_npz (str): Path of the converted chainer model.
        """

        # As CaffeFunction uses shortcut symbols,
        # we import CaffeFunction here.
        from chainer.links.caffe.caffe_function import CaffeFunction
        caffemodel = CaffeFunction(path_caffemodel)
        chainermodel = cls(pretrained_model=None)
        _transfer_googlenet(caffemodel, chainermodel)
        npz.save_npz(path_npz, chainermodel, compression=False)

    def forward(self, x, layers=None, **kwargs):
        """forward(self, x, layers=['prob'])

        Computes all the feature maps specified by ``layers``.

        Args:
            x (~chainer.Variable): Input variable. It should be prepared by
                ``prepare`` function.
            layers (list of str): The list of layer names you want to extract.

        Returns:
            Dictionary of ~chainer.Variable: A directory in which
            the key contains the layer name and the value contains
            the corresponding feature map variable.

        """

        if layers is None:
            layers = ['prob']

        if kwargs:
            argument.check_unexpected_kwargs(
                kwargs, train='train argument is not supported anymore. '
                'Use chainer.using_config')
            argument.assert_kwargs_empty(kwargs)

        h = x
        activations = {}
        inception_4a_cache = None
        inception_4d_cache = None
        target_layers = set(layers)
        for key, funcs in self.functions.items():
            if not target_layers:
                break

            if key == 'loss1_fc2':
                h = inception_4a_cache
            elif key == 'loss2_fc2':
                h = inception_4d_cache

            for func in funcs:
                h = func(h)
            if key in target_layers:
                activations[key] = h
                target_layers.remove(key)

            if key == 'inception_4a':
                inception_4a_cache = h
            elif key == 'inception_4d':
                inception_4d_cache = h

        return activations

    def extract(self, images, layers=None, size=(224, 224), **kwargs):
        """extract(self, images, layers=['pool5'], size=(224, 224))

        Extracts all the feature maps of given images.

        The difference of directly executing ``forward`` is that
        it directly accepts images as an input and automatically
        transforms them to a proper variable. That is,
        it is also interpreted as a shortcut method that implicitly calls
        ``prepare`` and ``forward`` functions.

        Unlike ``predict`` method, this method does not override
        ``chainer.config.train`` and ``chainer.config.enable_backprop``
        configuration. If you want to extract features without updating
        model parameters, you need to manually set configuration when
        calling this method as follows:

         .. code-block:: python

             # model is an instance of `GoogLeNet`
             with chainer.using_config('train', False):
                 with chainer.using_config('enable_backprop', False):
                     feature = model.extract([image])

        Args:
            images (iterable of PIL.Image or numpy.ndarray): Input images.
            layers (list of str): The list of layer names you want to extract.
            size (pair of ints): The resolution of resized images used as
                an input of CNN. All the given images are not resized
                if this argument is ``None``, but the resolutions of
                all the images should be the same.

        Returns:
            Dictionary of ~chainer.Variable: A directory in which
            the key contains the layer name and the value contains
            the corresponding feature map variable.

        """

        if layers is None:
            layers = ['pool5']

        if kwargs:
            argument.check_unexpected_kwargs(
                kwargs, train='train argument is not supported anymore. '
                'Use chainer.using_config',
                volatile='volatile argument is not supported anymore. '
                'Use chainer.using_config')
            argument.assert_kwargs_empty(kwargs)

        x = concat_examples([prepare(img, size=size) for img in images])
        x = Variable(self.xp.asarray(x))
        return self(x, layers=layers)

    def predict(self, images, oversample=True):
        """Computes all the probabilities of given images.

        Args:
            images (iterable of PIL.Image or numpy.ndarray): Input images.
                When you specify a color image as a :class:`numpy.ndarray`,
                make sure that color order is RGB.
            oversample (bool): If ``True``, it averages results across
                center, corners, and mirrors. Otherwise, it uses only the
                center.

        Returns:
            ~chainer.Variable: Output that contains the class probabilities
            of given images.

        """

        x = concat_examples([prepare(img, size=(256, 256)) for img in images])
        if oversample:
            x = imgproc.oversample(x, crop_dims=(224, 224))
        else:
            x = x[:, :, 16:240, 16:240]
        # Use no_backprop_mode to reduce memory consumption
        with function.no_backprop_mode(), chainer.using_config('train', False):
            x = Variable(self.xp.asarray(x))
            y = self(x, layers=['prob'])['prob']
            if oversample:
                n = len(y) // 10
                y_shape = y.shape[1:]
                y = reshape(y, (n, 10) + y_shape)
                y = average(y, axis=1)
        return y

def prepare(image, size=(224, 224)):
    """Converts the given image to the numpy array for GoogLeNet.

    Note that you have to call this method before ``forward``
    because the pre-trained GoogLeNet model requires to resize the given
    image, covert the RGB to the BGR, subtract the mean,
    and permute the dimensions before calling.

    Args:
        image (PIL.Image or numpy.ndarray): Input image.
            If an input is ``numpy.ndarray``, its shape must be
            ``(height, width)``, ``(height, width, channels)``,
            or ``(channels, height, width)``, and
            the order of the channels must be RGB.
        size (pair of ints): Size of converted images.
            If ``None``, the given image is not resized.

    Returns:
        numpy.ndarray: The converted output array.

    """

    if not available:
        raise ImportError('PIL cannot be loaded. Install Pillow!\n'
                          'The actual import error is as follows:\n' +
                          str(_import_error))
    dtype = chainer.get_dtype()
    if isinstance(image, numpy.ndarray):
        if image.ndim == 3:
            if image.shape[0] == 1:
                image = image[0, :, :]
            elif image.shape[0] == 3:
                image = image.transpose((1, 2, 0))
        image = Image.fromarray(image.astype(numpy.uint8))
    image = image.convert('RGB')
    if size:
        image = image.resize(size)
    image = numpy.asarray(image, dtype=dtype)
    image = image[:, :, ::-1]
    image -= numpy.array([104.0, 117.0, 123.0], dtype=dtype)  # BGR
    image = image.transpose((2, 0, 1))
    return image

def _transfer_inception(src, dst, names):
    for name in names:
        chain = getattr(dst, 'inc{}'.format(name))
        src_prefix = 'inception_{}/'.format(name)
        chain.conv1.W.array[:] = src[src_prefix + '1x1'].W.array
        chain.conv1.b.array[:] = src[src_prefix + '1x1'].b.array
        chain.proj3.W.array[:] = src[src_prefix + '3x3_reduce'].W.array
        chain.proj3.b.array[:] = src[src_prefix + '3x3_reduce'].b.array
        chain.conv3.W.array[:] = src[src_prefix + '3x3'].W.array
        chain.conv3.b.array[:] = src[src_prefix + '3x3'].b.array
        chain.proj5.W.array[:] = src[src_prefix + '5x5_reduce'].W.array
        chain.proj5.b.array[:] = src[src_prefix + '5x5_reduce'].b.array
        chain.conv5.W.array[:] = src[src_prefix + '5x5'].W.array
        chain.conv5.b.array[:] = src[src_prefix + '5x5'].b.array
        chain.projp.W.array[:] = src[src_prefix + 'pool_proj'].W.array
        chain.projp.b.array[:] = src[src_prefix + 'pool_proj'].b.array

def _transfer_googlenet(src, dst):
    # 1 #################################################################
    dst.conv1.W.array[:] = src['conv1/7x7_s2'].W.array
    dst.conv1.b.array[:] = src['conv1/7x7_s2'].b.array

    # 2 #################################################################
    dst.conv2_reduce.W.array[:] = src['conv2/3x3_reduce'].W.array
    dst.conv2_reduce.b.array[:] = src['conv2/3x3_reduce'].b.array
    dst.conv2.W.array[:] = src['conv2/3x3'].W.array
    dst.conv2.b.array[:] = src['conv2/3x3'].b.array

    # 3, 4, 5 ###########################################################
    _transfer_inception(src, dst, ['3a', '3b',
                                   '4a', '4b', '4c', '4d', '4e',
                                   '5a', '5b'])

    # outputs ############################################################
    dst.loss1_conv.W.array[:] = src['loss1/conv'].W.array
    dst.loss1_conv.b.array[:] = src['loss1/conv'].b.array
    dst.loss1_fc1.W.array[:] = src['loss1/fc'].W.array
    dst.loss1_fc1.b.array[:] = src['loss1/fc'].b.array
    dst.loss1_fc2.W.array[:] = src['loss1/classifier'].W.array
    dst.loss1_fc2.b.array[:] = src['loss1/classifier'].b.array

    dst.loss2_conv.W.array[:] = src['loss2/conv'].W.array
    dst.loss2_conv.b.array[:] = src['loss2/conv'].b.array
    dst.loss2_fc1.W.array[:] = src['loss2/fc'].W.array
    dst.loss2_fc1.b.array[:] = src['loss2/fc'].b.array
    dst.loss2_fc2.W.array[:] = src['loss2/classifier'].W.array
    dst.loss2_fc2.b.array[:] = src['loss2/classifier'].b.array

    dst.loss3_fc.W.array[:] = src['loss3/classifier'].W.array
    dst.loss3_fc.b.array[:] = src['loss3/classifier'].b.array

def _max_pooling_2d(x):
    return max_pooling_2d(x, ksize=3, stride=2)

def _local_response_normalization(x):
    return local_response_normalization(x, n=5, k=1, alpha=1e-4 / 5)

def _average_pooling_2d_k5(x):
    return average_pooling_2d(x, ksize=5, stride=3)

def _average_pooling_2d_k7(x):
    return average_pooling_2d(x, ksize=7, stride=1)

def _dropout(x):
    return dropout(x, ratio=0.4)

def _make_npz(path_npz, url, model):
    path_caffemodel = download.cached_download(url)
    sys.stderr.write(
        'Now loading caffemodel (usually it may take few minutes)\n')
    sys.stderr.flush()
    GoogLeNet.convert_caffemodel_to_npz(path_caffemodel, path_npz)
    npz.load_npz(path_npz, model)
    return model

def _retrieve(name_npz, url, model):
    root = download.get_dataset_directory('pfnet/chainer/models/')
    path = os.path.join(root, name_npz)
    return download.cache_or_load_file(
        path, lambda path: _make_npz(path, url, model),
        lambda path: npz.load_npz(path, model))


text:
<link href='http://fonts.googleapis.com/css?family=Fenix' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,
    900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Source+Code+Pro:300,400' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Crimson+Text' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Kameron' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Lato:200' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Lato:300' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Lato:400' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Source+Code+Pro' rel='stylesheet' type='text/css'>

<style>

@font-face {
    font-family: "Computer Modern";
    src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');
}

#notebook_panel { /* establish main background and color */
    background: #fff;
    color: #ff0000;
}

div.cell { /* set cell width */
    width:800px;
    margin-left:0%;
    margin-right:auto;
}

div #notebook { /* centers the content */
    background: #fff;
    width: 1000px;
    margin: auto;
    padding-left: 1em;
}

#notebook li { /* more space between bullet points */
    margin-top:0.8em;
}

/* draw border around running cells */
div.cell.border-box-sizing.code_cell.running {
    border: 3px solid #111;
}

/* Put a solid color box around each code cell and its output,
     visually linking them together */
div.cell.code_cell {
    background-color: /*#fff*/ rgba(171,165,131,0.2);
    border-radius: 10px; /* rounded borders */
    padding: 1em;
    margin-top: 1em;
}

.CodeMirror {
    font-family: "Source Code Pro";
    font-size: 90%;
}

div.text_cell_render code {
    font-family: "Source Code Pro";
    font-size: 90%;
    color: red;
}

pre {
    font-family: "Source Code Pro";
    font-size: 90%;
}

div.text_cell_render { /* rendering of basic text cell */
    font-family: 'Alegreya Sans', Computer Modern, "Helvetica Neue", Arial, Helvetica, sans-serif;
    line-height: 135%;
    font-size: 120%;
    width:700px;
    margin-left:auto;
    margin-right:auto;
}

.text_cell_render h1 {
    font-family: 'Alegreya Sans', sans-serif;
    font-weight: 300;
    font-size: 32pt;
    line-height: 100%;
    color:#CD2305;
    margin-bottom: 0.4em;
    margin-top: 0em;
    display: block;
}

h2 {
    font-family: 'Fenix', serif;
}

h3 {
    font-family: 'Fenix', serif;
    margin-top:12px;
    margin-bottom: 3px;
}

h4 {
    font-family: 'Fenix', serif;
}

.text_cell_render h5 {
    font-family: 'Alegreya Sans', sans-serif;
    font-weight: 100;
    font-size: 16pt;
    color: #CD2305;
    font-style: italic;
    margin-bottom: .5em;
    margin-top: 0.5em;
    display: block;
}

.text_cell_render h6 { /*use this for copyright note*/
    font-family: 'Alegreya Sans', sans-serif;
    font-weight: 400;
    font-size: 10pt;
    font-style: normal;
    line-height: 120%;
    margin-bottom: 1px;
    margin-top: 1px;
}

.MathJax, .MathJax_Display  {
    font-family: 'Alegreya Sans', sans-serif  !important;
    font-size: 90%  !important;
    vertical-align: 0px  !important;
}

.warning{
    color: rgb( 240, 20, 20 )
}

</style>

<script>
MathJax.Hub.Config({
    TeX: {
        extensions: ["AMSmath.js"]
    },
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"] ],
        displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
        processEscapes: true
    },
    displayAlign: 'center', // Change this to 'center' to center equations.
    "HTML-CSS": {
        styles: {'.MathJax_Display': {"margin": 4}}
    }
});
</script>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.ComponentModel;

namespace Azure.ResourceManager.DigitalTwins.Models
{
    /// <summary> The provisioning state. </summary>
    public readonly partial struct DigitalTwinsPrivateLinkResourceProvisioningState : IEquatable<DigitalTwinsPrivateLinkResourceProvisioningState>
    {
        private readonly string _value;

        /// <summary> Initializes a new instance of <see cref="DigitalTwinsPrivateLinkResourceProvisioningState"/>. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public DigitalTwinsPrivateLinkResourceProvisioningState(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string PendingValue = "Pending";
        private const string ApprovedValue = "Approved";
        private const string RejectedValue = "Rejected";
        private const string DisconnectedValue = "Disconnected";

        /// <summary> Pending. </summary>
        public static DigitalTwinsPrivateLinkResourceProvisioningState Pending { get; } = new DigitalTwinsPrivateLinkResourceProvisioningState(PendingValue);
        /// <summary> Approved. </summary>
        public static DigitalTwinsPrivateLinkResourceProvisioningState Approved { get; } = new DigitalTwinsPrivateLinkResourceProvisioningState(ApprovedValue);
        /// <summary> Rejected. </summary>
        public static DigitalTwinsPrivateLinkResourceProvisioningState Rejected { get; } = new DigitalTwinsPrivateLinkResourceProvisioningState(RejectedValue);
        /// <summary> Disconnected. </summary>
        public static DigitalTwinsPrivateLinkResourceProvisioningState Disconnected { get; } = new DigitalTwinsPrivateLinkResourceProvisioningState(DisconnectedValue);
        /// <summary> Determines if two <see cref="DigitalTwinsPrivateLinkResourceProvisioningState"/> values are the same. </summary>
        public static bool operator ==(DigitalTwinsPrivateLinkResourceProvisioningState left, DigitalTwinsPrivateLinkResourceProvisioningState right) => left.Equals(right);
        /// <summary> Determines if two <see cref="DigitalTwinsPrivateLinkResourceProvisioningState"/> values are not the same. </summary>
        public static bool operator !=(DigitalTwinsPrivateLinkResourceProvisioningState left, DigitalTwinsPrivateLinkResourceProvisioningState right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="DigitalTwinsPrivateLinkResourceProvisioningState"/>. </summary>
        public static implicit operator DigitalTwinsPrivateLinkResourceProvisioningState(string value) => new DigitalTwinsPrivateLinkResourceProvisioningState(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is DigitalTwinsPrivateLinkResourceProvisioningState other && Equals(other);
        /// <inheritdoc />
        public bool Equals(DigitalTwinsPrivateLinkResourceProvisioningState other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
<IMAGE src="images/uofn.gif" BORDER=none>

Contents

General

Numerical Expressions

Boolean Expressions

Text

Images

<IMAGE src="images/spacer.gif" BORDER=none>

Boolean Expressions

The Boolean Expression components are all expressions that have a boolean value when evaluated.

Standard Boolean Expressions

The Standard Boolean Expression components all take other boolean expressions (including the comparison boolean expressions) as there arguments, those currently available are and (\&), or (|), not (!), and the booleans true, and false. These expressions can be constructed, and then edited in much the same way as the numerical expressions above. (including the use of brackets)

Comparison Boolean Expressions

What i have called comparison boolen expressions are boolean expressions themselves, but whose arguments are numerical expressions. The boolean value of these expressions depends on some sort of comparison between the two numerical expressions. The available operators are currently equals (=), not equals (!=), greater than (>), less than (<), at least (>=), and at most (<=). These expressions are also created and edited in much the same way as the other types of expression above.

<IMAGE src="images/uofn2.gif" BORDER=none>


text:
.class Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry;
.super Ljava/lang/Object;
.source "Collections.java"

# interfaces
.implements Ljava/util/Map$Entry;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "UnmodifiableMapEntry"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "<K:",
        "Ljava/lang/Object;",
        "V:",
        "Ljava/lang/Object;",
        ">",
        "Ljava/lang/Object;",
        "Ljava/util/Map$Entry",
        "<TK;TV;>;"
    }
.end annotation

# instance fields
.field mapEntry:Ljava/util/Map$Entry;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/Map$Entry",
            "<TK;TV;>;"
        }
    .end annotation
.end field

# direct methods
.method constructor <init>(Ljava/util/Map$Entry;)V
    .locals 0
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/util/Map$Entry",
            "<TK;TV;>;)V"
        }
    .end annotation

    .prologue
    .line 1160
    .local p0, "this":Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry;, "Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry<TK;TV;>;"
    .local p1, "entry":Ljava/util/Map$Entry;, "Ljava/util/Map$Entry<TK;TV;>;"
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 1161
    iput-object p1, p0, Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry;->mapEntry:Ljava/util/Map$Entry;

    .line 1162
    return-void
.end method

# virtual methods
.method public equals(Ljava/lang/Object;)Z
    .locals 1
    .param p1, "object"    # Ljava/lang/Object;

    .prologue
    .line 1165
    .local p0, "this":Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry;, "Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry<TK;TV;>;"
    iget-object v0, p0, Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry;->mapEntry:Ljava/util/Map$Entry;

    invoke-interface {v0, p1}, Ljava/util/Map$Entry;->equals(Ljava/lang/Object;)Z

    move-result v0

    return v0
.end method

.method public getKey()Ljava/lang/Object;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()TK;"
        }
    .end annotation

    .prologue
    .line 1169
    .local p0, "this":Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry;, "Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry<TK;TV;>;"
    iget-object v0, p0, Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry;->mapEntry:Ljava/util/Map$Entry;

    invoke-interface {v0}, Ljava/util/Map$Entry;->getKey()Ljava/lang/Object;

    move-result-object v0

    return-object v0
.end method

.method public getValue()Ljava/lang/Object;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()TV;"
        }
    .end annotation

    .prologue
    .line 1173
    .local p0, "this":Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry;, "Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry<TK;TV;>;"
    iget-object v0, p0, Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry;->mapEntry:Ljava/util/Map$Entry;

    invoke-interface {v0}, Ljava/util/Map$Entry;->getValue()Ljava/lang/Object;

    move-result-object v0

    return-object v0
.end method

.method public hashCode()I
    .locals 1

    .prologue
    .line 1177
    .local p0, "this":Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry;, "Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry<TK;TV;>;"
    iget-object v0, p0, Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry;->mapEntry:Ljava/util/Map$Entry;

    invoke-interface {v0}, Ljava/util/Map$Entry;->hashCode()I

    move-result v0

    return v0
.end method

.method public setValue(Ljava/lang/Object;)Ljava/lang/Object;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(TV;)TV;"
        }
    .end annotation

    .prologue
    .line 1181
    .local p0, "this":Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry;, "Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry<TK;TV;>;"
    .local p1, "object":Ljava/lang/Object;, "TV;"
    new-instance v0, Ljava/lang/UnsupportedOperationException;

    invoke-direct {v0}, Ljava/lang/UnsupportedOperationException;-><init>()V

    throw v0
.end method

.method public toString()Ljava/lang/String;
    .locals 1

    .prologue
    .line 1185
    .local p0, "this":Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry;, "Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry<TK;TV;>;"
    iget-object v0, p0, Ljava/util/Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableMapEntry;->mapEntry:Ljava/util/Map$Entry;

    invoke-virtual {v0}, Ljava/lang/Object;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method


text:
import java.awt.Graphics2D;
import javax.swing.ImageIcon;

public class Turtle {

	//Declare field variables
	private int xPos, yPos, width, height;
	private ImageIcon imgTurtle;

	//Declare constructor
	public Turtle(ImageIcon imgTurtle, int xPos, int yPos) {

		this.xPos = xPos;
		this.yPos = yPos;
		this.imgTurtle = imgTurtle;
		this.width = imgTurtle.getIconWidth();
		this.height = imgTurtle.getIconHeight();
	}

	//Declare accessor methods
	public int getX(){

		return xPos;
	}

	public int getY(){

		return yPos;
	}
	public int getWidth(){

		return width;
	}
	public int getHeight(){

		return height;
	}
	public ImageIcon getImage(){

		return imgTurtle;
	}
	//Declare method to move the x position of the log;
	public void move(int pixels, int FRAME_WIDTH){

		xPos -= pixels;

		if(xPos + width <= 0) // When turtle's x is less than 0, set the turtle's x to the right of the frame
		{
			xPos = FRAME_WIDTH;
		}
	}

	//Declare mutator methods
	public void setX(int x){

		xPos = x;
	}
	public void setY(int y){

		yPos = y;
	}
	public void setWidth(int width){

		this.width = width;
	}
	public void setHeight(int height){

		this.height = height;
	}
	public void setImage(ImageIcon imgTurtle){

		this.imgTurtle = imgTurtle;
	}
	//Draw turtle
	public void drawTurtle(Graphics2D g2){

		g2.drawImage(imgTurtle.getImage(), xPos, yPos, null);
	}

}


text:
/**
 * Created by wangchun-imac on 1/26/17.
 */
import {NgModule} from "@angular/core";

import {DynamicComponent} from './dynami.component';
import {SpendingMainComponent} from './spending/spending.main.component';
import {FinanceMainComponent} from './finance/finance.main.component';

@NgModule({
    imports: [],
    exports: [SpendingMainComponent, FinanceMainComponent, DynamicComponent],
    declarations: [SpendingMainComponent, FinanceMainComponent, DynamicComponent],
    providers: [],
})
export class AppsModule {
}


text:
require "test_helper"

module ActiveRecord
  class Migration
    class IndexTest < SpannerAdapter::TestCase
      include SpannerAdapter::Migration::TestHelper

      attr_reader :table_name

      def setup
        skip_test_table_create!
        super

        @table_name = :testings

        connection.ddl_batch do
          connection.create_table table_name do |t|
            t.column :foo, :string, limit: 100
            t.column :bar, :string, limit: 100

            t.string :first_name
            t.string :last_name, limit: 100
            t.string :key,       limit: 100
            t.boolean :administrator
          end
        end
      end

      def teardown
        connection.ddl_batch do
          connection.drop_table :testings
        end rescue nil
        ActiveRecord::Base.primary_key_prefix_type = nil
      end

      def test_rename_index
        connection.add_index(table_name, [:foo], name: "old_idx")
        connection.ddl_batch do
          connection.rename_index(table_name, "old_idx", "new_idx")
        end

        assert_not connection.index_name_exists?(table_name, "old_idx")
        assert connection.index_name_exists?(table_name, "new_idx")
      end

      def test_rename_index_too_long
        too_long_index_name = good_index_name + "x"
        connection.add_index(table_name, [:foo], name: "old_idx")
        e = assert_raises(ArgumentError) {
          connection.rename_index(table_name, "old_idx", too_long_index_name)
        }
        assert_match(/too long; the limit is #{connection.index_name_length} characters/, e.message)

        assert connection.index_name_exists?(table_name, "old_idx")
      end

      def test_remove_nonexistent_index
        assert_raise(ArgumentError) { connection.remove_index(table_name, "no_such_index") }
      end

      def test_add_index_works_with_long_index_names
        connection.add_index(table_name, "foo", name: good_index_name)

        assert connection.index_name_exists?(table_name, good_index_name)
        connection.remove_index(table_name, name: good_index_name)
      end

      def test_add_index_does_not_accept_too_long_index_names
        too_long_index_name = good_index_name + "x"

        e = assert_raises(ArgumentError) {
          connection.add_index(table_name, "foo", name: too_long_index_name)
        }
        assert_match(/too long; the limit is #{connection.index_name_length} characters/, e.message)

        assert_not connection.index_name_exists?(table_name, too_long_index_name)
        connection.add_index(table_name, "foo", name: good_index_name)
      end

      def test_internal_index_with_name_matching_database_limit
        good_index_name = "x" * connection.index_name_length
        connection.add_index(table_name, "foo", name: good_index_name)

        assert connection.index_name_exists?(table_name, good_index_name)
        connection.remove_index(table_name, name: good_index_name)
      end

      def test_index_symbol_names
        connection.add_index table_name, :foo, name: :symbol_index_name
        assert connection.index_exists?(table_name, :foo, name: :symbol_index_name)

        connection.remove_index table_name, name: :symbol_index_name
        assert_not connection.index_exists?(table_name, :foo, name: :symbol_index_name)
      end

      def test_index_exists
        connection.add_index :testings, :foo

        assert connection.index_exists?(:testings, :foo)
        assert_not connection.index_exists?(:testings, :bar)
      end

      def test_index_exists_on_multiple_columns
        connection.add_index :testings, [:foo, :bar]

        assert connection.index_exists?(:testings, [:foo, :bar])
      end

      def test_index_exists_with_custom_name_checks_columns
        connection.add_index :testings, [:foo, :bar], name: "my_index"
        assert connection.index_exists?(:testings, [:foo, :bar], name: "my_index")
        assert_not connection.index_exists?(:testings, [:foo], name: "my_index")
      end

      def test_valid_index_options
        assert_raise ArgumentError do
          connection.add_index :testings, :foo, unqiue: true
        end
      end

      def test_unique_index_exists
        connection.add_index :testings, :foo, unique: true

        assert connection.index_exists?(:testings, :foo, unique: true)
      end

      def test_order_index_exists
        connection.add_index :testings, :foo, order: { foo: :desc }

        assert connection.index_exists?(:testings, :foo)

        index = connection.indexes(:testings).first
        assert_equal({ foo: :desc }, index.orders)
      end

      def test_named_index_exists
        connection.add_index :testings, :foo, name: "custom_index_name"

        assert connection.index_exists?(:testings, :foo)
        assert connection.index_exists?(:testings, :foo, name: "custom_index_name")
        assert_not connection.index_exists?(:testings, :foo, name: "other_index_name")
      end

      def test_remove_named_index
        connection.add_index :testings, :foo, name: "index_testings_on_custom_index_name"

        assert connection.index_exists?(:testings, :foo)

        assert_raise(ArgumentError) { connection.remove_index(:testings, "custom_index_name") }

        connection.remove_index :testings, :foo
        assert_not connection.index_exists?(:testings, :foo)
      end

      def test_add_index
        connection.add_index("testings", "last_name")
        connection.remove_index("testings", "last_name")

        connection.add_index("testings", ["last_name", "first_name"])
        connection.remove_index("testings", column: ["last_name", "first_name"])

        connection.add_index("testings", ["last_name", "first_name"])
        connection.remove_index("testings", name: :index_testings_on_last_name_and_first_name)
        connection.add_index("testings", ["last_name", "first_name"])
        connection.remove_index("testings", "last_name_and_first_name")

        connection.add_index("testings", ["last_name", "first_name"])
        connection.remove_index("testings", ["last_name", "first_name"])

        connection.add_index("testings", "key", unique: true)
        connection.remove_index("testings", "key")

        connection.add_index("testings", ["key"], name: "key_idx", unique: true)
        connection.remove_index("testings", name: "key_idx")

        connection.add_index("testings", %w(last_name first_name administrator), name: "named_admin")
        connection.remove_index("testings", name: "named_admin")

        connection.add_index("testings", ["last_name"], order: { last_name: :desc })
        connection.remove_index("testings", ["last_name"])
        connection.add_index("testings", ["last_name", "first_name"], order: { last_name: :desc })
        connection.remove_index("testings", ["last_name", "first_name"])
        connection.add_index("testings", ["last_name", "first_name"], order: { last_name: :desc, first_name: :asc })
        connection.remove_index("testings", ["last_name", "first_name"])
        connection.add_index("testings", ["last_name", "first_name"], order: :desc)
        connection.remove_index("testings", ["last_name", "first_name"])
      end

      def test_add_interleaved_index
        connection.add_index "albums", ["singerid", "title"], interleave_in: :singers
        index = connection.indexes(:albums).first

        assert index, "Could not find interleaved index"
        assert_equal "singers", index.interleave_in
      end

      private
      def good_index_name
        "x" * connection.index_name_length
      end
    end
  end
end


text:
1.0.6
-----

* Updated some maths trig functions
* Merged [pull request 33](https://github.com/sutoiku/formula.js/pull/33)

1.0.5
-----

* Remove console.log statements.
* index.js was accidentally truncated by jima.

1.0.4
-----

* Added the missing 22 EXCEL functions and associated test cases.

1.0.3
-----

* Removed the dependency on moment and md5

0.0.32
------

* Added the following google spreadsheet functions ADD, DIVIDE, EQ, GTE, LT, LTE, MINUS, MULTIPLY, NE and POW
* Added associated test cases

0.0.26
------

* Add grunt support from João Jerónimo (joaojeronimo)
* POWER function with negative base now works from João Jerónimo (joaojeronimo)
* SUM supports multi-dimensional arrays from João Jerónimo (joaojeronimo)

0.0.25
------

* Integrate a really old but useful pull request to add database functions (https://github.com/sutoiku/formula.js/pull/9)
* Thanks a heap to Sam Dao (grasscrm) for all the database features
* Cleared all but 1 outstanding issue on github

0.0.19
------

* Added full match support to REGEXMATCH

0.0.18
------

* Removed CONCAT and INITIALS functions

0.0.17
------

* Added support for FROMNOW

0.0.16
------

* Added support for NUMERAL function

0.0.15
------

* Improved our bower support
* Upgraded some of our dependencies

0.0.14
------

* Added support for MD5 and some test cases

0.0.13
------

* Problem with computing weekdays with NETWORKDAYS #62319048
* Fixed issue wih DATEVALUE #62514386

0.0.12
------

* Added support for the SWITCH function (#60883740)

0.0.11
------

* Add some defensive coding around the LOWER function and add associated test cases

0.0.10
------

* Add pull request to fix DATEVALUE and add some test cases
* Add the begining support for bower package management
* Removed dependency on financial.js as this is now in the expression parser

0.0.9
-----

* Fixed issue with CONCATENATE function (#59947518)

0.0.8
-----

* Added HTML2TEXT and associated test cases
* Added HUMANIZE and associated test cases (#59192844)
* Added JSON2TEXT and associated test cases (#59604642)

0.0.7
-----

* Moved the lodash functions to expression parser
* Moved the callback registration functions to expression parser module

0.0.6
-----

* Fixed the way jStat uses formula's arguments
* Dates returned as string instead of JavaScript Date object

0.0.5
-----

* Replaced sugar with lodash

0.0.4
-----

* Placed a work around for some functions in lodash that do not work well with the expression parser
* Switched across from using underscore to lodash

0.0.3
-----

* Merged in the changes in stoic.io
* Added more test coverage (we're up to about 55%)
* Added support for the financial package (https://github.com/mfreilich/financial.js)
* Did some refactoring to better support running in browser and nodejs
* Upgraded to moment v2.0.0
* Added support for requirejs
* Added support for function


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

<TITLE>
ProtocolReader
</TITLE>

<META NAME="keywords" CONTENT="edu.sdsc.inca.protocol.ProtocolReader class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

edu.sdsc.inca.protocol

Class ProtocolReader

java.lang.Object
  java.io.Reader
      java.io.BufferedReader
          edu.sdsc.inca.protocol.ProtocolReader

All Implemented Interfaces:
java.io.Closeable, java.lang.Readable

public class ProtocolReader
extends java.io.BufferedReader

Author:

Cathie Olschanowsky, Jim Hayes

 Used for efficiently handling the input streams that hold inca
 protocol bytes.

 To use it

 reader = new ProtocolReader(new InputStreamReader(inputStream));
 reader.peekCommand
 reader.getStatement ...

Field Summary

protected  boolean
closed

static int
CR

static int
LF

protected static org.apache.log4j.Logger
logger

static int
MAX_COMMAND_LENGTH

static int
SP

Fields inherited from class java.io.Reader

lock

Constructor Summary

ProtocolReader(java.io.Reader reader)

          Create a buffering protocol-input stream that uses a default-sized
 input buffer.

ProtocolReader(java.io.Reader reader,
               int i)

          Create a buffering character-input stream that uses an input
 buffer of the specified size.

Method Summary

 void
close()

          Closes the reader.

 boolean
isClosed()

          Indicates whether or not the reader has been closed.

 java.lang.String
peekCommand()

          Returns the next command from the stream, or null on end.

 Statement
readStatement()

          Reads a complete statement from the input stream, or null if the stream
 has been closed.

Methods inherited from class java.io.BufferedReader

mark, markSupported, read, read, readLine, ready, reset, skip

Methods inherited from class java.io.Reader

read, read

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

MAX_COMMAND_LENGTH

public static final int MAX_COMMAND_LENGTH

See Also:
Constant Field Values

CR

public static final int CR

See Also:
Constant Field Values

LF

public static final int LF

See Also:
Constant Field Values

SP

public static final int SP

See Also:
Constant Field Values

logger

protected static org.apache.log4j.Logger logger

closed

protected boolean closed

Constructor Detail

ProtocolReader

public ProtocolReader(java.io.Reader reader,
                      int i)

Create a buffering character-input stream that uses an input
 buffer of the specified size.

Parameters:
reader - the reader that the data can be read from
i - size of the input buffer

ProtocolReader

public ProtocolReader(java.io.Reader reader)

Create a buffering protocol-input stream that uses a default-sized
 input buffer.

Parameters:
reader - the reader that the protocol can be read from

Method Detail

close

public void close()
           throws java.io.IOException

Closes the reader.

Specified by:
close in interface java.io.Closeable
Overrides:
close in class java.io.BufferedReader

Throws:

java.io.IOException - on a close error

isClosed

public boolean isClosed()

Indicates whether or not the reader has been closed.

Returns:
true if the reader is closed, else false

peekCommand

public java.lang.String peekCommand()
                             throws java.io.IOException,
                                    ProtocolException

Returns the next command from the stream, or null on end.  The command
 will be re-read by the next call to readStatement.

Returns:
the next command

Throws:

java.io.IOException - on a read error

ProtocolException - if the contents of the read are malformed

readStatement

public Statement readStatement()
                        throws java.io.IOException,
                               ProtocolException

Reads a complete statement from the input stream, or null if the stream
 has been closed.

Returns:
the next statement -- complete

Throws:

java.io.IOException - on a read error

ProtocolException - if the contents of the read are malformed

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
#import "APHCardiovascularHealthSurveyController.h"

static NSString *const kHeartAgeQuestionIdentifier = @"heart_disease_q";
@interface APHCardiovascularHealthSurveyController ()

@end

@implementation APHCardiovascularHealthSurveyController

- (void)viewWillAppear:(BOOL)animated  {
    [super viewWillAppear:animated];

}

- (void)taskViewController:(ORKTaskViewController *)taskViewController didFinishWithReason:(ORKTaskViewControllerFinishReason)reason error:(NSError *)error {

    switch (reason) {
        case ORKTaskViewControllerFinishReasonCompleted:
        {
            APCAppDelegate *appDelegate = (APCAppDelegate *)[[UIApplication sharedApplication] delegate];

            ORKStepResult *stepResult = [self.result stepResultForStepIdentifier:kHeartAgeQuestionIdentifier];
            NSNumber *boolAnswer = [stepResult.results.firstObject booleanAnswer];

            appDelegate.dataSubstrate.currentUser.hasHeartDisease = [boolAnswer integerValue];
        }
            break;
        case ORKTaskViewControllerFinishReasonDiscarded:
            break;
        case ORKTaskViewControllerFinishReasonSaved:
            break;
        case ORKTaskViewControllerFinishReasonFailed:
            break;
    }

    [super taskViewController:taskViewController didFinishWithReason:reason error:error];
}

@end


text:
#ifndef GAMESTATE_FINALSCREEN_H
#define GAMESTATE_FINALSCREEN_H
#include "GameState.h"

#include <string>
class GameState_FinalScreen : public GameState
{
public:

    // Constructors/Destructors
    //

    /**
     * Empty Constructor
     */
    GameState_FinalScreen ( );

    /**
     * Empty Destructor
     */
    virtual ~GameState_FinalScreen ( );

};

#endif // GAMESTATE_FINALSCREEN_H


text:
![phoenix logo](https://raw.githubusercontent.com/phoenixframework/phoenix/master/priv/static/phoenix.png)
> ### Productive. Reliable. Fast.
> A productive web framework that does not compromise speed and maintainability.

[![Build Status](https://api.travis-ci.org/phoenixframework/phoenix.svg?branch=master)](https://travis-ci.org/phoenixframework/phoenix)
[![Inline docs](http://inch-ci.org/github/phoenixframework/phoenix.svg)](http://inch-ci.org/github/phoenixframework/phoenix)

## Getting started

See the official site at http://www.phoenixframework.org/

Install the latest version of Phoenix by following the instructions at https://hexdocs.pm/phoenix/installation.html#phoenix

## Documentation

API documentation is available at [https://hexdocs.pm/phoenix](https://hexdocs.pm/phoenix)

Phoenix.js documentation is available at [https://hexdocs.pm/phoenix/js](https://hexdocs.pm/phoenix/js)

## Contributing

We appreciate any contribution to Phoenix. Check our [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) and [CONTRIBUTING.md](CONTRIBUTING.md) guides for more information. We usually keep a list of features and bugs [in the issue tracker][4].

### Generating a Phoenix project from unreleased versions

You can create a new project using the latest Phoenix source installer (the `phx.new` Mix task) with the following steps:

1. Remove any previously installed `phx_new` archives so that Mix will pick up the local source code. This can be done with `mix archive.uninstall phx_new` or by simply deleting the file, which is usually in `~/.mix/archives/`.
2. Copy this repo via `git clone https://github.com/phoenixframework/phoenix` or by downloading it
3. Run the `phx.new` mix task from within the `installer` directory, for example:

```bash
$ cd installer
$ mix phx.new dev_app --dev
```

The `--dev` flag will configure your new project's `:phoenix` dep as a relative path dependency, pointing to your local Phoenix checkout:

```elixir
defp deps do
  [{:phoenix, path: "../..", override: true},
```

To create projects outside of the `installer/` directory, add the latest archive to your machine by following the instructions in [installer/README.md](https://github.com/phoenixframework/phoenix/blob/master/installer/README.md)

To build the documentation from source:

```bash
$ cd assets
$ npm install
$ cd ..
$ MIX_ENV=docs mix docs
```

To build Phoenix from source:

```bash
$ mix deps.get
$ mix compile
```

To build the Phoenix installer from source:

```bash
$ mix deps.get
$ mix compile
$ mix archive.build
```

### Building phoenix.js

```bash
$ cd assets
$ npm install
$ npm run watch
```

## Important links

* [#elixir-lang][1] on [Freenode][2] IRC
* [elixir-lang slack channel][3]
* [Issue tracker][4]
* [Phoenix Forum (questions)][5]
* [phoenix-core Mailing list (development)][6]
* Visit Phoenix's sponsor, DockYard, for expert [phoenix consulting](https://dockyard.com/phoenix-consulting)
* Privately disclose security vulnerabilities to phoenix-security@googlegroups.com

  [1]: https://webchat.freenode.net/?channels=#elixir-lang
  [2]: http://www.freenode.net/
  [3]: https://elixir-slackin.herokuapp.com/
  [4]: https://github.com/phoenixframework/phoenix/issues
  [5]: https://elixirforum.com/c/phoenix-forum
  [6]: http://groups.google.com/group/phoenix-core

## Copyright and License

Copyright (c) 2014, Chris McCord.

Phoenix source code is licensed under the [MIT License](LICENSE.md).


text:
package com.winterwell.bob;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Set;

import com.winterwell.bob.tasks.Classpath;
import com.winterwell.bob.tasks.CompileTask;
import com.winterwell.bob.tasks.EclipseClasspath;
import com.winterwell.utils.FailureException;
import com.winterwell.utils.ReflectionUtils;
import com.winterwell.utils.StrUtils;
import com.winterwell.utils.containers.Containers;
import com.winterwell.utils.containers.Pair;
import com.winterwell.utils.containers.Pair2;
import com.winterwell.utils.io.FileUtils;
import com.winterwell.utils.log.Log;

public class BobScriptFactory {

	private static final String LOGTAG = "BobScriptFactory";
	private final File baseDir;

	public BobScriptFactory(File workingDirectory) {
		baseDir = workingDirectory;
	}

	File findBuildScript(String optionalName) {
		File f = findBuildScript2(baseDir, optionalName);
		return f;
	}

	/**
	 * ??how best to expose this method
	 * @param projectDir
	 * @param optionalName
	 * @return BuildX.java, or null
	 * ??change to List so we can better communicate around failed-to-find/pick
	 */
	public File findBuildScript2(File projectDir, String optionalName) {
		File bdir = new File(projectDir, "builder");
		if ( ! bdir.isDirectory()) {
			return null;
		}
		String namePattern = ".*Build.*\\.java";
		if (optionalName!=null) {
			namePattern = ".*"+optionalName+"\\.java";
		}
		List<File> files = FileUtils.find(bdir, namePattern);
		if (files.isEmpty()) return null;
		if (files.size()==1) {
			Log.i(LOGTAG, "Auto-build: found file "+files.get(0));
			return files.get(0);
		}
		Log.w(LOGTAG, "Auto-build: could not pick between "+files.size()+" tasks in "+bdir);
		Log.w(LOGTAG, Containers.apply(files, FileUtils::getBasename));
		return null;
	}

	/**
	 * TODO refactor into a BobBuildScript class 'cos this is actually quite complex
	 * @throws Exception
	 */
	Class getClass(String classOrFileName) throws Exception {
		try {
			return getClass2_instantiateOrCompile(classOrFileName);
		} catch(Exception ex) {
			// partial name? try a find
			File buildFile = findBuildScript(classOrFileName);
			if (buildFile!=null && ! buildFile.toString().equals(classOrFileName)) {
				return getClass2_instantiateOrCompile(buildFile.toString());
			}
			throw ex;
		}
	}

	Class getClass2_instantiateOrCompile(String classOrFileName) throws Exception {
		String className = classOrFileName;
		// Strip endings if they were used
		if (classOrFileName.endsWith(".java")) {
			className = classOrFileName.substring(0, classOrFileName.length() - 5);
		}
		if (classOrFileName.endsWith(".class")) {
			className = classOrFileName.substring(0, classOrFileName.length() - 6);
		}
		try {
			Class<?> clazz = Class.forName(className);
			return clazz;
		} catch(ClassNotFoundException ex) {
			// is it a directory?
			File dir = new File(classOrFileName);
			if (dir.isDirectory()) {
				File found = findBuildScript2(dir, null);
				if (found!=null) {
					Log.d(LOGTAG, "located build-script "+found+" in directory "+dir);
					classOrFileName = found.toString();
				}
			}

			File baseDir = FileUtils.getWorkingDirectory();
			Pair2<File, File> klass = getClass3_compileClass(baseDir, classOrFileName);
			if (klass == null) {
				throw ex; // oh well - failed
			}
			assert claspath != null;
			// dynamically load a class from a file?
			Class clazz = ReflectionUtils.loadClassFromFile(klass.first, klass.second, claspath.getFiles());
			return clazz;
		}
	}

	Classpath claspath;

	/**
	 * From a .java file or fully-qualified classname,
	 * compile it to a .class file
	 * @param baseDir
	 * @param classOrFileName
	 * @return (temp-output-dir, class-file)
	 * @throws Exception
	 */
	Pair<File> getClass3_compileClass(File baseDir, String classOrFileName) throws Exception {
		// Can we compile it here and now?
		// 1. Look for the .java file
		String fileName = classOrFileName;
		File f = new File(fileName);
		if ( ! f.isFile()) {
			// classname? turn into a file
			fileName = fileName.replace('.', '/');
			// .java ending
			if (fileName.endsWith("/java")) {
				fileName = fileName.substring(0, fileName.length()-5)+".java";
			}
			if ( ! fileName.endsWith(".java")) {
				fileName = fileName+".java";
			}
			f = new File(fileName);
			if ( f.isDirectory()) {
				throw new IllegalArgumentException(f+" from "+classOrFileName+" should have been handled via find-build-script");
			}
			if ( ! f.isFile()) {
				throw new FileNotFoundException(f+" = "+f.getAbsolutePath()+" from "+classOrFileName);
			}
		}

		// sniff package
		String src = FileUtils.read(f);
		String[] fnd = StrUtils.find("package (.+);", src);
		// full classname
		String className = (fnd==null? "" : fnd[1]+".") + new File(FileUtils.getBasename(f)).getName();

		// output
		File tempDir = FileUtils.createTempDir();

		// simple compile?
		try {
			CompileTask cp = new CompileTask(null, tempDir);
			// classpath
			claspath = Bob.getSingleton().getClasspath();
			cp.setClasspath(claspath);
			// our .java file to compile
			cp.setSrcFiles(f);
			// ...compile
			Log.i(LOGTAG, "Compiling the Bob build script...");
			cp.doTask();
			FileUtils.close(cp);
		} catch(FailureException fex) {
			try {
				Log.d(LOGTAG, "Simple single-file compile failed: "+fex+". Trying for eclipse info...");
				EclipseClasspath ec = new EclipseClasspath(baseDir);
				List<File> srcDirs = ec.getSrcDirs();
				CompileTask compile = new CompileTask(null, tempDir);
				for (File sd : srcDirs) {
					compile.addSrcDir(sd);
				}
				ec.setIncludeProjectJars(true);
				claspath = Bob.getSingleton().getClasspath();
				Set<File> libs = ec.getCollectedLibs();
				claspath.addAll(libs);
				compile.setClasspath(claspath);
				compile.setDebug(true);
				// our .java file to compile
				compile.addSrcFile(f);
				// ...compile
				compile.doTask();
				FileUtils.close(compile);
			} catch(Exception fex2) {
				Log.d(LOGTAG, "Trief sniffing Eclipse .classpath - compile also failed: "+fex2);
				throw fex;
			}
		}

		// success?
		File klass = new File(tempDir, className.replace('.', '/')+".class");
		if (klass.isFile()) {
			return new Pair<File>(tempDir, klass);
		}
		throw new FailureException("Bootstrap compile failed for "+classOrFileName+" = "+f);
	}
}


text:
Create a map in a React application,

Add interaction to the map (zoom, pan, resize window)

# Starting With a Map

[react-map-gl](https://github.com/uber/react-map-gl) is a `React` wrapper around
the powerful `MapboxGL` mapping library. `react-map-gl` makes it super easy to
drop a mapping component into your application.

Checkout the complete code for this step
[here](https://github.com/uber-common/vis-academy/blob/master/src/demos/building-a-geospatial-app/1-starting-with-map/src/app.js).

## 1. Start with a bare React Component

**HOLD UP!!!** If you got here without reading the **Setup** step, it is
highly recommended that you do so, or your application might not work.
[GO HERE](#/building-a-geospatial-app/0-setup.md) and go through it now.

The app component in the starting code above currently looks like this:
```js
...
export default class App extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <div className="intro">
          {MAPBOX_TOKEN ? (
            `You mapbox token is set. You're good to go!`
          ) : (
            <SetToken />
          )}
        </div>
      </div>
    );
  }
}

```
The next steps of this tutorial will only refer to parts of the outline shown
above, and not the whole thing.

## 2. Adding Default Viewport State

`react-map-gl` requires a viewport that specifies the dimensions, location, and
basic settings of the map, so let's give ourselves a set of defaults:
```js
...
export default class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      style: 'mapbox://styles/mapbox/light-v9',
      viewport: {
        width: window.innerWidth,
        height: window.innerHeight,
        longitude: -74,
        latitude: 40.7,
        zoom: 11,
        maxZoom: 16
      }
    };
  }

}
```
We set the viewport object on component state because `react-map-gl` leaves
the control of the viewport to the implementer. We will have to update this viewport
manually and pass it back into `react-map-gl` if we want to change it.

## 3. Adding the Map Component

Now that we have a viewport object, let's add the actual map component.
`react-map-gl` makes this extremely easy.

```js
import MapGL from 'react-map-gl';
```
Add to `render()`

```js

export default class App extends Component {
  // ...
  render() {
    return (
      <div>
        <MapGL
          {...this.state.viewport}
          mapStyle={this.state.style}
        </MapGL>
      </div>
    );
  }

}
```

Note: if a MapboxAccessToken exists in the environment variables, which we've done earlier, the ReactMapGL component will use it automatically. If not, you'd have to supply it explicity:

```js
  <MapGL
    {...this.state.viewport}
    mapStyle={this.state.style}
    mapboxApiAccessToken={YOUR_TOKEN}>
  </MapGL>
```

## 4. Changing styles

We can easily use any of the Mapbox default styles. To that end, let's add a drop-down to change them:

After the last import:
```js
import {MapStylePicker} from './controls';
```

As one of the components properties:
```js
  onStyleChange = (style) => {
    this.setState({style});
  }
```

In the render function, before the <MapGL> component:

```js
<MapStylePicker onStyleChange={this.onStyleChange} currentStyle={this.state.style}/>
```

(The MapStylePicker is just a boring, plain select component. You can look up its code in ./controls if you're interested).

If you feel creative, you can also create your own styles in [Mapbox Studio](https://www.mapbox.com/studio/) and put their url (starting with http://api.mapbox.com/styles/) in the state instead.

## 5. `onViewportChange` Callback

Remember that `react-map-gl` leaves maintaining the viewport to the user. It would
be super tedious if you had to implement the event handling yourself.

Luckily, `react-map-gl` provides a callback that we can use to update our viewport.
This `onViewportChange` callback will be called with the updated viewport
every time the user interacts with the map (panning, zooming, rotating, etc.)

For a truly interactive map, let's add the callback and update our state. We
already passed in the callback when we defined the component so now we just
need to define it.
```js
export default class App extends Component {

  _onViewportChange(viewport) {
    this.setState({
      viewport: {...this.state.viewport, ...viewport}
    });
  }

}
```

Now that we have defined the callback. Let's pass it into the react-map-gl component
```js
return (
  <div>
    <MapGL
      // ...
      // Callback for viewport changes, addressed below
      onViewportChange={viewport => this._onViewportChange(viewport)}
      // ...
    ></MapGL>
  </div>
);
```

## 6. Adding Polish

We now have a fully functional map, and we could stop here. But what happens
when you resize the window? If you do it right now, you'll notice that the map
stays the same size. That's a terrible user experience, and we wouldn't want that.

Let's quickly add a resize handler that updates our viewport with the new dimension
```js
export default class App extends Component {

  componentDidMount() {
    window.addEventListener('resize', this._resize);
    this._resize();
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this._resize);
  }

  _resize = () => {
    this._onViewportChange({
      width: window.innerWidth,
      height: window.innerHeight
    });
  }

}
```
We leverage the `onViewportChange` callback to make sure there's only one place
where viewport state is actually being updated.

We can use the ReactMapGL's MapGL component to use a map in React.

MapGL behaves just as another React component with props and callbacks.

Basic settings of the map are stored in the __viewport__ prop.

the __onViewportChange__ prop can be used to update the viewport when a user interacts with the map.

## 6. Completed Code

Our completed component [app.js](https://github.com/uber-common/vis-academy/blob/master/src/demos/building-a-geospatial-app/1-starting-with-map/src/app.js) should now look like this:

```js
/* global window */
import React, { Component } from 'react';
import MapGL from 'react-map-gl';
import {MapStylePicker} from './controls';

export default class App extends Component {
  state = {
    style: 'mapbox://styles/mapbox/light-v9',
    viewport: {
      width: window.innerWidth,
      height: window.innerHeight,
      longitude: -74,
      latitude: 40.7,
      zoom: 11,
      maxZoom: 16
    }
  }

  componentDidMount() {
    window.addEventListener('resize', this._resize);
    this._resize();
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this._resize);
  }

  onStyleChange = (style) => {
    this.setState({style});
  }

  _onViewportChange = (viewport) => {
    this.setState({
      viewport: { ...this.state.viewport, ...viewport }
    });
  }

  _resize = () => {
    this._onViewportChange({
      width: window.innerWidth,
      height: window.innerHeight
    });
  }

  render() {
    return (
      <div>
        <MapStylePicker onStyleChange={this.onStyleChange} currentStyle={this.state.style}/>
        <MapGL
          {...this.state.viewport}
          mapStyle={this.state.style}
          onViewportChange={viewport => this._onViewportChange(viewport)}
        >
        </MapGL>
      </div>
    );
  }
}

```

That's all you need to render a map and make it interactive!
Let's dig a bit into what each one of those properties does.

## Properties

##### `width, height, longitude, latitude, zoom` {Number} (required)
These are the `viewport` properties and indicate the starting point of
your map.

##### `mapStyle` {String | Object | Immutable.Map}
This is the map style, either as a URL string or a full style object.

#### `onViewportChange` {Function}
Callback that will be called whenever the map updates (i.e. during interaction).
You **must** implement this and update the component with the new `viewport`
properties for a truly interactive map experience.

#### `mapboxApiAccessToken` {String}
The `MapboxGL` token required if you're trying to load a `mapStyle` that uses
mapbox data - which is any of their default styles.
[More Info](https://www.mapbox.com/help/create-api-access-token/)

For more detail information about `react-map-gl`,
[visit its Github](https://github.com/uber/react-map-gl).


text:
Ti.include('/src/code/towel/include.js');
var compare  = TT.require(TT.Module.Compare);
var validate = TT.require(TT.Module.Validate);
var sequence = TT.require(TT.Module.Sequence);

exports.UID = 0;

	var UIDs     = exports.UIDs     = {};
	var entities = exports.entities = []; // starts at size 0

	function get(entity)
	{
		exports.entities = sequence.append(entity, exports.entities); // JIC gets deleted, it will re-generate
		   exports.UID   = exports.entities.length;
	return exports.UID; // TODO what to return if entities gets deleted?
	}exports.get = get;

	function entity_get(entity)
	{
validate.isSomeString(entity, 'UID.get.entity_get is False for is entity');
		exports.get(entity);
exports.UIDs[entity] = compare.defaultNumber( exports.UIDs[entity] ) +1;
	return exports.UIDs[entity];
	}exports.entity_get = exports.entity = exports.getEntity = entity_get;


text:
<select ng-style="{'background-color': badgeColor}" class="select-genre"
  ng-options="g as g.name for g in genres" ng-change="change()">
</select>


text:
<!DOCTYPE html>

  <title>style.scss</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <link rel="stylesheet" media="all" href="../../../../../../doc-style.css" />

      Files
      Headings

style.scss

  ¶

@import "../styles/common";

h1 {
  color: grey;
}


text:
namespace ServiceStack.OrmLite.Dapper
{
    public static partial class SqlMapper
    {
        /// <summary>
        /// Extends IDynamicParameters providing by-name lookup of parameter values
        /// </summary>
        public interface IParameterLookup : IDynamicParameters
        {
            /// <summary>
            /// Get the value of the specified parameter (return null if not found)
            /// </summary>
            /// <param name="name">The name of the parameter to get.</param>
            object this[string name] { get; }
        }
    }
}


text:
@import url(https://fonts.googleapis.com/css?family=Roboto:400,300);
body {
  font-family: Roboto, Verdana, Sans Serif;
  background: black; }

.jumbotron {
  margin: auto;
  margin-top: 25px;
  width: 50%;
  background: white; }

.mainText {
  font-size: 20px; }

.subText {
  font-size: 15px; }

.system {
  display: inline-block; }

.selected {
  font-weight: bold; }

.system a {
  margin-right: 5px; }

#location {
  width: 75px; }

/*# sourceMappingURL=style.css.map */


text:
#import <UIKit/UIKit.h>
#import "TiWindowProxy.h"

/**
 The protocol for root controller.
 It is not intended to be implemented by clients.
 @see TiRootViewController
 */
@protocol TiRootController
@required

/**
 Tells the root controller that a window became focused.
 @param focusedViewController The focused view controller.
 */
-(void)windowFocused:(UIViewController*)focusedViewController;

/**
 Tells the root controller that a window was closed.
 @param closedViewController The closed view controller.
 */
-(void)windowClosed:(UIViewController *)closedViewController;

/**
 Tells the root controller to resize its view to the size of main screen.
 @return The bounds of the view after resize.
 */
-(CGRect)resizeView;

/**
 Tells the root controller to reposition all its subviews.
 */
-(void)repositionSubviews;

/**
 Tells the root controller that the view controller will hide.
 @param viewController The view controller to hide.
 @param animated The animation flag.
 */
- (void)willHideViewController:(UIViewController *)viewController animated:(BOOL)animated;

/**
 Tells the root controller that the view controller was hidden.
 @param viewController The view controller hidden.
 @param animated The animation flag.
 */
- (void)didHideViewController:(UIViewController *)viewController animated:(BOOL)animated;

/**
 Tells the root controller that the view controller will show.
 @param viewController The view controller to show.
 @param animated The animation flag.
 */
- (void)willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;

/**
 Tells the root controller that the view controller was shown.
 @param viewController The view controller shown.
 @param animated The animation flag.
 */
- (void)didShowViewController:(UIViewController *)viewController animated:(BOOL)animated;

/**
 Tells the root controller that the keyboard received a focus.
 @param visibleProxy The view proxy that received keyboard focus.
 */
-(void)didKeyboardFocusOnProxy:(TiViewProxy<TiKeyboardFocusableView> *)visibleProxy;

/**
 Tells the root controller that the keyboard was blurred.
 @param blurredProxy The view proxy that blurred keyboard focus.
 */
-(void)didKeyboardBlurOnProxy:(TiViewProxy<TiKeyboardFocusableView> *)blurredProxy;

/**
 Whether or not the window proxy is the top window.
 @param window The window proxy
 @return _YES_ if the window proxy is the top window, _NO_ otherwise.
 */
-(BOOL)isTopWindow:(TiWindowProxy*)window;

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace BowlingGame7
{
    [TestClass]
    public class GameScoringTests
    {
        [TestMethod]
        public void ShouldScoreSimpleEngine()
        {
            int actual = new GameScoring().Score(new SimpleScore(), new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            Assert.AreEqual(55, actual);
        }

        [TestMethod]
        public void ShouldScoreBlackJack()
        {
            int blackjackScore = new GameScoring().Score(new BlackJackGame(), new[] { 1, 2, 3, 4 });
            Assert.AreEqual(10, blackjackScore);
        }

        [TestMethod]
        public void ShouldScoreBowling()
        {
            int score = new GameScoring().Score(new BowlingGame(), new[] { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 });
            Assert.AreEqual(300, score);
        }

        [TestMethod]
        public void ShouldScoreFizzBuzz()
        {
            string score = new GameScoring().Score(new FizzBuzzScore(), 15);
            Assert.AreEqual("FizzBuzz", score);
        }

    }

    public class SimpleScore : GameScoring.IScoreEngine<int[], int>
    {
        public int Score(int[] values)
        {
            return values.Sum();
        }
    }

    public class GameScoring
    {
        public interface IScoreEngine<in T, out TU>
        {
            TU Score(T values);
        }

        public TU Score<T, TU>(IScoreEngine<T, TU> simpleScore, T values)
        {
            return simpleScore.Score(values);
        }
    }
}


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms").   Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.

/*---
es5id: 15.2.3.13-2-16
description: >
    Object.isExtensible returns true for all built-in objects
    (String.prototype)
includes: [runTestCase.js]
---*/

function testcase() {
  var e = Object.isExtensible(String.prototype);
  if (e === true) {
    return true;
  }
 }
runTestCase(testcase);


text:
using System.IO;
using cohort.Email;
using cohort.Logging;
using cohort.Models;
using depot;

namespace cohort.Services
{
    public class EmailService : IEmailService
    {
        private readonly IEmailTemplateEngine _composer;
        private readonly IEmailProvider _sender;
        private readonly IEmailRepository _repository;
        private static readonly ICache Cache;

        static EmailService()
        {
            Cache = new DefaultCache();
        }

        public EmailService(IEmailTemplateEngine composer, IEmailProvider sender, IEmailRepository repository)
        {
            _composer = composer;
            _sender = sender;
            _repository = repository;
        }

        public void Send(string templateName, dynamic model)
        {
            string textLocation;
            if (Cohort.Site.Email.Templates.TryGetValue(templateName, out textLocation))
            {
                textLocation = Cohort.Site.Email.BaseDirectory + textLocation;
                var htmlLocation = textLocation.Replace(".liquid", ".html.liquid");

                var textTemplate = LoadOrGetCachedTemplate(textLocation);
                var htmlTemplate = LoadOrGetCachedTemplate(htmlLocation);

                var hasText = textTemplate != null;
                var hasHtml = htmlTemplate != null;

                EmailMessage email = null;
                if(hasText && hasHtml)
                {
                    email = _composer.CreateCombinedEmail(htmlTemplate, textTemplate, model);
                }
                else if (hasText)
                {
                    email = _composer.CreateTextEmail(textTemplate, model);
                }
                else if (hasHtml)
                {
                    _composer.CreateHtmlEmail(htmlTemplate, model);
                }

                DeliverAndLog(email);
            }
            else
            {
                Logger.Warn("No email template named {0} found!");
            }
        }

        private void DeliverAndLog(EmailMessage email)
        {
            if (email != null)
            {
                _sender.Send(email);
            }
            _repository.Save(email);
        }

        private static string LoadOrGetCachedTemplate(string location)
        {
            // TODO use that funky cache func thing
            string template = Cache.Get<string>(location);
            if(template == null)
            {
                if (File.Exists(location))
                {
                    template = File.ReadAllText(location);
                    var dependency = new DefaultFileCacheDependency();
                    dependency.FilePaths.Add(location);
                    Cache.Add(location, template, dependency);
                }
            }
            return template;
        }
    }
}


text:
'use strict';

/**
 * @ngdoc function
 * @name MaterialApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of MaterialApp
 */
angular.module('MaterialApp').controller('calendarCtrl', function ($scope) {

  $scope.selectedDate = null;
    $scope.firstDayOfWeek = 0; // First day of the week, 0 for Sunday, 1 for Monday, etc.
    $scope.setDirection = function(direction) {
      $scope.direction = direction;
    };

    $scope.dayClick = function(date) {
      $scope.msg = "You clicked " + $filter("date")(date, "MMM d, y h:mm:ss a Z");
    };

    $scope.prevMonth = function(data) {
      $scope.msg = "You clicked (prev) month " + data.month + ", " + data.year;
    };

    $scope.nextMonth = function(data) {
      $scope.msg = "You clicked (next) month " + data.month + ", " + data.year;
    };

});


text:
// Copyright (c) 2020 Vivaldi Technologies AS. All rights reserved

#include "menus/menu_storage.h"

#include <memory>
#include <utility>

#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/guid.h"
#include "base/json/json_file_value_serializer.h"
#include "base/json/json_string_value_serializer.h"
#include "base/path_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/task/post_task.h"
#include "base/values.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"

#include "components/datasource/resource_reader.h"
#include "menus/menu_codec.h"
#include "menus/menu_model.h"
#include "menus/menu_node.h"
#include "menus/menu_upgrade.h"

namespace menus {

const base::FilePath::CharType kMenuFolder[] = FILE_PATH_LITERAL("menus");
const base::FilePath::CharType kMainMenuFileName[] =
    FILE_PATH_LITERAL("mainmenu.json");
const base::FilePath::CharType kContextMenuFileName[] =
    FILE_PATH_LITERAL("contextmenu.json");
const base::FilePath::CharType kBackupExtension[] = FILE_PATH_LITERAL("bak");

// How often we save.
const int kSaveDelayMS = 2500;

// Generator for setting up guids. Useful for development. Use in OnLoad for the
// bundles file if necessary.
/*
void MakeGuids(const base::FilePath& path) {
  FILE *fp = fopen(path.AsUTF8Unsafe().c_str(), "r");
  if (fp) {
    char buf[1000];
    while (fgets(buf, 999, fp)) {
      printf("%s", buf);
      char* s = strstr(buf, "\"action\":");
      if (s) {
        sprintf(&buf[s-buf], "\"guid\": \"%s\",", base::GenerateGUID().c_str());
        puts(buf);
      }
    }
    fclose(fp);
  }
} Menu_Model* model,
*/

const base::FilePath::CharType* GetFileName(Menu_Model* model) {
  if (model->mode() == Menu_Model::kMainMenu) {
    return kMainMenuFileName;
  } else {
    return kContextMenuFileName;
  }
}

// Make a backup. Note, this file only exists during startup, It is deleted
// elsewhere once startup completes.
void MakeBackup(const base::FilePath& path) {
  base::FilePath backup_path = path.ReplaceExtension(kBackupExtension);
  base::CopyFile(path, backup_path);
}

bool GetVersion(std::string* version, const base::FilePath& file) {
  bool exists = base::PathExists(file);
  if (exists) {
    JSONFileValueDeserializer serializer(file);
    std::unique_ptr<base::Value> root(serializer.Deserialize(NULL, NULL));
    if (root.get()) {
      MenuCodec codec;
      return codec.GetVersion(version, *root.get());
    }
  }
  return false;
}

bool HasVersionStepped(const std::string& bundled_version,
                       const std::string& profile_version) {
  if (bundled_version != profile_version) {
    std::vector<std::string> bundled_array = base::SplitString(
        bundled_version, ".", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
    std::vector<std::string> profile_array = base::SplitString(
        profile_version, ".", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
    if (bundled_array.size() != 4) {
      LOG(ERROR) << "Menu Storage: Failed to upgrade, illegal bundled version: "
                 << bundled_version;
      return false;  // Should never happen. We have full control of the string.
    }
    if (profile_array.size() != 4) {
      return true;  // If profile is broken we should upgrade to correct it.
    }
    bool increased[4];  // major, minor, build, patch
    for (int i = 0; i < 4; i++) {
      int bundled, profile;
      if (!base::StringToInt(bundled_array[i], &bundled)) {
        LOG(ERROR)
            << "Menu Storage: Failed to upgrade, illegal bundled version: "
            << bundled_version;
        return false;  // Should never happen. We have full control of the
                       // string.
      }
      if (!base::StringToInt(profile_array[i], &profile)) {
        return true;  // If profile is broken we should upgrade to correct it.
      }
      increased[i] = bundled > profile;
    }
    // We only upgrade upwards to prevent potential looping if sync is enabled
    // between two diffrent builds.
    return increased[0] || (!increased[0] && increased[1]) || increased[2] ||
           (!increased[2] && increased[3]);
  }
  return false;
}

void OnLoad(const base::FilePath& profile_file,
            const base::FilePath::StringPieceType& filename,
            const base::WeakPtr<menus::MenuStorage> storage,
            std::unique_ptr<MenuLoadDetails> details) {
  bool exists;
  const base::FilePath* file;

  // Set up the bundled path here as GetResourceDirectory() calls code
  // that should not be used in the UI thread.
  base::FilePath bundled_file = ResourceReader::GetResourceDirectory()
                                    .Append(kMenuFolder)
                                    .Append(filename);

  if (details->force_bundle()) {
    // Revert to default while running.
    file = &bundled_file;
    exists = base::PathExists(*file);
  } else {
    // Check for upgrade. We use the full build number as a version test key.
    // The build number is saved in the profile file, but not in the bundled
    // so we take the bundled value from the load details segment.
    if (base::PathExists(profile_file)) {
      std::string profile_version;
      if (!GetVersion(&profile_version, profile_file)) {
        LOG(ERROR) << "Menu Storage: Failed to upgrade, version missing";
      } else {
        std::string bundled_version = details->control()->version;
        if (HasVersionStepped(bundled_version, profile_version)) {
          MenuUpgrade upgrade;
          std::unique_ptr<base::Value> root(
              upgrade.Run(profile_file, bundled_file, bundled_version));
          if (root.get()) {
            MenuCodec codec;
            if (!codec.Decode(details->mainmenu_node(), details->control(),
                              *root.get(), false, "")) {
              LOG(ERROR) << "Menu Storage: Failed to decode JSON content after "
                            "upgrade";
            } else {
              details->SetUpgradeRoot(std::move(root));
            }
          }
        }
      }
    }

    if (!details->has_upgraded()) {
      // Load on startup. Read from profile file if exists, otherwise bundled.
      file = &profile_file;
      exists = base::PathExists(*file);
      if (!exists) {
        file = &bundled_file;
        exists = base::PathExists(*file);
      }
    }
  }

  if (!details->has_upgraded()) {
    if (!exists) {
      if (details->force_bundle()) {
        LOG(ERROR) << "Menu Storage: File does not exist: " << bundled_file;
      } else {
        LOG(ERROR) << "Menu Storage: No files exists:\n"
                   << profile_file << "\n"
                   << bundled_file;
      }
    } else {
      // Loop so that we can attempt the bundled file if the local fails.
      while (exists) {
        bool is_error = false;

        JSONFileValueDeserializer serializer(*file);
        std::unique_ptr<base::Value> root(serializer.Deserialize(NULL, NULL));
        if (!root.get()) {
          LOG(ERROR) << "Menu Storage: Failed to parse JSON. Check format";
          std::string content;
          base::ReadFileToString(*file, &content);
          LOG(ERROR) << "Menu Storage: " << *file;
          LOG(ERROR) << "Menu Storage: Content: " << content;
          is_error = true;
        } else {
          MenuCodec codec;
          // Use the version set up in 'details' when reading from the bundle.
          std::string version =
              file == &bundled_file ? details->control()->version : "";
          if (!codec.Decode(details->mainmenu_node(), details->control(),
                            *root.get(), file == &bundled_file, version)) {
            LOG(ERROR) << "Menu Storage: Failed to decode JSON content from: "
                       << *file;
            is_error = true;
          }
        }

        if (!is_error || file == &bundled_file) {
          break;
        }
        // Fallback to bundled file.
        file = &bundled_file;
        exists = base::PathExists(*file);
        if (!exists) {
          LOG(ERROR) << "Menu Storage: Bundled file does not exist "
                     << bundled_file;
        } else {
          LOG(ERROR) << "Menu Storage: Attempting fallback " << bundled_file;
        }
      }
    }
  }

  base::PostTask(FROM_HERE, {content::BrowserThread::UI},
                 base::BindRepeating(&MenuStorage::OnLoadFinished, storage,
                                     base::Passed(&details)));
}

MenuLoadDetails::MenuLoadDetails(Menu_Node* mainmenu_node,
                                 Menu_Control* control,
                                 int64_t id,
                                 bool force_bundle)
    : mainmenu_node_(mainmenu_node),
      control_(control),
      id_(id),
      force_bundle_(force_bundle) {}

MenuLoadDetails::MenuLoadDetails(Menu_Node* mainmenu_node,
                                 Menu_Control* control,
                                 const std::string& menu,
                                 bool force_bundle)
    : mainmenu_node_(mainmenu_node),
      control_(control),
      id_(-1),
      force_bundle_(force_bundle),
      menu_(menu) {}

MenuLoadDetails::~MenuLoadDetails() {}

void MenuLoadDetails::SetUpgradeRoot(
    std::unique_ptr<base::Value> upgrade_root) {
  upgrade_root_ = std::move(upgrade_root);
}

MenuStorage::MenuStorage(content::BrowserContext* context,
                         Menu_Model* model,
                         base::SequencedTaskRunner* sequenced_task_runner)
    : model_(model),
      writer_(context->GetPath().Append(GetFileName(model)),
              sequenced_task_runner,
              base::Milliseconds(kSaveDelayMS)),
      weak_factory_(this) {
  sequenced_task_runner_ = sequenced_task_runner;
  sequenced_task_runner_->PostTask(FROM_HERE,
                                   base::BindOnce(&MakeBackup, writer_.path()));
}

MenuStorage::~MenuStorage() {
  if (writer_.HasPendingWrite())
    writer_.DoScheduledWrite();
}

void MenuStorage::Load(std::unique_ptr<MenuLoadDetails> details) {
  DCHECK(details);
  sequenced_task_runner_->PostTask(
      FROM_HERE,
      base::BindRepeating(&OnLoad, writer_.path(), GetFileName(model_),
                          weak_factory_.GetWeakPtr(), base::Passed(&details)));
}

void MenuStorage::ScheduleSave() {
  switch (backup_state_) {
    case BACKUP_NONE:
      backup_state_ = BACKUP_DISPATCHED;
      sequenced_task_runner_->PostTaskAndReply(
          FROM_HERE, base::BindOnce(&MakeBackup, writer_.path()),
          base::BindOnce(&MenuStorage::OnBackupFinished,
                         weak_factory_.GetWeakPtr()));
      return;
    case BACKUP_DISPATCHED:
      return;
    case BACKUP_ATTEMPTED:
      writer_.ScheduleWrite(this);
      return;
  }
  NOTREACHED();
}

void MenuStorage::OnBackupFinished() {
  backup_state_ = BACKUP_ATTEMPTED;
  ScheduleSave();
}

void MenuStorage::OnModelWillBeDeleted() {
  // We need to save now as otherwise by the time SaveNow is invoked
  // the model is gone.
  if (writer_.HasPendingWrite())
    SaveNow();

  model_ = NULL;
}

bool MenuStorage::SerializeData(std::string* output) {
  MenuCodec codec;
  JSONStringValueSerializer serializer(output);
  serializer.set_pretty_print(true);
  base::Value value = codec.Encode(model_);
  return serializer.Serialize(value);
}

void MenuStorage::OnLoadFinished(std::unique_ptr<MenuLoadDetails> details) {
  if (details->has_upgraded()) {
    SaveValue(details->get_upgrade_root());
  }
  if (model_) {
    model_->LoadFinished(std::move(details));
  }
}

bool MenuStorage::SaveNow() {
  if (!model_ || !model_->loaded()) {
    // We should only get here if we have a valid model and it's finished
    // loading.
    NOTREACHED();
    return false;
  }

  std::unique_ptr<std::string> data(new std::string);
  if (!SerializeData(data.get()))
    return false;
  writer_.WriteNow(std::move(data));
  return true;
}

bool MenuStorage::SaveValue(const std::unique_ptr<base::Value>& value) {
  std::unique_ptr<std::string> data(new std::string);
  JSONStringValueSerializer serializer(data.get());
  serializer.set_pretty_print(true);
  if (!serializer.Serialize(*(value.get()))) {
    return false;
  }
  writer_.WriteNow(std::move(data));
  return true;
}

}  // namespace menus


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using ESRI.ArcLogistics.Geometry;
using ESRI.ArcLogistics.DomainObjects;

namespace ESRI.ArcLogistics.App.Mapping
{
    class EditingMarker
    {
        #region constructors

        public EditingMarker(int multipleIndex, object obj)
        {
            _multipleIndex = multipleIndex;
            _editingObject = obj;
        }

        #endregion

        #region public members

        public int MultipleIndex
        {
            get { return _multipleIndex; }
        }

        #endregion public members

        #region private methods

        public object EditingObject
        {
            get { return _editingObject; }
        }

        #endregion

        #region private members

        private int _multipleIndex;
        private object _editingObject;

        #endregion private members
    }
}


text:
{% load i18n pybb_tags thumbnail %}

 {# may be remove this string? #}

        #
        {% pybb_time post.created %}

            {% include "pybb/avatar.html" %}

{{ post.user.username }}

            {% if post.user.get_profile.rank %}
                {% with post.user.get_profile as profile %}

                        {% trans "Rank" %}: {{ profile.rank }}
                        {% if user.is_authenticated and user != post.user %}
                            +
                            -
                        {% endif %}

                {% endwith %}
            {% endif %}
            {% if user.is_superuser %}

{{ post.user_ip }}

            {% endif %}

                {% if user.is_moderator or post|pybb_posted_by:user %}
                    {% trans "Edit" %}
                {% endif %}
                {% if user.is_moderator %}
                    {% trans "Delete" %}
                    {% if post.on_moderation %}
                    {% trans "Approve post" %}
                    {% endif %}
                {% endif %}

                {% if perms.pybb.change_post and user.is_staff %}
                    {% trans 'Admin' %}
                {% endif %}

            {{ post.body_html|safe }}
            {% if not user.is_authenticated or user.get_profile.show_signatures %}
                {% if post.user.get_profile.signature %}

                        {{ post.user.get_profile.signature_html|safe }}

                {% endif %}
            {% endif %}
            {% if post.updated %}

{% trans "Edited" %} {% pybb_time post.updated %}

            {% endif %}

            {% comment %}
                    {% if post.attachment_cache %}
                    {% for attach in post.attachment_cache %}

                    {% trans "Attachment" %}: {{ attach.name }} ({{ attach.size_display }})
                    {% endfor %}
                    {% endif %}
            {% endcomment %}

                {% trans "quote" %}

                    {% for attachment in post.attachments.all %}
                         {{ attachment.size_display }}
                    {% endfor %}


text:
package org.aexlib.gae.datastore.impl;

import java.util.concurrent.ConcurrentHashMap;

import org.aexlib.gae.datastore.DataTypeTranslator;

public class EnumDataTypeTranslatorImpl implements DataTypeTranslator {
    private static final ConcurrentHashMap<Class<?>, EnumDataTypeTranslatorImpl> instances =
        new ConcurrentHashMap<Class<?>, EnumDataTypeTranslatorImpl>();

    private final Class<?> userTypeClass;

    public static DataTypeTranslator getInstance(Class<?> userTypeClass) {
        if (!userTypeClass.isEnum()) {
            return null;
        }

        EnumDataTypeTranslatorImpl inst = instances.get(userTypeClass);
        if (inst == null) {
            instances.putIfAbsent(userTypeClass, inst = new EnumDataTypeTranslatorImpl(userTypeClass));
        }
        return inst;
    }

    private EnumDataTypeTranslatorImpl(Class<?> userTypeClass) {
        this.userTypeClass = userTypeClass;
    }

    public Object toStoreType(Object userData) {
        return userData != null ? userData.toString() : null;
    }

    public Object toUserType(Object storedData) {
        if (storedData == null || userTypeClass.getEnumConstants() == null) {
            return null;
        }

        for (Object o : userTypeClass.getEnumConstants()) {
            if (o != null && storedData.equals(o.toString())) {
                return o;
            }
        }

        return null;
    }

}


text:
using System;
using System.Globalization;

namespace Org.Apache.REEF.Wake.Time
{
    /// <summary>
    /// Time object
    /// </summary>
    public abstract class Time : IComparable<Time>
    {
        public Time(long timeStamp)
        {
            TimeStamp = timeStamp;
        }

        public long TimeStamp { get; private set; }

        public override string ToString()
        {
            return string.Format(CultureInfo.InvariantCulture, "{0}:[{1}]", GetType().Name, TimeStamp);
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            if (this == obj)
            {
                return true;
            }
            Time other = obj as Time;
            if (other != null)
            {
                return CompareTo(other) == 0;
            }
            return false;
        }

        public int CompareTo(Time other)
        {
            if (TimeStamp < other.TimeStamp)
            {
                return -1;
            }
            if (TimeStamp > other.TimeStamp)
            {
                return 1;
            }
            if (GetHashCode() < other.GetHashCode())
            {
                return -1;
            }
            if (GetHashCode() > other.GetHashCode())
            {
                return 1;
            }
            return 0;
        }
    }
}