text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Indentation
{
    internal abstract partial class AbstractIndentationService<TSyntaxRoot>
        : AbstractIndentation<TSyntaxRoot>, IIndentationService
        where TSyntaxRoot : SyntaxNode, ICompilationUnitSyntax
    {
        public IndentationResult GetIndentation(
            ParsedDocument document, int lineNumber, IndentationOptions options, CancellationToken cancellationToken)
        {
            var indentStyle = options.IndentStyle;

            if (indentStyle == FormattingOptions2.IndentStyle.None)
            {
                // If there is no indent style, then do nothing.
                return new IndentationResult(basePosition: 0, offset: 0);
            }

            var indenter = GetIndenter(document, lineNumber, options, cancellationToken);

            if (indentStyle == FormattingOptions2.IndentStyle.Smart &&
                indenter.TryGetSmartTokenIndentation(out var indentationResult))
            {
                return indentationResult;
            }

            // If the indenter can't produce a valid result, just default to 0 as our indentation.
            return indenter.GetDesiredIndentation(indentStyle) ?? default;
        }

        private Indenter GetIndenter(ParsedDocument document, int lineNumber, IndentationOptions options, CancellationToken cancellationToken)
        {
            var syntaxFormatting = this.SyntaxFormatting;

            var lineToBeIndented = document.Text.Lines[lineNumber];

#if CODE_STYLE
            var baseIndentationRule = NoOpFormattingRule.Instance;
#else
            var formattingRuleFactory = document.SolutionServices.GetRequiredService<IHostDependentFormattingRuleFactoryService>();
            var baseIndentationRule = formattingRuleFactory.CreateRule(document, lineToBeIndented.Start);
#endif

            var formattingRules = ImmutableArray.Create(
                baseIndentationRule,
                this.GetSpecializedIndentationFormattingRule(options.IndentStyle)).AddRange(
                syntaxFormatting.GetDefaultFormattingRules());

            var smartTokenFormatter = CreateSmartTokenFormatter(
                (TSyntaxRoot)document.Root, document.Text, lineToBeIndented, options, baseIndentationRule);
            return new Indenter(this, document.SyntaxTree, formattingRules, options, lineToBeIndented, smartTokenFormatter, cancellationToken);
        }
    }
}


text:
package com.biglakesystems.scamp.requirejs;

import com.biglakesystems.scamp.spi.config.EvaluatorConfiguration;
import com.biglakesystems.scamp.spi.module.ModuleSupport;
import com.biglakesystems.scamp.spi.module.ResourceRegistry;

public class RequireJSModule extends ModuleSupport
{
    /**
     * Construct a {@link RequireJSModule} instance.
     */
    public RequireJSModule()
    {
        super();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void registerResources(final ResourceRegistry registry, final EvaluatorConfiguration configuration)
    {
        registry.registerLibrary(RequireJSLibrary.INSTANCE);
        registry.registerSourceLocator(RequireJSSourceLocator.INSTANCE);
    }
}

redpajama_set_name: RedPajamaGithub


text:
var HitEffect = cc.Sprite.extend({
    active:true,
    ctor:function () {
        this._super("#hit.png");
        this.setBlendFunc(cc.SRC_ALPHA, cc.ONE);
    },
    reset:function (x, y, rotation, scale) {
        this.attr({
	        x: x,
	        y: y,
	        rotation: rotation,
	        scale: scale
        });
        this.runAction(cc.scaleBy(0.3, 2, 2));
        this.runAction(cc.sequence(cc.fadeOut(0.3), cc.callFunc(this.destroy, this)));
    },
    destroy:function () {
        this.visible = false;
        this.active = false;
    }
});

HitEffect.getOrCreateHitEffect = function (x, y, rotation, scale) {
    var selChild = null;
    for (var j = 0; j < MW.CONTAINER.HITS.length; j++) {
        selChild = MW.CONTAINER.HITS[j];
        if (selChild.active == false) {
            selChild.visible = true;
            selChild.active = true;
            selChild.reset(x, y, rotation, scale);
            return selChild;
        }
    }
    selChild = HitEffect.create();
    selChild.reset(x, y, rotation, scale);
    return selChild;
};

HitEffect.create = function () {
    var hitEffect = new HitEffect();
    g_sharedGameLayer.addBulletHits(hitEffect, 9999);
    MW.CONTAINER.HITS.push(hitEffect);
    return hitEffect;
};

HitEffect.preSet = function () {
    var hitEffect = null;
    for (var i = 0; i < 10; i++) {
        hitEffect = HitEffect.create();
        hitEffect.setVisible(false);
        hitEffect.active = false;
    }
};


text:
NAME = WP4_DSL_Y2_review

default: ${NAME}.pdf

SWarch.pdf: SWarch.dot
	dot -Tpdf SWarch.dot > SWarch.pdf

${NAME}.pdf: ${NAME}.md template.tex SWarch.pdf
	pandoc -t beamer -H template.tex ${NAME}.md -o ${NAME}.pdf
#	pandoc -t beamer --variable classoption="aspectratio=1610" -H template.tex ${NAME}.md -o ${NAME}.pdf

${NAME}.tex: ${NAME}.md template.tex
	pandoc -t beamer -H template.tex ${NAME}.md -o ${NAME}.tex

${NAME}.html: ${NAME}.md
	pandoc --self-contained -S --latexmathml -t slidy ${NAME}.md -o ${NAME}.html

# Dependencies:
# * http://pandoc.org/ - a universal document converter
# * http://pandoc.org/demo/example9/producing-slide-shows-with-pandoc.html


text:
namespace caffe2 {

// This is Caffe's InnerProductOp, with a name that fits its purpose better.
template <class Context, class Engine = DefaultEngine>
class FullyConnectedOp final : public Operator<Context> {
 public:
  USE_OPERATOR_CONTEXT_FUNCTIONS;
  FullyConnectedOp(const OperatorDef& operator_def, Workspace* ws)
      : Operator<Context>(operator_def, ws),
        axis_(OperatorBase::GetSingleArgument<int32_t>("axis", 1)) {}
  ~FullyConnectedOp() {}

  template <
      typename T_X,
      typename T_W,
      typename T_B,
      typename T_Y,
      typename MATH>
  bool DoRunWithType() {
    const auto& X = Input(0);
    const auto& W = Input(1);
    const auto& b = Input(2);
    auto* Y = Output(0);
    CAFFE_ENFORCE(W.ndim() == 2, W.ndim());
    CAFFE_ENFORCE(b.ndim() == 1, b.ndim());
    // batch size
    const auto canonical_axis = X.canonical_axis_index(axis_);
    const auto M = X.size_to_dim(canonical_axis);
    const auto K = X.size_from_dim(canonical_axis);
    const int N = W.dim32(0);

    auto dimErrorString = [&]() {
      return MakeString(
          "Dimension mismatch: ",
          "X: ",
          X.dims(),
          ", W: ",
          W.dims(),
          ", b: ",
          b.dims(),
          ", axis: ",
          axis_,
          ", M: ",
          M,
          ", N: ",
          N,
          ", K: ",
          K);
    };

    // Error checking
    CAFFE_ENFORCE(M == X.size() / K, dimErrorString());
    CAFFE_ENFORCE(K == W.size() / W.dim32(0), dimErrorString());
    CAFFE_ENFORCE(N == b.dim32(0), dimErrorString());
    CAFFE_ENFORCE(N == b.size(), dimErrorString());

    Y_shape_cache_ = X.dims();
    // This is an invariant of canonical_axis, so we can DCHECK.
    DCHECK_LE(canonical_axis + 1, Y_shape_cache_.size());
    Y_shape_cache_.resize(canonical_axis + 1);
    Y_shape_cache_[canonical_axis] = N;
    Y->Resize(Y_shape_cache_);
    CAFFE_ENFORCE(M * N == Y->size(), dimErrorString());

    // W * x
    math::Gemm<T_X, Context, Engine>(
        CblasNoTrans,
        CblasTrans,
        M,
        N,
        K,
        1,
        X.template data<T_X>(),
        W.template data<T_W>(),
        0,
        Y->template mutable_data<T_Y>(),
        &context_);
    // Add bias term
    if (bias_multiplier_.size() != M) {
      // If the helper bias multiplier is not M, reshape and fill it with one.
      bias_multiplier_.Resize(M);
      math::Set<T_B, Context>(
          M,
          convert::To<float, T_B>(1),
          bias_multiplier_.template mutable_data<T_B>(),
          &context_);
    }
    math::Gemm<T_B, Context, Engine>(
        CblasNoTrans,
        CblasNoTrans,
        M,
        N,
        1,
        1,
        bias_multiplier_.template data<T_B>(),
        b.template data<T_B>(),
        1,
        Y->template mutable_data<T_Y>(),
        &context_);
    return true;
  }

  bool RunOnDevice() override {
    return DoRunWithType<
        float, // X
        float, // W
        float, // B
        float, // Y
        float>(); // Math
  }

 protected:
  size_t axis_{1};
  // A local vector to cache the output shape so we don't need to recreate
  // a vector object every time we run Run().
  vector<TIndex> Y_shape_cache_;
  Tensor<Context> bias_multiplier_;
};

template <class Context, class Engine = DefaultEngine>
class FullyConnectedGradientOp : public Operator<Context> {
 public:
  USE_OPERATOR_CONTEXT_FUNCTIONS;
  FullyConnectedGradientOp(const OperatorDef& operator_def, Workspace* ws)
      : Operator<Context>(operator_def, ws),
        axis_(OperatorBase::GetSingleArgument<int32_t>("axis", 1)) {}
  ~FullyConnectedGradientOp() {}

  template <
      typename T_X,
      typename T_W,
      typename T_DY,
      typename T_B,
      typename T_DX,
      typename T_DW,
      typename T_DB,
      typename MATH>
  bool DoRunWithType() {
    const auto& X = Input(0);
    const auto& W = Input(1);
    const auto& dY = Input(2);
    CAFFE_ENFORCE(W.ndim() == 2, W.ndim());
    // batch size
    const auto canonical_axis = X.canonical_axis_index(axis_);
    const int M = X.size_to_dim(canonical_axis);
    const int K = X.size_from_dim(canonical_axis);
    const int N = W.dim32(0);
    CAFFE_ENFORCE(M * K == X.size());
    CAFFE_ENFORCE(K * N == W.size());

    auto* dW = Output(0);
    auto* db = Output(1);
    dW->ResizeLike(W);
    db->Resize(N);

    // Compute dW
    math::Gemm<T_DY, Context, Engine>(
        CblasTrans,
        CblasNoTrans,
        N,
        K,
        M,
        convert::To<float, MATH>(1),
        dY.template data<T_DY>(),
        X.template data<T_X>(),
        convert::To<float, MATH>(0),
        dW->template mutable_data<T_DW>(),
        &context_);
    if (bias_multiplier_.size() != M) {
      // If the helper bias multiplier is not M, reshape and fill it
      // with one.
      bias_multiplier_.Resize(M);
      math::Set<T_B, Context>(
          M,
          convert::To<float, T_B>(1),
          bias_multiplier_.template mutable_data<T_B>(),
          &context_);
    }
    // Compute dB
    math::Gemv<T_DY, Context>(
        CblasTrans,
        M,
        N,
        convert::To<float, MATH>(1),
        dY.template data<T_DY>(),
        bias_multiplier_.template data<T_B>(),
        convert::To<float, MATH>(0),
        db->template mutable_data<T_DB>(),
        &context_);

    // Compute dX
    if (OutputSize() == 3) {
      auto* dX = Output(2);
      dX->ResizeLike(X);
      math::Gemm<T_DX, Context, Engine>(
          CblasNoTrans,
          CblasNoTrans,
          M,
          K,
          N,
          convert::To<float, MATH>(1),
          dY.template data<T_DY>(),
          W.template data<T_W>(),
          convert::To<float, MATH>(0),
          dX->template mutable_data<T_DX>(),
          &context_);
    }
    return true;
  }

  bool RunOnDevice() override {
    return DoRunWithType<
        float, //  X
        float, //  W
        float, // dY
        float, //  B
        float, // dX
        float, // dW
        float, // dB
        float>(); // Math
  }

 protected:
  size_t axis_{1};
  Tensor<Context> bias_multiplier_;
};

} // namespace caffe2

#endif // CAFFE2_OPERATORS_FULLY_CONNECTED_OP_H_


text:
<?php

namespace Cubalider\Component\Money\Model;

/**
 * @author Yosmany Garcia <yosmanyga@gmail.com>
 */
class Money
{
    /**
     * @var float
     */
    private $amount;

    /**
     * @var Currency
     */
    private $currency;

