text:
"""Nearest Neighbor related algorithms"""

# Author: Fabian Pedregosa <fabian.pedregosa@inria.fr>
#         Alexandre Gramfort <alexandre.gramfort@inria.fr>
#         Sparseness support by Lars Buitinck <L.J.Buitinck@uva.nl>
#
# License: BSD, (C) INRIA, University of Amsterdam

import numpy as np
from scipy import linalg
from scipy.sparse import csr_matrix, issparse

from .base import BaseEstimator, ClassifierMixin, RegressorMixin
from .ball_tree import BallTree
from .metrics import euclidean_distances
from .utils import safe_asanyarray, atleast2d_or_csr

class NeighborsClassifier(BaseEstimator, ClassifierMixin):
    """Classifier implementing the k-nearest neighbors (k-NN) algorithm.

    Parameters
    ----------
    n_neighbors : int, optional
        Default number of neighbors. Defaults to 5.

    leaf_size : int, optional
        Leaf size passed to BallTree.  This can affect the speed of
        the nearest neighbors query.  The optimal value depends on the
        nature of the problem (see Discussion below).  Defaults to 20.

    algorithm : {'auto', 'ball_tree', 'brute'}, optional
        Algorithm used to compute the nearest neighbors. 'ball_tree' will
        construct a BallTree while 'brute'will perform brute-force
        search. 'auto' will guess the most appropriate based on current
        dataset.  See Discussion below for notes on choosing the optimal
        method. Fitting on sparse input will override the setting of this
        parameter.

    Examples
    --------
    >>> samples = [[0, 0, 2], [1, 0, 0]]
    >>> labels = [0, 1]
    >>> from sklearn.neighbors import NeighborsClassifier
    >>> neigh = NeighborsClassifier(n_neighbors=1)
    >>> neigh.fit(samples, labels)
    NeighborsClassifier(algorithm='auto', leaf_size=20, n_neighbors=1)
    >>> print neigh.predict([[0,0,0]])
    [1]

    See also
    --------
    BallTree

    Discussion
    ----------
    The optimal algorithm for a given dataset is a complicated choice, and
    depends on a number of factors:
    * number of samples N (n_samples).
      * 'brute' query time grows as O[N], while
      * 'ball_tree' query time grows as O[log(N)]
    * dimensionality D (n_features)
      Intrinsic dimensionality refers to the dimension of a manifold which
      is linearly or nonlinearly embedded within the parameter space
      * 'brute' query time grows as O[D], and is unaffected by the value of d.
      * 'ball_tree' query time may grow faster or slower than this, depending
        on the structure of the data.
    * data structure: intrinsic dimensionality of the data and/or sparsity
      of the data. Intrinsic dimensionality refers to the dimension d<=D
      of a manifold on which the data lies, which can be linearly or
      nonlinearly embedded in the parameter space. Sparsity refers to the
      degree to which the data fills the parameter space (this is to be
      distinguished from the concept as used in "sparse" matrices.  The data
      matrix may have no zero entries, but the structure can still be
      "sparse" in this sense).
      * 'brute' query time is unchanged by data structure.
      * 'ball_tree' query time is greatly influenced by data structure.
        In general, the more sparse the data is, and the smaller the intrinsic
        dimension d, the faster the ball_tree algorithm will be compared to
        a brute-force search.  For data which densely fills the parameter
      space, brute-force is generally a better choice.
    * number of neighbors k requested for a query point.
      * 'brute' query time is unaffected by the value of k
      * 'ball_tree' query time is slower for k>1, mainly due to the internal
        queueing and sorting that takes place during the query.
    * leaf_size of the ball_tree
      The leaf_size parameter controls the point at which the ball_tree
      algorithm switches from a tree-based query to a brute-force search.
      As the number of points 'n' in a node becomes smaller, the difference
      between a brute-force query time O[n] and a ball-tree query time
      O[log(n)] becomes less significant.  At some point, depending on all
      the above-mentioned factors, brute-force becomes more efficient.
      The parameter leaf_size sets this threshold.
    * number of query points.
      The ball_tree algorithm requires a one-time building phase.  For very
      few queries, the time to build the tree may overwhelm any gain during
      the query time.

    Currently, the algorithm='auto' option chooses between 'brute' and
    'ball_tree' using an unsophisticated rubric.  In practice, it is
    suggested that the user experiment with different choices of
    `algorithm` and `leaf_size` to determine the optimal configuration.

    References
    ----------
    http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm
    """

    def __init__(self, n_neighbors=5, algorithm='auto', leaf_size=20):
        self.n_neighbors = n_neighbors
        self.leaf_size = leaf_size
        self.algorithm = algorithm

    def fit(self, X, y):
        """Fit the model using X, y as training data

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = [n_samples, n_features]
            Training data.

        y : {array-like, sparse matrix}, shape = [n_samples]
            Target values, array of integer values.

        """
        X = safe_asanyarray(X)
        if y is None:
            raise ValueError("y must not be None")
        self._y = np.asanyarray(y)

        if issparse(X):
            self.ball_tree = None
            self._fit_X = X.tocsr()
        elif self.algorithm == 'ball_tree' or \
           (self.algorithm == 'auto' and X.shape[1] < 20):
            self.ball_tree = BallTree(X, self.leaf_size)
        else:
            self.ball_tree = None
            self._fit_X = X
        return self

    def kneighbors(self, X, n_neighbors=None, return_distance=True):
        """Finds the K-neighbors of a point.

        Returns distance

        Parameters
        ----------
        point : array-like
            The new point.

        n_neighbors : int
            Number of neighbors to get (default is the value
            passed to the constructor).

        return_distance : boolean, optional. Defaults to True.
            If False, distances will not be returned

        Returns
        -------
        dist : array
            Array representing the lengths to point, only present if
            return_distance=True

        ind : array
            Indices of the nearest points in the population matrix.

        Examples
        --------
        In the following example, we construnct a NeighborsClassifier
        class from an array representing our data set and ask who's
        the closest point to [1,1,1]

        >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]]
        >>> labels = [0, 0, 1]
        >>> from sklearn.neighbors import NeighborsClassifier
        >>> neigh = NeighborsClassifier(n_neighbors=1)
        >>> neigh.fit(samples, labels)
        NeighborsClassifier(algorithm='auto', leaf_size=20, n_neighbors=1)
        >>> print neigh.kneighbors([1., 1., 1.]) # doctest: +ELLIPSIS
        (array([[ 0.5]]), array([[2]]...))

        As you can see, it returns [[0.5]], and [[2]], which means that the
        element is at distance 0.5 and is the third element of samples
        (indexes start at 0). You can also query for multiple points:

        >>> X = [[0., 1., 0.], [1., 0., 1.]]
        >>> neigh.kneighbors(X, return_distance=False) # doctest: +ELLIPSIS
        array([[1],
               [2]]...)

        """
        X = atleast2d_or_csr(X)
        if n_neighbors is None:
            n_neighbors = self.n_neighbors
        if self.ball_tree is None:
            dist = euclidean_distances(X, self._fit_X, squared=True)
            # XXX: should be implemented with a partial sort
            neigh_ind = dist.argsort(axis=1)[:, :n_neighbors]
            if not return_distance:
                return neigh_ind
            else:
                return dist.T[neigh_ind], neigh_ind
        else:
            return self.ball_tree.query(X, n_neighbors,
                                        return_distance=return_distance)

    def predict(self, X):
        """Predict the class labels for the provided data

        Parameters
        ----------
        X: array
            A 2-D array representing the test point.

        n_neighbors : int
            Number of neighbors to get (default is the value
            passed to the constructor).

        Returns
        -------
        labels: array
            List of class labels (one for each data sample).
        """
        X = atleast2d_or_csr(X)

        # get neighbors
        neigh_ind = self.kneighbors(X, return_distance=False)

        # compute the most popular label
        pred_labels = self._y[neigh_ind]
        from scipy import stats
        mode, _ = stats.mode(pred_labels, axis=1)
        return mode.flatten().astype(np.int)

###############################################################################
# NeighborsRegressor class for regression problems

class NeighborsRegressor(NeighborsClassifier, RegressorMixin):
    """Regression based on k-Nearest Neighbor Algorithm

    The target is predicted by local interpolation of the targets
    associated of the k-Nearest Neighbors in the training set.

    Different modes for estimating the result can be set via parameter
    mode. 'barycenter' will apply the weights that best reconstruct
    the point from its neighbors while 'mean' will apply constant
    weights to each point.

    Parameters
    ----------
    n_neighbors : int, optional
        Default number of neighbors. Defaults to 5.

    leaf_size : int, optional
        Leaf size passed to BallTree.  This can affect the speed of
        the nearest neighbors query.  The optimal value depends on the
        nature of the problem.  Defaults to 20.

    mode : {'mean', 'barycenter'}, optional
        Weights to apply to labels.

    algorithm : {'auto', 'ball_tree', 'brute'}, optional
        Algorithm used to compute the nearest neighbors. 'ball_tree' will
        construct a BallTree, while 'brute' will perform brute-force
        search. 'auto' will guess the most appropriate based on current
        dataset.

    Examples
    --------
    >>> X = [[0], [1], [2], [3]]
    >>> y = [0, 0, 1, 1]
    >>> from sklearn.neighbors import NeighborsRegressor
    >>> neigh = NeighborsRegressor(n_neighbors=2)
    >>> neigh.fit(X, y)
    NeighborsRegressor(algorithm='auto', leaf_size=20, mode='mean', n_neighbors=2)
    >>> print neigh.predict([[1.5]])
    [ 0.5]

    Notes
    -----
    See Discussion in NeighborsClassifier docstring regarding the optimal
    choice of algorithm and leaf_size.
    http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm
    """

    def __init__(self, n_neighbors=5, mode='mean', algorithm='auto',
                 leaf_size=20):
        self.n_neighbors = n_neighbors
        self.leaf_size = leaf_size
        self.mode = mode
        self.algorithm = algorithm

    def predict(self, X):
        """Predict the target for the provided data

        Parameters
        ----------
        X : array
            A 2-D array representing the test data.

        n_neighbors : int, optional
            Number of neighbors to get (default is the value
            passed to the constructor).

        Returns
        -------
        y: array
            List of target values (one for each data sample).
        """
        X = atleast2d_or_csr(X)

        # compute nearest neighbors
        neigh_ind = self.kneighbors(X, return_distance=False)
        if self.ball_tree is None:
            neigh = self._fit_X[neigh_ind]
        else:
            neigh = self.ball_tree.data[neigh_ind]

        # compute interpolation on y
        if self.mode == 'barycenter':
            W = barycenter_weights(X, neigh)
            return (W * self._y[neigh_ind]).sum(axis=1)

        elif self.mode == 'mean':
            return np.mean(self._y[neigh_ind], axis=1)

        else:
            raise ValueError(
                'Unsupported mode, must be one of "barycenter" or '
                '"mean" but got %s instead' % self.mode)

