text:
% Chapter Template

\chapter{Parallel Primitives} % Main chapter title
\label{ch:ParallelPrimitives}

\section{Introduction}

Parallel primitives form the building blocks for implementing parallel algorithms such as radix and merge sorting, determining minimum and maximum values, summing a set of values, to name just a few. This chapter describes two such parallel primitives: a \emph{reduction} and a \emph{scan}.

\emph{Reduction} is a parallel primitive that reduces a set of $n$ values to a single value by applying a binary associative operator $\oplus$ over the set. For example, a sum is an example of an operation that can be implemented as a reduction.

\emph{Scan} is another parallel primitive that takes a set of $n$ values $[a_0, a_1, \cdots, a_{n-1}]$ and applies the binary associative operator $\oplus$ to produce the set $[a_0,(a_0\oplus a_1),\cdots,(a_0\oplus a_1\oplus\cdots\oplus a_{n-1})]$ in the case of an \emph{inclusive scan} or $[i_{\oplus},a_0,(a_0\oplus a_1),\cdots,(a_0\oplus a_1\oplus\cdots\oplus a_{n-2})]$ in the case of an \emph{exclusive scan} where $i_{\oplus}$ is the identity of the set such that it does not effect the result of any value in the set when the $\oplus$ operator is applied. For example, $i_{\oplus}$ is a $0$ for addition and a $1$ for multiplication \parencite{35_blelloch_1989, 23_wilt_2013}.

\section{Reduction}
\label{sec:Reduction}

A parallel reduction is a useful building block for various GPU algorithms such as finding minimum or maximum values in a set, or summing a set of data in parallel. The parallel reduction technique described here is derived from \emph{The CUDA Handbook} \parencite{23_wilt_2013} and \emph{DirectCompute Optimizations and Best Practices} \parencite{29_young_2010}.

The parallel reduction technique described here is a 2-pass reduction. In the first pass, a maximum of $p$ thread groups are dispatched. Each thread group reduces to a single value that is written to global memory. The maximum number of thread groups ($p$) should be chosen so that only a single thread group is required to perform the final reduction in the second pass. The number of threads per thread group ($t$) should be chosen so that the reduction can be performed using group shared memory without exceeding group shared memory limits (Section \ref{sec:Thread-Dispatch}). The second pass dispatches a single thread group that reduces the remaining $p$ values into a single value.

The reduction requires two passes because the first pass writes a maximum of $p$ values to global memory. Since there are no synchronization primitives for global memory access within a dispatch, invoking a second dispatch is the only way to guarantee that all of the thread groups from the first pass have finished writing their value to global memory.

There are several methods that can be used to implement a reduction \parencite{23_wilt_2013}.

\begin{enumerate}
\item{Serial}
\item{Pair-wise Log-Step}
\item{Interleaved Log-Step}
\end{enumerate}

In simplified terms, a reduction applies a binary associative operator $\oplus$ over a data set of $n$ values reducing to a single value.

\begin{equation}
\sum_{i=0}^{n}a_i = a_0 \oplus a_1 \oplus a_2 \oplus a_3 \cdots \oplus a_n
\label{eqn:reduction}
\end{equation}

As the name implies, a \emph{serial} reduction (Figure \ref{fig:Serial_Reduction}) applies the binary operator to two operands per pass and requires $(n-1)$ passes to reduce to a single value. This technique is commonly used when the reduction is performed on a single thread of execution.

\begin{figure}[H]
\centering
\includegraphics[width=0.5\textwidth]{Figures/Serial_Reduction}
\decoRule
\caption{Serial reduction applied over an array of eight values.}
\label{fig:Serial_Reduction}
\end{figure}

\begin{equation}
((((((( a_0 \oplus a_1 ) \oplus a_2 ) \oplus a_3 ) \oplus a_4 ) \oplus a_5 ) \oplus a_6 ) \oplus a_7 )
\label{eqn:Serial_Reduction}
\end{equation}

The \emph{pair-wise} log-step reduction is performed in $\mathcal{O}(\log_{2}n)$ steps. This method performs poorly on the GPU because when a single thread accesses adjacent memory locations in global memory, uncoalesced memory transactions will occur. As mentioned in Section \ref{sec:Coalesced_Access_to_Global_Memory} coalescing will occur when the k\textsuperscript{th} thread in a warp accesses the k\textsuperscript{th} word in a memory segment. In this case, the k\textsuperscript{th} thread in a warp is accessing the 2k\textsuperscript{th} word in a memory segment causing uncoalasced memory transactions to occur.

\emph{Pair-wise} log-step reduction will also cause 2-way bank conflicts in shared memory to occur when this access pattern is used.

\begin{figure}[H]
\centering
\includegraphics[width=0.5\textwidth]{Figures/Pairwise_LogStep_Reduction}
\decoRule
\caption{Pair-wise log-step reduction. This method does not make optimal use of memory access patterns in GPU memory.}
\label{fig:Pairwise_LogStep_Reduction}
\end{figure}

\begin{equation}
( ( (a_0 \oplus a_1) \oplus ( a_2 \oplus a_3 ) ) \oplus ( ( a_4 \oplus a_5 ) \oplus ( a_6 \oplus a_7 ) ) )
\label{eqn:Pairwise-LogStep-Reduction}
\end{equation}

The log-step reduction algorithm performs best when each thread accesses global memory by interleaving addresses by a multiple of $(t\times p)$ where $t$ is the number of threads per thread group and $p$ is the number of thread groups in the dispatch.

The \emph{interleaved} log-step reduction (Figure \ref{fig:Interleaved_LogStep_Reduction}) performs better than the \emph{pair-wise} reduction because bank conflicts are avoided when the addresses are accessed in an interleaved pattern (Figure \ref{fig:Interleaved_LogStep_Reduction_Shared_Memory_Access_Pattern}).

\begin{figure}[H]
\centering
\includegraphics[width=0.5\textwidth]{Figures/Interleaved_LogStep_Reduction}
\decoRule
\caption{Interleaved log-step reduction. Accessing both global and shared memory is optimized.}
\label{fig:Interleaved_LogStep_Reduction}
\end{figure}

\begin{equation}
( ( (a_0 \oplus a_4) \oplus ( a_1 \oplus a_5 ) ) \oplus ( ( a_2 \oplus a_6 ) \oplus ( a_3 \oplus a_7 ) ) )
\label{eqn:Interleaved-LogStep-Reduction}
\end{equation}

\begin{figure}[h]
\centering
\includegraphics[width=\textwidth]{Figures/Interleaved_LogStep_Reduction_Shared_Memory_Access_Pattern}
\decoRule
\caption{Bank conflicts are avoided when using an interleaved access pattern.}
\label{fig:Interleaved_LogStep_Reduction_Shared_Memory_Access_Pattern}
\end{figure}

As previously mentioned, the parallel reduction algorithm operates in two passes. The first pass executes a dispatch of a maximum of $p$ thread groups. Each thread group consists of $t$ threads. In the first pass, each thread will reduce $n/(t \times p)$  values where $n$ is the number of values to be reduced. Each thread writes its reduced value to group shared memory. The reduction continues by halving the number of active threads and reducing the two values at $tid$ and $tid+(t/2^i)$ where $tid$ is the thread index within the thread group, $t$ is the number of threads in the thread group, and $i$ is the current iteration of the reduction. The reduction step is repeated until $\floor{t/2^i} < 1$. Algorithm \ref{alg:Log-Step-Reduction} shows the pseudo code for the interleaved log-step reduction function.

\begin{algorithm}[h]
\caption{Interleaved log-step parallel reduction.}
\label{alg:Log-Step-Reduction}
\begin{algorithmic}[1]
\Require $x$ is a list of $n$ input values in group shared memory.
\Require $y$ stores the result of the reduction in global memory.
\Require $gid$ is the index of the current thread group.
\Require $tid$ is the index of the thread within the thread group.
\Require $p$ is the number of thread groups.
\Require $t$ is the number of threads per thread group.
\Function{LogStepReduction}{$gid$,$tid$,$\oplus$}
\State $k \gets t/2$
\While{$k > 0$}
\If{$tid < k$}
\State $x[tid] \gets x[tid] \oplus x[tid+k]$
\EndIf
\State $k \gets \floor{k/2}$
\EndWhile
\If{$tid = 0$}
\State $y[gid] \gets x[tid]$
\EndIf
\EndFunction
\end{algorithmic}
\end{algorithm}

It is interesting to note that the \emph{LogStepReduction} function shown in Algorithm \ref{alg:Log-Step-Reduction} does not show the group shared memory barrier that is required to guarantee all threads in a thread group have finished reading or writing to shared memory. The group shared memory barriers should be inserted after line 6 in Algorithm \ref{alg:Log-Step-Reduction}.

The \emph{LogStepReduction} function shown in Algorithm \ref{alg:Log-Step-Reduction} can be optimized in the case the thread count ($k$) is less than or equal to the size of a warp. In this case, when $k$ is 32 or less then the threads in the thread group execute in warp-synchronise lock-step and group shared memory barriers are no longer required. According to Young, unrolling the last warp and removing group shared memory barrier results in a 45\% increase in performance \parencite{29_young_2010}. Algorithm \ref{alg:Log-Step-Reduction-WS} shows the \emph{LogStepReduction} function with the warp-synchronous optimization applied. In this case the group shared memory barrier is added to the algorithm for clarity.

\begin{algorithm}[H]
\caption{Interleaved log-step parallel reduction with warp-synchronous optimization.}
\label{alg:Log-Step-Reduction-WS}
\begin{algorithmic}[1]
\Require $x$ is a list of $n$ values in group shared memory.
\Require $y$ stores the result of the reduction in global memory.
\Require $gid$ is the index of the current thread group.
\Require $tid$ is the index of the thread within the thread group.
\Require $p$ is the number of thread groups.
\Require $t$ is the number of threads per thread group.
\Function{LogStepReduction}{$gid$,$tid$,$\oplus$}
\State $k \gets t/2$
\While{$k > 32$}
\If{$tid < k$}
\State $x[tid] \gets x[tid] \oplus x[tid+k]$
\EndIf
\State \Call{GroupSharedMemoryBarrier}{}
\State $k \gets \floor{k/2}$
\EndWhile
\If{$tid < 32$}
\While{$k > 0$}
\State $x[tid] \gets x[tid] \oplus x[tid+k]$
\State $k \gets \floor{k/2}$
\EndWhile
\EndIf
\If{$tid = 0$}
\State $y[gid] \gets x[tid]$
\EndIf
\EndFunction
\end{algorithmic}
\end{algorithm}

The result of the first pass is $p$ values written to global memory, where $p$ is the number of thread groups dispatched in the first pass. In the second pass, a single thread group is executed to reduce the final $p$ values from the first pass. The algorithm for the second pass is identical to that of the first pass. The only difference between the first and second passes of the reduction algorithm is the number of resulting values.

\section{Scan}
\label{sec:Scan}

According to Blelloch, a scan operation takes a binary operator $\oplus$ with the identity $i_{\oplus}$ and an ordered set $[a_0,a_1,\cdots,a_{n-1}]$ of $n$ elements and returns the ordered set $[i_{\oplus},a_0,(a_0\oplus a_1),\cdots,(a_0\oplus a_1\oplus\cdots\oplus a_{n-2})]$ where $i_{\oplus}$ is the identity value for the $\oplus$ operator ($0$ for addition and $1$ for multiplication) \parencite{35_blelloch_1989}.

