text:
using System.IO;
using System.Text;

namespace Alphaleonis.Win32.Filesystem
{
   internal static partial class NativeMethods
   {
      public static readonly bool IsAtLeastWindows8 = OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.Windows8);
      public static readonly bool IsAtLeastWindows7 = OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.Windows7);
      public static readonly bool IsAtLeastWindowsVista = OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.WindowsVista);

      /// The FindFirstFileEx function does not query the short file name, improving overall enumeration speed.
      /// <para> </para>
      /// <remarks>
      /// <para>The data is returned in a <see cref="WIN32_FIND_DATA"/> structure,</para>
      /// <para>and cAlternateFileName member is always a NULL string.</para>
      /// <para>This value is not supported until Windows Server 2008 R2 and Windows 7.</para>
      /// </remarks>
      ///
      public static readonly FINDEX_INFO_LEVELS FindexInfoLevel = IsAtLeastWindows7 ? FINDEX_INFO_LEVELS.Basic : FINDEX_INFO_LEVELS.Standard;

      /// Uses a larger buffer for directory queries, which can increase performance of the find operation.
      /// <remarks>This value is not supported until Windows Server 2008 R2 and Windows 7.</remarks>
      public static readonly FIND_FIRST_EX_FLAGS UseLargeCache = IsAtLeastWindows7 ? FIND_FIRST_EX_FLAGS.LARGE_FETCH : FIND_FIRST_EX_FLAGS.NONE;

      /// DefaultFileBufferSize = 4096; Default type buffer size used for reading and writing files.
      public const int DefaultFileBufferSize = 4096;

      /// DefaultFileEncoding = Encoding.UTF8; Default type of Encoding used for reading and writing files.
      public static readonly Encoding DefaultFileEncoding = Encoding.UTF8;

      /// MaxDirectoryLength = 255
      internal const int MaxDirectoryLength = 255;

      /// MaxPath = 260
      /// The specified path, file name, or both exceed the system-defined maximum length.
      /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
      ///
      internal const int MaxPath = 260;

      /// MaxPathUnicode = 32700
      internal const int MaxPathUnicode = 32700;

      /// When an exception is raised, bit shifting is needed to prevent: "System.OverflowException: Arithmetic operation resulted in an overflow."
      internal const int OverflowExceptionBitShift = 65535;

      /// Invalid FileAttributes = -1
      internal const FileAttributes InvalidFileAttributes = (FileAttributes) (-1);

      /// MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384
      internal const int MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384;

      /// REPARSE_DATA_BUFFER_HEADER_SIZE = 8
      internal const int REPARSE_DATA_BUFFER_HEADER_SIZE = 8;

      private const int DeviceIoControlMethodBuffered = 0;
      private const int DeviceIoControlFileDeviceFileSystem = 9;

      // Command to compression state of a file or directory on a volume whose file system supports per-file and per-directory compression.
      internal const int FSCTL_SET_COMPRESSION = (DeviceIoControlFileDeviceFileSystem << 16) | (16 << 2) | DeviceIoControlMethodBuffered | (int) (FileAccess.Read | FileAccess.Write) << 14;

      // Command to set the reparse point data block.
      internal const int FSCTL_SET_REPARSE_POINT = (DeviceIoControlFileDeviceFileSystem << 16) | (41 << 2) | DeviceIoControlMethodBuffered | (0 << 14);

      /// Command to delete the reparse point data base.
      internal const int FSCTL_DELETE_REPARSE_POINT = (DeviceIoControlFileDeviceFileSystem << 16) | (43 << 2) | DeviceIoControlMethodBuffered | (0 << 14);

      /// Command to get the reparse point data block.
      internal const int FSCTL_GET_REPARSE_POINT = (DeviceIoControlFileDeviceFileSystem << 16) | (42 << 2) | DeviceIoControlMethodBuffered | (0 << 14);
   }
}


text:
package org.spongycastle.cert.crmf;

import java.io.IOException;
import java.io.OutputStream;

import org.spongycastle.asn1.ASN1Encoding;
import org.spongycastle.asn1.cmp.PBMParameter;
import org.spongycastle.asn1.crmf.PKMACValue;
import org.spongycastle.asn1.x509.SubjectPublicKeyInfo;
import org.spongycastle.operator.MacCalculator;
import org.spongycastle.util.Arrays;

class PKMACValueVerifier
{
    private final PKMACBuilder builder;

    public PKMACValueVerifier(PKMACBuilder builder)
    {
        this.builder = builder;
    }