###############################################################################
# Utils k-NN based Functions

def barycenter_weights(X, Z, reg=1e-3):
    """Compute barycenter weights of X from Y along the first axis

    We estimate the weights to assign to each point in Y[i] to recover
    the point X[i]. The barycenter weights sum to 1.

    Parameters
    ----------
    X : array-like, shape (n_samples, n_dim)

    Z : array-like, shape (n_samples, n_neighbors, n_dim)

    reg: float, optional
        amount of regularization to add for the problem to be
        well-posed in the case of n_neighbors > n_dim

    Returns
    -------
    B : array-like, shape (n_samples, n_neighbors)

    Notes
    -----
    See developers note for more information.
    """
    X, Z = map(np.asanyarray, (X, Z))
    n_samples, n_neighbors = X.shape[0], Z.shape[1]
    if X.dtype.kind == 'i':
        X = X.astype(np.float)
    if Z.dtype.kind == 'i':
        Z = Z.astype(np.float)
    B = np.empty((n_samples, n_neighbors), dtype=X.dtype)
    v = np.ones(n_neighbors, dtype=X.dtype)

    # this might raise a LinalgError if G is singular and has trace
    # zero
    for i, A in enumerate(Z.transpose(0, 2, 1)):
        C = A.T - X[i]  # broadcasting
        G = np.dot(C, C.T)
        trace = np.trace(G)
        if trace > 0:
            R = reg * trace
        else:
            R = reg
        G.flat[::Z.shape[1] + 1] += R
        w = linalg.solve(G, v, sym_pos=True)
        B[i, :] = w / np.sum(w)
    return B

def kneighbors_graph(X, n_neighbors, mode='connectivity', reg=1e-3):
    """Computes the (weighted) graph of k-Neighbors for points in X

    Parameters
    ----------
    X : array-like or BallTree, shape = [n_samples, n_features]
        Sample data, in the form of a numpy array or a precomputed
        :class:`BallTree`.

    n_neighbors : int
        Number of neighbors for each sample.

    mode : {'connectivity', 'distance', 'barycenter'}, optional
        Type of returned matrix: 'connectivity' will return the
        connectivity matrix with ones and zeros, in 'distance' the
        edges are Euclidean distance between points. In 'barycenter'
        they are the weights that best reconstruncts the point from
        its nearest neighbors.

    reg : float, optional
        Amount of regularization when solving the least-squares
        problem. Only relevant if mode='barycenter'. If None, use the
        default.

    Returns
    -------
    A : sparse matrix in CSR format, shape = [n_samples, n_samples]
        A[i, j] is assigned the weight of edge that connects i to j.

    Examples
    --------
    >>> X = [[0], [3], [1]]
    >>> from sklearn.neighbors import kneighbors_graph
    >>> A = kneighbors_graph(X, 2)
    >>> A.todense()
    matrix([[ 1.,  0.,  1.],
            [ 0.,  1.,  1.],
            [ 1.,  0.,  1.]])

    See also
    --------
    radius_neighbors_graph
    """
    if isinstance(X, BallTree):
        ball_tree = X
        X = ball_tree.data
    else:
        X = np.asanyarray(X)
        ball_tree = BallTree(X)

    n_samples = X.shape[0]
    n_nonzero = n_neighbors * n_samples
    A_indptr = np.arange(0, n_nonzero + 1, n_neighbors)

    # construct CSR matrix representation of the k-NN graph
    if mode == 'connectivity':
        A_data = np.ones((n_samples, n_neighbors))
        A_ind = ball_tree.query(
            X, k=n_neighbors, return_distance=False)

    elif mode == 'distance':
        data, ind = ball_tree.query(X, k=n_neighbors + 1)
        A_data, A_ind = data[:, 1:], ind[:, 1:]

    elif mode == 'barycenter':
        ind = ball_tree.query(
            X, k=n_neighbors + 1, return_distance=False)
        A_ind = ind[:, 1:]
        A_data = barycenter_weights(X, X[A_ind], reg=reg)

    else:
        raise ValueError(
            'Unsupported mode, must be one of "connectivity", '
            '"distance" or "barycenter" but got %s instead' % mode)

    return csr_matrix((A_data.ravel(), A_ind.ravel(), A_indptr),
                      shape=(n_samples, n_samples))

def radius_neighbors_graph(X, radius, mode='connectivity'):
    """Computes the (weighted) graph of Neighbors for points in X

    Neighborhoods are restricted the points at a distance lower than
    radius.

    Parameters
    ----------
    X : array-like or BallTree, shape = [n_samples, n_features]
        Sample data, in the form of a numpy array or a precomputed
        :class:`BallTree`.

    radius : float
        Radius of neighborhoods.

    mode : {'connectivity', 'distance'}, optional
        Type of returned matrix: 'connectivity' will return the
        connectivity matrix with ones and zeros, in 'distance' the
        edges are Euclidean distance between points.

    Returns
    -------
    A : sparse matrix in CSR format, shape = [n_samples, n_samples]
        A[i, j] is assigned the weight of edge that connects i to j.

    Examples
    --------
    >>> X = [[0], [3], [1]]
    >>> from sklearn.neighbors import radius_neighbors_graph
    >>> A = radius_neighbors_graph(X, 1.5)
    >>> A.todense()
    matrix([[ 1.,  0.,  1.],
            [ 0.,  1.,  0.],
            [ 1.,  0.,  1.]])

    See also
    --------
    kneighbors_graph
    """
    if isinstance(X, BallTree):
        ball_tree = X
        X = ball_tree.data
    else:
        X = np.asanyarray(X)
        ball_tree = BallTree(X)

    n_samples = X.shape[0]

    # construct CSR matrix representation of the NN graph
    if mode == 'connectivity':
        A_ind = ball_tree.query_radius(X, radius, return_distance=False)
        A_data = None
    elif mode == 'distance':
        A_ind, dist = ball_tree.query_radius(X, radius, return_distance=True)
        A_data = np.concatenate(list(dist))
    else:
        raise ValueError(
            'Unsupported mode, must be one of "connectivity", '
            'or "distance" but got %s instead' % mode)

    n_neighbors = np.array([len(a) for a in A_ind])
    n_nonzero = np.sum(n_neighbors)
    A_ind = np.concatenate(list(A_ind))
    A_indptr = np.concatenate((np.zeros(1, dtype=int), np.cumsum(n_neighbors)))

    if A_data is None:
        A_data = np.ones(n_nonzero)

    return csr_matrix((A_data, A_ind, A_indptr), shape=(n_samples, n_samples))


text:
// -----------------------------------------------------------------------
// <copyright file="InputService.cs" company="Kyle Kestell">
// <para>Copyright (c) 2012 Kyle Kestell</para>
// <para>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:</para>
// <para>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.</para>
// <para>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</para>
// </copyright>
// -----------------------------------------------------------------------

namespace Erebus
{
    using System;
    using System.Collections.Generic;
    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Input;

    public class InputService : GameComponent
    {
        private KeyboardState oldKeyboardState;
        private MouseState oldMouseState;
        private List<Keys> pressed;
        private List<Keys> released;
        private List<Keys> repeated;
        private Vector2 mouseDelta;

        public InputService(Game game)
            : base(game)
        {
            this.pressed = new List<Keys>();
            this.released = new List<Keys>();
            this.repeated = new List<Keys>();
            this.mouseDelta = new Vector2();
        }

        public List<Keys> Pressed
        {
            get { return this.pressed; }
        }

        public List<Keys> Released
        {
            get { return this.released; }
        }

        public List<Keys> Repeated
        {
            get { return this.repeated; }
        }

        public Vector2 MouseDelta
        {
            get { return this.mouseDelta; }
        }

        public void CenterMouse()
        {
            Mouse.SetPosition(Config.WindowWidth / 2, Config.WindowHeight / 2);
        }