If the $\oplus$ operator is addition then the scan operation applied to the array

\begin{equation}
[2, 1, 2, 3, 4, 8, 13, 21]
\end{equation}

would produce

\begin{equation}
[0, 2, 3, 5, 8, 12, 20, 33]
\end{equation}

The pseudo code for a sequential scan is shown in Algorithm \ref{alg:Sequential_Scan}.

\begin{algorithm}[h]
\caption{Sequential scan.}
\label{alg:Sequential_Scan}
\begin{algorithmic}[1]
\Require $x$ is a list of $n$ values.
\Ensure $y$ contains the result of the scan operation.
\Function{SequentialScan}{$x$,$i_{\oplus}$,$\oplus$}
\State $y[0] \gets i_{\oplus}$
\For{ $i=1$ to $n$ }
\State $y[i] \gets y[i-1]\oplus x[i-1]$
\EndFor
\State \Return $y$
\EndFunction
\end{algorithmic}
\end{algorithm}

The sequential scan algorithm operates in $\mathcal{O}(n)$ time in a single thread of execution. The algorithm can be parallelized to operate in $\mathcal{O}(\log_2 n)$ steps. For each step $i$ of the parallel scan algorithm, if the thread id ($tid$) of the current thread is greater than $2^i$ then the value of $x[tid]$ and $x[tid-2^i]$ is summed and stores the result at $x[tid]$.

The pseudo code for the parallel scan is shown in Algorithm \ref{alg:Parallel_Scan}. This algorithm is based on the naive parallel scan operation presented by Mark Harris, Shubhabrata Sengupta, and John D. Owens in chapter 39 of \emph{GPU Gems 3} \parencite{34_harris_sengupta_owens_2008}.

\begin{algorithm}[h]
\caption{Parallel scan.}
\label{alg:Parallel_Scan}
\begin{algorithmic}[1]
\Require $x$ is a list of $n$ values.
\Require $I_{\oplus}$ is the identity.
\Require $tid$ is the ID of the thread in the thread group.
\Ensure $y$ contains the result of the scan operation.
\Function{ParallelScan}{$x$,$tid$,$i_{\oplus}$,$\oplus$}
\If{ $tid = 0$ }
\State $y[0] \gets i_{\oplus}$
\Else
\State $y[tid] \gets x[tid-1]$
\EndIf
\For{ $i \gets 0$ to $\log_2{n}-1$}
\State $t \gets y[tid]$
\If{ $tid > 2^i$ }
\State $t \gets t \oplus y[tid-2^i]$
\EndIf
\State $y[tid] \gets t$
\EndFor
\State \Return $y$
\EndFunction
\end{algorithmic}
\end{algorithm}

In the first step, the output array $y$ is primed by copying all of the elements from the input array ($x$) to the output array ($y$) shifted one index to the right. A loop is iterated $log_2{n}$ times and for each thread whose thread ID is greater than $2^i$ where $i$ is the loop iteration counter, the sum of $y[tid] \oplus y[tid-2^i]$ is computed and stored at $y[tid]$ where $tid$ is the ID of the thread in the thread group. Figure \ref{fig:Parallel-Scan} shows a graphical implementation of performing the parallel scan over a set of eight values. Each thread operates on a single index in the set.

\begin{figure}[h]
\centering
\includegraphics[width=\textwidth]{Figures/Parallel-Scan}
\decoRule
\caption{Parallel scan. For each iteration $i$ of the parallel scan, each thread $t$ larger than $2^i$ computes $x[t] \oplus x[t-2^i]$ and stores the result at index $t$.}
\label{fig:Parallel-Scan}
\end{figure}


text:
<?php

namespace DCarbone\PHPFHIRGenerated\R4\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRSpecimen;

use PHPUnit\Framework\TestCase;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSpecimen\FHIRSpecimenProcessing;

/**
 * Class FHIRSpecimenProcessingTest
 * @package \DCarbone\PHPFHIRGenerated\R4\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRSpecimen
 */
class FHIRSpecimenProcessingTest extends TestCase
{
    public function testCanConstructTypeNoArgs()
    {
        $type = new FHIRSpecimenProcessing();
        $this->assertInstanceOf('\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSpecimen\FHIRSpecimenProcessing', $type);
    }
}

redpajama_set_name: RedPajamaGithub


text:
import pygame
from pygame.locals import *
import sys
from game import *

FPS = 30 #frames per second
MOVE_TIME = 500 #moves will be displayed for 1 second
SCREEN_SIZE = (500, 500)

def main():

	pygame.init()

	screen = pygame.display.set_mode(SCREEN_SIZE)
	clock = pygame.time.Clock()
	pygame.display.set_caption("PyMemory")

	game = Game(SCREEN_SIZE[0], SCREEN_SIZE[1])
	game.draw_all(screen)
	game.generate_moves()
	game.update_score(screen)
	game.draw_credits(screen)

	elapsed = 0
	i = 0
	last = 0
	drawn = False
	pause = False

	while 1:
		elapsed += clock.tick(FPS)

		if game.current_player == 0: #CPU turn
			if pause == False:
				if drawn == False:
					game.delete_cpu_move(screen, game.cpu_moves[last])
					game.draw_cpu_move(screen, game.cpu_moves[i])
					drawn = True
				if elapsed >= MOVE_TIME:
					last = i
					i += 1
					if i > len(game.cpu_moves) - 1:
						game.toggle_turn()
					game.delete_cpu_move(screen, game.cpu_moves[last])
					elapsed = 0
					drawn = False
					pause = True
			else:
				if elapsed >= MOVE_TIME:
					pause = False
					elapsed = 0

			pygame.event.clear([pygame.KEYDOWN, pygame.KEYUP]) #ignore events when clicking during CPU turn
			for event in pygame.event.get():
				if event.type == pygame.QUIT:
					sys.exit(0)

		elif game.current_player == 1: #Player turn
			for event in pygame.event.get():
				if event.type == pygame.QUIT:
					sys.exit(0)
				elif event.type == pygame.KEYDOWN:
					if event.key == K_ESCAPE:
						sys.exit(0)
					elif event.key == K_UP:
						game.draw_to(screen, 0)
					elif event.key == K_RIGHT:
						game.draw_to(screen, 1)
					elif event.key == K_DOWN:
						game.draw_to(screen, 2)
					elif event.key == K_LEFT:
						game.draw_to(screen, 3)
				elif event.type == pygame.KEYUP:
					if event.key == K_UP:
						game.draw_from(screen, 0)
					elif event.key == K_RIGHT:
						game.draw_from(screen, 1)
					elif event.key == K_DOWN:
						game.draw_from(screen, 2)
					elif event.key == K_LEFT:
						game.draw_from(screen, 3)

					if len(game.cpu_moves) == len(game.player_moves):
						game.check_solution()
						game.generate_moves()
						game.toggle_turn()
						game.update_score(screen)
						elapsed = 0
						i = 0
						last = 0
						drawn = False

		pygame.display.flip()

if __name__== "__main__":
    main()


text:
import rospy
from task_processor import TaskProcessor
from riptide_msgs.msg import GateData, BoundingBox
from riptide_vision import RiptideVision
from geometry_msgs.msg import Point
import time
import lib

# Class GateProcessor
# Inherits from TaskProcessor
class GateProcessor(TaskProcessor):
    def __init__(self):
        gate_pub = rospy.Publisher("/task/gate", GateData, queue_size=1)
        TaskProcessor.__init__(self, gate_pub)

    # Normal Processing
    def Process(self, image, debug_pub=None):
        gate_msg = GateData()
        gate_msg.left_pole_visible = False
        gate_msg.right_pole_visible = False
        pos = None
        bbox = None

        # Process the image
        t = time.time()
        response, _ = lib.find_gate(image)
        print "'New:' Found gate in %2.2f" % (time.time() - t)

        # Package data (if there is any)
        if (len(response) > 0):
            x_min = response[3]
            y_min = response[4]
            x_max = response[5]
            y_max = response[6]
            x_center = response[9]
            y_center = response[10]
            cam_center_x = response[11]
            cam_center_y = response[12]

            # Adjust all X and Y positions to be relative to the center of the camera frame
            # Also maintain the axes convention in here (X is pos. to the right, Y is pos. down)
            x_min = x_min - cam_center_x
            x_max = x_max - cam_center_x
            x_center = x_center - cam_center_x

            y_min = y_min - cam_center_y
            y_max = y_max - cam_center_y
            y_center = y_center - cam_center_y

            # pos = the middle of the gate in vehicle coordinate frame
            pos = Point()
            pos.x = 0
            pos.y = -x_center # Cam frame x negated
            pos.z = -y_center # Cam frame y negated

            bbox = BoundingBox()
            bbox.top_left = Point(0, -x_min, -y_min)
            bbox.bottom_right = Point(0, -x_max, -y_max)

            gate_msg.left_pole_visible = response[0]
            gate_msg.right_pole_visible = response[1]

        if debug_pub is not None:
            # Compress debug image
            debug_img = RiptideVision().detect_gate_vis(image, response)
            self.publish_debug_image(debug_img, debug_pub)

        # Publish data
        self.task_pub.publish(gate_msg)

        return pos, bbox


text:
namespace MyClinic.Model
{
    public class Diagnosis
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Code { get; set; }
    }
}


text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2017 The PIVX developers
// Copyright (c) 2018-2019 The Ion developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_POW_H
#define BITCOIN_POW_H

#include <stdint.h>

class CBlockHeader;
class CBlockIndex;
class uint256;
class arith_uint256;

// Define difficulty retarget algorithms
enum DiffMode {
    DIFF_DEFAULT = 0, // Default to invalid 0
    DIFF_BTC = 1,     // Retarget every x blocks (Bitcoin style)
    DIFF_MIDAS = 2,     // Retarget using MIDAS algo
    DIFF_DGW = 3,     // Retarget using Dark Gravity Wave v3
};

unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader* pblock);

/** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */
bool CheckProofOfWork(uint256 hash, unsigned int nBits);
uint256 GetBlockProof(const CBlockIndex& block);

#endif // BITCOIN_POW_H


text:
package br.org.itai.amqpservice.convertion.implementation.json;

import java.io.IOException;

import org.codehaus.jackson.map.ObjectMapper;

import br.org.itai.amqpservice.convertion.interfaces.Converter;

public class JsonConverter implements Converter {

	private ObjectMapper mapper;

	public JsonConverter(ObjectMapper mapper) {
		this.mapper = mapper;
	}

	public String marshall(Object object) throws IOException {
		return mapper.writeValueAsString(object);
	}

	public <T> T unmarshall(String message, Class<T> returnType)
			throws IOException {
		return mapper.readValue(message, returnType);
	}

}


text:
// $Id: CommentActionDebug.java 99 2005-02-28 21:37:53Z blindsey $

package com.blnz.xsl.tr;

import com.blnz.xsl.om.*;

/**
 * <xsl:comment
 */
class CommentActionDebug extends CommentAction
{

    private ActionDebugTarget _target;
    private String _templateIDHook;
    private Node _sheetNode;