    public boolean isValid(PKMACValue value, char[] password, SubjectPublicKeyInfo keyInfo)
        throws CRMFException
    {
        builder.setParameters(PBMParameter.getInstance(value.getAlgId().getParameters()));
        MacCalculator calculator = builder.build(password);

        OutputStream macOut = calculator.getOutputStream();

        try
        {
            macOut.write(keyInfo.getEncoded(ASN1Encoding.DER));

            macOut.close();
        }
        catch (IOException e)
        {
            throw new CRMFException("exception encoding mac input: " + e.getMessage(), e);
        }

        return Arrays.areEqual(calculator.getMac(), value.getValue().getBytes());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.nifi.registry.client.impl.request;

import org.apache.commons.lang3.Validate;
import org.apache.nifi.registry.client.RequestConfig;

import java.util.HashMap;
import java.util.Map;

/**
 * Implementation of RequestConfig for a request with a bearer token.
 */
public class BearerTokenRequestConfig implements RequestConfig {

    public static final String AUTHORIZATION_HEADER = "Authorization";
    public static final String BEARER = "Bearer";

    private final String token;

    public BearerTokenRequestConfig(final String token) {
        this.token = Validate.notBlank(token);
    }

    @Override
    public Map<String, String> getHeaders() {
        final Map<String,String> headers = new HashMap<>();
        headers.put(AUTHORIZATION_HEADER, BEARER + " " + token);
        return headers;
    }
}


text:
#pragma once

#include <cusp/format.h>
#include <cusp/csr_matrix.h>

#include <cusp/detail/functional.h>

#ifdef INTEL_MKL_SPBLAS
#include <cusp/detail/host/spmv_mkl.h>
#else
#include <cusp/detail/host/spmv.h>
#endif

#include <cusp/detail/host/detail/coo.h>
#include <cusp/detail/host/detail/csr.h>

namespace cusp
{
namespace detail
{
namespace host
{

//////////////////////////////////
// Dense Matrix-Vector Multiply //
//////////////////////////////////
template <typename Matrix,
          typename Vector1,
          typename Vector2>
void multiply(const Matrix&  A,
              const Vector1& B,
                    Vector2& C,
              cusp::array2d_format,
              cusp::array1d_format,
              cusp::array1d_format)
{
    typedef typename Vector2::value_type ValueType;

    for(size_t i = 0; i < A.num_rows; i++)
    {
        ValueType sum = 0;
        for(size_t j = 0; j < A.num_cols; j++)
        {
            sum += A(i,j) * B[j];
        }
        C[i] = sum;
    }
}

///////////////////////////////////
// Sparse Matrix-Vector Multiply //
///////////////////////////////////
template <typename Matrix,
          typename Vector1,
          typename Vector2>
void multiply(const Matrix&  A,
              const Vector1& B,
                    Vector2& C,
              cusp::coo_format,
              cusp::array1d_format,
              cusp::array1d_format)
{
    cusp::detail::host::spmv_coo(A, B, C);
}

template <typename Matrix,
          typename Vector1,
          typename Vector2>
void multiply(const Matrix&  A,
              const Vector1& B,
                    Vector2& C,
              cusp::csr_format,
              cusp::array1d_format,
              cusp::array1d_format)
{
    cusp::detail::host::spmv_csr(A, B, C);
}

template <typename Matrix,
          typename Vector1,
          typename Vector2>
void multiply(const Matrix&  A,
              const Vector1& B,
                    Vector2& C,
              cusp::dia_format,
              cusp::array1d_format,
              cusp::array1d_format)
{
    cusp::detail::host::spmv_dia(A, B, C);
}

template <typename Matrix,
          typename Vector1,
          typename Vector2>
void multiply(const Matrix&  A,
              const Vector1& B,
                    Vector2& C,
              cusp::ell_format,
              cusp::array1d_format,
              cusp::array1d_format)
{
    cusp::detail::host::spmv_ell(A, B, C);
}

template <typename Matrix,
          typename Vector1,
          typename Vector2>
void multiply(const Matrix&  A,
              const Vector1& B,
                    Vector2& C,
              cusp::hyb_format,
              cusp::array1d_format,
              cusp::array1d_format)
{
    typedef typename Vector2::value_type ValueType;

    cusp::detail::host::spmv_ell(A.ell, B, C);
    cusp::detail::host::spmv_coo(A.coo, B, C, thrust::identity<ValueType>(), thrust::multiplies<ValueType>(), thrust::plus<ValueType>());
}

////////////////////////////////////////
// Sparse Matrix-BlockVector Multiply //
////////////////////////////////////////
//// TODO implement this w/ repeated SpMVs and then specialize
//template <typename Matrix,
//          typename Vector1,
//          typename Vector2>
//void multiply(const Matrix&  A,
//              const Vector1& B,
//                    Vector2& C,
//              cusp::detail::sparse_format,
//              cusp::detail::array2d_format,
//              cusp::detail::array2d_format)
//{
//}

////////////////////////////////////////
// Dense Matrix-Matrix Multiplication //
////////////////////////////////////////
template <typename Matrix1,
          typename Matrix2,
          typename Matrix3>
void multiply(const Matrix1&  A,
              const Matrix2& B,
                    Matrix3& C,
              cusp::array2d_format,
              cusp::array2d_format,
              cusp::array2d_format)
{
    typedef typename Matrix3::value_type ValueType;

    C.resize(A.num_rows, B.num_cols);

    for(size_t i = 0; i < C.num_rows; i++)
    {
        for(size_t j = 0; j < C.num_cols; j++)
        {
            ValueType v = 0;

            for(size_t k = 0; k < A.num_cols; k++)
                v += A(i,k) * B(k,j);

            C(i,j) = v;
        }
    }
}

/////////////////////////////////////////
// Sparse Matrix-Matrix Multiplication //
/////////////////////////////////////////
template <typename Matrix1,
          typename Matrix2,
          typename Matrix3>
void multiply(const Matrix1& A,
              const Matrix2& B,
                    Matrix3& C,
              cusp::coo_format,
              cusp::coo_format,
              cusp::coo_format)
{
    cusp::detail::host::detail::spmm_coo(A,B,C);
}

template <typename Matrix1,
          typename Matrix2,
          typename Matrix3>
void multiply(const Matrix1& A,
              const Matrix2& B,
                    Matrix3& C,
              cusp::csr_format,
              cusp::csr_format,
              cusp::csr_format)
{
    cusp::detail::host::detail::spmm_csr(A,B,C);
}

template <typename Matrix1,
          typename Matrix2,
          typename Matrix3>
void multiply(const Matrix1& A,
              const Matrix2& B,
                    Matrix3& C,
              cusp::sparse_format,
              cusp::sparse_format,
              cusp::sparse_format)
{
    // other formats use CSR * CSR
    cusp::csr_matrix<typename Matrix1::index_type,typename Matrix1::value_type,cusp::host_memory> A_(A);
    cusp::csr_matrix<typename Matrix2::index_type,typename Matrix2::value_type,cusp::host_memory> B_(B);
    cusp::csr_matrix<typename Matrix3::index_type,typename Matrix3::value_type,cusp::host_memory> C_;

    cusp::detail::host::detail::spmm_csr(A_,B_,C_);

    cusp::convert(C_, C);
}

/////////////////
// Entry Point //
/////////////////
template <typename Matrix,
          typename MatrixOrVector1,
          typename MatrixOrVector2>
void multiply(const Matrix&  A,
              const MatrixOrVector1& B,
                    MatrixOrVector2& C)
{
  cusp::detail::host::multiply(A, B, C,
                               typename Matrix::format(),
                               typename MatrixOrVector1::format(),
                               typename MatrixOrVector2::format());
}

} // end namespace host
} // end namespace detail
} // end namespace cusp


text:
import * as R from 'ramda';
import * as Vars from '../game/vars';
import { isString, isArray, isObject } from '../util/utils';

import * as L from '../types/logic';
import { VariableRef } from '../types/common';
import { State } from '../data/state';
// import { isLogicAtom, isCombinator } from './typecheck';

type Condition = L.LogicAtom | L.Combinator;
type Expr = [VariableRef, VariableRef | number];

function compare(state: State, expr: Expr, comparison: any): boolean {
    const [var1, par] = expr;
    const gameVar = Vars.getValue(state, var1);
    const compareTo = isString(par) ? Vars.getValue(state, par) : par;
    return comparison(gameVar, compareTo);
}

const COMP = {
    exists: (state: State, ref: VariableRef): boolean =>
        Vars.getValue(state, ref) !== undefined,
    eq: (state: State, expr: Expr) =>
        compare(state, expr, (x: number, y: number) => x === y),
    lt: (state: State, expr: Expr) =>
        compare(state, expr, (x: number, y: number) => x < y),
    lte: (state: State, expr: Expr) =>
        compare(state, expr, (x: number, y: number) => x <= y),
    gt: (state: State, expr: Expr) =>
        compare(state, expr, (x: number, y: number) => x > y),
    gte: (state: State, expr: Expr) =>
        compare(state, expr, (x: number, y: number) => x >= y)
};

function isAndComb(a: any): a is L.AndCombinator { return !!a.and; }
function isOrComb(a: any): a is L.OrCombinator { return !!a.or; }
function isAllComb(a: any): a is L.AllCombinator { return !!a.all; }
function isAnyComb(a: any): a is L.AnyCombinator { return !!a.any; }
function isNoneComb(a: any): a is L.NoneCombinator { return !!a.none; }
function isNotComb(a: any): a is L.NotCombinator { return !!a.not; }

const LOGIC_ATOM_KEYS = ['exists', 'eq', 'lt', 'lte', 'gt', 'gte', 'value'];
function isLogicAtom(a: any): a is L.LogicAtom {
    return R.any((val) => val !== undefined, R.map((key) => a[key], LOGIC_ATOM_KEYS));
}

type ComparisonFunc = (state: State, expr: any) => boolean;
export function isTrue(state: State, expr: Condition | undefined): boolean {
    // The expression being undefined itself means it is true.
    if (!expr) {
        return true;
    }

    if (!isObject(expr)) {
        throw new Error('Logic expression was not an object.');
    }

    if (isLogicAtom(expr)) {
        if (expr.value !== undefined) {
            return expr.value;
        }
    }

    const callIsTrue = (e: Condition) => isTrue(state, e);

    if (isNoneComb(expr)) {
        return !R.any(callIsTrue, expr.none);
    }

    if (isAnyComb(expr)) {
        return R.any(callIsTrue, expr.any);
    }

    if (isAllComb(expr)) {
        return R.all(callIsTrue, expr.all);
    }

    if (isOrComb(expr)) {
        return isTrue(state, expr.or[0]) || isTrue(state, expr.or[1]);
    }

    if (isAndComb(expr)) {
        return isTrue(state, expr.and[0]) && isTrue(state, expr.and[1]);
    }

    if (isNotComb(expr)) {
        return isFalse(state, expr.not);
    }

    // --------------------------------
    // Actual game world checks
    const notExistsOrIsTrue = ([key, func]: [string, ComparisonFunc]) => {
        // const [key, func] = pair;
        if (expr[key]) {
            return func(state, expr[key]);
        }
        return true;
    };

    return R.all(notExistsOrIsTrue, R.toPairs(COMP));
    // --------------------
}

export function isFalse(state: any, expr: any): boolean {
    return !isTrue(state, expr);
}


text:
#include "PcapDeclarations.h"

namespace PcapDotNet { namespace Core
{
    /// <summary>
    /// Represents a buffer of packets to be sent.
    /// Note that transmitting a send buffer is much more efficient than performing a series of Send(), because the send buffer is buffered at kernel level drastically decreasing the number of context switches.
    /// </summary>
    public ref class PacketSendBuffer : System::IDisposable
    {
    public:
        /// <summary>
        /// This function allocates a send buffer, i.e. a buffer containing a set of raw packets that will be transimtted on the network with PacketCommunicator.Transmit().
        /// </summary>
        /// <param name="capacity">The size, in bytes, of the buffer, therefore it determines the maximum amount of data that the buffer will contain.</param>
        PacketSendBuffer(unsigned int capacity);

        property int Length
        {
            int get();
        }

        /// <summary>
        /// Adds a raw packet at the end of the send buffer.
        /// 'Raw packet' means that the sending application will have to include the protocol headers, since every packet is sent to the network 'as is'. The CRC of the packets needs not to be calculated, because it will be transparently added by the network interface.
        /// </summary>
        /// <param name="packet">The packet to be added to the buffer</param>
        /// <exception cref="System::InvalidOperationException">Thrown on failure.</exception>
        void Enqueue(Packets::Packet^ packet);

        /// <summary>
        /// Deletes a send buffer and frees all the memory associated with it.
        /// </summary>
        ~PacketSendBuffer();

    internal:
        void Transmit(pcap_t* pcapDescriptor, bool isSync);

    private:
        pcap_send_queue *_pcapSendQueue;
		int _length;
    };
}}


text:
RSpec.describe RestrictedStruct::Support do
  describe ".extract_keyword_args" do
    it "splits into list and last parameter if it is a hash" do
      expect(described_class.extract_keyword_args(
        [1, 2, 3, { :color => :red }]
      )).to eq([[1, 2, 3], { :color => :red }])
    end

    it "last parameter defaults to an empty hash" do
      expect(described_class.extract_keyword_args(
        [1, 2, 3, 4]
      )).to eq([[1, 2, 3, 4], {}])
    end

    it "list defaults to an empty list if only hash provided" do
      expect(described_class.extract_keyword_args(
        [{ :color => :red }]
      )).to eq([[], { :color => :red }])
    end

    it "returns empty list and hash if provided array is empty" do
      expect(described_class.extract_keyword_args([])).to eq([[], {}])
    end
  end
end


text:
<?php

namespace mako\gatekeeper\authorization;

/**
 * Authorizable interface.
 */
interface AuthorizableInterface
{
	/**
	 * Sets the authorizer.
	 *
	 * @param \mako\gatekeeper\authorization\AuthorizerInterface $authorizer Authorizer
	 */
	public function setAuthorizer(AuthorizerInterface $authorizer): void;

	/**
	 * Returns TRUE if allowed to perform the action on the entity and FALSE if not.
	 *
	 * @param  string        $action        Action
	 * @param  object|string $entity        Entity
	 * @param  mixed         ...$parameters Additional parameters
	 * @return bool
	 */
	public function can(string $action, object|string $entity, mixed ...$parameters): bool;
}


text:
using Robust.Shared.Interfaces.Serialization;
using Robust.Shared.IoC;
using Robust.Shared.Maths;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization;
using Robust.Shared.Utility;
using YamlDotNet.RepresentationModel;

namespace Content.Shared.Materials
{
    /// <summary>
    ///     Materials are read-only storage for the properties of specific materials.
    ///     Properties should be intrinsic (or at least as much is necessary for game purposes).
    /// </summary>
    public class Material : IExposeData
    {
        public string Name => _name;
        private string _name = "unobtanium";

        public Color Color => _color;
        private Color _color = Color.Gray;

        /// <summary>
        ///     Volumetric mass density, in kg.m^-3.
        /// </summary>
        public double Density => _density;
        private double _density = 1;

        /// <summary>
        ///     Electrical resistivity, NOT resistance.
        ///     Unit is ohm-meter (Ω⋅m).
        /// </summary>
        public double ElectricResistivity => _electricResistivity;
        private double _electricResistivity = 1;

        /// <summary>
        ///     Thermal conductivity, in W.m-1.K-1
        /// </summary>
        public double ThermalConductivity => _thermalConductivity;
        private double _thermalConductivity = 1;

        /// <summary>
        ///     Specific heat, in J.kg-1.K-1
        /// </summary>
        public double SpecificHeat => _specificHeat;
        private double _specificHeat = 1;

        /// <summary>
        ///     Controls how durable the material is.
        ///     Basically how slowly it degrades.
        /// </summary>
        public double Durability => _durability;
        private double _durability = 1;

        /// <summary>
        ///     Multiplier for how much this resists damage.
        ///     So higher means armor is more effective, for example.
        /// </summary>
        public double Hardness => _hardness;
        private double _hardness = 1;

        /// <summary>
        ///     Multiplier that determines damage on sharpness-based weapons like knives.
        ///     Higher means more damage is done.
        /// </summary>
        public double SharpDamage => _sharpDamage;
        private double _sharpDamage = 1;

        /// <summary>
        ///     Multiplier that determines damage on blunt-based weapons like clubs.
        ///     Higher means more damage is done.
        /// </summary>
        public double BluntDamage => _bluntDamage;
        private double _bluntDamage = 1;

        /// <summary>
        ///     An icon used to represent the material in graphic interfaces.
        /// </summary>
        public SpriteSpecifier Icon => _icon;
        private SpriteSpecifier _icon = SpriteSpecifier.Invalid;

        public string ID
        {
            get
            {
                var prototypeManager = IoCManager.Resolve<IPrototypeManager>();
                foreach (var prototype in prototypeManager.EnumeratePrototypes<MaterialPrototype>())
                {
                    if (prototype.Material == this) return prototype.ID;
                }

                return null;
            }
        }

        public void ExposeData(ObjectSerializer serializer)
        {
            serializer.DataField(ref _name, "name", "unobtanium", alwaysWrite: true);
            serializer.DataField(ref _color, "color", Color.Gray, alwaysWrite: true);

            // All default material params are initialized to 1 because
            // I'm too lazy to figure out for which that's necessary to prevent divisions by zero in case left out.
            serializer.DataField(ref _density, "density", 1, alwaysWrite: true);
            serializer.DataField(ref _electricResistivity, "electricResistivity", 1, alwaysWrite: true);
            serializer.DataField(ref _thermalConductivity, "thermalConductivity", 1, alwaysWrite: true);
            serializer.DataField(ref _specificHeat, "specificHeat", 1, alwaysWrite: true);
            serializer.DataField(ref _durability, "durability", 1, alwaysWrite: true);
            serializer.DataField(ref _hardness, "hardness", 1, alwaysWrite: true);
            serializer.DataField(ref _sharpDamage, "sharpDamage", 1, alwaysWrite: true);
            serializer.DataField(ref _bluntDamage, "bluntDamage", 1, alwaysWrite: true);
            serializer.DataField(ref _icon, "icon", SpriteSpecifier.Invalid, alwaysWrite: true);
        }
    }

    [Prototype("material")]
    public class MaterialPrototype : IPrototype, IIndexedPrototype
    {
        public string ID { get; private set; }

        public Material Material { get; private set; }

        public void LoadFrom(YamlMappingNode mapping)
        {
            ID = mapping["id"].AsString();

            var ser = YamlObjectSerializer.NewReader(mapping);
            Material = new Material();
            Material.ExposeData(ser);
        }
    }
}


text:
var fs = require('fs')
  , cssin = fs.readFileSync('test/acceptance/fixtures/css.in', 'ascii')
  , cssout = fs.readFileSync('test/acceptance/fixtures/css.out', 'ascii');

describe('diffs', function(){
  // uncomment the assertions, and run with different params to check the output
  // ex: --color, --no-color, --unified-diff

  it('should display a diff for small strings', function(){
    var expected = 'foo bar baz'
      , actual = 'foo rar baz';

    // expected.should.eql(actual);
  });

  it('should display a diff for medium strings', function(){
    var expected = 'foo bar baz\nfoo bar baz\nfoo bar baz'
      , actual = 'foo bar baz\nfoo rar baz\nfoo bar raz';

    // expected.should.eql(actual);
  });

  it('should display a diff for entire object dumps', function(){
     var expected = { name: 'joe',  age: 30, address: {city: 'new york', country: 'us'  }}
      , actual   = { name: 'joel', age: 30, address: {city: 'new york', country: 'usa' }};

      // actual.should.eql(expected);
  });

  it('should display a diff for multi-line strings', function(){
    var expected = 'one two three\nfour five six\nseven eight nine';
    var actual   = 'one two three\nfour zzzz six\nseven eight nine';

    // actual.should.eql(expected);
  });

  it('should display a diff for entire object dumps', function(){
    var expected = { name: 'joe',  age: 30, address: {city: 'new york', country: 'us'  }}
    var actual   = { name: 'joel', age: 30, address: {city: 'new york', country: 'usa' }};

    // actual.should.eql(expected);
  });

  it('should display a full-comparison with escaped special characters', function(){
    var expected = 'one\ttab\ntwo\t\ttabs';
    var actual   = 'one\ttab\ntwo\t\t\ttabs';

    //actual.should.equal(expected);
  });

  it('should display a word diff for large strings', function(){
    // cssin.should.equal(cssout);
  });

  it('should work with objects', function(){
    var tobi = {
      name: 'tobi',
      species: 'ferret',
      color: 'white',
      age: 2
    };

    var loki = {
      name: 'loki',
      species: 'ferret',
      color: 'brown',
      age: 2
    };

    // tobi.should.eql(loki);
  });
});


text:
package org.vizzini.illyriad.robot.inventory;

import org.apache.commons.lang3.StringUtils;
import org.vizzini.illyriad.City;
import org.vizzini.illyriad.ResourceIngredient;

/**
 * Provides inventory data.
 */
public final class InventoryData
{
    /** City. */
    private final City city;

    /** Count. */
    private final String count;

    /** Resource ingredient. */
    private final ResourceIngredient ingredient;

    /**
     * Construct this object.
     *
     * @param city City.
     * @param ingredient Resource ingredient.
     * @param count Count.
     */
    @SuppressWarnings("hiding")
    public InventoryData(final City city, final ResourceIngredient ingredient, final String count)
    {
        if (city == null)
        {
            throw new IllegalArgumentException("city is null");
        }

        if (ingredient == null)
        {
            throw new IllegalArgumentException("resource is null");
        }

        if (StringUtils.isEmpty(count))
        {
            throw new IllegalArgumentException("count is null or empty");
        }

        this.city = city;
        this.ingredient = ingredient;
        this.count = count;
    }

    /**
     * @return the city
     */
    public City getCity()
    {
        return city;
    }

    /**
     * @return the count
     */
    public String getCount()
    {
        return count;
    }

    /**
     * @return the ingredient
     */
    public ResourceIngredient getIngredient()
    {
        return ingredient;
    }
}


text:
<?php

declare(strict_types=1);

namespace Sphp\Tests\Apps\GettextFinder;

use PHPUnit\Framework\TestCase;
use SplFileInfo;
use Sphp\Apps\PoSearch\Data\PoFile;
use Sphp\Apps\PoSearch\Data\MoFile;

/**
 * Class MoFileTest
 *
 * @author  Sami Holck <sami.holck@gmail.com>
 * @license https://opensource.org/licenses/MIT MIT License
 * @link    https://github.com/samhol/SPHP-framework Github repository
 * @filesource
 */
class MoFileTest extends TestCase {

  public function validMoFiles(): array {
    $pos = glob('./sphp/locale/*/*/*.mo');
    // print_r($pos);
    $info = [];
    foreach ($pos as $po) {
      $info[] = [new SplFileInfo($po)];
    }
    return $info;
  }

  /**
   * @dataProvider validMoFiles
   *
   * @param  SplFileInfo $fileInfo
   * @return void
   */
  public function testConstructor(SplFileInfo $fileInfo): void {
   // print_r($fileInfo);
    $file = new MoFile($fileInfo);
    $this->assertSame($fileInfo, $file->getFileInfo());
    //$this->assertEquals(new PoEntryCollection($fileInfo->getRealPath()), $file->getEntryCollection());
    if (is_file($fileInfo->getPath() . '/' . $file->getFileName() . '.po')) {
      $this->assertTrue($file->hasPoFile());
      $po = $file->getPoFile();
      $this->assertInstanceOf(PoFile::class, $po);
    } else {
      $this->assertFalse($file->hasPoFile());
      $this->assertNull($file->getPoFile());
    }
  }

}


text:
import Checkbox from './Checkbox';
import CheckboxGroup from './ChekboxGroup';

export {
  CheckboxGroup,
  Checkbox,
};


text:
layout: docs
title: Build configuration
---

# Build configuration

## Build environment

Every build runs on a fresh virtual machine which is not shared with other builds and the state of which is not preserved between consequent builds. After the build is finished its virtual machine is decommissioned.

### Virtual machine configurations

    Environment/configuration
    CPU
    Memory
    Disk
    Network

    Pro
    2 cores
    2.5 GB
    SSD 127 GB
(30 GB available)
    1 Gbps

    Open-Source (Free)
    1 core
    1.7 GB
    SSD 127 GB
(20 GB available)
	1 Gbps

    Azure* (Pro)
    2 cores
(Basic_A2)
    3.5 GB
    127 GB
(30 GB available)
    200 Mbps

    Azure* (open-source)
    1 core
(Basic_A1)
    1.75 GB
    127 GB
(30 GB available)
    100 Mbps

> \* Builds configured to use custom image (`os` setting in `appveyor.yml` or `Operating system` on UI) run on virtual machines in Microsoft Azure data center.

### IP addresses

IP addresses assigned to build workers:

	169.54.128.0/27
	169.54.128.128/27
    75.126.44.184/29
    108.168.222.0/27
    192.155.202.64/27

IP address of AppVeyor workers (when deploying using "Environments"):

    138.91.141.243

## Build pipeline

Every build goes through the following steps:

1. Run `init` scripts
2. **Clone** repository into clone folder

    * Checkout build commit
    * `cd` to clone folder

3. Run `install` scripts
4. Patch `AssemblyInfo` files
5. Modify `hosts` files
6. Start services
7. **Build**

    * Run `before_build` scripts
    * Run msbuild
    * Run `after_build` scripts

8. **Test**

    * Run `before_test` scripts
    * Discover and run tests
    * Run `after_test` scripts

9. Call `build_success` webhooks
10. **Package** artifacts
11. **Deployment**

    * Run `before_deploy` scripts
    * Run all configured deployments
    * Run `after_deploy` scripts

12. For successful builds:

    * Call `deployment_success` webhooks
    * Run `on_success` scripts

13. For failed builds:

    * Call `build_failure` webhooks
    * Call `deployment_failure` webhooks
    * Run `on_failure` scripts

14. For both successful and failed builds:
    * Call `on_finish` scripts

### Time limitations

Free, Professional and Premium plans have a hard quota of 30 minutes on build execution time. Enterprise plans allow 50 minutes per build job.

## Configuring build

Project builds can be configured by either `appveyor.yml` or on the user interface.

Each method has pros and cons. Via the User interface one can control every aspect of the build process without ever touching the repository. On the other hand, YAML may seem more sophisticated and familiar for those coming from a Linux platform. Another thing to consider is that when you fork/clone a project with its configuration stored in `appveyor.yml`, you simply add a new project in AppVeyor referencing repo and you are good to go.

> It's worth noticing that both `appveyor.yml` and UI configuration are mutually exclusive. It's always either YAML or UI - the settings from each are not merged. If you have `appveyor.yml` in your repo it will override all settings made on the UI unless explicitly disabled by **Ignore appveyor.yml**. The only exceptions are environment variables and notification settings. Environment variables defined on UI are getting merged with those ones defined in `appveyor.yml`. Variable values with the same names are getting overridden with values from UI.

### appveyor.yml

`appveyor.yml` is a project configuration file in YAML format that should be placed in the root of your repository.
At a minimum `appveyor.yml` is just an empty file.

While working with YAML there are few important points to be aware of:

* YAML format is sensitive to indentations that must be **spaces**. Do not use tabs to indent configuration sections.
* Section names in YAML are case-sensitive, so "deploy" and "Deploy" are different things in YAML.

## Build versioning

Every time you push changes into repo or click the **New build** button AppVeyor starts a new build with an incremented build number.

You may use the **build number** for versioning purposes (assemblies version patching, naming artifacts, etc.) or just use it for reference.

AppVeyor uses the **version** value for naming builds. You can have "through" builds numbering in which major and minor parts of the version are changing and the build number is never reset or you can reset the build number for every new version. In any case, while the build number could be reset to any previously used value, the *version must be unique* across all builds.

You can specify version format in `appveyor.yml`:

    version: 1.0.{build}

## AssemblyInfo patching

AppVeyor has a built-in task for `AssemblyInfo` patching. Patching is disabled by default for newly added projects.

You can enable patching on the **General** tab of project settings or in `appveyor.yml`:

    assembly_info:
      patch: true
      file: MyVersion.cs
      assembly_version: '{version}'
      assembly_file_version: '{version}'
      assembly_informational_version: '{version}-rc1'

You can use environment variables substitution in file name and version formats, for example:

    assembly_version: $(appveyor_build_version)

## Clone directory

The format of the default directory on the build machine for cloning repository is `c:\projects\<project-slug>`.

If required by your project (say, if absolute paths are used to reference its parts) you can change the clone directory path on the **Environment** tab of project settings or in `appveyor.yml`:

    clone_folder: c:\projects\myproject

## Environment variables

Immediately after cloning the repo on the build worker AppVeyor sets [standard environment variables](/docs/environment-variables).

### Custom environment variables

Custom environment variables can be set on the **Environment** tab of project settings or in `appveyor.yml`:

    environment:
      variable1: value
      variable2: value

### Setting environment variables in build script

CMD:

    set MY_VARIABLE=value

PowerShell:

    $env:MY_VARIABLE="value"

### Secure variables

When you work with OSS projects and you'd like to hide some sensitive data from everyone's eyes you can use **secure variables** in `appveyor.yml`.

AppVeyor generates a unique encryption key for every account. To encrypt variable values go to **Account -> Encrypt data** tool.

To use encrypted variable in `appveyor.yml`:

    environment:
      my_variable:
        secure: <encrypt_value>

> "Secure" variables means you can safely put them into `appveyor.yml` that is visible to others. Other than that they are just regular environment variables in a build session that could be easily displayed in a build log by simple `Get-ChildItem env:`.

>However, secure variables are *not* decoded during Pull Request builds which prevents someone from submitting PR with malicious build script displaying those variables. In more controlled environment through with a trusted team and private GitHub repositories there is an option on General tab of project settings to allow secure variables for PRs.

## Script blocks in build configuration

There are a lot of places in configuration where you can inject your custom logic like "install" scripts, "before build", "after tests", "deploy" scripts, etc.

Every script could be authored either as a batch or PowerShell snippet.

When you set **Cmd** script on the UI its body will be split into lines and executed as separate commands with an exit code check after each line. For example, consider the following "install" script:

![install script cmd](/site/images/docs/install-script-cmd.png)

If exit code of the first command (`gem update --system`) is different from a 0 script execution will be terminated and entire build will return as failed.

When **PowerShell** is selected the entire body is treated as a single script, so you can use control flow logic inside it. For example:

![build script ps](/site/images/docs/build-script-ps.png)

PowerShell script is considered successful if it finishes without exception.

There are a few ways of configuring scripts in `appveyor.yml`.

For example, this is the same configuration as shown on the first screenshot:

    install:
      - gem update --system
      - gem install rake

By default, script line is treated as batch command, but you can specify script engine explicitly:

    before_build:
      - cmd: ECHO this is batch
      - ps: Write-Host "This is PowerShell"

To add multi-line PowerShell script covering an entire event:

	on_success:
	  - ps: |
	  if($true)
	  {
	    Write-Host "Success"
	  }

## Installing additional software

Every build runs on a pristine virtual machine that is not shared with any other builds. VM state is not preserved between builds.

You can install additional software on the build machine using Chocolatey, Web Platform Installer (Web PI) or PowerShell.

    install:


text:
using System;
using System.Collections.Generic;
using System.Linq;

using ASC.Common.Data;
using ASC.Common.Data.Sql;

namespace ASC.Core.Common.Notify.FireBase.Dao
{
    public class FirebaseDao
    {
        public FireBaseUser RegisterUserDevice(Guid userId, int tenantId, string fbDeviceToken, bool isSubscribed, string application)
        {
            using (var db = GetDbManager())
            {
                var q = new SqlQuery("firebase_users")
                        .SelectCount()
                        .Where("user_id", userId)
                        .Where("tenant_id", tenantId)
                        .Where("application", application)
                        .Where("firebase_device_token", fbDeviceToken);

                if (db.ExecuteScalar<int>(q) == 0)
                {
                    db.ExecuteScalar<int>(new SqlInsert("firebase_users").ReplaceExists(true)
                    .InColumnValue("user_id", userId)
                    .InColumnValue("tenant_id", tenantId)
                    .InColumnValue("firebase_device_token", fbDeviceToken)
                    .InColumnValue("application", application)
                    .InColumnValue("is_subscribed", isSubscribed));
                }

            }
            var list = GetUserDeviceTokens(userId, tenantId, application);
            foreach (var fb in list)
            {
                if (fb.FirebaseDeviceToken == fbDeviceToken)
                {
                    return fb;
                }
            }
            return null;

        }

        public List<FireBaseUser> GetUserDeviceTokens(Guid userId, int tenantId, string application)
        {
            using (var db = GetDbManager())
            {
                var q = new SqlQuery("firebase_users").SelectAll().Where("user_id", userId).Where("tenant_id", tenantId).Where("application", application);

                return db.ExecuteList(q, x => new FireBaseUser()
                {
                    UserId = Guid.Parse(x.Get<string>("user_id")),
                    TenantId = x.Get<int>("tenant_id"),
                    FirebaseDeviceToken = x.Get<string>("firebase_device_token"),
                    Application = x.Get<string>("application"),
                    IsSubscribed = Convert.ToBoolean(x.Get<int>("is_subscribed")),
                });
            }
        }

        public FireBaseUser UpdateUser(Guid userId, int tenantId, string fbDeviceToken, bool isSubscribed, string application)
        {
            using (var db = GetDbManager())
            {

                var q = new SqlUpdate("firebase_users")
                        .Set("is_subscribed", isSubscribed)
                        .Where("user_id", userId)
                        .Where("tenant_id", tenantId)
                        .Where("firebase_device_token", fbDeviceToken)
                        .Where("application", application);
                db.ExecuteNonQuery(q);

                return new FireBaseUser() { UserId = userId, TenantId = tenantId, FirebaseDeviceToken = fbDeviceToken, IsSubscribed = isSubscribed, Application = application };

            }
        }

        private IDbManager GetDbManager()
        {
            return DbManager.FromHttpContext("default");
        }

    }
}


text:
FactoryGirl.define do
  factory :user do
    email 'test@example.com'
    password 'password'
    password_confirmation 'password'

    factory :other_user do
      email 'otheruser@example.com'
      password 'password'
      password_confirmation 'password'
    end
  end
end


text:
======================================
 Image Processing: Arithmetic changes
======================================
Changed the name of the package folder img_proc to image_processing for
explicit clarity for users.
Changed the name of module mathops.py to arithmetic.py since this module
explicitly wraps or defines all of the basic image arithmetic and logic
operations


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

    <dataSet config="main" >
        <source path="/home/huibin/android/project/GradleProjectForAndroid/AndroidLibProject/src/main/assets" />
    </dataSet>
    <dataSet config="debug" >
        <source path="/home/huibin/android/project/GradleProjectForAndroid/AndroidLibProject/src/debug/assets" />
    </dataSet>

</merger>


text:
namespace ALinq.SqlClient
{
    internal static class SqlNodeTypeOperators
    {
        // Methods
        internal static bool IsBinaryOperatorExpectingPredicateOperands(this SqlNodeType nodeType)
        {
            switch (nodeType)
            {
                case SqlNodeType.BitAnd:
                case SqlNodeType.BitOr:
                case SqlNodeType.BitXor:
                case SqlNodeType.Add:
                case SqlNodeType.Coalesce:
                case SqlNodeType.Concat:
                case SqlNodeType.Div:
                case SqlNodeType.EQ:
                case SqlNodeType.EQ2V:
                case SqlNodeType.LE:
                case SqlNodeType.LT:
                case SqlNodeType.GE:
                case SqlNodeType.GT:
                case SqlNodeType.Mod:
                case SqlNodeType.Mul:
                case SqlNodeType.NE:
                case SqlNodeType.NE2V:
                case SqlNodeType.Sub:
                    return false;

                case SqlNodeType.And:
                case SqlNodeType.Or:
                    return true;
            }
            throw Error.UnexpectedNode(nodeType);
        }

        internal static bool IsClientAidedExpression(this SqlExpression expr)
        {
            SqlNodeType nodeType = expr.NodeType;
            if (nodeType <= SqlNodeType.Link)
            {
                switch (nodeType)
                {
                    case SqlNodeType.ClientQuery:
                    case SqlNodeType.Element:
                    case SqlNodeType.Link:
                        goto Label_002C;
                }
                goto Label_002E;
            }
            if (((nodeType != SqlNodeType.Multiset) && (nodeType != SqlNodeType.New)) &&
                (nodeType != SqlNodeType.TypeCase))
            {
                goto Label_002E;
            }
            Label_002C:
            return true;
            Label_002E:
            return false;
        }

        internal static bool IsComparisonOperator(this SqlNodeType nodeType)
        {
            switch (nodeType)
            {
                case SqlNodeType.BitAnd:
                case SqlNodeType.BitOr:
                case SqlNodeType.BitXor:
                case SqlNodeType.And:
                case SqlNodeType.Add:
                case SqlNodeType.Coalesce:
                case SqlNodeType.Concat:
                case SqlNodeType.Div:
                case SqlNodeType.Mod:
                case SqlNodeType.Mul:
                case SqlNodeType.Or:
                case SqlNodeType.Sub:
                    return false;

                case SqlNodeType.EQ:
                case SqlNodeType.EQ2V:
                case SqlNodeType.LE:
                case SqlNodeType.LT:
                case SqlNodeType.GE:
                case SqlNodeType.GT:
                case SqlNodeType.NE:
                case SqlNodeType.NE2V:
                    return true;
            }
            throw Error.UnexpectedNode(nodeType);
        }

        internal static bool IsPredicateBinaryOperator(this SqlNodeType nodeType)
        {
            switch (nodeType)
            {
                case SqlNodeType.BitAnd:
                case SqlNodeType.BitOr:
                case SqlNodeType.BitXor:
                case SqlNodeType.Add:
                case SqlNodeType.Coalesce:
                case SqlNodeType.Concat:
                case SqlNodeType.Div:
                case SqlNodeType.Mod:
                case SqlNodeType.Mul:
                case SqlNodeType.Sub:
                    return false;

                case SqlNodeType.And:
                case SqlNodeType.EQ:
                case SqlNodeType.EQ2V:
                case SqlNodeType.LE:
                case SqlNodeType.LT:
                case SqlNodeType.GE:
                case SqlNodeType.GT:
                case SqlNodeType.NE:
                case SqlNodeType.NE2V:
                case SqlNodeType.Or:
                    return true;
            }
            throw Error.UnexpectedNode(nodeType);
        }

        internal static bool IsPredicateUnaryOperator(this SqlNodeType nodeType)
        {
            switch (nodeType)
            {
                case SqlNodeType.Avg:
                case SqlNodeType.BitNot:
                case SqlNodeType.Cast:
                case SqlNodeType.LongCount:
                case SqlNodeType.Convert:
                case SqlNodeType.Count:
                case SqlNodeType.Covar:
                case SqlNodeType.ClrLength:
                case SqlNodeType.Negate:
                case SqlNodeType.Min:
                case SqlNodeType.Max:
                case SqlNodeType.Sum:
                case SqlNodeType.ValueOf:
                case SqlNodeType.OuterJoinedValue:
                case SqlNodeType.Stddev:
                    return false;

                case SqlNodeType.IsNotNull:
                case SqlNodeType.IsNull:
                case SqlNodeType.Not:
                case SqlNodeType.Not2V:
                    return true;
            }
            throw Error.UnexpectedNode(nodeType);
        }

        internal static bool IsUnaryOperatorExpectingPredicateOperand(this SqlNodeType nodeType)
        {
            SqlNodeType type = nodeType;
            if (type <= SqlNodeType.LongCount)
            {
                switch (type)
                {
                    case SqlNodeType.Avg:
                    case SqlNodeType.BitNot:
                    case SqlNodeType.Cast:
                    case SqlNodeType.IsNotNull:
                    case SqlNodeType.IsNull:
                    case SqlNodeType.LongCount:
                    case SqlNodeType.Convert:
                    case SqlNodeType.Count:
                    case SqlNodeType.Covar:
                    case SqlNodeType.ClrLength:
                        goto Label_00A9;
                }
                goto Label_00AB;
            }
            if (type <= SqlNodeType.Not2V)
            {
                switch (type)
                {
                    case SqlNodeType.Negate:
                    case SqlNodeType.Min:
                    case SqlNodeType.Max:
                        goto Label_00A9;

                    case SqlNodeType.New:
                        goto Label_00AB;

                    case SqlNodeType.Not:
                    case SqlNodeType.Not2V:
                        return true;
                }
                goto Label_00AB;
            }
            if (type <= SqlNodeType.Stddev)
            {
                switch (type)
                {
                    case SqlNodeType.OuterJoinedValue:
                    case SqlNodeType.Stddev:
                        goto Label_00A9;
                }
                goto Label_00AB;
            }
            if ((type != SqlNodeType.Sum) && (type != SqlNodeType.ValueOf))
            {
                goto Label_00AB;
            }
            Label_00A9:
            return false;
            Label_00AB:
            throw Error.UnexpectedNode(nodeType);
        }
    }
}


text:
@implementation Sprite
- (instancetype) initWithName: (NSString*) name
                      ownView: (UIView*) view
                      inScene: (Scene*) scene {
    if (self = [super init]) {
        self.name = name;
        self.view = view;
        self.scene = scene;
    }
    return self;
}

- (instancetype) initWithName: (NSString*) name
                      inScene: (Scene*) scene {
    if (self = [super init]) {
        self.name = name;
        self.scene = scene;
    }
    return self;
}
- (void) animate {
    //Do nothing here. All custome sprite need to override this method
}
@end


text:
<?php

/**
 * @file
 * Contains \Drupal\Tests\block\BlockFormControllerTest.
 */

namespace Drupal\Tests\block;

use Drupal\block\BlockFormController;
use Drupal\Tests\UnitTestCase;

// @todo Remove once the constants are replaced with constants on classes.
if (!defined('BLOCK_REGION_NONE')) {
  define('BLOCK_REGION_NONE', -1);
}

// @todo Remove once the constants are replaced with constants on classes.
if (!defined('FIELD_LOAD_CURRENT')) {
  define('FIELD_LOAD_CURRENT', 'FIELD_LOAD_CURRENT');
}

/**
 * Tests the block form controller.
 *
 * @see \Drupal\block\BlockFormController
 */
class BlockFormControllerTest extends UnitTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Block form controller',
      'description' => 'Tests the block form controller.',
      'group' => 'Block',
    );
  }

  /**
   * Tests the unique machine name generator.
   *
   * @see \Drupal\block\BlockFormController::getUniqueMachineName()
   */
  public function testGetUniqueMachineName() {
    $block_storage = $this->getMockBuilder('Drupal\block\BlockStorageController')
      ->disableOriginalConstructor()
      ->getMock();
    $blocks = array();

    $blocks['test'] = $this->getBlockMockWithMachineName('test');
    $blocks['other_test'] = $this->getBlockMockWithMachineName('other_test');
    $blocks['other_test_1'] = $this->getBlockMockWithMachineName('other_test');
    $blocks['other_test_2'] = $this->getBlockMockWithMachineName('other_test');

    $query = $this->getMockBuilder('Drupal\Core\Entity\Query\QueryInterface')
      ->disableOriginalConstructor()
      ->getMock();
    $query->expects($this->exactly(5))
      ->method('condition')
      ->will($this->returnValue($query));

    $query->expects($this->exactly(5))
      ->method('execute')
      ->will($this->returnValue(array('test', 'other_test', 'other_test_1', 'other_test_2')));

    $query_factory = $this->getMockBuilder('Drupal\Core\Entity\Query\QueryFactory')
      ->disableOriginalConstructor()
      ->getMock();
    $query_factory->expects($this->exactly(5))
      ->method('get')
      ->with('block', 'AND')
      ->will($this->returnValue($query));

    $entity_manager = $this->getMockBuilder('Drupal\Core\Entity\EntityManager')
      ->disableOriginalConstructor()
      ->getMock();

    $entity_manager->expects($this->any())
      ->method('getStorageController')
      ->will($this->returnValue($block_storage));

    $language_manager = $this->getMockBuilder('Drupal\Core\Language\LanguageManager')
      ->disableOriginalConstructor()
      ->getMock();

    $block_form_controller = new BlockFormController($entity_manager, $query_factory, $language_manager);

    // Ensure that the block with just one other instance gets the next available
    // name suggestion.
    $this->assertEquals('test_2', $block_form_controller->getUniqueMachineName($blocks['test']));

    // Ensure that the block with already three instances (_0, _1, _2) gets the
    // 4th available name.
    $this->assertEquals('other_test_3', $block_form_controller->getUniqueMachineName($blocks['other_test']));
    $this->assertEquals('other_test_3', $block_form_controller->getUniqueMachineName($blocks['other_test_1']));
    $this->assertEquals('other_test_3', $block_form_controller->getUniqueMachineName($blocks['other_test_2']));

    // Ensure that a block without an instance yet gets the suggestion as
    // unique machine name.
    $last_block = $this->getBlockMockWithMachineName('last_test');
    $this->assertEquals('last_test', $block_form_controller->getUniqueMachineName($last_block));
  }

}