        public override void Update(GameTime gameTime)
        {
            var keyboardState = Keyboard.GetState();
            var mouseState = Mouse.GetState();

            this.pressed.Clear();
            this.released.Clear();
            this.repeated.Clear();

            foreach (var key in keyboardState.GetPressedKeys())
            {
                if (this.oldKeyboardState.IsKeyDown(key))
                {
                    this.repeated.Add(key);
                } else
                {
                    this.pressed.Add(key);
                }
            }

            foreach (var key in this.oldKeyboardState.GetPressedKeys())
            {
                if (!keyboardState.IsKeyDown(key))
                {
                    this.released.Add(key);
                }
            }

            this.mouseDelta.X = mouseState.X - (Config.WindowWidth / 2);
            this.mouseDelta.Y = mouseState.Y - (Config.WindowHeight / 2);

            this.oldKeyboardState = keyboardState;
            this.oldMouseState = mouseState;

            // Only center the mouse when the window is active.
            // Allows the user to alt+tab away from the game
            if (this.Game.IsActive)
            {
                this.CenterMouse();
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.eldoraludo.tripexpense;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.eldoraludo.tripexpense.database.DatabaseHandler;
import com.eldoraludo.tripexpense.entite.Depense;
import com.eldoraludo.tripexpense.entite.Participant;
import com.eldoraludo.tripexpense.entite.TypeDeDepense;
import com.eldoraludo.tripexpense.util.DateHelper;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;

import org.joda.time.DateTime;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class AjouterDepenseActivity extends Activity {
    private Integer idDepense;
    private Integer idProjet;
    private Button ajouterOuModifierDepenseButton;
    private EditText nomDepenseText;
    private EditText montantText;
    private TextView tvDisplayDateDebutDepense;
    private Button btnChangeDateDebutDepense;
    private TextView tvDisplayDateFinDepense;
    private Button btnChangeDateFinDepense;
    private Spinner listeParticipant;

    private int anneeDebutDepense;
    private int moisDebutDepense;
    private int jourDebutDepense;
    private int anneeFinDepense;
    private int moisFinDepense;
    private int jourFinDepense;
    private DatabaseHandler databaseHandler;
    static final int DATE_DIALOG_ID_DEBUT_DEPENSE = 999;
    static final int DATE_DIALOG_ID_FIN_DEPENSE = 1999;
    private static final int ERROR_DIALOG_DATE_INCOHERENTE = 45464;

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

        Intent intent = getIntent();
        idDepense = intent.getIntExtra(GestionDepenseActivity.ID_DEPENSE, -1);
        idProjet = intent.getIntExtra(GestionProjetActivity.ID_PROJET_COURANT,
                -1);
        Preconditions.checkState(!idProjet.equals(-1),
                "L'id du projet doit être définit");
        databaseHandler = new DatabaseHandler(this);
        nomDepenseText = (EditText) findViewById(R.id.nomDepenseText);
        montantText = (EditText) findViewById(R.id.montantText);
        ajouterOuModifierDepenseButton = (Button) findViewById(R.id.ajouterOuModifierDepenseButton);

        listeParticipant = (Spinner) findViewById(R.id.listeParticipant);
        List<Participant> list = new ArrayList<Participant>();
        try {
            list = databaseHandler.getAllParticipant(idProjet);
        } catch (Exception e) {
            Toast.makeText(this, "Une erreur est arrivée: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        ArrayAdapter<Participant> dataAdapter = new ArrayAdapter<Participant>(
                this, android.R.layout.simple_spinner_item, list);
        dataAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        listeParticipant.setAdapter(dataAdapter);

        Depense depense = null;
        if (idDepense != -1) {
            try {
                depense = databaseHandler.trouverLaDepense(idDepense);
                Preconditions.checkNotNull(depense,
                        "La dépense n'a pas été trouvée");
                nomDepenseText.setText(depense.getNomDepense());
                montantText.setText(String.valueOf(depense.getMontant()));
                anneeDebutDepense = depense.getDateDebut().getYear();
                moisDebutDepense = depense.getDateDebut().getMonthOfYear();
                jourDebutDepense = depense.getDateDebut().getDayOfMonth();

                anneeFinDepense = depense.getDateFin().getYear();
                moisFinDepense = depense.getDateFin().getMonthOfYear();
                jourFinDepense = depense.getDateFin().getDayOfMonth();
                Participant participant = databaseHandler
                        .trouverLeParticipant(depense.getParticipantId());
                int pos = list.indexOf(participant);
                listeParticipant.setSelection(pos);
                ajouterOuModifierDepenseButton.setText("Modifier");
            } catch (Exception e) {
                Toast.makeText(this, "Une erreur est arrivée: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
        if (depense == null) {
            final Calendar c = Calendar.getInstance();
            anneeDebutDepense = c.get(Calendar.YEAR);
            moisDebutDepense = c.get(Calendar.MONTH) + 1;
            jourDebutDepense = c.get(Calendar.DAY_OF_MONTH);
            anneeFinDepense = c.get(Calendar.YEAR);
            moisFinDepense = c.get(Calendar.MONTH) + 1;
            jourFinDepense = c.get(Calendar.DAY_OF_MONTH) + 1;
        }

        setCurrentDateOnView();
        addListenerOnButton();

    }

    public void onClick(View view) {
        try {
            // If add button was clicked
            if (ajouterOuModifierDepenseButton.isPressed()) {
                // Get entered text
                String nomDepenseTextValue = nomDepenseText.getText().toString();
                if (nomDepenseTextValue == null || nomDepenseTextValue.isEmpty()) {
                    Toast.makeText(this, "Il faut préciser un nom de dépense", Toast.LENGTH_SHORT).show();
                    return;
                }
                String montantDepenseTextValue = montantText.getText().toString();
                if (montantDepenseTextValue == null || montantDepenseTextValue.isEmpty()) {
                    Toast.makeText(this, "Il faut préciser un montant", Toast.LENGTH_SHORT).show();
                    return;
                }
                // verification des dates
                // date de debut avec date de fin
                DateTime dateDebut = DateHelper.convertirIntsToDate(
                        jourDebutDepense, moisDebutDepense, anneeDebutDepense);
                DateTime dateFin = DateHelper.convertirIntsToDate(jourFinDepense,
                        moisFinDepense, anneeFinDepense);
                if (dateDebut.isAfter(dateFin)) {
                    // showDialog(ERROR_DIALOG_DATE_INCOHERENTE);
                    Toast.makeText(this, "La date de début doit être avant la date de fin", Toast.LENGTH_SHORT).show();
                    return;
                }
                // ecart date contient participant
                if (verificationPresenceParticipant(dateDebut, dateFin)) {
                    return;
                }

                nomDepenseText.setText("");
                montantText.setText("");
                Participant participantSelectionne = (Participant) listeParticipant
                        .getSelectedItem();
                this.ajouterDepense(nomDepenseTextValue, montantDepenseTextValue,
                        participantSelectionne.getId(), dateDebut, dateFin);
                Intent i = new Intent();
                setResult(RESULT_OK, i);
                super.finish();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Une erreur est arrivée: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private boolean verificationPresenceParticipant(DateTime dateDebut, DateTime dateFin) {
        List<Participant> allParticipant = databaseHandler
                .getAllParticipant(idProjet);
        DateTime dateCourante = dateDebut;
        while (!dateCourante.isAfter(dateFin)) {
            final DateTime finalDateCourante = dateCourante;
            if (!Iterables.any(allParticipant, new Predicate<Participant>() {
                @Override
                public boolean apply(Participant participant) {
                    return !participant.getDateArrive().isAfter(finalDateCourante) && !finalDateCourante.isAfter(participant.getDateDepart());
                }
            })) {
                Toast.makeText(this, "Aucun participant n'a été trouvé pour la date " + finalDateCourante.toString("dd/MM/YYYY"), Toast.LENGTH_SHORT).show();
                return true;
            }
            dateCourante = dateCourante.plusDays(1);
        }
        return false;
    }

    private void ajouterDepense(String nomDepenseTextValue,
                                String montantDepenseTextValue, Integer participantId,
                                DateTime dateDebut, DateTime dateFin) {
        // Add text to the database
        databaseHandler.ajouterOuModifierDepense(Depense.newBuilder()
                .withId(idDepense == -1 ? null : idDepense)
                .withNomDepense(nomDepenseTextValue)
                .withMontant(Double.valueOf(montantDepenseTextValue))
                .withDateDebut(dateDebut).withDateFin(dateFin)
                .withParticipantId(participantId)
                .withTypeDeDepense(TypeDeDepense.COURSE).withProjetId(idProjet)
                .build());
    }

    // display current date
    public void setCurrentDateOnView() {
        tvDisplayDateDebutDepense = (TextView) findViewById(R.id.afficherDateDebutDepense);
        tvDisplayDateFinDepense = (TextView) findViewById(R.id.afficherDateFinDepense);
        // set current date into textview
        tvDisplayDateDebutDepense.setText(new StringBuilder().append("   ")
                // Month is 0 based, just add 1
                .append(jourDebutDepense).append("/").append(moisDebutDepense)
                .append("/").append(anneeDebutDepense).append(" "));
        tvDisplayDateFinDepense.setText(new StringBuilder().append("   ")
                // Month is 0 based, just add 1
                .append(jourFinDepense).append("/").append(moisFinDepense)
                .append("/").append(anneeFinDepense).append(" "));
    }

    public void addListenerOnButton() {

        btnChangeDateDebutDepense = (Button) findViewById(R.id.btnChangeDateDebutDepense);

        btnChangeDateDebutDepense.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                showDialog(DATE_DIALOG_ID_DEBUT_DEPENSE);

            }

        });
        btnChangeDateFinDepense = (Button) findViewById(R.id.btnChangeDateFinDepense);

        btnChangeDateFinDepense.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                showDialog(DATE_DIALOG_ID_FIN_DEPENSE);

            }

        });

    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG_ID_DEBUT_DEPENSE:
                // set date picker as current date
                return new DatePickerDialog(this, datePickerListenerDebutDepense,
                        anneeDebutDepense, moisDebutDepense - 1, jourDebutDepense);
            case DATE_DIALOG_ID_FIN_DEPENSE:
                // set date picker as current date
                return new DatePickerDialog(this, datePickerListenerFinDepense,
                        anneeFinDepense, moisFinDepense - 1, jourFinDepense);
        /*    case ERROR_DIALOG_DATE_INCOHERENTE:
                // AlertDialog create = getDialogError("La date de début doit être avant la date de fin");
                return null;*/
        }
        return null;
    }

    /*private AlertDialog getDialogError(String errorMessage) {
        AlertDialog.Builder builder = new AlertDialog.Builder(
                AjouterDepenseActivity.this);
        builder.setTitle("Une erreur est arrivé");
        builder.setIcon(R.drawable.ic_action_error);
        // Add the buttons
        builder.setNeutralButton(errorMessage,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });

        AlertDialog create = builder.create();
        return create;
    }*/

    private DatePickerDialog.OnDateSetListener datePickerListenerDebutDepense = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,
                              int selectedMonth, int selectedDay) {
            anneeDebutDepense = selectedYear;
            moisDebutDepense = selectedMonth + 1;
            jourDebutDepense = selectedDay;

            // set selected date into textview
            tvDisplayDateDebutDepense.setText(new StringBuilder().append("   ")
                    .append(jourDebutDepense).append("/")
                    .append(moisDebutDepense).append("/")
                    .append(anneeDebutDepense).append(" "));

        }
    };

    private DatePickerDialog.OnDateSetListener datePickerListenerFinDepense = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,
                              int selectedMonth, int selectedDay) {
            anneeFinDepense = selectedYear;
            moisFinDepense = selectedMonth + 1;
            jourFinDepense = selectedDay;

            // set selected date into textview
            tvDisplayDateFinDepense.setText(new StringBuilder().append("   ")
                    .append(jourFinDepense).append("/").append(moisFinDepense)
                    .append("/").append(anneeFinDepense).append(" "));

        }
    };

}


text:
@interface PTLoginViewController : PTBaseLoginViewController

@end


text:
jME3 Application Display Settings

Every class that extends jme3.app.SimpleApplication has properties that can be configured by customizing a com.jme3.system.AppSettings object. Configure the settings before you call app.start() on the application object. If you change display settings during runtime, call app.restart() to make them take effect.

Note: Other runtime settings are covered in SimpleApplication.

Code Sample

public static void main(String[] args) {
  AppSettings settings = new AppSettings(true);
  settings.setResolution(640,480);
  ... // other properties see below

  MyGame app = new MyGame(); // or Main or whatever you called your SimpleApplication
  app.setSettings(settings);
  app.start();
}

Set the boolean in the AppSettings contructor to true if you want to keep the default settings for everything that you do not specify. Set this parameter to false if you want to change some of the settings, but otherwise want the application to load user settings from previous launches.

Use app.setShowSettings(true); to present the user with a splashscreen and display settings dialog when starting the game, or app.setShowSettings(false); to hide the custom splashscreen. Set this boolean before calling app.start() on the SimpleApplication.

Properties

		Settings Property (Video)	Description	Default

		setRenderer(AppSettings.LWJGL_OPENGL2)

setRenderer(AppSettings.LWJGL_OPENGL3)	Switch Video Renderer	OpenGL 2

		setBitsPerPixel(8)	Set color depth.

1 = black and white, 2 bit = gray,