    /**
     * @param float $amount
     * @param Currency $currency
     */
    function __construct($amount, Currency $currency)
    {
        $this->amount = $amount;
        $this->currency = $currency;
    }

    /**
     * @return float
     */
    public function getAmount()
    {
        return $this->amount;
    }

    /**
     * @return Currency
     */
    public function getCurrency()
    {
        return $this->currency;
    }
}


text:
/**
 * Created by SamChow on 16/4/5.
 */
import {
    LOGIN,
    LOGOUT
} from '../mutation-types.js'

const state = {
    userid: '',
    islogin: false,
    username: '',
    usermessages: ''
};

const mutations = {
    [LOGIN](state, userid, username){
        state.userid = userid;
        state.username = username;
        state.islogin = true;
    },
    [LOGOUT](state){
        state.userid = '';
        state.islogin = false;
        state.username= '';
    }
}

export default {
    state,
    mutations
}


text:
const path = require("path");

module.exports = {
  contentBase: path.resolve(__dirname, 'dist'),
  compress: true,
  port: 9999,
  stats: 'errors-only',
  open: true
};


text:
layout: post
title: Unity 3D Terrain from Blender ANT Landscape Generator
date: 2012-12-20 03:50:00
tags:
- Unity
- 3D
- Blender
- terrain
---

Terrains in Unity may be generated using Blender's ANT Landscape Generator.

Install ANT Landscape Generator if not already in Blender.

In Blender, select *File* » *User Preferences...*:

Under the *Addons* group, select the *Install Addon...* button.

Navigate to the *add_mesh_ant_landscape.py* script, and with the script selected press the *Install Addon...* button.

Once installed, enable the add-on by placing a check in the *Add Mesh: ANT Landscape* group.

With a new scene ready in Blender, the default camera and lamp may be removed. Only the terrain is needed for import to Unity.

Create a landscape in Blender by selecting *Add* » *Mesh* » *Landscape*.

Blender will generate a 3D mesh of a landscape.

Landscape parameters may be tuned to different terrains.

With the landscape selected in Blender, export the mesh to a Wavefront OBJ file by selecting *File* » *Export* » *Wavefront (.obj)*.

In Unity, create a new terrain by selecting *Terrain* » *Create Terrain*

Import the landscape Wavefront OBJ file.

Drag the default mesh from the terrain OBJ file, and drop it on the Unity terrain.

This will result in the mesh as a child of the Terrain hierarchy.

To apply to the imported landscape mesh to the terrain object in Unity, use the Object2Terrain.js script.

Under the Unity project assets, create an Editor folder, and place the Object2Terrain.js script in the folder.

Now with the default mesh of the terrain selected in the hierarchy, select *Terrain* » *Object to Terrain*.

Unity terrain object now reflects the imported landscape mesh from Blender.

Children of the Unity may now be deleted from the terrain object.

### Scripts

[Blender ANT Landscape Generator](https://gist.github.com/jasonsturges/01ed26d36ffef78a53d9)

```py
# ##### BEGIN GPL LICENSE BLOCK #####
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####

bl_info = {
    "name": "ANT Landscape",
    "author": "Jimmy Hazevoet",
    "version": (0,1,2),
    "blender": (2, 6, 1),
    "location": "View3D > Add > Mesh",
    "description": "Add a landscape primitive",
    "warning": "", # used for warning icon and text in addons panel
    "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.6/Py/"\
        "Scripts/Add_Mesh/ANT_Landscape",
    "tracker_url": "https://projects.blender.org/tracker/index.php?"\
        "func=detail&aid=23130",
    "category": "Add Mesh"}

"""
Another Noise Tool: Landscape mesh generator

MESH OPTIONS:
Mesh update:     Turn this on for interactive mesh update.
Sphere:          Generate sphere or a grid mesh. (Turn height falloff off for sphere mesh)
Smooth:          Generate smooth shaded mesh.
Subdivision:     Number of mesh subdivisions, higher numbers gives more detail but also slows down the script.
Mesh size:       X,Y size of the grid mesh (in blender units).

NOISE OPTIONS: ( Most of these options are the same as in blender textures. )
Random seed:     Use this to randomise the origin of the noise function.
Noise size:      Size of the noise.
Noise type:      Available noise types: multiFractal, ridgedMFractal, hybridMFractal, heteroTerrain, Turbulence, Distorted Noise, Cellnoise, Shattered_hTerrain, Marble
Noise basis:     Blender, Perlin, NewPerlin, Voronoi_F1, Voronoi_F2, Voronoi_F3, Voronoi_F4, Voronoi_F2-F1, Voronoi Crackle, Cellnoise
VLNoise basis:   Blender, Perlin, NewPerlin, Voronoi_F1, Voronoi_F2, Voronoi_F3, Voronoi_F4, Voronoi_F2-F1, Voronoi Crackle, Cellnoise
Distortion:      Distortion amount.
Hard:            Hard/Soft turbulence noise.
Depth:           Noise depth, number of frequencies in the fBm.
Dimension:       Musgrave: Fractal dimension of the roughest areas.
Lacunarity:      Musgrave: Gap between successive frequencies.
Offset:          Musgrave: Raises the terrain from sea level.
Gain:            Musgrave: Scale factor.
Marble Bias:     Sin, Tri, Saw
Marble Sharpnes: Soft, Sharp, Sharper
Marble Shape:    Shape of the marble function: Default, Ring, Swirl, X, Y

HEIGHT OPTIONS:
Invert:          Invert terrain height.
Height:          Scale terrain height.
Offset:          Terrain height offset.
Falloff:         Terrain height falloff: Type 1, Type 2, X, Y
Sealevel:        Flattens terrain below sealevel.
Platlevel:       Flattens terrain above plateau level.
Strata:          Strata amount, number of strata/terrace layers.
Strata type:     Strata types, Smooth, Sharp-sub, Sharp-add
"""

# import modules
import bpy
from bpy.props import *
from mathutils import *
from mathutils.noise import *
from math import *

# Create a new mesh (object) from verts/edges/faces.
# verts/edges/faces ... List of vertices/edges/faces for the
#                    new mesh (as used in from_pydata).
# name ... Name of the new mesh (& object).
def create_mesh_object(context, verts, edges, faces, name):
    # Create new mesh
    mesh = bpy.data.meshes.new(name)

    # Make a mesh from a list of verts/edges/faces.
    mesh.from_pydata(verts, edges, faces)

    # Update mesh geometry after adding stuff.
    mesh.update()

    from bpy_extras import object_utils
    return object_utils.object_data_add(context, mesh, operator=None)

# A very simple "bridge" tool.
# Connects two equally long vertex rows with faces.
# Returns a list of the new faces (list of  lists)
#
# vertIdx1 ... First vertex list (list of vertex indices).
# vertIdx2 ... Second vertex list (list of vertex indices).
# closed ... Creates a loop (first & last are closed).
# flipped ... Invert the normal of the face(s).
#
# Note: You can set vertIdx1 to a single vertex index to create
#    a fan/star of faces.
# Note: If both vertex idx list are the same length they have
#    to have at least 2 vertices.
def createFaces(vertIdx1, vertIdx2, closed=False, flipped=False):
    faces = []

    if not vertIdx1 or not vertIdx2:
        return None

    if len(vertIdx1) < 2 and len(vertIdx2) < 2:         return None     fan = False     if (len(vertIdx1) != len(vertIdx2)):         if (len(vertIdx1) == 1 and len(vertIdx2) > 1):
            fan = True
        else:
            return None

    total = len(vertIdx2)

    if closed:
        # Bridge the start with the end.
        if flipped:
            face = [
                vertIdx1[0],
                vertIdx2[0],
                vertIdx2[total - 1]]
            if not fan:
                face.append(vertIdx1[total - 1])
            faces.append(face)

        else:
            face = [vertIdx2[0], vertIdx1[0]]
            if not fan:
                face.append(vertIdx1[total - 1])
            face.append(vertIdx2[total - 1])
            faces.append(face)

    # Bridge the rest of the faces.
    for num in range(total - 1):
        if flipped:
            if fan:
                face = [vertIdx2[num], vertIdx1[0], vertIdx2[num + 1]]
            else:
                face = [vertIdx2[num], vertIdx1[num],
                    vertIdx1[num + 1], vertIdx2[num + 1]]
            faces.append(face)
        else:
            if fan:
                face = [vertIdx1[0], vertIdx2[num], vertIdx2[num + 1]]
            else:
                face = [vertIdx1[num], vertIdx2[num],
                    vertIdx2[num + 1], vertIdx1[num + 1]]
            faces.append(face)

    return faces

###------------------------------------------------------------
###------------------------------------------------------------
# some functions for marble_noise
def sin_bias(a):
    return 0.5 + 0.5 * sin(a)

def tri_bias(a):
    b = 2 * pi
    a = 1 - 2 * abs(floor((a * (1/b))+0.5) - (a*(1/b)))
    return a

def saw_bias(a):
    b = 2 * pi
    n = int(a/b)
    a -= n * b
    if a < 0: a += b
    return a / b

def soft(a):
    return a

def sharp(a):
    return a**0.5

def sharper(a):
    return sharp(sharp(a))

def shapes(x,y,shape=0):
    if shape == 1:
        # ring
        x = x*2
        y = y*2
        s = (-cos(x**2+y**2)/(x**2+y**2+0.5))
    elif shape == 2:
        # swirl
        x = x*2
        y = y*2
        s = (( x*sin( x*x+y*y ) + y*cos( x*x+y*y ) ) / (x**2+y**2+0.5))
    elif shape == 3:
        # bumps
        x = x*2
        y = y*2
        s = ((cos( x*pi ) + cos( y*pi ))-0.5)
    elif shape == 4:
        # y grad.
        s = (y*pi)
    elif shape == 5:
        # x grad.
        s = (x*pi)
    else:
        # marble
        s = ((x+y)*5)
    return s

# marble_noise
def marble_noise(x,y,z, origin, size, shape, bias, sharpnes, turb, depth, hard, basis ):
    x = x / size
    y = y / size
    z = z / size
    s = shapes(x,y,shape)

    x += origin[0]
    y += origin[1]
    z += origin[2]
    value = s + turb * turbulence_vector((x,y,z), depth, hard, basis )[0]

    if bias == 1:
        value = tri_bias( value )
    elif bias == 2:
        value = saw_bias( value )
    else:
        value = sin_bias( value )

    if sharpnes == 1:
        value = sharp( value )
    elif sharpnes == 2:
        value = sharper( value )
    else:
        value = soft( value )

    return value

###------------------------------------------------------------
# custom noise types

# shattered_hterrain:
def shattered_hterrain( x,y,z, H, lacunarity, octaves, offset, distort, basis ):
    d = ( turbulence_vector( ( x, y, z ), 6, 0, 0 )[0] * 0.5 + 0.5 )*distort*0.5
    t1 = ( turbulence_vector( ( x+d, y+d, z ), 0, 0, 7 )[0] + 0.5 )
    t2 = ( hetero_terrain(( x*2, y*2, z*2 ), H, lacunarity, octaves, offset, basis )*0.5 )
    return (( t1*t2 )+t2*0.5) * 0.5

# strata_hterrain
def strata_hterrain( x,y,z, H, lacunarity, octaves, offset, distort, basis ):
    value = hetero_terrain(( x, y, z ), H, lacunarity, octaves, offset, basis )*0.5
    steps = ( sin( value*(distort*5)*pi ) * ( 0.1/(distort*5)*pi ) )
    return ( value * (1.0-0.5) + steps*0.5 )

###------------------------------------------------------------
# landscape_gen
def landscape_gen(x,y,z,falloffsize,options=[0,1.0,1, 0,0,1.0,0,6,1.0,2.0,1.0,2.0,0,0,0, 1.0,0.0,1,0.0,1.0,0,0,0]):

    # options
    rseed    = options[0]
    nsize    = options[1]
    ntype      = int( options[2][0] )
    nbasis     = int( options[3][0] )
    vlbasis    = int( options[4][0] )
    distortion = options[5]
    hardnoise  = options[6]
    depth      = options[7]
    dimension  = options[8]
    lacunarity = options[9]
    offset     = options[10]
    gain       = options[11]
    marblebias     = int( options[12][0] )
    marblesharpnes = int( options[13][0] )
    marbleshape    = int( options[14][0] )
    invert       = options[15]
    height       = options[16]
    heightoffset = options[17]
    falloff      = int( options[18][0] )
    sealevel     = options[19]
    platlevel    = options[20]
    strata       = options[21]
    stratatype   = options[22]
    sphere       = options[23]

    # origin
    if rseed == 0:
        origin = 0.0,0.0,0.0
        origin_x = 0.0
        origin_y = 0.0
        origin_z = 0.0
    else:
        # randomise origin
        seed_set( rseed )
        origin = random_unit_vector()
        origin_x = ( 0.5 - origin[0] ) * 1000.0
        origin_y = ( 0.5 - origin[1] ) * 1000.0
        origin_z = ( 0.5 - origin[2] ) * 1000.0

    # adjust noise size and origin
    ncoords = ( x / nsize + origin_x, y / nsize + origin_y, z / nsize + origin_z )

    # noise basis type's
    if nbasis == 9: nbasis = 14  # to get cellnoise basis you must set 14 instead of 9
    if vlbasis ==9: vlbasis = 14
    # noise type's
    if ntype == 0:   value = multi_fractal(        ncoords, dimension, lacunarity, depth, nbasis ) * 0.5
    elif ntype == 1: value = ridged_multi_fractal( ncoords, dimension, lacunarity, depth, offset, gain, nbasis ) * 0.5
    elif ntype == 2: value = hybrid_multi_fractal( ncoords, dimension, lacunarity, depth, offset, gain, nbasis ) * 0.5
    elif ntype == 3: value = hetero_terrain(       ncoords, dimension, lacunarity, depth, offset, nbasis ) * 0.25
    elif ntype == 4: value = fractal(              ncoords, dimension, lacunarity, depth, nbasis )
    elif ntype == 5: value = turbulence_vector(    ncoords, depth, hardnoise, nbasis )[0]
    elif ntype == 6: value = variable_lacunarity(            ncoords, distortion, nbasis, vlbasis ) + 0.5
    elif ntype == 7: value = marble_noise( x*2.0/falloffsize,y*2.0/falloffsize,z*2/falloffsize, origin, nsize, marbleshape, marblebias, marblesharpnes, distortion, depth, hardnoise, nbasis )
    elif ntype == 8: value = shattered_hterrain( ncoords[0], ncoords[1], ncoords[2], dimension, lacunarity, depth, offset, distortion, nbasis )
    elif ntype == 9: value = strata_hterrain( ncoords[0], ncoords[1], ncoords[2], dimension, lacunarity, depth, offset, distortion, nbasis )
    else:
        value = 0.0

    # adjust height
    if invert !=0:
        value = (1-value) * height + heightoffset
    else:
        value = value * height + heightoffset

    # edge falloff
    if sphere == 0: # no edge falloff if spherical
        if falloff != 0:
            fallofftypes = [ 0, sqrt((x*x)**2+(y*y)**2), sqrt(x*x+y*y), sqrt(y*y), sqrt(x*x) ]
            dist = fallofftypes[ falloff]
            if falloff ==1:
                radius = (falloffsize/2)**2
            else:
                radius = falloffsize/2
            value = value - sealevel
            if( dist < radius ):
                dist = dist / radius
                dist = ( (dist) * (dist) * ( 3-2*(dist) ) )
                value = ( value - value * dist ) + sealevel
            else:
                value = sealevel

    # strata / terrace / layered
    if stratatype !='0':
        strata = strata / height
    if stratatype == '1':
        strata *= 2
        steps = ( sin( value*strata*pi ) * ( 0.1/strata*pi ) )
        value = ( value * (1.0-0.5) + steps*0.5 ) * 2.0
    elif stratatype == '2':
        steps = -abs( sin( value*(strata)*pi ) * ( 0.1/(strata)*pi ) )
        value =( value * (1.0-0.5) + steps*0.5 ) * 2.0
    elif stratatype == '3':
        steps = abs( sin( value*(strata)*pi ) * ( 0.1/(strata)*pi ) )
        value =( value * (1.0-0.5) + steps*0.5 ) * 2.0
    else:
        value = value

    # clamp height
    if ( value < sealevel ): value = sealevel     if ( value > platlevel ): value = platlevel

    return value

# generate grid
def grid_gen( sub_d, size_me, options ):

    verts = []
    faces = []
    edgeloop_prev = []

    delta = size_me / float(sub_d - 1)
    start = -(size_me / 2.0)

    for row_x in range(sub_d):
        edgeloop_cur = []
        x = start + row_x * delta
        for row_y in range(sub_d):
            y = start + row_y * delta
            z = landscape_gen(x,y,0.0,size_me,options)

            edgeloop_cur.append(len(verts))
            verts.append((x,y,z))

        if len(edgeloop_prev) > 0:
            faces_row = createFaces(edgeloop_prev, edgeloop_cur)
            faces.extend(faces_row)

        edgeloop_prev = edgeloop_cur

    return verts, faces

# generate sphere
def sphere_gen( sub_d, size_me, options ):

    verts = []
    faces = []
    edgeloop_prev = []

    for row_x in range(sub_d):
        edgeloop_cur = []
        for row_y in range(sub_d):
            u = sin(row_y*pi*2/(sub_d-1)) * cos(-pi/2+row_x*pi/(sub_d-1)) * size_me/2
            v = cos(row_y*pi*2/(sub_d-1)) * cos(-pi/2+row_x*pi/(sub_d-1)) * size_me/2
            w = sin(-pi/2+row_x*pi/(sub_d-1)) * size_me/2
            h = landscape_gen(u,v,w,size_me,options) / size_me
            u,v,w = u+u*h, v+v*h, w+w*h

            edgeloop_cur.append(len(verts))
            verts.append((u, v, w))

        if len(edgeloop_prev) > 0:
            faces_row = createFaces(edgeloop_prev, edgeloop_cur)
            faces.extend(faces_row)

        edgeloop_prev = edgeloop_cur

    return verts, faces

###------------------------------------------------------------
# Add landscape
class landscape_add(bpy.types.Operator):
    """Add a landscape mesh"""
    bl_idname = "mesh.landscape_add"
    bl_label = "Landscape"
    bl_options = {'REGISTER', 'UNDO', 'PRESET'}
    bl_description = "Add landscape mesh"

    # properties
    AutoUpdate = BoolProperty(name="Mesh update",
                default=True,
                description="Update mesh")

    SphereMesh = BoolProperty(name="Sphere",
                default=False,
                description="Generate Sphere mesh")

    SmoothMesh = BoolProperty(name="Smooth",
                default=True,
                description="Shade smooth")

    Subdivision = IntProperty(name="Subdivisions",
                min=4,
                max=6400,
                default=64,
                description="Mesh x y subdivisions")

    MeshSize = FloatProperty(name="Mesh Size",
                min=0.01,
                max=100000.0,
                default=2.0,
                description="Mesh size")

    RandomSeed = IntProperty(name="Random Seed",
                min=0,
                max=9999,
                default=0,
                description="Randomize noise origin")

    NoiseSize = FloatProperty(name="Noise Size",
                min=0.01,
                max=10000.0,
                default=1.0,
                description="Noise size")

    NoiseTypes = [
                ("0","multiFractal","multiFractal"),
                ("1","ridgedMFractal","ridgedMFractal"),
                ("2","hybridMFractal","hybridMFractal"),
                ("3","heteroTerrain","heteroTerrain"),
                ("4","fBm","fBm"),
                ("5","Turbulence","Turbulence"),
                ("6","Distorted Noise","Distorted Noise"),
                ("7","Marble","Marble"),
                ("8","Shattered_hTerrain","Shattered_hTerrain"),
                ("9","Strata_hTerrain","Strata_hTerrain")]

    NoiseType = EnumProperty(name="Type",
                description="Noise type",
                items=NoiseTypes)

    BasisTypes = [
                ("0","Blender","Blender"),
                ("1","Perlin","Perlin"),
                ("2","NewPerlin","NewPerlin"),
                ("3","Voronoi_F1","Voronoi_F1"),
                ("4","Voronoi_F2","Voronoi_F2"),
                ("5","Voronoi_F3","Voronoi_F3"),
                ("6","Voronoi_F4","Voronoi_F4"),
                ("7","Voronoi_F2-F1","Voronoi_F2-F1"),
                ("8","Voronoi Crackle","Voronoi Crackle"),
                ("9","Cellnoise","Cellnoise")]
    BasisType = EnumProperty(name="Basis",
                description="Noise basis",
                items=BasisTypes)

    VLBasisTypes = [
                ("0","Blender","Blender"),
                ("1","Perlin","Perlin"),
                ("2","NewPerlin","NewPerlin"),
                ("3","Voronoi_F1","Voronoi_F1"),
                ("4","Voronoi_F2","Voronoi_F2"),
                ("5","Voronoi_F3","Voronoi_F3"),
                ("6","Voronoi_F4","Voronoi_F4"),
                ("7","Voronoi_F2-F1","Voronoi_F2-F1"),
                ("8","Voronoi Crackle","Voronoi Crackle"),
                ("9","Cellnoise","Cellnoise")]
    VLBasisType = EnumProperty(name="VLBasis",
                description="VLNoise basis",
                items=VLBasisTypes)

    Distortion = FloatProperty(name="Distortion",
                min=0.01,
                max=1000.0,
                default=1.0,
                description="Distortion amount")

    HardNoise = BoolProperty(name="Hard",
                default=True,
                description="Hard noise")

    NoiseDepth = IntProperty(name="Depth",
                min=1,
                max=16,
                default=6,
                description="Noise Depth - number of frequencies in the fBm")

    mDimension = FloatProperty(name="Dimension",
                min=0.01,
                max=2.0,
                default=1.0,
                description="H - fractal dimension of the roughest areas")

    mLacunarity = FloatProperty(name="Lacunarity",
                min=0.01,
                max=6.0,
                default=2.0,
                description="Lacunarity - gap between successive frequencies")

    mOffset = FloatProperty(name="Offset",
                min=0.01,
                max=6.0,
                default=1.0,
                description="Offset - raises the terrain from sea level")

    mGain = FloatProperty(name="Gain",
                min=0.01,
                max=6.0,
                default=1.0,
                description="Gain - scale factor")

    BiasTypes = [
                ("0","Sin","Sin"),
                ("1","Tri","Tri"),
                ("2","Saw","Saw")]
    MarbleBias = EnumProperty(name="Bias",
                description="Marble bias",
                items=BiasTypes)

    SharpTypes = [
                ("0","Soft","Soft"),
                ("1","Sharp","Sharp"),
                ("2","Sharper","Sharper")]
    MarbleSharp = EnumProperty(name="Sharp",
                description="Marble sharp",
                items=SharpTypes)

    ShapeTypes = [
                ("0","Default","Default"),
                ("1","Ring","Ring"),
                ("2","Swirl","Swirl"),
                ("3","Bump","Bump"),
                ("4","Y","Y"),
                ("5","X","X")]
    MarbleShape = EnumProperty(name="Shape",
                description="Marble shape",
                items=ShapeTypes)

    Invert = BoolProperty(name="Invert",
                default=False,
                description="Invert noise input")

    Height = FloatProperty(name="Height",
                min=0.01,
                max=10000.0,
                default=0.5,
                description="Height scale")

    Offset = FloatProperty(name="Offset",
                min=-10000.0,
                max=10000.0,
                default=0.0,
                description="Height offset")

    fallTypes = [
                ("0","None","None"),
                ("1","Type 1","Type 1"),
                ("2","Type 2","Type 2"),
                ("3","Y","Y"),
                ("4","X","X")]
    Falloff = EnumProperty(name="Falloff",
                description="Edge falloff",
                default="1",
                items=fallTypes)

    Sealevel = FloatProperty(name="Sealevel",
                min=-10000.0,
                max=10000.0,
                default=0.0,
                description="Sealevel")

    Plateaulevel = FloatProperty(name="Plateau",
                min=-10000.0,
                max=10000.0,
                default=1.0,
                description="Plateau level")

    Strata = FloatProperty(name="Strata",
                min=0.01,
                max=1000.0,
                default=3.0,
                description="Strata amount")

    StrataTypes = [
                ("0","None","None"),
                ("1","Type 1","Type 1"),
                ("2","Type 2","Type 2"),
                ("3","Type 3","Type 3")]
    StrataType = EnumProperty(name="Strata",
                description="Strata type",
                default="0",
                items=StrataTypes)

    ###------------------------------------------------------------
    # Draw
    def draw(self, context):
        layout = self.layout

        box = layout.box()
        box.prop(self, 'AutoUpdate')
        box.prop(self, 'SphereMesh')
        box.prop(self, 'SmoothMesh')
        box.prop(self, 'Subdivision')
        box.prop(self, 'MeshSize')

        box = layout.box()
        box.prop(self, 'NoiseType')
        if self.NoiseType != '7':
            box.prop(self, 'BasisType')
        box.prop(self, 'RandomSeed')
        box.prop(self, 'NoiseSize')
        if self.NoiseType == '0':
            box.prop(self, 'NoiseDepth')
            box.prop(self, 'mDimension')
            box.prop(self, 'mLacunarity')
        elif self.NoiseType == '1':
            box.prop(self, 'NoiseDepth')
            box.prop(self, 'mDimension')
            box.prop(self, 'mLacunarity')
            box.prop(self, 'mOffset')
            box.prop(self, 'mGain')
        elif self.NoiseType == '2':
            box.prop(self, 'NoiseDepth')
            box.prop(self, 'mDimension')
            box.prop(self, 'mLacunarity')
            box.prop(self, 'mOffset')
            box.prop(self, 'mGain')
        elif self.NoiseType == '3':
            box.prop(self, 'NoiseDepth')
            box.prop(self, 'mDimension')
            box.prop(self, 'mLacunarity')
            box.prop(self, 'mOffset')
        elif self.NoiseType == '4':
            box.prop(self, 'NoiseDepth')
            box.prop(self, 'mDimension')
            box.prop(self, 'mLacunarity')
        elif self.NoiseType == '5':
            box.prop(self, 'NoiseDepth')
            box.prop(self, 'HardNoise')
        elif self.NoiseType == '6':
            box.prop(self, 'VLBasisType')
            box.prop(self, 'Distortion')
        elif self.NoiseType == '7':
            box.prop(self, 'MarbleShape')
            box.prop(self, 'MarbleBias')
            box.prop(self, 'MarbleSharp')
            box.prop(self, 'Distortion')
            box.prop(self, 'NoiseDepth')
            box.prop(self, 'HardNoise')
        elif self.NoiseType == '8':
            box.prop(self, 'NoiseDepth')
            box.prop(self, 'mDimension')
            box.prop(self, 'mLacunarity')
            box.prop(self, 'mOffset')
            box.prop(self, 'Distortion')
        elif self.NoiseType == '9':
            box.prop(self, 'NoiseDepth')
            box.prop(self, 'mDimension')
            box.prop(self, 'mLacunarity')
            box.prop(self, 'mOffset')
            box.prop(self, 'Distortion')

        box = layout.box()
        box.prop(self, 'Invert')
        box.prop(self, 'Height')
        box.prop(self, 'Offset')
        box.prop(self, 'Plateaulevel')
        box.prop(self, 'Sealevel')
        if self.SphereMesh == False:
            box.prop(self, 'Falloff')
        box.prop(self, 'StrataType')
        if self.StrataType != '0':
            box.prop(self, 'Strata')

    ###------------------------------------------------------------
    # Execute
    def execute(self, context):

        #mesh update
        if self.AutoUpdate != 0:

            # turn off undo
            undo = bpy.context.user_preferences.edit.use_global_undo
            bpy.context.user_preferences.edit.use_global_undo = False

            # deselect all objects when in object mode
            if bpy.ops.object.select_all.poll():
                bpy.ops.object.select_all(action='DESELECT')

            # options
            options = [
                self.RandomSeed,    #0
                self.NoiseSize,     #1
                self.NoiseType,     #2
                self.BasisType,     #3
                self.VLBasisType,   #4
                self.Distortion,    #5
                self.HardNoise,     #6
                self.NoiseDepth,    #7
                self.mDimension,    #8
                self.mLacunarity,   #9
                self.mOffset,       #10
                self.mGain,         #11
                self.MarbleBias,    #12
                self.MarbleSharp,   #13
                self.MarbleShape,   #14
                self.Invert,        #15
                self.Height,        #16
                self.Offset,        #17
                self.Falloff,       #18
                self.Sealevel,      #19
                self.Plateaulevel,  #20
                self.Strata,        #21
                self.StrataType,    #22
                self.SphereMesh     #23
                ]

            # Main function
            if self.SphereMesh !=0:
                # sphere
                verts, faces = sphere_gen( self.Subdivision, self.MeshSize, options )
            else:
                # grid
                verts, faces = grid_gen( self.Subdivision, self.MeshSize, options )

            # create mesh object
            obj = create_mesh_object(context, verts, [], faces, "Landscape")
            bpy.ops.object.mode_set(mode='EDIT')
            bpy.ops.mesh.normals_make_consistent(inside=False)
            bpy.ops.object.mode_set(mode='OBJECT')
            # sphere, remove doubles
            if self.SphereMesh !=0:
                bpy.ops.object.mode_set(mode='EDIT')
                bpy.ops.mesh.remove_doubles(mergedist=0.0001)
                bpy.ops.object.mode_set(mode='OBJECT')

            # Shade smooth
            if self.SmoothMesh !=0:
                if bpy.ops.object.shade_smooth.poll():
                    bpy.ops.object.shade_smooth()
                else: # edit mode
                    bpy.ops.mesh.faces_shade_smooth()

            # restore pre operator undo state
            bpy.context.user_preferences.edit.use_global_undo = undo

            return {'FINISHED'}
        else:
            return {'PASS_THROUGH'}

###------------------------------------------------------------
# Register

    # Define "Landscape" menu
def menu_func_landscape(self, context):
    self.layout.operator(landscape_add.bl_idname, text="Landscape", icon="PLUGIN")

def register():
    bpy.utils.register_module(__name__)

    bpy.types.INFO_MT_mesh_add.append(menu_func_landscape)

def unregister():
    bpy.utils.unregister_module(__name__)

    bpy.types.INFO_MT_mesh_add.remove(menu_func_landscape)

if __name__ == "__main__":
    register()
```

[Unity Object to Terrain](https://gist.github.com/jasonsturges/1f1c8df23aad35aa8236)

```js
@MenuItem ("Terrain/Object to Terrain")

static function Object2Terrain () {
	// See if a valid object is selected
	var obj = Selection.activeObject as GameObject;
	if (obj == null) {
		EditorUtility.DisplayDialog("No object selected", "Please select an object.", "Cancel");
		return;
	}
	if (obj.GetComponent(MeshFilter) == null) {
		EditorUtility.DisplayDialog("No mesh selected", "Please select an object with a mesh.", "Cancel");
		return;
	}
	else if ((obj.GetComponent(MeshFilter) as MeshFilter).sharedMesh == null) {
		EditorUtility.DisplayDialog("No mesh selected", "Please select an object with a valid mesh.", "Cancel");
		return;
	}
	if (Terrain.activeTerrain == null) {
		EditorUtility.DisplayDialog("No terrain found", "Please make sure a terrain exists.", "Cancel");
		return;
	}
	var terrain = Terrain.activeTerrain.terrainData;

	// If there's no mesh collider, add one (and then remove it later when done)
	var addedCollider = false;
	var addedMesh = false;
	var objCollider = obj.collider as MeshCollider;
	if (objCollider == null) {
		objCollider = obj.AddComponent(MeshCollider);
		addedCollider = true;
	}
	else if (objCollider.sharedMesh == null) {
		objCollider.sharedMesh = (obj.GetComponent(MeshFilter) as MeshFilter).sharedMesh;
		addedMesh = true;
	}

	Undo.RegisterUndo (terrain, "Object to Terrain");

	var resolutionX = terrain.heightmapWidth;
	var resolutionZ = terrain.heightmapHeight;
	var heights = terrain.GetHeights(0, 0, resolutionX, resolutionZ);

	// Use bounds a bit smaller than the actual object; otherwise raycasting tends to miss at the edges
	var objectBounds = objCollider.bounds;
	var leftEdge = objectBounds.center.x - objectBounds.extents.x + .01;
	var bottomEdge = objectBounds.center.z - objectBounds.extents.z + .01;
	var stepX = (objectBounds.size.x - .019) / resolutionX;
	var stepZ = (objectBounds.size.z - .019) / resolutionZ;

	// Set up raycast vars
	var y = objectBounds.center.y + objectBounds.extents.y + .01;
	var hit : RaycastHit;
	var ray = new Ray(Vector3.zero, -Vector3.up);
	var rayDistance = objectBounds.size.y + .02;
	var heightFactor = 1.0 / rayDistance;

	// Do raycasting samples over the object to see what terrain heights should be
	var z = bottomEdge;
	for (zCount = 0; zCount < resolutionZ; zCount++) {
		var x = leftEdge;
		for (xCount = 0; xCount < resolutionX; xCount++) {
			ray.origin = Vector3(x, y, z);
			if (objCollider.Raycast(ray, hit, rayDistance)) {
				heights[zCount, xCount] = 1.0 - (y - hit.point.y)*heightFactor;
			}
			else {
				heights[zCount, xCount] = 0.0;
			}
			x += stepX;
		}
		z += stepZ;
	}

	terrain.SetHeights(0, 0, heights);

	if (addedMesh) {
		objCollider.sharedMesh = null;
	}
	if (addedCollider) {
		DestroyImmediate(objCollider);
	}
}
```


text:
package org.opencb.opencga.storage.core.variant;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.opencb.biodata.models.feature.Genotype;
import org.opencb.biodata.models.variant.Variant;
import org.opencb.biodata.models.variant.VariantFactory;
import org.opencb.biodata.models.variant.VariantSource;
import org.opencb.biodata.models.variant.VariantSourceEntry;
import org.opencb.biodata.models.variant.annotation.VariantAnnotation;
import org.opencb.biodata.models.variant.stats.VariantStats;
import org.opencb.commons.run.Task;
import org.opencb.opencga.storage.core.runner.StringDataWriter;
import org.opencb.opencga.storage.core.variant.io.json.*;

import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Jacobo Coll <jacobo167@gmail.com>
 */
class VariantJsonTransformTask extends Task<String> {

    final VariantFactory factory;
    final ObjectWriter objectWriter;
    private final VariantSource source;
    private final ObjectMapper jsonObjectMapper;
    private final Path outputFileJsonFile;

    public VariantJsonTransformTask(VariantFactory factory, VariantSource source, Path outputFileJsonFile) {
        this.factory = factory;
        this.source = source;
        this.outputFileJsonFile = outputFileJsonFile;

        JsonFactory jsonFactory = new JsonFactory();
        ObjectMapper jsonObjectMapper = new ObjectMapper(jsonFactory);
        jsonObjectMapper.addMixInAnnotations(VariantSourceEntry.class, VariantSourceEntryJsonMixin.class);
        jsonObjectMapper.addMixInAnnotations(Genotype.class, GenotypeJsonMixin.class);
        jsonObjectMapper.addMixInAnnotations(VariantStats.class, VariantStatsJsonMixin.class);
        jsonObjectMapper.addMixInAnnotations(VariantSource.class, VariantSourceJsonMixin.class);
        jsonObjectMapper.addMixInAnnotations(VariantAnnotation.class, VariantAnnotationMixin.class);

        this.jsonObjectMapper = jsonObjectMapper;
        this.objectWriter = jsonObjectMapper.writerWithType(Variant.class);
    }

    @Override
    public boolean pre() {
        return super.pre();
    }

    @Override
    public boolean post() {
        ObjectWriter variantSourceObjectWriter = jsonObjectMapper.writerWithType(VariantSource.class);
        try {
            String sourceJsonString = variantSourceObjectWriter.writeValueAsString(source);
            StringDataWriter.write(outputFileJsonFile, Collections.singletonList(sourceJsonString));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return false;
        }
        return super.post();
    }

    @Override
    public boolean apply(List<String> batch) {
        List<String> outputBatch = new ArrayList<>(batch.size());
//            logger.info("batch.size() = " + batch.size());
        try {
            for (String line : batch) {
                if (line.startsWith("#") || line.trim().isEmpty()) {
                    continue;
                }
                List<Variant> variants = factory.create(source, line);
                for (Variant variant : variants) {
                    try {
                        String e = objectWriter.writeValueAsString(variant);
                        outputBatch.add(e + "\n");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
//            logger.info("outputBatch.size() = " + outputBatch.size());
            batch.clear();
            batch.addAll(outputBatch);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}


text:
import mock
from webob import exc
import webtest

from quantum.api.v2 import resource as wsgi_resource
from quantum.common import exceptions as q_exc
from quantum import context
from quantum.tests import base
from quantum import wsgi

class RequestTestCase(base.BaseTestCase):
    def setUp(self):
        super(RequestTestCase, self).setUp()
        self.req = wsgi_resource.Request({'foo': 'bar'})

    def test_content_type_missing(self):
        request = wsgi.Request.blank('/tests/123', method='POST')
        request.body = "<body />"
        self.assertEqual(None, request.get_content_type())

    def test_content_type_with_charset(self):
        request = wsgi.Request.blank('/tests/123')
        request.headers["Content-Type"] = "application/json; charset=UTF-8"
        result = request.get_content_type()
        self.assertEqual(result, "application/json")

    def test_content_type_from_accept(self):
        for content_type in ('application/xml',
                             'application/json'):
            request = wsgi.Request.blank('/tests/123')
            request.headers["Accept"] = content_type
            result = request.best_match_content_type()
            self.assertEqual(result, content_type)

    def test_content_type_from_accept_best(self):
        request = wsgi.Request.blank('/tests/123')
        request.headers["Accept"] = "application/xml, application/json"
        result = request.best_match_content_type()
        self.assertEqual(result, "application/json")

        request = wsgi.Request.blank('/tests/123')
        request.headers["Accept"] = ("application/json; q=0.3, "
                                     "application/xml; q=0.9")
        result = request.best_match_content_type()
        self.assertEqual(result, "application/xml")

    def test_content_type_from_query_extension(self):
        request = wsgi.Request.blank('/tests/123.xml')
        result = request.best_match_content_type()
        self.assertEqual(result, "application/xml")

        request = wsgi.Request.blank('/tests/123.json')
        result = request.best_match_content_type()
        self.assertEqual(result, "application/json")

        request = wsgi.Request.blank('/tests/123.invalid')
        result = request.best_match_content_type()
        self.assertEqual(result, "application/json")

    def test_content_type_accept_and_query_extension(self):
        request = wsgi.Request.blank('/tests/123.xml')
        request.headers["Accept"] = "application/json"
        result = request.best_match_content_type()
        self.assertEqual(result, "application/xml")

    def test_content_type_accept_default(self):
        request = wsgi.Request.blank('/tests/123.unsupported')
        request.headers["Accept"] = "application/unsupported1"
        result = request.best_match_content_type()
        self.assertEqual(result, "application/json")

    def test_context_with_quantum_context(self):
        ctxt = context.Context('fake_user', 'fake_tenant')
        self.req.environ['quantum.context'] = ctxt
        self.assertEqual(self.req.context, ctxt)

    def test_context_without_quantum_context(self):
        self.assertTrue(self.req.context.is_admin)

class ResourceTestCase(base.BaseTestCase):
    def test_unmapped_quantum_error(self):
        controller = mock.MagicMock()
        controller.test.side_effect = q_exc.QuantumException()

        resource = webtest.TestApp(wsgi_resource.Resource(controller))

        environ = {'wsgiorg.routing_args': (None, {'action': 'test'})}
        res = resource.get('', extra_environ=environ, expect_errors=True)
        self.assertEqual(res.status_int, exc.HTTPInternalServerError.code)

    def test_mapped_quantum_error(self):
        controller = mock.MagicMock()
        controller.test.side_effect = q_exc.QuantumException()

        faults = {q_exc.QuantumException: exc.HTTPGatewayTimeout}
        resource = webtest.TestApp(wsgi_resource.Resource(controller,
                                                          faults=faults))

        environ = {'wsgiorg.routing_args': (None, {'action': 'test'})}
        res = resource.get('', extra_environ=environ, expect_errors=True)
        self.assertEqual(res.status_int, exc.HTTPGatewayTimeout.code)

    def test_http_error(self):
        controller = mock.MagicMock()
        controller.test.side_effect = exc.HTTPGatewayTimeout()

        resource = webtest.TestApp(wsgi_resource.Resource(controller))

        environ = {'wsgiorg.routing_args': (None, {'action': 'test'})}
        res = resource.get('', extra_environ=environ, expect_errors=True)
        self.assertEqual(res.status_int, exc.HTTPGatewayTimeout.code)

    def test_unhandled_error(self):
        controller = mock.MagicMock()
        controller.test.side_effect = Exception()

        resource = webtest.TestApp(wsgi_resource.Resource(controller))

        environ = {'wsgiorg.routing_args': (None, {'action': 'test'})}
        res = resource.get('', extra_environ=environ, expect_errors=True)
        self.assertEqual(res.status_int, exc.HTTPInternalServerError.code)

    def test_status_200(self):
        controller = mock.MagicMock()
        controller.test = lambda request: {'foo': 'bar'}

        resource = webtest.TestApp(wsgi_resource.Resource(controller))

        environ = {'wsgiorg.routing_args': (None, {'action': 'test'})}
        res = resource.get('', extra_environ=environ, expect_errors=True)
        self.assertEqual(res.status_int, 200)

    def test_status_204(self):
        controller = mock.MagicMock()
        controller.test = lambda request: {'foo': 'bar'}

        resource = webtest.TestApp(wsgi_resource.Resource(controller))

        environ = {'wsgiorg.routing_args': (None, {'action': 'delete'})}
        res = resource.delete('', extra_environ=environ, expect_errors=True)
        self.assertEqual(res.status_int, 204)

    def test_no_route_args(self):
        controller = mock.MagicMock()

        resource = webtest.TestApp(wsgi_resource.Resource(controller))

        environ = {}
        res = resource.get('', extra_environ=environ, expect_errors=True)
        self.assertEqual(res.status_int, exc.HTTPInternalServerError.code)

    def test_post_with_body(self):
        controller = mock.MagicMock()
        controller.test = lambda request, body: {'foo': 'bar'}

        resource = webtest.TestApp(wsgi_resource.Resource(controller))

        environ = {'wsgiorg.routing_args': (None, {'action': 'test'})}
        res = resource.post('', params='{"key": "val"}',
                            extra_environ=environ, expect_errors=True)
        self.assertEqual(res.status_int, 200)


text:
// LICENSE : MIT
"use strict";
/**
 * capture current frame of the video, then return dataURL as a image.
 * @param {HTMLVideoElement} video
 * @returns {string}
 */
export function captureVideo(video) {
    var canvas = document.createElement("canvas");
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    var canvasContext = canvas.getContext("2d");
    canvasContext.drawImage(video, 0, 0);
    return canvas.toDataURL('image/png');
}


text:
package com.github.mkopylec.errorest.logging;

import com.github.mkopylec.errorest.handling.errordata.ErrorData;
import org.slf4j.Logger;

import static com.github.mkopylec.errorest.logging.LoggingLevel.DEBUG;
import static com.github.mkopylec.errorest.logging.LoggingLevel.ERROR;
import static com.github.mkopylec.errorest.logging.LoggingLevel.INFO;
import static com.github.mkopylec.errorest.logging.LoggingLevel.TRACE;
import static com.github.mkopylec.errorest.logging.LoggingLevel.WARN;
import static org.slf4j.LoggerFactory.getLogger;

public class ExceptionLogger {

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

    public void log(ErrorData errorData) {
        log(TRACE, errorData, () -> log.trace(createLogMessage(errorData), errorData.getThrowable()));
        log(DEBUG, errorData, () -> log.debug(createLogMessage(errorData), errorData.getThrowable()));
        log(INFO, errorData, () -> log.info(createLogMessage(errorData), errorData.getThrowable()));
        log(WARN, errorData, () -> log.warn(createLogMessage(errorData), errorData.getThrowable()));
        log(ERROR, errorData, () -> log.error(createLogMessage(errorData), errorData.getThrowable()));
    }

    protected void log(LoggingLevel loggingLevel, ErrorData errorData, Runnable logger) {
        if (!errorData.hasLoggingLevel(loggingLevel)) {
            return;
        }
        logger.run();
    }

    protected String createLogMessage(ErrorData errorData) {
        return "ID: " + errorData.getId() + " | " + errorData.getRequestMethod() + " " + errorData.getRequestUri() + " " + errorData.getResponseStatus() + " | " + errorData.getErrors();
    }
}


text:
import { PlanAlimenticioService } from './plan-alimenticio.service';
import { PlanAlimenticio } from './../../models/plan-alimenticio.model';
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class PlanAlimenticioResolver implements Resolve <PlanAlimenticio> {

  constructor(private planAlimenticioService: PlanAlimenticioService, private router: Router) { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    let id = +route.params['id'];
    if(isNaN(id)){
      return new PlanAlimenticio();
    }
    return this.planAlimenticioService.getPlanAlimenticio(id)
    .map(planAlimenticio =>{
      if(planAlimenticio){
        return planAlimenticio;
      }
    })
  }

}


text:
package com.mobilecashout.osprey.project;

import com.mobilecashout.osprey.exception.BaseException;

public class ProjectConfigurationError extends BaseException {
    public ProjectConfigurationError(String message) {
        super(message);
    }

    public ProjectConfigurationError(Exception e) {
        super(e);
    }
}


text:
/* Sasukette board configuration */

#ifndef __CROS_EC_BOARD_H
#define __CROS_EC_BOARD_H

/* Select Baseboard features */
#define VARIANT_DEDEDE_EC_IT8320
#include "baseboard.h"
#undef GPIO_VOLUME_UP_L
#undef GPIO_VOLUME_DOWN_L
#undef CONFIG_VOLUME_BUTTONS
#undef CONFIG_I2C_DEBUG

/* EC console commands */
#define CONFIG_CMD_TCPC_DUMP
#define CONFIG_CMD_CHARGER_DUMP

/* Battery */
#define CONFIG_BATTERY_FUEL_GAUGE
#define CONFIG_BATTERY_CHECK_CHARGE_TEMP_LIMITS

/* BC 1.2 */
#define CONFIG_BC12_DETECT_PI3USB9201

/* Charger */
#define CONFIG_CHARGER_RAA489000
#define PD_MAX_VOLTAGE_MV 20000
#define CONFIG_CHARGER_SENSE_RESISTOR_AC 10
#define CONFIG_CHARGER_SENSE_RESISTOR 10
#define CONFIG_CHARGER_SINGLE_CHIP
#define CONFIG_CHARGER_PROFILE_OVERRIDE
#undef CONFIG_USB_PD_TCPC_LPM_EXIT_DEBOUNCE
#define CONFIG_USB_PD_TCPC_LPM_EXIT_DEBOUNCE (100 * MSEC)
/*
 * b/147463641: The charger IC seems to overdraw ~4%, therefore we
 * reduce our target accordingly.
 */
#define CONFIG_CHARGER_INPUT_CURRENT_DERATE_PCT 4

/* LED */
#define CONFIG_LED_COMMON
#define CONFIG_LED_ONOFF_STATES
#define GPIO_BAT_LED_RED_L GPIO_LED_R_ODL
#define GPIO_BAT_LED_GREEN_L GPIO_LED_G_ODL
#define GPIO_PWR_LED_BLUE_L GPIO_LED_B_ODL

/* TCPC */
#define CONFIG_USB_PD_PORT_MAX_COUNT 1
#define CONFIG_USB_PD_TCPM_RAA489000

/* USB defines specific to external TCPCs */
#define CONFIG_USB_PD_DUAL_ROLE_AUTO_TOGGLE
#define CONFIG_USB_PD_VBUS_DETECT_TCPC
#define CONFIG_USB_PD_DISCHARGE_TCPC
#define CONFIG_USB_PD_TCPC_LOW_POWER
#define CONFIG_USB_PD_5V_EN_CUSTOM

/* Thermistors */
#define CONFIG_TEMP_SENSOR
#define CONFIG_THERMISTOR
#define CONFIG_STEINHART_HART_3V3_51K1_47K_4050B

/* USB Mux and Retimer */
#define CONFIG_USB_MUX_IT5205 /* C1: ITE Mux */
#define I2C_PORT_USB_MUX I2C_PORT_USB_C0 /* Required for ITE Mux */

#ifndef __ASSEMBLER__

#include "gpio_signal.h"
#include "registers.h"

/* ADC channels */
enum adc_channel {
	ADC_VSNS_PP3300_A, /* ADC0 */
	ADC_TEMP_SENSOR_1, /* ADC2 */
	ADC_TEMP_SENSOR_2, /* ADC3 */
	ADC_TEMP_SENSOR_3, /* ADC15*/
	ADC_CH_COUNT
};

enum temp_sensor_id {
	TEMP_SENSOR_1,
	TEMP_SENSOR_2,
	TEMP_SENSOR_3,
	TEMP_SENSOR_COUNT
};

/* List of possible batteries */
enum battery_type {
	BATTERY_SDI,
	BATTERY_TYPE_COUNT,
};

#endif /* !__ASSEMBLER__ */

#endif /* __CROS_EC_BOARD_H */


text:
<?xml version="1.0" ?>
<dataset id="participants-challenge">

<question id="1" answertype="resource" aggregation="false" yago="false">
<string><![CDATA[
Give me all people that wrote lyrics for bands from Seattle.
]]></string>
<query><![CDATA[
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX res: <http://dbpedia.org/resource/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX mo: <http://purl.org/ontology/mo/>
SELECT DISTINCT ?uri ?string
WHERE {
  ?dbp_band owl:sameAs ?band .
  ?dbp_band dbo:hometown res:Seattle.
  ?album foaf:maker ?band .
  ?album mo:lyricist ?uri .
  ?uri foaf:name ?string .
}
]]></query>
</question>

<question id="2" answertype="resource" aggregation="true" yago="false">
<string><![CDATA[
How many singles were produced by bands under contract with Roadrunner Records.
]]></string>
<query> <![CDATA[
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX res: <http://dbpedia.org/resource/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX mo: <http://purl.org/ontology/mo/>
PREFIX dc: <http://purl.org/dc/elements/1.1/>
SELECT COUNT(DISTINCT ?uri)
WHERE {
  ?dbp_band rdf:type dbo:Band .
  ?dbp_band dbo:recordLabel res:Roadrunner_Records .
  ?dbp_band owl:sameAs ?mb_band .
  ?uri rdf:type mo:Record .
  ?uri mo:release_type mo:single .
  ?uri foaf:maker ?mb_band .
}
]]></query>
</question>

<question id="3" answertype="number" aggregation="true" yago="false">
<string><![CDATA[
Give me all records that were released during the lifetime of John F. Kennedy.
]]></string>
<query><![CDATA[
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX res: <http://dbpedia.org/resource/>
PREFIX mo: <http://purl.org/ontology/mo/>
SELECT DISTINCT ?uri ?string
WHERE {
   ?uri rdf:type mo:Record .
   ?uri dc:title ?string .
   ?album owl:sameAs ?uri .
   ?album dbo:releaseDate ?date .
   res:John_F._Kennedy dbo:birthDate ?start .
   res:John_F._Kennedy dbo:deathDate ?end .
   FILTER (?date >= ?start && ?date <= ?end)
}
]]></query>
</question>

<question id="4" answertype="resource" aggregation="true" yago="true">
<string><![CDATA[
Give me all anarcho punk bands that were formed in the 80s.
]]></string>
<query><![CDATA[
PREFIX yago: <http://dbpedia.org/class/yago/>
PREFIX bio: <http://purl.org/vocab/bio/0.1/>
SELECT DISTINCT ?uri ?string
WHERE {
  ?uri rdf:type yago:Anarcho-punkGroups .
  ?uri owl:sameAs ?mb_band .
  ?mb_band bio:event ?event .
  ?event rdf:type bio:Birth .
  ?event bio:date ?date .
  { ?event bio:date ?date .
    FILTER (?date <= '1989-12-31'^^xsd:date || ?date >= '1980-01-01'^^xsd:date ) }
  UNION
  { ?event bio:date ?date .
    FILTER regex(?date,'^198') }
  OPTIONAL { ?uri rdfs:label ?string . FILTER (lang(?string) = 'en') }
}
]]></query>
</question>

<question id="5" answertype="resource" aggregation="false" yago="false">
<string><![CDATA[
Give me all singles released by daughter labels of Sony Music.
]]></string>
<query><![CDATA[
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX dbp: <http://dbpedia.org/property/>
PREFIX res: <http://dbpedia.org/resource/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX mo: <http://purl.org/ontology/mo/>
SELECT DISTINCT ?uri ?string
WHERE {
  ?label dbp:parent res:Sony_Music_Entertainment .
  ?dbp_band dbo:recordLabel ?label .
  ?dbp_band owl:sameAs ?mb_band .
  ?uri rdf:type mo:Record .
  ?uri mo:release_type mo:single .
  ?uri foaf:maker ?mb_band .
  ?uri dc:title ?string .
}
]]></query>
</question>

<question id="6" answertype="boolean" aggregation="true" yago="false">
<string><![CDATA[
Was the Cracow Klezmer Band founded before DJ Tomekk was born?
]]></string>
<query><![CDATA[
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX res: <http://dbpedia.org/resource/>
PREFIX bio: <http://purl.org/vocab/bio/0.1/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX mo: <http://purl.org/ontology/mo/>
ASK
WHERE {
  ?mb_band foaf:name 'The Cracow Klezmer Band' .
  ?mb_band bio:event ?event .
  ?event rdf:type bio:Birth .
  ?event bio:date ?birthdate1 .
  res:DJ_Tomekk dbo:birthDate ?birthdate2 .
  FILTER (?birthdate1 <= ?birthdate2)
}
]]></query>
</question>

<question id="7" answertype="resource" aggregation="false" yago="false">
<string><![CDATA[
In which country was the singer of the Drunken Lullabies by Flogging Molly born?
]]></string>
<query><![CDATA[
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX mo: <http://purl.org/ontology/mo/>
SELECT DISTINCT ?uri ?string
WHERE {
  ?album rdf:type mo:Record .
  ?album dc:title 'Drunken Lullabies' .
  ?album mo:singer ?mb_singer .
  ?album foaf:maker ?mb_band .
  ?mb_band foaf:name 'Flogging Molly' .
  ?dbp_singer owl:sameAs ?mb_singer .
  ?dbp_singer dbo:birthPlace ?city .
  ?city dbo:country ?uri .
  ?uri rdf:type dbo:Country .
  OPTIONAL { ?uri rdfs:label ?string . FILTER (lang(?string) = 'en') }
}
]]>
</query>
</question>

</dataset>


text:
import Vue from './../../lib/vue'
import maptool from './map.vue'

var css = require('../style/main.css')
// import style from '../style/main.css'

var b = new Vue({
	el: '#app',
	components: {
		maptool:maptool
	}
});


text:
'use strict';
const common = require('../common.js');

const bench = common.createBenchmark(main, {
  n: [1e6],
  listeners: [1, 5, 10]
}, { flags: ['--expose-internals'] });

function main({ n, listeners }) {
  const { EventTarget, Event } = require('internal/event_target');
  const target = new EventTarget();

  for (let n = 0; n < listeners; n++)
    target.addEventListener('foo', () => {});

  bench.start();
  for (let i = 0; i < n; i++) {
    target.dispatchEvent(new Event('foo'));
  }
  bench.end(n);

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pestalotia veneta var. tricuspis Sacc.

### Remarks
null


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Agaricus subrepandus var. subrepandus Bull.

### Remarks
null


text:
using System;
using NUnit.Framework;

namespace Shuttle.Esb.Process.Tests
{
	[TestFixture]
	public class DefaultProcessActivatorFixture
	{
		[Test]
		public void Should_be_able_to_request_mapping_registration()
		{
			var transportMessage = new TransportMessage();
			var activator = new DefaultProcessActivator();

			activator.RegisterMappings();

			Assert.IsFalse(activator.IsProcessMessage(transportMessage, new MockNullCommand()));

			Assert.IsTrue(activator.IsProcessMessage(transportMessage, new MockRegisterOrderCommand()));
			Assert.IsTrue(activator.IsProcessMessage(transportMessage, new MockEMailSentEvent()));
			Assert.IsTrue(activator.IsProcessMessage(transportMessage, new MockCompleteOrderCommand()));

			Assert.IsTrue(activator.IsProcessMessage(transportMessage, new MockRegisterMemberCommand()));
			Assert.IsTrue(activator.IsProcessMessage(transportMessage, new MockCompleteMemberRegistrationCommand()));
		}

		[Test]
		public void Should_be_able_to_resolve_message_to_multiple_processes()
		{
			var transportMessage = new TransportMessage
			{
				CorrelationId = Guid.NewGuid().ToString()
			};

			var activator = new DefaultProcessActivator();

			activator.RegisterMappings();

			activator.RegisterResolver<MockEMailSentEvent>(
				(transport, message) => new MessageProcessType(typeof (MockOrderProcess), false));

			var instance = activator.Create(transportMessage, new MockEMailSentEvent());

			Assert.IsTrue(instance.GetType() == typeof (MockOrderProcess));
		}

		[Test]
		public void Should_be_able_to_start_process()
		{
			var transportMessage = new TransportMessage();
			var activator = new DefaultProcessActivator();

			activator.RegisterMappings();

			Assert.IsTrue(typeof (MockOrderProcess) ==
			              activator.Create(transportMessage, new MockRegisterOrderCommand()).GetType());
			Assert.IsTrue(typeof (MockMemberRegistrationProcess) ==
			              activator.Create(transportMessage, new MockRegisterMemberCommand()).GetType());
		}

		[Test]
		public void Should_throw_exception_when_creating_unknown_process()
		{
			var transportMessage = new TransportMessage();
			var activator = new DefaultProcessActivator();

			Assert.Throws<ProcessException>(() => activator.Create(transportMessage, new MockRegisterMemberCommand()));
		}

		[Test]
		public void Should_throw_exception_when_no_resolver_for_message_to_multiple_processes()
		{
			var transportMessage = new TransportMessage();
			var activator = new DefaultProcessActivator();

			activator.RegisterMappings();

			Assert.Throws<ProcessException>(() => activator.Create(transportMessage, new MockEMailSentEvent()));
		}
	}
}


text:
//
//  MacrosUnit.h
//  MALHelp
//
//  Created by wangtian on 15-3-5.
//  Copyright (c) 2015年 wangtian. All rights reserved.
//

#ifndef MALHelp_MacrosUnit_h
#define MALHelp_MacrosUnit_h

//------------------View
#pragma mark -
#pragma mark iOS Frame
//获取当前screen
#define mainSize    [UIScreen mainScreen].bounds.size
#define IOS_SCREEN  [ UIScreen mainScreen ].bounds

// 屏幕高度
#define SCREEN_HEIGHT         [[UIScreen mainScreen] bounds].size.height

// 屏幕宽度
#define SCREEN_WIDTH          [[UIScreen mainScreen] bounds].size.width
#define SYSTEM_VERSION        [[[UIDevice currentDevice] systemVersion] floatValue]
#define STATUSBAR_HEIGHT      [[UIApplication sharedApplication] statusBarFrame].size.height
#define NAVBAR_HEIGHT         (44.f + ((SYSTEM_VERSION >= 7) ? STATUSBAR_HEIGHT : 0))
#define FULL_WIDTH            SCREEN_WIDTH
#define FULL_HEIGHT           (SCREEN_HEIGHT - ((SYSTEM_VERSION >= 7) ? 0 : STATUSBAR_HEIGHT))
#define CONTENT_HEIGHT        (FULL_HEIGHT - NAVBAR_HEIGHT)

#define WIDTH(view) view.frame.size.width
#define HEIGHT(view) view.frame.size.height
#define X(view) view.frame.origin.x
#define Y(view) view.frame.origin.y
#define LEFT(view) view.frame.origin.x
#define TOP(view) view.frame.origin.y
#define BOTTOM(view) (view.frame.origin.y + view.frame.size.height)
#define RIGHT(view) (view.frame.origin.x + view.frame.size.width)

//------------------View

//-----------------系统信息
#pragma mark -
#pragma mark iOS info

//++++++++ app常用变量
#define APPDELEGATE  [[UIApplication sharedApplication]delegate] //appdelegate
#define KEYWINDOW    [UIApplication sharedApplication].keyWindow // keywindow
#define AppInfoDic   [[NSBundle mainBundle] infoDictionary] //应用信息字典
#define AppVersion   [AppInfoDic objectForKey:@"CFBundleVersion"] //应用版本号
#define AppName      [AppInfoDic objectForKey:@"CFBundleDisplayName"] //应用名称
#define userDefaults [NSUserDefaults standardUserDefaults]

//++++++++ 系统版本
#define IOS_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
#define IOS_VERSION_EQUAL_TO(v)                 [[[UIDevice currentDevice] systemVersion] floatValue]==v
#define IOS_VERSION_GREATER_THAN(v)              [[[UIDevice currentDevice] systemVersion] floatValue]>v
#define IOS_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  [[[UIDevice currentDevice] systemVersion] floatValue]>=v
#define IOS_VERSION_LESS_THAN(v)                 [[[UIDevice currentDevice] systemVersion] floatValue]<v
#define IOS_VERSION_LESS_THAN_OR_EQUAL_TO(v)     [[[UIDevice currentDevice] systemVersion] floatValue]<=v

//++++++++ storyBoard
#define StoryBoardWithName(name)  [UIStoryboard storyboardWithName:name bundle:nil]
#define ControllerWithSBAndIdentifier(sb,identifier)  [sb instantiateViewControllerWithIdentifier:identifier]
#define MALNibWithName(name)   [[NSBundle mainBundle] loadNibNamed:name owner:nil options:nil]
#define MALUINibWithName(name)  [UINib nibWithNibName:name bundle:nil];

//++++++++ 沙盒文件路径

//-----------------系统信息

//-----------------颜色
#pragma mark -
#pragma mark UIColor
#define UIColorFromHexWithAlpha(hexValue,a) [UIColor colorWithRed:((float)((hexValue & 0xFF0000) >> 16))/255.0 green:((float)((hexValue & 0xFF00) >> 8))/255.0 blue:((float)(hexValue & 0xFF))/255.0 alpha:a]
#define UIColorFromHex(hexValue)            UIColorFromHexWithAlpha(hexValue,1.0)
#define RGBA(r,g,b,a)            [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]
#define RGB(r,g,b)                RGBA(r,g,b,1.0)
//-----------------颜色

//-----------------object
#pragma mark -
#pragma mark object

//++++++++NSValue
#define POINTERIZE(x) ((__typeof__(x) []){ x })
#define NSVALUE(x) [NSValue valueWithBytes: POINTERIZE(x) objCType: @encode(__typeof__(x))]

//++++++++NSNumber
#define NUM_INT(int) [NSNumber numberWithInt:int]
#define NUM_FLOAT(float) [NSNumber numberWithFloat:float]
#define NUM_BOOL(bool) [NSNumber numberWithBool:bool]

//++++++NSString
#define MALStringFormat(fmt,...)  [NSString stringWithFormat:fmt,## __VA_ARGS__]

//弱指针
#define WeakSelf(ws) __weak __typeof(&*self) ws = self
//-----------------object

//----------------function
#pragma mark -
#pragma mark function
/**
 *  判断id是为空
 */
static inline BOOL IsEmpty(id thing) {
    return thing == nil || [thing isEqual:[NSNull null]]
    || ([thing respondsToSelector:@selector(length)]
        && [(NSData *)thing length] == 0)
    || ([thing respondsToSelector:@selector(count)]
        && [(NSArray *)thing count] == 0);
}

static inline NSString *StringFromObject(id object) {
    if (object == nil || [object isEqual:[NSNull null]]) {
        return @"";
    } else if ([object isKindOfClass:[NSString class]]) {
        return object;
    } else if ([object respondsToSelector:@selector(stringValue)]){
        return [object stringValue];
    } else {
        return [object description];
    }
}

//log输出
#ifndef __OPTIMIZE__
#define Log(FORMAT,...)  fprintf(stderr,"file:%s\nline:%d\nfunc:%s\noutput:%s\n\n",[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__,__func__ ,[[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String])
#else
#define Log(...)  {}
#endif

#ifndef __OPTIMIZE__
#define YNLog(...) NSLog(__VA_ARGS__)
#else
#define YNLog(...){}
#endif

//设置导航栏返回标题
#define SetBackItemTitle(title)  [self.navigationItem setBackBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:nil action:nil]]
#define SetBackItem  SetBackItemTitle(@"")

//----------------function

//----------------thread
#pragma mark -
#pragma mark - thread
/**
 *  在主线程执行代码
 *
 *  @param block 你要执行的代码块
 *
 */
#define HandleOnMainThread(block) dispatch_async(dispatch_get_main_queue(),block);

/**
 *  gcd调度时间 dispatch_time
 */
#define MGCDTime(time) dispatch_time(DISPATCH_TIME_NOW, time * NSEC_PER_SEC)

/**
 *  dispatch_after   延时执行代码
 */
#define MGCDAfter(delayTime,block)  dispatch_after(MGCDTime(delayTime), dispatch_get_main_queue(),block)

//----------------thread

//----------------UIView
#pragma mark -
#pragma mark - UIView

//弹出框
#define AlertViewWithTitleAndMsg(title,msg)  [[[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show]
#define AlertViewWithTitle(title)   AlertViewWithTitleAndMsg(title,nil)

//按钮
#define BtnTitleForState(btn,state)  (NSString *)[btn titleForState:state]
#define BtnTitleForNormal(btn)        BtnTitleForState(btn,UIControlStateNormal)

//----------------UIView

#endif


text:
var express = require('express'),
    mongoose = require('mongoose'),
    moment = require('moment'),
    winston = require('winston'),
    exphbs = require('express-handlebars');

// Add timestamp to logs
// http://stackoverflow.com/questions/10271373/how-can-i-add-timestamp-to-logs-using-node-js-library-winston
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp': true});

var app = express();
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.set('views', 'views');
app.use(express.static('assets'));

var RedditPost = null;

app.get('/', function (req, res) {
    var minUpvotes = process.env.REDDIT_MIN_UPVOTES || 1;
    RedditPost.find({'data.ups': {$gt: minUpvotes}}).sort({'data.ups': -1}).exec(function (err, posts) {
        if (err) {
            winston.warn("Error while fetching reddit posts from the DB: ", err);
            res.render('index', {title: 'pnews', message: 'An error occurred while fetching the results from the DB'});
        } else {
            // Create human friendly date strings for each post
            var now = moment.utc();
            var filteredPosts = [];
            for (var i = 0, len = posts.length; i < len; i++) {
                var date = moment.unix(posts[i].data.created_utc);
                var diff = moment.duration(now.diff(date)).days();
                // only keep posts of the last day
                if (diff < 1) {
                    filteredPosts.push(posts[i]);
                    posts[i].data.date_str = date.fromNow();//  + " (" + date.format("ddd, MMM Do YYYY, h:mm A") + ")";
                }
            }
            res.render('home', {title: 'pnews', message: 'Pnews', posts: filteredPosts});
        }
    });

});

var server = app.listen(process.env.WEB_SERVER_PORT || 3000, function () {
    winston.info("Starting pnews-web...");
    var host = server.address().address;
    var port = server.address().port;

    // Set connection to keep-alive so that we don't need to worry about losing the db connection:
    // http://mongoosejs.com/docs/connections.html
    var options = {
        server: {socketOptions: {keepAlive: 1}},
        replset: {socketOptions: {keepAlive: 1}}
    };
    mongoose.connect(process.env.MONGO_DB_URL, options);

    // set strict: false so that we can just insert reddit posts without having to define the schema here
    var RedditPostSchema = mongoose.Schema({
        data: {
            id: {type: [String], index: true},
            title: String,
            url: String,
            permalink: String,
            num_comments: Number,
            created_utc: Number,
            ups: Number
        }
    }, {strict: false});
    RedditPost = mongoose.model('RedditPost', RedditPostSchema);

    winston.info('pnews listening at http://%s:%s', host, port);
});


text:
"""
Settings for the wishlist. These should not be edited directly. Instead,
overwrite them in the main project's setting file.
"""
from django.conf import settings

# The name of the wishlist
WISHLIST_TITLE = getattr(settings, 'WISHLIST_TITLE', 'My Wishlist')

# Currency to list prices in.
# This should be a tuple, with the first item being the currency abbreviation and the
# second item being the currency symbol.
WISHLIST_CURRENCY = getattr(settings, 'WISHLIST_CURRENCY', ('USD', '$'))

# Should all items on the wishlist be public.
WISHLIST_PUBLIC = getattr(settings, 'WISHLIST_PUBLIC', False)

# A tuple of tags which mark the tagged item as being public.
# This is only considered if WISHLIST_PUBLIC above is set to False
WISHLIST_PUBLIC_TAGS = getattr(settings, 'WISHLIST_PUBLIC_TAGS', ('public',))


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

<!--

 This file is part of the Sylius package.

 (c) Paweł Jędrzejewski

 For the full copyright and license information, please view the LICENSE
 file that was distributed with this source code.

-->

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services
                               http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="sylius.translatable.listener.class">Sylius\Bundle\TranslationBundle\EventListener\TranslatableListener</parameter>
        <parameter key="sylius.translatable.listener.locale.class">Sylius\Bundle\TranslationBundle\EventListener\LocaleListener</parameter>
    </parameters>

    <services>
        <service id="sylius.translatable.listener" class="%sylius.translatable.listener.class%">
            <argument>%sylius.translation.mapping%</argument>
            <argument>%sylius.locale%</argument>
            <tag name="doctrine.event_subscriber" connection="default" />
        </service>

        <service id="sylius.translatable.listener.locale" class="%sylius.translatable.listener.locale.class%">
            <argument type="service" id="sylius.translatable.listener" />
            <tag name="kernel.event_subscriber" priority="98"/>
        </service>
    </services>
</container>


text:
真奇怪啊,Binder客户端这头竟然没有把outSurface的信息发过去。我们赶紧看看服务端。服务端这边处理是在onTranscat函数中。
```
@Override
public boolean onTransact(int code, android.os.Parcel data,
		android.os.Parcel reply, int flags)
		throws android.os.RemoteException {
	switch (code) {
	case TRANSACTION_relayout: {
		data.enforceInterface(DESCRIPTOR);
		android.view.IWindow _arg0;
		android.view.Surface _arg10;
		// 刚才说了,Surface信息并没有传过来,那么我们在relayOut中看到的outSurface是怎么
		// 出来的呢?看下面这句,原来在服务端这边竟然new了一个新的Surface!!!
		_arg10 = new android.view.Surface();
		int _result = this.relayout(_arg0, _arg1, _arg2, _arg3, _arg4,
				_arg5, _arg6, _arg7, _arg8, _arg9, _arg10);
		reply.writeNoException();
		reply.writeInt(_result);
		// _arg10是copyFrom了,那怎么传到客户端呢?
		if ((_arg10 != null)) {
			reply.writeInt(1);// 调用Surface的writeToParcel,把信息加入reply
			_arg10.writeToParcel(reply,
					android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
		}
		return true;
	}
	}
}
```
客户端虽然传了一个surface,但其实没传递给服务端。服务端调用writeToParcel,把信息写到Parcel中,然后数据传回客户端。客户端调用Surface的readFromParcel,获得surface信息。那就去看看writeToParcel吧。
```
static void Surface_writeToParcel(
JNIEnv* env, jobject clazz, jobject argParcel, jint flags) {
	Parcel* parcel = (Parcel*)env->GetIntField(argParcel, no.native_parcel);
	const sp& control(getSurfaceControl(env, clazz));
	//还好,只是把数据序列化到Parcel中
	SurfaceControl::writeSurfaceToParcel(control, parcel);
	if (flags & PARCELABLE_WRITE_RETURN_VALUE) {
		setSurfaceControl(env, clazz, 0);
	}
}
```
那看看客户端的Surface_readFromParcel吧。
```
static void Surface_readFromParcel(
JNIEnv* env, jobject clazz, jobject argParcel)
{
	Parcel* parcel = (Parcel*)env->GetIntField( argParcel, no.native_parcel);
	//客户端这边还没有surface呢
	const sp& control(getSurface(env, clazz));
	//不过我们看到希望了,根据服务端那边Parcel信息来构造一个新的surface
	sp rhs = new Surface(*parcel);
	if (!Surface::isSameSurface(control, rhs)) {
		setSurface(env, clazz, rhs); //把这个新surface赋给客户端。终于我们有了surface!
	}
}
```
到此,我们终于七拐八绕的得到了surface,这其中经历太多曲折了。下一节,我们将精简这其中复杂的操作,统一归到Native层,以这样为切入点来了解Surface的工作流程和原理。
反正你知道ViewRoot调用了relayout后,Surface就真正从WindowManagerService那得到了。继续回到ViewRoot,其中还有一个重要地方是我们知道却不了解的。
```
private void performTraversals() {
	final View host = mView;
	boolean initialized = false;
	boolean contentInsetsChanged = false;
	boolean visibleInsetsChanged;
	try {
		relayoutResult = relayoutWindow(params, viewVisibility,
				insetsPending);
		// relayoutWindow完后,我们得到了一个无比宝贵的Surface
		// 那我们画界面的地方在哪里?就在这个函数中,离relayoutWindow不远处。
		boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
		if (!cancelDraw && !newSurface) {
			mFullRedrawNeeded = false;
			draw(fullRedrawNeeded);
		}
	} catch (Exception e) {
	}
}
private void draw(boolean fullRedrawNeeded) {
	Surface surface = mSurface; // 嘿嘿,不担心了,surface资源都齐全了
	if (surface == null || !surface.isValid()) {
		return;
	}
	if (mAttachInfo.mViewScrollChanged) {
		mAttachInfo.mViewScrollChanged = false;
		mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
	}
	int yoff;
	final boolean scrolling = mScroller != null
			&& mScroller.computeScrollOffset();
	if (scrolling) {
		yoff = mScroller.getCurrY();
	} else {
		yoff = mScrollY;
	}
	if (mCurScrollY != yoff) {
		mCurScrollY = yoff;
		fullRedrawNeeded = true;
	}
	float appScale = mAttachInfo.mApplicationScale;
	boolean scalingRequired = mAttachInfo.mScalingRequired;
	Rect dirty = mDirty;
	if (mUseGL) { // 我们不用OPENGL
	}
	Canvas canvas;
	try {
		int left = dirty.left;
		int top = dirty.top;
		int right = dirty.right;
		int bottom = dirty.bottom;
		// 从Surface中锁定一块区域,这块区域是我们认为的需要重绘的区域
		canvas = surface.lockCanvas(dirty);
		canvas.setDensity(mDensity);
	} catch (Exception e) {
	}
	try {
		if (!dirty.isEmpty() || mIsAnimating) {
			long startTime = 0L;
			try {
				canvas.translate(0, -yoff);
				if (mTranslator != null) {
					mTranslator.translateCanvas(canvas);
				}
				canvas.setScreenDensity(scalingRequired);
				// mView就是之前的decoreView,
				mView.draw(canvas);
			} finally {
				// 我们的图画完了,告诉surface释放这块区域
				surface.unlockCanvasAndPost(canvas);
			}
			if (scrolling) {
				mFullRedrawNeeded = true;
				scheduleTraversals();
			}
		}
	} finally {
	}
}
```


text:
Бог свидетель, что мы вели себя среди них как святые, как умершие для мира, отказав- шись от всяких радостей, веселья и шуток, в совершеннейшей нравственности, хотя по нужде, а не добровольно. Находясь зимой в холодном храме, мы стояли с непокрытой го- ловою от начала и до конца обедни, ибо от греков сюда пришёл обычай, что священник и диакон постоянно остаются с открытой го- ловой. По этой причине и нам против воли надлежало подражать им.

Мы выходили от обедни едва волоча ноги от усталости и бесконечного стояния, выхо- дили не иначе как слепыми. Бог свидетель, что в ушах у нас гудело и мы оставались не- сколько дней лишенными слуха. Но труднее всего было то, что мы покидали храм только перед закатом, а когда ещё сидели за сто- лом, уже начинали звонить к вечерне.


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.3.xsd">

    <changeSet author="tjeandet" id="workflow-store-state-widening" dbms="mysql,hsqldb">
        <modifyDataType columnName="WORKFLOW_STATE"
                        newDataType="varchar(20)"
                        tableName="WORKFLOW_STORE_ENTRY"/>
    </changeSet>
</databaseChangeLog>


text:
package com.hp.hpl.jena.db.impl;

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

import com.hp.hpl.jena.db.RDFRDBException;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Node_Variable;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.graph.query.Bound;
import com.hp.hpl.jena.graph.query.Domain;
import com.hp.hpl.jena.graph.query.Element;
import com.hp.hpl.jena.graph.query.Fixed;
import com.hp.hpl.jena.graph.query.Mapping;
import com.hp.hpl.jena.graph.query.Query;
import com.hp.hpl.jena.shared.BrokenException;

public class DBPattern
    {
    final Triple pattern;
    final Element S;
    final Element P;
    final Element O;

    private int Scost, Pcost, Ocost;

    private boolean isBusy;

	private boolean isConnected;  // pattern can be joined to previously staged pattern for this query.

    private boolean isStmt;  // pattern is over only asserted statement tables (no reified)
	private boolean isReif;  // pattern is over only reified statement tables (no asserted)

	private List<SpecializedGraph> sources; // specialized graphs with triples for this pattern

    private char subsumed;

	public DBPattern ( Triple pat, Mapping varMap ) {
		pattern = pat;
		sources = new ArrayList<SpecializedGraph>();
		isBusy = false;
		isConnected = false;
		isStmt = isReif = false;
		S = nodeToElement( pattern.getSubject(), varMap );
		P = nodeToElement( pattern.getPredicate(), varMap );
		O = nodeToElement( pattern.getObject(), varMap );
		Scost = elementCost(S);
		Pcost = elementCost(P);
		Ocost = elementCost(O);
	}

    public void setBusy()
        { // pro tem, in case the old `isStaged` actually still meant something
        if (isBusy) throw new BrokenException( "a DBPattern can be made busy at most once" );
        isBusy = true;
        }

    public boolean isConnected()
        { return isConnected; }
	/**
		this nodeToElement is pretty much identical to that of
		graph.query.patternstagecompiler.compile.
	*/
	private Element nodeToElement( Node X, Mapping map )
		{
		if (X.equals( Query.ANY )) return Element.ANY;
		if (X.isVariable()) {
			if (map.hasBound(X))
				return new Bound (map.indexOf(X));
			else {
				freeVarCnt++;
				return new Free( X );
			}
		}
		return new Fixed( X );
		}

	public void sourceAdd( SpecializedGraph sg, char sub )
        {
        if (sources.isEmpty())
            {
            subsumed = sub;
            if (sg instanceof SpecializedGraphReifier_RDB) isReif = true;
            else isStmt = true;
            }
        else
            {
            if (subsumed != sub) throw new RDFRDBException( "Specialized graphs incorrectly subsume pattern" );
            if (sg instanceof SpecializedGraphReifier_RDB) isStmt = false;
            else isReif = false;
            }
        sources.add( sg );
        }

	public boolean hasSource()
        { return sources.size() > 0; }

    /**
        Answer true iff this pattern [currently] is associated with exactly one source.
    */
	public boolean isSingleSource()
        { return sources.size() == 1; }

    public SpecializedGraph singleSource() { return sources.get(0); }

	protected void addFreeVars ( List<VarDesc> varList ) {
		if (freeVarCnt > 0) {
			if (S instanceof Free)
				addVar(varList, (Free) S);
			if (P instanceof Free)
				addVar(varList, (Free) P);
			if (O instanceof Free)
				addVar(varList, (Free) O);
		}
	}

	private int findVar ( List<VarDesc> varList, Node_Variable var ) {
		for (int i = 0; i < varList.size(); i += 1 ) {
			Node_Variable v = varList.get(i).var;
			if (var.equals( v )) return i;
		}
		return -1;
	}

	private void addVar ( List<VarDesc> varList, Free var ) {
		int i = findVar(varList,var.var());
		if ( i < 0 ) {
			i = varList.size();
			VarDesc vx;
			if ( var.isArg() ) {
				vx = new VarDesc (var.var(), var.getMapping(), i);
			} else {
				vx = new VarDesc (var.var(), i);
			}
			varList.add(vx);
		}
		var.setListing(i);
	}

    /**
        currently, we can only join over the same table, and, in general, we
        can't join if the pattern has a predicate variable -- but, if we are only
        querying asserted stmts and the pattern is over asserted stmts, we can
        do the join.
    */
	public boolean joinsWith
        ( DBPattern other, List<VarDesc> varList, boolean onlyStmt, boolean onlyReif, boolean implicitJoin )
        {
        boolean includesSource = other.isSingleSource() && sources.contains( other.sources.get( 0 ) );
        boolean newSourceTest = sources.containsAll( other.sources );
        // if (includesSource != newSourceTest) System.err.println( ">> old source test: " + includesSource + ", but new source test: " + newSourceTest );
        if (includesSource && (!(P instanceof Free) || (onlyStmt && isStmt)))
            { // other has same source. See if there's a join variable.
            return
                appearsIn( S, varList )
                || appearsIn( O, varList )
                || (onlyStmt && isStmt && appearsIn( P, varList ))
                || (implicitJoin && shareFixedSubject( other ))
                ;
            }
        return false;
        }

    private boolean shareFixedSubject( DBPattern other )
        { // Yukk.
        boolean originalDefinition =
            S instanceof Fixed
            && other.S instanceof Fixed
            && S.match( (Domain) null, other.S.asNodeMatch( (Domain) null ) )
            ;
        return
            originalDefinition;
        }

    /**
     	Answer true iff e is a free variable that appears in
        varList.
    */
    private boolean appearsIn( Element e, List<VarDesc> varList )
        { return e instanceof Free && findVar( varList, ((Free) e).var() ) >= 0; }

	/**
	 * Return the relative cost of evaluating the pattern with the current.
	 * @return the relative cost.
	 */

	public int cost ( Mapping varMap ) {
		if ( costInit ) {
			costInit = false;
			costCur = costCalc();
		} else if ( freeVarCnt > 0 ) {
			// only recompute cost if there's a chance it changed.
			if ( anyBound(varMap) ) {
				costCur = costCalc();
			}
		}
		return costCur;
	}

	static final int costMax = 100;
	static final int costMin = 1;
	int costCur;

	private boolean costInit = true;
	private int freeVarCnt = 0;

	protected boolean isArgCheck ( Free v, Mapping map ) {
		int ix = map.lookUp( v.var() );
		if ( ix >= 0 ) {
			v.setIsArg( ix );
			isConnected = true;
			freeVarCnt -= 1;
			return true;
		} else
			return false;
	}

	protected boolean anyBound(Mapping map) {
		boolean res = false;
		if ( S instanceof Free )
			if ( isArgCheck((Free)S,map) ) {
				Scost = elementCost(S);
				res = true;
			}
		if ( P instanceof Free )
			if ( isArgCheck((Free)P,map) ) {
				Pcost = elementCost(P);
				res = true;
			}
		if ( O instanceof Free )
			if ( isArgCheck((Free)O,map) ) {
				Ocost = elementCost(O);
				res = true;
			}
		return res;
	}

	private int fixedCost = 0;
	private int boundCost = 0;
	private int unboundCost = 4;
	// private int unboundPredFactor = 4;

	private int elementCost ( Element x ) {
		if ( x instanceof Fixed )
			return fixedCost;
		else if ( x instanceof Bound )
			return boundCost;
		else if ( (x instanceof Free) && ((Free)x).isArg() )
			return boundCost;
		else
			return unboundCost;
	}

	/*
	 * compute the "estimated cost" to evaluate the pattern. in fact,
	 * it is just a relative ranking that favors patterns with bound
	 * nodes (FIXED or bound variables) over unbound nodes (unbound
	 * variables and ANY).
	 * @return int The estimated cost in the range [costmin,costMax).
	 */

	private int costCalc() {
		return Scost+Pcost+Ocost;
	}
}

/*
 * (c) Copyright 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


text:
class GameController < ApplicationController
  include ActionView::Helpers::TextHelper

  before_filter :set_params
  before_filter :get_game, :except => [:create]
  before_filter :calculate_round_and_ball, :only => [:update]

  def create
    @game = BowlingGame.create
    redirect_to show_game_url(@game.id.to_s, @round, @ball)
  end

  def update
    @game.attempt(@pins_down)
    @game.save
    if game_finished?
      redirect_to finished_game_url(@game.id.to_s)
    else
      flash[:notice] = get_notice(@pins_down)
      redirect_to show_game_url(@game.id.to_s, @round, @ball)
    end
  end

  def show
    if @ball > 1 && !extra_round?
      last_hit = @game.hits.last.to_i
      @pins_availables -=  last_hit if last_hit < 10
    end
  end

  def finished
  end

  private
  def game_finished?
    (@round == 11 && @ball == 1 && @pins_down < 10) ||
    (@round == 11 && @ball == 3)
  end

  def get_notice(pins_down)
    if strike? pins_down
      "STRIKE!"
    elsif spare? pins_down
      "SPARE!"
    else
      "#{pluralize(pins_down, 'pin')} knocked down."
    end
  end

  def spare?(pins_down)
    last_hit = @game.hits[-2].to_i
    strike?(pins_down + last_hit)
  end

  def calculate_round_and_ball
    if extra_round? && @pins_down >= 0
      @ball = @ball + 1
    elsif strike?(@pins_down) || @ball == 2
      @round = @round + 1
      @ball = 1
    elsif @pins_down >= 0
      @ball = @ball + 1
    end
  end

  def extra_round?
    @round == 11
  end

  def strike?(pins_down)
    pins_down == 10
  end

  def get_game
    @game = BowlingGame.find(params[:id]) rescue BowlingGame.new
  end

  def set_params
    @round = params[:round_id].present? ? params[:round_id].to_i : 1
    @ball =  params[:ball_id].present? ? params[:ball_id].to_i : 1
    @pins_down = params[:pins].present? ? params[:pins].to_i : -1
    @pins_availables = 10
  end

end


text:
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
 <env:Header/>
 <env:Body xmlns="urn:TestService">
	<mixedRequest>
      <string>foo</string>
      <request xmlns="http://codehaus.org/xfire/xmlbeans">
        <sessionId>foo</sessionId>
      </request>
	</mixedRequest>
 </env:Body>
</env:Envelope>


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using NBitcoin;
using WalletWasabi.Blockchain.Keys;

namespace WalletWasabi.WebClients.PayJoin
{
	public interface IPayjoinClient
	{
		Uri PaymentUrl { get; }

		Task<PSBT?> RequestPayjoin(PSBT originalTx, IHDKey accountKey, RootedKeyPath rootedKeyPath, HdPubKey changeHdPubKey, CancellationToken cancellationToken);
	}
}