text:
#ifndef PageRuntimeAgent_h
#define PageRuntimeAgent_h

#include "InspectorWebAgentBase.h"
#include <inspector/InspectorFrontendDispatchers.h>
#include <inspector/agents/InspectorRuntimeAgent.h>

namespace JSC {
class ExecState;
}

namespace Inspector {
class InjectedScriptManager;
}

namespace WebCore {

class InspectorPageAgent;
class Frame;
class Page;
class SecurityOrigin;
typedef String ErrorString;

class PageRuntimeAgent final : public Inspector::InspectorRuntimeAgent {
    WTF_MAKE_FAST_ALLOCATED;
public:
    PageRuntimeAgent(PageAgentContext&, InspectorPageAgent*);
    virtual ~PageRuntimeAgent() { }

    void didCreateFrontendAndBackend(Inspector::FrontendRouter*, Inspector::BackendDispatcher*) override;
    void willDestroyFrontendAndBackend(Inspector::DisconnectReason) override;
    void enable(ErrorString&) override;
    void disable(ErrorString&) override;

    // InspectorInstrumentation callbacks.
    void didCreateMainWorldContext(Frame&);

private:
    Inspector::InjectedScript injectedScriptForEval(ErrorString&, const int* executionContextId) override;
    void muteConsole() override;
    void unmuteConsole() override;
    void reportExecutionContextCreation();
    void notifyContextCreated(const String& frameId, JSC::ExecState*, SecurityOrigin*, bool isPageContext);

