text:
POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_BEGIN
#include <algorithm>
#include <utility>
POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_END

namespace pomdog::gpu::detail::direct3d11 {
namespace {

using Microsoft::WRL::ComPtr;

D3D11_PRIMITIVE_TOPOLOGY
ToPrimitiveTopology(PrimitiveTopology primitiveTopology) noexcept
{
    switch (primitiveTopology) {
    case PrimitiveTopology::TriangleStrip:
        return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
    case PrimitiveTopology::TriangleList:
        return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
    case PrimitiveTopology::LineList:
        return D3D11_PRIMITIVE_TOPOLOGY_LINELIST;
    case PrimitiveTopology::LineStrip:
        return D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP;
    }
    return D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED;
}

D3D11_BLEND_OP ToBlendOperation(BlendOperation blendOperation) noexcept
{
    switch (blendOperation) {
    case BlendOperation::Add:
        return D3D11_BLEND_OP_ADD;
    case BlendOperation::Subtract:
        return D3D11_BLEND_OP_SUBTRACT;
    case BlendOperation::ReverseSubtract:
        return D3D11_BLEND_OP_REV_SUBTRACT;
    case BlendOperation::Min:
        return D3D11_BLEND_OP_MIN;
    case BlendOperation::Max:
        return D3D11_BLEND_OP_MAX;
    }
    return D3D11_BLEND_OP_ADD;
}

D3D11_BLEND ToBlend(BlendFactor blend) noexcept
{
    switch (blend) {
    case BlendFactor::Zero:
        return D3D11_BLEND_ZERO;
    case BlendFactor::One:
        return D3D11_BLEND_ONE;
    case BlendFactor::SourceColor:
        return D3D11_BLEND_SRC_COLOR;
    case BlendFactor::InverseSourceColor:
        return D3D11_BLEND_INV_SRC_COLOR;
    case BlendFactor::SourceAlpha:
        return D3D11_BLEND_SRC_ALPHA;
    case BlendFactor::InverseSourceAlpha:
        return D3D11_BLEND_INV_SRC_ALPHA;
    case BlendFactor::DestinationAlpha:
        return D3D11_BLEND_DEST_ALPHA;
    case BlendFactor::InverseDestinationAlpha:
        return D3D11_BLEND_INV_DEST_ALPHA;
    case BlendFactor::DestinationColor:
        return D3D11_BLEND_DEST_COLOR;
    case BlendFactor::InverseDestinationColor:
        return D3D11_BLEND_INV_DEST_COLOR;
    case BlendFactor::SourceAlphaSaturation:
        return D3D11_BLEND_SRC_ALPHA_SAT;
    case BlendFactor::BlendFactor:
        return D3D11_BLEND_BLEND_FACTOR;
    case BlendFactor::InvereseBlendFactor:
        return D3D11_BLEND_INV_BLEND_FACTOR;
    case BlendFactor::Source1Color:
        return D3D11_BLEND_SRC1_COLOR;
    case BlendFactor::InverseSource1Color:
        return D3D11_BLEND_INV_SRC1_COLOR;
    case BlendFactor::Source1Alpha:
        return D3D11_BLEND_SRC1_ALPHA;
    case BlendFactor::InverseSource1Alpha:
        return D3D11_BLEND_INV_SRC1_ALPHA;
    }
    return D3D11_BLEND_ONE;
}

D3D11_STENCIL_OP ToStencilOperation(StencilOperation operation) noexcept
{
    switch (operation) {
    case StencilOperation::Keep:
        return D3D11_STENCIL_OP_KEEP;
    case StencilOperation::Zero:
        return D3D11_STENCIL_OP_ZERO;
    case StencilOperation::Replace:
        return D3D11_STENCIL_OP_REPLACE;
    case StencilOperation::IncrementSaturation:
        return D3D11_STENCIL_OP_INCR_SAT;
    case StencilOperation::DecrementSaturation:
        return D3D11_STENCIL_OP_DECR_SAT;
    case StencilOperation::Invert:
        return D3D11_STENCIL_OP_INVERT;
    case StencilOperation::Increment:
        return D3D11_STENCIL_OP_INCR;
    case StencilOperation::Decrement:
        return D3D11_STENCIL_OP_DECR;
    }
    return D3D11_STENCIL_OP_KEEP;
}

D3D11_CULL_MODE ToCullMode(CullMode cullMode) noexcept
{
    switch (cullMode) {
    case CullMode::ClockwiseFace:
        return D3D11_CULL_FRONT;
    case CullMode::CounterClockwiseFace:
        return D3D11_CULL_BACK;
    case CullMode::None:
        return D3D11_CULL_NONE;
    }
    return D3D11_CULL_BACK;
}

D3D11_FILL_MODE ToFillMode(FillMode fillMode) noexcept
{
    switch (fillMode) {
    case FillMode::Solid:
        return D3D11_FILL_SOLID;
    case FillMode::Wireframe:
        return D3D11_FILL_WIREFRAME;
    }
    return D3D11_FILL_SOLID;
}

D3D11_INPUT_CLASSIFICATION ToD3D11InputClassification(
    InputClassification slotClass) noexcept
{
    switch (slotClass) {
    case InputClassification::InputPerVertex:
        return D3D11_INPUT_PER_VERTEX_DATA;
    case InputClassification::InputPerInstance:
        return D3D11_INPUT_PER_INSTANCE_DATA;
    }
    return D3D11_INPUT_PER_VERTEX_DATA;
}

inline BOOL ToD3D11Boolean(bool is) noexcept
{
    return is ? TRUE : FALSE;
}

void ToD3D11Desc(
    const RenderTargetBlendDescriptor& desc,
    D3D11_RENDER_TARGET_BLEND_DESC& result) noexcept
{
    result.BlendEnable = ToD3D11Boolean(desc.BlendEnable);
    result.BlendOp = ToBlendOperation(desc.ColorBlendOperation);
    result.BlendOpAlpha = ToBlendOperation(desc.AlphaBlendOperation);
    result.DestBlend = ToBlend(desc.ColorDestinationBlend);
    result.DestBlendAlpha = ToBlend(desc.AlphaDestinationBlend);
    result.SrcBlend = ToBlend(desc.ColorSourceBlend);
    result.SrcBlendAlpha = ToBlend(desc.AlphaSourceBlend);
    result.RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
}

[[nodiscard]] std::tuple<ComPtr<ID3D11BlendState>, std::unique_ptr<Error>>
CreateBlendState(
    ID3D11Device* nativeDevice,
    const BlendDescriptor& descriptor) noexcept
{
    D3D11_BLEND_DESC blendDesc;
    ::ZeroMemory(&blendDesc, sizeof(blendDesc));
    blendDesc.AlphaToCoverageEnable = ToD3D11Boolean(descriptor.AlphaToCoverageEnable);
    blendDesc.IndependentBlendEnable = ToD3D11Boolean(descriptor.IndependentBlendEnable);

    const auto renderTargetCount = std::min<int>(
        static_cast<int>(descriptor.RenderTargets.size()),
        D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT);

    for (int i = 0; i < renderTargetCount; ++i) {
        ToD3D11Desc(descriptor.RenderTargets[i], blendDesc.RenderTarget[i]);
    }

    POMDOG_ASSERT(nativeDevice != nullptr);

    ComPtr<ID3D11BlendState> blendState;
    HRESULT hr = nativeDevice->CreateBlendState(&blendDesc, &blendState);

    if (FAILED(hr)) {
        return std::make_tuple(nullptr, errors::New("failed to create ID3D11BlendState"));
    }

    return std::make_tuple(std::move(blendState), nullptr);
}

[[nodiscard]] std::tuple<ComPtr<ID3D11DepthStencilState>, std::unique_ptr<Error>>
CreateDepthStencilState(
    ID3D11Device* nativeDevice,
    const DepthStencilDescriptor& descriptor) noexcept
{
    D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
    ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

    depthStencilDesc.DepthEnable = ToD3D11Boolean(descriptor.DepthBufferEnable);
    depthStencilDesc.DepthFunc = ToComparisonFunction(descriptor.DepthBufferFunction);
    depthStencilDesc.DepthWriteMask = (descriptor.DepthBufferWriteEnable
                                           ? D3D11_DEPTH_WRITE_MASK_ALL
                                           : D3D11_DEPTH_WRITE_MASK_ZERO);

    depthStencilDesc.StencilEnable = ToD3D11Boolean(descriptor.StencilEnable);
    depthStencilDesc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK;
    depthStencilDesc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK;

    depthStencilDesc.BackFace.StencilDepthFailOp = ToStencilOperation(descriptor.CounterClockwiseFace.StencilDepthBufferFail);
    depthStencilDesc.BackFace.StencilFailOp = ToStencilOperation(descriptor.CounterClockwiseFace.StencilFail);
    depthStencilDesc.BackFace.StencilPassOp = ToStencilOperation(descriptor.CounterClockwiseFace.StencilPass);
    depthStencilDesc.BackFace.StencilFunc = ToComparisonFunction(descriptor.CounterClockwiseFace.StencilFunction);

    depthStencilDesc.FrontFace.StencilDepthFailOp = ToStencilOperation(descriptor.ClockwiseFace.StencilDepthBufferFail);
    depthStencilDesc.FrontFace.StencilFailOp = ToStencilOperation(descriptor.ClockwiseFace.StencilFail);
    depthStencilDesc.FrontFace.StencilPassOp = ToStencilOperation(descriptor.ClockwiseFace.StencilPass);
    depthStencilDesc.FrontFace.StencilFunc = ToComparisonFunction(descriptor.ClockwiseFace.StencilFunction);

    POMDOG_ASSERT(nativeDevice != nullptr);

    ComPtr<ID3D11DepthStencilState> depthStencilState;
    HRESULT hr = nativeDevice->CreateDepthStencilState(&depthStencilDesc, &depthStencilState);

    if (FAILED(hr)) {
        return std::make_tuple(nullptr, errors::New("failed to create ID3D11DepthStencilState"));
    }

    return std::make_tuple(std::move(depthStencilState), nullptr);
}

[[nodiscard]] std::tuple<ComPtr<ID3D11RasterizerState>, std::unique_ptr<Error>>
CreateRasterizerState(
    ID3D11Device* nativeDevice,
    const RasterizerDescriptor& descriptor) noexcept
{
    D3D11_RASTERIZER_DESC rasterizerDesc;
    ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc));

    rasterizerDesc.CullMode = ToCullMode(descriptor.CullMode);
    rasterizerDesc.FillMode = ToFillMode(descriptor.FillMode);
    rasterizerDesc.FrontCounterClockwise = FALSE;

    rasterizerDesc.DepthBias = static_cast<INT>(descriptor.DepthBias);
    rasterizerDesc.DepthBiasClamp = 0.0f;
    rasterizerDesc.SlopeScaledDepthBias = descriptor.SlopeScaledDepthBias;
    rasterizerDesc.AntialiasedLineEnable = FALSE;
    rasterizerDesc.MultisampleEnable = ToD3D11Boolean(descriptor.MultisampleEnable);

    // NOTE: Modern graphics APIs (Direct3D 12, Metal and Vulkan) don't include
    // a parameter like ScissorEnable to enable/disable scissor test. So we
    // always set ScissorEnable to true in Direct3D 11.
    rasterizerDesc.ScissorEnable = TRUE;

    POMDOG_ASSERT(!rasterizerDesc.AntialiasedLineEnable ||
                  (rasterizerDesc.AntialiasedLineEnable && !rasterizerDesc.MultisampleEnable));

    POMDOG_ASSERT(nativeDevice != nullptr);

    ComPtr<ID3D11RasterizerState> rasterizerState;
    HRESULT hr = nativeDevice->CreateRasterizerState(&rasterizerDesc, &rasterizerState);

    if (FAILED(hr)) {
        return std::make_tuple(nullptr, errors::New("failed to create ID3D11RasterizerState"));
    }

    return std::make_tuple(std::move(rasterizerState), nullptr);
}

[[nodiscard]] std::unique_ptr<Error>
ReflectShaderBytecode(
    const ShaderBytecode& shaderBytecode,
    Microsoft::WRL::ComPtr<ID3D11ShaderReflection>& shaderReflector,
    D3D11_SHADER_DESC& shaderDesc) noexcept
{
    if (auto hr = D3DReflect(
            shaderBytecode.Code,
            shaderBytecode.ByteLength,
            IID_PPV_ARGS(&shaderReflector));
        FAILED(hr)) {
        return errors::New("D3DReflect() failed");
    }

    POMDOG_ASSERT(shaderReflector != nullptr);

    if (auto hr = shaderReflector->GetDesc(&shaderDesc); FAILED(hr)) {
        return errors::New("failed to get shader descriptor");
    }

    return nullptr;
}

