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;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Xml;
using XmlNames = Roslyn.Utilities.DocumentationCommentXmlNames;

namespace Microsoft.CodeAnalysis.Shared.Utilities
{
    /// <summary>
    /// A documentation comment derived from either source text or metadata.
    /// </summary>
    internal sealed class DocumentationComment
    {
        /// <summary>
        /// True if an error occurred when parsing.
        /// </summary>
        public bool HadXmlParseError { get; private set; }

        /// <summary>
        /// The full XML text of this tag.
        /// </summary>
        public string FullXmlFragment { get; private set; }

        /// <summary>
        /// The text in the <example> tag. Null if no tag existed.
        /// </summary>
        public string ExampleText { get; private set; }

        /// <summary>
        /// The text in the <summary> tag. Null if no tag existed.
        /// </summary>
        public string SummaryText { get; private set; }

        /// <summary>
        /// The text in the <returns> tag. Null if no tag existed.
        /// </summary>
        public string ReturnsText { get; private set; }

        /// <summary>
        /// The text in the <value> tag. Null if no tag existed.
        /// </summary>
        public string ValueText { get; private set; }

        /// <summary>
        /// The text in the <remarks> tag. Null if no tag existed.
        /// </summary>
        public string RemarksText { get; private set; }

        /// <summary>
        /// The names of items in <param> tags.
        /// </summary>
        public ImmutableArray<string> ParameterNames { get; private set; }

        /// <summary>
        /// The names of items in <typeparam> tags.
        /// </summary>
        public ImmutableArray<string> TypeParameterNames { get; private set; }

        /// <summary>
        /// The types of items in <exception> tags.
        /// </summary>
        public ImmutableArray<string> ExceptionTypes { get; private set; }

        /// <summary>
        /// The item named in the <completionlist> tag's cref attribute.
        /// Null if the tag or cref attribute didn't exist.
        /// </summary>
        public string CompletionListCref { get; private set; }

        /// <summary>
        /// Used for <see cref="CommentBuilder.TrimEachLine"/> method, to prevent new allocation of string
        /// </summary>
        private static readonly string[] s_NewLineAsStringArray = new string[] { "\n" };

        private DocumentationComment()
        {
            ParameterNames = ImmutableArray<string>.Empty;
            TypeParameterNames = ImmutableArray<string>.Empty;
            ExceptionTypes = ImmutableArray<string>.Empty;
        }

        /// <summary>
        /// Cache of the most recently parsed fragment and the resulting DocumentationComment
        /// </summary>
        private static volatile DocumentationComment s_cacheLastXmlFragmentParse;

        /// <summary>
        /// Parses and constructs a <see cref="DocumentationComment" /> from the given fragment of XML.
        /// </summary>
        /// <param name="xml">The fragment of XML to parse.</param>
        /// <returns>A DocumentationComment instance.</returns>
        public static DocumentationComment FromXmlFragment(string xml)
        {
            var result = s_cacheLastXmlFragmentParse;
            if (result == null || result.FullXmlFragment != xml)
            {
                // Cache miss
                result = CommentBuilder.Parse(xml);
                s_cacheLastXmlFragmentParse = result;
            }

            return result;
        }

        /// <summary>
        /// Helper class for parsing XML doc comments. Encapsulates the state required during parsing.
        /// </summary>
        private class CommentBuilder
        {
            private readonly DocumentationComment _comment;
            private ImmutableArray<string>.Builder _parameterNamesBuilder;
            private ImmutableArray<string>.Builder _typeParameterNamesBuilder;
            private ImmutableArray<string>.Builder _exceptionTypesBuilder;
            private Dictionary<string, ImmutableArray<string>.Builder> _exceptionTextBuilders;

            /// <summary>
            /// Parse and construct a <see cref="DocumentationComment" /> from the given fragment of XML.
            /// </summary>
            /// <param name="xml">The fragment of XML to parse.</param>
            /// <returns>A DocumentationComment instance.</returns>
            public static DocumentationComment Parse(string xml)
            {
                try
                {
                    return new CommentBuilder(xml).ParseInternal(xml);
                }
                catch (Exception)
                {
                    // It would be nice if we only had to catch XmlException to handle invalid XML
                    // while parsing doc comments. Unfortunately, other exceptions can also occur,
                    // so we just catch them all. See Dev12 Bug 612456 for an example.
                    return new DocumentationComment { FullXmlFragment = xml, HadXmlParseError = true };
                }
            }

            private CommentBuilder(string xml)
            {
                _comment = new DocumentationComment() { FullXmlFragment = xml };
            }

            private DocumentationComment ParseInternal(string xml)
            {
                XmlFragmentParser.ParseFragment(xml, ParseCallback, this);

                if (_exceptionTextBuilders != null)
                {
                    foreach (var typeAndBuilderPair in _exceptionTextBuilders)
                    {
                        _comment._exceptionTexts.Add(typeAndBuilderPair.Key, typeAndBuilderPair.Value.AsImmutable());
                    }
                }

                _comment.ParameterNames = _parameterNamesBuilder == null ? ImmutableArray<string>.Empty : _parameterNamesBuilder.ToImmutable();
                _comment.TypeParameterNames = _typeParameterNamesBuilder == null ? ImmutableArray<string>.Empty : _typeParameterNamesBuilder.ToImmutable();
                _comment.ExceptionTypes = _exceptionTypesBuilder == null ? ImmutableArray<string>.Empty : _exceptionTypesBuilder.ToImmutable();

                return _comment;
            }

            private static void ParseCallback(XmlReader reader, CommentBuilder builder)
            {
                builder.ParseCallback(reader);
            }

            private string TrimEachLine(string text)
            {
                return string.Join(Environment.NewLine, text.Split(s_NewLineAsStringArray, StringSplitOptions.RemoveEmptyEntries).Select(i => i.Trim()));
            }

            private void ParseCallback(XmlReader reader)
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    var localName = reader.LocalName;
                    if (XmlNames.ElementEquals(localName, XmlNames.ExampleElementName) && _comment.ExampleText == null)
                    {
                        _comment.ExampleText = TrimEachLine(reader.ReadInnerXml());
                    }
                    else if (XmlNames.ElementEquals(localName, XmlNames.SummaryElementName) && _comment.SummaryText == null)
                    {
                        _comment.SummaryText = TrimEachLine(reader.ReadInnerXml());
                    }
                    else if (XmlNames.ElementEquals(localName, XmlNames.ReturnsElementName) && _comment.ReturnsText == null)
                    {
                        _comment.ReturnsText = TrimEachLine(reader.ReadInnerXml());
                    }
                    else if (XmlNames.ElementEquals(localName, XmlNames.ValueElementName) && _comment.ValueText == null)
                    {
                        _comment.ValueText = TrimEachLine(reader.ReadInnerXml());
                    }
                    else if (XmlNames.ElementEquals(localName, XmlNames.RemarksElementName) && _comment.RemarksText == null)
                    {
                        _comment.RemarksText = TrimEachLine(reader.ReadInnerXml());
                    }
                    else if (XmlNames.ElementEquals(localName, XmlNames.ParameterElementName))
                    {
                        var name = reader.GetAttribute(XmlNames.NameAttributeName);
                        var paramText = reader.ReadInnerXml();

                        if (!string.IsNullOrWhiteSpace(name) && !_comment._parameterTexts.ContainsKey(name))
                        {
                            (_parameterNamesBuilder ?? (_parameterNamesBuilder = ImmutableArray.CreateBuilder<string>())).Add(name);
                            _comment._parameterTexts.Add(name, TrimEachLine(paramText));
                        }
                    }
                    else if (XmlNames.ElementEquals(localName, XmlNames.TypeParameterElementName))
                    {
                        var name = reader.GetAttribute(XmlNames.NameAttributeName);
                        var typeParamText = reader.ReadInnerXml();

                        if (!string.IsNullOrWhiteSpace(name) && !_comment._typeParameterTexts.ContainsKey(name))
                        {
                            (_typeParameterNamesBuilder ?? (_typeParameterNamesBuilder = ImmutableArray.CreateBuilder<string>())).Add(name);
                            _comment._typeParameterTexts.Add(name, TrimEachLine(typeParamText));
                        }
                    }
                    else if (XmlNames.ElementEquals(localName, XmlNames.ExceptionElementName))
                    {
                        var type = reader.GetAttribute(XmlNames.CrefAttributeName);
                        var exceptionText = reader.ReadInnerXml();

                        if (!string.IsNullOrWhiteSpace(type))
                        {
                            if (_exceptionTextBuilders == null || !_exceptionTextBuilders.ContainsKey(type))
                            {
                                (_exceptionTypesBuilder ?? (_exceptionTypesBuilder = ImmutableArray.CreateBuilder<string>())).Add(type);
                                (_exceptionTextBuilders ?? (_exceptionTextBuilders = new Dictionary<string, ImmutableArray<string>.Builder>())).Add(type, ImmutableArray.CreateBuilder<string>());
                            }

                            _exceptionTextBuilders[type].Add(exceptionText);
                        }
                    }
                    else if (XmlNames.ElementEquals(localName, XmlNames.CompletionListElementName))
                    {
                        var cref = reader.GetAttribute(XmlNames.CrefAttributeName);
                        if (!string.IsNullOrWhiteSpace(cref))
                        {
                            _comment.CompletionListCref = cref;
                        }

                        reader.ReadInnerXml();
                    }
                    else
                    {
                        // This is an element we don't handle. Skip it.
                        reader.Read();
                    }
                }
                else
                {
                    // We came across something that isn't a start element, like a block of text.
                    // Skip it.
                    reader.Read();
                }
            }
        }

        private readonly Dictionary<string, string> _parameterTexts = new Dictionary<string, string>();
        private readonly Dictionary<string, string> _typeParameterTexts = new Dictionary<string, string>();
        private readonly Dictionary<string, ImmutableArray<string>> _exceptionTexts = new Dictionary<string, ImmutableArray<string>>();

        /// <summary>
        /// Returns the text for a given parameter, or null if no documentation was given for the parameter.
        /// </summary>
        public string GetParameterText(string parameterName)
        {
            _parameterTexts.TryGetValue(parameterName, out var text);
            return text;
        }

        /// <summary>
        /// Returns the text for a given type parameter, or null if no documentation was given for the type parameter.
        /// </summary>
        public string GetTypeParameterText(string typeParameterName)
        {
            _typeParameterTexts.TryGetValue(typeParameterName, out var text);
            return text;
        }

        /// <summary>
        /// Returns the texts for a given exception, or an empty <see cref="ImmutableArray"/> if no documentation was given for the exception.
        /// </summary>
        public ImmutableArray<string> GetExceptionTexts(string exceptionName)
        {
            _exceptionTexts.TryGetValue(exceptionName, out var texts);

            if (texts.IsDefault)
            {
                // If the exception wasn't found, TryGetValue will set "texts" to a default value.
                // To be friendly, we want to return an empty array rather than a null array.
                texts = ImmutableArray.Create<string>();
            }

            return texts;
        }

        /// <summary>
        /// An empty comment.
        /// </summary>
        public static readonly DocumentationComment Empty = new DocumentationComment();
    }
}


text:
"""Falcon API class."""

class API(object):

    def add_route(self, uri_template, resource, **kwargs):
        pass

    def add_sink(self, sink, prefix=r'/'):
        pass

    def add_error_handler(self, exception, handler=None):
        pass

redpajama_set_name: RedPajamaGithub


text:
package storm.cookbook.tfidf.functions;

import backtype.storm.tuple.Values;
import storm.trident.tuple.TridentTuple;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * User: domenicosolazzo
 */
public class OuterJoinState {
    //2 columns, based on streamId. Each column contains the tuples from the given stream
    private HashMap<Integer, List<Object[]>> bothSides = new HashMap<Integer,List<Object[]>>();