    CommentActionDebug(
                       ActionDebugTarget target,
                       Node sheetNode,
                       String templateIDHook,
                       Action content)
    {
        super(content);

        _target = target;
        _sheetNode = sheetNode;
        _templateIDHook = templateIDHook;

    }

    /**
     *
     */
    public void invoke(ProcessContext context, Node sourceNode,
                       Result result)
        throws XSLException
    {
        _target.startAction(_sheetNode, sourceNode, this);

        super.invoke(context, sourceNode, result);

        _target.endAction(_sheetNode, sourceNode, this);
    }

}


text:
package com.github.q115.goalie_android.modelsTest;

import com.github.q115.goalie_android.models.Goal;

import org.junit.Test;

import test_util.ModelUtil;

import static com.github.q115.goalie_android.models.Goal.GoalCompleteResult.Failed;
import static com.github.q115.goalie_android.models.Goal.GoalCompleteResult.Success;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class GoalTest {
    @Test
    public void defaultConstructor() throws Exception {
        Goal goal = new Goal();
        assertEquals("", goal.guid);
        assertEquals("", goal.title);
        assertEquals("", goal.encouragement);
        assertEquals(0, goal.startDate);
        assertEquals(0, goal.endDate);
        assertEquals(0, goal.wager);
        assertEquals(Goal.GoalCompleteResult.None, goal.goalCompleteResult);
    }

    @Test
    public void initConstructor1() throws Exception {
        Goal goal = new Goal("guid", "createdByUsername", "title", 111, 999, 100, "encouragement",
                Success, "referee", System.currentTimeMillis());
        Goal goalTest = new Goal();
        goalTest.guid = "guid";
        goalTest.createdByUsername = "createdByUsername";
        goalTest.title = "title";
        goalTest.startDate = 111;
        goalTest.endDate = 999;
        goalTest.wager = 100;
        goalTest.referee = "referee";
        goalTest.encouragement = "encouragement";
        goalTest.goalCompleteResult = Success;
        assertTrue(ModelUtil.isGoalEqual(goal, goalTest));
    }

    @Test
    public void initConstructor2() throws Exception {
        Goal goal = new Goal("newguid", Failed);
        Goal goalTest = new Goal();
        goalTest.guid = "newguid";
        goalTest.goalCompleteResult = Failed;
        assertTrue(ModelUtil.isGoalEqual(goal, goalTest));
    }
}


text:
package com.opengamma.strata.math.impl.minimization;

import java.util.function.Function;

/**
 * Interface for classes that extends the functionality of {@link Minimizer} by providing a method that takes a gradient function.
 * @param <F> The type of the function to minimize
 * @param <G> The type of the gradient function
 * @param <S> The type of the start position of the minimization
 */
public interface MinimizerWithGradient<F extends Function<S, ?>, G extends Function<S, ?>, S> extends Minimizer<F, S> {

  /**
   * @param function The function to minimize, not null
   * @param gradient The gradient function, not null
   * @param startPosition The start position, not null
   * @return The minimum
   */
  public abstract S minimize(F function, G gradient, S startPosition);

}


text:
'use strict';
/**
 * UserController
 *
 * @description :: Server-side logic for managing users
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

/**
 * res.negotiate() - является функцией, которая проверяет предоставленную ошибку (err) и
 * определяет соответствующее поведение обработки ошибок с помощью свойства status errors и
 * перенаправляет его в один из следующих ответов в словаре res: res.badRequest () [400 ошибок],
 * res.forbidden () [403 ошибки], res.notFound () [404 ошибки] или res.serverError () [500 ошибок].
 */
//var Emailaddresses = require('machinepack-emailaddresses');
const Passwords = require('machinepack-passwords');
const Gravatar = require('machinepack-gravatar');
const _ = require('lodash');
const Email = require('machinepack-email');
const ldap = require('ldapjs');
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const moment = require('moment');
moment.locale('ru');
const error = {
  date: moment().format('LLLL'),
};
//var URI = require('urijs');
//const URITemplate = require('urijs/src/URITemplate');
let count = 5;