[[nodiscard]] std::tuple<std::vector<D3D11_INPUT_ELEMENT_DESC>, std::unique_ptr<Error>>
BuildInputElements(
    const std::vector<D3D11_SIGNATURE_PARAMETER_DESC>& signatureParameters,
    const InputLayoutDescriptor& descriptor) noexcept
{
    POMDOG_ASSERT(!signatureParameters.empty());
    POMDOG_ASSERT(!descriptor.InputElements.empty());
    POMDOG_ASSERT(signatureParameters.size() == descriptor.InputElements.size());

    std::vector<D3D11_INPUT_ELEMENT_DESC> inputElements;
    inputElements.reserve(descriptor.InputElements.size());

    auto signature = std::begin(signatureParameters);

    for (auto& sourceElement : descriptor.InputElements) {
        POMDOG_ASSERT(signature != std::end(signatureParameters));

        if (signature == std::end(signatureParameters)) {
            return std::make_tuple(std::move(inputElements), errors::New("invalid input elements"));
        }

        POMDOG_ASSERT(sourceElement.InstanceStepRate == 0 ||
                      sourceElement.InputSlotClass == InputClassification::InputPerInstance);

        D3D11_INPUT_ELEMENT_DESC elementDesc;
        elementDesc.SemanticName = signature->SemanticName;
        elementDesc.SemanticIndex = signature->SemanticIndex;
        elementDesc.Format = dxgi::ToDXGIFormat(sourceElement.Format);
        elementDesc.InputSlot = sourceElement.InputSlot;
        elementDesc.AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
        elementDesc.InputSlotClass = ToD3D11InputClassification(sourceElement.InputSlotClass);
        elementDesc.InstanceDataStepRate = sourceElement.InstanceStepRate;

        POMDOG_ASSERT(elementDesc.InputSlot <= D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT);
        static_assert(std::is_unsigned_v<decltype(elementDesc.InstanceDataStepRate)>, "elementDesc.InstanceDataStepRate >= 0");

        inputElements.push_back(std::move(elementDesc));

        ++signature;
    }

    return std::make_tuple(std::move(inputElements), nullptr);
}

[[nodiscard]] std::vector<D3D11_SIGNATURE_PARAMETER_DESC>
EnumerateSignatureParameters(
    ID3D11ShaderReflection* shaderReflector,
    const D3D11_SHADER_DESC& shaderDesc) noexcept
{
    POMDOG_ASSERT(shaderReflector);

    std::vector<D3D11_SIGNATURE_PARAMETER_DESC> signatureParameters;

    for (UINT i = 0; i < shaderDesc.InputParameters; ++i) {
        D3D11_SIGNATURE_PARAMETER_DESC signatureDesc;
        shaderReflector->GetInputParameterDesc(i, &signatureDesc);

        switch (signatureDesc.SystemValueType) {
        case D3D_NAME_INSTANCE_ID:
        case D3D_NAME_VERTEX_ID:
        case D3D_NAME_PRIMITIVE_ID:
            continue;
        default:
            break;
        }
        signatureParameters.push_back(signatureDesc);
    }
    return std::move(signatureParameters);
}

[[nodiscard]] std::tuple<ComPtr<ID3D11InputLayout>, std::unique_ptr<Error>>
CreateInputLayout(
    ID3D11Device* device,
    const ShaderBytecode& vertexShaderBytecode,
    const InputLayoutDescriptor& descriptor) noexcept
{
    POMDOG_ASSERT(device);
    POMDOG_ASSERT(vertexShaderBytecode.Code);

    D3D11_SHADER_DESC shaderDesc;
    Microsoft::WRL::ComPtr<ID3D11ShaderReflection> shaderReflector;

    if (auto err = ReflectShaderBytecode(
            vertexShaderBytecode,
            shaderReflector,
            shaderDesc);
        err != nullptr) {
        return std::make_tuple(nullptr, errors::Wrap(std::move(err), "ReflectShaderBytecode() failed"));
    }

    auto signatureParameters = EnumerateSignatureParameters(
        shaderReflector.Get(), shaderDesc);

    auto [inputElements, buildErr] = BuildInputElements(signatureParameters, descriptor);
    if (buildErr != nullptr) {
        return std::make_tuple(nullptr, errors::Wrap(std::move(buildErr), "BuildInputElements() failed"));
    }

    Microsoft::WRL::ComPtr<ID3D11InputLayout> nativeInputLayout;
    HRESULT hr = device->CreateInputLayout(
        inputElements.data(),
        static_cast<UINT>(inputElements.size()),
        vertexShaderBytecode.Code,
        vertexShaderBytecode.ByteLength,
        &nativeInputLayout);

    if (FAILED(hr)) {
        return std::make_tuple(nullptr, errors::New("failed to create ID3D11InputLayout"));
    }

    return std::make_tuple(std::move(nativeInputLayout), nullptr);
}

} // namespace

std::unique_ptr<Error>
PipelineStateDirect3D11::Initialize(
    ID3D11Device* device,
    const PipelineDescriptor& descriptor) noexcept
{
    POMDOG_ASSERT(device);

    sampleMask = descriptor.MultiSampleMask;

    if (auto [result, err] = CreateBlendState(device, descriptor.BlendState); err != nullptr) {
        return errors::Wrap(std::move(err), "CreateBlendState() failed");
    }
    else {
        blendState = std::move(result);
    }

    if (auto [result, err] = CreateDepthStencilState(device, descriptor.DepthStencilState); err != nullptr) {
        return errors::Wrap(std::move(err), "CreateDepthStencilState() failed");
    }
    else {
        depthStencilState = std::move(result);
    }

    if (auto [result, err] = CreateRasterizerState(device, descriptor.RasterizerState); err != nullptr) {
        return errors::Wrap(std::move(err), "CreateRasterizerState() failed");
    }
    else {
        rasterizerState = std::move(result);
    }

    auto vertexShaderD3D = std::dynamic_pointer_cast<VertexShaderDirect3D11>(descriptor.VertexShader);
    if (vertexShaderD3D == nullptr) {
        return errors::New("invalid vertex shader");
    }

    vertexShader = vertexShaderD3D->GetShader();
    if (vertexShader == nullptr) {
        return errors::New("vertexShader must be != nullptr");
    }

    auto pixelShaderD3D = std::dynamic_pointer_cast<PixelShaderDirect3D11>(descriptor.PixelShader);
    if (pixelShaderD3D == nullptr) {
        return errors::New("invalid pixel shader");
    }

    pixelShader = pixelShaderD3D->GetShader();
    if (pixelShader == nullptr) {
        return errors::New("pixelShader must be != nullptr");
    }

    if (auto [result, err] = CreateInputLayout(
            device,
            vertexShaderD3D->GetShaderBytecode(),
            descriptor.InputLayout);
        err != nullptr) {
        return errors::Wrap(std::move(err), "CreateBlendState() failed");
    }
    else {
        inputLayout = std::move(result);
    }

    primitiveTopology = ToPrimitiveTopology(descriptor.PrimitiveTopology);

    return nullptr;
}

void PipelineStateDirect3D11::Apply(
    ID3D11DeviceContext* deviceContext,
    FLOAT const blendFactor[4])
{
    POMDOG_ASSERT(deviceContext);
    POMDOG_ASSERT(inputLayout);
    POMDOG_ASSERT(vertexShader);
    POMDOG_ASSERT(pixelShader);
    POMDOG_ASSERT(blendState);
    POMDOG_ASSERT(rasterizerState);
    POMDOG_ASSERT(depthStencilState);

    deviceContext->IASetInputLayout(inputLayout.Get());
    deviceContext->IASetPrimitiveTopology(primitiveTopology);
    deviceContext->VSSetShader(vertexShader.Get(), nullptr, 0);
    deviceContext->PSSetShader(pixelShader.Get(), nullptr, 0);
    deviceContext->OMSetBlendState(blendState.Get(), blendFactor, sampleMask);
    deviceContext->OMSetDepthStencilState(depthStencilState.Get(), 0);
    deviceContext->RSSetState(rasterizerState.Get());
}

} // namespace pomdog::gpu::detail::direct3d11


text:
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import unittest
import emission.analysis.section_features as fc

class TestFeatureCalc(unittest.TestCase):
  def testCalSpeedWithZeroTime(self):
    trackpoint1 = {"track_location": {"coordinates": [-122.0861645, 37.3910201]},
                   "time" : "20150127T203305-0800"}
    trackpoint2 = {"track_location": {"coordinates": [-122.0858963, 37.3933358]},
                   "time" : "20150127T203305-0800"}
    self.assertEqual(fc.calSpeed(trackpoint1, trackpoint2), None)

  def testCalSpeedsWithZeroTime(self):
    trackpoint1 = {"track_location": {"coordinates": [-122.0861645, 37.3910201]},
                   "time" : "20150127T203305-0800"}
    trackpoint2 = {"track_location": {"coordinates": [-122.0858963, 37.3933358]},
                   "time" : "20150127T203305-0800"}
    testSeg = {"track_points": [trackpoint1, trackpoint2]}
    self.assertEqual(fc.calSpeeds(testSeg), [0])

  def testCalSpeedsWithOnePoint(self):
    trackpoint1 = {"track_location": {"coordinates": [-122.0861645, 37.3910201]},
                   "time" : "20150127T203305-0800"}
    testSeg = {"track_points": [trackpoint1]}
    self.assertEqual(len(fc.calSpeeds(testSeg)), 0)

  def testCalAccelsWithOnePoint(self):
    trackpoint1 = {"track_location": {"coordinates": [-122.0861645, 37.3910201]},
                   "time" : "20150127T203305-0800"}
    testSeg = {"track_points": [trackpoint1]}
    self.assertEqual(fc.calAccels(testSeg), None)

  def testCalSpeedsWithOnePoint(self):
    trackpoint1 = {"track_location": {"coordinates": [-122.0861645, 37.3910201]},
                   "time" : "20150127T203305-0800"}
    testSeg = {"track_points": [trackpoint1]}
    self.assertEqual(len(fc.calSpeeds(testSeg)), 0)

if __name__ == '__main__':
    unittest.main()

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Arthopyrenia atroalba Vain.

### Remarks
null


text:
from pysb.logging import get_logger
import logging

# Nosetests adds its own logging handler - console_output=False avoids
# duplication
get_logger(level=logging.DEBUG, console_output=False)


text:
package main

import . "testing"  // defines file-level T

type _ B // make use of package "testing" (but don't refer to T)

type S struct {
	T int
}

func main() {
	_ = &S{T: 1}	// should work
}


text:
package org.codehaus.plexus.archiver.diags;

import org.codehaus.plexus.archiver.*;
import org.codehaus.plexus.components.io.resources.PlexusIoResource;
import org.codehaus.plexus.components.io.resources.PlexusIoResourceCollection;
import org.codehaus.plexus.util.StringUtils;

import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A diagnostic archiver that keeps track of stuff that has been added.
 */