    public void addValues(int streamId, TridentTuple input){
        if(!bothSides.keySet().contains(streamId)){
            if(bothSides.keySet().size() >= 2)
                throw new IllegalArgumentException("Outer join can only be performed between 2 streams");
            bothSides.put(streamId, new ArrayList<Object[]>());
        }
        bothSides.get(streamId).add(input.toArray());
    }

    //the shorter side is the LHS
    private int getLHS(){
        int len = Integer.MAX_VALUE;
        int index = 0;
        for(int id : bothSides.keySet()){
            if(bothSides.get(id).size() < len){
                len = bothSides.get(id).size();
                index = id;
            }
        }
        return index;
    }

    private int getRhs(int lhs){
        for(int test : bothSides.keySet()){
            if(test != lhs)
                return test;
        }
        throw new IllegalArgumentException("Can't find RHS!");
    }

    public List<Values> join(){
        List<Values> ret = new ArrayList<Values>();
        try{
            int lhsId = getLHS();
            int rhsId = getRhs(lhsId);
            for(Object[] lhs : bothSides.get(lhsId)){
                for(Object[] rhs : bothSides.get(rhsId)){
                    Values vals = new Values(lhs);
                    vals.addAll(Arrays.asList(rhs));
                    ret.add(vals);
                }
            }
        }catch(Exception e){}
        return ret;
    }

}


text:
using System;
using System.Collections.Generic;
using Csla;
using ProjectsVendors.DataAccess;

namespace ProjectsVendors.Business
{

    ///
    /// VendorCollection (editable child list).

    /// This is a generated <see cref="VendorCollection"/> business object.
    ///
    /// <remarks>
    /// This class is child of <see cref="ProjectEdit"/> editable root object.

    /// The items of the collection are <see cref="VendorItem"/> objects.
    /// </remarks>
    [Serializable]
#if WINFORMS
    public partial class VendorCollection : BusinessBindingListBase<VendorCollection, VendorItem>
#else
    public partial class VendorCollection : BusinessListBase<VendorCollection, VendorItem>
#endif
    {

        #region Collection Business Methods

        ///
        /// Removes a <see cref="VendorItem"/> item from the collection.
        ///
        /// <param name="vendorId">The VendorId of the item to be removed.</param>
        public void Remove(int vendorId)
        {
            foreach (var vendorItem in this)
            {
                if (vendorItem.VendorId == vendorId)
                {
                    Remove(vendorItem);
                    break;
                }
            }
        }

        ///
        /// Determines whether a <see cref="VendorItem"/> item is in the collection.
        ///
        /// <param name="vendorId">The VendorId of the item to search for.</param>
        /// <returns><c>true</c> if the VendorItem is a collection item; otherwise, <c>false</c>.</returns>
        public bool Contains(int vendorId)
        {
            foreach (var vendorItem in this)
            {
                if (vendorItem.VendorId == vendorId)
                {
                    return true;
                }
            }
            return false;
        }

        ///
        /// Determines whether a <see cref="VendorItem"/> item is in the collection's DeletedList.
        ///
        /// <param name="vendorId">The VendorId of the item to search for.</param>
        /// <returns><c>true</c> if the VendorItem is a deleted collection item; otherwise, <c>false</c>.</returns>
        public bool ContainsDeleted(int vendorId)
        {
            foreach (var vendorItem in DeletedList)
            {
                if (vendorItem.VendorId == vendorId)
                {
                    return true;
                }
            }
            return false;
        }

        #endregion

        #region Constructor

        ///
        /// Initializes a new instance of the <see cref="VendorCollection"/> class.
        ///
        /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
        [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
        public VendorCollection()
        {
            // Use factory methods and do not use direct creation.

            // show the framework that this is a child object
            MarkAsChild();

            var rlce = RaiseListChangedEvents;
            RaiseListChangedEvents = false;
            AllowNew = true;
            AllowEdit = true;
            AllowRemove = true;
            RaiseListChangedEvents = rlce;
        }

        #endregion

        #region Data Access

        ///
        /// Loads a <see cref="VendorCollection"/> collection from the database, based on given criteria.
        ///
        /// <param name="projectId">The Project Id.</param>
        protected void DataPortal_Fetch(int projectId)
        {
            var args = new DataPortalHookArgs(projectId);
            OnFetchPre(args);
            using (var dalManager = DalFactoryProjectsVendors.GetManager())
            {
                var dal = dalManager.GetProvider<IVendorCollectionDal>();
                var data = dal.Fetch(projectId);
                Fetch(data);
            }
            OnFetchPost(args);
        }

        ///
        /// Loads all <see cref="VendorCollection"/> collection items from the given list of VendorItemDto.
        ///
        /// <param name="data">The list of <see cref="VendorItemDto"/>.</param>
        private void Fetch(List<VendorItemDto> data)
        {
            var rlce = RaiseListChangedEvents;
            RaiseListChangedEvents = false;
            foreach (var dto in data)
            {
                Add(DataPortal.FetchChild<VendorItem>(dto));
            }
            RaiseListChangedEvents = rlce;
        }

        #endregion

        #region DataPortal Hooks

        ///
        /// Occurs after setting query parameters and before the fetch operation.
        ///
        partial void OnFetchPre(DataPortalHookArgs args);

        ///
        /// Occurs after the fetch operation (object or collection is fully loaded and set up).
        ///
        partial void OnFetchPost(DataPortalHookArgs args);

        #endregion

    }
}


text:
var Store = require("local-store")
    , reductions = require("reducers/reductions")
    , patch = require("diffpatcher/patch")
    , compound = require("compound")