module.exports = {
  /**
   * Авторизация. Проверка логина и пароля.
   *
   * @param req
   * @param res
   */
  login: function (req, res) {
    User.findOne({
      or: [
        {email: req.param('email')},
        {login: req.param('email')}
      ]
    }, function foundUser(err, user) {

      // console.log('user', user);
      if (err) return res.negotiate(err);
      if (!user) return res.notFound();
      Passwords.checkPassword({
        passwordAttempt: req.param('password'), encryptedPassword: user.encryptedPassword
      }).exec({
        error: function (err) {
          // console.log('err',err);
          return res.negotiate(err);
        },
        incorrect: function () {
          // console.log('NO');
          return res.notFound();
        },
        success: function () {
          if (user.deleted) {
            return res.forbidden("Ваша учетная запись удалена. " +
              "Перейдите на страницу 'Восстановить профиль'.");
          }
          if (!user.action) {
            return res.forbidden("Ваша учетная запись заблокирована, " +
              "пожалуйста свяжитесь с администратором: " + sails.config.admin.email);
          }
          console.log('Вход в систему: ', error.date + ', ' + user.lastName + ' ' + user.firstName + ' ' + user.patronymicName + ', ' + user.email);
          req.session.me = user.id;
          //req.session.admin = user.admin;
          //req.session.kadr = 11;
          //req.session.me = user;
          return res.ok();
        }
      });
    });
  },

  /**
   * Авторизация LDAP. Проверка логина и пароля.
   *
   * @param req - запрос от клиента к серверу
   * @param res - ответ сервера клиенту
   */
  loginLDAP: function (req, res) {
    User.findOne({
      or: [
        {email: req.param('email')},
        {login: req.param('email')}
      ]
    }).exec((err, user) => {
      if (err) return res.negotiate(err);
      if (!user) return res.notFound('Пользователь не найден.');

      if (user.deleted) {
        return res.forbidden("Ваша учетная запись удалена. " +
          "Перейдите на страницу 'Восстановить профиль'.");
      }
      if (!user.action) {
        return res.forbidden("Ваша учетная запись заблокирована, " +
          "пожалуйста свяжитесь с администратором: " + sails.config.admin.email);
      }

      const clientLDAP = ldap.createClient({
        url: sails.config.ldap.uri
      });

      var opts = {
        scope: 'sub',
        filter: '(sAMAccountName=' + user.login + ')',
        attributes: sails.config.ldap.attributes,
        reconnect: false
        //paged: true,
        //sizeLimit: 50
        //idleTimeout: 3000
      };

      /**
       * Соединение с сервером LDAP
       */
      clientLDAP.bind(user.login + '@' + sails.config.admin.company, req.param('password'), function (err) {
        if (err) {
          console.log('LDAP ошибка входа: ', err);
          clientLDAP.unbind(function () {
            clientLDAP.destroy();
          });
          --count;
          if (+count < 0) return res.forbidden('Аккаунт заблокирован! Обращайтесь к системному администратору или через 10 мин. блокировка будет снята автоматически.');
          switch (+count) {
            case 1:
              word = 'попытка';
              break;
            case 0:
              word = 'попыток';
              break;
            default:
              var word = 'попытки';
          }
          return res.forbidden('Не верный логин или пароль. У вас осталось ' + count + ' ' + word + '.');
        }
        clientLDAP.search(sails.config.ldap.dn, opts, function (err, ldapUser) {
          if (err) {
            console.log('LDAP ошибка поиска: ', err);
            return res.negotiate(err);
          }

          ldapUser.on('searchEntry', function (entry) {
            console.log('Вход в систему: ' + new Date() + ', ' + JSON.stringify(entry.object.displayName + ', ' + entry.object.department + ', ' + entry.object.title + ', ' + entry.object.telephoneNumber + ', ' + entry.object.mail + ', ' + entry.object.physicalDeliveryOfficeName + ', Руководитель: ' + entry.object.manager));
            count = 5;
          });

          //ldapUser.on('searchReference', function (referral) {
          //    console.log('referral: ' + referral.uris.join());
          //});

          ldapUser.on('error', function (err) {
            //if (err) return res.forbidden('Ошибка поиска в соединение LDAP: ' + err.message);
            console.warn('LDAP connection failed, but fear not, it will reconnect No', err);
          });

          ldapUser.on('end', function (result) {
            if (result.status == 0) {
              req.session.me = user.id;
              clientLDAP.unbind(function () {
                clientLDAP.destroy();
              });
              return res.ok();
            }
            return res.forbidden(result.errorMessage);
          });
        });
      });
    });
  },

  /**
   * Поиск пользователей по LDAP
   * @param req
   * @param res
   */
  searchLDAP: function (req, res) {
    console.log('Поиск пользователя в LDAP: ', req.param('name'));

    const clientSearchLDAP = ldap.createClient({
      url: sails.config.ldap.uri
    });
    let opts = {
      scope: 'sub',
      filter: '(displayName=' + req.param('name') + '*)',
      //filter: '(mail=apetrov@landata.ru)',
      //filter: '(sAMAccountName=' + user.login + ')',
      attributes: sails.config.ldap.attributes,
      reconnect: false
      //paged: true,
      //sizeLimit: 50
    };
    /**
     * Соединение с сервером LDAP
     */
    clientSearchLDAP.bind(sails.config.ldap.username, sails.config.ldap.password, function (err) {
      if (err) {
        console.log('searchLDAP ошибка входа: ', err);
        clientSearchLDAP.unbind(function () {
          clientSearchLDAP.destroy();
        });

        //--count;
        //if (+count < 0)  return res.forbidden('Аккаунт заблокирован! Обращайтесь к системному администратору.');
        //switch (+count) {
        //    case 1:
        //        word = 'попытка';
        //        break;
        //    case 0:
        //        word = 'попыток';
        //        break;
        //    default:
        //        var word = 'попытки';
        //}
        return res.forbidden('searchLDAP: Не верный логин или пароль. ');
      }
      var userAr = [];

      /**
       * Поиск по dn
       */
      clientSearchLDAP.search(sails.config.ldap.dn, opts, function (err, ldapUser) {
        if (err) {
          console.log('searchLDAP ошибка поиска: ', err);
          return res.negotiate(err);
        }
        ldapUser.on('searchEntry', function (entry) {
          //console.log('entry: ' + JSON.stringify(entry.object));
          userAr.push(entry.object);
        });

        ldapUser.on('error', function (err) {
          console.error('ОШибка-222: ' + err.message);
        });

        ldapUser.on('end', function (result) {
          if (result.status == 0) {
            if (!userAr.length) {
              clientSearchLDAP.unbind(function () {
                clientSearchLDAP.destroy();
              });
              return res.notFound('Нет таких!');
            }
            clientSearchLDAP.unbind(function () {
              clientSearchLDAP.destroy();
            });
            return res.ok(userAr);
          }
          return res.forbidden(result.errorMessage);
        });

      });
    });

  },

  /**
   * Регистрация нового пользователя.
   */
  signup: function (req, res) {
    Passwords.encryptPassword({
      password: req.param('password'), difficulty: 10
    }).exec({
      error: function (err) {
        return res.negotiate(err);
      },
      success: function (encryptedPassword) {
        Gravatar.getImageUrl({
          emailAddress: req.param('email')
        }).exec({
          error: function (err) {
            return res.negotiate(err);
          },
          success: function (gravatarUrl) {
            User.find({login: req.param('login')}).exec((err, findUsers) => {
              if (err) return res.redirect('/');
              console.log('findUsers1', findUsers);
              if (findUsers.length) return res.loginInUse();

              User.find({email: req.param('email')}).exec((err, findUsers) => {
                if (err) return res.redirect('/');
                console.log('findUsers2', findUsers);
                if (findUsers.length) return res.emailAddressInUse();

                let potentiallyCorrectedEmail;
                try {
                  potentiallyCorrectedEmail = EmailService.validateInternalEmailAddress({
                    emailAddress: req.param('email') // e.g. 'mikermcneil@gmail.com'
                  });
                }
                catch (err) {
                  if (err.code === 'notInternal') {
                    return res.badRequest('Failed to create account.  The specified email address does not seem to be from Greaseworthy Enterprises.');
                  }
                  else {
                    return res.serverError(err);
                  }
                }

                User.create({
                    login: req.param('login'),
                    email: potentiallyCorrectedEmail,
                    firstName: req.param('firstName'),
                    lastName: req.param('lastName'),
                    patronymicName: req.param('patronymicName'),
                    encryptedPassword: encryptedPassword,
                    birthday: req.param('birthday'),
                    contacts: req.param('contacts'),
                    subdivision: req.param('subdivision'),
                    position: req.param('position'),
                    pfr: req.param('pfr'),
                    dateInWork: req.param('dateInWork'),
                    lastLoggedIn: new Date(),
                    gravatarUrl: gravatarUrl,
                    avatar: req.param('avatar'),
                    room: req.param('room')
                  },
                  function userCreated(err, newUser) {
                    if (err) {
                      console.log('err:', err);
                      if (err.invalidAttributes && err.invalidAttributes.email && err.invalidAttributes.email[0] && err.invalidAttributes.email[0].rule === 'unique') {
                        return res.emailAddressInUse();
                      }
                      if (err.invalidAttributes && err.invalidAttributes.login && err.invalidAttributes.login[0] && err.invalidAttributes.login[0].rule === 'unique') {
                        console.log('err.invalidAttributes: ', err.invalidAttributes);
                        return res.loginInUse();
                      }
                      return res.negotiate(err);
                    }

                    EmailService.sendWelcomeEmail({
                      emailAddress: potentiallyCorrectedEmail,
                      firstName: req.param('firstName'), // e.g. 'Mike'
                      apiKey: sails.config.mailgun.apiKey,
                      domain: sails.config.mailgun.domain
                    }, function (err) {
                      if (err) {
                        return res.serverError(err);
                      }

                      // It worked!  The welcome email was sent.
                      req.session.me = newUser.id;
                      return res.json(newUser);

                    });

                  });
              });
            });
          }
        });
      }
    });
  },

  /**
   * Создать нового пользователя
   * @param req
   * @param res
   */
  createUser: function (req, res) {
    if (!req.session.me) return res.view('public/header', {layout: 'homepage'});

    if (!_.isString(req.param('lastName'))) {
      return res.badRequest('Фамилия не заполнена.');
    }
    if (!_.isString(req.param('firstName'))) {
      return res.badRequest('Имя не заполнено.');
    }
    // if (!_.isString(req.param('patronymicName'))) {
    //     return res.badRequest('Отчество не заполнено.');
    // }
    if (!_.isString(req.param('login'))) {
      return res.badRequest('Логин не заполнен.');
    }
    if (!_.isString(req.param('email'))) {
      return res.badRequest('Email не заполнен.');
    }

    // if (req.param('patronymicName').length < 2 || req.param('patronymicName').length > 15) {
    //     return res.badRequest('Отчество должно быть от 2 до 15 знаков!');
    // }
    if (req.param('firstName').length < 2 || req.param('firstName').length > 15) {
      return res.badRequest('Имя должно быть от 2 до 15 знаков!');
    }
    if (req.param('lastName').length < 2 || req.param('lastName').length > 15) {
      return res.badRequest('Фамилия должна быть от 2 до 15 знаков!');
    }

    Passwords.encryptPassword({
      password: req.param('password'), difficulty: 10
    }).exec({
      error: function (err) {
        return res.negotiate(err);
      },
      success: function (encryptedPassword) {

        /**
         * Поднимаем все первые буквы имени в верхний регистр
         */
        let firstName = req.param('firstName')
          .split(' ')
          .map(function (el) {
            return el.charAt(0).toUpperCase() + el.slice(1);
          })
          .join(' ');

        let lastName = req.param('lastName')
          .split(' ')
          .map(function (el) {
            return el.charAt(0).toUpperCase() + el.slice(1);
          })
          .join(' ');
        let patronymicName = '';

        if (_.isString(req.param('patronymicName'))) {
          patronymicName = req.param('patronymicName')
            .split(' ')
            .map(function (el) {
              return el.charAt(0).toUpperCase() + el.slice(1);
            })
            .join(' ');
        }
        let obj = {
          login: req.param('login'),
          email: req.param('email'),
          firstName: firstName,
          lastName: lastName,
          patronymicName: patronymicName,
          encryptedPassword: encryptedPassword,
          birthday: req.param('birthday'),
          contacts: req.param('contacts'),
          subdivision: req.param('subdivision'),
          position: req.param('position'),
          pfr: req.param('pfr'),
          dateInWork: req.param('dateInWork'),
          city: req.param('city'),
          country: req.param('country'),
          address: req.param('address'),
          lastLoggedIn: new Date()
          //gravatarUrl: gravatarUrl
        };
        User.find({email: req.param('email')}).exec((err, findUsers) => {
          if (err) return res.redirect('/admin/users/edit/' + req.param('id'));
          console.log('findUsers', findUsers);
          if (findUsers.length) return res.notFound('Такой email зарегистрирован.');

          User.create(obj, function (err, newUser) {
            if (err) return res.negotiate(err);
            sails.log('Создан новый пользователь с логином:' + newUser.login);
            res.send({id: newUser.id});
          });
        });
      }
    });
  },

  /**
   * Выход с сайта
   * @param req
   * @param res
   */
  logout: function (req, res) {
    if (!req.session.me) return res.view('public/header', {layout: 'homepage'});
    User.findOne(req.session.me, function foundUser(err, user) {
      //if (err) return res.view('public/header', {layout: 'homepage'});
      if (err) return res.negotiate(err);
      if (!user) {
        sails.log.verbose('Сессия относится к пользователю, который больше не существует/');
        return res.backToHomePage();
      }
      req.session.me = null;
      console.log('Выход из системы: ', error.date + ', ' + user.lastName + ' ' + user.firstName + ' ' + user.patronymicName + ', ' + user.email);
      return res.backToHomePage();
    });
  },

  /**
   *  Восстановление пароля
   * @param req
   * @param res
   * @returns {*}
   */
  generateRecoveryEmail: function (req, res) {

    // secondary check for email parameter
    if (_.isUndefined(req.param('email'))) {
      return res.badRequest('Необходимо указать адрес электронной почты!');
    }

    // Find user by the incoming `email` parameter
    User.findOne({
      email: req.param('email')
    }).exec(function foundUser(err, user) {

      if (err) return res.negotiate(err);

      if (!user) return res.notFound();

      // Generate random alphanumeric string for the passwordRecoveryToken
      try {
        var randomString = Strings.random({}).execSync();
      } catch (err) {
        return res.serverError(err);
      }

      // Update user's paswordRecoveryToken attribute with the newly created alphanumeric string
      User.update({
        id: user.id
      }, {
        passwordRecoveryToken: randomString
      }).exec(function updateUser(err, updatedUser) {
        if (err) return res.negotiate(err);

        // email user with a URL which includes the password recovery token as a parameter

        // The Url that inclues the password recovery token as a parameter
        var recoverUrl = sails.config.mailgun.baseUrl + '/password-reset-form/' + updatedUser[0].passwordRecoveryToken;

        var messageTemplate = 'Восстановление пароля! \n' +
          '\n' +
          'Для сброса пароля, воспользуйтесь следующей ссылкой: \n' +
          recoverUrl + '\n' +
          '\n' +
          'Удачи.';

        // Send a simple plaintext email.
        Mailgun.sendPlaintextEmail({
          apiKey: sails.config.mailgun.apiKey,
          domain: sails.config.mailgun.domain,
          toEmail: updatedUser[0].email,
          subject: '[KADR] Сброс пароля',
          message: messageTemplate,
          fromEmail: sails.config.admin.email,
          fromName: sails.config.admin.name
        }).exec({
          // An unexpected error occurred.
          error: function (err) {
            return res.negotiate(err);
          },
          success: function () {
            return res.ok();
          }
        });
      });
    });
  },

  /**
   * Сброс пароля при восстановлении
   * @param req
   * @param res
   * @returns {*}
   */
  resetPassword: function (req, res) {

    // check for token parameter
    if (!_.isString(req.param('passwordRecoveryToken'))) {
      return res.badRequest('A password recovery token is required!');
    }

    // secondary check for password parameter
    if (!_.isString(req.param('password'))) {
      return res.badRequest('A password is required!');
    }

    // Fallback to client-side length check validation
    if (req.param('password').length < 6) {
      return res.badRequest('Password must be at least 6 characters!');
    }

    // Try to find user with passwordRecoveryToken
    User.findOne({
      passwordRecoveryToken: req.param('passwordRecoveryToken')
    }).exec(function foundUser(err, user) {
      if (err) return res.negotiate(err);

      // If this token doesn't correspond with a real user record, it is invalid.
      // We send a 404 response so that our front-end code can show an
      // appropriate error message.
      if (!user) {
        return res.notFound();
      }

      // Encrypt new password
      Passwords.encryptPassword({
        password: req.param('password'),
      }).exec({
        error: function (err) {
          return res.serverError(err);
        },
        success: function (encryptedPassword) {

          User.update(user.id, {
            encryptedPassword: encryptedPassword,
            passwordRecoveryToken: null
          }).exec(function (err, updatedUsers) {
            if (err) {
              return res.negotiate(err);
            }

            // Log the user in
            req.session.userId = updatedUsers[0].id;

            // If successful return updatedUsers
            return res.json({
              username: updatedUsers[0].username
            });
          });
        }
      });
    });
  },

  /**
   * Получить конкретного пользователя
   * @param req
   * @param res
   */
  findOne: function (req, res) {
    if (!req.session.me) return res.view('public/header', {layout: 'homepage'});
    User.findOne(req.param('id'))
      .populate('positions')
      .populate('subdivision')
      .populate('departments')
      .populate('furloughs')
      .populate('breederCatalogs')
      .populate('catalogs')
      .exec(function foundUser(err, user) {
        if (err) return res.serverError(err);
        if (!user) return res.notFound();
        res.ok(user);
      });
  },

  /**
   * Получить всех пользователей системы
   * @param req
   * @param res
   */
  findUsers: function (req, res) {
    if (!req.session.me) return res.view('public/header', {layout: 'homepage'});
    // console.log("REQUEST BODY USER1:", req.body);
    // console.log("REQUEST BODY USER2:", req.param('char'));
    if (req.param('id')) {
      User.findOne(req.param('id'))
        .populate('positions')
        .populate('furloughs')
        .populate('departments')
        .populate('breederCatalogs')
        .populate('catalogs')
        .exec(function foundUser(err, user) {
          if (err) return res.serverError(err);
          if (!user) return res.notFound();
          res.ok(user);

        });
    } else {
      if (!_.isUndefined(req.param('where')) && req.param('char').length > 0) {

        var q = {
          limit: req.params.limit,
          sort: req.params.sort
        };
        let y = {};
        y[req.param('property')] = {'like': req.param('char')};
        q.where = y;

        // console.log('СДЕСЯ яяяя ++ q!',q);

        User.find(q)
          .populate('positions')
          .populate('furloughs')
          .populate('departments')
          .populate('breederCatalogs')
          .populate('catalogs')
          .exec(function foundUser(err, users) {
            if (err) return res.serverError(err);
            if (!users) return res.notFound();
            return res.ok(users);
          });
      } else {
        User.find()
          .populate('positions')
          .populate('furloughs')
          .exec(function foundUser(err, users) {
            if (err) return res.serverError(err);
            if (!users) return res.notFound();

            res.ok(users);
          });
      }
    }
  },

  /**
   * Показать пользователя
   * @param req
   * @param res
   * @param next
   */
  show: function (req, res, next) {
    if (!req.session.me) return res.view('public/header', {layout: 'homepage'});
    User.findOne(req.param('id'))
      .populate('departments')
      .populate('breederCatalogs')
      .populate('catalogs')
      .exec(function foundUser(err, user) {
        if (err) return next(err);
        if (!user) return next();

        res.view({
          user: user, me: req.session.me
        });
      });
  },

  /**
   * Редактировать пользователя
   * @param req
   * @param res
   * @param next
   */
  edit: function (req, res, next) {
    if (!req.session.me) return res.view('public/header', {layout: 'homepage'});
    User.find(req.param('id'))
      .populate('positions')
      .populate('furloughs')
      .exec((err, user) => {
        if (err) return next(err);
        if (!user) return next('User doesn\'t exists.');
        //user.birthday = Sugar.Date.format(user.birthday, '%d.%m.%Y');
        res.view({
          user: user, me: req.session.me
        });
      });
  },

  /**
   * Обновить пользователя
   * @param req
   * @param res
   */
  update: function (req, res) {
    if (!req.session.me) return res.view('public/header', {layout: 'homepage'});
    let fDt = (req.param('firedDate')) ? req.param('firedDate') : null;

    var obj = {
      // login: req.param('login'),
      // email: req.param('email'),
      firstName: req.param('firstName'),
      lastName: req.param('lastName'),
      patronymicName: req.param('patronymicName'),
      departments: req.param('departments'),
      birthday: req.param('birthday'),
      fired: req.param('fired'),
      dateInWork: req.param('dateInWork'),
      decree: req.param('decree'),
      position: req.param('position'),
      contacts: req.param('contacts'),
      firedDate: fDt,
      action: req.param('action'),
      pfr: req.param('pfr'),
      avatarUrl: req.param('avatarUrl'),
      room: req.param('room'),
      city: req.param('city'),
      country: req.param('country'),
      address: req.param('address'),
      email: req.param('email'),
      furlough: req.param('furlough')

    };

    //console.log('Param ID: ', req.param('id'));
    //console.log('objEdit555: ', obj);
    User.find({email: req.param('email'), id: {'!': req.param('id')}}).exec((err, findUsers) => {
      if (err) return res.redirect('/admin/users/edit/' + req.param('id'));
      console.log('findUsers', findUsers);
      if (findUsers.length) return res.notFound('Такой email зарегистрирован.');
      User.update(req.param('id'), obj).exec(function updateObj(err, objEdit) {
        if (err) return res.redirect('/admin/users/edit/' + req.param('id'));
        User.findOne(req.param('id'))
          .populate('positions')
          .populate('furloughs')
          .populate('departments')
          .exec(function (err, user) {
            if (err) return res.negotiate(err);
            if (!user) return res.notFound('Не могу');

            // console.log('positionRemove:', req.param('positionRemove'));
            user.positions.add(req.param('positions'));
            user.departments.add(req.param('departments'));
            user.furloughs.add(req.param('furloughs'));

            // if (_.isEmpty(req.param('position'))) {
            //     user.positions.add({})
            // }
            if (req.param('positionRemove')) {
              user.positions.remove(req.param('positionRemove'));
            }
            if (req.param('furloughRemove')) {
              user.furloughs.remove(req.param('furloughRemove'));
            }
            if (req.param('departmentRemove')) {
              user.departments.remove(req.param('departmentRemove'));
            }
            user.save(function (err) {
              if (err) return res.negotiate('Ошибка при сохранении...');
              res.ok();
            });
          });
      });
    });

  },

  /**
   * Удалить пользователя
   * @param req
   * @param res
   * @param next
   */
  destroy: function (req, res, next) {
    if (!req.session.me) return res.view('public/header', {layout: 'homepage'});
    User.findOne(req.param('id'), function foundUser(err, user) {
      if (err) return next(err);
      if (!user) return next('User doesn\'t exists.');
      User.destroy(req.param('id'), function userDestroyed(err) {
        if (err) return next(err);
      });
      // res.redirect('/admin/users');
      res.ok();
    });
  },

  /**
   * Удалить профиль
   * @param req
   * @param res
   */
  removeProfile: function (req, res) {

    //if (!req.param('id')) {
    //    return res.badRequest('id is a required parameter.');
    //}

    User.update({
      id: req.session.me
    }, {
      deleted: true
    }, function (err, removedUser) {

      if (err) return res.negotiate(err);
      if (removedUser.length === 0) {
        return res.notFound();
      }
      req.session.me = null;
      return res.ok();
    });
  },

  /**
   * Восстановить профиль
   * @param req
   * @param res
   */
  restoreProfile: function (req, res) {

    User.findOne({
      email: req.param('email')
    }, function foundUser(err, user) {
      if (err) return res.negotiate(err);
      if (!user) return res.notFound();

      Passwords.checkPassword({
        passwordAttempt: req.param('password'),
        encryptedPassword: user.encryptedPassword
      }).exec({

        error: function (err) {
          return res.negotiate(err);
        },

        incorrect: function () {
          return res.notFound();
        },

        success: function () {
          User.update({
            id: user.id
          }, {
            deleted: false
          }).exec(function (err, updatedUser) {
            req.session.me = user.id;
            return res.json(updatedUser);
          });
        }
      });
    });
  },

  /**
   * Восстановить Gravatar
   * @param req
   * @param res
   * @returns {*}
   */
  restoreGravatarURL: function (req, res) {
    let gravatarUrl;
    try {

      var restoredGravatarURL = gravatarUrl = Gravatar.getImageUrl({
        emailAddress: req.param('email')
      }).execSync();

      return res.json(restoredGravatarURL);

    } catch (err) {
      return res.serverError(err);
    }
  },

  /**
   * Обновить профиль
   * @param req
   * @param res
   */
  updateProfile: function (req, res) {

    User.update({
      id: req.session.me
    }, {
      gravatarUrl: req.param('gravatarUrl')
    }, function (err, updatedUser) {

      if (err) return res.negotiate(err);

      return res.json(updatedUser);

    });
  },

  /**
   * Сменить пароль (функция для использования только админами)
   * @param req
   * @param res
   * @returns {*}
   */
  changePassword: function (req, res) {

    if (_.isUndefined(req.param('password'))) {
      return res.badRequest('A password is required!');
    }

    if (req.param('password').length < 6) {
      return res.badRequest('Password must be at least 6 characters!');
    }

    Passwords.encryptPassword({
      password: req.param('password')
    }).exec({
      error: function (err) {
        return res.serverError(err);
      },
      success: function (encryptedPassword) {

        User.update({id: req.param('id')}, {encryptedPassword: encryptedPassword})
          .exec(function (err, updatedUser) {
            if (err) {
              return res.negotiate(err);
            }
            return res.json(updatedUser);
          });
      }
    });
  },

  /**
   * Сменить пароль (функция для авторизованного пользователя)
   * @param req
   * @param res
   * @returns {*}
   */
  changePasswordProfile: function (req, res) {

    if (_.isUndefined(req.param('password'))) {
      return res.badRequest('A password is required!');
    }

    if (req.param('password').length < 6) {
      return res.badRequest('Password must be at least 6 characters!');
    }

    Passwords.encryptPassword({
      password: req.param('password')
    }).exec({
      error: function (err) {
        return res.serverError(err);
      },
      success: function (encryptedPassword) {

        User.update({id: req.session.me}, {encryptedPassword: encryptedPassword})
          .exec(function (err, updatedUser) {
            if (err) {
              return res.negotiate(err);
            }
            return res.json(updatedUser);
          });
      }
    });
  },

  adminUsers: function (req, res) {

    User.find({limit: 1000, sort: 'lastName'}).exec(function (err, users) {

      if (err) return res.negotiate(err);

      return res.json(users);

    });
  },

  /**
   * Установка пользователю прав администратора
   * @param req
   * @param res
   */
  updateAdmin: function (req, res) {
    if (!req.session.me) return res.view('public/header', {layout: 'homepage'});
    User.update(req.param('id'), {
      admin: req.param('admin')
    }).exec(function (err, update) {
      if (err) return res.negotiate(err);
      return res.ok();
    });
  },

  /**
   * Установка пользователю прав кадровика
   * @param req
   * @param res
   */
  updateKadr: function (req, res) {
    if (!req.session.me) return res.view('public/header', {layout: 'homepage'});
    User.update(req.param('id'), {
      kadr: req.param('kadr')
    }).exec(function (err, update) {
      if (err) return res.negotiate(err);
      return res.ok();
    });
  },

  /**
   * Установка пользователю прав руководителя
   * @param req
   * @param res
   */
  //updateLeader: function (req, res) {
  //    if (!req.session.me) return res.view('public/header', {layout: 'homepage'});
  //    User.update(req.param('id'), {
  //        leader: req.param('leader')
  //    }).exec(function (err, update) {
  //        if (err) return res.negotiate(err);
  //        return res.ok();
  //    });
  //},

  /**
   * Установка пользователю состояния активации (action)
   * @param req
   * @param res
   */
  updateAction: function (req, res) {
    if (!req.session.me) return res.view('public/header', {layout: 'homepage'});
    User.update(req.param('id'), {
      action: req.param('action')
    }).exec(function (err, update) {
      if (err) return res.negotiate(err);
      return res.ok();
    });
  },

  /**
   * Установка пользователю состояния удалён (deleted)
   * @param req
   * @param res
   */
  updateDeleted: function (req, res) {
    if (!req.session.me) return res.view('public/header', {layout: 'homepage'});
    User.update(req.param('id'), {
      deleted: req.param('deleted')
    }).exec(function (err, update) {
      if (err) return res.negotiate(err);
      return res.ok();
    });
  },

  /**
   * Получить всех сотрудников по ID департамента
   */
  getUsersDepartment: function (req, res) {
    // if (!req.session.me) return res.view('public/header', {layout: 'homepage'});
    // db.user.find({subdivision:{id:'589b22e8789b83a241b55fd1'}})
    if (req.param('id')) {
      User.find({where: {subdivision: {id: req.param('id')}, fired: false}})
        .populate('positions')
        .populate('furloughs')
        .exec(function foundUser(err, user) {
          if (err) return res.serverError(err);
          if (!user) return res.notFound();
          res.ok(user);

        });
    }

    // else {
    //     if (!_.isUndefined(req.param('where')) && req.param('char').length > 0) {
    //         var q = {
    //             limit: req.params.limit,
    //             sort: req.params.sort
    //         };
    //         var y = {};
    //         y[req.param('property')] = {'like': req.param('char')};
    //         q.where = y;
    //         User.find(q)
    //             .exec(function foundUser(err, users) {
    //                 if (err) return res.serverError(err);
    //                 if (!users) return res.notFound();
    //                 return res.ok(users);
    //             });
    //     } else {
    //         User.find()
    //             .exec(function foundUser(err, users) {
    //                 if (err) return res.serverError(err);
    //                 if (!users) return res.notFound();
    //                 res.ok(users);
    //             });
    //     }
    // }
  },

  /**
   * Загрузка аватара на сервер
   * @param req
   * @param res
   */
  upload: function (req, res) {
    if (!req.session.me) return res.view('public/header', {layout: 'homepage'});
    //console.log('formData: ', req.body);
    const dir = require('util').format('%s/images/user/avatar/%s', sails.config.appUrl.rootDir, req.body.id);
    let fileName = req.file('file')._files[0].stream.headers['content-disposition'].split('"').reverse()[1];
    console.log('fileName', fileName);
    console.log('dir', dir);
    req.file('file').upload({
        dirname: dir,
        saveAs: fileName
      },
      function (err, files) {
        console.log('err', err);
        console.log('files', files);
        if (err) return res.serverError(err);
        if (_.isUndefined(files[0])) return res.notFound('Нет файла!');
        //if (files.length === 0) {
        //    return res.badRequest('Файл не загружен');
        //}
        //console.log("files: ", files);

        User.update(req.body.id, {
          avatarUrl: require('util').format('/images/user/avatar/%s/%s', req.body.id, fileName),
          avatarFd: files[0].fd,
          fileNameAvatar: fileName
        })
          .exec(function (err) {
            if (err) return res.negotiate(err);
            //console.log(' avatarUrl: ', dir);
            //console.log(' avatarUrl2: ', require('util').format('/images/user/avatar/%s/%s', req.body.id, fileName));
            return res.ok();
          });
      });
  },

  /**
   * Обновить 'кол-во строк в таблице' пользователю
   * @param req
   * @param res
   */
  updateDefaultRows: function (req, res) {
    //if (!req.session.me) return res.view('public/header', {layout: 'homepage'});
    User.update(req.session.me, {
      defaultRows: req.param('defaultRows')
    })
      .exec(function (err, update) {
        if (err) return res.negotiate(err);
        return res.ok(update);
      });
  },

};