public class TrackingArchiver
    implements Archiver
{
    private File destFile;

    public final List<Addition> added = new ArrayList<Addition>();

    private boolean useJvmChmod;

    private boolean ignorePermissions;

    public void createArchive()
        throws ArchiverException, IOException
    {
    }

    public void addDirectory( final @Nonnull File directory )
        throws ArchiverException
    {
        added.add( new Addition( directory, null, null, null, -1 ) );
    }

    public void addDirectory( final @Nonnull File directory, final String prefix )
        throws ArchiverException
    {
        added.add( new Addition( directory, prefix, null, null, -1 ) );
    }

    public void addDirectory( final @Nonnull File directory, final String[] includes, final String[] excludes )
        throws ArchiverException
    {
        added.add( new Addition( directory, null, includes, excludes, -1 ) );
    }

    public void addDirectory( final @Nonnull File directory, final String prefix, final String[] includes,
                              final String[] excludes )
        throws ArchiverException
    {
        added.add( new Addition( directory, prefix, includes, excludes, -1 ) );
    }

    public void addFileSet( final @Nonnull FileSet fileSet )
        throws ArchiverException
    {
        added.add( new Addition( fileSet, null, null, null, -1 ) );
    }

    public void addFile( final @Nonnull File inputFile, final @Nonnull String destFileName )
        throws ArchiverException
    {
        added.add( new Addition( inputFile, destFileName, null, null, -1 ) );
    }

    public void addFile( final @Nonnull File inputFile, final @Nonnull String destFileName, final int permissions )
        throws ArchiverException
    {
        added.add( new Addition( inputFile, destFileName, null, null, permissions ) );
    }

    public void addArchivedFileSet( final @Nonnull File archiveFile )
        throws ArchiverException
    {
        added.add( new Addition( archiveFile, null, null, null, -1 ) );
    }

    public void addArchivedFileSet( final @Nonnull File archiveFile, final String prefix )
        throws ArchiverException
    {
        added.add( new Addition( archiveFile, prefix, null, null, -1 ) );
    }

    public void addSymlink( String s, String s2 )
        throws ArchiverException
    {
        added.add( new Addition( s, null, null, null, -1 ) );
    }

    public void addSymlink( String s, int i, String s2 )
        throws ArchiverException
    {
        added.add( new Addition( s, null, null, null, -1 ) );

    }

    public void addArchivedFileSet( final File archiveFile, final String[] includes, final String[] excludes )
        throws ArchiverException
    {
        added.add( new Addition( archiveFile, null, includes, excludes, -1 ) );
    }

    public void addArchivedFileSet( final @Nonnull File archiveFile, final String prefix, final String[] includes,
                                    final String[] excludes )
        throws ArchiverException
    {
        added.add( new Addition( archiveFile, prefix, includes, excludes, -1 ) );
    }

    public void addArchivedFileSet( final ArchivedFileSet fileSet )
        throws ArchiverException
    {
        added.add( new Addition( fileSet, null, null, null, -1 ) );
    }

    public void addArchivedFileSet( final ArchivedFileSet fileSet, Charset charset )
        throws ArchiverException
    {
        added.add( new Addition( fileSet, null, null, null, -1 ) );
    }

    public void addResource( final PlexusIoResource resource, final String destFileName, final int permissions )
        throws ArchiverException
    {
        added.add( new Addition( resource, destFileName, null, null, permissions ) );
    }

    public void addResources( final PlexusIoResourceCollection resources )
        throws ArchiverException
    {
        added.add( new Addition( resources, null, null, null, -1 ) );
    }

    public File getDestFile()
    {
        return destFile;
    }

    public void setDestFile( final File destFile )
    {
        this.destFile = destFile;
    }

    public void setFileMode( final int mode )
    {
    }

    public int getFileMode()
    {
        return Integer.parseInt( "0644", 8 );
    }

    public int getOverrideFileMode()
    {
        return Integer.parseInt( "0644", 8 );
    }

    public void setDefaultFileMode( final int mode )
    {
    }

    public int getDefaultFileMode()
    {
        return Integer.parseInt( "0644", 8 );
    }

    public void setDirectoryMode( final int mode )
    {
    }

    public int getDirectoryMode()
    {
        return Integer.parseInt( "0755", 8 );
    }

    public int getOverrideDirectoryMode()
    {
        return Integer.parseInt( "0755", 8 );
    }

    public void setDefaultDirectoryMode( final int mode )
    {
    }

    public int getDefaultDirectoryMode()
    {
        return Integer.parseInt( "0755", 8 );
    }

    public boolean getIncludeEmptyDirs()
    {
        return false;
    }

    public void setIncludeEmptyDirs( final boolean includeEmptyDirs )
    {
    }

    public void setDotFileDirectory( final File dotFileDirectory )
    {
    }

    public
    @Nonnull
    ResourceIterator getResources()
        throws ArchiverException
    {
        throw new RuntimeException("Not implemented");
    }

    @SuppressWarnings( "rawtypes" )
    public Map<String, ArchiveEntry> getFiles()
    {
        return new HashMap<String, ArchiveEntry>();
    }

    public boolean isForced()
    {
        return false;
    }

    public void setForced( final boolean forced )
    {
    }

    public boolean isSupportingForced()
    {
        return true;
    }

    public String getDuplicateBehavior()
    {
        return null;
    }

    public void setDuplicateBehavior( final String duplicate )
    {
    }

    public class Addition
    {
        /**
         * {@inheritDoc}
         *
         * @see Object#toString()
         */
        @Override
        public String toString()
        {
            return "Addition (\n    resource= " + resource + "\n    directory= " + directory + "\n    destination= "
                + destination + "\n    permissions= " + permissions + "\n    includes= " + ( includes == null
                ? "-none-"
                : StringUtils.join( includes, ", " ) ) + "\n    excludes= " + ( excludes == null
                ? "-none-"
                : StringUtils.join( excludes, ", " ) ) + "\n)";
        }

        public final Object resource;

        public final File directory;

        public final String destination;

        public final int permissions;

        public final String[] includes;

        public final String[] excludes;

        public Addition( final Object resource, final String destination, final String[] includes,
                         final String[] excludes, final int permissions )
        {
            this.resource = resource;
            if ( resource instanceof FileSet)
            {
                final FileSet fs = (FileSet) resource;
                directory = fs.getDirectory();
                this.destination = fs.getPrefix();
                this.includes = fs.getIncludes();
                this.excludes = fs.getExcludes();
                this.permissions = permissions;
            }
            else
            {
                if ( resource instanceof File && ( (File) resource ).isDirectory() )
                {
                    directory = (File) resource;
                }
                else
                {
                    directory = null;
                }

                this.destination = destination;
                this.includes = includes;
                this.excludes = excludes;
                this.permissions = permissions;
            }
        }
    }

    public boolean isUseJvmChmod()
    {
        return useJvmChmod;
    }

    public void setUseJvmChmod( final boolean useJvmChmod )
    {
        this.useJvmChmod = useJvmChmod;
    }

    public boolean isIgnorePermissions()
    {
        return ignorePermissions;
    }

    public void setIgnorePermissions( final boolean ignorePermissions )
    {
        this.ignorePermissions = ignorePermissions;
    }
}


text:
package org.pathwayeditor.visualeditor.commands;

import org.pathwayeditor.businessobjects.drawingprimitives.IDrawingNodeAttribute;
import org.pathwayeditor.figure.geometry.Dimension;
import org.pathwayeditor.figure.geometry.Point;

public class ResizeNodeCommand implements ICommand {
	private final IDrawingNodeAttribute node;
	private final Point originDelta;
	private final Dimension sizeDelta;

	public ResizeNodeCommand(IDrawingNodeAttribute drawingElement, Point originDelta, Dimension sizeDelta) {
		this.node = drawingElement;
		this.originDelta = originDelta;
		this.sizeDelta = sizeDelta;
	}

	@Override
	public void execute() {
		redo();
	}

	@Override
	public void redo() {
		this.node.resize(this.originDelta, this.sizeDelta);
	}

	@Override
	public void undo() {
		this.node.resize(this.originDelta.negate(), this.sizeDelta.negate());
	}

}


text:
package org.refptr.parsing.mathematica

import java.io.File

import scala.annotation.tailrec
import scala.util.matching.Regex

import scala.util.parsing.combinator.{RegexParsers,PackratParsers}
import scala.util.parsing.input.Position

class MathematicaParser extends RegexParsers with PackratParsers with ExtraParsers with ExtraRegexParsers {
    protected override val whiteSpace = """(\s|(?m)\(\*(\*(?!/)|[^*])*\*\))+""".r

    type ExprParser = PackratParser[Expr]

    import Implicits._

    protected val name = "[a-zA-Z$][a-zA-Z0-9$]*"

    lazy val ident: PackratParser[String] = regex(name.r)

    lazy val pattern: ExprParser =
        log(symbolBlankWithHead | symbolBlank | symbol | blankWithHead | blank)("pattern")

    protected def buildBlank(underscores: String): Expr = underscores.length match {
        case 1 => 'Blank
        case 2 => 'BlankSequence
        case 3 => 'BlankNullSequence
    }

    lazy val blank: ExprParser = regexMatch("(_{1,3})".r) ^^ {
        case Regex.Groups(underscores) => buildBlank(underscores)()
    }
    lazy val blankWithHead: ExprParser = regexMatch(s"(_{1,3})($name)".r) ^^ {
        case Regex.Groups(underscores, head) => buildBlank(underscores)(Sym(head))
    }
    lazy val symbol: ExprParser = regexMatch(s"($name)".r) ^^ {
        case Regex.Groups(name) => Sym(name)
    }
    lazy val symbolBlank: ExprParser = regexMatch(s"($name)(_{1,3})".r) ^^ {
        case Regex.Groups(name, underscores) => 'Pattern(Sym(name), buildBlank(underscores)())
    }
    lazy val symbolBlankWithHead: ExprParser = regexMatch(s"($name)(_{1,3})($name)".r) ^^ {
        case Regex.Groups(name, underscores, head) => 'Pattern(Sym(name), buildBlank(underscores)(Sym(head)))
    }

    lazy val number: PackratParser[Num] = log("""(\d+\.\d*|\d*\.\d+|\d+)([eE][+-]?\d+)?""".r)("number") ^^ {
        case value => Num(value)
    }

    lazy val str: PackratParser[Str] = log(("\"" + """(\\.|[^"])*""" + "\"").r)("str") ^^ {
        case value => Str(value.stripPrefix("\"").stripSuffix("\"").replace("\\\\\"", "\""))
    }

    lazy val out: ExprParser = outNumber | outClassic
    lazy val outNumber: ExprParser = "%\\d+".r ^^ {
        case value => 'Out(Num(value.stripPrefix("%")))
    }
    lazy val outClassic: ExprParser = "%+".r ^^ {
        case "%"   => 'Out()
        case value => 'Out(Num(s"-${value.length}"))
    }

    lazy val slot: ExprParser = regexMatch("(#{1,2})(\\d*)".r) ^^ {
        case Regex.Groups("#",  "")    => 'Slot(1)
        case Regex.Groups("#",  index) => 'Slot(index.toInt)
        case Regex.Groups("##", "")    => 'SlotSequence(1)
        case Regex.Groups("##", index) => 'SlotSequence(index.toInt)
    }

    lazy val list: ExprParser = "{" ~ repsep(expr, ",") ~ "}" ^^ {
        case "{" ~ elems ~ "}" => 'List(elems: _*)
    }

    protected def rulesFrom(p: ExprParser): ExprParser =
        precedence.dropWhile(p != _).reduce(_ | _)

    protected def rulesFrom(p: ExprParser, drop: ExprParser): ExprParser =
        precedence.dropWhile(p != _).filterNot(_ == drop).reduce(_ | _)

    // Precedence in increasing order:
    protected val precedence: List[ExprParser] =
        compound  :: // infix, flat  :  ;
        assign    :: // infix, right :  = := += -= *= /=
        aply      :: // infix, left  :  //
        func      :: // postfix      :  &
        replace   :: // infix, left  :  /.
        rule      :: // infix, right :  -> :>
        cond      :: // infix, left  :  /;
        alt       :: // infix, flat  :  |
        repeated  :: // postfix      :  .. ...
        or        :: // infix, flat  :  ||
        and       :: // infix, flat  :  &&
        not       :: // prefix       :  !
        same      :: // infix, flat  :  ===, =!=
        cmp       :: // infix, flat  :  == != <= < >= >
        span      :: // infix, none  :  ;;
        add       :: // infix, flat  :  + -
        mul       :: // infix, flat  :  * /
        dot       :: // infix, flat  :  .
        neg       :: // prefix       :  -
        exp       :: // infix, right :  ^
        map       :: // infix, right :  @@ /@
        postfix   :: // postfix      :  ' [[]] [] ! !! -- ++
        test      :: // infix, none  :  ?
        tightest  ::
        Nil

    lazy val expr: ExprParser = log(precedence.reduce(_ | _))("precedence")

    lazy val compound: ExprParser = log(complexCompound | simpleCompound)("compound")
    lazy val semicolon: PackratParser[String] = notFollowedBy(";", ';')
    lazy val complexCompound: ExprParser = compoundExpr ~ semicolon ~ rep1sep(compoundExpr, semicolon) ~ opt(semicolon) ^^ {
        case elem ~ _ ~ elems ~ None =>
            'CompoundExpression(elem :: elems: _*)
        case elem ~ _ ~ elems ~ _ =>
            'CompoundExpression(elem +: elems :+ Sym("Null"): _*)
    }
    lazy val simpleCompound: ExprParser = compoundExpr ~ semicolon ^^ {
        case elem ~ _ => 'CompoundExpression(elem, Sym("Null"))
    }
    lazy val compoundExpr: ExprParser = rulesFrom(assign)

    lazy val assign: ExprParser = log(assignExpr ~ ("=" | ":=" | "+=" | "-=" | "*=" | "/=") ~ (assign | assignExpr))("assign") ^^ {
        case lhs ~  "=" ~ rhs => 'Set(lhs, rhs)
        case lhs ~ ":=" ~ rhs => 'SetDelayed(lhs, rhs)
        case lhs ~ "+=" ~ rhs => 'AddTo(lhs, rhs)
        case lhs ~ "-=" ~ rhs => 'SubtractFrom(lhs, rhs)
        case lhs ~ "*=" ~ rhs => 'TimesBy(lhs, rhs)
        case lhs ~ "/=" ~ rhs => 'DivideBy(lhs, rhs)
    }
    lazy val assignExpr: ExprParser = rulesFrom(aply)

    lazy val aply: ExprParser = log((aply | aplyExpr) ~ "//" ~ aplyExpr)("aply") ^^ {
        case lhs ~ _ ~ rhs => rhs(lhs)
    }
    lazy val aplyExpr: ExprParser = rulesFrom(func)

    lazy val func: ExprParser = log((func | funcExpr) ~ notFollowedBy("&", '&'))("func") ^^ {
        case expr ~ _ => 'Function(expr)
    }
    lazy val funcExpr: ExprParser = rulesFrom(replace)

    lazy val replace: ExprParser = log((replace | replaceExpr) ~ "/." ~ replaceExpr)("replace") ^^ {
        case lhs ~ _ ~ rhs => 'ReplaceAll(lhs, rhs)
    }
    lazy val replaceExpr: ExprParser = rulesFrom(rule)

