text:
name: logout.js
language: html
---

```html
<template>
  <div>
    <button @click="logout">Log out</button>
  </div>
</template>
<script>
  // Composition API
  import { useAuth0 } from '@auth0/auth0-vue';

  export default {
    setup() {
      const auth0 = useAuth0();

      return {
        logout() {
          auth0.logout({ returnTo: window.location.origin });
        }
      };
    }
  };

  // Options API
  export default {
    methods: {
      logout() {
        this.$auth0.logout({ returnTo: window.location.origin });
      }
    }
  };
</script>
```


text:
/**
  @module ember-flexberry-designer
*/

import { computed } from '@ember/object';
import { isArray } from '@ember/array';
import joint from 'npm:jointjs';

import FdUmlElement from './fd-uml-element';
import { BaseObject } from './fd-uml-baseobject';

/**
  An object that describes a note on the UML diagram.

  @class FdUmlNote
  @extends FdUmlElement
*/
export default FdUmlElement.extend({

  /**
    The name of the note, actually its content.

    @property name
    @type String
  */
  name: computed('primitive.Name.Text', {
    get() {
      return this.get('primitive.Name.Text');
    },
    set(key, value) {
      let nameTxt = (isArray(value)) ? value.join('\n') : value;
      this.set('primitive.Name.Text', nameTxt);
      return value;
    },
  }),

  /**
    See {{#crossLink "FdUmlPrimitive/JointJS:method"}}here{{/crossLink}}.

    @method JointJS
  */
  JointJS() {
    let properties = this.getProperties('id', 'size', 'position');
    properties.objectModel = this;
    return new Note(properties);
  },
});

/**
  Defines the JointJS element, which represents the note in the UML diagram.

  @for FdUmlNote
  @class Note
  @extends BaseObject
  @namespace flexberry.uml
  @constructor
*/
export let Note = BaseObject.define('flexberry.uml.Note', {
  attrs: {
    '.corner-rect': {
      'ref': '.flexberry-uml-header-rect',
      'stroke': 'white',
      'stroke-width': '2',
      'ref-dx': -10
    },
    '.corner': {
      'ref': '.flexberry-uml-header-rect',
      'stroke': 'black',
      'stroke-width': '1',
      'd': 'M0,0 L0,10 L10,10 L0,0',
      'ref-dx': -10
    },
  },

  // Minimum height.
  minHeight: 17,
}, {
  markup: [
    '<g class="rotatable">',
    '<rect class="flexberry-uml-header-rect"/>',
    '<rect class="corner-rect" width="10" height="10"/>',
    '<path class="corner"/>',
    '</g>'
  ].join(''),

  getRectangles() {
    return [
      { type: 'header', element: this },
    ];
  },
});

joint.util.setByPath(joint.shapes, 'flexberry.uml.Note', Note, '.');

joint.shapes.flexberry.uml.NoteView = joint.shapes.flexberry.uml.BaseObjectView.extend({
  template: [
    '
',
    '<textarea class="class-name-input header-input" value="" rows="1" wrap="off" style="text-align: left;"></textarea>',
    '

',
    '
'
  ].join(''),

  initialize: function () {
    joint.shapes.flexberry.uml.BaseObjectView.prototype.initialize.apply(this, arguments);
    let paramsBox = this.$box.find('.header-input');
    paramsBox.css({
      left: 2,
      position: 'absolute'
    });
  },
});

redpajama_set_name: RedPajamaGithub


text:
module Development.Shake.Rule(
    -- * Builtin rules
    -- $builtin_rules

    -- ** Extensions
    -- $extensions

    -- ** Worked example
    -- $example

    -- * Defining builtin rules
    -- | Functions and types for defining new types of Shake rules.
    addBuiltinRule,
    BuiltinLint, noLint, BuiltinIdentity, noIdentity, BuiltinRun, RunMode(..), RunChanged(..), RunResult(..),
    -- * Calling builtin rules
    -- | Wrappers around calling Shake rules. In general these should be specialised to a builtin rule.
    apply, apply1,
    -- * User rules
    -- | Define user rules that can be used by builtin rules.
    --   Absent any builtin rule making use of a user rule at a given type, a user rule will have on effect -
    --   they have no inherent effect or interpretation on their own.
    addUserRule, getUserRuleList, getUserRuleMaybe, getUserRuleOne,
    -- * Lint integration
    -- | Provide lint warnings when running code.
    lintTrackRead, lintTrackWrite, lintTrackAllow,
    -- * History caching
    -- | Interact with the non-local cache. When using the cache it is important that all
    --   rules have accurate 'BuiltinIdentity' functions.
    historyIsEnabled, historySave, historyLoad
    ) where

import Development.Shake.Internal.Core.Types
import Development.Shake.Internal.Core.Action
import Development.Shake.Internal.Core.Build
import Development.Shake.Internal.Core.Rules

-- $builtin_rules
--
--   Shake \"Builtin\" rules are ones map keys to values - e.g. files to file contents. For each builtin rule you need to think:
--
-- * What is the @key@ type, which uniquely identifies each location, e.g. a filename.
--
-- * What is the @value@ type. The @value@ is not necessarily the full value, but is the result people can get if they ask
--   for the value associated with the @key@. As an example, for files when you 'need' a file you don't get any value back from
--   the file, so a simple file rule could have @()@ as its value.
--
-- * What information is stored between runs. This information should be sufficient to check if the value has changed since last time,
--   e.g. the modification time for files.
--
--   Typically a custom rule will define a wrapper of type 'Rules' that calls 'addBuiltinRule', along with a type-safe wrapper over
--   'apply' so users can introduce dependencies.

-- $extensions
--
--   Once you have implemented the basic functionality there is more scope for embracing additional features of Shake, e.g.:
--
-- * You can integrate with cached history by providing a working 'BuiltinIdentity' and using 'historySave' and 'historyLoad'.
--
-- * You can let users provide their own rules which you interpret with 'addUserRule'.
--
-- * You can integrate with linting by specifying a richer 'BuiltinLint' and options like 'lintTrackRead'.
--
--   There are lots of rules defined in the Shake repo at <https://github.com/ndmitchell/shake/tree/master/src/Development/Shake/Internal/Rules>.
--   You are encouraged to read those for inspiration.

-- $example
--
--   Shake provides a very comprehensive file rule which currently runs to over 500 lines of code, and supports lots of features
--   and optimisations. However, let's imagine we want to define a simpler rule type for files. As mentioned earlier, we have to make some decisions.
--
-- * A @key@ will just be the file name.
--
-- * A @value@ will be @()@ - when the user depends on a file they don't expect any information in return.
--
-- * The stored information will be the contents of the file, in it's entirety. Alternative choices would be the modtime or a hash of the contents,
--   but Shake doesn't require that. The stored information in Shake must be stored in a 'ByteString', so we 'Data.ByteString.pack' and
--   'Data.ByteString.unpack' to convert.
--
-- * We will allow user rules to be defined saying how to build any individual file.
--
--   First we define the type of key and value, deriving all the necessary type classes. We define a @newtype@ over 'FilePath' so we can
--   guarantee not to conflict with anyone else. Typically you wouldn't export the @File@ type, providing only sugar functions over it.
--
-- > newtype File = File FilePath
-- >     deriving (Show,Eq,Hashable,Binary,NFData)
-- > type instance RuleResult File = ()
--
--   Since we have decided we are also going to have user rules, we need to define a new type to capture the information stored by the rules.
--   We need to store at least the file it is producing and the action, which we do with:
--
-- > data FileRule = FileRule File (Action ())
--
--   With the definitions above users could call 'apply' and 'addUserRule' directly, but that's tedious and not very type safe. To make it easier
--   we introduce some helpers:
--
-- > fileRule :: FilePath -> Action () -> Rules ()
-- > fileRule file act = addUserRule $ FileRule (File file) act
-- >
-- > fileNeed :: FilePath -> Action ()
-- > fileNeed = apply1 . File
--
--   These helpers just add our type names, providing a more pleasant interface for the user. Using these function we can
--   exercise our build system with:
--
-- > example = do
-- >     fileRule "a.txt" $ pure ()
-- >     fileRule "b.txt" $ do
-- >         fileNeed "a.txt"
-- >         liftIO $ writeFile "b.txt" . reverse =<< readFile "a.txt"
-- >
-- >     action $ fileNeed "b.txt"
--
--   This example defines rules for @a.txt@ (a source file) and @b.txt@ (the 'reverse' of @a.txt@). At runtime this example will
--   complain about not having a builtin rule for @File@, so the only thing left is to provide one.
--
-- > addBuiltinFileRule :: Rules ()
-- > addBuiltinFileRule = addBuiltinRule noLint noIdentity run
-- >     where
-- >         fileContents (File x) = do b <- IO.doesFileExist x; if b then IO.readFile' x else pure ""
-- >
-- >         run :: BuiltinRun File ()
-- >         run key old mode = do
-- >             now <- liftIO $ fileContents key
-- >             if mode == RunDependenciesSame && fmap BS.unpack old == Just now then
-- >                 pure $ RunResult ChangedNothing (BS.pack now) ()
-- >             else do
-- >                 (_, act) <- getUserRuleOne key (const Nothing) $ \(FileRule k act) -> if k == key then Just act else Nothing
-- >                 act
-- >                 now <- liftIO $ fileContents key
-- >                 pure $ RunResult ChangedRecomputeDiff (BS.pack now) ()
--
--   We define a wrapper @addBuiltinFileRule@ that calls @addBuiltinRule@, opting out of linting and cached storage.
--   The only thing we provide is a 'BuiltinRun' function which gets the previous state, and whether any dependency has changed,
--   and decides whether to rebuild. If something has changed we call 'getUserRuleOne' to find the users rule and rerun it.
--   The 'RunResult' says what changed (either 'ChangedNothing' or 'ChangedRecomputeDiff' in our cases), gives us a new stored value
--   (just packing the contents) and the @value@ which is @()@.
--
--   To execute our example we need to also call @addBuiltinFileRule@, and now everything works.


text:
package com.jivesoftware.sdk.api.tile;

import com.jivesoftware.sdk.api.entity.TileInstance;
import com.jivesoftware.sdk.api.tile.data.BaseTile;
import com.jivesoftware.sdk.client.JiveClientException;

/**
 * Created by rrutan on 2/4/14.
 */
public interface JiveTile<T extends BaseTile> {

    public String getName();

    public T fetchData(TileInstance tileInstance) throws JiveClientException;

    public void pushData(TileInstance tileInstance, T data) throws JiveClientException;

} // end interface


text:
from .array import ARRAY
from ... import util
from ...sql import coercions
from ...sql import elements
from ...sql import expression
from ...sql import functions
from ...sql import roles
from ...sql.schema import ColumnCollectionConstraint