4 = 16 colors, 8 = 256 colors, 24 or 32 = "truecolor".	24

		setFrequency(60)	The screen frequency (refresh rate of the graphics card), usually 60 or 75 fps.	60 fps

		setFramerate(60)	How often per second the engine should try to refresh the frame. For the release, usually 60 fps. Can be lower (59-30) for FX-intensive games. No use setting it to a higher value than the screen frequency. If the framerate goes below 30 fps, viewers start to notice choppiness or flickering.	-1 (auto)

		setFullscreen(true)	Set this to true to make the game window fill the whole screen; you need to provide a key that calls app.stop() to exit the fullscreen view gracefully (default: escape).

Set this to false to play the game in a normal window of its own.	False (windowed)

		setHeight(480), setWidth(640)

setResolution(640,480)	Two equivalent ways of setting the display resolution.	640x480 pixels

		setSamples(4)	Set multisampling to 0 to switch antialiasing off (harder edges, faster.)

Set multisampling to 2 or 4 to activate antialising (softer edges, may be slower.)

Depending on your graphic card, you may be able to set multisampling to higher values such as 8, 16, or 32 samples.	0

		setVSync(true)	Set vertical syncing to true to time the frame buffer to coincide with the refresh interval of the screen: Prevents page tearing, but slower; recommened for release.

Set to false to deactivate vertical syncing (faster, but possible page tearing artifacts); can be deactivated during development.	false

		Settings Property (Input)	Description	Default

		setUseInput(false)	Respond to user input by mouse and keyboard. Can be deactivated for use cases where you only display a 3D scene on the canvas without any interaction.	true

		setUseJoysticks(true)	Activate optional joystick support	false

		Settings Property (Audio)	Description	Default

		setAudioRenderer(AppSettings.LWJGL_OPENAL)

setAudioRenderer(AppSettings.LWJGL_JOAL)	Switch Audio Renderer	OpenAL

		setStereo3D(true)	Enable 3D stereo. This feature requires hardware support from the GPU driver. See <object classid="java:org.netbeans.modules.javahelp.BrowserDisplayer"><param name="content" value="http://en.wikipedia.org/wiki/Quad_buffering"><param name="text" value="Quad Buffering"><param name="textColor" value="blue"></object>.	false

		Settings Property (Branding)	Description	Default

		setTitle("My Game")	This string will be visible in the titlebar, unless the window is fullscreen.	"jMonkey Engine 3.0"

		setIcons(new BufferedImage[]{

ImageIO.read(new File("")), …});	This specifies the little application icon in the titlebar of the application. You should specify the icon in various sizes (256,128,32,16) to look good on each <acronym title="Operating System">OS</acronym>. Note: This is not the application icon on the desktop.	null

		setSettingsDialogImage("/path/to/splash.png")	A custom splashscreen image in the assets directory which is displayed when the settings dialog is shown.	"/com/jme3/app/Monkey.png"

Saving and Loading Settings

An AppSettings object also supports the following methods:

 Use settings.save("unique_key") to save your settings via standard java.io serialization.

 Use settings.load("unique_key") to load your settings.

 Use settings2.copyFrom(settings) to copy a settings object.

Usage:

Provide the unique name of your jME3 application as the String argument. For example com.foo.MyCoolGame3.

    try { settings.save("com.foo.MyCoolGame3"); }
    catch (BackingStoreException ex) { /** could not save settings */ }

 On Windows, the preferences are saved under the following registry key:

HKEY_CURRENT_USER\Software\JavaSoft\Prefs\com\foo\MyCoolGame3

 On Linux, the preferences are saved in an <acronym title="Extensible Markup Language">XML</acronym> file under:

$HOME/.java/.userPrefs/com/foo/MyCoolGame3

 On Mac <acronym title="Operating System">OS</acronym> X, the preferences are saved as <acronym title="Extensible Markup Language">XML</acronym> file under:

$HOME/Library/Preferences/com.foo.MyCoolGame3.plist

view online version


text:
#pragma once
#include "PimInternal.h"
#include "PimSprite.h"

namespace Pim {
	/**
	 @class 		ParticleSystem
	 @brief 		Particle emitting class.
	 @details 		A single particle system can only emit particles according
	 				to a single configuration. If you want advanced effects, you
	 				should use multiple ParticleSystems and add them to the same
	 				GameNode.

	 				Most attributes in the particle system has a default and a
	 				@e variance variable. The actual value of the particles will
	 				be in the range [base, base ± variance].

	 				The ParticleSystem class is a Sprite derivative, and the
	 				texture loaded by Sprite is used as the particle texture.

	 				A visual particle editor is a goal, but at the time not a
	 				priority.
	 */

	class ParticleSystem : public Sprite {
	protected:
		struct Particle;
		struct Vertex;

	public:
		enum PositionType {
			PART_RELATIVE,	// The particles will move WITH the system. Default.
			PART_ABSOLUTE	// The particles will move relatively to the point of
							// their emission.
		};

		PositionType 			positionType;
		int						maxParticles;
		float					emitRate;
		float					emitAngle;
		float					emitAngleVariance;
		float					speed;
		float					speedVariance;
		float					startSize;
		float					startSizeVariance;
		float					endSize;
		float					endSizeVariance;
		float					startRotation;
		float					startRotationVariance;
		float					endRotation;
		float					endRotationVariance;
		float 					lifetime;
		float 					lifetimeVariance;
		Color					startColor;
		Color					startColorVariance;
		Color					endColor;
		Color					endColorVariance;
		Vec2					startPosition;
		Vec2					startPositionVariance;
		Vec2					gravity;

		static float			RanBaseVar(float base, float variance, bool neg=true);
		static float			Interpolate(float start, float end, float fac);

								ParticleSystem(string texturePath);
								ParticleSystem();
								~ParticleSystem(void);
		virtual void			Update(float dt);
		virtual void			Draw();
		virtual void			BatchDraw();
		int						GetParticleCount();
		void					RemoveAllParticles();

	protected:
		/**
		 @struct 		Particle
		 @brief 		Particle used by ParticleSystem
		 @details 		Only used for storing the result of the particle simulation,
		 				the struct does nothing on it's own.
		 */
		struct Particle {
			Vec2 				spawnPos;	// Used with positionType ABSOLUTE
			Vec2				position;
			Vec2				velocity;
			float				startRotation;
			float				endRotation;
			float				rotation;
			Color				color;
			Color				startColor;
			Color				endColor;
			float				size;
			float				startSize;
			float				endSize;
			float				age;
			float				lifetime;

								Particle();
		};

		/**
		 @struct 		Vertex
		 @brief 		Describes how and where a particle will be drawn.
		 @todo			Rotation
		 */
		struct Vertex {
			Vec2				position;
			Vec2				texCoord;
			Color				color;
		};

		vector<Particle*>		particles;
		vector<Vertex>			vertices;
		float					timeSinceLastEmit;

		void					UpdateAllParticles(float dt);
		void					CreateVertexData();

		virtual void			InitiateParticle(Particle *particle);
		virtual void			UpdateParticle(Particle *particle, float dt);
	};
}


text:
[Simple Token][website-url] is the bridge between crypto-currencies and mainstream consumer apps. Learn more about the project in the [documentation][documentation-url].

This repo contains the source code for the smart contracts used for the token sale.

[website-url]: https://simpletoken.org/
[documentation-url]: https://simpletoken.org/documents/

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)


text:
Doricha is my personal Vim configurations and some plugins.

# Usage

## Installation and Requisites

### Windows Version:

1. BACKUP your `_vimrc` and `vimfiles` folder.

2. Clone this repository to vim home directory.

		$ git clone git@github.com:allotory/doricha.git vimfiles

	or using the following command to clone plugins directly and Ignore step 4:

		$ git clone --recursive git@github.com:allotory/doricha.git vimfiles

3. Config `_vimrc` file add:

		if(has('win32') || has('win64'))
			source $VIM/vimfiles/vundle_vimrc
			source $VIM/vimfiles/basic_vimrc
		else
			source ~/.vim/vundle_vimrc
			source ~/.vim/basic_vimrc
		endif

4. Update plugins.

		$ git submodule init
		$ git submodule update

### Linux Version:

1. BACKUP your `.vimrc` and `.vim` folder.

2. Clone this repository to vim home directory.

		$ git clone git@github.com:allotory/doricha.git ~/.vim

	or using the following command to clone plugins directly and Ignore step 4:

		$ git clone --recursive git@github.com:allotory/doricha.git ~/.vim

3. Other steps is the same as the windows version.

# Plugin list

1. [Vundle.vim][1] - Vundle is a Vim plugin manager.

2. [auto-pairs][2] - Insert or delete brackets, parens, quotes in pairs.

3. [molokai][3] - Molokai color scheme for Vim.

4. [nerdtree][4] - A tree explorer plugin for vim.

5. [syntastic][5] - Syntax checking hacks for vim.

6. [tagbar][6] - A class outline viewer for Vim.

7. [vim-airline][7] - Lean & mean status/tabline for vim.

# License

The MIT License.

# Contact

Enjoy it.

[1]: https://github.com/VundleVim/Vundle.vim
[2]: https://github.com/jiangmiao/auto-pairs
[3]: https://github.com/tomasr/molokai
[4]: https://github.com/scrooloose/nerdtree
[5]: https://github.com/scrooloose/syntastic
[6]: https://github.com/majutsushi/tagbar
[7]: https://github.com/vim-airline/vim-airline


text:
package retrofit2.adapter.rxjava;

import java.lang.reflect.Type;
import javax.annotation.Nullable;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Response;
import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Scheduler;

final class RxJavaCallAdapter<R> implements CallAdapter<R, Object> {
  private final Type responseType;
  private final @Nullable Scheduler scheduler;
  private final boolean isAsync;
  private final boolean isResult;
  private final boolean isBody;
  private final boolean isSingle;
  private final boolean isCompletable;

  RxJavaCallAdapter(Type responseType, @Nullable Scheduler scheduler, boolean isAsync,
      boolean isResult, boolean isBody, boolean isSingle, boolean isCompletable) {
    this.responseType = responseType;
    this.scheduler = scheduler;
    this.isAsync = isAsync;
    this.isResult = isResult;
    this.isBody = isBody;
    this.isSingle = isSingle;
    this.isCompletable = isCompletable;
  }

  @Override public Type responseType() {
    return responseType;
  }

  @Override public Object adapt(Call<R> call) {
    OnSubscribe<Response<R>> callFunc = isAsync
        ? new CallEnqueueOnSubscribe<>(call)
        : new CallExecuteOnSubscribe<>(call);

    OnSubscribe<?> func;
    if (isResult) {
      func = new ResultOnSubscribe<>(callFunc);
    } else if (isBody) {
      func = new BodyOnSubscribe<>(callFunc);
    } else {
      func = callFunc;
    }
    Observable<?> observable = Observable.create(func);

    if (scheduler != null) {
      observable = observable.subscribeOn(scheduler);
    }

    if (isSingle) {
      return observable.toSingle();
    }
    if (isCompletable) {
      return observable.toCompletable();
    }
    return observable;
  }
}


