text:
'use strict';

/**
 * Main module for TARS
 */

/**
 * Reqiure modules from TARS-CLI, if tars was executed via CLI and from local node_modules instead
 * @param  {String} packageName Name of the required package
 * @return {Object}             Required package
 */
function tarsRequire(packageName) {
    if (process.env.npmRoot) {
        return require(process.env.npmRoot + packageName);
    } else {
        return require(packageName);
    }
}

/**
 * Check operation system name
 * @return {Boolean}
 */
function isWindows() {
    return (/^win/i).test(os.platform());
}

// TARS is a global var
global.tars = {
    require: tarsRequire,
    cli: (process.env.npmRoot ? true : false)
};

var gutil = tars.require('gulp-util');
var os = require('os');
var tarsConfig = require('../tars-config');
var templaterName;
var templaterExtension = 'jade';
var cssPreprocName = tarsConfig.cssPreprocessor.toLowerCase();
var cssPreprocExtension = cssPreprocName;
var buildVersion = require('./helpers/set-build-version')();
var buildOptions = {};

if (cssPreprocName === 'stylus') {
    cssPreprocExtension = 'styl';
}

// Generate build version
if (tarsConfig.useBuildVersioning) {
    buildOptions.buildVersion = buildVersion;
    buildOptions.buildPath = tarsConfig.buildPath + 'build' + buildOptions.buildVersion + '/';
} else {
    buildOptions.buildVersion = '';
    buildOptions.buildPath = tarsConfig.buildPath;
}

// EXPORTING

// Tars config
tars.config = tarsConfig;

// Flags
tars.flags = gutil.env;

tars.say = function say(message) {
    if (os.platform() === 'darwin') {
        console.log(gutil.colors.cyan.bold('🅃 🄰 🅁 🅂 : ') + gutil.colors.white.bold(message));
    } else {
        console.log(gutil.colors.cyan.bold('[ TARS ]: ') + gutil.colors.white.bold(message));
    }
};

// Generate start screen
require('./helpers/start-screen-generator')(gutil);

// Required packages
tars.packages = {
    addsrc: tars.require('gulp-add-src'),
    autoprefixer: tars.require('autoprefixer'),
    browserSync: tars.require('browser-sync'),
    cache: tars.require('gulp-cached'),
    changed: tars.require('gulp-changed'),
    chokidar: tars.require('chokidar'),
    concat: tars.require('gulp-concat'),
    csso: tars.require('gulp-csso'),
    data: tars.require('gulp-data'),
    del: tars.require('del'),
    digits: tars.require('digits'),
    download: tars.require('download'),
    gulp: require('gulp'),
    gulpHandlebars: tars.require('gulp-compile-handlebars'),
    gulpif: tars.require('gulp-if'),
    gutil: gutil,
    handlebars: tars.require('gulp-compile-handlebars/node_modules/handlebars'),
    htmlMin: tars.require('gulp-minify-html'),
    imagemin: tars.require('gulp-imagemin'),
    jade: tars.require('gulp-jade'),
    jscs: tars.require('gulp-jscs'),
    jshint: tars.require('gulp-jshint'),
    less: tars.require('gulp-less'),
    mkdirp: tars.require('mkdirp'),
    ncp: tars.require('ncp'),
    notify: tars.require('gulp-notify'),
    plumber: tars.require('gulp-plumber'),
    postcss: tars.require('gulp-postcss'),
    promisePolyfill: tars.require('es6-promise'),
    rename: tars.require('gulp-rename'),
    replace: tars.require('gulp-replace-task'),
    runSequence: tars.require('run-sequence'),
    sass: tars.require('gulp-sass'),
    sourcemaps: tars.require('gulp-sourcemaps'),
    spritesmith: tars.require('gulp.spritesmith'),
    stripDebug: tars.require('gulp-strip-debug'),
    stylus: tars.require('gulp-stylus'),
    svg2png: tars.require('gulp-svg2png'),
    svgspritesheet: tars.require('gulp-svg-spritesheet'),
    streamCombiner: tars.require('stream-combiner'),
    through2: tars.require('through2'),
    uglify: tars.require('gulp-uglify'),
    zip: tars.require('gulp-zip')
}

// Links to helpers
tars.helpers = {
    buildVersion: buildVersion,
    dateFormatter: require('./helpers/modify-date-formatter'),
    fileLoader: require('./helpers/file-loader'),
    notifier: require('./helpers/notifier'),
    setUlimit: require('./helpers/set-ulimit'),
    watcherLog: require('./helpers/watcher-log')
}

templaterName = require('./helpers/templater-name-setter')();

// Set template's extension
if (templaterName === 'handlebars') {
    templaterExtension = ['html', 'hbs'];
} else {
    templaterExtension = ['jade'];
}

// Info about templater
tars.templater = {
    name: templaterName,
    ext: templaterExtension
};

// Info about css preprocessor
tars.cssPreproc = {
    name: cssPreprocName,
    ext: cssPreprocExtension
}

// Build options
tars.options = {
    notify: true,
    build: {
        hash: tars.flags.release ? Math.random().toString(36).substring(7) : '',
        path: buildOptions.buildPath,
        version: buildOptions.buildVersion
    }
}


text:
using AssistantTraining.DAL;
using AssistantTraining.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;

namespace AssistantTraining.Controllers
{
    [Authorize]
    public class TrainingController : Controller
    {
        /* Staff Training*/
        /*z jakich instrukcji pracownik powinien być przeszkolony i czy te szkolenia się odbyły*/
        /*
         * W1
         *  I1 Przeszkolony: Tak/Nie T.Date
         *  I2 Przeszkolony: Tak/Nie T.Date
         * W2
         *  I1 Przeszkolony: Tak/Nie T.Date
         *  I2 Przeszkolony: Tak/Nie T.Date
         *
                Select * from [dbo].[Workers] w
                LEFT JOIN [dbo].[GroupInstructions] gi ON w.ID = gi.WorkerID
                LEFT JOIN [dbo].[Instructions] i ON gi.GroupID = i.GroupID
                LEFT JOIN [dbo].[Trainings] t ON t.WorkerId = w.ID AND t.[InstructionId] = i.ID
                order BY w.LastName, w.FirstMidName
         */

        /* Training */
        /*śledzenie instrukcji – jacy pracownicy są podpięci do tych instrukcji i którzy wymagają przeszkolenia*/
        /*
         * I1
         *  W1 Przeszkolony: Tak/Nie
         *  W2 Przeszkolony: Tak/Nie
         * I12
         *  W1 Przeszkolony: Tak/Nie
         *  W2 Przeszkolony: Tak/Nie
         */

        private AssistantTrainingContext db = new AssistantTrainingContext();