    , state = require("./reflex/state")
    , Writer = require("./reflex/writer")

/*
    The persistance is a composition of a

        - fork (fork the changes into states)
        - writer. Open the store & write to it for each new
            state
        - reader. Return the initial state
*/
module.exports = (compound)
    (states)
    (Writer(swap, open))
    (read)

function read(store) {
    return store.get("state")
}

function swap(store, current) {
    delete current.operation
    // console.log("persisting", current)
    store.set("state", current)
}

function open() {
    return Store("reflex-todo")
}

function states(changes) {
    return reductions(changes, patch, state())
}


text:
---
uid: SolidEdgeAssembly.Occurrence.GetMatrix(System.Array@)
summary:
remarks:
syntax:
    parameters:
    - id: Matrix
      description: Returns the 4x4 array that specifies the position and orientation of the part. This is a single-dimension Double array that contains 16 elements.
example: [*content]
---
[!code-vb[Main](..\snippets\SolidEdgeAssembly.Occurrence.GetMatrix.vb]
[!code-csharp[Main](..\snippets\SolidEdgeAssembly.Occurrence.GetMatrix.cs]


text:
package esapi

import (
	"context"
	"net/http"
	"strings"
)

func newCCRPauseFollowFunc(t Transport) CCRPauseFollow {
	return func(index string, o ...func(*CCRPauseFollowRequest)) (*Response, error) {
		var r = CCRPauseFollowRequest{Index: index}
		for _, f := range o {
			f(&r)
		}
		return r.Do(r.ctx, t)
	}
}

// ----- API Definition -------------------------------------------------------

// CCRPauseFollow - Pauses a follower index. The follower index will not fetch any additional operations from the leader index.
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/current/ccr-post-pause-follow.html.
//
type CCRPauseFollow func(index string, o ...func(*CCRPauseFollowRequest)) (*Response, error)

// CCRPauseFollowRequest configures the CCR Pause Follow API request.
//
type CCRPauseFollowRequest struct {
	Index string

	Pretty     bool
	Human      bool
	ErrorTrace bool
	FilterPath []string

	Header http.Header

	ctx context.Context
}

// Do executes the request and returns response or error.
//
func (r CCRPauseFollowRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
	var (
		method string
		path   strings.Builder
		params map[string]string
	)

	method = "POST"

	path.Grow(1 + len(r.Index) + 1 + len("_ccr") + 1 + len("pause_follow"))
	path.WriteString("/")
	path.WriteString(r.Index)
	path.WriteString("/")
	path.WriteString("_ccr")
	path.WriteString("/")
	path.WriteString("pause_follow")

	params = make(map[string]string)

	if r.Pretty {
		params["pretty"] = "true"
	}

	if r.Human {
		params["human"] = "true"
	}

	if r.ErrorTrace {
		params["error_trace"] = "true"
	}

	if len(r.FilterPath) > 0 {
		params["filter_path"] = strings.Join(r.FilterPath, ",")
	}

	req, err := newRequest(method, path.String(), nil)
	if err != nil {
		return nil, err
	}

	if len(params) > 0 {
		q := req.URL.Query()
		for k, v := range params {
			q.Set(k, v)
		}
		req.URL.RawQuery = q.Encode()
	}

	if len(r.Header) > 0 {
		if len(req.Header) == 0 {
			req.Header = r.Header
		} else {
			for k, vv := range r.Header {
				for _, v := range vv {
					req.Header.Add(k, v)
				}
			}
		}
	}

	if ctx != nil {
		req = req.WithContext(ctx)
	}

	res, err := transport.Perform(req)
	if err != nil {
		return nil, err
	}

	response := Response{
		StatusCode: res.StatusCode,
		Body:       res.Body,
		Header:     res.Header,
	}

	return &response, nil
}

// WithContext sets the request context.
//
func (f CCRPauseFollow) WithContext(v context.Context) func(*CCRPauseFollowRequest) {
	return func(r *CCRPauseFollowRequest) {
		r.ctx = v
	}
}

// WithPretty makes the response body pretty-printed.
//
func (f CCRPauseFollow) WithPretty() func(*CCRPauseFollowRequest) {
	return func(r *CCRPauseFollowRequest) {
		r.Pretty = true
	}
}

// WithHuman makes statistical values human-readable.
//
func (f CCRPauseFollow) WithHuman() func(*CCRPauseFollowRequest) {
	return func(r *CCRPauseFollowRequest) {
		r.Human = true
	}
}

// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f CCRPauseFollow) WithErrorTrace() func(*CCRPauseFollowRequest) {
	return func(r *CCRPauseFollowRequest) {
		r.ErrorTrace = true
	}
}

// WithFilterPath filters the properties of the response body.
//
func (f CCRPauseFollow) WithFilterPath(v ...string) func(*CCRPauseFollowRequest) {
	return func(r *CCRPauseFollowRequest) {
		r.FilterPath = v
	}
}

// WithHeader adds the headers to the HTTP request.
//
func (f CCRPauseFollow) WithHeader(h map[string]string) func(*CCRPauseFollowRequest) {
	return func(r *CCRPauseFollowRequest) {
		if r.Header == nil {
			r.Header = make(http.Header)
		}
		for k, v := range h {
			r.Header.Add(k, v)
		}
	}
}

// WithOpaqueID adds the X-Opaque-Id header to the HTTP request.
//
func (f CCRPauseFollow) WithOpaqueID(s string) func(*CCRPauseFollowRequest) {
	return func(r *CCRPauseFollowRequest) {
		if r.Header == nil {
			r.Header = make(http.Header)
		}
		r.Header.Set("X-Opaque-Id", s)
	}
}


text:
import { nu as NuSpotInfo } from '../view/SpotInfo';
import { Bubble } from './Bubble';
import * as Direction from './Direction';
import { AnchorBoxBounds, boundsRestriction } from './LayoutBounds';
import { AnchorBox, AnchorElement, AnchorLayout } from './LayoutTypes';
import { Placement, getPlacement } from './Placement';

/*
  Layouts for things that overlay over the anchor element/box. These are designed to mirror
  the `Layout` logic.

  As an example `Layout.north` will appear horizontally centered above the anchor, whereas
  `LayoutInset.north` will appear horizontally centered overlapping the top of the anchor.
 */

const labelPrefix = 'layout-inset';

// returns left edge of anchor - used to display element to the left, left edge against the anchor
const westEdgeX = (anchor: AnchorBox): number => anchor.x;

// returns middle of anchor minus half the element width - used to horizontally centre element to the anchor
const middleX = (anchor: AnchorBox, element: AnchorElement): number => anchor.x + (anchor.width / 2) - (element.width / 2);

// returns right edge of anchor minus element width - used to display element to the right, right edge against the anchor
const eastEdgeX = (anchor: AnchorBox, element: AnchorElement): number => anchor.x + anchor.width - element.width;

// returns top edge - used to display element to the top, top edge against the anchor
const northY = (anchor: AnchorBox): number => anchor.y;

// returns bottom edge minus element height - used to display element at the bottom, bottom edge against the anchor
const southY = (anchor: AnchorBox, element: AnchorElement): number => anchor.y + anchor.height - element.height;

// returns centre of anchor minus half the element height - used to vertically centre element to the anchor
const centreY = (anchor: AnchorBox, element: AnchorElement): number => anchor.y + (anchor.height / 2) - (element.height / 2);

// positions element relative to the bottom right of the anchor
const southwest: AnchorLayout = (anchor: AnchorBox, element: AnchorElement, bubbles: Bubble) => NuSpotInfo(
  eastEdgeX(anchor, element),
  southY(anchor, element),
  bubbles.insetSouthwest(),
  Direction.northwest(),
  Placement.Southwest,
  boundsRestriction(anchor, { right: AnchorBoxBounds.RightEdge, bottom: AnchorBoxBounds.BottomEdge }),
  labelPrefix
);

// positions element relative to the bottom left of the anchor
const southeast: AnchorLayout = (anchor: AnchorBox, element: AnchorElement, bubbles: Bubble) => NuSpotInfo(
  westEdgeX(anchor),
  southY(anchor, element),
  bubbles.insetSoutheast(),
  Direction.northeast(),
  Placement.Southeast,
  boundsRestriction(anchor, { left: AnchorBoxBounds.LeftEdge, bottom: AnchorBoxBounds.BottomEdge }),
  labelPrefix
);

// positions element relative to the top right of the anchor
const northwest: AnchorLayout = (anchor: AnchorBox, element: AnchorElement, bubbles: Bubble) => NuSpotInfo(
  eastEdgeX(anchor, element),
  northY(anchor),
  bubbles.insetNorthwest(),
  Direction.southwest(),
  Placement.Northwest,
  boundsRestriction(anchor, { right: AnchorBoxBounds.RightEdge, top: AnchorBoxBounds.TopEdge }),
  labelPrefix
);

// positions element relative to the top left of the anchor
const northeast: AnchorLayout = (anchor: AnchorBox, element: AnchorElement, bubbles: Bubble) => NuSpotInfo(
  westEdgeX(anchor),
  northY(anchor),
  bubbles.insetNortheast(),
  Direction.southeast(),
  Placement.Northeast,
  boundsRestriction(anchor, { left: AnchorBoxBounds.LeftEdge, top: AnchorBoxBounds.TopEdge }),
  labelPrefix
);

// positions element relative to the top of the anchor, horizontally centered
const north: AnchorLayout = (anchor: AnchorBox, element: AnchorElement, bubbles: Bubble) => NuSpotInfo(
  middleX(anchor, element),
  northY(anchor),
  bubbles.insetNorth(),
  Direction.south(),
  Placement.North,
  boundsRestriction(anchor, { top: AnchorBoxBounds.TopEdge }),
  labelPrefix
);

// positions element relative to the bottom of the anchor, horizontally centered
const south: AnchorLayout = (anchor: AnchorBox, element: AnchorElement, bubbles: Bubble) => NuSpotInfo(
  middleX(anchor, element),
  southY(anchor, element),
  bubbles.insetSouth(),
  Direction.north(),
  Placement.South,
  boundsRestriction(anchor, { bottom: AnchorBoxBounds.BottomEdge }),
  labelPrefix
);

// positions element with the right edge against the anchor, vertically centered
const east: AnchorLayout = (anchor: AnchorBox, element: AnchorElement, bubbles: Bubble) => NuSpotInfo(
  eastEdgeX(anchor, element),
  centreY(anchor, element),
  bubbles.insetEast(),
  Direction.west(),
  Placement.East,
  boundsRestriction(anchor, { right: AnchorBoxBounds.RightEdge }),
  labelPrefix
);

// positions element with the left each against the anchor, vertically centered
const west: AnchorLayout = (anchor: AnchorBox, element: AnchorElement, bubbles: Bubble) => NuSpotInfo(
  westEdgeX(anchor),
  centreY(anchor, element),
  bubbles.insetWest(),
  Direction.east(),
  Placement.West,
  boundsRestriction(anchor, { left: AnchorBoxBounds.LeftEdge }),
  labelPrefix
);

const all = (): AnchorLayout[] => [ southeast, southwest, northeast, northwest, south, north, east, west ];
const allRtl = (): AnchorLayout[] => [ southwest, southeast, northwest, northeast, south, north, east, west ];

const lookupPreserveLayout = (lastPlacement: Placement) => {
  switch (lastPlacement) {
    case Placement.North:
      return north;
    case Placement.Northeast:
      return northeast;
    case Placement.Northwest:
      return northwest;
    case Placement.South:
      return south;
    case Placement.Southeast:
      return southeast;
    case Placement.Southwest:
      return southwest;
    case Placement.East:
      return east;
    case Placement.West:
      return west;
  }
};

const preserve: AnchorLayout = (anchor, element, bubbles, placee, bounds) => {
  const layout = getPlacement(placee).map(lookupPreserveLayout).getOr(north);
  return layout(anchor, element, bubbles, placee, bounds);
};

const lookupFlippedLayout = (lastPlacement: Placement) => {
  switch (lastPlacement) {
    case Placement.North:
      return south;
    case Placement.Northeast:
      return southeast;
    case Placement.Northwest:
      return southwest;
    case Placement.South:
      return north;
    case Placement.Southeast:
      return northeast;
    case Placement.Southwest:
      return northwest;
    case Placement.East:
      return west;
    case Placement.West:
      return east;
  }
};

const flip: AnchorLayout = (anchor, element, bubbles, placee, bounds) => {
  const layout = getPlacement(placee).map(lookupFlippedLayout).getOr(north);
  return layout(anchor, element, bubbles, placee, bounds);
};

export {
  southeast,
  northeast,
  southwest,
  northwest,
  south,
  north,
  east,
  west,
  all,
  allRtl,
  preserve,
  flip
};


text:
package org.apache.cassandra.db;

import com.google.common.base.Charsets;

import org.apache.cassandra.OrderedJUnit4ClassRunner;
import org.apache.cassandra.Util;
import org.apache.cassandra.cache.ChunkCache;
import org.apache.cassandra.UpdateBuilder;
import org.apache.cassandra.db.compaction.CompactionManager;
import org.apache.cassandra.db.compaction.Verifier;
import org.apache.cassandra.db.marshal.UUIDType;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.exceptions.WriteTimeoutException;
import org.apache.cassandra.io.FSWriteError;
import org.apache.cassandra.io.sstable.Component;
import org.apache.cassandra.io.sstable.CorruptSSTableException;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.schema.CompressionParams;
import org.apache.cassandra.schema.KeyspaceParams;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.commons.lang3.StringUtils;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.*;
import java.nio.file.Files;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;

import static org.apache.cassandra.SchemaLoader.counterCFMD;
import static org.apache.cassandra.SchemaLoader.createKeyspace;
import static org.apache.cassandra.SchemaLoader.loadSchema;
import static org.apache.cassandra.SchemaLoader.standardCFMD;
import static org.junit.Assert.fail;

@RunWith(OrderedJUnit4ClassRunner.class)
public class VerifyTest
{
    public static final String KEYSPACE = "Keyspace1";
    public static final String CF = "Standard1";
    public static final String CF2 = "Standard2";
    public static final String CF3 = "Standard3";
    public static final String CF4 = "Standard4";
    public static final String COUNTER_CF = "Counter1";
    public static final String COUNTER_CF2 = "Counter2";
    public static final String COUNTER_CF3 = "Counter3";
    public static final String COUNTER_CF4 = "Counter4";
    public static final String CORRUPT_CF = "Corrupt1";
    public static final String CORRUPT_CF2 = "Corrupt2";
    public static final String CORRUPTCOUNTER_CF = "CounterCorrupt1";
    public static final String CORRUPTCOUNTER_CF2 = "CounterCorrupt2";

    public static final String CF_UUID = "UUIDKeys";

    @BeforeClass
    public static void defineSchema() throws ConfigurationException
    {
        CompressionParams compressionParameters = CompressionParams.snappy(32768);

        loadSchema();
        createKeyspace(KEYSPACE,
                       KeyspaceParams.simple(1),
                       standardCFMD(KEYSPACE, CF).compression(compressionParameters),
                       standardCFMD(KEYSPACE, CF2).compression(compressionParameters),
                       standardCFMD(KEYSPACE, CF3),
                       standardCFMD(KEYSPACE, CF4),
                       standardCFMD(KEYSPACE, CORRUPT_CF),
                       standardCFMD(KEYSPACE, CORRUPT_CF2),
                       counterCFMD(KEYSPACE, COUNTER_CF).compression(compressionParameters),
                       counterCFMD(KEYSPACE, COUNTER_CF2).compression(compressionParameters),
                       counterCFMD(KEYSPACE, COUNTER_CF3),
                       counterCFMD(KEYSPACE, COUNTER_CF4),
                       counterCFMD(KEYSPACE, CORRUPTCOUNTER_CF),
                       counterCFMD(KEYSPACE, CORRUPTCOUNTER_CF2),
                       standardCFMD(KEYSPACE, CF_UUID, 0, UUIDType.instance));
    }

    @Test
    public void testVerifyCorrect() throws IOException
    {
        CompactionManager.instance.disableAutoCompaction();
        Keyspace keyspace = Keyspace.open(KEYSPACE);
        ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF);

        fillCF(cfs, 2);

        SSTableReader sstable = cfs.getLiveSSTables().iterator().next();

        try (Verifier verifier = new Verifier(cfs, sstable, false))
        {
            verifier.verify(false);
        }
        catch (CorruptSSTableException err)
        {
            fail("Unexpected CorruptSSTableException");
        }
    }

    @Test
    public void testVerifyCounterCorrect() throws IOException
    {
        CompactionManager.instance.disableAutoCompaction();
        Keyspace keyspace = Keyspace.open(KEYSPACE);
        ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(COUNTER_CF);

        fillCounterCF(cfs, 2);

        SSTableReader sstable = cfs.getLiveSSTables().iterator().next();

        try (Verifier verifier = new Verifier(cfs, sstable, false))
        {
            verifier.verify(false);
        }
        catch (CorruptSSTableException err)
        {
            fail("Unexpected CorruptSSTableException");
        }
    }

    @Test
    public void testExtendedVerifyCorrect() throws IOException
    {
        CompactionManager.instance.disableAutoCompaction();
        Keyspace keyspace = Keyspace.open(KEYSPACE);
        ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF2);

        fillCF(cfs, 2);

        SSTableReader sstable = cfs.getLiveSSTables().iterator().next();

        try (Verifier verifier = new Verifier(cfs, sstable, false))
        {
            verifier.verify(true);
        }
        catch (CorruptSSTableException err)
        {
            fail("Unexpected CorruptSSTableException");
        }
    }

    @Test
    public void testExtendedVerifyCounterCorrect() throws IOException
    {
        CompactionManager.instance.disableAutoCompaction();
        Keyspace keyspace = Keyspace.open(KEYSPACE);
        ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(COUNTER_CF2);

        fillCounterCF(cfs, 2);

        SSTableReader sstable = cfs.getLiveSSTables().iterator().next();

        try (Verifier verifier = new Verifier(cfs, sstable, false))
        {
            verifier.verify(true);
        }
        catch (CorruptSSTableException err)
        {
            fail("Unexpected CorruptSSTableException");
        }
    }