    std::unique_ptr<Inspector::RuntimeFrontendDispatcher> m_frontendDispatcher;
    RefPtr<Inspector::RuntimeBackendDispatcher> m_backendDispatcher;
    InspectorPageAgent* m_pageAgent;

    Page& m_inspectedPage;

    bool m_mainWorldContextCreated { false };
};

} // namespace WebCore

#endif // !defined(InspectorPagerAgent_h)


text:
package org.ofbiz.content.webapp.ftl;

import java.io.IOException;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.content.content.ContentUrlFilter;
import org.ofbiz.webapp.control.WebAppConfigurationException;
import org.ofbiz.webapp.renderer.RenderEnvType;

import com.ilscipio.scipio.ce.webapp.ftl.context.ContextFtlUtil;
import com.ilscipio.scipio.ce.webapp.ftl.context.TransformUtil;
import com.ilscipio.scipio.ce.webapp.ftl.context.UrlTransformUtil;

import freemarker.core.Environment;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateTransformModel;

/**
 * Content Alt URL transform.
 *

 * SCIPIO: Added urlDecode boolean param.
 * and changed the logical default to false compared to stock Ofbiz (where
 * it would have been true).
 */
public class OfbizContentAltUrlTransforms implements TemplateTransformModel {
    private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());

    @Override
    public Writer getWriter(final Writer out, @SuppressWarnings("rawtypes") final Map args)
            throws TemplateModelException, IOException {
        //final StringBuilder buf = new StringBuilder(); // SCIPIO: Does nothing
        return new Writer(out) {

            @Override
            public void write(char[] cbuf, int off, int len) throws IOException {
                //buf.append(cbuf, off, len);
            }

            @Override
            public void flush() throws IOException {
                out.flush();
            }

            @Override
            public void close() throws IOException {
                try {
                    Environment env = FreeMarkerWorker.getCurrentEnvironment();
                    HttpServletRequest request = ContextFtlUtil.getRequest(env); // SCIPIO
                    HttpServletResponse response = ContextFtlUtil.getResponse(env);
                    RenderEnvType renderEnvType = ContextFtlUtil.getRenderEnvType(env, request);
                    //FullWebappInfo.Cache webappInfoCache = ContextFtlUtil.getWebappInfoCacheAndCurrent(env, request, renderEnvType);

                    final String escapeAs = TransformUtil.getStringArg(args, "escapeAs"); // SCIPIO: new
                    boolean rawParamsDefault = UtilValidate.isNotEmpty(escapeAs) ? true : false; // SCIPIO: if we're post-escaping, we can assume we should get rawParams
                    boolean rawParams = TransformUtil.getBooleanArg(args, "rawParams", rawParamsDefault); // SCIPIO: new
                    boolean strictDefault = UtilValidate.isNotEmpty(escapeAs) ? true : false; // SCIPIO: if we're post-escaping, we can assume we want strict handling
                    final Boolean strict = TransformUtil.getBooleanArg(args, "strict", strictDefault); // SCIPIO: new

                    Boolean fullPath = UrlTransformUtil.determineFullPath(TransformUtil.getBooleanArg(args, "fullPath"), renderEnvType, env); // SCIPIO: changed from boolean to Boolean
                    Boolean secure = TransformUtil.getBooleanArg(args, "secure"); // SCIPIO: changed from boolean to Boolean
                    Boolean encode = TransformUtil.getBooleanArg(args, "encode"); // SCIPIO: new flag
                    Object urlParams = TransformUtil.getStringArg(args, "params", rawParams); // SCIPIO: new; TODO: support map (but needs special handling to respect rawParams)

                    String contentId = TransformUtil.getStringArg(args, "contentId", rawParams);
                    String viewContent = TransformUtil.getStringArg(args, "viewContent", rawParams);
                    Boolean urlDecode = TransformUtil.getBooleanArg(args, "urlDecode");

                    String url = "";
                    if (UtilValidate.isNotEmpty(contentId)) {
                        Locale locale = TransformUtil.getOfbizLocaleArgOrCurrent(args, "locale", env); // SCIPIO
                        if (request != null) {
                            // SCIPIO: replaced
                            //url = ContentUrlFilter.makeContentAltUrl(request, response, contentId, viewContent, urlDecode);
                            url = ContentUrlFilter.makeContentAltLink(request, response, locale, contentId, viewContent, urlDecode, urlParams, fullPath, secure, encode);
                        } else {
                            // TODO: when from static context...
                            Debug.logWarning("@ofbizContentAltUrl transform is not implemented for non-webapp render contexts", module);
                        }
                        out.write(UrlTransformUtil.escapeGeneratedUrl(url, escapeAs, strict, env));
                    }
                } catch (TemplateModelException e) {
                    throw new IOException(e.getMessage());
                } catch (WebAppConfigurationException e) { // SCIPIO
                    throw new IOException(e.getMessage());
                }
            }
        };
    }
}