text:
import { helper } from '@ember/component/helper';

import format from 'date-fns/format';

export default helper(function ([date, pattern], options) {
  if (date) {
    return format(date, pattern, { ...options });
  }
});


text:
<?php

namespace mh\BTBundle\Controller\Backend;

use mh\BTBundle\DBAL\ModerationStatusType;

class ContentObjectCRUDController extends Base\BaseCRUDController
{
    // ïîäòâåðæäåíèå êîððåêòíîñòè ìàòåðèàëà
    public function approveAction($id)
    {
        $class = $this->getClassname();
        $object = $this->getRepository($this->getClassname())->find($id);

        if ($object) {
            $em = $this->getEM();

            $object->setModerationStatus(ModerationStatusType::VALID);
            //if ($class == "Post" && $object->getDelayedPublication() == null) {
                $object->setIsPublished(true);
            //}

            $contentObject = $object->getContentObject();
            // îòâåðãàåì âñå æàëîáû
            $complaints = $this->getRepository('ContentObjectComplaint')->findBy(array(
                'moderationStatus' => ModerationStatusType::NOT_MODERATED,
                'target' => $contentObject->getId(),
            ));

            $allocator = $this->get('scores_allocator');
            foreach ($complaints as $complaint) {
                $complaint->setModerationStatus(ModerationStatusType::NOT_VALID);
    			$allocator->allocateScoresForComplaint($complaint);
            }

            $contentObject->setComplaintsCount(0);

            $em->flush();
        }

        return $this->redirect($this->getRequest()->headers->get('referer'));
    }