        public ActionResult Index(int? id)
        {
            var viewModel = new TrainingIndexData();

            var lst = (from w in db.Workers
                       join gw in db.GroupWorkers on w.ID equals gw.WorkerId
                       join ig in db.InstructionGroups on new { GroupId = gw.GroupId } equals new { GroupId = Convert.ToInt32(ig.GroupId) }
                       join i in db.Instructions on ig.InstructionId equals i.ID
                       join t in db.Trainings on new { wID = w.ID , iID = i.ID } equals new { wID = t.WorkerId, iID = t.InstructionId }
                       into gj
                       from e in gj.DefaultIfEmpty()
                       select new TrainingItemIndexData{ WorkId=w.ID, Worker =w, Instruction =i, Training =e}
                       //select new {w, i= (new InstructionExt(w.ID,i)),e = (new TrainingExt{ WorkerID = w.ID }) }
                       ).OrderBy(x=>x.Worker.LastName).ToList();
            viewModel.items = lst;

            return View(viewModel);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
class CreateGeoLocationPoints < ActiveRecord::Migration
  def change
    create_table :geo_location_points, :options => 'ENGINE=MyISAM' do |t|
      t.decimal :lat, :precision => 9, :scale => 6
      t.decimal :lng, :precision => 9, :scale => 6
      t.integer :record_id

      t.timestamps
    end
  end
end


text:
\chapter{Fluid dynamics}\label{chap:fluid}
\section{Continuity equation and constructive relations}

\textbf{Nov 29.}

\scalefig{../Figs/handdraw1129_1}{0.4}{Fluid motion.}
The equation of fluid can be written as
\begin{align}
\fbox{$\pt{\rho} + \bigtriangledown \cdot j =0$}.\label{eq:continuity3d}
\end{align}
This is the continuity equation of fluid. For 1-D case,
\begin{align}
\pt{\rho} + \px{j} &=0.\label{eq:continuity1d}
\end{align}

Another relationship between $ \rho $ and $ j $ can be given through constitutive relation (we will play with different cases first).

If we have
\begin{align}
\pm c\rho &=j,
\end{align}
Equ.~\eqref{eq:continuity1d} gives
\begin{align}
\pt{\rho } \pm \px{c\rho} &=0,\\
\mathrm{or,}\qquad\qquad \qquad  \spt{\rho} &=c^2 \spx{\rho}.
\end{align}
This is the wave equation.

If we have
\begin{align}
-D \px{\rho} &=j.
\end{align}
Hence
\begin{align}
\frac{\partial}{\partial x} \left( -D\px{\rho} \right) + \px{\rho} &=0,\\
\pt{\rho} &= D\spx{\rho}.
\end{align}
This is the diffusion equation.

If we combine the two cases above and make
\begin{align}
j &=\rho c -D \px{\rho}\\
\Rightarrow \quad \frac{\partial }{\partial x} \left[ \rho c -D\px{\rho } \right] + \pt{\rho} &=0,\\
\Rightarrow \quad \pt{\rho} + c \px{\rho } &= D\spx{\rho}.
\end{align}
Finally, we arrive at the telegrapher's equation.

$ j $ may be like the velocity of a particle, and $ \rho $ may be like the position of a particle. The equation of fluid is like the equation of the movement of a particle.

What constitutive relation can give the telegrapher's equation?
\begin{align}
\spt{\rho} +\alpha \pt{\rho} &= c^2 \spx{\rho}.
\end{align}
Alternatively, we have the memory equation
\begin{align}
\pt{\rho(x,t)} &= D\int_0^t \drv t' \phi (t-t') \spx{\rho(x,t)},
\end{align}
where $ \phi(t)=\alpha e^{\alpha t} $ and $ D\alpha=c^2 $.

\section{Smoluchowski equation and methods to solve PDEs}
Now, we go back to the third case. In that case, the $ \rho $ is given almost as a constant. What will happen if all variables are not constant? This is like a tetherzed game (I have no idea what it is...).

Firstly, we change the $ c $ in the advective differential equation, and consider $\text{``velocity''}=-\gamma x$. One suggestion:
\begin{align}
\sdt{x} +\mathrm{const}\dt{x} + c x&=0.
\end{align}
We drop the first and the third terms,
\begin{align}
\dt{x} &= -\mathrm{const}\, x.
\end{align}

Next, we consider to form a term of $ \px{c\rho} $ in the third case mentioned above.
Possibly, we can make
\begin{align}
j &= -\gamma x\rho -D\px{\rho},
\end{align}
so that
\begin{align}
\pt{\rho} &= \frac{\partial}{\partial x} \left( \gamma x\rho \right) + D\spx{\rho},\label{eq:Smoluchowski0}\\
\Leftrightarrow\quad \pt{\rho} &= \frac{\partial}{\partial x} \left[ \gamma x\rho  + D\px{\rho}\right].\label{eq:Smoluchowski1}
\end{align}
The term of $\frac{\partial}{\partial x} \left( \gamma x\rho \right)  $ is tethezing. The term of $ D\spx{\rho} $ is homogeneous. The equation above is called Smoluchowski equation.

If the fluid is in equillibrium or stable state, then $ \pt{\rho}=0 $. So,
\begin{align}
\px{x} + \frac{\gamma x}{D}\rho &=0,\\
\Rightarrow\quad \frac{\drv \rho}{\rho} &= -\frac{\gamma}{D} x \drv x.
\end{align}
It will give a Gaussian solution.

\scalefig{../Figs/handdraw1129_2}{0.4}{ Flow in stable state.}

Recall that the Fourier transforms give
\begin{align}
\hat{f}(k) &= \intf{f(x)e^{ikx}}{x}\\
f(x) &= \frac{1}{2\pi} \intf{\hat{f}(k)e^{-ikx}}{k}
\end{align}

We can obtian
\begin{align}
\intf{xf(x)e^{ikx}}{x} &= -i \pp{\hat{f}(k)}{k}\\
\frac{-i}{2\pi} \intf{k\hat{f}(k)e^{-ikx}}{k} &= \px{f(x)}.
\end{align}

F.T. of
\begin{align}
xf(x) \quad &\mathrm{is}\quad -i\pp{\hat{f}(x)}{k}\\
\px{f(x)} \quad &\mathrm{is}\quad -ik\hat{f}(k).
\end{align}

\begin{align}
\pt{\hat{\rho}} &= -ik \gamma (-i)\pp{\hat{\rho}(k)}{k} -Dk^2 \hat{\rho} (k)\\
\pt{\hat{\rho}(k,t)} &+ \gamma k \pp{\hat{\rho}(k,t)}{k} + Dk^2 \hat{\rho} (k,t) = 0.
\end{align}

There are two methods to solve the equation above: one is called brvte force; the other is a clever one.

The brvte force method is related to the method of characteristics for the first-order PDE's. A good discussion is performed in the first question of Midterm Exam 3. Meanwhile, Ornstern and Vhlenbeck discovered another method of solving the equations above. We will discuss the latter method in the next section (lecture in Dec 4).

\textbf{Dec 4.}

\begin{align}
\pt{\rho(x,t)} &= \px{} \left[ \gamma x \rho(x,t)\right] + D \spx{\rho(x,t)}\\
j &= \rho (-\gamma x).\label{eq:Smoluchowski2}
\end{align}
We can make $ \gamma = \frac{k}{\Gamma} $, compared to the damped pendulum equation in the form of
\begin{align}
M \sdt{x} + \Gamma \dt{x  } + \frac{kx}{\Gamma} &=0.
\end{align}

Since the Smoluchowski equation (Equ.~\eqref{eq:Smoluchowski2}) is a second-order PDE, it is hard to solve.  Fortunately, through Fourier Transformation mentioned above, we can transfer it into a first-order PDE so that we can solve it using the method of characteristics. The F.T. yields
\begin{align}
\pt{\hat{\rho}(k,t)} + \gamma k \pp{\hat{\rho}(k,t)}{k} + D k^2 \hat{\rho} (k,t) &=0.
\end{align}

In this section, we will play with the equation in another way.
Let us make $ U'(x) = \dx{U(x)} $ to replace $ \gamma x $.

In steady state, we have
\begin{align}
0 &= \px{} \left[ U'(x)\overbrace{\rho(x)}^{\rho(x,\infty)}+ D \px{\rho(x)} \right].
\end{align}
Hence, we can make
\begin{align}
U'(x)\overbrace{\rho(x)}^{\rho(x,\infty)}+ D \px{\rho(x)} &= 0.
\end{align}

\begin{align}
\px{\rho(x)} &= - \frac{U'(x)}{D} \rho(x),\\
\Rightarrow \rho &= \mathrm{const.}\cdot e^{-\frac{U(x)}{D}}
\end{align}
This result is similar to Boltzman distribution function in statistaical mechanics.

Let us try
\begin{align}
\hat{\rho} &= \mathrm{const.} e^{-Dk^2 \underbrace{f(t)}_{\text{instead of $ t $, we use $ f(t) $}}}
\end{align}
\begin{align}
\mathrm{const.} e^{-Dk^2 f(t)} \left[ -Dk^2 \dot{f}(t) \right] &+ \mathrm{const.} e^{-Dk^2 f(t)} \gamma k\left[ -2Dkf(t) \right] + \mathrm{const.} e^{-Dk^2 f(t)} \left[ Dk^2 \right] =0\\
\Leftrightarrow -\dot{f}(t) - 2\gamma f(t) +1 &=0\\
\Leftrightarrow \dot{f}(t) + 2\gamma f(t) &=1.
\end{align}
It can be solved and give
\begin{align}
f(t) &= \frac{1- e^{-2\gamma t}}{2\gamma}\quad\qquad \qquad \mathrm{for } \quad f(0)=0.
\end{align}

If $ \rho(x,0) =\delta(x) $, then with
\begin{align}
\tau &= \frac{1- e^{-2\gamma t}}{2\gamma}
\end{align}
we have
\begin{align}
\rho (x,t) &= \frac{e^{-\frac{x^2}{4D\tau(t)} }}{\sqrt{4\pi D\tau(t)}}
= \frac{e^{-\frac{x^2}{4D\frac{1- e^{-2\gamma t}}{2\gamma}} }}{\sqrt{4\pi D\frac{1- e^{-2\gamma t}}{2\gamma}}}
\end{align}

We look at the relationship between $ \tau  $ and $ t $. If $ t\rightarrow 0 $, $ \tau = \frac{1-(1-2\gamma t+(2\gamma)^2t^2)/2}{2\gamma}\approx t $; if $ t $ is large, $ \tau $ approaches and is stabalized at $ \frac{1}{2\gamma} $.
\scalefig{../Figs/handdraw1204_1}{0.5}{ The evolution of $ \tau(t) $.}

This method of solving equations is called Ornstein-Uhlenbeck method.

Generally, for $ \rho(x,0)=\delta(x-y) $, we can replace $ x^2 $ by $(x-ye^{-\gamma t})^2$. The memory function gives
\begin{align}
\rho(x,t) &= \intf{G(x,y,t)\rho(y,0)}{y},
\end{align}
where
\begin{align}
G(x,y,t) &= \frac{e^{-\frac{(x-ye^{-\gamma t})^2}{4D\tau(t)}}}{\sqrt{4\pi D \tau (t)}}.
\end{align}

Convective differential equation
\begin{align}
\pt{\rho} + c \px{\rho} &= D \spx{\rho}
\end{align}
with \begin{align}
j &= c\rho -D \px{\rho}
\end{align}
can be solved in the similar way. We can make a transformation of $ x \rightarrow x- ct $. The behavior of the Gaussian function is determined by the propagator moving in speed $ c $.

\section{Burger's equation and nonlinear cases}
All the features of the equations above come from the form of $ j $ which may generate diffusion and fluctuations.

\scalefig{../Figs/handdraw1204_2}{0.6}{Changing $ j $ to give a different equation.}
Now, we consider a nonlinear $ j=j(\rho) = c\rho -b\rho^2$ (see Fig.~\ref{../Figs/handdraw1204_2}). Using $ \px{j} + \pt{\rho}=0 $ , we have
\begin{align}
\pt{\rho} + \pp{\left( c\rho -b\rho^2 \right)}{\rho} \px{\rho} &= 0.
\end{align}

Alternatively, for a homogeneous system
\begin{align}
\pt{\rho} + \left( c-2b\rho \right) \px{\rho} &=0.
\end{align}
We have a nonlinear partial differential equation of
\begin{align}
\pt{\rho} + \left( c-2b\rho \right) \px{\rho} &= D \spx{\rho}.
\end{align}

We multiply $ -2b $ and add $ c $ to the $ \rho $ in the equation above, we have
\begin{align}
\pt{(c-2b \rho)} + (c- 2b\rho ) \px{}\left[ c-2b\rho \right] &= D\spx{\left[c-2b\rho\right]}\\
\Leftrightarrow\qquad  \pt{V} + V \px{V} &= D\spx{V},
\end{align}
where $ V= c- 2b\rho $. This equation is called Burger's equation.

Compared with the propagator of $ x\rightarrow x-ct $, the $ V $ has the same form of a propagator with a speed $ 2b $ on $ \rho $ axis.

This equation has the exact solution as follows. The Cole-Hopb transformation
\begin{align}
V(x,t) &= -2D \ln \phi(x,t)
\end{align}
is the solution, where $ \phi(x,t) $ obeys
\begin{align}
\pt{\phi} &= D \spx{\phi}.
\end{align}

We discuss the behavior of the solution now. The initial wave can be seen in Fig.~\ref{../Figs/handdraw1204_3}.
\scalefig{../Figs/handdraw1204_3}{0.4}{ Wave of $ V(x,0) $. It will move and fall down as time marches.}

If $ D=0 $, the solution will have singularities and shocks.

The Burger's equation can be used to describe some behaviors of ions in certain crystals.

\textbf{Dec 6.}

If we start from
\begin{align}
j &= c\rho -b\rho^2 -D \px{\rho},
\end{align}
we will get the Burger's equation
\begin{align}
\pt{V} + V \px{V} &= D \spx{V}
\end{align}
with $ V = c- 2b\rho $. The solution is
\begin{align}
V &= -2D \px{}\left[ \ln \phi(x,t) \right],
\end{align}
where $ \phi(x,t) $ comes from the Cole-Hopf transformation:
\begin{align}
\pt{\phi} &= D \spx{\phi}.
\end{align}

If we take an initial wave like the one in Figs.~\ref{../Figs/handdraw1204_3}. This gives the brith of shocks and so on.

Using the initial value of $ V(x,0) $, we integrate it to give two parts which can be written as
\begin{align}
\int V(x,0)\drv x &= \ln \phi(x,0) + \mathrm{const.} V_0.
\end{align}
\scalefig{../Figs/handdraw1206_1}{.4}{ Initial wave slope of $ V(x,0) $.}

Therefore, we can obtain the initial condition for $ \phi(x,t) $, and solve $ \phi(x,t) $ using the Cole-Hopf transformation equation. Next, we can obtain the solution for $ V(x,t) $.

Notice that $ D=0 $ and $ D\neq 0 $ can give very different results.

Nonlinear Schrodinger equation, first introduced in optics, can be solved in the similar way. It can be discussed using eigenfunction techniques, and can be transformed into linear equations used in classical mechanics. Characteristic method is useful in solving similar equations.

We look at the equation of
\begin{align}
\pt{\rho} &= \underbrace{D \spx{\rho}}_{diffusion} + \underbrace{a\rho -b\rho^2}_{lvqister}
\end{align}
which is called Fisher-*-*-* equation. It can produce or can be transformed into many other forms of equations. So far, it cannot be solved analytically.

We can solve the steady state equation in terms of elliptic functions based on the pendulium models we discussed in earlier chapters.

Now,
\begin{align}
D \spx{\rho} + a\rho -b\rho^2 &=0.
\end{align}
Suppose $ a=b=0 $, it will give a second-order function of $ \rho $. What if $ a=0 $ but $ b\neq 0 $? It will grow, until it reaches $ \frac{a}{b} $. What if $ a\neq 0 $ but $ b=0 $? It will grow and never reaches a stop value. What if $ a\neq 0 $ and $ b\neq 0 $? It will grow and move like a sunami. See Fig.~\ref{../Figs/handdraw1206_2}.
\scalefig{../Figs/handdraw1206_2}{.4}{ Evolution of Fisher's equation.}

Murray's book tells more details on this Fisher's equation.


text:
package org.petuum.jbosen.table;

import org.petuum.jbosen.PsTableGroup;
import org.petuum.jbosen.client.ClientTable;
import org.petuum.jbosen.row.RowUpdate;
import org.petuum.jbosen.row.double_.DoubleRow;
import org.petuum.jbosen.row.double_.DoubleRowUpdate;
import org.petuum.jbosen.row.double_.SparseDoubleRowUpdate;

/**
 * An object of this class offers a view of a table that contains rows of
 * double values. Methods of this class should only be accessed from registered
 * worker threads. This class is thread-safe and can be shared between
 * different worker threads. Tables of this type should be created with
 * {@link PsTableGroup#createDenseDoubleTable(int, int, int)} or
 * {@link PsTableGroup#createSparseDoubleTable(int, int)}, and be retrieved
 * with {@link PsTableGroup#getDoubleTable(int)}.
 */
public final class DoubleTable {

    private ClientTable clientTable;

    /**
     * Internal use only.
     *
     * @param clientTable internal use only.
     */
    public DoubleTable(ClientTable clientTable) {
        this.clientTable = clientTable;
    }

    /**
     * Retrieve a row from this table.
     *
     * @param rowId     ID of the row to retrieve.
     * @param <RowType> type of the row to cast to before returning.
     * @return locally cached copy of the row.
     * @see Table#get(int)
     */
    @SuppressWarnings("unchecked")
    public <RowType extends DoubleRow> RowType get(int rowId) {
        return (RowType) clientTable.get(rowId).getRow();
    }

    /**
     * Retrieve a single column from a row in this table.
     *
     * @param rowId    row ID of the value to retrieve.
     * @param columnId column ID of the value to retrieve.
     * @return the value at the given row and column.
     */
    public double get(int rowId, int columnId) {
        DoubleRow doubleRow = (DoubleRow) clientTable.get(rowId).getRow();
        return doubleRow.get(columnId);
    }

    /**
     * Apply a batch update to an entire row.
     *
     * @param rowId     ID of the row to update.
     * @param rowUpdate update object to apply.
     * @see Table#inc(int, RowUpdate)
     */
    public void inc(int rowId, DoubleRowUpdate rowUpdate) {
        clientTable.inc(rowId, rowUpdate);
    }

    /**
     * Add a single value to a given row and column.
     *
     * @param rowId    row ID of the value to increment.
     * @param columnId column ID of the value to increment.
     * @param update   value to increment by.
     */
    public void inc(int rowId, int columnId, double update) {
        SparseDoubleRowUpdate rowUpdate = new SparseDoubleRowUpdate();
        rowUpdate.set(columnId, update);
        clientTable.inc(rowId, rowUpdate);
    }

}


text:
package com.tle.common.i18n;

import com.tle.common.Check;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** @author Nicholas Read */
public final class LocaleUtils {
  private static final Pattern LOCALE_REGEX =
      Pattern.compile("^([a-z][a-z])?(?:_([A-Z][A-Z])?(?:_(\\w+))?)?$"); // $NON-NLS-1$

  @SuppressWarnings("nls")
  public static String toHtmlLang(Locale locale) {
    String lang = locale.getLanguage();
    String country = locale.getCountry();
    String variant = locale.getVariant();
    return lang
        + (!Check.isEmpty(country) ? '-' + country : "")
        + (!Check.isEmpty(variant) ? '-' + variant : "");
  }

  /**
   * From the supplied list of locales, find the closest one to the supplies locale
   *
   * @param locales A collection possible locales to choose from
   * @param locale The locale you would like to match
   * @return The closest matching locale, or just the first available locale if no match
   */
  public static Locale getClosestLocale(Collection<Locale> locales, Locale locale) {
    Map<String, Locale> possibleMap = new LinkedHashMap<String, Locale>();
    for (Locale l : locales) {
      possibleMap.put(getExactKey(l), l);
    }
    return getClosestObjectForLocale(possibleMap, locale);
  }

  /** Retrieves the closest matching value from a map of Locale strings to values of some type. */
  public static <T> T getClosestObjectForLocale(Map<String, T> values, Locale locale) {
    Stack<String> keys = getAllPossibleKeys(locale);
    while (!keys.isEmpty()) {
      String key = keys.pop();
      T value = values.get(key);
      if (value != null) {
        return value;
      }
    }

    Collection<T> vs = values.values();
    return vs.isEmpty() ? null : vs.iterator().next();
  }

  /** Parses a locale from a string. */
  public static Locale parseLocale(String localeString) {
    if (localeString != null) {
      Matcher m = LOCALE_REGEX.matcher(localeString.trim());
      if (m.matches()) {
        return new Locale(
            Check.nullToEmpty(m.group(1)),
            Check.nullToEmpty(m.group(2)),
            Check.nullToEmpty(m.group(3)));
      }
    }
    throw new RuntimeException("Error parsing locale: " + localeString);
  }

  /** Determines the priority for a LanaguageString based on a locale. */
  public static int getPriorityForLocale(Locale locale) {
    if (Check.isEmpty(locale.getLanguage())) {
      return 0;
    } else if (Check.isEmpty(locale.getCountry())) {
      return 1;
    } else if (Check.isEmpty(locale.getVariant())) {
      return 2;
    } else {
      return 3;
    }
  }

  /** Returns the exact locale string. */
  public static String getExactKey(Locale locale) {
    return getKeys(
        new KeyGatherer<String>() {
          @Override
          void addKey(String part) {
            addToBuffer(part);
          }

          @Override
          public String getResult() {
            return buffer.toString();
          }
        },
        locale);
  }

  /** Returns a stack of locale strings, with the most specific locale on top. */
  public static Stack<String> getAllPossibleKeys(Locale locale) {
    return getKeys(
        new KeyGatherer<Stack<String>>() {
          Stack<String> result = new Stack<String>();

          @Override
          void addKey(String part) {
            addToBuffer(part);
            result.push(buffer.toString());
          }

          @Override
          Stack<String> getResult() {
            return result;
          }
        },
        locale);
  }

  /** Transforms a locale to possible key strings, and passes them to a key gatherer. */
  private static <T> T getKeys(KeyGatherer<T> gatherer, Locale locale) {
    return getKeys(gatherer, locale.getLanguage(), locale.getCountry(), locale.getVariant());
  }

  /**
   * Transforms the given locale elements to possible key strings, and passes them to the gatherer.
   */
  private static <T> T getKeys(
      KeyGatherer<T> gatherer, String language, String country, String variant) {
    boolean l = !Check.isEmpty(language);
    boolean c = !Check.isEmpty(country);
    boolean v = !Check.isEmpty(variant);

    gatherer.addKey(language);

    if (c || (l && v)) {
      gatherer.addKey(country); // This may just append '_'
    }

    if (v && (l || c)) {
      gatherer.addKey(variant);
    }

    return gatherer.getResult();
  }

  protected abstract static class KeyGatherer<T> {
    protected StringBuilder buffer = new StringBuilder(15);

    protected void addToBuffer(String part) {
      if (buffer.length() > 0) {
        buffer.append('_');
      }
      buffer.append(part);
    }

    abstract void addKey(String part);

    abstract T getResult();
  }

  private LocaleUtils() {
    throw new Error();
  }
}


text:
var isObject = require('./isObject');

/** Built-in value references. */
var objectCreate = Object.create;

/**
 * The base implementation of `_.create` without support for assigning
 * properties to the created object.
 *
 * @private
 * @param {Object} prototype The object to inherit from.
 * @returns {Object} Returns the new object.
 */
function baseCreate(proto) {
  return isObject(proto) ? objectCreate(proto) : {};
}

module.exports = baseCreate;


text:
CLASS({
  package: 'com.google.ow.stream',
  name: 'MultiplexDAO',
  extends: 'foam.dao.ProxyDAO',

  requires: [ 'com.google.ow.model.Envelope' ],

  properties: [
    {
      type: 'StringArray',
      name: 'people',
    },
    {
      type: 'Boolean',
      name: 'repackageOriginal',
      defaultValue: false,
    },
    {
      type: 'Function',
      name: 'envelopeFactory',
      defaultValue: function(baseEnv, pid) {
        var env = baseEnv.clone();
        env.id = baseEnv.id + '-' + pid;
        env.timestamp = new Date();
        env.owner = pid;
        env.data = this.dataFactory(baseEnv.data, pid);
        return env;
      },
    },
    {
      type: 'Function',
      name: 'dataFactory',
      defaultValue: function(data, pid) {
        return data.clone();
      },
    },
    {
      type: 'Function',
      name: 'putTo',
      defaultValue: function(env, sink, pid) {
        this.delegate.put(this.envelopeFactory(env, pid), sink);
      },
    },
  ],

  methods: [
    function getSharedSink_(env, sink, numOps) {
      var ownerEnv = null;
      var self = this;
      var ops = self.people.length + 1;
      var count = 0;
      var err = false;
      return {
        put: function(putEnv) {
          if ( err ) return;
          if ( putEnv.owner === env.owner ) ownerEnv = putEnv;
          ++count;
          if ( count === numOps ) sink && sink.put && sink.put(ownerEnv);
        },
        remove: function() {
          if ( err ) return;
          ++count;
        },
        error: function() {
          err = true;
          sink.error.apply(sink, arguments);
        }
      };
    },
    function put(env, sink) {
      var sharedSink = sink ?
          this.getSharedSink_(env, sink, self.people.length + 1) : null;
      if ( this.repackageOriginal )
        this.delegate.remove(env, sharedSink);
      for ( var i = 0; i < this.people.length; ++i ) {
        var pid = this.people[i];
        if ( this.repackageOriginal || pid !== env.owner )
          this.putTo(env, sharedSink, pid);
      }
      // var sinkError = sink && sink.error ? sink.error.bind(sink) : nop;
      // var putToNext = function(i) {
      //   if ( i >= self.people.length ) {
      //     sink && sink.put && sink.put(ownerEnv);
      //     return;
      //   }
      //   var pid = self.people[i];
      //   var pidEnv = this.envelopeFactory(env, pid);
      //   if ( pid === env.owner ) ownerEnv = pidEnv;
      //   this.delegate.put(pidEnv, {
      //     put: putToNext.bind(this, i + 1),
      //     error: sinkError,
      //   });
      // };
      // // Remove original envelope for replacement with multipliexed versions.
      // this.delegate.remove(env, {
      //   remove: putToNext.bind(this, 0),
      //   error: putToNext.bind(this, 0)
      // });
      // Put to everyone.
      // this.people.forEach(function(pid) {
      //   // Notify sink when we put for the original owner.
      //   if ( pid === env.owner ) this.putTo(env, pid, sink);
      //   else                     this.putTo(env, pid);
      // }.bind(this));
    },
  ],
});


text:
package com.cloudera.oryx.app.batch.mllib.rdf;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import com.google.common.base.Preconditions;
import com.typesafe.config.Config;
import net.openhft.koloboke.collect.map.IntLongMap;
import net.openhft.koloboke.collect.map.hash.HashIntLongMaps;
import org.apache.hadoop.fs.Path;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.mllib.linalg.Vectors;
import org.apache.spark.mllib.regression.LabeledPoint;
import org.apache.spark.mllib.tree.RandomForest;
import org.apache.spark.mllib.tree.configuration.Algo;
import org.apache.spark.mllib.tree.configuration.FeatureType;
import org.apache.spark.mllib.tree.model.DecisionTreeModel;
import org.apache.spark.mllib.tree.model.Predict;
import org.apache.spark.mllib.tree.model.RandomForestModel;
import org.apache.spark.mllib.tree.model.Split;
import org.dmg.pmml.Array;
import org.dmg.pmml.DataDictionary;
import org.dmg.pmml.FieldName;
import org.dmg.pmml.MiningFunctionType;
import org.dmg.pmml.MiningModel;
import org.dmg.pmml.MissingValueStrategyType;
import org.dmg.pmml.Model;
import org.dmg.pmml.MultipleModelMethodType;
import org.dmg.pmml.Node;
import org.dmg.pmml.PMML;
import org.dmg.pmml.Predicate;
import org.dmg.pmml.ScoreDistribution;
import org.dmg.pmml.Segment;
import org.dmg.pmml.Segmentation;
import org.dmg.pmml.SimplePredicate;
import org.dmg.pmml.SimpleSetPredicate;
import org.dmg.pmml.TreeModel;
import org.dmg.pmml.True;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.collection.JavaConversions;

import com.cloudera.oryx.app.classreg.example.Example;
import com.cloudera.oryx.app.classreg.example.ExampleUtils;
import com.cloudera.oryx.app.common.fn.MLFunctions;
import com.cloudera.oryx.app.pmml.AppPMMLUtils;
import com.cloudera.oryx.app.rdf.RDFPMMLUtils;
import com.cloudera.oryx.app.rdf.tree.DecisionForest;
import com.cloudera.oryx.app.schema.CategoricalValueEncodings;
import com.cloudera.oryx.app.schema.InputSchema;
import com.cloudera.oryx.common.collection.Pair;
import com.cloudera.oryx.common.pmml.PMMLUtils;
import com.cloudera.oryx.common.random.RandomManager;
import com.cloudera.oryx.common.text.TextUtils;
import com.cloudera.oryx.ml.MLUpdate;
import com.cloudera.oryx.ml.param.HyperParamValues;
import com.cloudera.oryx.ml.param.HyperParams;

/**
 * Update function that builds and evaluates random decision forest models in the Batch Layer.
 */
public final class RDFUpdate extends MLUpdate<String> {

  private static final Logger log = LoggerFactory.getLogger(RDFUpdate.class);

  private final int numTrees;
  private final List<HyperParamValues<?>> hyperParamValues;
  private final InputSchema inputSchema;

  public RDFUpdate(Config config) {
    super(config);
    numTrees = config.getInt("oryx.rdf.num-trees");
    Preconditions.checkArgument(numTrees >= 1);
    hyperParamValues = Arrays.asList(
        HyperParams.fromConfig(config, "oryx.rdf.hyperparams.max-split-candidates"),
        HyperParams.fromConfig(config, "oryx.rdf.hyperparams.max-depth"),
        HyperParams.fromConfig(config, "oryx.rdf.hyperparams.impurity"));

    inputSchema = new InputSchema(config);
    Preconditions.checkArgument(inputSchema.hasTarget());
  }

  @Override
  public List<HyperParamValues<?>> getHyperParameterValues() {
    return hyperParamValues;
  }

  @Override
  public PMML buildModel(JavaSparkContext sparkContext,
                         JavaRDD<String> trainData,
                         List<?> hyperParameters,
                         Path candidatePath) {

    int maxSplitCandidates = (Integer) hyperParameters.get(0);
    int maxDepth = (Integer) hyperParameters.get(1);
    String impurity = (String) hyperParameters.get(2);
    Preconditions.checkArgument(maxSplitCandidates >= 2,
                                "max-split-candidates must be at least 2");
    Preconditions.checkArgument(maxDepth > 0,
                                "max-depth must be at least 1");

    JavaRDD<String[]> parsedRDD = trainData.map(MLFunctions.PARSE_FN);
    CategoricalValueEncodings categoricalValueEncodings =
        new CategoricalValueEncodings(getDistinctValues(parsedRDD));
    JavaRDD<LabeledPoint> trainPointData =
        parseToLabeledPointRDD(parsedRDD, categoricalValueEncodings);

    Map<Integer,Integer> categoryInfo = categoricalValueEncodings.getCategoryCounts();
    categoryInfo.remove(inputSchema.getTargetFeatureIndex()); // Don't specify target count
    // Need to translate indices to predictor indices
    Map<Integer,Integer> categoryInfoByPredictor = new HashMap<>(categoryInfo.size());
    categoryInfo.forEach((k, v) -> categoryInfoByPredictor.put(inputSchema.featureToPredictorIndex(k), v));

    int seed = RandomManager.getRandom().nextInt();

    RandomForestModel model;
    if (inputSchema.isClassification()) {
      int numTargetClasses =
          categoricalValueEncodings.getValueCount(inputSchema.getTargetFeatureIndex());
      model = RandomForest.trainClassifier(trainPointData,
                                           numTargetClasses,
                                           categoryInfoByPredictor,
                                           numTrees,
                                           "auto",
                                           impurity,
                                           maxDepth,
                                           maxSplitCandidates,
                                           seed);
    } else {
      model = RandomForest.trainRegressor(trainPointData,
                                          categoryInfoByPredictor,
                                          numTrees,
                                          "auto",
                                          impurity,
                                          maxDepth,
                                          maxSplitCandidates,
                                          seed);
    }

    List<Map<Integer,Long>> treeNodeIDCounts = treeNodeExampleCounts(trainPointData, model);
    Map<Integer,Long> predictorIndexCounts = predictorExampleCounts(trainPointData, model);

    return rdfModelToPMML(model,
                          categoricalValueEncodings,
                          maxDepth,
                          maxSplitCandidates,
                          impurity,
                          treeNodeIDCounts,
                          predictorIndexCounts);
  }

  @Override
  public double evaluate(JavaSparkContext sparkContext,
                         PMML model,
                         Path modelParentPath,
                         JavaRDD<String> testData,
                         JavaRDD<String> trainData) {
    RDFPMMLUtils.validatePMMLVsSchema(model, inputSchema);
    Pair<DecisionForest,CategoricalValueEncodings> forestAndEncoding = RDFPMMLUtils.read(model);
    DecisionForest forest = forestAndEncoding.getFirst();
    CategoricalValueEncodings valueEncodings = forestAndEncoding.getSecond();

    InputSchema inputSchema = this.inputSchema;
    JavaRDD<Example> examplesRDD = testData.map(MLFunctions.PARSE_FN).
        map(data -> ExampleUtils.dataToExample(data, inputSchema, valueEncodings));

    double eval;
    if (inputSchema.isClassification()) {
      double accuracy = Evaluation.accuracy(forest, examplesRDD);
      log.info("Accuracy: {}", accuracy);
      eval = accuracy;
    } else {
      double rmse = Evaluation.rmse(forest, examplesRDD);
      log.info("RMSE: {}", rmse);
      eval = -rmse;
    }
    return eval;
  }

  private Map<Integer,Collection<String>> getDistinctValues(JavaRDD<String[]> parsedRDD) {
    int[] categoricalIndices = IntStream.range(0, inputSchema.getNumFeatures()).
        filter(inputSchema::isCategorical).toArray();

    return parsedRDD.mapPartitions(data -> {
        Map<Integer,Collection<String>> categoryValues = new HashMap<>();
        for (int i : categoricalIndices) {
          categoryValues.put(i, new HashSet<>());
        }
        data.forEachRemaining(datum ->
          categoryValues.forEach((category, values) -> values.add(datum[category]))
        );
        return Collections.singleton(categoryValues);
      }).reduce((v1, v2) -> {
        // Assumes both have the same key set
        v1.forEach((category, values) -> values.addAll(v2.get(category)));
        return v1;
      });
  }

  private JavaRDD<LabeledPoint> parseToLabeledPointRDD(
      JavaRDD<String[]> parsedRDD,
      CategoricalValueEncodings categoricalValueEncodings) {

    return parsedRDD.map(data -> {
      try {
        double[] features = new double[inputSchema.getNumPredictors()];
        double target = Double.NaN;
        for (int featureIndex = 0; featureIndex < data.length; featureIndex++) {
          double encoded;
          if (inputSchema.isNumeric(featureIndex)) {
            encoded = Double.parseDouble(data[featureIndex]);
          } else if (inputSchema.isCategorical(featureIndex)) {
            Map<String,Integer> valueEncoding =
                categoricalValueEncodings.getValueEncodingMap(featureIndex);
            encoded = valueEncoding.get(data[featureIndex]);
          } else {
            continue;
          }
          if (inputSchema.isTarget(featureIndex)) {
            target = encoded;
          } else {
            features[inputSchema.featureToPredictorIndex(featureIndex)] = encoded;
          }
        }
        Preconditions.checkState(!Double.isNaN(target));
        return new LabeledPoint(target, Vectors.dense(features));
      } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
        log.warn("Bad input: {}", Arrays.toString(data));
        throw e;
      }
    });
  }

  /**
   * @param trainPointData data to run down trees
   * @param model random decision forest model to count on
   * @return maps of node IDs to the count of training examples that reached that node, one
   *  per tree in the model
   * @see #predictorExampleCounts(JavaRDD,RandomForestModel)
   */
  private static List<Map<Integer,Long>> treeNodeExampleCounts(JavaRDD<LabeledPoint> trainPointData,
                                                               RandomForestModel model) {
    return trainPointData.mapPartitions(data -> {
        DecisionTreeModel[] trees = model.trees();
        List<IntLongMap> treeNodeIDCounts = IntStream.range(0, trees.length).
            mapToObj(i -> HashIntLongMaps.newMutableMap()).collect(Collectors.toList());
        data.forEachRemaining(datum -> {
          double[] featureVector = datum.features().toArray();
          for (int i = 0; i < trees.length; i++) {
            DecisionTreeModel tree = trees[i];
            IntLongMap nodeIDCount = treeNodeIDCounts.get(i);
            org.apache.spark.mllib.tree.model.Node node = tree.topNode();
            // This logic cloned from Node.predict:
            while (!node.isLeaf()) {
              // Count node ID
              nodeIDCount.addValue(node.id(), 1);
              Split split = node.split().get();
              int featureIndex = split.feature();
              node = nextNode(featureVector, node, split, featureIndex);
            }
            nodeIDCount.addValue(node.id(), 1);
          }
        });
        return Collections.<List<Map<Integer,Long>>>singleton(
            treeNodeIDCounts.stream().map(HashMap::new).collect(Collectors.toList()));
      }
    ).reduce((a, b) -> {
        Preconditions.checkArgument(a.size() == b.size());
        for (int i = 0; i < a.size(); i++) {
          merge(a.get(i), b.get(i));
        }
        return a;
      });
  }

  /**
   * @param trainPointData data to run down trees
   * @param model random decision forest model to count on
   * @return map of predictor index to the number of training examples that reached a
   *  node whose decision is based on that feature. The index is among predictors, not all
   *  features, since there are fewer predictors than features. That is, the index will
   *  match the one used in the {@link RandomForestModel}.
   */
  private static Map<Integer,Long> predictorExampleCounts(JavaRDD<LabeledPoint> trainPointData,
                                                          RandomForestModel model) {
    return trainPointData.mapPartitions(data -> {
        IntLongMap featureIndexCount = HashIntLongMaps.newMutableMap();
        data.forEachRemaining(datum -> {
          double[] featureVector = datum.features().toArray();
          for (DecisionTreeModel tree : model.trees()) {
            org.apache.spark.mllib.tree.model.Node node = tree.topNode();
            // This logic cloned from Node.predict:
            while (!node.isLeaf()) {
              Split split = node.split().get();
              int featureIndex = split.feature();
              // Count feature
              featureIndexCount.addValue(featureIndex, 1);
              node = nextNode(featureVector, node, split, featureIndex);
            }
          }
        });
        // Clone to avoid problem with Kryo serializing Koloboke
        return Collections.<Map<Integer,Long>>singleton(new HashMap<>(featureIndexCount));
    }).reduce(RDFUpdate::merge);
  }

  private static org.apache.spark.mllib.tree.model.Node nextNode(
      double[] featureVector,
      org.apache.spark.mllib.tree.model.Node node,
      Split split,
      int featureIndex) {
    double featureValue = featureVector[featureIndex];
    if (split.featureType().equals(FeatureType.Continuous())) {
      if (featureValue <= split.threshold()) {
        return node.leftNode().get();
      } else {
        return node.rightNode().get();
      }
    } else {
      if (split.categories().contains(featureValue)) {
        return node.leftNode().get();
      } else {
        return node.rightNode().get();
      }
    }
  }

  private static <T> Map<T,Long> merge(Map<T,Long> a, Map<T,Long> b) {
    if (b.size() > a.size()) {
      return merge(b, a);
    }
    b.forEach((key, value) -> a.merge(key, value, (x, y) -> x + y));
    return a;
  }

  private static <T> long get(Map<T,Long> map, T key) {
    Long count = map.get(key);
    return count == null ? 0L : count;
  }

  private PMML rdfModelToPMML(RandomForestModel rfModel,
                              CategoricalValueEncodings categoricalValueEncodings,
                              int maxDepth,
                              int maxSplitCandidates,
                              String impurity,
                              List<Map<Integer,Long>> nodeIDCounts,
                              Map<Integer,Long> predictorIndexCounts) {

    boolean classificationTask = rfModel.algo().equals(Algo.Classification());
    Preconditions.checkState(classificationTask == inputSchema.isClassification());

    DecisionTreeModel[] trees = rfModel.trees();

    Model model;
    if (trees.length == 1) {
      model = toTreeModel(trees[0], categoricalValueEncodings, nodeIDCounts.get(0));
    } else {
      MiningModel miningModel = new MiningModel();
      model = miningModel;
      MultipleModelMethodType multipleModelMethodType = classificationTask ?
          MultipleModelMethodType.WEIGHTED_MAJORITY_VOTE :
          MultipleModelMethodType.WEIGHTED_AVERAGE;
      List<Segment> segments = new ArrayList<>(trees.length);
      for (int treeID = 0; treeID < trees.length; treeID++) {
        TreeModel treeModel =
            toTreeModel(trees[treeID], categoricalValueEncodings, nodeIDCounts.get(treeID));
        segments.add(new Segment()
             .setId(Integer.toString(treeID))
             .setPredicate(new True())
             .setModel(treeModel)
             .setWeight(1.0)); // No weights in MLlib impl now
      }
      miningModel.setSegmentation(new Segmentation(multipleModelMethodType, segments));
    }

    model.setFunctionName(classificationTask ?
                          MiningFunctionType.CLASSIFICATION :
                          MiningFunctionType.REGRESSION);

    double[] importances = countsToImportances(predictorIndexCounts);
    model.setMiningSchema(AppPMMLUtils.buildMiningSchema(inputSchema, importances));
    DataDictionary dictionary =
        AppPMMLUtils.buildDataDictionary(inputSchema, categoricalValueEncodings);

    PMML pmml = PMMLUtils.buildSkeletonPMML();
    pmml.setDataDictionary(dictionary);
    pmml.addModels(model);

    AppPMMLUtils.addExtension(pmml, "maxDepth", maxDepth);
    AppPMMLUtils.addExtension(pmml, "maxSplitCandidates", maxSplitCandidates);
    AppPMMLUtils.addExtension(pmml, "impurity", impurity);

    return pmml;
  }

  private TreeModel toTreeModel(DecisionTreeModel dtModel,
                                CategoricalValueEncodings categoricalValueEncodings,
                                Map<Integer,Long> nodeIDCounts) {

    boolean classificationTask = dtModel.algo().equals(Algo.Classification());
    Preconditions.checkState(classificationTask == inputSchema.isClassification());

    Node root = new Node();
    root.setId("r");

    Queue<Node> modelNodes = new ArrayDeque<>();
    modelNodes.add(root);

    Queue<Pair<org.apache.spark.mllib.tree.model.Node,Split>> treeNodes = new ArrayDeque<>();
    treeNodes.add(new Pair<>(dtModel.topNode(), (Split) null));

    while (!treeNodes.isEmpty()) {

      Pair<org.apache.spark.mllib.tree.model.Node,Split> treeNodePredicate = treeNodes.remove();
      Node modelNode = modelNodes.remove();

      // This is the decision that got us here from the parent, if any;
      // not the predicate at this node
      Predicate predicate = buildPredicate(treeNodePredicate.getSecond(),
                                           categoricalValueEncodings);
      modelNode.setPredicate(predicate);

      org.apache.spark.mllib.tree.model.Node treeNode = treeNodePredicate.getFirst();
      long nodeCount = get(nodeIDCounts, treeNode.id());
      modelNode.setRecordCount((double) nodeCount);

      if (treeNode.isLeaf()) {

        Predict prediction = treeNode.predict();
        int targetEncodedValue = (int) prediction.predict();
        if (classificationTask) {
          Map<Integer,String> targetEncodingToValue =
              categoricalValueEncodings.getEncodingValueMap(inputSchema.getTargetFeatureIndex());
          double predictedProbability = prediction.prob();
          Preconditions.checkState(predictedProbability >= 0.0 && predictedProbability <= 1.0);
          // Not sure how nodeCount == 0 can happen but it does in the MLlib model
          long effectiveNodeCount = Math.max(1, nodeCount);
          // Problem: MLlib only gives a predicted class and its probability, and no distribution
          // over the rest. Infer that the rest of the probability is evenly distributed.
          double restProbability = (1.0 - predictedProbability) / (targetEncodingToValue.size() - 1);

          targetEncodingToValue.forEach((encodedValue, value) -> {
            double probability = encodedValue == targetEncodedValue ? predictedProbability : restProbability;
            // Yes, recordCount may be fractional; it's a relative indicator
            double recordCount = probability * effectiveNodeCount;
            if (recordCount > 0.0) {
              ScoreDistribution distribution = new ScoreDistribution(value, recordCount);
              // Not "confident" enough in the "probability" to call it one
              distribution.setConfidence(probability);
              modelNode.addScoreDistributions(distribution);
            }
          });
        } else {
          modelNode.setScore(Double.toString(targetEncodedValue));
        }

      } else {

        Split split = treeNode.split().get();

        Node positiveModelNode = new Node().setId(modelNode.getId() + '+');
        Node negativeModelNode = new Node().setId(modelNode.getId() + '-');
        modelNode.addNodes(positiveModelNode, negativeModelNode);

        org.apache.spark.mllib.tree.model.Node rightTreeNode = treeNode.rightNode().get();
        org.apache.spark.mllib.tree.model.Node leftTreeNode = treeNode.leftNode().get();

        boolean defaultRight = get(nodeIDCounts, rightTreeNode.id()) > get(nodeIDCounts, leftTreeNode.id());
        modelNode.setDefaultChild(defaultRight ? positiveModelNode.getId() : negativeModelNode.getId());

        // Right node is "positive", so carries the predicate. It must evaluate first
        // and therefore come first in the tree
        modelNodes.add(positiveModelNode);
        modelNodes.add(negativeModelNode);
        treeNodes.add(new Pair<>(rightTreeNode, split));
        treeNodes.add(new Pair<>(leftTreeNode, (Split) null));

      }

    }

    return new TreeModel()
        .setNode(root)
        .setSplitCharacteristic(TreeModel.SplitCharacteristic.BINARY_SPLIT)
        .setMissingValueStrategy(MissingValueStrategyType.DEFAULT_CHILD);
  }

  private Predicate buildPredicate(Split split,
                                   CategoricalValueEncodings categoricalValueEncodings) {
    if (split == null) {
      // Left child always applies, but is evaluated second
      return new True();
    }

    int featureIndex = inputSchema.predictorToFeatureIndex(split.feature());
    FieldName fieldName = FieldName.create(inputSchema.getFeatureNames().get(featureIndex));

    if (split.featureType().equals(FeatureType.Categorical())) {
      // Note that categories in MLlib model select the *left* child but the
      // convention here will be that the predicate selects the *right* child
      // So the predicate will evaluate "not in" this set
      // More ugly casting
      @SuppressWarnings("unchecked")
      List<Double> javaCategories = (List<Double>) (List<?>)
          JavaConversions.seqAsJavaList(split.categories());
      Set<Integer> negativeEncodings = javaCategories.stream().map(Double::intValue).collect(Collectors.toSet());

      Map<Integer,String> encodingToValue =
          categoricalValueEncodings.getEncodingValueMap(featureIndex);
      List<String> negativeValues = negativeEncodings.stream().map(encodingToValue::get).collect(Collectors.toList());

      String joinedValues = TextUtils.joinPMMLDelimited(negativeValues);
      return new SimpleSetPredicate(fieldName,
                                    SimpleSetPredicate.BooleanOperator.IS_NOT_IN,
                                    new Array(Array.Type.STRING, joinedValues));

    } else {
      // For MLlib, left means <= threshold, so right means >
      return new SimplePredicate(fieldName, SimplePredicate.Operator.GREATER_THAN)
          .setValue(Double.toString(split.threshold()));
    }
  }

  private double[] countsToImportances(Map<Integer,Long> predictorIndexCounts) {
    double[] importances = new double[inputSchema.getNumPredictors()];
    long total = predictorIndexCounts.values().stream().collect(Collectors.summingLong(l -> l));
    Preconditions.checkArgument(total > 0);
    predictorIndexCounts.forEach((k, count) -> importances[k] = (double) count / total);
    return importances;
  }

}


text:
using System;

using GoogleMobileAds;
using GoogleMobileAds.Common;

namespace GoogleMobileAds.Api
{
    public class InterstitialAd
    {
        private IInterstitialClient client;

        // Creates an InterstitialAd.
        public InterstitialAd(string adUnitId)
        {
            this.client = GoogleMobileAdsClientFactory.BuildInterstitialClient();
            client.CreateInterstitialAd(adUnitId);

            this.client.OnAdLoaded += (sender, args) =>
            {
                if (this.OnAdLoaded != null)
                {
                    this.OnAdLoaded(this, args);
                }
            };

            this.client.OnAdFailedToLoad += (sender, args) =>
            {
                if (this.OnAdFailedToLoad != null)
                {
                    this.OnAdFailedToLoad(this, args);
                }
            };

            this.client.OnAdOpening += (sender, args) =>
            {
                if (this.OnAdOpening != null)
                {
                    this.OnAdOpening(this, args);
                }
            };

            this.client.OnAdClosed += (sender, args) =>
            {
                if (this.OnAdClosed != null)
                {
                    this.OnAdClosed(this, args);
                }
            };

            this.client.OnAdLeavingApplication += (sender, args) =>
            {
                if (this.OnAdLeavingApplication != null)
                {
                    this.OnAdLeavingApplication(this, args);
                }
            };

            this.client.OnPaidEvent += (sender, args) =>
            {
                if (this.OnPaidEvent != null)
                {
                    this.OnPaidEvent(this, args);
                }
            };

        }

        // These are the ad callback events that can be hooked into.
        public event EventHandler<EventArgs> OnAdLoaded;

        public event EventHandler<AdFailedToLoadEventArgs> OnAdFailedToLoad;

        public event EventHandler<EventArgs> OnAdOpening;

        public event EventHandler<EventArgs> OnAdClosed;

        public event EventHandler<EventArgs> OnAdLeavingApplication;

        // Called when the ad is estimated to have earned money.
        public event EventHandler<AdValueEventArgs> OnPaidEvent;

        // Loads an InterstitialAd.
        public void LoadAd(AdRequest request)
        {
            client.LoadAd(request);
        }

        // Determines whether the InterstitialAd has loaded.
        public bool IsLoaded()
        {
            return client.IsLoaded();
        }

        // Displays the InterstitialAd.
        public void Show()
        {
            client.ShowInterstitial();
        }

        // Destroys the InterstitialAd.
        public void Destroy()
        {
            client.DestroyInterstitial();
        }

        // Returns the mediation adapter class name.
        public string MediationAdapterClassName()
        {
            return this.client.MediationAdapterClassName();
        }
    }
}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta property="og:image" content="https://origamiwolf.github.io/dotSpace/images/splash.png" />
		<meta name="description" content="Transforming paintings into RGB space"/>
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>dotSpace</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">

dotSpace

    Select a painting.  Left mouse - orbit, right mouse - pan, mouse scroll - zoom, 'R' - reset view, 'S' - toggle auto rotate.


text:
using extensions::AppSorting;
using extensions::Extension;
using extensions::ExtensionPrefs;
using extensions::ExtensionRegistry;
using extensions::ExtensionSet;
using extensions::ExtensionSyncData;
using extensions::ExtensionSystem;
using extensions::SyncBundle;

namespace {

void OnWebApplicationInfoLoaded(
    WebApplicationInfo synced_info,
    base::WeakPtr<ExtensionService> extension_service,
    const WebApplicationInfo& loaded_info) {
  DCHECK_EQ(synced_info.app_url, loaded_info.app_url);

  if (!extension_service)
    return;

  // Use the old icons if they exist.
  synced_info.icons = loaded_info.icons;
  CreateOrUpdateBookmarkApp(extension_service.get(), &synced_info);
}

// Returns the pref value for "all urls enabled" for the given extension id.
ExtensionSyncData::OptionalBoolean GetAllowedOnAllUrlsOptionalBoolean(
    const std::string& extension_id,
    content::BrowserContext* context) {
  bool allowed_on_all_urls =
      extensions::util::AllowedScriptingOnAllUrls(extension_id, context);
  // If the extension is not allowed on all urls (which is not the default),
  // then we have to sync the preference.
  if (!allowed_on_all_urls)
    return ExtensionSyncData::BOOLEAN_FALSE;

  // If the user has explicitly set a value, then we sync it.
  if (extensions::util::HasSetAllowedScriptingOnAllUrls(extension_id, context))
    return ExtensionSyncData::BOOLEAN_TRUE;

  // Otherwise, unset.
  return ExtensionSyncData::BOOLEAN_UNSET;
}

// Returns true if the sync type of |extension| matches |type|.
bool IsCorrectSyncType(const Extension& extension, syncer::ModelType type) {
  return (type == syncer::EXTENSIONS && extension.is_extension()) ||
         (type == syncer::APPS && extension.is_app());
}

syncer::SyncDataList ToSyncerSyncDataList(
    const std::vector<ExtensionSyncData>& data) {
  syncer::SyncDataList result;
  result.reserve(data.size());
  for (const ExtensionSyncData& item : data)
    result.push_back(item.GetSyncData());
  return result;
}

}  // namespace

ExtensionSyncService::ExtensionSyncService(Profile* profile)
    : profile_(profile),
      registry_observer_(this),
      prefs_observer_(this),
      flare_(sync_start_util::GetFlareForSyncableService(profile->GetPath())) {
  registry_observer_.Add(ExtensionRegistry::Get(profile_));
  prefs_observer_.Add(ExtensionPrefs::Get(profile_));
}

ExtensionSyncService::~ExtensionSyncService() {
}

// static
ExtensionSyncService* ExtensionSyncService::Get(
    content::BrowserContext* context) {
  return ExtensionSyncServiceFactory::GetForBrowserContext(context);
}

void ExtensionSyncService::SyncExtensionChangeIfNeeded(
    const Extension& extension) {
  if (!extensions::util::ShouldSync(&extension, profile_))
    return;

  syncer::ModelType type =
      extension.is_app() ? syncer::APPS : syncer::EXTENSIONS;
  SyncBundle* bundle = GetSyncBundle(type);
  if (bundle->IsSyncing()) {
    bundle->PushSyncAddOrUpdate(extension.id(),
                                CreateSyncData(extension).GetSyncData());
    DCHECK(!ExtensionPrefs::Get(profile_)->NeedsSync(extension.id()));
  } else {
    ExtensionPrefs::Get(profile_)->SetNeedsSync(extension.id(), true);
    if (extension_service()->is_ready() && !flare_.is_null())
      flare_.Run(type);  // Tell sync to start ASAP.
  }
}

syncer::SyncMergeResult ExtensionSyncService::MergeDataAndStartSyncing(
    syncer::ModelType type,
    const syncer::SyncDataList& initial_sync_data,
    scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
    scoped_ptr<syncer::SyncErrorFactory> sync_error_factory) {
  CHECK(sync_processor.get());
  LOG_IF(FATAL, type != syncer::EXTENSIONS && type != syncer::APPS)
      << "Got " << type << " ModelType";

  SyncBundle* bundle = GetSyncBundle(type);
  bundle->StartSyncing(sync_processor.Pass());

  // Apply the initial sync data, filtering out any items where we have more
  // recent local changes. Also tell the SyncBundle the extension IDs.
  for (const syncer::SyncData& sync_data : initial_sync_data) {
    scoped_ptr<ExtensionSyncData> extension_sync_data(
        ExtensionSyncData::CreateFromSyncData(sync_data));
    // If the extension has local state that needs to be synced, ignore this
    // change (we assume the local state is more recent).
    if (extension_sync_data &&
        !ExtensionPrefs::Get(profile_)->NeedsSync(extension_sync_data->id())) {
      ApplySyncData(*extension_sync_data);
    }
  }

  // Now push those local changes to sync.
  // TODO(treib,kalman): We should only have to send out changes for extensions
  // which have NeedsSync set (i.e. |GetLocalSyncDataList(type, false)|). That
  // makes some sync_integration_tests fail though - figure out why and fix it!
  std::vector<ExtensionSyncData> data_list = GetLocalSyncDataList(type, true);
  bundle->PushSyncDataList(ToSyncerSyncDataList(data_list));
  for (const ExtensionSyncData& data : data_list)
    ExtensionPrefs::Get(profile_)->SetNeedsSync(data.id(), false);

  if (type == syncer::APPS)
    ExtensionSystem::Get(profile_)->app_sorting()->FixNTPOrdinalCollisions();

  return syncer::SyncMergeResult(type);
}

void ExtensionSyncService::StopSyncing(syncer::ModelType type) {
  GetSyncBundle(type)->Reset();
}

syncer::SyncDataList ExtensionSyncService::GetAllSyncData(
    syncer::ModelType type) const {
  const SyncBundle* bundle = GetSyncBundle(type);
  if (!bundle->IsSyncing())
    return syncer::SyncDataList();

  std::vector<ExtensionSyncData> sync_data_list =
      GetLocalSyncDataList(type, true);

  // Add pending data (where the local extension is not installed yet).
  std::vector<ExtensionSyncData> pending_extensions =
      bundle->GetPendingExtensionData();
  sync_data_list.insert(sync_data_list.begin(),
                        pending_extensions.begin(),
                        pending_extensions.end());

  return ToSyncerSyncDataList(sync_data_list);
}

syncer::SyncError ExtensionSyncService::ProcessSyncChanges(
    const tracked_objects::Location& from_here,
    const syncer::SyncChangeList& change_list) {
  for (const syncer::SyncChange& sync_change : change_list) {
    scoped_ptr<ExtensionSyncData> extension_sync_data(
        ExtensionSyncData::CreateFromSyncChange(sync_change));
    if (extension_sync_data)
      ApplySyncData(*extension_sync_data);
  }

  ExtensionSystem::Get(profile_)->app_sorting()->FixNTPOrdinalCollisions();

  return syncer::SyncError();
}

ExtensionSyncData ExtensionSyncService::CreateSyncData(
    const Extension& extension) const {
  const ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(profile_);
  // Query the enabled state from ExtensionPrefs rather than
  // ExtensionService::IsExtensionEnabled - the latter uses ExtensionRegistry
  // which might not have been updated yet (ExtensionPrefs are updated first,
  // and we're listening for changes to these).
  bool enabled = !extension_prefs->IsExtensionDisabled(extension.id());
  enabled = enabled &&
      !extension_prefs->IsExternalExtensionUninstalled(extension.id());
  // Blacklisted extensions are not marked as disabled in ExtensionPrefs.
  enabled = enabled &&
      extension_prefs->GetExtensionBlacklistState(extension.id()) ==
          extensions::NOT_BLACKLISTED;
  int disable_reasons = extension_prefs->GetDisableReasons(extension.id());
  bool incognito_enabled = extensions::util::IsIncognitoEnabled(extension.id(),
                                                                profile_);
  bool remote_install =
      extension_prefs->HasDisableReason(extension.id(),
                                        Extension::DISABLE_REMOTE_INSTALL);
  ExtensionSyncData::OptionalBoolean allowed_on_all_url =
      GetAllowedOnAllUrlsOptionalBoolean(extension.id(), profile_);
  AppSorting* app_sorting = ExtensionSystem::Get(profile_)->app_sorting();

  ExtensionSyncData result = extension.is_app()
      ? ExtensionSyncData(
            extension, enabled, disable_reasons, incognito_enabled,
            remote_install, allowed_on_all_url,
            app_sorting->GetAppLaunchOrdinal(extension.id()),
            app_sorting->GetPageOrdinal(extension.id()),
            extensions::GetLaunchTypePrefValue(extension_prefs,
                                               extension.id()))
      : ExtensionSyncData(
            extension, enabled, disable_reasons, incognito_enabled,
            remote_install, allowed_on_all_url);

  // If there's a pending update, send the new version to sync instead of the
  // installed one.
  auto it = pending_update_versions_.find(extension.id());
  if (it != pending_update_versions_.end()) {
    const base::Version& version = it->second;
    // If we have a pending version, it should be newer than the installed one.
    DCHECK_EQ(-1, extension.version()->CompareTo(version));
    result.set_version(version);
  }
  return result;
}

void ExtensionSyncService::ApplySyncData(
    const ExtensionSyncData& extension_sync_data) {
  syncer::ModelType type = extension_sync_data.is_app() ? syncer::APPS
                                                        : syncer::EXTENSIONS;
  const std::string& id = extension_sync_data.id();
  // Note: |extension| may be null if it hasn't been installed yet.
  const Extension* extension =
      ExtensionRegistry::Get(profile_)->GetInstalledExtension(id);
  // TODO(bolms): we should really handle this better.  The particularly bad
  // case is where an app becomes an extension or vice versa, and we end up with
  // a zombie extension that won't go away.
  // TODO(treib): Is this still true?
  if (extension && !IsCorrectSyncType(*extension, type))
    return;

  SyncBundle* bundle = GetSyncBundle(type);
  // Forward to the bundle. This will just update the list of synced extensions.
  bundle->ApplySyncData(extension_sync_data);

  // Handle uninstalls first.
  if (extension_sync_data.uninstalled()) {
    if (!ExtensionService::UninstallExtensionHelper(
            extension_service(), id, extensions::UNINSTALL_REASON_SYNC)) {
      LOG(WARNING) << "Could not uninstall extension " << id << " for sync";
    }
    return;
  }

  // Extension from sync was uninstalled by the user as an external extension.
  // Honor user choice and skip installation/enabling.
  // TODO(treib): Should we still apply pref changes?
  if (ExtensionPrefs::Get(profile_)->IsExternalExtensionUninstalled(id)) {
    LOG(WARNING) << "Extension with id " << id
                 << " from sync was uninstalled as external extension";
    return;
  }

  int version_compare_result = extension ?
      extension->version()->CompareTo(extension_sync_data.version()) : 0;

  // Enable/disable the extension.
  if (extension_sync_data.enabled()) {
    DCHECK(!extension_sync_data.disable_reasons());

    // Only grant permissions if the sync data explicitly sets the disable
    // reasons to Extension::DISABLE_NONE (as opposed to the legacy (<M45) case
    // where they're not set at all), and if the version from sync matches our
    // local one. Otherwise we just enable it without granting permissions. If
    // any permissions are missing, CheckPermissionsIncrease will soon disable
    // it again.
    bool grant_permissions =
        extension_sync_data.supports_disable_reasons() &&
        extension && (version_compare_result == 0);
    if (grant_permissions)
      extension_service()->GrantPermissionsAndEnableExtension(extension);
    else
      extension_service()->EnableExtension(id);
  } else {
    int disable_reasons = extension_sync_data.disable_reasons();
    if (extension_sync_data.remote_install()) {
      if (!(disable_reasons & Extension::DISABLE_REMOTE_INSTALL)) {
        // In the non-legacy case (>=M45) where disable reasons are synced at
        // all, DISABLE_REMOTE_INSTALL should be among them already.
        DCHECK(!extension_sync_data.supports_disable_reasons());
        disable_reasons |= Extension::DISABLE_REMOTE_INSTALL;
      }
    } else if (!extension_sync_data.supports_disable_reasons()) {
      // Legacy case (<M45), from before we synced disable reasons (see
      // crbug.com/484214).
      disable_reasons = Extension::DISABLE_UNKNOWN_FROM_SYNC;
    }

    // In the non-legacy case (>=M45), clear any existing disable reasons first.
    // Otherwise sync can't remove just some of them.
    if (extension_sync_data.supports_disable_reasons())
      ExtensionPrefs::Get(profile_)->ClearDisableReasons(id);

    extension_service()->DisableExtension(id, disable_reasons);
  }

  // If the target extension has already been installed ephemerally, it can
  // be promoted to a regular installed extension and downloading from the Web
  // Store is not necessary.
  if (extension && extensions::util::IsEphemeralApp(id, profile_))
    extension_service()->PromoteEphemeralApp(extension, true);

  // Cache whether the extension was already installed because setting the
  // incognito flag invalidates the |extension| pointer (it reloads the
  // extension).
  bool extension_installed = (extension != nullptr);

  // Update the incognito flag.
  extensions::util::SetIsIncognitoEnabled(
      id, profile_, extension_sync_data.incognito_enabled());
  extension = nullptr;  // No longer safe to use.

  // Update the all urls flag.
  if (extension_sync_data.all_urls_enabled() !=
          ExtensionSyncData::BOOLEAN_UNSET) {
    bool allowed = extension_sync_data.all_urls_enabled() ==
        ExtensionSyncData::BOOLEAN_TRUE;
    extensions::util::SetAllowedScriptingOnAllUrls(id, profile_, allowed);
  }

  // Set app-specific data.
  if (extension_sync_data.is_app()) {
    if (extension_sync_data.app_launch_ordinal().IsValid() &&
        extension_sync_data.page_ordinal().IsValid()) {
      AppSorting* app_sorting = ExtensionSystem::Get(profile_)->app_sorting();
      app_sorting->SetAppLaunchOrdinal(
          id,
          extension_sync_data.app_launch_ordinal());
      app_sorting->SetPageOrdinal(id, extension_sync_data.page_ordinal());
    }

    // The corresponding validation of this value during ExtensionSyncData
    // population is in ExtensionSyncData::ToAppSpecifics.
    if (extension_sync_data.launch_type() >= extensions::LAUNCH_TYPE_FIRST &&
        extension_sync_data.launch_type() < extensions::NUM_LAUNCH_TYPES) {
      extensions::SetLaunchType(
          profile_, id, extension_sync_data.launch_type());
    }

    if (!extension_sync_data.bookmark_app_url().empty())
      ApplyBookmarkAppSyncData(extension_sync_data);
  }

  // Finally, trigger installation/update as required.
  bool check_for_updates = false;
  if (extension_installed) {
    // If the extension is installed but outdated, store the new version.
    if (version_compare_result < 0) {
      pending_update_versions_[id] = extension_sync_data.version();
      check_for_updates = true;
    }
  } else {
    if (!extension_service()->pending_extension_manager()->AddFromSync(
            id,
            extension_sync_data.update_url(),
            extension_sync_data.version(),
            extensions::sync_helper::IsSyncable,
            extension_sync_data.remote_install(),
            extension_sync_data.installed_by_custodian())) {
      LOG(WARNING) << "Could not add pending extension for " << id;
      // This means that the extension is already pending installation, with a
      // non-INTERNAL location.  Add to pending_sync_data, even though it will
      // never be removed (we'll never install a syncable version of the
      // extension), so that GetAllSyncData() continues to send it.
    }
    // Track pending extensions so that we can return them in GetAllSyncData().
    bundle->AddPendingExtensionData(id, extension_sync_data);
    check_for_updates = true;
  }

  if (check_for_updates)
    extension_service()->CheckForUpdatesSoon();
}

void ExtensionSyncService::ApplyBookmarkAppSyncData(
    const ExtensionSyncData& extension_sync_data) {
  DCHECK(extension_sync_data.is_app());

  // Process bookmark app sync if necessary.
  GURL bookmark_app_url(extension_sync_data.bookmark_app_url());
  if (!bookmark_app_url.is_valid() ||
      extension_sync_data.uninstalled()) {
    return;
  }

  const Extension* extension =
      extension_service()->GetInstalledExtension(extension_sync_data.id());

  // Return if there are no bookmark app details that need updating.
  if (extension &&
      extension->non_localized_name() == extension_sync_data.name() &&
      extension->description() ==
          extension_sync_data.bookmark_app_description()) {
    return;
  }

  WebApplicationInfo web_app_info;
  web_app_info.app_url = bookmark_app_url;
  web_app_info.title = base::UTF8ToUTF16(extension_sync_data.name());
  web_app_info.description =
      base::UTF8ToUTF16(extension_sync_data.bookmark_app_description());
  if (!extension_sync_data.bookmark_app_icon_color().empty()) {
    extensions::image_util::ParseCSSColorString(
        extension_sync_data.bookmark_app_icon_color(),
        &web_app_info.generated_icon_color);
  }
  for (const auto& icon : extension_sync_data.linked_icons()) {
    WebApplicationInfo::IconInfo icon_info;
    icon_info.url = icon.url;
    icon_info.width = icon.size;
    icon_info.height = icon.size;
    web_app_info.icons.push_back(icon_info);
  }

  // If the bookmark app already exists, keep the old icons.
  if (!extension) {
    CreateOrUpdateBookmarkApp(extension_service(), &web_app_info);
  } else {
    GetWebApplicationInfoFromApp(profile_,
                                 extension,
                                 base::Bind(&OnWebApplicationInfoLoaded,
                                            web_app_info,
                                            extension_service()->AsWeakPtr()));
  }
}

void ExtensionSyncService::SetSyncStartFlareForTesting(
    const syncer::SyncableService::StartSyncFlare& flare) {
  flare_ = flare;
}

ExtensionService* ExtensionSyncService::extension_service() const {
  return ExtensionSystem::Get(profile_)->extension_service();
}

void ExtensionSyncService::OnExtensionInstalled(
    content::BrowserContext* browser_context,
    const Extension* extension,
    bool is_update) {
  DCHECK_EQ(profile_, browser_context);
  // Clear pending version if the installed one has caught up.
  auto it = pending_update_versions_.find(extension->id());
  if (it != pending_update_versions_.end()) {
    const base::Version& pending_version = it->second;
    if (extension->version()->CompareTo(pending_version) >= 0)
      pending_update_versions_.erase(it);
  }
  SyncExtensionChangeIfNeeded(*extension);
}

void ExtensionSyncService::OnExtensionUninstalled(
    content::BrowserContext* browser_context,
    const Extension* extension,
    extensions::UninstallReason reason) {
  DCHECK_EQ(profile_, browser_context);
  // Don't bother syncing if the extension will be re-installed momentarily.
  if (reason == extensions::UNINSTALL_REASON_REINSTALL ||
      !extensions::util::ShouldSync(extension, profile_))
    return;

  // TODO(tim): If we get here and IsSyncing is false, this will cause
  // "back from the dead" style bugs, because sync will add-back the extension
  // that was uninstalled here when MergeDataAndStartSyncing is called.
  // See crbug.com/256795.
  // Possible fix: Set NeedsSync here, then in MergeDataAndStartSyncing, if
  // NeedsSync is set but the extension isn't installed, send a sync deletion.
  syncer::ModelType type =
      extension->is_app() ? syncer::APPS : syncer::EXTENSIONS;
  SyncBundle* bundle = GetSyncBundle(type);
  if (bundle->IsSyncing()) {
    bundle->PushSyncDeletion(extension->id(),
                             CreateSyncData(*extension).GetSyncData());
  } else if (extension_service()->is_ready() && !flare_.is_null()) {
    flare_.Run(type);  // Tell sync to start ASAP.
  }

  pending_update_versions_.erase(extension->id());
}

void ExtensionSyncService::OnExtensionStateChanged(
    const std::string& extension_id,
    bool state) {
  ExtensionRegistry* registry = ExtensionRegistry::Get(profile_);
  const Extension* extension = registry->GetInstalledExtension(extension_id);
  // We can get pref change notifications for extensions that aren't installed
  // (yet). In that case, we'll pick up the change later via ExtensionRegistry
  // observation (in OnExtensionInstalled).
  if (extension)
    SyncExtensionChangeIfNeeded(*extension);
}

void ExtensionSyncService::OnExtensionDisableReasonsChanged(
    const std::string& extension_id,
    int disabled_reasons) {
  ExtensionRegistry* registry = ExtensionRegistry::Get(profile_);
  const Extension* extension = registry->GetInstalledExtension(extension_id);
  // We can get pref change notifications for extensions that aren't installed
  // (yet). In that case, we'll pick up the change later via ExtensionRegistry
  // observation (in OnExtensionInstalled).
  if (extension)
    SyncExtensionChangeIfNeeded(*extension);
}

SyncBundle* ExtensionSyncService::GetSyncBundle(syncer::ModelType type) {
  return const_cast<SyncBundle*>(
      const_cast<const ExtensionSyncService&>(*this).GetSyncBundle(type));
}

const SyncBundle* ExtensionSyncService::GetSyncBundle(
    syncer::ModelType type) const {
  return (type == syncer::APPS) ? &app_sync_bundle_ : &extension_sync_bundle_;
}

std::vector<ExtensionSyncData> ExtensionSyncService::GetLocalSyncDataList(
    syncer::ModelType type,
    bool include_everything) const {
  // Collect the local state.
  ExtensionRegistry* registry = ExtensionRegistry::Get(profile_);
  std::vector<ExtensionSyncData> data;
  // TODO(treib, kalman): Should we be including blacklisted/blocked extensions
  // here? I.e. just calling registry->GeneratedInstalledExtensionsSet()?
  // It would be more consistent, but the danger is that the black/blocklist
  // hasn't been updated on all clients by the time sync has kicked in -
  // so it's safest not to. Take care to add any other extension lists here
  // in the future if they are added.
  FillSyncDataList(
      registry->enabled_extensions(), type, include_everything, &data);
  FillSyncDataList(
      registry->disabled_extensions(), type, include_everything, &data);
  FillSyncDataList(
      registry->terminated_extensions(), type, include_everything, &data);
  return data;
}

void ExtensionSyncService::FillSyncDataList(
    const ExtensionSet& extensions,
    syncer::ModelType type,
    bool include_everything,
    std::vector<ExtensionSyncData>* sync_data_list) const {
  for (const scoped_refptr<const Extension>& extension : extensions) {
    if (IsCorrectSyncType(*extension, type) &&
        extensions::util::ShouldSync(extension.get(), profile_) &&
        (include_everything ||
         ExtensionPrefs::Get(profile_)->NeedsSync(extension->id()))) {
      // We should never have pending data for an installed extension.
      DCHECK(!GetSyncBundle(type)->HasPendingExtensionData(extension->id()));
      sync_data_list->push_back(CreateSyncData(*extension));
    }
  }
}


text:
struct hyper_event;

struct hyper_event_ops {
	int		(*read)(struct hyper_event *e, int efd, int events);
	int		(*write)(struct hyper_event *e, int efd, int events);
	void		(*hup)(struct hyper_event *e, int efd);
	int		rbuf_size;
	int		wbuf_size;
};

struct hyper_buf {
	uint32_t		get;
	uint32_t		size;
	uint8_t			*data;
};

struct hyper_event {
	int			fd;
	int			hup;
	int			flag;
	struct hyper_buf	rbuf;
	struct hyper_buf	wbuf;
	struct hyper_event_ops	*ops;
	void			*ptr;
};

#define FULL(buf) \
	(buf->size - buf->get <= 12)

int hyper_add_event(int efd, struct hyper_event *de, int flag);
int hyper_modify_event(int efd, struct hyper_event *de, int flag);
int hyper_requeue_event(int efd, struct hyper_event *ev);
int hyper_init_event(struct hyper_event *de, struct hyper_event_ops *ops,
		     void *arg);
int hyper_handle_event(int efd, struct epoll_event *event);
void hyper_reset_event(struct hyper_event *de);
void hyper_event_hup(struct hyper_event *de, int efd);
int hyper_event_write(struct hyper_event *de, int efd, int events);
int hyper_wbuf_append_msg(struct hyper_event *de, uint8_t *data, uint32_t len);
#endif


text:
			<?php echo Localized::ModelLabel($this->model->tableName(), "active" ); ?>
			<?php echo Localized::ModelLabel($this->model->tableName(), "name" ); ?>
			<?php echo Localized::ModelLabel($this->model->tableName(), "email" ); ?>
			<?php echo Localized::ModelLabel($this->model->tableName(), "type" ); ?>
			<?php echo Localized::ModelLabel($this->model->tableName(), "last_login_timestamp" ); ?>
			<?php echo Localized::ModelLabel($this->model->tableName(), "last_failed_login" ); ?>
			<?php echo Localized::ModelLabel($this->model->tableName(), "api_hash" ); ?>

	<?php
		if ($this->users) {
			foreach($this->users as $key => $value) {
				echo '

					isActive() ? 'true' : 'false') . '">
					' . htmlentities($value->name) . '
					' . $value->email .'
					' . $value->account_type .'
					' . $value->formattedDateTime_last_login_timestamp() .'
					' . $value->formattedDateTime_last_failed_login() .'
					' . $value->api_hash .'
					id) . '">
					id) . '" href="#">

';
			}
		} else {
			echo 'No users yet. Create some !';
		}
	?>


text:
using namespace IECore;
using namespace std;

static IndexedIO::EntryID g_snapshotsEntry("snapshots");
static IndexedIO::EntryID g_primitiveEntry("primitive");
static IndexedIO::EntryID g_timeEntry("time");

const unsigned int MotionPrimitive::m_ioVersion = 0;
IE_CORE_DEFINEOBJECTTYPEDESCRIPTION( MotionPrimitive );

MotionPrimitive::MotionPrimitive()
{
}

MotionPrimitive::~MotionPrimitive()
{
}

void MotionPrimitive::addSnapshot( float time, PrimitivePtr primitive )
{
	m_snapshots[time] = primitive;
}

void MotionPrimitive::removeSnapshot( float time )
{
	m_snapshots.erase( time );
}

void MotionPrimitive::removeSnapshot( PrimitivePtr primitive )
{
	SnapshotMap::iterator it=m_snapshots.begin();
	while( it!=m_snapshots.end() )
	{
		SnapshotMap::iterator next = it; next++;
		if( it->second==primitive )
		{
			m_snapshots.erase( it );
		}
		it = next;
	}
}

const MotionPrimitive::SnapshotMap &MotionPrimitive::snapshots() const
{
	return m_snapshots;
}

MotionPrimitive::SnapshotMap &MotionPrimitive::snapshots()
{
	return m_snapshots;
}

void MotionPrimitive::render( Renderer *renderer ) const
{
	if( !m_snapshots.size() )
	{
		return;
	}
	if( m_snapshots.size()==1 )
	{
		m_snapshots.begin()->second->render( renderer );
		return;
	}

	TypeId t = m_snapshots.begin()->second->typeId();
	size_t cs = m_snapshots.begin()->second->variableSize( PrimitiveVariable::Constant );
	size_t us = m_snapshots.begin()->second->variableSize( PrimitiveVariable::Uniform );
	size_t vs = m_snapshots.begin()->second->variableSize( PrimitiveVariable::Varying );
	size_t ves = m_snapshots.begin()->second->variableSize( PrimitiveVariable::Vertex );
	size_t fs = m_snapshots.begin()->second->variableSize( PrimitiveVariable::FaceVarying );

	set<float> times;
	for( SnapshotMap::const_iterator it=m_snapshots.begin(); it!=m_snapshots.end(); it++ )
	{
		if( it->second->typeId()!=t )
		{
			throw Exception( "Primitive types do not match." );
		}
		if( it->second->variableSize( PrimitiveVariable::Constant )!=cs ||
			it->second->variableSize( PrimitiveVariable::Uniform )!=us ||
			it->second->variableSize( PrimitiveVariable::Varying )!=vs ||
			it->second->variableSize( PrimitiveVariable::Vertex )!=ves ||
			it->second->variableSize( PrimitiveVariable::FaceVarying )!=fs
		)
		{
			throw Exception( "Primitive variable sizes do not match." );
		}
		times.insert( it->first );
	}
	renderer->motionBegin( times );
		for( SnapshotMap::const_iterator it=m_snapshots.begin(); it!=m_snapshots.end(); it++ )
		{
			it->second->render( renderer );
		}
	renderer->motionEnd();
}

Imath::Box3f MotionPrimitive::bound() const
{
	Imath::Box3f result;
	for( SnapshotMap::const_iterator it=m_snapshots.begin(); it!=m_snapshots.end(); it++ )
	{
		result.extendBy( it->second->bound() );
	}
	return result;
}

////////////////////////////////////////////////////////////////////////////////////////////
// Object interface
////////////////////////////////////////////////////////////////////////////////////////////

void MotionPrimitive::copyFrom( const Object *other, Object::CopyContext *context )
{
	VisibleRenderable::copyFrom( other, context );
	const MotionPrimitive *tOther = static_cast<const MotionPrimitive *>( other );
	m_snapshots.clear();
	for( SnapshotMap::const_iterator it=tOther->m_snapshots.begin(); it!=tOther->m_snapshots.end(); it++ )
	{
		m_snapshots[it->first] = context->copy<Primitive>( it->second );
	}
}

void MotionPrimitive::save( IECore::Object::SaveContext *context ) const
{
	VisibleRenderable::save( context );
	IndexedIOPtr container = context->container( staticTypeName(), m_ioVersion );
	IndexedIOPtr snapshots = container->subdirectory( g_snapshotsEntry, IndexedIO::CreateIfMissing );

	int i = 0;
	for( SnapshotMap::const_iterator it=m_snapshots.begin(); it!=m_snapshots.end(); it++ )
	{
		string is = str( boost::format( "%d" ) % i );
		IndexedIOPtr snapshot = snapshots->subdirectory( is, IndexedIO::CreateIfMissing );
		snapshot->write( g_timeEntry, it->first );
		context->save( it->second, snapshot, g_primitiveEntry );
		i++;
	}
}

void MotionPrimitive::load( IECore::Object::LoadContextPtr context )
{
	VisibleRenderable::load( context );
	unsigned int v = m_ioVersion;
	ConstIndexedIOPtr container = context->container( staticTypeName(), v );
	ConstIndexedIOPtr snapshots = container->subdirectory( g_snapshotsEntry );
	m_snapshots.clear();
	IndexedIO::EntryIDList names;
	snapshots->entryIds( names, IndexedIO::Directory );
	IndexedIO::EntryIDList::const_iterator it;
	for( it=names.begin(); it!=names.end(); it++ )
	{
		ConstIndexedIOPtr snapshot = snapshots->subdirectory( *it );
		float t;
		snapshot->read( g_timeEntry, t );
		m_snapshots[t] = context->load<Primitive>( snapshot, g_primitiveEntry );
	}
}

bool MotionPrimitive::isEqualTo( const Object *other ) const
{
	if( !VisibleRenderable::isEqualTo( other ) )
	{
		return false;
	}
	const MotionPrimitive *tOther = static_cast<const MotionPrimitive *>( other );
	if( tOther->m_snapshots.size()!=m_snapshots.size() )
	{
		return false;
	}
	SnapshotMap::const_iterator tIt = m_snapshots.begin();
	SnapshotMap::const_iterator oIt = tOther->m_snapshots.begin();
	while( tIt!=m_snapshots.end() )
	{
		if( tIt->first!=oIt->first )
		{
			return false;
		}
		if( !tIt->second->isEqualTo( oIt->second ) )
		{
			return false;
		}
		tIt++;
		oIt++;
	}
	return true;
}

void MotionPrimitive::memoryUsage( Object::MemoryAccumulator &a ) const
{
	VisibleRenderable::memoryUsage( a );
	for( SnapshotMap::const_iterator it=m_snapshots.begin(); it!=m_snapshots.end(); it++ )
	{
		a.accumulate( it->second );
	}
}

void MotionPrimitive::hash( MurmurHash &h ) const
{
	VisibleRenderable::hash( h );
	for( SnapshotMap::const_iterator it=m_snapshots.begin(); it!=m_snapshots.end(); it++ )
	{
		h.append( it->first );
		it->second->hash( h );
	}
}


text:
Tutorial on how to create a chat bar that is reusable and efficient that you can easily include in your layout for the apps you create. The design is very flat (no nested layouts) so less cpu rendering which increases app preformance.

Learn more here http://androidbox.me/efficient-reusable-layouts/linearlayout-and-framelayout/

Video Presentation https://youtu.be/wSunuMPGYn8

![alt text](https://github.com/steve1rm/chatbar/blob/master/completedChatBar.png "Chat bar with unread message counter")


text:
using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Drawing;
using MonoTouch.ObjCRuntime;

namespace LMT64
{
    public partial class AnimationDemoViewController : UIViewController
    {
        PointF p0;

        #region Constructors

        // The IntPtr and initWithCoder constructors are required for items that need
        // to be able to be created from a xib rather than from managed code

        public AnimationDemoViewController (IntPtr handle) : base(handle)
        {
            Initialize ();
        }

        [Export("initWithCoder:")]
        public AnimationDemoViewController (NSCoder coder) : base(coder)
        {
            Initialize ();
        }

        public AnimationDemoViewController () : base("AnimationDemoViewController", null)
        {
            Initialize ();
        }

        void Initialize ()
        {
        }

        #endregion

        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();

            // iOS 3.x style animations
            startAnimation.TouchUpInside += delegate {

                p0 = monkeyImageView.Center;

                UIView.BeginAnimations ("slideMonkeyAnimation");

                UIView.SetAnimationDuration(2);
                UIView.SetAnimationCurve(UIViewAnimationCurve.EaseInOut);
                UIView.SetAnimationRepeatCount(2);
                UIView.SetAnimationRepeatAutoreverses(true);
                UIView.SetAnimationDelegate(this);
                UIView.SetAnimationDidStopSelector(new Selector("slideMonkeyStopped:"));

                monkeyImageView.Center = new PointF (UIScreen.MainScreen.Bounds.Right - monkeyImageView.Frame.Width / 2, monkeyImageView.Center.Y);

                UIView.CommitAnimations ();

            };

            // or using new iOS 4+ blocks from MonoTouch
//
//                startAnimation.TouchUpInside += delegate {
//                p0 = monkeyImageView.Center;
//
//                UIView.Animate (2, 0,
//                    UIViewAnimationOptions.CurveEaseInOut | UIViewAnimationOptions.Autoreverse,
//                    () => { monkeyImageView.Center =
//                        new PointF (UIScreen.MainScreen.Bounds.Right - monkeyImageView.Frame.Width / 2,
//                            monkeyImageView.Center.Y);
//                    },
//                    () => { monkeyImageView.Center = p0; }
//                );
//            };

        }

        [Export("slideMonkeyStopped:")]
        void SlideMonkeyStopped ()
        {
            monkeyImageView.Center = p0;
        }
    }
}


text:
<!DOCTYPE html>

	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>MessageToast - sap.m</title>


text:
An interactive exploration of Tilezen's [Vector Tile](https://mapzen.com/projects/vector-tiles/) data.

### Live demo:

https://tangrams.github.io/explorer


text:
package generics;// generics/ErasedTypeEquivalence.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;

public class ErasedTypeEquivalence {
  public static void main(String[] args) {
    Class c1 = new ArrayList<String>().getClass();
    Class c2 = new ArrayList<Integer>().getClass();
    System.out.println(c1 == c2);
  }
}
/* Output:
true
*/


text:
<?php

namespace PhpSsrs\ReportingService2010;

class SetDataDrivenSubscriptionPropertiesResponse
{