text:
<suite name="SauceTestSuite" verbose="5" parallel="tests" thread-count="10">
    <test name="WebDriverTests">
        <classes>
            <class name="com.saucelabs.WebDriverTest"/>
        </classes>
    </test>

    <listeners>
        <listener class-name="com.saucelabs.testng.SauceOnDemandTestListener"/>
    </listeners>
</suite>


text:
<?php if(!defined('IN_PHPVMS') && IN_PHPVMS !== true) { die(); } ?>
<?php
/*
 * DO NOT EDIT THIS TEMPLATE UNLESS:
 *   1. YOU HAVE ALOT OF TIME
 *   2. YOU DON'T MIND LOSING SOME HAIR
 *   3. YOU HAVE BIG BALLS MADE OF STEEL
 *
 *	It can cause incontinence
 *
 *	YOU HAVE BEEN WARNED!!!
 */
?><?php Template::Show('finance_header.tpl'); ?>

<?php echo $title?>

<?php

	$total = 0;

	$profit = array();
	$pilot_pay = array();
	$revenue = array();
	$expenses = array();
	$flightexpenses = array();
	$fuelexpenses = array();
	$months=array();

?>

		Month
		Flights
		Revenue
		Pilot Pay
		Expenses
		Fuel
		Total

<?php
echo '
';
//print_r($allfinances);
echo '
';
foreach ($allfinances as $month)
{
?>

			<?php
			echo $month->ym;
			?>

		<?php
			echo $month->total;
		?>

			<?php
			echo FinanceData::FormatMoney($month->gross);
			?>

			<?php
			echo FinanceData::FormatMoney(-1 * $month->pilotpay);
			?>

			<?php
			echo FinanceData::FormatMoney((-1) * $month->expenses_total);
			?>

			<?php
			echo FinanceData::FormatMoney((-1) * $month->fuelprice);
			?>

			<?php
			$profit[] = round($month->revenue, 2);
			$total += $month->revenue;
			echo FinanceData::FormatMoney($month->revenue);
			?>

<?php
}
?>

	Total:
	<?php echo FinanceData::FormatMoney($total);?>

Breakdown

<?php
/*
	Added in 2.0!
*/
$chart_width = '800';
$chart_height = '500';

/* Don't need to change anything below this here */
?>

<?php
/* End added in 2.0
*/
?>


text:
import { Component } from '@angular/core';

import { NavController, AlertController } from 'ionic-angular';

import { AuthService } from '../../../providers/auth-service';

import { CategoryData } from '../../../providers/category-data';

import { CategoryPage } from '../category/category';

@Component({
  selector: 'page-category-list',
  templateUrl: 'category-list.html'
})

export class CategoryListPage {

  incomeCategories: {};
  expenseCategories: {};
  previousgroup: string;
  previouscategory: string;

  constructor(
      public navCtrl: NavController,
      public alertController: AlertController,
      public auth: AuthService,
      public categoryData: CategoryData) {}