    // ìàòåðèàë íåêîððåêòåí ïî êàêîé òî ïðè÷èíå
    public function disapproveAction($id)
    {
        $class = $this->getClassname();
        $object = $this->getRepository($this->getClassname())->find($id);

        if ($object) {
            $em = $this->getEM();

            $object->setModerationStatus(ModerationStatusType::NOT_VALID);
            $object->setIsPublished(false);

            // ïîäòâåðæäàåì âñå æàëîáû
            $complaints = $this->getRepository( 'ContentObjectComplaint')->findBy(array(
                'moderationStatus' => ModerationStatusType::NOT_MODERATED,
                'target' => $object->getContentObject()->getId(),
            ));

            $allocator = $this->get('scores_allocator');
            foreach ($complaints as $complaint) {
                $complaint->setModerationStatus(ModerationStatusType::VALID);
    			$allocator->allocateScoresForComplaint($complaint);
            }

            $object->getContentObject()->setComplaintsCount(0);

            $em->flush();
        }

        return $this->redirect($this->getRequest()->headers->get('referer'));
    }
}


text:
using MonkeyOthello.Learning;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MonkeyOthello.Tests
{
    class Controller
    {
        public static void Run()
        {
            //var start = 38;
            //var span = 4;
            var start = 54;
            var span = 1;
            for (var x = start; x <= 54; x += span)
            {
                CloseColosseumPlatforms();
                Thread.Sleep(5000);
                UpdateColosseumPlatforms();
                Thread.Sleep(5000);
                RunColosseumPlatforms(Enumerable.Range(x, span).ToArray());
                //wait until creating more than 10k items
                var i = 0;
                while (true)
                {
                    try
                    {
                        Console.WriteLine($"waited {i++} minute(s)");
                        Thread.Sleep(2000);
                        Console.WriteLine("check...");
                        var counts = CheckColosseumItemsCount(Enumerable.Range(x, span).ToArray());

                        if (counts.All(c => c > 10000))
                        {
                            break;
                        }
                    }catch(Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }

                CloseColosseumPlatforms();

                //awake
                Console.WriteLine($"Begin learning {x}");
                Learning(x, x + span-1);
                Console.WriteLine($"Done learning {x}");

                //backup last results
                Console.WriteLine($"Backup last results");
                DirectoryCopy(@"E:\projects\MonkeyOthello\tests\test-results\networks",
                    $@"E:\projects\MonkeyOthello\tests\test-results\networks-{DateTime.Today:yyyyMMdd}",
                    false);

                //copy results
                Console.WriteLine($"Copy results");
                var networksPath = Path.Combine(Environment.CurrentDirectory, @"networks\");
                DirectoryCopy(networksPath, @"E:\projects\MonkeyOthello\tests\test-results\networks", false);

                //backup last knowledge
                Console.WriteLine($"Backup last knowledge");
                DirectoryCopy(@"E:\projects\MonkeyOthello\tests\test-results\knowledge",
                    $@"E:\projects\MonkeyOthello\tests\test-results\knowledge-{DateTime.Today:yyyyMMdd}",
                    false);

                //copy results
                Console.WriteLine($"Copy knowledge");
                var knowledgePath = Path.Combine(Environment.CurrentDirectory, @"knowledge\");
                DirectoryCopy(knowledgePath, @"E:\projects\MonkeyOthello\tests\test-results\knowledge", false);
            }
        }

        public static void Learning(int from, int to)
        {
            DeepLearning.PrepareData($@"E:\projects\MonkeyOthello\tests\", from, to);
            DeepLearning.TrainAll(from, to);
            DeepLearning.TestAll(from, to);
        }

        private static int[] CheckColosseumItemsCount(params int[] numbers)
        {
            if (numbers == null || numbers.Length == 0)
            {
                Console.WriteLine("No ColosseumPlatforms.");
                return new int[0];
            }

            var counts = new List<int>();
            foreach (var i in numbers)
            {
                var targetPath = $@"E:\projects\MonkeyOthello\tests\k-dl-{i}\knowledge";
                if (Directory.Exists(targetPath))
                {
                    var count = Directory.GetFiles(targetPath)
                          .Select(file => File.ReadAllLines(file).Length)
                          .Sum();

                    Console.WriteLine($"{i}'s items: {count}");
                    counts.Add(count);
                }
            }

            return counts.ToArray();
        }

        private static void CloseColosseumPlatforms()
        {
            Console.WriteLine("closing all MonkeyOthello.Colosseum.Platform...");
            var processes = Process.GetProcessesByName("MonkeyOthello.Colosseum.Platform");
            Console.WriteLine($"total: {processes.Length}");
            foreach (var p in processes)
            {
                p.Kill();
                //p.Close();
                //p.Dispose();
            }
            Console.WriteLine("closed all MonkeyOthello.Colosseum.Platform.");
        }

        private static void UpdateColosseumPlatforms()
        {
            var releasePath = @"E:\projects\MonkeyOthello\MonkeyOthello.Colosseum.Platform\bin\Release";

            var dlls = Directory.GetFiles(releasePath, "*.dll");
            var exe = Path.Combine(releasePath, "MonkeyOthello.Colosseum.Platform.exe");
            var config = Path.Combine(releasePath, "MonkeyOthello.Colosseum.Platform.exe.config");
            var releaseFiles = new List<string>();
            releaseFiles.AddRange(dlls);
            releaseFiles.Add(exe);
            releaseFiles.Add(config);

            var targetBasePath = @"E:\projects\MonkeyOthello\tests";

            //Parallel.For(30, 54, i =>
            for (var i = 30; i <= 54; i++)
            {
                var targetFolder = $@"k-dl-{i}\";
                var targetPath = Path.Combine(targetBasePath, targetFolder);

                //copy relaese files
                Console.WriteLine($"{i}. copy files to {targetFolder}");

                if (!Directory.Exists(targetPath))
                {
                    Directory.CreateDirectory(targetPath);
                }

                foreach (var f in releaseFiles)
                {
                    var fileName = Path.GetFileName(f);
                    var targetFile = Path.Combine(targetPath, fileName);
                    File.Copy(f, targetFile, true);
                }

                //update config
                Console.WriteLine($"{i}. update config");
                var targetConfig = Path.Combine(targetPath, "MonkeyOthello.Colosseum.Platform.exe.config");

                var configContent = File.ReadAllText(targetConfig);
                configContent = configContent.Replace("{TrainDepth}", i.ToString());
                File.WriteAllText(targetConfig, configContent);

                //copy engines
                Console.WriteLine($@"{i}. copy engines to {targetFolder}\edax\");

                DirectoryCopy(Path.Combine(releasePath, @"edax\"),
                    Path.Combine(targetPath, @"edax\"),
                    true);

                //copy networks
                Console.WriteLine($@"{i}. copy networks to {targetFolder}\networks\");
                DirectoryCopy(Path.Combine(targetBasePath, @"test-results\networks\"),
                    Path.Combine(targetPath, @"networks\"),
                    true);

                Console.WriteLine($"{i}. done!");

            }
            //);

        }

        private static void RunColosseumPlatforms(params int[] numbers)
        {
            if (numbers == null || numbers.Length == 0)
            {
                Console.WriteLine("No ColosseumPlatforms.");
                return;
            }

            foreach (var i in numbers)
            {
                var exe = $@"E:\projects\MonkeyOthello\tests\k-dl-{i}\MonkeyOthello.Colosseum.Platform.exe";
                var process = new Process();
                process.StartInfo.FileName = exe;
                process.StartInfo.WorkingDirectory = Path.GetDirectoryName(exe);
                process.Start();
                Console.WriteLine($"{i}. running.");
            }
        }

        private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
        {
            // Get the subdirectories for the specified directory.
            DirectoryInfo dir = new DirectoryInfo(sourceDirName);

            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException(
                    "Source directory does not exist or could not be found: "
                    + sourceDirName);
            }

            DirectoryInfo[] dirs = dir.GetDirectories();
            // If the destination directory doesn't exist, create it.
            if (!Directory.Exists(destDirName))
            {
                Directory.CreateDirectory(destDirName);
            }

            // Get the files in the directory and copy them to the new location.
            FileInfo[] files = dir.GetFiles();
            foreach (FileInfo file in files)
            {
                string temppath = Path.Combine(destDirName, file.Name);
                file.CopyTo(temppath, true);
            }

            // If copying subdirectories, copy them and their contents to new location.
            if (copySubDirs)
            {
                foreach (DirectoryInfo subdir in dirs)
                {
                    string temppath = Path.Combine(destDirName, subdir.Name);
                    DirectoryCopy(subdir.FullName, temppath, copySubDirs);
                }
            }
        }
    }
}


text:
package com.zepp.www.likeanimation;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.zepp.www.likeanimation.leonids.ParticleSystem;

public class MainActivity extends AppCompatActivity {

    private SmallBang mSmallBang;
    private ImageView mImage;
    private Button mButton;
    private TextView mText;

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

        mSmallBang = SmallBang.attach2Window(this);

        mImage = (ImageView)findViewById(R.id.image);
        mImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                like(v);
            }
        });

        mButton = (Button) findViewById(R.id.button);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addNumber(v);
            }
        });

        mText = (TextView) findViewById(R.id.text);
        mText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                redText(v);
            }
        });
    }

    public void addNumber(View view){
        mSmallBang.bang(view,new SmallBangListener() {
            @Override
            public void onAnimationStart() {
            }

            @Override
            public void onAnimationEnd() {
                toast("button +1");
            }
        });
    }

    public void redText(View view){
        mText.setTextColor(0xFFCD8BF8);
        mSmallBang.bang(view,50,new SmallBangListener() {
            @Override
            public void onAnimationStart() {
            }

            @Override
            public void onAnimationEnd() {
                toast("text+1");
            }
        });
    }

    public void like(View view){
        mImage.setImageResource(R.mipmap.ic_star_rate_on);
        mSmallBang.bang(view);
        mSmallBang.setSmallBangListener(new SmallBangListener() {
            @Override
            public void onAnimationStart() {
            }

            @Override
            public void onAnimationEnd() {
                toast("heart+1");
            }
        });
    }

    private void toast(String text) {
        Toast.makeText(this,text,Toast.LENGTH_SHORT).show();
    }

    public void goPraticale(View view) {
        ParticleSystem ps = new ParticleSystem(this, 100, R.mipmap.ic_launcher, 800);
        ps.setScaleRange(0.7f, 1.3f);
        ps.setSpeedRange(0.1f, 0.25f);
        ps.setAcceleration(0.0001f, 90);
        ps.setRotationSpeedRange(90, 180);
        ps.setFadeOut(200, new AccelerateInterpolator());
        ps.oneShot(view, 100);
    }
}