    lazy val rule: ExprParser = log(ruleExpr ~ ("->" | ":>") ~ (rule | ruleExpr))("rule") ^^ {
        case lhs ~ "->" ~ rhs => 'Rule(lhs, rhs)
        case lhs ~ ":>" ~ rhs => 'DelayedRule(lhs, rhs)
    }
    lazy val ruleExpr: ExprParser = rulesFrom(cond)

    lazy val cond: ExprParser = log((cond | condExpr) ~ "/;" ~ condExpr)("cond") ^^ {
        case lhs ~ _ ~ rhs => 'Condition(lhs, rhs)
    }
    lazy val condExpr: ExprParser = rulesFrom(alt)

    lazy val alt: ExprParser = log(altExpr ~ rep1(notFollowedBy("|", '|') ~> altExpr))("alt") ^^ {
        case head ~ tail => 'Alternatives(head :: tail: _*)
    }
    lazy val altExpr: ExprParser = rulesFrom(repeated)

    lazy val repeated: ExprParser = log((repeated | repeatedExpr) ~ ("..." | ".."))("repeated") ^^ {
        case expr ~ ".."  => 'Repeated(expr)
        case expr ~ "..." => 'RepeatedNull(expr)
    }
    lazy val repeatedExpr: ExprParser = rulesFrom(or)

    lazy val or: ExprParser = log(orExpr ~ rep1("||" ~> orExpr))("or") ^^ {
        case head ~ tail => 'Or(head :: tail: _*)
    }
    lazy val orExpr: ExprParser = rulesFrom(and)

    lazy val and: ExprParser = log(andExpr ~ rep1("&&" ~> andExpr))("and") ^^ {
        case head ~ tail => 'And(head :: tail: _*)
    }
    lazy val andExpr: ExprParser = rulesFrom(not)

    lazy val not: ExprParser = log(notFollowedBy("!", '=') ~ (not | notExpr))("not") ^^ {
        case _ ~ expr => 'Not(expr)
    }
    lazy val notExpr: ExprParser = rulesFrom(same)

    // XXX: special case of `not' on rhs
    lazy val same: ExprParser = log(sameExpr ~ rep1(("===" | "=!=") ~ (not | sameExpr)))("same") ^^ {
        case head ~ tail =>
            case class OpExpr(op: String, expr: Expr)

            @tailrec def buildAST(init: Expr, rest: List[OpExpr]): Expr = {
                rest match {
                    case Nil =>
                        init
                    case OpExpr(op, _) :: _ =>
                        val (head, tail) = rest.span(_.op == op)
                        val args = init :: head.map(_.expr)
                        val result = (op match {
                            case "===" => 'SameQ
                            case "=!=" => 'UnsameQ
                        })(args: _*)
                        buildAST(result, tail)
                }
            }

            buildAST(head, tail.map { case op ~ expr => OpExpr(op, expr) })
    }
    lazy val sameExpr: ExprParser = rulesFrom(cmp)

    protected def getCmpOp(op: String): Expr = op match {
        case "==" => 'Equal
        case "!=" => 'Unequal
        case "<=" => 'LessEqual
        case "<"  => 'Less
        case ">=" => 'GreaterEqual
        case ">"  => 'Greater
    }

    lazy val cmp: ExprParser = log(cmpExpr ~ rep1(("==" | "!="  | "<=" | "<" | ">=" | ">") ~ cmpExpr))("cmp") ^^ {
        case head ~ tail =>
            tail.collect { case op ~ _ => op }.distinct match {
                case op :: Nil =>
                    val args = head :: tail.collect {
                        case _ ~ expr => expr
                    }
                    getCmpOp(op)(args: _*)
                case _ =>
                    val args = head :: tail.flatMap {
                        case op ~ expr => Seq(getCmpOp(op), expr)
                    }
                    'Inequality(args: _*)
            }
    }
    lazy val cmpExpr: ExprParser = rulesFrom(span)

    lazy val span: ExprParser = log(spanParser)("span")
    lazy val spanParser: ExprParser =
        spanExpr ~ ";;" ~ spanExpr ~ ";;" ~ spanExpr ^^ { case i ~ _ ~ j ~ _ ~ k => 'Span(i, j, k)    } |
        spanExpr ~ ";;"            ~ ";;" ~ spanExpr ^^ { case i ~ _     ~ _ ~ k => 'Span(i, 'All, k) } |
                   ";;" ~ spanExpr ~ ";;" ~ spanExpr ^^ { case     _ ~ j ~ _ ~ k => 'Span(1, j, k)    } |
                   ";;"            ~ ";;" ~ spanExpr ^^ { case     _     ~ _ ~ k => 'Span(1, 'All, k) } |
        spanExpr ~ ";;" ~ spanExpr                   ^^ { case i ~ _ ~ j         => 'Span(i, j)       } |
        spanExpr ~ ";;"                              ^^ { case i ~ _             => 'Span(i, 'All)    } |
                   ";;" ~ spanExpr                   ^^ { case     _ ~ j         => 'Span(1, j)       } |
                   ";;"                              ^^ { case     _             => 'Span(1, 'All)    }
    lazy val spanExpr: ExprParser = rulesFrom(add)

    lazy val add: ExprParser = log(addExpr ~ rep1(("+" | "-") ~ addExpr))("add") ^^ {
        case head ~ tail =>
            val args = head :: tail.map {
                case "+" ~ expr       => expr
                case "-" ~ Num(value) => Num(s"-$value")
                case "-" ~ expr       => 'Times(-1, expr)
            }
            'Plus(args: _*)
    }
    lazy val addExpr: ExprParser = rulesFrom(mul)

    lazy val mul: ExprParser = log(mulImplied | mulExplicit)("mul")
    lazy val mulImplied: ExprParser = mulExpr ~ rep1(mulImpliedRhsExpr) ^^ {
        case head ~ tail =>
            val args = head :: tail
            'Times(args: _*)
    }
    lazy val mulExplicit: ExprParser = mulExpr ~ rep1(("*" | notFollowedBy("/", ';', '.')) ~ mulExpr) ^^ {
        case head ~ tail =>
            val args = head :: tail.map {
                case "*" ~ expr => expr
                case "/" ~ expr => 'Power(expr, -1)
            }
            'Times(args: _*)
    }
    // TODO: what about `not'?
    lazy val mulImpliedRhsExpr: ExprParser = rulesFrom(dot, drop=neg)
    lazy val mulExpr: ExprParser = rulesFrom(dot)

    lazy val dot: ExprParser = log(dotExpr ~ rep1("." ~> dotExpr))("dot") ^^ {
        case head ~ tail => 'Dot(head :: tail: _*)
    }
    lazy val dotExpr: ExprParser = rulesFrom(neg)

    lazy val neg: ExprParser = log("-" ~ (neg | negExpr))("neg") ^^ {
        case _ ~ Num(value) => Num(s"-$value")
        case _ ~ expr => 'Times(-1, expr)
    }
    lazy val negExpr: ExprParser = rulesFrom(exp)

    lazy val exp: ExprParser = log(expLhsExpr ~ "^" ~ (exp | expRhsExpr))("exp") ^^ {
        case lhs ~ _ ~ rhs => 'Power(lhs, rhs)
    }
    lazy val expLhsExpr: ExprParser = rulesFrom(map)
    lazy val expRhsExpr: ExprParser = neg | expLhsExpr

    lazy val map: ExprParser = log(mapExpr ~ ("@@" | "/@") ~ (map | mapExpr))("map") ^^ {
        case lhs ~ "@@" ~ rhs => 'Apply(lhs, rhs)
        case lhs ~ "/@" ~ rhs => 'Map(lhs, rhs)
    }
    lazy val mapExpr: ExprParser = rulesFrom(postfix)

    protected sealed trait PostfixOp
    protected case class DerivOp(n: Int) extends PostfixOp
    protected case class PartOp(args: Expr*) extends PostfixOp
    protected case class EvalOp(args: Expr*) extends PostfixOp
    protected case object FactorialOp extends PostfixOp
    protected case object Factorial2Op extends PostfixOp
    protected case object DecrementOp extends PostfixOp
    protected case object IncrementOp extends PostfixOp

    lazy val derivOp: PackratParser[PostfixOp] = "'+".r ^^ {
        case ticks => DerivOp(ticks.length)
    }
    lazy val partOp: PackratParser[PostfixOp] = "[[" ~> repsep(expr, ",") <~ "]]" ^^ {
        case exprs => PartOp(exprs: _*)
    }
    lazy val evalOp: PackratParser[PostfixOp] = "[" ~> repsep(expr, ",") <~ "]" ^^ {
        case exprs => EvalOp(exprs: _*)
    }
    lazy val factorialOp: PackratParser[PostfixOp] = ("!!" | notFollowedBy("!", '=')) ^^ {
        case "!" => FactorialOp
        case "!!" => Factorial2Op
    }
    lazy val postIncDecOp: PackratParser[PostfixOp] = ("--" | "++") ^^ {
        case "--" => DecrementOp
        case "++" => IncrementOp
    }

    lazy val postfix: ExprParser = log(postfixExpr ~ rep1(derivOp | partOp | evalOp | factorialOp | postIncDecOp))("postfix") ^^ {
        case expr ~ ops => ops.foldLeft(expr) {
            case (expr, DerivOp(n)) => 'Derivative(n)(expr)
            case (expr, PartOp(indices @ _*)) => 'Part(expr +: indices: _*)
            case (head, EvalOp(args @ _*)) => head(args: _*)
            case (expr, FactorialOp) => 'Factorial(expr)
            case (expr, Factorial2Op) => 'Factorial2(expr)
            case (expr, DecrementOp) => 'Decrement(expr)
            case (expr, IncrementOp) => 'Increment(expr)
        }
    }
    lazy val postfixExpr: ExprParser = rulesFrom(test)

    lazy val test: ExprParser = log(testExpr ~ "?" ~ testExpr)("test") ^^ {
        case lhs ~ _ ~ rhs => 'PatternTest(lhs, rhs)
    }
    lazy val testExpr: ExprParser = rulesFrom(tightest)

    lazy val tightest: ExprParser = log(group | value)("tightest")

    lazy val group: ExprParser = "(" ~> expr <~ ")"
    lazy val value: ExprParser = list | slot | out | pattern | number | str

    lazy val mathematica: ExprParser = expr
}

sealed trait ParseOutput

case class ParseResult(expr: Expr) extends ParseOutput {
    def toFullForm = expr.toFullForm
}

case class ParseError(msg: String, file: String, pos: Position) extends ParseOutput {
    def message: String = {
        val fileName = (new java.io.File(file)).getName()
        s"$fileName:$pos failure: $msg\n\n${pos.longString}"
    }
}

object MathematicaParser {
    def parse(source: String, name: String = "<string>"): ParseOutput = {
        val parser = new MathematicaParser
        parser.parseAll(parser.mathematica, source) match {
            case parser.Success(expr, _) =>
                ParseResult(expr)
            case parser.NoSuccess(msg, ctx) =>
                ParseError(msg, name, ctx.pos)
        }
    }

    def parse(source: File): ParseOutput =
        parse(FileUtils.readFromFile(source), source.getPath)
}


text:
class AddCategoryToBooks < ActiveRecord::Migration
  def change
    add_reference :books, :category, index: true, foreign_key: true
  end
end


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Builders;
using NUnit.TestUtilities;

namespace NUnit.Framework.Attributes
{
    [TestFixture(45, 45, 90)]
    [TestFixture(null, null, null)]
    public class NullableParameterizedTestFixture
    {
        int? _one;
        int? _two;
        int? _expected;

        public NullableParameterizedTestFixture(int? one, int? two, int? expected)
        {
            _one = one;
            _two = two;
            _expected = expected;
        }

        [Test]
        public void TestAddition()
        {
            if(_one.HasValue && _two.HasValue && _expected.HasValue)
            {
                Assert.That(_one.Value + _two.Value, Is.EqualTo(_expected.Value));
            }
            else
            {
                Assert.That(_one, Is.Null);
                Assert.That(_two, Is.Null);
            }
        }
    }

    [TestFixture("hello", "hello", "goodbye")]
    [TestFixture("zip", "zip")]
    [TestFixture(42, 42, 99)]
    [TestFixture(null, null, "null test")]
    [TestFixture((string)null, (string)null, "typed null test")]
    public class ParameterizedTestFixture
    {
        private readonly string eq1;
        private readonly string eq2;
        private readonly string neq;

        public ParameterizedTestFixture(string eq1, string eq2, string neq)
        {
            this.eq1 = eq1;
            this.eq2 = eq2;
            this.neq = neq;
        }

        public ParameterizedTestFixture(string eq1, string eq2)
            : this(eq1, eq2, null) { }

        public ParameterizedTestFixture(int eq1, int eq2, int neq)
        {
            this.eq1 = eq1.ToString();
            this.eq2 = eq2.ToString();
            this.neq = neq.ToString();
        }