text:
"""
Copyright 2022 Google LLC

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

    https://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.
"""

"""
Document Status object in the ORM
"""
import os
from common.models import BaseModel
from fireo.fields import TextField, ListField, NumberField, BooleanField, DateTime

DATABASE_PREFIX = os.getenv("DATABASE_PREFIX", "")
PROJECT_ID = os.environ.get("PROJECT_ID", "")

class Document(BaseModel):
  """Documentstatus ORM class  """
  case_id = TextField()
  uid = TextField()
  url = TextField()
  document_type = TextField()
  document_class = TextField()
  context = TextField()
  system_status = ListField()
  hitl_status = ListField()
  active = TextField()
  upload_timestamp = DateTime(auto=True)
  entities = ListField()
  extraction_score = NumberField()
  validation_score = NumberField()
  matching_score = NumberField()
  auto_approval = TextField()
  is_autoapproved = TextField()
  is_hitl_classified = BooleanField()
  external_case_id = TextField()
  extraction_status = TextField()
  error_detail = TextField()

  class Meta:
    ignore_none_field = False
    collection_name = DATABASE_PREFIX + "document"

  @classmethod
  def find_by_uid(cls, uid):
    """Find the document  using  uid
    Args:
        uid (string):  UID
    Returns:
        Document: Document Object
    """
    return Document.collection.filter("uid", "==", uid).get()


text: pimcore.available_languages = <?php echo Zend_Json::encode($this->languages) ?>;


text:
namespace media {

typedef bool (*CodecIDValidatorFunction)(
    const std::string& codecs_id, const LogCB& log_cb);

struct CodecInfo {
  enum Type {
    UNKNOWN,
    AUDIO,
    VIDEO
  };

  // Update tools/metrics/histograms/histograms.xml if new values are added.
  enum HistogramTag {
    HISTOGRAM_UNKNOWN,
    HISTOGRAM_VP8,
    HISTOGRAM_VP9,
    HISTOGRAM_VORBIS,
    HISTOGRAM_H264,
    HISTOGRAM_MPEG2AAC,
    HISTOGRAM_MPEG4AAC,
    HISTOGRAM_EAC3,
    HISTOGRAM_MP3,
    HISTOGRAM_OPUS,
    HISTOGRAM_MAX  // Must be the last entry.
  };

  const char* pattern;
  Type type;
  CodecIDValidatorFunction validator;
  HistogramTag tag;
};

typedef StreamParser* (*ParserFactoryFunction)(
    const std::vector<std::string>& codecs,
    const LogCB& log_cb);

struct SupportedTypeInfo {
  const char* type;
  const ParserFactoryFunction factory_function;
  const CodecInfo** codecs;
};

static const CodecInfo kVP8CodecInfo = { "vp8", CodecInfo::VIDEO, NULL,
                                         CodecInfo::HISTOGRAM_VP8 };
static const CodecInfo kVP9CodecInfo = { "vp9", CodecInfo::VIDEO, NULL,
                                         CodecInfo::HISTOGRAM_VP9 };
static const CodecInfo kVorbisCodecInfo = { "vorbis", CodecInfo::AUDIO, NULL,
                                            CodecInfo::HISTOGRAM_VORBIS };
static const CodecInfo kOpusCodecInfo = { "opus", CodecInfo::AUDIO, NULL,
                                          CodecInfo::HISTOGRAM_OPUS };

static const CodecInfo* kVideoWebMCodecs[] = {
  &kVP8CodecInfo,
#if !defined(OS_ANDROID)
  // TODO(wonsik): crbug.com/285016 query Android platform for codec
  // capabilities.
  &kVP9CodecInfo,
#endif
  &kVorbisCodecInfo,
  &kOpusCodecInfo,
  NULL
};

static const CodecInfo* kAudioWebMCodecs[] = {
  &kVorbisCodecInfo,
  &kOpusCodecInfo,
  NULL
};

static StreamParser* BuildWebMParser(
    const std::vector<std::string>& codecs,
    const LogCB& log_cb) {
  return new WebMStreamParser();
}

#if defined(USE_PROPRIETARY_CODECS)
// AAC Object Type IDs that Chrome supports.
static const int kAACLCObjectType = 2;
static const int kAACSBRObjectType = 5;

static int GetMP4AudioObjectType(const std::string& codec_id,
                                 const LogCB& log_cb) {
  int audio_object_type;
  std::vector<std::string> tokens;
  if (Tokenize(codec_id, ".", &tokens) != 3 ||
      tokens[0] != "mp4a" || tokens[1] != "40" ||
      !base::HexStringToInt(tokens[2], &audio_object_type)) {
    MEDIA_LOG(log_cb) << "Malformed mimetype codec '" << codec_id << "'";
    return -1;
  }

  return audio_object_type;
}

bool ValidateMP4ACodecID(const std::string& codec_id, const LogCB& log_cb) {
  int audio_object_type = GetMP4AudioObjectType(codec_id, log_cb);
  if (audio_object_type == kAACLCObjectType ||
      audio_object_type == kAACSBRObjectType) {
    return true;
  }

  MEDIA_LOG(log_cb) << "Unsupported audio object type "
                    << "0x" << std::hex << audio_object_type
                    << " in codec '" << codec_id << "'";
  return false;
}

static const CodecInfo kH264CodecInfo = { "avc1.*", CodecInfo::VIDEO, NULL,
                                          CodecInfo::HISTOGRAM_H264 };
static const CodecInfo kMPEG4AACCodecInfo = { "mp4a.40.*", CodecInfo::AUDIO,
                                              &ValidateMP4ACodecID,
                                              CodecInfo::HISTOGRAM_MPEG4AAC };
static const CodecInfo kMPEG2AACLCCodecInfo = { "mp4a.67", CodecInfo::AUDIO,
                                                NULL,
                                                CodecInfo::HISTOGRAM_MPEG2AAC };

#if defined(ENABLE_EAC3_PLAYBACK)
static const CodecInfo kEAC3CodecInfo = { "mp4a.a6", CodecInfo::AUDIO, NULL,
                                          CodecInfo::HISTOGRAM_EAC3 };
#endif

static const CodecInfo* kVideoMP4Codecs[] = {
  &kH264CodecInfo,
  &kMPEG4AACCodecInfo,
  &kMPEG2AACLCCodecInfo,
  NULL
};

static const CodecInfo* kAudioMP4Codecs[] = {
  &kMPEG4AACCodecInfo,
  &kMPEG2AACLCCodecInfo,
#if defined(ENABLE_EAC3_PLAYBACK)
  &kEAC3CodecInfo,
#endif
  NULL
};

static StreamParser* BuildMP4Parser(
    const std::vector<std::string>& codecs, const LogCB& log_cb) {
  std::set<int> audio_object_types;

  bool has_sbr = false;
#if defined(ENABLE_EAC3_PLAYBACK)
  bool enable_eac3 = CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableEac3Playback);
#endif
  for (size_t i = 0; i < codecs.size(); ++i) {
    std::string codec_id = codecs[i];
    if (MatchPattern(codec_id, kMPEG2AACLCCodecInfo.pattern)) {
      audio_object_types.insert(mp4::kISO_13818_7_AAC_LC);
    } else if (MatchPattern(codec_id, kMPEG4AACCodecInfo.pattern)) {
      int audio_object_type = GetMP4AudioObjectType(codec_id, log_cb);
      DCHECK_GT(audio_object_type, 0);

      audio_object_types.insert(mp4::kISO_14496_3);

      if (audio_object_type == kAACSBRObjectType) {
        has_sbr = true;
        break;
      }
#if defined(ENABLE_EAC3_PLAYBACK)
    } else if (enable_eac3 && MatchPattern(codec_id, kEAC3CodecInfo.pattern)) {
      audio_object_types.insert(mp4::kEAC3);
#endif
    }
  }

  return new mp4::MP4StreamParser(audio_object_types, has_sbr);
}

static const CodecInfo kMP3CodecInfo = { NULL, CodecInfo::AUDIO, NULL,
                                         CodecInfo::HISTOGRAM_MP3 };

static const CodecInfo* kAudioMP3Codecs[] = {
  &kMP3CodecInfo,
  NULL
};

static StreamParser* BuildMP3Parser(
    const std::vector<std::string>& codecs, const LogCB& log_cb) {
  return new MP3StreamParser();
}

#if defined(ENABLE_MPEG2TS_STREAM_PARSER)
static const CodecInfo* kVideoMP2TCodecs[] = {
  &kH264CodecInfo,
  &kMPEG4AACCodecInfo,
  &kMPEG2AACLCCodecInfo,
  NULL
};

static StreamParser* BuildMP2TParser(
    const std::vector<std::string>& codecs, const media::LogCB& log_cb) {
  return new media::mp2t::Mp2tStreamParser();
}
#endif
#endif

static const SupportedTypeInfo kSupportedTypeInfo[] = {
  { "video/webm", &BuildWebMParser, kVideoWebMCodecs },
  { "audio/webm", &BuildWebMParser, kAudioWebMCodecs },
#if defined(USE_PROPRIETARY_CODECS)
  { "audio/mpeg", &BuildMP3Parser, kAudioMP3Codecs },
  { "video/mp4", &BuildMP4Parser, kVideoMP4Codecs },
  { "audio/mp4", &BuildMP4Parser, kAudioMP4Codecs },
#if defined(ENABLE_MPEG2TS_STREAM_PARSER)
  { "video/mp2t", &BuildMP2TParser, kVideoMP2TCodecs },
#endif
#endif
};

// Verify that |codec_info| is supported on this platform.
//
// Returns true if |codec_info| is a valid audio/video codec and is allowed.
// |audio_codecs| has |codec_info|.tag added to its list if |codec_info| is an
// audio codec. |audio_codecs| may be NULL, in which case it is not updated.
// |video_codecs| has |codec_info|.tag added to its list if |codec_info| is a
// video codec. |video_codecs| may be NULL, in which case it is not updated.
//
// Returns false otherwise, and |audio_codecs| and |video_codecs| not touched.
static bool VerifyCodec(
    const CodecInfo* codec_info,
    std::vector<CodecInfo::HistogramTag>* audio_codecs,
    std::vector<CodecInfo::HistogramTag>* video_codecs) {
  switch (codec_info->type) {
    case CodecInfo::AUDIO:
#if defined(ENABLE_EAC3_PLAYBACK)
      if (codec_info->tag == CodecInfo::HISTOGRAM_EAC3) {
        const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
        if (!cmd_line->HasSwitch(switches::kEnableEac3Playback))
          return false;
      }
#endif
      if (codec_info->tag == CodecInfo::HISTOGRAM_OPUS) {
        const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
        if (!cmd_line->HasSwitch(switches::kEnableOpusPlayback))
          return false;
      }
      if (audio_codecs)
        audio_codecs->push_back(codec_info->tag);
      return true;
    case CodecInfo::VIDEO:
      if (video_codecs)
        video_codecs->push_back(codec_info->tag);
      return true;
    default:
      // Not audio or video, so skip it.
      DVLOG(1) << "CodecInfo type of " << codec_info->type
               << " should not be specified in a SupportedTypes list";
      return false;
  }
}