text:
<?php
namespace AppBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

class FloorAdmin extends Admin
{
	protected function configureFormFields(FormMapper $formMapper)
	{

		$formMapper
		->with('Floor Info', array('class' => 'col-md-8'))
			->add('floorNumber', 'number')
			->add('building', 'sonata_type_model_list', array())
		->end();
	}

	protected function configureDatagridFilters(DatagridMapper $datagridMapper)
	{
		$datagridMapper
			->add('floorNumber')
			->add('building')
		;
	}

	protected function configureListFields(ListMapper $listMapper)
	{
		$listMapper
			->addIdentifier('floorNumber')
			->add('building')
		;
	}

	public function toString($object){
		return $object->getFloornumber();
	}
}
?>


text:
using l10n_util::GetStringUTF16;
using l10n_util::GetStringUTF8;

namespace views::examples {

// ScrollView's content, which draws gradient color on background.
// TODO(oshima): add child views as well.
class ScrollViewExample::ScrollableView : public BoxLayoutView {
 public:
  ScrollableView() {
    SetColor(ExamplesColorIds::kColorScrollViewExampleTallFrom,
             ExamplesColorIds::kColorScrollViewExampleTallTo);

    SetOrientation(views::BoxLayout::Orientation::kVertical);
    SetInsideBorderInsets(gfx::Insets());
    SetBetweenChildSpacing(0);

    const auto add_child = [this](std::unique_ptr<View> view) {
      auto* container = AddChildView(std::make_unique<BoxLayoutView>());
      container->SetOrientation(views::BoxLayout::Orientation::kVertical);
      container->AddChildView(std::move(view));
    };
    add_child(std::make_unique<LabelButton>(
        Button::PressedCallback(),
        GetStringUTF16(IDS_SCROLL_VIEW_BUTTON_LABEL)));
    add_child(std::make_unique<RadioButton>(
        GetStringUTF16(IDS_SCROLL_VIEW_RADIO_BUTTON_LABEL), 0));
    SetDefaultFlex(1);
  }

  ScrollableView(const ScrollableView&) = delete;
  ScrollableView& operator=(const ScrollableView&) = delete;

  void SetColor(ui::ColorId from_id, ui::ColorId to_id) {
    from_color_id_ = from_id;
    to_color_id_ = to_id;
  }

  std::pair<SkColor, SkColor> GetColors() const {
    auto* const cp = GetColorProvider();
    if (!cp)
      return {gfx::kPlaceholderColor, gfx::kPlaceholderColor};
    return {cp->GetColor(from_color_id_), cp->GetColor(to_color_id_)};
  }

  void OnPaintBackground(gfx::Canvas* canvas) override {
    cc::PaintFlags flags;
    std::pair<SkColor, SkColor> gradient_colors = GetColors();
    flags.setShader(gfx::CreateGradientShader(
        gfx::Point(), gfx::Point(0, height()), gradient_colors.first,
        gradient_colors.second));
    flags.setStyle(cc::PaintFlags::kFill_Style);
    canvas->DrawRect(GetLocalBounds(), flags);
  }

 private:
  ui::ColorId from_color_id_;
  ui::ColorId to_color_id_;
};

ScrollViewExample::ScrollViewExample()
    : ExampleBase(GetStringUTF8(IDS_SCROLL_VIEW_SELECT_LABEL).c_str()) {}

ScrollViewExample::~ScrollViewExample() = default;

void ScrollViewExample::CreateExampleView(View* container) {
  auto scroll_view = std::make_unique<ScrollView>();
  scrollable_ = scroll_view->SetContents(std::make_unique<ScrollableView>());
  scrollable_->SetBounds(0, 0, 1000, 100);
  scrollable_->SetColor(ExamplesColorIds::kColorScrollViewExampleWideFrom,
                        ExamplesColorIds::kColorScrollViewExampleWideTo);

  container->SetLayoutManager(std::make_unique<FlexLayout>())
      ->SetOrientation(LayoutOrientation::kVertical);

  auto full_flex = FlexSpecification(MinimumFlexSizeRule::kScaleToZero,
                                     MaximumFlexSizeRule::kUnbounded)
                       .WithWeight(1);

  // Add scroll view.
  scroll_view_ = container->AddChildView(std::move(scroll_view));
  scroll_view_->SetProperty(views::kFlexBehaviorKey, full_flex);

  // Add control buttons.
  auto* button_panel = container->AddChildView(std::make_unique<View>());
  button_panel->SetLayoutManager(std::make_unique<FlexLayout>())
      ->SetOrientation(LayoutOrientation::kHorizontal);

  button_panel->AddChildView(std::make_unique<LabelButton>(
      base::BindRepeating(&ScrollViewExample::ButtonPressed,
                          base::Unretained(this), gfx::Rect(0, 0, 1000, 100),
                          ExamplesColorIds::kColorScrollViewExampleWideFrom,
                          ExamplesColorIds::kColorScrollViewExampleWideTo),
      GetStringUTF16(IDS_SCROLL_VIEW_WIDE_LABEL)));
  button_panel->AddChildView(std::make_unique<LabelButton>(
      base::BindRepeating(&ScrollViewExample::ButtonPressed,
                          base::Unretained(this), gfx::Rect(0, 0, 100, 1000),
                          ExamplesColorIds::kColorScrollViewExampleTallFrom,
                          ExamplesColorIds::kColorScrollViewExampleTallTo),
      GetStringUTF16(IDS_SCROLL_VIEW_TALL_LABEL)));
  button_panel->AddChildView(std::make_unique<LabelButton>(
      base::BindRepeating(
          &ScrollViewExample::ButtonPressed, base::Unretained(this),
          gfx::Rect(0, 0, 1000, 1000),
          ExamplesColorIds::kColorScrollViewExampleBigSquareFrom,
          ExamplesColorIds::kColorScrollViewExampleBigSquareTo),
      GetStringUTF16(IDS_SCROLL_VIEW_BIG_SQUARE_LABEL)));
  button_panel->AddChildView(std::make_unique<LabelButton>(
      base::BindRepeating(
          &ScrollViewExample::ButtonPressed, base::Unretained(this),
          gfx::Rect(0, 0, 100, 100),
          ExamplesColorIds::kColorScrollViewExampleSmallSquareFrom,
          ExamplesColorIds::kColorScrollViewExampleSmallSquareTo),
      GetStringUTF16(IDS_SCROLL_VIEW_SMALL_SQUARE_LABEL)));
  button_panel->AddChildView(std::make_unique<LabelButton>(
      base::BindRepeating(&View::ScrollRectToVisible,
                          base::Unretained(scroll_view_->contents()),
                          gfx::Rect(20, 500, 1000, 500)),
      GetStringUTF16(IDS_SCROLL_VIEW_SCROLL_TO_LABEL)));

  for (View* child : button_panel->children())
    child->SetProperty(views::kFlexBehaviorKey, full_flex);
}

void ScrollViewExample::ButtonPressed(gfx::Rect bounds,
                                      ui::ColorId from,
                                      ui::ColorId to) {
  scrollable_->SetBoundsRect(std::move(bounds));
  scrollable_->SetColor(from, to);
}

}  // namespace views::examples


text:
import Transaction from './Transaction';

class LoginTransaction extends Transaction {

    constructor(transactionId, credentials) {
        super(transactionId, 'user', 'login');
        this._credentials = credentials;
        this._userId = null;
        this._validationErrors = {};
    }

    get userId() {
        return this._userId;
    }

    get credentials() {
        return _credentials;
    }