  /**
   *
   * @access public
   */
  public function __construct()
  {

  }

}


text:
var express = require('express');
var rooms = require('./routes/rooms');
var projects = require('./routes/projects');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/rpgd');

var db = mongoose.connection;

var startingRoom = {
    name: "Entry",
    description: "you wake up in a silent dark room, slowly your sight comes back and youd discover shimmering candle light. To your left you see a hallway which seems to lead to a brighter place",
    type: "Dungeon",
    actions: [{
        type: "navigateRoom",
        label: "Take the door to the left",
        data: {"roomName":"Hallway"}
    }],
    inventory: []
}

var room2 = {
    name: "Hallway",
    description: "As you enter the hallway b...",
    type: "Dungeon",
    actions: [{
        type: "navigateRoom",
        label: "Go back to the initial room",
        data: {"roomName":"Entry"}
    }],
    inventory: []
}

var user1 = {
    name: "atla",
    bio: "famous rpg coder"
};
var user2 = {
    name: "atla2",
    bio: "famous rpg coder 222"
};

var projects = [{
    name: "Leihwelt reboot 2",
    subtitle: "Yet another try",
    creator: user1,
    contributors: [user1, user2],
    summary: "Deep down the nexus lies ...",
    description: String,
    comments: [{
        text: "This is a comment",
        author: user2,
        date: Date.now()
    }],
    created: Date.now(),
    private: false,
    meta: {
        votes: 12,
        favs: 3
    }
}];

db.collection('projects', function (err, collection) {
    collection.insert(projects, {
        safe: true
    }, function (err, result) {});
});

db.collection('rooms', function (err, collection) {
    collection.insert(rooms, {
        safe: true
    }, function (err, result) {});
});


text:
<?php

declare(strict_types=1);

namespace DoctrineMigrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Create initial schema, designed to mirror old SQLite DIY one.
 */
final class Version20200924213211 extends AbstractMigration
{
    public function getDescription() : string
    {
        return 'Create initial schema';
    }