// Checks to see if the specified |type| and |codecs| list are supported.
//
// Returns true if |type| and all codecs listed in |codecs| are supported.
// |factory_function| contains a function that can build a StreamParser for this
// type. Value may be NULL, in which case it is not touched.
// |audio_codecs| is updated with the appropriate HistogramTags for matching
// audio codecs specified in |codecs|. Value may be NULL, in which case it is
// not touched.
// |video_codecs| is updated with the appropriate HistogramTags for matching
// video codecs specified in |codecs|. Value may be NULL, in which case it is
// not touched.
//
// Returns false otherwise. The values of |factory_function|, |audio_codecs|,
// and |video_codecs| are undefined.
static bool CheckTypeAndCodecs(
    const std::string& type,
    const std::vector<std::string>& codecs,
    const LogCB& log_cb,
    ParserFactoryFunction* factory_function,
    std::vector<CodecInfo::HistogramTag>* audio_codecs,
    std::vector<CodecInfo::HistogramTag>* video_codecs) {

  // Search for the SupportedTypeInfo for |type|.
  for (size_t i = 0; i < arraysize(kSupportedTypeInfo); ++i) {
    const SupportedTypeInfo& type_info = kSupportedTypeInfo[i];
    if (type == type_info.type) {
      if (codecs.empty()) {

#if defined(USE_PROPRIETARY_CODECS)
        if (type_info.codecs == kAudioMP3Codecs &&
            !CommandLine::ForCurrentProcess()->HasSwitch(
                switches::kEnableMP3StreamParser)) {
          DVLOG(1) << "MP3StreamParser is not enabled.";
          return false;
        }
#endif

        const CodecInfo* codec_info = type_info.codecs[0];
        if (codec_info && !codec_info->pattern &&
            VerifyCodec(codec_info, audio_codecs, video_codecs)) {

          if (factory_function)
            *factory_function = type_info.factory_function;
          return true;
        }

        MEDIA_LOG(log_cb) << "A codecs parameter must be provided for '"
                          << type << "'";
        return false;
      }

      // Make sure all the codecs specified in |codecs| are
      // in the supported type info.
      for (size_t j = 0; j < codecs.size(); ++j) {
        // Search the type info for a match.
        bool found_codec = false;
        std::string codec_id = codecs[j];
        for (int k = 0; type_info.codecs[k]; ++k) {
          if (MatchPattern(codec_id, type_info.codecs[k]->pattern) &&
              (!type_info.codecs[k]->validator ||
               type_info.codecs[k]->validator(codec_id, log_cb))) {
            found_codec =
                VerifyCodec(type_info.codecs[k], audio_codecs, video_codecs);
            break;  // Since only 1 pattern will match, no need to check others.
          }
        }

        if (!found_codec) {
          MEDIA_LOG(log_cb) << "Codec '" << codec_id
                            << "' is not supported for '" << type << "'";
          return false;
        }
      }

      if (factory_function)
        *factory_function = type_info.factory_function;

      // All codecs were supported by this |type|.
      return true;
    }
  }

  // |type| didn't match any of the supported types.
  return false;
}

bool StreamParserFactory::IsTypeSupported(
    const std::string& type, const std::vector<std::string>& codecs) {
  return CheckTypeAndCodecs(type, codecs, LogCB(), NULL, NULL, NULL);
}

scoped_ptr<StreamParser> StreamParserFactory::Create(
    const std::string& type,
    const std::vector<std::string>& codecs,
    const LogCB& log_cb,
    bool* has_audio,
    bool* has_video) {
  scoped_ptr<StreamParser> stream_parser;
  ParserFactoryFunction factory_function;
  std::vector<CodecInfo::HistogramTag> audio_codecs;
  std::vector<CodecInfo::HistogramTag> video_codecs;
  *has_audio = false;
  *has_video = false;

  if (CheckTypeAndCodecs(type,
                         codecs,
                         log_cb,
                         &factory_function,
                         &audio_codecs,
                         &video_codecs)) {
    *has_audio = !audio_codecs.empty();
    *has_video = !video_codecs.empty();

    // Log the number of codecs specified, as well as the details on each one.
    UMA_HISTOGRAM_COUNTS_100("Media.MSE.NumberOfTracks", codecs.size());
    for (size_t i = 0; i < audio_codecs.size(); ++i) {
      UMA_HISTOGRAM_ENUMERATION(
          "Media.MSE.AudioCodec", audio_codecs[i], CodecInfo::HISTOGRAM_MAX);
    }
    for (size_t i = 0; i < video_codecs.size(); ++i) {
      UMA_HISTOGRAM_ENUMERATION(
          "Media.MSE.VideoCodec", video_codecs[i], CodecInfo::HISTOGRAM_MAX);
    }

    stream_parser.reset(factory_function(codecs, log_cb));
  }

  return stream_parser.Pass();
}

}  // namespace media


text:
<?php

namespace Roots\Sage\Setup;

use Roots\Sage\Assets;

/**
 * Theme setup
 */

// content width
if ( !isset($content_width) ) { $content_width = 750; }

// images sizes
add_image_size('post-thumbnail', 370, 210, true);

function setup() {
	// Enable features from Soil when plugin is activated
	// https://roots.io/plugins/soil/
	add_theme_support('soil-clean-up');
	add_theme_support('soil-nav-walker');
	add_theme_support('soil-nice-search');
	add_theme_support('soil-jquery-cdn');
	add_theme_support('soil-relative-urls');
	add_theme_support('woocommerce');

	// Make theme available for translation
	// Community translations can be found at https://github.com/roots/sage-translations
	load_theme_textdomain('sage', get_template_directory() . '/lang');

	// Enable plugins to manage the document title
	// http://codex.wordpress.org/Function_Reference/add_theme_support#Title_Tag
	add_theme_support('title-tag');

	// Register wp_nav_menu() menus
	// http://codex.wordpress.org/Function_Reference/register_nav_menus
	register_nav_menus([
	'primary_navigation' 	=> __('Primary Navigation', 'sage'),
	'footer_navigation' 	=> __('Footer Navigation', 'sage')
	]);

	// Enable post thumbnails
	// http://codex.wordpress.org/Post_Thumbnails
	// http://codex.wordpress.org/Function_Reference/set_post_thumbnail_size
	// http://codex.wordpress.org/Function_Reference/add_image_size
	add_theme_support('post-thumbnails');

	// Enable HTML5 markup support
	// http://codex.wordpress.org/Function_Reference/add_theme_support#HTML5
	add_theme_support('html5', ['caption', 'comment-form', 'comment-list', 'gallery', 'search-form']);

	add_theme_support( 'custom-logo', array(
		'height'      => 50,
		'width'       => 140,
		'flex-height' => true,
	) );

	// Use main stylesheet for visual editor
	// To add custom styles edit /assets/styles/layouts/_tinymce.scss
	add_editor_style(Assets\asset_path('styles/main.css'));
}
add_action('after_setup_theme', __NAMESPACE__ . '\\setup');

/**
 * Register sidebars
 */
function widgets_init() {
  register_sidebar([
    'name'          => __('Primary', 'sage'),
    'id'            => 'sidebar-primary',
    'before_widget' => '
',
    'after_widget'  => '
',
    'before_title'  => '

',
    'after_title'   => '

'
  ]);

  register_sidebar([
    'name'          => __('Footer', 'sage'),
    'id'            => 'sidebar-footer',
    'before_widget' => '
',
    'after_widget'  => '
',
    'before_title'  => '
',
    'after_title'   => '
'
  ]);
}
add_action('widgets_init', __NAMESPACE__ . '\\widgets_init');

/**
 * Determine which pages should NOT display the sidebar
 */
function display_sidebar() {
  static $display;

  isset($display) || $display = in_array(true, [
    // The sidebar will NOT be displayed if ANY of the following return true.
    // @link https://codex.wordpress.org/Conditional_Tags
	is_404(),
	is_page_template('template-sidebar.php'),
	is_page_template('template-sidebar-naked.php'),
	is_product(),
	is_cart()
  ]);

  return apply_filters('sage/display_sidebar', $display);
}

/**
 * Theme assets
 */
function assets() {

	// Fonts
	wp_enqueue_style('roboto', 'https://fonts.googleapis.com/css?family=Roboto:700,400,300,100', false, null);
	wp_enqueue_style('font-awesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css', false, null);
	wp_enqueue_style('sage/css', Assets\asset_path('styles/main.css'), false, null);
	wp_enqueue_style('sage/custom', get_template_directory_uri() . '/assets/styles/custom.css', false, null);

	if (is_single() && comments_open() && get_option('thread_comments')) {
		wp_enqueue_script('comment-reply');
	}

	wp_enqueue_script('sage/js', Assets\asset_path('scripts/main.js'), ['jquery'], null, true);
}
add_action('wp_enqueue_scripts', __NAMESPACE__ . '\\assets', 100);


text:
#pragma once
#include <aws/managedblockchain/ManagedBlockchain_EXPORTS.h>
#include <aws/managedblockchain/ManagedBlockchainRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Http
{
    class URI;
} //namespace Http
namespace ManagedBlockchain
{
namespace Model
{

  /**
   */
  class AWS_MANAGEDBLOCKCHAIN_API ListProposalVotesRequest : public ManagedBlockchainRequest
  {
  public:
    ListProposalVotesRequest();

    // 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 "ListProposalVotes"; }

    Aws::String SerializePayload() const override;

    void AddQueryStringParameters(Aws::Http::URI& uri) const override;

    /**
     * <p> The unique identifier of the network. </p>
     */
    inline const Aws::String& GetNetworkId() const{ return m_networkId; }

    /**
     * <p> The unique identifier of the network. </p>
     */
    inline bool NetworkIdHasBeenSet() const { return m_networkIdHasBeenSet; }

    /**
     * <p> The unique identifier of the network. </p>
     */
    inline void SetNetworkId(const Aws::String& value) { m_networkIdHasBeenSet = true; m_networkId = value; }

    /**
     * <p> The unique identifier of the network. </p>
     */
    inline void SetNetworkId(Aws::String&& value) { m_networkIdHasBeenSet = true; m_networkId = std::move(value); }

    /**
     * <p> The unique identifier of the network. </p>
     */
    inline void SetNetworkId(const char* value) { m_networkIdHasBeenSet = true; m_networkId.assign(value); }