  ionViewDidLoad() {

    this.auth.getIncomeCategories().on('value', (incomecategories) => {
      let rawList= [];
      incomecategories.forEach( spanshot => {
        var cat = spanshot.val();
        rawList.push({
          $key: spanshot.key,
          categoryname: cat.categoryname,
          categorytype: cat.categorytype,
          categoryparent: cat.categoryparent,
          categorysort: cat.categorysort
        });
      });
      this.incomeCategories = rawList;
    });

    this.auth.getExpenseCategories().on('value', (expensecategories) => {
      let rawList= [];
      expensecategories.forEach( spanshot => {
        var cat = spanshot.val();
        rawList.push({
          $key: spanshot.key,
          categoryname: cat.categoryname,
          categorytype: cat.categorytype,
          categoryparent: cat.categoryparent,
          categorysort: cat.categorysort
        });
      });
      this.expenseCategories = rawList;
    });

    // Disable loading controller when the promise is complete
    this.auth.LoadingControllerDismiss();

  }

  viewItemDetails() {
    console.log('feature coming soon');
  }

  addItem() {
    this.navCtrl.push(CategoryPage, { key: '0' });
  }

  editItem(slidingItem, item) {
    this.handleSlidingItems(slidingItem);
    this.navCtrl.push(CategoryPage, { categorytype: item.categorytype, key: item.$key });
  }

  deleteItem(slidingItem, item) {
    let alert = this.alertController.create({
      title: 'Delete Category',
      message: 'Are you sure you want to delete ' + item.categoryname + ' and ALL the transactions?',
      buttons: [
        {
          text: 'Cancel',
          handler: () => {
            this.handleSlidingItems(slidingItem);
          }
        },
        {
          text: 'Delete',
          cssClass: 'alertDanger',
          handler: () => {
            this.handleSlidingItems(slidingItem);
            this.auth.deleteCategory(item);
          }
        }
      ]
    });
    alert.present();
  }

  showTransactions() {
    console.log('TO DO: show transactions view');
  }

  handleSlidingItems(slidingItem) {
    // Close any open sliding items when the page updates
    slidingItem.close();
  }

}


text:
layout: bigdata
type: bigdata
published: true
image: images/elk.png
title: cisco asa to ELK
permalink: bigdatas/data-asa-elk
date: 2017
labels:
  - cisco asa 5510
  - elk stack
summary: asa data collection - ELK.
---

what is elk stack?
what is elastic, logstash, kibana

There are few options when it comes to setting up ELK containers.
 * use base ubuntu and create ELK image from scratch
 * download images with all three in one which are available in docker hub.
 * donwload images for each of elasticsearch, logstash and kibana individually

For this project I chose to download the official image of each and create a container for each. Having separate container allows us to mimic a cluster of machines with each of those three apps running in separate machine.

```bash
docker pull elasticsearch
docker pull logstash
docker pull kibana
```

After the images have been downloaded, it is time to create a container of each with necessary settings. It is of utmost importance to create elasticsearch container before kibana or logstash since the later two need to be linked to former upon creation.

#### elasticsearch

```bash
docker run -d -p 9200:9200 -p 9300:9300 -t \
-hostname elastic1 --name elastic1 \
 elasticsearch
```
The above command uses elasticsearch image as base to create a container with hostname elastic1 and name the container elastic1. Moreover, the comand binds port 9200 and 9300 of the container to the same port numbers of the docker host machine. **-p** is the option we use to publish the ports. Port 9200 is for RESTful service that publishes basic information about the elasticsearch in JSON format. We can use a web browser or curl to download the content in port 9200 which can be used to verify whether elasticsearch is working as expected. While publishing port 9200 is optional, port 9300 is a necessity for elastic container. Port 9300 is used for communication between nodes.

#### kibana

```bash
docker run -d -p 5601:5601 -h kibana --name kibana \
--link elasticsearch:elasticsearch \
kibana
```

The command to run container is very similar to that of elasticsearch with couple of key differences. The command above uses kibana as base image to create a container named kibana and same hostname. **-h** is the same as **--hostname** and is used to give hostname to a docker container. The command also publishes port 5601 to the docker host and opens up the web interface to manipulate underlying data in elasticsearch. **-d** in kibana command is to simply create a container in detached mode. Finally, **--link** is the most important option when creating kibana container. Since kibana is a web interface to elasticsearch, we need to point kibana container to elasticsearch.

#### logstash

I kept logstash for the end as it requires more configuration. Command to create logstash container is similar to the other two up to contain extent, the biggest difference being the config file for logstash.

```bash
docker run -h logstash --name logstash \
--link elasticsearch:elasticsearch \
-it --rm -v "$PWD":/config-dir logstash \
-f /config-dir/logstash1.conf
```
The above command uses logstash image to create a container named logstash and same hostname. Like kibana, logstash needs to be linked to elasticsearch as well. The above command has three more options, **-rm, -v, -f**. Those three commands were added specifically to to run and test config files. The biggest problem I had when creating cluster of ELK stack was getting the config files working as expected.

Option **-v** mounts a folder in docker host as a volume in the container. Having a shared volume between host and container simplifies the process of modifying the config files. Once the config file is in the container, we can use option **-f** to point the logstash to the our config file rather than the default that ships with logstash image.

The other option to point logstash to the correct config file would be to use Dockerfile. First copy the file  from host to container and then point.

```bash
COPY logstash.conf /config-dir/
CMD ["-f", "/config-dir/logstash1.conf"]
```

Regardless of how the config file is set, we will have to teat the file incrementally to achieve the desired result. I was creating container with a config file, stop the container, remove the container, tweak my config file and create the container again. This is a tedious process but docker option **--rm** simplifies the process of testing config file. We create the container with **--rm** option while we test and tweak the config file. Once we have a config file to our liking, the same command without **--rm** can be used the create a stable container. **-d** can be added to the command to start the container in detached mode once we are satisfied with out config file.

#### asa


text:
"use strict" ;

const BaseObject = require( './BaseObject.js' ) ;
const tree = require( 'tree-kit' ) ;
const copyData = require( '../copyData.js' ) ;
const Ngev = require( 'nextgen-events' ) ;

const log = require( 'logfella' ).global.use( 'spellcast' ) ;

/*
	Items can be object like weapon, armor, keys, or anything providing bonuses or maluses to an entity,
	like enchantment, spells, illness...
*/

var autoId = 0 ;

function Item( book , id , options ) {
	if ( ! options || typeof options !== 'object' ) {
		options = {} ;
	}
	else {
		// Clone options to avoid parts to be shared
		options = copyData.deep( options ) ;
	}

	if ( ! id ) { id = 'item_' + ( autoId ++ ) ; }

	BaseObject.call( this , book , id , options ) ;

	Object.defineProperties( this , {
		// Global statistics of this item, bonus given to stats out of any usages (e.g. ring & necklace bonuses)
		stats: { value: options.stats || {} , writable: true , enumerable: true } ,

		// Global skills of this item, bonus given to skills out of any usages (e.g. ring & necklace bonuses)
		skills: { value: options.skills || {} , writable: true , enumerable: true } ,

		// Global status bonuses
		status: { value: options.status || {} , writable: true , enumerable: true } ,

		// Global compound stats bonuses (not formula)
		compound: { value: options.compound || {} , writable: true , enumerable: true } ,

		// Own stats of the item (like its durability, ...)
		"own-stats": { value: options['own-stats'] || {} , writable: true , enumerable: true } ,

		// ?? Own skills of the item (not sure if its useful, just there for consistency)
		"own-skills": { value: options['own-skills'] || {} , writable: true , enumerable: true } ,

		// Own status of the item (like its remaining durability, ...)
		"own-status": { value: options['own-status'] || {} , writable: true , enumerable: true } ,

		// Type of slots the item will use when equipped on an entity (e.g. armor, hand, neck, ...)
		"slot-type": { value: options['slot-type'] || 'equipment' , writable: true , enumerable: true } ,

		// How many slots (of the previous type) it would use
		"slot-count": { value: options['slot-count'] !== undefined ? options['slot-count'] : 1 , writable: true , enumerable: true } ,

		// Usages/functions of this item, i.e. a per-function stats and bonuses, K/V pairs as function name/bonuses,
		// where bonuses is an object with keys: params, stats, skills, status, compound, adhoc
		usages: { value: options.usages || {} , writable: true , enumerable: true }
	} ) ;
}

module.exports = Item ;

Item.prototype = Object.create( BaseObject.prototype ) ;
Item.prototype.constructor = Item ;
Item.prototype.__prototypeUID__ = 'spellcast/Item' ;
Item.prototype.__prototypeVersion__ = require( '../../package.json' ).version ;


text:
package codegen

import (
	"bytes"
	"errors"
	"fmt"
	"math"
	"strings"
	"text/template"

	"github.com/goadesign/goa/design"
)

var (
	enumValT     *template.Template
	formatValT   *template.Template
	patternValT  *template.Template
	minMaxValT   *template.Template
	lengthValT   *template.Template
	requiredValT *template.Template
)

//  init instantiates the templates.
func init() {
	var err error
	fm := template.FuncMap{
		"tabs":     Tabs,
		"slice":    toSlice,
		"oneof":    oneof,
		"constant": constant,
		"goifyAtt": GoifyAtt,
		"add":      Add,
	}
	if enumValT, err = template.New("enum").Funcs(fm).Parse(enumValTmpl); err != nil {
		panic(err)
	}
	if formatValT, err = template.New("format").Funcs(fm).Parse(formatValTmpl); err != nil {
		panic(err)
	}
	if patternValT, err = template.New("pattern").Funcs(fm).Parse(patternValTmpl); err != nil {
		panic(err)
	}
	if minMaxValT, err = template.New("minMax").Funcs(fm).Parse(minMaxValTmpl); err != nil {
		panic(err)
	}
	if lengthValT, err = template.New("length").Funcs(fm).Parse(lengthValTmpl); err != nil {
		panic(err)
	}
	if requiredValT, err = template.New("required").Funcs(fm).Parse(requiredValTmpl); err != nil {
		panic(err)
	}
}

// Validator is the code generator for the 'Validate' type methods.
type Validator struct {
	arrayValT *template.Template
	hashValT  *template.Template
	userValT  *template.Template
	seen      map[string]*bytes.Buffer
}

// NewValidator instantiates a validate code generator.
func NewValidator() *Validator {
	var (
		v   = &Validator{seen: make(map[string]*bytes.Buffer)}
		err error
	)
	fm := template.FuncMap{
		"tabs":             Tabs,
		"slice":            toSlice,
		"oneof":            oneof,
		"constant":         constant,
		"goifyAtt":         GoifyAtt,
		"add":              Add,
		"recurseAttribute": v.recurseAttribute,
	}
	v.arrayValT, err = template.New("array").Funcs(fm).Parse(arrayValTmpl)
	if err != nil {
		panic(err)
	}
	v.hashValT, err = template.New("hash").Funcs(fm).Parse(hashValTmpl)
	if err != nil {
		panic(err)
	}
	v.userValT, err = template.New("user").Funcs(fm).Parse(userValTmpl)
	if err != nil {
		panic(err)
	}
	return v
}

// Code produces Go code that runs the validation checks recursively over the given attribute.
func (v *Validator) Code(att *design.AttributeDefinition, nonzero, required, hasDefault bool, target, context string, depth int, private bool) string {
	if _, ok := att.Metadata["struct:field:type"]; ok {
		// Skip validation generation for attributes with custom types
		return ""
	}
	buf := v.recurse(att, nonzero, required, hasDefault, target, context, depth, private)
	return buf.String()
}

func (v *Validator) arrayValCode(att *design.AttributeDefinition, nonzero, required, hasDefault bool, target, context string, depth int, private bool) []byte {
	a := att.Type.ToArray()
	if a == nil {
		return nil
	}

	var buf bytes.Buffer

	// Perform any validation on the array type such as MinLength, MaxLength, etc.
	validation := ValidationChecker(att, nonzero, required, hasDefault, target, context, depth, private)
	first := true
	if validation != "" {
		buf.WriteString(validation)
		first = false
	}
	val := v.Code(a.ElemType, true, false, false, "e", context+"[*]", depth+1, false)
	if val != "" {
		switch a.ElemType.Type.(type) {
		case *design.UserTypeDefinition, *design.MediaTypeDefinition:
			// For user and media types, call the Validate method
			val = RunTemplate(v.userValT, map[string]interface{}{
				"depth":  depth + 2,
				"target": "e",
			})
			val = fmt.Sprintf("%sif e != nil {\n%s\n%s}", Tabs(depth+1), val, Tabs(depth+1))
		}
		data := map[string]interface{}{
			"elemType":   a.ElemType,
			"context":    context,
			"target":     target,
			"depth":      1,
			"private":    private,
			"validation": val,
		}
		validation = RunTemplate(v.arrayValT, data)
		if !first {
			buf.WriteByte('\n')
		} else {
			first = false
		}
		buf.WriteString(validation)
	}
	return buf.Bytes()
}