class aggregate_order_by(expression.ColumnElement):
    """Represent a PostgreSQL aggregate order by expression.

    E.g.::

        from sqlalchemy.dialects.postgresql import aggregate_order_by
        expr = func.array_agg(aggregate_order_by(table.c.a, table.c.b.desc()))
        stmt = select([expr])

    would represent the expression::

        SELECT array_agg(a ORDER BY b DESC) FROM table;

    Similarly::

        expr = func.string_agg(
            table.c.a,
            aggregate_order_by(literal_column("','"), table.c.a)
        )
        stmt = select([expr])

    Would represent::

        SELECT string_agg(a, ',' ORDER BY a) FROM table;

    .. versionadded:: 1.1

    .. versionchanged:: 1.2.13 - the ORDER BY argument may be multiple terms

    .. seealso::

        :class:`.array_agg`

    """

    __visit_name__ = "aggregate_order_by"

    def __init__(self, target, *order_by):
        self.target = coercions.expect(roles.ExpressionElementRole, target)

        _lob = len(order_by)
        if _lob == 0:
            raise TypeError("at least one ORDER BY element is required")
        elif _lob == 1:
            self.order_by = coercions.expect(
                roles.ExpressionElementRole, order_by[0]
            )
        else:
            self.order_by = elements.ClauseList(
                *order_by, _literal_as_text_role=roles.ExpressionElementRole
            )

    def self_group(self, against=None):
        return self

    def get_children(self, **kwargs):
        return self.target, self.order_by

    def _copy_internals(self, clone=elements._clone, **kw):
        self.target = clone(self.target, **kw)
        self.order_by = clone(self.order_by, **kw)

    @property
    def _from_objects(self):
        return self.target._from_objects + self.order_by._from_objects

class ExcludeConstraint(ColumnCollectionConstraint):
    """A table-level EXCLUDE constraint.

    Defines an EXCLUDE constraint as described in the `postgres
    documentation`__.

    __ http://www.postgresql.org/docs/9.0/static/sql-createtable.html#SQL-CREATETABLE-EXCLUDE

    """  # noqa

    __visit_name__ = "exclude_constraint"

    where = None

    @elements._document_text_coercion(
        "where",
        ":class:`.ExcludeConstraint`",
        ":paramref:`.ExcludeConstraint.where`",
    )
    def __init__(self, *elements, **kw):
        r"""
        Create an :class:`.ExcludeConstraint` object.

        E.g.::

            const = ExcludeConstraint(
                (Column('period'), '&&'),
                (Column('group'), '='),
                where=(Column('group') != 'some group')
            )

        The constraint is normally embedded into the :class:`.Table` construct
        directly, or added later using :meth:`.append_constraint`::

            some_table = Table(
                'some_table', metadata,
                Column('id', Integer, primary_key=True),
                Column('period', TSRANGE()),
                Column('group', String)
            )

            some_table.append_constraint(
                ExcludeConstraint(
                    (some_table.c.period, '&&'),
                    (some_table.c.group, '='),
                    where=some_table.c.group != 'some group',
                    name='some_table_excl_const'
                )
            )

        :param \*elements:

          A sequence of two tuples of the form ``(column, operator)`` where
          "column" is a SQL expression element or a raw SQL string, most
          typically a :class:`.Column` object, and "operator" is a string
          containing the operator to use.   In order to specify a column name
          when a  :class:`.Column` object is not available, while ensuring
          that any necessary quoting rules take effect, an ad-hoc
          :class:`.Column` or :func:`.sql.expression.column` object should be
          used.

        :param name:
          Optional, the in-database name of this constraint.

        :param deferrable:
          Optional bool.  If set, emit DEFERRABLE or NOT DEFERRABLE when
          issuing DDL for this constraint.

        :param initially:
          Optional string.  If set, emit INITIALLY <value> when issuing DDL
          for this constraint.

        :param using:
          Optional string.  If set, emit USING <index_method> when issuing DDL
          for this constraint. Defaults to 'gist'.

        :param where:
          Optional SQL expression construct or literal SQL string.
          If set, emit WHERE <predicate> when issuing DDL
          for this constraint.

        """
        columns = []
        render_exprs = []
        self.operators = {}

        expressions, operators = zip(*elements)

        for (expr, column, strname, add_element), operator in zip(
            coercions.expect_col_expression_collection(
                roles.DDLConstraintColumnRole, expressions
            ),
            operators,
        ):
            if add_element is not None:
                columns.append(add_element)

            name = column.name if column is not None else strname

            if name is not None:
                # backwards compat
                self.operators[name] = operator

            render_exprs.append((expr, name, operator))

        self._render_exprs = render_exprs

        ColumnCollectionConstraint.__init__(
            self,
            *columns,
            name=kw.get("name"),
            deferrable=kw.get("deferrable"),
            initially=kw.get("initially")
        )
        self.using = kw.get("using", "gist")
        where = kw.get("where")
        if where is not None:
            self.where = coercions.expect(roles.StatementOptionRole, where)

    def _set_parent(self, table):
        super(ExcludeConstraint, self)._set_parent(table)

        self._render_exprs = [
            (
                expr if isinstance(expr, elements.ClauseElement) else colexpr,
                name,
                operator,
            )
            for (expr, name, operator), colexpr in util.zip_longest(
                self._render_exprs, self.columns
            )
        ]

    def copy(self, **kw):
        elements = [(col, self.operators[col]) for col in self.columns.keys()]
        c = self.__class__(
            *elements,
            name=self.name,
            deferrable=self.deferrable,
            initially=self.initially,
            where=self.where,
            using=self.using
        )
        c.dispatch._update(self.dispatch)
        return c

def array_agg(*arg, **kw):
    """PostgreSQL-specific form of :class:`.array_agg`, ensures
    return type is :class:`.postgresql.ARRAY` and not
    the plain :class:`.types.ARRAY`, unless an explicit ``type_``
    is passed.

    .. versionadded:: 1.1

    """
    kw["_default_array_type"] = ARRAY
    return functions.func.array_agg(*arg, **kw)


text:
layout: post
title: Deep Learning for Multivariate Time Series Forecasting using Apache MXNet
---