    @Test
    public void testVerifyCorrectUncompressed() throws IOException
    {
        CompactionManager.instance.disableAutoCompaction();
        Keyspace keyspace = Keyspace.open(KEYSPACE);
        ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF3);

        fillCF(cfs, 2);

        SSTableReader sstable = cfs.getLiveSSTables().iterator().next();

        try (Verifier verifier = new Verifier(cfs, sstable, false))
        {
            verifier.verify(false);
        }
        catch (CorruptSSTableException err)
        {
            fail("Unexpected CorruptSSTableException");
        }
    }

    @Test
    public void testVerifyCounterCorrectUncompressed() throws IOException
    {
        CompactionManager.instance.disableAutoCompaction();
        Keyspace keyspace = Keyspace.open(KEYSPACE);
        ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(COUNTER_CF3);

        fillCounterCF(cfs, 2);

        SSTableReader sstable = cfs.getLiveSSTables().iterator().next();

        try (Verifier verifier = new Verifier(cfs, sstable, false))
        {
            verifier.verify(false);
        }
        catch (CorruptSSTableException err)
        {
            fail("Unexpected CorruptSSTableException");
        }
    }

    @Test
    public void testExtendedVerifyCorrectUncompressed() throws IOException
    {
        CompactionManager.instance.disableAutoCompaction();
        Keyspace keyspace = Keyspace.open(KEYSPACE);
        ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF4);

        fillCF(cfs, 2);

        SSTableReader sstable = cfs.getLiveSSTables().iterator().next();

        try (Verifier verifier = new Verifier(cfs, sstable, false))
        {
            verifier.verify(true);
        }
        catch (CorruptSSTableException err)
        {
            fail("Unexpected CorruptSSTableException");
        }
    }

    @Test
    public void testExtendedVerifyCounterCorrectUncompressed() throws IOException
    {
        CompactionManager.instance.disableAutoCompaction();
        Keyspace keyspace = Keyspace.open(KEYSPACE);
        ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(COUNTER_CF4);

        fillCounterCF(cfs, 2);

        SSTableReader sstable = cfs.getLiveSSTables().iterator().next();

        try (Verifier verifier = new Verifier(cfs, sstable, false))
        {
            verifier.verify(true);
        }
        catch (CorruptSSTableException err)
        {
            fail("Unexpected CorruptSSTableException");
        }
    }

    @Test
    public void testVerifyIncorrectDigest() throws IOException, WriteTimeoutException
    {
        CompactionManager.instance.disableAutoCompaction();
        Keyspace keyspace = Keyspace.open(KEYSPACE);
        ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CORRUPT_CF);

        fillCF(cfs, 2);

        Util.getAll(Util.cmd(cfs).build());

        SSTableReader sstable = cfs.getLiveSSTables().iterator().next();

        try (RandomAccessFile file = new RandomAccessFile(sstable.descriptor.filenameFor(Component.DIGEST), "rw"))
        {
            Long correctChecksum = Long.valueOf(file.readLine());

            writeChecksum(++correctChecksum, sstable.descriptor.filenameFor(Component.DIGEST));
        }

        try (Verifier verifier = new Verifier(cfs, sstable, false))
        {
            verifier.verify(false);
            fail("Expected a CorruptSSTableException to be thrown");
        }
        catch (CorruptSSTableException err) {}
    }

    @Test
    public void testVerifyCorruptRowCorrectDigest() throws IOException, WriteTimeoutException
    {
        CompactionManager.instance.disableAutoCompaction();
        Keyspace keyspace = Keyspace.open(KEYSPACE);
        ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CORRUPT_CF2);

        fillCF(cfs, 2);

        Util.getAll(Util.cmd(cfs).build());

        SSTableReader sstable = cfs.getLiveSSTables().iterator().next();

        // overwrite one row with garbage
        long row0Start = sstable.getPosition(PartitionPosition.ForKey.get(ByteBufferUtil.bytes("0"), cfs.getPartitioner()), SSTableReader.Operator.EQ).position;
        long row1Start = sstable.getPosition(PartitionPosition.ForKey.get(ByteBufferUtil.bytes("1"), cfs.getPartitioner()), SSTableReader.Operator.EQ).position;
        long startPosition = row0Start < row1Start ? row0Start : row1Start;
        long endPosition = row0Start < row1Start ? row1Start : row0Start;

        RandomAccessFile file = new RandomAccessFile(sstable.getFilename(), "rw");
        file.seek(startPosition);
        file.writeBytes(StringUtils.repeat('z', (int) 2));
        file.close();
        if (ChunkCache.instance != null)
            ChunkCache.instance.invalidateFile(sstable.getFilename());

        // Update the Digest to have the right Checksum
        writeChecksum(simpleFullChecksum(sstable.getFilename()), sstable.descriptor.filenameFor(Component.DIGEST));

        try (Verifier verifier = new Verifier(cfs, sstable, false))
        {
            // First a simple verify checking digest, which should succeed
            try
            {
                verifier.verify(false);
            }
            catch (CorruptSSTableException err)
            {
                fail("Simple verify should have succeeded as digest matched");
            }

            // Now try extended verify
            try
            {
                verifier.verify(true);

            }
            catch (CorruptSSTableException err)
            {
                return;
            }
            fail("Expected a CorruptSSTableException to be thrown");
        }
    }

    @Test(expected = CorruptSSTableException.class)
    public void testVerifyBrokenSSTableMetadata() throws IOException, WriteTimeoutException
    {
        CompactionManager.instance.disableAutoCompaction();
        Keyspace keyspace = Keyspace.open(KEYSPACE);
        ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CORRUPT_CF2);

        fillCF(cfs, 2);

        Util.getAll(Util.cmd(cfs).build());

        SSTableReader sstable = cfs.getLiveSSTables().iterator().next();

        String filenameToCorrupt = sstable.descriptor.filenameFor(Component.STATS);
        RandomAccessFile file = new RandomAccessFile(filenameToCorrupt, "rw");
        file.seek(0);
        file.writeBytes(StringUtils.repeat('z', 2));
        file.close();

        try (Verifier verifier = new Verifier(cfs, sstable, false))
        {
            verifier.verify(false);
        }
    }

    protected void fillCF(ColumnFamilyStore cfs, int partitionsPerSSTable)
    {
        for (int i = 0; i < partitionsPerSSTable; i++)
        {
            UpdateBuilder.create(cfs.metadata(), String.valueOf(i))
                         .newRow("c1").add("val", "1")
                         .newRow("c2").add("val", "2")
                         .apply();
        }

        cfs.forceBlockingFlush();
    }

    protected void fillCounterCF(ColumnFamilyStore cfs, int partitionsPerSSTable) throws WriteTimeoutException
    {
        for (int i = 0; i < partitionsPerSSTable; i++)
        {
            UpdateBuilder.create(cfs.metadata(), String.valueOf(i))
                         .newRow("c1").add("val", 100L)
                         .apply();
        }

        cfs.forceBlockingFlush();
    }

    protected long simpleFullChecksum(String filename) throws IOException
    {
        try (FileInputStream inputStream = new FileInputStream(filename))
        {
            CRC32 checksum = new CRC32();
            CheckedInputStream cinStream = new CheckedInputStream(inputStream, checksum);
            byte[] b = new byte[128];
            while (cinStream.read(b) >= 0) {
            }
            return cinStream.getChecksum().getValue();
        }
    }

    protected void writeChecksum(long checksum, String filePath)
    {
        File outFile = new File(filePath);
        BufferedWriter out = null;
        try
        {
            out = Files.newBufferedWriter(outFile.toPath(), Charsets.UTF_8);
            out.write(String.valueOf(checksum));
            out.flush();
            out.close();
        }
        catch (IOException e)
        {
            throw new FSWriteError(e, outFile);
        }
        finally
        {
            FileUtils.closeQuietly(out);
        }

    }

}


text:
namespace Benchmark {
    template<typename KeyType>
    void sort_by_algorithm(Benchmark::Algorithm::Value algorithm, bool keys_only, std::vector<KeyType> &data);
}


text:
module Footnotes
  module Notes
    # This is the abstract class for notes.
    # You can overwrite all instance public methods to create your notes.
    #
    class AbstractNote

      # Class methods. Do NOT overwrite them.
      #
      class << self
        # Returns the symbol that represents this note.
        # It's the name of the class, underscored and without _note.
        #
        # For example, for ControllerNote it will return :controller.
        #
        def to_sym
          @note_sym ||= self.title.underscore.to_sym
        end

        # Returns the title that represents this note.
        # It's the name of the class without Note.
        #
        # For example, for ControllerNote it will return Controller.
        #
        def title
          @note_title ||= self.name.match(/^Footnotes::Notes::(\w+)Note$/)[1]
        end

        # Return true if Note is included in notes array.
        #
        def included?
          Footnotes::Filter.notes.include?(self.to_sym)
        end

        # Action to be called to start the Note.
        # This is applied as a before_filter.
        #
        def start!(controller = nil)
        end

        # Action to be called after the Note was used.
        # This is applied as an after_filter.
        #
        def close!(controller = nil)
        end
      end

      # Initialize notes.
      # Always receives a controller.
      #
      def initialize(controller = nil)
      end

      # Returns the symbol that represents this note.
      #
      def to_sym
        self.class.to_sym
      end

      # Specifies in which row should appear the title.
      # The default is :show.
      #
      def row
        :show
      end

      # Returns the title to be used as link.
      # The default is the note title.
      #
      def title
        self.class.title
      end

      # If has_fieldset? is true, create a fieldset with the value returned as legend.
      # By default, returns the title of the class (defined above).
      #
      def legend
        self.class.title
      end

      # If content is defined, has_fieldset? returns true and the value of content
      # is displayed when the Note is clicked. See has_fieldset? below for more info.
      #
      # def content
      # end

      # Set href field for Footnotes links.
      # If it's nil, Footnotes will use '#'.
      #
      def link
      end

      # Set onclick field for Footnotes links.
      # If it's nil, Footnotes will make it open the fieldset.
      #
      def onclick
      end

      # Insert here any additional stylesheet.
      # This is directly inserted into a


text:
package gcm

type GCMClient interface {
	// Sends GCM message to GCM server.
	Send(apiKey string, data map[string]interface{}, regIds ...string) (Response, error)
}

type Response struct {
}


text:
package com.laegler.stubbr.lang.tests.xtext;

import org.junit.runner.RunWith;
import org.xpect.runner.Xpect;
import org.xpect.runner.XpectRunner;
import org.xpect.runner.XpectTestFiles;

@RunWith(XpectRunner.class)
@XpectTestFiles(fileExtensions = "xt")
@SuppressWarnings("all")
public class StubbrXtextTest {
  @Xpect
  public void simple() {
    System.out.println("Hello World");
  }
}


text:
package solutions.alterego.android.unisannio.giurisprudenza;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

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

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import solutions.alterego.android.unisannio.models.Article;
import solutions.alterego.android.unisannio.R;
import solutions.alterego.android.unisannio.URLS;
import solutions.alterego.android.unisannio.utils.VHHeader;