func (v *Validator) hashValCode(att *design.AttributeDefinition, nonzero, required, hasDefault bool, target, context string, depth int, private bool) []byte {
	h := att.Type.ToHash()
	if h == nil {
		return nil
	}

	var buf bytes.Buffer

	// Perform any validation on the hash type such as MinLength, MaxLength, etc.
	validation := ValidationChecker(att, nonzero, required, hasDefault, target, context, depth, private)
	first := true
	if validation != "" {
		buf.WriteString(validation)
		first = false
	}
	keyVal := v.Code(h.KeyType, true, false, false, "k", context+"[*]", depth+1, false)
	if keyVal != "" {
		switch h.KeyType.Type.(type) {
		case *design.UserTypeDefinition, *design.MediaTypeDefinition:
			// For user and media types, call the Validate method
			keyVal = RunTemplate(v.userValT, map[string]interface{}{
				"depth":  depth + 2,
				"target": "k",
			})
			keyVal = fmt.Sprintf("%sif e != nil {\n%s\n%s}", Tabs(depth+1), keyVal, Tabs(depth+1))
		}
	}
	elemVal := v.Code(h.ElemType, true, false, false, "e", context+"[*]", depth+1, false)
	if elemVal != "" {
		switch h.ElemType.Type.(type) {
		case *design.UserTypeDefinition, *design.MediaTypeDefinition:
			// For user and media types, call the Validate method
			elemVal = RunTemplate(v.userValT, map[string]interface{}{
				"depth":  depth + 2,
				"target": "e",
			})
			elemVal = fmt.Sprintf("%sif e != nil {\n%s\n%s}", Tabs(depth+1), elemVal, Tabs(depth+1))
		}
	}
	if keyVal != "" || elemVal != "" {
		data := map[string]interface{}{
			"depth":          1,
			"target":         target,
			"keyValidation":  keyVal,
			"elemValidation": elemVal,
		}
		validation = RunTemplate(v.hashValT, data)
		if !first {
			buf.WriteByte('\n')
		} else {
			first = false
		}
		buf.WriteString(validation)
	}
	return buf.Bytes()
}

func (v *Validator) recurse(att *design.AttributeDefinition, nonzero, required, hasDefault bool, target, context string, depth int, private bool) *bytes.Buffer {
	var (
		buf   = new(bytes.Buffer)
		first = true
	)

	// Break infinite recursions
	switch dt := att.Type.(type) {
	case *design.MediaTypeDefinition:
		if buf, ok := v.seen[dt.TypeName]; ok {
			return buf
		}
		v.seen[dt.TypeName] = buf
	case *design.UserTypeDefinition:
		if buf, ok := v.seen[dt.TypeName]; ok {
			return buf
		}
		v.seen[dt.TypeName] = buf
	}

	if o := att.Type.ToObject(); o != nil {
		if ds, ok := att.Type.(design.DataStructure); ok {
			att = ds.Definition()
		}
		validation := ValidationChecker(att, nonzero, required, hasDefault, target, context, depth, private)
		if validation != "" {
			buf.WriteString(validation)
			first = false
		}
		o.IterateAttributes(func(n string, catt *design.AttributeDefinition) error {
			validation := v.recurseAttribute(att, catt, n, target, context, depth, private)
			if validation != "" {
				if !first {
					buf.WriteByte('\n')
				} else {
					first = false
				}
				buf.WriteString(validation)
			}
			return nil
		})
	} else if a := att.Type.ToArray(); a != nil {
		buf.Write(v.arrayValCode(att, nonzero, required, hasDefault, target, context, depth, private))
	} else if h := att.Type.ToHash(); h != nil {
		buf.Write(v.hashValCode(att, nonzero, required, hasDefault, target, context, depth, private))
	} else {
		validation := ValidationChecker(att, nonzero, required, hasDefault, target, context, depth, private)
		if validation != "" {
			buf.WriteString(validation)
		}
	}
	return buf
}

func (v *Validator) recurseAttribute(att, catt *design.AttributeDefinition, n, target, context string, depth int, private bool) string {
	var validation string
	if ds, ok := catt.Type.(design.DataStructure); ok {
		// We need to check empirically whether there are validations to be
		// generated, we can't just generate and check whether something was
		// generated to avoid infinite recursions.
		hasValidations := false
		done := errors.New("done")
		ds.Walk(func(a *design.AttributeDefinition) error {
			if a.Validation != nil {
				if private {
					hasValidations = true
					return done
				}
				// For public data structures there is a case where
				// there is validation but no actual validation
				// code: if the validation is a required validation
				// that applies to attributes that cannot be nil or
				// empty string i.e. primitive types other than
				// string.
				if !a.Validation.HasRequiredOnly() {
					hasValidations = true
					return done
				}
				for _, name := range a.Validation.Required {
					att := a.Type.ToObject()[name]
					if att != nil && (!att.Type.IsPrimitive() || att.Type.Kind() == design.StringKind) {
						hasValidations = true
						return done
					}
				}
			}
			return nil
		})
		if hasValidations {
			validation = RunTemplate(v.userValT, map[string]interface{}{
				"depth":  depth,
				"target": fmt.Sprintf("%s.%s", target, GoifyAtt(catt, n, true)),
			})
		}
	} else {
		dp := depth
		if catt.Type.IsObject() {
			dp++
		}
		validation = v.recurse(
			catt,
			att.IsNonZero(n),
			att.IsRequired(n),
			att.HasDefaultValue(n),
			fmt.Sprintf("%s.%s", target, GoifyAtt(catt, n, true)),
			fmt.Sprintf("%s.%s", context, n),
			dp,
			private,
		).String()
	}
	if validation != "" {
		if catt.Type.IsObject() {
			validation = fmt.Sprintf("%sif %s.%s != nil {\n%s\n%s}",
				Tabs(depth), target, GoifyAtt(catt, n, true), validation, Tabs(depth))
		}
	}
	return validation
}

// ValidationChecker produces Go code that runs the validation defined in the given attribute
// definition against the content of the variable named target recursively.
// context is used to keep track of recursion to produce helpful error messages in case of type
// validation error.
// The generated code assumes that there is a pre-existing "err" variable of type
// error. It initializes that variable in case a validation fails.
// Note: we do not want to recurse here, recursion is done by the marshaler/unmarshaler code.
func ValidationChecker(att *design.AttributeDefinition, nonzero, required, hasDefault bool, target, context string, depth int, private bool) string {
	if att.Validation == nil {
		return ""
	}
	t := target
	isPointer := private || (!required && !hasDefault && !nonzero)
	if isPointer && att.Type.IsPrimitive() {
		t = "*" + t
	}
	data := map[string]interface{}{
		"attribute": att,
		"isPointer": private || isPointer,
		"nonzero":   nonzero,
		"context":   context,
		"target":    target,
		"targetVal": t,
		"string":    att.Type.Kind() == design.StringKind,
		"array":     att.Type.IsArray(),
		"hash":      att.Type.IsHash(),
		"depth":     depth,
		"private":   private,
	}
	res := validationsCode(att, data)
	return strings.Join(res, "\n")
}

func validationsCode(att *design.AttributeDefinition, data map[string]interface{}) (res []string) {
	validation := att.Validation
	if values := validation.Values; values != nil {
		data["values"] = values
		if val := RunTemplate(enumValT, data); val != "" {
			res = append(res, val)
		}
	}
	if format := validation.Format; format != "" {
		data["format"] = format
		if val := RunTemplate(formatValT, data); val != "" {
			res = append(res, val)
		}
	}
	if pattern := validation.Pattern; pattern != "" {
		data["pattern"] = pattern
		if val := RunTemplate(patternValT, data); val != "" {
			res = append(res, val)
		}
	}
	if min := validation.Minimum; min != nil {
		if att.Type == design.Integer {
			data["min"] = renderInteger(*min)
		} else {
			data["min"] = fmt.Sprintf("%f", *min)
		}
		data["isMin"] = true
		delete(data, "max")
		if val := RunTemplate(minMaxValT, data); val != "" {
			res = append(res, val)
		}
	}
	if max := validation.Maximum; max != nil {
		if att.Type == design.Integer {
			data["max"] = renderInteger(*max)
		} else {
			data["max"] = fmt.Sprintf("%f", *max)
		}
		data["isMin"] = false
		delete(data, "min")
		if val := RunTemplate(minMaxValT, data); val != "" {
			res = append(res, val)
		}
	}
	if minLength := validation.MinLength; minLength != nil {
		data["minLength"] = minLength
		data["isMinLength"] = true
		delete(data, "maxLength")
		if val := RunTemplate(lengthValT, data); val != "" {
			res = append(res, val)
		}
	}
	if maxLength := validation.MaxLength; maxLength != nil {
		data["maxLength"] = maxLength
		data["isMinLength"] = false
		delete(data, "minLength")
		if val := RunTemplate(lengthValT, data); val != "" {
			res = append(res, val)
		}
	}
	if required := validation.Required; len(required) > 0 {
		var val string
		for i, r := range required {
			if i > 0 {
				val += "\n"
			}
			data["required"] = r
			val += RunTemplate(requiredValT, data)
		}
		res = append(res, val)
	}
	return
}

// renderInteger renders a max or min value properly, taking into account
// overflows due to casting from a float value.
func renderInteger(f float64) string {
	if f > math.Nextafter(float64(math.MaxInt64), 0) {
		return fmt.Sprintf("%d", int64(math.MaxInt64))
	}
	if f < math.Nextafter(float64(math.MinInt64), 0) {
		return fmt.Sprintf("%d", int64(math.MinInt64))
	}
	return fmt.Sprintf("%d", int64(f))
}

// oneof produces code that compares target with each element of vals and ORs
// the result, e.g. "target == 1 || target == 2".
func oneof(target string, vals []interface{}) string {
	elems := make([]string, len(vals))
	for i, v := range vals {
		elems[i] = fmt.Sprintf("%s == %#v", target, v)
	}
	return strings.Join(elems, " || ")
}

// constant returns the Go constant name of the format with the given value.
func constant(formatName string) string {
	switch formatName {
	case "date":
		return "goa.FormatDate"
	case "date-time":
		return "goa.FormatDateTime"
	case "email":
		return "goa.FormatEmail"
	case "hostname":
		return "goa.FormatHostname"
	case "ipv4":
		return "goa.FormatIPv4"
	case "ipv6":
		return "goa.FormatIPv6"
	case "ip":
		return "goa.FormatIP"
	case "uri":
		return "goa.FormatURI"
	case "mac":
		return "goa.FormatMAC"
	case "cidr":
		return "goa.FormatCIDR"
	case "regexp":
		return "goa.FormatRegexp"
	case "rfc1123":
		return "goa.FormatRFC1123"
	}
	panic("unknown format") // bug
}