    public function up(Schema $schema) : void
    {
        $this->addSql('CREATE TABLE packages (id SERIAL PRIMARY KEY, class_name VARCHAR(50) NOT NULL, name VARCHAR(255) NOT NULL, last_committed TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, last_fetched TIMESTAMP(0) WITHOUT TIME ZONE, versions JSON, is_active BOOLEAN NOT NULL, display_name VARCHAR(255))');
        $this->addSql('CREATE INDEX last_committed_idx ON packages (last_committed)');
        $this->addSql('CREATE INDEX last_fetched_idx ON packages (last_fetched)');
        $this->addSql('CREATE UNIQUE INDEX type_and_name_unique ON packages (class_name, name)');
        $this->addSql('CREATE TABLE requests (id SERIAL PRIMARY KEY, ip_address VARCHAR(15) NOT NULL, last_request TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, request_count INT NOT NULL)');
        $this->addSql('CREATE UNIQUE INDEX UNIQ_7B85D65122FFD58C ON requests (ip_address)');
        $this->addSql('CREATE TABLE state (key VARCHAR(50) NOT NULL, value VARCHAR(50) NOT NULL, PRIMARY KEY(key))');

        // Sly actually-a-fixture to maintain compatibility with the previous Sqlite auto setup.
        $this->addSql("INSERT INTO state (key, value) VALUES ('build_required', '')");
    }