public class GiurisprudenzaAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int TYPE_HEADER = 0;

    private static final int TYPE_ITEM = 1;

    private List<Article> mNewsList = new ArrayList<>();

    public GiurisprudenzaAdapter(List<Article> newsList) {
        mNewsList = newsList;
    }

    public void addNews(List<Article> newsList) {
        mNewsList.clear();
        mNewsList.add(null);
        mNewsList.addAll(newsList);
        notifyDataSetChanged();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup viewGroup, int viewType) {
        Context context = viewGroup.getContext();

        if (viewType == TYPE_ITEM) {
            View v = LayoutInflater.from(context).inflate(R.layout.article_card, viewGroup, false);
            return new ViewHolder(v);
        } else if (viewType == TYPE_HEADER) {
            View v = LayoutInflater.from(context).inflate(R.layout.recyclerview_header_image, viewGroup, false);
            return new VHHeader(v);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int i) {
        if (holder instanceof GiurisprudenzaAdapter.ViewHolder) {
            final Article news = mNewsList.get(i);
            ((ViewHolder) holder).setItem(news);
        } else if (holder instanceof VHHeader) {
            ((VHHeader) holder).header.setImageResource(R.drawable.calandra);
        }
    }

    @Override
    public int getItemCount() {
        return mNewsList == null ? 0 : mNewsList.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (isPositionHeader(position)) {
            return TYPE_HEADER;
        }

        return TYPE_ITEM;
    }

    private boolean isPositionHeader(int position) {
        return position == 0;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        @InjectView(R.id.ingengeria_card)
        CardView card;

        @InjectView(R.id.article_card_title)
        TextView body;

        @InjectView(R.id.article_card_date)
        TextView date;

        private Article mNews;

        public ViewHolder(View view) {
            super(view);
            ButterKnife.inject(this, view);
        }

        void setItem(Article news) {
            mNews = news;
            date.setText(news.getDate());
            body.setText(news.getTitle());
        }

        @OnClick(R.id.ingengeria_card)
        public void openDetailPage(View v) {
            String url = URLS.GIURISPRUDENZA + mNews.getUrl();
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            v.getContext().startActivity(browserIntent);
        }
    }
}


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

require("babel-polyfill");

describe("HookTester", () => {
	it("should run", () => {});
});

process.on("unhandledRejection", err => console.error(err.stack));

class HookTester {
	constructor(hookCreator, sync) {
		this.hookCreator = hookCreator;
		this.sync = sync;
	}

	async run(syncOnly) {
		const result = {
			sync: {},
			async: {},
			intercept: {}
		};

		if(syncOnly) {

			await this.runSync(result.sync, "call");

		} else {

			await this.runAsync(result.async, "callAsync");
			await this.runAsync(result.async, "promise");

			await this.runIntercept(result.intercept, "callAsync");
			await this.runIntercept(result.intercept, "promise");

		}

		await this.runSync(result.sync, "callAsync");
		await this.runSync(result.sync, "promise");

		return result;
	}

	async runForLoop(syncOnly) {
		const result = {
			sync: {},
			async: {}
		};

		if(syncOnly) {

			await this.runForLoopSync(result.sync, "call");

		} else {

			await this.runForLoopAsync(result.async, "callAsync");
			await this.runForLoopAsync(result.async, "promise");

		}

		await this.runForLoopSync(result.sync, "callAsync");
		await this.runForLoopSync(result.sync, "promise");

		return result;
	}

	async runForLoopAsync(result, method) {
		{
			const hook = this.createHook([], `${method}SinglePromise`);
			hook.tapPromise("promise", () => {
				result[`${method}SinglePromiseCalled`] = (result[`${method}SinglePromiseCalled`] || 0) + 1;
				if(result[`${method}SinglePromiseCalled`] < 42)
					return Promise.resolve().then(() => true);
				return Promise.resolve().then(() => {});
			});
			result[`${method}SinglePromise`] = await this.gainResult(cb => hook[method](cb));
		}

		{
			const hook = this.createHook([], `${method}MultiplePromise`);
			hook.tapPromise("promise1", () => {
				result[`${method}MultiplePromiseCalled1`] = (result[`${method}MultiplePromiseCalled1`] || 0) + 1;
				if(result[`${method}MultiplePromiseCalled1`] < 42)
					return Promise.resolve().then(() => true);
				return Promise.resolve().then(() => {});
			});
			hook.tapPromise("promise2", () => {
				result[`${method}MultiplePromiseCalled2`] = (result[`${method}MultiplePromiseCalled2`] || 0) + 1;
				if(result[`${method}MultiplePromiseCalled2`] < 42)
					return Promise.resolve().then(() => true);
				return Promise.resolve().then(() => {});
			});
			result[`${method}MultiplePromise`] = await this.gainResult(cb => hook[method](cb));
		}

		{
			const hook = this.createHook([], `${method}SingleAsync`);
			hook.tapAsync("async", (callback) => {
				result[`${method}SingleAsyncCalled`] = (result[`${method}SingleAsyncCalled`] || 0) + 1;
				if(result[`${method}SingleAsyncCalled`] < 42)
					return Promise.resolve().then(() => callback(null, true));
				return Promise.resolve().then(() => callback());
			});
			result[`${method}SingleAsync`] = await this.gainResult(cb => hook[method](cb));
		}

		{
			const hook = this.createHook([], `${method}MultipleAsync`);
			hook.tapAsync("async1", (callback) => {
				result[`${method}MultipleAsyncCalled1`] = (result[`${method}MultipleAsyncCalled1`] || 0) + 1;
				if(result[`${method}MultipleAsyncCalled1`] < 42)
					return Promise.resolve().then(() => callback(null, true));
				return Promise.resolve().then(() => callback());
			});
			hook.tapAsync("async2", (callback) => {
				result[`${method}MultipleAsyncCalled2`] = (result[`${method}MultipleAsyncCalled2`] || 0) + 1;
				if(result[`${method}MultipleAsyncCalled2`] < 42)
					return Promise.resolve().then(() => callback(null, true));
				return Promise.resolve().then(() => callback());
			});
			result[`${method}MultipleAsync`] = await this.gainResult(cb => hook[method](cb));
		}

		{
			const hook = this.createHook([], `${method}Mixed`);
			hook.tapAsync("async1", (callback) => {
				result[`${method}MixedCalled1`] = (result[`${method}MixedCalled1`] || 0) + 1;
				if(result[`${method}MixedCalled1`] < 42)
					return Promise.resolve().then(() => callback(null, true));
				return Promise.resolve().then(() => callback());
			});
			hook.tap("sync2", () => {
				result[`${method}MixedCalled2`] = (result[`${method}MixedCalled2`] || 0) + 1;
				if(result[`${method}MixedCalled2`] < 42)
					return true;
			});
			hook.tapPromise("promise3", () => {
				result[`${method}MixedCalled3`] = (result[`${method}MixedCalled3`] || 0) + 1;
				if(result[`${method}MixedCalled3`] < 42)
					return Promise.resolve().then(() => true);
				return Promise.resolve().then(() => {});
			});
			result[`${method}Mixed`] = await this.gainResult(cb => hook[method](cb));
		}
	}

	async runForLoopSync(result, method) {
		{
			const hook = this.createHook([], `${method}None`);
			result[`${method}None`] = await this.gainResult(cb => hook[method](cb));
		}

		{
			const hook = this.createHook(["arg"], `${method}NoneWithArg`);
			result[`${method}NoneWithArg`] = await this.gainResult(cb => hook[method](42, cb));
		}

		{
			const hook = this.createHook([], `${method}SingleSync`);
			hook.tap("sync", () => {
				result[`${method}SingleSyncCalled`] = (result[`${method}SingleSyncCalled`] || 0) + 1;
				if(result[`${method}SingleSyncCalled`] < 42)
					return true;
			});
			result[`${method}SingleSync`] = await this.gainResult(cb => hook[method](cb));
		}

		{
			const hook = this.createHook([], `${method}MultipleSync`);
			hook.tap("sync1", () => {
				result[`${method}MultipleSyncCalled1`] = (result[`${method}MultipleSyncCalled1`] || 0) + 1;
				if(result[`${method}MultipleSyncCalled1`] < 42)
					return true;
			});
			hook.tap("sync2", () => {
				result[`${method}MultipleSyncCalled2`] = (result[`${method}MultipleSyncCalled2`] || 0) + 1;
				if(result[`${method}MultipleSyncCalled2`] < 42)
					return true;
			});
			result[`${method}MultipleSync`] = await this.gainResult(cb => hook[method](cb));
		}

		{
			const hook = this.createHook([], `${method}InterceptedSync`);
			hook.tap("sync1", () => {
				result[`${method}InterceptedSyncCalled1`] = (result[`${method}InterceptedSyncCalled1`] || 0) + 1;
				if(result[`${method}InterceptedSyncCalled1`] < 42)
					return true;
			});
			hook.tap("sync2", () => {
				result[`${method}InterceptedSyncCalled2`] = (result[`${method}InterceptedSyncCalled2`] || 0) + 1;
				if(result[`${method}InterceptedSyncCalled2`] < 42)
					return true;
			});
			hook.intercept({
				call: (a) => result[`${method}InterceptedSyncCalledCall`] = (result[`${method}InterceptedSyncCalledCall`] || 0) + 1,
				loop: (a) => result[`${method}InterceptedSyncCalledLoop`] = (result[`${method}InterceptedSyncCalledLoop`] || 0) + 1,
				tap: (tap) => {
					result[`${method}InterceptedSyncCalledTap`] = (result[`${method}InterceptedSyncCalledTap`] || 0) + 1
				},
			})
			result[`${method}InterceptedSync`] = await this.gainResult(cb => hook[method](cb));
		}
	}

	async runSync(result, method) {
		{
			const hook = this.createHook([], `${method}None`);
			result[`${method}None`] = await this.gainResult(cb => hook[method](cb));
		}

		{
			const hook = this.createHook(["arg"], `${method}NoneWithArg`);
			result[`${method}NoneWithArg`] = await this.gainResult(cb => hook[method](42, cb));
		}

		{
			const hook = this.createHook([], `${method}SingleSync`);
			hook.tap("sync", () => {
				result[`${method}SingleSyncCalled`] = true;
				return 42;
			});
			result[`${method}SingleSync`] = await this.gainResult(cb => hook[method](cb));
		}

		{
			const hook = this.createHook(["myArg"], `${method}SingleSyncWithArg`);
			hook.tap("sync", (nr) => {
				result[`${method}SingleSyncWithArgCalled`] = nr;
				return nr;
			});
			result[`${method}SingleSyncWithArg`] = await this.gainResult(cb => hook[method](42, cb));
		}

		{
			const hook = this.createHook([], `${method}MultipleSync`);
			hook.tap("sync1", () => {
				result[`${method}MultipleSyncCalled1`] = true;
				return 42;
			});
			hook.tap("sync2", () => {
				result[`${method}MultipleSyncCalled2`] = true;
				return 43;
			});
			result[`${method}MultipleSync`] = await this.gainResult(cb => hook[method](cb));
		}

		{
			const hook = this.createHook(["a"], `${method}MultipleSyncWithArg`);
			hook.tap("sync1", (a) => {
				result[`${method}MultipleSyncWithArgCalled1`] = a;
				return 42 + a;
			});
			hook.tap("sync2", (a) => {
				result[`${method}MultipleSyncWithArgCalled2`] = a;
				return 43 + a;
			});
			result[`${method}MultipleSyncWithArg`] = await this.gainResult(cb => hook[method](42, cb));
		}

		{
			const hook = this.createHook(["a"], `${method}MultipleSyncWithArgNoReturn`);
			hook.tap("sync1", (a) => {
				result[`${method}MultipleSyncWithArgNoReturnCalled1`] = a;
			});
			hook.tap("sync2", (a) => {
				result[`${method}MultipleSyncWithArgNoReturnCalled2`] = a;
			});
			result[`${method}MultipleSyncWithArgNoReturn`] = await this.gainResult(cb => hook[method](42, cb));
		}

		{
			const hook = this.createHook(["a"], `${method}MultipleSyncWithArgFirstReturn`);
			hook.tap("sync1", (a) => {
				result[`${method}MultipleSyncWithArgFirstReturnCalled1`] = a;
				return 42 + a;
			});
			hook.tap("sync2", (a) => {
				result[`${method}MultipleSyncWithArgFirstReturnCalled2`] = a;
			});
			result[`${method}MultipleSyncWithArgFirstReturn`] = await this.gainResult(cb => hook[method](42, cb));
		}

		{
			const hook = this.createHook(["a"], `${method}MultipleSyncWithArgLastReturn`);
			hook.tap("sync1", (a) => {
				result[`${method}MultipleSyncWithArgLastReturnCalled1`] = a;
			});
			hook.tap("sync2", (a) => {
				result[`${method}MultipleSyncWithArgLastReturnCalled2`] = a;
				return 43 + a;
			});
			result[`${method}MultipleSyncWithArgLastReturn`] = await this.gainResult(cb => hook[method](42, cb));
		}

		{
			const hook = this.createHook(["a", "b", "c"], `${method}MultipleSyncWithArgs`);
			hook.tap("sync1", (a, b, c) => {
				result[`${method}MultipleSyncWithArgsCalled1`] = [a, b, c];
				return a + b + c;
			});
			hook.tap("sync2", (a, b, c) => {
				result[`${method}MultipleSyncWithArgsCalled2`] = [a, b, c];
				return a + b + c + 1;
			});
			result[`${method}MultipleSyncWithArgs`] = await this.gainResult(cb => hook[method](42, 43, 44, cb));
		}

		{
			const hook = this.createHook([], `${method}MultipleSyncError`);
			hook.tap("sync1", () => {
				result[`${method}MultipleSyncErrorCalled1`] = true;
			});
			hook.tap("sync2", () => {
				result[`${method}MultipleSyncErrorCalled2`] = true;
				throw new Error("Error in sync2")
			});
			hook.tap("sync3", () => {
				result[`${method}MultipleSyncErrorCalled3`] = true;
			});
			result[`${method}MultipleSyncError`] = await this.gainResult(cb => hook[method](cb));
		}

		{
			const hook = this.createHook(["a", "b", "c"], `${method}Intercepted`);
			hook.intercept({
				call: (a, b, c) => {
					result[`${method}InterceptedCall1`] = [a, b, c];
				},
				tap: (tap) => {
					result[`${method}InterceptedTap1`] = Object.assign({}, tap, { fn: tap.fn.length });
				}
			});
			hook.intercept({
				call: (a, b, c) => {
					result[`${method}InterceptedCall2`] = [a, b, c];
				},
				tap: (tap) => {
					if(!result[`${method}InterceptedTap2`])
						result[`${method}InterceptedTap2`] = Object.assign({}, tap, { fn: tap.fn.length });
				}
			});
			hook.tap("sync1", (a, b, c) => a + b + c);
			hook.tap("sync2", (a, b) => a + b + 1);
			result[`${method}Intercepted`] = await this.gainResult((cb) => hook[method](1, 2, 3, cb));
		}
	}