    /**
     * <p> The unique identifier of the network. </p>
     */
    inline ListProposalVotesRequest& WithNetworkId(const Aws::String& value) { SetNetworkId(value); return *this;}

    /**
     * <p> The unique identifier of the network. </p>
     */
    inline ListProposalVotesRequest& WithNetworkId(Aws::String&& value) { SetNetworkId(std::move(value)); return *this;}

    /**
     * <p> The unique identifier of the network. </p>
     */
    inline ListProposalVotesRequest& WithNetworkId(const char* value) { SetNetworkId(value); return *this;}

    /**
     * <p> The unique identifier of the proposal. </p>
     */
    inline const Aws::String& GetProposalId() const{ return m_proposalId; }

    /**
     * <p> The unique identifier of the proposal. </p>
     */
    inline bool ProposalIdHasBeenSet() const { return m_proposalIdHasBeenSet; }

    /**
     * <p> The unique identifier of the proposal. </p>
     */
    inline void SetProposalId(const Aws::String& value) { m_proposalIdHasBeenSet = true; m_proposalId = value; }

    /**
     * <p> The unique identifier of the proposal. </p>
     */
    inline void SetProposalId(Aws::String&& value) { m_proposalIdHasBeenSet = true; m_proposalId = std::move(value); }

    /**
     * <p> The unique identifier of the proposal. </p>
     */
    inline void SetProposalId(const char* value) { m_proposalIdHasBeenSet = true; m_proposalId.assign(value); }

    /**
     * <p> The unique identifier of the proposal. </p>
     */
    inline ListProposalVotesRequest& WithProposalId(const Aws::String& value) { SetProposalId(value); return *this;}

    /**
     * <p> The unique identifier of the proposal. </p>
     */
    inline ListProposalVotesRequest& WithProposalId(Aws::String&& value) { SetProposalId(std::move(value)); return *this;}

    /**
     * <p> The unique identifier of the proposal. </p>
     */
    inline ListProposalVotesRequest& WithProposalId(const char* value) { SetProposalId(value); return *this;}

    /**
     * <p> The maximum number of votes to return. </p>
     */
    inline int GetMaxResults() const{ return m_maxResults; }

    /**
     * <p> The maximum number of votes to return. </p>
     */
    inline bool MaxResultsHasBeenSet() const { return m_maxResultsHasBeenSet; }

    /**
     * <p> The maximum number of votes to return. </p>
     */
    inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; }

    /**
     * <p> The maximum number of votes to return. </p>
     */
    inline ListProposalVotesRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;}

    /**
     * <p> The pagination token that indicates the next set of results to retrieve.
     * </p>
     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     * <p> The pagination token that indicates the next set of results to retrieve.
     * </p>
     */
    inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; }

    /**
     * <p> The pagination token that indicates the next set of results to retrieve.
     * </p>
     */
    inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }

    /**
     * <p> The pagination token that indicates the next set of results to retrieve.
     * </p>
     */
    inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }

    /**
     * <p> The pagination token that indicates the next set of results to retrieve.
     * </p>
     */
    inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }

    /**
     * <p> The pagination token that indicates the next set of results to retrieve.
     * </p>
     */
    inline ListProposalVotesRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     * <p> The pagination token that indicates the next set of results to retrieve.
     * </p>
     */
    inline ListProposalVotesRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     * <p> The pagination token that indicates the next set of results to retrieve.
     * </p>
     */
    inline ListProposalVotesRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    Aws::String m_networkId;
    bool m_networkIdHasBeenSet;

    Aws::String m_proposalId;
    bool m_proposalIdHasBeenSet;

    int m_maxResults;
    bool m_maxResultsHasBeenSet;

    Aws::String m_nextToken;
    bool m_nextTokenHasBeenSet;
  };

} // namespace Model
} // namespace ManagedBlockchain
} // namespace Aws


text:
[![Build Status][travis-image]][travis-url]
[![DevDependency Status][daviddm-dev-image]][daviddm-dev-url]
[![License][license-image]][license-url]

Development Rules and Knowledge for React Native + Redux

## Installation

```
git clonet https://github.com/tongariboyz/react-native-redux-dev-notes.git
npm install
```

## Development

### サーバ起動

```
npm start
```

http://localhost:4000 にアクセスすることでプレビューできる。

### ディレクトリ構成

```
.
├── README
├── SUMMARY.md <= 目次
├── ja/ <= .mdの章を追加する
├── ja/resources/ <= 画像などリソースファイルを追加する
├── prh.yml
├── src/ <= サンプルコード
└── test/ <= サンプルコードのテスト
```

## Build

### HTML

```
npm run build
```

[travis-url]: https://travis-ci.org/tongariboyz/react-native-redux-dev-notes
[travis-image]: https://img.shields.io/travis/tongariboyz/react-native-redux-dev-notes.svg?style=flat-square
[daviddm-dev-url]: https://david-dm.org/tongariboyz/react-native-redux-dev-notes#info=devDependencies
[daviddm-dev-image]: https://img.shields.io/david/dev/tongariboyz/react-native-redux-dev-notes.svg?style=flat-square
[license-url]: https://github.com/tongariboyz/react-native-redux-dev-notes/blob/master/LICENSE
[license-image]: https://img.shields.io/github/license/tongariboyz/react-native-redux-dev-notes.svg?style=flat-square


text:
package com.currencycloud.client.model;

import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Rate {

    private BigDecimal bid;

    private BigDecimal offer;

    private Rate(BigDecimal bid, BigDecimal offer) {
        this.bid = bid;
        this.offer = offer;
    }

    public static Rate create(List<BigDecimal> bidOffer) {
        return new Rate(bidOffer.get(0), bidOffer.get(1));
    }

    public BigDecimal getBid() {
        return bid;
    }

    public BigDecimal getOffer() {
        return offer;
    }

    @Override
    public String toString() {
        final ObjectMapper objectMapper = new ObjectMapper()
                .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                .setDateFormat(new SimpleDateFormat(Utils.dateFormat));

        Map<String, Object> map = new HashMap<>();
        map.put("bid", bid);
        map.put("offer", offer);

        try {
            return objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            return String.format("{\"error\": \"%s\"}", e.getMessage());
        }
    }
}


text:
package com.facebook.buck.shell;

import com.facebook.buck.core.build.context.BuildContext;
import com.facebook.buck.core.build.execution.context.StepExecutionContext;
import com.facebook.buck.core.filesystems.AbsPath;
import com.facebook.buck.core.filesystems.PathWrapper;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.OutputLabel;
import com.facebook.buck.core.model.impl.BuildTargetPaths;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.core.rules.attr.HasRuntimeDeps;
import com.facebook.buck.core.rules.common.BuildableSupport;
import com.facebook.buck.core.rules.impl.NoopBuildRuleWithDeclaredAndExtraDeps;
import com.facebook.buck.core.rules.tool.BinaryBuildRule;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolverAdapter;
import com.facebook.buck.core.test.rule.ExternalTestRunnerRule;
import com.facebook.buck.core.test.rule.ExternalTestRunnerTestSpec;
import com.facebook.buck.core.test.rule.TestRule;
import com.facebook.buck.core.toolchain.tool.Tool;
import com.facebook.buck.core.toolchain.tool.impl.CommandTool;
import com.facebook.buck.io.filesystem.BuildCellRelativePath;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.rules.args.Arg;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.facebook.buck.test.TestCaseSummary;
import com.facebook.buck.test.TestResultSummary;
import com.facebook.buck.test.TestResults;
import com.facebook.buck.test.TestRunningOptions;
import com.facebook.buck.util.json.ObjectMappers;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.stream.Stream;

/**
 * Test whose correctness is determined by running a specified shell script. If running the shell
 * script returns a non-zero error code, the test is considered a failure.
 */