    public function down(Schema $schema) : void
    {
        $this->addSql('DROP TABLE packages');
        $this->addSql('DROP TABLE requests');
        $this->addSql('DROP TABLE state');
    }
}


text:
function Assert() {}

Assert.prototype.eq = function(expected, actual, message) {
    console.log(message, expected == actual ? ' PASS ': ' FAIL ', actual);
};

Assert.prototype.isTrue = function(actual, message) {
    console.log(message, actual ? ' PASS ': ' FAIL ', actual);
};

module.exports = new Assert();


text:
package org.webcurator.core.util;

import java.util.Calendar;
import java.util.Date;

/**
 * A set of static utilities that can be reused throughout the WCT.
 * These utilities should be generic functions that manipulate
 * simple objects. More complex functionality should be isolated
 * in the managers.
 *
 * @author bbeaumont
 */
public class Utils {

	/**
	 * Checks if a String is null or space.
	 * @param str The string to test.
	 * @return True if the string is null or whitespace; otherwise false.
	 */
	private static boolean isNullOrWhitespace(String str) {
		return str == null || "".equals(str.trim());
	}

	/**
	 * This method checks if a value has changed between the original
	 * and the new values. This is typically used for testing if a
	 * change in parameter should cause an object to be dirty.
	 * @param originalValue The original value.
	 * @param newValue The new value.
	 * @return true of the value has changed
	 */
	public static boolean hasChanged(Object originalValue, Object newValue) {
		// If they are both null, then it hasn't changed.
		if( originalValue == null && newValue == null) {
			return true;
		}

		// For Strings, we allow null and empty string to be the same.
		if( (originalValue == null ||
			 originalValue instanceof String &&
			 isNullOrWhitespace((String) originalValue)) &&
			(newValue == null ||
			 newValue instanceof String &&
			 isNullOrWhitespace((String) newValue))) {
			return true;
		}

		return originalValue == null && newValue == null ||
		       originalValue != null && originalValue.equals(newValue);
	}