        [Test]
        public void TestEquality()
        {
            Assert.AreEqual(eq1, eq2);
            if (eq1 != null && eq2 != null)
                Assert.AreEqual(eq1.GetHashCode(), eq2.GetHashCode());
        }

        [Test]
        public void TestInequality()
        {
            Assert.AreNotEqual(eq1, neq);
            if (eq1 != null && neq != null)
                Assert.AreNotEqual(eq1.GetHashCode(), neq.GetHashCode());
        }
    }

    public class ParameterizedTestFixtureNamingTests
    {
        TestSuite fixture;

        [SetUp]
        public void MakeFixture()
        {
            fixture = TestBuilder.MakeFixture(typeof(NUnit.TestData.ParameterizedTestFixture));
        }

        [Test]
        public void TopLevelSuiteIsNamedCorrectly()
        {
            Assert.That(fixture.Name, Is.EqualTo("ParameterizedTestFixture"));
            Assert.That(fixture.FullName, Is.EqualTo("NUnit.TestData.ParameterizedTestFixture"));
        }

        [Test]
        public void SuiteHasCorrectNumberOfInstances()
        {
            Assert.That(fixture.Tests.Count, Is.EqualTo(2));
        }

        [Test]
        public void FixtureInstancesAreNamedCorrectly()
        {
            var names = new List<string>();
            var fullnames = new List<string>();
            foreach (Test test in fixture.Tests)
            {
                names.Add(test.Name);
                fullnames.Add(test.FullName);
            }

            Assert.That(names, Is.EquivalentTo(new[] {
                "ParameterizedTestFixture(1)", "ParameterizedTestFixture(2)" }));
            Assert.That(fullnames, Is.EquivalentTo(new[] {
                "NUnit.TestData.ParameterizedTestFixture(1)", "NUnit.TestData.ParameterizedTestFixture(2)" }));
        }

        [Test]
        public void MethodWithoutParamsIsNamedCorrectly()
        {
            TestSuite instance = (TestSuite)fixture.Tests[0];
            Test method = TestFinder.Find("MethodWithoutParams", instance, false);
            Assert.That(method, Is.Not.Null );
            Assert.That(method.FullName, Is.EqualTo(instance.FullName + ".MethodWithoutParams"));
        }

        [Test]
        public void MethodWithParamsIsNamedCorrectly()
        {
            TestSuite instance = (TestSuite)fixture.Tests[0];
            TestSuite method = (TestSuite)TestFinder.Find("MethodWithParams", instance, false);
            Assert.That(method, Is.Not.Null);

            Test testcase = (Test)method.Tests[0];
            Assert.That(testcase.Name, Is.EqualTo("MethodWithParams(10,20)"));
            Assert.That(testcase.FullName, Is.EqualTo(instance.FullName + ".MethodWithParams(10,20)"));
        }
    }

    public class ParameterizedTestFixtureTests
    {
        [Test]
        public void CanSpecifyCategory()
        {
            Test fixture = TestBuilder.MakeFixture(typeof(NUnit.TestData.TestFixtureWithSingleCategory));
            Assert.AreEqual("XYZ", fixture.Properties.Get(PropertyNames.Category));
        }

        [Test]
        public void CanSpecifyMultipleCategories()
        {
            Test fixture = TestBuilder.MakeFixture(typeof(NUnit.TestData.TestFixtureWithMultipleCategories));
            Assert.AreEqual(new[] { "X", "Y", "Z" }, fixture.Properties[PropertyNames.Category]);
        }

        [Test]
        public void NullArgumentForOrdinaryValueTypeParameterDoesNotThrowNullReferenceException()
        {
            Test fixture = TestBuilder.MakeFixture(typeof(NUnit.TestData.TestFixtureWithNullArgumentForOrdinaryValueTypeParameter));
            Assert.That(fixture.RunState, Is.EqualTo(RunState.NotRunnable));
            Assert.That(fixture.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("No suitable constructor was found"));
        }

        [Test]
        public void NullArgumentForGenericParameterDoesNotThrowNullReferenceException()
        {
            Test parameterizedFixture = TestBuilder.MakeFixture(typeof(NUnit.TestData.TestFixtureWithNullArgumentForGenericParameter<>));
            ITest fixture = parameterizedFixture.Tests.Single();

            Assert.That(fixture.RunState, Is.EqualTo(RunState.NotRunnable));
            Assert.That(fixture.Properties.Get(PropertyNames.SkipReason), Is.EqualTo(
                "Fixture type contains generic parameters. You must either provide Type arguments or specify constructor arguments that allow NUnit to deduce the Type arguments."));
        }
    }

    [TestFixture(typeof(int))]
    [TestFixture(typeof(string))]
    public class ParameterizedTestFixtureWithTypeAsArgument
    {
        private readonly Type _someType;

        public ParameterizedTestFixtureWithTypeAsArgument(Type someType)
        {
            _someType = someType;
        }

        [Test]
        public void MakeSureTypeIsInSystemNamespace()
        {
            Assert.AreEqual("System", _someType.Namespace);
        }
    }
}


text:
// Created on 20.11.2003 by RST.
// $Id: particle_t.java,v 1.3 2004/12/14 12:48:51 cawe Exp $
package org.free.jake2.client;

import org.free.jake2.Defines;
import org.free.jake2.util.Lib;

import java.nio.*;

public class particle_t {

  // lwjgl renderer needs a ByteBuffer
  private static ByteBuffer colorByteArray = Lib.newByteBuffer(Defines.MAX_PARTICLES * Lib.SIZEOF_INT, ByteOrder.LITTLE_ENDIAN);
  public static FloatBuffer vertexArray = Lib.newFloatBuffer(Defines.MAX_PARTICLES * 3);
  public static int[] colorTable = new int[256];
  public static IntBuffer colorArray = colorByteArray.asIntBuffer();

  public static void setColorPalette(int[] palette) {
    for (int i = 0; i < 256; i++) {
      colorTable[i] = palette[i] & 0x00FFFFFF;
    }
  }

  public static ByteBuffer getColorAsByteBuffer() {
    return colorByteArray;
  }
}


text:
<?php namespace PCI\Events\Petition;

/**
 * Class PetitionApprovalRequest
 *
 * @package PCI\Events\Petition
 * @author  Alejandro Granadillo <slayerfat@gmail.com>
 * @link    https://github.com/slayerfat/sistemaPCI Repositorio en linea.
 */
class PetitionApprovalRequest extends NewPetitionCreation
{

    //
}


text:
var https = require('https');
var util = require('util');
var events = require('events');
var fs = require('fs');
var WebSocket = require('ws');

var SERVER = 'scratch.mit.edu';
var PROJECTS_SERVER = 'projects.scratch.mit.edu';
var CDN_SERVER = 'cdn.scratch.mit.edu';
var CLOUD_SERVER = 'clouddata.scratch.mit.edu';
var API_SERVER = 'api.scratch.mit.edu';

var SESSION_FILE = '.scratchSession';

function request(options, cb) {
  var headers = {
    'Cookie': 'scratchcsrftoken=a; scratchlanguage=en;',
    'X-CSRFToken': 'a',
    'referer': 'https://scratch.mit.edu' // Required by Scratch servers
  };
  if (options.headers) {
    for (var name in options.headers) {
      headers[name] = options.headers[name];
    }
  }
  if (options.body) headers['Content-Length'] = Buffer.byteLength(options.body);
  if (options.sessionId) headers.Cookie += 'scratchsessionsid=' + options.sessionId + ';';
  var req = https.request({
    hostname: options.hostname || SERVER,
    port: 443,
    path: options.path,
    method: options.method || 'GET',
    headers: headers
  }, function(response) {
    var parts = [];
    response.on('data', function(chunk) { parts.push(chunk); });
    response.on('end', function() { cb(null, Buffer.concat(parts).toString(), response); });
  });
  req.on('error', cb);
  if (options.body) req.write(options.body);
  req.end();
}

function requestJSON(options, cb) {
  request(options, function(err, body, response) {
    if (err) return cb(err);
    try {
      cb(null, JSON.parse(body));
    } catch (e) {
      cb(e);
    }
  });
}

function parseCookie(cookie) {
  var cookies = {};
  var each = cookie.split(';');
  var i = each.length;
  while (i--) {
    if (each[i].indexOf('=') === -1) {
      continue;
    }
    var pair = each[i].split('=');
    cookies[pair[0].trim()] = pair[1].trim();
  }
  return cookies;
}

var Scratch = {};

Scratch.getProject = function(projectId, cb) {
  requestJSON({
    hostname: PROJECTS_SERVER,
    path: '/' + projectId,
    method: 'GET',
  }, cb);
};
Scratch.getProjects = function(username, cb) {
  requestJSON({
    hostname: API_SERVER,
    path: '/users/' + username + '/projects',
    method: 'GET'
  }, cb);
};
Scratch.UserSession = function(username, id, sessionId) {
  this.username = username;
  this.id = id;
  this.sessionId = sessionId;
};
Scratch.UserSession.create = function(username, password, cb) {
  request({
    path: '/login/',
    method: 'POST',
    body: JSON.stringify({username: username, password: password}),
    headers: {'X-Requested-With': 'XMLHttpRequest'}
  }, function(err, body, response) {
    if (err) return cb(err);
    try {
      var user = JSON.parse(body)[0];
      if (user.msg) return cb(new Error(user.msg));
      cb(null, new Scratch.UserSession(user.username, user.id, parseCookie(response.headers['set-cookie'][0]).scratchsessionsid));
    } catch (e) {
      cb(e);
    }
  });
};
Scratch.UserSession.prompt = function(cb) {
  var prompt = require('prompt');
  prompt.start();
  prompt.get([
    { name: 'username' },
    { name: 'password', hidden: true }
  ], function(err, results) {
    if (err) return cb(err);
    Scratch.UserSession.create(results.username, results.password, cb);
  });
};
Scratch.UserSession.load = function(cb) {
  function prompt() {
    Scratch.UserSession.prompt(function(err, session) {
      if (err) return cb(err);
      session._saveSession(function() {
        cb(null, session);
      });
    });
  }
  fs.readFile(SESSION_FILE, function(err, data) {
    if (err) return prompt();
    var obj = JSON.parse(data.toString());
    var session = new Scratch.UserSession(obj.username, obj.id, obj.sessionId);
    session.verify(function(err, valid) {
      if (err) return cb(err);
      if (valid) return cb(null, session);
      prompt();
    });
  });
};
Scratch.UserSession.prototype._saveSession = function(cb) {
  fs.writeFile(SESSION_FILE, JSON.stringify({
    username: this.username,
    id: this.id,
    sessionId: this.sessionId
  }), cb);
};
Scratch.UserSession.prototype.verify = function(cb) {
  request({
    path: '/messages/ajax/get-message-count/', // probably going to change quite soon
    sessionId: this.sessionId
  }, function(err, body, response) {
    cb(null, !err && response.statusCode === 200);
  });
};
Scratch.UserSession.prototype.getProject = Scratch.getProject;
Scratch.UserSession.prototype.getProjects = function(cb) {
  Scratch.getProjects(this.username, cb);
};

Scratch.UserSession.prototype.getAllProjects = function(cb) {
  requestJSON({
    hostname: SERVER,
    path: '/site-api/projects/all/',
    method: 'GET',
    sessionId: this.sessionId
  }, cb);
};
Scratch.UserSession.prototype.setProject = function(projectId, payload, cb) {
  if (typeof payload !== 'string') payload = JSON.stringify(payload);
  requestJSON({
    hostname: PROJECTS_SERVER,
    path: '/internalapi/project/' + projectId + '/set/',
    method: 'POST',
    body: payload,
    sessionId: this.sessionId
  }, cb);
};
Scratch.UserSession.prototype.getBackpack = function(cb) {
  requestJSON({
    hostname: SERVER,
    path: '/internalapi/backpack/' + this.username + '/get/',
    method: 'GET',
    sessionId: this.sessionId
  }, cb);
};
Scratch.UserSession.prototype.setBackpack = function(payload, cb) {
  if (typeof payload !== 'string') payload = JSON.stringify(payload);
  requestJSON({
    hostname: SERVER,
    path: '/internalapi/backpack/' + this.username + '/set/',
    method: 'POST',
    body: payload,
    sessionId: this.sessionId
  }, cb);
};
Scratch.UserSession.prototype.addComment = function(options, cb) {
  var type, id;
  if (options.project) {
    type = 'project';
    id = options.project;
  } else if (options.user) {
    type = 'user';
    id = options.user;
  } else if (options.studio) {
    type = 'gallery';
    id = options.studio;
  }
  request({
    hostname: SERVER,
    path: '/site-api/comments/' + type + '/' + id + '/add/',
    method: 'POST',
    body: JSON.stringify({
      content: options.content,
      parent_id: options.parent || '',
      commentee_id: options.replyto || '',
    }),
    sessionId: this.sessionId
  }, cb);
};
Scratch.UserSession.prototype.cloudSession = function(projectId, cb) {
    Scratch.CloudSession._create(this, projectId, cb);
};