@SuppressWarnings("PMD.TestClassWithoutTestCases")
public class ShTest extends NoopBuildRuleWithDeclaredAndExtraDeps
    implements TestRule, HasRuntimeDeps, ExternalTestRunnerRule, BinaryBuildRule {

  private final ImmutableList<Arg> args;
  private final ImmutableMap<String, Arg> env;
  private final Optional<String> type;
  private final ImmutableSortedSet<? extends SourcePath> resources;
  private final Optional<Long> testRuleTimeoutMs;
  private final ImmutableSet<String> contacts;
  private final boolean runTestSeparately;
  private final ImmutableSet<String> labels;
  private final boolean withDownwardApi;

  protected ShTest(
      BuildTarget buildTarget,
      ProjectFilesystem projectFilesystem,
      BuildRuleParams params,
      ImmutableList<Arg> args,
      ImmutableMap<String, Arg> env,
      ImmutableSortedSet<? extends SourcePath> resources,
      Optional<Long> testRuleTimeoutMs,
      boolean runTestSeparately,
      Set<String> labels,
      Optional<String> type,
      ImmutableSet<String> contacts,
      boolean withDownwardApi) {
    super(buildTarget, projectFilesystem, params);
    this.args = args;
    this.env = env;
    this.resources = resources;
    this.testRuleTimeoutMs = testRuleTimeoutMs;
    this.runTestSeparately = runTestSeparately;
    this.labels = ImmutableSet.copyOf(labels);
    this.type = type;
    this.contacts = contacts;
    this.withDownwardApi = withDownwardApi;
  }

  @Override
  public ImmutableSet<String> getLabels() {
    return labels;
  }

  @Override
  public ImmutableSet<String> getContacts() {
    return contacts;
  }

  @Override
  public ImmutableList<Step> runTests(
      StepExecutionContext executionContext,
      TestRunningOptions options,
      BuildContext buildContext,
      TestReportingCallback testReportingCallback) {
    return new ImmutableList.Builder<Step>()
        .addAll(
            MakeCleanDirectoryStep.of(
                BuildCellRelativePath.fromCellRelativePath(
                    buildContext.getBuildCellRootPath(),
                    getProjectFilesystem(),
                    getPathToTestOutputDirectory())))
        .add(
            // Return a single command that runs an .sh file with no arguments.
            new RunShTestAndRecordResultStep(
                getProjectFilesystem(),
                Arg.stringify(args, buildContext.getSourcePathResolver()),
                Arg.stringify(env, buildContext.getSourcePathResolver()),
                testRuleTimeoutMs,
                getBuildTarget(),
                getPathToTestOutputResult(),
                withDownwardApi))
        .build();
  }

  @Override
  public Path getPathToTestOutputDirectory() {
    return BuildTargetPaths.getGenPath(
            getProjectFilesystem().getBuckPaths(), getBuildTarget(), "__sh_test_%s_output__")
        .getPath();
  }

  @VisibleForTesting
  Path getPathToTestOutputResult() {
    return getPathToTestOutputDirectory().resolve("result.json");
  }

  @Override
  public Callable<TestResults> interpretTestResults(
      StepExecutionContext context,
      SourcePathResolverAdapter pathResolver,
      boolean isUsingTestSelectors) {
    return () -> {
      Optional<String> resultsFileContents =
          getProjectFilesystem().readFileIfItExists(getPathToTestOutputResult());
      TestResultSummary testResultSummary =
          ObjectMappers.readValue(resultsFileContents.get(), TestResultSummary.class);
      TestCaseSummary testCaseSummary =
          new TestCaseSummary(
              getBuildTarget().getFullyQualifiedName(), ImmutableList.of(testResultSummary));
      return TestResults.of(
          getBuildTarget(),
          ImmutableList.of(testCaseSummary),
          contacts,
          labels.stream().map(Object::toString).collect(ImmutableSet.toImmutableSet()));
    };
  }

  @Override
  public boolean runTestSeparately() {
    return runTestSeparately;
  }

  // A shell test has no real build dependencies.  Instead interpret the dependencies as runtime
  // dependencies, as these are always components that the shell test needs available to run.
  @Override
  public Stream<BuildTarget> getRuntimeDeps(BuildRuleResolver buildRuleResolver) {
    return getBuildDeps().stream().map(BuildRule::getBuildTarget);
  }

  @Override
  public boolean supportsStreamingTests() {
    return false;
  }

  @Override
  public Tool getExecutableCommand(OutputLabel outputLabel) {
    CommandTool.Builder builder = new CommandTool.Builder().addInputs(resources);

    for (Arg arg : args) {
      builder.addArg(arg);
    }
    for (ImmutableMap.Entry<String, Arg> envVar : env.entrySet()) {
      builder.addEnv(envVar.getKey(), envVar.getValue());
    }
    return builder.build();
  }

  @Override
  public ExternalTestRunnerTestSpec getExternalTestRunnerSpec(
      StepExecutionContext executionContext,
      TestRunningOptions testRunningOptions,
      BuildContext buildContext) {

    List<AbsPath> requiredPaths = new ArrayList<>();

    // Extract any required paths from args and env vars.
    for (Arg arg : Iterables.concat(args, getEnv().values())) {
      BuildableSupport.deriveInputs(arg)
          .map(buildContext.getSourcePathResolver()::getAbsolutePath)
          .forEach(requiredPaths::add);
    }

    // Add resources to required paths.
    resources.stream()
        .map(buildContext.getSourcePathResolver()::getAbsolutePath)
        .forEach(requiredPaths::add);

    return ExternalTestRunnerTestSpec.builder()
        .setCwd(getProjectFilesystem().getRootPath().getPath())
        .setTarget(getBuildTarget())
        .setType(type.orElse("custom"))
        .addAllCommand(Arg.stringify(args, buildContext.getSourcePathResolver()))
        .setEnv(Arg.stringify(env, buildContext.getSourcePathResolver()))
        .addAllLabels(getLabels())
        .addAllContacts(getContacts())
        .setRequiredPaths(
            requiredPaths.stream()
                .map(PathWrapper::getPath)
                .collect(ImmutableList.toImmutableList()))
        .build();
  }

  @VisibleForTesting
  protected ImmutableList<Arg> getArgs() {
    return args;
  }

  @VisibleForTesting
  protected ImmutableMap<String, Arg> getEnv() {
    return env;
  }
}


text:
'use strict';

import { TPromise } from 'vs/base/common/winjs.base';
import URI from 'vs/base/common/uri';
import { RunOnceScheduler, wireCancellationToken } from 'vs/base/common/async';
import { IModelService } from 'vs/editor/common/services/modelService';
import { LinkProviderRegistry, ILink } from 'vs/editor/common/modes';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { OUTPUT_MODE_ID } from 'vs/workbench/parts/output/common/output';
import { MonacoWebWorker, createWebWorker } from 'vs/editor/common/services/webWorker';
import { ICreateData, OutputLinkComputer } from 'vs/workbench/parts/output/common/outputLinkComputer';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';

export class OutputLinkProvider {

	private static readonly DISPOSE_WORKER_TIME = 3 * 60 * 1000; // dispose worker after 3 minutes of inactivity

	private worker: MonacoWebWorker<OutputLinkComputer>;
	private disposeWorkerScheduler: RunOnceScheduler;
	private linkProviderRegistration: IDisposable;

	constructor(
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
		@IModelService private modelService: IModelService
	) {
		this.disposeWorkerScheduler = new RunOnceScheduler(() => this.disposeWorker(), OutputLinkProvider.DISPOSE_WORKER_TIME);

		this.registerListeners();
		this.updateLinkProviderWorker();
	}

	private registerListeners(): void {
		this.contextService.onDidChangeWorkspaceFolders(() => this.updateLinkProviderWorker());
	}

	private updateLinkProviderWorker(): void {

		// Setup link provider depending on folders being opened or not
		const folders = this.contextService.getWorkspace().folders;
		if (folders.length > 0) {
			if (!this.linkProviderRegistration) {
				this.linkProviderRegistration = LinkProviderRegistry.register({ language: OUTPUT_MODE_ID, scheme: '*' }, {
					provideLinks: (model, token): Thenable<ILink[]> => {
						return wireCancellationToken(token, this.provideLinks(model.uri));
					}
				});
			}
		} else {
			this.linkProviderRegistration = dispose(this.linkProviderRegistration);
		}

		// Dispose worker to recreate with folders on next provideLinks request
		this.disposeWorker();
		this.disposeWorkerScheduler.cancel();
	}

	private getOrCreateWorker(): MonacoWebWorker<OutputLinkComputer> {
		this.disposeWorkerScheduler.schedule();

		if (!this.worker) {
			const createData: ICreateData = {
				workspaceFolders: this.contextService.getWorkspace().folders.map(folder => folder.uri.toString())
			};

			this.worker = createWebWorker<OutputLinkComputer>(this.modelService, {
				moduleId: 'vs/workbench/parts/output/common/outputLinkComputer',
				createData,
				label: 'outputLinkComputer'
			});
		}

		return this.worker;
	}

	private provideLinks(modelUri: URI): TPromise<ILink[]> {
		return this.getOrCreateWorker().withSyncedResources([modelUri]).then(linkComputer => {
			return linkComputer.computeLinks(modelUri.toString());
		});
	}

	private disposeWorker(): void {
		if (this.worker) {
			this.worker.dispose();
			this.worker = null;
		}
	}
}


text:
Controls the default site.

## Properties

| Name              | Type           | Default                        | Description                                                                                |
|-------------------|----------------|--------------------------------|----------------------------------------------------------------------------------------------------------------------------------------|
| default_site_name | String         | `default-site`                 | The default site name                                                                                |
| site_action       | String, Symbol | `:enable`                      | Enable the site. Allows you to place all the configuration on disk but not enable the site                                             |
| port              | String         | `80`                           | Listen port                                                                                |
| template_cookbook | String         | `apache2`                      | Cookbook to source the template file from                                                                                |
| server_admin      | String         | `root@localhost`               | Default site contact name                                                                                |
| log_level         | String         | `warn`                         | Log level for apache2                                                                                |
| log_dir           | String         | `default_log_dir`              | Defaults to platform specific locations, see libraries/helpers.rb                                                                      |
| docroot_dir       | String         | `default_docroot_dir`          | Apache document root. Defaults to platform specific locations, see libraries/helpers.rb                                                |
| apache_root_group | String         | `node['root_group']`           | Group that the root user on the box runs as. Defaults to platform specific value from ohai root_group                                  |
| template_source   | String         | `default_site_template_source` | Source for the template. Defaults to #{new_resource.default_site_name}.conf on Debian flavours and welcome.conf on all other platforms |
| variables         | Hash           | `{}`                           | A hash of variables to pass into the template                                                                                |

## Actions

- `:enable`
- `:disable`

## Examples

```ruby
apache2_default_site '' do
  default_site_name String
  site_action       [String, Symbol]
  port              String
  template_cookbook String
  server_admin      String
  log_level         String
  action :enable
end
```

```ruby
apache2_default_site 'config-with-variables' do
  default_site_name 'example'
  site_action       :enable
  port              443
  template_cookbook 'my_cookbook'
  template_source   'ssl-enabled.conf.erb'
  server_admin      'webmaster@example.com'
  variables(
    ssl_cert_file: "#{apache_dir}/ssl/server.crt",
    ssl_cert_key_file: "#{apache_dir}/ssl/server.key",
  )
  action :enable
end
```


text:
class AddMorePrevColsToLocation < ActiveRecord::Migration
  def change
    add_column :locations, :prev2_location_id, :integer
    add_column :locations, :prev2_distance, :decimal
    add_column :locations, :prev2_elapsed, :decimal
    add_column :locations, :calced2_speed, :decimal

    add_column :locations, :prev3_location_id, :integer
    add_column :locations, :prev3_distance, :decimal
    add_column :locations, :prev3_elapsed, :decimal
    add_column :locations, :calced3_speed, :decimal
  end
end


text:
#pragma once
#include <aws/apprunner/AppRunner_EXPORTS.h>
#include <aws/apprunner/model/AutoScalingConfiguration.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace AppRunner
{
namespace Model
{
  class AWS_APPRUNNER_API DeleteAutoScalingConfigurationResult
  {
  public:
    DeleteAutoScalingConfigurationResult();
    DeleteAutoScalingConfigurationResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    DeleteAutoScalingConfigurationResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
A description of the App Runner auto scaling configuration that this request
     * just deleted.

     */
    inline const AutoScalingConfiguration& GetAutoScalingConfiguration() const{ return m_autoScalingConfiguration; }

    /**
     *
A description of the App Runner auto scaling configuration that this request
     * just deleted.

     */
    inline void SetAutoScalingConfiguration(const AutoScalingConfiguration& value) { m_autoScalingConfiguration = value; }

    /**
     *
A description of the App Runner auto scaling configuration that this request
     * just deleted.

     */
    inline void SetAutoScalingConfiguration(AutoScalingConfiguration&& value) { m_autoScalingConfiguration = std::move(value); }

    /**
     *
A description of the App Runner auto scaling configuration that this request
     * just deleted.

     */
    inline DeleteAutoScalingConfigurationResult& WithAutoScalingConfiguration(const AutoScalingConfiguration& value) { SetAutoScalingConfiguration(value); return *this;}

    /**
     *
A description of the App Runner auto scaling configuration that this request
     * just deleted.

     */
    inline DeleteAutoScalingConfigurationResult& WithAutoScalingConfiguration(AutoScalingConfiguration&& value) { SetAutoScalingConfiguration(std::move(value)); return *this;}

  private:

    AutoScalingConfiguration m_autoScalingConfiguration;
  };

} // namespace Model
} // namespace AppRunner
} // namespace Aws