	/**
	 * Clears the time component on a Calendar object. The
	 * passed in Calendar object is updated.
	 * @param cal The calendar object to clear.
	 */
	public static void clearTime(Calendar cal) {
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.clear(Calendar.MINUTE);
		cal.clear(Calendar.SECOND);
		cal.clear(Calendar.MILLISECOND);
	}

	/**
	 * Clears the time on a Date object.
	 * @param dt The input date.
	 * @return A new date with the same date, but with the time cleared.
	 */
	public static Date clearTime(Date dt) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(dt);
		clearTime(cal);
		return cal.getTime();
	}

	/**
	 * Returns a new date at the end of the day of the original
	 * date.
	 * @param dt The date to find the end of day for.
	 * @return A new date representing the end of the day.
	 */
	public static Date endOfDay(Date dt) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(dt);
		clearTime(cal);

		cal.add(Calendar.DAY_OF_MONTH, 1);
		cal.add(Calendar.MILLISECOND, -1);

		return cal.getTime();
	}

	/**
	 * Friendly display of a duration

	 * Format returned is d:hh:mm:ss
	 * with 2 digits for hours/minutes/seconds.
	 *
	 * @param duration Duration in seconds
	 * @return String friendly duration
	 */
	public static String getDDhhmmss(Long duration){
		Long days = duration / 24 / 3600;
		Long rest = duration % (24 * 3600);//duration - 24 * 3600 * days;
		Long hours = rest / 3600;
		rest %= 3600;
		Long minutes = rest / 60;
		rest %= 60;
		Long seconds = rest;

		String sDays = days.toString();

		String sHours = hours.toString();
		if(sHours.length() == 1){
			sHours = "0" + sHours;
		}

		String sMinutes = minutes.toString();
		if(sMinutes.length() == 1){
			sMinutes = "0" + sMinutes;
		}

		String sSeconds = seconds.toString();
		if(sSeconds.length() == 1){
			sSeconds = "0" + sSeconds;
		}

		return sDays + ":" + sHours + ":" + sMinutes + ":" + sSeconds;
	}

}