Scratch.CloudSession = function(user, projectId) {
  this.user = user;
  this.projectId = '' + projectId;
  this.connection = null;
  this.attemptedPackets = [];
  this.variables = Object.create(null);
  this._variables = Object.create(null);
};
util.inherits(Scratch.CloudSession, events.EventEmitter);
Scratch.CloudSession._create = function(user, projectId, cb) {
  var session = new Scratch.CloudSession(user, projectId);
  session._connect(function(err) {
    if (err) return cb(err);
    cb(null, session);
  });
};
Scratch.CloudSession.prototype._connect = function(cb) {
  var self = this;

  this.connection = new WebSocket('wss://' + CLOUD_SERVER + '/', [], {
      headers: {
        cookie: 'scratchsessionsid=' + this.user.sessionId + ';',
        origin: 'https://scratch.mit.edu'
      }
    }
  );
  this.connection.on('open', function() {
    self._sendHandshake();
    for (var i = 0; i < self.attemptedPackets.length; i++) {
      self._sendPacket(self.attemptedPackets[i]);
    }
    self.attemptedPackets = [];
    if (cb) cb();
  });

  this.connection.on('close', function() {
    // Reconnect because Scratch disconnects clients after no activity
    // Probably will cause some data to not be pushed
    self._connect();
  });

  var stream = '';
  this.connection.on('message', function(chunk) {
    stream += chunk;
    var packets = stream.split('\n');
    for(var i = 0; i < packets.length - 1; i++) {
      var line = packets[i];
      var packet;
      try {
        packet = JSON.parse(line);
      } catch (err) {
        console.warn('Invalid packet %s', line);
        return;
      }
      self._handlePacket(packet);
    }
    stream = packets[packets.length - 1];
  });
};
Scratch.CloudSession.prototype.end = function() {
  if (this.connection) {
    this.connection.close();
  }
};
Scratch.CloudSession.prototype.get = function(name) {
  return this._variables[name];
};
Scratch.CloudSession.prototype.set = function(name, value) {
  this._variables[name] = value;
  this._sendSet(name, value);
};
Scratch.CloudSession.prototype._handlePacket = function(packet) {
  switch (packet.method) {
    case 'set':
      if (!({}).hasOwnProperty.call(this.variables, packet.name)) {
        this._addVariable(packet.name, packet.value);
      }
      this._variables[packet.name] = packet.value;
      this.emit('set', packet.name, packet.value);
      break;
    default:
      console.warn('Unimplemented packet', packet.method);
  }
};
Scratch.CloudSession.prototype._sendHandshake = function() {
  this._send('handshake', {});
};
Scratch.CloudSession.prototype._sendSet = function(name, value) {
  this._send('set', {
    name: name,
    value: value
  });
};
Scratch.CloudSession.prototype._send = function(method, options) {
  var object = {
    user: this.user.username,
    project_id: this.projectId,
    method: method
  };
  for (var name in options) {
    object[name] = options[name];
  }

  this._sendPacket(JSON.stringify(object) + '\n');
};
Scratch.CloudSession.prototype._sendPacket = function(data) {
  if (this.connection.readyState === WebSocket.OPEN) {
    this.connection.send(data);
  } else {
    this.attemptedPackets.push(data);
  }
};
Scratch.CloudSession.prototype._addVariable = function(name, value) {
  var self = this;
  this._variables[name] = value;
  Object.defineProperty(this.variables, name, {
    enumerable: true,
    get: function() {
      return self.get(name);
    },
    set: function(value) {
      self.set(name, value);
    }
  });
};

module.exports = Scratch;


text:
package com.planet_ink.coffee_mud.Races;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class WereAmphibian extends StdRace
{
	@Override
	public String ID()
	{
		return "WereAmphibian";
	}

	private final static String localizedStaticName = CMLib.lang().L("WereAmphibian");

	@Override
	public String name()
	{
		return localizedStaticName;
	}

	@Override
	public int shortestMale()
	{
		return 59;
	}

	@Override
	public int shortestFemale()
	{
		return 59;
	}

	@Override
	public int heightVariance()
	{
		return 12;
	}

	@Override
	public int lightestWeight()
	{
		return 80;
	}

	@Override
	public int weightVariance()
	{
		return 80;
	}

	@Override
	public long forbiddenWornBits()
	{
		return 0;
	}

	private final static String localizedStaticRacialCat = CMLib.lang().L("Amphibian");

	@Override
	public String racialCategory()
	{
		return localizedStaticRacialCat;
	}

	private final String[]	racialAbilityNames			= { "Skill_Swim" };
	private final int[]		racialAbilityLevels			= { 1 };
	private final int[]		racialAbilityProficiencies	= { 100 };
	private final boolean[]	racialAbilityQuals			= { false };
	private final String[]	racialAbilityParms			= { "" };

	@Override
	protected String[] racialAbilityNames()
	{
		return racialAbilityNames;
	}

	@Override
	protected int[] racialAbilityLevels()
	{
		return racialAbilityLevels;
	}

	@Override
	protected int[] racialAbilityProficiencies()
	{
		return racialAbilityProficiencies;
	}

	@Override
	protected boolean[] racialAbilityQuals()
	{
		return racialAbilityQuals;
	}

	@Override
	public String[] racialAbilityParms()
	{
		return racialAbilityParms;
	}

	@Override
	public int[] getBreathables()
	{
		return breatheAirWaterArray;
	}

	//  							  an ey ea he ne ar ha to le fo no gi mo wa ta wi
	private static final int[] parts={0 ,2 ,2 ,1 ,1 ,2 ,2 ,1 ,2 ,2 ,1 ,1 ,1 ,1 ,1 ,0 };

	@Override
	public int[] bodyMask()
	{
		return parts;
	}

	private final int[]	agingChart	= { 0, 4, 8, 12, 16, 20, 24, 28, 32 };

	@Override
	public int[] getAgingChart()
	{
		return agingChart;
	}

	private static Vector<RawMaterial>	resources	= new Vector<RawMaterial>();

	@Override
	public Weapon myNaturalWeapon()
	{
		if(naturalWeapon==null)
		{
			naturalWeapon=CMClass.getWeapon("StdWeapon");
			naturalWeapon.setName(L("sharp claws"));
			naturalWeapon.setMaterial(RawMaterial.RESOURCE_BONE);
			naturalWeapon.setUsesRemaining(1000);
			naturalWeapon.setWeaponDamageType(Weapon.TYPE_SLASHING);
		}
		return naturalWeapon;
	}

	@Override
	public void affectPhyStats(final Physical affected, final PhyStats affectableStats)
	{
		final MOB mob=(MOB)affected;
		final Room R=mob.location();
		if((R!=null)
		&&(CMLib.flags().isWateryRoom(R)))
			affectableStats.setDisposition(affectableStats.disposition()|PhyStats.IS_SWIMMING);
	}

	@Override
	public String healthText(final MOB viewer, final MOB mob)
	{
		final double pct=(CMath.div(mob.curState().getHitPoints(),mob.maxState().getHitPoints()));

		if(pct<.10)
			return L("^r@x1^r is facing a cold death!^N",mob.name(viewer));
		else
		if(pct<.20)
			return L("^r@x1^r is covered in blood.^N",mob.name(viewer));
		else
		if(pct<.30)
			return L("^r@x1^r is bleeding badly from lots of wounds.^N",mob.name(viewer));
		else
		if(pct<.40)
			return L("^y@x1^y has numerous bloody wounds and gashes.^N",mob.name(viewer));
		else
		if(pct<.50)
			return L("^y@x1^y has some bloody wounds and gashes.^N",mob.name(viewer));
		else
		if(pct<.60)
			return L("^p@x1^p has a few bloody wounds.^N",mob.name(viewer));
		else
		if(pct<.70)
			return L("^p@x1^p is cut and bruised heavily.^N",mob.name(viewer));
		else
		if(pct<.80)
			return L("^g@x1^g has some minor cuts and bruises.^N",mob.name(viewer));
		else
		if(pct<.90)
			return L("^g@x1^g has a few bruises and scratched scales.^N",mob.name(viewer));
		else
		if(pct<.99)
			return L("^g@x1^g has a few small bruises.^N",mob.name(viewer));
		else
			return L("^c@x1^c is in perfect health.^N",mob.name(viewer));
	}

	@Override
	public List<RawMaterial> myResources()
	{
		synchronized(resources)
		{
			if(resources.size()==0)
			{
				resources.addElement(makeResource
				(L("a @x1 tongue",name().toLowerCase()),RawMaterial.RESOURCE_MEAT));
				for(int i=0;i<5;i++)
				{
					resources.addElement(makeResource
					(L("a pound of @x1 meat",name().toLowerCase()),RawMaterial.RESOURCE_MEAT));
				}
				for(int i=0;i<15;i++)
				{
					resources.addElement(makeResource
					(L("a @x1 hide",name().toLowerCase()),RawMaterial.RESOURCE_HIDE));
				}
				resources.addElement(makeResource
				(L("some @x1 blood",name().toLowerCase()),RawMaterial.RESOURCE_BLOOD));
			}
		}
		return resources;
	}
}


text:
package ninchatapi

// MemberAttrs action parameter type.
type MemberAttrs interface {
	memberAttrs()
}

func (*ChannelMemberAttrs) memberAttrs() {}
func (*QueueMemberAttrs) memberAttrs()   {}
func (*RealmMemberAttrs) memberAttrs()   {}

// UserInfoAttr represents the user "info" attribute.
type UserInfoAttr struct {
	Company *string `json:"company,omitempty"`
	Url     *string `json:"url,omitempty"`
}

// NewUserInfoAttr.
func NewUserInfoAttr(source map[string]interface{}) (target *UserInfoAttr) {
	target = new(UserInfoAttr)

	if x := source["company"]; x != nil {
		if y, ok := x.(string); ok {
			target.Company = &y
		}
	}

	if x := source["url"]; x != nil {
		if y, ok := x.(string); ok {
			target.Url = &y
		}
	}

	return
}

// RealmOwnerAccountAttr represents the realm "owner_account" attribute.
type RealmOwnerAccountAttr struct {
	Channels     *UserAccountObjects `json:"channels"`
	QueueMembers *UserAccountMembers `json:"queue_members"`
	Queues       *UserAccountObjects `json:"queues"`
}

// NewRealmOwnerAccountAttr.
func NewRealmOwnerAccountAttr(source map[string]interface{}) (target *RealmOwnerAccountAttr) {
	target = new(RealmOwnerAccountAttr)

	if x := source["channels"]; x != nil {
		if y, ok := x.(map[string]interface{}); ok {
			target.Channels = NewUserAccountObjects(y)
		}
	}

	if x := source["queue_members"]; x != nil {
		if y, ok := x.(map[string]interface{}); ok {
			target.QueueMembers = NewUserAccountMembers(y)
		}
	}

	if x := source["queues"]; x != nil {
		if y, ok := x.(map[string]interface{}); ok {
			target.Queues = NewUserAccountObjects(y)
		}
	}

	return
}

// ThemeAttr represents "theme" attributes.
type ThemeAttr struct {
	Color *string `json:"color,omitempty"`
}

func (target *ThemeAttr) init(source map[string]interface{}) {
	if x := source["color"]; x != nil {
		if y, ok := x.(string); ok {
			target.Color = &y
		}
	}
}

// RealmThemeAttr represents the realm "theme" attribute.
type RealmThemeAttr struct {
	ThemeAttr
}

// NewRealmThemeAttr.
func NewRealmThemeAttr(source map[string]interface{}) (target *RealmThemeAttr) {
	target = new(RealmThemeAttr)
	target.init(source)
	return
}

// TagThemeAttr represents the tag "theme" attribute.
type TagThemeAttr struct {
	ThemeAttr
}

// NewTagThemeAttr.
func NewTagThemeAttr(source map[string]interface{}) (target *TagThemeAttr) {
	target = new(TagThemeAttr)
	target.init(source)
	return
}


text:
[GoXyMemory][git-goxymemory-url] is a port of [XyMemory][git-xymemory-url] (Python) to GoLang.
This project allows read and write process memory using a [fork][git-w32-fork-url] of syscalls wrapper called
[w32][git-w32-url] from [AllenDang][git-allen-url].

# Example of use
First, we need download and install this [repo][git-goxymemory-url] with go commands and next, use the DataManager
class like the [example][git-goxymemory-example-url] below.

```
$> go get github.com/Xustyx/goxymemory
$> go install github.com/Xustyx/goxymemory
```