const (
	arrayValTmpl = `{{ tabs .depth }}for _, e := range {{ .target }} {
{{ .validation }}
{{ tabs .depth }}}`

	hashValTmpl = `{{ tabs .depth }}for {{ if .keyValidation }}k{{ else }}_{{ end }}, {{ if .elemValidation }}e{{ else }}_{{ end }} := range {{ .target }} {
{{- if .keyValidation }}
{{ .keyValidation }}{{ end }}{{ if .elemValidation }}
{{ .elemValidation }}{{ end }}
{{ tabs .depth }}}`

	userValTmpl = `{{ tabs .depth }}if err2 := {{ .target }}.Validate(); err2 != nil {
{{ tabs .depth }}	err = goa.MergeErrors(err, err2)
{{ tabs .depth }}}`

	enumValTmpl = `{{ $depth := or (and .isPointer (add .depth 1)) .depth }}{{/*
*/}}{{ if .isPointer }}{{ tabs .depth }}if {{ .target }} != nil {
{{ end }}{{ tabs $depth }}if !({{ oneof .targetVal .values }}) {
{{ tabs $depth }}	err = goa.MergeErrors(err, goa.InvalidEnumValueError(` + "`" + `{{ .context }}` + "`" + `, {{ .targetVal }}, {{ slice .values }}))
{{ if .isPointer }}{{ tabs $depth }}}
{{ end }}{{ tabs .depth }}}`

	patternValTmpl = `{{ $depth := or (and .isPointer (add .depth 1)) .depth }}{{/*
*/}}{{ if .isPointer }}{{ tabs .depth }}if {{ .target }} != nil {
{{ end }}{{ tabs $depth }}if ok := goa.ValidatePattern(` + "`{{ .pattern }}`" + `, {{ .targetVal }}); !ok {
{{ tabs $depth }}	err = goa.MergeErrors(err, goa.InvalidPatternError(` + "`" + `{{ .context }}` + "`" + `, {{ .targetVal }}, ` + "`{{ .pattern }}`" + `))
{{ tabs $depth }}}{{ if .isPointer }}
{{ tabs .depth }}}{{ end }}`

	formatValTmpl = `{{ $depth := or (and .isPointer (add .depth 1)) .depth }}{{/*
*/}}{{ if .isPointer }}{{ tabs .depth }}if {{ .target }} != nil {
{{ end }}{{ tabs $depth }}if err2 := goa.ValidateFormat({{ constant .format }}, {{ .targetVal }}); err2 != nil {
{{ tabs $depth }}		err = goa.MergeErrors(err, goa.InvalidFormatError(` + "`" + `{{ .context }}` + "`" + `, {{ .targetVal }}, {{ constant .format }}, err2))
{{ if .isPointer }}{{ tabs $depth }}}
{{ end }}{{ tabs .depth }}}`

	minMaxValTmpl = `{{ $depth := or (and .isPointer (add .depth 1)) .depth }}{{/*
*/}}{{ if .isPointer }}{{ tabs .depth }}if {{ .target }} != nil {
{{ end }}{{ tabs .depth }}	if {{ .targetVal }} {{ if .isMin }}<{{ else }}>{{ end }} {{ if .isMin }}{{ .min }}{{ else }}{{ .max }}{{ end }} {
{{ tabs $depth }}	err = goa.MergeErrors(err, goa.InvalidRangeError(` + "`" + `{{ .context }}` + "`" + `, {{ .targetVal }}, {{ if .isMin }}{{ .min }}, true{{ else }}{{ .max }}, false{{ end }}))
{{ if .isPointer }}{{ tabs $depth }}}
{{ end }}{{ tabs .depth }}}`

	lengthValTmpl = `{{ $depth := or (and .isPointer (add .depth 1)) .depth }}{{/*
*/}}{{ $target := or (and (or (or .array .hash) .nonzero) .target) .targetVal }}{{/*
*/}}{{ if .isPointer }}{{ tabs .depth }}if {{ .target }} != nil {
{{ end }}{{ tabs .depth }}	if {{ if .string }}utf8.RuneCountInString({{ $target }}){{ else }}len({{ $target }}){{ end }} {{ if .isMinLength }}<{{ else }}>{{ end }} {{ if .isMinLength }}{{ .minLength }}{{ else }}{{ .maxLength }}{{ end }} {
{{ tabs $depth }}	err = goa.MergeErrors(err, goa.InvalidLengthError(` + "`" + `{{ .context }}` + "`" + `, {{ $target }}, {{ if .string }}utf8.RuneCountInString({{ $target }}){{ else }}len({{ $target }}){{ end }}, {{ if .isMinLength }}{{ .minLength }}, true{{ else }}{{ .maxLength }}, false{{ end }}))
{{ if .isPointer }}{{ tabs $depth }}}
{{ end }}{{ tabs .depth }}}`

	requiredValTmpl = `{{ $att := index $.attribute.Type.ToObject .required }}{{/*
*/}}{{ if and (not $.private) (eq $att.Type.Kind 4) }}{{ tabs $.depth }}if {{ $.target }}.{{ goifyAtt $att .required true }} == "" {
{{ tabs $.depth }}	err = goa.MergeErrors(err, goa.MissingAttributeError(` + "`" + `{{ $.context }}` + "`" + `, "{{  .required  }}"))
{{ tabs $.depth }}}{{ else if or $.private (not $att.Type.IsPrimitive) }}{{ tabs $.depth }}if {{ $.target }}.{{ goifyAtt $att .required true }} == nil {
{{ tabs $.depth }}	err = goa.MergeErrors(err, goa.MissingAttributeError(` + "`" + `{{ $.context }}` + "`" + `, "{{ .required }}"))
{{ tabs $.depth }}}{{ end }}`
)


text:
package nz.govt.doc.t1m.services.dataSheet.beachCharacterization;

import nz.govt.doc.t1m.domain.criteria.AbstractCriteria;

/**
 * Created by McCaulC on 28/01/2015.
 */
public class BeachCharacterizationCriteria extends AbstractCriteria {

    private String beachCharacterizationCriteria;

    public BeachCharacterizationCriteria() {
        super();
    }

    public String getBeachCharacterizationCriteria() {
        return beachCharacterizationCriteria;
    }

    public void setBeachCharacterizationCriteria(String beachCharacterizationCriteria) {
        this.beachCharacterizationCriteria = beachCharacterizationCriteria;
    }

    private Integer dataSheetId;
    private Integer surveyId;

    public Integer getDataSheetId() {
        return dataSheetId;
    }

    public void setDataSheetId(Integer dataSheetId) {
        this.dataSheetId = dataSheetId;
    }

    public Integer getSurveyId() {
        return surveyId;
    }

    public void setSurveyId(Integer surveyId) {
        this.surveyId = surveyId;
    }

    private String beachId;
    private String beachName;
    private String beachLength;
    private String regionName;
    private String latitudeStart;
    private String longitudeStart;
    private String latitudeEnd;
    private String longitudeEnd;
    private String coordSystem;
    private String substratumType;
    private String substratumUniformity;
    private String tidalRange;
    private String tidalDistance;
    private String beachBacking;
    private String location;
    private String majorUsage;
    private String access;
    private String nearestTown;
    private String nearestTownDistance;
    private String nearestTownDirection;
    private String nearestRiver;
    private String nearestRiverDistance;
    private String nearestRiverDirection;
    private String riversCreeks;
    private String pipesDrains;
    private String notes;

    public String getBeachId() {
        return beachId;
    }

    public void setBeachId(String beachId) {
        this.beachId = beachId;
    }

    public String getBeachName() {
        return beachName;
    }

    public void setBeachName(String beachName) {
        this.beachName = beachName;
    }

    public String getBeachLength() {
        return beachLength;
    }

    public void setBeachLength(String beachLength) {
        this.beachLength = beachLength;
    }

    public String getRegionName() {
        return regionName;
    }

    public void setRegionName(String regionName) {
        this.regionName = regionName;
    }

    public String getLatitudeStart() {
        return latitudeStart;
    }

    public void setLatitudeStart(String latitudeStart) {
        this.latitudeStart = latitudeStart;
    }

    public String getLongitudeStart() {
        return longitudeStart;
    }

    public void setLongitudeStart(String longitudeStart) {
        this.longitudeStart = longitudeStart;
    }

    public String getLatitudeEnd() {
        return latitudeEnd;
    }

    public void setLatitudeEnd(String latitudeEnd) {
        this.latitudeEnd = latitudeEnd;
    }

    public String getLongitudeEnd() {
        return longitudeEnd;
    }

    public void setLongitudeEnd(String longitudeEnd) {
        this.longitudeEnd = longitudeEnd;
    }

    public String getCoordSystem() {
        return coordSystem;
    }

    public void setCoordSystem(String coordSystem) {
        this.coordSystem = coordSystem;
    }

    public String getSubstratumType() {
        return substratumType;
    }

    public void setSubstratumType(String substratumType) {
        this.substratumType = substratumType;
    }

    public String getSubstratumUniformity() {
        return substratumUniformity;
    }

    public void setSubstratumUniformity(String substratumUniformity) {
        this.substratumUniformity = substratumUniformity;
    }

    public String getTidalRange() {
        return tidalRange;
    }

    public void setTidalRange(String tidalRange) {
        this.tidalRange = tidalRange;
    }

    public String getTidalDistance() {
        return tidalDistance;
    }

    public void setTidalDistance(String tidalDistance) {
        this.tidalDistance = tidalDistance;
    }

    public String getBeachBacking() {
        return beachBacking;
    }

    public void setBeachBacking(String beachBacking) {
        this.beachBacking = beachBacking;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getMajorUsage() {
        return majorUsage;
    }

    public void setMajorUsage(String majorUsage) {
        this.majorUsage = majorUsage;
    }

    public String getAccess() {
        return access;
    }

    public void setAccess(String access) {
        this.access = access;
    }

    public String getNearestTown() {
        return nearestTown;
    }

    public void setNearestTown(String nearestTown) {
        this.nearestTown = nearestTown;
    }

    public String getNearestTownDistance() {
        return nearestTownDistance;
    }

    public void setNearestTownDistance(String nearestTownDistance) {
        this.nearestTownDistance = nearestTownDistance;
    }

    public String getNearestTownDirection() {
        return nearestTownDirection;
    }

    public void setNearestTownDirection(String nearestTownDirection) {
        this.nearestTownDirection = nearestTownDirection;
    }

    public String getNearestRiver() {
        return nearestRiver;
    }

    public void setNearestRiver(String nearestRiver) {
        this.nearestRiver = nearestRiver;
    }

    public String getNearestRiverDistance() {
        return nearestRiverDistance;
    }

    public void setNearestRiverDistance(String nearestRiverDistance) {
        this.nearestRiverDistance = nearestRiverDistance;
    }

    public String getNearestRiverDirection() {
        return nearestRiverDirection;
    }

    public void setNearestRiverDirection(String nearestRiverDirection) {
        this.nearestRiverDirection = nearestRiverDirection;
    }

    public String getRiversCreeks() {
        return riversCreeks;
    }

    public void setRiversCreeks(String riversCreeks) {
        this.riversCreeks = riversCreeks;
    }

    public String getPipesDrains() {
        return pipesDrains;
    }

    public void setPipesDrains(String pipesDrains) {
        this.pipesDrains = pipesDrains;
    }

    public String getNotes() {
        return notes;
    }

    public void setNotes(String notes) {
        this.notes = notes;
    }
}


text:
<?xml version="1.0"?>
<!--
     Copyright (C) 2016 The Android Open Source Project

     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.
-->
<resources>
  <string name="exo_controls_previous_description">"ເພງກ່ອນໜ້າ"</string>
  <string name="exo_controls_next_description">"ເພງຕໍ່ໄປ"</string>
  <string name="exo_controls_pause_description">"ຢຸດຊົ່ວຄາວ"</string>
  <string name="exo_controls_play_description">"ຫຼິ້ນ"</string>
  <string name="exo_controls_stop_description">"ຢຸດ"</string>
  <string name="exo_controls_rewind_description">"ຣີວາຍກັບ"</string>
  <string name="exo_controls_fastforward_description">"ເລື່ອນໄປໜ້າ"</string>
  <string name="exo_controls_repeat_all_description">"ຫຼິ້ນຊ້ຳທັງໝົດ"</string>
  <string name="exo_controls_repeat_off_description">"ບໍ່ຫຼິ້ນຊ້ຳ"</string>
  <string name="exo_controls_repeat_one_description">"ຫຼິ້ນຊ້ຳ"</string>
</resources>