	async runAsync(result, type) {
		{
			const hook = this.createHook([], `${type}None`);
			result[`${type}None`] = await this.gainResult((cb) => hook[type](cb));
		}

		{
			const hook = this.createHook(["arg"], `${type}NoneWithArg`);
			result[`${type}NoneWithArg`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook([], `${type}SingleSync`);
			hook.tap("sync", () => {
				result[`${type}SingleSyncCalled1`] = true;
				return 42;
			});
			result[`${type}SingleSync`] = await this.gainResult((cb) => hook[type](cb));
		}

		{
			const hook = this.createHook(["x"], `${type}SingleSyncWithArg`);
			hook.tap("sync", arg => {
				result[`${type}SingleSyncWithArgCalled1`] = arg;
				return arg + 1;
			});
			result[`${type}SingleSyncWithArg`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["x"], `${type}SingleSyncWithArgNoReturn`);
			hook.tap("sync", arg => {
				result[`${type}SingleSyncWithArgNoReturnCalled1`] = arg;
			});
			result[`${type}SingleSyncWithArgNoReturn`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook([], `${type}MultipleSync`);
			hook.tap("sync1", () => {
				result[`${type}MultipleSyncCalled1`] = true;
				return 42;
			});
			hook.tap("sync2", () => {
				result[`${type}MultipleSyncCalled2`] = true;
				return 43;
			});
			result[`${type}MultipleSync`] = await this.gainResult((cb) => hook[type](cb));
		}

		{
			const hook = this.createHook([], `${type}MultipleSyncLastReturn`);
			hook.tap("sync1", () => {
				result[`${type}MultipleSyncLastReturnCalled1`] = true;
			});
			hook.tap("sync2", () => {
				result[`${type}MultipleSyncLastReturnCalled2`] = true;
				return 43;
			});
			result[`${type}MultipleSyncLastReturn`] = await this.gainResult((cb) => hook[type](cb));
		}

		{
			const hook = this.createHook([], `${type}MultipleSyncNoReturn`);
			hook.tap("sync1", () => {
				result[`${type}MultipleSyncNoReturnCalled1`] = true;
			});
			hook.tap("sync2", () => {
				result[`${type}MultipleSyncNoReturnCalled2`] = true;
			});
			result[`${type}MultipleSyncNoReturn`] = await this.gainResult((cb) => hook[type](cb));
		}

		{
			const hook = this.createHook(["arg"], `${type}MultipleSyncWithArg`);
			hook.tap("sync1", arg => {
				result[`${type}MultipleSyncWithArgCalled1`] = arg;
				return arg + 1;
			});
			hook.tap("sync2", arg => {
				result[`${type}MultipleSyncWithArgCalled2`] = arg;
				return arg + 2;
			});
			result[`${type}MultipleSyncWithArg`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["arg"], `${type}MultipleSyncWithArgNoReturn`);
			hook.tap("sync1", arg => {
				result[`${type}MultipleSyncWithArgNoReturnCalled1`] = arg;
			});
			hook.tap("sync2", arg => {
				result[`${type}MultipleSyncWithArgNoReturnCalled2`] = arg;
			});
			result[`${type}MultipleSyncWithArgNoReturn`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["arg"], `${type}MultipleSyncWithArgLastReturn`);
			hook.tap("sync1", arg => {
				result[`${type}MultipleSyncWithArgLastReturnCalled1`] = arg;
			});
			hook.tap("sync2", arg => {
				result[`${type}MultipleSyncWithArgLastReturnCalled2`] = arg;
				return arg + 2;
			});
			result[`${type}MultipleSyncWithArgLastReturn`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["arg"], `${type}MultipleSyncWithArgFirstReturn`);
			hook.tap("sync1", arg => {
				result[`${type}MultipleSyncWithArgFirstReturnCalled1`] = arg;
				return arg + 1;
			});
			hook.tap("sync2", arg => {
				result[`${type}MultipleSyncWithArgFirstReturnCalled2`] = arg;
			});
			result[`${type}MultipleSyncWithArgFirstReturn`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["x"], `${type}SingleAsyncWithArg`);
			hook.tapAsync("async", (arg, callback) => {
				result[`${type}SingleAsyncWithArgCalled1`] = arg;
				callback(null, arg);
			});
			result[`${type}SingleAsyncWithArg`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["x"], `${type}MultipleAsyncWithArg`);
			hook.tapAsync("async1", (arg, callback) => {
				result[`${type}MultipleAsyncWithArgCalled1`] = arg;
				callback(null, arg + 1);
			});
			hook.tapAsync("async2", (arg, callback) => {
				result[`${type}MultipleAsyncWithArgCalled2`] = arg;
				callback(null, arg + 2);
			});
			result[`${type}MultipleAsyncWithArg`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["x"], `${type}MultipleAsyncWithArgNoReturn`);
			hook.tapAsync("async1", (arg, callback) => {
				result[`${type}MultipleAsyncWithArgNoReturnCalled1`] = arg;
				callback();
			});
			hook.tapAsync("async2", (arg, callback) => {
				result[`${type}MultipleAsyncWithArgNoReturnCalled2`] = arg;
				callback();
			});
			result[`${type}MultipleAsyncWithArgNoReturn`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["x"], `${type}MultipleAsyncWithArgFirstReturn`);
			hook.tapAsync("async1", (arg, callback) => {
				result[`${type}MultipleAsyncWithArgFirstReturnCalled1`] = arg;
				callback(null, arg + 1);
			});
			hook.tapAsync("async2", (arg, callback) => {
				result[`${type}MultipleAsyncWithArgFirstReturnCalled2`] = arg;
				callback();
			});
			result[`${type}MultipleAsyncWithArgFirstReturn`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["x"], `${type}MultipleAsyncWithArgLastReturn`);
			hook.tapAsync("async1", (arg, callback) => {
				result[`${type}MultipleAsyncWithArgLastReturnCalled1`] = arg;
				callback();
			});
			hook.tapAsync("async2", (arg, callback) => {
				result[`${type}MultipleAsyncWithArgLastReturnCalled2`] = arg;
				callback(null, arg + 2);
			});
			result[`${type}MultipleAsyncWithArgLastReturn`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["x"], `${type}SinglePromiseWithArg`);
			hook.tapPromise("promise", arg => {
				result[`${type}SinglePromiseWithArgCalled1`] = arg;
				return Promise.resolve(arg + 1);
			});
			result[`${type}SinglePromiseWithArg`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["x"], `${type}MultiplePromiseWithArg`);
			hook.tapPromise("promise1", arg => {
				result[`${type}MultiplePromiseWithArgCalled1`] = arg;
				return Promise.resolve(arg + 1);
			});
			hook.tapPromise("promise2", arg => {
				result[`${type}MultiplePromiseWithArgCalled2`] = arg;
				return Promise.resolve(arg + 2);
			});
			result[`${type}MultiplePromiseWithArg`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["x"], `${type}MultiplePromiseWithArgNoReturn`);
			hook.tapPromise("promise1", arg => {
				result[`${type}MultiplePromiseWithArgNoReturnCalled1`] = arg;
				return Promise.resolve();
			});
			hook.tapPromise("promise2", arg => {
				result[`${type}MultiplePromiseWithArgNoReturnCalled2`] = arg;
				return Promise.resolve();
			});
			result[`${type}MultiplePromiseWithArgNoReturn`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["x"], `${type}MultiplePromiseWithArgFirstReturn`);
			hook.tapPromise("promise1", arg => {
				result[`${type}MultiplePromiseWithArgFirstReturnCalled1`] = arg;
				return Promise.resolve(arg + 1);
			});
			hook.tapPromise("promise2", arg => {
				result[`${type}MultiplePromiseWithArgFirstReturnCalled2`] = arg;
				return Promise.resolve();
			});
			result[`${type}MultiplePromiseWithArgFirstReturn`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["x"], `${type}MultiplePromiseWithArgLastReturn`);
			hook.tapPromise("promise1", arg => {
				result[`${type}MultiplePromiseWithArgLastReturnCalled1`] = arg;
				return Promise.resolve();
			});
			hook.tapPromise("promise2", arg => {
				result[`${type}MultiplePromiseWithArgLastReturnCalled2`] = arg;
				return Promise.resolve(arg + 2);
			});
			result[`${type}MultiplePromiseWithArgLastReturn`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["x"], `${type}MultipleMixed1WithArg`);
			hook.tapAsync("async", (arg, callback) => {
				result[`${type}MultipleMixed1WithArgCalled1`] = arg;
				callback(null, arg + 1);
			});
			hook.tapPromise("promise", arg => {
				result[`${type}MultipleMixed1WithArgCalled2`] = arg;
				return Promise.resolve(arg + 2);
			});
			hook.tap("sync", arg => {
				result[`${type}MultipleMixed1WithArgCalled3`] = arg;
				return arg + 3;
			});
			result[`${type}MultipleMixed1WithArg`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["x"], `${type}MultipleMixed2WithArg`);
			hook.tapAsync("async", (arg, callback) => {
				result[`${type}MultipleMixed2WithArgCalled1`] = arg;
				setTimeout(() => callback(null, arg + 1), 100);
			});
			hook.tapPromise("promise", arg => {
				result[`${type}MultipleMixed2WithArgCalled2`] = arg;
				return Promise.resolve(arg + 2);
			});
			result[`${type}MultipleMixed2WithArg`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["x"], `${type}MultipleMixed3WithArg`);
			hook.tapAsync("async1", (arg, callback) => {
				result[`${type}MultipleMixed3WithArgCalled1`] = arg;
				callback(null, arg + 1);
			});
			hook.tapPromise("promise", arg => {
				result[`${type}MultipleMixed3WithArgCalled2`] = arg;
				return Promise.resolve(arg + 2);
			});
			hook.tapAsync("async2", (arg, callback) => {
				result[`${type}MultipleMixed3WithArgCalled3`] = arg;
				setTimeout(() => callback(null, arg + 3), 100);
			});
			result[`${type}MultipleMixed3WithArg`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook([], `${type}MultipleSyncError`);
			hook.tap("sync1", () => {
				result[`${type}MultipleSyncErrorCalled1`] = true;
			});
			hook.tap("sync2", () => {
				throw new Error("Error in sync2")
			});
			hook.tap("sync3", () => {
				result[`${type}MultipleSyncErrorCalled3`] = true;
			});
			result[`${type}MultipleSyncError`] = await this.gainResult((cb) => hook[type](cb));
		}

		{
			const hook = this.createHook([], `${type}MultipleAsyncError`);
			hook.tapAsync("async1", (callback) => {
				result[`${type}MultipleAsyncErrorCalled1`] = true;
				callback();
			});
			hook.tapAsync("async2", (callback) => {
				callback(new Error("Error in async2"));
			});
			hook.tapAsync("async3", (callback) => {
				result[`${type}MultipleAsyncErrorCalled3`] = true;
				callback();
			});
			result[`${type}MultipleAsyncError`] = await this.gainResult((cb) => hook[type](cb));
		}

		{
			const hook = this.createHook([], `${type}MultipleAsyncLateError`);
			hook.tapAsync("async1", (callback) => {
				result[`${type}MultipleAsyncLateErrorCalled1`] = true;
				callback();
			});
			hook.tapAsync("async2", (callback) => {
				setTimeout(() => callback(new Error("Error in async2")), 100);
			});
			hook.tapAsync("async3", (callback) => {
				result[`${type}MultipleAsyncLateErrorCalled3`] = true;
				callback();
			});
			result[`${type}MultipleAsyncLateError`] = await this.gainResult((cb) => hook[type](cb));
		}

		{
			const hook = this.createHook([], `${type}MultipleAsyncLateErrorEarlyResult1`);
			hook.tapAsync("async1", (callback) => {
				result[`${type}MultipleAsyncLateErrorEarlyResult1Called1`] = true;
				callback();
			});
			hook.tapAsync("async2", (callback) => {
				setTimeout(() => callback(new Error("Error in async2")), 100);
			});
			hook.tapAsync("async3", (callback) => {
				result[`${type}MultipleAsyncLateErrorEarlyResult1Called3`] = true;
				callback(null, 7);
			});
			result[`${type}MultipleAsyncLateErrorEarlyResult1`] = await this.gainResult((cb) => hook[type](cb));
		}

		{
			const hook = this.createHook([], `${type}MultipleAsyncLateErrorEarlyResult2`);
			hook.tapAsync("async1", (callback) => {
				result[`${type}MultipleAsyncLateErrorEarlyResult2Called1`] = true;
				setTimeout(() => callback(null, 42), 200);
			});
			hook.tapAsync("async2", (callback) => {
				setTimeout(() => callback(new Error("Error in async2")), 100);
			});
			hook.tapAsync("async3", (callback) => {
				result[`${type}MultipleAsyncLateErrorEarlyResult2Called3`] = true;
				callback(null, 7);
			});
			result[`${type}MultipleAsyncLateErrorEarlyResult2`] = await this.gainResult((cb) => hook[type](cb));
		}

		{
			const hook = this.createHook([], `${type}MultipleAsyncEarlyError`);
			hook.tapAsync("async1", (callback) => {
				result[`${type}MultipleAsyncEarlyErrorCalled1`] = true;
				setTimeout(() => callback(), 100);
			});
			hook.tapAsync("async2", (callback) => {
				callback(new Error("Error in async2"));
			});
			hook.tapAsync("async3", (callback) => {
				result[`${type}MultipleAsyncEarlyErrorCalled3`] = true;
				setTimeout(() => callback(), 100);
			});
			result[`${type}MultipleAsyncEarlyError`] = await this.gainResult((cb) => hook[type](cb));
		}

		{
			const hook = this.createHook([], `${type}MultiplePromiseError`);
			hook.tapPromise("promise1", () => {
				result[`${type}MultiplePromiseErrorCalled1`] = true;
				return Promise.resolve();
			});
			hook.tapPromise("promise2", () => {
				return Promise.resolve().then(() => { throw new Error("Error in async2"); });
			});
			hook.tapPromise("promise3", () => {
				result[`${type}MultiplePromiseErrorCalled3`] = true;
				return Promise.resolve();
			});
			result[`${type}MultiplePromiseError`] = await this.gainResult((cb) => hook[type](cb));
		}

		{
			const hook = this.createHook([], `${type}MultiplePromiseLateError`);
			hook.tapPromise("promise1", () => {
				result[`${type}MultiplePromiseLateErrorCalled1`] = true;
				return Promise.resolve();
			});
			hook.tapPromise("promise2", () => {
				return new Promise((resolve, reject) => {
					setTimeout(() => reject(new Error("Error in async2")), 100);
				});
			});
			hook.tapPromise("promise3", () => {
				result[`${type}MultiplePromiseLateErrorCalled3`] = true;
				return Promise.resolve();
			});
			result[`${type}MultiplePromiseLateError`] = await this.gainResult((cb) => hook[type](cb));
		}

		{
			const hook = this.createHook([], `${type}MultiplePromiseEarlyError`);
			hook.tapPromise("promise1", () => {
				result[`${type}MultiplePromiseEarlyErrorCalled1`] = true;
				return new Promise(resolve => setTimeout(() => resolve(), 100));
			});
			hook.tapPromise("promise2", () => {
				return Promise.resolve().then(() => { throw new Error("Error in async2"); });
			});
			hook.tapPromise("promise3", () => {
				result[`${type}MultiplePromiseEarlyErrorCalled3`] = true;
				return new Promise(resolve => setTimeout(() => resolve(), 100));
			});
			result[`${type}MultiplePromiseEarlyError`] = await this.gainResult((cb) => hook[type](cb));
		}

		{
			const hook = this.createHook(["x"], `${type}MultipleMixedError1WithArg`);
			hook.tapAsync("async", (arg, callback) => {
				result[`${type}MultipleMixedError1WithArgCalled1`] = arg;
				callback(null, arg);
			});
			hook.tapPromise("promise", arg => {
				result[`${type}MultipleMixedError1WithArgCalled2`] = arg;
				return Promise.resolve(arg + 1);
			});
			hook.tap("sync", arg => {
				result[`${type}MultipleMixedError1WithArgCalled3`] = arg;
				throw new Error("Error in sync");
			});
			result[`${type}MultipleMixedError1WithArg`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["x"], `${type}MultipleMixedError2WithArg`);
			hook.tapAsync("async", (arg, callback) => {
				result[`${type}MultipleMixedError2WithArgCalled1`] = arg;
				callback(null, arg);
			});
			hook.tapPromise("promise", arg => {
				result[`${type}MultipleMixedError2WithArgCalled2`] = arg;
				return Promise.resolve().then(() => { throw new Error("Error in promise"); });
			});
			hook.tap("sync", arg => {
				result[`${type}MultipleMixedError2WithArgCalled3`] = arg;
				return arg + 2;
			});
			result[`${type}MultipleMixedError2WithArg`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook(["x"], `${type}MultipleMixedError3WithArg`);
			hook.tapAsync("async", (arg, callback) => {
				result[`${type}MultipleMixedError3WithArgCalled1`] = arg;
				callback(new Error("Error in async"));
			});
			hook.tapPromise("promise", arg => {
				result[`${type}MultipleMixedError3WithArgCalled2`] = arg;
				return Promise.resolve(arg + 1);
			});
			hook.tap("sync", arg => {
				result[`${type}MultipleMixedError3WithArgCalled3`] = arg;
				return arg + 2;
			});
			result[`${type}MultipleMixedError3WithArg`] = await this.gainResult((cb) => hook[type](42, cb));
		}

		{
			const hook = this.createHook([], `${type}MultipleMixedLateError`);
			hook.tapAsync("async", (callback) => {
				result[`${type}MultipleMixedLateErrorCalled1`] = true;
				setTimeout(() => callback(new Error("Error in async")), 100);
			});
			hook.tapPromise("promise", () => {
				result[`${type}MultipleMixedLateErrorCalled2`] = true;
				return Promise.resolve(42);
			});
			hook.tap("sync", () => {
				result[`${type}MultipleMixedLateErrorCalled3`] = true;
				return 43;
			});
			result[`${type}MultipleMixedLateError`] = await this.gainResult((cb) => hook[type](cb));
		}
	}

	async runIntercept(result, type) {
		{
			const hook = this.createHook(["a", "b", "c"], `${type}Intercepted`);
			hook.intercept({
				call: (a, b, c) => {
					result[`${type}InterceptedCall1`] = [a, b, c];
				},
				tap: (tap) => {
					result[`${type}InterceptedTap1`] = Object.assign({}, tap, { fn: tap.fn.length });
				}
			});
			hook.intercept({
				call: (a, b, c) => {
					result[`${type}InterceptedCall2`] = [a, b, c];
				},
				tap: (tap) => {
					if(!result[`${type}InterceptedTap2`])
						result[`${type}InterceptedTap2`] = Object.assign({}, tap, { fn: tap.fn.length });
				}
			});
			hook.tap("sync", (a, b, c) => a + b + c);
			hook.tapPromise("promise", (a, b) => Promise.resolve(a + b + 1));
			result[`${type}Intercepted`] = await this.gainResult((cb) => hook[type](1, 2, 3, cb));
		}

		{
			const hook = this.createHook(["a", "b", "c"], `${type}ContextIntercepted`);
			hook.intercept({
				call: (context, a, b, c) => {
					context.number = 42;
					result[`${type}ContextInterceptedCall1`] = [context, a, b, c];
				},
				loop: (context, a, b, c) => {
					context.number2 = 88;
					result[`${type}ContextInterceptedLoop1`] = [context, a, b, c];
				},
				tap: (context, tap) => {
					result[`${type}ContextInterceptedTap1`] = context;
				},
				context: true
			});
			hook.intercept({
				call: (a, b, c) => {
					result[`${type}ContextInterceptedCall2`] = [a, b, c];
				}
			});
			hook.tap({
				name: "sync",
				context: true
			}, (context, a, b, c) => context.number + a + b + c);
			result[`${type}ContextIntercepted`] = await this.gainResult((cb) => hook[type](1, 2, 3, cb));
		}

		{
			const hook = this.createHook(["a", "b", "c"], `${type}UnusedContextIntercepted`);
			hook.intercept({
				call: (context, a, b, c) => {
					result[`${type}UnusedContextInterceptedCall1`] = [context, a, b, c];
				},
				tap: (context, tap) => {
					result[`${type}UnusedContextInterceptedTap1`] = context;
				},
				context: true
			});
			hook.intercept({
				call: (a, b, c) => {
					result[`${type}UnusedContextInterceptedCall2`] = [a, b, c];
				}
			});
			hook.tap("sync", (a, b, c) => a + b + c);
			result[`${type}UnusedContextIntercepted`] = await this.gainResult((cb) => hook[type](1, 2, 3, cb));
		}
	}

	gainResult(fn) {
		return Promise.race([new Promise(resolve => {
			try {
				const ret = fn((err, result) => {
					if(err) {
						resolve({
							type: "async",
							error: err.message
						});
					} else {
						resolve({
							type: "async",
							value: result
						});
					}
				});
				if(ret instanceof Promise) {
					resolve(ret.then(res => ({
						type: "promise",
						value: res
					}), err => ({
						type: "promise",
						error: err.message
					})));
				} else if(ret !== undefined) {
					resolve({
						type: "return",
						value: ret
					})
				}
			} catch(e) {
				resolve({
					error: e.message
				});
			}
		}), new Promise(resolve => {
			setTimeout(() => resolve({
				type: "no result"
			}), 1000);
		})]);
	}

	createHook(args, name) {
		try {
			return this.hookCreator(args, name);
		} catch(err) {
			return {
				tap: () => {},
				tapPromise: () => {},
				tapAsync: () => {},
				intercept: () => {},
				call: () => { throw err; },
				callAsync: () => { throw err; },
				promise: () => { throw err; },
			}
		}
	}
}

module.exports = HookTester;


text:
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */

#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>

#include "vtkPolyDataAlgorithmWrap.h"
#include "vtkEarthSourceWrap.h"
#include "vtkObjectWrap.h"
#include "../../plus/plus.h"

using namespace v8;

extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkEarthSourceWrap::ptpl;

VtkEarthSourceWrap::VtkEarthSourceWrap()
{ }

VtkEarthSourceWrap::VtkEarthSourceWrap(vtkSmartPointer<vtkEarthSource> _native)
{ native = _native; }

VtkEarthSourceWrap::~VtkEarthSourceWrap()
{ }

void VtkEarthSourceWrap::Init(v8::Local<v8::Object> exports)
{
	Nan::SetAccessor(exports, Nan::New("vtkEarthSource").ToLocalChecked(), ConstructorGetter);
	Nan::SetAccessor(exports, Nan::New("EarthSource").ToLocalChecked(), ConstructorGetter);
}

void VtkEarthSourceWrap::ConstructorGetter(
	v8::Local<v8::String> property,
	const Nan::PropertyCallbackInfo<v8::Value>& info)
{
	InitPtpl();
	info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}

void VtkEarthSourceWrap::InitPtpl()
{
	if (!ptpl.IsEmpty()) return;
	v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
	VtkPolyDataAlgorithmWrap::InitPtpl( );
	tpl->Inherit(Nan::New<FunctionTemplate>(VtkPolyDataAlgorithmWrap::ptpl));
	tpl->SetClassName(Nan::New("VtkEarthSourceWrap").ToLocalChecked());
	tpl->InstanceTemplate()->SetInternalFieldCount(1);

	Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName);
	Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName);

	Nan::SetPrototypeMethod(tpl, "GetOnRatio", GetOnRatio);
	Nan::SetPrototypeMethod(tpl, "getOnRatio", GetOnRatio);

	Nan::SetPrototypeMethod(tpl, "GetOnRatioMaxValue", GetOnRatioMaxValue);
	Nan::SetPrototypeMethod(tpl, "getOnRatioMaxValue", GetOnRatioMaxValue);

	Nan::SetPrototypeMethod(tpl, "GetOnRatioMinValue", GetOnRatioMinValue);
	Nan::SetPrototypeMethod(tpl, "getOnRatioMinValue", GetOnRatioMinValue);

	Nan::SetPrototypeMethod(tpl, "GetOutline", GetOutline);
	Nan::SetPrototypeMethod(tpl, "getOutline", GetOutline);

	Nan::SetPrototypeMethod(tpl, "GetRadius", GetRadius);
	Nan::SetPrototypeMethod(tpl, "getRadius", GetRadius);

	Nan::SetPrototypeMethod(tpl, "GetRadiusMaxValue", GetRadiusMaxValue);
	Nan::SetPrototypeMethod(tpl, "getRadiusMaxValue", GetRadiusMaxValue);

	Nan::SetPrototypeMethod(tpl, "GetRadiusMinValue", GetRadiusMinValue);
	Nan::SetPrototypeMethod(tpl, "getRadiusMinValue", GetRadiusMinValue);

	Nan::SetPrototypeMethod(tpl, "IsA", IsA);
	Nan::SetPrototypeMethod(tpl, "isA", IsA);

	Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
	Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);

	Nan::SetPrototypeMethod(tpl, "OutlineOff", OutlineOff);
	Nan::SetPrototypeMethod(tpl, "outlineOff", OutlineOff);

	Nan::SetPrototypeMethod(tpl, "OutlineOn", OutlineOn);
	Nan::SetPrototypeMethod(tpl, "outlineOn", OutlineOn);

	Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
	Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);