```go
//Init
dm := goxymemmory.DataManager("StarCraft.exe") 	        //Get the DataManager with the process passed.
if !dm.IsOpen{				                            //Check if process was opened.
    fmt.Printf("Failed opening process.\n")
    return
}

//(READ/WRITE) String example.
err := dm.Write(0X0059B420,
    goxymemmory.Data{"TROLORO", goxymemmory.STRING})	//Write a string.
if err != nil {							                //Check if not failed.
    fmt.Printf("Failed writing memory. %s", err)
}
data, err := dm.Read(0X0059B420, goxymemmory.STRING)	//Reads the string.
if err != nil {						                    //Check if not failed.
    fmt.Printf("Failed reading memory. %s", err)
}
fmt.Println("STRING: ", data)					        //Print the value.

//(READ/WRITE) Byte example.
err = dm.Write(0X0059B420,
    goxymemmory.Data{256, goxymemmory.BYTE})		    //Write a byte.
if err != nil {							                //Check if not failed.
    fmt.Printf("Failed writing memory. %s", err)
}
data, err = dm.Read(0X0059B420 ,goxymemmory.BYTE)		//Reads the byte.
if err != nil {							                //Check if not failed.
    fmt.Printf("Failed reading memory. %s", err)
}
fmt.Println("BYTE: ", data)				            	//Print the value.

//(READ/WRITE) Int example.
err = dm.Write(0X0057F0F4,
    goxymemmory.Data{-1, goxymemmory.INT})			     //Write an int.
if err != nil {							                 //Check if not failed.
    fmt.Printf("Failed writing memory. %s", err)
}
data, err = dm.Read(0X0057F0F4, goxymemmory.INT)		//Reads the int.
if err != nil {						                	//Check if not failed.
    fmt.Printf("Failed reading memory. %s", err)
}
fmt.Println("INT: ", data)					            //Print the value.

//(READ/WRITE) Uint example.
err = dm.Write(0X0057F0F0,
    goxymemmory.Data{500, goxymemmory.UINT})	    	//Write an uint.
if err != nil {							                //Check if not failed.
    fmt.Printf("Failed writing memory. %s", err)
}
data, err = dm.Read(0X0057F0F0, goxymemmory.UINT)		//Reads the uint.
if err != nil {						                	//Check if not failed.
    fmt.Printf("Failed reading memory. %s", err)
}
fmt.Println("UINT: ", data)					            //Print the value.
```

# Actually supported types and methods
### Types
- BYTE: 'byte'
- STRING: 'string'
- INT: 'int'
- UINT: 'uint'

### Methods (DataManager)
* DataManager(processName string)
  * processName: The process name to handle.
* read(address uint, dataType DataType)
  * address: Memory address in hexadecimal format.
  * dataType: The enum value of desired Type.
* write(address uint, data Data)
  * address: Memory address in hexadecimal format.
  * data: Struct that contains the data to add and the enum value of desired Type.

#Disclaimer
The author can not be held liable for any use of this code.

[git-goxymemory-example-url]: <https://github.com/Xustyx/goxymemory/tree/master/example>
[git-goxymemory-url]: <https://github.com/Xustyx/goxymemory>
[git-xymemory-url]: <https://github.com/Xustyx/xymemory>
[git-w32-url]: <https://github.com/AllenDang/w32>
[git-allen-url]: <https://github.com/AllenDang/w32>
[git-w32-fork-url]: <https://github.com/Xustyx/w32>


text:
/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.uccollaborationlib;
import com.wilutions.com.*;

/**
 * ILocaleString.
 * ILocaleString Interface
 */
@CoInterface(guid="{C12F0DE5-9A7D-425C-B391-8BE004EAA2F6}")
public interface ILocaleString extends IDispatch {
  static boolean __typelib__loaded = __TypeLib.load();
  @DeclDISPID(1610743808)  public Integer getLocaleId() throws ComException;
  @DeclDISPID(1610743809)  public String getValue() throws ComException;
}


text:
package org.apache.camel.component.dozer;

import org.apache.camel.CamelContext;
import org.apache.camel.EndpointInject;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.dozer.example.abc.ABCOrder;
import org.apache.camel.component.dozer.example.abc.ABCOrder.Header;
import org.apache.camel.component.dozer.example.xyz.XYZOrder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class VariableMappingTest {

    @EndpointInject("mock:result")
    private MockEndpoint resultEndpoint;

    @Produce("direct:start")
    private ProducerTemplate startEndpoint;

    @Autowired
    private CamelContext camelContext;

    @After
    public void tearDown() {
        resultEndpoint.reset();
    }

    @Test
    public void testLiteralMapping() throws Exception {
        resultEndpoint.expectedMessageCount(1);
        ABCOrder abcOrder = new ABCOrder();
        abcOrder.setHeader(new Header());
        abcOrder.getHeader().setStatus("GOLD");
        startEndpoint.sendBody(abcOrder);
        // check results
        resultEndpoint.assertIsSatisfied();
        XYZOrder result = resultEndpoint.getExchanges().get(0).getIn().getBody(XYZOrder.class);
        Assert.assertEquals(result.getPriority(), "GOLD");
        Assert.assertEquals("ACME-SALES", result.getCustId());
        Assert.assertEquals("W123-EG", result.getOrderId());
    }
}


text:
package net.imagej.ops.geom.geom2d;

import java.util.List;

import net.imagej.ops.Ops;
import net.imagej.ops.geom.GeomUtils;
import net.imagej.ops.special.function.Functions;
import net.imagej.ops.special.function.UnaryFunctionOp;
import net.imagej.ops.special.hybrid.AbstractUnaryHybridCF;
import net.imglib2.RealLocalizable;
import net.imglib2.roi.geom.real.Polygon2D;
import net.imglib2.type.numeric.real.DoubleType;

import org.scijava.plugin.Plugin;

/**
 * Generic implementation of {@code geom.mainElongation} based on
 * http://www.math.uci.edu/icamp/summer/research_11/park/
 * shape_descriptors_survey.pdf.
 *
 * @author Tim-Oliver Buchholz, University of Konstanz
 */
@Plugin(type = Ops.Geometric.MainElongation.class,
	label = "Geometric (2D): Elongation")
public class DefaultElongation extends
	AbstractUnaryHybridCF<Polygon2D, DoubleType> implements
	Ops.Geometric.MainElongation
{

	private UnaryFunctionOp<Polygon2D, Polygon2D> minimumBoundingBoxFunc;

	@Override
	public void initialize() {
		minimumBoundingBoxFunc = Functions.unary(ops(),
			Ops.Geometric.SmallestEnclosingBoundingBox.class, Polygon2D.class, in());
	}

	@Override
	public void compute(final Polygon2D input, final DoubleType output) {
		final List<? extends RealLocalizable> minBB = GeomUtils.vertices(
			minimumBoundingBoxFunc.calculate(input));

		final RealLocalizable p1 = minBB.get(0);
		final RealLocalizable p2 = minBB.get(1);
		final RealLocalizable p3 = minBB.get(2);

		double width = Math.sqrt(Math.pow(p1.getDoublePosition(0) - p2
			.getDoublePosition(0), 2) + Math.pow(p1.getDoublePosition(1) - p2
				.getDoublePosition(1), 2));
		double length = Math.sqrt(Math.pow(p2.getDoublePosition(0) - p3
			.getDoublePosition(0), 2) + Math.pow(p2.getDoublePosition(1) - p3
				.getDoublePosition(1), 2));

		if (width > length) {
			final double tmp = width;
			width = length;
			length = tmp;
		}
		output.set(1d - (width / length));
	}

	@Override
	public DoubleType createOutput(Polygon2D input) {
		return new DoubleType();
	}

}


text:
package com.ftoslab.openweatherretrieverz;

import java.util.Date;
import java.util.List;
import java.util.TimeZone;

public class Main {

	/**
	 * @param args
	 */
//	public static void main(String[] args) {
//		// TODO Auto-generated method stub
//		Date date = new Date(System.currentTimeMillis() + TimeZone.getDefault().getRawOffset());
//		System.out.println("date: " + date.toString());
//		OpenWeatherRetrieverZ retreiever = new OpenWeatherRetrieverZ("ea6ab1ca55169a961c105dd860a3d79f");
//		retreiever.updateCurrentWeatherInfo("6167865", new WeatherCallback(){
//
//			@Override
//			public void onReceiveWeatherInfo(CurrentWeatherInfo currentWeatherInfo) {
//				// TODO Auto-generated method stub
//				System.out.println("---------------------Current Weather Default---------------------");
//				System.out.println("cityName: " + currentWeatherInfo.getCityName());
//				System.out.println("cityId: " + currentWeatherInfo.getCityId());
//				System.out.println("short: " + currentWeatherInfo.getWeatherDescriptionShort());
//				System.out.println("long: " + currentWeatherInfo.getWeatherDescriptionLong());
//				System.out.println("icon: " + currentWeatherInfo.getWeatherIconId());
//				System.out.println("temp: " + currentWeatherInfo.getCurrentTemperature());
//				System.out.println("temp max: " + currentWeatherInfo.getCurrentTemperatureMax());
//				System.out.println("temp min: " + currentWeatherInfo.getCurrentTemperatureMin());
//				System.out.println("pressure: " + currentWeatherInfo.getPressure());
//				System.out.println("humidity: " + currentWeatherInfo.getHumidity());
//				System.out.println("wind speed: " + currentWeatherInfo.getWindSpeed());
//				System.out.println("snow vol: " + currentWeatherInfo.getSnowVolumeLast3hrs());
//				System.out.println("rain vol: " + currentWeatherInfo.getRainVolumeLast3hrs());
//				System.out.println("---------------------------------------------------------");
//				currentWeatherInfo = WeatherUnitConverter.convertToImperial(currentWeatherInfo);
//				System.out.println("---------------------Current Weather Imperial---------------------");
//				System.out.println("cityName: " + currentWeatherInfo.getCityName());
//				System.out.println("cityId: " + currentWeatherInfo.getCityId());
//				System.out.println("short: " + currentWeatherInfo.getWeatherDescriptionShort());
//				System.out.println("long: " + currentWeatherInfo.getWeatherDescriptionLong());
//				System.out.println("icon: " + currentWeatherInfo.getWeatherIconId());
//				System.out.println("temp: " + currentWeatherInfo.getCurrentTemperature());
//				System.out.println("temp max: " + currentWeatherInfo.getCurrentTemperatureMax());
//				System.out.println("temp min: " + currentWeatherInfo.getCurrentTemperatureMin());
//				System.out.println("pressure: " + currentWeatherInfo.getPressure());
//				System.out.println("humidity: " + currentWeatherInfo.getHumidity());
//				System.out.println("wind speed: " + currentWeatherInfo.getWindSpeed());
//				System.out.println("snow vol: " + currentWeatherInfo.getSnowVolumeLast3hrs());
//				System.out.println("rain vol: " + currentWeatherInfo.getRainVolumeLast3hrs());
//				System.out.println("---------------------------------------------------------");
//				currentWeatherInfo = WeatherUnitConverter.convertToMetric(currentWeatherInfo);
//				System.out.println("---------------------Current Weather Metric---------------------");
//				System.out.println("cityName: " + currentWeatherInfo.getCityName());
//				System.out.println("cityId: " + currentWeatherInfo.getCityId());
//				System.out.println("short: " + currentWeatherInfo.getWeatherDescriptionShort());
//				System.out.println("long: " + currentWeatherInfo.getWeatherDescriptionLong());
//				System.out.println("icon: " + currentWeatherInfo.getWeatherIconId());
//				System.out.println("temp: " + currentWeatherInfo.getCurrentTemperature());
//				System.out.println("temp max: " + currentWeatherInfo.getCurrentTemperatureMax());
//				System.out.println("temp min: " + currentWeatherInfo.getCurrentTemperatureMin());
//				System.out.println("pressure: " + currentWeatherInfo.getPressure());
//				System.out.println("humidity: " + currentWeatherInfo.getHumidity());
//				System.out.println("wind speed: " + currentWeatherInfo.getWindSpeed());
//				System.out.println("snow vol: " + currentWeatherInfo.getSnowVolumeLast3hrs());
//				System.out.println("rain vol: " + currentWeatherInfo.getRainVolumeLast3hrs());
//				System.out.println("---------------------------------------------------------");
//			}
//
//			@Override
//			public void onFailure(String error) {
//				// TODO Auto-generated method stub
//				System.err.println(error);
//			}
//
//		});
//		retreiever.updateDailyForecastInfo("6167865", TimeZone.getDefault(), new DailyForecastCallback(){
//
//			@Override
//			public void onReceiveDailyForecastInfoList(List<DailyForecastInfo> dailyForecastInfoList) {
//				// TODO Auto-generated method stub
//				System.out.println("onReceiveDailyForecastList");
//			}
//
//			@Override
//			public void onFailure(String error) {
//				// TODO Auto-generated method stub
//				//System.err.println(error);
//			}
//
//
//
//		});
//
//		//System.out.println("shouldn't be waiting");
//		// TODO Test if thread calls back
//		try {
//			Thread.sleep(100000);
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}

}


text:
namespace LayoutEngine {
    public enum ElementType {
        Text,
        Tag
    }
}


text:
namespace ui {

// Provides common implementation of a GPU memory buffer.
class MUS_COMMON_EXPORT GpuMemoryBufferImpl : public gfx::GpuMemoryBuffer {
 public:
  ~GpuMemoryBufferImpl() override;

  // Type-checking upcast routine. Returns an NULL on failure.
  static GpuMemoryBufferImpl* FromClientBuffer(ClientBuffer buffer);