    get hasValidationErrors() {
        return (Object.keys(this.validationErrors).length > 0);
    }

    get validationErrors() {
        return this._validationErrors;
    }

    setUserId(userId) {
        this._userId = userId;
        this.markAsChanged();
        return this;
    }

    setValidationErrors(errors) {
        this._validationErrors = validationErrors;
        this.markAsChanged();
        return this;
    }
}

export default LoginTransaction;


text:
<?php

namespace Guzzle\Http\Message;

use Guzzle\Common\Collection;
use Guzzle\Common\Exception\InvalidArgumentException;

/**
 * Abstract HTTP request/response message
 */
abstract class AbstractMessage implements MessageInterface
{
    /**
     * @var array HTTP headers
     */
    protected $headers = array();

    /**
     * @var Collection Custom message parameters that are extendable by plugins
     */
    protected $params;

    /**
     * @var array Cache-Control directive information
     */
    private $cacheControl = array();

    /*
     * @var string HTTP protocol version of the message
     */
    protected $protocolVersion = '1.1';

    /**
     * {@inheritdoc}
     */
    public function getParams()
    {
        return $this->params;
    }

    /**
     * {@inheritdoc}
     */
    public function addHeader($header, $value)
    {
        $key = strtolower($header);
        if (!isset($this->headers[$key])) {
            $this->headers[$key] = new Header($header, $value);
        } else {
            $this->headers[$key]->add($value, $header);
        }
        $this->changedHeader($key);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function addHeaders(array $headers)
    {
        foreach ($headers as $key => $value) {
            $this->addHeader($key, $value);
        }

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getHeader($header, $string = false)
    {
        $key = strtolower($header);
        if (!isset($this->headers[$key])) {
            return null;
        }

        return $string ? (string) $this->headers[$key] : $this->headers[$key];
    }

    /**
     * {@inheritdoc}
     */
    public function getHeaders($asObjects = false)
    {
        if ($asObjects) {
            $result = $this->headers;
        } else {
            $result = array();
            // Convert all of the headers into a collection
            foreach ($this->headers as $header) {
                foreach ($header->raw() as $key => $value) {
                    $result[$key] = $value;
                }
            }
        }

        return new Collection($result);
    }

    /**
     * {@inheritdoc}
     */
    public function getHeaderLines()
    {
        $headers = array();
        foreach ($this->headers as $value) {
            $glue = $value->getGlue();
            foreach ($value->raw() as $key => $v) {
                $headers[] = rtrim($key . ': ' . implode($glue, $v));
            }
        }

        return $headers;
    }

    /**
     * {@inheritdoc}
     */
    public function setHeader($header, $value)
    {
        // Remove any existing header
        $key = strtolower($header);
        unset($this->headers[$key]);

        if ($value instanceof Header) {
            $this->headers[$key] = $value;
        } else {
            // Allow for 0, '', and NULL to be set
            if (!$value) {
                $value = array($value);
            }
            $this->headers[$key] = new Header($header, $value);
        }
        $this->changedHeader($key);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function setHeaders(array $headers)
    {
        // Get the keys that are changing
        $changed = array_keys($this->headers);
        // Erase the old headers
        $this->headers = array();
        // Add the new headers
        foreach ($headers as $key => $value) {
            $changed[] = $key;
            $this->addHeader($key, $value);
        }

        // Notify of the changed headers
        foreach (array_unique($changed) as $header) {
            $this->changedHeader(strtolower($header));
        }

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function hasHeader($header)
    {
        return array_key_exists(strtolower($header), $this->headers);
    }

    /**
     * {@inheritdoc}
     */
    public function removeHeader($header)
    {
        $header = strtolower($header);
        unset($this->headers[$header]);
        $this->changedHeader($header);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getTokenizedHeader($header, $token = ';')
    {
        if (!$this->hasHeader($header)) {
            return null;
        }

        $data = new Collection();

        foreach ($this->getHeader($header) as $singleValue) {
            foreach (explode($token, $singleValue) as $kvp) {
                $parts = explode('=', $kvp, 2);
                if (!isset($parts[1])) {
                    $data[count($data)] = trim($parts[0]);
                } else {
                    $data->add(trim($parts[0]), trim($parts[1]));
                }
            }
        }

        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $data->set($key, array_unique($value));
            }
        }

        return $data;
    }

    /**
     * {@inheritdoc}
     */
    public function setTokenizedHeader($header, $data, $token = ';')
    {
        if (!($data instanceof Collection) && !is_array($data)) {
            throw new InvalidArgumentException('Data must be a Collection or array');
        }

        $values = array();
        foreach ($data as $key => $value) {
            foreach ((array) $value as $v) {
                $values[] = is_int($key) ? $v : $key . '=' . $v;
            }
        }

        return $this->setHeader($header, implode($token, $values));
    }

    /**
     * {@inheritdoc}
     */
    public function getCacheControlDirective($directive)
    {
        return isset($this->cacheControl[$directive]) ? $this->cacheControl[$directive] : null;
    }

    /**
     * {@inheritdoc}
     */
    public function hasCacheControlDirective($directive)
    {
        return isset($this->cacheControl[$directive]);
    }

    /**
     * {@inheritdoc}
     */
    public function addCacheControlDirective($directive, $value = true)
    {
        $this->cacheControl[$directive] = $value;
        $this->rebuildCacheControlDirective();

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function removeCacheControlDirective($directive)
    {
        if (array_key_exists($directive, $this->cacheControl)) {
            unset($this->cacheControl[$directive]);
            $this->rebuildCacheControlDirective();
        }

        return $this;
    }

    /**
     * Check to see if the modified headers need to reset any of the managed
     * headers like cache-control
     *
     * @param string $header Header that changed
     */
    protected function changedHeader($header)
    {
        if ($header == 'cache-control') {
            $this->parseCacheControlDirective();
        }
    }

    /**
     * Parse the Cache-Control HTTP header into an array
     */
    private function parseCacheControlDirective()
    {
        $this->cacheControl = array();
        $tokenized = $this->getTokenizedHeader('Cache-Control', ',') ?: array();
        foreach ($tokenized as $key => $value) {
            if (is_numeric($key)) {
                $this->cacheControl[$value] = true;
            } else {
                $this->cacheControl[$key] = $value;
            }
        }
    }

    /**
     * Rebuild the Cache-Control HTTP header using the user-specified values
     */
    private function rebuildCacheControlDirective()
    {
        $cacheControl = array();
        foreach ($this->cacheControl as $key => $value) {
            $cacheControl[] = ($value === true) ? $key : ($key . '=' . $value);
        }
        $this->headers['cache-control'] = new Header('Cache-Control', $cacheControl, ', ');
    }
}


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

// This is a test app for Evergreen that only works when it loads the
// evergreen-cert-test.html page.

#include <string>

#include "base/callback.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "cobalt/base/wrap_main.h"
#include "cobalt/browser/application.h"
#include "cobalt/browser/switches.h"
#include "cobalt/version.h"
#include "starboard/event.h"
#include "starboard/loader_app/app_key.h"
#include "starboard/system.h"

namespace {

const char kMainAppKey[] = "aHR0cHM6Ly93d3cueW91dHViZS5jb20vdHY=";
// Use the html instead of url or app key to target the Evergreen cert test
// page, because there are various urls to launch the test page.
const char kEvergreenCertTestHtml[] = "evergreen-cert-test.html";

bool is_target_app = false;

cobalt::browser::Application* g_application = NULL;
bool g_is_startup_switch_set = false;

// Get the current version if the switch is set
bool CheckForAndExecuteVersionSwitch() {
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          cobalt::browser::switches::kVersion)) {
    SbLogRaw(base::StringPrintf("Cobalt version %s\n", COBALT_VERSION).c_str());
    return true;
  }
  return false;
}

// Get the help message if the switch is set
bool CheckForAndExecuteHelpSwitch() {
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          cobalt::browser::switches::kHelp)) {
    SbLogRaw("Options: \n");
    SbLogRaw(cobalt::browser::switches::HelpMessage().c_str());
    return true;
  }
  return false;
}

// If startup switches are set, the Cobalt browser application will not be
// initiallized and will exit early.
bool CheckForAndExecuteStartupSwitches() {
  if (CheckForAndExecuteVersionSwitch()) g_is_startup_switch_set = true;
  if (CheckForAndExecuteHelpSwitch()) g_is_startup_switch_set = true;
  return g_is_startup_switch_set;
}

void PreloadApplication(int argc, char** argv, const char* link,
                        const base::Closure& quit_closure,
                        SbTimeMonotonic timestamp) {
  if (CheckForAndExecuteStartupSwitches()) {
    SbSystemRequestStop(0);
    return;
  }
  LOG(INFO) << "Concealing application.";
  DCHECK(!g_application);
  g_application = new cobalt::browser::Application(
      quit_closure, true /*should_preload*/, timestamp);
  DCHECK(g_application);
}

void StartApplication(int argc, char** argv, const char* link,
                      const base::Closure& quit_closure,
                      SbTimeMonotonic timestamp) {
  if (CheckForAndExecuteStartupSwitches()) {
    SbSystemRequestStop(0);
    return;
  }
  LOG(INFO) << "Starting application.";
#if SB_API_VERSION >= 13
  DCHECK(!g_application);
  g_application = new cobalt::browser::Application(
      quit_closure, false /*not_preload*/, timestamp);
  DCHECK(g_application);
#else
  if (!g_application) {
    g_application = new cobalt::browser::Application(
        quit_closure, false /*should_preload*/, timestamp);
    DCHECK(g_application);
  } else {
    g_application->Start(timestamp);
  }
#endif  // SB_API_VERSION >= 13
}

void StopApplication() {
  LOG(INFO) << "Stopping application.";
  delete g_application;
  g_application = NULL;
}

void HandleStarboardEvent(const SbEvent* starboard_event) {
  DCHECK(starboard_event);
  if (g_application) {
    g_application->HandleStarboardEvent(starboard_event);
  } else if (!g_is_startup_switch_set) {
    LOG(ERROR) << "Unable to handle starboard event because there is no "
                  "existing application!";
  }
}

}  // namespace

void SbEventHandle(const SbEvent* event) {
  if (is_target_app)
    return ::cobalt::wrap_main::BaseEventHandler<
        PreloadApplication, StartApplication, HandleStarboardEvent,
        StopApplication>(event);

  const SbEventStartData* data = static_cast<SbEventStartData*>(event->data);
  const base::CommandLine command_line(
      data->argument_count, const_cast<const char**>(data->argument_values));

  if (command_line.HasSwitch(cobalt::browser::switches::kInitialURL)) {
    std::string url = command_line.GetSwitchValueASCII(
        cobalt::browser::switches::kInitialURL);
    if (starboard::loader_app::GetAppKey(url) != kMainAppKey &&
        url.find(kEvergreenCertTestHtml) == std::string::npos) {
      // If the app is not the main app nor Evergreen cert test page, stop the
      // app.
      SbSystemRequestStop(0);
    }
  }

  // If the url is the main app or the Evergreen cert test page, hook up the app
  // lifecycle functions.
  is_target_app = true;
  return ::cobalt::wrap_main::BaseEventHandler<
      PreloadApplication, StartApplication, HandleStarboardEvent,
      StopApplication>(event);
}