This tutorial shows how to implement LSTNet, a multivariate time series forecasting model submitted by Wei-Cheng Chang, Yiming Yang, Hanxiao Liu and Guokun Lai in their paper [Modeling Long- and Short-Term Temporal Patterns](https://arxiv.org/pdf/1703.07015.pdf) in March 2017.  This model achieved state of the art performance on 3 of the 4 public datasets it was evaluated on.

We will use MXNet to train a neural network with convolutional, recurrent, recurrent-skip and autoregressive components.  The result is a model that predicts the future value for all input variables, given a specific horizon.

![](/example/multivariate_time_series/docs/model_architecture.png)

> Image from [Modeling Long- and Short-Term Temporal Patterns
with Deep Neural Networks](https://arxiv.org/abs/1703.07015), Figure 2

Our first step will be to download and unpack the public electricity dataset used in the paper.  This dataset comprises measurements of electricity consumption in kWh every hour from 2012 to 2014 for 321 different clients.

```s
$ wget https://github.com/laiguokun/multivariate-time-series-data/raw/master/electricity/electricity.txt.gz
$ gunzip electricity.txt.gz
```

Now we need to preprocess the data.  Each training record is the previous q values of each time series (see figure above).  Each label is the value of each of the 321 time series, h steps ahead.

```python
#modules
import math
import os
import sys
import numpy as np
import math
import mxnet as mx
import pandas as pd

#custom modules
import config

##############################################
#load input data
##############################################

#read tar.gz data into a pandas dataframe
df = pd.read_csv("./electricity.txt", sep=",", header=None)

#convert to numpy array
x = df.astype(float).as_matrix()

print("\n\tlength of time series: ", x.shape[0])

################################################
# define model hyperparameters and preprocessing parameters
################################################

#input data parameters
max_training_examples = None  # limit the number of training examples used
split = [0.6, 0.2, 0.2] # the proportion of training, validation and testing examples
horizon = 3  # how many time steps ahead do we wish to predict?
time_interval = 60 * 60  # seconds between feature values (data defined)

#model hyperparameters
batch_size = 128  # number of examples to pass into the network/use to compute gradient of the loss function
num_epoch = 100  # how many times to backpropogate and update weights
seasonal_period = 24 * 60 * 60  # seconds between important measurements (tune)
q = max(24 * 7, math.ceil(seasonal_period / time_interval)) # windowsize used to make a prediction
filter_list = [6] #size of each filter we wish to apply
num_filter = 50  # number of each filter size
recurrent_state_size = 50  # number of hidden units for each unrolled recurrent layer
recurrent_skip_state_size = 20 # number of hidden units for each unrolled recurrent-skip layer
optimizer = 'Adam'
optimizer_params = {'learning_rate': 0.001,
                    'beta1': 0.9,
                    'beta2': 0.999}
dropout = 0.1  # dropout probability applied after convolutional/recurrent and autoregressive layers
rcells = [mx.rnn.GRUCell(num_hidden=recurrent_state_size)] #recurrent cell types we wish to use
skiprcells = [mx.rnn.GRUCell(num_hidden=recurrent_skip_state_size, prefix="skip_")] # recurrent-skip cell types we wish to use

#computational parameters
context = mx.cpu()  # train on cpu or gpu

##############################################
# loop through data constructing features/labels
##############################################

#create arrays for storing values in
x_ts = np.zeros((x.shape[0] - q,  q, x.shape[1]))
y_ts = np.zeros((x.shape[0] - q, x.shape[1]))

#loop through collecting records for ts analysis depending on q
for n in list(range(x.shape[0])):

    if n + 1 < q:
        continue

    if n + 1 + horizon > x.shape[0]:
        continue

    else:
        y_n = x[n+horizon,:]
        x_n = x[n+1 - q:n+1,:]

    x_ts[n - q] = x_n
    y_ts[n - q] = y_n

#split into training and testing data
training_examples = int(x_ts.shape[0] * split[0])
valid_examples = int(x_ts.shape[0] * split[1])

x_train = x_ts[:training_examples]
y_train = y_ts[:training_examples]
x_valid = x_ts[training_examples:training_examples + valid_examples]
y_valid = y_ts[training_examples:training_examples + valid_examples]
x_test = x_ts[training_examples + valid_examples:]
y_test = y_ts[training_examples + valid_examples:]

print("\ntraining examples: ", x_train.shape[0],
        "\n\nvalidation examples: ", x_valid.shape[0],
        "\n\ntest examples: ", x_test.shape[0],
        "\n\nwindow size: ", q,
        "\n\nskip length p: ", seasonal_period / time_interval)
```

Now that we have our input data we are ready to start building the network graph.   First lets consider the data iterators and convolutional component.  If you're not solid on convolutions check out [this blog post](http://colah.github.io/posts/2014-07-Conv-Nets-Modular/).

All filters have width = number of time series.  The input data is zero padded on one side before being passed into the convolutional layer, ensuring the output from each kernel has the same dimensions, regardless of the filter size.

Each filter slides over the input data producing a 1D array of length q.  Relu activation is used as per the paper.  The resulting output from the convolutional component is of shape (batch size, q, total number of filters).

```python
###############################################
#define input data iterators for training and testing
###############################################

train_iter = mx.io.NDArrayIter(data={'seq_data': x_train},
                               label={'seq_label': y_train},
                               batch_size=batch_size)

val_iter = mx.io.NDArrayIter(data={'seq_data': x_valid},
                             label={'seq_label': y_valid},
                             batch_size=batch_size)

test_iter = mx.io.NDArrayIter(data={'seq_data': x_test},
                             label={'seq_label': y_test},
                             batch_size=batch_size)

#print input shapes
input_feature_shape = train_iter.provide_data[0][1]
input_label_shape = train_iter.provide_label[0][1]
print("\nfeature input shape: ", input_feature_shape,
      "\nlabel input shape: ", input_label_shape)

####################################
# define neural network graph
####################################

#create placeholders to refer to when creating network graph (names are defined in data iterators)
seq_data = mx.symbol.Variable(train_iter.provide_data[0].name)
seq_label = mx.sym.Variable(train_iter.provide_label[0].name)

# reshape data before applying convolutional layer (takes 4D shape)
conv_input = mx.sym.Reshape(data=seq_data, shape=(batch_size, 1, q, x.shape[1]))

print("\n\t#################################\n\
       #convolutional component:\n\
       #################################\n")

#create many convolutional filters to slide over the input
outputs = []
for i, filter_size in enumerate(filter_list):

        # zero pad the input array, adding rows at the top only
        # this ensures the number output rows = number input rows after applying kernel
        padi = mx.sym.pad(data=conv_input, mode="constant", constant_value=0,
                            pad_width=(0, 0, 0, 0, filter_size - 1, 0, 0, 0))
        padi_shape = padi.infer_shape(seq_data=input_feature_shape)[1][0]

        # apply convolutional layer (the result of each kernel position is a single number)
        convi = mx.sym.Convolution(data=padi, kernel=(filter_size, x.shape[1]), num_filter=num_filter)
        convi_shape = convi.infer_shape(seq_data=input_feature_shape)[1][0]

        #apply relu activation function as per paper
        acti = mx.sym.Activation(data=convi, act_type='relu')

        #transpose output shape in preparation for recurrent layer (batches, q, num filter, 1)
        transposed_convi = mx.symbol.transpose(data=acti, axes= (0,2,1,3))
        transposed_convi_shape = transposed_convi.infer_shape(seq_data=input_feature_shape)[1][0]

        #reshape to (batches, q, num filter) for recurrent layers
        reshaped_transposed_convi = mx.sym.Reshape(data=transposed_convi, target_shape=(batch_size, q, num_filter))
        reshaped_transposed_convi_shape = reshaped_transposed_convi.infer_shape(seq_data=input_feature_shape)[1][0]

        #append resulting symbol to a list
        outputs.append(reshaped_transposed_convi)

        print("\n\tpadded input size: ", padi_shape)
        print("\n\t\tfilter size: ", (filter_size, x.shape[1]), " , number of filters: ", num_filter)
        print("\n\tconvi output layer shape (notice length is maintained): ", convi_shape)
        print("\n\tconvi output layer after transposing: ", transposed_convi_shape)
        print("\n\tconvi output layer after reshaping: ", reshaped_transposed_convi_shape)

#concatenate symbols to (batch, total_filters, q, 1)
conv_concat = mx.sym.Concat(*outputs, dim=2)
conv_concat_shape = conv_concat.infer_shape(seq_data=input_feature_shape)[1][0]
print("\nconcat output layer shape: ", conv_concat_shape)

#apply a dropout layer
conv_dropout = mx.sym.Dropout(conv_concat, p = dropout)
```

The output from the convolutional layer is used in two places.  The first is a simple recurrent layer.  A gated recurrent unit is unrolled through q time steps.  The output of the last time step is taken.  Here's an [awesome blog post](http://colah.github.io/posts/2015-08-Understanding-LSTMs/) explaining different types of recurrent cells.

```python
print("\n\t#################################\n\
       #recurrent component:\n\
       #################################\n")

#define a gated recurrent unit cell, which we can unroll into many symbols based on our desired time dependancy
cell_outputs = []
for i, recurrent_cell in enumerate(rcells):

    #unroll the lstm cell, obtaining a symbol each time step
    outputs, states = recurrent_cell.unroll(length=conv_concat_shape[1], inputs=conv_dropout, merge_outputs=False, layout="NTC")

    #we only take the output from the recurrent layer at time t
    output = outputs[-1]

    #just ensures we can have multiple RNN layer types
    cell_outputs.append(output)

    print("\n\teach of the ", conv_concat_shape[1], " unrolled hidden cells in the RNN is of shape: ",
          output.infer_shape(seq_data=input_feature_shape)[1][0],
          "\nNOTE: only the output from the unrolled cell at time t is used...")

#concatenate output from each type of recurrent cell
rnn_component = mx.sym.concat(*cell_outputs, dim=1)
print("\nshape after combining RNN cell types: ", rnn_component.infer_shape(seq_data=input_feature_shape)[1][0])

#apply a dropout layer to output
rnn_dropout = mx.sym.Dropout(rnn_component, p=dropout)
```

The output from the convolutional layer is also passed to the recurrent-skip component.  Again a gated recurrent unit is unrolled through q time steps.  Unrolled units a prespecified time interval (seasonal period) apart are connected. In practice recurrent cells do not capture long term dependencies.  When predicting electricity consumption the measurements from the previous day could be very useful predictors.  By introducing skip connections 24 hours apart we ensure the model can leverage these historical dependencies.

```python
print("\n\t#################################\n\
       #recurrent-skip component:\n\
       #################################\n")

#define number of cells to skip through to get a certain time interval back from current hidden state
p =int(seasonal_period / time_interval)
print("adding skip connections for cells ", p, " intervals apart...")

#define a gated recurrent unit cell, which we can unroll into many symbols based on our desired time dependancy
skipcell_outputs = []
for i, recurrent_cell in enumerate(skiprcells):

    #unroll the rnn cell, obtaining an output and state symbol each time
    outputs, states = recurrent_cell.unroll(length=conv_concat_shape[1], inputs=conv_dropout, merge_outputs=False, layout="NTC")

    #for each unrolled timestep
    counter = 0
    connected_outputs = []
    for i, current_cell in enumerate(reversed(outputs)):

        #try adding a concatenated skip connection
        try:

            #get seasonal cell p steps apart
            skip_cell = outputs[i + p]

            #connect this cell to is seasonal neighbour
            cell_pair = [current_cell, skip_cell]
            concatenated_pair = mx.sym.concat(*cell_pair, dim=1)

            #prepend symbol to a list
            connected_outputs.insert(0, concatenated_pair)

            counter += 1

        except IndexError:

            #prepend symbol to a list without skip connection
            connected_outputs.insert(0, current_cell)

    selected_outputs = []
    for i, current_cell in enumerate(connected_outputs):

        t = i + 1

        #use p hidden states of Recurrent-skip component from time stamp t − p + 1 to t as outputs
        if t > conv_concat_shape[1] - p:

            selected_outputs.append(current_cell)

    #concatenate outputs
    concatenated_output = mx.sym.concat(*selected_outputs, dim=1)

    #append to list
    skipcell_outputs.append(concatenated_output)

print("\n\t", len(selected_outputs), " hidden cells used in output of shape: ",
        concatenated_pair.infer_shape(seq_data=input_feature_shape)[1][0], " after adding skip connections")

print("\n\tconcatenated output shape for each skipRNN cell type: ",
      concatenated_output.infer_shape(seq_data=input_feature_shape)[1][0])

#concatenate output from each type of recurrent cell
skiprnn_component = mx.sym.concat(*skipcell_outputs, dim=1)
print("\ncombined flattened recurrent-skip shape : ", skiprnn_component.infer_shape(seq_data=input_feature_shape)[1][0])

#apply a dropout layer
skiprnn_dropout = mx.sym.Dropout(skiprnn_component, p=dropout)
```

The final component is a simple autoregressive layer.  This splits the input data into 321 individual time series and passes each to a fully connected layer of size 1, with no activation function.  The effect of this is to predict the next value as a linear combination of the previous q values.

```python
print("\n\t#################################\n\
       #autoregressive component:\n\
       #################################\n")

auto_list = []
for i in list(range(x.shape[1])):

    #get a symbol representing data in each individual time series
    time_series = mx.sym.slice_axis(data=seq_data, axis=2, begin=i, end=i + 1)

    #pass to a fully connected layer
    fc_ts = mx.sym.FullyConnected(data=time_series, num_hidden=1)

    auto_list.append(fc_ts)

print("\neach time series shape: ", time_series.infer_shape(seq_data=input_feature_shape)[1][0])

#concatenate fully connected outputs
ar_output = mx.sym.concat(*auto_list, dim=1)
print("\nar component shape: ", ar_output.infer_shape(
    seq_data=input_feature_shape)[1][0])

#do not apply activation function since we want this to be linear
```

Now lets combine all the components, define a loss function and create a trainable module from the final symbol.  I found I achieved good performance with the L2 loss function.

```python
print("\n\t#################################\n\
       #combine AR and NN components:\n\
       #################################\n")

#combine model components
neural_components = mx.sym.concat(*[rnn_dropout, skiprnn_dropout], dim=1)

#pass to fully connected layer to map to a single value
neural_output = mx.sym.FullyConnected(
    data=neural_components, num_hidden=x.shape[1])
print("\nNN output shape : ", neural_output.infer_shape(
    seq_data=input_feature_shape)[1][0])

#sum the output from AR and deep learning
model_output = neural_output + ar_output
print("\nshape after adding autoregressive output: ",
      model_output.infer_shape(seq_data=input_feature_shape)[1][0])

#########################################
# loss function
#########################################

#compute the gradient of the L2 loss
loss_grad = mx.sym.LinearRegressionOutput(data=model_output, label=seq_label)

#set network point to back so name is interpretable
batmans_NN = loss_grad

#########################################
# create a trainable module on CPU/GPUs
#########################################

model = mx.mod.Module(symbol=batmans_NN,
                      context=context,
                      data_names=[v.name for v in train_iter.provide_data],
                      label_names=[v.name for v in train_iter.provide_label])
```

We are ready to start training, however, before we do so lets create some custom metrics.  Please see the paper for a definition of the three metrics: Relative square error, relative absolute error and correlation.

Note: although MXNet has functions for creating custom metrics, I found the metric output of my implementation varied with batch size, so defined them explicity.

```python
####################################
#define evaluation metrics to show when training
#####################################

#root relative squared error
def rse(label, pred):
    """computes the root relative squared error
    (condensed using standard deviation formula)"""

    #compute the root of the sum of the squared error
    numerator = np.sqrt(np.mean(np.square(label - pred), axis=None))
    #numerator = np.sqrt(np.sum(np.square(label - pred), axis=None))

    #compute the RMSE if we were to simply predict the average of the previous values
    denominator = np.std(label, axis=None)
    #denominator = np.sqrt(np.sum(np.square(label - np.mean(label, axis = None)), axis=None))

    return numerator / denominator

#relative absolute error
def rae(label, pred):
    """computes the relative absolute error
    (condensed using standard deviation formula)"""

    #compute the root of the sum of the squared error
    numerator = np.mean(np.abs(label - pred), axis=None)
    #numerator = np.sum(np.abs(label - pred), axis = None)

    #compute AE if we were to simply predict the average of the previous values
    denominator = np.mean(np.abs(label - np.mean(label, axis=None)), axis=None)
    #denominator = np.sum(np.abs(label - np.mean(label, axis = None)), axis=None)

    return numerator / denominator

#empirical correlation coefficient
def corr(label, pred):
    """computes the empirical correlation coefficient"""

    #compute the root of the sum of the squared error
    numerator1 = label - np.mean(label, axis=0)
    numerator2 = pred - np.mean(pred, axis=0)
    numerator = np.mean(numerator1 * numerator2, axis=0)

    #compute the root of the sum of the squared error if we were to simply predict the average of the previous values
    denominator = np.std(label, axis=0) * np.std(pred, axis=0)

    #value passed here should be 321 numbers
    return np.mean(numerator / denominator)

#create a composite metric manually
def metrics(label, pred):
    return ["RSE: ", rse(label, pred), "RAE: ", rae(label, pred), "CORR: ", corr(label, pred)]
```

Time to train.

```python
################
# #fit the model
################

# allocate memory given the input data and label shapes
model.bind(data_shapes=train_iter.provide_data,
           label_shapes=train_iter.provide_label)

# initialize parameters by uniform random numbers
model.init_params()

# optimizer
model.init_optimizer(optimizer=optimizer,
                     optimizer_params=optimizer_params)

# train n epochs, i.e. going over the data iter one pass
for epoch in range(num_epoch):

    train_iter.reset()
    val_iter.reset()

    for batch in train_iter:
        # compute predictions
        model.forward(batch, is_train=True)
        model.backward()                                # compute gradients
        model.update()                                  # update parameters

    # compute train metrics
    pred = model.predict(train_iter).asnumpy()
    label = y_train

    print('\n', 'Epoch %d, Training %s' % (epoch, metrics(label, pred)))

    # compute test metrics
    pred = model.predict(val_iter).asnumpy()
    label = y_valid
    print('Epoch %d, Validation %s' % (epoch, metrics(label, pred)))
```

The hyperparameters previously specified resulted in comparible performance to the results in the paper (*RSE = 0.0967, RAE = 0.0581 and CORR = 0.8941*) with horizon = 3 hours.

This model took ~10 hours to train on an [Nvidia Tesla K80 GPU](http://www.nvidia.ca/object/tesla-k80.html).

This code can be found in [my github repo](https://github.com/opringle/multivariate_time_series_forecasting), separated into training and config files. You can find the trained model symbol and parameters in the results folder.  This model was originally implemented in PyTorch and can be found [here](https://github.com/laiguokun/LSTNet).

Happy forecasting!

# About the author

>[Oliver Pringle](https://www.linkedin.com/in/oliverpringle/) graduated from the UBC Master of Data Science Program in 2017 and is currently a Data Scientist at [Finn.ai](http://finn.ai/) working on AI driven conversational assistants.


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#include "EnginePrivate.h"
#include "SoundDefinitions.h"
#include "Sound/SoundNodeBranch.h"

#define LOCTEXT_NAMESPACE "SoundNodeBranch"

/*-----------------------------------------------------------------------------
    USoundNodeLocality implementation.
-----------------------------------------------------------------------------*/
USoundNodeBranch::USoundNodeBranch(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
}

void USoundNodeBranch::ParseNodes( FAudioDevice* AudioDevice, const UPTRINT NodeWaveInstanceHash, FActiveSound& ActiveSound, const FSoundParseParameters& ParseParams, TArray<FWaveInstance*>& WaveInstances )
{
	BranchPurpose BranchToUse = BranchPurpose::ParameterUnset;
	bool bParamValue = false;

	if (ActiveSound.GetBoolParameter( BoolParameterName, bParamValue ))
	{
		BranchToUse = (bParamValue ? BranchPurpose::ParameterTrue : BranchPurpose::ParameterFalse);
	}

	const int32 ChildNodeIndex = (int32)BranchToUse;
	if (ChildNodeIndex < ChildNodes.Num() && ChildNodes[ChildNodeIndex])
	{
		ChildNodes[ChildNodeIndex]->ParseNodes(AudioDevice, GetNodeWaveInstanceHash(NodeWaveInstanceHash, ChildNodes[ChildNodeIndex], ChildNodeIndex), ActiveSound, ParseParams, WaveInstances);
	}
}

#if WITH_EDITOR
FText USoundNodeBranch::GetInputPinName(int32 PinIndex) const
{
	const BranchPurpose Branch = (BranchPurpose)PinIndex;
	switch (Branch)
	{
	case BranchPurpose::ParameterTrue:
		return LOCTEXT("True", "True");

	case BranchPurpose::ParameterFalse:
		return LOCTEXT("False", "False");

	case BranchPurpose::ParameterUnset:
		return LOCTEXT("ParamUnset", "Parameter Unset");
	}

	return Super::GetInputPinName(PinIndex);
}

FText USoundNodeBranch::GetTitle() const
{
	FFormatNamedArguments Arguments;
	Arguments.Add(TEXT("Description"), Super::GetTitle());
	Arguments.Add(TEXT("ParameterName"), FText::FromName(BoolParameterName));

	return FText::Format(LOCTEXT("Title", "{Description} ({ParameterName})"), Arguments);
}
#endif //WITH_EDITOR

#undef LOCTEXT_NAMESPACE


text:
Contributing
============

Details how to contribute are available in the
`OpenStack infrastructure manual <http://docs.openstack.org/infra/manual/developers.html>`__.

Changes be submitted for review via the Gerrit tool, following the workflow
documented in the
`OpenStack infrastructure manual <http://docs.openstack.org/infra/manual/developers.html#development-workflow>`__.

Bugs and feature requests should be filed on
`Launchpad <https://launchpad.net/packstack-vagrant.>`__, not GitHub:


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="global_actions_toggle_airplane_mode">Chế độ máy bay</string>
    <string name="global_actions_airplane_mode_on_status">Chế độ máy bay BẬT</string>
    <string name="dialer_keyboard_hint_txt">Dùng bàn phím để quay số</string>
</resources>


text:
"use strict";
var env = require('../lib/env');
var Spec = require('../lib/Spec');
var SecondPreciseClock = require('../lib/SecondPreciseClock');
var MinutePreciseClock = require('../lib/MinutePreciseClock');
var LamportClock = require('../lib/LamportClock');

env.debug = console.log;
env.multihost = true;

asyncTest('1.a timestamp sequence test', function () {
    var clock = new SecondPreciseClock('gritzko');
    expect(100);
    var ts1 = clock.issueTimestamp(), ts2, i=0;
    var iv = setInterval(function(){
        ts2 = clock.issueTimestamp();
        if (ts2<=ts1) {
            console.error(ts2, '<=', ts1);
        }
        if (i++==100) {
            start();
            clearInterval(iv);
        } else {
            ok(ts2 > ts1);
        }
        ts1 = ts2;
    }, 0);
    //swarm.close();
});

test('1.b basic specifier syntax', function (test) {
    var testSpec = '/Class#ID!7Umum+gritzko~ssn.event';
    var spec = new Spec(testSpec);
    equal(spec.version(),'7Umum+gritzko~ssn');
    equal(spec.token('!').ext,'gritzko~ssn');
    equal(spec.source(),'gritzko~ssn');
    equal(spec.author(),'gritzko');
    var rev = spec.toString();
    equal(rev,testSpec);
    /*var time = '20130811192020';
    var iso = Spec.timestamp2iso(time);
    var date = new Date(iso);
    test.equal(date.getMonth(),7); // zero based
    test.equal(date.getSeconds(),20);*/
    var spec2 = new Spec(spec);
    equal(spec.toString(),spec2.toString());
    var def = new Spec('/Type#id!ver.method');
    var over = def.set('#newid.newmethod');
    equal(over,'/Type#newid!ver.newmethod');
    var abc = new Spec('!abc');
    equal(abc.has('!ab'), false); // ?
    equal(abc.has('!'), true);
});

test('1.c spec filters', function () {
    var filter = '.on';
    equal (new Spec('!abc.on/Class').fits(filter), true);
    equal (new Spec('.off/Class').fits(filter), false);
    equal (new Spec('/Type!abc.off.on').fits(filter), true);

});

test('1.d version vector', function (){
    // the convention is: use "!version" for vectors and
    // simply "version" for scalars
    var vec = '!7AM0f+gritzko!0longago+krdkv!7AMTc+aleksisha!0ld!00ld#some+garbage';
    var map = new Spec.Map(vec);
    ok(map.covers('7AM0f+gritzko'));
    ok(!map.covers('7AMTd+aleksisha'));
    ok(!map.covers('6AMTd+maxmaxmax'));
    ok(map.covers('0ld'));
    ok(!map.covers('0le'));
    equal(map.map['swarm'],'0ld');
    ok(!('garbage' in map.map));
    equal(map.toString({rot:'6'}),'!7AMTc+aleksisha!7AM0f+gritzko');
    equal(map.toString({rot:'6',top:1}),'!7AMTc+aleksisha');

    var map2 = new Spec.Map("!1QDpv03+anon000qO!1P7AE05+anon000Bu");
    equal(!map2.covers(new Spec('!1P7AE05+anon000Bu.in').version()),false);
});

test('1.e corner cases', function () {
    var empty = new Spec('');
    equal(empty.type()||empty.id()||empty.op()||empty.version(),'');
    equal(empty.toString(),'');
    var action = new Spec('.on+re');
    equal(action.op(),'on+re');
    var fieldSet = new Spec('/TodoItem#7AM0f+gritzko!7AMTc+gritzko.set');
    equal(fieldSet.type(),'TodoItem');
    equal(fieldSet.id(),'7AM0f+gritzko');
    equal(fieldSet.version(),'7AMTc+gritzko');
    equal(fieldSet.op(),'set');
});

test('1.f minute-precise clox', function(test){
    var clock = new MinutePreciseClock('min');
    var prevts = '';
    for(var i=0; i<64; i++) {
        var ts = clock.issueTimestamp();
        ok(/^[0-9a-zA-Z_~]{5}\+min$/.test(ts));
        ok(ts>prevts);
        prevts = ts;
    }
    for(var i=0; i<130; i++) {
        var ts = clock.issueTimestamp();
    }
    ok(/^[0-9a-zA-Z_~]{7}\+min$/.test(ts));

    // tick 60 times
    // check the last char is changing
    // unless minute changed then restart
    // tick 60 times
    // see it spills over (extended ts)
});

test('1.g timestamp-ahead', function(test){
    var clock = new SecondPreciseClock('normal');
    var ts = clock.issueTimestamp();
    var parsed = clock.parseTimestamp(ts);
    //var tenAhead = Spec.int2base(parsed.time+10, 5)+'+ahead';
    //var tenBehind = Spec.int2base(parsed.time-10, 5)+'+behind';
    var clockAhead = new SecondPreciseClock('ahead', 10000);
    var clockBehind = new SecondPreciseClock('behind', -10000);
    var tsAhead = clockAhead.issueTimestamp();
    var tsBehind = clockBehind.issueTimestamp();
    ok(tsAhead>ts);
    ok(ts>tsBehind);
});

test('1.h timestamp to date', function(test){
    var clock = new SecondPreciseClock('normal');
    var ts = clock.issueTimestamp();
    var date = new Date();
    var recovered = clock.timestamp2date(ts);
    ok( Math.abs(date.getTime()-recovered.getTime()) < 2000 );
});

test('1.i Lamport clocks', function(test){
    var clock = new LamportClock('leslie');
    var ts1 = clock.issueTimestamp();
    equal(ts1,'00000+leslie');
    var ts2 = clock.issueTimestamp();
    equal(ts2,'00001+leslie');
    clock.checkTimestamp('00004+leslie');
    equal(clock.issueTimestamp(),'00005+leslie');
});


text:
require.def('antie/widgets/component',
    [
        'antie/widgets/container',
        'antie/runtimecontext'
    ],
    function(Container, RuntimeContext) {
        'use strict';

        /**
         * The Component widget class represents sections of UI that may be dynamically loaded.
         * @name antie.widgets.Component
         * @class
         * @extends antie.widgets.Container
         * @requires antie.RuntimeContext
         * @param {String} [id] The unique ID of the widget. If excluded, a temporary internal ID will be used (but not included in any output).
         */
        return Container.extend(/** @lends antie.widgets.Component.prototype */ {
            /**
             * @constructor
             * @ignore
             */
            init: function(id) {
                this._super(id);
                this.addClass('component');
                this._isModal = false;
            },
            /**
             * Hide the component.
             */
            hide: function() {
                if(this.parentWidget) {
                    this.parentWidget.hide();
                }
            },
            /**
             * Returns any state information required (in addition to the initial arguments) that is required to restore this component.
             * @returns State information
             */
            getCurrentState: function() {
                return null;
            },

            getIsModal: function() {
                return this._isModal;
            },

            setIsModal: function(modal) {
                this._isModal = modal;
            },

            getConfig: function() {
                return RuntimeContext.getDevice().getConfig();
            },

            /**
             * Returns whether the widget is a Component.
             * @returns {Boolean} True if the widget is a Component.
             */
            isComponent: function() {
                return true;
            }
        });
    }
);


text:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { DataService } from '../shared/data.service';
import { Speaker } from '../shared/model';

@Component({
  selector: 'conf-speakers',
  templateUrl: './speakers.component.html'
})
export class SpeakersComponent implements OnInit {
  speakers: Speaker[];

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.getSpeakers();
  }

  getSpeakers(): void {
    this.dataService
      .getSpeakers()
      .then(speakers => this.speakers = speakers);
  }

}


text:
<?php

/**
 * Skeleton subclass for performing query and update operations on the 'poplfdata' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 * @package    propel.generator.fbapp
 */
class PoplfdataQuery extends BasePoplfdataQuery
{
}


text:
package com.emitrom.lienzo.client.core.event;

import com.google.gwt.event.shared.EventHandler;

public interface ResizeEndHandler extends EventHandler
{
    public void onResizeEnd(int width, int height);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using SIL.LCModel;
using SIL.LCModel.Core.KernelInterfaces;

namespace LfMerge.Core.DataConverters.CanonicalSources
{
	public struct SemDomQuestion
	{
		public string Question;
		public string ExampleWords;      // Might be null if none found
		public string ExampleSentences;  // Might be null if none found
	}

	public class CanonicalSemanticDomainItem : CanonicalItem
	{
		// Get an <AUni ws="en"> type value
		// or an <AStr ws="en"><Run ws="en"> type value as well.
		// Will never return null. Returns an empty string if no text found.
		private string GetStr(XmlReader reader, out string ws)
		{
			ws = string.Empty;
			string result = string.Empty;
			string name = reader.LocalName;
			while (reader.Read())
			{
				switch (reader.NodeType)
				{
					case XmlNodeType.Element:
						{
							switch (reader.LocalName)
							{
								case "AUni":
								case "Run":
									ws = reader.GetAttribute("ws");
									result = reader.ReadInnerXml();
									break;
								case "Uni":
									result = reader.ReadInnerXml();
									break;
							}
						}
						break;
					case XmlNodeType.EndElement:
						if (reader.LocalName == name)
						{
							// Advance past closing element before returning
							reader.Read();
							return result ?? string.Empty;
						}
						break;
				}
			}
			return result ?? string.Empty;
		}

		private SemDomQuestion GetQuestion(XmlReader reader, out string ws)
		{
			ws = string.Empty;
			SemDomQuestion result = new SemDomQuestion();
			if (reader.LocalName != "CmDomainQ")
				return result;  // If we weren't on the right kind of node, return empty SemDomQuestion
			string name = reader.LocalName;
			while (reader.Read())
			{
				while (reader.Read())
				{
					switch (reader.NodeType)
					{
						case XmlNodeType.Element:
							{
								switch (reader.LocalName)
								{
									case "Question":
										result.Question = GetStr(reader, out ws);
										break;
									case "ExampleWords":
										result.ExampleWords = GetStr(reader, out ws);
										break;
									case "ExampleSentences":
										result.ExampleSentences = GetStr(reader, out ws);
										break;
								}
							}
							break;
						case XmlNodeType.EndElement:
							if (reader.LocalName == "CmDomainQ")
							{
								// Advance past closing element before returning
								reader.Read();
								return result;
							}
							break;
					}
				}
			}
			return result;
		}

		public override void PopulateFromXml(XmlReader reader)
		{
			if (reader.LocalName != "CmSemanticDomain")
				return;  // If we weren't on the right kind of node, do nothing
			GuidStr = reader.GetAttribute("guid");
			string ws = string.Empty; // Used as the out param in GetStr()
			// Note that if the writing systems in the SemDom.xml file are inconsistent, then
			// using a single out parameter everywhere may create inconsistent results. If we
			// ever need to parse a SemDom.xml with multiple writing systems in it, we might
			// have to change how we handle the "out ws" parameters in this function.
			while (reader.Read())
			{
				switch (reader.NodeType)
				{
					case XmlNodeType.Element:
						{
							switch (reader.LocalName)
							{
								case "CmSemanticDomain":
									var child = new CanonicalSemanticDomainItem();
									child.PopulateFromXml(reader);
									AppendChild(child);
									break;
								case "Abbreviation":
									string abbrev = GetStr(reader, out ws);
									AddAbbrev(ws, abbrev);
									break;
								case "Name":
									string name = GetStr(reader, out ws);
									AddName(ws, name);
									break;
								case "Description":
									string desc = GetStr(reader, out ws);
									AddDescription(ws, desc);
									break;
								case "OcmCodes":
									List<string> ocmCodes = GetExtraDataList<string>("OcmCodes");
									string ocmCodesText = GetStr(reader, out ws);
									ocmCodes.AddRange(ocmCodesText.Split(new string[] { ";  " }, StringSplitOptions.None));
									break;
								case "LouwNidaCodes":
									List<string> louwNidaCodes = GetExtraDataList<string>("OcmCodes");
									string louwNidaCodesText = GetStr(reader, out ws);
									louwNidaCodes.AddRange(louwNidaCodesText.Split(new string[] { ";  " }, StringSplitOptions.None));
									break;
								case "CmDomainQ":
									Dictionary<string, List<SemDomQuestion>> questionsDict = GetExtraDataWsDict<SemDomQuestion>("Questions");
									SemDomQuestion question = GetQuestion(reader, out ws);
									List<SemDomQuestion> questions = GetListFromDict<SemDomQuestion>(questionsDict, ws);
									questions.Add(question);
									break;
							}
							break;
						}
					case XmlNodeType.EndElement:
						{
							if (reader.LocalName == "CmSemanticDomain")
							{
								Key = AbbrevByWs(KeyWs);
								reader.Read(); // Skip past the closing element before returning
								return;
							}
							break;
						}
				}
			}
		}

		protected override void PopulatePossibilityFromExtraData(ICmPossibility poss)
		{
			ICmSemanticDomain semdom = poss as ICmSemanticDomain;
			if (semdom == null)
				return;
			ILgWritingSystemFactory wsf = semdom.Cache.WritingSystemFactory;
			var questionFactory = semdom.Cache.ServiceLocator.GetInstance<ICmDomainQFactory>();
			Dictionary<string, List<SemDomQuestion>> questionsByWs = GetExtraDataWsDict<SemDomQuestion>("Questions");
			// This dict looks like {"en": (question 1, question 2...)} but each question object wants to get data that
			// looks more or less like {"en": "the question in English", "fr": "la question en francais"}...
			// So first we ensure that there are enough question objects available, and then we'll access them by index
			// as we step through the writing systems.
			int numQuestions = questionsByWs.Values.Select(questionList => questionList.Count).Max();
			while (semdom.QuestionsOS.Count < numQuestions)
			{
				semdom.QuestionsOS.Add(questionFactory.Create());
			}
			foreach (string ws in questionsByWs.Keys)
			{
				int wsId = wsf.GetWsFromStr(ws);
				int i = 0;
				foreach (SemDomQuestion qStruct in questionsByWs[ws])
				{
					// TODO: Find out what set_String() would do with a null value. Would it remove the string?
					// If it would *remove* it, then we might be able to replace string.Empty with nulls in the code below
					// Right now, just be extra-cautious and ensure we never put nulls into set_String().
					semdom.QuestionsOS[i].Question.set_String(wsId, qStruct.Question ?? string.Empty);
					semdom.QuestionsOS[i].ExampleSentences.set_String(wsId, qStruct.ExampleSentences ?? string.Empty);
					semdom.QuestionsOS[i].ExampleWords.set_String(wsId, qStruct.ExampleWords ?? string.Empty);
					i++;
				}
			}
		}
	}
}


text:
package city.gui.interiors;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Timer;

import city.bases.interfaces.AnimationInterface;
import city.gui.BuildingCard;

public class MarketPanel extends BuildingCard implements ActionListener {

	private static final long serialVersionUID = 1355285244678935863L;
//	Data
//	=====================================================================
//	Fixed Numbers
//	--------------------------------------------------------------------
	public static final int RECTDIM = 20;
    public static final int ENTRANCEX = 40, ENTRANCEY = 470;
    public static final int EXITX = 420, EXITY = 520;

//	Phone
//	--------------------------------------------------------------------
    public static final int PHONEX = 40, PHONEY = 0;
    public static final int PHONEW = 20, PHONEH = 10;

//	Shelf
//	--------------------------------------------------------------------
    public static final int SHELFX = 35, SHELFY = 50;
    public static final int SHELFW = 30, SHELFH = 150;
    public static final int SHELFGAP = 70;

//	Counter
//	--------------------------------------------------------------------
    public static final int COUNTERX = 0, COUNTERY = 275;
    public static final int COUNTERW = 500, COUNTERH = 25;
    public static final int COUNTERINTERACTIONY = COUNTERY+COUNTERH;

//	Cashier
//	--------------------------------------------------------------------
    public static final int CASHIERX = 440, CASHIERY = 275-RECTDIM;
    public static final int CASHIEREMPINTERACTIONX = CASHIERX-RECTDIM, CASHIEREMPINTERACTIONY = CASHIERY;
    public static final int CASHIERCUSTINTERACTIONY = COUNTERY+COUNTERH;

//	Waiting Areas
//	--------------------------------------------------------------------
    public static final int SERVICEWAITINGX = 100, SERVICEWAITINGY = 420;
    public static final int ITEMSWAITINGX = 400, ITEMSWAITINGY = 320;

	private final int delayMS = 5;

//	Constructor
//	=====================================================================
	public MarketPanel(Color color) {
		super(color);

		setVisible(true);

		Timer timer = new Timer(delayMS, this);
		timer.start();
	}

	public void actionPerformed(ActionEvent e) {
		repaint();
	}

	@Override
	public void paint(Graphics graphics) {
		Graphics2D g2 = (Graphics2D)graphics;
		// Clear the screen by painting a rectangle the size of the frame

		g2.setColor(background);
		g2.fillRect(0, 0, CARD_WIDTH, CARD_HEIGHT);

		g2.setColor(Color.YELLOW);
		g2.fillRect(PHONEX, PHONEY, PHONEW, PHONEH);

		g2.setColor(Color.DARK_GRAY);
		for (int i = 0; i < 5; i++) {
			g2.fillRect(SHELFX+((SHELFW+SHELFGAP)*i), SHELFY, SHELFW, SHELFH);
		}

		g2.setColor(Color.YELLOW);
		g2.fillRect(COUNTERX, COUNTERY, COUNTERW, COUNTERH);

		// Update the position of each visible element
		for(AnimationInterface animation : animations) {
//			if (animation.getVisible()) {
				animation.updatePosition();
//			}
		}

		// Draw each visible element after updating their positions
		// TODO generates concurrent modification exception
		for(AnimationInterface animation : animations) {
//			if (animation.getVisible()) {
				animation.draw(g2);
//			}
		}
	}
}


text:
/* Generic context menu styles */
.contextMenu {
    position: absolute;
    width: 120px;
    z-index: 99999;
    border: solid 1px #CCC;
    background: #FFF;
    padding: 0px;
    margin: 0px;
    display: none;
}

.contextMenu LI {
    list-style: none;
    padding: 0px;
    margin: 0px;
}

.contextMenu A {
    color: #333;
    text-decoration: none;
    display: block;
    line-height: 20px;
    height: 20px;
    background-position: 6px center;
    background-repeat: no-repeat;
    outline: none;
    padding: 1px 5px;
    padding-left: 28px;
}

.contextMenu LI.hover A {
    color: #FFF;
    background-color: #3399FF;
}

.contextMenu LI.disabled A {
    color: #AAA;
    cursor: default;
}

.contextMenu LI.hover.disabled A {
    background-color: transparent;
}

.contextMenu LI.separator {
    border-top: solid 1px #CCC;
}

/*
    Adding Icons

    You can add icons to the context menu by adding
    classes to the respective LI element(s)
*/

.contextMenu LI.download A { background-image: url(/esup-filemanager/img/flaticons/download_16px.png); }
.contextMenu LI.zip A { background-image: url(/esup-filemanager/img/flaticons/zip_16px.png); }
.contextMenu LI.cut A { background-image: url(/esup-filemanager/img/flaticons/cut_16px.png); }
.contextMenu LI.copy A { background-image: url(/esup-filemanager/img/flaticons/copy_16px.png); }
.contextMenu LI.paste A { background-image: url(/esup-filemanager/img/flaticons/paste_16px.png);  }
.contextMenu LI.delete A { background-image: url(/esup-filemanager/img/flaticons/delete_16px.png);  }
.contextMenu LI.rename A { background-image: url(/esup-filemanager/img/flaticons/rename_16px.png); }


text:
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="org.flowable.standalone.cfg.TaskMapper">

  <!-- CUSTOM TASK RESULTMAP -->

  <resultMap id="customTaskResultMap" type="org.flowable.standalone.cfg.CustomTask">
    <id property="id" column="ID_" jdbcType="VARCHAR"/>
    <result property="name" column="NAME_" jdbcType="VARCHAR"/>
    <result property="priority" column="PRIORITY_" jdbcType="INTEGER"/>
    <result property="createTime" column="CREATE_TIME_" jdbcType="TIMESTAMP" />
    <result property="owner" column="OWNER_" jdbcType="VARCHAR"/>
    <result property="assignee" column="ASSIGNEE_" jdbcType="VARCHAR"/>
  </resultMap>

  <sql id="selectCustomTaskColumns">
		RES.ID_, RES.NAME_, RES.PRIORITY_, RES.CREATE_TIME_, RES.OWNER_, RES.ASSIGNEE_
	</sql>

	<select id="selectCustomTaskList" parameterType="string" resultMap="customTaskResultMap">
		select <include refid="selectCustomTaskColumns"/> from ACT_RU_TASK RES
	</select>

	<select id="selectOneCustomTask" parameterType="string" resultMap="customTaskResultMap">
		select <include refid="selectCustomTaskColumns"/> from ACT_RU_TASK RES where RES.ID_ = #{id}
	</select>

	<select id="selectCustomTaskCountByQueryCriteria" parameterType="org.flowable.standalone.cfg.CustomTaskQuery" resultType="long">
    select count(distinct RES.ID_)
    <include refid="selectCustomTaskByQueryCriteriaSql"/>
  </select>

  <select id="selectCustomTaskByQueryCriteria" parameterType="org.flowable.standalone.cfg.CustomTaskQuery" resultMap="customTaskResultMap">
    <if test="firstResult != null and firstResult >= 0">${limitBefore}</if>
    select distinct <include refid="selectCustomTaskColumns"/> <if test="firstResult != null and firstResult >= 0">${limitBetween}</if>
    <include refid="selectCustomTaskByQueryCriteriaSql"/>
    ${orderBy}
    <if test="firstResult != null and firstResult >= 0">${limitAfter}</if>
  </select>

  <sql id="selectCustomTaskByQueryCriteriaSql">
  from ${prefix}ACT_RU_TASK RES
  <where>
	<if test="taskId != null">
		RES.ID_ = #{taskId}
	</if>
	<if test="owner != null">
		and RES.OWNER_ = #{owner}
	</if>
	<if test="unOwned">
		and RES.OWNER_ IS NULL
	</if>
  </where>
  </sql>
</mapper>


text:
package org.devgateway.ocds.web.rest.controller;

import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.devgateway.toolkit.persistence.repository.AdminSettingsRepository;
import org.devgateway.toolkit.web.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by mpostelnicu on 16-May-17.
 */
@RestController
public class AuthenticatedCheckerController {

    public static class AuthenticatedCheckerResponse {
        private Boolean authenticated;
        private Boolean disabledApiSecurity;

        public Boolean getAuthenticated() {
            return authenticated;
        }

        public void setAuthenticated(Boolean authenticated) {
            this.authenticated = authenticated;
        }

        public Boolean getDisabledApiSecurity() {
            return disabledApiSecurity;
        }

        public void setDisabledApiSecurity(Boolean disabledApiSecurity) {
            this.disabledApiSecurity = disabledApiSecurity;
        }
    }

    @Autowired
    protected AdminSettingsRepository adminSettingsRepository;

    @ApiOperation(value = "Returns true if the user is authenticated, false otherwise")
    @RequestMapping(value = "/isAuthenticated", method = {RequestMethod.GET, RequestMethod.POST})
    public AuthenticatedCheckerResponse isAuthenticated(final HttpServletResponse response) throws IOException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        AuthenticatedCheckerResponse r = new AuthenticatedCheckerResponse();

        r.setAuthenticated(false);
        r.setDisabledApiSecurity(SecurityUtil.getDisabledApiSecurity(adminSettingsRepository));

        if (authentication != null && authentication.isAuthenticated()) {
            r.setAuthenticated(true);
        }

        return r;
    }

}


text:
package org.apache.catalina.deploy;

import org.apache.catalina.util.RequestUtil;
import java.io.Serializable;

/**
 * Representation of a login configuration element for a web application,
 * as represented in a <login-config> element in the
 * deployment descriptor.
 *
 * @author Craig R. McClanahan
 *
 */

public class LoginConfig implements Serializable {

    // ----------------------------------------------------------- Constructors

    /**
     * Construct a new LoginConfig with default properties.
     */
    public LoginConfig() {

        super();

    }

    /**
     * Construct a new LoginConfig with the specified properties.
     *
     * @param authMethod The authentication method
     * @param realmName The realm name
     * @param loginPage The login page URI
     * @param errorPage The error page URI
     */
    public LoginConfig(String authMethod, String realmName,
                       String loginPage, String errorPage) {

        super();
        setAuthMethod(authMethod);
        setRealmName(realmName);
        setLoginPage(loginPage);
        setErrorPage(errorPage);

    }

    // ------------------------------------------------------------- Properties

    /**
     * The authentication method to use for application login.  Must be
     * BASIC, DIGEST, FORM, or CLIENT-CERT.
     */
    private String authMethod = null;

    public String getAuthMethod() {
        return (this.authMethod);
    }

    public void setAuthMethod(String authMethod) {
        this.authMethod = authMethod;
    }

    /**
     * The context-relative URI of the error page for form login.
     */
    private String errorPage = null;

    public String getErrorPage() {
        return (this.errorPage);
    }

    public void setErrorPage(String errorPage) {
        //        if ((errorPage == null) || !errorPage.startsWith("/"))
        //            throw new IllegalArgumentException
        //                ("Error Page resource path must start with a '/'");
        this.errorPage = RequestUtil.URLDecode(errorPage);
    }

    /**
     * The context-relative URI of the login page for form login.
     */
    private String loginPage = null;

    public String getLoginPage() {
        return (this.loginPage);
    }

    public void setLoginPage(String loginPage) {
        //        if ((loginPage == null) || !loginPage.startsWith("/"))
        //            throw new IllegalArgumentException
        //                ("Login Page resource path must start with a '/'");
        this.loginPage = RequestUtil.URLDecode(loginPage);
    }

    /**
     * The realm name used when challenging the user for authentication
     * credentials.
     */
    private String realmName = null;

    public String getRealmName() {
        return (this.realmName);
    }

    public void setRealmName(String realmName) {
        this.realmName = realmName;
    }

    // --------------------------------------------------------- Public Methods

    /**
     * Return a String representation of this object.
     */
    public String toString() {

        StringBuffer sb = new StringBuffer("LoginConfig[");
        sb.append("authMethod=");
        sb.append(authMethod);
        if (realmName != null) {
            sb.append(", realmName=");
            sb.append(realmName);
        }
        if (loginPage != null) {
            sb.append(", loginPage=");
            sb.append(loginPage);
        }
        if (errorPage != null) {
            sb.append(", errorPage=");
            sb.append(errorPage);
        }
        sb.append("]");
        return (sb.toString());

    }

}


text:
<?php

namespace CDMonte\SuiteCRMBridgeBundle\DAO\EndPoint;

/**
 * Class Auth
 * @package CDMonte\SuiteCRMBridgeBundle\DAO\EndPoint
 */
class Auth
{
    /**
     * @param $url
     * @param $version
     * @return EndPointInterface
     * @throws \Exception
     */
    public static function createEndPoint($url, $version)
    {
        /** @var EndPointInterface $endPoint */
        $endPoint = (new EndPointFactory($version))->getInstance();
        $endPoint->initialize($url);

        if (! $endPoint) {
            throw new \Exception("No endpoint");
        }

        return $endPoint;
    }
}


text:
package org.jvyamlb.exceptions;

/**
 * @author Ola Bini
 */
public class RepresenterException extends YAMLException {
    public RepresenterException(final String msg) {
        super(msg);
    }

    public RepresenterException(final Throwable thr) {
        super(thr);
    }
}// RepresenterException


text:
'use strict';

import Reflux             from 'reflux';

import API from '../utils/API';

var MenuSectionStore = Reflux.createStore({

  init() {
    API.get('menusections').then(resp => {
      this.menusections = resp;
      this.trigger(this.menusections);
    });
  },

});

export default MenuSectionStore;


text:
@interface YYFMDatabasePool()

- (void)pushDatabaseBackInPool:(YYFMDatabase*)db;
- (YYFMDatabase*)db;

@end

@implementation YYFMDatabasePool
@synthesize path=_path;
@synthesize delegate=_delegate;
@synthesize maximumNumberOfDatabasesToCreate=_maximumNumberOfDatabasesToCreate;

+ (id)databasePoolWithPath:(NSString*)aPath {
    return YYFMDBReturnAutoreleased([[self alloc] initWithPath:aPath]);
}

- (id)initWithPath:(NSString*)aPath {

    self = [super init];

    if (self != nil) {
        _path               = [aPath copy];
        _lockQueue          = dispatch_queue_create([[NSString stringWithFormat:@"YYFMDB.%@", self] UTF8String], NULL);
        _databaseInPool     = YYFMDBReturnRetained([NSMutableArray array]);
        _databaseOutPool    = YYFMDBReturnRetained([NSMutableArray array]);
    }

    return self;
}

- (void)dealloc {

    _delegate = 0x00;
    YYFMDBRelease(_path);
    YYFMDBRelease(_databaseInPool);
    YYFMDBRelease(_databaseOutPool);

    if (_lockQueue) {
        YYFMDBDispatchQueueRelease(_lockQueue);
        _lockQueue = 0x00;
    }
#if ! __has_feature(objc_arc)
    [super dealloc];
#endif
}

- (void)executeLocked:(void (^)(void))aBlock {
    dispatch_sync(_lockQueue, aBlock);
}

- (void)pushDatabaseBackInPool:(YYFMDatabase*)db {

    if (!db) { // db can be null if we set an upper bound on the # of databases to create.
        return;
    }

    [self executeLocked:^() {

        if ([_databaseInPool containsObject:db]) {
            [[NSException exceptionWithName:@"Database already in pool" reason:@"The YYFMDatabase being put back into the pool is already present in the pool" userInfo:nil] raise];
        }

        [_databaseInPool addObject:db];
        [_databaseOutPool removeObject:db];

    }];
}

- (YYFMDatabase*)db {

    __block YYFMDatabase *db;

    [self executeLocked:^() {
        db = [_databaseInPool lastObject];

        if (db) {
            [_databaseOutPool addObject:db];
            [_databaseInPool removeLastObject];
        }
        else {

            if (_maximumNumberOfDatabasesToCreate) {
                NSUInteger currentCount = [_databaseOutPool count] + [_databaseInPool count];

                if (currentCount >= _maximumNumberOfDatabasesToCreate) {
                    NSLog(@"Maximum number of databases (%ld) has already been reached!", (long)currentCount);
                    return;
                }
            }

            db = [YYFMDatabase databaseWithPath:_path];
        }

        //This ensures that the db is opened before returning
        if ([db open]) {
            if ([_delegate respondsToSelector:@selector(databasePool:shouldAddDatabaseToPool:)] && ![_delegate databasePool:self shouldAddDatabaseToPool:db]) {
                [db close];
                db = 0x00;
            }
            else {
                //It should not get added in the pool twice if lastObject was found
                if (![_databaseOutPool containsObject:db]) {
                    [_databaseOutPool addObject:db];
                }
            }
        }
        else {
            NSLog(@"Could not open up the database at path %@", _path);
            db = 0x00;
        }
    }];

    return db;
}

- (NSUInteger)countOfCheckedInDatabases {

    __block NSUInteger count;

    [self executeLocked:^() {
        count = [_databaseInPool count];
    }];

    return count;
}

- (NSUInteger)countOfCheckedOutDatabases {

    __block NSUInteger count;

    [self executeLocked:^() {
        count = [_databaseOutPool count];
    }];

    return count;
}

- (NSUInteger)countOfOpenDatabases {
    __block NSUInteger count;

    [self executeLocked:^() {
        count = [_databaseOutPool count] + [_databaseInPool count];
    }];

    return count;
}

- (void)releaseAllDatabases {
    [self executeLocked:^() {
        [_databaseOutPool removeAllObjects];
        [_databaseInPool removeAllObjects];
    }];
}

- (void)inDatabase:(void (^)(YYFMDatabase *db))block {

    YYFMDatabase *db = [self db];

    block(db);

    [self pushDatabaseBackInPool:db];
}

- (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(YYFMDatabase *db, BOOL *rollback))block {

    BOOL shouldRollback = NO;

    YYFMDatabase *db = [self db];

    if (useDeferred) {
        [db beginDeferredTransaction];
    }
    else {
        [db beginTransaction];
    }

    block(db, &shouldRollback);

    if (shouldRollback) {
        [db rollback];
    }
    else {
        [db commit];
    }

    [self pushDatabaseBackInPool:db];
}

- (void)inDeferredTransaction:(void (^)(YYFMDatabase *db, BOOL *rollback))block {
    [self beginTransaction:YES withBlock:block];
}

- (void)inTransaction:(void (^)(YYFMDatabase *db, BOOL *rollback))block {
    [self beginTransaction:NO withBlock:block];
}
#if SQLITE_VERSION_NUMBER >= 3007000
- (NSError*)inSavePoint:(void (^)(YYFMDatabase *db, BOOL *rollback))block {

    static unsigned long savePointIdx = 0;

    NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++];

    BOOL shouldRollback = NO;

    YYFMDatabase *db = [self db];

    NSError *err = 0x00;

    if (![db startSavePointWithName:name error:&err]) {
        [self pushDatabaseBackInPool:db];
        return err;
    }

    block(db, &shouldRollback);

    if (shouldRollback) {
        [db rollbackToSavePointWithName:name error:&err];
    }
    else {
        [db releaseSavePointWithName:name error:&err];
    }

    [self pushDatabaseBackInPool:db];

    return err;
}
#endif

@end


text:
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.

using DotSpatial.Analysis;
using DotSpatial.Data;
using DotSpatial.Modeling.Forms;
using DotSpatial.Modeling.Forms.Parameters;

namespace DotSpatial.Tools
{
    /// <summary>
    /// This tool provides access to the random geometry functionality in DotSpatial.Analysis.RandomGeometry.
    /// DotSpatial tools are intended to be used through the DotSpatial toolbox or modeler.
    /// To perform buffer analysis through code, consider using DotSpatial.Analysis.RandomGeometry directly.
    /// </summary>
    public class RandomGeometryTool : Tool
    {
        #region Fields

        // Declare input and output parameter arrays
        private Parameter[] _inputParam;
        private Parameter[] _outputParam;

        #endregion

        #region  Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="RandomGeometryTool"/> class.
        /// Create a new instance of the RandomGeometry tool
        /// </summary>
        public RandomGeometryTool()
        {
            Name = TextStrings.RandomGeometry;
            Category = TextStrings.Analysis;
            Description = TextStrings.RandomGeometryDescription;
            ToolTip = TextStrings.RandomGeometryToolTip;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the input paramater array.
        /// Number of parameter and parameter types are defined during initialize.
        /// </summary>
        public override Parameter[] InputParameters => _inputParam;

        /// <summary>
        /// Gets the output paramater array.
        /// Number of parameter and parameter types are defined during initialize.
        /// </summary>
        public override Parameter[] OutputParameters => _outputParam;

        #endregion

        #region Methods

        /// <summary>
        /// Executes the random geometry tool, returning true when it has completed.
        /// </summary>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        /// <returns>True, if executed successfully.</returns>
        public override bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            // Get the needed input and output parameters
            IFeatureSet inputFeatures = _inputParam[0].Value as IFeatureSet;
            IFeatureSet outputFeatures = _outputParam[0].Value as IFeatureSet;
            IntParam intInput = _inputParam[1] as IntParam;

            int numPoints = 1;
            if (intInput != null)
            {
                numPoints = intInput.Value;
            }

            RandomGeometry.RandomPoints(inputFeatures, numPoints, outputFeatures, cancelProgressHandler);

            if (cancelProgressHandler.Cancel)
            {
                // Set output param to null so that ToolManager does not attempt to open file.
                _outputParam = null;
                return false;
            }

            if (outputFeatures == null) return false;

            outputFeatures.Save();
            return true;
        }

        /// <summary>
        /// Inititalize input and output arrays with parameter types and default values.
        /// </summary>
        public override void Initialize()
        {
            _inputParam = new Parameter[2];
            _inputParam[0] = new FeatureSetParam(TextStrings.InputFeatureSet);
            _inputParam[1] = new IntParam(TextStrings.RandomGeometryNumPoint, 10);
            _outputParam = new Parameter[2];
            _outputParam[0] = new FeatureSetParam(TextStrings.OutputFeatureSet);
            _outputParam[1] = new BooleanParam(TextStrings.OutputParameter_AddToMap, TextStrings.OutputParameter_AddToMap_CheckboxText, true);
        }

        #endregion
    }
}


text:
package org.willianzhao.omnitureanalysis.mapred.commons.misc.timezonehelper;

/**
 * Created by weilzhao on 9/28/14.
 */
public class ZipcodeGeo {

}


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.testutil;

import com.google.devtools.build.lib.util.Preconditions;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * A helper class to find all classes on the current classpath. This is used to automatically create
 * JUnit 3 and 4 test suites.
 */
final class Classpath {
  private static final String CLASS_EXTENSION = ".class";

  /**
   * Finds all classes that live in or below the given package.
   */
  static Set<Class<?>> findClasses(String packageName) {
    Set<Class<?>> result = new LinkedHashSet<>();
    String pathPrefix = (packageName + '.').replace('.', '/');
    for (String entryName : getClassPath()) {
      File classPathEntry = new File(entryName);
      if (classPathEntry.exists()) {
        try {
          Set<String> classNames;
          if (classPathEntry.isDirectory()) {
            classNames = findClassesInDirectory(classPathEntry, pathPrefix);
          } else {
            classNames = findClassesInJar(classPathEntry, pathPrefix);
          }
          for (String className : classNames) {
            Class<?> clazz = Class.forName(className);
            result.add(clazz);
          }
        } catch (IOException e) {
          throw new AssertionError("Can't read classpath entry "
              + entryName + ": " + e.getMessage());
        } catch (ClassNotFoundException e) {
          throw new AssertionError("Class not found even though it is on the classpath "
              + entryName + ": " + e.getMessage());
        }
      }
    }
    return result;
  }

  private static Set<String> findClassesInDirectory(File classPathEntry, String pathPrefix) {
    Set<String> result = new TreeSet<>();
    File directory = new File(classPathEntry, pathPrefix);
    innerFindClassesInDirectory(result, directory, pathPrefix);
    return result;
  }

  /**
   * Finds all classes and sub packages in the given directory that are below the given package and
   * add them to the respective sets.
   *
   * @param directory Directory to inspect
   * @param pathPrefix Prefix for the path to the classes that are requested
   *                   (ex: {@code com/google/foo/bar})
   */
  private static void innerFindClassesInDirectory(Set<String> classNames, File directory,
      String pathPrefix) {
    Preconditions.checkArgument(pathPrefix.endsWith("/"));
    if (directory.exists()) {
      for (File f : directory.listFiles()) {
        String name = f.getName();
        if (name.endsWith(CLASS_EXTENSION)) {
          String clzName = getClassName(pathPrefix + name);
          classNames.add(clzName);
        } else if (f.isDirectory()) {
          findClassesInDirectory(f, pathPrefix + name + "/");
        }
      }
    }
  }

  /**
   * Returns a set of all classes in the jar that start with the given prefix.
   */
  private static Set<String> findClassesInJar(File jarFile, String pathPrefix) throws IOException {
    Set<String> classNames = new TreeSet<>();
    try (ZipFile zipFile = new ZipFile(jarFile)) {
      Enumeration<? extends ZipEntry> entries = zipFile.entries();
      while (entries.hasMoreElements()) {
        String entryName = entries.nextElement().getName();
        if (entryName.startsWith(pathPrefix) && entryName.endsWith(CLASS_EXTENSION)) {
          classNames.add(getClassName(entryName));
        }
      }
    }
    return classNames;
  }

  /**
   * Given the absolute path of a class file, return the class name.
   */
  private static String getClassName(String className) {
    int classNameEnd = className.length() - CLASS_EXTENSION.length();
    return className.substring(0, classNameEnd).replace('/', '.');
  }

  private static void getClassPathsFromClasspathJar(File classpathJar, Set<String> classPaths)
      throws IOException {
    Manifest manifest = new JarFile(classpathJar).getManifest();
    Attributes attributes = manifest.getMainAttributes();
    for (String classPath : attributes.getValue("Class-Path").split(" ")) {
      try {
        classPaths.add(Paths.get(new URI(classPath)).toAbsolutePath().toString());
      } catch (URISyntaxException e) {
        throw new AssertionError(
            "Error parsing classpath uri " + classPath + ": " + e.getMessage());
      }
    }
  }

  /**
   * Gets the classpath from current classloader.
   */
  private static Set<String> getClassPath() {
    ClassLoader classloader = Classpath.class.getClassLoader();
    if (!(classloader instanceof URLClassLoader)) {
      throw new IllegalStateException("Unable to find classes to test, since Test Suite class is "
          + "loaded by an unsupported Classloader.");
    }

    Set<String> completeClassPaths = new TreeSet<>();
    URL[] urls = ((URLClassLoader) classloader).getURLs();
    for (URL url : urls) {
      String entryName = url.getPath();
      completeClassPaths.add(entryName);
      if (entryName.endsWith("-classpath.jar")) {
        // Bazel creates a classpath jar when the class path length exceeds command line length
        // limit, read the class path value from its manifest file if it's a classpath jar.
        File classPathEntry = new File(entryName);
        if (classPathEntry.exists() && classPathEntry.isFile()) {
          try {
            getClassPathsFromClasspathJar(classPathEntry, completeClassPaths);
          } catch (IOException e) {
            throw new AssertionError(
                "Can't read classpath entry " + entryName + ": " + e.getMessage());
          }
        }
      }
    }
    return completeClassPaths;
  }
}


text:
The following organizations or individuals have contributed to ScanCode:

- Chin-Yeung Li @chinyeungli
- Jillian Daguil @jdaguil
- Li Ha @linexb
- nexB Inc. @nexB
- Philippe Ombredanne @pombredanne
- Sebastian Roth @ened
- Steven Esser @majurg


text:
namespace TaskScheduler.Web.Extensions
{
    public static class StringExtensions
    {
        public static string RemoveFromEnd(this string text, string patternToRemove)
        {
            if (text.EndsWith(patternToRemove))
            {
                text = text.Substring(0, text.LastIndexOf(patternToRemove));
            }

            return text;
        }
    }
}


text:
package eu.hyvar.feature.expression.resource.hyexpression.ui;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.viewers.IStructuredSelection;

public class HyexpressionEObjectSelection implements IStructuredSelection {

	private final EObject selectedObject;

	public HyexpressionEObjectSelection(EObject selectedObject) {
		super();
		this.selectedObject = selectedObject;
	}

	public EObject getSelectedObject() {
		return selectedObject;
	}

	public boolean isEmpty() {
		return false;
	}

	public Object getFirstElement() {
		return selectedObject;
	}

	public Iterator<?> iterator() {
		return new Iterator<EObject>() {

			private boolean hasNext = true;

			public boolean hasNext() {
				return hasNext;
			}

			public EObject next(){
				hasNext = false;
				return selectedObject;
			}

			public void remove() {
			}
		};
	}

	public int size() {
		return 1;
	}

	public Object[] toArray() {
		return new Object[] {selectedObject};
	}

	public List<?> toList() {
		return Collections.singletonList(selectedObject);
	}

}


text:
<!DOCTYPE HTML>

<title>SSHConnection (xenon 3.1.0 API for Xenon developers)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Package nl.esciencecenter.xenon.adaptors.shared.ssh

Class SSHConnection

java.lang.Object

nl.esciencecenter.xenon.adaptors.shared.ssh.SSHConnection

All Implemented Interfaces:

java.lang.AutoCloseable

public class SSHConnection
extends java.lang.Object
implements java.lang.AutoCloseable

Field Summary

Fields

Modifier and Type
Field
Description

private org.apache.sshd.client.SshClient
client

private boolean
closed

private int
hops

private org.apache.sshd.client.session.ClientSession
session

private org.apache.sshd.client.session.ClientSession[]
sessions

private SSHUtil.Tunnel[]
tunnels

Constructor Summary

Constructors

Modifier
Constructor
Description

protected
SSHConnection(org.apache.sshd.client.SshClient client,
             int hops)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method
Description

protected void
addHop(int hop,
      org.apache.sshd.client.session.ClientSession session,
      SSHUtil.Tunnel tunnel)

void
close()

org.apache.sshd.client.subsystem.sftp.SftpClient
createSftpClient()

org.apache.sshd.client.session.ClientSession
getSession()

boolean
isClosed()

boolean
isOpen()

protected void
setSession(org.apache.sshd.client.session.ClientSession session)

Methods inherited from class java.lang.Object

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

Field Detail

client

private final org.apache.sshd.client.SshClient client

sessions

private final org.apache.sshd.client.session.ClientSession[] sessions

tunnels

private final SSHUtil.Tunnel[] tunnels

hops

private final int hops

closed

private boolean closed

session

private org.apache.sshd.client.session.ClientSession session

Constructor Detail

SSHConnection

protected SSHConnection(org.apache.sshd.client.SshClient client,
                        int hops)

Method Detail

addHop

protected void addHop(int hop,
                      org.apache.sshd.client.session.ClientSession session,
                      SSHUtil.Tunnel tunnel)

setSession

protected void setSession(org.apache.sshd.client.session.ClientSession session)

createSftpClient

public org.apache.sshd.client.subsystem.sftp.SftpClient createSftpClient()
                                                                  throws java.io.IOException

Throws:

java.io.IOException

getSession

public org.apache.sshd.client.session.ClientSession getSession()

isClosed

public boolean isClosed()

isOpen

public boolean isOpen()

close

public void close()

Specified by:

close in interface java.lang.AutoCloseable

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
#pragma once
#include <aws/elasticmapreduce/EMR_EXPORTS.h>
#include <aws/elasticmapreduce/EMRRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/elasticmapreduce/model/IdentityType.h>
#include <utility>

namespace Aws
{
namespace EMR
{
namespace Model
{

  /**
   */
  class AWS_EMR_API ListStudioSessionMappingsRequest : public EMRRequest
  {
  public:
    ListStudioSessionMappingsRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "ListStudioSessionMappings"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The ID of the Amazon EMR Studio.

     */
    inline const Aws::String& GetStudioId() const{ return m_studioId; }

    /**
     *
The ID of the Amazon EMR Studio.

     */
    inline bool StudioIdHasBeenSet() const { return m_studioIdHasBeenSet; }

    /**
     *
The ID of the Amazon EMR Studio.

     */
    inline void SetStudioId(const Aws::String& value) { m_studioIdHasBeenSet = true; m_studioId = value; }

    /**
     *
The ID of the Amazon EMR Studio.

     */
    inline void SetStudioId(Aws::String&& value) { m_studioIdHasBeenSet = true; m_studioId = std::move(value); }

    /**
     *
The ID of the Amazon EMR Studio.

     */
    inline void SetStudioId(const char* value) { m_studioIdHasBeenSet = true; m_studioId.assign(value); }

    /**
     *
The ID of the Amazon EMR Studio.

     */
    inline ListStudioSessionMappingsRequest& WithStudioId(const Aws::String& value) { SetStudioId(value); return *this;}

    /**
     *
The ID of the Amazon EMR Studio.

     */
    inline ListStudioSessionMappingsRequest& WithStudioId(Aws::String&& value) { SetStudioId(std::move(value)); return *this;}

    /**
     *
The ID of the Amazon EMR Studio.

     */
    inline ListStudioSessionMappingsRequest& WithStudioId(const char* value) { SetStudioId(value); return *this;}

    /**
     *
Specifies whether to return session mappings for users or groups. If not
     * specified, the results include session mapping details for both users and
     * groups.

     */
    inline const IdentityType& GetIdentityType() const{ return m_identityType; }

    /**
     *
Specifies whether to return session mappings for users or groups. If not
     * specified, the results include session mapping details for both users and
     * groups.

     */
    inline bool IdentityTypeHasBeenSet() const { return m_identityTypeHasBeenSet; }

    /**
     *
Specifies whether to return session mappings for users or groups. If not
     * specified, the results include session mapping details for both users and
     * groups.

     */
    inline void SetIdentityType(const IdentityType& value) { m_identityTypeHasBeenSet = true; m_identityType = value; }

    /**
     *
Specifies whether to return session mappings for users or groups. If not
     * specified, the results include session mapping details for both users and
     * groups.

     */
    inline void SetIdentityType(IdentityType&& value) { m_identityTypeHasBeenSet = true; m_identityType = std::move(value); }

    /**
     *
Specifies whether to return session mappings for users or groups. If not
     * specified, the results include session mapping details for both users and
     * groups.

     */
    inline ListStudioSessionMappingsRequest& WithIdentityType(const IdentityType& value) { SetIdentityType(value); return *this;}

    /**
     *
Specifies whether to return session mappings for users or groups. If not
     * specified, the results include session mapping details for both users and
     * groups.

     */
    inline ListStudioSessionMappingsRequest& WithIdentityType(IdentityType&& value) { SetIdentityType(std::move(value)); return *this;}

    /**
     *
The pagination token that indicates the set of results to retrieve.

     */
    inline const Aws::String& GetMarker() const{ return m_marker; }

    /**
     *
The pagination token that indicates the set of results to retrieve.

     */
    inline bool MarkerHasBeenSet() const { return m_markerHasBeenSet; }

    /**
     *
The pagination token that indicates the set of results to retrieve.

     */
    inline void SetMarker(const Aws::String& value) { m_markerHasBeenSet = true; m_marker = value; }

    /**
     *
The pagination token that indicates the set of results to retrieve.

     */
    inline void SetMarker(Aws::String&& value) { m_markerHasBeenSet = true; m_marker = std::move(value); }

    /**
     *
The pagination token that indicates the set of results to retrieve.

     */
    inline void SetMarker(const char* value) { m_markerHasBeenSet = true; m_marker.assign(value); }

    /**
     *
The pagination token that indicates the set of results to retrieve.

     */
    inline ListStudioSessionMappingsRequest& WithMarker(const Aws::String& value) { SetMarker(value); return *this;}

    /**
     *
The pagination token that indicates the set of results to retrieve.

     */
    inline ListStudioSessionMappingsRequest& WithMarker(Aws::String&& value) { SetMarker(std::move(value)); return *this;}

    /**
     *
The pagination token that indicates the set of results to retrieve.

     */
    inline ListStudioSessionMappingsRequest& WithMarker(const char* value) { SetMarker(value); return *this;}

  private:

    Aws::String m_studioId;
    bool m_studioIdHasBeenSet = false;

    IdentityType m_identityType;
    bool m_identityTypeHasBeenSet = false;

    Aws::String m_marker;
    bool m_markerHasBeenSet = false;
  };

} // namespace Model
} // namespace EMR
} // namespace Aws


text:
package com.twu.biblioteca;

import com.twu.biblioteca.Movie.Movie;
import com.twu.biblioteca.Movie.MovieRepository;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Created by lixueying on 16/2/22.
 */
public class MovieRepositoryTest {
    private MovieRepository movieRepository;
    private ArrayList<Movie> movies;

    @Before
    public void setUp(){
        movieRepository = new MovieRepository();
        movies = new ArrayList<Movie>();
    }

    @Test
    public void should_return_movies_size_3(){
        movies = movieRepository.movieShelf();
        assertThat(movies.size(), is(3));
    }

    @Test
    public void return_list_first_movie_name_123(){
        movies = movieRepository.movieShelf();
        assertThat(movies.get(0).getName(), is("123"));
    }
}