	Nan::SetPrototypeMethod(tpl, "SetOnRatio", SetOnRatio);
	Nan::SetPrototypeMethod(tpl, "setOnRatio", SetOnRatio);

	Nan::SetPrototypeMethod(tpl, "SetOutline", SetOutline);
	Nan::SetPrototypeMethod(tpl, "setOutline", SetOutline);

	Nan::SetPrototypeMethod(tpl, "SetRadius", SetRadius);
	Nan::SetPrototypeMethod(tpl, "setRadius", SetRadius);

#ifdef VTK_NODE_PLUS_VTKEARTHSOURCEWRAP_INITPTPL
	VTK_NODE_PLUS_VTKEARTHSOURCEWRAP_INITPTPL
#endif
	ptpl.Reset( tpl );
}

void VtkEarthSourceWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	if(!info.IsConstructCall())
	{
		Nan::ThrowError("Constructor not called in a construct call.");
		return;
	}

	if(info.Length() == 0)
	{
		vtkSmartPointer<vtkEarthSource> native = vtkSmartPointer<vtkEarthSource>::New();
		VtkEarthSourceWrap* obj = new VtkEarthSourceWrap(native);
		obj->Wrap(info.This());
	}
	else
	{
		if(info[0]->ToObject() != vtkNodeJsNoWrap )
		{
			Nan::ThrowError("Parameter Error");
			return;
		}
	}

	info.GetReturnValue().Set(info.This());
}

void VtkEarthSourceWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkEarthSourceWrap *wrapper = ObjectWrap::Unwrap<VtkEarthSourceWrap>(info.Holder());
	vtkEarthSource *native = (vtkEarthSource *)wrapper->native.GetPointer();
	char const * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetClassName();
	info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}

void VtkEarthSourceWrap::GetOnRatio(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkEarthSourceWrap *wrapper = ObjectWrap::Unwrap<VtkEarthSourceWrap>(info.Holder());
	vtkEarthSource *native = (vtkEarthSource *)wrapper->native.GetPointer();
	int r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetOnRatio();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkEarthSourceWrap::GetOnRatioMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkEarthSourceWrap *wrapper = ObjectWrap::Unwrap<VtkEarthSourceWrap>(info.Holder());
	vtkEarthSource *native = (vtkEarthSource *)wrapper->native.GetPointer();
	int r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetOnRatioMaxValue();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkEarthSourceWrap::GetOnRatioMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkEarthSourceWrap *wrapper = ObjectWrap::Unwrap<VtkEarthSourceWrap>(info.Holder());
	vtkEarthSource *native = (vtkEarthSource *)wrapper->native.GetPointer();
	int r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetOnRatioMinValue();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkEarthSourceWrap::GetOutline(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkEarthSourceWrap *wrapper = ObjectWrap::Unwrap<VtkEarthSourceWrap>(info.Holder());
	vtkEarthSource *native = (vtkEarthSource *)wrapper->native.GetPointer();
	int r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetOutline();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkEarthSourceWrap::GetRadius(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkEarthSourceWrap *wrapper = ObjectWrap::Unwrap<VtkEarthSourceWrap>(info.Holder());
	vtkEarthSource *native = (vtkEarthSource *)wrapper->native.GetPointer();
	double r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetRadius();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkEarthSourceWrap::GetRadiusMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkEarthSourceWrap *wrapper = ObjectWrap::Unwrap<VtkEarthSourceWrap>(info.Holder());
	vtkEarthSource *native = (vtkEarthSource *)wrapper->native.GetPointer();
	double r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetRadiusMaxValue();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkEarthSourceWrap::GetRadiusMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkEarthSourceWrap *wrapper = ObjectWrap::Unwrap<VtkEarthSourceWrap>(info.Holder());
	vtkEarthSource *native = (vtkEarthSource *)wrapper->native.GetPointer();
	double r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetRadiusMinValue();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkEarthSourceWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkEarthSourceWrap *wrapper = ObjectWrap::Unwrap<VtkEarthSourceWrap>(info.Holder());
	vtkEarthSource *native = (vtkEarthSource *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsString())
	{
		Nan::Utf8String a0(info[0]);
		int r;
		if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		r = native->IsA(
			*a0
		);
		info.GetReturnValue().Set(Nan::New(r));
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkEarthSourceWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkEarthSourceWrap *wrapper = ObjectWrap::Unwrap<VtkEarthSourceWrap>(info.Holder());
	vtkEarthSource *native = (vtkEarthSource *)wrapper->native.GetPointer();
	vtkEarthSource * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->NewInstance();
	VtkEarthSourceWrap::InitPtpl();
	v8::Local<v8::Value> argv[1] =
		{ Nan::New(vtkNodeJsNoWrap) };
	v8::Local<v8::Function> cons =
		Nan::New<v8::FunctionTemplate>(VtkEarthSourceWrap::ptpl)->GetFunction();
	v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
	VtkEarthSourceWrap *w = new VtkEarthSourceWrap();
	w->native = r;
	w->Wrap(wo);
	info.GetReturnValue().Set(wo);
}

void VtkEarthSourceWrap::OutlineOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkEarthSourceWrap *wrapper = ObjectWrap::Unwrap<VtkEarthSourceWrap>(info.Holder());
	vtkEarthSource *native = (vtkEarthSource *)wrapper->native.GetPointer();
		if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	native->OutlineOff();
}

void VtkEarthSourceWrap::OutlineOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkEarthSourceWrap *wrapper = ObjectWrap::Unwrap<VtkEarthSourceWrap>(info.Holder());
	vtkEarthSource *native = (vtkEarthSource *)wrapper->native.GetPointer();
		if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	native->OutlineOn();
}

void VtkEarthSourceWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkEarthSourceWrap *wrapper = ObjectWrap::Unwrap<VtkEarthSourceWrap>(info.Holder());
	vtkEarthSource *native = (vtkEarthSource *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0]))
	{
		VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject());
		vtkEarthSource * r;
		if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		r = native->SafeDownCast(
			(vtkObject *) a0->native.GetPointer()
		);
		VtkEarthSourceWrap::InitPtpl();
		v8::Local<v8::Value> argv[1] =
			{ Nan::New(vtkNodeJsNoWrap) };
		v8::Local<v8::Function> cons =
			Nan::New<v8::FunctionTemplate>(VtkEarthSourceWrap::ptpl)->GetFunction();
		v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
		VtkEarthSourceWrap *w = new VtkEarthSourceWrap();
		w->native = r;
		w->Wrap(wo);
		info.GetReturnValue().Set(wo);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkEarthSourceWrap::SetOnRatio(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkEarthSourceWrap *wrapper = ObjectWrap::Unwrap<VtkEarthSourceWrap>(info.Holder());
	vtkEarthSource *native = (vtkEarthSource *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsInt32())
	{
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetOnRatio(
			info[0]->Int32Value()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkEarthSourceWrap::SetOutline(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkEarthSourceWrap *wrapper = ObjectWrap::Unwrap<VtkEarthSourceWrap>(info.Holder());
	vtkEarthSource *native = (vtkEarthSource *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsInt32())
	{
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetOutline(
			info[0]->Int32Value()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkEarthSourceWrap::SetRadius(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkEarthSourceWrap *wrapper = ObjectWrap::Unwrap<VtkEarthSourceWrap>(info.Holder());
	vtkEarthSource *native = (vtkEarthSource *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsNumber())
	{
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetRadius(
			info[0]->NumberValue()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}