  // Overridden from gfx::GpuMemoryBuffer:
  gfx::Size GetSize() const override;
  gfx::BufferFormat GetFormat() const override;
  gfx::GpuMemoryBufferId GetId() const override;
  ClientBuffer AsClientBuffer() override;

  // Returns the type of this GpuMemoryBufferImpl.
  virtual gfx::GpuMemoryBufferType GetBufferType() const = 0;

#if defined(USE_OZONE)
  // Returns a ui::NativePixmap when one is available.
  virtual scoped_refptr<ui::NativePixmap> GetNativePixmap();
#endif

 protected:
  GpuMemoryBufferImpl(gfx::GpuMemoryBufferId id,
                      const gfx::Size& size,
                      gfx::BufferFormat format);

  const gfx::GpuMemoryBufferId id_;
  const gfx::Size size_;
  const gfx::BufferFormat format_;
  bool mapped_;

 private:
  DISALLOW_COPY_AND_ASSIGN(GpuMemoryBufferImpl);
};

}  // namespace ui

#endif  // SERVICES_UI_COMMON_GPU_MEMORY_BUFFER_IMPL_H_


text:
<?php
/**
 * Author: Jon Garcia.
 * Date: 4/28/17
 * Time: 7:41 PM
 */

namespace App\Core\Mail\Adapters;

interface MailAdapter
{
    /**
     * MailAdapter constructor.
     * @param array $settings
     */
    public function __construct(array $settings);

    /**
     * @param string $recipients
     * @param string $subject
     * @param string $body
     * @param string $headers
     * @param string|null $from
     * @param string|null $fromName
     * @return bool
     */
    public function send(
        string $recipients,
        string $subject,
        string $body,
        string $headers,
        string $from = null,
        string $fromName = null): bool;
}


text:
package com.ctrip.platform.dal.dao.unittests;

import com.ctrip.platform.dal.dao.DalClientFactory;
import org.junit.Assert;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;

public class DalClientFactoryLazeLoadTest {
	@Test
	public void testLazeLoad(){
		Assert.assertNotNull(DalClientFactory.getClient("dao_test"));
	}

	@Test
	public void testIitShutdown(){
		final CountDownLatch cdl = new CountDownLatch(10);
		for(int i=0; i < 10; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						for(int i=0; i < 100; i++) {
							DalClientFactory.initClientFactory();
							DalClientFactory.initClientFactory();
							DalClientFactory.shutdownFactory();
							DalClientFactory.shutdownFactory();
						}
					} catch (Exception e) {
						e.printStackTrace();
						Assert.fail();
					}
					cdl.countDown();
				}
			}).run();
		}
		try {
			cdl.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}


text:
from gengo import Gengo

# Get an instance of Gengo to work with...
gengo = Gengo(
    public_key='your_public_key',
    private_key='your_private_key',
    sandbox=True,
)

# Think of this as a "search my jobs" method, and it becomes very
# self-explanatory.
print gengo.getTranslationJobs(status="accepted", count=15)


text:
package com.bazaarvoice.ostrich.discovery.zookeeper;

import com.bazaarvoice.curator.recipes.NodeDiscovery;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.io.Closeables;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.ZKPaths;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class ZooKeeperServiceDiscoveryTest {
    private ZooKeeperServiceDiscovery _discovery;
    private NodeDiscovery<String> _nodeDiscovery;

    @SuppressWarnings("unchecked")
    @Before
    public void setup() throws Exception {
        _nodeDiscovery = mock(NodeDiscovery.class);
        _discovery = new ZooKeeperServiceDiscovery(_nodeDiscovery);
    }

    @After
    public void teardown() throws Exception {
        Closeables.close(_discovery, true);
    }

    @Test(expected = NullPointerException.class)
    public void testNullCurator() {
        new ZooKeeperServiceDiscovery((CuratorFramework) null);
    }

    @Test
    public void testNoServices() {
        setServices();
        assertEquals(0, Iterables.size(_discovery.getServices()));
    }

    @Test
    public void testOneService() {
        setServices("service");

        Iterable<String> services = _discovery.getServices();
        assertEquals(1, Iterables.size(services));
        assertEquals("service", Iterables.get(services, 0));
    }

    @Test
    public void testMultipleServices() {
        setServices("service1", "service2");

        Iterable<String> services = _discovery.getServices();
        assertEquals(2, Iterables.size(services));
        assertTrue(Iterables.contains(services, "service1"));
        assertTrue(Iterables.contains(services, "service2"));
    }

    @Test
    public void testClosesNodeDiscovery() throws IOException {
        _discovery.close();
        verify(_nodeDiscovery).close();
    }

    @Test
    public void testServiceNameParser() {
        String path = ZKPaths.makePath(ZooKeeperServiceDiscovery.ROOT_SERVICES_PATH, "service");

        String service = ZooKeeperServiceDiscovery.SERVICE_NAME_PARSER.parse(path, null);
        assertEquals("service", service);
    }

    private void setServices(String... services) {
        Map<String, String> serviceMap = Maps.newHashMap();
        for (String service : services) {
            serviceMap.put(service, service);
        }

        when(_nodeDiscovery.getNodes()).thenReturn(serviceMap);
    }
}


text:
Multiplayer
===========

A tiny library to build nice HTML embed codes for videos.

Example
-------

```php
$Multiplayer = new Multiplayer\Multiplayer();
$options = array(
	'autoPlay' => true,
	'foregroundColor' => 'BADA55'
);

echo $Multiplayer->html('http://www.dailymotion.com/video/xzn5qk', $options);
echo $Multiplayer->html('http://vimeo.com/47457051', $options);
echo $Multiplayer->html('http://www.youtube.com/watch?v=3qSMS4c5WAk', $options);
```

This code would produce:

```html
<iframe src="http://www.dailymotion.com/embed/video/xzn5qk?autoplay=1&foreground=#BADA55" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<iframe src="http://player.vimeo.com/video/47457051?autoplay=1&color=BADA55" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<iframe src="http://www.youtube-nocookie.com/embed/3qSMS4c5WAk?autoplay=1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
```

Templating
----------

You can customize the generated HTML code by passing a templating function:

```php
echo $Multiplayer->html($url, $options, function($playerUrl) {
    return '<iframe src="' . $playerUrl . '" class="video-player">'
});
```

A default one can also be set on instanciation:

```php
new Multiplayer\Multiplayer($services, function($playerUrl) {
    return '<iframe src="' . $playerUrl . '" class="video-player">'
});
```


text:
package com.huawei.esdk.fusionmanager.local.model.alarm;

import com.huawei.esdk.fusionmanager.local.model.FMSDKResponse;

/**
 * 修改SNMP连接信息返回信息。
 * <p>
 * @since eSDK Cloud V100R003C30
 */
public class ModifySnmpClinetResp extends FMSDKResponse
{

}


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Arch.CFX.Test.Aggregating
{
    [TestClass]
    public class NameHelperTest
    {
        [TestMethod]
        [TestCategory("Aggregating")]
        public void GetFullName_Test()
        {
            string fullname = Arch.CFramework.Aggregating.NameHelper.GetFullName("nameSpace", "name");
            Assert.AreEqual(fullname, "__nameSpace__name");
        }
    }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model common\models\TblAssetTestLaptopBag */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'inventory_id')->textInput() ?>

    <?= $form->field($model, 'empty_bag')->textInput() ?>

    <?= $form->field($model, 'test_strap')->textInput() ?>

    <?= $form->field($model, 'clean_bag_monthly')->textInput() ?>

    <?= $form->field($model, 'created_date')->widget(\yii\jui\DatePicker::classname(), [
    'language' => 'eng',
    'dateFormat' => 'yyyy-MM-dd',
]) ?>

    <?= $form->field($model, 'update_date')->widget(\yii\jui\DatePicker::classname(), [
    'language' => 'eng',
    'dateFormat' => 'yyyy-MM-dd',
]) ?>

    <?= $form->field($model, 'service_period')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'status')->textInput() ?>

    <?= $form->field($model, 'comment')->textInput(['maxlength' => true]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
#include <aws/elasticache/model/UnprocessedUpdateAction.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::Utils::Xml;
using namespace Aws::Utils;

namespace Aws
{
namespace ElastiCache
{
namespace Model
{

UnprocessedUpdateAction::UnprocessedUpdateAction() :
    m_replicationGroupIdHasBeenSet(false),
    m_cacheClusterIdHasBeenSet(false),
    m_serviceUpdateNameHasBeenSet(false),
    m_errorTypeHasBeenSet(false),
    m_errorMessageHasBeenSet(false)
{
}

UnprocessedUpdateAction::UnprocessedUpdateAction(const XmlNode& xmlNode) :
    m_replicationGroupIdHasBeenSet(false),
    m_cacheClusterIdHasBeenSet(false),
    m_serviceUpdateNameHasBeenSet(false),
    m_errorTypeHasBeenSet(false),
    m_errorMessageHasBeenSet(false)
{
  *this = xmlNode;
}

UnprocessedUpdateAction& UnprocessedUpdateAction::operator =(const XmlNode& xmlNode)
{
  XmlNode resultNode = xmlNode;

  if(!resultNode.IsNull())
  {
    XmlNode replicationGroupIdNode = resultNode.FirstChild("ReplicationGroupId");
    if(!replicationGroupIdNode.IsNull())
    {
      m_replicationGroupId = Aws::Utils::Xml::DecodeEscapedXmlText(replicationGroupIdNode.GetText());
      m_replicationGroupIdHasBeenSet = true;
    }
    XmlNode cacheClusterIdNode = resultNode.FirstChild("CacheClusterId");
    if(!cacheClusterIdNode.IsNull())
    {
      m_cacheClusterId = Aws::Utils::Xml::DecodeEscapedXmlText(cacheClusterIdNode.GetText());
      m_cacheClusterIdHasBeenSet = true;
    }
    XmlNode serviceUpdateNameNode = resultNode.FirstChild("ServiceUpdateName");
    if(!serviceUpdateNameNode.IsNull())
    {
      m_serviceUpdateName = Aws::Utils::Xml::DecodeEscapedXmlText(serviceUpdateNameNode.GetText());
      m_serviceUpdateNameHasBeenSet = true;
    }
    XmlNode errorTypeNode = resultNode.FirstChild("ErrorType");
    if(!errorTypeNode.IsNull())
    {
      m_errorType = Aws::Utils::Xml::DecodeEscapedXmlText(errorTypeNode.GetText());
      m_errorTypeHasBeenSet = true;
    }
    XmlNode errorMessageNode = resultNode.FirstChild("ErrorMessage");
    if(!errorMessageNode.IsNull())
    {
      m_errorMessage = Aws::Utils::Xml::DecodeEscapedXmlText(errorMessageNode.GetText());
      m_errorMessageHasBeenSet = true;
    }
  }

  return *this;
}

void UnprocessedUpdateAction::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
  if(m_replicationGroupIdHasBeenSet)
  {
      oStream << location << index << locationValue << ".ReplicationGroupId=" << StringUtils::URLEncode(m_replicationGroupId.c_str()) << "&";
  }

  if(m_cacheClusterIdHasBeenSet)
  {
      oStream << location << index << locationValue << ".CacheClusterId=" << StringUtils::URLEncode(m_cacheClusterId.c_str()) << "&";
  }

  if(m_serviceUpdateNameHasBeenSet)
  {
      oStream << location << index << locationValue << ".ServiceUpdateName=" << StringUtils::URLEncode(m_serviceUpdateName.c_str()) << "&";
  }

  if(m_errorTypeHasBeenSet)
  {
      oStream << location << index << locationValue << ".ErrorType=" << StringUtils::URLEncode(m_errorType.c_str()) << "&";
  }

  if(m_errorMessageHasBeenSet)
  {
      oStream << location << index << locationValue << ".ErrorMessage=" << StringUtils::URLEncode(m_errorMessage.c_str()) << "&";
  }

}

void UnprocessedUpdateAction::OutputToStream(Aws::OStream& oStream, const char* location) const
{
  if(m_replicationGroupIdHasBeenSet)
  {
      oStream << location << ".ReplicationGroupId=" << StringUtils::URLEncode(m_replicationGroupId.c_str()) << "&";
  }
  if(m_cacheClusterIdHasBeenSet)
  {
      oStream << location << ".CacheClusterId=" << StringUtils::URLEncode(m_cacheClusterId.c_str()) << "&";
  }
  if(m_serviceUpdateNameHasBeenSet)
  {
      oStream << location << ".ServiceUpdateName=" << StringUtils::URLEncode(m_serviceUpdateName.c_str()) << "&";
  }
  if(m_errorTypeHasBeenSet)
  {
      oStream << location << ".ErrorType=" << StringUtils::URLEncode(m_errorType.c_str()) << "&";
  }
  if(m_errorMessageHasBeenSet)
  {
      oStream << location << ".ErrorMessage=" << StringUtils::URLEncode(m_errorMessage.c_str()) << "&";
  }
}

} // namespace Model
} // namespace ElastiCache
} // namespace Aws